edifact-data 0.53.5

CLI tool for downloading EDIFACT mapping data bundles
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
use std::path::PathBuf;

use clap::{Parser, Subcommand, ValueEnum};
use edifact_mapper::DataDir;
use mig_bo4e::engine::DataBundle;

#[derive(Parser)]
#[command(name = "edifact-data", about = "Manage EDIFACT mapping data bundles")]
struct Cli {
    #[command(subcommand)]
    command: Command,

    /// Where to download bundles from.
    #[arg(long, global = true, value_enum, default_value_t = SourceKind::Github)]
    source: SourceKind,

    /// GitHub token for private repo access. Also reads GITHUB_TOKEN env var.
    #[arg(long, global = true, env = "GITHUB_TOKEN", hide_env_values = true)]
    token: Option<String>,

    /// JFrog host for `--source jfrog`, e.g. https://hochfrequenz.jfrog.io
    /// (the Hochfrequenz org variable JFROG_URL). Bundles are read from
    /// <url>/artifactory/<repo>/edifact-data/v<version>/edifact-data-<FV>.bin.gz.
    #[arg(long, global = true, env = "JFROG_URL")]
    jfrog_url: Option<String>,

    /// JFrog generic repository holding the bundles.
    #[arg(long, global = true, env = "JFROG_GENERIC_REPO", default_value = "hf")]
    jfrog_repo: String,

