xls-rs 0.1.2

A powerful CLI tool and library for spreadsheet manipulation with pandas-style operations. Supports CSV, Excel (XLSX, XLS, ODS), Parquet, and Avro formats with formula evaluation, data transformation, and comprehensive analytics capabilities.
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
//! REST API server mode
//!
//! Provides HTTP API endpoints for xls-rs operations using axum.
//!
//! # Example
//!
//! ```no_run
//! use xls_rs::api::{ApiConfig, ApiServer};
//!
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//!     let config = ApiConfig::default();
//!     let server = ApiServer::new(config);
//!     server.start().await?;
//!     Ok(())
//! }
//! ```

use anyhow::Result;
use serde::{Deserialize, Serialize};

#[cfg(feature = "api")]
use axum::{
    extract::{DefaultBodyLimit, Json},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::post,
    Router,
};
#[cfg(feature = "api")]
use tower_http::{
    cors::{Any, CorsLayer},
    limit::RequestBodyLimitLayer,
};

#[cfg(feature = "api")]
use anyhow::Context;

/// API server configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApiConfig {
    pub host: String,
    pub port: u16,
    pub cors_enabled: bool,
    pub max_request_size: usize,
}

impl Default for ApiConfig {
    fn default() -> Self {
        Self {
            host: "127.0.0.1".to_string(),
            port: 8080,
            cors_enabled: true,
            max_request_size: 10 * 1024 * 1024, // 10MB
        }
    }
}

/// API request types
#[derive(Debug, Deserialize)]
#[serde(tag = "operation")]
pub enum ApiRequest {
    Read {
        input: String,
        sheet: Option<String>,
        range: Option<String>,
    },
    Write {
        output: String,
        data: Vec<Vec<String>>,
        sheet: Option<String>,
    },
    Convert {
        input: String,
        output: String,
        sheet: Option<String>,
    },
    Profile {
        input: String,
        sample_size: Option<usize>,
    },
    Validate {
        input: String,
        rules: String,
    },
    Filter {
        input: String,
        where_clause: String,
    },
    Sort {
        input: String,
        column: String,
        ascending: bool,
    },
}

/// API response
#[derive(Debug, Serialize)]
pub struct ApiResponse {
    pub success: bool,
    pub data: Option<serde_json::Value>,
    pub error: Option<String>,
    pub message: Option<String>,
}

impl ApiResponse {
    pub fn success(data: serde_json::Value) -> Self {
        Self {
            success: true,
            data: Some(data),
            error: None,
            message: None,
        }
    }

    pub fn error(message: String) -> Self {
        Self {
            success: false,
            data: None,
            error: Some(message),
            message: None,
        }
    }

    pub fn message(message: String) -> Self {
        Self {
            success: true,
            data: None,
            error: None,
            message: Some(message),
        }
    }
}

/// API server
pub struct ApiServer {
    config: ApiConfig,
}

impl ApiServer {
    pub fn new(config: ApiConfig) -> Self {
        Self { config }
    }

    /// Start the API server (requires the "api" feature)
    #[cfg(feature = "api")]
    pub async fn start(&self) -> Result<()> {
        // Build our application with routes
        let app = Router::new()
            .route("/api/read", post(handle_read))
            .route("/api/write", post(handle_write))
            .route("/api/convert", post(handle_convert))
            .route("/api/profile", post(handle_profile))
            .route("/api/validate", post(handle_validate))
            .route("/api/filter", post(handle_filter))
            .route("/api/sort", post(handle_sort))
            .layer(DefaultBodyLimit::max(self.config.max_request_size))
            .layer(RequestBodyLimitLayer::new(self.config.max_request_size));

        let app = if self.config.cors_enabled {
            app.layer(CorsLayer::new().allow_origin(Any).allow_methods(Any).allow_headers(Any))
        } else {
            app
        };

        let addr = format!("{}:{}", self.config.host, self.config.port);
        let listener = tokio::net::TcpListener::bind(&addr)
            .await
            .with_context(|| format!("Failed to bind to {addr}"))?;

        println!("🚀 API server listening on http://{}", addr);
        println!("📊 Available endpoints:");
        println!("   POST /api/read      - Read data from a file");
        println!("   POST /api/write     - Write data to a file");
        println!("   POST /api/convert   - Convert between file formats");
        println!("   POST /api/profile   - Generate data profile");
        println!("   POST /api/validate  - Validate data against rules");
        println!("   POST /api/filter    - Filter data rows");
        println!("   POST /api/sort      - Sort data by column");

        axum::serve(listener, app).await.context("API server error")?;

        Ok(())
    }

    /// Start the API server (fallback when "api" feature is not enabled)
    #[cfg(not(feature = "api"))]
    pub async fn start(&self) -> Result<()> {
        use anyhow::bail;
        bail!(
            "API server is not enabled. Please rebuild with the 'api' feature: cargo build --features api"
        )
    }
}

