use std::path::{Path, PathBuf};
use serde::Serialize;
use crate::agent::{self, LegacySwap};
use crate::apply::{
self, ApplyEnv, ApplyRequest, EntryFilter, EntryState, PlanOptions, TargetFilter,
};
use crate::brand;
use crate::env::{Env, KnownFolder, Os};
use crate::error::{CoreError, ErrorCode};
use crate::formats::NativeValue;
use crate::fs::Fs;
use crate::local_settings::LocalSettings;
use crate::model::applied::ApplyTrigger;
use crate::paths::{self, SurjectionHome};
use crate::skills::SkillsEnv;
use crate::store::{CommitId, Operation, Store};
use crate::versions;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum StepKind {
DataFolder,
FileNames,
WebviewProfile,
Launchers,
AgentSkill,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum StepStatus {
Done,
Planned,
NotNeeded,
Skipped,
Failed,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Step {
pub step: StepKind,
pub status: StepStatus,
pub detail: String,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub items: Vec<String>,
}
impl Step {
fn new(step: StepKind, status: StepStatus, detail: impl Into<String>) -> Self {
Self {
step,
status,
detail: detail.into(),
items: Vec::new(),
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
pub struct Report {
pub dry_run: bool,
pub steps: Vec<Step>,
#[serde(skip_serializing_if = "Option::is_none")]
pub commit: Option<String>,
}
impl Report {
pub fn changed(&self) -> bool {
self.steps
.iter()
.any(|step| matches!(step.status, StepStatus::Done | StepStatus::Planned))
}
pub fn failed(&self) -> bool {
self.steps
.iter()
.any(|step| step.status == StepStatus::Failed)
}
pub fn step(&self, kind: StepKind) -> Option<&Step> {
self.steps.iter().find(|step| step.step == kind)
}
}
pub fn data_folder(env: &Env, dry_run: bool) -> Step {
let kind = StepKind::DataFolder;
if let Some((name, _)) = paths::home_var(env) {
return Step::new(
kind,
StepStatus::Skipped,
format!("{name} is set: that folder stays where it is"),
);
}
let new = paths::default_surjection_home(env);
let old = paths::legacy_default_home(env);
if is_link(&old) {
return Step::new(
kind,
StepStatus::NotNeeded,
format!("{} is a link already", old.display()),
);
}
if !old.is_dir() {
return Step::new(
kind,
StepStatus::NotNeeded,
format!(
"no {} data folder at {}",
brand::legacy::PRODUCT_NAME,
old.display()
),
);
}
if new.exists() {
return Step::new(
kind,
StepStatus::Skipped,
format!(
"{} exists, so {} is left as it is",
new.display(),
old.display()
),
);
}
if dry_run {
return Step::new(
kind,
StepStatus::Planned,
format!(
"move {} to {} and leave a link at the old path",
old.display(),
new.display()
),
);
}
if in_use(&old) {
return in_use_step(&old);
}
if let Some(parent) = new.parent()
&& let Err(err) = std::fs::create_dir_all(parent)
{
return Step::new(
kind,
StepStatus::Failed,
format!("cannot create {}: {err}", parent.display()),
);
}
if let Err(err) = std::fs::rename(&old, &new) {
if new.is_dir() && (is_link(&old) || !old.exists()) {
return Step::new(
kind,
StepStatus::NotNeeded,
format!("{} was moved already", old.display()),
);
}
return if is_sharing_error(&err) {
in_use_step(&old)
} else {
Step::new(
kind,
StepStatus::Failed,
format!("cannot move {} to {}: {err}", old.display(), new.display()),
)
};
}
let detail = match make_link(&new, &old).or_else(|err| {
if is_link(&old) { Ok(()) } else { Err(err) }
}) {
Ok(()) => format!(
"moved {} to {}; {} now links to it",
old.display(),
new.display(),
old.display()
),
Err(err) => format!(
"moved {} to {} (no link left at the old path: {err})",
old.display(),
new.display()
),
};
Step::new(kind, StepStatus::Done, detail)
}
fn in_use_step(old: &Path) -> Step {
Step::new(
StepKind::DataFolder,
StepStatus::Failed,
format!(
"{} is in use (is {} running?); close it and run `{} migrate loadout` again (it also \
runs at the next start)",
old.display(),
brand::legacy::PRODUCT_NAME,
brand::BIN_NAME
),
)
}
fn in_use(old: &Path) -> bool {
let lock = old.join("state").join("loadout.lock");
let Ok(file) = std::fs::OpenOptions::new()
.read(true)
.write(true)
.open(&lock)
else {
return false;
};
matches!(file.try_lock(), Err(std::fs::TryLockError::WouldBlock))
}
fn is_sharing_error(err: &std::io::Error) -> bool {
err.kind() == std::io::ErrorKind::PermissionDenied
|| matches!(err.raw_os_error(), Some(5 | 32 | 33))
|| err.kind() == std::io::ErrorKind::ResourceBusy
}
fn is_link(path: &Path) -> bool {
std::fs::symlink_metadata(path).is_ok_and(|meta| meta.file_type().is_symlink())
|| is_junction(path)
}
#[cfg(windows)]
fn is_junction(path: &Path) -> bool {
junction::exists(path).unwrap_or(false)
}
#[cfg(not(windows))]
fn is_junction(_path: &Path) -> bool {
false
}
#[cfg(windows)]
fn make_link(target: &Path, link: &Path) -> std::io::Result<()> {
junction::create(target, link)
}
#[cfg(unix)]
fn make_link(target: &Path, link: &Path) -> std::io::Result<()> {
std::os::unix::fs::symlink(target, link)
}
pub fn file_names(fs: &dyn Fs, home: &SurjectionHome, dry_run: bool) -> Step {
let kind = StepKind::FileNames;
let names = if dry_run {
versions::legacy_names(fs, home)
} else {
versions::rename_legacy_names(fs, home)
};
if names.is_empty() {
return Step::new(
kind,
StepStatus::NotNeeded,
"no file carries the former name",
);
}
let status = if dry_run {
StepStatus::Planned
} else {
StepStatus::Done
};
let mut step = Step::new(kind, status, format!("{} file(s) renamed", names.len()));
step.items = names
.into_iter()
.map(|name| format!("{} -> {}", name.from, name.to))
.collect();
step
}
pub fn webview_dir(env: &Env, id: &str) -> PathBuf {
let base = match env.os() {
Os::Windows => env
.known_folder(KnownFolder::LocalAppData)
.map(Path::to_path_buf)
.unwrap_or_else(|| env.home().join("AppData").join("Local")),
Os::Linux => env
.var("XDG_DATA_HOME")
.map(PathBuf::from)
.filter(|path| path.is_absolute())
.unwrap_or_else(|| env.home().join(".local").join("share")),
Os::MacOs => env.home().join("Library").join("WebKit"),
};
base.join(id)
}
pub fn webview_profile(env: &Env, dry_run: bool) -> Step {
let kind = StepKind::WebviewProfile;
let old = webview_dir(env, brand::legacy::APP_ID);
let new = webview_dir(env, brand::APP_ID);
if !old.is_dir() || is_link(&old) {
return Step::new(kind, StepStatus::NotNeeded, "no former app profile");
}
if new.exists() {
return Step::new(
kind,
StepStatus::NotNeeded,
format!("{} exists already", new.display()),
);
}
if dry_run {
return Step::new(
kind,
StepStatus::Planned,
format!("copy {} to {}", old.display(), new.display()),
);
}
let temp = new.with_file_name(format!(
".{}.copy-{}",
new.file_name().unwrap_or_default().to_string_lossy(),
std::process::id()
));
let _ = std::fs::remove_dir_all(&temp);
let copied = copy_dir(&old, &temp).and_then(|()| std::fs::rename(&temp, &new));
match copied {
Err(_) if new.is_dir() => {
let _ = std::fs::remove_dir_all(&temp);
Step::new(
kind,
StepStatus::NotNeeded,
format!("{} exists already", new.display()),
)
}
Ok(()) => Step::new(
kind,
StepStatus::Done,
format!("copied {} to {}", old.display(), new.display()),
),
Err(err) => {
let _ = std::fs::remove_dir_all(&temp);
Step::new(
kind,
StepStatus::Failed,
format!("cannot copy {}: {err}", old.display()),
)
}
}
}
fn copy_dir(from: &Path, to: &Path) -> std::io::Result<()> {
std::fs::create_dir_all(to)?;
for entry in std::fs::read_dir(from)? {
let entry = entry?;
let kind = entry.file_type()?;
let target = to.join(entry.file_name());
if kind.is_dir() {
copy_dir(&entry.path(), &target)?;
} else if kind.is_file() {
std::fs::copy(entry.path(), &target)?;
}
}
Ok(())
}
fn is_launcher(token: &str, stem: &str) -> bool {
let name = token.rsplit(['/', '\\']).next().unwrap_or(token);
let name = name
.strip_suffix(".exe")
.or_else(|| name.strip_suffix(".EXE"))
.unwrap_or(name);
name.eq_ignore_ascii_case(stem)
}
fn mask_launchers(text: &str, stem: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut word = String::new();
let flush = |word: &mut String, out: &mut String| {
if is_launcher(word, stem) {
out.push('\u{0}');
} else {
out.push_str(word);
}
word.clear();
};
for ch in text.chars() {
if ch.is_whitespace() || ch == '"' || ch == '\'' {
flush(&mut word, &mut out);
out.push(ch);
} else {
word.push(ch);
}
}
flush(&mut word, &mut out);
out
}
pub fn launcher_only(observed: &NativeValue, desired: &NativeValue) -> bool {
let mut launcher = false;
same_but_launcher(observed, desired, &mut launcher) && launcher
}
fn same_but_launcher(a: &NativeValue, b: &NativeValue, launcher: &mut bool) -> bool {
match (a, b) {
(NativeValue::String(x), NativeValue::String(y)) => {
if x == y {
return true;
}
let same =
mask_launchers(x, brand::legacy::BIN_NAME) == mask_launchers(y, brand::BIN_NAME);
*launcher |= same;
same
}
(NativeValue::Array(x), NativeValue::Array(y)) => {
x.len() == y.len()
&& x.iter()
.zip(y)
.all(|(x, y)| same_but_launcher(x, y, launcher))
}
(NativeValue::Object(x), NativeValue::Object(y)) => {
x.len() == y.len()
&& x.keys().all(|key| {
y.get(key)
.zip(x.get(key))
.is_some_and(|(y, x)| same_but_launcher(x, y, launcher))
})
}
_ => a == b,
}
}
pub fn legacy_bare_launcher(observed: &NativeValue, desired: &NativeValue) -> bool {
let mut launcher = false;
same_but_bare(observed, desired, &mut launcher) && launcher
}
fn mask_bare(text: &str, word: &str) -> String {
text.split(' ')
.map(|token| if token == word { "\u{0}" } else { token })
.collect::<Vec<_>>()
.join(" ")
}
fn same_but_bare(a: &NativeValue, b: &NativeValue, launcher: &mut bool) -> bool {
match (a, b) {
(NativeValue::String(x), NativeValue::String(y)) => {
if x == y {
return true;
}
let same = mask_bare(x, brand::legacy::BIN_NAME) == mask_bare(y, brand::BIN_NAME);
*launcher |= same;
same
}
(NativeValue::Array(x), NativeValue::Array(y)) => {
x.len() == y.len() && x.iter().zip(y).all(|(x, y)| same_but_bare(x, y, launcher))
}
(NativeValue::Object(x), NativeValue::Object(y)) => {
x.len() == y.len()
&& x.keys().all(|key| {
y.get(key)
.zip(x.get(key))
.is_some_and(|(y, x)| same_but_bare(x, y, launcher))
})
}
_ => a == b,
}
}
#[derive(Debug, Clone, PartialEq)]
struct Repair {
filter: TargetFilter,
pointer: String,
name: String,
label: String,
}
fn filter_of(target: &apply::TargetPlan) -> TargetFilter {
TargetFilter {
scope: target.scope,
project: target.project.clone(),
file: target.file.clone(),
}
}
fn repairs(store: Option<&Store<'_>>, ax: &ApplyEnv<'_>) -> Result<Vec<Repair>, CoreError> {
let plan = apply::preview(store, ax, &PlanOptions::default())?;
let mut repairs = Vec::new();
for target in &plan.targets {
if target.problem.is_some() || target.read_only.is_some() {
continue;
}
for entry in &target.entries {
let (Some(observed), Some(desired)) = (&entry.observed, &entry.desired) else {
continue;
};
if entry.state == EntryState::PendingUpdate
&& entry.action == apply::Action::Update
&& launcher_only(observed, desired)
{
repairs.push(Repair {
filter: filter_of(target),
pointer: target.pointer.clone(),
name: entry.name.clone(),
label: label(target, entry),
});
}
}
}
Ok(repairs)
}
fn label(target: &apply::TargetPlan, entry: &apply::EntryPlan) -> String {
format!(
"{} {}: {}",
entry
.client
.unwrap_or(target.clients.first().copied().unwrap_or("")),
target.file.display(),
entry.name
)
}
fn options(repairs: &[Repair]) -> PlanOptions {
let mut targets: Vec<TargetFilter> = Vec::new();
for repair in repairs {
if !targets.contains(&repair.filter) {
targets.push(repair.filter.clone());
}
}
PlanOptions {
targets: Some(targets),
entries: Some(
repairs
.iter()
.map(|repair| EntryFilter {
target: repair.filter.clone(),
pointer: repair.pointer.clone(),
name: repair.name.clone(),
})
.collect(),
),
..PlanOptions::default()
}
}
pub fn launchers(
store: Option<&Store<'_>>,
ax: &ApplyEnv<'_>,
dry_run: bool,
) -> Result<(Step, Option<CommitId>), CoreError> {
let kind = StepKind::Launchers;
let Some(store) = store else {
return Ok((Step::new(kind, StepStatus::NotNeeded, "no store"), None));
};
let repairs = repairs(Some(store), ax)?;
if repairs.is_empty() {
return Ok((
Step::new(
kind,
StepStatus::NotNeeded,
"no entry uses the former launcher",
),
None,
));
}
let labels: Vec<String> = repairs.iter().map(|repair| repair.label.clone()).collect();
if dry_run {
let mut step = Step::new(
kind,
StepStatus::Planned,
format!("{} entr{} to repair", labels.len(), plural_y(labels.len())),
);
step.items = labels;
return Ok((step, None));
}
let request = ApplyRequest {
options: options(&repairs),
trigger: ApplyTrigger::Review,
};
let operation = Operation::new(
"apply",
format!(
"migrate: loadout launchers ({} entr{})",
labels.len(),
plural_y(labels.len())
),
);
let committed = store.transaction(operation, |tx| apply::apply_in(tx, ax, &request))?;
let report = committed.value;
let written: Vec<String> = report
.targets
.iter()
.filter(|target| target.written)
.flat_map(|target| {
target
.entries
.iter()
.filter(|entry| entry.action == apply::Action::Update)
.map(move |entry| {
format!(
"{} {}: {}",
entry
.client
.unwrap_or(target.clients.first().copied().unwrap_or("")),
target.file.display(),
entry.name
)
})
})
.collect();
let failed = report.targets.iter().any(|target| target.error.is_some());
let status = if failed {
StepStatus::Failed
} else {
StepStatus::Done
};
let mut step = Step::new(
kind,
status,
format!("{} entr{} repaired", written.len(), plural_y(written.len())),
);
step.items = written;
Ok((step, committed.commit))
}
fn plural_y(n: usize) -> &'static str {
if n == 1 { "y" } else { "ies" }
}
pub fn agent_skill(
store: Option<&Store<'_>>,
sx: &SkillsEnv<'_>,
dry_run: bool,
) -> Result<Step, CoreError> {
let kind = StepKind::AgentSkill;
let Some(store) = store else {
return Ok(Step::new(kind, StepStatus::NotNeeded, "no store"));
};
let legacy = brand::legacy::SKILL_ID;
Ok(match agent::swap_legacy(store, sx, dry_run)? {
LegacySwap::Absent => Step::new(
kind,
StepStatus::NotNeeded,
format!("no {legacy:?} skill in the store"),
),
LegacySwap::Foreign => Step::new(
kind,
StepStatus::Skipped,
format!("the store skill {legacy:?} is your own; it is kept"),
),
LegacySwap::Customized => Step::new(
kind,
StepStatus::Skipped,
format!("the {legacy:?} skill was edited; it is kept as it is"),
),
LegacySwap::Planned => Step::new(
kind,
StepStatus::Planned,
format!(
"replace the {legacy:?} skill with {:?} for the same clients",
agent::SKILL_ID
),
),
LegacySwap::Swapped { .. } => Step::new(
kind,
StepStatus::Done,
format!(
"replaced the {legacy:?} skill with {:?} for the same clients",
agent::SKILL_ID
),
),
})
}
pub fn is_done(fs: &dyn Fs, home: &SurjectionHome) -> bool {
LocalSettings::load(fs, &home.state_dir())
.is_ok_and(|settings| settings.loadout_migration.is_some())
}
pub fn mark_done(fs: &dyn Fs, home: &SurjectionHome) -> Result<(), CoreError> {
if !fs.is_dir(&home.state_dir()) {
return Ok(());
}
let state = home.state_dir();
let mut settings = LocalSettings::load(fs, &state)?;
if settings.loadout_migration.as_deref() == Some(agent::BUNDLED_VERSION) {
return Ok(());
}
settings.loadout_migration = Some(agent::BUNDLED_VERSION.to_owned());
settings.save(fs, &state)
}
pub fn run_in_home(
early: Vec<Step>,
store: Option<&Store<'_>>,
ax: &ApplyEnv<'_>,
sx: &SkillsEnv<'_>,
dry_run: bool,
) -> Result<Report, CoreError> {
let mut report = Report {
dry_run,
steps: early,
commit: None,
};
report.steps.push(file_names(ax.fs, ax.home, dry_run));
if report.step(StepKind::WebviewProfile).is_none() {
report.steps.push(webview_profile(ax.env, dry_run));
}
let (launchers, commit) = launchers(store, ax, dry_run)?;
report.steps.push(launchers);
report.commit = commit.map(|commit| commit.to_string());
report.steps.push(agent_skill(store, sx, dry_run)?);
if !dry_run && !report.failed() {
mark_done(ax.fs, ax.home)?;
}
Ok(report)
}
pub fn step_error(step: &Step) -> CoreError {
CoreError::new(ErrorCode::IoError, step.detail.clone())
}