fledge 1.0.0

Dev lifecycle CLI. One tool for the dev loop, any language.
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
use anyhow::{bail, Context, Result};
use console::style;
use serde::Deserialize;
use std::collections::{BTreeMap, HashSet};
use std::path::PathBuf;

use crate::trust::determine_trust_tier;

mod community;
mod create;
mod defaults;
mod execute;
mod publish;
mod validate;

#[cfg(test)]
mod tests;

#[cfg(test)]
use community::{base64_decode, parse_import_source};
#[cfg(test)]
use create::create_lane_repo;
#[cfg(test)]
use defaults::lane_defaults;
#[cfg(test)]
use execute::execute_lane;
#[cfg(test)]
use validate::validate_lanes;

/// Per-command JSON schema versions. Each constant tracks the wire shape of one
/// `lanes` subcommand's `--json` envelope independently so that future shape
/// changes can bump exactly the affected envelope without semantically
/// corrupting the meaning of `schema_version` for unrelated commands. Additive
/// changes (new optional fields) do not bump.
pub(super) const LANES_LIST_SCHEMA: u32 = 1;
pub(super) const LANES_DRY_RUN_SCHEMA: u32 = 1;
pub(super) const LANES_RUN_SCHEMA: u32 = 1;
pub(super) const LANES_INIT_SCHEMA: u32 = 1;
pub(super) const LANES_SEARCH_SCHEMA: u32 = 1;
pub(super) const LANES_IMPORT_SCHEMA: u32 = 1;
pub(super) const LANES_CREATE_SCHEMA: u32 = 1;
pub(super) const LANES_PUBLISH_SCHEMA: u32 = 1;

#[derive(Debug, Deserialize)]
pub(super) struct FledgeFileWithLanes {
    #[serde(default)]
    pub(super) tasks: BTreeMap<String, TaskDef>,
    #[serde(default)]
    pub(super) lanes: BTreeMap<String, LaneDef>,
}

#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub(super) enum TaskDef {
    Short(String),
    Full(TaskConfig),
}

#[derive(Debug, Deserialize)]
pub(super) struct TaskConfig {
    pub(super) cmd: String,
    #[serde(default)]
    pub(super) deps: Vec<String>,
    #[serde(default)]
    pub(super) env: BTreeMap<String, String>,
    #[serde(default)]
    pub(super) dir: Option<String>,
}

impl TaskDef {
    pub(super) fn cmd(&self) -> &str {
        match self {
            TaskDef::Short(s) => s,
            TaskDef::Full(c) => &c.cmd,
        }
    }

    pub(super) fn deps(&self) -> &[String] {
        match self {
            TaskDef::Short(_) => &[],
            TaskDef::Full(c) => &c.deps,
        }
    }

    pub(super) fn env(&self) -> &BTreeMap<String, String> {
        static EMPTY: BTreeMap<String, String> = BTreeMap::new();
        match self {
            TaskDef::Short(_) => &EMPTY,
            TaskDef::Full(c) => &c.env,
        }
    }

    pub(super) fn dir(&self) -> Option<&str> {
        match self {
            TaskDef::Short(_) => None,
            TaskDef::Full(c) => c.dir.as_deref(),
        }
    }
}

#[derive(Debug, Deserialize)]
pub struct LaneDef {
    #[serde(default)]
    pub(super) description: Option<String>,
    pub(super) steps: Vec<Step>,
    #[serde(default = "default_true")]
    pub(super) fail_fast: bool,
    #[serde(skip, default)]
    pub(super) source: Option<String>,
}

pub(super) fn default_true() -> bool {
    true
}

#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub(super) enum Step {
    TaskRef(String),
    Inline { run: String },
    Parallel { parallel: Vec<ParallelItem> },
}

#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub(super) enum ParallelItem {
    TaskRef(String),
    Inline { run: String },
}

pub enum LaneAction {
    Run {
        name: String,
        dry_run: bool,
        json: bool,
    },
    List {
        json: bool,
    },
    Init {
        json: bool,
    },
    Search {
        query: Option<String>,
        author: Option<String>,
        json: bool,
    },
    Import {
        source: String,
        yes: bool,
        json: bool,
    },
    Publish {
        path: PathBuf,
        org: Option<String>,
        private: bool,
        description: Option<String>,
        yes: bool,
        json: bool,
    },
    Create {
        name: String,
        output: PathBuf,
        description: Option<String>,
        yes: bool,
        json: bool,
    },
    Validate {
        path: PathBuf,
        strict: bool,
        json: bool,
    },
}

