silcrow 0.2.1

Deterministic CLI for a citable, checkable graph of laws in a git tree.
use super::*;

fn entry(src: &str, line: usize) -> Option<&str> {
    let tree = parse(&YAML, src).expect("parse");
    span_range(&YAML, src, &tree, line).map(|(s, e)| &src[s..e])
}

const MANIFEST: &str = "apiVersion: apps/v1\nkind: Deployment\nspec:\n  # pin\n  replicas: 3\n  template:\n    # pin\n    spec:\n      containers:\n        # pin\n        - name: app\n          image: nginx:1.25\n        - name: side\n";

#[test]
fn a_marker_spans_the_entry_or_item_below_it() {
    assert_eq!(entry(MANIFEST, 4), Some("replicas: 3"));
    assert_eq!(
        entry(MANIFEST, 7),
        Some("spec:\n      containers:\n        # pin\n        - name: app\n          image: nginx:1.25\n        - name: side")
    );
    assert_eq!(
        entry(MANIFEST, 10),
        Some("- name: app\n          image: nginx:1.25")
    );
    let first = "# pin\na: 1\nb:\n  # pin\n  c: 2\n---\n# pin\nd: &x\n  # pin\n  e: 3\n";
    assert_eq!(
        entry(first, 1),
        Some("a: 1\nb:\n  # pin\n  c: 2"),
        "a document"
    );
    assert_eq!(entry(first, 4), Some("c: 2"));
    assert_eq!(entry(first, 7), Some("d: &x\n  # pin\n  e: 3"));
    assert_eq!(entry(first, 9), Some("e: 3"));
    assert_eq!(entry("a: 1\n# pin\n", 2), None);
}

/// YAML hangs a comment that follows a nested block inside that block, at any depth: the
/// marker still spans the entry or item right below it.
#[test]
fn a_marker_after_a_nested_block_spans_the_member_below_it() {
    let src = "steps:\n  - run: make\n  # pin\n  - run: test\nother:\n  list:\n    - a: 1\n    # pin\n    - b: 2\n  # pin\n  more: 3\nflat:\n- x\n# pin\n- y\ndeep:\n  a:\n    b:\n      c:\n        - d: 1\n  # pin\n  e: 2\nscalar: |\n  text\n# pin\nlast: 4\n";
    for (line, member) in [
        (3, "- run: test"),
        (8, "- b: 2"),
        (10, "more: 3"),
        (14, "- y"),
        (21, "e: 2"),
        (25, "last: 4"),
    ] {
        assert_eq!(entry(src, line), Some(member), "line {line}");
    }
    let tail = "a:\n  - run: make\n  # pin\n";
    assert_eq!(entry(tail, 3), None);
}

#[test]
fn a_marker_line_inside_a_block_scalar_is_text() {
    let src = "a: |\n  # § abcdefgh1\n  x\n# § abcdefgh1\nb: 1\n";
    let tree = parse(&YAML, src).expect("parse");
    assert_eq!(
        literal_lines(&YAML, src, &tree),
        [false, true, false, false, false]
    );
}

#[test]
fn quoting_styles_that_read_alike_stay() {
    let f = |key: &str, value: &str| format!("m:\n  # pin\n  {key}: {value}\n");
    for (key, value) in [("\"app\"", "web"), ("app", "\"web\""), ("'app'", "'web'")] {
        stays(&YAML, &f("app", "web"), &f(key, value), 2);
    }
    stays(&YAML, &f("a", "'it''s'"), &f("a", "\"it's\""), 2);
    stays(&YAML, &f("a", "foo\n    bar"), &f("a", "foo bar"), 2);
}

#[test]
fn a_scalar_that_reads_as_another_type_moves() {
    let f = |value: &str| format!("m:\n  # pin\n  a: {value}\n");
    for (plain, quoted) in [
        ("3", "\"3\""),
        ("NO", "\"NO\""),
        ("on", "'on'"),
        ("null", "\"null\""),
        ("1.0", "\"1.0\""),
    ] {
        moves(&YAML, &f(plain), &f(quoted), 2);
    }
    moves(&YAML, &f("\"a\\tb\""), &f("\"a\tb\""), 2);
    moves(&YAML, &f("foo\n\n    bar"), &f("foo bar"), 2);
}

#[test]
fn a_value_change_or_a_key_order_moves() {
    let src = "m:\n  # pin\n  spec:\n    replicas: 3\n    image: nginx\n";
    moves(&YAML, src, &src.replace("3", "4"), 2);
    moves(&YAML, src, &src.replace("image", "img"), 2);
    let swapped = "m:\n  # pin\n  spec:\n    image: nginx\n    replicas: 3\n";
    moves(&YAML, src, swapped, 2);
}

