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, DraftReason, Error, EventKind, FailureKind, HeldBy, Holding, Hosting, Identity,
19 Landed, Lifecycle, MergeOutcome, MergePolicy, PreservedBranch, Provenance, Publication,
20 PublishOutcome, PublishRequest, Recoverable, Result, Scope, Session, SessionRecord,
21 SessionRequest, 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 // A run root of its own, which is the one placement a provider
205 // that keeps no pool can make — and the one every real session
206 // gets on a host that configures none.
207 "placement": {"kind": "run-root"},
208 })),
209 };
210 Ok((session, emission))
211 })?;
212 if self.trees == Trees::Created {
213 std::fs::create_dir_all(&session.worktree).map_err(|e| Error::Invalid {
214 reason: format!("cannot create {}: {e}", session.worktree.display()),
215 })?;
216 }
217 events::emit(&emission);
218 Ok(session)
219 }
220
221 fn adopt_session(&self, token: SessionToken) -> Result<Session> {
222 self.store.with(|state| {
223 state::session_of(state, &token)
224 .cloned()
225 .ok_or_else(|| Error::Invalid {
226 reason: format!(
227 "no session {:?} is open; `onevcs session open` prints a token",
228 token.0
229 ),
230 })
231 })
232 }
233
234 fn preserve(&self, s: &Session, provenance: Provenance) -> Result<PreservedBranch> {
235 let (branch, emission) = self.store.with(|state| {
236 let identity = state::identity_for(state, &s.token)?;
237 let branch = PreservedBranch {
238 branch: s.branch.clone(),
239 base: s.base.clone(),
240 provenance,
241 change_url: None,
242 change_base: None,
243 };
244 let row = Recoverable {
245 identity: identity.clone(),
246 branch: branch.clone(),
247 checkout: s.worktree.clone(),
248 stopped_because: format!("session {} was left open", s.token.0),
249 recover_command: recover_command(&s.branch, &s.worktree, provenance),
250 // Preserved work this provider was handed is work nobody published:
251 // there is no base here whose history could record a landing, and no
252 // tree to compare content against, so the one answer it can give is
253 // the one it knows.
254 landed: Landed::No,
255 // Both answered where the row is *read* rather than frozen in here:
256 // whether a session still holds its branch is a fact about the session
257 // now, and there is no tree here to count a diff's lines against.
258 held_by: None,
259 net_negative: None,
260 // A preservation onto an origin is a thing only a real repository can
261 // do — there is no git here and no remote to push to — so this provider
262 // answers what a scenario wrote down and nothing else. A hand-written
263 // state may still seed one, exactly as it seeds a hold.
264 on_origin: None,
265 };
266 // Preserving the same branch twice replaces its row rather than listing
267 // it twice, which is what `recoverable` does across the checkouts a
268 // branch is reachable from.
269 state.preserved.retain(|kept| {
270 kept.identity != row.identity || kept.branch.branch != row.branch.branch
271 });
272 state.preserved.push(row);
273 let emission = Emission {
274 stream: s.token.0.clone(),
275 // No identity label, because the real implementation carries none
276 // here: the label is stamped where a session is opened, and work is
277 // preserved against a stream a later process opened fresh. Claiming
278 // it would be drift in the direction that looks like more
279 // information.
280 identity: None,
281 kind: EventKind::CommitPreserved,
282 payload: object(json!({
283 "branch": s.branch,
284 "sha": events::stable_sha(&[&s.token.0, &s.branch, spell(provenance)]),
285 "provenance": spell(provenance),
286 })),
287 };
288 Ok((branch, emission))
289 })?;
290 events::emit(&emission);
291 Ok(branch)
292 }
293
294 fn session(&self, token: &SessionToken) -> Result<SessionRecord> {
295 self.store.with(|state| {
296 let session = state::session_of(state, token)
297 .cloned()
298 .ok_or_else(|| unknown_session(token))?;
299 let identity = state::identity_for(state, token)?;
300 // Read off what was preserved rather than remembered separately: the
301 // real implementation reads the branch, so a session whose work was
302 // preserved behind an incomplete-step marker answers the same here.
303 let provenance = state
304 .preserved
305 .iter()
306 .find(|row| row.identity == identity && row.branch.branch == session.branch)
307 .map_or(Provenance::Complete, |row| row.branch.provenance);
308 Ok(SessionRecord {
309 lifecycle: if state.closed_sessions.contains(token) {
310 Lifecycle::Closed
311 } else {
312 Lifecycle::Open
313 },
314 session,
315 identity,
316 provenance,
317 // A retry link is a fact about run clones under a state root, and
318 // this provider keeps none: its sessions are records in a store, so
319 // there is no second copy of a branch for one to tell apart.
320 retried_by: None,
321 })
322 })
323 }
324
325 fn close_session(&self, token: &SessionToken) -> Result<Session> {
326 self.store.with(|state| {
327 let session = state::session_of(state, token)
328 .cloned()
329 .ok_or_else(|| unknown_session(token))?;
330 let emission = Emission {
331 stream: token.0.clone(),
332 // No identity label, because the real implementation carries none
333 // here: closing opens the stream fresh, and the label is stamped
334 // where a session is opened.
335 identity: None,
336 kind: EventKind::SessionClosed,
337 payload: object(json!({"token": token.0, "branch": session.branch})),
338 };
339 // Match the real provider's observable ordering: a follower reads the
340 // stream before consulting this state, so the terminator must exist
341 // before `Closed` can be returned to that concurrent reader.
342 events::emit(&emission);
343 state.closed_sessions.insert(token.clone());
344 Ok(session)
345 })
346 }
347
348 /// Publish a session's branch, as far as a provider honestly can.
349 ///
350 /// The host side is performed rather than described: a change request is really
351 /// opened against the [`Hosting`] this was handed, really adopted when one is
352 /// already open, and really merged under the policy — so the six host methods
353 /// are exercised and what the host recorded is what a journey reads back.
354 ///
355 /// The repository side is not, and none of it is claimed. There is no origin to
356 /// fetch from, no tree to build in, no push, and no lock to queue behind, so no
357 /// `fetch`, `push`, `lock-wait`, `lock-acquired`, or `merge-queued` event is
358 /// emitted. What is emitted is what was decided: the change that was opened, and
359 /// the merge that landed.
360 fn publish(
361 &self,
362 token: &SessionToken,
363 request: &PublishRequest,
364 hosting: &dyn Hosting,
365 ) -> Result<Publication> {
366 let (publication, emissions) = self.store.with(|state| {
367 let session = state::session_of(state, token)
368 .cloned()
369 .ok_or_else(|| unknown_session(token))?;
370 let identity = state::identity_for(state, token)?;
371 // The publication rule the crate next door states, applied rather than
372 // restated: a reason that would not render as itself is refused here
373 // exactly where the real implementation refuses it, before any host is
374 // asked and before anything is recorded.
375 if let Some(reason) = &request.draft {
376 reason.checked()?;
377 }
378 let resolved = state.policy.unwrap_or(DEFAULT_PUBLICATION);
379 let policy = match request.policy {
380 Some(requested) => resolved.narrow(requested)?,
381 None => resolved,
382 };
383 let published = |outcome, emissions| {
384 (
385 Publication {
386 session: token.clone(),
387 branch: session.branch.clone(),
388 policy,
389 outcome,
390 },
391 emissions,
392 )
393 };
394 // A session that has already landed has nothing the base does not carry,
395 // which is what the real implementation reports for the same reason. One
396 // whose change request is merely open or queued has *not* landed, and
397 // publishing it again adopts that change rather than opening a second —
398 // so it falls through to the host, as it does there.
399 if state.publications.iter().any(|earlier| {
400 earlier.session == *token && matches!(earlier.outcome, PublishOutcome::Merged(_))
401 }) {
402 let (publication, emissions) =
403 published(PublishOutcome::NothingToPublish, Vec::new());
404 state.publications.push(publication.clone());
405 return Ok((publication, emissions));
406 }
407
408 let (outcome, emissions) = if policy == MergePolicy::LocalDirect {
409 // The same refusal the real publication makes at the same boundary: a
410 // local-direct publication opens no change request, so there is
411 // nothing to draft and the work would land carrying the very pin the
412 // draft exists to hold back.
413 match &request.draft {
414 Some(reason) => (
415 failed(&Error::Invalid {
416 reason: format!(
417 "{branch:?} was asked to publish as {asked}, and this identity \
418 publishes with local-direct, which opens no change request at \
419 all",
420 branch = session.branch,
421 asked = asked_for(reason),
422 ),
423 }),
424 Vec::new(),
425 ),
426 None => record_local_landing(&identity, &session, token),
427 }
428 } else {
429 match slug(&identity) {
430 Some(slug) => match publish_as_change(
431 hosting, &slug, &identity, &session, policy, request, token,
432 ) {
433 Ok(published) => published,
434 // Once a publication has started, what stops it is an outcome
435 // rather than a refusal — the same split the real
436 // implementation keeps, so a caller reads one shape.
437 Err(error) => (failed(&error), Vec::new()),
438 },
439 None => (refusal(&identity), Vec::new()),
440 }
441 };
442 let (publication, emissions) = published(outcome, emissions);
443 state.publications.push(publication.clone());
444 Ok((publication, emissions))
445 })?;
446 for emission in &emissions {
447 events::emit(emission);
448 }
449 Ok(publication)
450 }
451
452 /// The same rows [`Vcs::recoverable`] answers with.
453 ///
454 /// This provider is *handed* its preserved work, and what it is handed is work
455 /// nobody published: there is no base here whose history could record a landing
456 /// and no tree to compare content against, so it withholds nothing and the wider
457 /// question has the same answer as the narrower one.
458 fn preserved(&self, scope: Scope) -> Result<Vec<Recoverable>> {
459 self.recoverable(scope)
460 }
461
462 fn recoverable(&self, scope: Scope) -> Result<Vec<Recoverable>> {
463 self.store.with(|state| {
464 let wanted = match &scope {
465 Scope::All => None,
466 Scope::Repo(repo) => Some(
467 state::identity_of(state, repo)
468 .map(|identity| identity.origin.clone())
469 .ok_or_else(|| Error::Invalid {
470 reason: format!(
471 "{repo:?} does not name a repository this provider knows; {}",
472 state::known(state)
473 ),
474 })?,
475 ),
476 };
477 // Newest first, as the real implementation reports them.
478 Ok(state
479 .preserved
480 .iter()
481 .rev()
482 .filter(|row| wanted.as_ref().is_none_or(|key| *key == row.identity))
483 .cloned()
484 .map(|row| held(state, row))
485 .collect())
486 })
487 }
488}
489
490/// Say which live session still holds a row's branch, when one of this provider's
491/// does.
492///
493/// Read here rather than written when the work was preserved, because closing the
494/// session is what ends the hold and a row that had frozen the answer would go on
495/// saying somebody is in there. What makes it *live* is the same thing that makes it
496/// live for the real implementation in-process: the session is open, and the process
497/// that opened it is this one. A row a scenario seeded the answer into keeps it — a
498/// hand-written state says what it means to say.
499fn held(state: &VcsState, row: Recoverable) -> Recoverable {
500 if row.held_by.is_some() {
501 return row;
502 }
503 let holder = state.sessions.iter().find(|session| {
504 session.branch == row.branch.branch
505 && state.session_identities.get(&session.token) == Some(&row.identity)
506 && !state.closed_sessions.contains(&session.token)
507 });
508 Recoverable {
509 held_by: holder.map(|session| HeldBy {
510 token: session.token.clone(),
511 worktree: session.worktree.clone(),
512 holding: Holding::OwnerRunning,
513 }),
514 ..row
515 }
516}
517
518/// The refusal a session this provider never opened meets.
519fn unknown_session(token: &SessionToken) -> Error {
520 Error::Invalid {
521 reason: format!(
522 "no session {:?} is open; `onevcs session open` prints a token",
523 token.0
524 ),
525 }
526}
527
528/// The `owner/name` slug an identity key spells, when it is a GitHub one.
529///
530/// The host is checked rather than assumed, exactly as the real implementation
531/// checks it: a GitLab origin has the same three segments, and a provider that
532/// published one anyway would let a journey pass where the real run answers that
533/// nobody has implemented that host.
534fn slug(identity: &str) -> Option<String> {
535 let mut parts = identity.split('/');
536 let (host, owner, name) = (parts.next()?, parts.next()?, parts.next()?);
537 if parts.next().is_some() || host != DEFAULT_HOST || owner.is_empty() || name.is_empty() {
538 return None;
539 }
540 Some(format!("{owner}/{name}"))
541}
542
543/// Record that a `local-direct` publication landed — record, and nothing more.
544///
545/// Landing one is entirely repository-side work, a squash built detached and
546/// pushed, which this provider does not perform and must not be named as if it
547/// did. What it does is decide the outcome and emit the completion that says so.
548fn record_local_landing(
549 identity: &str,
550 session: &Session,
551 token: &SessionToken,
552) -> (PublishOutcome, Vec<Emission>) {
553 let sha = events::stable_sha(&["publish", &token.0, &session.branch]);
554 let emission = Emission {
555 stream: token.0.clone(),
556 identity: Some(identity.to_owned()),
557 kind: EventKind::MergeCompleted,
558 payload: object(json!({"identity": identity, "sha": sha, "base": session.base})),
559 };
560 (PublishOutcome::Merged(Sha(sha)), vec![emission])
561}
562
563/// Publish as a change request: open the session's change on the host, or adopt
564/// the one it already holds, and then do with it what the policy asks — which for
565/// `change-open` is to leave it open and ask the host for nothing more.
566fn publish_as_change(
567 hosting: &dyn Hosting,
568 slug: &str,
569 identity: &str,
570 session: &Session,
571 policy: MergePolicy,
572 request: &PublishRequest,
573 token: &SessionToken,
574) -> Result<(PublishOutcome, Vec<Emission>)> {
575 let host = hosting.for_repo(slug)?;
576 // Who the host believes is calling travels with the change, as it does in the
577 // real publication and for the same reason.
578 let author = host.authenticated_user()?;
579 let existing = host.find_changes(&session.branch, &session.base)?;
580 // Whether the host already held it, which is what decides whether there can be a
581 // draft to lift — and, as next door, keeps a publication that opens its own change
582 // request from asking this host anything extra.
583 let adopted = !existing.is_empty();
584 let change = match existing.into_iter().next() {
585 Some(change) => change,
586 None => host.open_change(ChangeSpec {
587 head: session.branch.clone(),
588 base: session.base.clone(),
589 // A requested title has been checked by the conversion that built it, so
590 // this provider cannot accept one the real publication would refuse. The
591 // real implementation takes the subject from the branch's commits when no
592 // title was requested, and a provider has no commits to read — so an
593 // unrequested title names the branch instead.
594 title: request
595 .title
596 .as_deref()
597 .map_or_else(|| format!("Publish {}", session.branch), str::to_owned),
598 // Verbatim, and nothing when there is none — the real publication
599 // composes no body either, so a provider that composed one would be a
600 // consumer's suite proving a change request nobody opens.
601 body: request.body.clone(),
602 // The reason travels to the host and no further, as it does there: what
603 // the host does with it is open the change as a draft.
604 draft: request.draft.clone(),
605 })?,
606 };
607 let mut emissions = vec![Emission {
608 stream: token.0.clone(),
609 identity: Some(identity.to_owned()),
610 kind: EventKind::ChangeOpened,
611 payload: object(json!({
612 "url": change.url.to_string(),
613 "host": "github",
614 "id": change.id.0,
615 "base": change.base,
616 "author": author,
617 })),
618 }];
619 if let Some(reason) = &request.draft {
620 // The same question the real publication asks, for the same reason: a host
621 // that ignored the request, or a change request already open for review,
622 // would otherwise be reported as held back while it can land.
623 if !host.is_draft(&change)? {
624 return Err(Error::Invalid {
625 reason: format!(
626 "{url} is open for review on the host, and this publication asked for \
627 {asked}. A change that is open can land, so reporting it as a draft would \
628 say the work is held back when nothing is holding it",
629 url = change.url,
630 asked = asked_for(reason),
631 ),
632 });
633 }
634 // The publication record, and the only place the reason is written: the real
635 // implementation writes nothing of it into the change request, and a provider
636 // that did would be a consumer's suite proving a body nobody renders. The
637 // payload is the reason's own serialized form — its `kind` and every field of
638 // that kind — under the change request it holds, exactly as next door.
639 let mut drafted = object(json!({
640 "url": change.url.to_string(),
641 "id": change.id.0,
642 "base": change.base,
643 }));
644 if let serde_json::Value::Object(fields) =
645 serde_json::to_value(reason).expect("a draft reason serializes")
646 {
647 drafted.extend(fields);
648 }
649 emissions.push(Emission {
650 stream: token.0.clone(),
651 identity: Some(identity.to_owned()),
652 kind: EventKind::ChangeDrafted,
653 payload: drafted,
654 });
655 // Under every policy: a draft is unmergeable in that state, so nothing below
656 // asks this host to merge it.
657 return Ok((PublishOutcome::ChangeDraft(change.url.clone()), emissions));
658 }
659 // Publishing without a reason is what lifts a draft, and a change that is not one
660 // is asked for nothing — which is what makes a second publication idempotent.
661 // Asked only of a change the host already held, as next door: one opened moments
662 // ago without a reason is one nobody drafted. Three answers, told apart the same
663 // way — a host that was never taught to draft one has nothing to lift and is
664 // passed over, and a host that *could not say* is a refusal rather than a change
665 // nobody is holding.
666 match if adopted {
667 host.is_draft(&change)
668 } else {
669 Ok(false)
670 } {
671 Ok(true) => {
672 host.ready_for_review(&change)?;
673 emissions.push(Emission {
674 stream: token.0.clone(),
675 identity: Some(identity.to_owned()),
676 kind: EventKind::DraftLifted,
677 payload: object(json!({"url": change.url.to_string(), "id": change.id.0})),
678 });
679 }
680 Ok(false) => {}
681 Err(Error::NotImplemented { .. }) => {}
682 Err(unreadable) => return Err(unreadable),
683 }
684
685 if policy == MergePolicy::ChangeOpen {
686 return Ok((PublishOutcome::ChangeOpen(change.url.clone()), emissions));
687 }
688 Ok(match host.merge(&change, policy)? {
689 MergeOutcome::Merged(sha) => {
690 emissions.push(Emission {
691 stream: token.0.clone(),
692 identity: Some(identity.to_owned()),
693 kind: EventKind::ChangeMerged,
694 payload: object(json!({"url": change.url.to_string(), "sha": sha.0})),
695 });
696 emissions.push(Emission {
697 stream: token.0.clone(),
698 identity: Some(identity.to_owned()),
699 kind: EventKind::MergeCompleted,
700 payload: object(json!({"identity": identity, "sha": sha.0})),
701 });
702 (PublishOutcome::Merged(sha), emissions)
703 }
704 MergeOutcome::Queued => (PublishOutcome::Queued(change.url.clone()), emissions),
705 MergeOutcome::Open => (PublishOutcome::ChangeOpen(change.url.clone()), emissions),
706 })
707}
708
709/// The draft a publication asked for, as the two refusals next door spell it: "a
710/// draft awaiting <repository> <target>", or "a draft held by the session that opened
711/// it (<why>)". A restatement, so the refusals here read as the real ones do.
712fn asked_for(reason: &DraftReason) -> String {
713 match reason {
714 DraftReason::AwaitingRelease {
715 awaiting, target, ..
716 } => format!("a draft awaiting {awaiting} {target}"),
717 DraftReason::Held { because } => {
718 format!("a draft held by the session that opened it ({because})")
719 }
720 }
721}
722
723/// What a publication answers for an identity no change request can be opened
724/// against.
725///
726/// Two failures rather than one, as the real implementation keeps them: an
727/// identity that is not hosted at all is asking for the wrong policy, while a
728/// hosted one on a host this build does not speak for is asking for an
729/// implementation that has not arrived.
730fn refusal(identity: &str) -> PublishOutcome {
731 failed(&if identity.split('/').count() == 3 {
732 Error::NotImplemented {
733 operation: "RemoteHost for a host other than github.com",
734 }
735 } else {
736 Error::Invalid {
737 reason: format!(
738 "identity {identity:?} is not a hosted repository, so it cannot publish a \
739 change request; a local identity publishes with local-direct"
740 ),
741 }
742 })
743}
744
745/// One failure, as the outcome a publication that started and did not land is.
746fn failed(error: &Error) -> PublishOutcome {
747 PublishOutcome::Failed {
748 // Through the crate's own mapping, so the kind a caller branches on is the
749 // one the real implementation would report for the same failure.
750 kind: FailureKind::of(error),
751 reason: error.to_string(),
752 // A provider has no execution checkout, so there is nowhere a branch could
753 // have been handed back to and nothing to report about one.
754 retained: None,
755 }
756}
757
758/// The argv that lands a preserved branch, as `recoverable` reports it.
759///
760/// Both verbs take the branch by name and the repository by path, the way the real
761/// implementation reports them: the provenance decides which one, and neither
762/// depends on the directory a reader happens to be standing in.
763// llmlint: ignore[names_match_behavior] named for the public
764// `Recoverable::recover_command` field it fills, which `onevcs` publishes and this
765// crate must answer identically; a provider whose helper were named otherwise would
766// read as filling something else.
767fn recover_command(branch: &str, checkout: &Path, provenance: Provenance) -> Vec<String> {
768 let verb = match provenance {
769 Provenance::IncompleteStep => "recover",
770 Provenance::Complete => "publish-branch",
771 };
772 vec![
773 "onevcs".to_owned(),
774 verb.to_owned(),
775 branch.to_owned(),
776 "--repo".to_owned(),
777 checkout.display().to_string(),
778 ]
779}
780
781/// How a provenance kind is spelled in an event payload.
782fn spell(provenance: Provenance) -> &'static str {
783 match provenance {
784 Provenance::Complete => "complete",
785 Provenance::IncompleteStep => "incomplete-step",
786 }
787}
788
789fn object(value: Value) -> Map<String, Value> {
790 value.as_object().cloned().unwrap_or_default()
791}