g1t/crates/contracts/src/repos.rs

1,273 lines42,957 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/// `last_commits`: which commit last changed each entry of a directory at
569/// `ref` (the default branch when absent). Returns `Outcome<LastCommits>`.
570#[derive(Debug, Serialize, Deserialize)]
571#[serde(rename_all = "camelCase")]
572pub struct LastCommitsArgs {
573 pub path: RepoPath,
574 pub viewer: Viewer,
575 #[serde(default, rename = "ref")]
576 pub git_ref: Option<String>,
577 #[serde(default)]
578 pub tree_path: String,
579}
580
581/// An entry of a directory and the commit that last changed it.
582#[derive(Clone, Debug, Serialize, Deserialize)]
583pub struct LastCommit {
584 pub name: String,
585 pub commit: Commit,
586}
587
588/// The entries' last commits. `complete` is false when the history walked
589/// ran out before every entry was placed; those entries are left out.
590#[derive(Clone, Debug, Serialize, Deserialize)]
591pub struct LastCommits {
592 pub entries: Vec<LastCommit>,
593 pub complete: bool,
594}
595
596/// `tags`: the repository's tags, newest commit first, each with the
597/// commit it names. Returns `Outcome<Vec<Tag>>`.
598#[derive(Debug, Serialize, Deserialize)]
599pub struct TagsArgs {
600 pub path: RepoPath,
601 pub viewer: Viewer,
602}
603
604/// A tag, and its commit when it could be read.
605#[derive(Clone, Debug, Serialize, Deserialize)]
606pub struct Tag {
607 pub name: String,
608 pub commit: Option<Commit>,
609}
610
611/// `branches`: the repository's branches, default branch first.
612/// Returns `Outcome<Vec<Branch>>`.
613#[derive(Debug, Serialize, Deserialize)]
614pub struct BranchesArgs {
615 pub path: RepoPath,
616 pub viewer: Viewer,
617}
618
619/// `behind`: whether the default branch of the repository a pull request
620/// would merge into has commits its source does not. For services that
621/// have already decided the caller may see the pull request; it reveals
622/// one bit. Returns `bool`.
623#[derive(Debug, Serialize, Deserialize)]
624#[serde(rename_all = "camelCase")]
625pub struct BehindArgs {
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 compared on its default branch.
629 #[serde(default)]
630 pub branch: Option<String>,
631}
632
633/// `divergence`: how a pull request's source and the default branch it
634/// would merge into have moved apart since they last agreed: the files each
635/// side changed. Takes `BehindArgs`. For services that have already decided
636/// the caller may see the pull request; it reveals paths, not contents.
637/// Returns `Option<Divergence>`, null when either side has no commits.
638#[derive(Clone, Debug, Default, Serialize, Deserialize)]
639#[serde(rename_all = "camelCase")]
640pub struct Divergence {
641 /// The source's commit.
642 pub head: String,
643 /// The default branch's commit.
644 pub base: String,
645 /// Where they last agreed, if that could be found.
646 pub merge_base: Option<String>,
647 /// Whether the default branch has commits the source does not.
648 pub behind: bool,
649 /// The files the source changed since the merge base.
650 pub ours: Vec<String>,
651 /// The files the default branch changed since the merge base. Empty
652 /// when it is not behind.
653 pub theirs: Vec<String>,
654 /// Whether either list was cut short.
655 pub truncated: bool,
656}
657
658/// `update_pull_branch`: brings a pull request's source up to date with the
659/// default branch it would merge into, without a sandbox, when that can be
660/// done safely: merges the default branch's head into the source's head and
661/// pushes the merge commit to the source's branch, as `actor`, only if the
662/// branch has not moved meanwhile. It applies only when the two sides
663/// changed different files since they last agreed; otherwise the answer is
664/// [`PullBranchUpdate::NeedsAgent`] and nothing is pushed. Refused unless
665/// `actor` may push to the source. Returns `Outcome<PullBranchUpdate>`.
666#[derive(Debug, Serialize, Deserialize)]
667#[serde(rename_all = "camelCase")]
668pub struct UpdatePullBranchArgs {
669 /// The pull request's fork, or the repository itself for a branch.
670 pub source_id: String,
671 /// The branch of the source. A fork is updated on its default branch.
672 #[serde(default)]
673 pub branch: Option<String>,
674 /// The pull request's number, to name it in the merge commit's message
675 /// when its branch has the same name as the default branch.
676 pub number: u32,
677 /// Who asked: the merge commit's author and committer, and the pusher.
678 pub actor: User,
679}
680
681/// Why an update has to be left to a sandbox.
682#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
683#[serde(rename_all = "snake_case")]
684pub enum NeedsAgentReason {
685 /// Both sides changed some of the same files; merging them needs a
686 /// real merge, which may or may not conflict.
687 Overlap,
688 /// Merging is known to conflict.
689 Conflicting,
690 /// The update could not be worked out here, such as when the two sides
691 /// share no history g1t can see, or the change is too large to list.
692 Unsupported,
693}
694
695/// What came of `update_pull_branch` (or the work service's `catch_up_pull`).
696#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
697#[serde(tag = "outcome", rename_all = "snake_case")]
698pub enum PullBranchUpdate {
699 /// The merge commit was pushed: the branch moved from `previous` to
700 /// `commit`.
701 Updated { commit: String, previous: String },
702 /// The source already holds the default branch's head.
703 UpToDate { commit: String },
704 /// Nothing was pushed; a sandbox has to merge it. `paths` are the
705 /// files both sides changed, or that conflict, when known.
706 NeedsAgent {
707 reason: NeedsAgentReason,
708 detail: String,
709 paths: Vec<String>,
710 },
711}
712
713/// `head`: the commit a branch points to, or null. For services reacting
714/// to a push, which have no viewer; it reveals nothing but a commit hash.
715/// Returns `Option<String>`.
716#[derive(Debug, Serialize, Deserialize)]
717#[serde(rename_all = "camelCase")]
718pub struct HeadArgs {
719 pub repo_id: String,
720 /// Empty for the repository's default branch.
721 pub branch: String,
722}
723
724/// Where g1t keeps branches of its own in a repository, such as the merge
725/// queue's tested states. Only these can be removed with `delete_branch`.
726pub const G1T_BRANCH_PREFIX: &str = "g1t-";
727
728/// `delete_branch`: removes a branch g1t made for itself once it is done
729/// with it, never one of people's: the name must start with
730/// [`G1T_BRANCH_PREFIX`]. For services, which have no viewer. Returns
731/// `Outcome<bool>`: whether there was such a branch.
732#[derive(Debug, Serialize, Deserialize)]
733#[serde(rename_all = "camelCase")]
734pub struct DeleteBranchArgs {
735 pub repo_id: String,
736 pub branch: String,
737}
738
739/// `commit_file`: writes one file on a new branch made from the default
740/// branch's head, as one commit by `actor`, without a sandbox. For a change
741/// g1t proposes on someone's behalf, such as a starter workflow, which then
742/// becomes a pull request. Refused unless `actor` may push, when the branch
743/// already exists, or when the file is already there. Returns
744/// `Outcome<CommittedFile>`.
745#[derive(Debug, Serialize, Deserialize)]
746#[serde(rename_all = "camelCase")]
747pub struct CommitFileArgs {
748 pub repo: RepoPath,
749 pub actor: User,
750 /// The new branch, which must not exist yet.
751 pub branch: String,
752 /// Where the file goes, such as `.g1t/workflows/ci.yml`.
753 pub path: String,
754 pub content: String,
755 pub message: String,
756}
757
758/// The commit `commit_file` made.
759#[derive(Clone, Debug, Serialize, Deserialize)]
760#[serde(rename_all = "camelCase")]
761pub struct CommittedFile {
762 pub branch: String,
763 pub commit: String,
764}
765
766/// `readable`: of these repository ids, the repositories the viewer may
767/// read, as `get_by_id` decides; forks and unknown ids are left out. For
768/// services that hold ids and must show only what the viewer could open.
769/// At most [`MAX_READABLE`] ids are looked at. Returns `Vec<Repo>`.
770#[derive(Debug, Serialize, Deserialize)]
771pub struct ReadableArgs {
772 pub ids: Vec<String>,
773 pub viewer: Viewer,
774}
775
776/// The most ids one `readable` call looks at.
777pub const MAX_READABLE: usize = 500;
778
779/// `public_namespaces`: the workspaces in which this account made a public
780/// repository, and so a public project, which anyone can see on its page.
781/// Returns `Vec<String>` of workspace slugs.
782#[derive(Debug, Serialize, Deserialize)]
783#[serde(rename_all = "camelCase")]
784pub struct PublicNamespacesArgs {
785 pub owner_id: String,
786}
787
788/// One file on a branch, or one a change touched: its path and blob.
789#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
790pub struct FileEntry {
791 pub path: String,
792 /// The blob it holds now; null when the change deleted it.
793 pub hash: Option<String>,
794}
795
796/// Files, and whether there were more than were listed.
797#[derive(Clone, Debug, Default, Serialize, Deserialize)]
798#[serde(rename_all = "camelCase")]
799pub struct FileList {
800 /// The commit the files were read at; null for an empty repository.
801 pub commit: Option<String>,
802 pub files: Vec<FileEntry>,
803 pub truncated: bool,
804}
805
806/// `list_files`: every file on a branch (the default branch when absent),
807/// path order by level, never descending into a directory named in
808/// `skip_dirs`. For services that index a repository; no viewer, since it
809/// is only reached by g1t's own services. Returns `FileList`.
810#[derive(Debug, Default, Serialize, Deserialize)]
811#[serde(rename_all = "camelCase")]
812pub struct ListFilesArgs {
813 pub repo_id: String,
814 #[serde(default, rename = "ref")]
815 pub git_ref: Option<String>,
816 #[serde(default)]
817 pub skip_dirs: Vec<String>,
818 /// At most this many files; capped at [`MAX_LISTED_FILES`].
819 pub limit: u32,
820}
821
822/// `changed_files`: the files that differ between two commits, as
823/// `list_files` reads them. With no `base`, every file at `head`. Returns
824/// `FileList`.
825#[derive(Debug, Default, Serialize, Deserialize)]
826#[serde(rename_all = "camelCase")]
827pub struct ChangedFilesArgs {
828 pub repo_id: String,
829 #[serde(default)]
830 pub base: Option<String>,
831 pub head: String,
832 #[serde(default)]
833 pub skip_dirs: Vec<String>,
834 pub limit: u32,
835}
836
837/// The most files one `list_files` or `changed_files` call lists.
838pub const MAX_LISTED_FILES: u32 = 10_000;
839
840/// `read_blobs`: the text of these blobs of a repository, for services
841/// that index it. A blob larger than `max_bytes`, or binary, comes back
842/// with no text. Returns `Vec<BlobText>`, in the order asked.
843#[derive(Debug, Default, Serialize, Deserialize)]
844#[serde(rename_all = "camelCase")]
845pub struct ReadBlobsArgs {
846 pub repo_id: String,
847 pub hashes: Vec<String>,
848 pub max_bytes: u32,
849}
850
851/// The most blobs one `read_blobs` call reads.
852pub const MAX_READ_BLOBS: usize = 100;
853
854/// `refs`: a repository's branches and tags with the commit each points to
855/// (annotated tags peeled), for services that follow them, such as the
856/// packages service's Composer registry. No viewer: g1t's own services
857/// only. Returns `Option<RepoRefs>`, null for a fork or an unknown id.
858#[derive(Debug, Default, Serialize, Deserialize)]
859#[serde(rename_all = "camelCase")]
860pub struct RefsArgs {
861 pub repo_id: String,
862}
863
864#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
865pub struct GitRefEntry {
866 /// The full ref: `refs/heads/main`, `refs/tags/v1.0.0`.
867 pub name: String,
868 pub commit: String,
869}
870
871#[derive(Clone, Debug, Serialize, Deserialize)]
872pub struct RepoRefs {
873 pub repo: Repo,
874 pub refs: Vec<GitRefEntry>,
875}
876
877/// `raw_file`: one file's bytes at a ref or commit, base64, for g1t's own
878/// services (no viewer). Returns `Option<RawFile>`: null when the file is
879/// missing or larger than `max_bytes`.
880#[derive(Debug, Default, Serialize, Deserialize)]
881#[serde(rename_all = "camelCase")]
882pub struct RawFileArgs {
883 pub repo_id: String,
884 #[serde(rename = "ref")]
885 pub git_ref: String,
886 pub path: String,
887 pub max_bytes: u32,
888}
889
890#[derive(Clone, Debug, Serialize, Deserialize)]
891pub struct RawFile {
892 pub size: u64,
893 /// Standard base64.
894 pub data: String,
895}
896
897/// `raw_blobs`: blobs' bytes, base64, in the order asked, at most
898/// [`MAX_READ_BLOBS`]; `data` is null for one missing or larger than
899/// `max_bytes`. For g1t's own services. Returns `Vec<RawBlob>`.
900#[derive(Debug, Default, Serialize, Deserialize)]
901#[serde(rename_all = "camelCase")]
902pub struct RawBlobsArgs {
903 pub repo_id: String,
904 pub hashes: Vec<String>,
905 pub max_bytes: u32,
906}
907
908#[derive(Clone, Debug, Serialize, Deserialize)]
909pub struct RawBlob {
910 pub hash: String,
911 pub size: u64,
912 pub data: Option<String>,
913}
914
915#[derive(Clone, Debug, Serialize, Deserialize)]
916pub struct BlobText {
917 pub hash: String,
918 pub size: u64,
919 /// Null when the blob is missing, binary or larger than asked.
920 pub text: Option<String>,
921}
922
923/// `all_ids`: every repository that is not a fork, by id, a page at a
924/// time, for services that index all of them. Returns `IdPage`.
925#[derive(Debug, Default, Serialize, Deserialize)]
926pub struct AllIdsArgs {
927 /// Ids after this one.
928 #[serde(default)]
929 pub after: Option<String>,
930 pub limit: u32,
931}
932
933#[derive(Clone, Debug, Default, Serialize, Deserialize)]
934pub struct IdPage {
935 pub ids: Vec<String>,
936 /// Where the next page starts; null on the last.
937 pub next: Option<String>,
938}
939
940/// `visibility`: which of these repositories (`namespace/name`) are
941/// private, for billing, which pays for work on public ones from g1t's
942/// open-source pool. A pull request's working copy answers as the
943/// repository it is a copy of. Unknown paths are left out. Returns
944/// `Vec<RepoVisibility>`.
945#[derive(Debug, Default, Serialize, Deserialize)]
946pub struct VisibilityArgs {
947 pub paths: Vec<String>,
948}
949
950#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
951pub struct RepoVisibility {
952 pub path: String,
953 pub is_private: bool,
954}
955
956/// `git_operations`: how many git operations (clones, fetches and pushes
957/// through g1t's git endpoints) each workspace's repositories had in a
958/// month, for billing's git meter. Cloudflare Artifacts charges per
959/// operation from 2026-10-14. Pushes from agents' sandboxes go to the
960/// store directly and are not counted here. Returns
961/// `Vec<WorkspaceGitOperations>`.
962#[derive(Debug, Serialize, Deserialize)]
963pub struct GitOperationsArgs {
964 /// YYYY-MM.
965 pub month: String,
966 /// Count only from this hour on, `YYYY-MM-DDTHH`, such as the day the
967 /// provider starts charging.
968 #[serde(default)]
969 pub since: Option<String>,
970 /// One workspace only; every workspace with any when absent.
971 #[serde(default)]
972 pub namespace: Option<String>,
973}
974
975#[derive(Clone, Debug, Serialize, Deserialize)]
976pub struct WorkspaceGitOperations {
977 pub namespace: String,
978 pub operations: u64,
979}
980
981/// `storage`: what each workspace's private repositories hold, as far as
982/// g1t can measure it, for billing's daily storage meter. Returns
983/// `Vec<WorkspaceStorage>`.
984///
985/// The git store does not report a repository's size. What is counted is
986/// the bytes of every pack pushed through g1t's git endpoints to the
987/// repository or to its pull requests' working copies. Pushes made from
988/// agents' sandboxes, which go to the store directly, and imports are not
989/// counted, so it is a lower bound on what is stored.
990#[derive(Debug, Default, Serialize, Deserialize)]
991pub struct StorageArgs {}
992
993#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
994pub struct WorkspaceStorage {
995 pub namespace: String,
996 pub private_bytes: i64,
997 pub public_bytes: i64,
998}
999
1000/// `transfer`: moves a repository to another workspace, keeping its name,
1001/// its id and everything kept under it. The actor must own both
1002/// workspaces. The old path keeps working as a redirect (see
1003/// `resolve_path`) until a repository is made there. Publishes
1004/// `repo.transferred`. Returns `Outcome<Repo>`, the repository at its new
1005/// path.
1006#[derive(Debug, Serialize, Deserialize)]
1007#[serde(rename_all = "camelCase")]
1008pub struct TransferArgs {
1009 pub actor: User,
1010 pub path: RepoPath,
1011 /// The destination workspace's slug.
1012 pub to: String,
1013 /// Where the request came in, for the audit log; g1t.sh when absent.
1014 #[serde(default)]
1015 pub surface: Option<crate::audit::Surface>,
1016}
1017
1018/// `resolve_path`: where a repository that was transferred away from
1019/// `path` is now, while nothing else is there. Returns `Option<RepoPath>`:
1020/// null when `path` is a repository, or never was one that moved. Callers
1021/// check the viewer may see the repository at its new path, as for any
1022/// other.
1023#[derive(Debug, Serialize, Deserialize)]
1024pub struct ResolvePathArgs {
1025 pub path: RepoPath,
1026}
1027
1028/// `namespace_count`: how many repositories (not pull request working
1029/// copies) a workspace holds, private or not, for deciding whether it can
1030/// be deleted. Returns `u32`.
1031#[derive(Debug, Serialize, Deserialize)]
1032pub struct NamespaceCountArgs {
1033 pub namespace: String,
1034}
1035
1036/// `delete`: deletes a repository. Owners of its workspace only, who type
1037/// its full name (`namespace/name`) as `confirm`. It is hidden at once,
1038/// git refuses it, and nothing runs for it; it can be restored for
1039/// [`RESTORE_DAYS`] days, then it is purged, its git data with it. Its
1040/// name stays taken until then, or until it is purged sooner from the
1041/// workspace's Recently deleted list. Publishes `repo.deleted`. Returns
1042/// `Outcome<DeletedRepo>`.
1043#[derive(Debug, Serialize, Deserialize)]
1044#[serde(rename_all = "camelCase")]
1045pub struct DeleteArgs {
1046 pub actor: User,
1047 pub path: RepoPath,
1048 #[serde(default)]
1049 pub confirm: String,
1050 #[serde(default)]
1051 pub surface: Option<crate::audit::Surface>,
1052}
1053
1054/// `deleted`: a workspace's recently deleted repositories, newest first.
1055/// Owners only; empty for anyone else. Returns `Vec<DeletedRepo>`.
1056#[derive(Debug, Serialize, Deserialize)]
1057pub struct DeletedArgs {
1058 pub viewer: Viewer,
1059 pub namespace: String,
1060}
1061
1062/// `restore` and `purge`: a deleted repository, by the path it had.
1063/// `restore` brings it back as it was, at that path (`repo.restored`).
1064/// `purge` removes it for good now, its git data with it, and frees its
1065/// name (`repo.purged`); it takes the full name typed as `confirm`.
1066/// Owners only. Return `Outcome<Repo>` and `Outcome<bool>`.
1067#[derive(Debug, Serialize, Deserialize)]
1068#[serde(rename_all = "camelCase")]
1069pub struct DeletedRepoArgs {
1070 pub actor: User,
1071 pub path: RepoPath,
1072 #[serde(default)]
1073 pub confirm: Option<String>,
1074 #[serde(default)]
1075 pub surface: Option<crate::audit::Surface>,
1076}
1077
1078/// `purge_due`: purges deleted repositories whose time has passed, at
1079/// most `limit` (25 when absent). The service's own schedule runs it.
1080/// Returns `u32`, how many were purged.
1081#[derive(Debug, Default, Serialize, Deserialize)]
1082pub struct PurgeDueArgs {
1083 #[serde(default)]
1084 pub limit: Option<u32>,
1085}
1086
1087/// `rename`: gives a repository a new name in its workspace, keeping its
1088/// id, its git data and everything kept under it. Owners only. The old
1089/// path keeps redirecting, as after a transfer, until a repository is made
1090/// there. Publishes `repo.renamed`. Returns `Outcome<Repo>`.
1091#[derive(Debug, Serialize, Deserialize)]
1092#[serde(rename_all = "camelCase")]
1093pub struct RenameArgs {
1094 pub actor: User,
1095 pub path: RepoPath,
1096 pub name: String,
1097 #[serde(default)]
1098 pub surface: Option<crate::audit::Surface>,
1099}
1100
1101/// `archive`: makes a repository read-only (`archived: true`), or writable
1102/// again. Owners only. While archived, pushes and merges are refused,
1103/// issues and pull requests are locked, and agents and workflows do not
1104/// run; deployments keep serving. Publishes `repo.archived` or
1105/// `repo.unarchived`. Returns `Outcome<Repo>`.
1106#[derive(Debug, Serialize, Deserialize)]
1107#[serde(rename_all = "camelCase")]
1108pub struct ArchiveArgs {
1109 pub actor: User,
1110 pub path: RepoPath,
1111 pub archived: bool,
1112 #[serde(default)]
1113 pub surface: Option<crate::audit::Surface>,
1114}
1115
1116/// `set_visibility`: makes a repository public or private. Owners only,
1117/// who type its full name as `confirm`. A free workspace takes a private
1118/// repository only while its private storage has room. Publishes
1119/// `repo.updated` and `repo.visibility_changed`. Returns `Outcome<Repo>`.
1120#[derive(Debug, Serialize, Deserialize)]
1121#[serde(rename_all = "camelCase")]
1122pub struct SetVisibilityArgs {
1123 pub actor: User,
1124 pub path: RepoPath,
1125 pub is_private: bool,
1126 #[serde(default)]
1127 pub confirm: String,
1128 #[serde(default)]
1129 pub surface: Option<crate::audit::Surface>,
1130}
1131
1132/// `set_default_branch`: makes another existing branch the one everything
1133/// lands on. Members of its workspace. Open pull requests then merge into
1134/// it. Publishes `repo.default_branch_changed`. Returns `Outcome<Repo>`.
1135#[derive(Debug, Serialize, Deserialize)]
1136#[serde(rename_all = "camelCase")]
1137pub struct SetDefaultBranchArgs {
1138 pub actor: User,
1139 pub path: RepoPath,
1140 pub branch: String,
1141 #[serde(default)]
1142 pub surface: Option<crate::audit::Surface>,
1143}
1144
1145/// `rename_branch`: renames a branch. Members of its workspace; only an
1146/// owner renames the default branch, which stays the default. Pull
1147/// requests from it follow, and web addresses naming the old branch
1148/// redirect until a branch of that name is made again. Publishes
1149/// `branch.renamed` (and `repo.default_branch_changed` for the default).
1150/// Returns `Outcome<Repo>`.
1151#[derive(Debug, Serialize, Deserialize)]
1152#[serde(rename_all = "camelCase")]
1153pub struct RenameBranchArgs {
1154 pub actor: User,
1155 pub path: RepoPath,
1156 pub from: String,
1157 pub to: String,
1158 #[serde(default)]
1159 pub surface: Option<crate::audit::Surface>,
1160}
1161
1162/// `resolve_branch`: what a branch renamed away from `branch` is called
1163/// now, for web addresses that name the old one; null when `branch` was
1164/// never renamed or exists again. Returns `Option<String>`.
1165#[derive(Debug, Serialize, Deserialize)]
1166#[serde(rename_all = "camelCase")]
1167pub struct ResolveBranchArgs {
1168 pub repo_id: String,
1169 pub branch: String,
1170}
1171
1172/// `status_by_id`: whether a repository is archived or deleted, for g1t's
1173/// own services deciding whether to act on it. An unknown id answers as
1174/// deleted. Returns `RepoStatus`.
1175#[derive(Debug, Serialize, Deserialize)]
1176pub struct StatusByIdArgs {
1177 pub id: String,
1178}
1179
1180#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
1181pub struct RepoStatus {
1182 pub archived: bool,
1183 pub deleted: bool,
1184}
1185
1186impl RepoStatus {
1187 /// Whether work may start on it: neither archived nor deleted.
1188 pub fn active(&self) -> bool {
1189 !self.archived && !self.deleted
1190 }
1191}
1192
1193/// What a person is told when something would change an archived
1194/// repository.
1195pub fn archived_message(namespace: &str, name: &str) -> String {
1196 format!(
1197 "{namespace}/{name} is archived, so it is read-only. An owner can unarchive it in its settings."
1198 )
1199}
1200
1201/// The path a repository was transferred from, and when, as `transfer`
1202/// keeps it so old addresses redirect.
1203#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1204#[serde(rename_all = "camelCase")]
1205pub struct RepoRedirect {
1206 pub from: RepoPath,
1207 pub repo_id: String,
1208 /// RFC 3339.
1209 pub created_at: String,
1210}
1211
1212#[cfg(test)]
1213mod topic_tests {
1214 use super::*;
1215
1216 fn topics(list: &[&str]) -> Result<Vec<String>, String> {
1217 clean_topics(&list.iter().map(|t| t.to_string()).collect::<Vec<_>>())
1218 }
1219
1220 #[test]
1221 fn topics_are_tidied() {
1222 assert_eq!(topics(&["Rust", " web_server ", "rust", ""]).unwrap(), vec!["rust", "web-server"]);
1223 }
1224
1225 #[test]
1226 fn websites_are_tidied() {
1227 assert_eq!(clean_website(" example.com ").unwrap().as_deref(), Some("https://example.com"));
1228 assert_eq!(clean_website("http://a.io/x").unwrap().as_deref(), Some("http://a.io/x"));
1229 assert_eq!(clean_website("").unwrap(), None);
1230 assert!(clean_website("ftp://a.io").is_err());
1231 assert!(clean_website("localhost").is_err());
1232 assert!(clean_website("https://a b.io").is_err());
1233 }
1234
1235 #[test]
1236 fn branch_names_follow_git() {
1237 for good in ["main", "trunk", "release/1.2", "feat-x_y"] {
1238 assert!(is_valid_branch_name(good), "{good}");
1239 }
1240 for bad in ["", "-x", "a..b", "a b", "x.lock", "a/", ".hidden", "a/.b", "g1t-queue", "a~1", "a:b", "@"] {
1241 assert!(!is_valid_branch_name(bad), "{bad}");
1242 }
1243 }
1244
1245 #[test]
1246 fn odd_topics_are_refused() {
1247 assert!(topics(&["c++"]).is_err());
1248 assert!(topics(&["-lead"]).is_err());
1249 assert!(topics(&[&"a".repeat(36)]).is_err());
1250 let many: Vec<String> = (0..21).map(|i| format!("t{i}")).collect();
1251 assert!(clean_topics(&many).is_err());
1252 }
1253}
1254
1255#[cfg(test)]
1256mod tests {
1257 use super::*;
1258
1259 #[test]
1260 fn a_pull_branch_update_reads_as_the_web_expects() {
1261 let update = PullBranchUpdate::NeedsAgent {
1262 reason: NeedsAgentReason::Overlap,
1263 detail: "both".into(),
1264 paths: vec!["a.rs".into()],
1265 };
1266 assert_eq!(
1267 serde_json::to_value(&update).unwrap(),
1268 serde_json::json!({ "outcome": "needs_agent", "reason": "overlap", "detail": "both", "paths": ["a.rs"] })
1269 );
1270 let done = PullBranchUpdate::UpToDate { commit: "c".into() };
1271 assert_eq!(serde_json::to_value(&done).unwrap(), serde_json::json!({ "outcome": "up_to_date", "commit": "c" }));
1272 }
1273}