#[test]
fn a_pure_reindent_or_a_comment_stays() {
    let two = "m:\n  # pin\n  spec:\n    args:\n    - a\n    - b\n    script: |\n      echo hi\n        nested\n    flags: {x: 1, y: [2, 3]}\n";
    let four = "m:\n    # pin\n    spec:\n        args:\n            - a\n            - b\n        script: |\n            echo hi\n              nested\n        flags: { x: 1, y: [ 2, 3 ] }\n";
    stays(&YAML, two, four, 2);
    let commented = two.replace("- a\n", "- a # first\n    # between\n");
    stays(&YAML, two, &commented, 2);
    moves(
        &YAML,
        two,
        &two.replace("        nested", "         nested"),
        2,
    );
    moves(&YAML, two, &two.replace("script: |", "script: >"), 2);
    moves(&YAML, two, &two.replace("script: |", "script: |-"), 2);
}

#[test]
fn kept_trailing_lines_of_a_block_scalar_move() {
    let f = |gap: &str| format!("m:\n  # pin\n  a: |+\n    x\n{gap}b: 1\n");
    moves(&YAML, &f(""), &f("\n"), 2);
    stays(
        &YAML,
        &f("\n").replace("|+", "|"),
        &f("").replace("|+", "|"),
        2,
    );
}

/// An alias reads as its text: the node its anchor names is not read, a stated limit.
#[test]
fn anchors_and_aliases_read_as_text() {
    let src = "base: &b\n  cpu: 1\nm:\n  # pin\n  res: *b\n";
    stays(&YAML, src, &src.replace("cpu: 1", "cpu: 2"), 4);
    moves(&YAML, src, &src.replace("*b", "*c").replace("&b", "&c"), 4);
}

fn pod(init: &str, app: &str, side: &str) -> String {
    let context = |entry: &str| format!("      securityContext:\n        runAsUser: 1000\n{entry}");
    format!("apiVersion: v1\nkind: Pod\nspec:\n  initContainers:\n    - name: init\n{}  containers:\n    - name: app\n      image: nginx\n{}    - name: side\n{}", context(init), context(app), context(side))
}

const PRIVILEGED: &str = "        # pin\n        privileged: true\n";

fn shape_at(src: &str) -> String {
    let line = src.lines().position(|l| l.contains("# pin")).expect("pin") + 1;
    mint_span_digests(&YAML, src, line, &[])
        .unwrap_or_else(|| panic!("no digest for {src:?}"))
        .shape
}

#[test]
fn a_span_reads_the_keys_and_items_around_it() {
    let init = pod(PRIVILEGED, "", "");
    let side = pod("", "", PRIVILEGED);
    let app = pod("", PRIVILEGED, "");
    assert_ne!(shape_at(&init), shape_at(&side));
    assert_ne!(shape_at(&app), shape_at(&side));
    let renamed = init.replace("initContainers", "ephemeralContainers");
    assert_ne!(shape_at(&init), shape_at(&renamed));
    let under = |key: &str| format!("res:\n  {key}:\n    # pin\n    cpu: 1\n");
    assert_ne!(shape_at(&under("limits")), shape_at(&under("requests")));
    let second = "a: [\n  x,\n  {\n    # pin\n    b: 1\n  }\n]\n";
    let first = "a: [\n  {\n    # pin\n    b: 1\n  },\n  x\n]\n";
    assert_eq!(entry(second, 4), Some("b: 1"));
    assert_ne!(shape_at(second), shape_at(first));
    // An item a marker spans whole reads its own entries, not its position.
    assert_eq!(
        shape_at("a:\n  # pin\n  - y\n  - x\n"),
        shape_at("a:\n  - x\n  # pin\n  - y\n")
    );
}

const TWO: &str = "spec:\n  containers:\n    - name: api\n      image: api:1\n      env:\n        - name: A\n          value: \"1\"\n      securityContext:\n        runAsUser: 1000\n        # pin\n        privileged: false\n    - name: sidecar\n      image: proxy:1\n      env:\n        - name: B\n          value: \"2\"\n      securityContext:\n        privileged: true\n";

#[test]
fn a_duplicate_key_in_a_mapping_that_holds_or_encloses_a_span_fails() {
    let dupes = |src: &str| {
        let tree = parse(&YAML, src).expect("parse");
        let line = src.lines().position(|l| l.contains("# pin")).expect("pin") + 1;
        let extent = span_range(&YAML, src, &tree, line).expect("span");
        yaml_duplicate_keys(&YAML, src, &tree, std::iter::once(extent))
    };
    let after =
        "securityContext:\n  # pin\n  privileged: false\n  runAsUser: 1\n  privileged: true\n";
    assert_eq!(dupes(after), [(3, 5, "privileged".to_string())]);
    let inside = "# pin\nres:\n  cpu: 1\n  \"cpu\": 2\n";
    assert_eq!(dupes(inside), [(3, 4, "\"cpu\"".to_string())]);
    let elsewhere = "a:\n  x: 1\n  x: 2\nb:\n  # pin\n  y: 1\n";
    assert!(dupes(elsewhere).is_empty());
    let marked = after.replace("# pin", "# § abcdefgh1");
    let checked = crate::span::verify_file(Path::new("k.yaml"), &marked, SERIALIZATION);
    assert!(
        checked
            .errors
            .iter()
            .any(|e| e.starts_with("k.yaml:5: the key `privileged` repeats the one at line 3")),
        "{:?}",
        checked.errors
    );
}