pub fn run(action: LaneAction) -> Result<()> {
    match action {
        LaneAction::Search {
            query,
            author,
            json,
        } => community::search_lanes(query.as_deref(), author.as_deref(), json),
        LaneAction::Import { source, yes, json } => community::import_lanes(&source, yes, json),
        LaneAction::Init { json } => defaults::init_lanes(json),
        LaneAction::Publish {
            path,
            org,
            private,
            description,
            yes,
            json,
        } => publish::publish_lanes(
            &path,
            org.as_deref(),
            private,
            description.as_deref(),
            yes,
            json,
        ),
        LaneAction::Create {
            name,
            output,
            description,
            yes,
            json,
        } => create::create_lane_repo(&name, &output, description.as_deref(), yes, json),
        LaneAction::Validate { path, strict, json } => {
            validate::validate_lanes(&path, strict, json)
        }
        LaneAction::List { json } => {
            let config = load_lane_config()?;
            list_lanes(&config.lanes, json)
        }
        LaneAction::Run {
            name,
            dry_run,
            json,
        } => {
            let config = load_lane_config()?;
            let lane = config.lanes.get(&name).ok_or_else(|| {
                let available: Vec<&str> = config.lanes.keys().map(|s| s.as_str()).collect();
                anyhow::anyhow!(
                    "Unknown lane '{}'. Available lanes: {}",
                    name,
                    available.join(", ")
                )
            })?;

            if lane.steps.is_empty() {
                bail!("Lane '{}' has no steps defined", name);
            }

            validate_lane(&name, lane, &config.tasks)?;

            if dry_run {
                dry_run_lane(&name, lane, json)
            } else {
                let project_dir = std::env::current_dir().context("getting current directory")?;
                execute::execute_lane(&name, lane, &config.tasks, &project_dir, json)
            }
        }
    }
}

/// Run a lane as a pre-release gate without emitting anything to stdout.
/// The release command's own JSON envelope is the only thing the agent
/// consumer parses; the lane runs silently and bails on failure.
pub fn run_for_pre_release(name: &str, dry_run: bool) -> Result<()> {
    let config = load_lane_config()?;
    let lane = config.lanes.get(name).ok_or_else(|| {
        let available: Vec<&str> = config.lanes.keys().map(|s| s.as_str()).collect();
        anyhow::anyhow!(
            "Unknown lane '{}'. Available lanes: {}",
            name,
            available.join(", ")
        )
    })?;

    if lane.steps.is_empty() {
        bail!("Lane '{}' has no steps defined", name);
    }

    validate_lane(name, lane, &config.tasks)?;

    if dry_run {
        return Ok(());
    }

    let project_dir = std::env::current_dir().context("getting current directory")?;
    execute::execute_lane_silent(name, lane, &config.tasks, &project_dir)
}

pub(super) fn load_lane_config() -> Result<FledgeFileWithLanes> {
    let project_dir = std::env::current_dir().context("getting current directory")?;
    let config_path = project_dir.join("fledge.toml");

    if !config_path.exists() {
        bail!(
            "No fledge.toml found in current directory.\n  Run {} to create one.",
            style("fledge run --init").cyan()
        );
    }

    let content = std::fs::read_to_string(&config_path).context("reading fledge.toml")?;
    let mut config: FledgeFileWithLanes = toml::from_str(&content).map_err(|e| {
        let msg = e.to_string();
        if msg.contains("lanes") || msg.contains("steps") {
            anyhow::anyhow!(
                "Error parsing lanes in fledge.toml: {e}\n\n  \
                 Lanes must use table syntax:\n    \
                 [lanes.ci]\n    \
                 steps = [\"lint\", \"test\", \"build\"]\n\n  \
                 Not shorthand like: ci = [\"lint\", \"test\"]"
            )
        } else {
            anyhow::anyhow!("parsing fledge.toml: {e}")
        }
    })?;

    let lanes_dir = project_dir.join(".fledge").join("lanes");
    if lanes_dir.is_dir() {
        if let Ok(entries) = std::fs::read_dir(&lanes_dir) {
            for entry in entries.flatten() {
                let path = entry.path();
                if path.extension().is_some_and(|e| e == "toml") {
                    let imported_content = std::fs::read_to_string(&path)
                        .with_context(|| format!("reading {}", path.display()))?;
                    let imported: FledgeFileWithLanes = toml::from_str(&imported_content)
                        .with_context(|| format!("parsing {}", path.display()))?;
                    let import_source = imported_content
                        .lines()
                        .find(|l| l.starts_with("# Imported from "))
                        .map(|l| l.trim_start_matches("# Imported from ").trim().to_string());
                    for (name, task) in imported.tasks {
                        config.tasks.entry(name).or_insert(task);
                    }
                    for (name, mut lane) in imported.lanes {
                        lane.source = import_source.clone();
                        config.lanes.entry(name).or_insert(lane);
                    }
                }
            }
        }
    }

    if config.lanes.is_empty() {
        bail!(
            "No lanes defined.\n  Add lanes to fledge.toml, import with {}, or run {} to add defaults.",
            style("fledge lanes import <source>").cyan(),
            style("fledge lanes init").cyan()
        );
    }

    Ok(config)
}

