pmat 3.16.0

PMAT - Zero-config AI context generation and code quality toolkit (CLI, MCP, HTTP)
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
532
533
534
535
536
use crate::cli::args;
use crate::models::template::{
    ParameterSpec, ParameterType, TemplateCategory, TemplateResource, Toolchain,
};
use crate::stateless_server::StatelessTemplateServer;
use semver::Version;
use serde_json::{json, Value};
use std::sync::Arc;
use tempfile::TempDir;
use tokio::fs;

#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod cli_args_tests {
    use super::*;

    #[test]
    fn test_validate_params_all_valid() {
        let specs = vec![
            ParameterSpec {
                name: "project_name".to_string(),
                param_type: ParameterType::String,
                required: true,
                default_value: None,
                description: "Project name".to_string(),
                validation_pattern: None,
            },
            ParameterSpec {
                name: "has_tests".to_string(),
                param_type: ParameterType::Boolean,
                required: false,
                default_value: Some("true".to_string()),
                description: "Include tests".to_string(),
                validation_pattern: None,
            },
        ];

        let mut params = serde_json::Map::new();
        params.insert("project_name".to_string(), json!("my-project"));
        params.insert("has_tests".to_string(), json!(false));

        let result = args::validate_params(&specs, &params);
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_params_missing_required() {
        let specs = vec![ParameterSpec {
            name: "project_name".to_string(),
            param_type: ParameterType::String,
            required: true,
            default_value: None,
            description: "Project name".to_string(),
            validation_pattern: None,
        }];

        let params = serde_json::Map::new();

        let result = args::validate_params(&specs, &params);
        assert!(result.is_err());
        let errors = result.unwrap_err();
        assert_eq!(errors.len(), 1);
        assert!(errors[0].contains("Missing required parameter: project_name"));
    }

    #[test]
    fn test_validate_params_unknown_parameter() {
        let specs = vec![ParameterSpec {
            name: "project_name".to_string(),
            param_type: ParameterType::String,
            required: true,
            default_value: None,
            description: "Project name".to_string(),
            validation_pattern: None,
        }];

        let mut params = serde_json::Map::new();
        params.insert("project_name".to_string(), json!("my-project"));
        params.insert("unknown_param".to_string(), json!("value"));

        let result = args::validate_params(&specs, &params);
        assert!(result.is_err());
        let errors = result.unwrap_err();
        assert!(errors
            .iter()
            .any(|e| e.contains("Unknown parameter: unknown_param")));
    }

    #[test]
    fn test_validate_params_type_validation() {
        let specs = vec![ParameterSpec {
            name: "has_tests".to_string(),
            param_type: ParameterType::Boolean,
            required: true,
            default_value: None,
            description: "Include tests".to_string(),
            validation_pattern: None,
        }];

        // Boolean value should work
        let mut params = serde_json::Map::new();
        params.insert("has_tests".to_string(), json!(true));
        assert!(args::validate_params(&specs, &params).is_ok());

        // String value should also work (will be parsed later)
        let mut params = serde_json::Map::new();
        params.insert("has_tests".to_string(), json!("true"));
        assert!(args::validate_params(&specs, &params).is_ok());

        // Number value should fail
        let mut params = serde_json::Map::new();
        params.insert("has_tests".to_string(), json!(123));
        let result = args::validate_params(&specs, &params);
        assert!(result.is_err());
        let errors = result.unwrap_err();
        assert!(errors[0].contains("Invalid type"));
    }

    #[test]
    fn test_expand_env_vars() {
        std::env::set_var("TEST_USER", "alice");
        std::env::set_var("TEST_HOME", "/home/alice");

        let template = "Hello ${TEST_USER}, your home is ${TEST_HOME}";
        let expanded = args::expand_env_vars(template);
        assert_eq!(expanded, "Hello alice, your home is /home/alice");

        // Test with missing env var
        let template = "Missing: ${NONEXISTENT_VAR}";
        let expanded = args::expand_env_vars(template);
        assert_eq!(expanded, "Missing: ${NONEXISTENT_VAR}");

        // Cleanup
        std::env::remove_var("TEST_USER");
        std::env::remove_var("TEST_HOME");
    }

    #[test]
    fn test_expand_env_vars_no_vars() {
        let template = "No variables here";
        let expanded = args::expand_env_vars(template);
        assert_eq!(expanded, "No variables here");
    }

    #[test]
    fn test_expand_env_vars_multiple_occurrences() {
        std::env::set_var("TEST_VAR", "value");

        let template = "${TEST_VAR} and ${TEST_VAR} again";
        let expanded = args::expand_env_vars(template);
        assert_eq!(expanded, "value and value again");

        std::env::remove_var("TEST_VAR");
    }
}