/// The scalar entries of each mapping around a span name the item it sits in: swapping the
/// `name` of two containers moves the pin.
#[test]
fn a_span_reads_the_scalar_entries_around_it() {
    let swapped = TWO
        .replace("name: api", "name: @")
        .replace("name: sidecar", "name: api")
        .replace("name: @", "name: sidecar");
    assert_ne!(shape_at(TWO), shape_at(&swapped));
    for (from, to) in [
        ("image: api:1", "image: api:2"),
        ("runAsUser: 1000", "runAsUser: 0"),
    ] {
        assert_ne!(shape_at(TWO), shape_at(&TWO.replace(from, to)), "{from}");
    }
}

#[test]
fn an_edit_of_a_nested_block_or_another_item_a_reindent_or_a_quoted_key_stays() {
    for (from, to) in [
        ("value: \"2\"", "value: \"3\""),
        ("value: \"1\"", "value: \"9\""),
        ("- name: A\n", "- name: C\n"),
        ("image: proxy:1", "image: proxy:2"),
        ("privileged: true", "privileged: false"),
        ("  containers:", "  \"containers\":"),
        ("name: api", "name: 'api'"),
    ] {
        let edited = TWO.replace(from, to);
        assert_ne!(edited, TWO, "{from}");
        assert_eq!(shape_at(TWO), shape_at(&edited), "{from}");
    }
    assert_eq!(shape_at(TWO), shape_at(&TWO.replace("\n  ", "\n    ")));
    let inserted = TWO.replace(
        "    - name: api\n",
        "    - name: first\n      image: busybox\n    - name: api\n",
    );
    assert_ne!(shape_at(TWO), shape_at(&inserted));
}

const CHART: &str = r#"apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ include "app.fullname" . }}
  labels:
    {{- include "app.labels" . | nindent 4 }}
spec:
  # pin
  {{- if not .Values.autoscaling.enabled }}
  replicas: {{ .Values.replicaCount }}
  {{- end }}
  template:
    spec:
      # pin
      containers:
        - name: {{ .Chart.Name }}
          image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default "x }}" }}"
          {{- with .Values.resources }}
          resources:
            {{- toYaml . | nindent 12 }}
          {{- end }}
          {{/* a note
          that spans lines */}}
"#;

#[test]
fn a_yaml_file_under_a_templates_directory_reads_as_a_helm_template() {
    assert!(
        lang_for_path(Path::new("charts/app/templates/deploy.yaml")).is_some_and(|l| l.template)
    );
    assert!(lang_for_path(Path::new("charts/app/templates/x/a.yml")).is_some_and(|l| l.template));
    assert!(lang_for_path(Path::new("charts/app/values.yaml")).is_some_and(|l| !l.template));
    assert!(lang_for_path(Path::new("templates.yaml")).is_some_and(|l| !l.template));
    assert!(!parse(&HELM, CHART).expect("parse").root_node().has_error());
    assert!(parse(&YAML, CHART).expect("parse").root_node().has_error());
}

#[test]
fn a_template_action_reads_as_its_text() {
    let tree = parse(&HELM, CHART).expect("parse");
    let (s, e) = span_range(&HELM, CHART, &tree, 8).expect("span");
    assert_eq!(&CHART[s..e], "replicas: {{ .Values.replicaCount }}");
    for (from, to) in [
        (".Values.replicaCount", ".Values.count"),
        (
            "{{ .Values.replicaCount }}",
            "\"{{ .Values.replicaCount }}\"",
        ),
    ] {
        moves(&HELM, CHART, &CHART.replace(from, to), 8);
    }
    for (from, to) in [
        ("with .Values.resources", "with .Values.limits"),
        ("nindent 12", "nindent 10"),
        ("default \"x }}\"", "default \"y }}\""),
        (
            "{{- end }}\n          {{/*",
            "{{- end }}\n          {{- end }}\n          {{/*",
        ),
        ("{{ .Chart.Name }}", "{{.Chart.Name}}"),
        ("a note", "the note"),
    ] {
        moves(&HELM, CHART, &CHART.replace(from, to), 14);
    }
    stays(&HELM, CHART, &CHART.replace("autoscaling", "scaling"), 14);
    stays(&HELM, CHART, &CHART.replace("      ", "        "), 14);
    every_byte_reaches_the_walk(&HELM, CHART, 14);
}