use std::ffi::OsStr;
use std::fs;
use std::path::{Path, PathBuf};
use std::time::Duration;
use semver::Version;
use crate::util::managed_bin::{self, Release, WhenMissing};
const REPO: &str = "storytold/photocraft";
const DOWNLOADS: &str = "https://github.com/storytold/photocraft/releases/download";
const CHECKSUMS: &str = "SHA256SUMS.txt";
const VERSION_TIMEOUT: Duration = Duration::from_secs(10);
const fn program_file() -> &'static str {
if cfg!(windows) {
"photocraft-cli.exe"
} else {
"photocraft-cli"
}
}
static INSTALLING: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
static IN_USE: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(());
#[cfg_attr(
test,
expect(clippy::unnecessary_wraps, reason = "the test root always resolves")
)]
fn root() -> Result<PathBuf, String> {
#[cfg(test)]
let dir = crate::util::test::test_root().join("photocraft");
#[cfg(not(test))]
let dir = crate::config::default_config_dir()
.map_err(|_| "the product's configuration directory is unavailable".to_string())?
.join("photocraft");
Ok(dir)
}
fn installed() -> bool {
root().is_ok_and(|root| crate::util::is_executable(&root.join(program_file())))
}
pub(super) async fn hold_for_run()
-> Result<(tokio::sync::RwLockReadGuard<'static, ()>, PathBuf, PathBuf), String> {
ensure_installed().await.map_err(recorded)?;
let held = IN_USE.read().await;
let root = root()?;
let program = root.join(program_file());
Ok((held, root, program))
}
async fn ensure_installed() -> Result<(), String> {
if installed() {
return Ok(());
}
let _installing = INSTALLING.lock().await;
if installed() {
return Ok(());
}
let release = managed_bin::latest_release(REPO, managed_bin::METADATA_TIMEOUT).await?;
let program = install_locked(&release).await?;
tracing::info!(
"photocraft {} installed at {}",
release.version,
program.display()
);
Ok(())
}
pub async fn install_on_start() {
managed_bin::install_on_start(
"photocraft",
installed,
installed_version,
async || managed_bin::latest_release(REPO, managed_bin::METADATA_TIMEOUT).await,
async |release| {
let release = managed_bin::release_or_reason(release)?;
install(&release).await
},
WhenMissing::Skip,
)
.await;
}
async fn installed_version() -> Option<Version> {
installed_version_at(&root().ok()?).await
}
async fn installed_version_at(root: &Path) -> Option<Version> {
let program = root.join(program_file());
if !crate::util::is_executable(&program) {
return None;
}
reports(root, &program).await
}
async fn reports(cwd: &Path, program: &Path) -> Option<Version> {
let outcome = crate::tools::shell::run_internal_program_outcome(
cwd,
program,
&["--version".to_string()],
&[],
Some(VERSION_TIMEOUT),
)
.await;
if !outcome.success {
return None;
}
banner_version(&outcome.output)
}
fn banner_version(text: &str) -> Option<Version> {
text.lines()
.next()?
.split_whitespace()
.find_map(managed_bin::parse_version_token)
}
fn asset_name(version: &str, os: &str, arch: &str) -> Option<String> {
let name = match (os, arch) {
("macos", "x86_64" | "aarch64") => format!("photocraft-cli-{version}-macos-universal.zip"),
("linux", "x86_64") => format!("photocraft-{version}-linux-x86_64.tar.gz"),
("linux", "aarch64") => format!("photocraft-{version}-linux-aarch64.tar.gz"),
("windows", "x86_64") => format!("photocraft-{version}-windows-x64-portable.zip"),
("windows", "aarch64") => format!("photocraft-{version}-windows-arm64-portable.zip"),
_ => return None,
};
Some(name)
}
async fn install(release: &Release) -> Result<PathBuf, String> {
let _installing = INSTALLING.lock().await;
install_locked(release).await
}
async fn install_locked(release: &Release) -> Result<PathBuf, String> {
use crate::util::http::{DownloadSizeCheck, download_verified};
let root = root()?;
let program = root.join(program_file());
if installed_version_at(&root).await.as_ref() == Some(&release.version) {
return Ok(program);
}
let asset = prepare(&root, &release.version)?;
let tag = &release.tag;
let sums = managed_bin::fetch_sha256_sums(
&format!("{DOWNLOADS}/{tag}/{CHECKSUMS}"),
"the release's checksum file",
)
.await?;
let digest = managed_bin::sha256_for(&sums, &asset)
.ok_or_else(|| "the release carries no checksum for this platform's archive".to_string())?;
let staging = tempfile::Builder::new()
.prefix(".staging-")
.tempdir_in(&root)
.map_err(|e| format!("the staging directory could not be created ({})", e.kind()))?;
let archive = staging.path().join(&asset);
download_verified(
managed_bin::download_client()?,
&format!("{DOWNLOADS}/{tag}/{asset}"),
&archive,
&digest,
None,
DownloadSizeCheck::Exact,
|_, _| {},
)
.await
.map_err(|e| {
format!(
"the photocraft release could not be downloaded: {}",
managed_bin::download_reason(&e)
)
})?;
let staged = extract(&archive, staging.path())?;
if reports(&root, &staged).await.as_ref() != Some(&release.version) {
return Err(format!(
"the downloaded photocraft-cli could not run, or does not report version {}",
release.version
));
}
let _swap = managed_bin::swap_when_idle(&IN_USE).await;
managed_bin::place_extracted(&staged, &program)?;
Ok(program)
}
fn prepare(root: &Path, version: &Version) -> Result<String, String> {
fs::create_dir_all(root).map_err(|e| {
format!(
"the product's photocraft directory could not be created ({})",
e.kind()
)
})?;
let (os, arch) = managed_bin::host_os_arch()?;
asset_name(&version.to_string(), os, arch)
.ok_or_else(|| format!("the vendor publishes no photocraft build for {os}-{arch}"))
}
fn extract(archive: &Path, dir: &Path) -> Result<PathBuf, String> {
if archive.extension().and_then(OsStr::to_str) == Some("zip") {
managed_bin::extract_single_file_zip(archive, dir, program_file())
} else {
let member = format!("bin/{}", program_file());
managed_bin::extract_member_tar_gz(archive, dir, &member)
}
}
fn recorded(reason: String) -> String {
tracing::warn!(
"photocraft could not be installed (retried on the next use): {}",
crate::util::truncate(&reason, 1024)
);
reason
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_platform_pair_gets_the_archive_the_vendor_publishes() {
let version = "0.20.1";
for arch in ["x86_64", "aarch64"] {
assert_eq!(
asset_name(version, "macos", arch).as_deref(),
Some("photocraft-cli-0.20.1-macos-universal.zip")
);
}
assert_eq!(
asset_name(version, "linux", "x86_64").as_deref(),
Some("photocraft-0.20.1-linux-x86_64.tar.gz")
);
assert_eq!(
asset_name(version, "linux", "aarch64").as_deref(),
Some("photocraft-0.20.1-linux-aarch64.tar.gz")
);
assert_eq!(
asset_name(version, "windows", "x86_64").as_deref(),
Some("photocraft-0.20.1-windows-x64-portable.zip")
);
assert_eq!(
asset_name(version, "windows", "aarch64").as_deref(),
Some("photocraft-0.20.1-windows-arm64-portable.zip")
);
}
#[test]
fn a_pair_the_product_does_not_build_for_is_refused() {
assert_eq!(asset_name("0.20.1", "freebsd", "x86_64"), None);
assert_eq!(asset_name("0.20.1", "linux", "riscv64"), None);
assert_eq!(asset_name("0.20.1", "linux", "armv7"), None);
assert_eq!(asset_name("0.20.1", "macos", "powerpc"), None);
assert_eq!(asset_name("0.20.1", "windows", "amd64"), None);
}
#[test]
fn an_install_creates_its_root_before_it_fetches_anything() {
let parent = tempfile::tempdir().expect("a temporary parent");
let root = parent.path().join("photocraft");
assert!(!root.exists());
let _ = prepare(&root, &Version::new(0, 20, 1));
assert!(root.is_dir(), "{} was not created", root.display());
}
fn write_tar_gz(dir: &Path, entries: &[(&str, &[u8])]) -> PathBuf {
let path = dir.join("photocraft-0.20.1-linux-x86_64.tar.gz");
let encoder = flate2::write::GzEncoder::new(
fs::File::create(&path).expect("the archive is created"),
flate2::Compression::default(),
);
let mut builder = tar::Builder::new(encoder);
for (name, contents) in entries {
let mut header = tar::Header::new_gnu();
header.set_size(contents.len() as u64);
header.set_mode(0o644);
header.set_entry_type(tar::EntryType::Regular);
builder
.append_data(&mut header, name, *contents)
.expect("the entry is written");
}
builder
.into_inner()
.expect("the archive is finished")
.finish()
.expect("the gzip stream is finished");
path
}
#[test]
fn the_tar_extraction_takes_the_program_and_not_the_completion_script_named_like_it() {
let dir = tempfile::tempdir().expect("a temporary directory");
let top = "photocraft-0.20.1-linux-x86_64";
let decoy = format!("{top}/share/bash-completion/completions/{}", program_file());
let program = format!("{top}/bin/{}", program_file());
let archive = write_tar_gz(
dir.path(),
&[
(&decoy, b"complete -W 'convert run info' photocraft-cli"),
(&program, b"the program"),
],
);
let out = extract(&archive, dir.path()).expect("the program is extracted");
assert_eq!(out, dir.path().join(program_file()));
assert_eq!(
fs::read(&out).expect("the extracted file is readable"),
b"the program"
);
}
#[test]
fn the_banner_names_the_release_version() {
assert_eq!(
banner_version("photocraft-cli 0.20.1 (b8c3f3aa8, 2026-10-28)"),
Some(Version::new(0, 20, 1))
);
assert_eq!(banner_version("photocraft-cli\n"), None);
}
}