Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / scripts / maps / gtfs_ingest / src / bin / resolve_feeds.rs

resolve_feeds.rs295 lines · 10.1 KiBRaw
1//! `resolve_feeds` — turn the Transitous registry plus transitland-atlas into a
2//! download plan whose feeds can carry MOTIS stop ids.
3//!
4//! Usage:
5//! resolve_feeds --registry DIR --atlas DIR --out PLAN.tsv
6//! [--region GLOB] [--max-feeds N] [--report]
7//!
8//! `--registry` is an extracted `public-transport/transitous` checkout (its
9//! `feeds/*.json`); `--atlas` is an extracted `transitland/transitland-atlas`
10//! (its `feeds/*.dmfr.json`). Both are **fetched by the shell**, not here: this
11//! crate has no HTTP stack and no dependencies at all, which is what lets it build
12//! and run offline.
13//!
14//! The plan is a TSV of `name<TAB>url<TAB>motis_prefix`, which
15//! `build_world_transit.ps1` downloads and then turns into the three-field manifest
16//! `manifest.rs::parse_feed_spec` reads.
17//!
18//! `--region` and `--max-feeds` are not conveniences. Resolving every `feeds/*.json`
19//! means hundreds of feeds and many GB of downloads, against today's 18.9 MB
20//! `world.transit` built from `.url` fields alone. Stage it: California first
21//! (known-good), then a few regions, then the world.
22
23use std::path::{Path, PathBuf};
24use std::process::ExitCode;
25
26use gtfs_ingest::json;
27use gtfs_ingest::registry::{self, Resolution};
28
29fn main() -> ExitCode {
30 let argv: Vec<String> = std::env::args().skip(1).collect();
31 let mut registry_dir: Option<PathBuf> = None;
32 let mut atlas_dir: Option<PathBuf> = None;
33 let mut out: Option<PathBuf> = None;
34 let mut region = "*".to_string();
35 let mut max_feeds = 0usize;
36 let mut report = false;
37
38 let mut i = 0;
39 while i < argv.len() {
40 let value = || argv.get(i + 1).cloned();
41 match argv[i].as_str() {
42 "--registry" => {
43 registry_dir = value().map(PathBuf::from);
44 i += 2;
45 }
46 "--atlas" => {
47 atlas_dir = value().map(PathBuf::from);
48 i += 2;
49 }
50 "--out" => {
51 out = value().map(PathBuf::from);
52 i += 2;
53 }
54 "--region" => {
55 match value() {
56 Some(v) => region = v,
57 None => return fail("--region needs a value"),
58 }
59 i += 2;
60 }
61 "--max-feeds" => {
62 let Some(raw) = value() else {
63 return fail("--max-feeds needs a value");
64 };
65 let Ok(n) = raw.parse() else {
66 return fail(&format!("--max-feeds wants a number, got '{raw}'"));
67 };
68 max_feeds = n;
69 i += 2;
70 }
71 "--report" => {
72 report = true;
73 i += 1;
74 }
75 "-h" | "--help" => {
76 usage();
77 return ExitCode::SUCCESS;
78 }
79 other => {
80 eprintln!("resolve_feeds: unexpected argument '{other}'");
81 usage();
82 return ExitCode::from(2);
83 }
84 }
85 }
86
87 let (Some(registry_dir), Some(atlas_dir), Some(out)) = (registry_dir, atlas_dir, out) else {
88 eprintln!("resolve_feeds: --registry, --atlas and --out are all required");
89 usage();
90 return ExitCode::from(2);
91 };
92
93 // --- index the atlas ---
94 let atlas_files = match json_files(&atlas_dir.join("feeds"), "*") {
95 Ok(f) => f,
96 Err(e) => return fail(&e),
97 };
98 let mut atlas_docs = Vec::with_capacity(atlas_files.len());
99 for path in &atlas_files {
100 match read_json(path) {
101 Ok(v) => atlas_docs.push(v),
102 // One malformed atlas document must not sink the whole resolution: the
103 // atlas is a third-party checkout of thousands of files.
104 Err(e) => eprintln!("resolve_feeds: skipping {}: {e}", path.display()),
105 }
106 }
107 let atlas = registry::index_atlas(&atlas_docs);
108 eprintln!(
109 "resolve_feeds: indexed {} atlas feed(s) from {} document(s)",
110 atlas.len(),
111 atlas_docs.len()
112 );
113
114 // --- resolve the matching region files ---
115 let region_files = match json_files(&registry_dir.join("feeds"), &region) {
116 Ok(f) => f,
117 Err(e) => return fail(&e),
118 };
119 if region_files.is_empty() {
120 return fail(&format!(
121 "no registry file matches --region '{region}' under {}/feeds",
122 registry_dir.display()
123 ));
124 }
125 eprintln!(
126 "resolve_feeds: {} registry file(s) match --region '{region}'",
127 region_files.len()
128 );
129
130 let mut resolution = Resolution::default();
131 for path in &region_files {
132 let name = path
133 .file_stem()
134 .map(|s| s.to_string_lossy().into_owned())
135 .unwrap_or_default();
136 match read_json(path) {
137 Ok(doc) => registry::resolve_region(&name, &doc, &atlas, &mut resolution),
138 Err(e) => eprintln!("resolve_feeds: skipping {}: {e}", path.display()),
139 }
140 }
141
142 let before = resolution.feeds.len();
143 registry::dedup(&mut resolution.feeds);
144 let deduped = before - resolution.feeds.len();
145 // Sorted before the cap, so --max-feeds takes a stable prefix rather than
146 // whichever feeds the filesystem happened to list first.
147 resolution.feeds.sort_by(|a, b| a.name.cmp(&b.name));
148 if max_feeds > 0 && resolution.feeds.len() > max_feeds {
149 eprintln!(
150 "resolve_feeds: capping {} feed(s) at --max-feeds {max_feeds}",
151 resolution.feeds.len()
152 );
153 resolution.feeds.truncate(max_feeds);
154 }
155
156 eprintln!(
157 "resolve_feeds: {} feed(s) from {} source(s); {} skipped, {} duplicate(s) dropped",
158 resolution.feeds.len(),
159 resolution.considered,
160 resolution.skipped.len(),
161 deduped
162 );
163 if report {
164 for f in &resolution.feeds {
165 eprintln!(" {:<28} via {:<50} {}", f.name, f.via, f.url);
166 }
167 for s in &resolution.skipped {
168 eprintln!(" SKIP {:<24} {}", s.name, s.why);
169 }
170 }
171 if resolution.feeds.is_empty() {
172 eprintln!("resolve_feeds: nothing resolved -- refusing to write an empty plan");
173 return ExitCode::FAILURE;
174 }
175
176 let mut text = String::new();
177 for f in &resolution.feeds {
178 text.push_str(&format!("{}\t{}\t{}\n", f.name, f.url, f.source));
179 }
180 if let Err(e) = std::fs::write(&out, text) {
181 return fail(&format!("cannot write {}: {e}", out.display()));
182 }
183 eprintln!("resolve_feeds: wrote {}", out.display());
184 ExitCode::SUCCESS
185}
186
187fn fail(msg: &str) -> ExitCode {
188 eprintln!("resolve_feeds: {msg}");
189 ExitCode::FAILURE
190}
191
192fn usage() {
193 eprintln!("usage: resolve_feeds --registry DIR --atlas DIR --out PLAN.tsv");
194 eprintln!(" [--region GLOB] [--max-feeds N] [--report]");
195}
196
197fn read_json(path: &Path) -> Result<json::Json, String> {
198 let text = std::fs::read_to_string(path).map_err(|e| e.to_string())?;
199 json::parse(&text)
200}
201
202/// `.json` files in `dir` whose stem matches `pattern`, sorted so a run is
203/// reproducible whatever order the filesystem lists them in.
204fn json_files(dir: &Path, pattern: &str) -> Result<Vec<PathBuf>, String> {
205 let entries = std::fs::read_dir(dir)
206 .map_err(|e| format!("cannot read {}: {e}", dir.display()))?;
207 let mut out = Vec::new();
208 for e in entries {
209 let path = e.map_err(|e| e.to_string())?.path();
210 if !path.is_file() {
211 continue;
212 }
213 let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
214 continue;
215 };
216 if !name.ends_with(".json") {
217 continue;
218 }
219 // Match on the stem, so `--region us-ca` finds `us-ca.json` and
220 // `--region 'us-*'` finds every US state. The atlas's `.dmfr.json` files
221 // have a `.dmfr` stem suffix, which `*` covers.
222 let stem = name.trim_end_matches(".json");
223 if glob_match(pattern, stem) {
224 out.push(path);
225 }
226 }
227 out.sort();
228 Ok(out)
229}
230
231/// Shell-style `*` and `?` matching, which is what `--region` promises.
232///
233/// Iterative with a backtrack point rather than recursive: a pattern of all stars
234/// against a long name is a well-known way to make the naive recursion take
235/// exponential time.
236fn glob_match(pattern: &str, text: &str) -> bool {
237 let p: Vec<char> = pattern.chars().collect();
238 let t: Vec<char> = text.chars().collect();
239 let (mut pi, mut ti) = (0usize, 0usize);
240 let mut star: Option<(usize, usize)> = None;
241 while ti < t.len() {
242 if pi < p.len() && (p[pi] == '?' || p[pi] == t[ti]) {
243 pi += 1;
244 ti += 1;
245 } else if pi < p.len() && p[pi] == '*' {
246 star = Some((pi, ti));
247 pi += 1;
248 } else if let Some((sp, st)) = star {
249 // Backtrack: let the star consume one more character.
250 pi = sp + 1;
251 ti = st + 1;
252 star = Some((sp, st + 1));
253 } else {
254 return false;
255 }
256 }
257 while pi < p.len() && p[pi] == '*' {
258 pi += 1;
259 }
260 pi == p.len()
261}
262
263#[cfg(test)]
264mod tests {
265 use super::*;
266
267 #[test]
268 fn glob_matches_the_forms_region_promises() {
269 assert!(glob_match("*", "us-ca"));
270 assert!(glob_match("us-ca", "us-ca"));
271 assert!(glob_match("us-*", "us-ca"));
272 assert!(glob_match("us-*", "us-ny"));
273 assert!(!glob_match("us-*", "de-by"));
274 assert!(glob_match("*-ca", "us-ca"));
275 assert!(glob_match("us-??", "us-ca"));
276 assert!(!glob_match("us-??", "us-cal"));
277 assert!(glob_match("*ca*", "us-ca-extra"));
278 assert!(!glob_match("us-ca", "us-cal"));
279 // An atlas document's stem keeps its `.dmfr`.
280 assert!(glob_match("*", "bayarea.dmfr"));
281 }
282
283 #[test]
284 fn glob_handles_the_pathological_patterns_without_hanging() {
285 // The case the naive recursion goes exponential on.
286 let text = "a".repeat(40) + "b";
287 assert!(!glob_match("*a*a*a*a*a*a*a*a*c", &text));
288 assert!(glob_match("*a*a*a*a*a*a*a*a*b", &text));
289 assert!(glob_match("**", "anything"));
290 assert!(glob_match("*", ""));
291 assert!(!glob_match("?", ""));
292 assert!(glob_match("", ""));
293 assert!(!glob_match("", "x"));
294 }
295}