aboutsummaryrefslogtreecommitdiffstats
path: root/pkgs/populate/src/flake.rs
blob: f03e4431746deae342d21365b089437e235e0ef9 (plain)
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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
//! Drawing inputs of flakes in sources from other sources.
//!
//! This builds the same shell code as shell.nix generates, with every value
//! quoted, so both implementations behave alike while the code moves to
//! Rust piece by piece.

use crate::run::{quote as q, Context};
use crate::sh;
use crate::spec::{Follows, Source};
use serde_json::{Map, Value};
use std::collections::{BTreeMap, BTreeSet};

/// Nix function returning 1 if the lock file locks has an input at path, a
/// list of input names, resolving inputs that follow others, and else 0.
/// Like lockHasInput in flake-jq.nix, for the shell code drawing inputs.
pub const LOCK_HAS_INPUT: &str = r#"locks: path: let
  nodes = locks.nodes;
  input = key: name: (nodes.${key}.inputs or {}).${name} or null;
  # The node an input refers to, following follows from the root.
  node = ref:
    if ref == null then null
    else if builtins.isList ref then
      builtins.foldl'
        (key: name: if key == null then null else node (input key name))
        locks.root
        ref
    else ref;
  has = key: path:
    if path == [] then true
    else let next = node (input key (builtins.head path)); in
      next != null && has next (builtins.tail path);
in
  if has locks.root path then "1" else "0"
"#;

fn bool_setting(settings: &Map<String, Value>, key: &str, default: bool) -> bool {
    settings
        .get(key)
        .and_then(Value::as_bool)
        .unwrap_or(default)
}

fn patches(settings: &Map<String, Value>) -> Vec<&str> {
    settings
        .get("patches")
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
        .filter_map(Value::as_str)
        .collect()
}

/// Whether a source's inputs get drawn from other sources by a generated
/// flake in .populate/flakes, instead of by rewriting the lock file of the
/// flake in the source.  Symlink sources point at other sources, whose lock
/// files stay as they are.
pub fn has_generated_flake(source: &Source) -> bool {
    !source.follows().is_empty()
        && (source.kind == "symlink" || !bool_setting(&source.settings, "rewriteLock", true))
}

/// Whether a flake or flake-input source gets delivered as a copy, which
/// gets patched, gets its lock file rewritten, or is materialized.
pub fn derives_flake(source: &Source) -> bool {
    let settings = &source.settings;
    matches!(source.kind.as_str(), "flake" | "flake-input")
        && (bool_setting(settings, "materialize", false)
            || !patches(settings).is_empty()
            || (bool_setting(settings, "rewriteLock", true) && !source.follows().is_empty()))
}

fn use_state(sentinel: &str, names: &[&str]) -> String {
    let mut call = format!("use_state {}", q(sentinel));
    for name in names {
        call.push(' ');
        call.push_str(&q(name));
    }
    call
}

