geolith-cli 0.4.2

Rust vector tile generator — OSM + Overture Maps → protomaps PMTiles
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
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
#![allow(clippy::unwrap_used)] // tests and benches may unwrap (AGENTS.md).

//! The golden suite: the `geolith` binary on small committed inputs, each
//! output compared with a sha256 recorded before the crates were split.
//!
//! The suite drives the binary, not the library, so it keeps working while
//! code moves between crates. Every build runs on one thread and on the
//! default pool; both must give the same bytes before the hash is checked.
//!
//! `GEOLITH_GOLDEN_RECORD=1 cargo test --test golden -- --nocapture` prints
//! the hashes (and rewrites the help snapshots) instead of checking them.
//! Inputs: `tests/fixtures/golden/{tiles,search}` were written by the
//! fixture writers of `pipeline.rs` and `geocoding.rs` at `655f13e`.
//! Not covered here: `raster` (it needs an HTTP tile server) and the
//! dataset engine, which `dataset_golden.rs` and `dataset_areas_golden.rs`
//! already compare byte for byte.

use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};

use sha2::{Digest, Sha256};

const GEOLITH: &str = env!("CARGO_BIN_EXE_geolith");

/// `name -> sha256` of every golden output.
const GOLDENS: &[(&str, &str)] = &[
    (
        "tiles.pmtiles",
        "731277617de516a7a8ecdc95cb5c6acd5b45be3541166c57f919415fb0aca017",
    ),
    (
        "search.glx",
        "ee1d2c35476e9180a840c65e81c2b019a40adefa65411364d25b744b9513d610",
    ),
    (
        "search.tsv",
        "1d5e0a60f08a77d9ba29cc72a6f8bd7101b0705f5896931e2f90f0a7a77a1a8c",
    ),
    (
        "search.pelias.ndjson",
        "5877d1e54921eadc8dbafa537a6be20031ac1f99bdb73b7328824b04b154c5a1",
    ),
    (
        "search.photon.ndjson",
        "dbcfd173228449a7c01be7915456cb76868f8f6c36b166e4a61e21db987da671",
    ),
    (
        "routing.glx",
        "58a0f2587ec9a1949bdfbdcb23d76e11ffc55420a36d8ef1c10749ac72a5d322",
    ),
    (
        "routing-cch.glx",
        "1e25d918d024aaf7a9a6b4eedeaaa06bc204850e527f166ab3c591dc937fe2f3",
    ),
    (
        "terrain.pmtiles",
        "93413f837ec7959b5934afa610bf5e5b8c495a7cb46140670018bdcb2dc78444",
    ),
    (
        "splat-tiles",
        "863bfb91055130fcabb16d753eaf923c69d9f4b16efa29c4ff00ed646b99e7cb",
    ),
];

fn crate_dir() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
}

fn fixtures() -> PathBuf {
    crate_dir().join("tests/fixtures")
}

fn recording() -> bool {
    std::env::var_os("GEOLITH_GOLDEN_RECORD").is_some()
}

fn hex(bytes: &[u8]) -> String {
    let mut out = String::with_capacity(bytes.len() * 2);
    for byte in bytes {
        write!(out, "{byte:02x}").unwrap();
    }
    out
}

fn sha256(bytes: &[u8]) -> String {
    hex(&Sha256::digest(bytes))
}