/// Error response type
#[cfg(feature = "api")]
struct ApiError(anyhow::Error);

#[cfg(feature = "api")]
impl IntoResponse for ApiError {
    fn into_response(self) -> Response {
        let body = Json(ApiResponse::error(self.0.to_string()));
        (StatusCode::INTERNAL_SERVER_ERROR, body).into_response()
    }
}

/// Handler for /api/read
#[cfg(feature = "api")]
async fn handle_read(Json(req): Json<ApiRequest>) -> Result<Json<ApiResponse>, ApiError> {
    use crate::converter::Converter;
    use crate::csv_handler::CellRange;
    use crate::helpers::filter_by_range;

    let converter = Converter::new();

    let (input, sheet, range) = match req {
        ApiRequest::Read { input, sheet, range } => (input, sheet, range),
        _ => return Err(ApiError(anyhow::anyhow!("Invalid request"))),
    };

    let mut data = converter
        .read_any_data(&input, sheet.as_deref())
        .map_err(ApiError)?;

    if let Some(ref range_str) = range {
        let cell = CellRange::parse(range_str).map_err(ApiError)?;
        data = filter_by_range(&data, &cell);
    }

    let response = ApiResponse::success(serde_json::json!({ "data": data }));

    Ok(Json(response))
}

/// Handler for /api/write
#[cfg(feature = "api")]
async fn handle_write(Json(req): Json<ApiRequest>) -> Result<Json<ApiResponse>, ApiError> {
    use crate::traits::{DataWriteOptions, DataWriter};

    let (output, data, sheet) = match req {
        ApiRequest::Write { output, data, sheet } => (output, data, sheet),
        _ => return Err(ApiError(anyhow::anyhow!("Invalid request"))),
    };

    // Determine file format from extension
    let format = output
        .rsplit('.')
        .next()
        .ok_or_else(|| ApiError(anyhow::anyhow!("Invalid file path")))?;

    let options = DataWriteOptions {
        sheet_name: sheet,
        column_names: None,
        include_headers: true,
    };

    match format {
        "csv" => {
            use crate::csv_handler::CsvHandler;
            let handler = CsvHandler::new();
            handler
                .write(&output, &data, options)
                .map_err(ApiError)?;
        }
        "xlsx" => {
            use crate::excel::ExcelHandler;
            let handler = ExcelHandler::new();
            handler
                .write(&output, &data, options)
                .map_err(ApiError)?;
        }
        "parquet" => {
            use crate::columnar::ParquetHandler;
            let handler = ParquetHandler::new();
            let (col_names, body): (Option<&[String]>, &[Vec<String>]) =
                if options.include_headers && !data.is_empty() {
                    (Some(&data[0]), data.get(1..).unwrap_or_default())
                } else {
                    (None, &data)
                };
            if body.is_empty() {
                return Err(ApiError(anyhow::anyhow!(
                    "Cannot write empty data to Parquet"
                )));
            }
            handler
                .write(&output, body, col_names)
                .map_err(ApiError)?;
        }
        "avro" => {
            use crate::columnar::AvroHandler;
            let handler = AvroHandler::new();
            let (field_names, body): (Option<&[String]>, &[Vec<String>]) =
                if options.include_headers && !data.is_empty() {
                    (Some(&data[0]), data.get(1..).unwrap_or_default())
                } else {
                    (None, &data)
                };
            if body.is_empty() {
                return Err(ApiError(anyhow::anyhow!("Cannot write empty data to Avro")));
            }
            handler
                .write(&output, body, field_names)
                .map_err(ApiError)?;
        }
        _ => {
            return Err(ApiError(anyhow::anyhow!(
                "Unsupported output format: {}",
                format
            )))
        }
    }

    Ok(Json(ApiResponse::message(format!(
        "Data written to {}",
        output
    ))))
}

/// Handler for /api/convert
#[cfg(feature = "api")]
async fn handle_convert(Json(req): Json<ApiRequest>) -> Result<Json<ApiResponse>, ApiError> {
    use crate::converter::Converter;

    let (input, output, sheet) = match req {
        ApiRequest::Convert { input, output, sheet } => (input, output, sheet),
        _ => return Err(ApiError(anyhow::anyhow!("Invalid request"))),
    };

    let converter = Converter::new();
    converter
        .convert(&input, &output, sheet.as_deref())
        .map_err(ApiError)?;

    Ok(Json(ApiResponse::message(format!(
        "Converted {} to {}",
        input, output
    ))))
}

