oxigeo-cli 0.2.3

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
//! Merge command - Merge/mosaic multiple rasters
//!
//! This command merges multiple input rasters into a single output raster.
//! Handles overlapping areas using first-valid-pixel strategy.

use crate::OutputFormat;
use crate::util::{progress, raster};
use anyhow::{Context, Result};
use clap::Args;
use console::style;
use oxigeo_core::buffer::RasterBuffer;
use oxigeo_core::types::GeoTransform;
use serde::Serialize;
use std::path::PathBuf;

/// Merge multiple rasters into a single output
#[derive(Args, Debug)]
pub struct MergeArgs {
    /// Output file path
    #[arg(short = 'o', long, value_name = "OUTPUT")]
    output: PathBuf,

    /// Input raster files
    #[arg(value_name = "INPUT", required = true)]
    inputs: Vec<PathBuf>,

    /// NoData value for inputs
    #[arg(long)]
    no_data: Option<f64>,

    /// Output NoData value
    #[arg(long)]
    output_no_data: Option<f64>,

    /// Target EPSG code (must match all inputs)
    #[arg(long)]
    epsg: Option<u32>,

    /// Overwrite existing output file
    #[arg(long)]
    overwrite: bool,

    /// Show progress bar
    #[arg(long, default_value = "true")]
    progress: bool,

    /// Creation options (KEY=VALUE, GDAL-compatible)
    #[arg(long = "co", value_parser = crate::util::creation_options::parse_key_value)]
    pub creation_options: Vec<(String, String)>,
}

#[derive(Serialize)]
struct MergeResult {
    output_file: String,
    input_count: usize,
    width: u64,
    height: u64,
    bands: usize,
}

pub fn execute(args: MergeArgs, format: OutputFormat) -> Result<()> {
    let _co = crate::util::creation_options::map_creation_options(&args.creation_options);

    if args.output.exists() && !args.overwrite {
        anyhow::bail!(
            "Output file already exists: {}. Use --overwrite to replace.",
            args.output.display()
        );
    }

    if args.inputs.len() < 2 {
        anyhow::bail!("Merge requires at least 2 input files");
    }

    // Validate all inputs exist and read metadata
    let pb = if args.progress {
        Some(progress::create_progress_bar(
            args.inputs.len() as u64,
            "Reading input metadata",
        ))
    } else {
        None
    };

    let mut all_info = Vec::new();
    for input in &args.inputs {
        if !input.exists() {
            anyhow::bail!("Input file not found: {}", input.display());
        }

        let info = raster::read_raster_info(input)
            .with_context(|| format!("Failed to read {}", input.display()))?;
        all_info.push(info);

        if let Some(ref pb) = pb {
            pb.inc(1);
        }
    }

    if let Some(ref pb) = pb {
        pb.finish_with_message("Metadata loaded");
    }

    // Validate compatibility
    let first_bands = all_info[0].bands;
    let first_data_type = all_info[0].data_type;

    for (i, info) in all_info.iter().enumerate() {
        if info.bands != first_bands {
            anyhow::bail!(
                "Input {} has {} bands, but first input has {} bands",
                i,
                info.bands,
                first_bands
            );
        }
        if info.data_type != first_data_type {
            anyhow::bail!(
                "Input {} has data type {:?}, but first input has {:?}",
                i,
                info.data_type,
                first_data_type
            );
        }
        if let Some(epsg) = args.epsg
            && info.epsg_code != Some(epsg)
        {
            anyhow::bail!(
                "Input {} has EPSG:{:?}, but target is EPSG:{}",
                i,
                info.epsg_code,
                epsg
            );
        }
    }

    // Calculate output bounds and resolution
    let (out_min_x, out_min_y, out_max_x, out_max_y, pixel_width, pixel_height) =
        calculate_output_extent(&all_info).context("Failed to calculate output extent")?;

    let out_width = ((out_max_x - out_min_x) / pixel_width).ceil() as u64;
    let out_height = ((out_max_y - out_min_y) / pixel_height.abs()).ceil() as u64;

    let output_geotransform = GeoTransform {
        origin_x: out_min_x,
        origin_y: out_max_y,
        pixel_width,
        pixel_height,
        row_rotation: 0.0,
        col_rotation: 0.0,
    };

    let pb = if args.progress {
        Some(progress::create_progress_bar(
            first_bands as u64,
            "Merging bands",
        ))
    } else {
        None
    };

    // Merge each band
    let mut output_bands = Vec::with_capacity(first_bands as usize);

    for band_idx in 0..first_bands {
        if let Some(ref pb) = pb {
            pb.set_message(format!("Merging band {}/{}", band_idx + 1, first_bands));
        }

        let merged_band = merge_band(
            &args.inputs,
            band_idx,
            out_width,
            out_height,
            &output_geotransform,
            &all_info,
            args.no_data,
        )
        .with_context(|| format!("Failed to merge band {}", band_idx))?;

        output_bands.push(merged_band);

        if let Some(ref pb) = pb {
            pb.inc(1);
        }
    }

    if let Some(ref pb) = pb {
        pb.finish_with_message("Merging complete");
    }

    // Write output
    let spinner = if args.progress {
        Some(progress::create_spinner("Writing output file"))
    } else {
        None
    };

    raster::write_multi_band(
        &args.output,
        &output_bands,
        Some(output_geotransform),
        args.epsg.or(all_info[0].epsg_code),
        args.output_no_data,
    )
    .context("Failed to write output raster")?;

    if let Some(ref sp) = spinner {
        sp.finish_with_message("Output written successfully");
    }

    let result = MergeResult {
        output_file: args.output.display().to_string(),
        input_count: args.inputs.len(),
        width: out_width,
        height: out_height,
        bands: output_bands.len(),
    };

    match format {
        OutputFormat::Json => {
            let json =
                serde_json::to_string_pretty(&result).context("Failed to serialize to JSON")?;
            println!("{}", json);
        }
        OutputFormat::Text => {
            println!("{}", style("Merge complete").green().bold());
            println!("  Inputs:     {} files", result.input_count);
            println!("  Output:     {}", result.output_file);
            println!("  Dimensions: {} x {}", result.width, result.height);
            println!("  Bands:      {}", result.bands);
        }
    }

    Ok(())
}

