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