internal/control/commitfile.go

ac8d910ff31c2fadc452928e1d56c64b4af25495
gitbay/internal/control/commitfile.go

132 lines · 4881 bytes

  1package control
  2
  3import (
  4	"fmt"
  5	"io"
  6	"slices"
  7	"strings"
  8
  9	"gitbay.org/gitbay/internal/gitutil"
 10	"gitbay.org/gitbay/internal/policy"
 11	"gitbay.org/gitbay/internal/protocol"
 12)
 13
 14func init() {
 15	register(Command{
 16		Path:    []string{"repo", "commit-file"},
 17		Summary: "write a file and commit it",
 18		Usage: "repo commit-file <owner/name> <path> " +
 19			"--ref <branch> [--from <base>] [--message <m>] [--file -]",
 20		Flags: []Flag{
 21			{"--ref", "<branch>", "branch to commit to", ""},
 22			{"--from", "<base>", "base branch when creating a new branch", ""},
 23			{"--message", "<m>", "the commit message", ""},
 24			{"--file", "-", "read the new content from stdin", ""},
 25		},
 26		Examples: []string{
 27			`repo commit-file krz/gitbay CHANGELOG.org --ref main --message "note the release" --file - < CHANGELOG.org`,
 28		},
 29		ReadsStdin: true,
 30		Run:        runCommitFile,
 31	})
 32}
 33
 34// maxCommitFileBytes bounds one edit. Large content belongs in a push,
 35// not a single-file commit over the control plane.
 36const maxCommitFileBytes = 1 << 20
 37
 38// runCommitFile commits one file's contents to a branch. It exists so the
 39// capability is reachable from every surface: the web's editor dispatches
 40// this rather than calling git itself, which is what kept editing off the
 41// CLI and the API.
 42//
 43// Commits made here are unsigned, because the server is authoring them.
 44// A repository that requires verified signatures therefore refuses the
 45// command rather than writing a commit its own policy would reject.
 46func runCommitFile(c *Ctx, args []string) int {
 47	f, err := c.parseArgs(args, flagSpec{Values: []string{"--ref", "--from", "--message", "--file"}, MaxPos: -1, Usage: c.Cmd.Usage})
 48	if err != nil {
 49		return c.fail(protocol.ExitUsage, "%v", err)
 50	}
 51	rest := f.Pos
 52	ref, fromRef, message, file := f.Value("--ref"), f.Value("--from"), f.Value("--message"), f.Value("--file")
 53	if len(rest) != 2 || ref == "" {
 54		return c.usage()
 55	}
 56	if strings.HasPrefix(ref, "-") || strings.HasPrefix(ref, "/") || strings.HasSuffix(ref, "/") || strings.HasSuffix(ref, ".lock") || strings.Contains(ref, "..") || strings.Contains(ref, "//") || strings.ContainsAny(ref, " \t\r\n~^:?*[\\") || strings.Contains(ref, "@{") || ref == "@" {
 57		return c.fail(protocol.ExitUsage, "invalid branch name %q", ref)
 58	}
 59	repo, code := resolveRepo(c, rest[0], policy.CanWrite)
 60	if code >= 0 {
 61		return code
 62	}
 63	if code := refuseArchived(c, repo); code >= 0 {
 64		return code
 65	}
 66	filePath, ok := cleanRepoPath(rest[1])
 67	if !ok || filePath == "" {
 68		return c.fail(protocol.ExitUsage, "path must stay inside the repository")
 69	}
 70	if repo.Settings.RequireMR && slices.Contains(repo.Settings.ProtectedBranches, ref) {
 71		return c.fail(protocol.ExitDenied, "branch %s accepts changes through merge requests only; push another branch and open one", ref)
 72	}
 73	// The server authors this commit, so it cannot sign it.
 74	if repo.Settings.RequireSignedCommits {
 75		return c.fail(protocol.ExitDenied,
 76			"%s requires signed commits; this writes an unsigned one — push a signed commit instead",
 77			repo.Path())
 78	}
 79	if code := checkStorageQuota(c, repo); code >= 0 {
 80		return code
 81	}
 82	// A commit carries an identity, and an unverified address is not one.
 83	email, err := c.Store.PrimaryVerifiedEmail(c.User.ID)
 84	if err != nil {
 85		return c.fail(protocol.ExitFailure, "%v", err)
 86	}
 87	if email == "" {
 88		return c.fail(protocol.ExitDenied,
 89			"commits carry your identity: your account needs a verified primary email")
 90	}
 91
 92	var content []byte
 93	if file != "" {
 94		if file != "-" {
 95			return c.fail(protocol.ExitUsage, "--file only supports - (stdin)")
 96		}
 97		content, err = io.ReadAll(io.LimitReader(c.Stdin, maxCommitFileBytes))
 98		if err != nil {
 99			return c.fail(protocol.ExitFailure, "reading content: %v", err)
100		}
101	}
102	if message = strings.TrimSpace(message); message == "" {
103		message = "edit " + filePath
104	}
105
106	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
107	// The head before the commit bounds what landed; a branch that does
108	// not exist fails in CommitFileFrom unless --from names its base.
109	parent, _ := gitutil.ResolveRef(dir, "refs/heads/"+ref)
110	sha, err := gitutil.CommitFileFrom(dir, ref, fromRef, filePath, content,
111		c.User.Username, email, message)
112	if err != nil {
113		return c.fail(protocol.ExitFailure, "%v", err)
114	}
115	c.Store.MarkMirrorsDirty(repo.ID, "push")
116	// This bypasses receive-pack like a merge does, so the commit-message
117	// issue actions (closes #N, references) run here for the default
118	// branch, with the session's scope (#210).
119	if ref == repo.DefaultBranch {
120		ProcessCommitMessages(c.Store, dir, repo, c.User.ID, c.Scope, parent, sha)
121	}
122
123	d := struct {
124		Path string `json:"path"`
125		Ref  string `json:"ref"`
126		File string `json:"file"`
127		SHA  string `json:"sha"`
128	}{repo.Path(), ref, filePath, sha}
129	return c.emit(d, func(w io.Writer) {
130		fmt.Fprintf(w, "committed %s on %s: %.10s\n", filePath, ref, sha)
131	})
132}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form