1use std::path::{Path, PathBuf};
23
24use serde::Serialize;
25
26use crate::agent::{self, LegacySwap};
27use crate::apply::{
28 self, ApplyEnv, ApplyRequest, EntryFilter, EntryState, PlanOptions, TargetFilter,
29};
30use crate::brand;
31use crate::env::{Env, KnownFolder, Os};
32use crate::error::{CoreError, ErrorCode};
33use crate::formats::NativeValue;
34use crate::fs::Fs;
35use crate::local_settings::LocalSettings;
36use crate::model::applied::ApplyTrigger;
37use crate::paths::{self, SurjectionHome};
38use crate::skills::SkillsEnv;
39use crate::store::{CommitId, Operation, Store};
40use crate::versions;
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
44#[serde(rename_all = "snake_case")]
45pub enum StepKind {
46 DataFolder,
47 FileNames,
48 WebviewProfile,
49 Launchers,
50 AgentSkill,
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
55#[serde(rename_all = "snake_case")]
56pub enum StepStatus {
57 Done,
59 Planned,
61 NotNeeded,
63 Skipped,
65 Failed,
67}
68
69#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
70pub struct Step {
71 pub step: StepKind,
72 pub status: StepStatus,
73 pub detail: String,
74 #[serde(skip_serializing_if = "Vec::is_empty")]
76 pub items: Vec<String>,
77}
78
79impl Step {
80 fn new(step: StepKind, status: StepStatus, detail: impl Into<String>) -> Self {
81 Self {
82 step,
83 status,
84 detail: detail.into(),
85 items: Vec::new(),
86 }
87 }
88}
89
90#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
92pub struct Report {
93 pub dry_run: bool,
94 pub steps: Vec<Step>,
95 #[serde(skip_serializing_if = "Option::is_none")]
97 pub commit: Option<String>,
98}
99
100impl Report {
101 pub fn changed(&self) -> bool {
103 self.steps
104 .iter()
105 .any(|step| matches!(step.status, StepStatus::Done | StepStatus::Planned))
106 }
107
108 pub fn failed(&self) -> bool {
110 self.steps
111 .iter()
112 .any(|step| step.status == StepStatus::Failed)
113 }
114
115 pub fn step(&self, kind: StepKind) -> Option<&Step> {
116 self.steps.iter().find(|step| step.step == kind)
117 }
118}
119
120pub fn data_folder(env: &Env, dry_run: bool) -> Step {
125 let kind = StepKind::DataFolder;
126 if let Some((name, _)) = paths::home_var(env) {
127 return Step::new(
128 kind,
129 StepStatus::Skipped,
130 format!("{name} is set: that folder stays where it is"),
131 );
132 }
133 let new = paths::default_surjection_home(env);
134 let old = paths::legacy_default_home(env);
135 if is_link(&old) {
136 return Step::new(
137 kind,
138 StepStatus::NotNeeded,
139 format!("{} is a link already", old.display()),
140 );
141 }
142 if !old.is_dir() {
143 return Step::new(
144 kind,
145 StepStatus::NotNeeded,
146 format!(
147 "no {} data folder at {}",
148 brand::legacy::PRODUCT_NAME,
149 old.display()
150 ),
151 );
152 }
153 if new.exists() {
154 return Step::new(
155 kind,
156 StepStatus::Skipped,
157 format!(
158 "{} exists, so {} is left as it is",
159 new.display(),
160 old.display()
161 ),
162 );
163 }
164 if dry_run {
165 return Step::new(
166 kind,
167 StepStatus::Planned,
168 format!(
169 "move {} to {} and leave a link at the old path",
170 old.display(),
171 new.display()
172 ),
173 );
174 }
175 if in_use(&old) {
176 return in_use_step(&old);
177 }
178 if let Some(parent) = new.parent()
179 && let Err(err) = std::fs::create_dir_all(parent)
180 {
181 return Step::new(
182 kind,
183 StepStatus::Failed,
184 format!("cannot create {}: {err}", parent.display()),
185 );
186 }
187 if let Err(err) = std::fs::rename(&old, &new) {
188 if new.is_dir() && (is_link(&old) || !old.exists()) {
190 return Step::new(
191 kind,
192 StepStatus::NotNeeded,
193 format!("{} was moved already", old.display()),
194 );
195 }
196 return if is_sharing_error(&err) {
197 in_use_step(&old)
198 } else {
199 Step::new(
200 kind,
201 StepStatus::Failed,
202 format!("cannot move {} to {}: {err}", old.display(), new.display()),
203 )
204 };
205 }
206 let detail = match make_link(&new, &old).or_else(|err| {
207 if is_link(&old) { Ok(()) } else { Err(err) }
209 }) {
210 Ok(()) => format!(
211 "moved {} to {}; {} now links to it",
212 old.display(),
213 new.display(),
214 old.display()
215 ),
216 Err(err) => format!(
217 "moved {} to {} (no link left at the old path: {err})",
218 old.display(),
219 new.display()
220 ),
221 };
222 Step::new(kind, StepStatus::Done, detail)
223}
224
225fn in_use_step(old: &Path) -> Step {
226 Step::new(
227 StepKind::DataFolder,
228 StepStatus::Failed,
229 format!(
230 "{} is in use (is {} running?); close it and run `{} migrate loadout` again (it also \
231 runs at the next start)",
232 old.display(),
233 brand::legacy::PRODUCT_NAME,
234 brand::BIN_NAME
235 ),
236 )
237}
238
239fn in_use(old: &Path) -> bool {
241 let lock = old.join("state").join("loadout.lock");
242 let Ok(file) = std::fs::OpenOptions::new()
243 .read(true)
244 .write(true)
245 .open(&lock)
246 else {
247 return false;
248 };
249 matches!(file.try_lock(), Err(std::fs::TryLockError::WouldBlock))
250}
251
252fn is_sharing_error(err: &std::io::Error) -> bool {
255 err.kind() == std::io::ErrorKind::PermissionDenied
256 || matches!(err.raw_os_error(), Some(5 | 32 | 33))
257 || err.kind() == std::io::ErrorKind::ResourceBusy
258}
259
260fn is_link(path: &Path) -> bool {
261 std::fs::symlink_metadata(path).is_ok_and(|meta| meta.file_type().is_symlink())
262 || is_junction(path)
263}
264
265#[cfg(windows)]
266fn is_junction(path: &Path) -> bool {
267 junction::exists(path).unwrap_or(false)
268}
269
270#[cfg(not(windows))]
271fn is_junction(_path: &Path) -> bool {
272 false
273}
274
275#[cfg(windows)]
276fn make_link(target: &Path, link: &Path) -> std::io::Result<()> {
277 junction::create(target, link)
278}
279
280#[cfg(unix)]
281fn make_link(target: &Path, link: &Path) -> std::io::Result<()> {
282 std::os::unix::fs::symlink(target, link)
283}
284
285pub fn file_names(fs: &dyn Fs, home: &SurjectionHome, dry_run: bool) -> Step {
289 let kind = StepKind::FileNames;
290 let names = if dry_run {
291 versions::legacy_names(fs, home)
292 } else {
293 versions::rename_legacy_names(fs, home)
294 };
295 if names.is_empty() {
296 return Step::new(
297 kind,
298 StepStatus::NotNeeded,
299 "no file carries the former name",
300 );
301 }
302 let status = if dry_run {
303 StepStatus::Planned
304 } else {
305 StepStatus::Done
306 };
307 let mut step = Step::new(kind, status, format!("{} file(s) renamed", names.len()));
308 step.items = names
309 .into_iter()
310 .map(|name| format!("{} -> {}", name.from, name.to))
311 .collect();
312 step
313}
314
315pub fn webview_dir(env: &Env, id: &str) -> PathBuf {
320 let base = match env.os() {
321 Os::Windows => env
322 .known_folder(KnownFolder::LocalAppData)
323 .map(Path::to_path_buf)
324 .unwrap_or_else(|| env.home().join("AppData").join("Local")),
325 Os::Linux => env
326 .var("XDG_DATA_HOME")
327 .map(PathBuf::from)
328 .filter(|path| path.is_absolute())
329 .unwrap_or_else(|| env.home().join(".local").join("share")),
330 Os::MacOs => env.home().join("Library").join("WebKit"),
331 };
332 base.join(id)
333}
334
335pub fn webview_profile(env: &Env, dry_run: bool) -> Step {
337 let kind = StepKind::WebviewProfile;
338 let old = webview_dir(env, brand::legacy::APP_ID);
339 let new = webview_dir(env, brand::APP_ID);
340 if !old.is_dir() || is_link(&old) {
341 return Step::new(kind, StepStatus::NotNeeded, "no former app profile");
342 }
343 if new.exists() {
344 return Step::new(
345 kind,
346 StepStatus::NotNeeded,
347 format!("{} exists already", new.display()),
348 );
349 }
350 if dry_run {
351 return Step::new(
352 kind,
353 StepStatus::Planned,
354 format!("copy {} to {}", old.display(), new.display()),
355 );
356 }
357 let temp = new.with_file_name(format!(
361 ".{}.copy-{}",
362 new.file_name().unwrap_or_default().to_string_lossy(),
363 std::process::id()
364 ));
365 let _ = std::fs::remove_dir_all(&temp);
366 let copied = copy_dir(&old, &temp).and_then(|()| std::fs::rename(&temp, &new));
367 match copied {
368 Err(_) if new.is_dir() => {
370 let _ = std::fs::remove_dir_all(&temp);
371 Step::new(
372 kind,
373 StepStatus::NotNeeded,
374 format!("{} exists already", new.display()),
375 )
376 }
377 Ok(()) => Step::new(
378 kind,
379 StepStatus::Done,
380 format!("copied {} to {}", old.display(), new.display()),
381 ),
382 Err(err) => {
383 let _ = std::fs::remove_dir_all(&temp);
384 Step::new(
385 kind,
386 StepStatus::Failed,
387 format!("cannot copy {}: {err}", old.display()),
388 )
389 }
390 }
391}
392
393fn copy_dir(from: &Path, to: &Path) -> std::io::Result<()> {
394 std::fs::create_dir_all(to)?;
395 for entry in std::fs::read_dir(from)? {
396 let entry = entry?;
397 let kind = entry.file_type()?;
398 let target = to.join(entry.file_name());
399 if kind.is_dir() {
400 copy_dir(&entry.path(), &target)?;
401 } else if kind.is_file() {
402 std::fs::copy(entry.path(), &target)?;
403 }
404 }
405 Ok(())
406}
407
408fn is_launcher(token: &str, stem: &str) -> bool {
413 let name = token.rsplit(['/', '\\']).next().unwrap_or(token);
414 let name = name
415 .strip_suffix(".exe")
416 .or_else(|| name.strip_suffix(".EXE"))
417 .unwrap_or(name);
418 name.eq_ignore_ascii_case(stem)
419}
420
421fn mask_launchers(text: &str, stem: &str) -> String {
423 let mut out = String::with_capacity(text.len());
424 let mut word = String::new();
425 let flush = |word: &mut String, out: &mut String| {
426 if is_launcher(word, stem) {
427 out.push('\u{0}');
428 } else {
429 out.push_str(word);
430 }
431 word.clear();
432 };
433 for ch in text.chars() {
434 if ch.is_whitespace() || ch == '"' || ch == '\'' {
435 flush(&mut word, &mut out);
436 out.push(ch);
437 } else {
438 word.push(ch);
439 }
440 }
441 flush(&mut word, &mut out);
442 out
443}
444
445pub fn launcher_only(observed: &NativeValue, desired: &NativeValue) -> bool {
449 let mut launcher = false;
450 same_but_launcher(observed, desired, &mut launcher) && launcher
451}
452
453fn same_but_launcher(a: &NativeValue, b: &NativeValue, launcher: &mut bool) -> bool {
454 match (a, b) {
455 (NativeValue::String(x), NativeValue::String(y)) => {
456 if x == y {
457 return true;
458 }
459 let same =
460 mask_launchers(x, brand::legacy::BIN_NAME) == mask_launchers(y, brand::BIN_NAME);
461 *launcher |= same;
462 same
463 }
464 (NativeValue::Array(x), NativeValue::Array(y)) => {
465 x.len() == y.len()
466 && x.iter()
467 .zip(y)
468 .all(|(x, y)| same_but_launcher(x, y, launcher))
469 }
470 (NativeValue::Object(x), NativeValue::Object(y)) => {
471 x.len() == y.len()
472 && x.keys().all(|key| {
473 y.get(key)
474 .zip(x.get(key))
475 .is_some_and(|(y, x)| same_but_launcher(x, y, launcher))
476 })
477 }
478 _ => a == b,
479 }
480}
481
482pub fn legacy_bare_launcher(observed: &NativeValue, desired: &NativeValue) -> bool {
487 let mut launcher = false;
488 same_but_bare(observed, desired, &mut launcher) && launcher
489}
490
491fn mask_bare(text: &str, word: &str) -> String {
492 text.split(' ')
493 .map(|token| if token == word { "\u{0}" } else { token })
494 .collect::<Vec<_>>()
495 .join(" ")
496}
497
498fn same_but_bare(a: &NativeValue, b: &NativeValue, launcher: &mut bool) -> bool {
499 match (a, b) {
500 (NativeValue::String(x), NativeValue::String(y)) => {
501 if x == y {
502 return true;
503 }
504 let same = mask_bare(x, brand::legacy::BIN_NAME) == mask_bare(y, brand::BIN_NAME);
505 *launcher |= same;
506 same
507 }
508 (NativeValue::Array(x), NativeValue::Array(y)) => {
509 x.len() == y.len() && x.iter().zip(y).all(|(x, y)| same_but_bare(x, y, launcher))
510 }
511 (NativeValue::Object(x), NativeValue::Object(y)) => {
512 x.len() == y.len()
513 && x.keys().all(|key| {
514 y.get(key)
515 .zip(x.get(key))
516 .is_some_and(|(y, x)| same_but_bare(x, y, launcher))
517 })
518 }
519 _ => a == b,
520 }
521}
522
523#[derive(Debug, Clone, PartialEq)]
525struct Repair {
526 filter: TargetFilter,
527 pointer: String,
528 name: String,
529 label: String,
530}
531
532fn filter_of(target: &apply::TargetPlan) -> TargetFilter {
533 TargetFilter {
534 scope: target.scope,
535 project: target.project.clone(),
536 file: target.file.clone(),
537 }
538}
539
540fn repairs(store: Option<&Store<'_>>, ax: &ApplyEnv<'_>) -> Result<Vec<Repair>, CoreError> {
543 let plan = apply::preview(store, ax, &PlanOptions::default())?;
544 let mut repairs = Vec::new();
545 for target in &plan.targets {
546 if target.problem.is_some() || target.read_only.is_some() {
547 continue;
548 }
549 for entry in &target.entries {
550 let (Some(observed), Some(desired)) = (&entry.observed, &entry.desired) else {
551 continue;
552 };
553 if entry.state == EntryState::PendingUpdate
554 && entry.action == apply::Action::Update
555 && launcher_only(observed, desired)
556 {
557 repairs.push(Repair {
558 filter: filter_of(target),
559 pointer: target.pointer.clone(),
560 name: entry.name.clone(),
561 label: label(target, entry),
562 });
563 }
564 }
565 }
566 Ok(repairs)
567}
568
569fn label(target: &apply::TargetPlan, entry: &apply::EntryPlan) -> String {
570 format!(
571 "{} {}: {}",
572 entry
573 .client
574 .unwrap_or(target.clients.first().copied().unwrap_or("")),
575 target.file.display(),
576 entry.name
577 )
578}
579
580fn options(repairs: &[Repair]) -> PlanOptions {
583 let mut targets: Vec<TargetFilter> = Vec::new();
584 for repair in repairs {
585 if !targets.contains(&repair.filter) {
586 targets.push(repair.filter.clone());
587 }
588 }
589 PlanOptions {
590 targets: Some(targets),
591 entries: Some(
592 repairs
593 .iter()
594 .map(|repair| EntryFilter {
595 target: repair.filter.clone(),
596 pointer: repair.pointer.clone(),
597 name: repair.name.clone(),
598 })
599 .collect(),
600 ),
601 ..PlanOptions::default()
602 }
603}
604
605pub fn launchers(
607 store: Option<&Store<'_>>,
608 ax: &ApplyEnv<'_>,
609 dry_run: bool,
610) -> Result<(Step, Option<CommitId>), CoreError> {
611 let kind = StepKind::Launchers;
612 let Some(store) = store else {
613 return Ok((Step::new(kind, StepStatus::NotNeeded, "no store"), None));
614 };
615 let repairs = repairs(Some(store), ax)?;
616 if repairs.is_empty() {
617 return Ok((
618 Step::new(
619 kind,
620 StepStatus::NotNeeded,
621 "no entry uses the former launcher",
622 ),
623 None,
624 ));
625 }
626 let labels: Vec<String> = repairs.iter().map(|repair| repair.label.clone()).collect();
627 if dry_run {
628 let mut step = Step::new(
629 kind,
630 StepStatus::Planned,
631 format!("{} entr{} to repair", labels.len(), plural_y(labels.len())),
632 );
633 step.items = labels;
634 return Ok((step, None));
635 }
636 let request = ApplyRequest {
637 options: options(&repairs),
638 trigger: ApplyTrigger::Review,
639 };
640 let operation = Operation::new(
641 "apply",
642 format!(
643 "migrate: loadout launchers ({} entr{})",
644 labels.len(),
645 plural_y(labels.len())
646 ),
647 );
648 let committed = store.transaction(operation, |tx| apply::apply_in(tx, ax, &request))?;
649 let report = committed.value;
650 let written: Vec<String> = report
651 .targets
652 .iter()
653 .filter(|target| target.written)
654 .flat_map(|target| {
655 target
656 .entries
657 .iter()
658 .filter(|entry| entry.action == apply::Action::Update)
659 .map(move |entry| {
660 format!(
661 "{} {}: {}",
662 entry
663 .client
664 .unwrap_or(target.clients.first().copied().unwrap_or("")),
665 target.file.display(),
666 entry.name
667 )
668 })
669 })
670 .collect();
671 let failed = report.targets.iter().any(|target| target.error.is_some());
672 let status = if failed {
673 StepStatus::Failed
674 } else {
675 StepStatus::Done
676 };
677 let mut step = Step::new(
678 kind,
679 status,
680 format!("{} entr{} repaired", written.len(), plural_y(written.len())),
681 );
682 step.items = written;
683 Ok((step, committed.commit))
684}
685
686fn plural_y(n: usize) -> &'static str {
687 if n == 1 { "y" } else { "ies" }
688}
689
690pub fn agent_skill(
694 store: Option<&Store<'_>>,
695 sx: &SkillsEnv<'_>,
696 dry_run: bool,
697) -> Result<Step, CoreError> {
698 let kind = StepKind::AgentSkill;
699 let Some(store) = store else {
700 return Ok(Step::new(kind, StepStatus::NotNeeded, "no store"));
701 };
702 let legacy = brand::legacy::SKILL_ID;
703 Ok(match agent::swap_legacy(store, sx, dry_run)? {
704 LegacySwap::Absent => Step::new(
705 kind,
706 StepStatus::NotNeeded,
707 format!("no {legacy:?} skill in the store"),
708 ),
709 LegacySwap::Foreign => Step::new(
710 kind,
711 StepStatus::Skipped,
712 format!("the store skill {legacy:?} is your own; it is kept"),
713 ),
714 LegacySwap::Customized => Step::new(
715 kind,
716 StepStatus::Skipped,
717 format!("the {legacy:?} skill was edited; it is kept as it is"),
718 ),
719 LegacySwap::Planned => Step::new(
720 kind,
721 StepStatus::Planned,
722 format!(
723 "replace the {legacy:?} skill with {:?} for the same clients",
724 agent::SKILL_ID
725 ),
726 ),
727 LegacySwap::Swapped { .. } => Step::new(
728 kind,
729 StepStatus::Done,
730 format!(
731 "replaced the {legacy:?} skill with {:?} for the same clients",
732 agent::SKILL_ID
733 ),
734 ),
735 })
736}
737
738pub fn is_done(fs: &dyn Fs, home: &SurjectionHome) -> bool {
742 LocalSettings::load(fs, &home.state_dir())
743 .is_ok_and(|settings| settings.loadout_migration.is_some())
744}
745
746pub fn mark_done(fs: &dyn Fs, home: &SurjectionHome) -> Result<(), CoreError> {
749 if !fs.is_dir(&home.state_dir()) {
750 return Ok(());
751 }
752 let state = home.state_dir();
753 let mut settings = LocalSettings::load(fs, &state)?;
754 if settings.loadout_migration.as_deref() == Some(agent::BUNDLED_VERSION) {
755 return Ok(());
756 }
757 settings.loadout_migration = Some(agent::BUNDLED_VERSION.to_owned());
758 settings.save(fs, &state)
759}
760
761pub fn run_in_home(
766 early: Vec<Step>,
767 store: Option<&Store<'_>>,
768 ax: &ApplyEnv<'_>,
769 sx: &SkillsEnv<'_>,
770 dry_run: bool,
771) -> Result<Report, CoreError> {
772 let mut report = Report {
773 dry_run,
774 steps: early,
775 commit: None,
776 };
777 report.steps.push(file_names(ax.fs, ax.home, dry_run));
778 if report.step(StepKind::WebviewProfile).is_none() {
779 report.steps.push(webview_profile(ax.env, dry_run));
780 }
781 let (launchers, commit) = launchers(store, ax, dry_run)?;
782 report.steps.push(launchers);
783 report.commit = commit.map(|commit| commit.to_string());
784 report.steps.push(agent_skill(store, sx, dry_run)?);
785 if !dry_run && !report.failed() {
786 mark_done(ax.fs, ax.home)?;
787 }
788 Ok(report)
789}
790
791pub fn step_error(step: &Step) -> CoreError {
793 CoreError::new(ErrorCode::IoError, step.detail.clone())
794}