/// Calculate output extent covering all inputs
fn calculate_output_extent(
    all_info: &[raster::RasterInfo],
) -> Result<(f64, f64, f64, f64, f64, f64)> {
    let mut min_x = f64::INFINITY;
    let mut min_y = f64::INFINITY;
    let mut max_x = f64::NEG_INFINITY;
    let mut max_y = f64::NEG_INFINITY;

    let mut pixel_widths = Vec::new();
    let mut pixel_heights = Vec::new();

    for info in all_info {
        let gt = info
            .geo_transform
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("Input has no geotransform"))?;

        let input_min_x = gt.origin_x;
        let input_max_x = gt.origin_x + gt.pixel_width * info.width as f64;
        let input_max_y = gt.origin_y;
        let input_min_y = gt.origin_y + gt.pixel_height * info.height as f64;

        min_x = min_x.min(input_min_x.min(input_max_x));
        max_x = max_x.max(input_min_x.max(input_max_x));
        min_y = min_y.min(input_min_y.min(input_max_y));
        max_y = max_y.max(input_min_y.max(input_max_y));

        pixel_widths.push(gt.pixel_width.abs());
        pixel_heights.push(gt.pixel_height.abs());
    }

    // Use finest resolution
    let pixel_width = pixel_widths.iter().fold(f64::INFINITY, |a, &b| a.min(b));
    let pixel_height = -pixel_heights.iter().fold(f64::INFINITY, |a, &b| a.min(b));

    Ok((min_x, min_y, max_x, max_y, pixel_width, pixel_height))
}

