plzplz 0.0.11

A simple cross-platform task runner with helpful defaults
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
use anyhow::{Context, Result, bail};
use schemars::{JsonSchema, SchemaGenerator, json_schema};
use serde::Deserialize;
use serde::de::{self, Deserializer, Visitor};
use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt;
use std::path::Path;
use toml_edit::DocumentMut;

pub const VALID_GIT_HOOKS: &[&str] = &[
    "applypatch-msg",
    "pre-applypatch",
    "post-applypatch",
    "pre-commit",
    "prepare-commit-msg",
    "commit-msg",
    "post-commit",
    "pre-rebase",
    "post-checkout",
    "post-merge",
    "pre-push",
    "pre-receive",
    "update",
    "post-receive",
    "post-update",
    "push-to-checkout",
    "pre-auto-gc",
    "post-rewrite",
    "sendemail-validate",
];

#[derive(Debug, Default, Clone, Deserialize, JsonSchema)]
pub struct GlobalSettings {
    /// Tool environment wrapper applied to all tasks: "pnpm", "npm", "uv", or "uvx"
    #[serde(default, rename = "env")]
    #[schemars(rename = "env")]
    pub tool_env: Option<String>,
    /// Default working directory (relative to plz.toml) for all tasks
    #[serde(default)]
    pub dir: Option<String>,
}

#[derive(Debug)]
pub struct TaskGroup {
    pub extends: Option<GlobalSettings>,
    pub tasks: HashMap<String, Task>,
}

impl<'de> Deserialize<'de> for TaskGroup {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct TaskGroupVisitor;

        impl<'de> Visitor<'de> for TaskGroupVisitor {
            type Value = TaskGroup;

            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.write_str("a task group table with optional 'extends' and task entries")
            }

            fn visit_map<M>(self, mut map: M) -> std::result::Result<TaskGroup, M::Error>
            where
                M: de::MapAccess<'de>,
            {
                let mut extends = None;
                let mut tasks = HashMap::new();

                while let Some(key) = map.next_key::<String>()? {
                    if key == "extends" {
                        extends = Some(map.next_value::<GlobalSettings>()?);
                    } else {
                        tasks.insert(key, map.next_value::<Task>()?);
                    }
                }

                Ok(TaskGroup { extends, tasks })
            }
        }

        deserializer.deserialize_map(TaskGroupVisitor)
    }
}

impl JsonSchema for TaskGroup {
    fn schema_name() -> Cow<'static, str> {
        Cow::Borrowed("TaskGroup")
    }

    fn json_schema(generator: &mut SchemaGenerator) -> schemars::Schema {
        json_schema!({
            "type": "object",
            "description": "A group of related tasks with optional shared defaults",
            "properties": {
                "extends": generator.subschema_for::<GlobalSettings>()
            },
            "additionalProperties": generator.subschema_for::<Task>()
        })
    }
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct PlzConfig {
    /// Global defaults that apply to all tasks (can be overridden per-task)
    #[serde(default)]
    pub extends: Option<GlobalSettings>,
    /// Task groups for namespacing related tasks (e.g. [taskgroup.rust.test])
    #[serde(default)]
    pub taskgroup: Option<HashMap<String, TaskGroup>>,
    /// Tasks to run, keyed by name (e.g. [tasks.build]). Run with `plz <name>`.
    #[serde(default)]
    pub tasks: HashMap<String, Task>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct Task {
    /// A single shell command to run
    #[serde(default)]
    pub run: Option<String>,
    /// Multiple commands to run one after another (stops on first failure)
    #[serde(default)]
    pub run_serial: Option<Vec<String>>,
    /// Multiple commands to run concurrently
    #[serde(default)]
    pub run_parallel: Option<Vec<String>>,
    /// Tool environment wrapper: "pnpm" (uses `pnpm exec`), "npm" (uses `npx`), "uv" (uses `uv run`), or "uvx" (uses `uvx`)
    #[serde(default, rename = "env")]
    #[schemars(rename = "env")]
    pub tool_env: Option<String>,
    /// Working directory (relative to plz.toml)
    #[serde(default)]
    pub dir: Option<String>,
    /// Action to take when the task fails: a command string, { suggest_command = "..." }, or { message = "..." }
    #[serde(default)]
    pub fail_hook: Option<FailHook>,
    /// Description shown in `plz list`
    #[serde(default)]
    pub description: Option<String>,
    /// Git hook stage to associate this task with (e.g. "pre-commit", "pre-push")
    #[serde(default)]
    pub git_hook: Option<String>,
}

#[derive(Debug)]
pub enum FailHook {
    Command(String),
    Suggest { suggest_command: String },
    Message(String),
}

impl JsonSchema for FailHook {
    fn inline_schema() -> bool {
        true
    }

    fn schema_name() -> Cow<'static, str> {
        Cow::Borrowed("FailHook")
    }

    fn json_schema(_: &mut SchemaGenerator) -> schemars::Schema {
        json_schema!({
            "oneOf": [
                {
                    "type": "string",
                    "description": "Shell command to run on failure"
                },
                {
                    "type": "object",
                    "properties": {
                        "suggest_command": {
                            "type": "string",
                            "description": "Command to suggest to the user on failure"
                        }
                    },
                    "required": ["suggest_command"],
                    "additionalProperties": false
                },
                {
                    "type": "object",
                    "properties": {
                        "message": {
                            "type": "string",
                            "description": "Message to display on failure"
                        }
                    },
                    "required": ["message"],
                    "additionalProperties": false
                }
            ]
        })
    }
}

