g1t/services/actions/src/trigger.rs

626 lines27,956 bytesCodeBlame

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

GitHub Actions on g1t, part two: running workflows1//! What starts a run: an event on the bus, a schedule, or someone running a
2//! workflow by hand. Each finds the workflows that want it, at the commit
3//! the event is about, and checks their filters.
4
5use g1t_actions::events::{RunInfo, github_events};
6use g1t_actions::workflow::{self, Trigger, Workflow};
7use g1t_contracts::actions::{DispatchArgs, WorkflowRun};
8use g1t_contracts::events::Event;
9use g1t_contracts::identity::{AGENT_ID, AGENT_NAME, UsernameArgs, UsernamesArgs};
10use g1t_contracts::repos::{Commit, CompareArgs, Comparison, LogArgs, Repo, RepoPath};
11use g1t_contracts::work::{IssueDetail, PullDetail, ViewArgs};
12use g1t_contracts::{FailureCode, Outcome, User, Viewer, new_id};
13use g1t_kit::now_ms;
14use serde_json::{Map, Value, json};
15use worker::Result;
16
17use crate::plan::NewRun;
18use crate::sync::{Read, WorkflowRow};
19use crate::{API, Actions, SITE, check, fail, payload};
20
21/// What an event is about, worked out once for every workflow it starts.
22struct Subject {
23 /// Where the workflow files are read, and at which commit.
24 source: RepoPath,
25 source_ref: Option<String>,
26 git_ref: String,
27 sha: String,
28 head_ref: Option<String>,
29 base_ref: Option<String>,
30 pull: Option<u32>,
31 /// The branch or tag for `branches`/`tags` filters; for pull requests,
32 /// the branch they merge into.
33 filter_ref: String,
34 /// The files it changes, for `paths` filters; `None` until needed.
35 paths: Option<Vec<String>>,
36 /// For a push, what to compare to find the files.
37 compare: Option<(Option<String>, String)>,
38 payload: Value,
39 title: String,
40 trusted: bool,
41}
42
43impl Actions {
44 async fn username(&self, id: Option<&str>) -> Result<Option<String>> {
45 let Some(id) = id else { return Ok(None) };
46 if id == AGENT_ID {
47 return Ok(Some(AGENT_NAME.to_owned()));
48 }
49 let names: std::collections::HashMap<String, String> =
50 g1t_kit::call(&self.identity, "usernames", &UsernamesArgs { ids: vec![id.to_owned()] }).await?;
51 Ok(names.get(id).cloned())
52 }
53
54 /// Whether someone belongs to the workspace, so their pull requests'
55 /// runs get the secrets.
56 async fn insider(&self, author: &User, namespace: &str) -> Result<bool> {
57 if author.id == AGENT_ID || author.is_member(&namespace.to_lowercase()) {
58 return Ok(true);
59 }
60 let found: Viewer = g1t_kit::call(&self.identity, "user_by_username", &UsernameArgs { username: author.username.clone() }).await?;
61 Ok(found.is_some_and(|user| user.is_member(&namespace.to_lowercase())))
62 }
63
64 async fn commits(&self, repo: &Repo, actor: &User, after: &str, before: Option<&str>) -> Result<Vec<Commit>> {
65 let log: Outcome<Vec<Commit>> = g1t_kit::call(
66 &self.repos,
67 "log",
68 &LogArgs {
69 path: RepoPath {
70 namespace: repo.namespace.clone(),
71 name: repo.name.clone(),
72 },
73 viewer: Some(actor.clone()),
74 git_ref: Some(after.to_owned()),
75 limit: 20,
76 },
77 )
78 .await?;
79 let mut commits: Vec<Commit> = log.into_result().unwrap_or_default();
80 if let Some(before) = before
81 && let Some(at) = commits.iter().position(|commit| commit.hash == before)
82 {
83 commits.truncate(at);
84 }
85 // GitHub lists them oldest first, with the head commit last.
86 commits.reverse();
87 Ok(commits)
88 }
89
90 async fn changed_paths(&self, repo: &Repo, actor: &User, base: Option<String>, head: String) -> Result<Vec<String>> {
91 let compared: Outcome<Comparison> = g1t_kit::call(
92 &self.repos,
93 "compare",
94 &CompareArgs {
95 repo_id: repo.id.clone(),
96 viewer: Some(actor.clone()),
97 base,
98 head: Some(head),
99 },
100 )
101 .await?;
102 Ok(compared.into_result().map(|c| c.files.into_iter().map(|f| f.path).collect()).unwrap_or_default())
103 }
104
105 async fn default_head(&self, repo: &Repo) -> Result<Option<String>> {
106 g1t_kit::call(
107 &self.repos,
108 "head",
109 &g1t_contracts::repos::HeadArgs {
110 repo_id: repo.id.clone(),
111 branch: repo.default_branch.clone(),
112 },
113 )
114 .await
115 }
116
117 fn repo_path(repo: &Repo) -> RepoPath {
118 RepoPath {
119 namespace: repo.namespace.clone(),
120 name: repo.name.clone(),
121 }
122 }
123
124 /// The subject of an event of `kind`, as GitHub's `event_name`.
125 async fn subject(&self, event: &Event, event_name: &str, action: Option<&str>, repo: &Repo, ws: &User, sender: &str) -> Result<Option<Subject>> {
126 let path = Self::repo_path(repo);
127 let data = &event.data;
128 let on_default = |sha: String, payload: Value, title: String, pull: Option<u32>| Subject {
129 source: path.clone(),
130 source_ref: None,
131 git_ref: format!("refs/heads/{}", repo.default_branch),
132 sha,
133 head_ref: None,
134 base_ref: None,
135 pull,
136 filter_ref: format!("refs/heads/{}", repo.default_branch),
137 paths: None,
138 compare: None,
139 payload,
140 title,
141 trusted: true,
142 };
143 let view = |number: u32| ViewArgs {
144 repo: path.clone(),
145 number,
146 viewer: Some(ws.clone()),
147 after_seq: 0,
148 };
149 Ok(match event_name {
150 "push" => {
151 let (Some(git_ref), Some(after)) = (data["ref"].as_str(), data["after"].as_str()) else {
152 return Ok(None);
153 };
154 let before = data["before"].as_str();
155 let commits = self.commits(repo, ws, after, before).await?;
156 let title = commits.last().map(|c| c.message.lines().next().unwrap_or_default().to_owned()).unwrap_or_default();
157 let mut payload = payload::push(repo, git_ref, before, after, &commits, sender);
158 if let Some(head) = commits.last() {
159 payload["head_commit"] = payload::commit(repo, head);
160 }
161 Some(Subject {
162 source: path.clone(),
163 source_ref: Some(after.to_owned()),
164 git_ref: git_ref.to_owned(),
165 sha: after.to_owned(),
166 head_ref: None,
167 base_ref: None,
168 pull: None,
169 filter_ref: git_ref.to_owned(),
170 paths: None,
171 compare: Some((before.map(str::to_owned), after.to_owned())),
172 payload,
173 title,
174 trusted: true,
175 })
176 }
177 "pull_request" | "pull_request_target" | "pull_request_review" => {
178 let Some(number) = data["number"].as_u64().map(|n| n as u32) else { return Ok(None) };
179 let detail: Outcome<PullDetail> = g1t_kit::call(&self.work, "get_pull", &view(number)).await?;
180 let Outcome::Ok(detail) = detail else { return Ok(None) };
181 let pull = &detail.pull;
182 let labels = detail.issue.as_ref().map(|i| i.labels.clone()).unwrap_or_default();
183 let mut payload = json!({
184 "action": action,
185 "number": pull.number,
186 "pull_request": payload::pull(repo, pull, &labels),
187 "repository": payload::repository(repo),
188 "sender": payload::user(sender),
189 });
190 if event_name == "pull_request_review" {
191 let review = detail.comments.iter().rev().find(|c| c.verdict.is_some());
192 payload["review"] = json!({
193 "state": review.and_then(|r| r.verdict).map(|v| format!("{v:?}").to_lowercase()),
194 "body": review.map(|r| r.body.clone()),
195 "user": review.map(|r| payload::user(&r.author.username)),
196 });
197 }
198 let trusted = self.insider(&pull.author, &repo.namespace).await?;
199 let head_ref = payload::head_ref(pull);
200 if event_name == "pull_request_target" {
201 // In the base's context: its workflows, its head.
202 let Some(sha) = self.default_head(repo).await? else { return Ok(None) };
203 let mut subject = on_default(sha, payload, pull.title.clone(), Some(pull.number));
204 subject.head_ref = Some(head_ref);
205 subject.base_ref = Some(repo.default_branch.clone());
206 subject.paths = Some(pull.files.iter().map(|f| f.path.clone()).collect());
207 return Ok(Some(subject));
208 }
209 // A merged pull request's run is on the commit it landed as.
210 let sha = match (action, data["commit"].as_str()) {
211 (Some("closed"), Some(commit)) => commit.to_owned(),
212 _ => match &pull.head_commit {
213 Some(head) => head.clone(),
214 None => return Ok(None),
215 },
216 };
217 let source = pull.fork.clone().unwrap_or_else(|| path.clone());
218 Some(Subject {
219 source: if data["commit"].is_string() { path.clone() } else { source },
220 source_ref: Some(sha.clone()),
221 git_ref: format!("refs/pull/{}/merge", pull.number),
222 sha,
223 head_ref: Some(head_ref),
224 base_ref: Some(repo.default_branch.clone()),
225 pull: Some(pull.number),
226 filter_ref: format!("refs/heads/{}", repo.default_branch),
227 paths: Some(pull.files.iter().map(|f| f.path.clone()).collect()),
228 compare: None,
229 payload,
230 title: pull.title.clone(),
231 trusted,
232 })
233 }
234 "issues" | "issue_comment" => {
235 let Some(number) = data["number"].as_u64().map(|n| n as u32) else { return Ok(None) };
236 let Some(sha) = self.default_head(repo).await? else { return Ok(None) };
237 let issue: Outcome<IssueDetail> = g1t_kit::call(&self.work, "get_issue", &view(number)).await?;
238 let (issue_json, comments, title, on_pull) = match issue {
239 Outcome::Ok(detail) => (payload::issue(repo, &detail.issue), detail.comments, detail.issue.title.clone(), false),
240 Outcome::Fail(_) => {
241 let pull: Outcome<PullDetail> = g1t_kit::call(&self.work, "get_pull", &view(number)).await?;
242 let Outcome::Ok(detail) = pull else { return Ok(None) };
243 let labels = detail.issue.as_ref().map(|i| i.labels.clone()).unwrap_or_default();
244 (payload::pull_as_issue(repo, &detail.pull, &labels), detail.comments, detail.pull.title.clone(), true)
245 }
246 };
247 let mut payload = json!({
248 "action": action,
249 "issue": issue_json,
250 "repository": payload::repository(repo),
251 "sender": payload::user(sender),
252 });
253 if event_name == "issue_comment" {
254 let comment_id = data["commentId"].as_str();
255 let comment = comments.iter().find(|c| Some(c.id.as_str()) == comment_id).or(comments.last());
256 match comment {
257 Some(comment) => payload["comment"] = payload::comment(repo, number, comment, on_pull),
258 None => return Ok(None),
259 }
260 }
261 Some(on_default(sha, payload, title, on_pull.then_some(number)))
262 }
263 _ => None,
264 })
265 }
266
267 pub async fn on_event(&self, event: &Event) -> Result<()> {
268 let Some(repo_id) = event.repo_id.as_deref() else { return Ok(()) };
269 let mapped = github_events(&event.kind);
270 let pushed_default = event.kind == "git.push" && event.data["defaultBranch"].as_bool() == Some(true);
271 if mapped.is_empty() && !pushed_default {
272 return Ok(());
273 }
274 let Some((repo, ws)) = self.repo_by_id(repo_id).await? else { return Ok(()) };
275 if pushed_default {
276 self.sync(&repo, &ws).await?;
277 }
278 let sender = self.username(event.actor.as_deref()).await?.unwrap_or_else(|| repo.namespace.clone());
279 for (event_name, action) in mapped {
280 let Some(mut subject) = self.subject(event, event_name, action, &repo, &ws, &sender).await? else {
281 continue;
282 };
283 let read = self.read_workflows(&subject.source, &ws, subject.source_ref.as_deref()).await?;
284 self.start_matching(&repo, &ws, read, &mut subject, event_name, action, &event.id, event.actor.as_deref(), &sender)
285 .await?;
286 }
287 Ok(())
288 }
289
290 #[allow(clippy::too_many_arguments)]
291 async fn start_matching(
292 &self,
293 repo: &Repo,
294 ws: &User,
295 read: Read,
296 subject: &mut Subject,
297 event_name: &str,
298 action: Option<&str>,
299 event_key: &str,
300 actor_id: Option<&str>,
301 sender: &str,
302 ) -> Result<()> {
303 for file in read.files {
304 let parsed = workflow::parse(&file.source);
305 let workflow = match parsed {
306 Ok(workflow) => workflow,
307 Err(problem) => {
308 // A push shows a broken workflow as a failed run, as GitHub does.
309 if event_name == "push" && file.source.contains("on") {
310 self.record_invalid(repo, &file.path, &file.source, subject, event_key, actor_id, sender, &problem)
311 .await?;
312 }
313 continue;
314 }
315 };
316 let Some(trigger) = workflow.trigger(event_name) else { continue };
317 if !trigger.wants_type(action) || !self.passes(repo, ws, trigger, subject, event_name).await? {
318 continue;
319 }
320 if self.disabled(&repo.id, &file.path).await? {
321 continue;
322 }
323 self.create_run(NewRun {
324 repo: repo.clone(),
325 path: file.path,
326 source: file.source,
327 info: self.run_info(repo, &workflow, event_name, subject, sender, actor_id),
328 workflow,
329 action: action.map(str::to_owned),
330 pull: subject.pull,
331 title: subject.title.clone(),
332 inputs: Map::new(),
333 event_key: event_key.to_owned(),
334 actor_id: actor_id.map(str::to_owned),
335 actor: Some(sender.to_owned()),
336 trusted: subject.trusted,
337 })
338 .await?;
339 }
340 Ok(())
341 }
342
343 /// Whether the branch, tag and path filters let the event through.
344 async fn passes(&self, repo: &Repo, ws: &User, trigger: &Trigger, subject: &mut Subject, event_name: &str) -> Result<bool> {
345 let git_ref = subject.filter_ref.as_str();
346 if let Some(tag) = git_ref.strip_prefix("refs/tags/") {
347 // A tag push runs a workflow that filters tags, or filters nothing.
348 if trigger.tags.is_set() {
349 if !trigger.tags.allows(tag) {
350 return Ok(false);
351 }
352 } else if trigger.branches.is_set() {
353 return Ok(false);
354 }
355 // Paths are not checked for tags, as on GitHub.
356 return Ok(true);
357 }
358 let branch = git_ref.strip_prefix("refs/heads/").unwrap_or(git_ref);
359 if trigger.branches.is_set() {
360 if !trigger.branches.allows(branch) {
361 return Ok(false);
362 }
363 } else if event_name == "push" && trigger.tags.is_set() {
364 return Ok(false);
365 }
366 if trigger.paths.is_set() {
367 if subject.paths.is_none() {
368 let (base, head) = subject.compare.clone().unwrap_or((None, subject.sha.clone()));
369 subject.paths = Some(self.changed_paths(repo, ws, base, head).await?);
370 }
371 if !trigger.paths.allows_paths(subject.paths.as_deref().unwrap_or_default()) {
372 return Ok(false);
373 }
374 }
375 Ok(true)
376 }
377
378 async fn disabled(&self, repo_id: &str, path: &str) -> Result<bool> {
379 let row = self
380 .db
381 .prepare("SELECT * FROM workflows WHERE repo_id = ? AND path = ?")
382 .bind(&[repo_id.into(), path.into()])?
383 .first::<WorkflowRow>(None)
384 .await?;
385 Ok(row.is_some_and(|row| row.state == "disabled"))
386 }
387
388 fn run_info(&self, repo: &Repo, workflow: &Workflow, event_name: &str, subject: &Subject, sender: &str, actor_id: Option<&str>) -> RunInfo {
389 RunInfo {
390 repository: format!("{}/{}", repo.namespace, repo.name),
391 repository_id: repo.id.clone(),
392 default_branch: repo.default_branch.clone(),
393 event_name: event_name.to_owned(),
394 event: subject.payload.clone(),
395 git_ref: subject.git_ref.clone(),
396 sha: subject.sha.clone(),
397 head_ref: subject.head_ref.clone(),
398 base_ref: subject.base_ref.clone(),
399 actor: sender.to_owned(),
400 actor_id: actor_id.unwrap_or_default().to_owned(),
401 triggering_actor: sender.to_owned(),
402 run_id: String::new(),
403 run_number: 0,
404 run_attempt: 1,
405 workflow: workflow.name.clone().unwrap_or_default(),
406 workflow_path: String::new(),
407 server_url: SITE.to_owned(),
408 api_url: API.to_owned(),
409 }
410 }
411
412 #[allow(clippy::too_many_arguments)]
413 async fn record_invalid(
414 &self,
415 repo: &Repo,
416 path: &str,
417 source: &str,
418 subject: &Subject,
419 event_key: &str,
420 actor_id: Option<&str>,
421 sender: &str,
422 problem: &str,
423 ) -> Result<()> {
424 let row = self.workflow_row(repo, path, path, source).await?;
425 self.record_failed_run(&row, subject.git_ref.as_str(), &subject.sha, event_key, actor_id, sender, problem).await
426 }
427
428 /// Scheduled workflows whose cron fires this minute, on the default branch.
429 pub async fn run_schedules(&self, minute: u64) -> Result<()> {
430 let rows = self
431 .db
432 .prepare("SELECT * FROM workflows WHERE state = 'active' AND crons != '[]' AND error IS NULL")
433 .all()
434 .await?
435 .results::<WorkflowRow>()?;
436 for row in rows {
437 let crons: Vec<String> = serde_json::from_str(&row.crons).unwrap_or_default();
438 let Some(cron) = crons.iter().find(|cron| g1t_actions::cron::Schedule::parse(cron).is_ok_and(|s| s.fires_at(minute))) else {
439 continue;
440 };
441 let Ok(workflow) = workflow::parse(&row.source) else { continue };
442 let Some((repo, _ws)) = self.repo_by_id(&row.repo_id).await? else { continue };
443 let Some(sha) = self.default_head(&repo).await? else { continue };
444 let payload = json!({ "schedule": cron, "repository": payload::repository(&repo), "workflow": row.path });
445 let mut subject = Subject {
446 source: Self::repo_path(&repo),
447 source_ref: None,
448 git_ref: format!("refs/heads/{}", repo.default_branch),
449 sha,
450 head_ref: None,
451 base_ref: None,
452 pull: None,
453 filter_ref: String::new(),
454 paths: None,
455 compare: None,
456 payload,
457 title: format!("Scheduled: {cron}"),
458 trusted: true,
459 };
460 subject.filter_ref = subject.git_ref.clone();
461 let info = self.run_info(&repo, &workflow, "schedule", &subject, &repo.namespace, None);
462 self.create_run(NewRun {
463 repo: repo.clone(),
464 path: row.path.clone(),
465 source: row.source.clone(),
466 workflow,
467 info,
468 action: None,
469 pull: None,
470 title: subject.title.clone(),
471 inputs: Map::new(),
472 event_key: format!("schedule:{minute}"),
473 actor_id: None,
474 actor: None,
475 trusted: true,
476 })
477 .await?;
478 }
479 Ok(())
480 }
481
482 /// `dispatch`: a member runs a workflow that has `workflow_dispatch`.
483 pub async fn dispatch(&self, a: DispatchArgs) -> Result<Outcome<WorkflowRun>> {
484 if let Some(refused) = Self::member(&a.actor, &a.repo) {
485 return Ok(check_refusal(refused));
486 }
487 let Some(repo) = self.visible_repo(&a.repo, &Some(a.actor.clone())).await? else {
488 return Ok(fail(FailureCode::NotFound, "There is no such repository."));
489 };
490 let Some(ws) = self.workspace_actor(&repo.namespace).await? else {
491 return Ok(fail(FailureCode::NotFound, "There is no such workspace."));
492 };
493 let git_ref = a.git_ref.clone().unwrap_or_else(|| repo.default_branch.clone());
494 let full_ref = if git_ref.starts_with("refs/") {
495 git_ref.clone()
496 } else {
497 // A branch if there is one by that name, otherwise a tag.
498 let branches: Outcome<Vec<g1t_contracts::repos::Branch>> = g1t_kit::call(
499 &self.repos,
500 "branches",
501 &g1t_contracts::repos::BranchesArgs {
502 path: Self::repo_path(&repo),
503 viewer: Some(ws.clone()),
504 },
505 )
506 .await?;
507 let is_branch = branches.into_result().unwrap_or_default().iter().any(|branch| branch.name == git_ref);
508 format!("refs/{}/{git_ref}", if is_branch { "heads" } else { "tags" })
509 };
510 let short = full_ref.trim_start_matches("refs/heads/").trim_start_matches("refs/tags/").to_owned();
511 let read = self.read_workflows(&Self::repo_path(&repo), &ws, Some(&short)).await?;
512 let Some(sha) = read.head.clone() else {
513 return Ok(fail(FailureCode::NotFound, format!("There is no branch or tag called {short}.")));
514 };
515 let wanted = a.workflow.trim_start_matches(".github/workflows/");
516 let Some(file) = read.files.iter().find(|file| {
517 file.path.rsplit('/').next() == Some(wanted) || file.path == a.workflow
518 }) else {
519 return Ok(fail(FailureCode::NotFound, format!("There is no workflow {wanted} on {short}.")));
520 };
521 let workflow = match workflow::parse(&file.source) {
522 Ok(workflow) => workflow,
523 Err(problem) => return Ok(fail(FailureCode::Invalid, format!("The workflow does not read: {problem}"))),
524 };
525 let Some(trigger) = workflow.trigger("workflow_dispatch") else {
526 return Ok(fail(FailureCode::Invalid, "That workflow cannot be run by hand: it has no `workflow_dispatch` trigger."));
527 };
528 let inputs = check!(dispatch_inputs(trigger, &a.inputs));
529 let payload = json!({
530 "inputs": inputs,
531 "ref": full_ref,
532 "repository": payload::repository(&repo),
533 "sender": payload::user(&a.actor.username),
534 "workflow": file.path,
535 });
536 let subject = Subject {
537 source: Self::repo_path(&repo),
538 source_ref: Some(sha.clone()),
539 git_ref: full_ref.clone(),
540 sha,
541 head_ref: None,
542 base_ref: None,
543 pull: None,
544 filter_ref: full_ref,
545 paths: None,
546 compare: None,
547 payload,
548 title: format!("{} run by {}", workflow.display_name(&file.path), a.actor.username),
549 trusted: true,
550 };
551 let info = self.run_info(&repo, &workflow, "workflow_dispatch", &subject, &a.actor.username, Some(&a.actor.id));
552 let created = self
553 .create_run(NewRun {
554 repo: repo.clone(),
555 path: file.path.clone(),
556 source: file.source.clone(),
557 workflow,
558 info,
559 action: None,
560 pull: None,
561 title: subject.title.clone(),
562 inputs,
563 event_key: format!("dispatch:{}", new_id("dsp", now_ms())),
564 actor_id: Some(a.actor.id.clone()),
565 actor: Some(a.actor.username.clone()),
566 trusted: true,
567 })
568 .await?;
569 match created {
570 Some(id) => self.run_summary(&id).await,
571 None => Ok(fail(FailureCode::Conflict, "It did not start.")),
572 }
573 }
574}
575
576fn check_refusal<T>(refused: Outcome<()>) -> Outcome<T> {
577 match refused {
578 Outcome::Fail(failure) => Outcome::Fail(failure),
579 Outcome::Ok(()) => fail(FailureCode::Forbidden, "Not allowed."),
580 }
581}
582
583/// The inputs of a manual run: what was given, checked against the
584/// workflow's declared inputs, with their defaults filled in.
585fn dispatch_inputs(trigger: &Trigger, given: &Map<String, Value>) -> Outcome<Map<String, Value>> {
586 let mut inputs = Map::new();
587 for (name, spec) in &trigger.inputs {
588 let kind = spec.get("type").and_then(Value::as_str).unwrap_or("string");
589 let value = given.get(name).cloned().or_else(|| spec.get("default").cloned());
590 let required = spec.get("required").and_then(Value::as_bool).unwrap_or(false);
591 let value = match value {
592 Some(Value::Null) | None if required => return fail(FailureCode::Invalid, format!("The input `{name}` is required.")),
593 Some(Value::Null) | None => match kind {
594 "boolean" => Value::Bool(false),
595 _ => Value::String(String::new()),
596 },
597 Some(value) => match kind {
598 "boolean" => Value::Bool(match &value {
599 Value::Bool(flag) => *flag,
600 Value::String(text) => text == "true",
601 _ => false,
602 }),
603 "number" => match &value {
604 Value::Number(_) => value,
605 Value::String(text) => match text.parse::<f64>().ok().and_then(serde_json::Number::from_f64) {
606 Some(number) => Value::Number(number),
607 None => return fail(FailureCode::Invalid, format!("The input `{name}` is a number.")),
608 },
609 _ => return fail(FailureCode::Invalid, format!("The input `{name}` is a number.")),
610 },
611 "choice" => {
612 let text = g1t_actions::expr::to_text(&value);
613 let options: Vec<String> =
614 spec.get("options").and_then(Value::as_array).map(|o| o.iter().map(g1t_actions::expr::to_text).collect()).unwrap_or_default();
615 if !options.is_empty() && !options.contains(&text) {
616 return fail(FailureCode::Invalid, format!("The input `{name}` is one of {}.", options.join(", ")));
617 }
618 Value::String(text)
619 }
620 _ => Value::String(g1t_actions::expr::to_text(&value)),
621 },
622 };
623 inputs.insert(name.clone(), value);
624 }
625 Outcome::Ok(inputs)
626}