Skip to main content

orch/config/
projects_yaml.rs

1//! Edit the `projects:` list in `config.yml` as text so comments stay
2
3use anyhow::Context;
4
5/// Result of a comment-preserving `projects:` edit
6#[derive(Debug, Clone, PartialEq, Eq)]
7pub enum ProjectsEdit {
8    /// Path already present on add, or missing on remove
9    Unchanged,
10    /// New document text
11    Updated(String),
12}
13
14/// Insert `path` into the root `projects:` list
15pub fn add_project(content: &str, path: &str) -> anyhow::Result<ProjectsEdit> {
16    match parsed_string_projects(content)? {
17        ParsedProjects::NotAList => anyhow::bail!("projects is not a list"),
18        ParsedProjects::List(items) if items.iter().any(|p| p == path) => {
19            Ok(ProjectsEdit::Unchanged)
20        }
21        ParsedProjects::Missing | ParsedProjects::List(_) => insert_project(content, path),
22    }
23}
24
25/// Remove list entries whose value equals any of `candidates`
26pub fn remove_project(content: &str, candidates: &[&str]) -> anyhow::Result<ProjectsEdit> {
27    match parsed_string_projects(content)? {
28        ParsedProjects::Missing | ParsedProjects::NotAList => {
29            anyhow::bail!("no projects list in config")
30        }
31
32        ParsedProjects::List(items) => {
33            if !items.iter().any(|p| candidates.contains(&p.as_str())) {
34                return Ok(ProjectsEdit::Unchanged);
35            }
36            delete_project(content, candidates)
37        }
38    }
39}
40
41enum ParsedProjects {
42    Missing,
43    NotAList,
44    List(Vec<String>),
45}
46
47fn parsed_string_projects(content: &str) -> anyhow::Result<ParsedProjects> {
48    if content.trim().is_empty() {
49        return Ok(ParsedProjects::Missing);
50    }
51    let doc: serde_norway::Value = serde_norway::from_str(content).context("parsing config.yml")?;
52    let Some(root) = doc.as_mapping() else {
53        anyhow::bail!("config is not a YAML mapping");
54    };
55    match root.get("projects") {
56        None | Some(serde_norway::Value::Null) => Ok(ParsedProjects::Missing),
57        Some(serde_norway::Value::Sequence(seq)) => Ok(ParsedProjects::List(
58            seq.iter()
59                .filter_map(|item| item.as_str().map(str::to_string))
60                .collect(),
61        )),
62        Some(_) => Ok(ParsedProjects::NotAList),
63    }
64}
65
66fn insert_project(content: &str, path: &str) -> anyhow::Result<ProjectsEdit> {
67    let (mut lines, newline_at_end) = split_lines(content);
68    match find_root_projects(&lines) {
69        None => {
70            append_projects_block(&mut lines, path);
71            Ok(ProjectsEdit::Updated(join_lines(&lines, newline_at_end)))
72        }
73        Some(key_line) => {
74            let same_line = projects_value(&lines[key_line]).unwrap_or("").to_string();
75            let (value, comment) = split_value_and_comment(&same_line);
76            let value = value.trim();
77            if is_complete_flow(value) && value != "[]" {
78                let updated = add_to_flow_line(&lines[key_line], path)
79                    .ok_or_else(|| anyhow::anyhow!("could not edit projects: list as text"))?;
80                lines[key_line] = updated;
81                return Ok(ProjectsEdit::Updated(join_lines(&lines, newline_at_end)));
82            }
83            if is_empty_list_value(value) {
84                if comment.trim().is_empty() {
85                    lines[key_line] = "projects:".to_string();
86                } else {
87                    lines[key_line] = format!("projects:{comment}");
88                }
89            } else if !value.is_empty() {
90                anyhow::bail!("could not edit projects: list as text");
91            }
92            let indent = detect_indent(&lines, key_line);
93            let insert_at = insert_index(&lines, key_line) + 1;
94            lines.insert(insert_at, format!("{indent}- {}", format_yaml_string(path)));
95            Ok(ProjectsEdit::Updated(join_lines(&lines, newline_at_end)))
96        }
97    }
98}
99
100fn delete_project(content: &str, candidates: &[&str]) -> anyhow::Result<ProjectsEdit> {
101    let (mut lines, newline_at_end) = split_lines(content);
102    let key_line = find_root_projects(&lines)
103        .ok_or_else(|| anyhow::anyhow!("could not edit projects: list as text"))?;
104    let same_line = projects_value(&lines[key_line]).unwrap_or("").to_string();
105    let (value, _) = split_value_and_comment(&same_line);
106    let value = value.trim();
107    if is_complete_flow(value) {
108        let updated = remove_from_flow_line(&lines[key_line], candidates)
109            .ok_or_else(|| anyhow::anyhow!("could not edit projects: list as text"))?;
110        lines[key_line] = updated;
111        return Ok(ProjectsEdit::Updated(join_lines(&lines, newline_at_end)));
112    }
113    if !value.is_empty() && !is_empty_list_value(value) {
114        anyhow::bail!("could not edit projects: list as text");
115    }
116    let mut removed = false;
117    let mut idx = key_line + 1;
118    while idx < lines.len() {
119        if is_section_end(&lines[idx]) {
120            break;
121        }
122        if let Some(item) = block_item_value(&lines[idx])
123            && candidates.contains(&item.as_str())
124        {
125            lines.remove(idx);
126            removed = true;
127            continue;
128        }
129        idx += 1;
130    }
131    if !removed {
132        anyhow::bail!("could not edit projects: list as text");
133    }
134    Ok(ProjectsEdit::Updated(join_lines(&lines, newline_at_end)))
135}
136
137fn append_projects_block(lines: &mut Vec<String>, path: &str) {
138    if lines.last().is_some_and(|line| !line.is_empty()) {
139        lines.push(String::new());
140    }
141    lines.push("projects:".to_string());
142    lines.push(format!("  - {}", format_yaml_string(path)));
143}
144
145fn find_root_projects(lines: &[String]) -> Option<usize> {
146    lines.iter().position(|line| projects_value(line).is_some())
147}
148
149fn projects_value(line: &str) -> Option<&str> {
150    let rest = line.strip_prefix("projects:")?;
151    if rest.is_empty() || rest.starts_with([' ', '\t']) {
152        Some(rest)
153    } else {
154        None
155    }
156}
157
158fn insert_index(lines: &[String], key_line: usize) -> usize {
159    let mut last = key_line;
160    for (idx, line) in lines.iter().enumerate().skip(key_line + 1) {
161        if is_section_end(line) {
162            break;
163        }
164        if block_item_value(line).is_some() || is_commented_list_item(line) || is_continuation(line)
165        {
166            last = idx;
167        }
168    }
169    last
170}
171
172fn detect_indent(lines: &[String], key_line: usize) -> String {
173    for line in lines.iter().skip(key_line + 1) {
174        if is_section_end(line) {
175            break;
176        }
177        if block_item_value(line).is_some() || is_commented_list_item(line) {
178            let trimmed = line.trim_start();
179            return line[..line.len() - trimmed.len()].to_string();
180        }
181    }
182    "  ".to_string()
183}
184
185fn is_section_end(line: &str) -> bool {
186    let trimmed = line.trim_start();
187    if trimmed.is_empty() || trimmed.starts_with('#') {
188        return false;
189    }
190    if trimmed == "---" || trimmed == "..." {
191        return true;
192    }
193    if line.starts_with([' ', '\t']) {
194        return false;
195    }
196    if trimmed.starts_with('-') {
197        return false;
198    }
199    trimmed.contains(':')
200}
201
202fn block_item_value(line: &str) -> Option<String> {
203    let trimmed = line.trim_start();
204    if trimmed.starts_with('#') {
205        return None;
206    }
207    let rest = trimmed.strip_prefix('-')?;
208    if !rest.is_empty() && !rest.starts_with([' ', '\t']) {
209        return None;
210    }
211    Some(parse_scalar(rest))
212}
213
214fn is_commented_list_item(line: &str) -> bool {
215    let trimmed = line.trim_start();
216    let Some(rest) = trimmed.strip_prefix('#') else {
217        return false;
218    };
219    rest.trim_start().starts_with('-')
220}
221
222fn is_continuation(line: &str) -> bool {
223    let trimmed = line.trim_start();
224    if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with('-') {
225        return false;
226    }
227    line.starts_with([' ', '\t'])
228}
229
230fn is_empty_list_value(value: &str) -> bool {
231    matches!(value, "" | "[]" | "~" | "null" | "Null" | "NULL")
232}
233
234fn is_complete_flow(value: &str) -> bool {
235    value.starts_with('[') && value.ends_with(']')
236}
237
238struct FlowLine<'a> {
239    prefix: &'a str,
240    inner: &'a str,
241    comment: &'a str,
242}
243
244fn parse_flow_line(line: &str) -> Option<FlowLine<'_>> {
245    let rest = projects_value(line)?;
246    let (value, comment) = split_value_and_comment(rest);
247    let open = value.find('[')?;
248    let close = value.rfind(']')?;
249    Some(FlowLine {
250        prefix: &value[..open],
251        inner: &value[open + 1..close],
252        comment,
253    })
254}
255
256fn write_flow_line(flow: &FlowLine<'_>, inner: &str) -> String {
257    format!("projects:{}[{inner}]{}", flow.prefix, flow.comment)
258}
259
260fn add_to_flow_line(line: &str, path: &str) -> Option<String> {
261    let flow = parse_flow_line(line)?;
262    let inner = flow.inner.trim();
263    let formatted = format_yaml_string(path);
264    let new_inner = if inner.is_empty() {
265        formatted
266    } else {
267        format!("{inner}, {formatted}")
268    };
269    Some(write_flow_line(&flow, &new_inner))
270}
271
272fn remove_from_flow_line(line: &str, candidates: &[&str]) -> Option<String> {
273    let flow = parse_flow_line(line)?;
274    let items = parse_flow_items(flow.inner)?;
275    let remaining: Vec<String> = items
276        .into_iter()
277        .filter(|item| !candidates.contains(&item.as_str()))
278        .map(|item| format_yaml_string(&item))
279        .collect();
280    Some(write_flow_line(&flow, &remaining.join(", ")))
281}
282
283fn parse_flow_items(inner: &str) -> Option<Vec<String>> {
284    if inner.trim().is_empty() {
285        return Some(Vec::new());
286    }
287    let mut items = Vec::new();
288    let mut current = String::new();
289    let mut in_single = false;
290    let mut in_double = false;
291    let mut chars = inner.chars();
292    while let Some(c) = chars.next() {
293        match c {
294            '\\' if in_double => {
295                current.push(c);
296                if let Some(next) = chars.next() {
297                    current.push(next);
298                }
299            }
300            '\'' if !in_double => {
301                in_single = !in_single;
302                current.push(c);
303            }
304            '"' if !in_single => {
305                in_double = !in_double;
306                current.push(c);
307            }
308            ',' if !in_single && !in_double => {
309                items.push(parse_scalar(&current));
310                current.clear();
311            }
312            _ => current.push(c),
313        }
314    }
315    if in_single || in_double {
316        return None;
317    }
318    if !current.trim().is_empty() {
319        items.push(parse_scalar(&current));
320    }
321    Some(items)
322}
323
324fn split_value_and_comment(s: &str) -> (&str, &str) {
325    match inline_comment_index(s) {
326        Some(hash_idx) => {
327            let value = s[..hash_idx].trim_end();
328            let comment = &s[value.len()..];
329            (value, comment)
330        }
331        None => (s, ""),
332    }
333}
334
335fn inline_comment_index(s: &str) -> Option<usize> {
336    let mut in_single = false;
337    let mut in_double = false;
338    let mut chars = s.char_indices();
339    while let Some((i, c)) = chars.next() {
340        match c {
341            '\\' if in_double => {
342                chars.next();
343            }
344            '\'' if !in_double => in_single = !in_single,
345            '"' if !in_single => in_double = !in_double,
346            '#' if !in_single
347                && !in_double
348                && (i == 0 || s.as_bytes().get(i - 1).is_some_and(u8::is_ascii_whitespace)) =>
349            {
350                return Some(i);
351            }
352            _ => {}
353        }
354    }
355    None
356}
357
358fn parse_scalar(s: &str) -> String {
359    let s = if let Some(i) = inline_comment_index(s) {
360        s[..i].trim()
361    } else {
362        s.trim()
363    };
364    if s.len() >= 2 && s.starts_with('"') && s.ends_with('"') {
365        return s[1..s.len() - 1]
366            .replace("\\\\", "\\")
367            .replace("\\\"", "\"");
368    }
369    if s.len() >= 2 && s.starts_with('\'') && s.ends_with('\'') {
370        return s[1..s.len() - 1].replace("''", "'");
371    }
372    s.to_string()
373}
374
375pub(crate) fn format_yaml_string(s: &str) -> String {
376    if needs_yaml_quotes(s) {
377        format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\""))
378    } else {
379        s.to_string()
380    }
381}
382
383fn needs_yaml_quotes(s: &str) -> bool {
384    s.is_empty()
385        || s.starts_with([' ', '\t', '-'])
386        || s.ends_with([' ', '\t'])
387        || matches!(
388            s,
389            "null" | "Null" | "NULL" | "~" | "true" | "false" | "yes" | "no"
390        )
391        || s.bytes().any(|b| {
392            matches!(
393                b,
394                b':' | b'#'
395                    | b'{'
396                    | b'}'
397                    | b'['
398                    | b']'
399                    | b','
400                    | b'&'
401                    | b'*'
402                    | b'!'
403                    | b'|'
404                    | b'>'
405                    | b'<'
406                    | b'='
407                    | b'%'
408                    | b'@'
409                    | b'`'
410                    | b'\''
411                    | b'"'
412                    | b'\\'
413            )
414        })
415}
416
417fn split_lines(content: &str) -> (Vec<String>, bool) {
418    if content.is_empty() {
419        return (Vec::new(), false);
420    }
421    let newline_at_end = content.ends_with('\n');
422    let body = content.strip_suffix('\n').unwrap_or(content);
423    (
424        body.split('\n').map(str::to_string).collect(),
425        newline_at_end,
426    )
427}
428
429fn join_lines(lines: &[String], newline_at_end: bool) -> String {
430    let mut out = lines.join("\n");
431    if (newline_at_end || !out.is_empty()) && !out.ends_with('\n') {
432        out.push('\n');
433    }
434    out
435}
436
437#[cfg(test)]
438mod tests {
439    use super::*;
440
441    const COMMENTED_CONFIG: &str = "\
442# Orch global configuration
443# See: https://github.com/gabrielkoerich/orch
444
445projects:
446  - /Users/me/Projects/orch
447  # - /Users/me/Projects/old-app
448
449# Agents to discover in PATH
450agents:
451  - claude
452  - codex
453  # - glm
454  # - olm  # Ollama via Claude-compatible CLI
455
456router:
457  mode: \"round_robin\"
458  # weights:
459  #   claude: 0.25
460  #   codex: 0.1
461  # pool:
462  #   - claude:haiku
463  #   - opencode:free
464";
465
466    fn updated(edit: ProjectsEdit) -> String {
467        match edit {
468            ProjectsEdit::Updated(s) => s,
469            ProjectsEdit::Unchanged => panic!("expected Updated"),
470        }
471    }
472
473    fn comment_lines(content: &str) -> Vec<&str> {
474        content
475            .lines()
476            .filter(|line| line.trim_start().starts_with('#'))
477            .collect()
478    }
479
480    fn blank_line_count(content: &str) -> usize {
481        content.lines().filter(|line| line.is_empty()).count()
482    }
483
484    #[test]
485    fn project_add_preserves_comments_and_blank_lines() {
486        let after = updated(add_project(COMMENTED_CONFIG, "/Users/me/Projects/new").unwrap());
487        assert_eq!(comment_lines(COMMENTED_CONFIG), comment_lines(&after));
488        assert_eq!(blank_line_count(COMMENTED_CONFIG), blank_line_count(&after));
489        assert!(after.contains("  - /Users/me/Projects/new\n"));
490        assert!(after.contains("  - /Users/me/Projects/orch\n"));
491        assert_eq!(
492            after,
493            "\
494# Orch global configuration
495# See: https://github.com/gabrielkoerich/orch
496
497projects:
498  - /Users/me/Projects/orch
499  # - /Users/me/Projects/old-app
500  - /Users/me/Projects/new
501
502# Agents to discover in PATH
503agents:
504  - claude
505  - codex
506  # - glm
507  # - olm  # Ollama via Claude-compatible CLI
508
509router:
510  mode: \"round_robin\"
511  # weights:
512  #   claude: 0.25
513  #   codex: 0.1
514  # pool:
515  #   - claude:haiku
516  #   - opencode:free
517"
518        );
519    }
520
521    #[test]
522    fn project_add_existing_path_changes_nothing() {
523        let edit = add_project(COMMENTED_CONFIG, "/Users/me/Projects/orch").unwrap();
524        assert_eq!(edit, ProjectsEdit::Unchanged);
525    }
526
527    #[test]
528    fn project_add_quoted_duplicate_changes_nothing() {
529        let config = "projects:\n  - \"/Users/me/Projects/orch\"\n# keep me\n";
530        let edit = add_project(config, "/Users/me/Projects/orch").unwrap();
531        assert_eq!(edit, ProjectsEdit::Unchanged);
532    }
533
534    #[test]
535    fn project_remove_preserves_comments() {
536        let after =
537            updated(remove_project(COMMENTED_CONFIG, &["/Users/me/Projects/orch"]).unwrap());
538        assert_eq!(comment_lines(COMMENTED_CONFIG), comment_lines(&after));
539        assert!(!after.contains("  - /Users/me/Projects/orch\n"));
540        assert!(after.contains("  # - /Users/me/Projects/old-app\n"));
541        assert!(after.contains("  # - glm\n"));
542        assert_eq!(
543            after,
544            "\
545# Orch global configuration
546# See: https://github.com/gabrielkoerich/orch
547
548projects:
549  # - /Users/me/Projects/old-app
550
551# Agents to discover in PATH
552agents:
553  - claude
554  - codex
555  # - glm
556  # - olm  # Ollama via Claude-compatible CLI
557
558router:
559  mode: \"round_robin\"
560  # weights:
561  #   claude: 0.25
562  #   codex: 0.1
563  # pool:
564  #   - claude:haiku
565  #   - opencode:free
566"
567        );
568    }
569
570    #[test]
571    fn project_remove_missing_path_changes_nothing() {
572        let edit = remove_project(COMMENTED_CONFIG, &["/nope"]).unwrap();
573        assert_eq!(edit, ProjectsEdit::Unchanged);
574    }
575
576    #[test]
577    fn project_add_empty_flow_list_keeps_surrounding_comments() {
578        let config = "\
579# header
580
581projects: []
582
583# Agents
584agents:
585  # - glm
586  - claude
587";
588        let after = updated(add_project(config, "/tmp/app").unwrap());
589        assert_eq!(comment_lines(config), comment_lines(&after));
590        assert_eq!(
591            after,
592            "\
593# header
594
595projects:
596  - /tmp/app
597
598# Agents
599agents:
600  # - glm
601  - claude
602"
603        );
604    }
605
606    #[test]
607    fn project_add_appends_block_when_projects_key_missing() {
608        let config = "# just a comment\n\nrouter:\n  mode: llm\n";
609        let after = updated(add_project(config, "/tmp/app").unwrap());
610        assert!(after.contains("# just a comment\n"));
611        assert!(after.ends_with("projects:\n  - /tmp/app\n"));
612    }
613
614    #[test]
615    fn project_add_rejects_non_list_projects() {
616        let err = add_project("projects: nope\n", "/tmp/app").unwrap_err();
617        assert!(err.to_string().contains("projects is not a list"));
618    }
619
620    #[test]
621    fn project_add_appends_to_flow_list() {
622        let config = "# keep\nprojects: [/a, /b]\n# tail\n";
623        let after = updated(add_project(config, "/c").unwrap());
624        assert_eq!(after, "# keep\nprojects: [/a, /b, /c]\n# tail\n");
625    }
626
627    #[test]
628    fn project_remove_from_flow_list() {
629        let config = "# keep\nprojects: [/a, /b]\n# tail\n";
630        let after = updated(remove_project(config, &["/a"]).unwrap());
631        assert_eq!(after, "# keep\nprojects: [/b]\n# tail\n");
632    }
633
634    #[test]
635    fn project_add_to_flow_list_keeps_an_inline_comment() {
636        let config = "projects: [/a, /b] # keep\n";
637        let after = updated(add_project(config, "/c").unwrap());
638        assert_eq!(after, "projects: [/a, /b, /c] # keep\n");
639    }
640
641    #[test]
642    fn project_remove_from_flow_list_keeps_an_inline_comment() {
643        let config = "projects: [/a, /b] # keep\n";
644        let after = updated(remove_project(config, &["/a"]).unwrap());
645        assert_eq!(after, "projects: [/b] # keep\n");
646    }
647
648    #[test]
649    fn project_remove_last_flow_item_leaves_empty_brackets() {
650        let after = updated(remove_project("projects: [/a]\n", &["/a"]).unwrap());
651        assert_eq!(after, "projects: []\n");
652    }
653
654    #[test]
655    fn compact_projects_key_without_space_is_not_a_mapping() {
656        let add_err = add_project("projects:[/a]\n", "/b").unwrap_err();
657        assert!(add_err.to_string().contains("config is not a YAML mapping"));
658        let remove_err = remove_project("projects:[/a]\n", &["/a"]).unwrap_err();
659        assert!(
660            remove_err
661                .to_string()
662                .contains("config is not a YAML mapping")
663        );
664    }
665
666    #[test]
667    fn project_remove_quoted_flow_item_rewrites_remaining_unquoted() {
668        let after = updated(remove_project("projects: [\"/a\", /b]\n", &["/a"]).unwrap());
669        assert_eq!(after, "projects: [/b]\n");
670    }
671
672    #[test]
673    fn project_add_quotes_a_flow_path_that_needs_quoting() {
674        let after = updated(add_project("projects: [/a]\n", "#weird").unwrap());
675        assert_eq!(after, "projects: [/a, \"#weird\"]\n");
676    }
677}