/// Draws inputs of flakes in sources from other sources, and derives what
/// the target paths of flake and flake-input sources that get patched, get
/// their lock files rewritten, or are materialized get.  Sources get
/// processed in the order they draw inputs from each other.  Returns the
/// shell code to run on the target, which also removes state that sources
/// don't need anymore.
///
/// Inputs get drawn by rewriting the lock file of the flake in the source
/// with nix flake lock --override-input: in place for file and git sources,
/// and in a copy for flake and flake-input sources.  Sources with
/// rewriteLock set to false, and symlink sources, get a generated flake in
/// .populate/flakes/<name> instead, which re-exports the outputs of the
/// flake in the source, with those inputs drawn from the other sources.
/// Lock files get rewritten or generated on every run, so they match the
/// sources.
pub fn flakes(context: &Context, dir: &str, sources: &BTreeMap<String, Source>) -> String {
    let sentinel = format!("{dir}/.populate");
    let flakes_dir = format!("{sentinel}/flakes");
    let derived_dir = format!("{sentinel}/derived");
    let patches_dir = format!("{sentinel}/patches");
    let follows: BTreeMap<&str, Vec<Follows>> = sources
        .iter()
        .map(|(n, s)| (n.as_str(), s.follows()))
        .collect();
    let drawing: BTreeSet<&str> = follows
        .iter()
        .filter(|(_, f)| !f.is_empty())
        .map(|(n, _)| *n)
        .collect();
    let generated: BTreeSet<&str> = sources
        .iter()
        .filter(|(_, s)| has_generated_flake(s))
        .map(|(n, _)| n.as_str())
        .collect();
    let derived: BTreeSet<&str> = sources
        .iter()
        .filter(|(_, s)| derives_flake(s))
        .map(|(n, _)| n.as_str())
        .collect();
    let patched: BTreeSet<&str> = sources
        .iter()
        .filter(|(_, s)| !patches(&s.settings).is_empty())
        .map(|(n, _)| n.as_str())
        .collect();
    let names: BTreeSet<&str> = drawing.union(&derived).copied().collect();

    // Source names become input names in generated flakes, where Nix
    // accepts fewer names than populate.  Others get replaced by one
    // derived from them.
    let input_name = |name: &str| -> String {
        let ok = name.chars().next().is_some_and(|c| c.is_ascii_alphabetic())
            && name
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
            && name != "self";
        if ok {
            name.to_string()
        } else {
            format!("source-{}", &sha256_hex(name.as_bytes())[..16])
        }
    };
    let drawn_from =
        |name: &str| -> Vec<String> { follows[name].iter().map(|f| f.source.clone()).collect() };
    let sorted = toposort(&names, &drawn_from);

    // Shell word for the URL of the flake that inputs drawn from a source
    // use: its generated flake, if it has one, so overrides don't need to
    // be repeated, or else the flake in the source.  Nix refuses path: URLs
    // with symlinks on the way, which the target directory may be, so paths
    // get resolved.
    let url = |name: &str| -> String {
        if generated.contains(name) {
            format!(
                "\"path:$(url_path \"$(readlink -f {})\")\"",
                q(&format!("{flakes_dir}/{name}"))
            )
        } else {
            format!("\"$(flake_url {})\"", q(name))
        }
    };

    // Where the input at path of the flake in the source named name is in
    // the flake that the source's inputs get drawn into: the flake itself,
    // or its generated flake.  On the way, inputs that get drawn from
    // sources are the flakes of those sources, where drawing went on, so
    // the path continues there.  A generated flake has its source and the
    // sources that one draws from as inputs, and nothing else, so the path
    // names them there.
    fn parent_of<'a>(follows: &'a [Follows], path: &[String]) -> Option<&'a Follows> {
        (1..path.len())
            .rev()
            .find_map(|n| follows.iter().find(|f| f.path == path[..n]))
    }
    fn drawn_path(
        name: &str,
        path: &[String],
        follows: &BTreeMap<&str, Vec<Follows>>,
        generated: &BTreeSet<&str>,
        input_name: &dyn Fn(&str) -> String,
    ) -> Vec<String> {
        let parent = parent_of(&follows[name], path);
        match (generated.contains(name), parent) {
            (true, None) => [vec![input_name(name)], path.to_vec()].concat(),
            (true, Some(p)) => [
                vec![input_name(&p.source)],
                drawn_path(
                    &p.source,
                    &path[p.path.len()..],
                    follows,
                    generated,
                    input_name,
                ),
            ]
            .concat(),
            (false, None) => path.to_vec(),
            (false, Some(p)) => [
                p.path.clone(),
                drawn_path(
                    &p.source,
                    &path[p.path.len()..],
                    follows,
                    generated,
                    input_name,
                ),
            ]
            .concat(),
        }
    }
    let drawn_path =
        |name: &str, path: &[String]| drawn_path(name, path, &follows, &generated, &input_name);

    // The inputs that drawing the input at path of the flake in the source
    // named name needs to exist, as (name, path) of the source whose flake
    // has the input at path.
    fn input_checks(
        name: &str,
        path: &[String],
        follows: &BTreeMap<&str, Vec<Follows>>,
    ) -> Vec<(String, Vec<String>)> {
        match parent_of(&follows[name], path) {
            None => vec![(name.to_string(), path.to_vec())],
            Some(p) => [
                vec![(name.to_string(), p.path.clone())],
                input_checks(&p.source, &path[p.path.len()..], follows),
            ]
            .concat(),
        }
    }

    // Sets the positional parameters to nix flake lock's arguments for
    // drawing the inputs of the flake in source name from other sources.
    let override_args = |name: &str| -> String {
        let mut text = String::from("set --\n");
        for f in &follows[name] {
            text += &format!(
                "set -- \"$@\" --override-input {} {}\n",
                q(&drawn_path(name, &f.path).join("/")),
                url(&f.source)
            );
        }
        text
    };

    // Rewrites the lock file of the flake in a file or git source in place.
    let rewrite = |name: &str| -> String {
        format!(
            "(\n{}own_lock \"$(readlink -f {})\"\nnix flake lock \"$@\" \"$(flake_url {})\" >&2\n)\n",
            override_args(name),
            q(&format!("{dir}/{name}")),
            q(name)
        )
    };

    // Derives what the target path of a flake or flake-input source gets
    // from what got delivered to .populate/derived/<name>/original: a copy,
    // which gets patched and gets its lock file rewritten.  Unless
    // materialized, the copy gets added to the store, and the target path
    // becomes a link to it.  Copies get made again only if what they derive
    // from changes: materialized ones if the delivered store path, the
    // patches, or what inputs get drawn from which sources changes, and
    // others also if the sources they draw inputs from change.
    let derive = |name: &str| -> String {
        let source = &sources[name];
        let settings = &source.settings;
        let materialize = bool_setting(settings, "materialize", false);
        let rewrite_lock = bool_setting(settings, "rewriteLock", true) && drawing.contains(name);
        let target_path = format!("{dir}/{name}");
        let dir_ = format!("{derived_dir}/{name}");
        let has_patches = !patches(settings).is_empty();
        let follows_json: Vec<Value> = follows[name]
            .iter()
            .map(|f| serde_json::json!({ "path": f.path, "source": f.source }))
            .collect();
        // Like Nix' toJSON: attributes sorted by name.
        let spec = serde_json::to_string(&serde_json::json!({
            "follows": follows_json,
            "materialize": materialize,
            "rewriteLock": rewrite_lock,
        }))
        .expect("serializes");
        let patch_dir = format!("{patches_dir}/{name}");
        let apply_patches = if has_patches {
            format!(
                r#"ls {pd} | while read -r patch; do
  if ! patch -p1 -s --batch --no-backup-if-mismatch \
      -i {pd}/"$patch" >&2; then
    >&2 printf 'error: patch %s does not apply to source %s\n' \
        "$(printf %s "$patch" | cut -c6-)" {name}
    exit 1
  fi
done
"#,
                pd = q(&patch_dir),
                name = q(name)
            )
        } else {
            String::new()
        };
        let remove_work = format!("remove_tree {}", q(&format!("{dir_}/work")));
        let key_patches = if has_patches {
            format!(
                "ls {pd} | while read -r patch; do\n  sha256sum {pd}/\"$patch\"\ndone\n",
                pd = q(&patch_dir)
            )
        } else {
            String::new()
        };
        let key_drawn = if rewrite_lock && !materialize {
            let mut text = override_args(name);
            text += "printf '%s\\n' \"$@\"\n# Sources outside the store can change without changing their\n# path.\n";
            let mut seen = BTreeSet::new();
            for source in drawn_from(name) {
                if !seen.insert(source.clone()) {
                    continue;
                }
                let source = source.as_str();
                let p = if generated.contains(source) {
                    format!("{flakes_dir}/{source}")
                } else {
                    format!("{dir}/{source}")
                };
                text += &format!(
                    "drawn=$(readlink -f {})\ncase $drawn in\n  /nix/store/*) ;;\n  *) nix-hash --type sha256 \"$drawn\" ;;\nesac\n",
                    q(&p)
                );
            }
            text
        } else {
            String::new()
        };
        let body = if materialize {
            let relock = if rewrite_lock {
                format!(
                    "{}own_lock {}\nnix flake lock \"$@\" \"$(flake_url {})\" >&2\n",
                    override_args(name),
                    q(&target_path),
                    q(name)
                )
            } else {
                String::new()
            };
            format!(
                r#"if ! test -e {key} ||
    test "$(cat {key})" != "$key" ||
    test -L {tp} ||
    ! test -d {tp}; then
  cp -R "$original" {work}
  chmod -R u+w {work}
  (
    cd {work}
    {apply_patches}
  )
  remove_foreign_link {tp} {tp_name}
  rm -fR {tp}
  mv {work} {tp}
  write_key "$key"
fi
{relock}
"#,
                key = q(&format!("{dir_}/key")),
                tp = q(&target_path),
                tp_name = q(&context.name(&target_path)),
                work = q(&format!("{dir_}/work")),
            )
        } else {
            let relock = if rewrite_lock {
                format!(
                    "{}# Not just the path, which Nix takes for the enclosing Git\n# work tree, if any.\nnix flake lock \"$@\" \"path:$(url_path \"$work\")${{subdir:+?dir=$subdir}}\" >&2\n",
                    override_args(name)
                )
            } else {
                String::new()
            };
            format!(
                r#"if test -e {key} &&
    test "$(cat {key})" = "$key" &&
    result=$(readlink {result}) &&
    nix-store --check-validity "$result" 2>/dev/null; then
  :
else
  # The copy keeps the name of the delivered store path.
  mkdir {work}
  work=$(readlink -f {work})/$(basename "$path" | cut -c34-)
  cp -R "$path" "$work"
  chmod -R u+w "$work"
  (
    cd "$work"/"$subdir"
    {apply_patches}
  )
  {relock}
  result=$(nix-store --add-fixed --recursive sha256 "$work")
  {remove_work}
  nix-store --realise "$result" \
      --add-root {result} --indirect >/dev/null
  write_key "$key"
fi
make_room_for_link {tp} {tp_name}
# .populate/derived/<name>/result roots the store path.
ln -fns "$result${{subdir:+/$subdir}}" {tp}
"#,
                key = q(&format!("{dir_}/key")),
                result = q(&format!("{dir_}/result")),
                work = q(&format!("{dir_}/work")),
                tp = q(&target_path),
                tp_name = q(&context.name(&target_path)),
            )
        };
        format!(
            r#"(
  # Writes the key $1 to a new file, which then replaces the key, so
  # nothing at its place gets written through, e.g. a symlink.
  write_key() {{
    key_file=$(mktemp {key}.XXXXXX)
    printf '%s\n' "$1" > "$key_file"
    mv -f "$key_file" {key}
  }}
  original=$(readlink -f {original})
  path=$(printf '%s\n' "$original" | cut -d/ -f1-4)
  subdir=${{original#"$path"}}
  subdir=${{subdir#/}}
  key=$(
    {{
      printf '%s\n' "$original" {spec}
      {key_patches}
      {key_drawn}
    }} | sha256sum | cut -c-64
  )
  {remove_work}
  {body}
)
"#,
            key = q(&format!("{dir_}/key")),
            original = q(&format!("{dir_}/original")),
            spec = q(&spec),
        )
    };

    // Generates the flake of a source in .populate/flakes/<name>.
    let generate = |name: &str| -> String {
        let mut drawn: Vec<&str> = Vec::new();
        for f in &follows[name] {
            if !drawn.contains(&f.source.as_str()) {
                drawn.push(&f.source);
            }
        }
        let json = |s: &str| serde_json::to_string(s).expect("serializes");
        // Nix ignores overrides below an input that follows another input,
        // so an input of an input drawn from a source gets overridden at
        // that source.
        let override_line = |f: &Follows| -> String {
            format!(
                "inputs.{}.follows = {};",
                drawn_path(name, &f.path)
                    .iter()
                    .map(|n| json(n))
                    .collect::<Vec<_>>()
                    .join(".inputs."),
                json(&input_name(&f.source))
            )
        };
        let mut text = format!("(\nurl=$(flake_url {})\n", q(name));
        for (i, source) in drawn.iter().enumerate() {
            text += &format!("url{}={}\n", i + 1, url(source));
        }
        let fd = q(&format!("{flakes_dir}/{name}"));
        text += &format!("rm -fR {fd}\nmkdir {fd}\ncd {fd}\n{{\n  echo '{{'\n");
        text += &format!(
            "  printf '  inputs.%s.url = \"%s\";\\n' {} \"$url\"\n",
            q(&json(&input_name(name)))
        );
        for (i, source) in drawn.iter().enumerate() {
            text += &format!(
                "  printf '  inputs.%s.url = \"%s\";\\n' {} \"$url{}\"\n",
                q(&json(&input_name(source))),
                i + 1
            );
            if !generated.contains(source) {
                text += &format!(
                    "  if ! test -e \"$(readlink -f {})\"/flake.nix; then\n    printf '  inputs.%s.flake = false;\\n' {}\n  fi\n",
                    q(&format!("{dir}/{source}")),
                    q(&json(&input_name(source)))
                );
            }
        }
        for f in &follows[name] {
            text += &format!("  printf '  %s\\n' {}\n", q(&override_line(f)));
        }
        text += &format!(
            "  printf '  outputs = inputs: inputs.%s;\\n' {}\n  echo '}}'\n}} > flake.nix\n",
            q(&json(&input_name(name)))
        );
        text += "# Not just ., which Nix takes for the enclosing Git work tree, if any.\nnix flake lock \"path:$(url_path \"$(pwd -P)\")\" >&2\n)\n";
        text
    };

    let process = |name: &str| -> String {
        let mut text = String::new();
        if derived.contains(name) {
            text += &derive(name);
        }
        if generated.contains(name) {
            text += &generate(name);
        } else if drawing.contains(name) && !derived.contains(name) {
            text += &rewrite(name);
        }
        text
    };

    // Removes the entries of the state directory that sources named names
    // don't need anymore, and the directory once it's empty.
    let remove_stale = |state_dir: &str, names: &BTreeSet<&str>| -> String {
        let mut call = format!("remove_others {} ''", q(state_dir));
        for name in names {
            call += &format!(" {}", q(name));
        }
        format!(
            "if test -d {d}; then\n  {call}\n  if test -z \"$(ls -A {d})\"; then\n    rmdir {d}\n  fi\nfi\n",
            d = q(state_dir)
        )
    };

    let all_names: Vec<&str> = sources.keys().map(String::as_str).collect();
    let mut text = format!("set -efu\n{}\n", use_state(&sentinel, &all_names));
    if !names.is_empty() {
        if !drawing.is_empty() {
            text += "require_flakes 'drawing flake inputs from sources'\n";
        }
        text += &format!(
            r#"
# Nix rewrites lock files in place, which also changes what else is a hard
# link to the lock file, e.g. in a backup, or what it is a symlink to.  So
# the lock file of the flake in the directory $1 gets replaced by a copy
# first.  The copy goes to a new file, so nothing that's there already gets
# written through.
own_lock() {{
  if test -e "$1"/flake.lock; then
    own_lock_copy=$(mktemp "$1"/.flake.lock.XXXXXX)
    cp -p "$1"/flake.lock "$own_lock_copy"
    mv -f "$own_lock_copy" "$1"/flake.lock
  fi
}}

# Prints the flake URL of the source named $1.
flake_url() {{
  path=$(readlink -f {dir}/"$1")
  if ! test -d "$path"; then
    >&2 printf 'error: source %s is not a directory\n' "$1"
    exit 1
  fi
  if test -e "$path"/.git; then
    if test -e "$path"/.gitmodules; then
      printf 'git+file:%s?submodules=1' "$(url_path "$path")"
    else
      printf 'git+file:%s' "$(url_path "$path")"
    fi
  else
    printf 'path:%s' "$(url_path "$path")"
  fi
}}

# Inputs can only be drawn into flakes, so check all sources before
# changing anything.
missing=
"#,
            dir = q(dir)
        );
        for name in &drawing {
            let p = if derived.contains(name) {
                format!("{derived_dir}/{name}/original")
            } else {
                format!("{dir}/{name}")
            };
            text += &format!(
                "if ! test -e {}/flake.nix; then\n  missing=\"$missing \"{}\nfi\n",
                q(&p),
                q(name)
            );
        }
        let derived_names: Vec<&str> = derived.iter().copied().collect();
        text += &format!(
            r#"if test -n "$missing"; then
  >&2 printf 'error: source %s draws flake inputs from other sources, but contains no flake.nix\n' $missing
  exit 1
fi

# Nix ignores inputs drawn that the flake doesn't have, with a warning, so a
# misspelt input name would draw nothing.  Prints the flake URL of the
# flake in the source named $1 as delivered.
own_flake_url() {{
  case " "{derived_names}" " in
    *" $1 "*)
      printf 'path:%s' "$(url_path "$(readlink -f {derived_dir}/"$1"/original)")"
      ;;
    *)
      flake_url "$1"
      ;;
  esac
}}
# The lock files of the flakes in the sources, as Nix locks them now, with
# an empty flake in place of each input drawn from a source, which may not
# be reachable, as the one the flake's lock file pins.
locks_dir=$(mktemp -d)
echo '{{ outputs = _: {{}}; }}' > "$locks_dir"/flake.nix
"#,
            derived_names = q(&derived_names.join(" ")),
            derived_dir = q(&derived_dir),
        );
        let mut locked: Vec<String> = Vec::new();
        for name in &drawing {
            for f in &follows[*name] {
                for (c, _) in input_checks(name, &f.path, &follows) {
                    if !locked.contains(&c) {
                        locked.push(c);
                    }
                }
            }
        }
        for name in &locked {
            text += "set --\n";
            for f in &follows[name.as_str()] {
                text += &format!(
                    "set -- \"$@\" --override-input {} \"path:$locks_dir\"\n",
                    q(&f.path.join("/"))
                );
            }
            text += &format!(
                r#"if ! nix flake metadata --json --no-write-lock-file "$@" \
    "$(own_flake_url {n})" > "$locks_dir"/{n}.json; then
  >&2 printf 'error: source %s draws inputs from other sources, but its flake can'"'"'t be locked\n' \
      {n}
  exit 1
fi
"#,
                n = q(name)
            );
        }
        text += &format!(
            r#"# Fails, naming the input, unless the flake in the source named $1 has
# an input at the path $2, a JSON list of input names.  $3 is the source
# that the input $4 of the source $5 gets drawn from.
require_input() {{
  if ! test "$(
    METADATA=$(cat "$locks_dir/$1.json") INPUT=$2 nix eval --impure --raw --expr {expr}
  )" = 1; then
    if test "$1" = "$5"; then
      >&2 printf 'error: source %s draws input %s from source %s, but its flake has no input %s\n' \
          "$5" "$4" "$3" "$4"
    else
      >&2 printf 'error: source %s draws input %s from source %s, but the flake of source %s has no input %s\n' \
          "$5" "$4" "$3" "$1" "$(printf %s "$2" | tr -d '[]"' | tr , /)"
    fi
    exit 1
  fi
}}
"#,
            expr = q(&format!(
                "({LOCK_HAS_INPUT})\n  (builtins.fromJSON (builtins.getEnv \"METADATA\")).locks\n  (builtins.fromJSON (builtins.getEnv \"INPUT\"))\n"
            ))
        );
        for name in &drawing {
            for f in &follows[*name] {
                for (c, path) in input_checks(name, &f.path, &follows) {
                    text += &format!(
                        "require_input {} {} \\\n    {} {} {}\n",
                        q(&c),
                        q(&serde_json::to_string(&path).expect("serializes")),
                        q(&f.source),
                        q(&f.path.join("/")),
                        q(name)
                    );
                }
            }
        }
        text += "rm -R \"$locks_dir\"\n\n";
        if !generated.is_empty() {
            text += &format!("mkdir -p {}\n", q(&flakes_dir));
        }
        for name in &sorted {
            text += &process(name);
        }
    }
    text += "# Remove roots of flake inputs of sources that are neither flake nor\n# flake-input sources anymore.\n";
    for (name, source) in sources {
        if !matches!(source.kind.as_str(), "flake" | "flake-input") {
            text += &format!("rm -fR {}\n", q(&format!("{sentinel}/flake-inputs/{name}")));
        }
    }
    let fi = q(&format!("{sentinel}/flake-inputs"));
    text += &format!(
        "if test -d {fi} &&\n    test -z \"$(ls -A {fi})\"; then\n  rmdir {fi}\nfi\n# Remove what sources left behind that don't need it anymore.\n"
    );
    text += &remove_stale(&flakes_dir, &generated);
    text += &remove_stale(&derived_dir, &derived);
    text += &remove_stale(&patches_dir, &patched);
    format!("{}\n{text}", sh::prelude())
}

