genfile 0.6.0

CLI for genfile_core template archive management - create, manage, and materialize code generation templates.
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
//! Analysis command handlers - FR8: Archive Analysis
//!
//! Provides inspection and analysis capabilities for template archives.
//!
//! ## Design Decisions
//!
//! **Idempotent Read-Only Operations:**
//! All analysis commands are read-only and idempotent - they never modify archive state.
//! This allows safe exploration without worrying about side effects.
//!
//! **`genfile_core` API Usage:**
//! - `archive.discover_parameters()` - Auto-detects {{}} placeholders via regex
//! - `archive.analyze_parameter_usage()` - Maps parameters to files using them
//! - `archive.file_count()`, `text_file_count()`, `binary_file_count()` - Statistics
//! - `archive.total_size()` - Size calculations
//!
//! **Verbosity Levels:**
//! - 0: Silent (for scripting)
//! - 1: Summary (default, user-friendly)
//! - 2+: Detailed (includes lists, breakdowns)

// Handler functions are registered via unilang::CommandRegistry::command_add_runtime,
// which requires fn(VerifiedCommand, ExecutionContext) -> ... by value.
#![ allow( clippy::needless_pass_by_value ) ]

use unilang::semantic::VerifiedCommand;
use unilang::data::{ OutputData, ErrorData };
use unilang::interpreter::ExecutionContext;
use core::fmt::Write as _;

/// Handler for .info command
///
/// Displays archive metadata and statistics.
///
/// # Parameters
/// - `verbosity` - Output verbosity (0-5, default: 1)
///
/// # Errors
/// Returns state error if no archive is loaded.
#[ allow( clippy::too_many_lines ) ]
pub fn info_handler(
  cmd : VerifiedCommand,
  _ctx : ExecutionContext
) -> Result< OutputData, ErrorData >
{
  let verbosity = cmd.get_integer( "verbosity" ).unwrap_or( 1 );

  // Get loaded archive from shared state
  let archive = crate::handlers::shared_state::get_current_archive()
    .ok_or_else( || crate::error::state_error( "No archive loaded. Use .archive.load first." ) )?;

  let file_count = archive.file_count();
  let text_count = archive.text_file_count();
  let binary_count = archive.binary_file_count();
  let total_size = archive.total_size();
  let param_count = archive.parameters.descriptors.len();

  // Format output based on verbosity
  let output_content = match verbosity
  {
    0 => String::new(),
    1 =>
    {
      format!(
        "Archive: {}\nFiles: {} ({} text, {} binary)\nSize: {} bytes\nParameters: {}",
        archive.name,
        file_count,
        text_count,
        binary_count,
        total_size,
        param_count
      )
    }
    _ =>
    {
      let mut details = format!(
        "Archive Information\n\
        ==================\n\
        Name: {}\n\
        Version: {}\n",
        archive.name,
        archive.version
      );

      if let Some( ref desc ) = archive.description
      {
        let _ = writeln!( &mut details, "Description: {desc}" );
      }

      let _ = write!(
        &mut details,
        "\nStatistics\n\
        ----------\n\
        Total Files: {file_count}\n\
        Text Files: {text_count}\n\
        Binary Files: {binary_count}\n\
        Total Size: {total_size} bytes\n\
        Parameters Defined: {param_count}\n"
      );

      if verbosity >= 3 && !archive.files.is_empty()
      {
        details.push_str( "\nFiles\n-----\n" );
        for file in &archive.files
        {
          let _ = writeln!( &mut details, "  {}", file.path.display() );
        }
      }

      details
    }
  };

  Ok( OutputData
  {
    content : output_content,
    format : "text".to_string(),
    execution_time_ms : None,
  } )
}