pub(super) fn list_lanes(lanes: &BTreeMap<String, LaneDef>, json: bool) -> Result<()> {
    if json {
        let entries: Vec<serde_json::Value> = lanes
            .iter()
            .map(|(name, lane)| {
                let mut entry = serde_json::json!({
                    "name": name,
                    "description": lane.description,
                    "step_count": lane.steps.len(),
                    "fail_fast": lane.fail_fast,
                });
                if let Some(ref src) = lane.source {
                    let tier = determine_trust_tier(src);
                    entry["source"] = serde_json::json!(src);
                    entry["trust_tier"] = serde_json::json!(tier.label());
                } else {
                    entry["trust_tier"] = serde_json::json!("local");
                }
                entry
            })
            .collect();
        let result = serde_json::json!({
            "schema_version": LANES_LIST_SCHEMA,
            "lanes": entries,
        });
        println!("{}", serde_json::to_string_pretty(&result)?);
        return Ok(());
    }

    println!("{}", style("Available lanes:").bold());
    let max_name_len = lanes.keys().map(|k| k.len()).max().unwrap_or(0);
    for (name, lane) in lanes {
        let desc = lane.description.as_deref().unwrap_or("(no description)");
        let tier_label = match &lane.source {
            Some(src) => {
                let tier = determine_trust_tier(src);
                format!(" [{}]", tier.styled_label())
            }
            None => String::new(),
        };
        println!(
            "  {:<width$}  {}{}",
            style(name).green(),
            style(desc).dim(),
            tier_label,
            width = max_name_len
        );
    }
    Ok(())
}

pub(super) fn validate_lane(
    lane_name: &str,
    lane: &LaneDef,
    tasks: &BTreeMap<String, TaskDef>,
) -> Result<()> {
    for (i, step) in lane.steps.iter().enumerate() {
        match step {
            Step::TaskRef(name) => {
                if !tasks.contains_key(name) {
                    bail!(
                        "Lane '{}' step {} references unknown task '{}'.\n  Define it in [tasks] first.",
                        lane_name,
                        i + 1,
                        name
                    );
                }
                check_dep_cycle(name, tasks, &mut HashSet::new())
                    .map_err(|e| anyhow::anyhow!("Lane '{}' step {}: {}", lane_name, i + 1, e))?;
            }
            Step::Inline { .. } => {}
            Step::Parallel { parallel } => {
                for item in parallel {
                    if let ParallelItem::TaskRef(name) = item {
                        if !tasks.contains_key(name) {
                            bail!(
                                "Lane '{}' step {} parallel group references unknown task '{}'.\n  Define it in [tasks] first.",
                                lane_name,
                                i + 1,
                                name
                            );
                        }
                        check_dep_cycle(name, tasks, &mut HashSet::new()).map_err(|e| {
                            anyhow::anyhow!("Lane '{}' step {}: {}", lane_name, i + 1, e)
                        })?;
                    }
                }
            }
        }
    }
    Ok(())
}

pub(super) fn check_dep_cycle(
    name: &str,
    tasks: &BTreeMap<String, TaskDef>,
    visiting: &mut HashSet<String>,
) -> Result<()> {
    if !visiting.insert(name.to_string()) {
        bail!("circular dependency detected involving task '{}'", name);
    }
    if let Some(task) = tasks.get(name) {
        for dep in task.deps() {
            check_dep_cycle(dep, tasks, visiting)?;
        }
    }
    visiting.remove(name);
    Ok(())
}

