Skip to main content

geolith_cli/
config.rs

1//! CLI configuration via clap.
2
3// The clap help text is golden-tested and names placeholders such as <output>.
4#![allow(rustdoc::invalid_html_tags)]
5
6use clap::{CommandFactory, Parser};
7use geolith_tiles_builder::TilesConfig;
8use std::path::{Path, PathBuf};
9
10/// A path flag that only some output formats read.
11#[non_exhaustive]
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum PathFlag {
14    /// `--data`.
15    Data,
16    /// `--natural-earth`.
17    NaturalEarth,
18    /// `--water-polygons`.
19    WaterPolygons,
20    /// `--land-polygons`.
21    LandPolygons,
22    /// `--output`.
23    Output,
24}
25
26impl PathFlag {
27    /// The flag as the usage line names it.
28    #[must_use]
29    pub const fn usage(self) -> &'static str {
30        match self {
31            Self::Data => "--data <DATA>",
32            Self::NaturalEarth => "--natural-earth <NATURAL_EARTH>",
33            Self::WaterPolygons => "--water-polygons <WATER_POLYGONS>",
34            Self::LandPolygons => "--land-polygons <LAND_POLYGONS>",
35            Self::Output => "--output <OUTPUT>",
36        }
37    }
38}
39
40pub use geolith_search_builder::PgIndexFlavor;
41
42/// Switches that reuse work an earlier run already did, flattened into
43/// [`Config`] so the flags stay `--node-cache` and `--resume`.
44#[derive(Debug, Parser)]
45pub struct RunReuse {
46    /// Enable node store caching between runs.
47    ///
48    /// When enabled (default), a sidecar `.meta.json` file is written
49    /// alongside the node store. On re-runs with the same PBF file,
50    /// the node collection pass is skipped entirely — reducing from
51    /// 2 PBF reads to 1.
52    #[arg(long, default_value = "true")]
53    pub node_cache: bool,
54
55    /// Resume from existing sort chunks in --tmpdir, skipping Phase 1.
56    ///
57    /// When set, the pipeline discovers chunk files from the temporary
58    /// directory and proceeds directly to merge + encode + write.
59    /// Requires --tmpdir to point at a directory with sort chunks from
60    /// a previous (interrupted) run.
61    ///
62    /// The build refuses, and says why, when the chunks are not all there:
63    /// phase 1 did not finish (no `phase1.complete` marker), a run is
64    /// missing, or an earlier merge with --reclaim-chunks began to consume
65    /// them. A merge from such a folder would leave tiles out of the archive.
66    #[arg(long, default_value = "false")]
67    pub resume: bool,
68}
69
70/// Rust vector tile generator — OSM + Overture Maps → protomaps `PMTiles`.
71#[derive(Debug, Parser)]
72#[command(
73    name = "geolith",
74    version,
75    long_version = crate::cli::LONG_VERSION,
76    about,
77    override_usage = "geolith --data <DATA> --natural-earth <NATURAL_EARTH> --water-polygons <WATER_POLYGONS> --land-polygons <LAND_POLYGONS> --output <OUTPUT>\n       geolith --output-format routing --osm-pbf <OSM_PBF> --routing-output <ROUTING_OUTPUT>"
78)]
79pub struct Config {
80    /// Path to Overture Maps data directory (hive-partitioned Parquet).
81    ///
82    /// Required by the tiles and geocoding formats.
83    #[arg(long)]
84    pub data: Option<PathBuf>,
85
86    /// Path to planet.osm.pbf file (optional — omit for Overture-only builds).
87    #[arg(long)]
88    pub osm_pbf: Option<PathBuf>,
89
90    /// Path to Natural Earth SQLite file.
91    ///
92    /// Required by the tiles format.
93    #[arg(long)]
94    pub natural_earth: Option<PathBuf>,
95
96    /// Path to water-polygons-split-3857 shapefile directory.
97    ///
98    /// Required by the tiles format.
99    #[arg(long)]
100    pub water_polygons: Option<PathBuf>,
101
102    /// Path to land-polygons-split-3857 shapefile directory.
103    ///
104    /// Required by the tiles format.
105    #[arg(long)]
106    pub land_polygons: Option<PathBuf>,
107
108    /// Path to India boundary `GeoJSON` file (optional).
109    #[arg(long)]
110    pub india_boundary: Option<PathBuf>,
111
112    /// India's outline on the Survey of India map (`GeoJSON` polygons, e.g.
113    /// `DataMeet`'s `india-composite.geojson`). Geocoding draws and resolves
114    /// India, Ladakh, Jammu and Kashmir, Pakistan and China with it;
115    /// required when the geocoding build covers India, and when the
116    /// --routing-admins source holds India (routing nodes inside it are in
117    /// India).
118    #[arg(long)]
119    pub india_outline: Option<PathBuf>,
120
121    /// Output `PMTiles` file path.
122    ///
123    /// Required by the tiles format, and by geocoding without
124    /// --geocoding-output.
125    #[arg(long, short)]
126    pub output: Option<PathBuf>,
127
128    /// Bounding box filter: `min_lon,min_lat,max_lon,max_lat`
129    #[arg(long, allow_hyphen_values = true)]
130    pub bbox: Option<String>,
131
132    /// Maximum zoom level (default: 15).
133    #[arg(long, default_value = "15")]
134    pub max_zoom: u8,
135
136    /// Number of threads (default: available parallelism).
137    #[arg(long)]
138    pub threads: Option<usize>,
139
140    /// Sort buffer size per thread in megabytes (0 = auto-detect).
141    ///
142    /// When set to 0 (the default), the chunk size is computed as
143    /// `min(2 GB, total_RAM / (3 × threads))`. Larger chunks produce
144    /// fewer files, speeding up the k-way merge phase.
145    #[arg(long, default_value = "0")]
146    pub chunk_size_mb: usize,
147
148    /// Directory for sort chunks and scratch files (default: the system
149    /// temporary directory). Point it at a volume with room: a planet build
150    /// writes about 200 GiB of chunks here.
151    #[arg(long)]
152    pub tmpdir: Option<PathBuf>,
153
154    /// Path to node coordinate store (mmap file for OSM processing).
155    #[arg(long)]
156    pub node_store: Option<PathBuf>,
157
158    /// Buildings data source: "osm", "overture", or "both".
159    #[arg(long, default_value = "both")]
160    pub buildings_source: String,
161
162    /// Places data source: "osm", "overture", or "both".
163    #[arg(long, default_value = "both")]
164    pub places_source: String,
165
166    /// Divisions data source: "overture" or "none".
167    #[arg(long, default_value = "overture")]
168    pub divisions_source: String,
169
170    /// Landcover data source: "overture" or "none".
171    #[arg(long, default_value = "overture")]
172    pub landcover_source: String,
173
174    /// Bathymetry data source: "overture" or "none".
175    #[arg(long, default_value = "overture")]
176    pub bathymetry_source: String,
177
178    /// Roads data source: "osm", "overture", or "both".
179    #[arg(long, default_value = "both")]
180    pub roads_source: String,
181
182    /// POIs data source: "osm", "overture", or "both".
183    #[arg(long, default_value = "both")]
184    pub pois_source: String,
185
186    /// Water data source: "osm", "overture", or "both".
187    #[arg(long, default_value = "both")]
188    pub water_source: String,
189
190    /// Landuse data source: "osm", "overture", or "both".
191    #[arg(long, default_value = "both")]
192    pub landuse_source: String,
193
194    /// Enable node store caching between runs.
195    ///
196    /// When enabled (default), a sidecar `.meta.json` file is written
197    /// alongside the node store. On re-runs with the same PBF file,
198    /// the node collection pass is skipped entirely — reducing from
199    /// 2 PBF reads to 1.
200    #[command(flatten)]
201    pub reuse: RunReuse,
202
203    /// Output format: "tiles" (default), "geocoding" or "routing".
204    ///
205    /// "routing" builds the routing graph from --osm-pbf and writes a
206    /// `.glx` file with one routing part to --routing-output. Any other
207    /// value fails with an error.
208    #[arg(long, default_value = "tiles")]
209    pub output_format: String,
210
211    /// Tile encoding format: "mlt" (default) or "mvt".
212    ///
213    /// MLT (`MapLibre` Tiles) uses columnar encoding with built-in compression,
214    /// producing 50–80% smaller tiles. MVT uses protobuf + gzip.
215    #[arg(long, default_value = "mvt")]
216    pub tile_format: String,
217
218    /// Directory containing GERS bridge Parquet files for OSM deduplication.
219    ///
220    /// When provided, all `.parquet` files in this directory (recursively) are
221    /// loaded into the deduplication index. If not set, geolith automatically
222    /// looks for a `gers-bridge/` sibling directory next to `--data`.
223    ///
224    /// Expected structure:
225    /// ```text
226    /// gers-bridge/
227    /// ├── buildings/*.zstd.parquet
228    /// ├── transportation/*.zstd.parquet
229    /// └── divisions/*.zstd.parquet
230    /// ```
231    #[arg(long)]
232    pub bridge_dir: Option<PathBuf>,
233
234    /// Disable GERS conflation even when bridge files are found.
235    ///
236    /// By default, conflation is enabled automatically when bridge files
237    /// are discovered. Set this flag to skip deduplication.
238    #[arg(long, default_value = "false")]
239    pub no_conflate: bool,
240
241    /// Paths to individual GERS bridge Parquet files (can be specified multiple times).
242    ///
243    /// Alternative to `--bridge-dir` for specifying individual bridge files.
244    /// These are loaded in addition to any files found via `--bridge-dir`.
245    #[arg(long)]
246    pub bridge_files: Vec<PathBuf>,
247
248    /// Geocoding output format: "glx" (default: one `.glx` index file that
249    /// geolith search serves), "pg-copy" (rows and schema for your own
250    /// Postgres), "photon", or "pelias".
251    ///
252    /// Only used when --output-format geocoding.
253    #[arg(long, default_value = "glx")]
254    pub geocoding_format: String,
255
256    /// Text index emitted in the companion DDL for the pg-copy format.
257    ///
258    /// `tin` (default) needs the `tin` extension, available on `PlanetScale`
259    /// Postgres and Neki. `gin` needs no extension and runs anywhere.
260    #[arg(long, value_enum, default_value_t = PgIndexFlavor::Tin)]
261    pub pg_index_flavor: PgIndexFlavor,
262
263    /// Output path for geocoding data.
264    ///
265    /// Only used when --output-format geocoding. Defaults to <output>.tsv for
266    /// pg-copy, <output>.ndjson for photon and pelias, and <output>.glx for glx.
267    #[arg(long)]
268    pub geocoding_output: Option<PathBuf>,
269
270    /// Nominatim's Wikipedia importance file, `wikimedia-importance.csv.gz`
271    /// from <https://nominatim.org/data/>. An OSM place with a `wikidata`
272    /// tag takes the importance of its Wikipedia article, so "London" finds
273    /// the city before a shop named after it. Without the file, a place
274    /// takes a default from its type.
275    ///
276    /// Only used when --output-format geocoding.
277    #[arg(long)]
278    pub wikimedia_importance: Option<PathBuf>,
279
280    /// Output path for the routing `.glx` file.
281    ///
282    /// Only used when --output-format routing.
283    #[arg(long)]
284    pub routing_output: Option<PathBuf>,
285
286    /// Directory to write the auto metric to as a turn-expanded graph
287    /// (`RoutingKit` vectors: `first_out`, `head`, `travel_time`, `latitude`,
288    /// `longitude` and the `vertex_*` mapping), the input of the
289    /// customizable contraction hierarchy.
290    ///
291    /// Only used when --output-format routing.
292    #[arg(long)]
293    pub routing_metric_out: Option<PathBuf>,
294
295    /// Costing profiles to build a customizable contraction hierarchy for,
296    /// comma-separated (`auto`, `pedestrian`, `bicycle`). Each becomes its
297    /// own set of sections in the routing part (glx spec v1, 10.5).
298    ///
299    /// Only used when --output-format routing.
300    #[arg(long, value_delimiter = ',')]
301    pub routing_cch: Vec<String>,
302
303    /// Directory of historical speeds in the reference CSV format: one file
304    /// per graph tile named by tile path (`2/000/753/554.csv`), rows
305    /// `edge_graph_id,free_flow_kph,constrained_kph,encoded_dct`. Fills the
306    /// tiles' predicted-speeds section and flow speeds exactly as
307    /// `valhalla_add_predicted_traffic` does.
308    ///
309    /// Only used when --output-format routing.
310    #[arg(long)]
311    pub routing_predicted_speeds: Option<PathBuf>,
312
313    /// Default speed table in the reference `default_speeds_config` format
314    /// (`OpenStreetMapSpeeds` `default_speeds.json`): km/h per region,
315    /// rural/suburban/urban density band, road class, link, roundabout and
316    /// service use. A configured speed replaces the heuristic speed of every
317    /// vehicular non-ferry edge, a tagged `maxspeed` included, exactly as
318    /// the reference `SpeedAssigner` does.
319    ///
320    /// Only used when --output-format routing.
321    #[arg(long)]
322    pub routing_default_speeds: Option<PathBuf>,
323
324    /// OSM PBF whose admin boundary relations give each routing node its
325    /// country and state, side of the road and country access rules, and
326    /// each edge its row of --routing-default-speeds: the reference's admin
327    /// database (`valhalla_build_admins`), read from relations with
328    /// `type=boundary` at `admin_level` 2 and 4 (3 and 6 in a few countries)
329    /// and their member ways and nodes. May be the --osm-pbf itself or a
330    /// file of boundaries only. Nodes inside India take India as drawn by
331    /// the Survey of India: --india-outline is required when the source
332    /// holds India.
333    ///
334    /// Only used when --output-format routing.
335    #[arg(long)]
336    pub routing_admins: Option<PathBuf>,
337
338    /// Time zone areas for the routing nodes: the `.shp` of a
339    /// timezone-boundary-builder shapefile release
340    /// (`combined-shapefile-with-oceans-1970.shp`, attribute `tzid`), as
341    /// the reference's `valhalla_build_timezones` imports it. Each node
342    /// takes the index of the zone that holds it, which the router uses for
343    /// local time. Without it every node has no time zone and routes at a
344    /// `date_time` run in UTC.
345    ///
346    /// Only used when --output-format routing.
347    #[arg(long)]
348    pub routing_timezones: Option<PathBuf>,
349
350    /// Delete each Overture Parquet file once its features are safely in the
351    /// sort chunks.
352    ///
353    /// Phase 1 streams every source exactly once and Phases 2-4 read only the
354    /// chunks, so the source tree can be released progressively rather than
355    /// held alongside it. That keeps the peak footprint near the release size
356    /// instead of `release + chunks`, which is the difference between fitting
357    /// on a disk-constrained machine and hitting ENOSPC mid-read.
358    ///
359    /// Only Overture inputs are affected, and only after both the read and the
360    /// chunk flush for a file succeed. Re-download the release to restore.
361    #[arg(long, default_value = "false")]
362    pub reclaim_source_after_read: bool,
363
364    /// Give the disk space of each sort chunk back while the merge reads it.
365    ///
366    /// The merge reads every chunk once, front to back. With this flag it
367    /// frees each block of a chunk as soon as the block is read and deletes
368    /// the chunk at its end, so the chunks shrink while the archive grows and
369    /// the two do not peak together. On a planet build that is the difference
370    /// between `chunks + archive` and the larger of the two.
371    ///
372    /// A build that stops during the merge cannot `--resume` from its chunks
373    /// afterwards: they are gone as far as they were read. The merge writes a
374    /// `merge.reclaiming` marker into --tmpdir before it reads the first
375    /// chunk, and `--resume` stops with an error that names the folder when it
376    /// finds the marker. Delete the folder and build again from phase 1.
377    #[arg(long, default_value = "false")]
378    pub reclaim_chunks: bool,
379
380    /// Skip the check of free disk space before phase 1.
381    ///
382    /// Without this flag the tile build estimates the disk it needs from the
383    /// size of the inputs and stops at once, naming the GiB, when the volume
384    /// of --tmpdir, --output or --node-store is short.
385    #[arg(long, default_value = "false")]
386    pub no_disk_check: bool,
387}
388
389impl Config {
390    /// Parse CLI arguments, exiting with a usage error when a flag the
391    /// output format reads is missing.
392    pub fn parse_args() -> Self {
393        let config = Self::parse();
394        if let Err(e) = config.check_required() {
395            e.exit();
396        }
397        config
398    }
399
400    /// The value of a path flag.
401    #[must_use]
402    pub fn path(&self, flag: PathFlag) -> Option<&Path> {
403        match flag {
404            PathFlag::Data => self.data.as_deref(),
405            PathFlag::NaturalEarth => self.natural_earth.as_deref(),
406            PathFlag::WaterPolygons => self.water_polygons.as_deref(),
407            PathFlag::LandPolygons => self.land_polygons.as_deref(),
408            PathFlag::Output => self.output.as_deref(),
409        }
410    }
411
412    /// The path flags the output format reads, in usage order: all five
413    /// for tiles (and an unknown format, which fails later), `--data` and
414    /// `--output` for geocoding (`--output` only without
415    /// `--geocoding-output`), none for routing.
416    #[must_use]
417    pub fn required_flags(&self) -> Vec<PathFlag> {
418        match self.output_format.as_str() {
419            "routing" => Vec::new(),
420            "geocoding" => {
421                let mut flags = vec![PathFlag::Data];
422                if self.geocoding_output.is_none() {
423                    flags.push(PathFlag::Output);
424                }
425                flags
426            }
427            _ => vec![
428                PathFlag::Data,
429                PathFlag::NaturalEarth,
430                PathFlag::WaterPolygons,
431                PathFlag::LandPolygons,
432                PathFlag::Output,
433            ],
434        }
435    }
436
437    /// A usage error naming the flags in `missing`, worded as the
438    /// argument parser words a missing required argument.
439    fn missing_error(missing: &[PathFlag]) -> clap::Error {
440        let mut msg = String::from("the following required arguments were not provided:");
441        for f in missing {
442            msg.push_str("\n  ");
443            msg.push_str(f.usage());
444        }
445        Self::command().error(clap::error::ErrorKind::MissingRequiredArgument, msg)
446    }
447
448    /// Check that every path flag the output format reads is present.
449    ///
450    /// # Errors
451    ///
452    /// A usage error naming each missing flag.
453    pub fn check_required(&self) -> Result<(), clap::Error> {
454        let missing: Vec<PathFlag> = self
455            .required_flags()
456            .into_iter()
457            .filter(|&f| self.path(f).is_none())
458            .collect();
459        if missing.is_empty() {
460            Ok(())
461        } else {
462            Err(Self::missing_error(&missing))
463        }
464    }
465
466    /// The value of a path flag the running format needs.
467    ///
468    /// # Errors
469    ///
470    /// The usage error for a missing required flag.
471    pub fn required_path(&self, flag: PathFlag) -> Result<&Path, clap::Error> {
472        self.path(flag).ok_or_else(|| Self::missing_error(&[flag]))
473    }
474
475    /// Check if India boundary fix is enabled.
476    pub const fn has_india_boundary(&self) -> bool {
477        self.india_boundary.is_some()
478    }
479
480    /// Check if a source should include OSM data.
481    pub fn uses_osm(&self, source: &str) -> bool {
482        self.tiles_view().uses_osm(source)
483    }
484
485    /// Check if a source should include Overture data.
486    pub fn uses_overture(&self, source: &str) -> bool {
487        self.tiles_view().uses_overture(source)
488    }
489
490    /// Whether Overture data should be included for a given layer.
491    ///
492    /// Layers without a dedicated source flag always include Overture data.
493    pub fn overture_enabled(&self, layer: crate::layers::Layer) -> bool {
494        self.tiles_view().overture_enabled(layer)
495    }
496
497    /// Whether OSM data should be included for a given layer.
498    ///
499    /// Returns `false` for all layers when `--osm-pbf` is not provided.
500    pub fn osm_enabled(&self, layer: crate::layers::Layer) -> bool {
501        self.tiles_view().osm_enabled(layer)
502    }
503
504    /// Compute the effective sort-buffer size in bytes per thread.
505    pub fn effective_chunk_bytes(&self) -> usize {
506        self.tiles_view().effective_chunk_bytes()
507    }
508
509    /// Discover all GERS bridge Parquet files for OSM deduplication.
510    ///
511    /// Resolution order: explicit `--bridge-files`, then `--bridge-dir`,
512    /// then the `gers-bridge/` sibling of `--data`.
513    #[must_use]
514    pub fn discover_bridge_files(&self) -> Vec<PathBuf> {
515        self.tiles_view().discover_bridge_files()
516    }
517
518    /// The tile build this invocation describes.
519    ///
520    /// # Errors
521    ///
522    /// A usage error naming each path flag the tile build needs and lacks.
523    pub fn tiles(&self) -> Result<TilesConfig, clap::Error> {
524        let missing: Vec<PathFlag> = [
525            PathFlag::Data,
526            PathFlag::NaturalEarth,
527            PathFlag::WaterPolygons,
528            PathFlag::LandPolygons,
529            PathFlag::Output,
530        ]
531        .into_iter()
532        .filter(|&f| self.path(f).is_none())
533        .collect();
534        if missing.is_empty() {
535            Ok(self.tiles_view())
536        } else {
537            Err(Self::missing_error(&missing))
538        }
539    }
540
541    /// The tile build with empty paths where a flag is missing: enough for
542    /// the questions that do not read a path.
543    fn tiles_view(&self) -> TilesConfig {
544        let path = |flag| self.path(flag).map(Path::to_path_buf).unwrap_or_default();
545        let mut tiles = TilesConfig::new(
546            path(PathFlag::Data),
547            path(PathFlag::NaturalEarth),
548            path(PathFlag::WaterPolygons),
549            path(PathFlag::LandPolygons),
550            path(PathFlag::Output),
551        );
552        tiles.osm_pbf.clone_from(&self.osm_pbf);
553        tiles.india_boundary.clone_from(&self.india_boundary);
554        tiles.bbox.clone_from(&self.bbox);
555        tiles.max_zoom = self.max_zoom;
556        tiles.threads = self.threads;
557        tiles.chunk_size_mb = self.chunk_size_mb;
558        tiles.tmpdir.clone_from(&self.tmpdir);
559        tiles.node_store.clone_from(&self.node_store);
560        tiles.buildings_source.clone_from(&self.buildings_source);
561        tiles.places_source.clone_from(&self.places_source);
562        tiles.divisions_source.clone_from(&self.divisions_source);
563        tiles.landcover_source.clone_from(&self.landcover_source);
564        tiles.bathymetry_source.clone_from(&self.bathymetry_source);
565        tiles.roads_source.clone_from(&self.roads_source);
566        tiles.pois_source.clone_from(&self.pois_source);
567        tiles.water_source.clone_from(&self.water_source);
568        tiles.landuse_source.clone_from(&self.landuse_source);
569        tiles.reuse = geolith_tiles_builder::Reuse::new(self.reuse.node_cache, self.reuse.resume);
570        tiles.tile_format.clone_from(&self.tile_format);
571        tiles.bridge_dir.clone_from(&self.bridge_dir);
572        tiles.no_conflate = self.no_conflate;
573        tiles.bridge_files.clone_from(&self.bridge_files);
574        tiles.reclaim_source_after_read = self.reclaim_source_after_read;
575        tiles.reclaim_chunks = self.reclaim_chunks;
576        tiles.disk_check = !self.no_disk_check;
577        tiles
578    }
579}
580
581#[cfg(test)]
582mod tests {
583    use super::*;
584
585    #[test]
586    fn uses_osm_for_both() {
587        let config = Config::try_parse_from([
588            "geolith",
589            "--data",
590            "/tmp/data",
591            "--osm-pbf",
592            "/tmp/planet.osm.pbf",
593            "--natural-earth",
594            "/tmp/ne.sqlite",
595            "--water-polygons",
596            "/tmp/water",
597            "--land-polygons",
598            "/tmp/land",
599            "--output",
600            "/tmp/out.pmtiles",
601        ])
602        .expect("parse should succeed");
603
604        assert!(config.uses_osm("both"));
605        assert!(config.uses_osm("osm"));
606        assert!(!config.uses_osm("overture"));
607        assert!(config.uses_overture("both"));
608        assert!(config.uses_overture("overture"));
609        assert!(!config.uses_overture("osm"));
610        assert!(!config.has_india_boundary());
611    }
612
613    #[test]
614    fn default_source_values() {
615        let config = Config::try_parse_from([
616            "geolith",
617            "--data",
618            "/tmp/data",
619            "--osm-pbf",
620            "/tmp/planet.osm.pbf",
621            "--natural-earth",
622            "/tmp/ne.sqlite",
623            "--water-polygons",
624            "/tmp/water",
625            "--land-polygons",
626            "/tmp/land",
627            "--output",
628            "/tmp/out.pmtiles",
629        ])
630        .expect("parse should succeed");
631
632        assert_eq!(config.buildings_source, "both");
633        assert_eq!(config.places_source, "both");
634        assert_eq!(config.divisions_source, "overture");
635        assert_eq!(config.landcover_source, "overture");
636        assert_eq!(config.bathymetry_source, "overture");
637        assert_eq!(config.roads_source, "both");
638        assert_eq!(config.pois_source, "both");
639        assert_eq!(config.water_source, "both");
640        assert_eq!(config.landuse_source, "both");
641        assert_eq!(config.max_zoom, 15);
642    }
643
644    #[test]
645    fn overture_enabled_respects_source_flags() {
646        let config = Config::try_parse_from([
647            "geolith",
648            "--data",
649            "/tmp/data",
650            "--osm-pbf",
651            "/tmp/planet.osm.pbf",
652            "--natural-earth",
653            "/tmp/ne.sqlite",
654            "--water-polygons",
655            "/tmp/water",
656            "--land-polygons",
657            "/tmp/land",
658            "--output",
659            "/tmp/out.pmtiles",
660            "--buildings-source",
661            "osm",
662            "--roads-source",
663            "overture",
664            "--landcover-source",
665            "none",
666        ])
667        .expect("parse should succeed");
668
669        use crate::layers::Layer;
670
671        assert!(!config.overture_enabled(Layer::Buildings));
672        assert!(config.overture_enabled(Layer::Roads));
673        assert!(!config.overture_enabled(Layer::Landcover));
674        assert!(config.overture_enabled(Layer::Earth));
675        assert!(config.overture_enabled(Layer::Water));
676        assert!(config.overture_enabled(Layer::Pois));
677        assert!(config.overture_enabled(Layer::Landuse));
678    }
679    #[test]
680    fn osm_enabled_respects_source_flags() {
681        let config = Config::try_parse_from([
682            "geolith",
683            "--data",
684            "/tmp/data",
685            "--osm-pbf",
686            "/tmp/planet.osm.pbf",
687            "--natural-earth",
688            "/tmp/ne.sqlite",
689            "--water-polygons",
690            "/tmp/water",
691            "--land-polygons",
692            "/tmp/land",
693            "--output",
694            "/tmp/out.pmtiles",
695            "--buildings-source",
696            "overture",
697            "--roads-source",
698            "osm",
699        ])
700        .expect("parse should succeed");
701
702        use crate::layers::Layer;
703
704        assert!(!config.osm_enabled(Layer::Buildings));
705        assert!(config.osm_enabled(Layer::Roads));
706        assert!(config.osm_enabled(Layer::Earth));
707        assert!(config.osm_enabled(Layer::Water));
708        assert!(config.osm_enabled(Layer::Landuse));
709        assert!(config.osm_enabled(Layer::Pois));
710        assert!(config.osm_enabled(Layer::Places));
711    }
712
713    #[test]
714    fn osm_pbf_omitted_disables_all_osm_layers() {
715        let config = Config::try_parse_from([
716            "geolith",
717            "--data",
718            "/tmp/data",
719            "--natural-earth",
720            "/tmp/ne.sqlite",
721            "--water-polygons",
722            "/tmp/water",
723            "--land-polygons",
724            "/tmp/land",
725            "--output",
726            "/tmp/out.pmtiles",
727        ])
728        .expect("parse should succeed without --osm-pbf");
729
730        use crate::layers::Layer;
731
732        assert!(config.osm_pbf.is_none());
733        assert!(!config.osm_enabled(Layer::Buildings));
734        assert!(!config.osm_enabled(Layer::Roads));
735        assert!(!config.osm_enabled(Layer::Earth));
736        assert!(!config.osm_enabled(Layer::Water));
737        assert!(!config.osm_enabled(Layer::Landuse));
738        assert!(!config.osm_enabled(Layer::Pois));
739        assert!(!config.osm_enabled(Layer::Places));
740        assert!(!config.osm_enabled(Layer::Transit));
741        assert!(!config.osm_enabled(Layer::Boundaries));
742
743        assert!(config.overture_enabled(Layer::Buildings));
744        assert!(config.overture_enabled(Layer::Roads));
745        assert!(config.overture_enabled(Layer::Water));
746        assert!(config.overture_enabled(Layer::Landuse));
747    }
748
749    #[test]
750    fn default_output_format_is_tiles() {
751        let config = Config::try_parse_from([
752            "geolith",
753            "--data",
754            "/tmp/data",
755            "--osm-pbf",
756            "/tmp/planet.osm.pbf",
757            "--natural-earth",
758            "/tmp/ne.sqlite",
759            "--water-polygons",
760            "/tmp/water",
761            "--land-polygons",
762            "/tmp/land",
763            "--output",
764            "/tmp/out.pmtiles",
765        ])
766        .expect("parse");
767        assert_eq!(config.output_format, "tiles");
768    }
769
770    #[test]
771    fn output_format_flag_parsed() {
772        let config = Config::try_parse_from([
773            "geolith",
774            "--data",
775            "/tmp/data",
776            "--osm-pbf",
777            "/tmp/planet.osm.pbf",
778            "--natural-earth",
779            "/tmp/ne.sqlite",
780            "--water-polygons",
781            "/tmp/water",
782            "--land-polygons",
783            "/tmp/land",
784            "--output",
785            "/tmp/out.pmtiles",
786            "--output-format",
787            "routing",
788        ])
789        .expect("parse");
790        assert_eq!(config.output_format, "routing");
791    }
792
793    /// The `--schema` flag is gone: tiles always follow the protomaps
794    /// basemap schema, so an old script that still passes it fails loudly.
795    #[test]
796    fn schema_flag_is_refused() {
797        let err = Config::try_parse_from([
798            "geolith",
799            "--data",
800            "/tmp/data",
801            "--natural-earth",
802            "/tmp/ne.sqlite",
803            "--water-polygons",
804            "/tmp/water",
805            "--land-polygons",
806            "/tmp/land",
807            "--output",
808            "/tmp/out.pmtiles",
809            "--schema",
810            "protomaps",
811        ])
812        .expect_err("--schema is no longer a flag");
813        assert_eq!(err.kind(), clap::error::ErrorKind::UnknownArgument);
814    }
815
816    #[test]
817    fn osrm_output_is_no_longer_a_flag() {
818        let err = Config::try_parse_from([
819            "geolith",
820            "--data",
821            "/tmp/data",
822            "--natural-earth",
823            "/tmp/ne.sqlite",
824            "--water-polygons",
825            "/tmp/water",
826            "--land-polygons",
827            "/tmp/land",
828            "--output",
829            "/tmp/out.pmtiles",
830            "--osrm-output",
831            "/tmp/routing.osrm.tar",
832        ])
833        .expect_err("the OSRM writer was removed");
834        assert_eq!(err.kind(), clap::error::ErrorKind::UnknownArgument);
835    }
836}