repolens 1.4.0

A CLI tool to audit and prepare repositories for open source or enterprise standards
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
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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
//! Template file creation

use crate::error::{ActionError, RepoLensError};
use std::collections::HashMap;
use std::fs;
use std::path::Path;

/// Create a file from a template
pub fn create_file_from_template(
    path: &str,
    template_name: &str,
    variables: &HashMap<String, String>,
) -> Result<(), RepoLensError> {
    let template_content = get_template(template_name)?;

    // Replace variables in template
    let mut content = template_content;
    for (key, value) in variables {
        content = content.replace(&format!("{{{{ {} }}}}", key), value);
        content = content.replace(&format!("{{{{{}}}}}", key), value);
    }

    // Write the file
    let file_path = Path::new(path);

    // Create parent directories if needed
    if let Some(parent) = file_path.parent() {
        if !parent.as_os_str().is_empty() {
            fs::create_dir_all(parent).map_err(|e| {
                RepoLensError::Action(ActionError::DirectoryCreate {
                    path: parent.display().to_string(),
                    source: e,
                })
            })?;
        }
    }

    fs::write(file_path, content).map_err(|e| {
        RepoLensError::Action(ActionError::FileWrite {
            path: path.to_string(),
            source: e,
        })
    })?;

    Ok(())
}

/// Get template content by name
fn get_template(name: &str) -> Result<String, RepoLensError> {
    match name {
        "LICENSE/MIT" => Ok(MIT_LICENSE.to_string()),
        "LICENSE/Apache-2.0" => Ok(APACHE_LICENSE.to_string()),
        "LICENSE/GPL-3.0" => Ok(GPL_LICENSE_HEADER.to_string()),
        "CONTRIBUTING.md" => Ok(CONTRIBUTING_TEMPLATE.to_string()),
        "CODE_OF_CONDUCT.md" => Ok(CODE_OF_CONDUCT_TEMPLATE.to_string()),
        "SECURITY.md" => Ok(SECURITY_TEMPLATE.to_string()),
        "ISSUE_TEMPLATE/bug_report.md" => Ok(BUG_REPORT_TEMPLATE.to_string()),
        "ISSUE_TEMPLATE/feature_request.md" => Ok(FEATURE_REQUEST_TEMPLATE.to_string()),
        "PULL_REQUEST_TEMPLATE/pull_request_template.md" => Ok(PULL_REQUEST_TEMPLATE.to_string()),
        _ => Err(RepoLensError::Action(ActionError::UnknownTemplate {
            name: name.to_string(),
        })),
    }
}

const MIT_LICENSE: &str = r#"MIT License

Copyright (c) {{ year }} {{ author }}

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"#;

const APACHE_LICENSE: &str = r#"                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   Copyright {{ year }} {{ author }}

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
"#;

const GPL_LICENSE_HEADER: &str = r#"Copyright (C) {{ year }} {{ author }}

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
"#;

const CONTRIBUTING_TEMPLATE: &str = r#"# Contributing

Thank you for your interest in contributing to this project!

## How to Contribute

### Reporting Issues

- Check if the issue already exists
- Use a clear and descriptive title
- Provide steps to reproduce the issue
- Include relevant logs or screenshots

### Pull Requests

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Make your changes
4. Run tests to ensure everything works
5. Commit your changes (`git commit -m 'Add amazing feature'`)
6. Push to the branch (`git push origin feature/amazing-feature`)
7. Open a Pull Request

### Code Style

- Follow the existing code style
- Write meaningful commit messages
- Add tests for new features
- Update documentation as needed

### Development Setup

```bash
# Clone the repository
git clone <repository-url>
cd <project>

# Install dependencies
# Add project-specific setup instructions here
```

## Questions?

Feel free to open an issue for any questions or concerns.
"#;

const CODE_OF_CONDUCT_TEMPLATE: &str = r#"# Code of Conduct

## Our Pledge

We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, caste, color, religion, or sexual
identity and orientation.

## Our Standards

Examples of behavior that contributes to a positive environment:

* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members

Examples of unacceptable behavior:

* The use of sexualized language or imagery, and sexual attention or advances
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information without explicit permission
* Other conduct which could reasonably be considered inappropriate

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the project maintainers. All complaints will be reviewed and
investigated promptly and fairly.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org),
version 2.1.
"#;

const SECURITY_TEMPLATE: &str = r#"# Security Policy

## Reporting a Vulnerability

We take security seriously. If you discover a security vulnerability, please follow these steps:

