Skip to main content

onevcs_testing/
repository.rs

1//! The repository side: one implementation of [`Vcs`] over either store.
2//!
3//! What it is not: git. It answers the questions the interface asks, records what
4//! it was asked, and emits the events the real implementation emits. What it
5//! cannot do is tell you whether a tree is dirty or whether a merge conflicts,
6//! because there is no tree — a journey that needs those drives the real `Git`.
7//!
8//! Publishing is the one operation that reaches past the repository: the host side
9//! of it is *performed*, against the [`Hosting`] the publication was handed, and
10//! the repository side of it is neither performed nor claimed. What that leaves
11//! out is written where each piece is left out.
12
13use std::path::{Path, PathBuf};
14
15use serde_json::{json, Map, Value};
16
17use onevcs::{
18    ChangeSpec, Error, EventKind, FailureKind, HeldBy, Holding, Hosting, Identity, Landed,
19    Lifecycle, MergeOutcome, MergePolicy, PreservedBranch, Provenance, Publication, PublishOutcome,
20    PublishRequest, Recoverable, Result, Scope, Session, SessionRecord, SessionRequest,
21    SessionToken, Sha, Vcs,
22};
23
24use crate::events::{self, Emission};
25use crate::remote::DEFAULT_HOST;
26use crate::state::{self, VcsState};
27use crate::store::{FileStore, MemoryStore, Store};
28
29/// The base a session is cut from when the request names none.
30///
31/// The real implementation asks the origin for its default branch, and this
32/// provider has no origin to ask.
33pub const DEFAULT_BASE: &str = "main";
34
35/// The policy a publication takes when nothing was seeded and nothing requested.
36///
37/// The policy the contract's own `default:` names, which is what the real
38/// implementation resolves to for a registry with no rules file.
39pub const DEFAULT_PUBLICATION: MergePolicy = MergePolicy::ChangeOpen;
40
41/// The repository side of a run, over whichever store holds its state.
42///
43/// The two flavours below are this one behaviour with a different store under it,
44/// so neither can learn something the other does not know.
45#[derive(Debug)]
46pub struct Repository<T> {
47    store: T,
48    root: PathBuf,
49    trees: Trees,
50}
51
52/// What a session's worktree path means.
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54enum Trees {
55    /// The path is named and nothing is created there: the in-memory provider
56    /// touches no filesystem beyond the event stream.
57    Named,
58    /// The directory is created, so a journey has somewhere to write work.
59    Created,
60}
61
62/// A repository provider that keeps its state in this process: no disk, no
63/// visibility to a second process, and the fastest of the two.
64///
65/// Its sessions name a worktree under the system temporary directory and **do not
66/// create it** — nothing here touches the filesystem except the event stream, which
67/// is the record a journey reads.
68pub type MemoryVcs = Repository<MemoryStore<VcsState>>;
69
70/// A repository provider that keeps its state in one JSON document, so several
71/// `onevcs` invocations see one another's effects.
72///
73/// Its sessions name a worktree beside that document **and create it**, so a
74/// journey that writes a file into a session's tree has somewhere to write it.
75pub type FileVcs = Repository<FileStore<VcsState>>;
76
77impl MemoryVcs {
78    /// A repository provider knowing nothing.
79    pub fn new() -> Self {
80        Self::seeded(VcsState::default())
81    }
82
83    /// A repository provider that starts from a scenario.
84    pub fn seeded(state: VcsState) -> Self {
85        Self {
86            store: MemoryStore::new(state),
87            root: std::env::temp_dir().join("onevcs-testing-memory"),
88            trees: Trees::Named,
89        }
90    }
91
92    /// Everything it knows.
93    pub fn state(&self) -> VcsState {
94        self.store
95            .snapshot()
96            .expect("an in-memory store always answers")
97    }
98}
99
100impl Default for MemoryVcs {
101    fn default() -> Self {
102        Self::new()
103    }
104}
105
106impl FileVcs {
107    /// A repository provider keeping its state at `path`: whatever is already
108    /// there, or nothing.
109    ///
110    /// Attaching rather than replacing, so a second provider over the same path
111    /// picks up what the first one left — which is what a journey driving several
112    /// invocations reaches for this flavour to get.
113    pub fn create(path: impl Into<PathBuf>) -> Result<Self> {
114        Self::over(FileStore::attach(path, &VcsState::default())?)
115    }
116
117    /// A repository provider that starts from a scenario, keeping its state at
118    /// `path` and replacing whatever was there.
119    pub fn seeded(path: impl Into<PathBuf>, state: VcsState) -> Result<Self> {
120        Self::over(FileStore::replace(path, &state)?)
121    }
122
123    fn over(store: FileStore<VcsState>) -> Result<Self> {
124        let root = store
125            .path()
126            .parent()
127            .filter(|parent| !parent.as_os_str().is_empty())
128            .unwrap_or_else(|| Path::new("."))
129            .join("worktrees");
130        Ok(Self {
131            store,
132            root,
133            trees: Trees::Created,
134        })
135    }
136
137    /// Everything it knows, read back out of its document.
138    pub fn state(&self) -> Result<VcsState> {
139        self.store.snapshot()
140    }
141}
142
143impl<T: Store<VcsState>> Vcs for Repository<T> {
144    fn resolve_identity(&self, origin_or_path: &str) -> Result<Identity> {
145        self.store.with(|state| {
146            state::identity_of(state, origin_or_path)
147                .cloned()
148                .ok_or_else(|| Error::Invalid {
149                    reason: format!(
150                        "{origin_or_path:?} does not name a repository this provider knows; {}",
151                        state::known(state)
152                    ),
153                })
154        })
155    }
156
157    fn open_session(&self, req: SessionRequest) -> Result<Session> {
158        let root = self.root.clone();
159        let (session, emission) = self.store.with(|state| {
160            let identity = state::identity_of(state, &req.repo)
161                .cloned()
162                .ok_or_else(|| Error::Invalid {
163                    reason: format!(
164                        "{:?} does not name a repository this provider knows; {}",
165                        req.repo,
166                        state::known(state)
167                    ),
168                })?;
169            // Consecutive and predictable, so a journey can name the session it is
170            // about to open — the one thing a digest-shaped token takes away.
171            let token = SessionToken(format!("s-testing-{}", state.sessions.len() + 1));
172            let run_root = root.join(&token.0);
173            // Both names are checked before they are recorded, because both go on to
174            // spell a ref for whoever holds the session — and a provider that
175            // accepted a name git refuses would let a journey pass where the real
176            // run stops.
177            let base = req.base.clone().unwrap_or_else(|| DEFAULT_BASE.to_owned());
178            state::named_branch(&base, "the base")?;
179            let session = Session {
180                worktree: run_root.join("worktree"),
181                branch: state::requested_branch(&req, &token)?,
182                base,
183                token: token.clone(),
184            };
185            state.sessions.push(session.clone());
186            state
187                .session_identities
188                .insert(token.clone(), identity.origin.clone());
189            let emission = Emission {
190                stream: token.0.clone(),
191                identity: Some(identity.origin.clone()),
192                kind: EventKind::SessionOpened,
193                payload: object(json!({
194                    "token": token.0,
195                    "identity": identity.origin,
196                    "branch": session.branch,
197                    "base": session.base,
198                    "worktree": session.worktree.display().to_string(),
199                    // Synthetic, and named anyway: a consumer reading this event
200                    // reads the same keys whichever implementation produced it.
201                    "clone": run_root.join("clone").display().to_string(),
202                    "execution_checkout": run_root.join("checkout").display().to_string(),
203                    "publication_checkout": run_root.join("checkout").display().to_string(),
204                })),
205            };
206            Ok((session, emission))
207        })?;
208        if self.trees == Trees::Created {
209            std::fs::create_dir_all(&session.worktree).map_err(|e| Error::Invalid {
210                reason: format!("cannot create {}: {e}", session.worktree.display()),
211            })?;
212        }
213        events::emit(&emission);
214        Ok(session)
215    }
216
217    fn adopt_session(&self, token: SessionToken) -> Result<Session> {
218        self.store.with(|state| {
219            state::session_of(state, &token)
220                .cloned()
221                .ok_or_else(|| Error::Invalid {
222                    reason: format!(
223                        "no session {:?} is open; `onevcs session open` prints a token",
224                        token.0
225                    ),
226                })
227        })
228    }
229
230    fn preserve(&self, s: &Session, provenance: Provenance) -> Result<PreservedBranch> {
231        let (branch, emission) = self.store.with(|state| {
232            let identity = state::identity_for(state, &s.token)?;
233            let branch = PreservedBranch {
234                branch: s.branch.clone(),
235                base: s.base.clone(),
236                provenance,
237                change_url: None,
238                change_base: None,
239            };
240            let row = Recoverable {
241                identity: identity.clone(),
242                branch: branch.clone(),
243                checkout: s.worktree.clone(),
244                stopped_because: format!("session {} was left open", s.token.0),
245                recover_command: recover_command(&s.branch, &s.worktree, provenance),
246                // Preserved work this provider was handed is work nobody published:
247                // there is no base here whose history could record a landing, and no
248                // tree to compare content against, so the one answer it can give is
249                // the one it knows.
250                landed: Landed::No,
251                // Both answered where the row is *read* rather than frozen in here:
252                // whether a session still holds its branch is a fact about the session
253                // now, and there is no tree here to count a diff's lines against.
254                held_by: None,
255                net_negative: None,
256            };
257            // Preserving the same branch twice replaces its row rather than listing
258            // it twice, which is what `recoverable` does across the checkouts a
259            // branch is reachable from.
260            state.preserved.retain(|kept| {
261                kept.identity != row.identity || kept.branch.branch != row.branch.branch
262            });
263            state.preserved.push(row);
264            let emission = Emission {
265                stream: s.token.0.clone(),
266                // No identity label, because the real implementation carries none
267                // here: the label is stamped where a session is opened, and work is
268                // preserved against a stream a later process opened fresh. Claiming
269                // it would be drift in the direction that looks like more
270                // information.
271                identity: None,
272                kind: EventKind::CommitPreserved,
273                payload: object(json!({
274                    "branch": s.branch,
275                    "sha": events::stable_sha(&[&s.token.0, &s.branch, spell(provenance)]),
276                    "provenance": spell(provenance),
277                })),
278            };
279            Ok((branch, emission))
280        })?;
281        events::emit(&emission);
282        Ok(branch)
283    }
284
285    fn session(&self, token: &SessionToken) -> Result<SessionRecord> {
286        self.store.with(|state| {
287            let session = state::session_of(state, token)
288                .cloned()
289                .ok_or_else(|| unknown_session(token))?;
290            let identity = state::identity_for(state, token)?;
291            // Read off what was preserved rather than remembered separately: the
292            // real implementation reads the branch, so a session whose work was
293            // preserved behind an incomplete-step marker answers the same here.
294            let provenance = state
295                .preserved
296                .iter()
297                .find(|row| row.identity == identity && row.branch.branch == session.branch)
298                .map_or(Provenance::Complete, |row| row.branch.provenance);
299            Ok(SessionRecord {
300                lifecycle: if state.closed_sessions.contains(token) {
301                    Lifecycle::Closed
302                } else {
303                    Lifecycle::Open
304                },
305                session,
306                identity,
307                provenance,
308                // A retry link is a fact about run clones under a state root, and
309                // this provider keeps none: its sessions are records in a store, so
310                // there is no second copy of a branch for one to tell apart.
311                retried_by: None,
312            })
313        })
314    }
315
316    fn close_session(&self, token: &SessionToken) -> Result<Session> {
317        self.store.with(|state| {
318            let session = state::session_of(state, token)
319                .cloned()
320                .ok_or_else(|| unknown_session(token))?;
321            let emission = Emission {
322                stream: token.0.clone(),
323                // No identity label, because the real implementation carries none
324                // here: closing opens the stream fresh, and the label is stamped
325                // where a session is opened.
326                identity: None,
327                kind: EventKind::SessionClosed,
328                payload: object(json!({"token": token.0, "branch": session.branch})),
329            };
330            // Match the real provider's observable ordering: a follower reads the
331            // stream before consulting this state, so the terminator must exist
332            // before `Closed` can be returned to that concurrent reader.
333            events::emit(&emission);
334            state.closed_sessions.insert(token.clone());
335            Ok(session)
336        })
337    }
338
339    /// Publish a session's branch, as far as a provider honestly can.
340    ///
341    /// The host side is performed rather than described: a change request is really
342    /// opened against the [`Hosting`] this was handed, really adopted when one is
343    /// already open, and really merged under the policy — so the six host methods
344    /// are exercised and what the host recorded is what a journey reads back.
345    ///
346    /// The repository side is not, and none of it is claimed. There is no origin to
347    /// fetch from, no tree to build in, no push, and no lock to queue behind, so no
348    /// `fetch`, `push`, `lock-wait`, `lock-acquired`, or `merge-queued` event is
349    /// emitted. What is emitted is what was decided: the change that was opened, and
350    /// the merge that landed.
351    fn publish(
352        &self,
353        token: &SessionToken,
354        request: &PublishRequest,
355        hosting: &dyn Hosting,
356    ) -> Result<Publication> {
357        let (publication, emissions) = self.store.with(|state| {
358            let session = state::session_of(state, token)
359                .cloned()
360                .ok_or_else(|| unknown_session(token))?;
361            let identity = state::identity_for(state, token)?;
362            // The publication rule the crate next door states, applied rather than
363            // restated: a reason that would not render as itself is refused here
364            // exactly where the real implementation refuses it, before any host is
365            // asked and before anything is recorded.
366            if let Some(reason) = &request.draft {
367                reason.checked()?;
368            }
369            let resolved = state.policy.unwrap_or(DEFAULT_PUBLICATION);
370            let policy = match request.policy {
371                Some(requested) => resolved.narrow(requested)?,
372                None => resolved,
373            };
374            let published = |outcome, emissions| {
375                (
376                    Publication {
377                        session: token.clone(),
378                        branch: session.branch.clone(),
379                        policy,
380                        outcome,
381                    },
382                    emissions,
383                )
384            };
385            // A session that has already landed has nothing the base does not carry,
386            // which is what the real implementation reports for the same reason. One
387            // whose change request is merely open or queued has *not* landed, and
388            // publishing it again adopts that change rather than opening a second —
389            // so it falls through to the host, as it does there.
390            if state.publications.iter().any(|earlier| {
391                earlier.session == *token && matches!(earlier.outcome, PublishOutcome::Merged(_))
392            }) {
393                let (publication, emissions) =
394                    published(PublishOutcome::NothingToPublish, Vec::new());
395                state.publications.push(publication.clone());
396                return Ok((publication, emissions));
397            }
398
399            let (outcome, emissions) = if policy == MergePolicy::LocalDirect {
400                // The same refusal the real publication makes at the same boundary: a
401                // local-direct publication opens no change request, so there is
402                // nothing to draft and the work would land carrying the very pin the
403                // draft exists to hold back.
404                match &request.draft {
405                    Some(reason) => (
406                        failed(&Error::Invalid {
407                            reason: format!(
408                                "{branch:?} was asked to publish as a draft awaiting {awaiting} \
409                                 {target}, and this identity publishes with local-direct, which \
410                                 opens no change request at all",
411                                branch = session.branch,
412                                awaiting = reason.awaiting,
413                                target = reason.target,
414                            ),
415                        }),
416                        Vec::new(),
417                    ),
418                    None => record_local_landing(&identity, &session, token),
419                }
420            } else {
421                match slug(&identity) {
422                    Some(slug) => match publish_as_change(
423                        hosting, &slug, &identity, &session, policy, request, token,
424                    ) {
425                        Ok(published) => published,
426                        // Once a publication has started, what stops it is an outcome
427                        // rather than a refusal — the same split the real
428                        // implementation keeps, so a caller reads one shape.
429                        Err(error) => (failed(&error), Vec::new()),
430                    },
431                    None => (refusal(&identity), Vec::new()),
432                }
433            };
434            let (publication, emissions) = published(outcome, emissions);
435            state.publications.push(publication.clone());
436            Ok((publication, emissions))
437        })?;
438        for emission in &emissions {
439            events::emit(emission);
440        }
441        Ok(publication)
442    }
443
444    /// The same rows [`Vcs::recoverable`] answers with.
445    ///
446    /// This provider is *handed* its preserved work, and what it is handed is work
447    /// nobody published: there is no base here whose history could record a landing
448    /// and no tree to compare content against, so it withholds nothing and the wider
449    /// question has the same answer as the narrower one.
450    fn preserved(&self, scope: Scope) -> Result<Vec<Recoverable>> {
451        self.recoverable(scope)
452    }
453
454    fn recoverable(&self, scope: Scope) -> Result<Vec<Recoverable>> {
455        self.store.with(|state| {
456            let wanted = match &scope {
457                Scope::All => None,
458                Scope::Repo(repo) => Some(
459                    state::identity_of(state, repo)
460                        .map(|identity| identity.origin.clone())
461                        .ok_or_else(|| Error::Invalid {
462                            reason: format!(
463                                "{repo:?} does not name a repository this provider knows; {}",
464                                state::known(state)
465                            ),
466                        })?,
467                ),
468            };
469            // Newest first, as the real implementation reports them.
470            Ok(state
471                .preserved
472                .iter()
473                .rev()
474                .filter(|row| wanted.as_ref().is_none_or(|key| *key == row.identity))
475                .cloned()
476                .map(|row| held(state, row))
477                .collect())
478        })
479    }
480}
481
482/// Say which live session still holds a row's branch, when one of this provider's
483/// does.
484///
485/// Read here rather than written when the work was preserved, because closing the
486/// session is what ends the hold and a row that had frozen the answer would go on
487/// saying somebody is in there. What makes it *live* is the same thing that makes it
488/// live for the real implementation in-process: the session is open, and the process
489/// that opened it is this one. A row a scenario seeded the answer into keeps it — a
490/// hand-written state says what it means to say.
491fn held(state: &VcsState, row: Recoverable) -> Recoverable {
492    if row.held_by.is_some() {
493        return row;
494    }
495    let holder = state.sessions.iter().find(|session| {
496        session.branch == row.branch.branch
497            && state.session_identities.get(&session.token) == Some(&row.identity)
498            && !state.closed_sessions.contains(&session.token)
499    });
500    Recoverable {
501        held_by: holder.map(|session| HeldBy {
502            token: session.token.clone(),
503            worktree: session.worktree.clone(),
504            holding: Holding::OwnerRunning,
505        }),
506        ..row
507    }
508}
509
510/// The refusal a session this provider never opened meets.
511fn unknown_session(token: &SessionToken) -> Error {
512    Error::Invalid {
513        reason: format!(
514            "no session {:?} is open; `onevcs session open` prints a token",
515            token.0
516        ),
517    }
518}
519
520/// The `owner/name` slug an identity key spells, when it is a GitHub one.
521///
522/// The host is checked rather than assumed, exactly as the real implementation
523/// checks it: a GitLab origin has the same three segments, and a provider that
524/// published one anyway would let a journey pass where the real run answers that
525/// nobody has implemented that host.
526fn slug(identity: &str) -> Option<String> {
527    let mut parts = identity.split('/');
528    let (host, owner, name) = (parts.next()?, parts.next()?, parts.next()?);
529    if parts.next().is_some() || host != DEFAULT_HOST || owner.is_empty() || name.is_empty() {
530        return None;
531    }
532    Some(format!("{owner}/{name}"))
533}
534
535/// Record that a `local-direct` publication landed — record, and nothing more.
536///
537/// Landing one is entirely repository-side work, a squash built detached and
538/// pushed, which this provider does not perform and must not be named as if it
539/// did. What it does is decide the outcome and emit the completion that says so.
540fn record_local_landing(
541    identity: &str,
542    session: &Session,
543    token: &SessionToken,
544) -> (PublishOutcome, Vec<Emission>) {
545    let sha = events::stable_sha(&["publish", &token.0, &session.branch]);
546    let emission = Emission {
547        stream: token.0.clone(),
548        identity: Some(identity.to_owned()),
549        kind: EventKind::MergeCompleted,
550        payload: object(json!({"identity": identity, "sha": sha, "base": session.base})),
551    };
552    (PublishOutcome::Merged(Sha(sha)), vec![emission])
553}
554
555/// Publish as a change request: open the session's change on the host, or adopt
556/// the one it already holds, and then do with it what the policy asks — which for
557/// `change-open` is to leave it open and ask the host for nothing more.
558fn publish_as_change(
559    hosting: &dyn Hosting,
560    slug: &str,
561    identity: &str,
562    session: &Session,
563    policy: MergePolicy,
564    request: &PublishRequest,
565    token: &SessionToken,
566) -> Result<(PublishOutcome, Vec<Emission>)> {
567    let host = hosting.for_repo(slug)?;
568    // Who the host believes is calling travels with the change, as it does in the
569    // real publication and for the same reason.
570    let author = host.authenticated_user()?;
571    let existing = host.find_changes(&session.branch, &session.base)?;
572    // Whether the host already held it, which is what decides whether there can be a
573    // draft to lift — and, as next door, keeps a publication that opens its own change
574    // request from asking this host anything extra.
575    let adopted = !existing.is_empty();
576    let change = match existing.into_iter().next() {
577        Some(change) => change,
578        None => host.open_change(ChangeSpec {
579            head: session.branch.clone(),
580            base: session.base.clone(),
581            // A requested title has been checked by the conversion that built it, so
582            // this provider cannot accept one the real publication would refuse. The
583            // real implementation takes the subject from the branch's commits when no
584            // title was requested, and a provider has no commits to read — so an
585            // unrequested title names the branch instead.
586            title: request
587                .title
588                .as_deref()
589                .map_or_else(|| format!("Publish {}", session.branch), str::to_owned),
590            // Verbatim, and nothing when there is none — the real publication
591            // composes no body either, so a provider that composed one would be a
592            // consumer's suite proving a change request nobody opens.
593            body: request.body.clone(),
594            // The reason travels to the host and no further, as it does there: what
595            // the host does with it is open the change as a draft.
596            draft: request.draft.clone(),
597        })?,
598    };
599    let mut emissions = vec![Emission {
600        stream: token.0.clone(),
601        identity: Some(identity.to_owned()),
602        kind: EventKind::ChangeOpened,
603        payload: object(json!({
604            "url": change.url.to_string(),
605            "host": "github",
606            "id": change.id.0,
607            "base": change.base,
608            "author": author,
609        })),
610    }];
611    if let Some(reason) = &request.draft {
612        // The same question the real publication asks, for the same reason: a host
613        // that ignored the request, or a change request already open for review,
614        // would otherwise be reported as held back while it can land.
615        if !host.is_draft(&change)? {
616            return Err(Error::Invalid {
617                reason: format!(
618                    "{url} is open for review on the host, and this publication asked for a \
619                     draft awaiting {awaiting} {target}. A change that is open can land, so \
620                     reporting it as a draft would say the work is held back when nothing is \
621                     holding it",
622                    url = change.url,
623                    awaiting = reason.awaiting,
624                    target = reason.target,
625                ),
626            });
627        }
628        // The publication record, and the only place the reason is written: the real
629        // implementation writes nothing of it into the change request, and a provider
630        // that did would be a consumer's suite proving a body nobody renders.
631        emissions.push(Emission {
632            stream: token.0.clone(),
633            identity: Some(identity.to_owned()),
634            kind: EventKind::ChangeDrafted,
635            payload: object(json!({
636                "url": change.url.to_string(),
637                "id": change.id.0,
638                "base": change.base,
639                "awaiting": reason.awaiting,
640                "target": reason.target.to_string(),
641                "reference": reason.reference,
642                "because": reason.because,
643            })),
644        });
645        // Under every policy: a draft is unmergeable in that state, so nothing below
646        // asks this host to merge it.
647        return Ok((PublishOutcome::ChangeDraft(change.url.clone()), emissions));
648    }
649    // Publishing without a reason is what lifts a draft, and a change that is not one
650    // is asked for nothing — which is what makes a second publication idempotent.
651    // Asked only of a change the host already held, as next door: one opened moments
652    // ago without a reason is one nobody drafted. Three answers, told apart the same
653    // way — a host that was never taught to draft one has nothing to lift and is
654    // passed over, and a host that *could not say* is a refusal rather than a change
655    // nobody is holding.
656    match if adopted {
657        host.is_draft(&change)
658    } else {
659        Ok(false)
660    } {
661        Ok(true) => {
662            host.ready_for_review(&change)?;
663            emissions.push(Emission {
664                stream: token.0.clone(),
665                identity: Some(identity.to_owned()),
666                kind: EventKind::DraftLifted,
667                payload: object(json!({"url": change.url.to_string(), "id": change.id.0})),
668            });
669        }
670        Ok(false) => {}
671        Err(Error::NotImplemented { .. }) => {}
672        Err(unreadable) => return Err(unreadable),
673    }
674
675    if policy == MergePolicy::ChangeOpen {
676        return Ok((PublishOutcome::ChangeOpen(change.url.clone()), emissions));
677    }
678    Ok(match host.merge(&change, policy)? {
679        MergeOutcome::Merged(sha) => {
680            emissions.push(Emission {
681                stream: token.0.clone(),
682                identity: Some(identity.to_owned()),
683                kind: EventKind::ChangeMerged,
684                payload: object(json!({"url": change.url.to_string(), "sha": sha.0})),
685            });
686            emissions.push(Emission {
687                stream: token.0.clone(),
688                identity: Some(identity.to_owned()),
689                kind: EventKind::MergeCompleted,
690                payload: object(json!({"identity": identity, "sha": sha.0})),
691            });
692            (PublishOutcome::Merged(sha), emissions)
693        }
694        MergeOutcome::Queued => (PublishOutcome::Queued(change.url.clone()), emissions),
695        MergeOutcome::Open => (PublishOutcome::ChangeOpen(change.url.clone()), emissions),
696    })
697}
698
699/// What a publication answers for an identity no change request can be opened
700/// against.
701///
702/// Two failures rather than one, as the real implementation keeps them: an
703/// identity that is not hosted at all is asking for the wrong policy, while a
704/// hosted one on a host this build does not speak for is asking for an
705/// implementation that has not arrived.
706fn refusal(identity: &str) -> PublishOutcome {
707    failed(&if identity.split('/').count() == 3 {
708        Error::NotImplemented {
709            operation: "RemoteHost for a host other than github.com",
710        }
711    } else {
712        Error::Invalid {
713            reason: format!(
714                "identity {identity:?} is not a hosted repository, so it cannot publish a \
715                 change request; a local identity publishes with local-direct"
716            ),
717        }
718    })
719}
720
721/// One failure, as the outcome a publication that started and did not land is.
722fn failed(error: &Error) -> PublishOutcome {
723    PublishOutcome::Failed {
724        // Through the crate's own mapping, so the kind a caller branches on is the
725        // one the real implementation would report for the same failure.
726        kind: FailureKind::of(error),
727        reason: error.to_string(),
728        // A provider has no execution checkout, so there is nowhere a branch could
729        // have been handed back to and nothing to report about one.
730        retained: None,
731    }
732}
733
734/// The argv that lands a preserved branch, as `recoverable` reports it.
735///
736/// Both verbs take the branch by name and the repository by path, the way the real
737/// implementation reports them: the provenance decides which one, and neither
738/// depends on the directory a reader happens to be standing in.
739// llmlint: ignore[names_match_behavior] named for the public
740// `Recoverable::recover_command` field it fills, which `onevcs` publishes and this
741// crate must answer identically; a provider whose helper were named otherwise would
742// read as filling something else.
743fn recover_command(branch: &str, checkout: &Path, provenance: Provenance) -> Vec<String> {
744    let verb = match provenance {
745        Provenance::IncompleteStep => "recover",
746        Provenance::Complete => "publish-branch",
747    };
748    vec![
749        "onevcs".to_owned(),
750        verb.to_owned(),
751        branch.to_owned(),
752        "--repo".to_owned(),
753        checkout.display().to_string(),
754    ]
755}
756
757/// How a provenance kind is spelled in an event payload.
758fn spell(provenance: Provenance) -> &'static str {
759    match provenance {
760        Provenance::Complete => "complete",
761        Provenance::IncompleteStep => "incomplete-step",
762    }
763}
764
765fn object(value: Value) -> Map<String, Value> {
766    value.as_object().cloned().unwrap_or_default()
767}