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,142 lines38,853 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/// `readable`: of these repository ids, the repositories the viewer may
697/// read, as `get_by_id` decides; forks and unknown ids are left out. For
698/// services that hold ids and must show only what the viewer could open.
699/// At most [`MAX_READABLE`] ids are looked at. Returns `Vec<Repo>`.
700#[derive(Debug, Serialize, Deserialize)]
701pub struct ReadableArgs {
702 pub ids: Vec<String>,
703 pub viewer: Viewer,
704}
705
706/// The most ids one `readable` call looks at.
707pub const MAX_READABLE: usize = 500;
708
709/// `public_namespaces`: the workspaces in which this account made a public
710/// repository, and so a public project, which anyone can see on its page.
711/// Returns `Vec<String>` of workspace slugs.
712#[derive(Debug, Serialize, Deserialize)]
713#[serde(rename_all = "camelCase")]
714pub struct PublicNamespacesArgs {
715 pub owner_id: String,
716}
717
718/// One file on a branch, or one a change touched: its path and blob.
719#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
720pub struct FileEntry {
721 pub path: String,
722 /// The blob it holds now; null when the change deleted it.
723 pub hash: Option<String>,
724}
725
726/// Files, and whether there were more than were listed.
727#[derive(Clone, Debug, Default, Serialize, Deserialize)]
728#[serde(rename_all = "camelCase")]
729pub struct FileList {
730 /// The commit the files were read at; null for an empty repository.
731 pub commit: Option<String>,
732 pub files: Vec<FileEntry>,
733 pub truncated: bool,
734}
735
736/// `list_files`: every file on a branch (the default branch when absent),
737/// path order by level, never descending into a directory named in
738/// `skip_dirs`. For services that index a repository; no viewer, since it
739/// is only reached by g1t's own services. Returns `FileList`.
740#[derive(Debug, Default, Serialize, Deserialize)]
741#[serde(rename_all = "camelCase")]
742pub struct ListFilesArgs {
743 pub repo_id: String,
744 #[serde(default, rename = "ref")]
745 pub git_ref: Option<String>,
746 #[serde(default)]
747 pub skip_dirs: Vec<String>,
748 /// At most this many files; capped at [`MAX_LISTED_FILES`].
749 pub limit: u32,
750}
751
752/// `changed_files`: the files that differ between two commits, as
753/// `list_files` reads them. With no `base`, every file at `head`. Returns
754/// `FileList`.
755#[derive(Debug, Default, Serialize, Deserialize)]
756#[serde(rename_all = "camelCase")]
757pub struct ChangedFilesArgs {
758 pub repo_id: String,
759 #[serde(default)]
760 pub base: Option<String>,
761 pub head: String,
762 #[serde(default)]
763 pub skip_dirs: Vec<String>,
764 pub limit: u32,
765}
766
767/// The most files one `list_files` or `changed_files` call lists.
768pub const MAX_LISTED_FILES: u32 = 10_000;
769
770/// `read_blobs`: the text of these blobs of a repository, for services
771/// that index it. A blob larger than `max_bytes`, or binary, comes back
772/// with no text. Returns `Vec<BlobText>`, in the order asked.
773#[derive(Debug, Default, Serialize, Deserialize)]
774#[serde(rename_all = "camelCase")]
775pub struct ReadBlobsArgs {
776 pub repo_id: String,
777 pub hashes: Vec<String>,
778 pub max_bytes: u32,
779}
780
781/// The most blobs one `read_blobs` call reads.
782pub const MAX_READ_BLOBS: usize = 100;
783
784#[derive(Clone, Debug, Serialize, Deserialize)]
785pub struct BlobText {
786 pub hash: String,
787 pub size: u64,
788 /// Null when the blob is missing, binary or larger than asked.
789 pub text: Option<String>,
790}
791
792/// `all_ids`: every repository that is not a fork, by id, a page at a
793/// time, for services that index all of them. Returns `IdPage`.
794#[derive(Debug, Default, Serialize, Deserialize)]
795pub struct AllIdsArgs {
796 /// Ids after this one.
797 #[serde(default)]
798 pub after: Option<String>,
799 pub limit: u32,
800}
801
802#[derive(Clone, Debug, Default, Serialize, Deserialize)]
803pub struct IdPage {
804 pub ids: Vec<String>,
805 /// Where the next page starts; null on the last.
806 pub next: Option<String>,
807}
808
809/// `visibility`: which of these repositories (`namespace/name`) are
810/// private, for billing, which pays for work on public ones from g1t's
811/// open-source pool. A pull request's working copy answers as the
812/// repository it is a copy of. Unknown paths are left out. Returns
813/// `Vec<RepoVisibility>`.
814#[derive(Debug, Default, Serialize, Deserialize)]
815pub struct VisibilityArgs {
816 pub paths: Vec<String>,
817}
818
819#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
820pub struct RepoVisibility {
821 pub path: String,
822 pub is_private: bool,
823}
824
825/// `git_operations`: how many git operations (clones, fetches and pushes
826/// through g1t's git endpoints) each workspace's repositories had in a
827/// month, for billing's git meter. Cloudflare Artifacts charges per
828/// operation from 2026-10-14. Pushes from agents' sandboxes go to the
829/// store directly and are not counted here. Returns
830/// `Vec<WorkspaceGitOperations>`.
831#[derive(Debug, Serialize, Deserialize)]
832pub struct GitOperationsArgs {
833 /// YYYY-MM.
834 pub month: String,
835 /// Count only from this hour on, `YYYY-MM-DDTHH`, such as the day the
836 /// provider starts charging.
837 #[serde(default)]
838 pub since: Option<String>,
839 /// One workspace only; every workspace with any when absent.
840 #[serde(default)]
841 pub namespace: Option<String>,
842}
843
844#[derive(Clone, Debug, Serialize, Deserialize)]
845pub struct WorkspaceGitOperations {
846 pub namespace: String,
847 pub operations: u64,
848}
849
850/// `storage`: what each workspace's private repositories hold, as far as
851/// g1t can measure it, for billing's daily storage meter. Returns
852/// `Vec<WorkspaceStorage>`.
853///
854/// The git store does not report a repository's size. What is counted is
855/// the bytes of every pack pushed through g1t's git endpoints to the
856/// repository or to its pull requests' working copies. Pushes made from
857/// agents' sandboxes, which go to the store directly, and imports are not
858/// counted, so it is a lower bound on what is stored.
859#[derive(Debug, Default, Serialize, Deserialize)]
860pub struct StorageArgs {}
861
862#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
863pub struct WorkspaceStorage {
864 pub namespace: String,
865 pub private_bytes: i64,
866 pub public_bytes: i64,
867}
868
869/// `transfer`: moves a repository to another workspace, keeping its name,
870/// its id and everything kept under it. The actor must own both
871/// workspaces. The old path keeps working as a redirect (see
872/// `resolve_path`) until a repository is made there. Publishes
873/// `repo.transferred`. Returns `Outcome<Repo>`, the repository at its new
874/// path.
875#[derive(Debug, Serialize, Deserialize)]
876#[serde(rename_all = "camelCase")]
877pub struct TransferArgs {
878 pub actor: User,
879 pub path: RepoPath,
880 /// The destination workspace's slug.
881 pub to: String,
882 /// Where the request came in, for the audit log; g1t.sh when absent.
883 #[serde(default)]
884 pub surface: Option<crate::audit::Surface>,
885}
886
887/// `resolve_path`: where a repository that was transferred away from
888/// `path` is now, while nothing else is there. Returns `Option<RepoPath>`:
889/// null when `path` is a repository, or never was one that moved. Callers
890/// check the viewer may see the repository at its new path, as for any
891/// other.
892#[derive(Debug, Serialize, Deserialize)]
893pub struct ResolvePathArgs {
894 pub path: RepoPath,
895}
896
897/// `namespace_count`: how many repositories (not pull request working
898/// copies) a workspace holds, private or not, for deciding whether it can
899/// be deleted. Returns `u32`.
900#[derive(Debug, Serialize, Deserialize)]
901pub struct NamespaceCountArgs {
902 pub namespace: String,
903}
904
905/// `delete`: deletes a repository. Owners of its workspace only, who type
906/// its full name (`namespace/name`) as `confirm`. It is hidden at once,
907/// git refuses it, and nothing runs for it; it can be restored for
908/// [`RESTORE_DAYS`] days, then it is purged, its git data with it. Its
909/// name stays taken until then, or until it is purged sooner from the
910/// workspace's Recently deleted list. Publishes `repo.deleted`. Returns
911/// `Outcome<DeletedRepo>`.
912#[derive(Debug, Serialize, Deserialize)]
913#[serde(rename_all = "camelCase")]
914pub struct DeleteArgs {
915 pub actor: User,
916 pub path: RepoPath,
917 #[serde(default)]
918 pub confirm: String,
919 #[serde(default)]
920 pub surface: Option<crate::audit::Surface>,
921}
922
923/// `deleted`: a workspace's recently deleted repositories, newest first.
924/// Owners only; empty for anyone else. Returns `Vec<DeletedRepo>`.
925#[derive(Debug, Serialize, Deserialize)]
926pub struct DeletedArgs {
927 pub viewer: Viewer,
928 pub namespace: String,
929}
930
931/// `restore` and `purge`: a deleted repository, by the path it had.
932/// `restore` brings it back as it was, at that path (`repo.restored`).
933/// `purge` removes it for good now, its git data with it, and frees its
934/// name (`repo.purged`); it takes the full name typed as `confirm`.
935/// Owners only. Return `Outcome<Repo>` and `Outcome<bool>`.
936#[derive(Debug, Serialize, Deserialize)]
937#[serde(rename_all = "camelCase")]
938pub struct DeletedRepoArgs {
939 pub actor: User,
940 pub path: RepoPath,
941 #[serde(default)]
942 pub confirm: Option<String>,
943 #[serde(default)]
944 pub surface: Option<crate::audit::Surface>,
945}
946
947/// `purge_due`: purges deleted repositories whose time has passed, at
948/// most `limit` (25 when absent). The service's own schedule runs it.
949/// Returns `u32`, how many were purged.
950#[derive(Debug, Default, Serialize, Deserialize)]
951pub struct PurgeDueArgs {
952 #[serde(default)]
953 pub limit: Option<u32>,
954}
955
956/// `rename`: gives a repository a new name in its workspace, keeping its
957/// id, its git data and everything kept under it. Owners only. The old
958/// path keeps redirecting, as after a transfer, until a repository is made
959/// there. Publishes `repo.renamed`. Returns `Outcome<Repo>`.
960#[derive(Debug, Serialize, Deserialize)]
961#[serde(rename_all = "camelCase")]
962pub struct RenameArgs {
963 pub actor: User,
964 pub path: RepoPath,
965 pub name: String,
966 #[serde(default)]
967 pub surface: Option<crate::audit::Surface>,
968}
969
970/// `archive`: makes a repository read-only (`archived: true`), or writable
971/// again. Owners only. While archived, pushes and merges are refused,
972/// issues and pull requests are locked, and agents and workflows do not
973/// run; deployments keep serving. Publishes `repo.archived` or
974/// `repo.unarchived`. Returns `Outcome<Repo>`.
975#[derive(Debug, Serialize, Deserialize)]
976#[serde(rename_all = "camelCase")]
977pub struct ArchiveArgs {
978 pub actor: User,
979 pub path: RepoPath,
980 pub archived: bool,
981 #[serde(default)]
982 pub surface: Option<crate::audit::Surface>,
983}
984
985/// `set_visibility`: makes a repository public or private. Owners only,
986/// who type its full name as `confirm`. A free workspace takes a private
987/// repository only while its private storage has room. Publishes
988/// `repo.updated` and `repo.visibility_changed`. Returns `Outcome<Repo>`.
989#[derive(Debug, Serialize, Deserialize)]
990#[serde(rename_all = "camelCase")]
991pub struct SetVisibilityArgs {
992 pub actor: User,
993 pub path: RepoPath,
994 pub is_private: bool,
995 #[serde(default)]
996 pub confirm: String,
997 #[serde(default)]
998 pub surface: Option<crate::audit::Surface>,
999}
1000
1001/// `set_default_branch`: makes another existing branch the one everything
1002/// lands on. Members of its workspace. Open pull requests then merge into
1003/// it. Publishes `repo.default_branch_changed`. Returns `Outcome<Repo>`.
1004#[derive(Debug, Serialize, Deserialize)]
1005#[serde(rename_all = "camelCase")]
1006pub struct SetDefaultBranchArgs {
1007 pub actor: User,
1008 pub path: RepoPath,
1009 pub branch: String,
1010 #[serde(default)]
1011 pub surface: Option<crate::audit::Surface>,
1012}
1013
1014/// `rename_branch`: renames a branch. Members of its workspace; only an
1015/// owner renames the default branch, which stays the default. Pull
1016/// requests from it follow, and web addresses naming the old branch
1017/// redirect until a branch of that name is made again. Publishes
1018/// `branch.renamed` (and `repo.default_branch_changed` for the default).
1019/// Returns `Outcome<Repo>`.
1020#[derive(Debug, Serialize, Deserialize)]
1021#[serde(rename_all = "camelCase")]
1022pub struct RenameBranchArgs {
1023 pub actor: User,
1024 pub path: RepoPath,
1025 pub from: String,
1026 pub to: String,
1027 #[serde(default)]
1028 pub surface: Option<crate::audit::Surface>,
1029}
1030
1031/// `resolve_branch`: what a branch renamed away from `branch` is called
1032/// now, for web addresses that name the old one; null when `branch` was
1033/// never renamed or exists again. Returns `Option<String>`.
1034#[derive(Debug, Serialize, Deserialize)]
1035#[serde(rename_all = "camelCase")]
1036pub struct ResolveBranchArgs {
1037 pub repo_id: String,
1038 pub branch: String,
1039}
1040
1041/// `status_by_id`: whether a repository is archived or deleted, for g1t's
1042/// own services deciding whether to act on it. An unknown id answers as
1043/// deleted. Returns `RepoStatus`.
1044#[derive(Debug, Serialize, Deserialize)]
1045pub struct StatusByIdArgs {
1046 pub id: String,
1047}
1048
1049#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
1050pub struct RepoStatus {
1051 pub archived: bool,
1052 pub deleted: bool,
1053}
1054
1055impl RepoStatus {
1056 /// Whether work may start on it: neither archived nor deleted.
1057 pub fn active(&self) -> bool {
1058 !self.archived && !self.deleted
1059 }
1060}
1061
1062/// What a person is told when something would change an archived
1063/// repository.
1064pub fn archived_message(namespace: &str, name: &str) -> String {
1065 format!(
1066 "{namespace}/{name} is archived, so it is read-only. An owner can unarchive it in its settings."
1067 )
1068}
1069
1070/// The path a repository was transferred from, and when, as `transfer`
1071/// keeps it so old addresses redirect.
1072#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1073#[serde(rename_all = "camelCase")]
1074pub struct RepoRedirect {
1075 pub from: RepoPath,
1076 pub repo_id: String,
1077 /// RFC 3339.
1078 pub created_at: String,
1079}
1080
1081#[cfg(test)]
1082mod topic_tests {
1083 use super::*;
1084
1085 fn topics(list: &[&str]) -> Result<Vec<String>, String> {
1086 clean_topics(&list.iter().map(|t| t.to_string()).collect::<Vec<_>>())
1087 }
1088
1089 #[test]
1090 fn topics_are_tidied() {
1091 assert_eq!(topics(&["Rust", " web_server ", "rust", ""]).unwrap(), vec!["rust", "web-server"]);
1092 }
1093
1094 #[test]
1095 fn websites_are_tidied() {
1096 assert_eq!(clean_website(" example.com ").unwrap().as_deref(), Some("https://example.com"));
1097 assert_eq!(clean_website("http://a.io/x").unwrap().as_deref(), Some("http://a.io/x"));
1098 assert_eq!(clean_website("").unwrap(), None);
1099 assert!(clean_website("ftp://a.io").is_err());
1100 assert!(clean_website("localhost").is_err());
1101 assert!(clean_website("https://a b.io").is_err());
1102 }
1103
1104 #[test]
1105 fn branch_names_follow_git() {
1106 for good in ["main", "trunk", "release/1.2", "feat-x_y"] {
1107 assert!(is_valid_branch_name(good), "{good}");
1108 }
1109 for bad in ["", "-x", "a..b", "a b", "x.lock", "a/", ".hidden", "a/.b", "g1t-queue", "a~1", "a:b", "@"] {
1110 assert!(!is_valid_branch_name(bad), "{bad}");
1111 }
1112 }
1113
1114 #[test]
1115 fn odd_topics_are_refused() {
1116 assert!(topics(&["c++"]).is_err());
1117 assert!(topics(&["-lead"]).is_err());
1118 assert!(topics(&[&"a".repeat(36)]).is_err());
1119 let many: Vec<String> = (0..21).map(|i| format!("t{i}")).collect();
1120 assert!(clean_topics(&many).is_err());
1121 }
1122}
1123
1124#[cfg(test)]
1125mod tests {
1126 use super::*;
1127
1128 #[test]
1129 fn a_pull_branch_update_reads_as_the_web_expects() {
1130 let update = PullBranchUpdate::NeedsAgent {
1131 reason: NeedsAgentReason::Overlap,
1132 detail: "both".into(),
1133 paths: vec!["a.rs".into()],
1134 };
1135 assert_eq!(
1136 serde_json::to_value(&update).unwrap(),
1137 serde_json::json!({ "outcome": "needs_agent", "reason": "overlap", "detail": "both", "paths": ["a.rs"] })
1138 );
1139 let done = PullBranchUpdate::UpToDate { commit: "c".into() };
1140 assert_eq!(serde_json::to_value(&done).unwrap(), serde_json::json!({ "outcome": "up_to_date", "commit": "c" }));
1141 }
1142}