oxigeo-cli 0.2.1

Command-line interface for OxiGeo geospatial operations
Documentation
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
//! Integration tests for vector format conversion via `util::vector`.

use anyhow::{Context, Result, anyhow};
use oxigeo_cli::util::vector::{AttributeFilter, FilterOp, convert_vector};
use std::io::Write as _;

// ── Helpers ───────────────────────────────────────────────────────────────────

/// Write a minimal GeoJSON FeatureCollection to a temp file and return the path.
fn write_temp_geojson(name: &str, json: &str) -> Result<std::path::PathBuf> {
    let mut path = std::env::temp_dir();
    path.push(format!("oxigeo_vct_{name}.geojson"));
    let mut f = std::fs::File::create(&path)
        .with_context(|| format!("create temp geojson: {}", path.display()))?;
    f.write_all(json.as_bytes()).context("write temp geojson")?;
    Ok(path)
}

fn temp_path(name: &str, ext: &str) -> std::path::PathBuf {
    let mut path = std::env::temp_dir();
    path.push(format!("oxigeo_vct_{name}.{ext}"));
    path
}

// 3-feature GeoJSON with different "kind" properties
const GEOJSON_3F: &str = r#"{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "geometry": { "type": "Point", "coordinates": [10.0, 20.0] },
      "properties": { "name": "Alpha", "kind": "city", "pop": 1000 }
    },
    {
      "type": "Feature",
      "geometry": { "type": "Point", "coordinates": [11.0, 21.0] },
      "properties": { "name": "Beta", "kind": "town", "pop": 500 }
    },
    {
      "type": "Feature",
      "geometry": { "type": "Point", "coordinates": [12.0, 22.0] },
      "properties": { "name": "Gamma", "kind": "city", "pop": 2000 }
    }
  ]
}"#;

// 5-feature GeoJSON with varied names
const GEOJSON_5F: &str = r#"{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "geometry": { "type": "Point", "coordinates": [1.0, 2.0] },
      "properties": { "label": "apple", "score": 10 }
    },
    {
      "type": "Feature",
      "geometry": { "type": "Point", "coordinates": [2.0, 3.0] },
      "properties": { "label": "banana", "score": 20 }
    },
    {
      "type": "Feature",
      "geometry": { "type": "Point", "coordinates": [3.0, 4.0] },
      "properties": { "label": "apricot", "score": 30 }
    },
    {
      "type": "Feature",
      "geometry": { "type": "Point", "coordinates": [4.0, 5.0] },
      "properties": { "label": "cherry", "score": 40 }
    },
    {
      "type": "Feature",
      "geometry": { "type": "Point", "coordinates": [5.0, 6.0] },
      "properties": { "label": "blueberry", "score": 50 }
    }
  ]
}"#;

// ── Test 1: GeoJSON → GeoJSON ─────────────────────────────────────────────────

#[test]
fn test_geojson_to_geojson() -> Result<()> {
    let input = write_temp_geojson("gj2gj_in", GEOJSON_3F)?;
    let output = temp_path("gj2gj_out", "geojson");

    let count = convert_vector(&input, &output, None)?;

    assert_eq!(count, 3, "expected 3 features written");
    assert!(output.exists(), "output file should exist");

    // Round-trip: read back and verify
    let content = std::fs::read_to_string(&output)?;
    let parsed: serde_json::Value = serde_json::from_str(&content)?;
    let features = parsed["features"]
        .as_array()
        .ok_or_else(|| anyhow!("expected features array in output"))?;
    assert_eq!(features.len(), 3);

    // Cleanup
    let _ = std::fs::remove_file(&input);
    let _ = std::fs::remove_file(&output);
    Ok(())
}

// ── Test 2: GeoJSON → Shapefile ───────────────────────────────────────────────