#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod cli_integration_tests {
    use super::*;

    async fn create_test_server() -> Arc<StatelessTemplateServer> {
        Arc::new(StatelessTemplateServer::new().unwrap())
    }

    #[tokio::test]
    async fn test_generate_command_to_stdout() {
        let _server = create_test_server().await;

        // Capture stdout by writing to a file
        let temp_dir = TempDir::new().unwrap();
        let _output_file = temp_dir.path().join("output.txt");

        // We can't easily test stdout directly in unit tests, but we can test the file output
        // Skip this test for now - would need to refactor CLI to be more testable
    }

    #[tokio::test]
    async fn test_generate_command_to_file() {
        let _server = create_test_server().await;
        let temp_dir = TempDir::new().unwrap();
        let output_file = temp_dir.path().join("Makefile");

        // Simulate CLI args
        let _args = [
            "pmat",
            "generate",
            "makefile",
            "rust/cli",
            "-p",
            "project_name=test-project",
            "-p",
            "has_tests=true",
            "-o",
            output_file.to_str().unwrap(),
        ];

        // We would need to refactor the CLI to make it testable
        // For now, we'll test the underlying functions directly
    }

    #[tokio::test]
    async fn test_list_command_json_format() {
        let _server = create_test_server().await;

        // Test listing templates - would need CLI refactoring for proper testing
    }

    #[tokio::test]
    async fn test_search_command() {
        let _server = create_test_server().await;

        // Test search functionality - would need CLI refactoring
    }

    #[tokio::test]
    async fn test_validate_command() {
        let _server = create_test_server().await;

        // Test validation - would need CLI refactoring
    }

    #[tokio::test]
    async fn test_scaffold_command() {
        let _server = create_test_server().await;
        let _temp_dir = TempDir::new().unwrap();

        // Test scaffolding - would need CLI refactoring
    }

    #[tokio::test]
    async fn test_context_command() {
        let _server = create_test_server().await;
        let temp_dir = TempDir::new().unwrap();

        // Create test project files
        let project_dir = temp_dir.path().join("test-project");
        fs::create_dir_all(&project_dir).await.unwrap();

        // Create a Rust project
        fs::write(
            project_dir.join("Cargo.toml"),
            r#"[package]
name = "test-project"
version = "0.1.0"
"#,
        )
        .await
        .unwrap();

        fs::write(
            project_dir.join("main.rs"),
            r#"fn main() {
    println!("Hello, world!");
}
"#,
        )
        .await
        .unwrap();

        // Test context generation - would need CLI refactoring
    }
}

#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod cli_parsing_tests {
    use super::*;

    #[test]
    fn test_parse_key_val() {
        // This function is private in the CLI module, but we can test similar logic

        // Test basic key=value
        let input = "name=value";
        let parts: Vec<&str> = input.splitn(2, '=').collect();
        assert_eq!(parts.len(), 2);
        assert_eq!(parts[0], "name");
        assert_eq!(parts[1], "value");

        // Test with = in value
        let input = "url=https://example.com?foo=bar";
        let parts: Vec<&str> = input.splitn(2, '=').collect();
        assert_eq!(parts.len(), 2);
        assert_eq!(parts[0], "url");
        assert_eq!(parts[1], "https://example.com?foo=bar");

        // Test without =
        let input = "invalid";
        let parts: Vec<&str> = input.splitn(2, '=').collect();
        assert_eq!(parts.len(), 1);
    }

    #[test]
    fn test_value_type_inference() {
        // Test boolean inference
        assert_eq!(json!("true"), Value::String("true".to_string()));
        assert_eq!(json!(true), Value::Bool(true));

        // Test number inference
        assert_eq!(json!("123"), Value::String("123".to_string()));
        assert_eq!(json!(123), Value::Number(123.into()));

        // Test float inference
        assert_eq!(json!("123.45"), Value::String("123.45".to_string()));
        assert_eq!(
            json!(123.45),
            Value::Number(serde_json::Number::from_f64(123.45).unwrap())
        );
    }
}

