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
//! Init command - Initialize a new configuration file

use colored::Colorize;
use dialoguer::{Confirm, Select};
use std::fs;
use std::path::Path;

use super::InitArgs;
use crate::config::presets::VALID_PRESETS;
use crate::config::{Config, Preset};
use crate::error::{ActionError, RepoLensError};
use crate::exit_codes;
use crate::utils::permissions::set_secure_permissions;
use crate::utils::prerequisites::{
    display_error_summary, display_report, display_warnings, run_all_checks, CheckOptions,
};

const CONFIG_FILENAME: &str = ".repolens.toml";

pub async fn execute(args: InitArgs) -> Result<i32, RepoLensError> {
    let root = std::env::current_dir().map_err(|e| {
        RepoLensError::Action(ActionError::ExecutionFailed {
            message: format!("Failed to get current directory: {}", e),
        })
    })?;
    let config_path = Path::new(CONFIG_FILENAME);

    // Run prerequisite checks unless skipped
    if !args.skip_checks {
        let options = CheckOptions::default();
        let report = run_all_checks(&root, &options);
        display_report(&report, false);

        if !report.all_required_passed() {
            display_error_summary(&report);

            if args.non_interactive {
                return Ok(exit_codes::ERROR);
            }

            // Ask if user wants to continue anyway
            let continue_anyway = Confirm::new()
                .with_prompt("Continue anyway?")
                .default(false)
                .interact()
                .map_err(|e| {
                    RepoLensError::Action(ActionError::ExecutionFailed {
                        message: format!("Failed to get user input: {}", e),
                    })
                })?;

            if !continue_anyway {
                return Ok(exit_codes::ERROR);
            }

            println!();
        } else if report.has_warnings() {
            display_warnings(&report);
        }
    }

    // Check if config already exists
    if config_path.exists() && !args.force {
        if args.non_interactive {
            eprintln!(
                "{} Configuration file already exists. Use --force to overwrite.",
                "Error:".red().bold()
            );
            return Ok(exit_codes::ERROR);
        }

        let overwrite = Confirm::new()
            .with_prompt("Configuration file already exists. Overwrite?")
            .default(false)
            .interact()
            .map_err(|e| {
                RepoLensError::Action(ActionError::ExecutionFailed {
                    message: format!("Failed to get user input: {}", e),
                })
            })?;

        if !overwrite {
            println!("{}", "Aborted.".yellow());
            return Ok(exit_codes::SUCCESS);
        }
    }

    // Determine preset with validation
    let preset = if let Some(preset_name) = args.preset {
        match Preset::from_name(&preset_name) {
            Some(p) => p,
            None => {
                eprintln!(
                    "{} Unknown preset '{}'. Valid presets: {}",
                    "Error:".red().bold(),
                    preset_name,
                    VALID_PRESETS.join(", ")
                );
                return Ok(exit_codes::INVALID_ARGS);
            }
        }
    } else if args.non_interactive {
        Preset::OpenSource
    } else {
        select_preset()?
    };

    // Create configuration
    let config = Config::from_preset(preset);

    // Write configuration file
    let config_content = config.to_toml()?;
    fs::write(config_path, &config_content).map_err(|e| {
        RepoLensError::Action(ActionError::FileWrite {
            path: config_path.display().to_string(),
            source: e,
        })
    })?;

    // Set secure permissions (owner read/write only) on Unix systems
    set_secure_permissions(config_path).map_err(|e| {
        RepoLensError::Action(ActionError::ExecutionFailed {
            message: format!(
                "Failed to set secure permissions on {}: {}",
                CONFIG_FILENAME, e
            ),
        })
    })?;

    println!(
        "{} Created {} with preset '{}'",
        "Success:".green().bold(),
        CONFIG_FILENAME.cyan(),
        preset.name().yellow()
    );

    println!("\nNext steps:");
    println!("  1. Review and customize {}", CONFIG_FILENAME.cyan());
    println!("  2. Run {} to see planned actions", "repolens plan".cyan());
    println!("  3. Run {} to apply changes", "repolens apply".cyan());

    Ok(exit_codes::SUCCESS)
}