    /// JFrog access token for `--source jfrog`, sent as a Bearer header.
    /// Omit for anonymous access.
    #[arg(long, global = true, env = "JFROG_TOKEN", hide_env_values = true)]
    jfrog_token: Option<String>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
enum SourceKind {
    /// GitHub releases of Hochfrequenz/edifact_mapper.
    Github,
    /// A JFrog Artifactory repository (`--jfrog-url`).
    Jfrog,
}

/// A configured download source.
enum Source {
    GitHub {
        token: Option<String>,
    },
    JFrog {
        url: String,
        repo: String,
        token: Option<String>,
    },
}

impl Source {
    fn from_cli(
        kind: SourceKind,
        github_token: Option<String>,
        jfrog_url: Option<String>,
        jfrog_repo: String,
        jfrog_token: Option<String>,
    ) -> Result<Self, String> {
        match kind {
            SourceKind::Github => Ok(Source::GitHub {
                token: github_token.or_else(resolve_gh_token),
            }),
            SourceKind::Jfrog => {
                let url = jfrog_url
                    .filter(|u| !u.is_empty())
                    .ok_or("--source jfrog needs the JFrog host: set --jfrog-url or JFROG_URL")?;
                Ok(Source::JFrog {
                    url,
                    repo: jfrog_repo,
                    token: jfrog_token.filter(|t| !t.is_empty()),
                })
            }
        }
    }
}

#[derive(Subcommand)]
enum Command {
    /// Download data bundle(s) from GitHub releases.
    Fetch {
        /// Format version to fetch (e.g., FV2504). Omit for --all.
        fv: Option<String>,
        #[arg(long)]
        all: bool,
        #[arg(long)]
        data_dir: Option<String>,
        /// Bundle version to download (e.g., 0.5.0). Defaults to this binary's version.
        #[arg(long)]
        version: Option<String>,
    },
    /// List locally available data bundles.
    List {
        #[arg(long)]
        data_dir: Option<String>,
    },
    /// Update bundles to latest compatible version.
    Update {
        #[arg(long)]
        data_dir: Option<String>,
        /// Bundle version to update to (e.g., 0.5.0). Defaults to this binary's version.
        #[arg(long)]
        version: Option<String>,
    },
}

const GITHUB_REPO: &str = "Hochfrequenz/edifact_mapper";
const KNOWN_FVS: &[&str] = &["FV2504", "FV2510", "FV2604", "FV2610"];

fn resolve_data_dir(data_dir: Option<&str>) -> PathBuf {
    data_dir
        .map(PathBuf::from)
        .unwrap_or_else(|| DataDir::auto().data_path().to_path_buf())
}

fn main() {
    let cli = Cli::parse();
    // Only commands that download need a source; `list` must not fail on it.
    let source = || {
        Source::from_cli(
            cli.source,
            cli.token.clone(),
            cli.jfrog_url.clone(),
            cli.jfrog_repo.clone(),
            cli.jfrog_token.clone(),
        )
        .unwrap_or_else(|e| {
            eprintln!("{e}");
            std::process::exit(2);
        })
    };

    match cli.command {
        Command::Fetch {
            fv,
            all,
            data_dir,
            version,
        } => {
            let source = source();
            let dir = resolve_data_dir(data_dir.as_deref());
            std::fs::create_dir_all(&dir).expect("Failed to create data directory");
            let fvs: Vec<&str> = if all {
                KNOWN_FVS.to_vec()
            } else if let Some(ref fv) = fv {
                vec![fv.as_str()]
            } else {
                eprintln!("Specify a format version or use --all");
                std::process::exit(1);
            };
            let version = version.as_deref().unwrap_or(env!("CARGO_PKG_VERSION"));
            let requested = fvs.len();
            let mut failed = 0usize;
            for fv in fvs {
                match fetch_bundle(fv, version, &dir, &source) {
                    Ok(size) => println!(
                        "Fetched {fv}: {:.1}MB -> {}",
                        size as f64 / 1_048_576.0,
                        dir.join(format!("edifact-data-{fv}.bin")).display()
                    ),
                    Err(e) => {
                        eprintln!("Failed to fetch {fv}: {e}");
                        failed += 1;
                    }
                }
            }
            if failed > 0 {
                eprintln!("Failed to fetch {failed} of {requested} bundle(s)");
                std::process::exit(1);
            }
        }
        Command::List { data_dir } => {
            let dir = resolve_data_dir(data_dir.as_deref());
            if !dir.exists() {
                println!("No data directory found at {}", dir.display());
                return;
            }
            let mut found = false;
            for fv in KNOWN_FVS {
                let path = dir.join(format!("edifact-data-{fv}.bin"));
                if path.exists() {
                    let meta = std::fs::metadata(&path).unwrap();
                    println!(
                        "  {fv}  {:.1}MB  {}",
                        meta.len() as f64 / 1_048_576.0,
                        path.display()
                    );
                    found = true;
                }
            }
            if !found {
                println!("No bundles found in {}", dir.display());
            }
        }
        Command::Update { data_dir, version } => {
            let source = source();
            let dir = resolve_data_dir(data_dir.as_deref());
            std::fs::create_dir_all(&dir).expect("Failed to create data directory");
            let version = version.as_deref().unwrap_or(env!("CARGO_PKG_VERSION"));
            let mut failed = 0usize;
            for fv in KNOWN_FVS {
                let path = dir.join(format!("edifact-data-{fv}.bin"));
                if path.exists() {
                    match fetch_bundle(fv, version, &dir, &source) {
                        Ok(size) => {
                            println!("Updated {fv}: {:.1}MB", size as f64 / 1_048_576.0)
                        }
                        Err(e) => {
                            eprintln!("Failed to update {fv}: {e}");
                            failed += 1;
                        }
                    }
                }
            }
            if failed > 0 {
                eprintln!("Failed to update {failed} bundle(s)");
                std::process::exit(1);
            }
        }
    }
}

/// Download a bundle from `source` and decompress it.
///
/// GitHub: for private repos, uses the GitHub API to find the release asset
/// ID, then downloads via the asset API with auth. For public repos (no
/// token), uses the direct download URL.
///
/// JFrog: downloads `<url>/artifactory/<repo>/edifact-data/v<version>/<asset>`,
/// where the release workflow uploads it.
fn fetch_bundle(
    fv: &str,
    version: &str,
    data_dir: &std::path::Path,
    source: &Source,
) -> Result<u64, Box<dyn std::error::Error>> {
    let asset_name = format!("edifact-data-{fv}.bin.gz");
    let client = reqwest::blocking::Client::builder()
        .user_agent("edifact-data")
        .build()?;

    let gz_bytes = match source {
        // Private repo: use GitHub API to resolve asset and download
        Source::GitHub { token: Some(token) } => {
            download_private_asset(&client, token, version, &asset_name)?
        }
        // Public repo: direct download URL
        Source::GitHub { token: None } => download_public_asset(&client, version, &asset_name)?,
        Source::JFrog { url, repo, token } => {
            download_jfrog_asset(&client, url, repo, token.as_deref(), version, &asset_name)?
        }
    };

    eprintln!(
        "Downloaded {:.1}MB compressed",
        gz_bytes.len() as f64 / 1_048_576.0
    );

    let out_path = data_dir.join(format!("edifact-data-{fv}.bin"));
    let verify = bundle_is_verifiable(version);
    if !verify {
        eprintln!(
            "Bundle v{version} targets a different release than this CLI (v{}); \
             skipping the load check since its format may not be readable here",
            env!("CARGO_PKG_VERSION")
        );
    }
    install_bundle(&gz_bytes, &out_path, verify)
}

/// Whether a bundle of `requested_version` can be load-checked by this binary.
///
/// The bundle format tracks the crate version, so the reader compiled in here
/// only understands bundles from its own release. Pinning `--version` to another
/// release is a supported use (that is what the flag is for: fetching bundles
/// for the library version a *consumer* links), and a load failure there says
/// nothing about the download — so the check is only meaningful for our own
/// version.
fn bundle_is_verifiable(requested_version: &str) -> bool {
    requested_version == env!("CARGO_PKG_VERSION")
}

/// Decompress `gz_bytes` into `out_path`, optionally load-checking it first.
///
/// Writes to a sibling `.part` file and renames into place only after the
/// bundle is complete and (when verifiable) loadable. Decompressing straight
/// into `out_path` used to leave a truncated or unreadable `.bin` behind on
/// failure, which callers could not tell apart from a good bundle.
fn install_bundle(
    gz_bytes: &[u8],
    out_path: &std::path::Path,
    verify: bool,
) -> Result<u64, Box<dyn std::error::Error>> {
    let part_path = out_path.with_extension("bin.part");
    let staged = (|| -> Result<u64, Box<dyn std::error::Error>> {
        let mut decoder = flate2::read::GzDecoder::new(gz_bytes);
        let mut part_file = std::fs::File::create(&part_path)?;
        let size = std::io::copy(&mut decoder, &mut part_file)?;
        part_file.sync_all()?;
        drop(part_file);
        if verify {
            DataBundle::load(&part_path)?;
        }
        Ok(size)
    })();

    match staged {
        Ok(size) => {
            std::fs::rename(&part_path, out_path)?;
            Ok(size)
        }
        Err(e) => {
            let _ = std::fs::remove_file(&part_path);
            Err(e)
        }
    }
}

fn download_public_asset(
    client: &reqwest::blocking::Client,
    version: &str,
    asset_name: &str,
) -> Result<bytes::Bytes, Box<dyn std::error::Error>> {
    let url = format!("https://github.com/{GITHUB_REPO}/releases/download/v{version}/{asset_name}");
    eprintln!("Downloading {url} ...");
    let response = client
        .get(&url)
        .header("Accept", "application/octet-stream")
        .send()?;
    if !response.status().is_success() {
        return Err(format!(
            "HTTP {}: Is v{version} released with {asset_name}? \
             For private repos, set GITHUB_TOKEN or use --token.",
            response.status()
        )
        .into());
    }
    Ok(response.bytes()?)
}

/// The JFrog URL of `asset_name` for release `version`, on host `url`.
fn jfrog_asset_url(url: &str, repo: &str, version: &str, asset_name: &str) -> String {
    format!(
        "{}/artifactory/{repo}/edifact-data/v{version}/{asset_name}",
        url.trim_end_matches('/')
    )
}

fn download_jfrog_asset(
    client: &reqwest::blocking::Client,
    url: &str,
    repo: &str,
    token: Option<&str>,
    version: &str,
    asset_name: &str,
) -> Result<bytes::Bytes, Box<dyn std::error::Error>> {
    let url = jfrog_asset_url(url, repo, version, asset_name);
    eprintln!("Downloading {url} ...");
    let mut request = client.get(&url);
    if let Some(token) = token {
        request = request.bearer_auth(token);
    }
    let response = request.send()?;
    if !response.status().is_success() {
        return Err(format!(
            "HTTP {}: Is v{version} uploaded to JFrog with {asset_name}? \
             For a protected repository, set JFROG_TOKEN or use --jfrog-token.",
            response.status()
        )
        .into());
    }
    Ok(response.bytes()?)
}

/// Try to resolve a GitHub token from the `gh` CLI (GitHub CLI).
/// Returns None silently if `gh` is not installed or not authenticated.
fn resolve_gh_token() -> Option<String> {
    std::process::Command::new("gh")
        .args(["auth", "token"])
        .output()
        .ok()
        .filter(|o| o.status.success())
        .and_then(|o| {
            let token = String::from_utf8(o.stdout).ok()?.trim().to_string();
            if token.is_empty() {
                None
            } else {
                eprintln!("Using GitHub token from `gh auth token`");
                Some(token)
            }
        })
}

fn download_private_asset(
    client: &reqwest::blocking::Client,
    token: &str,
    version: &str,
    asset_name: &str,
) -> Result<bytes::Bytes, Box<dyn std::error::Error>> {
    // Step 1: Get release by tag to find asset ID
    let release_url =
        format!("https://api.github.com/repos/{GITHUB_REPO}/releases/tags/v{version}");
    eprintln!("Fetching release v{version} from GitHub API ...");
    let release: serde_json::Value = client
        .get(&release_url)
        .header("Authorization", format!("Bearer {token}"))
        .header("Accept", "application/vnd.github+json")
        .send()?
        .error_for_status()?
        .json()?;

    // Step 2: Find the asset by name
    let assets = release["assets"].as_array().ok_or("No assets in release")?;
    let asset = assets
        .iter()
        .find(|a| a["name"].as_str() == Some(asset_name))
        .ok_or_else(|| format!("Asset {asset_name} not found in release v{version}"))?;
    let asset_url = asset["url"].as_str().ok_or("Asset missing url field")?;

    // Step 3: Download the asset binary
    eprintln!("Downloading {asset_name} ...");
    let response = client
        .get(asset_url)
        .header("Authorization", format!("Bearer {token}"))
        .header("Accept", "application/octet-stream")
        .send()?
        .error_for_status()?;
    Ok(response.bytes()?)
}
#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;

