|
1 | | -//! Project settings the domain reads. |
| 1 | +//! Projects: making one, its settings (as the MCP tools and the web app read and change them), and what the domain |
| 2 | +//! reads from them. |
2 | 3 |
|
3 | 4 | use visualci_core::config::ScopedIgnoreRule; |
4 | 5 |
|
@@ -39,3 +40,281 @@ pub fn diff_options( |
39 | 40 | pub fn renderer_key(engine: &str, dpi: i32, renderer_version: &str) -> String { |
40 | 41 | format!("{engine}/{dpi}dpi/{renderer_version}") |
41 | 42 | } |
| 43 | + |
| 44 | +/// Lowercase letters, digits and dashes, at most 60, and not `billing` (the organization's billing page is |
| 45 | +/// `app.visualci.com/<org>/billing`). |
| 46 | +#[must_use] |
| 47 | +pub fn valid_slug(s: &str) -> bool { |
| 48 | + !s.is_empty() |
| 49 | + && s.len() <= 60 |
| 50 | + && s.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') |
| 51 | + && s != "billing" |
| 52 | +} |
| 53 | + |
| 54 | +/// A project's settings, as the web app shows them and the MCP server returns them. |
| 55 | +#[derive(Debug, Clone, serde::Serialize)] |
| 56 | +pub struct Settings { |
| 57 | + pub slug: String, |
| 58 | + pub name: String, |
| 59 | + /// The forge the repository is on (`github`), and the repository's URL. |
| 60 | + pub forge: Option<String>, |
| 61 | + pub repository_url: Option<String>, |
| 62 | + /// Whether the forge's app is installed on the repository, so pull requests get VisualCI's check and people's |
| 63 | + /// access follows their permission on it. |
| 64 | + pub forge_app_installed: bool, |
| 65 | + /// When the forge's webhook last delivered a verified event, or VisualCI added it (GitLab). |
| 66 | + pub forge_webhook_at: Option<String>, |
| 67 | + /// Whether the screenshots visualci.yml's `gallery` names are public. |
| 68 | + pub gallery_enabled: bool, |
| 69 | + /// Whether project tokens may approve changes over MCP; off keeps approving with people. |
| 70 | + pub tokens_can_approve: bool, |
| 71 | + /// Whether VisualCI comments on a pull request whose builds are all unchanged. Off by default: the VisualCI check |
| 72 | + /// still passes, and a comment already there (an earlier build had changes) keeps being updated. |
| 73 | + pub comment_when_unchanged: bool, |
| 74 | + /// Whether anyone, signed in or not, can read the project's builds and diffs (open source). Settings, tokens and |
| 75 | + /// reviewing stay with its members. |
| 76 | + pub public: bool, |
| 77 | + /// The forge says the linked repository is public (checked on linking and once a day). Only then can the project |
| 78 | + /// be public. |
| 79 | + pub repository_public: bool, |
| 80 | + /// The forge verified the repository as public with an OSI-approved licence (checked on linking and once a day). |
| 81 | + pub open_source: bool, |
| 82 | + /// Why it isn't open source, or its licence when it is. |
| 83 | + pub open_source_note: Option<String>, |
| 84 | + /// Whether its builds draw from the open source pool now: open source, public, and not withdrawn by staff. |
| 85 | + pub open_source_pool: bool, |
| 86 | + pub open_source_withdrawn: bool, |
| 87 | + /// A change VisualCI made on its own (made private when its repository went private), until it's dismissed. |
| 88 | + pub notice: Option<String>, |
| 89 | + pub default_branch: String, |
| 90 | + pub ci_mode: String, |
| 91 | + pub renderer: String, |
| 92 | + pub dpi: i32, |
| 93 | + pub threshold: f64, |
| 94 | + pub ignore_anti_aliasing: bool, |
| 95 | + pub ignore_rules: Vec<ScopedIgnoreRule>, |
| 96 | +} |
| 97 | + |
| 98 | +impl From<&Project> for Settings { |
| 99 | + fn from(p: &Project) -> Self { |
| 100 | + Self { |
| 101 | + slug: p.slug.clone(), |
| 102 | + name: p.name.clone(), |
| 103 | + forge: p.forge.clone(), |
| 104 | + repository_url: p.repository_url.clone(), |
| 105 | + forge_app_installed: p.forge_installation.is_some(), |
| 106 | + forge_webhook_at: p.forge_webhook_at.map(|d| d.to_string()), |
| 107 | + gallery_enabled: p.gallery_enabled, |
| 108 | + tokens_can_approve: p.tokens_can_approve, |
| 109 | + comment_when_unchanged: p.comment_when_unchanged, |
| 110 | + public: p.public, |
| 111 | + repository_public: p.repository_public, |
| 112 | + open_source: p.open_source, |
| 113 | + open_source_note: p.open_source_note.clone(), |
| 114 | + open_source_pool: super::credits::counts_as_open_source(p), |
| 115 | + open_source_withdrawn: p.open_source_withdrawn, |
| 116 | + notice: p.notice.clone(), |
| 117 | + default_branch: p.default_branch.clone(), |
| 118 | + ci_mode: p.ci_mode.clone(), |
| 119 | + renderer: p.renderer.clone(), |
| 120 | + dpi: p.dpi, |
| 121 | + threshold: p.threshold, |
| 122 | + ignore_anti_aliasing: p.ignore_anti_aliasing, |
| 123 | + ignore_rules: ignore_rules(p), |
| 124 | + } |
| 125 | + } |
| 126 | +} |
| 127 | + |
| 128 | +/// Changes to a project's settings; fields left out stay as they are. |
| 129 | +#[derive(Debug, Default, serde::Deserialize, schemars::JsonSchema)] |
| 130 | +pub struct SettingsChange { |
| 131 | + /// A new slug, renaming the project (`acme/old` → `acme/new`): lowercase letters, digits and dashes. Its builds, |
| 132 | + /// baselines and tokens stay. The old address and `acme/old` stop working. |
| 133 | + pub slug: Option<String>, |
| 134 | + /// The project's display name. |
| 135 | + pub name: Option<String>, |
| 136 | + /// The repository this project tests, by URL (`https://github.com/acme/web`); an empty string unlinks it. |
| 137 | + /// Linking needs the forge's VisualCI app installed on the repository and you to be an admin or maintainer of |
| 138 | + /// it there. Its pull requests then get VisualCI's check, and people's access to this organization follows their |
| 139 | + /// permission on it. |
| 140 | + pub repository_url: Option<String>, |
| 141 | + /// A project on your organization's own GitLab instance: an access token for it (a project or group access token |
| 142 | + /// with the `api` scope and the Developer role, or Maintainer to let VisualCI add its webhook), sent with |
| 143 | + /// `repository_url`. Stored encrypted; never shown again. |
| 144 | + pub forge_token: Option<String>, |
| 145 | + /// With `repository_url`: a repository belongs to one organization, so when another organization has it linked, |
| 146 | + /// `true` moves the link here (you must maintain the repository; that organization's admins get an email). |
| 147 | + #[serde(default)] |
| 148 | + pub move_link: bool, |
| 149 | + /// `false` takes the public gallery down (visualci.yml's `gallery` decides what's in it); `true` puts it back. |
| 150 | + pub gallery_enabled: Option<bool>, |
| 151 | + /// `false`: project tokens can't approve changes (people do); `true` lets CI's agents approve again. |
| 152 | + pub tokens_can_approve: Option<bool>, |
| 153 | + /// `true`: comment on pull requests even when nothing changed. `false` (the default): a pull request whose builds |
| 154 | + /// are all unchanged gets no comment, only the passing check; a comment already there keeps being updated. |
| 155 | + pub comment_when_unchanged: Option<bool>, |
| 156 | + /// `true` lets anyone, signed in or not, read the project's builds and diffs (for open source projects); |
| 157 | + /// settings, tokens and reviewing stay with its members. Only a project linked to a public repository can be |
| 158 | + /// public. `false` makes it private again. |
| 159 | + pub public: Option<bool>, |
| 160 | + /// `true` dismisses the project's notice. |
| 161 | + pub dismiss_notice: Option<bool>, |
| 162 | + /// The branch whose builds become the baseline automatically. |
| 163 | + pub default_branch: Option<String>, |
| 164 | + /// `review` (CI passes, the check waits for review), `strict` (CI fails on unreviewed changes) or `wait`. |
| 165 | + pub ci_mode: Option<String>, |
| 166 | + /// The PDF renderer: `pdfbox` or `mutool`. |
| 167 | + pub renderer: Option<String>, |
| 168 | + /// Render resolution for documents, 36 to 600. |
| 169 | + pub dpi: Option<i32>, |
| 170 | + /// The diff threshold, 0 to 1: 0 compares exactly; above 0 it's pixelmatch's colour threshold (how different a |
| 171 | + /// pixel's colour must be to count), and anti-aliased pixels are ignored. |
| 172 | + pub threshold: Option<f64>, |
| 173 | + /// Ignore anti-aliasing differences in images. |
| 174 | + pub ignore_anti_aliasing: Option<bool>, |
| 175 | + /// Values in text snapshots that change on every run, ignored when comparing. Replaces the project's rules. Each |
| 176 | + /// rule names the snapshots it applies to with a glob (`api/invoices/**`; `**` for every snapshot). A build's |
| 177 | + /// `visualci.yml` replaces these rules when it has `ignore`. |
| 178 | + pub ignore_rules: Option<Vec<ScopedIgnoreRule>>, |
| 179 | +} |
| 180 | + |
| 181 | +/// Make a project in an organization, with the default settings. |
| 182 | +/// |
| 183 | +/// # Errors |
| 184 | +/// `Ok(Err(message))` for a slug that isn't valid or is taken; `Err` on a database error. |
| 185 | +pub async fn create(organization_id: i64, slug: &str, name: &str) -> laravel::Result<Result<Project, String>> { |
| 186 | + if !valid_slug(slug) { |
| 187 | + return Ok(Err("project slugs use lowercase letters, digits and dashes, and can't be billing".into())); |
| 188 | + } |
| 189 | + let taken = |
| 190 | + Project::query().filter(Project::organization_id.eq(organization_id) & Project::slug.eq(slug)).exists().await?; |
| 191 | + if taken { |
| 192 | + return Ok(Err(format!("the organization already has a project called {slug}"))); |
| 193 | + } |
| 194 | + let name = name.trim(); |
| 195 | + Ok(Ok(laravel::model::create!(Project { |
| 196 | + pid: laravel::str::uuid7(), |
| 197 | + organization_id: organization_id, |
| 198 | + slug: slug, |
| 199 | + name: name, |
| 200 | + }) |
| 201 | + .await?)) |
| 202 | +} |
| 203 | + |
| 204 | +/// The repository its newest CI build named (`environment_info.repository_url`), for suggesting a link. |
| 205 | +/// |
| 206 | +/// # Errors |
| 207 | +/// On a database error. |
| 208 | +pub async fn repository_seen_in_ci(project: &Project) -> laravel::Result<Option<String>> { |
| 209 | + let project_id = project.id; |
| 210 | + let info: Option<serde_json::Value> = laravel::db::query!( |
| 211 | + "SELECT environment_info FROM builds WHERE project_id = {project_id} AND mode = 'ci' ORDER BY id DESC LIMIT 1" |
| 212 | + ) |
| 213 | + .scalar() |
| 214 | + .await?; |
| 215 | + Ok(info |
| 216 | + .as_ref() |
| 217 | + .and_then(|i| i.get("repository_url")) |
| 218 | + .and_then(|v| v.as_str()) |
| 219 | + .and_then(crate::forge::Repository::parse) |
| 220 | + .map(|r| r.url)) |
| 221 | +} |
| 222 | + |
| 223 | +/// Apply a settings change, checking every field first. The repository link isn't set here: it needs the forge to agree |
| 224 | +/// (subdomains' `forge::link::link_repository`), which callers do first. Turning the gallery off purges what it |
| 225 | +/// published first. |
| 226 | +/// |
| 227 | +/// # Errors |
| 228 | +/// `Ok(Err(message))` for a value that isn't valid; `Err` on a database error. |
| 229 | +pub async fn change_settings(project: Project, p: SettingsChange) -> laravel::Result<Result<Project, String>> { |
| 230 | + let new_slug = p.slug.as_deref().map(str::trim).filter(|s| *s != project.slug).map(str::to_string); |
| 231 | + if let Some(slug) = &new_slug { |
| 232 | + if !valid_slug(slug) { |
| 233 | + return Ok(Err("slug must be lowercase letters, digits and dashes, at most 60 characters".into())); |
| 234 | + } |
| 235 | + let taken = Project::query() |
| 236 | + .filter(Project::organization_id.eq(project.organization_id) & Project::slug.eq(slug.as_str())) |
| 237 | + .exists() |
| 238 | + .await?; |
| 239 | + if taken { |
| 240 | + return Ok(Err(format!("the organization already has a project called {slug}"))); |
| 241 | + } |
| 242 | + } |
| 243 | + // A private repository's screenshots stay private: only a project whose repository the forge says is public can |
| 244 | + // be made public. |
| 245 | + if p.public == Some(true) && !project.public && !project.repository_public { |
| 246 | + return Ok(Err("only a project linked to a public repository can be public".into())); |
| 247 | + } |
| 248 | + if let Some(m) = &p.ci_mode |
| 249 | + && !["review", "strict", "wait"].contains(&m.as_str()) |
| 250 | + { |
| 251 | + return Ok(Err("ci_mode must be review, strict or wait".into())); |
| 252 | + } |
| 253 | + if let Some(r) = &p.renderer |
| 254 | + && !["pdfbox", "mutool"].contains(&r.as_str()) |
| 255 | + { |
| 256 | + return Ok(Err("renderer must be pdfbox or mutool".into())); |
| 257 | + } |
| 258 | + if p.dpi.is_some_and(|d| !(36..=600).contains(&d)) { |
| 259 | + return Ok(Err("dpi must be 36 to 600".into())); |
| 260 | + } |
| 261 | + if p.threshold.is_some_and(|t| !(0.0..=1.0).contains(&t)) { |
| 262 | + return Ok(Err("threshold must be between 0 and 1".into())); |
| 263 | + } |
| 264 | + let ignore_rules = match p.ignore_rules { |
| 265 | + Some(rules) => { |
| 266 | + let clean = |v: Vec<String>| -> Vec<String> { |
| 267 | + v.into_iter().map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect() |
| 268 | + }; |
| 269 | + let rules: Vec<ScopedIgnoreRule> = rules |
| 270 | + .into_iter() |
| 271 | + .map(|r| ScopedIgnoreRule { |
| 272 | + snapshots: r.snapshots.trim().to_string(), |
| 273 | + json_paths: clean(r.json_paths), |
| 274 | + text_patterns: clean(r.text_patterns), |
| 275 | + }) |
| 276 | + .collect(); |
| 277 | + if let Err(e) = visualci_core::config::validate_ignore_rules(&rules) { |
| 278 | + return Ok(Err(e)); |
| 279 | + } |
| 280 | + Some(serde_json::to_value(rules).unwrap_or_default()) |
| 281 | + } |
| 282 | + None => None, |
| 283 | + }; |
| 284 | + if p.gallery_enabled == Some(false) && project.gallery_enabled { |
| 285 | + super::gallery::purge_project(project.id).await?; |
| 286 | + } |
| 287 | + let mut project = project; |
| 288 | + let slug = new_slug.unwrap_or_else(|| project.slug.clone()); |
| 289 | + let name = p.name.unwrap_or_else(|| project.name.clone()); |
| 290 | + let tokens_can_approve = p.tokens_can_approve.unwrap_or(project.tokens_can_approve); |
| 291 | + let comment_when_unchanged = p.comment_when_unchanged.unwrap_or(project.comment_when_unchanged); |
| 292 | + let gallery_enabled = p.gallery_enabled.unwrap_or(project.gallery_enabled); |
| 293 | + let public = p.public.unwrap_or(project.public); |
| 294 | + let notice = if p.dismiss_notice == Some(true) { None } else { project.notice.clone() }; |
| 295 | + let default_branch = p.default_branch.unwrap_or_else(|| project.default_branch.clone()); |
| 296 | + let ci_mode = p.ci_mode.unwrap_or_else(|| project.ci_mode.clone()); |
| 297 | + let renderer = p.renderer.unwrap_or_else(|| project.renderer.clone()); |
| 298 | + let dpi = p.dpi.unwrap_or(project.dpi); |
| 299 | + let threshold = p.threshold.unwrap_or(project.threshold); |
| 300 | + let ignore_anti_aliasing = p.ignore_anti_aliasing.unwrap_or(project.ignore_anti_aliasing); |
| 301 | + let ignore_rules = ignore_rules.unwrap_or_else(|| project.ignore_rules.clone()); |
| 302 | + laravel::model::update!(project { |
| 303 | + slug, |
| 304 | + name, |
| 305 | + tokens_can_approve, |
| 306 | + comment_when_unchanged, |
| 307 | + gallery_enabled, |
| 308 | + public, |
| 309 | + notice, |
| 310 | + default_branch, |
| 311 | + ci_mode, |
| 312 | + renderer, |
| 313 | + dpi, |
| 314 | + threshold, |
| 315 | + ignore_anti_aliasing, |
| 316 | + ignore_rules, |
| 317 | + }) |
| 318 | + .await?; |
| 319 | + Ok(Ok(project)) |
| 320 | +} |
0 commit comments