#[test]
fn test_geojson_to_shapefile() -> Result<()> {
    let input = write_temp_geojson("gj2shp_in", GEOJSON_3F)?;
    let output = temp_path("gj2shp_out", "shp");

    let count = convert_vector(&input, &output, None)?;

    assert_eq!(count, 3, "expected 3 features written");
    assert!(output.exists(), ".shp file should exist");

    // Also verify .dbf exists
    let dbf = output.with_extension("dbf");
    assert!(dbf.exists(), ".dbf file should exist");

    // Read back via ShapefileReader
    let base = output.with_extension("");
    let reader = oxigeo_shapefile::ShapefileReader::open(&base)?;
    let features = reader.read_features()?;
    assert_eq!(features.len(), 3);

    // Cleanup
    let _ = std::fs::remove_file(&input);
    for ext in &["shp", "dbf", "shx"] {
        let _ = std::fs::remove_file(output.with_extension(ext));
    }
    Ok(())
}

// ── Test 3: Shapefile → GeoJSON ───────────────────────────────────────────────

#[test]
fn test_shapefile_to_geojson() -> Result<()> {
    // First create a shapefile via GeoJSON→Shapefile conversion
    let gj_input = write_temp_geojson("shp2gj_setup", GEOJSON_3F)?;
    let shp_intermediate = temp_path("shp2gj_inter", "shp");
    convert_vector(&gj_input, &shp_intermediate, None)?;

    // Now convert Shapefile → GeoJSON
    let gj_output = temp_path("shp2gj_out", "geojson");
    let count = convert_vector(&shp_intermediate, &gj_output, None)?;

    assert_eq!(count, 3, "expected 3 features in GeoJSON output");
    assert!(gj_output.exists(), "output GeoJSON should exist");

    let content = std::fs::read_to_string(&gj_output)?;
    let parsed: serde_json::Value = serde_json::from_str(&content)?;
    let features = parsed["features"]
        .as_array()
        .ok_or_else(|| anyhow!("expected features array in output"))?;
    assert_eq!(features.len(), 3);

    // Cleanup
    let _ = std::fs::remove_file(&gj_input);
    let _ = std::fs::remove_file(&gj_output);
    for ext in &["shp", "dbf", "shx"] {
        let _ = std::fs::remove_file(shp_intermediate.with_extension(ext));
    }
    Ok(())
}

// ── Test 4: Attribute filter eq ───────────────────────────────────────────────

#[test]
fn test_attribute_filter_eq() -> Result<()> {
    let input = write_temp_geojson("filt_eq_in", GEOJSON_3F)?;
    let output = temp_path("filt_eq_out", "geojson");

    let filter = AttributeFilter {
        field: "kind".to_string(),
        op: FilterOp::Eq,
        value: "city".to_string(),
    };

    let count = convert_vector(&input, &output, Some(&filter))?;

    // Only "Alpha" and "Gamma" have kind="city"
    assert_eq!(count, 2, "eq filter should match 2 features");

    let content = std::fs::read_to_string(&output)?;
    let parsed: serde_json::Value = serde_json::from_str(&content)?;
    let features = parsed["features"]
        .as_array()
        .ok_or_else(|| anyhow!("expected features array"))?;
    assert_eq!(features.len(), 2);

    // Verify all returned features have kind == "city"
    for f in features {
        let kind = f["properties"]["kind"]
            .as_str()
            .ok_or_else(|| anyhow!("expected kind field to be a string"))?;
        assert_eq!(kind, "city");
    }

    let _ = std::fs::remove_file(&input);
    let _ = std::fs::remove_file(&output);
    Ok(())
}

// ── Test 5: Attribute filter contains ────────────────────────────────────────

