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