#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod cli_output_tests {
    use super::*;

    #[test]
    fn test_table_formatting() {
        // Test table output formatting logic
        let templates = [
            Arc::new(TemplateResource {
                uri: "template://makefile/rust/cli".to_string(),
                category: TemplateCategory::Makefile,
                toolchain: Toolchain::RustCli {
                    cargo_features: vec![],
                },
                name: "Rust CLI Binary Makefile".to_string(),
                description: "Makefile for Rust CLI applications".to_string(),
                parameters: vec![ParameterSpec {
                    name: "project_name".to_string(),
                    param_type: ParameterType::String,
                    required: true,
                    default_value: None,
                    description: "Project name".to_string(),
                    validation_pattern: None,
                }],
                content_hash: "hash123".to_string(),
                semantic_version: Version::parse("1.0.0").unwrap(),
                dependency_graph: vec![],
                s3_object_key: "templates/makefile/rust/cli.hbs".to_string(),
            }),
            Arc::new(TemplateResource {
                uri: "template://readme/deno/cli".to_string(),
                category: TemplateCategory::Readme,
                toolchain: Toolchain::DenoTypescript {
                    deno_version: "1.40.0".to_string(),
                },
                name: "Deno CLI README".to_string(),
                description: "README for Deno CLI applications".to_string(),
                parameters: vec![],
                content_hash: "hash456".to_string(),
                semantic_version: Version::parse("1.0.0").unwrap(),
                dependency_graph: vec![],
                s3_object_key: "templates/readme/deno/cli.hbs".to_string(),
            }),
        ];

        // Calculate expected column width
        let expected_width = templates.iter().map(|t| t.uri.len()).max().unwrap_or(20);

        assert_eq!(
            expected_width,
            28 // Length of "template://makefile/rust/cli" which is the longest
        );
    }

    #[test]
    fn test_json_output_format() {
        let template = TemplateResource {
            uri: "template://makefile/rust/cli".to_string(),
            category: TemplateCategory::Makefile,
            toolchain: Toolchain::RustCli {
                cargo_features: vec![],
            },
            name: "Test Template".to_string(),
            description: "Test description".to_string(),
            parameters: vec![],
            content_hash: "hash789".to_string(),
            semantic_version: Version::parse("1.0.0").unwrap(),
            dependency_graph: vec![],
            s3_object_key: "test.hbs".to_string(),
        };

        let json = serde_json::to_string_pretty(&template).unwrap();
        assert!(json.contains("\"uri\": \"template://makefile/rust/cli\""));
        assert!(json.contains("\"category\": \"makefile\""));
        assert!(json.contains("\"type\": \"rust\""));
    }

    #[test]
    fn test_yaml_output_format() {
        let template = TemplateResource {
            uri: "template://makefile/rust/cli".to_string(),
            category: TemplateCategory::Makefile,
            toolchain: Toolchain::RustCli {
                cargo_features: vec![],
            },
            name: "Test Template".to_string(),
            description: "Test description".to_string(),
            parameters: vec![],
            content_hash: "hash789".to_string(),
            semantic_version: Version::parse("1.0.0").unwrap(),
            dependency_graph: vec![],
            s3_object_key: "test.hbs".to_string(),
        };

        let yaml = serde_yaml_ng::to_string(&template).unwrap();
        assert!(yaml.contains("uri: template://makefile/rust/cli"));
        assert!(yaml.contains("category: makefile"));
        assert!(yaml.contains("type: rust"));
    }
}

#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod cli_error_handling_tests {
    use super::*;

    #[test]
    fn test_missing_required_params_error() {
        let specs = vec![ParameterSpec {
            name: "required_param".to_string(),
            param_type: ParameterType::String,
            required: true,
            default_value: None,
            description: "Required parameter".to_string(),
            validation_pattern: None,
        }];

        let params = serde_json::Map::new();
        let result = args::validate_params(&specs, &params);

        assert!(result.is_err());
        let errors = result.unwrap_err();
        assert_eq!(errors.len(), 1);
        assert!(errors[0].contains("required_param"));
    }

    #[test]
    fn test_multiple_validation_errors() {
        let specs = vec![
            ParameterSpec {
                name: "param1".to_string(),
                param_type: ParameterType::String,
                required: true,
                default_value: None,
                description: "First param".to_string(),
                validation_pattern: None,
            },
            ParameterSpec {
                name: "param2".to_string(),
                param_type: ParameterType::Boolean,
                required: true,
                default_value: None,
                description: "Second param".to_string(),
                validation_pattern: None,
            },
        ];

        let mut params = serde_json::Map::new();
        // Missing param1
        // Invalid type for param2
        params.insert("param2".to_string(), json!(123));
        // Unknown param
        params.insert("unknown".to_string(), json!("value"));

        let result = args::validate_params(&specs, &params);
        assert!(result.is_err());
        let errors = result.unwrap_err();
        assert!(errors.len() >= 3);
    }
}

#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod cli_mode_detection_tests {

    #[test]
    fn test_cli_parameter_parsing() {
        // Test parameter parsing patterns
        let test_cases = [
            ("key=value", Some(("key", "value"))),
            ("key=", Some(("key", ""))),
            ("invalid", None),
            ("key=value=with=equals", Some(("key", "value=with=equals"))),
        ];

        for (input, expected) in test_cases {
            let parts: Vec<&str> = input.splitn(2, '=').collect();
            match expected {
                Some((key, val)) => {
                    assert_eq!(parts.len(), 2);
                    assert_eq!(parts[0], key);
                    assert_eq!(parts[1], val);
                }
                None => {
                    assert_eq!(parts.len(), 1);
                }
            }
        }
    }

    #[test]
    fn test_template_uri_patterns() {
        // Test valid template URI patterns
        let valid_uris = [
            "template://makefile/rust/cli",
            "template://readme/deno/cli",
            "template://gitignore/python-uv/cli",
        ];

        for uri in valid_uris {
            assert!(uri.starts_with("template://"));
            let parts: Vec<&str> = uri
                .strip_prefix("template://")
                .unwrap()
                .split('/')
                .collect();
            assert_eq!(parts.len(), 3);
        }
    }

    #[test]
    fn test_toolchain_names() {
        // Test expected toolchain names
        let toolchains = ["rust", "deno", "python-uv"];

        for toolchain in toolchains {
            assert!(!toolchain.is_empty());
            assert!(toolchain
                .chars()
                .all(|c| c.is_ascii_lowercase() || c == '-'));
        }
    }
}