#[test]
fn test_attribute_filter_contains() -> Result<()> {
    let input = write_temp_geojson("filt_contains_in", GEOJSON_5F)?;
    let output = temp_path("filt_contains_out", "geojson");

    let filter = AttributeFilter {
        field: "label".to_string(),
        op: FilterOp::Contains,
        value: "ap".to_string(), // matches "apple" and "apricot"
    };

    let count = convert_vector(&input, &output, Some(&filter))?;

    assert_eq!(
        count, 2,
        "contains filter should match 2 features ('apple', 'apricot')"
    );

    let content = std::fs::read_to_string(&output)?;
    let parsed: serde_json::Value = serde_json::from_str(&content)?;
    let features = parsed["features"]
        .as_array()
        .ok_or_else(|| anyhow!("expected features array"))?;
    assert_eq!(features.len(), 2);

    for f in features {
        let label = f["properties"]["label"]
            .as_str()
            .ok_or_else(|| anyhow!("expected label field to be a string"))?;
        assert!(label.contains("ap"), "label '{label}' should contain 'ap'");
    }

    let _ = std::fs::remove_file(&input);
    let _ = std::fs::remove_file(&output);
    Ok(())
}

// ── Test 6: Unknown output format error ──────────────────────────────────────

#[test]
fn test_unknown_output_format_error() -> Result<()> {
    let input = write_temp_geojson("unk_fmt_in", GEOJSON_3F)?;
    let output = temp_path("unk_fmt_out", "xyz");

    let result = convert_vector(&input, &output, None);
    assert!(result.is_err(), "should return error for unknown extension");

    if let Err(e) = result {
        let err_msg = e.to_string();
        assert!(
            err_msg.contains("Cannot determine output format") || err_msg.contains("Unknown"),
            "error message should mention unknown format, got: {err_msg}"
        );
    }

    let _ = std::fs::remove_file(&input);
    Ok(())
}

// ── Test 7: Attribute filter ne ───────────────────────────────────────────────

#[test]
fn test_attribute_filter_ne() -> Result<()> {
    let input = write_temp_geojson("filt_ne_in", GEOJSON_3F)?;
    let output = temp_path("filt_ne_out", "geojson");

    let filter = AttributeFilter {
        field: "kind".to_string(),
        op: FilterOp::Ne,
        value: "city".to_string(),
    };

    let count = convert_vector(&input, &output, Some(&filter))?;

    // Only "Beta" has kind="town" (not city)
    assert_eq!(count, 1, "ne filter should match 1 feature");

    let content = std::fs::read_to_string(&output)?;
    let parsed: serde_json::Value = serde_json::from_str(&content)?;
    let features = parsed["features"]
        .as_array()
        .ok_or_else(|| anyhow!("expected features array"))?;
    assert_eq!(features.len(), 1);

    let name = features[0]["properties"]["name"]
        .as_str()
        .ok_or_else(|| anyhow!("expected name field"))?;
    assert_eq!(name, "Beta");

    let _ = std::fs::remove_file(&input);
    let _ = std::fs::remove_file(&output);
    Ok(())
}

// ─────────────────────────────────────────────────────────────────────────────
// FlatGeobuf conversion tests
// ─────────────────────────────────────────────────────────────────────────────

/// Helper: write a minimal FlatGeobuf file with N point features to `path`.
///
/// Each feature has two string properties: `name` and `kind`.
fn write_temp_fgb(
    name: &str,
    features_data: &[(&str, &str, f64, f64)], // (name, kind, x, y)
) -> Result<std::path::PathBuf> {
    use oxigeo_core::vector::{Feature as CoreFeature, FieldValue, Geometry, Point};
    use oxigeo_flatgeobuf::{Column, ColumnType, FlatGeobufWriterBuilder, GeometryType};
    use std::fs::File;
    use std::io::BufWriter;

    let path = temp_path(name, "fgb");

    let builder = FlatGeobufWriterBuilder::new(GeometryType::Point)
        .with_index()
        .with_column(Column::new("name", ColumnType::String))
        .with_column(Column::new("kind", ColumnType::String));

    let file =
        File::create(&path).with_context(|| format!("create temp fgb: {}", path.display()))?;
    let buf_writer = BufWriter::new(file);
    let mut writer = builder.build(buf_writer).context("create FGB writer")?;

    for (feat_name, kind, x, y) in features_data {
        let mut feat = CoreFeature::new(Geometry::Point(Point::new(*x, *y)));
        feat.set_property("name", FieldValue::String(feat_name.to_string()));
        feat.set_property("kind", FieldValue::String(kind.to_string()));
        writer.add_feature(&feat).context("add feature to FGB")?;
    }

    writer.finish().context("finish FGB writer")?;
    Ok(path)
}

