use crate::{
Ctx, Status, ToolKind, ToolReport, UpdateMethod, Version, atomic_symlink, download_to_temp,
ensure_clean_dir, home_dir, http_get_json, info, keep_latest_with_version, link_dir_bins,
maybe_path_hint_for_dir, prune_tool_versions, run_output, run_status, warn, which_or_none,
};
use anyhow::{Context, Result, anyhow, bail};
use serde::Deserialize;
use std::{
env,
ffi::OsStr,
fs,
path::{Path, PathBuf},
};
#[derive(Debug, Deserialize)]
struct FlutterReleases {
releases: Vec<FlutterReleaseEntry>,
}
#[derive(Debug, Deserialize)]
struct FlutterReleaseEntry {
channel: String,
version: String,
archive: String,
hash: String,
}
pub fn flutter_releases_url(ctx: &Ctx) -> Result<&'static str> {
match ctx.os.as_str() {
"linux" => {
Ok("https://storage.googleapis.com/flutter_infra_release/releases/releases_linux.json")
}
"macos" => {
Ok("https://storage.googleapis.com/flutter_infra_release/releases/releases_macos.json")
}
"windows" => Ok(
"https://storage.googleapis.com/flutter_infra_release/releases/releases_windows.json",
),
_ => bail!("flutter releases json not supported for {}", ctx.os),
}
}
fn flutter_latest_stable_release(ctx: &Ctx) -> Result<FlutterReleaseEntry> {
let url = flutter_releases_url(ctx)?;
let data: FlutterReleases = http_get_json(ctx, url)?;
let mut best: Option<(Version, FlutterReleaseEntry)> = None;
for r in data.releases.into_iter().filter(|r| r.channel == "stable") {
if let Some(v) = Version::parse_loose(&r.version) {
keep_latest_with_version(&mut best, v, r);
}
}
best.map(|(_, r)| r)
.ok_or_else(|| anyhow!("could not determine flutter latest stable"))
}
pub fn flutter_latest_stable(ctx: &Ctx) -> Result<Version> {
let release = flutter_latest_stable_release(ctx)?;
Version::parse_loose(&release.version)
.ok_or_else(|| anyhow!("could not parse flutter version {}", release.version))
}
pub fn flutter_installed_version(bin: &Path) -> Option<Version> {
let args = [OsStr::new("--version"), OsStr::new("--machine")];
if let Ok(out) = run_output(bin.as_os_str(), &args) {
if out.status.success() {
let v: serde_json::Value = serde_json::from_slice(&out.stdout).ok()?;
let s = v.get("frameworkVersion")?.as_str()?;
if let Some(parsed) = Version::parse_loose(s) {
return Some(parsed);
}
}
}
flutter_version_from_root(bin)
}
fn flutter_version_from_root(bin: &Path) -> Option<Version> {
let canonical = fs::canonicalize(bin).ok()?;
let bin_dir = canonical.parent()?;
let root = bin_dir.parent()?;
let version_path = root.join("version");
let contents = fs::read_to_string(version_path).ok()?;
Version::parse_loose(contents.trim())
}
pub fn check_flutter(ctx: &Ctx) -> Result<ToolReport> {
let installed = if let Some(bin) = flutter_bin_in_bindir(ctx) {
flutter_installed_version(&bin)
} else if let Some(bin) = which_or_none("flutter") {
flutter_installed_version(&bin)
} else {
None
};
let latest = flutter_latest_stable(ctx).ok();
let status = Status::from_versions(installed.as_ref(), latest.as_ref());
Ok(ToolReport {
tool: ToolKind::Flutter,
installed,
latest,
status,
method: UpdateMethod::BuiltIn,
notes: vec!["Uses flutter upgrade (built-in updater).".into()],
})
}
pub fn update_flutter(ctx: &Ctx) -> Result<()> {
if ctx.offline {
bail!("offline mode enabled; Flutter update requires network access");
}
let report = check_flutter(ctx)?;
let bindir_flutter = flutter_bin_in_bindir(ctx);
let flutter_in_path = which_or_none("flutter").is_some();
if bindir_flutter.is_none() && !flutter_in_path {
let release = flutter_latest_stable_release(ctx)?;
info(ctx, format!("Installing flutter {}", release.version));
let download_url = format!(
"https://storage.googleapis.com/flutter_infra_release/releases/{}",
release.archive
);
if ctx.dry_run {
info(ctx, format!("[dry-run] would download {download_url}"));
return Ok(());
}
let tmp = download_to_temp(ctx, &download_url)
.with_context(|| format!("download flutter archive from {download_url}"))?;
if !release.hash.is_empty() {
}
let tool_root = ctx.home.join("flutter");
fs::create_dir_all(&tool_root)
.with_context(|| format!("create {}", tool_root.display()))?;
let ver_dir = tool_root.join(&release.version);
ensure_clean_dir(&ver_dir).with_context(|| format!("prepare {}", ver_dir.display()))?;
let archive = release.archive.as_str();
if archive.ends_with(".tar.xz") {
let f = fs::File::open(tmp.path()).context("open flutter archive")?;
let xz = xz2::read::XzDecoder::new(f);
let mut ar = tar::Archive::new(xz);
ar.unpack(&ver_dir)
.with_context(|| format!("extract flutter archive to {}", ver_dir.display()))?;
} else if archive.ends_with(".tar.gz") {
let f = fs::File::open(tmp.path()).context("open flutter archive")?;
let gz = flate2::read::GzDecoder::new(f);
let mut ar = tar::Archive::new(gz);
ar.unpack(&ver_dir)
.with_context(|| format!("extract flutter archive to {}", ver_dir.display()))?;
} else {
bail!("unsupported flutter archive format: {}", release.archive);
}
let extracted = ver_dir.join("flutter");
if !extracted.exists() {
bail!("unexpected flutter archive layout (missing flutter/ directory)");
}
let active = tool_root.join("active");
atomic_symlink(&extracted, &active).with_context(|| {
format!(
"link flutter active {} -> {}",
active.display(),
extracted.display()
)
})?;
let bin_dir = active.join("bin");
link_dir_bins(&bin_dir, &ctx.bindir, &["flutter", "dart", "pub"])
.context("link flutter binaries")?;
maybe_path_hint_for_dir(ctx, &bin_dir, "flutter bin");
maybe_hint_flutter_bins(ctx);
if let Err(err) = prune_tool_versions(&tool_root, &ver_dir, &["active"]) {
warn(ctx, format!("Failed to remove old flutter versions: {err}"));
}
info(ctx, "flutter installed");
return Ok(());
}
if matches!(report.status, Status::UpToDate) && !ctx.force {
info(ctx, "flutter is up-to-date");
return Ok(());
}
info(ctx, "Updating flutter via flutter upgrade");
if ctx.dry_run {
info(ctx, "[dry-run] would run: flutter upgrade");
return Ok(());
}
let status = if let Some(bin) = bindir_flutter {
let args = [OsStr::new("upgrade")];
run_status(bin.as_os_str(), &args).context("failed to run flutter upgrade")?
} else {
run_status("flutter", &["upgrade"]).context("failed to run flutter upgrade")?
};
if !status.success() {
bail!("flutter upgrade failed");
}
maybe_hint_flutter_bins(ctx);
info(ctx, "flutter updated");
Ok(())
}
fn maybe_hint_flutter_bins(ctx: &Ctx) {
if let Some(pub_cache) = pub_cache_dir() {
maybe_path_hint_for_dir(ctx, &pub_cache.join("bin"), "pub cache bin");
}
}
fn pub_cache_dir() -> Option<PathBuf> {
env::var("PUB_CACHE")
.ok()
.filter(|value| !value.trim().is_empty())
.map(PathBuf::from)
.or_else(|| home_dir().map(|home| home.join(".pub-cache")))
}
fn flutter_bin_in_bindir(ctx: &Ctx) -> Option<PathBuf> {
let candidate = ctx.bindir.join("flutter");
if candidate.exists() {
return Some(candidate);
}
None
}