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