/// Helper: write an empty FlatGeobuf file (no features).
fn write_empty_fgb(name: &str) -> Result<std::path::PathBuf> {
    use oxigeo_flatgeobuf::{FlatGeobufWriterBuilder, GeometryType};
    use std::fs::File;
    use std::io::BufWriter;

    let path = temp_path(name, "fgb");
    let builder = FlatGeobufWriterBuilder::new(GeometryType::Point).with_index();
    let file =
        File::create(&path).with_context(|| format!("create empty fgb: {}", path.display()))?;
    let buf_writer = BufWriter::new(file);
    let writer = builder
        .build(buf_writer)
        .context("create empty FGB writer")?;
    writer.finish().context("finish empty FGB writer")?;
    Ok(path)
}

// ── Test 8: FlatGeobuf → GeoJSON round-trip ───────────────────────────────────

#[test]
fn test_flatgeobuf_to_geojson() -> Result<()> {
    let fgb_data = &[
        ("Alpha", "city", 10.0f64, 20.0f64),
        ("Beta", "town", 11.0, 21.0),
        ("Gamma", "city", 12.0, 22.0),
    ];
    let input = write_temp_fgb("fgb2gj_in", fgb_data)?;
    let output = temp_path("fgb2gj_out", "geojson");

    let count = convert_vector(&input, &output, None)?;
    assert_eq!(count, 3, "expected 3 features written");
    assert!(output.exists(), "output file should exist");

    let content = std::fs::read_to_string(&output)?;
    let parsed: serde_json::Value = serde_json::from_str(&content)?;
    let features = parsed["features"]
        .as_array()
        .ok_or_else(|| anyhow!("expected features array"))?;
    assert_eq!(features.len(), 3, "GeoJSON should have 3 features");

    // Verify property round-trip
    let names: std::collections::HashSet<&str> = features
        .iter()
        .filter_map(|f| f["properties"]["name"].as_str())
        .collect();
    assert!(names.contains("Alpha"), "Alpha should be present");
    assert!(names.contains("Beta"), "Beta should be present");
    assert!(names.contains("Gamma"), "Gamma should be present");

    let _ = std::fs::remove_file(&input);
    let _ = std::fs::remove_file(&output);
    Ok(())
}

// ── Test 9: GeoJSON → FlatGeobuf conversion ───────────────────────────────────

#[test]
fn test_geojson_to_flatgeobuf() -> Result<()> {
    let input = write_temp_geojson("gj2fgb_in", GEOJSON_3F)?;
    let output = temp_path("gj2fgb_out", "fgb");

    let count = convert_vector(&input, &output, None)?;
    assert_eq!(count, 3, "expected 3 features written");
    assert!(output.exists(), "FGB output file should exist");

    // Verify the file is a valid FlatGeobuf by reading it back
    let read_back_path = temp_path("gj2fgb_readback", "geojson");
    let readback_count = convert_vector(&output, &read_back_path, None)?;
    assert_eq!(readback_count, 3, "round-trip should yield 3 features");

    let content = std::fs::read_to_string(&read_back_path)?;
    let parsed: serde_json::Value = serde_json::from_str(&content)?;
    let features = parsed["features"]
        .as_array()
        .ok_or_else(|| anyhow!("expected features array in read-back"))?;
    assert_eq!(features.len(), 3);

    let _ = std::fs::remove_file(&input);
    let _ = std::fs::remove_file(&output);
    let _ = std::fs::remove_file(&read_back_path);
    Ok(())
}

// ── Test 10: FlatGeobuf round-trip (FGB → GeoJSON → FGB) ──────────────────────