1. **Do not** open a public issue
2. Email us at [security@example.com] with details
3. Include steps to reproduce the vulnerability
4. Allow time for us to investigate and respond

## What to Include

- Type of vulnerability
- Steps to reproduce
- Potential impact
- Suggested fix (if any)

## Response Timeline

- **Initial Response**: Within 48 hours
- **Status Update**: Within 7 days
- **Resolution**: Depends on severity and complexity

## Supported Versions

| Version | Supported          |
| ------- | ------------------ |
| latest  | :white_check_mark: |
| < 1.0   | :x:                |

## Security Best Practices

When using this project:

- Keep dependencies up to date
- Use environment variables for secrets
- Follow the principle of least privilege
- Enable security features where available

Thank you for helping keep this project secure!
"#;

const BUG_REPORT_TEMPLATE: &str = r#"---
name: Bug Report
about: Create a report to help us improve
title: ''
labels: bug
assignees: ''
---

## Description

A clear and concise description of what the bug is.

## Steps to Reproduce

1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error

## Expected Behavior

A clear and concise description of what you expected to happen.

## Actual Behavior

A clear and concise description of what actually happened.

## Environment

- OS: [e.g. Ubuntu 22.04, macOS 13.0, Windows 11]
- Version: [e.g. 1.0.0]
- Rust version: [e.g. 1.70.0]

## Additional Context

Add any other context about the problem here.

## Screenshots

If applicable, add screenshots to help explain your problem.
"#;

const FEATURE_REQUEST_TEMPLATE: &str = r#"---
name: Feature Request
about: Suggest an idea for this project
title: ''
labels: enhancement
assignees: ''
---

## Problem Statement

A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

## Proposed Solution

A clear and concise description of what you want to happen.

## Alternatives Considered

A clear and concise description of any alternative solutions or features you've considered.

## Use Cases

Describe the use cases for this feature:

1. Use case 1
2. Use case 2
3. Use case 3

## Additional Context

Add any other context, mockups, or examples about the feature request here.

## Implementation Notes (Optional)

If you have ideas about how this could be implemented, please share them here.
"#;

const PULL_REQUEST_TEMPLATE: &str = r#"## Description

Brief description of changes.

## Type of Change

- [ ] Bug fix
- [ ] New feature
- [ ] Documentation update
- [ ] Refactoring

## Checklist

