Skip to main content

geolith_cli/
config.rs

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