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

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

resolve_feeds.rs289 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!("resolve_feeds: {} registry file(s) match --region '{region}'", region_files.len());
126
127 let mut resolution = Resolution::default();
128 for path in &region_files {
129 let name = path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
130 match read_json(path) {
131 Ok(doc) => registry::resolve_region(&name, &doc, &atlas, &mut resolution),
132 Err(e) => eprintln!("resolve_feeds: skipping {}: {e}", path.display()),
133 }
134 }
135
136 let before = resolution.feeds.len();
137 registry::dedup(&mut resolution.feeds);
138 let deduped = before - resolution.feeds.len();
139 // Sorted before the cap, so --max-feeds takes a stable prefix rather than
140 // whichever feeds the filesystem happened to list first.
141 resolution.feeds.sort_by(|a, b| a.name.cmp(&b.name));
142 if max_feeds > 0 && resolution.feeds.len() > max_feeds {
143 eprintln!(
144 "resolve_feeds: capping {} feed(s) at --max-feeds {max_feeds}",
145 resolution.feeds.len()
146 );
147 resolution.feeds.truncate(max_feeds);
148 }
149
150 eprintln!(
151 "resolve_feeds: {} feed(s) from {} source(s); {} skipped, {} duplicate(s) dropped",
152 resolution.feeds.len(),
153 resolution.considered,
154 resolution.skipped.len(),
155 deduped
156 );
157 if report {
158 for f in &resolution.feeds {
159 eprintln!(" {:<28} via {:<50} {}", f.name, f.via, f.url);
160 }
161 for s in &resolution.skipped {
162 eprintln!(" SKIP {:<24} {}", s.name, s.why);
163 }
164 }
165 if resolution.feeds.is_empty() {
166 eprintln!("resolve_feeds: nothing resolved -- refusing to write an empty plan");
167 return ExitCode::FAILURE;
168 }
169
170 let mut text = String::new();
171 for f in &resolution.feeds {
172 text.push_str(&format!("{}\t{}\t{}\n", f.name, f.url, f.source));
173 }
174 if let Err(e) = std::fs::write(&out, text) {
175 return fail(&format!("cannot write {}: {e}", out.display()));
176 }
177 eprintln!("resolve_feeds: wrote {}", out.display());
178 ExitCode::SUCCESS
179}
180
181fn fail(msg: &str) -> ExitCode {
182 eprintln!("resolve_feeds: {msg}");
183 ExitCode::FAILURE
184}
185
186fn usage() {
187 eprintln!("usage: resolve_feeds --registry DIR --atlas DIR --out PLAN.tsv");
188 eprintln!(" [--region GLOB] [--max-feeds N] [--report]");
189}
190
191fn read_json(path: &Path) -> Result<json::Json, String> {
192 let text = std::fs::read_to_string(path).map_err(|e| e.to_string())?;
193 json::parse(&text)
194}
195
196/// `.json` files in `dir` whose stem matches `pattern`, sorted so a run is
197/// reproducible whatever order the filesystem lists them in.
198fn json_files(dir: &Path, pattern: &str) -> Result<Vec<PathBuf>, String> {
199 let entries =
200 std::fs::read_dir(dir).map_err(|e| format!("cannot read {}: {e}", dir.display()))?;
201 let mut out = Vec::new();
202 for e in entries {
203 let path = e.map_err(|e| e.to_string())?.path();
204 if !path.is_file() {
205 continue;
206 }
207 let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
208 continue;
209 };
210 if !name.ends_with(".json") {
211 continue;
212 }
213 // Match on the stem, so `--region us-ca` finds `us-ca.json` and
214 // `--region 'us-*'` finds every US state. The atlas's `.dmfr.json` files
215 // have a `.dmfr` stem suffix, which `*` covers.
216 let stem = name.trim_end_matches(".json");
217 if glob_match(pattern, stem) {
218 out.push(path);
219 }
220 }
221 out.sort();
222 Ok(out)
223}
224
225/// Shell-style `*` and `?` matching, which is what `--region` promises.
226///
227/// Iterative with a backtrack point rather than recursive: a pattern of all stars
228/// against a long name is a well-known way to make the naive recursion take
229/// exponential time.
230fn glob_match(pattern: &str, text: &str) -> bool {
231 let p: Vec<char> = pattern.chars().collect();
232 let t: Vec<char> = text.chars().collect();
233 let (mut pi, mut ti) = (0usize, 0usize);
234 let mut star: Option<(usize, usize)> = None;
235 while ti < t.len() {
236 if pi < p.len() && (p[pi] == '?' || p[pi] == t[ti]) {
237 pi += 1;
238 ti += 1;
239 } else if pi < p.len() && p[pi] == '*' {
240 star = Some((pi, ti));
241 pi += 1;
242 } else if let Some((sp, st)) = star {
243 // Backtrack: let the star consume one more character.
244 pi = sp + 1;
245 ti = st + 1;
246 star = Some((sp, st + 1));
247 } else {
248 return false;
249 }
250 }
251 while pi < p.len() && p[pi] == '*' {
252 pi += 1;
253 }
254 pi == p.len()
255}
256
257#[cfg(test)]
258mod tests {
259 use super::*;
260
261 #[test]
262 fn glob_matches_the_forms_region_promises() {
263 assert!(glob_match("*", "us-ca"));
264 assert!(glob_match("us-ca", "us-ca"));
265 assert!(glob_match("us-*", "us-ca"));
266 assert!(glob_match("us-*", "us-ny"));
267 assert!(!glob_match("us-*", "de-by"));
268 assert!(glob_match("*-ca", "us-ca"));
269 assert!(glob_match("us-??", "us-ca"));
270 assert!(!glob_match("us-??", "us-cal"));
271 assert!(glob_match("*ca*", "us-ca-extra"));
272 assert!(!glob_match("us-ca", "us-cal"));
273 // An atlas document's stem keeps its `.dmfr`.
274 assert!(glob_match("*", "bayarea.dmfr"));
275 }
276
277 #[test]
278 fn glob_handles_the_pathological_patterns_without_hanging() {
279 // The case the naive recursion goes exponential on.
280 let text = "a".repeat(40) + "b";
281 assert!(!glob_match("*a*a*a*a*a*a*a*a*c", &text));
282 assert!(glob_match("*a*a*a*a*a*a*a*a*b", &text));
283 assert!(glob_match("**", "anything"));
284 assert!(glob_match("*", ""));
285 assert!(!glob_match("?", ""));
286 assert!(glob_match("", ""));
287 assert!(!glob_match("", "x"));
288 }
289}