/// The names sorted so each comes after the ones it draws inputs from, as
/// nixpkgs' toposort sorts them.  Cycles got refused by the checks.
fn toposort<'a>(
    names: &BTreeSet<&'a str>,
    drawn_from: &dyn Fn(&str) -> Vec<String>,
) -> Vec<&'a str> {
    // toposort a before b if a is drawn from by b: depth-first, like
    // nixpkgs' lib.toposort, on the list in attrNames order.
    fn visit<'a>(
        name: &'a str,
        names: &BTreeSet<&'a str>,
        drawn_from: &dyn Fn(&str) -> Vec<String>,
        done: &mut Vec<&'a str>,
    ) {
        if done.contains(&name) {
            return;
        }
        for from in drawn_from(name) {
            if let Some(from) = names.get(from.as_str()) {
                visit(from, names, drawn_from, done);
            }
        }
        if !done.contains(&name) {
            done.push(name);
        }
    }
    let mut done = Vec::new();
    for name in names {
        visit(name, names, drawn_from, &mut done);
    }
    done
}

/// SHA-256 of data, in hex, like Nix' builtins.hashString.
fn sha256_hex(data: &[u8]) -> String {
    const K: [u32; 64] = [
        0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4,
        0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe,
        0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f,
        0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
        0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
        0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
        0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116,
        0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
        0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
        0xc67178f2,
    ];
    let mut h: [u32; 8] = [
        0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab,
        0x5be0cd19,
    ];
    let mut message = data.to_vec();
    message.push(0x80);
    while message.len() % 64 != 56 {
        message.push(0);
    }
    message.extend_from_slice(&((data.len() as u64) * 8).to_be_bytes());
    for chunk in message.chunks(64) {
        let mut w = [0u32; 64];
        for i in 0..16 {
            w[i] = u32::from_be_bytes(chunk[4 * i..4 * i + 4].try_into().expect("4 bytes"));
        }
        for i in 16..64 {
            let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
            let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
            w[i] = w[i - 16]
                .wrapping_add(s0)
                .wrapping_add(w[i - 7])
                .wrapping_add(s1);
        }
        let mut v = h;
        for i in 0..64 {
            let s1 = v[4].rotate_right(6) ^ v[4].rotate_right(11) ^ v[4].rotate_right(25);
            let ch = (v[4] & v[5]) ^ (!v[4] & v[6]);
            let t1 = v[7]
                .wrapping_add(s1)
                .wrapping_add(ch)
                .wrapping_add(K[i])
                .wrapping_add(w[i]);
            let s0 = v[0].rotate_right(2) ^ v[0].rotate_right(13) ^ v[0].rotate_right(22);
            let maj = (v[0] & v[1]) ^ (v[0] & v[2]) ^ (v[1] & v[2]);
            let t2 = s0.wrapping_add(maj);
            v = [
                t1.wrapping_add(t2),
                v[0],
                v[1],
                v[2],
                v[3].wrapping_add(t1),
                v[4],
                v[5],
                v[6],
            ];
        }
        for (x, y) in h.iter_mut().zip(v) {
            *x = x.wrapping_add(y);
        }
    }
    h.iter().map(|x| format!("{x:08x}")).collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn sha256() {
        assert_eq!(
            sha256_hex(b""),
            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
        );
        assert_eq!(
            sha256_hex(b"abc"),
            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
        );
    }
}