/// Handler for /api/profile
#[cfg(feature = "api")]
async fn handle_profile(Json(req): Json<ApiRequest>) -> Result<Json<ApiResponse>, ApiError> {
    use crate::converter::Converter;
    use crate::profiling::DataProfiler;

    let (input, sample_size) = match req {
        ApiRequest::Profile { input, sample_size } => (input, sample_size),
        _ => return Err(ApiError(anyhow::anyhow!("Invalid request"))),
    };

    let converter = Converter::new();
    let data = converter
        .read_any_data(&input, None)
        .map_err(ApiError)?;

    let mut profiler = DataProfiler::new();
    if let Some(size) = sample_size {
        profiler = profiler.with_sample_size(size);
    }

    let profile = profiler.profile(&data, &input).map_err(ApiError)?;

    let value = serde_json::to_value(profile).map_err(|e| {
        ApiError(anyhow::anyhow!("Failed to serialize profile: {}", e))
    })?;

    Ok(Json(ApiResponse::success(value)))
}

/// Handler for /api/validate
#[cfg(feature = "api")]
async fn handle_validate(Json(req): Json<ApiRequest>) -> Result<Json<ApiResponse>, ApiError> {
    use crate::converter::Converter;
    use crate::validation::{DataValidator, ValidationConfig};

    let (input, rules) = match req {
        ApiRequest::Validate { input, rules } => (input, rules),
        _ => return Err(ApiError(anyhow::anyhow!("Invalid request"))),
    };

    let converter = Converter::new();
    let data = converter
        .read_any_data(&input, None)
        .map_err(ApiError)?;

    let config: ValidationConfig = serde_json::from_str(&rules)
        .map_err(|e| ApiError(anyhow::anyhow!("Invalid validation config JSON: {}", e)))?;

    let validator = DataValidator::new(config);
    let result = validator.validate(&data).map_err(ApiError)?;

    let value = serde_json::to_value(result)
        .map_err(|e| ApiError(anyhow::anyhow!("Failed to serialize validation result: {}", e)))?;

    Ok(Json(ApiResponse::success(value)))
}

/// Handler for /api/filter
#[cfg(feature = "api")]
async fn handle_filter(Json(req): Json<ApiRequest>) -> Result<Json<ApiResponse>, ApiError> {
    use crate::converter::Converter;
    use crate::operations::DataOperations;

    let (input, where_clause) = match req {
        ApiRequest::Filter {
            input,
            where_clause,
        } => (input, where_clause),
        _ => return Err(ApiError(anyhow::anyhow!("Invalid request"))),
    };

    let converter = Converter::new();
    let data = converter.read_any_data(&input, None).map_err(ApiError)?;

    let ops = DataOperations::new();
    let filtered = ops.query(&data, &where_clause).map_err(ApiError)?;

    Ok(Json(ApiResponse::success(serde_json::json!({ "data": filtered }))))
}

/// Handler for /api/sort
#[cfg(feature = "api")]
async fn handle_sort(Json(req): Json<ApiRequest>) -> Result<Json<ApiResponse>, ApiError> {
    use crate::converter::Converter;
    use crate::operations::DataOperations;
    use crate::traits::SortOperator;

    let (input, column, ascending) = match req {
        ApiRequest::Sort {
            input,
            column,
            ascending,
        } => (input, column, ascending),
        _ => return Err(ApiError(anyhow::anyhow!("Invalid request"))),
    };

    let converter = Converter::new();
    let mut data = converter.read_any_data(&input, None).map_err(ApiError)?;

    let ops = DataOperations::new();

    // Find column index by name
    if data.is_empty() {
        return Err(ApiError(anyhow::anyhow!("Data is empty")));
    }

    let column_idx = data[0]
        .iter()
        .position(|c| c == &column)
        .ok_or_else(|| ApiError(anyhow::anyhow!("Column '{}' not found", column)))?;

    ops.sort(&mut data, column_idx, ascending).map_err(ApiError)?;

    Ok(Json(ApiResponse::success(serde_json::json!({ "data": data }))))
}

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

    #[test]
    fn test_api_config_default() {
        let config = ApiConfig::default();
        assert_eq!(config.host, "127.0.0.1");
        assert_eq!(config.port, 8080);
        assert!(config.cors_enabled);
        assert_eq!(config.max_request_size, 10 * 1024 * 1024);
    }

    #[test]
    fn test_api_response_success() {
        let response = ApiResponse::success(serde_json::json!({"test": "data"}));
        assert!(response.success);
        assert!(response.data.is_some());
        assert!(response.error.is_none());
    }

    #[test]
    fn test_api_response_error() {
        let response = ApiResponse::error("Test error".to_string());
        assert!(!response.success);
        assert!(response.data.is_none());
        assert!(response.error.is_some());
    }

    #[test]
    fn test_api_response_message() {
        let response = ApiResponse::message("Test message".to_string());
        assert!(response.success);
        assert!(response.message.is_some());
        assert_eq!(response.message.unwrap(), "Test message");
    }
}