flagon-io/g1t

public

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t/crates/contracts/src/repos.rs

1,169 lines39,806 bytesCodeBlame
1//! The repos service: repository metadata, contents, forks and git access.
2//!
3//! Each `*Args` struct is the argument of the method of the same name,
4//! served at `POST /rpc/<method>`.
5
6use serde::{Deserialize, Serialize};
7
8use crate::{User, Viewer};
9
10#[derive(Clone, Debug, Serialize, Deserialize)]
11#[serde(rename_all = "camelCase")]
12pub struct Repo {
13 pub id: String,
14 /// The slug of the workspace that owns it: the first URL segment.
15 pub namespace: String,
16 pub name: String,
17 pub description: Option<String>,
18 pub is_private: bool,
19 pub owner_id: String,
20 pub default_branch: String,
21 /// Set when this repo is a pull request's working copy of another repo.
22 pub fork_of: Option<String>,
23 /// Whether the default branch is protected: it changes only by merging
24 /// a pull request, and pushes to it are refused.
25 #[serde(default)]
26 pub protected: bool,
27 /// RFC 3339.
28 pub created_at: String,
29 /// Words that say what it is about, for search and Explore: lowercase
30 /// letters, digits and hyphens. See [`clean_topics`].
31 #[serde(default)]
32 pub topics: Vec<String>,
33 /// Its home page, an http(s) address, shown beside its description.
34 /// See [`clean_website`].
35 #[serde(default)]
36 pub website: Option<String>,
37 /// RFC 3339: when it was archived, made read-only. Null when it is not.
38 #[serde(default)]
39 pub archived_at: Option<String>,
40}
41
42impl Repo {
43 pub fn archived(&self) -> bool {
44 self.archived_at.is_some()
45 }
46}
47
48/// How long a deleted repository can be restored before it is purged.
49pub const RESTORE_DAYS: u64 = 30;
50
51/// A deleted repository, as its workspace's Recently deleted list shows
52/// it: restorable until `purge_after`.
53#[derive(Clone, Debug, Serialize, Deserialize)]
54#[serde(rename_all = "camelCase")]
55pub struct DeletedRepo {
56 pub id: String,
57 pub namespace: String,
58 pub name: String,
59 pub description: Option<String>,
60 pub is_private: bool,
61 /// RFC 3339.
62 pub deleted_at: String,
63 /// The username of who deleted it.
64 pub deleted_by: String,
65 /// RFC 3339: when it is purged, unless restored first.
66 pub purge_after: String,
67}
68
69/// The longest website address a repository keeps.
70pub const MAX_WEBSITE_CHARS: usize = 255;
71
72/// A website as it is kept: an http(s) address, `https://` added when no
73/// scheme is given; empty clears it. Anything else is refused.
74pub fn clean_website(text: &str) -> Result<Option<String>, String> {
75 let text = text.trim();
76 if text.is_empty() {
77 return Ok(None);
78 }
79 let url = if text.starts_with("https://") || text.starts_with("http://") {
80 text.to_owned()
81 } else if text.contains("://") {
82 return Err("A website is an http or https address.".into());
83 } else {
84 format!("https://{text}")
85 };
86 let host = url
87 .split("://")
88 .nth(1)
89 .unwrap_or("")
90 .split(['/', '?', '#'])
91 .next()
92 .unwrap_or("");
93 if url.chars().count() > MAX_WEBSITE_CHARS
94 || host.is_empty()
95 || !host.contains('.')
96 || url.chars().any(char::is_whitespace)
97 {
98 return Err("That is not a website address, such as https://example.com.".into());
99 }
100 Ok(Some(url))
101}
102
103/// Whether `name` can be a branch people name: what `git check-ref-format
104/// --branch` accepts, less the names g1t keeps for itself
105/// ([`G1T_BRANCH_PREFIX`]).
106pub fn is_valid_branch_name(name: &str) -> bool {
107 !name.is_empty()
108 && name.len() <= 200
109 && !name.starts_with('-')
110 && !name.starts_with('/')
111 && !name.ends_with('/')
112 && !name.ends_with('.')
113 && !name.ends_with(".lock")
114 && !name.contains("..")
115 && !name.contains("//")
116 && !name.contains("@{")
117 && name != "@"
118 && !name.starts_with(G1T_BRANCH_PREFIX)
119 && !name.split('/').any(|part| part.starts_with('.'))
120 && name
121 .chars()
122 .all(|c| !c.is_control() && !matches!(c, ' ' | '~' | '^' | ':' | '?' | '*' | '[' | '\\'))
123}
124
125/// The most topics a repository has.
126pub const MAX_TOPICS: usize = 20;
127/// The longest topic.
128pub const MAX_TOPIC_CHARS: usize = 35;
129
130/// Topics as they are kept: lowercase, spaces and underscores made
131/// hyphens, each of letters, digits and hyphens, starting with a letter or
132/// digit, without repeats, at most [`MAX_TOPICS`]. Anything else is the
133/// first topic that could not be read.
134pub fn clean_topics(topics: &[String]) -> Result<Vec<String>, String> {
135 let mut kept: Vec<String> = Vec::new();
136 for topic in topics {
137 let topic: String = topic
138 .trim()
139 .to_lowercase()
140 .chars()
141 .map(|c| if c == ' ' || c == '_' { '-' } else { c })
142 .collect();
143 if topic.is_empty() {
144 continue;
145 }
146 let valid = topic.chars().count() <= MAX_TOPIC_CHARS
147 && topic.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
148 && topic.chars().next().is_some_and(|c| c.is_ascii_alphanumeric());
149 if !valid {
150 return Err(format!(
151 "\"{topic}\" is not a topic: use letters, digits and hyphens, at most {MAX_TOPIC_CHARS} characters."
152 ));
153 }
154 if !kept.contains(&topic) {
155 kept.push(topic);
156 }
157 }
158 if kept.len() > MAX_TOPICS {
159 return Err(format!("A repository has at most {MAX_TOPICS} topics."));
160 }
161 Ok(kept)
162}
163
164#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
165pub struct RepoPath {
166 pub namespace: String,
167 pub name: String,
168}
169
170#[derive(Clone, Debug, Serialize, Deserialize)]
171pub struct Signature {
172 pub name: String,
173 pub email: String,
174}
175
176#[derive(Clone, Debug, Serialize, Deserialize)]
177#[serde(rename_all = "camelCase")]
178pub struct Commit {
179 pub hash: String,
180 pub tree_hash: String,
181 pub message: String,
182 pub author: Signature,
183 pub parents: Vec<String>,
184 /// RFC 3339.
185 pub authored_at: String,
186}
187
188#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
189#[serde(rename_all = "lowercase")]
190pub enum EntryKind {
191 Tree,
192 Blob,
193 Symlink,
194 Gitlink,
195 Exec,
196}
197
198#[derive(Clone, Debug, Serialize, Deserialize)]
199pub struct TreeEntry {
200 pub name: String,
201 pub hash: String,
202 pub kind: EntryKind,
203}
204
205#[derive(Clone, Debug, Serialize, Deserialize)]
206pub struct Readme {
207 pub name: String,
208 /// Null when the file is binary or too large to show.
209 pub text: Option<String>,
210}
211
212#[derive(Clone, Debug, Serialize, Deserialize)]
213pub struct TreeView {
214 pub repo: Repo,
215 #[serde(rename = "ref")]
216 pub git_ref: String,
217 pub path: String,
218 /// Null when the repo has no commits yet.
219 pub head: Option<Commit>,
220 pub entries: Vec<TreeEntry>,
221 pub readme: Option<Readme>,
222}
223
224#[derive(Clone, Debug, Serialize, Deserialize)]
225pub struct BlobView {
226 pub repo: Repo,
227 #[serde(rename = "ref")]
228 pub git_ref: String,
229 pub path: String,
230 pub size: u64,
231 /// Null when the file is binary or too large to show.
232 pub text: Option<String>,
233}
234
235/// A git remote and a short-lived credential for it.
236#[derive(Clone, Debug, Serialize, Deserialize)]
237pub struct GitAccess {
238 pub remote: String,
239 pub token: String,
240}
241
242#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
243pub enum GitService {
244 #[serde(rename = "git-upload-pack")]
245 UploadPack,
246 #[serde(rename = "git-receive-pack")]
247 ReceivePack,
248}
249
250/// The result of landing a pull request.
251#[derive(Clone, Debug, Serialize, Deserialize)]
252pub struct Landed {
253 /// The commit the branch points to now.
254 pub commit: String,
255 /// The commit it pointed to before, if it had one. Comparing against
256 /// this shows what the pull request changed.
257 pub previous: Option<String>,
258}
259
260/// `get`. Returns `Outcome<Repo>`.
261#[derive(Debug, Serialize, Deserialize)]
262pub struct GetArgs {
263 pub path: RepoPath,
264 pub viewer: Viewer,
265}
266
267/// `path_by_id`: where a repository is, whoever may see it. For g1t's own
268/// services, which hold a repository's id from an event and act for its
269/// workspace; nothing outside reaches it. Returns `Option<RepoPath>`, null
270/// for a fork or an unknown id.
271#[derive(Debug, Serialize, Deserialize)]
272pub struct PathByIdArgs {
273 pub id: String,
274}
275
276/// `get_by_id`. Returns `Outcome<Repo>`.
277#[derive(Debug, Serialize, Deserialize)]
278pub struct GetByIdArgs {
279 pub id: String,
280 pub viewer: Viewer,
281}
282
283/// `list`: repos the viewer may see, newest first. Returns `Vec<Repo>`.
284#[derive(Debug, Default, Serialize, Deserialize)]
285#[serde(rename_all = "camelCase")]
286pub struct ListArgs {
287 pub viewer: Viewer,
288 #[serde(default)]
289 pub query: Option<String>,
290 /// Only repos in this workspace.
291 #[serde(default)]
292 pub namespace: Option<String>,
293 /// Only repos in workspaces the viewer belongs to.
294 #[serde(default)]
295 pub member_only: bool,
296}
297
298/// `create`. Returns `Outcome<Repo>`.
299#[derive(Debug, Serialize, Deserialize)]
300#[serde(rename_all = "camelCase")]
301pub struct CreateArgs {
302 /// Who is creating it; they must belong to the workspace.
303 pub owner: User,
304 /// The workspace it is created in.
305 pub namespace: String,
306 pub name: String,
307 #[serde(default)]
308 pub description: Option<String>,
309 #[serde(default)]
310 pub is_private: bool,
311 /// The https address of a public git repository to copy the default
312 /// branch of, such as `https://github.com/owner/repo`.
313 #[serde(default)]
314 pub import_url: Option<String>,
315 /// With `import_url`: a GitHub installation access token that opens it,
316 /// for a private repository. Every branch and tag is then copied, not
317 /// only the default branch. Set only by the integrations service.
318 #[serde(default, skip_serializing_if = "Option::is_none")]
319 pub import_token: Option<String>,
320}
321
322/// `mirror`: makes a repository's branches and tags match another git
323/// host's, or pushes its own out to one. Services only. Returns
324/// `Outcome<Mirrored>`.
325#[derive(Debug, Serialize, Deserialize)]
326#[serde(rename_all = "camelCase")]
327pub struct MirrorArgs {
328 pub repo_id: String,
329 /// The other host's https address, such as
330 /// `https://github.com/owner/repo.git`.
331 pub url: String,
332 /// A GitHub installation access token for it. Opaque: any length.
333 pub token: String,
334 pub direction: MirrorDirection,
335}
336
337#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
338#[serde(rename_all = "snake_case")]
339pub enum MirrorDirection {
340 /// The repository on g1t follows the other host: its refs are moved,
341 /// and removed, to match.
342 Pull,
343 /// The other host follows g1t: refs g1t has are pushed there; refs only
344 /// the other host has are left alone.
345 Push,
346}
347
348/// What a `mirror` changed.
349#[derive(Clone, Debug, Default, Serialize, Deserialize)]
350#[serde(rename_all = "camelCase")]
351pub struct Mirrored {
352 /// Full ref names created or moved.
353 pub updated: Vec<String>,
354 pub deleted: Vec<String>,
355}
356
357/// `update`: changes whichever of a repository's details are given.
358/// Members of its workspace only. Returns `Outcome<Repo>`.
359#[derive(Debug, Serialize, Deserialize)]
360#[serde(rename_all = "camelCase")]
361pub struct UpdateArgs {
362 pub actor: User,
363 pub path: RepoPath,
364 /// An empty description clears it.
365 #[serde(default)]
366 pub description: Option<String>,
367 #[serde(default)]
368 pub is_private: Option<bool>,
369 #[serde(default)]
370 pub protected: Option<bool>,
371 /// Replaces its topics; an empty list clears them.
372 #[serde(default)]
373 pub topics: Option<Vec<String>>,
374 /// Its home page; an empty string clears it.
375 #[serde(default)]
376 pub website: Option<String>,
377 /// Where the request came in, for the audit log; g1t.sh when absent.
378 #[serde(default)]
379 pub surface: Option<crate::audit::Surface>,
380}
381
382/// `tree`. Returns `Outcome<TreeView>`.
383#[derive(Debug, Serialize, Deserialize)]
384#[serde(rename_all = "camelCase")]
385pub struct TreeArgs {
386 pub path: RepoPath,
387 pub viewer: Viewer,
388 /// The default branch when absent.
389 #[serde(default, rename = "ref")]
390 pub git_ref: Option<String>,
391 #[serde(default)]
392 pub tree_path: String,
393}
394
395/// `blob`. Returns `Outcome<BlobView>`.
396#[derive(Debug, Serialize, Deserialize)]
397#[serde(rename_all = "camelCase")]
398pub struct BlobArgs {
399 pub path: RepoPath,
400 pub viewer: Viewer,
401 #[serde(rename = "ref")]
402 pub git_ref: String,
403 pub file_path: String,
404}
405
406/// `log`. Returns `Outcome<Vec<Commit>>`.
407#[derive(Debug, Serialize, Deserialize)]
408pub struct LogArgs {
409 pub path: RepoPath,
410 pub viewer: Viewer,
411 #[serde(default, rename = "ref")]
412 pub git_ref: Option<String>,
413 pub limit: u32,
414}
415
416/// `fork_for_pull`: a copy-on-write copy of the source repo, hidden from
417/// listings, for one pull request to be made in. Returns `Outcome<Repo>`.
418#[derive(Debug, Serialize, Deserialize)]
419#[serde(rename_all = "camelCase")]
420pub struct ForkArgs {
421 pub source_id: String,
422 pub pull_id: String,
423 pub actor: User,
424}
425
426/// `git_access`: authorizes a git operation and says where to send it.
427/// Pushing to a repo that does not exist creates it in the pusher's own
428/// namespace. Returns `Outcome<GitAccess>`.
429#[derive(Debug, Serialize, Deserialize)]
430pub struct GitAccessArgs {
431 pub path: RepoPath,
432 pub viewer: Viewer,
433 pub service: GitService,
434}
435
436/// `land`: moves a repository's default branch to the head of a pull
437/// request's source. Refused with `conflict` when the source is behind,
438/// since that would discard commits. Returns `Outcome<Landed>`.
439#[derive(Debug, Serialize, Deserialize)]
440#[serde(rename_all = "camelCase")]
441pub struct LandArgs {
442 /// The repository holding the commits: a pull request's fork, or the
443 /// target itself when landing one of its own branches.
444 pub source_id: String,
445 /// The branch of the source to land. Required when the source is the
446 /// target; a fork lands its default branch.
447 #[serde(default)]
448 pub branch: Option<String>,
449 pub actor: User,
450}
451
452#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
453#[serde(rename_all = "lowercase")]
454pub enum FileStatus {
455 Added,
456 Modified,
457 Deleted,
458}
459
460#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
461#[serde(rename_all = "lowercase")]
462pub enum LineKind {
463 /// Unchanged, shown for context.
464 Context,
465 Add,
466 Delete,
467}
468
469#[derive(Clone, Debug, Serialize, Deserialize)]
470pub struct DiffLine {
471 pub kind: LineKind,
472 /// Line number in the old file; absent for added lines.
473 pub old: Option<u32>,
474 /// Line number in the new file; absent for deleted lines.
475 pub new: Option<u32>,
476 pub text: String,
477}
478
479/// A run of changed lines with their surrounding context.
480#[derive(Clone, Debug, Serialize, Deserialize)]
481pub struct Hunk {
482 pub lines: Vec<DiffLine>,
483}
484
485#[derive(Clone, Debug, Serialize, Deserialize)]
486pub struct FileDiff {
487 pub path: String,
488 pub status: FileStatus,
489 pub additions: u32,
490 pub deletions: u32,
491 /// True when the file is binary or too large, so no lines are shown.
492 pub binary: bool,
493 pub hunks: Vec<Hunk>,
494}
495
496/// What changed between two commits.
497#[derive(Clone, Debug, Serialize, Deserialize)]
498pub struct Comparison {
499 /// Null when the head has no earlier commit to compare against.
500 pub base: Option<String>,
501 pub head: String,
502 pub files: Vec<FileDiff>,
503 /// True when the change was too large to return in full.
504 pub truncated: bool,
505}
506
507/// `compare`: what `head` changes relative to `base`.
508///
509/// `head` is a branch or a commit, and defaults to the default branch.
510/// With no `base`, a fork is compared against the point where it and the
511/// repository it came from last agreed; a branch against the point where it
512/// left the default branch; and the default branch against its head's
513/// parent. Returns `Outcome<Comparison>`.
514#[derive(Debug, Serialize, Deserialize)]
515#[serde(rename_all = "camelCase")]
516pub struct CompareArgs {
517 pub repo_id: String,
518 pub viewer: Viewer,
519 #[serde(default)]
520 pub base: Option<String>,
521 #[serde(default)]
522 pub head: Option<String>,
523}
524
525/// Lines `start` to `end` of a file, inclusive and counted from 1, last
526/// changed by `commit`.
527#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
528pub struct BlameRange {
529 pub start: u32,
530 pub end: u32,
531 pub commit: String,
532}
533
534/// Who last changed each line of a file.
535#[derive(Clone, Debug, Serialize, Deserialize)]
536pub struct Blame {
537 /// The commit the file was read at.
538 pub head: String,
539 /// Every line, in order, in runs that share a commit.
540 pub ranges: Vec<BlameRange>,
541 /// The commits the ranges name, each once.
542 pub commits: Vec<Commit>,
543 /// True when the history was too long to read in full, so the oldest
544 /// lines are given to the oldest commit read.
545 pub partial: bool,
546}
547
548/// `blame`: who last changed each line of `path` as of `ref` (the default
549/// branch if absent). Returns `Outcome<Blame>`; not found when the file is
550/// missing or is not text.
551#[derive(Debug, Serialize, Deserialize)]
552pub struct BlameArgs {
553 pub path: RepoPath,
554 pub viewer: Viewer,
555 #[serde(default, rename = "ref")]
556 pub git_ref: Option<String>,
557 #[serde(rename = "filePath")]
558 pub file_path: String,
559}
560
561/// A branch and the commit it points to.
562#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
563pub struct Branch {
564 pub name: String,
565 pub hash: String,
566}
567
568/// `branches`: the repository's branches, default branch first.
569/// Returns `Outcome<Vec<Branch>>`.
570#[derive(Debug, Serialize, Deserialize)]
571pub struct BranchesArgs {
572 pub path: RepoPath,
573 pub viewer: Viewer,
574}
575
576/// `behind`: whether the default branch of the repository a pull request
577/// would merge into has commits its source does not. For services that
578/// have already decided the caller may see the pull request; it reveals
579/// one bit. Returns `bool`.
580#[derive(Debug, Serialize, Deserialize)]
581#[serde(rename_all = "camelCase")]
582pub struct BehindArgs {
583 /// The pull request's fork, or the repository itself for a branch.
584 pub source_id: String,
585 /// The branch of the source. A fork is compared on its default branch.
586 #[serde(default)]
587 pub branch: Option<String>,
588}
589
590/// `divergence`: how a pull request's source and the default branch it
591/// would merge into have moved apart since they last agreed: the files each
592/// side changed. Takes `BehindArgs`. For services that have already decided
593/// the caller may see the pull request; it reveals paths, not contents.
594/// Returns `Option<Divergence>`, null when either side has no commits.
595#[derive(Clone, Debug, Default, Serialize, Deserialize)]
596#[serde(rename_all = "camelCase")]
597pub struct Divergence {
598 /// The source's commit.
599 pub head: String,
600 /// The default branch's commit.
601 pub base: String,
602 /// Where they last agreed, if that could be found.
603 pub merge_base: Option<String>,
604 /// Whether the default branch has commits the source does not.
605 pub behind: bool,
606 /// The files the source changed since the merge base.
607 pub ours: Vec<String>,
608 /// The files the default branch changed since the merge base. Empty
609 /// when it is not behind.
610 pub theirs: Vec<String>,
611 /// Whether either list was cut short.
612 pub truncated: bool,
613}
614
615/// `update_pull_branch`: brings a pull request's source up to date with the
616/// default branch it would merge into, without a sandbox, when that can be
617/// done safely: merges the default branch's head into the source's head and
618/// pushes the merge commit to the source's branch, as `actor`, only if the
619/// branch has not moved meanwhile. It applies only when the two sides
620/// changed different files since they last agreed; otherwise the answer is
621/// [`PullBranchUpdate::NeedsAgent`] and nothing is pushed. Refused unless
622/// `actor` may push to the source. Returns `Outcome<PullBranchUpdate>`.
623#[derive(Debug, Serialize, Deserialize)]
624#[serde(rename_all = "camelCase")]
625pub struct UpdatePullBranchArgs {
626 /// The pull request's fork, or the repository itself for a branch.
627 pub source_id: String,
628 /// The branch of the source. A fork is updated on its default branch.
629 #[serde(default)]
630 pub branch: Option<String>,
631 /// The pull request's number, to name it in the merge commit's message
632 /// when its branch has the same name as the default branch.
633 pub number: u32,
634 /// Who asked: the merge commit's author and committer, and the pusher.
635 pub actor: User,
636}
637
638/// Why an update has to be left to a sandbox.
639#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
640#[serde(rename_all = "snake_case")]
641pub enum NeedsAgentReason {
642 /// Both sides changed some of the same files; merging them needs a
643 /// real merge, which may or may not conflict.
644 Overlap,
645 /// Merging is known to conflict.
646 Conflicting,
647 /// The update could not be worked out here, such as when the two sides
648 /// share no history g1t can see, or the change is too large to list.
649 Unsupported,
650}
651
652/// What came of `update_pull_branch` (or the work service's `catch_up_pull`).
653#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
654#[serde(tag = "outcome", rename_all = "snake_case")]
655pub enum PullBranchUpdate {
656 /// The merge commit was pushed: the branch moved from `previous` to
657 /// `commit`.
658 Updated { commit: String, previous: String },
659 /// The source already holds the default branch's head.
660 UpToDate { commit: String },
661 /// Nothing was pushed; a sandbox has to merge it. `paths` are the
662 /// files both sides changed, or that conflict, when known.
663 NeedsAgent {
664 reason: NeedsAgentReason,
665 detail: String,
666 paths: Vec<String>,
667 },
668}
669
670/// `head`: the commit a branch points to, or null. For services reacting
671/// to a push, which have no viewer; it reveals nothing but a commit hash.
672/// Returns `Option<String>`.
673#[derive(Debug, Serialize, Deserialize)]
674#[serde(rename_all = "camelCase")]
675pub struct HeadArgs {
676 pub repo_id: String,
677 /// Empty for the repository's default branch.
678 pub branch: String,
679}
680
681/// Where g1t keeps branches of its own in a repository, such as the merge
682/// queue's tested states. Only these can be removed with `delete_branch`.
683pub const G1T_BRANCH_PREFIX: &str = "g1t-";
684
685/// `delete_branch`: removes a branch g1t made for itself once it is done
686/// with it, never one of people's: the name must start with
687/// [`G1T_BRANCH_PREFIX`]. For services, which have no viewer. Returns
688/// `Outcome<bool>`: whether there was such a branch.
689#[derive(Debug, Serialize, Deserialize)]
690#[serde(rename_all = "camelCase")]
691pub struct DeleteBranchArgs {
692 pub repo_id: String,
693 pub branch: String,
694}
695
696/// `commit_file`: writes one file on a new branch made from the default
697/// branch's head, as one commit by `actor`, without a sandbox. For a change
698/// g1t proposes on someone's behalf, such as a starter workflow, which then
699/// becomes a pull request. Refused unless `actor` may push, when the branch
700/// already exists, or when the file is already there. Returns
701/// `Outcome<CommittedFile>`.
702#[derive(Debug, Serialize, Deserialize)]
703#[serde(rename_all = "camelCase")]
704pub struct CommitFileArgs {
705 pub repo: RepoPath,
706 pub actor: User,
707 /// The new branch, which must not exist yet.
708 pub branch: String,
709 /// Where the file goes, such as `.g1t/workflows/ci.yml`.
710 pub path: String,
711 pub content: String,
712 pub message: String,
713}
714
715/// The commit `commit_file` made.
716#[derive(Clone, Debug, Serialize, Deserialize)]
717#[serde(rename_all = "camelCase")]
718pub struct CommittedFile {
719 pub branch: String,
720 pub commit: String,
721}
722
723/// `readable`: of these repository ids, the repositories the viewer may
724/// read, as `get_by_id` decides; forks and unknown ids are left out. For
725/// services that hold ids and must show only what the viewer could open.
726/// At most [`MAX_READABLE`] ids are looked at. Returns `Vec<Repo>`.
727#[derive(Debug, Serialize, Deserialize)]
728pub struct ReadableArgs {
729 pub ids: Vec<String>,
730 pub viewer: Viewer,
731}
732
733/// The most ids one `readable` call looks at.
734pub const MAX_READABLE: usize = 500;
735
736/// `public_namespaces`: the workspaces in which this account made a public
737/// repository, and so a public project, which anyone can see on its page.
738/// Returns `Vec<String>` of workspace slugs.
739#[derive(Debug, Serialize, Deserialize)]
740#[serde(rename_all = "camelCase")]
741pub struct PublicNamespacesArgs {
742 pub owner_id: String,
743}
744
745/// One file on a branch, or one a change touched: its path and blob.
746#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
747pub struct FileEntry {
748 pub path: String,
749 /// The blob it holds now; null when the change deleted it.
750 pub hash: Option<String>,
751}
752
753/// Files, and whether there were more than were listed.
754#[derive(Clone, Debug, Default, Serialize, Deserialize)]
755#[serde(rename_all = "camelCase")]
756pub struct FileList {
757 /// The commit the files were read at; null for an empty repository.
758 pub commit: Option<String>,
759 pub files: Vec<FileEntry>,
760 pub truncated: bool,
761}
762
763/// `list_files`: every file on a branch (the default branch when absent),
764/// path order by level, never descending into a directory named in
765/// `skip_dirs`. For services that index a repository; no viewer, since it
766/// is only reached by g1t's own services. Returns `FileList`.
767#[derive(Debug, Default, Serialize, Deserialize)]
768#[serde(rename_all = "camelCase")]
769pub struct ListFilesArgs {
770 pub repo_id: String,
771 #[serde(default, rename = "ref")]
772 pub git_ref: Option<String>,
773 #[serde(default)]
774 pub skip_dirs: Vec<String>,
775 /// At most this many files; capped at [`MAX_LISTED_FILES`].
776 pub limit: u32,
777}
778
779/// `changed_files`: the files that differ between two commits, as
780/// `list_files` reads them. With no `base`, every file at `head`. Returns
781/// `FileList`.
782#[derive(Debug, Default, Serialize, Deserialize)]
783#[serde(rename_all = "camelCase")]
784pub struct ChangedFilesArgs {
785 pub repo_id: String,
786 #[serde(default)]
787 pub base: Option<String>,
788 pub head: String,
789 #[serde(default)]
790 pub skip_dirs: Vec<String>,
791 pub limit: u32,
792}
793
794/// The most files one `list_files` or `changed_files` call lists.
795pub const MAX_LISTED_FILES: u32 = 10_000;
796
797/// `read_blobs`: the text of these blobs of a repository, for services
798/// that index it. A blob larger than `max_bytes`, or binary, comes back
799/// with no text. Returns `Vec<BlobText>`, in the order asked.
800#[derive(Debug, Default, Serialize, Deserialize)]
801#[serde(rename_all = "camelCase")]
802pub struct ReadBlobsArgs {
803 pub repo_id: String,
804 pub hashes: Vec<String>,
805 pub max_bytes: u32,
806}
807
808/// The most blobs one `read_blobs` call reads.
809pub const MAX_READ_BLOBS: usize = 100;
810
811#[derive(Clone, Debug, Serialize, Deserialize)]
812pub struct BlobText {
813 pub hash: String,
814 pub size: u64,
815 /// Null when the blob is missing, binary or larger than asked.
816 pub text: Option<String>,
817}
818
819/// `all_ids`: every repository that is not a fork, by id, a page at a
820/// time, for services that index all of them. Returns `IdPage`.
821#[derive(Debug, Default, Serialize, Deserialize)]
822pub struct AllIdsArgs {
823 /// Ids after this one.
824 #[serde(default)]
825 pub after: Option<String>,
826 pub limit: u32,
827}
828
829#[derive(Clone, Debug, Default, Serialize, Deserialize)]
830pub struct IdPage {
831 pub ids: Vec<String>,
832 /// Where the next page starts; null on the last.
833 pub next: Option<String>,
834}
835
836/// `visibility`: which of these repositories (`namespace/name`) are
837/// private, for billing, which pays for work on public ones from g1t's
838/// open-source pool. A pull request's working copy answers as the
839/// repository it is a copy of. Unknown paths are left out. Returns
840/// `Vec<RepoVisibility>`.
841#[derive(Debug, Default, Serialize, Deserialize)]
842pub struct VisibilityArgs {
843 pub paths: Vec<String>,
844}
845
846#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
847pub struct RepoVisibility {
848 pub path: String,
849 pub is_private: bool,
850}
851
852/// `git_operations`: how many git operations (clones, fetches and pushes
853/// through g1t's git endpoints) each workspace's repositories had in a
854/// month, for billing's git meter. Cloudflare Artifacts charges per
855/// operation from 2026-10-14. Pushes from agents' sandboxes go to the
856/// store directly and are not counted here. Returns
857/// `Vec<WorkspaceGitOperations>`.
858#[derive(Debug, Serialize, Deserialize)]
859pub struct GitOperationsArgs {
860 /// YYYY-MM.
861 pub month: String,
862 /// Count only from this hour on, `YYYY-MM-DDTHH`, such as the day the
863 /// provider starts charging.
864 #[serde(default)]
865 pub since: Option<String>,
866 /// One workspace only; every workspace with any when absent.
867 #[serde(default)]
868 pub namespace: Option<String>,
869}
870
871#[derive(Clone, Debug, Serialize, Deserialize)]
872pub struct WorkspaceGitOperations {
873 pub namespace: String,
874 pub operations: u64,
875}
876
877/// `storage`: what each workspace's private repositories hold, as far as
878/// g1t can measure it, for billing's daily storage meter. Returns
879/// `Vec<WorkspaceStorage>`.
880///
881/// The git store does not report a repository's size. What is counted is
882/// the bytes of every pack pushed through g1t's git endpoints to the
883/// repository or to its pull requests' working copies. Pushes made from
884/// agents' sandboxes, which go to the store directly, and imports are not
885/// counted, so it is a lower bound on what is stored.
886#[derive(Debug, Default, Serialize, Deserialize)]
887pub struct StorageArgs {}
888
889#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
890pub struct WorkspaceStorage {
891 pub namespace: String,
892 pub private_bytes: i64,
893 pub public_bytes: i64,
894}
895
896/// `transfer`: moves a repository to another workspace, keeping its name,
897/// its id and everything kept under it. The actor must own both
898/// workspaces. The old path keeps working as a redirect (see
899/// `resolve_path`) until a repository is made there. Publishes
900/// `repo.transferred`. Returns `Outcome<Repo>`, the repository at its new
901/// path.
902#[derive(Debug, Serialize, Deserialize)]
903#[serde(rename_all = "camelCase")]
904pub struct TransferArgs {
905 pub actor: User,
906 pub path: RepoPath,
907 /// The destination workspace's slug.
908 pub to: String,
909 /// Where the request came in, for the audit log; g1t.sh when absent.
910 #[serde(default)]
911 pub surface: Option<crate::audit::Surface>,
912}
913
914/// `resolve_path`: where a repository that was transferred away from
915/// `path` is now, while nothing else is there. Returns `Option<RepoPath>`:
916/// null when `path` is a repository, or never was one that moved. Callers
917/// check the viewer may see the repository at its new path, as for any
918/// other.
919#[derive(Debug, Serialize, Deserialize)]
920pub struct ResolvePathArgs {
921 pub path: RepoPath,
922}
923
924/// `namespace_count`: how many repositories (not pull request working
925/// copies) a workspace holds, private or not, for deciding whether it can
926/// be deleted. Returns `u32`.
927#[derive(Debug, Serialize, Deserialize)]
928pub struct NamespaceCountArgs {
929 pub namespace: String,
930}
931
932/// `delete`: deletes a repository. Owners of its workspace only, who type
933/// its full name (`namespace/name`) as `confirm`. It is hidden at once,
934/// git refuses it, and nothing runs for it; it can be restored for
935/// [`RESTORE_DAYS`] days, then it is purged, its git data with it. Its
936/// name stays taken until then, or until it is purged sooner from the
937/// workspace's Recently deleted list. Publishes `repo.deleted`. Returns
938/// `Outcome<DeletedRepo>`.
939#[derive(Debug, Serialize, Deserialize)]
940#[serde(rename_all = "camelCase")]
941pub struct DeleteArgs {
942 pub actor: User,
943 pub path: RepoPath,
944 #[serde(default)]
945 pub confirm: String,
946 #[serde(default)]
947 pub surface: Option<crate::audit::Surface>,
948}
949
950/// `deleted`: a workspace's recently deleted repositories, newest first.
951/// Owners only; empty for anyone else. Returns `Vec<DeletedRepo>`.
952#[derive(Debug, Serialize, Deserialize)]
953pub struct DeletedArgs {
954 pub viewer: Viewer,
955 pub namespace: String,
956}
957
958/// `restore` and `purge`: a deleted repository, by the path it had.
959/// `restore` brings it back as it was, at that path (`repo.restored`).
960/// `purge` removes it for good now, its git data with it, and frees its
961/// name (`repo.purged`); it takes the full name typed as `confirm`.
962/// Owners only. Return `Outcome<Repo>` and `Outcome<bool>`.
963#[derive(Debug, Serialize, Deserialize)]
964#[serde(rename_all = "camelCase")]
965pub struct DeletedRepoArgs {
966 pub actor: User,
967 pub path: RepoPath,
968 #[serde(default)]
969 pub confirm: Option<String>,
970 #[serde(default)]
971 pub surface: Option<crate::audit::Surface>,
972}
973
974/// `purge_due`: purges deleted repositories whose time has passed, at
975/// most `limit` (25 when absent). The service's own schedule runs it.
976/// Returns `u32`, how many were purged.
977#[derive(Debug, Default, Serialize, Deserialize)]
978pub struct PurgeDueArgs {
979 #[serde(default)]
980 pub limit: Option<u32>,
981}
982
983/// `rename`: gives a repository a new name in its workspace, keeping its
984/// id, its git data and everything kept under it. Owners only. The old
985/// path keeps redirecting, as after a transfer, until a repository is made
986/// there. Publishes `repo.renamed`. Returns `Outcome<Repo>`.
987#[derive(Debug, Serialize, Deserialize)]
988#[serde(rename_all = "camelCase")]
989pub struct RenameArgs {
990 pub actor: User,
991 pub path: RepoPath,
992 pub name: String,
993 #[serde(default)]
994 pub surface: Option<crate::audit::Surface>,
995}
996
997/// `archive`: makes a repository read-only (`archived: true`), or writable
998/// again. Owners only. While archived, pushes and merges are refused,
999/// issues and pull requests are locked, and agents and workflows do not
1000/// run; deployments keep serving. Publishes `repo.archived` or
1001/// `repo.unarchived`. Returns `Outcome<Repo>`.
1002#[derive(Debug, Serialize, Deserialize)]
1003#[serde(rename_all = "camelCase")]
1004pub struct ArchiveArgs {
1005 pub actor: User,
1006 pub path: RepoPath,
1007 pub archived: bool,
1008 #[serde(default)]
1009 pub surface: Option<crate::audit::Surface>,
1010}
1011
1012/// `set_visibility`: makes a repository public or private. Owners only,
1013/// who type its full name as `confirm`. A free workspace takes a private
1014/// repository only while its private storage has room. Publishes
1015/// `repo.updated` and `repo.visibility_changed`. Returns `Outcome<Repo>`.
1016#[derive(Debug, Serialize, Deserialize)]
1017#[serde(rename_all = "camelCase")]
1018pub struct SetVisibilityArgs {
1019 pub actor: User,
1020 pub path: RepoPath,
1021 pub is_private: bool,
1022 #[serde(default)]
1023 pub confirm: String,
1024 #[serde(default)]
1025 pub surface: Option<crate::audit::Surface>,
1026}
1027
1028/// `set_default_branch`: makes another existing branch the one everything
1029/// lands on. Members of its workspace. Open pull requests then merge into
1030/// it. Publishes `repo.default_branch_changed`. Returns `Outcome<Repo>`.
1031#[derive(Debug, Serialize, Deserialize)]
1032#[serde(rename_all = "camelCase")]
1033pub struct SetDefaultBranchArgs {
1034 pub actor: User,
1035 pub path: RepoPath,
1036 pub branch: String,
1037 #[serde(default)]
1038 pub surface: Option<crate::audit::Surface>,
1039}
1040
1041/// `rename_branch`: renames a branch. Members of its workspace; only an
1042/// owner renames the default branch, which stays the default. Pull
1043/// requests from it follow, and web addresses naming the old branch
1044/// redirect until a branch of that name is made again. Publishes
1045/// `branch.renamed` (and `repo.default_branch_changed` for the default).
1046/// Returns `Outcome<Repo>`.
1047#[derive(Debug, Serialize, Deserialize)]
1048#[serde(rename_all = "camelCase")]
1049pub struct RenameBranchArgs {
1050 pub actor: User,
1051 pub path: RepoPath,
1052 pub from: String,
1053 pub to: String,
1054 #[serde(default)]
1055 pub surface: Option<crate::audit::Surface>,
1056}
1057
1058/// `resolve_branch`: what a branch renamed away from `branch` is called
1059/// now, for web addresses that name the old one; null when `branch` was
1060/// never renamed or exists again. Returns `Option<String>`.
1061#[derive(Debug, Serialize, Deserialize)]
1062#[serde(rename_all = "camelCase")]
1063pub struct ResolveBranchArgs {
1064 pub repo_id: String,
1065 pub branch: String,
1066}
1067
1068/// `status_by_id`: whether a repository is archived or deleted, for g1t's
1069/// own services deciding whether to act on it. An unknown id answers as
1070/// deleted. Returns `RepoStatus`.
1071#[derive(Debug, Serialize, Deserialize)]
1072pub struct StatusByIdArgs {
1073 pub id: String,
1074}
1075
1076#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
1077pub struct RepoStatus {
1078 pub archived: bool,
1079 pub deleted: bool,
1080}
1081
1082impl RepoStatus {
1083 /// Whether work may start on it: neither archived nor deleted.
1084 pub fn active(&self) -> bool {
1085 !self.archived && !self.deleted
1086 }
1087}
1088
1089/// What a person is told when something would change an archived
1090/// repository.
1091pub fn archived_message(namespace: &str, name: &str) -> String {
1092 format!(
1093 "{namespace}/{name} is archived, so it is read-only. An owner can unarchive it in its settings."
1094 )
1095}
1096
1097/// The path a repository was transferred from, and when, as `transfer`
1098/// keeps it so old addresses redirect.
1099#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1100#[serde(rename_all = "camelCase")]
1101pub struct RepoRedirect {
1102 pub from: RepoPath,
1103 pub repo_id: String,
1104 /// RFC 3339.
1105 pub created_at: String,
1106}
1107
1108#[cfg(test)]
1109mod topic_tests {
1110 use super::*;
1111
1112 fn topics(list: &[&str]) -> Result<Vec<String>, String> {
1113 clean_topics(&list.iter().map(|t| t.to_string()).collect::<Vec<_>>())
1114 }
1115
1116 #[test]
1117 fn topics_are_tidied() {
1118 assert_eq!(topics(&["Rust", " web_server ", "rust", ""]).unwrap(), vec!["rust", "web-server"]);
1119 }
1120
1121 #[test]
1122 fn websites_are_tidied() {
1123 assert_eq!(clean_website(" example.com ").unwrap().as_deref(), Some("https://example.com"));
1124 assert_eq!(clean_website("http://a.io/x").unwrap().as_deref(), Some("http://a.io/x"));
1125 assert_eq!(clean_website("").unwrap(), None);
1126 assert!(clean_website("ftp://a.io").is_err());
1127 assert!(clean_website("localhost").is_err());
1128 assert!(clean_website("https://a b.io").is_err());
1129 }
1130
1131 #[test]
1132 fn branch_names_follow_git() {
1133 for good in ["main", "trunk", "release/1.2", "feat-x_y"] {
1134 assert!(is_valid_branch_name(good), "{good}");
1135 }
1136 for bad in ["", "-x", "a..b", "a b", "x.lock", "a/", ".hidden", "a/.b", "g1t-queue", "a~1", "a:b", "@"] {
1137 assert!(!is_valid_branch_name(bad), "{bad}");
1138 }
1139 }
1140
1141 #[test]
1142 fn odd_topics_are_refused() {
1143 assert!(topics(&["c++"]).is_err());
1144 assert!(topics(&["-lead"]).is_err());
1145 assert!(topics(&[&"a".repeat(36)]).is_err());
1146 let many: Vec<String> = (0..21).map(|i| format!("t{i}")).collect();
1147 assert!(clean_topics(&many).is_err());
1148 }
1149}
1150
1151#[cfg(test)]
1152mod tests {
1153 use super::*;
1154
1155 #[test]
1156 fn a_pull_branch_update_reads_as_the_web_expects() {
1157 let update = PullBranchUpdate::NeedsAgent {
1158 reason: NeedsAgentReason::Overlap,
1159 detail: "both".into(),
1160 paths: vec!["a.rs".into()],
1161 };
1162 assert_eq!(
1163 serde_json::to_value(&update).unwrap(),
1164 serde_json::json!({ "outcome": "needs_agent", "reason": "overlap", "detail": "both", "paths": ["a.rs"] })
1165 );
1166 let done = PullBranchUpdate::UpToDate { commit: "c".into() };
1167 assert_eq!(serde_json::to_value(&done).unwrap(), serde_json::json!({ "outcome": "up_to_date", "commit": "c" }));
1168 }
1169}