oxigdal-cli 0.1.4

Command-line interface for OxiGDAL geospatial operations
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
//! Validate command - Validate file format and compliance

use crate::OutputFormat;
use crate::util;
use anyhow::{Context, Result};
use clap::Args;
use console::style;
use oxigdal_core::io::FileDataSource;
use oxigdal_geojson::{GeoJsonReader, Validator as GeoJsonValidator};
use oxigdal_geotiff::GeoTiffReader;
use serde::Serialize;
use std::fs::File;
use std::io::BufReader;
use std::path::PathBuf;

/// Validate file format and compliance
#[derive(Args, Debug)]
pub struct ValidateArgs {
    /// Input file path
    #[arg(value_name = "FILE")]
    input: PathBuf,

    /// Validate as Cloud-Optimized GeoTIFF
    #[arg(long)]
    cog: bool,

    /// Validate GeoJSON against specification
    #[arg(long)]
    geojson: bool,

    /// Check for common issues
    #[arg(long)]
    strict: bool,

    /// Detailed validation report
    #[arg(short, long)]
    verbose: bool,
}

#[derive(Serialize)]
struct ValidationResult {
    file_path: String,
    format: String,
    valid: bool,
    warnings: Vec<String>,
    errors: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    cog_info: Option<CogInfo>,
    #[serde(skip_serializing_if = "Option::is_none")]
    geojson_info: Option<GeoJsonInfo>,
}

#[derive(Serialize)]
struct CogInfo {
    is_tiled: bool,
    has_overviews: bool,
    tile_size: Option<(u32, u32)>,
    compression: String,
}

#[derive(Serialize)]
struct GeoJsonInfo {
    feature_count: usize,
    has_crs: bool,
    has_bbox: bool,
    geometry_types: Vec<String>,
}

pub fn execute(args: ValidateArgs, format: OutputFormat) -> Result<()> {
    // Check if file exists
    if !args.input.exists() {
        anyhow::bail!("File not found: {}", args.input.display());
    }

    // Detect format
    let detected_format =
        util::detect_format(&args.input).ok_or_else(|| anyhow::anyhow!("Unknown file format"))?;

    let result = match detected_format {
        "GeoTIFF" => validate_geotiff(&args)?,
        "GeoJSON" => validate_geojson(&args)?,
        _ => {
            anyhow::bail!("Validation not supported for format: {}", detected_format);
        }
    };

    // Output results
    match format {
        OutputFormat::Json => {
            let json =
                serde_json::to_string_pretty(&result).context("Failed to serialize to JSON")?;
            println!("{}", json);
        }
        OutputFormat::Text => {
            print_validation_result(&result);
        }
    }

    // Return error if validation failed
    if !result.valid {
        anyhow::bail!("Validation failed");
    }

    Ok(())
}

fn validate_geotiff(args: &ValidateArgs) -> Result<ValidationResult> {
    let mut warnings = Vec::new();
    let mut errors = Vec::new();

    // Open file
    let source = match FileDataSource::open(&args.input) {
        Ok(s) => s,
        Err(e) => {
            errors.push(format!("Failed to open file: {}", e));
            return Ok(ValidationResult {
                file_path: args.input.display().to_string(),
                format: "GeoTIFF".to_string(),
                valid: false,
                warnings,
                errors,
                cog_info: None,
                geojson_info: None,
            });
        }
    };

    let reader = match GeoTiffReader::open(source) {
        Ok(r) => r,
        Err(e) => {
            errors.push(format!("Failed to read GeoTIFF: {}", e));
            return Ok(ValidationResult {
                file_path: args.input.display().to_string(),
                format: "GeoTIFF".to_string(),
                valid: false,
                warnings,
                errors,
                cog_info: None,
                geojson_info: None,
            });
        }
    };

    // Basic validation
    let width = reader.width();
    let height = reader.height();
    let bands = reader.band_count();

    if width == 0 || height == 0 {
        errors.push("Invalid raster dimensions".to_string());
    }

    if bands == 0 {
        errors.push("No bands found".to_string());
    }

    if reader.geo_transform().is_none() {
        warnings.push("No geotransform found".to_string());
    }

    if reader.epsg_code().is_none() {
        warnings.push("No CRS information found".to_string());
    }

    // COG validation
    let mut cog_info = None;
    if args.cog {
        let tile_size = reader.tile_size();
        let is_tiled = tile_size.is_some();

        if !is_tiled {
            warnings.push("File is not tiled (required for COG)".to_string());
        }

        let overview_count = reader.overview_count();
        let has_overviews = overview_count > 0;

        if !has_overviews {
            warnings.push("No overviews found (recommended for COG)".to_string());
        }

        let compression = format!("{:?}", reader.compression());

        cog_info = Some(CogInfo {
            is_tiled,
            has_overviews,
            tile_size,
            compression,
        });
    }

    // Strict validation
    if args.strict && (width % 16 != 0 || height % 16 != 0) {
        warnings
            .push("Dimensions are not multiples of 16 (recommended for performance)".to_string());
    }

    Ok(ValidationResult {
        file_path: args.input.display().to_string(),
        format: "GeoTIFF".to_string(),
        valid: errors.is_empty(),
        warnings,
        errors,
        cog_info,
        geojson_info: None,
    })
}

