9922873a5ec9073e20601f9a97b1db98e0d6e943 / cmd/simplegit/main.go · 12457 bytes · raw
// Command simplegit is a self-hosted git host: one static binary serving
// smart-HTTP git and a server-rendered web UI.
package main
import (
"bufio"
"bytes"
"database/sql"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"git.josie-c.com/josie/simplegit/internal/auth"
"git.josie-c.com/josie/simplegit/internal/config"
"git.josie-c.com/josie/simplegit/internal/db"
"git.josie-c.com/josie/simplegit/internal/git"
"git.josie-c.com/josie/simplegit/internal/web"
"golang.org/x/term"
)
func main() {
if len(os.Args) < 2 {
usage()
os.Exit(2)
}
var err error
switch os.Args[1] {
case "serve":
err = runServe(os.Args[2:])
case "adduser":
err = runAddUser(os.Args[2:])
case "release":
err = runRelease(os.Args[2:])
case "hook":
err = runHook(os.Args[2:])
case "gc":
err = runGC(os.Args[2:], os.Stdout)
case "-h", "--help", "help":
usage()
return
default:
fmt.Fprintf(os.Stderr, "simplegit: unknown command %q\n", os.Args[1])
usage()
os.Exit(2)
}
if err != nil {
fmt.Fprintln(os.Stderr, "simplegit:", err)
os.Exit(1)
}
}
func usage() {
fmt.Fprint(os.Stderr, `usage: simplegit <command> [flags]
commands:
serve run the HTTP server
adduser create the account
release publish a release (owner, via the server's API)
gc audit data-dir sizes and orphaned files (--clean, --vacuum)
hook post-receive callback (invoked by git, not by hand)
`)
}
func runServe(args []string) error {
fs := flag.NewFlagSet("serve", flag.ExitOnError)
configPath := fs.String("config", "simplegit.toml", "path to TOML config file")
if err := fs.Parse(args); err != nil {
return err
}
cfg, database, err := openStore(*configPath)
if err != nil {
return err
}
defer database.Close()
server, err := web.New(database, cfg)
if err != nil {
return err
}
fmt.Printf("simplegit: listening on %s (base URL %s)\n", cfg.ListenAddr, cfg.BaseURL)
return server.Listen()
}
// usernames become URL path segments (/user/repo), so keep them boring.
var usernamePattern = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_.-]*$`)
func runAddUser(args []string) error {
fs := flag.NewFlagSet("adduser", flag.ExitOnError)
configPath := fs.String("config", "simplegit.toml", "path to TOML config file")
if err := fs.Parse(args); err != nil {
return err
}
if fs.NArg() != 1 {
return fmt.Errorf("usage: simplegit adduser <username>")
}
username := fs.Arg(0)
if !usernamePattern.MatchString(username) {
return fmt.Errorf("username %q must be letters, digits, dot, dash or underscore", username)
}
_, database, err := openStore(*configPath)
if err != nil {
return err
}
defer database.Close()
_, err = db.GetUserByName(database, username)
if err == nil {
return fmt.Errorf("user %q already exists", username)
}
if !errors.Is(err, db.ErrNotFound) {
return err
}
password, err := readPassword()
if err != nil {
return err
}
hash, err := auth.HashPassword(password)
if err != nil {
return err
}
id, err := db.CreateUser(database, username, hash)
if err != nil {
return err
}
fmt.Printf("simplegit: created user %q (id %d)\n", username, id)
return nil
}
// readPassword takes the password from stdin when it is piped — so scripts
// can do `printf '%s\n' "$pw" | simplegit adduser josie` without exposing
// it in the process list — and falls back to the hidden terminal prompt.
func readPassword() (string, error) {
if term.IsTerminal(int(os.Stdin.Fd())) {
return promptPassword()
}
line, err := io.ReadAll(os.Stdin)
if err != nil {
return "", fmt.Errorf("read password: %w", err)
}
password := strings.TrimRight(string(line), "\r\n")
if password == "" {
return "", errors.New("password must not be empty")
}
return password, nil
}
func promptPassword() (string, error) {
fmt.Print("password: ")
first, err := term.ReadPassword(int(os.Stdin.Fd()))
fmt.Println()
if err != nil {
return "", fmt.Errorf("read password: %w", err)
}
fmt.Print("password (again): ")
second, err := term.ReadPassword(int(os.Stdin.Fd()))
fmt.Println()
if err != nil {
return "", fmt.Errorf("read password: %w", err)
}
if string(first) != string(second) {
return "", errors.New("passwords do not match")
}
if len(first) == 0 {
return "", errors.New("password must not be empty")
}
return string(first), nil
}
// runRelease publishes a release from the work machine, no SSH: it posts the
// owner's git token (or password) over the server's HTTP API with the tag,
// title, notes, and any asset files. The token may come from
// SIMPLEGIT_TOKEN, --token, or the SIMPLEGIT_TOKEN env var set in the shell.
func runRelease(args []string) error {
fs := flag.NewFlagSet("release", flag.ExitOnError)
baseURL := fs.String("base", "", "server base URL, e.g. https://git.example.com")
token := fs.String("token", "", "owner's git token (default $SIMPLEGIT_TOKEN)")
repoFlag := fs.String("repo", "", "owner/repo to publish into")
tagFlag := fs.String("tag", "", "tag the release is attached to (must exist)")
title := fs.String("title", "", "release title (default: the tag name)")
notesFile := fs.String("notes", "", "markdown release notes file (default: none)")
fs.Usage = func() {
fmt.Fprintf(fs.Output(), "usage: simplegit release -base URL -repo owner/repo -tag TAG [-title T] [-notes notes.md] [file ...]\n")
fs.PrintDefaults()
}
if err := fs.Parse(args); err != nil {
return err
}
if *baseURL == "" {
return errors.New("-base URL is required")
}
if *repoFlag == "" || *tagFlag == "" {
return errors.New("-repo owner/repo and -tag TAG are required")
}
// -repo stays owner/repo: the owner is the basic-auth username, while the
// URL is root-level (single-user host) and uses only the repo name.
owner, repoName, ok := strings.Cut(*repoFlag, "/")
if !ok || owner == "" || repoName == "" {
return errors.New("-repo must be owner/repo")
}
secret := strings.TrimSpace(*token)
if secret == "" {
secret = strings.TrimSpace(os.Getenv("SIMPLEGIT_TOKEN"))
}
if secret == "" {
return errors.New("a git token is required: pass -token or set SIMPLEGIT_TOKEN")
}
notes := ""
if *notesFile != "" {
b, err := os.ReadFile(*notesFile)
if err != nil {
return fmt.Errorf("read notes: %w", err)
}
notes = string(b)
}
// Build the multipart body.
var body bytes.Buffer
mw := multipart.NewWriter(&body)
writeField := func(name, value string) {
if value != "" {
_ = mw.WriteField(name, value)
}
}
writeField("tag", *tagFlag)
writeField("title", *title)
writeField("notes", notes)
for _, path := range fs.Args() {
f, err := os.Open(path)
if err != nil {
return fmt.Errorf("open %s: %w", path, err)
}
part, err := mw.CreateFormFile("assets", filepath.Base(path))
if err != nil {
f.Close()
return fmt.Errorf("multipart %s: %w", path, err)
}
if _, err := io.Copy(part, f); err != nil {
f.Close()
return fmt.Errorf("stream %s: %w", path, err)
}
f.Close()
}
if err := mw.Close(); err != nil {
return fmt.Errorf("close multipart: %w", err)
}
base, _ := url.Parse(strings.TrimSuffix(*baseURL, "/"))
endpoint := base.String() + "/" + repoName + "/releases"
req, err := http.NewRequest(http.MethodPost, endpoint, &body)
if err != nil {
return fmt.Errorf("build request: %w", err)
}
req.Header.Set("Content-Type", mw.FormDataContentType())
req.SetBasicAuth(owner, secret)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("POST %s: %w", endpoint, err)
}
defer resp.Body.Close()
respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
if resp.StatusCode >= 300 {
return fmt.Errorf("create release: %s: %s", resp.Status, strings.TrimSpace(string(respBody)))
}
var out struct{ URL, Title string }
_ = json.Unmarshal(respBody, &out)
fmt.Printf("release %s published: %s\n", *tagFlag, out.URL)
return nil
}
func runHook(args []string) error {
fs := flag.NewFlagSet("hook", flag.ExitOnError)
repoPath := fs.String("repo", "", "path to the bare repository (set by the installed hook)")
if err := fs.Parse(args); err != nil {
return err
}
if *repoPath == "" {
return errors.New("hook: --repo is required")
}
name, dataDir, err := splitRepoPath(*repoPath)
if err != nil {
return err
}
database, err := db.Open(filepath.Join(dataDir, "simplegit.db"))
if err != nil {
return err
}
defer database.Close()
branches, tags, err := pushRefs(os.Stdin)
if err != nil {
return err
}
// Establish a default branch when HEAD points at a branch that does not
// exist and this push created one (e.g. a first push of "master").
defaultBranch := ""
if current, err := git.DefaultBranch(*repoPath); err == nil {
if exists, _ := git.RefExists(*repoPath, current); !exists && len(branches) > 0 {
defaultBranch = branches[0]
if err := git.SetDefaultBranch(*repoPath, defaultBranch); err != nil {
return err
}
}
}
if err := db.RecordPush(database, name, time.Now().Unix(), defaultBranch); err != nil {
return err
}
return ensureReleases(database, *repoPath, name, tags)
}
// ensureReleases creates a release for each tag this push created that does
// not already have one, deriving the title and notes from the tag message.
// A repo with no metadata row (an out-of-band push) is skipped.
func ensureReleases(database *sql.DB, repoPath, name string, tags []string) error {
if len(tags) == 0 {
return nil
}
repo, err := db.GetRepoByName(database, name)
if errors.Is(err, db.ErrNotFound) {
return nil
}
if err != nil {
return err
}
ownerUser, err := db.GetUserByID(database, repo.OwnerID)
if err != nil {
return err
}
for _, tag := range tags {
_, err := db.GetReleaseByTag(database, repo.ID, tag)
if err == nil {
continue
}
if !errors.Is(err, db.ErrNotFound) {
return err
}
title, notes := tag, ""
if subject, body, found, err := git.TagMessage(repoPath, tag); err != nil {
return err
} else if found {
title, notes = subject, body
}
if _, err := db.CreateRelease(database, repo.ID, tag, title, notes, ownerUser.ID); err != nil && !errors.Is(err, db.ErrReleaseExists) {
return err
}
}
return nil
}
// splitRepoPath maps <dataDir>/repos/<name>.git back to its parts.
func splitRepoPath(repoPath string) (name, dataDir string, err error) {
abs, err := filepath.Abs(repoPath)
if err != nil {
return "", "", fmt.Errorf("resolve repo path: %w", err)
}
if !strings.HasSuffix(abs, ".git") {
return "", "", fmt.Errorf("hook: repo path %q is not a .git directory", repoPath)
}
name = strings.TrimSuffix(filepath.Base(abs), ".git")
dataDir = filepath.Dir(filepath.Dir(abs))
return name, dataDir, nil
}
// pushRefs returns the branch and tag names this push created, from the
// post-receive stdin updates ("old new ref"). A zero old SHA marks a newly
// created ref; deletions and moves are ignored (releases are add-only).
func pushRefs(r io.Reader) (branches, tags []string, err error) {
zero := strings.Repeat("0", 40)
scanner := bufio.NewScanner(r)
for scanner.Scan() {
fields := strings.Fields(scanner.Text())
if len(fields) < 3 {
continue
}
if fields[0] != zero {
continue
}
switch {
case strings.HasPrefix(fields[2], "refs/heads/"):
branches = append(branches, strings.TrimPrefix(fields[2], "refs/heads/"))
case strings.HasPrefix(fields[2], "refs/tags/"):
tags = append(tags, strings.TrimPrefix(fields[2], "refs/tags/"))
}
}
return branches, tags, scanner.Err()
}
// openStore loads the config, creates the runtime directory layout, and
// opens the metadata database — the setup shared by serve and adduser.
func openStore(configPath string) (config.Config, *sql.DB, error) {
cfg, err := config.Load(configPath)
if err != nil {
return cfg, nil, err
}
if err := ensureDataDir(cfg.DataDir); err != nil {
return cfg, nil, err
}
database, err := db.Open(filepath.Join(cfg.DataDir, "simplegit.db"))
if err != nil {
return cfg, nil, err
}
return cfg, database, nil
}
// ensureDataDir creates the runtime directory layout, idempotently. 0700
// keeps session tokens, password hashes, and private repo objects away
// from other local accounts.
func ensureDataDir(dir string) error {
for _, sub := range []string{"", "repos", "uploads"} {
if err := os.MkdirAll(filepath.Join(dir, sub), 0o700); err != nil {
return fmt.Errorf("create data dir: %w", err)
}
}
return nil
}