- [ ] Code compiles without errors
- [ ] Tests pass
- [ ] Code follows project style guidelines
- [ ] Documentation updated if needed
"#;

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

    #[test]
    fn test_get_template_mit() {
        let template = get_template("LICENSE/MIT").unwrap();
        assert!(template.contains("MIT License"));
        assert!(template.contains("{{ year }}"));
        assert!(template.contains("{{ author }}"));
    }

    #[test]
    fn test_get_template_apache() {
        let template = get_template("LICENSE/Apache-2.0").unwrap();
        assert!(template.contains("Apache License"));
    }

    #[test]
    fn test_get_template_gpl() {
        let template = get_template("LICENSE/GPL-3.0").unwrap();
        assert!(template.contains("GNU General Public License"));
    }

    #[test]
    fn test_get_template_contributing() {
        let template = get_template("CONTRIBUTING.md").unwrap();
        assert!(template.contains("Contributing"));
        assert!(template.contains("Pull Request"));
    }

    #[test]
    fn test_get_template_code_of_conduct() {
        let template = get_template("CODE_OF_CONDUCT.md").unwrap();
        assert!(template.contains("Code of Conduct"));
        assert!(template.contains("harassment-free"));
    }

    #[test]
    fn test_get_template_security() {
        let template = get_template("SECURITY.md").unwrap();
        assert!(template.contains("Security Policy"));
        assert!(template.contains("Vulnerability"));
    }

    #[test]
    fn test_get_template_bug_report() {
        let template = get_template("ISSUE_TEMPLATE/bug_report.md").unwrap();
        assert!(template.contains("Bug Report"));
        assert!(template.contains("Steps to Reproduce"));
    }

    #[test]
    fn test_get_template_feature_request() {
        let template = get_template("ISSUE_TEMPLATE/feature_request.md").unwrap();
        assert!(template.contains("Feature Request"));
        assert!(template.contains("Proposed Solution"));
    }

    #[test]
    fn test_get_template_pull_request() {
        let template = get_template("PULL_REQUEST_TEMPLATE/pull_request_template.md").unwrap();
        assert!(template.contains("Description"));
        assert!(template.contains("Checklist"));
    }

    #[test]
    fn test_get_template_unknown() {
        let result = get_template("UNKNOWN_TEMPLATE");
        assert!(result.is_err());
        match result {
            Err(RepoLensError::Action(ActionError::UnknownTemplate { name })) => {
                assert_eq!(name, "UNKNOWN_TEMPLATE");
            }
            _ => panic!("Expected UnknownTemplate error"),
        }
    }

    #[test]
    fn test_create_file_from_template() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("LICENSE");

        let mut variables = HashMap::new();
        variables.insert("year".to_string(), "2024".to_string());
        variables.insert("author".to_string(), "Test Author".to_string());

        create_file_from_template(file_path.to_str().unwrap(), "LICENSE/MIT", &variables).unwrap();

        let content = fs::read_to_string(&file_path).unwrap();
        assert!(content.contains("MIT License"));
        assert!(content.contains("2024"));
        assert!(content.contains("Test Author"));
        assert!(!content.contains("{{ year }}"));
        assert!(!content.contains("{{ author }}"));
    }

    #[test]
    fn test_create_file_from_template_with_nested_directory() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join(".github/ISSUE_TEMPLATE/bug_report.md");

        let variables = HashMap::new();

        create_file_from_template(
            file_path.to_str().unwrap(),
            "ISSUE_TEMPLATE/bug_report.md",
            &variables,
        )
        .unwrap();

        assert!(file_path.exists());
        let content = fs::read_to_string(&file_path).unwrap();
        assert!(content.contains("Bug Report"));
    }

    #[test]
    fn test_create_file_from_template_variable_replacement() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("LICENSE");

        let mut variables = HashMap::new();
        variables.insert("year".to_string(), "2025".to_string());
        variables.insert("author".to_string(), "My Company Inc.".to_string());

        create_file_from_template(
            file_path.to_str().unwrap(),
            "LICENSE/Apache-2.0",
            &variables,
        )
        .unwrap();

        let content = fs::read_to_string(&file_path).unwrap();
        assert!(content.contains("2025"));
        assert!(content.contains("My Company Inc."));
    }

    #[test]
    fn test_create_file_from_template_unknown_template() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("UNKNOWN");

        let variables = HashMap::new();
        let result = create_file_from_template(file_path.to_str().unwrap(), "UNKNOWN", &variables);

        assert!(result.is_err());
    }

    #[test]
    fn test_create_file_from_template_invalid_path() {
        let variables = HashMap::new();
        let result = create_file_from_template(
            "/nonexistent/deeply/nested/path/that/does/not/exist/FILE",
            "CONTRIBUTING.md",
            &variables,
        );

        // Creating dirs in /nonexistent should fail on most systems
        // unless the filesystem allows it
        let _ = result; // Just verify it doesn't panic
    }

    #[test]
    fn test_create_file_from_template_gpl_license() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("LICENSE");

        let mut variables = HashMap::new();
        variables.insert("year".to_string(), "2024".to_string());
        variables.insert("author".to_string(), "GPL Author".to_string());

        create_file_from_template(file_path.to_str().unwrap(), "LICENSE/GPL-3.0", &variables)
            .unwrap();

        let content = fs::read_to_string(&file_path).unwrap();
        assert!(content.contains("GNU General Public License"));
        assert!(content.contains("2024"));
        assert!(content.contains("GPL Author"));
    }

    #[test]
    fn test_create_file_from_template_pr_template() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("PULL_REQUEST_TEMPLATE.md");

        let variables = HashMap::new();
        create_file_from_template(
            file_path.to_str().unwrap(),
            "PULL_REQUEST_TEMPLATE/pull_request_template.md",
            &variables,
        )
        .unwrap();

        let content = fs::read_to_string(&file_path).unwrap();
        assert!(content.contains("Description"));
    }

    #[test]
    fn test_create_file_from_template_security() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("SECURITY.md");

        let variables = HashMap::new();
        create_file_from_template(file_path.to_str().unwrap(), "SECURITY.md", &variables).unwrap();

        let content = fs::read_to_string(&file_path).unwrap();
        assert!(content.contains("Security Policy"));
    }

    #[test]
    fn test_create_file_from_template_code_of_conduct() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("CODE_OF_CONDUCT.md");

        let variables = HashMap::new();
        create_file_from_template(
            file_path.to_str().unwrap(),
            "CODE_OF_CONDUCT.md",
            &variables,
        )
        .unwrap();

        let content = fs::read_to_string(&file_path).unwrap();
        assert!(content.contains("Code of Conduct"));
    }
}