fn validate_geojson(args: &ValidateArgs) -> Result<ValidationResult> {
    let mut warnings = Vec::new();
    let mut errors = Vec::new();

    // Open file
    let file = match File::open(&args.input) {
        Ok(f) => f,
        Err(e) => {
            errors.push(format!("Failed to open file: {}", e));
            return Ok(ValidationResult {
                file_path: args.input.display().to_string(),
                format: "GeoJSON".to_string(),
                valid: false,
                warnings,
                errors,
                cog_info: None,
                geojson_info: None,
            });
        }
    };

    let buf_reader = BufReader::new(file);
    let mut reader = GeoJsonReader::new(buf_reader);

    let feature_collection = match reader.read_feature_collection() {
        Ok(fc) => fc,
        Err(e) => {
            errors.push(format!("Failed to read GeoJSON: {}", e));
            return Ok(ValidationResult {
                file_path: args.input.display().to_string(),
                format: "GeoJSON".to_string(),
                valid: false,
                warnings,
                errors,
                cog_info: None,
                geojson_info: None,
            });
        }
    };

    // Validate with GeoJSON validator
    let mut validator = GeoJsonValidator::new();
    match validator.validate_feature_collection(&feature_collection) {
        Ok(_) => {}
        Err(e) => {
            errors.push(format!("GeoJSON validation failed: {}", e));
        }
    }

    // Check for CRS
    let has_crs = feature_collection.crs.is_some();
    if !has_crs && args.strict {
        warnings.push("No CRS specified (recommended for GeoJSON)".to_string());
    }

    // Check for bbox
    let has_bbox = feature_collection.bbox.is_some();
    if !has_bbox && args.strict {
        warnings.push("No bounding box specified (recommended for performance)".to_string());
    }

    // Count features
    let feature_count = feature_collection.features.len();
    if feature_count == 0 {
        warnings.push("No features found".to_string());
    }

    // Collect geometry types
    let mut geometry_types = std::collections::HashSet::new();
    for feature in &feature_collection.features {
        if let Some(ref geom) = feature.geometry {
            geometry_types.insert(format!("{:?}", geom));
        }
    }

    let geojson_info = Some(GeoJsonInfo {
        feature_count,
        has_crs,
        has_bbox,
        geometry_types: geometry_types.into_iter().collect(),
    });

    Ok(ValidationResult {
        file_path: args.input.display().to_string(),
        format: "GeoJSON".to_string(),
        valid: errors.is_empty(),
        warnings,
        errors,
        cog_info: None,
        geojson_info,
    })
}

fn print_validation_result(result: &ValidationResult) {
    println!("{}", style("Validation Result").bold().cyan());
    println!("  File:   {}", result.file_path);
    println!("  Format: {}", result.format);
    println!(
        "  Status: {}",
        if result.valid {
            style("VALID").green().bold()
        } else {
            style("INVALID").red().bold()
        }
    );
    println!();

    if !result.errors.is_empty() {
        println!("{}", style("Errors:").red().bold());
        for error in &result.errors {
            println!("  {} {}", style("").red(), error);
        }
        println!();
    }

    if !result.warnings.is_empty() {
        println!("{}", style("Warnings:").yellow().bold());
        for warning in &result.warnings {
            println!("  {} {}", style("").yellow(), warning);
        }
        println!();
    }

    if let Some(ref cog) = result.cog_info {
        println!("{}", style("COG Information").bold().cyan());
        println!(
            "  Tiled:     {}",
            if cog.is_tiled {
                style("Yes").green()
            } else {
                style("No").red()
            }
        );
        println!(
            "  Overviews: {}",
            if cog.has_overviews {
                style("Yes").green()
            } else {
                style("No").red()
            }
        );
        if let Some((w, h)) = cog.tile_size {
            println!("  Tile size: {} x {}", w, h);
        }
        println!("  Compression: {}", cog.compression);
        println!();
    }

    if let Some(ref geojson) = result.geojson_info {
        println!("{}", style("GeoJSON Information").bold().cyan());
        println!("  Features:       {}", geojson.feature_count);
        println!(
            "  Has CRS:        {}",
            if geojson.has_crs {
                style("Yes").green()
            } else {
                style("No").yellow()
            }
        );
        println!(
            "  Has BBox:       {}",
            if geojson.has_bbox {
                style("Yes").green()
            } else {
                style("No").yellow()
            }
        );
        println!("  Geometry types: {}", geojson.geometry_types.join(", "));
        println!();
    }

    if result.errors.is_empty() && result.warnings.is_empty() {
        println!("{} File is valid with no issues", style("").green().bold());
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_validation_result_creation() {
        let result = ValidationResult {
            file_path: "test.tif".to_string(),
            format: "GeoTIFF".to_string(),
            valid: true,
            warnings: vec![],
            errors: vec![],
            cog_info: None,
            geojson_info: None,
        };

        assert!(result.valid);
        assert!(result.errors.is_empty());
    }
}