/// Handler for .discover.parameters command
///
/// Auto-detects template parameters in archive files.
/// Uses `genfile_core`'s regex-based {{variable}} detection.
///
/// # Parameters
/// - `verbosity` - Output verbosity (0-5, default: 1)
///
/// # Errors
/// Returns state error if no archive is loaded.
#[ allow( clippy::too_many_lines ) ]
pub fn discover_parameters_handler(
  cmd : VerifiedCommand,
  _ctx : ExecutionContext
) -> Result< OutputData, ErrorData >
{
  let verbosity = cmd.get_integer( "verbosity" ).unwrap_or( 1 );

  // Get loaded archive from shared state
  let archive = crate::handlers::shared_state::get_current_archive()
    .ok_or_else( || crate::error::state_error( "No archive loaded. Use .archive.load first." ) )?;

  // Discover parameters using genfile_core
  let discovered = archive.discover_parameters();
  let param_count = discovered.len();

  // Convert HashSet to sorted Vec for consistent output
  let mut params : Vec< String > = discovered.into_iter().collect();
  params.sort();

  // Format output based on verbosity
  let output_content = match verbosity
  {
    0 => String::new(),
    1 =>
    {
      if param_count == 0
      {
        "No parameters discovered".to_string()
      }
      else
      {
        format!( "Discovered {} parameters: {}", param_count, params.join( ", " ) )
      }
    }
    _ =>
    {
      let mut details = format!(
        "Parameter Discovery\n\
        ===================\n\
        Found: {param_count} parameters\n"
      );

      if !params.is_empty()
      {
        details.push_str( "\nDiscovered Parameters\n---------------------\n" );
        for param in &params
        {
          let _ = writeln!( &mut details, "  - {param}" );
        }
      }

      if verbosity >= 3 && !params.is_empty()
      {
        // Show parameter usage across files
        let usage = archive.analyze_parameter_usage();
        details.push_str( "\nParameter Usage\n---------------\n" );
        for param in &params
        {
          if let Some( files ) = usage.get( param )
          {
            let _ = writeln!( &mut details, "  {} (used in {} files)", param, files.len() );
            if verbosity >= 4
            {
              for file in files
              {
                let _ = writeln!( &mut details, "    - {}", file.display() );
              }
            }
          }
        }
      }

      details
    }
  };

  Ok( OutputData
  {
    content : output_content,
    format : "text".to_string(),
    execution_time_ms : None,
  } )
}

/// Handler for .status command
///
/// Shows archive readiness and completeness status.
///
/// # Parameters
/// - `verbosity` - Output verbosity (0-5, default: 1)
///
/// # Errors
/// Returns state error if no archive is loaded.
#[ allow( clippy::too_many_lines ) ]
pub fn status_handler(
  cmd : VerifiedCommand,
  _ctx : ExecutionContext
) -> Result< OutputData, ErrorData >
{
  let verbosity = cmd.get_integer( "verbosity" ).unwrap_or( 1 );

  // Get loaded archive from shared state
  let archive = crate::handlers::shared_state::get_current_archive()
    .ok_or_else( || crate::error::state_error( "No archive loaded. Use .archive.load first." ) )?;

  // Analyze readiness
  let mandatory_params = archive.parameters.list_mandatory();
  let defined_params = archive.parameters.descriptors.len();
  let set_values = archive.values.as_ref().map_or( 0, genfile_core::Values::len );

  // Check if ready to materialize
  let missing_mandatory : Vec< &str > = mandatory_params
    .iter()
    .filter( | p |
    {
      archive
        .values
        .as_ref()
        .is_none_or( | v | !v.has_value( p ) )
    })
    .copied()
    .collect();

  let ready = missing_mandatory.is_empty();

  // Format output based on verbosity
  let output_content = match verbosity
  {
    0 => String::new(),
    1 =>
    {
      if ready
      {
        format!( "Status: Ready to materialize ({set_values} parameters set)" )
      }
      else
      {
        format!(
          "Status: Not ready - {} mandatory parameters missing: {}",
          missing_mandatory.len(),
          missing_mandatory.join( ", " )
        )
      }
    }
    _ =>
    {
      let mut details = format!(
        "Archive Status\n\
        ==============\n\
        Archive: {}\n\
        Files: {}\n\
        Parameters Defined: {}\n\
        Values Set: {}\n\
        Mandatory Parameters: {}\n",
        archive.name,
        archive.file_count(),
        defined_params,
        set_values,
        mandatory_params.len()
      );

      if ready
      {
        details.push_str( "\nReadiness: ✓ Ready to materialize\n" );
      }
      else
      {
        details.push_str( "\nReadiness: ✗ Not ready\n" );
        details.push_str( "\nMissing Mandatory Values\n------------------------\n" );
        for param in &missing_mandatory
        {
          let _ = writeln!( &mut details, "  - {param}" );
        }
      }

      if verbosity >= 3 && defined_params > 0
      {
        details.push_str( "\nDefined Parameters\n------------------\n" );
        for param_desc in &archive.parameters.descriptors
        {
          let mandatory_marker = if param_desc.is_mandatory { " (mandatory)" } else { "" };
          let has_value = archive
            .values
            .as_ref()
            .is_some_and( | v | v.has_value( &param_desc.parameter ) );
          let value_marker = if has_value { " [set]" } else { "" };

          let _ = writeln!(
            &mut details,
            "  - {}{}{}",
            param_desc.parameter,
            mandatory_marker,
            value_marker
          );
        }
      }

      details
    }
  };

  Ok( OutputData
  {
    content : output_content,
    format : "text".to_string(),
    execution_time_ms : None,
  } )
}