fn select_preset() -> Result<Preset, RepoLensError> {
    let presets = [
        (
            "opensource",
            "Open Source - Prepare repository for public release",
        ),
        ("enterprise", "Enterprise - Internal company standards"),
        ("strict", "Strict - Maximum security and compliance checks"),
    ];

    let selection = Select::new()
        .with_prompt("Select a preset")
        .items(&presets.iter().map(|(_, desc)| *desc).collect::<Vec<_>>())
        .default(0)
        .interact()
        .map_err(|e| {
            RepoLensError::Action(ActionError::ExecutionFailed {
                message: format!("Failed to get user input: {}", e),
            })
        })?;

    Ok(match selection {
        0 => Preset::OpenSource,
        1 => Preset::Enterprise,
        2 => Preset::Strict,
        _ => Preset::OpenSource,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use serial_test::serial;
    use std::process::Command;
    use tempfile::TempDir;

    fn init_git_repo(root: &Path) {
        Command::new("git")
            .args(["init"])
            .current_dir(root)
            .output()
            .ok();
        Command::new("git")
            .args(["config", "user.email", "test@test.com"])
            .current_dir(root)
            .output()
            .ok();
        Command::new("git")
            .args(["config", "user.name", "Test"])
            .current_dir(root)
            .output()
            .ok();
    }

    #[tokio::test]
    #[serial]
    async fn test_execute_creates_config() {
        let temp_dir = TempDir::new().unwrap();
        let root = temp_dir.path().canonicalize().unwrap();
        init_git_repo(&root);

        let original_dir = std::env::current_dir().unwrap();
        std::env::set_current_dir(&root).unwrap();

        let args = InitArgs {
            preset: Some("opensource".to_string()),
            non_interactive: true,
            force: false,
            skip_checks: true,
        };

        let result = execute(args).await;
        std::env::set_current_dir(&original_dir).unwrap();

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), exit_codes::SUCCESS);
        assert!(root.join(".repolens.toml").exists());
    }

    #[tokio::test]
    #[serial]
    async fn test_execute_with_enterprise_preset() {
        let temp_dir = TempDir::new().unwrap();
        let root = temp_dir.path().canonicalize().unwrap();
        init_git_repo(&root);

        let original_dir = std::env::current_dir().unwrap();
        std::env::set_current_dir(&root).unwrap();

        let args = InitArgs {
            preset: Some("enterprise".to_string()),
            non_interactive: true,
            force: false,
            skip_checks: true,
        };

        let result = execute(args).await;
        std::env::set_current_dir(&original_dir).unwrap();

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), exit_codes::SUCCESS);

        let config_content = fs::read_to_string(root.join(".repolens.toml")).unwrap();
        assert!(config_content.contains("enterprise"));
    }

    #[tokio::test]
    #[serial]
    async fn test_execute_with_strict_preset() {
        let temp_dir = TempDir::new().unwrap();
        let root = temp_dir.path().canonicalize().unwrap();
        init_git_repo(&root);

        let original_dir = std::env::current_dir().unwrap();
        std::env::set_current_dir(&root).unwrap();

        let args = InitArgs {
            preset: Some("strict".to_string()),
            non_interactive: true,
            force: false,
            skip_checks: true,
        };

        let result = execute(args).await;
        std::env::set_current_dir(&original_dir).unwrap();

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), exit_codes::SUCCESS);

        let config_content = fs::read_to_string(root.join(".repolens.toml")).unwrap();
        assert!(config_content.contains("strict"));
    }

    #[tokio::test]
    #[serial]
    async fn test_execute_invalid_preset() {
        let temp_dir = TempDir::new().unwrap();
        let root = temp_dir.path().canonicalize().unwrap();
        init_git_repo(&root);

        let original_dir = std::env::current_dir().unwrap();
        std::env::set_current_dir(&root).unwrap();

        let args = InitArgs {
            preset: Some("invalid_preset".to_string()),
            non_interactive: true,
            force: false,
            skip_checks: true,
        };

        let result = execute(args).await;
        std::env::set_current_dir(&original_dir).unwrap();

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), exit_codes::INVALID_ARGS);
    }

    #[tokio::test]
    #[serial]
    async fn test_execute_config_exists_no_force() {
        let temp_dir = TempDir::new().unwrap();
        let root = temp_dir.path().canonicalize().unwrap();
        init_git_repo(&root);

        // Create existing config
        fs::write(
            root.join(".repolens.toml"),
            "[general]\npreset = \"opensource\"\n",
        )
        .unwrap();

        let original_dir = std::env::current_dir().unwrap();
        std::env::set_current_dir(&root).unwrap();

        let args = InitArgs {
            preset: Some("strict".to_string()),
            non_interactive: true,
            force: false,
            skip_checks: true,
        };

        let result = execute(args).await;
        std::env::set_current_dir(&original_dir).unwrap();

        // Should return ERROR because config exists and no --force
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), exit_codes::ERROR);

        // Original config should be unchanged
        let config_content = fs::read_to_string(root.join(".repolens.toml")).unwrap();
        assert!(config_content.contains("opensource"));
    }

    #[tokio::test]
    #[serial]
    async fn test_execute_config_exists_with_force() {
        let temp_dir = TempDir::new().unwrap();
        let root = temp_dir.path().canonicalize().unwrap();
        init_git_repo(&root);

        // Create existing config
        fs::write(
            root.join(".repolens.toml"),
            "[general]\npreset = \"opensource\"\n",
        )
        .unwrap();

        let original_dir = std::env::current_dir().unwrap();
        std::env::set_current_dir(&root).unwrap();

        let args = InitArgs {
            preset: Some("strict".to_string()),
            non_interactive: true,
            force: true,
            skip_checks: true,
        };

        let result = execute(args).await;
        std::env::set_current_dir(&original_dir).unwrap();

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), exit_codes::SUCCESS);

        // Config should be overwritten
        let config_content = fs::read_to_string(root.join(".repolens.toml")).unwrap();
        assert!(config_content.contains("strict"));
    }

    #[tokio::test]
    #[serial]
    async fn test_execute_default_preset_non_interactive() {
        let temp_dir = TempDir::new().unwrap();
        let root = temp_dir.path().canonicalize().unwrap();
        init_git_repo(&root);

        let original_dir = std::env::current_dir().unwrap();
        std::env::set_current_dir(&root).unwrap();

        let args = InitArgs {
            preset: None, // No preset specified
            non_interactive: true,
            force: false,
            skip_checks: true,
        };

        let result = execute(args).await;
        std::env::set_current_dir(&original_dir).unwrap();

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), exit_codes::SUCCESS);

        // Should use opensource as default
        let config_content = fs::read_to_string(root.join(".repolens.toml")).unwrap();
        assert!(config_content.contains("opensource"));
    }

    #[test]
    fn test_preset_from_name() {
        assert!(Preset::from_name("opensource").is_some());
        assert!(Preset::from_name("enterprise").is_some());
        assert!(Preset::from_name("strict").is_some());
        assert!(Preset::from_name("invalid").is_none());
    }

    #[test]
    fn test_config_filename_constant() {
        assert_eq!(CONFIG_FILENAME, ".repolens.toml");
    }
}