/// Runs the binary and fails with its stderr when it does not exit 0.
fn run(args: &[String], threads: Option<&str>) -> Output {
    let mut command = Command::new(GEOLITH);
    command.args(args);
    if let Some(threads) = threads {
        command.env("RAYON_NUM_THREADS", threads);
    }
    let output = command.output().expect("binary runs");
    assert!(
        output.status.success(),
        "geolith {args:?} failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    output
}

fn strings(args: &[&str]) -> Vec<String> {
    args.iter().map(|arg| (*arg).to_string()).collect()
}

fn path_arg(path: &Path) -> String {
    path.to_str().expect("utf-8 path").to_string()
}

/// The sha256 of one output file, or of every file under a directory (path
/// and content, in path order).
fn output_hash(path: &Path) -> String {
    if path.is_dir() {
        let mut files = BTreeMap::new();
        let mut pending = vec![path.to_path_buf()];
        while let Some(dir) = pending.pop() {
            for entry in std::fs::read_dir(&dir).unwrap() {
                let entry = entry.unwrap().path();
                if entry.is_dir() {
                    pending.push(entry);
                } else {
                    let name = entry
                        .strip_prefix(path)
                        .unwrap()
                        .to_string_lossy()
                        .into_owned();
                    files.insert(name, sha256(&std::fs::read(&entry).unwrap()));
                }
            }
        }
        let mut listing = String::new();
        for (name, hash) in files {
            writeln!(listing, "{hash}  {name}").unwrap();
        }
        sha256(listing.as_bytes())
    } else {
        sha256(&std::fs::read(path).unwrap())
    }
}

/// Copies the output `from` to `to`: a file, or a directory with its tree.
/// `GEOLITH_GOLDEN_KEEP=<dir>` turns this on, so two builds of the binary
/// can be compared part by part.
fn keep_output(to: &Path, from: &Path) {
    if from.is_dir() {
        std::fs::create_dir_all(to).unwrap();
        for entry in std::fs::read_dir(from).unwrap() {
            let entry = entry.unwrap().path();
            keep_output(&to.join(entry.file_name().unwrap()), &entry);
        }
    } else {
        std::fs::create_dir_all(to.parent().unwrap()).unwrap();
        std::fs::copy(from, to).unwrap();
    }
}

/// Builds `name` twice (one thread, default pool) with `build`, which gets a
/// fresh directory and the thread setting and returns the output path. Both
/// builds must agree; the hash is then compared with the recorded one.
fn golden(name: &str, build: impl Fn(&Path, Option<&str>) -> PathBuf) {
    let mut hashes = Vec::new();
    for threads in [Some("1"), None] {
        let dir = tempfile::tempdir().unwrap();
        for scratch in ["scratch", "tmp"] {
            std::fs::create_dir_all(dir.path().join(scratch)).unwrap();
        }
        let out = build(dir.path(), threads);
        if out.is_file() {
            assert!(
                std::fs::metadata(&out).unwrap().len() > 100,
                "{name}: the output is empty"
            );
        }
        hashes.push(output_hash(&out));
        if let (Some(keep), Some("1")) = (std::env::var_os("GEOLITH_GOLDEN_KEEP"), threads) {
            keep_output(&PathBuf::from(keep).join(name), &out);
        }
    }
    assert_eq!(
        hashes[0], hashes[1],
        "{name}: one thread and the default pool give different bytes"
    );
    if recording() {
        println!("GOLDEN {name} {}", hashes[0]);
        return;
    }
    let expected = GOLDENS
        .iter()
        .find(|(known, _)| *known == name)
        .unwrap_or_else(|| panic!("no golden recorded for {name}"))
        .1;
    assert_eq!(hashes[0], expected, "{name}: output bytes changed");
}

#[test]
fn tiles_pmtiles() {
    let inputs = fixtures().join("golden/tiles");
    golden("tiles.pmtiles", |dir, threads| {
        let out = dir.join("out.pmtiles");
        run(
            &strings(&[
                "--data",
                &path_arg(&inputs.join("overture")),
                "--natural-earth",
                &path_arg(&inputs.join("ne.sqlite")),
                "--land-polygons",
                &path_arg(&inputs.join("land")),
                "--water-polygons",
                &path_arg(&inputs.join("water")),
                "--output",
                &path_arg(&out),
                "--tmpdir",
                &path_arg(&dir.join("tmp")),
                "--node-store",
                &path_arg(&dir.join("nodes.bin")),
                "--roads-source",
                "overture",
                "--no-conflate",
                "--bbox",
                "-0.3,51.4,0.3,51.6",
                "--max-zoom",
                "10",
            ]),
            threads,
        );
        out
    });
}

/// The search builds: one run per output format over the same inputs.
fn search(name: &str, format: &str, extension: &str) {
    let inputs = fixtures().join("golden/search/overture");
    let pbf = fixtures().join("golden/search/geocoding.osm.pbf");
    // A build with no --bbox covers the world, which touches Survey of India
    // land: it needs the outline (a tracked excerpt around Kashmir; the
    // fixture data lies in the Americas).
    let outline = Path::new(env!("CARGO_MANIFEST_DIR")).join(
        "../packages/routing-builder/tests/fixtures/routing/india-guard/soi-kashmir-excerpt.geojson",
    );
    golden(name, |dir, threads| {
        let out = dir.join(format!("search.{extension}"));
        run(
            &strings(&[
                "--data",
                &path_arg(&inputs),
                "--natural-earth",
                "/nonexistent/natural_earth.sqlite",
                "--land-polygons",
                "/nonexistent/land-polygons",
                "--water-polygons",
                "/nonexistent/water-polygons",
                "--output",
                &path_arg(&dir.join("unused.pmtiles")),
                "--output-format",
                "geocoding",
                "--geocoding-format",
                format,
                "--geocoding-output",
                &path_arg(&out),
                "--osm-pbf",
                &path_arg(&pbf),
                "--india-outline",
                &path_arg(&outline),
                "--tmpdir",
                &path_arg(&dir.join("scratch")),
            ]),
            threads,
        );
        out
    });
}

#[test]
fn search_glx() {
    search("search.glx", "glx", "glx");
}

#[test]
fn search_pg_copy() {
    search("search.tsv", "pg-copy", "tsv");
}

#[test]
fn search_pelias() {
    search("search.pelias.ndjson", "pelias", "ndjson");
}

#[test]
fn search_photon() {
    search("search.photon.ndjson", "photon", "ndjson");
}

fn routing(name: &str, extra: &[&str]) {
    let pbf =
        crate_dir().join("../packages/routing-builder/tests/fixtures/routing/halensee.osm.pbf");
    golden(name, |dir, threads| {
        let out = dir.join("routing.glx");
        let mut args = strings(&[
            "--output-format",
            "routing",
            "--osm-pbf",
            &path_arg(&pbf),
            "--routing-output",
            &path_arg(&out),
            "--tmpdir",
            &path_arg(&dir.join("scratch")),
        ]);
        args.extend(strings(extra));
        run(&args, threads);
        out
    });
}

#[test]
fn routing_glx() {
    routing("routing.glx", &[]);
}

#[test]
fn routing_glx_with_a_cch() {
    routing(
        "routing-cch.glx",
        &["--routing-cch", "auto,pedestrian,bicycle"],
    );
}

#[test]
fn terrain_pmtiles() {
    let dem = fixtures().join("inspect/f32-lzw-stripped.tif");
    golden("terrain.pmtiles", |dir, threads| {
        let out = dir.join("terrain.pmtiles");
        run(
            &strings(&[
                "terrain",
                "--dem",
                &path_arg(&dem),
                "--output",
                &path_arg(&out),
                "--min-zoom",
                "3",
                "--max-zoom",
                "4",
                "--tile-size",
                "256",
            ]),
            threads,
        );
        out
    });
}

/// The binary little-endian PLY of `tests/splat.rs`: `count` splats on a
/// diagonal, with the 14 float properties the converter reads.
fn ply(count: usize) -> Vec<u8> {
    const PROPERTIES: [&str; 14] = [
        "x", "y", "z", "f_dc_0", "f_dc_1", "f_dc_2", "opacity", "scale_0", "scale_1", "scale_2",
        "rot_0", "rot_1", "rot_2", "rot_3",
    ];
    let mut bytes = b"ply\nformat binary_little_endian 1.0\n".to_vec();
    writeln!(bytes, "element vertex {count}").unwrap();
    for property in PROPERTIES {
        writeln!(bytes, "property float {property}").unwrap();
    }
    bytes.extend_from_slice(b"end_header\n");
    for index in 0..count {
        let offset = index as f32;
        for value in [
            offset,
            offset * 0.5,
            offset * 0.25,
            0.4,
            0.5,
            0.6,
            1.1,
            -2.0,
            -2.1,
            -2.2,
            1.0,
            0.0,
            0.0,
            0.0,
        ] {
            bytes.extend_from_slice(&value.to_le_bytes());
        }
    }
    bytes
}

#[test]
fn splat_tiles() {
    golden("splat-tiles", |dir, threads| {
        let input = dir.join("scene.ply");
        std::fs::write(&input, ply(8)).unwrap();
        let out = dir.join("tileset");
        run(
            &strings(&[
                "splat-tiles",
                "--ply",
                &path_arg(&input),
                "--output",
                &path_arg(&out),
                "--longitude",
                "7.9797",
                "--latitude",
                "45.9756",
            ]),
            threads,
        );
        out
    });
}

/// What the binary prints for `args`, the contract of "existing flags keep
/// working".
fn help(args: &[&str]) -> String {
    let output = Command::new(GEOLITH)
        .args(args)
        .output()
        .expect("binary runs");
    assert!(output.status.success(), "geolith {args:?}: {output:?}");
    String::from_utf8(output.stdout).unwrap()
}

/// The verbs under `Commands:` of a help text.
fn commands(text: &str) -> Vec<String> {
    text.lines()
        .skip_while(|line| *line != "Commands:")
        .skip(1)
        .take_while(|line| line.starts_with("  "))
        .filter_map(|line| line.split_whitespace().next())
        .filter(|name| *name != "help")
        .map(str::to_string)
        .collect()
}

fn check_help(snapshots: &mut String, label: &str, args: &[&str]) {
    let text = help(args);
    writeln!(snapshots, "===== geolith {label}").unwrap();
    snapshots.push_str(&text);
    if !text.ends_with('\n') {
        snapshots.push('\n');
    }
}

#[test]
fn help_text_is_unchanged() {
    let mut snapshots = String::new();
    check_help(&mut snapshots, "--help", &["--help"]);
    for verb in [
        "terrain",
        "splat-tiles",
        "raster",
        "reconstruct",
        "dataset",
        "notices",
    ] {
        check_help(&mut snapshots, &format!("{verb} --help"), &[verb, "--help"]);
    }
    let dataset = help(&["dataset", "--help"]);
    for action in commands(&dataset) {
        check_help(
            &mut snapshots,
            &format!("dataset {action} --help"),
            &["dataset", &action, "--help"],
        );
    }
    let path = crate_dir().join("tests/fixtures/golden/help.txt");
    if recording() {
        std::fs::File::create(&path)
            .unwrap()
            .write_all(snapshots.as_bytes())
            .unwrap();
        println!("GOLDEN help.txt {}", sha256(snapshots.as_bytes()));
        return;
    }
    let expected = std::fs::read_to_string(&path).unwrap();
    assert!(
        expected == snapshots,
        "the help text of the binary changed; if it should, rerun with GEOLITH_GOLDEN_RECORD=1"
    );
}