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