/// Merge a single band from multiple inputs
fn merge_band(
    inputs: &[PathBuf],
    band_idx: u32,
    out_width: u64,
    out_height: u64,
    out_gt: &GeoTransform,
    all_info: &[raster::RasterInfo],
    no_data: Option<f64>,
) -> Result<RasterBuffer> {
    // Initialize output with NoData
    let no_data_value = no_data.unwrap_or(0.0);
    let mut output_data = vec![no_data_value; (out_width * out_height) as usize];

    // Process each input (first input has priority)
    for (input_path, info) in inputs.iter().zip(all_info.iter()) {
        let band_data = raster::read_band(input_path, band_idx)?;
        let input_gt = info
            .geo_transform
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("Input has no geotransform"))?;

        // Copy data from input to output
        for in_y in 0..band_data.height() {
            for in_x in 0..band_data.width() {
                // Convert input pixel to geo coordinates
                let geo_x = input_gt.origin_x + in_x as f64 * input_gt.pixel_width;
                let geo_y = input_gt.origin_y + in_y as f64 * input_gt.pixel_height;

                // Convert geo to output pixel
                let out_x = ((geo_x - out_gt.origin_x) / out_gt.pixel_width).floor() as i64;
                let out_y = ((geo_y - out_gt.origin_y) / out_gt.pixel_height).floor() as i64;

                // Check if within output bounds
                if out_x >= 0 && out_x < out_width as i64 && out_y >= 0 && out_y < out_height as i64
                {
                    let out_idx = (out_y as u64 * out_width + out_x as u64) as usize;
                    let value = band_data.get_pixel(in_x, in_y).unwrap_or(no_data_value);

                    // Only write if current output is NoData (first valid pixel wins)
                    if output_data[out_idx] == no_data_value && value != no_data_value {
                        output_data[out_idx] = value;
                    }
                }
            }
        }
    }

    // Convert f64 vec to bytes for RasterBuffer
    use oxigeo_core::types::RasterDataType;
    let byte_data: Vec<u8> = output_data
        .iter()
        .flat_map(|&val| val.to_le_bytes())
        .collect();

    RasterBuffer::new(
        byte_data,
        out_width,
        out_height,
        RasterDataType::Float64,
        oxigeo_core::types::NoDataValue::from_float(no_data_value),
    )
    .map_err(|e| anyhow::anyhow!("Failed to create output buffer: {}", e))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::OutputFormat;
    use std::sync::atomic::{AtomicU64, Ordering};

    /// Per-test scratch fixture inside the system temp dir (house policy: no
    /// hardcoded absolute paths).
    ///
    /// The leaf name embeds the process id and a monotonic counter, so no two
    /// test binaries — nor two concurrent runs of this one — can ever land on
    /// the same file.  Dropping the guard removes the fixture, so a panicking
    /// test leaks nothing.
    struct TempPath(PathBuf);

    impl TempPath {
        fn new(name: &str) -> Self {
            static COUNTER: AtomicU64 = AtomicU64::new(0);
            let seq = COUNTER.fetch_add(1, Ordering::Relaxed);
            Self(std::env::temp_dir().join(format!(
                "oxigeo_cli_merge_{}_{seq}_{name}",
                std::process::id()
            )))
        }
    }

    impl std::ops::Deref for TempPath {
        type Target = std::path::Path;

        fn deref(&self) -> &std::path::Path {
            &self.0
        }
    }

    impl AsRef<std::path::Path> for TempPath {
        fn as_ref(&self) -> &std::path::Path {
            &self.0
        }
    }

    impl Drop for TempPath {
        fn drop(&mut self) {
            let _ = std::fs::remove_file(&self.0);
        }
    }

    /// `execute` must reject a merge request with fewer than 2 inputs before
    /// touching the filesystem, with the exact "at least 2 input files"
    /// message from the check at the top of the function.
    #[test]
    fn test_merge_requires_multiple_inputs() {
        let output = TempPath::new("single_input.tif");
        let args = MergeArgs {
            output: output.to_path_buf(),
            inputs: vec![PathBuf::from("only_one_input.tif")],
            no_data: None,
            output_no_data: None,
            epsg: None,
            overwrite: true,
            progress: false,
            creation_options: Vec::new(),
        };

        let result = execute(args, OutputFormat::Text);
        let err = result.expect_err("merge with a single input must fail");
        assert!(
            err.to_string()
                .contains("Merge requires at least 2 input files"),
            "unexpected error message: {err}"
        );
    }

    /// Zero inputs must fail with the same "at least 2" message, not a
    /// different error (e.g. an index-out-of-bounds panic from `all_info[0]`).
    #[test]
    fn test_merge_requires_multiple_inputs_zero() {
        let output = TempPath::new("zero_inputs.tif");
        let args = MergeArgs {
            output: output.to_path_buf(),
            inputs: Vec::new(),
            no_data: None,
            output_no_data: None,
            epsg: None,
            overwrite: true,
            progress: false,
            creation_options: Vec::new(),
        };

        let result = execute(args, OutputFormat::Text);
        let err = result.expect_err("merge with zero inputs must fail");
        assert!(
            err.to_string()
                .contains("Merge requires at least 2 input files"),
            "unexpected error message: {err}"
        );
    }
}