#[test]
fn test_flatgeobuf_round_trip() -> Result<()> {
    let fgb_data = &[
        ("Node1", "type_a", 1.0f64, 2.0f64),
        ("Node2", "type_b", 3.0, 4.0),
    ];
    let input_fgb = write_temp_fgb("fgb_rt_in", fgb_data)?;
    let mid_geojson = temp_path("fgb_rt_mid", "geojson");
    let output_fgb = temp_path("fgb_rt_out", "fgb");
    let final_geojson = temp_path("fgb_rt_final", "geojson");

    // FGB → GeoJSON
    let c1 = convert_vector(&input_fgb, &mid_geojson, None)?;
    assert_eq!(c1, 2, "FGB→GeoJSON should yield 2 features");

    // GeoJSON → FGB
    let c2 = convert_vector(&mid_geojson, &output_fgb, None)?;
    assert_eq!(c2, 2, "GeoJSON→FGB should yield 2 features");

    // FGB → GeoJSON (final verification)
    let c3 = convert_vector(&output_fgb, &final_geojson, None)?;
    assert_eq!(c3, 2, "final FGB→GeoJSON should yield 2 features");

    let content = std::fs::read_to_string(&final_geojson)?;
    let parsed: serde_json::Value = serde_json::from_str(&content)?;
    let features = parsed["features"]
        .as_array()
        .ok_or_else(|| anyhow!("expected features array in final output"))?;
    assert_eq!(features.len(), 2);

    let names: std::collections::HashSet<&str> = features
        .iter()
        .filter_map(|f| f["properties"]["name"].as_str())
        .collect();
    assert!(names.contains("Node1"), "Node1 should survive round-trip");
    assert!(names.contains("Node2"), "Node2 should survive round-trip");

    let _ = std::fs::remove_file(&input_fgb);
    let _ = std::fs::remove_file(&mid_geojson);
    let _ = std::fs::remove_file(&output_fgb);
    let _ = std::fs::remove_file(&final_geojson);
    Ok(())
}

// ── Test 11: FlatGeobuf attribute filter ──────────────────────────────────────

#[test]
fn test_flatgeobuf_attribute_filter() -> Result<()> {
    let fgb_data = &[
        ("Alpha", "city", 10.0f64, 20.0f64),
        ("Beta", "town", 11.0, 21.0),
        ("Gamma", "city", 12.0, 22.0),
    ];
    let input = write_temp_fgb("fgb_filt_in", fgb_data)?;
    let output = temp_path("fgb_filt_out", "geojson");

    let filter = AttributeFilter {
        field: "kind".to_string(),
        op: FilterOp::Eq,
        value: "city".to_string(),
    };

    let count = convert_vector(&input, &output, Some(&filter))?;
    assert_eq!(count, 2, "filter should match 2 city features");

    let content = std::fs::read_to_string(&output)?;
    let parsed: serde_json::Value = serde_json::from_str(&content)?;
    let features = parsed["features"]
        .as_array()
        .ok_or_else(|| anyhow!("expected features array"))?;
    assert_eq!(features.len(), 2);

    for f in features {
        let kind = f["properties"]["kind"]
            .as_str()
            .ok_or_else(|| anyhow!("expected kind field"))?;
        assert_eq!(kind, "city", "all returned features should have kind=city");
    }

    let _ = std::fs::remove_file(&input);
    let _ = std::fs::remove_file(&output);
    Ok(())
}

// ── Test 12: FlatGeobuf empty file handled gracefully ─────────────────────────

#[test]
fn test_flatgeobuf_empty() -> Result<()> {
    let input = write_empty_fgb("fgb_empty_in")?;
    let output = temp_path("fgb_empty_out", "geojson");

    let count = convert_vector(&input, &output, None)?;
    assert_eq!(count, 0, "empty FGB should yield 0 features");
    assert!(output.exists(), "output GeoJSON should still be created");

    let content = std::fs::read_to_string(&output)?;
    let parsed: serde_json::Value = serde_json::from_str(&content)?;
    let features = parsed["features"]
        .as_array()
        .ok_or_else(|| anyhow!("expected features array even for empty collection"))?;
    assert!(features.is_empty(), "features array should be empty");

    let _ = std::fs::remove_file(&input);
    let _ = std::fs::remove_file(&output);
    Ok(())
}