    fn gzipped(bytes: &[u8]) -> Vec<u8> {
        let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
        encoder.write_all(bytes).unwrap();
        encoder.finish().unwrap()
    }

    /// Regression: FV2610 was released but missing here, so `fetch --all` and
    /// `update` skipped it. Every bundle the release ships must be known.
    #[test]
    fn known_fvs_match_the_released_bundles() {
        let dist = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../dist");
        let mut released: Vec<String> = std::fs::read_dir(&dist)
            .unwrap()
            .filter_map(|e| {
                let name = e.unwrap().file_name().into_string().unwrap();
                name.strip_prefix("edifact-data-")?
                    .strip_suffix(".bin.gz")
                    .map(String::from)
            })
            .collect();
        released.sort();
        assert!(!released.is_empty(), "no bundles in {}", dist.display());
        assert_eq!(KNOWN_FVS, released);
    }

    /// The org variable JFROG_URL is the bare host, with a trailing slash.
    #[test]
    fn jfrog_url_follows_the_release_upload_layout() {
        let expected = "https://example.jfrog.io/artifactory/hf/edifact-data/v0.51.1/edifact-data-FV2504.bin.gz";
        for host in ["https://example.jfrog.io", "https://example.jfrog.io/"] {
            assert_eq!(
                jfrog_asset_url(host, "hf", "0.51.1", "edifact-data-FV2504.bin.gz"),
                expected
            );
        }
    }