pub(super) fn dry_run_lane(lane_name: &str, lane: &LaneDef, json: bool) -> Result<()> {
    let desc = lane.description.as_deref().unwrap_or("(no description)");

    if json {
        let steps: Vec<serde_json::Value> = lane
            .steps
            .iter()
            .enumerate()
            .map(|(i, step)| match step {
                Step::TaskRef(name) => serde_json::json!({
                    "step": i + 1,
                    "kind": "task",
                    "name": name,
                }),
                Step::Inline { run: cmd } => serde_json::json!({
                    "step": i + 1,
                    "kind": "inline",
                    "name": cmd,
                }),
                Step::Parallel { parallel } => {
                    let items: Vec<serde_json::Value> = parallel
                        .iter()
                        .map(|item| match item {
                            ParallelItem::TaskRef(name) => serde_json::json!({
                                "kind": "task",
                                "name": name,
                            }),
                            ParallelItem::Inline { run: cmd } => serde_json::json!({
                                "kind": "inline",
                                "name": cmd,
                            }),
                        })
                        .collect();
                    serde_json::json!({
                        "step": i + 1,
                        "kind": "parallel",
                        "items": items,
                    })
                }
            })
            .collect();

        let output = serde_json::json!({
            "schema_version": LANES_DRY_RUN_SCHEMA,
            "lane": lane_name,
            "description": lane.description.as_deref().unwrap_or(""),
            "total_steps": lane.steps.len(),
            "fail_fast": lane.fail_fast,
            "dry_run": true,
            "steps": steps,
        });
        println!("{}", serde_json::to_string_pretty(&output)?);
        return Ok(());
    }

    println!(
        "{} {} — {}",
        style("Lane:").bold(),
        style(lane_name).green(),
        style(desc).dim()
    );
    if !lane.fail_fast {
        println!("  {} fail_fast = false", style("âš™").dim());
    }
    for (i, step) in lane.steps.iter().enumerate() {
        match step {
            Step::TaskRef(name) => {
                println!(
                    "  {}. {} {}",
                    i + 1,
                    style(name).cyan(),
                    style("(task)").dim()
                );
            }
            Step::Inline { run: cmd } => {
                println!(
                    "  {}. {} {}",
                    i + 1,
                    style(cmd).cyan(),
                    style("(inline)").dim()
                );
            }
            Step::Parallel { parallel } => {
                let names: Vec<String> = parallel
                    .iter()
                    .map(|item| match item {
                        ParallelItem::TaskRef(name) => name.clone(),
                        ParallelItem::Inline { run: cmd } => format!("run: {cmd}"),
                    })
                    .collect();
                println!(
                    "  {}. {} {}",
                    i + 1,
                    style(names.join(", ")).cyan(),
                    style("(parallel)").dim()
                );
            }
        }
    }
    Ok(())
}

pub(super) fn step_description(step: &Step) -> String {
    match step {
        Step::TaskRef(name) => name.clone(),
        Step::Inline { run: cmd } => cmd.clone(),
        Step::Parallel { parallel } => {
            let names: Vec<String> = parallel
                .iter()
                .map(|item| match item {
                    ParallelItem::TaskRef(name) => name.clone(),
                    ParallelItem::Inline { run: cmd } => cmd.clone(),
                })
                .collect();
            format!("parallel({})", names.join(", "))
        }
    }
}

pub(super) fn format_duration(d: std::time::Duration) -> String {
    let secs = d.as_secs();
    let millis = d.subsec_millis();
    if secs >= 60 {
        let mins = secs / 60;
        let remaining = secs % 60;
        format!("{mins}m {remaining}.{millis:03}s")
    } else if secs > 0 {
        format!("{secs}.{millis:03}s")
    } else {
        format!("{millis}ms")
    }
}

pub(super) fn escape_toml_value(s: &str) -> String {
    s.replace('\\', "\\\\").replace('"', "\\\"")
}

pub(super) fn format_lane_toml(name: &str, lane: &LaneDef) -> String {
    let mut out = format!("\n[lanes.{}]\n", name);
    if let Some(ref desc) = lane.description {
        out.push_str(&format!("description = \"{}\"\n", escape_toml_value(desc)));
    }
    if !lane.fail_fast {
        out.push_str("fail_fast = false\n");
    }
    out.push_str("steps = [");
    for (i, step) in lane.steps.iter().enumerate() {
        if i > 0 {
            out.push_str(", ");
        }
        match step {
            Step::TaskRef(name) => {
                out.push_str(&format!("\"{}\"", escape_toml_value(name)));
            }
            Step::Inline { run: cmd } => {
                out.push_str(&format!("{{ run = \"{}\" }}", escape_toml_value(cmd)));
            }
            Step::Parallel { parallel } => {
                let items: Vec<String> = parallel
                    .iter()
                    .map(|item| match item {
                        ParallelItem::TaskRef(name) => {
                            format!("\"{}\"", escape_toml_value(name))
                        }
                        ParallelItem::Inline { run: cmd } => {
                            format!("{{ run = \"{}\" }}", escape_toml_value(cmd))
                        }
                    })
                    .collect();
                out.push_str(&format!("{{ parallel = [{}] }}", items.join(", ")));
            }
        }
    }
    out.push_str("]\n");
    out
}