use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use anyhow::{Context, Result, bail};
use sha2::{Digest, Sha256};
pub const VERSION: &str = "4.3.3";
const SUMS: &[(&str, &str)] = &[
(
"tailwindcss-linux-arm64",
"55fd0b241214eff3de1e8ee4f22796662f2d2e7a49bcfca7477cfd0bac398195",
),
(
"tailwindcss-linux-arm64-musl",
"71ea4be79c9de9827545682df3e040053fb535d37c71ed2cfdedf9385a0868e0",
),
(
"tailwindcss-linux-x64",
"dc61b3ac6b8c9ca874c0cc4c57b2409791a64c5540404ca5f5367360babc313a",
),
(
"tailwindcss-linux-x64-musl",
"a04d34ceacc8f52cbe8920ad846cdeb61d3d0021dba32db0d1f77c9d9fad7a6c",
),
(
"tailwindcss-macos-arm64",
"cdf646702987a743464dff4d9c60fd4480d1c1e73dd819a9a67f1078815dce9d",
),
(
"tailwindcss-macos-x64",
"7922e0953f2110c05976e3bf58f14e643d90427575e766b7d433f5f80cbee7e1",
),
(
"tailwindcss-windows-x64.exe",
"e0e260ce048014e9268f6237ff18f8ccf02cef521cbd0ae04e82c2cdf7aa3955",
),
];
pub const INPUT: &str = "resources/css/app.css";
pub const OUTPUT: &str = "public/css/app.css";
pub const INPUT_STUB: &str = r#"/* Tailwind CSS (https://tailwindcss.com/docs), built by `rnx serve` and `rnx build`
into public/css/app.css with the standalone CLI: no Node needed.
Classes are found in the views; add other places with more @source lines. */
@import "tailwindcss";
@source "../views";
/* The UI kit (rx-* classes) sits outside Tailwind's layers, so its components keep their
look next to utilities. Rebrand it with its tokens, e.g. :root { --rx-accent: #0a7d5a; } */
"#;
pub fn enabled(root: &Path) -> bool {
root.join(INPUT).is_file()
}
fn asset() -> Result<&'static str> {
let musl = cfg!(target_env = "musl");
Ok(match (env::consts::OS, env::consts::ARCH) {
("linux", "x86_64") if musl => "tailwindcss-linux-x64-musl",
("linux", "x86_64") => "tailwindcss-linux-x64",
("linux", "aarch64") if musl => "tailwindcss-linux-arm64-musl",
("linux", "aarch64") => "tailwindcss-linux-arm64",
("macos", "x86_64") => "tailwindcss-macos-x64",
("macos", "aarch64") => "tailwindcss-macos-arm64",
("windows", "x86_64") => "tailwindcss-windows-x64.exe",
(os, arch) => bail!(
"Tailwind has no standalone CLI for {os}/{arch}; install one and set TAILWIND_BIN"
),
})
}
fn cache_dir() -> Result<PathBuf> {
if let Some(dir) = env::var_os("RNX_CACHE_DIR") {
return Ok(PathBuf::from(dir));
}
let base = if cfg!(windows) {
env::var_os("LOCALAPPDATA").map(PathBuf::from)
} else if cfg!(target_os = "macos") {
env::var_os("HOME").map(|home| PathBuf::from(home).join("Library/Caches"))
} else {
env::var_os("XDG_CACHE_HOME")
.map(PathBuf::from)
.or_else(|| env::var_os("HOME").map(|home| PathBuf::from(home).join(".cache")))
};
Ok(base
.context("no cache directory (set RNX_CACHE_DIR)")?
.join("renox"))
}
pub fn binary() -> Result<PathBuf> {
if let Some(bin) = env::var_os("TAILWIND_BIN").filter(|v| !v.is_empty()) {
return Ok(PathBuf::from(bin));
}
let asset = asset()?;
let path = cache_dir()?.join(format!("{VERSION}-{asset}"));
if !path.is_file() {
download(asset, &path)?;
}
Ok(path)
}
fn download(asset: &str, to: &Path) -> Result<()> {
let expected = SUMS
.iter()
.find(|(name, _)| *name == asset)
.map(|(_, sum)| *sum)
.context("no checksum for this platform")?;
let url =
format!("https://github.com/tailwindlabs/tailwindcss/releases/download/v{VERSION}/{asset}");
let dir = to.parent().context("the cache path has a parent")?;
fs::create_dir_all(dir).with_context(|| format!("could not create {}", dir.display()))?;
let partial = to.with_extension("download");
eprintln!("rnx: downloading Tailwind CSS {VERSION} ({asset})…");
let status = Command::new("curl")
.args([
"--fail",
"--silent",
"--show-error",
"--location",
"--retry",
"2",
])
.arg("--output")
.arg(&partial)
.arg(&url)
.status()
.context("could not run curl; install it, or download Tailwind and set TAILWIND_BIN")?;
if !status.success() {
let _ = fs::remove_file(&partial);
bail!("could not download {url}");
}
let bytes = fs::read(&partial)?;
let actual = hex(&Sha256::digest(&bytes));
if actual != expected {
let _ = fs::remove_file(&partial);
bail!("{asset} has SHA-256 {actual}, expected {expected}; not using it");
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(&partial, fs::Permissions::from_mode(0o755))?;
}
fs::rename(&partial, to)?;
eprintln!("rnx: saved {}", to.display());
Ok(())
}
fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
fn command(root: &Path) -> Result<Command> {
let mut command = Command::new(binary()?);
command
.current_dir(root)
.args(["--input", INPUT, "--output", OUTPUT]);
Ok(command)
}
pub fn build(root: &Path, minify: bool) -> Result<()> {
let mut command = command(root)?;
if minify {
command.arg("--minify");
}
let output = command.output().context("could not run Tailwind")?;
if !output.status.success() {
eprint!("{}", String::from_utf8_lossy(&output.stderr));
bail!("Tailwind failed");
}
Ok(())
}
pub fn watch(root: &Path) -> Result<Child> {
command(root)?
.arg("--watch=always")
.stdin(Stdio::null())
.spawn()
.context("could not start Tailwind")
}
pub fn run(root: &Path, watching: bool, minify: bool) -> Result<()> {
if !enabled(root) {
bail!("no {INPUT} here: this app doesn't use Tailwind (see `rnx new --tailwind`)");
}
if watching {
let mut child = watch(root)?;
child.wait()?;
return Ok(());
}
build(root, minify)?;
println!("Built {OUTPUT}.");
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_platform_has_a_pinned_sum() {
assert!(
SUMS.iter()
.any(|(name, _)| Ok(*name) == asset().as_deref().map_err(|_| ()))
);
for (_, sum) in SUMS {
assert_eq!(sum.len(), 64);
assert!(sum.chars().all(|c| c.is_ascii_hexdigit()));
}
assert_eq!(hex(&[0, 15, 255]), "000fff");
}
#[test]
fn apps_with_an_input_file_use_tailwind() {
let dir = tempfile::tempdir().unwrap();
assert!(!enabled(dir.path()));
let input = dir.path().join(INPUT);
fs::create_dir_all(input.parent().unwrap()).unwrap();
fs::write(&input, INPUT_STUB).unwrap();
assert!(enabled(dir.path()));
}
}