    #[test]
    fn jfrog_source_requires_a_url() {
        for url in [None, Some(String::new())] {
            let err = Source::from_cli(SourceKind::Jfrog, None, url, "hf".into(), None)
                .err()
                .expect("--source jfrog without a URL must fail");
            assert!(err.contains("JFROG_URL"), "{err}");
        }
    }

    #[test]
    fn jfrog_token_is_optional() {
        let url = Some("https://example.jfrog.io".to_string());
        for token in [None, Some("t".to_string())] {
            assert!(
                Source::from_cli(SourceKind::Jfrog, None, url.clone(), "hf".into(), token).is_ok()
            );
        }
    }

    #[test]
    fn only_our_own_version_is_verifiable() {
        assert!(bundle_is_verifiable(env!("CARGO_PKG_VERSION")));
        assert!(!bundle_is_verifiable("0.0.1-not-us"));
    }

    /// Regression: a bundle that decompresses but does not load left a bogus
    /// `.bin` in the data dir, indistinguishable from a good one.
    #[test]
    fn failed_verification_leaves_no_bundle_behind() {
        let dir = tempfile::tempdir().unwrap();
        let out_path = dir.path().join("edifact-data-FV2504.bin");

        let err = install_bundle(&gzipped(b"not a data bundle"), &out_path, true)
            .expect_err("a non-loadable bundle must not install");

        assert!(!out_path.exists(), "bundle left behind: {err}");
        assert!(
            !out_path.with_extension("bin.part").exists(),
            "staging file left behind"
        );
    }

    /// The `--version` skew case: nothing here can load a bundle built for
    /// another release, so it installs unverified rather than failing.
    #[test]
    fn unverifiable_bundle_installs_when_the_check_is_skipped() {
        let dir = tempfile::tempdir().unwrap();
        let out_path = dir.path().join("edifact-data-FV2504.bin");
        let payload = b"bundle for another release";

        let size = install_bundle(&gzipped(payload), &out_path, false)
            .expect("skipping verification must install the bundle");

        assert_eq!(size, payload.len() as u64);
        assert_eq!(std::fs::read(&out_path).unwrap(), payload);
        assert!(!out_path.with_extension("bin.part").exists());
    }

    /// Regression: a truncated download used to leave a partial `.bin` behind.
    #[test]
    fn corrupt_download_leaves_no_bundle_behind() {
        let dir = tempfile::tempdir().unwrap();
        let out_path = dir.path().join("edifact-data-FV2504.bin");
        let mut truncated = gzipped(b"a payload long enough to matter");
        truncated.truncate(truncated.len() / 2);

        install_bundle(&truncated, &out_path, false)
            .expect_err("a truncated download must not install");

        assert!(!out_path.exists());
        assert!(!out_path.with_extension("bin.part").exists());
    }
}