/// Handler for .analyze command
///
/// Comprehensive archive analysis combining all insights.
///
/// # Parameters
/// - `verbosity` - Output verbosity (0-5, default: 1)
///
/// # Errors
/// Returns state error if no archive is loaded.
#[ allow( clippy::too_many_lines ) ]
pub fn analyze_handler(
  cmd : VerifiedCommand,
  _ctx : ExecutionContext
) -> Result< OutputData, ErrorData >
{
  let verbosity = cmd.get_integer( "verbosity" ).unwrap_or( 1 );

  // Get loaded archive from shared state
  let archive = crate::handlers::shared_state::get_current_archive()
    .ok_or_else( || crate::error::state_error( "No archive loaded. Use .archive.load first." ) )?;

  // Gather all analysis data
  let file_count = archive.file_count();
  let text_count = archive.text_file_count();
  let binary_count = archive.binary_file_count();
  let total_size = archive.total_size();
  let discovered = archive.discover_parameters();
  let defined_params = archive.parameters.descriptors.len();
  let mandatory_params = archive.parameters.list_mandatory();
  let set_values = archive.values.as_ref().map_or( 0, genfile_core::Values::len );

  // Check readiness
  let missing_mandatory : Vec< &str > = mandatory_params
    .iter()
    .filter( | p |
    {
      archive
        .values
        .as_ref()
        .is_none_or( | v | !v.has_value( p ) )
    })
    .copied()
    .collect();

  let ready = missing_mandatory.is_empty();

  // Format output based on verbosity
  let output_content = match verbosity
  {
    0 => String::new(),
    1 =>
    {
      format!(
        "Archive Analysis Summary\n\
        Archive: {}\n\
        Files: {} ({} text, {} binary, {} bytes)\n\
        Parameters: {} defined, {} discovered\n\
        Status: {}",
        archive.name,
        file_count,
        text_count,
        binary_count,
        total_size,
        defined_params,
        discovered.len(),
        if ready { "Ready to materialize" } else { "Not ready (missing mandatory values)" }
      )
    }
    _ =>
    {
      let mut details = format!(
        "Comprehensive Archive Analysis\n\
        ==============================\n\
        \n\
        Archive Metadata\n\
        ----------------\n\
        Name: {}\n\
        Version: {}\n",
        archive.name,
        archive.version
      );

      if let Some( ref desc ) = archive.description
      {
        let _ = writeln!( &mut details, "Description: {desc}" );
      }

      let _ = write!(
        &mut details,
        "\nFile Statistics\n\
        ---------------\n\
        Total Files: {file_count}\n\
        Text Files: {text_count}\n\
        Binary Files: {binary_count}\n\
        Total Size: {total_size} bytes\n"
      );

      let _ = write!(
        &mut details,
        "\nParameter Analysis\n\
        ------------------\n\
        Discovered in Templates: {}\n\
        Defined: {}\n\
        Mandatory: {}\n\
        Values Set: {}\n",
        discovered.len(),
        defined_params,
        mandatory_params.len(),
        set_values
      );

      if ready
      {
        details.push_str( "\nReadiness Status\n----------------\n✓ Ready to materialize\n" );
      }
      else
      {
        let _ = write!(
          &mut details,
          "\nReadiness Status\n\
          ----------------\n\
          ✗ Not ready\n\
          Missing mandatory values: {}\n",
          missing_mandatory.join( ", " )
        );
      }

      if verbosity >= 3
      {
        let mut discovered_vec : Vec< String > = discovered.into_iter().collect();
        discovered_vec.sort();

        if !discovered_vec.is_empty()
        {
          details.push_str( "\nDiscovered Parameters\n---------------------\n" );
          for param in &discovered_vec
          {
            let _ = writeln!( &mut details, "  - {param}" );
          }
        }

        if !archive.files.is_empty()
        {
          details.push_str( "\nArchive Files\n-------------\n" );
          for file in &archive.files
          {
            let _ = writeln!( &mut details, "  {}", file.path.display() );
          }
        }
      }

      details
    }
  };

  Ok( OutputData
  {
    content : output_content,
    format : "text".to_string(),
    execution_time_ms : None,
  } )
}