impl<'de> Deserialize<'de> for FailHook {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct FailHookVisitor;

        impl<'de> Visitor<'de> for FailHookVisitor {
            type Value = FailHook;

            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.write_str("a string or a map with suggest_command")
            }

            fn visit_str<E: de::Error>(self, v: &str) -> std::result::Result<FailHook, E> {
                Ok(FailHook::Command(v.to_string()))
            }

            fn visit_map<M>(self, mut map: M) -> std::result::Result<FailHook, M::Error>
            where
                M: de::MapAccess<'de>,
            {
                let mut suggest_command = None;
                let mut message = None;
                while let Some(key) = map.next_key::<String>()? {
                    match key.as_str() {
                        "suggest_command" => suggest_command = Some(map.next_value::<String>()?),
                        "message" => message = Some(map.next_value::<String>()?),
                        _ => {
                            let _ = map.next_value::<de::IgnoredAny>()?;
                        }
                    }
                }
                if let Some(cmd) = suggest_command {
                    Ok(FailHook::Suggest {
                        suggest_command: cmd,
                    })
                } else if let Some(msg) = message {
                    Ok(FailHook::Message(msg))
                } else {
                    Err(de::Error::missing_field("suggest_command or message"))
                }
            }
        }

        deserializer.deserialize_any(FailHookVisitor)
    }
}

