use std::fs;
use std::path::{Path, PathBuf};
use sha2::{Digest as _, Sha256};
pub const DEPLOY_DIR: &str = ".deploy";
const READ_LIMIT: u64 = 256 * 1024;
pub const SHOWN_STEPS: usize = 8;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Kind {
Apps,
Web,
Cloud,
Servers,
Releases,
Database,
Build,
Other,
}
impl Kind {
const ALL: [Kind; 8] = [
Kind::Apps,
Kind::Web,
Kind::Cloud,
Kind::Servers,
Kind::Releases,
Kind::Database,
Kind::Build,
Kind::Other,
];
pub fn title(self) -> &'static str {
match self {
Kind::Apps => "Apps & Stores",
Kind::Web => "Web & Hosting",
Kind::Cloud => "Cloud & Containers",
Kind::Servers => "Servers",
Kind::Releases => "Releases",
Kind::Database => "Database",
Kind::Build => "Build & Test",
Kind::Other => "Other",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Env {
Production,
Staging,
Preview,
Development,
}
impl Env {
pub fn title(self) -> &'static str {
match self {
Env::Production => "Production",
Env::Staging => "Staging",
Env::Preview => "Preview",
Env::Development => "Development",
}
}
fn from_word(word: &str) -> Option<Self> {
Some(match word {
"prod" | "production" | "live" | "prd" => Env::Production,
"staging" | "stage" | "stg" => Env::Staging,
"preview" | "beta" | "qa" | "uat" => Env::Preview,
"dev" | "development" | "sandbox" => Env::Development,
_ => return None,
})
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DeployScript {
pub path: PathBuf,
pub file: String,
pub title: String,
pub kind: Kind,
pub group: String,
pub env: Option<Env>,
pub target: Option<String>,
pub about: Option<String>,
pub steps: Vec<String>,
pub needs: Vec<String>,
pub asks: bool,
pub command: String,
pub hash: String,
}
const SEARCH_DEPTH: usize = 2;
const SKIPPED: [&str; 12] = [
"node_modules",
"target",
"build",
"dist",
"out",
"bin",
"obj",
"vendor",
"third_party",
"Pods",
"DerivedData",
"venv",
];
pub fn find_bases(root: &Path, git: Option<&Path>) -> Vec<PathBuf> {
let mut bases: Vec<PathBuf> = std::iter::once(root)
.chain(git)
.filter(|base| base.join(DEPLOY_DIR).is_dir())
.map(Path::to_path_buf)
.collect();
let mut level = vec![root.to_path_buf()];
for _ in 0..SEARCH_DEPTH {
let mut next = Vec::new();
for dir in &level {
let Ok(entries) = fs::read_dir(dir) else {
continue;
};
let mut children: Vec<PathBuf> = entries
.flatten()
.filter(|entry| entry.file_type().is_ok_and(|kind| kind.is_dir()))
.filter(|entry| {
let name = entry.file_name();
let name = name.to_string_lossy();
!name.starts_with('.') && !SKIPPED.contains(&name.as_ref())
})
.map(|entry| entry.path())
.collect();
children.sort();
for child in &children {
if child.join(DEPLOY_DIR).is_dir() && !bases.contains(child) {
bases.push(child.clone());
}
}
next.extend(children);
}
level = next;
}
bases
}
pub fn scan(base: &Path) -> Vec<DeployScript> {
let Ok(entries) = fs::read_dir(base.join(DEPLOY_DIR)) else {
return Vec::new();
};
let files: Vec<(PathBuf, String, String)> = entries
.flatten()
.filter_map(|entry| {
let path = entry.path();
let name = path.file_name()?.to_str()?.to_string();
if !name.ends_with(".sh") || !path.is_file() {
return None;
}
let text = match entry.metadata() {
Ok(meta) if meta.len() <= READ_LIMIT => fs::read_to_string(&path).ok(),
_ => None,
}
.unwrap_or_default();
Some((path, name, text))
})
.collect();
let mut scripts: Vec<DeployScript> = files
.iter()
.filter(|(_, name, _)| {
!files
.iter()
.any(|(_, other, text)| other != name && sources(text, name))
})
.map(|(path, name, text)| {
let helpers: Vec<&str> = files
.iter()
.filter(|(_, other, _)| other != name && sources(text, other))
.map(|(_, _, helper)| helper.as_str())
.collect();
read_script(path.clone(), name, text, &Shared::from_helpers(&helpers))
})
.collect();
scripts.sort_by(|a, b| {
(a.kind, &a.group, a.title.to_lowercase(), &a.file).cmp(&(
b.kind,
&b.group,
b.title.to_lowercase(),
&b.file,
))
});
scripts
}
fn sources(text: &str, name: &str) -> bool {
text.lines().any(|line| {
let line = line.trim_start();
(line.starts_with("source ") || line.starts_with(". "))
&& line
.split(|ch: char| ch.is_whitespace() || "\"'/)".contains(ch))
.any(|word| word == name)
})
}
pub fn grouped(scripts: &[DeployScript]) -> Vec<(String, Kind, Vec<&DeployScript>)> {
let mut groups: Vec<(String, Kind, Vec<&DeployScript>)> = Vec::new();
for script in scripts {
match groups.iter_mut().find(|(name, ..)| *name == script.group) {
Some((_, _, members)) => members.push(script),
None => groups.push((script.group.clone(), script.kind, vec![script])),
}
}
groups
}
#[derive(Default)]
struct Shared {
set: Vec<String>,
remote: Vec<String>,
}
impl Shared {
fn from_helpers(helpers: &[&str]) -> Self {
let mut shared = Self::default();
for text in helpers {
shared.set.extend(assigned_variables(&logical_lines(text)));
shared.remote.extend(remote_functions(text));
}
shared
}
}
fn remote_functions(text: &str) -> Vec<String> {
let mut found: Vec<String> = Vec::new();
let mut current: Option<String> = None;
for line in text.lines() {
let line = line.trim();
if let Some(name) = function_name(line) {
current = Some(name);
}
let Some(name) = ¤t else {
continue;
};
let runs_ssh = segments(line).iter().any(|segment| {
command_words(segment)
.first()
.is_some_and(|word| base_name(word) == "ssh")
});
if runs_ssh && !found.contains(name) {
found.push(name.clone());
}
if line == "}" || line.ends_with("; }") {
current = None;
}
}
found
}
fn function_name(line: &str) -> Option<String> {
let (rest, keyword) = match line.strip_prefix("function ") {
Some(rest) => (rest.trim_start(), true),
None => (line, false),
};
let end = rest
.find(|ch: char| !(ch.is_ascii_alphanumeric() || ch == '_' || ch == '-'))
.unwrap_or(rest.len());
let (name, after) = rest.split_at(end);
let after = after.trim_start();
let defined = after.starts_with("()") || (keyword && after.starts_with('{'));
(defined && !name.is_empty()).then(|| name.to_string())
}
fn read_script(path: PathBuf, name: &str, text: &str, shared: &Shared) -> DeployScript {
let header = read_header(text);
let body = logical_lines(text);
let mut remote = shared.remote.clone();
remote.extend(remote_functions(text));
let mut found: Vec<Found> = Vec::new();
let mut progress = Vec::new();
let mut asks = false;
for line in &body {
let mut queue = segments(line);
queue.reverse();
while let Some(segment) = queue.pop() {
let words = command_words(&segment);
let Some((command, args)) = words.split_first() else {
continue;
};
let command = base_name(command);
if command == "read" || command == "select" {
asks = true;
continue;
}
if command == "echo" || command == "printf" {
if let Some(text) = progress_line(&segment) {
progress.push(text);
}
continue;
}
let args: Vec<&str> = args.iter().map(String::as_str).collect();
let is_remote = remote.iter().any(|function| function == command);
if is_remote {
found.push(if args.is_empty() {
self::found("Connects to the server", Kind::Servers)
} else {
self::found("Runs commands on the server", Kind::Servers)
});
} else if let Some(step) = describe(command, &args, &segment) {
found.push(step);
}
if (command == "ssh" || is_remote)
&& let Some(start) = segment.find(['\'', '"'])
{
let remote = segment[start..].trim_matches(['\'', '"']);
queue.extend(segments(remote).into_iter().rev());
}
}
}
let stem = name.strip_suffix(".sh").unwrap_or(name);
let (named, env) = title_from_name(stem);
let kind = main_kind(&found).unwrap_or_else(|| kind_from_name(stem));
let target = found
.iter()
.filter(|step| step.weight == 2)
.rev()
.find_map(|step| step.target.clone());
let mut steps: Vec<String> = Vec::new();
for step in found {
if !steps.contains(&step.step) {
steps.push(step.step);
}
}
if steps.is_empty() {
steps = progress;
steps.dedup();
}
let base = path
.parent()
.and_then(Path::parent)
.map(Path::to_path_buf)
.unwrap_or_default();
DeployScript {
hash: Sha256::digest(text.as_bytes())
.iter()
.map(|byte| format!("{byte:02x}"))
.collect(),
command: run_command(&path, name, text),
file: format!("{DEPLOY_DIR}/{name}"),
title: header.title.unwrap_or(named),
group: header.group.unwrap_or_else(|| kind.title().to_string()),
kind,
env: header.env.or(env),
target,
about: header.about,
steps,
needs: needed_variables(&body, &shared.set),
asks,
path: base.join(DEPLOY_DIR).join(name),
}
}
fn run_command(path: &Path, name: &str, text: &str) -> String {
let file = crate::quote(&format!("{DEPLOY_DIR}/{name}"));
if text.starts_with("#!") && is_executable(path) {
format!("./{file}")
} else if cfg!(windows) {
match crate::git_bash() {
Some(bash) => format!("& {} {file}", crate::quote(&bash.to_string_lossy())),
None => {
"Write-Error 'Deploy scripts need Git for Windows: https://git-scm.com/downloads'"
.into()
}
}
} else {
format!("bash {file}")
}
}
#[cfg(unix)]
fn is_executable(path: &Path) -> bool {
use std::os::unix::fs::PermissionsExt as _;
fs::metadata(path).is_ok_and(|meta| meta.permissions().mode() & 0o111 != 0)
}
#[cfg(not(unix))]
fn is_executable(_: &Path) -> bool {
false
}
#[derive(Default)]
struct Header {
title: Option<String>,
group: Option<String>,
env: Option<Env>,
about: Option<String>,
}
fn read_header(text: &str) -> Header {
let mut header = Header::default();
let mut about: Vec<String> = Vec::new();
let mut paragraph_done = false;
for (index, line) in text.lines().enumerate() {
let line = line.trim();
if index == 0 && line.starts_with("#!") {
continue;
}
if line.is_empty() {
if about.is_empty() {
continue;
}
break;
}
let Some(comment) = line.strip_prefix('#') else {
break;
};
let comment = comment.trim();
if comment.is_empty() || comment.chars().all(|ch| "#-=*~_/ ".contains(ch)) {
paragraph_done |= !about.is_empty();
continue;
}
let lower = comment.to_lowercase();
if lower.starts_with("shellcheck") {
continue;
}
if let Some((key, value)) = comment.split_once(':') {
let value = value.trim().to_string();
match key.trim().to_lowercase().as_str() {
"title" | "name" if !value.is_empty() => {
header.title = Some(value);
continue;
}
"group" | "category" if !value.is_empty() => {
header.group = Some(value);
continue;
}
"env" | "environment" => {
header.env = Env::from_word(&value.to_lowercase());
continue;
}
"description" | "about" | "summary" if !value.is_empty() => {
about = vec![value];
paragraph_done = true;
continue;
}
"usage" => {
paragraph_done = true;
continue;
}
_ => {}
}
}
if !paragraph_done && about.len() < 4 {
about.push(comment.to_string());
}
}
let about = about.join(" ");
header.about = (!about.is_empty()).then(|| sentence(&about));
header
}
fn sentence(text: &str) -> String {
let mut text = text.trim().to_string();
if let Some(first) = text.chars().next()
&& first.is_lowercase()
{
text.replace_range(..first.len_utf8(), &first.to_uppercase().to_string());
}
if !text.ends_with(['.', '!', '?', ':']) {
text.push('.');
}
text
}
fn title_from_name(stem: &str) -> (String, Option<Env>) {
let mut env = None;
let mut words = Vec::new();
for word in split_words(stem) {
let lower = word.to_lowercase();
if let Some(found) = Env::from_word(&lower) {
env = env.or(Some(found));
continue;
}
if words.is_empty() && lower.chars().all(|ch| ch.is_ascii_digit()) {
continue;
}
words.push(nice_word(&lower, words.is_empty()));
}
if words.is_empty() {
words.push("Deploy".to_string());
}
(words.join(" "), env)
}
fn split_words(stem: &str) -> Vec<String> {
let mut words = Vec::new();
for part in stem.split(['-', '_', '.', ' ']) {
let chars: Vec<char> = part.chars().collect();
let mut word = String::new();
for (index, &ch) in chars.iter().enumerate() {
let previous = index.checked_sub(1).map(|at| chars[at]);
let next = chars.get(index + 1);
if ch.is_uppercase()
&& previous.is_some_and(char::is_lowercase)
&& next.is_some_and(|next| next.is_lowercase())
{
words.push(std::mem::take(&mut word));
}
word.push(ch);
}
if !word.is_empty() {
words.push(word);
}
}
words
}
fn nice_word(word: &str, first: bool) -> String {
let known = match word {
"api" => "API",
"ios" => "iOS",
"macos" | "osx" => "macOS",
"ipados" => "iPadOS",
"db" => "DB",
"aws" => "AWS",
"gcp" => "GCP",
"k8s" => "K8s",
"s3" => "S3",
"cdn" => "CDN",
"dns" => "DNS",
"ssl" | "tls" => return word.to_uppercase(),
"sql" => "SQL",
"ui" => "UI",
"cli" => "CLI",
"gui" => "GUI",
"dmg" => "DMG",
"npm" => "npm",
"ci" => "CI",
"testflight" => "TestFlight",
"appstore" => "App Store",
"github" | "gh" => "GitHub",
"gitlab" => "GitLab",
"vps" => "VPS",
"ssh" => "SSH",
"www" => "WWW",
"fly" | "flyio" => "Fly.io",
"cloudflare" => "Cloudflare",
"vercel" => "Vercel",
"netlify" => "Netlify",
"docker" => "Docker",
"to" | "and" | "of" | "on" | "the" | "for" | "with" if !first => return word.to_string(),
_ => {
let mut chars = word.chars();
return match chars.next() {
Some(first) => first.to_uppercase().chain(chars).collect(),
None => String::new(),
};
}
};
known.to_string()
}
fn kind_from_name(stem: &str) -> Kind {
let words: Vec<String> = split_words(stem)
.iter()
.map(|word| word.to_lowercase())
.collect();
let any = |names: &[&str]| words.iter().any(|word| names.contains(&word.as_str()));
if any(&[
"ios",
"macos",
"app",
"appstore",
"testflight",
"android",
"play",
"dmg",
"notarize",
]) {
Kind::Apps
} else if any(&[
"web", "site", "website", "docs", "frontend", "static", "pages", "cdn",
]) {
Kind::Web
} else if any(&[
"docker", "k8s", "kube", "cluster", "cloud", "aws", "gcp", "azure", "infra",
]) {
Kind::Cloud
} else if any(&["server", "vps", "ssh", "host", "nginx", "backend"]) {
Kind::Servers
} else if any(&["release", "publish", "tag", "version", "bump", "changelog"]) {
Kind::Releases
} else if any(&[
"db",
"database",
"migrate",
"migrations",
"backup",
"seed",
"restore",
]) {
Kind::Database
} else if any(&["build", "test", "lint", "check"]) {
Kind::Build
} else {
Kind::Other
}
}
#[derive(Debug)]
struct Found {
step: String,
kind: Kind,
target: Option<String>,
weight: u8,
}
fn found(step: impl Into<String>, kind: Kind) -> Found {
Found {
step: step.into(),
kind,
target: None,
weight: 2,
}
}
impl Found {
fn to(mut self, target: impl Into<String>) -> Self {
self.target = Some(target.into());
self
}
fn minor(mut self) -> Self {
self.weight = 1;
self
}
fn side(mut self) -> Self {
self.weight = 0;
self
}
}
fn main_kind(found: &[Found]) -> Option<Kind> {
Kind::ALL
.into_iter()
.map(|kind| {
let weight: u32 = found
.iter()
.filter(|step| step.kind == kind)
.map(|step| u32::from(step.weight))
.sum();
(kind, weight)
})
.filter(|(_, weight)| *weight > 0)
.max_by(|a, b| a.1.cmp(&b.1).then(b.0.cmp(&a.0)))
.map(|(kind, _)| kind)
}
fn logical_lines(text: &str) -> Vec<String> {
let mut lines = Vec::new();
let mut current = String::new();
for line in text.lines() {
let trimmed = line.trim();
if current.is_empty() && (trimmed.is_empty() || trimmed.starts_with('#')) {
continue;
}
match trimmed.strip_suffix('\\') {
Some(start) => {
current.push_str(start);
current.push(' ');
}
None => {
current.push_str(trimmed);
lines.push(std::mem::take(&mut current));
}
}
}
if !current.is_empty() {
lines.push(current);
}
lines
}
fn segments(line: &str) -> Vec<String> {
let mut parts = vec![line.to_string()];
for separator in ["&&", "||", ";", "|", "$(", "`", ")"] {
parts = parts
.iter()
.flat_map(|part| part.split(separator).map(str::to_string))
.collect();
}
parts
.into_iter()
.map(|part| part.trim().to_string())
.filter(|part| !part.is_empty())
.collect()
}
fn command_words(segment: &str) -> Vec<String> {
let words: Vec<String> = segment
.split_whitespace()
.map(|word| {
word.trim_matches(['"', '\'', '{', '}', '(', '['])
.to_lowercase()
})
.filter(|word| !word.is_empty())
.collect();
let skip = words
.iter()
.position(|word| {
!matches!(
word.as_str(),
"if" | "then"
| "else"
| "elif"
| "do"
| "while"
| "until"
| "!"
| "time"
| "sudo"
| "exec"
| "command"
| "nohup"
| "env"
| "npx"
| "bunx"
| "run"
| "retry"
| "export"
| "local"
) && !is_assignment(word)
})
.unwrap_or(words.len());
words[skip..].to_vec()
}
fn is_assignment(word: &str) -> bool {
word.split_once('=').is_some_and(|(name, _)| {
!name.is_empty()
&& name
.chars()
.all(|ch| ch.is_ascii_alphanumeric() || ch == '_')
})
}
fn base_name(command: &str) -> &str {
command.rsplit('/').next().unwrap_or(command)
}
fn progress_line(segment: &str) -> Option<String> {
let mut text = segment.split_once(char::is_whitespace)?.1.trim();
while let Some(rest) = ["-n ", "-e ", "-en ", "-ne "]
.iter()
.find_map(|flag| text.strip_prefix(flag))
{
text = rest.trim_start();
}
let text = text.trim_matches(['"', '\'']).trim();
let marked = ["==>", "->", "→", "▶", "»", "***", "---", "::", "✓", "🚀"]
.iter()
.find_map(|mark| text.strip_prefix(mark));
let text = marked?.trim().trim_end_matches(['.', '…']).trim();
(text.len() > 2 && !text.contains('$'))
.then(|| sentence(text).trim_end_matches('.').to_string())
}
fn is_remote_path(arg: &str) -> bool {
!arg.starts_with('-')
&& !arg.contains("://")
&& (arg.contains('@')
|| arg
.split_once(':')
.is_some_and(|(host, _)| !host.contains('/')))
}
fn operand<'a>(args: &[&'a str]) -> Option<&'a str> {
args.iter().copied().find(|arg| !arg.starts_with('-'))
}
fn host(command: &str, args: &[&str]) -> Option<String> {
let mut skip_next = false;
let mut first_operand = None;
for arg in args {
if skip_next {
skip_next = false;
continue;
}
if arg.starts_with('-') {
skip_next = command == "ssh" && matches!(*arg, "-i" | "-p" | "-o" | "-l" | "-f" | "-j");
continue;
}
if let Some((_, rest)) = arg.split_once('@') {
return clean_host(rest.split(':').next().unwrap_or(rest));
}
if command != "ssh"
&& !arg.contains("://")
&& let Some((name, _)) = arg.split_once(':')
&& !name.contains('/')
{
return clean_host(name);
}
first_operand.get_or_insert(*arg);
}
if command == "ssh" {
return first_operand.and_then(clean_host);
}
None
}
fn clean_host(host: &str) -> Option<String> {
let host = host.trim_matches(['"', '\'']);
(!host.is_empty() && !host.contains('$') && !host.contains('<')).then(|| host.to_string())
}
fn describe(command: &str, args: &[&str], segment: &str) -> Option<Found> {
let has = |word: &str| args.contains(&word);
let first = args.first().copied().unwrap_or("");
let second = args.get(1).copied().unwrap_or("");
let lower = segment.to_lowercase();
Some(match command {
"xcodebuild" if has("archive") => found("Archives the app with Xcode", Kind::Apps).minor(),
"xcodebuild" if has("-exportarchive") => {
found("Exports the archive for distribution", Kind::Apps).minor()
}
"xcodebuild" if has("test") => found("Runs the Xcode tests", Kind::Build).minor(),
"xcodebuild" => found("Builds with Xcode", Kind::Apps).minor(),
"xcrun" => match first {
"notarytool" if has("submit") => {
found("Sends the app to Apple for notarization", Kind::Apps)
}
"stapler" => found("Staples the notarization ticket", Kind::Apps).minor(),
"altool" => {
found("Uploads the build to App Store Connect", Kind::Apps).to("App Store Connect")
}
_ => return None,
},
"stapler" => found("Staples the notarization ticket", Kind::Apps).minor(),
"codesign" => found("Code-signs the app", Kind::Apps).minor(),
"productbuild" | "pkgbuild" => found("Builds an installer package", Kind::Releases).minor(),
"hdiutil" if first == "create" => found("Packages a disk image", Kind::Releases).minor(),
"create-dmg" => found("Packages a disk image", Kind::Releases).minor(),
"fastlane" => {
let lane = args
.iter()
.copied()
.find(|arg| !arg.starts_with('-') && !matches!(*arg, "ios" | "android" | "mac"))?;
let step = found(format!("Runs the fastlane {lane} lane"), Kind::Apps);
if lane.contains("beta") || lane.contains("testflight") {
step.to("TestFlight")
} else if lane.contains("release") || lane.contains("store") || lane == "deliver" {
step.to("App Store")
} else if lane.contains("play") || lane == "supply" {
step.to("Google Play")
} else {
step
}
}
"gradlew" | "gradle" if args.iter().any(|arg| arg.starts_with("publish")) => {
found("Publishes the Android app", Kind::Apps).to("Google Play")
}
"gradlew" | "gradle" if args.iter().any(|arg| arg.contains("release")) => {
found("Builds the Android release", Kind::Apps).minor()
}
"vercel" if has("--prod") => found("Deploys to Vercel production", Kind::Web).to("Vercel"),
"vercel" if matches!(first, "" | "deploy") || first.starts_with('-') => {
found("Deploys a Vercel preview", Kind::Web).to("Vercel")
}
"netlify" if first == "deploy" => found("Deploys to Netlify", Kind::Web).to("Netlify"),
"wrangler" if first == "pages" => {
found("Deploys to Cloudflare Pages", Kind::Web).to("Cloudflare")
}
"wrangler" if matches!(first, "deploy" | "publish") => {
found("Deploys the Worker to Cloudflare", Kind::Web).to("Cloudflare")
}
"firebase" if first == "deploy" => found("Deploys to Firebase", Kind::Web).to("Firebase"),
"surge" => found("Publishes to Surge", Kind::Web).to("Surge"),
"gh-pages" => found("Publishes to GitHub Pages", Kind::Web).to("GitHub Pages"),
"aws" => match first {
"s3" if matches!(second, "sync" | "cp") => {
found("Uploads the files to S3", Kind::Web).to("S3")
}
"cloudfront" => found("Clears the CloudFront cache", Kind::Web).minor(),
"ecs" => found("Updates the ECS service", Kind::Cloud).to("AWS ECS"),
"lambda" => found("Updates the Lambda function", Kind::Cloud).to("AWS Lambda"),
"ecr" => found("Signs in to Amazon ECR", Kind::Cloud).minor(),
"cloudformation" => found("Deploys the CloudFormation stack", Kind::Cloud).to("AWS"),
"elasticbeanstalk" => found("Deploys to Elastic Beanstalk", Kind::Cloud).to("AWS"),
"" => return None,
other => found(format!("Calls AWS {other}"), Kind::Cloud).minor(),
},
"sam" if first == "deploy" => found("Deploys with AWS SAM", Kind::Cloud).to("AWS"),
"cdk" if first == "deploy" => found("Deploys the CDK stacks", Kind::Cloud).to("AWS"),
"serverless" | "sls" if first == "deploy" => {
found("Deploys with Serverless", Kind::Cloud).to("AWS")
}
"gcloud" if has("deploy") && has("run") => {
found("Deploys to Cloud Run", Kind::Cloud).to("Cloud Run")
}
"gcloud" if has("deploy") && has("app") => {
found("Deploys to App Engine", Kind::Cloud).to("App Engine")
}
"gcloud" if has("deploy") && has("functions") => {
found("Deploys the Cloud Functions", Kind::Cloud).to("Google Cloud")
}
"gcloud" if has("deploy") => {
found("Deploys to Google Cloud", Kind::Cloud).to("Google Cloud")
}
"gcloud" if has("builds") && has("submit") => {
found("Builds the image on Cloud Build", Kind::Cloud).minor()
}
"az" => match first {
"webapp" => found("Deploys the Azure web app", Kind::Cloud).to("Azure"),
"functionapp" => found("Deploys the Azure function app", Kind::Cloud).to("Azure"),
"containerapp" => found("Updates the Azure container app", Kind::Cloud).to("Azure"),
"acr" => found("Pushes to Azure Container Registry", Kind::Cloud).minor(),
"login" | "account" | "" => return None,
other => found(format!("Calls Azure {other}"), Kind::Cloud).minor(),
},
"fly" | "flyctl" if first == "deploy" => {
found("Deploys to Fly.io", Kind::Cloud).to("Fly.io")
}
"railway" if first == "up" => found("Deploys to Railway", Kind::Cloud).to("Railway"),
"heroku" if first.starts_with("container:release") || first == "releases" => {
found("Releases on Heroku", Kind::Cloud).to("Heroku")
}
"doctl" if first == "apps" => {
found("Updates the DigitalOcean app", Kind::Cloud).to("DigitalOcean")
}
"docker" | "podman" => match first {
"build" => found("Builds a Docker image", Kind::Cloud).minor(),
"buildx" if has("--push") => {
found("Builds and pushes a multi-platform image", Kind::Cloud)
}
"buildx" if has("build") => found("Builds a Docker image", Kind::Cloud).minor(),
"push" => found("Pushes the image to the registry", Kind::Cloud),
"login" => found("Signs in to the registry", Kind::Cloud).minor(),
"compose" => compose(&args[1..])?,
"stack" if has("deploy") => found("Deploys the Docker stack", Kind::Cloud),
"run" => found("Runs a container", Kind::Cloud).minor(),
_ => return None,
},
"docker-compose" => compose(args)?,
"kubectl" => match first {
"apply" => found("Applies the Kubernetes manifests", Kind::Cloud).to("Kubernetes"),
"rollout" if second == "restart" => {
found("Restarts the Kubernetes deployment", Kind::Cloud).to("Kubernetes")
}
"rollout" if second == "status" => {
found("Waits for the rollout to finish", Kind::Cloud).minor()
}
"set" if second == "image" => {
found("Points the deployment at the new image", Kind::Cloud).to("Kubernetes")
}
"scale" => found("Scales the deployment", Kind::Cloud).to("Kubernetes"),
"delete" => found("Deletes Kubernetes resources", Kind::Cloud).to("Kubernetes"),
_ => return None,
},
"helm" if matches!(first, "upgrade" | "install") => {
found("Upgrades the Helm release", Kind::Cloud).to("Kubernetes")
}
"skaffold" if matches!(first, "run" | "deploy") => {
found("Deploys with Skaffold", Kind::Cloud).to("Kubernetes")
}
"terraform" | "tofu" => match first {
"apply" => found("Applies the Terraform changes", Kind::Cloud),
"plan" => found("Plans the infrastructure changes", Kind::Cloud).minor(),
"destroy" => found("Destroys the Terraform infrastructure", Kind::Cloud),
_ => return None,
},
"pulumi" if first == "up" => found("Updates the Pulumi stack", Kind::Cloud),
"ssh" => match host("ssh", args) {
Some(host) => found(format!("Runs commands on {host}"), Kind::Servers).to(host),
None => found("Runs commands on the server", Kind::Servers),
},
"rsync" => match host("rsync", args) {
Some(host) => found(format!("Copies the files to {host}"), Kind::Servers).to(host),
None if args.iter().any(|arg| is_remote_path(arg)) => {
found("Copies the files to the server", Kind::Servers)
}
None => found("Syncs the files with rsync", Kind::Servers).minor(),
},
"scp" => match host("scp", args) {
Some(host) => found(format!("Copies files to {host}"), Kind::Servers).to(host),
None => found("Copies files to the server", Kind::Servers),
},
"sftp" => found("Uploads files over SFTP", Kind::Servers),
"ansible-playbook" => match operand(args) {
Some(book) => found(format!("Runs the Ansible playbook {book}"), Kind::Servers),
None => found("Runs an Ansible playbook", Kind::Servers),
},
"systemctl" if matches!(first, "restart" | "reload") => {
match operand(&args[1..]).filter(|service| !service.contains('$')) {
Some(service) => found(format!("Restarts the {service} service"), Kind::Servers),
None => found("Restarts the service", Kind::Servers),
}
}
"service" if matches!(second, "restart" | "reload") && !first.contains('$') => {
found(format!("Restarts the {first} service"), Kind::Servers)
}
"pm2" if matches!(first, "reload" | "restart" | "start") => {
found("Restarts the app with pm2", Kind::Servers)
}
"supervisorctl" if first == "restart" => {
found("Restarts the app with Supervisor", Kind::Servers)
}
"nginx" if has("reload") => found("Reloads nginx", Kind::Servers).minor(),
"git" => match first {
"tag" if args.len() > 1 => found("Tags the release", Kind::Releases),
"push" if has("--tags") || has("--follow-tags") => {
found("Pushes the tags", Kind::Releases)
}
"push" => found("Pushes to git", Kind::Releases).minor(),
"pull" => found("Pulls the latest code", Kind::Build).minor(),
"commit" => found("Commits the changes", Kind::Releases).minor(),
_ => return None,
},
"gh" => match (first, second) {
("release", "create") => found("Creates a GitHub release", Kind::Releases).to("GitHub"),
("release", "upload") => {
found("Uploads release files to GitHub", Kind::Releases).to("GitHub")
}
("workflow", "run") => found("Starts a GitHub workflow", Kind::Releases).to("GitHub"),
("pr", "create") => found("Opens a pull request", Kind::Releases).minor(),
_ => return None,
},
"goreleaser" => found(
"Builds and publishes the release with GoReleaser",
Kind::Releases,
),
"zip" | "ditto" => found("Packages an archive", Kind::Releases).minor(),
"tar" if first.starts_with('c') || first.starts_with("-c") => {
found("Packages an archive", Kind::Releases).minor()
}
"cargo" => match first {
"build" if has("--release") || has("-r") => {
found("Builds a Rust release", Kind::Build).minor()
}
"build" => found("Builds the Rust project", Kind::Build).minor(),
"test" | "nextest" => found("Runs the Rust tests", Kind::Build).minor(),
"clippy" => found("Lints the Rust code", Kind::Build).minor(),
"publish" => found("Publishes the crate to crates.io", Kind::Releases).to("crates.io"),
"bundle" | "dist" | "packager" => found("Packages the app", Kind::Releases).minor(),
_ => return None,
},
"npm" | "pnpm" | "yarn" | "bun" => package_script(command, args)?,
"dotnet" => match first {
"publish" => found("Publishes the .NET app", Kind::Build).minor(),
"build" => found("Builds the .NET solution", Kind::Build).minor(),
"test" => found("Runs the .NET tests", Kind::Build).minor(),
"ef" if has("update") => found("Applies the database migrations", Kind::Database),
"nuget" if second == "push" => {
found("Publishes the NuGet package", Kind::Releases).to("NuGet")
}
_ => return None,
},
"go" if first == "build" => found("Builds the Go binary", Kind::Build).minor(),
"go" if first == "test" => found("Runs the Go tests", Kind::Build).minor(),
"make" | "just" | "task" | "mise" => match operand(args) {
Some(target) => found(format!("Runs {command} {target}"), Kind::Build).minor(),
None => found(format!("Runs {command}"), Kind::Build).minor(),
},
"bash" | "sh" | "zsh" | "source" | "." | "python" | "python3" | "node" | "ruby" => {
let file = operand(args)?;
let name = base_name(file);
let script = [".sh", ".bash", ".zsh", ".py", ".js", ".mjs", ".ts", ".rb"]
.iter()
.any(|extension| name.ends_with(extension));
if !script || name.contains('$') {
return None;
}
found(format!("Runs {name}"), Kind::Other).side()
}
"pg_dump" | "mysqldump" | "mongodump" => found("Backs up the database", Kind::Database),
"pg_restore" | "mongorestore" => found("Restores the database", Kind::Database),
"psql" | "mysql" | "sqlite3" => found("Runs SQL against the database", Kind::Database),
"prisma" if first == "migrate" => found("Applies the database migrations", Kind::Database),
"sqlx" | "diesel" | "dbmate" | "flyway" | "goose" | "migrate"
if has("run") || has("up") || has("migrate") || command == "migrate" =>
{
found("Applies the database migrations", Kind::Database)
}
"alembic" if first == "upgrade" => found("Applies the database migrations", Kind::Database),
"liquibase" if first == "update" => {
found("Applies the database migrations", Kind::Database)
}
"rails" | "rake" if first.starts_with("db:migrate") => {
found("Applies the database migrations", Kind::Database)
}
"php" if first == "artisan" && second.starts_with("migrate") => {
found("Applies the database migrations", Kind::Database)
}
"supabase" if first == "db" && second == "push" => {
found("Pushes the database migrations", Kind::Database).to("Supabase")
}
"curl" | "wget"
if lower.contains("hooks.slack.com")
|| lower.contains("webhook")
|| lower.contains("discord.com/api") =>
{
found("Sends a notification", Kind::Other).side()
}
"curl" | "wget"
if lower.contains("health") || lower.contains("/status") || lower.contains("/ping") =>
{
found("Checks that the site responds", Kind::Other).side()
}
"open" if args.iter().any(|arg| arg.contains("http")) => {
found("Opens the site in the browser", Kind::Other).side()
}
_ => return None,
})
}
fn compose(args: &[&str]) -> Option<Found> {
let has = |word: &str| args.contains(&word);
Some(if has("up") {
found("Starts the services with Compose", Kind::Cloud)
} else if has("pull") {
found("Pulls the latest images", Kind::Cloud).minor()
} else if has("build") {
found("Builds the Compose images", Kind::Cloud).minor()
} else if has("down") {
found("Stops the services", Kind::Cloud).minor()
} else {
return None;
})
}
fn package_script(tool: &str, args: &[&str]) -> Option<Found> {
let mut words = args.iter().copied().filter(|arg| !arg.starts_with('-'));
let first = words.next().unwrap_or("");
let second = words.next().unwrap_or("");
let script = match first {
"ci" | "install" | "i" => {
return Some(found("Installs the npm packages", Kind::Build).minor());
}
"publish" => {
return Some(found("Publishes the package to npm", Kind::Releases).to("npm"));
}
"run" | "run-script" => second,
"" => return None,
other if tool != "npm" && !other.starts_with('-') => other,
"test" | "t" => "test",
_ => return None,
};
let name = script.trim_matches(['"', '\'']);
Some(match name {
"build" => found("Builds the web app", Kind::Build).minor(),
name if name.starts_with("build:") => {
found(format!("Builds the {} assets", &name[6..]), Kind::Build).minor()
}
"test" => found("Runs the tests", Kind::Build).minor(),
"lint" | "check" | "typecheck" => found("Checks the code", Kind::Build).minor(),
"" => return None,
name if name.contains("deploy") || name.contains("publish") || name.contains("release") => {
found(format!("Runs the {name} script"), Kind::Web)
}
name => found(format!("Runs the {name} script"), Kind::Build).minor(),
})
}
fn needed_variables(lines: &[String], known: &[String]) -> Vec<String> {
const GIVEN: [&str; 24] = [
"HOME",
"PATH",
"PWD",
"OLDPWD",
"USER",
"SHELL",
"TMPDIR",
"IFS",
"RANDOM",
"SECONDS",
"LINENO",
"HOSTNAME",
"LANG",
"TERM",
"CI",
"BASH_SOURCE",
"BASH_VERSION",
"FUNCNAME",
"PIPESTATUS",
"UID",
"EUID",
"OSTYPE",
"REPLY",
"EDITOR",
];
let mut set = assigned_variables(lines);
set.extend_from_slice(known);
let mut read: Vec<String> = Vec::new();
for line in lines {
let mut rest = line.as_str();
while let Some(at) = rest.find('$') {
rest = &rest[at + 1..];
let (name, has_default) = match rest.strip_prefix('{') {
Some(inner) => {
let end = inner
.find(|ch: char| !(ch.is_ascii_alphanumeric() || ch == '_'))
.unwrap_or(inner.len());
let tail = &inner[end..];
let default = tail.starts_with(":-")
|| tail.starts_with(":=")
|| tail.starts_with('-')
|| tail.starts_with('=');
(&inner[..end], default)
}
None => {
let end = rest
.find(|ch: char| !(ch.is_ascii_alphanumeric() || ch == '_'))
.unwrap_or(rest.len());
(&rest[..end], false)
}
};
let upper = name.len() > 1
&& name
.chars()
.all(|ch| ch.is_ascii_uppercase() || ch.is_ascii_digit() || ch == '_')
&& name.starts_with(|ch: char| ch.is_ascii_uppercase());
if has_default {
set.push(name.to_string());
} else if upper && !read.iter().any(|known| known == name) {
read.push(name.to_string());
}
}
}
read.retain(|name| !set.contains(name) && !GIVEN.contains(&name.as_str()));
read
}
fn assigned_variables(lines: &[String]) -> Vec<String> {
let mut set: Vec<String> = Vec::new();
for line in lines {
for segment in segments(line) {
let mut words: Vec<&str> = segment.split_whitespace().collect();
if words
.first()
.is_some_and(|word| matches!(*word, "while" | "until" | "if" | "!"))
{
words.remove(0);
}
let mut index = 0;
while let Some(word) = words.get(index) {
if matches!(
*word,
"export" | "local" | "declare" | "readonly" | "-r" | "-x" | "-a"
) {
index += 1;
continue;
}
if let Some((name, _)) = word.split_once('=')
&& is_variable_name(name)
{
set.push(name.to_string());
}
break;
}
if let Some(first) = words.first()
&& matches!(*first, "read" | "for" | "select")
{
set.extend(
words[1..]
.iter()
.filter(|word| is_variable_name(word))
.map(|word| word.to_string()),
);
}
}
}
set
}
fn is_variable_name(name: &str) -> bool {
!name.is_empty()
&& name.starts_with(|ch: char| ch.is_ascii_alphabetic() || ch == '_')
&& name
.chars()
.all(|ch| ch.is_ascii_alphanumeric() || ch == '_')
}
#[cfg(test)]
mod tests {
use super::*;
fn read(name: &str, text: &str) -> DeployScript {
read_script(
PathBuf::from(format!("/repo/.deploy/{name}")),
name,
text,
&Shared::default(),
)
}
#[test]
fn a_fly_deploy_is_cloud_with_its_steps_and_needs() {
let script = read(
"deploy-api-prod.sh",
"#!/usr/bin/env bash\nset -euo pipefail\n\
IMAGE=registry.fly.io/api:$(git rev-parse --short HEAD)\n\
docker build -t \"$IMAGE\" . && docker push \"$IMAGE\"\n\
flyctl deploy --image \"$IMAGE\" --app \"$FLY_APP\" \\\n --strategy rolling\n\
curl -fsS https://api.example.com/health\n",
);
assert_eq!(script.title, "Deploy API");
assert_eq!(script.env, Some(Env::Production));
assert_eq!(script.kind, Kind::Cloud);
assert_eq!(script.target.as_deref(), Some("Fly.io"));
assert_eq!(
script.steps,
[
"Builds a Docker image",
"Pushes the image to the registry",
"Deploys to Fly.io",
"Checks that the site responds",
]
);
assert_eq!(script.needs, ["FLY_APP"]);
if cfg!(windows) {
assert!(
script
.command
.ends_with("bash.exe' .deploy/deploy-api-prod.sh"),
"{}",
script.command
);
} else {
assert_eq!(script.command, "bash .deploy/deploy-api-prod.sh");
}
}
#[test]
fn the_header_comment_names_and_describes_the_script() {
let script = read(
"site.sh",
"#!/bin/sh\n# Title: Marketing site\n# Group: Websites\n#\n\
# builds the static site and uploads it\n# to the bucket behind the CDN\n\n\
npm ci\nnpm run build\naws s3 sync dist s3://$BUCKET --delete\n\
aws cloudfront create-invalidation --distribution-id \"${DIST:?}\" --paths '/*'\n",
);
assert_eq!(script.title, "Marketing site");
assert_eq!(script.group, "Websites");
assert_eq!(script.kind, Kind::Web);
assert_eq!(
script.about.as_deref(),
Some("Builds the static site and uploads it to the bucket behind the CDN.")
);
assert_eq!(script.target.as_deref(), Some("S3"));
assert_eq!(script.needs, ["BUCKET", "DIST"]);
}
#[test]
fn servers_are_named_by_host_and_prompts_are_noticed() {
let script = read(
"backend_staging.sh",
"read -p \"Deploy? [y/N] \" answer\n\
rsync -az --delete ./build/ deploy@staging.example.com:/srv/app/\n\
ssh -i ~/.ssh/id deploy@staging.example.com 'sudo systemctl restart app'\n",
);
assert_eq!(script.title, "Backend");
assert_eq!(script.env, Some(Env::Staging));
assert_eq!(script.kind, Kind::Servers);
assert_eq!(script.target.as_deref(), Some("staging.example.com"));
assert!(script.asks);
assert_eq!(
script.steps,
[
"Copies the files to staging.example.com",
"Runs commands on staging.example.com",
"Restarts the app service",
]
);
}
#[test]
fn an_app_release_goes_under_apps() {
let script = read(
"release-macOS.sh",
"cargo build --release\ncodesign --deep -s \"$IDENTITY\" Edit.app\n\
create-dmg Edit.dmg Edit.app\nxcrun notarytool submit Edit.dmg --wait\n\
xcrun stapler staple Edit.dmg\ngh release create \"v$VERSION\" Edit.dmg\n",
);
assert_eq!(script.title, "Release macOS");
assert_eq!(script.kind, Kind::Apps);
assert_eq!(script.target.as_deref(), Some("GitHub"));
assert_eq!(script.steps.len(), 6);
}
#[test]
fn progress_lines_stand_in_for_unknown_commands() {
let script = read(
"02_sync-assets.sh",
"echo \"==> Collecting assets\"\n./tools/collect\necho '==> Uploading…'\n",
);
assert_eq!(script.title, "Sync Assets");
assert_eq!(script.steps, ["Collecting assets", "Uploading"]);
assert_eq!(script.kind, Kind::Other);
}
#[test]
fn shared_helpers_and_subfolders() {
let root = std::env::temp_dir().join(format!("edit-deploy-{}", std::process::id()));
let dir = root.join("web").join(DEPLOY_DIR);
fs::create_dir_all(&dir).unwrap();
fs::create_dir_all(root.join("node_modules/x").join(DEPLOY_DIR)).unwrap();
fs::write(dir.join("config.sh"), "HOST=example.com\n").unwrap();
fs::write(
dir.join("deploy.sh"),
"source \"$(dirname \"$0\")/config.sh\"\nrsync -az dist/ \"$HOST:/srv\"\n",
)
.unwrap();
assert_eq!(find_bases(&root, None), [root.join("web")]);
let names: Vec<String> = scan(&root.join("web"))
.into_iter()
.map(|script| script.file)
.collect();
assert_eq!(names, [".deploy/deploy.sh"]);
fs::remove_dir_all(&root).unwrap();
}
#[test]
fn groups_keep_kind_order() {
let scripts = [
read("db-backup.sh", "pg_dump \"$DATABASE_URL\" > dump.sql\n"),
read("web.sh", "vercel --prod\n"),
read("web-preview.sh", "vercel\n"),
];
let mut scripts = scripts.to_vec();
scripts.sort_by(|a, b| (a.kind, &a.title).cmp(&(b.kind, &b.title)));
let groups = grouped(&scripts);
let names: Vec<&str> = groups.iter().map(|(name, ..)| name.as_str()).collect();
assert_eq!(names, ["Web & Hosting", "Database"]);
assert_eq!(groups[0].2.len(), 2);
}
}