pub fn load(path: &Path) -> Result<PlzConfig> {
    let content = std::fs::read_to_string(path)
        .with_context(|| format!("Failed to read {}", path.display()))?;

    let doc: DocumentMut = content
        .parse()
        .with_context(|| "Failed to parse plz.toml")?;

    let mut config: PlzConfig = toml_edit::de::from_document(doc.clone())
        .with_context(|| "Failed to deserialize config")?;

    // Extract comments above [tasks.*] as descriptions (fallback when no explicit description)
    if let Some(tasks_table) = doc.get("tasks").and_then(|v| v.as_table()) {
        for (key, item) in tasks_table.iter() {
            if let Some(task) = config.tasks.get_mut(key)
                && task.description.is_none()
                && let Some(decor) = item.as_table().map(|t| t.decor())
                && let Some(prefix) = decor.prefix().and_then(|p| p.as_str())
            {
                task.description = extract_comment(prefix);
            }
        }
    }

    // Apply global defaults from [extends] to tasks.
    // Empty string means "explicitly no value" (opt out of extends).
    if let Some(ref extends) = config.extends {
        for task in config.tasks.values_mut() {
            if task.tool_env.is_none() {
                task.tool_env.clone_from(&extends.tool_env);
            }
            if task.dir.is_none() {
                task.dir.clone_from(&extends.dir);
            }
        }
    }
    for task in config.tasks.values_mut() {
        if task.tool_env.as_deref() == Some("") {
            task.tool_env = None;
        }
        if task.dir.as_deref() == Some("") {
            task.dir = None;
        }
    }

    if config.tasks.contains_key("plz") {
        bail!("\"plz\" is a reserved name and cannot be used as a task name.");
    }

    // Validate git_hook values
    for (name, task) in &config.tasks {
        if let Some(ref hook) = task.git_hook {
            if !VALID_GIT_HOOKS.contains(&hook.as_str()) {
                bail!(
                    "Task \"{name}\" has invalid git_hook \"{hook}\". Valid hooks: {}",
                    VALID_GIT_HOOKS.join(", ")
                );
            }
        }
    }

    // Apply extends cascade to taskgroup tasks:
    // top-level [extends] → [taskgroup.X.extends] → per-task values
    if let Some(ref mut groups) = config.taskgroup {
        for (group_name, group) in groups.iter_mut() {
            // Compute effective extends: top-level, then group overrides
            let effective_env = group
                .extends
                .as_ref()
                .and_then(|e| e.tool_env.clone())
                .or_else(|| config.extends.as_ref().and_then(|e| e.tool_env.clone()));
            let effective_dir = group
                .extends
                .as_ref()
                .and_then(|e| e.dir.clone())
                .or_else(|| config.extends.as_ref().and_then(|e| e.dir.clone()));

            for task in group.tasks.values_mut() {
                if task.tool_env.is_none() {
                    task.tool_env.clone_from(&effective_env);
                }
                if task.dir.is_none() {
                    task.dir.clone_from(&effective_dir);
                }
            }

            // Clear empty-string opt-outs
            for task in group.tasks.values_mut() {
                if task.tool_env.as_deref() == Some("") {
                    task.tool_env = None;
                }
                if task.dir.as_deref() == Some("") {
                    task.dir = None;
                }
            }

            // Validate git_hook values in group tasks
            for (task_name, task) in &group.tasks {
                if let Some(ref hook) = task.git_hook {
                    if !VALID_GIT_HOOKS.contains(&hook.as_str()) {
                        bail!(
                            "Task \"{group_name}:{task_name}\" has invalid git_hook \"{hook}\". Valid hooks: {}",
                            VALID_GIT_HOOKS.join(", ")
                        );
                    }
                }
            }

            // Extract comments from taskgroup tables
            if let Some(group_table) = doc
                .get("taskgroup")
                .and_then(|v| v.as_table())
                .and_then(|t| t.get(group_name.as_str()))
                .and_then(|v| v.as_table())
            {
                for (key, item) in group_table.iter() {
                    if key == "extends" {
                        continue;
                    }
                    if let Some(task) = group.tasks.get_mut(key)
                        && task.description.is_none()
                        && let Some(decor) = item.as_table().map(|t| t.decor())
                        && let Some(prefix) = decor.prefix().and_then(|p| p.as_str())
                    {
                        task.description = extract_comment(prefix);
                    }
                }
            }
        }
    }

    Ok(config)
}

impl PlzConfig {
    pub fn get_group(&self, name: &str) -> Option<&TaskGroup> {
        self.taskgroup.as_ref()?.get(name)
    }

    pub fn get_group_task(&self, group: &str, task: &str) -> Option<&Task> {
        self.get_group(group)?.tasks.get(task)
    }
}

pub fn extract_comment(prefix: &str) -> Option<String> {
    let lines: Vec<&str> = prefix
        .lines()
        .filter_map(|line| {
            let trimmed = line.trim();
            if trimmed.starts_with('#') {
                Some(trimmed.trim_start_matches('#').trim())
            } else {
                None
            }
        })
        .collect();

    if lines.is_empty() {
        None
    } else {
        Some(lines.join(" "))
    }
}