Skip to main content

vtcode_config/loader/
bootstrap.rs

1use std::fs;
2use std::path::{Path, PathBuf};
3use vtcode_commons::VtCodePaths;
4
5use anyhow::{Context, Result};
6
7use super::config::VTCodeConfig;
8use crate::defaults::{self, ConfigDefaultsProvider};
9
10const DEFAULT_GITIGNORE_FILE_NAME: &str = ".vtcodegitignore";
11
12/// Determine where configuration and gitignore files should be created when
13/// bootstrapping a workspace.
14fn determine_bootstrap_targets(
15    workspace: &Path,
16    use_home_dir: bool,
17    config_file_name: &str,
18    defaults_provider: &dyn ConfigDefaultsProvider,
19) -> Result<(PathBuf, PathBuf)> {
20    if use_home_dir {
21        if let Some(home_config_path) = select_home_config_path(defaults_provider, config_file_name)? {
22            let gitignore_path = gitignore_path_for(&home_config_path);
23            return Ok((home_config_path, gitignore_path));
24        }
25    }
26
27    let config_path = workspace.join(config_file_name);
28    let gitignore_path = workspace.join(DEFAULT_GITIGNORE_FILE_NAME);
29    Ok((config_path, gitignore_path))
30}
31
32/// Returns the preferred gitignore path for a given configuration file.
33fn gitignore_path_for(config_path: &Path) -> PathBuf {
34    config_path
35        .parent()
36        .map(|parent| parent.join(DEFAULT_GITIGNORE_FILE_NAME))
37        .unwrap_or_else(|| PathBuf::from(DEFAULT_GITIGNORE_FILE_NAME))
38}
39
40/// Ensures the parent directory for the provided path exists, creating it if
41/// necessary.
42fn ensure_parent_dir(path: &Path) -> Result<()> {
43    if let Some(parent) = path.parent() {
44        fs::create_dir_all(parent).with_context(|| format!("Failed to create directory: {}", parent.display()))?;
45    }
46
47    Ok(())
48}
49
50/// Ensures a canonical user-level configuration parent exists privately.
51fn ensure_private_parent_dir(path: &Path) -> Result<()> {
52    if let Some(parent) = path.parent() {
53        let _ = VtCodePaths::ensure_user_dir(parent)
54            .with_context(|| format!("Failed to create private directory: {}", parent.display()))?;
55    }
56
57    Ok(())
58}
59
60/// Selects the canonical user configuration path from the defaults provider.
61fn select_home_config_path(
62    defaults_provider: &dyn ConfigDefaultsProvider,
63    config_file_name: &str,
64) -> Result<Option<PathBuf>> {
65    defaults_provider
66        .canonical_user_config_path(config_file_name)
67        .context("Failed to resolve canonical user configuration path")
68}
69
70impl VTCodeConfig {
71    /// Bootstrap project with config + gitignore
72    pub fn bootstrap_project<P: AsRef<Path>>(workspace: P, force: bool) -> Result<Vec<String>> {
73        Self::bootstrap_project_with_options(workspace, force, false)
74    }
75
76    /// Bootstrap project with config + gitignore, with option to create in home directory
77    pub fn bootstrap_project_with_options<P: AsRef<Path>>(
78        workspace: P,
79        force: bool,
80        use_home_dir: bool,
81    ) -> Result<Vec<String>> {
82        let workspace = workspace.as_ref().to_path_buf();
83        defaults::with_config_defaults(|provider| {
84            Self::bootstrap_project_with_provider(&workspace, force, use_home_dir, provider)
85        })
86    }
87
88    /// Bootstrap project files using the supplied [`ConfigDefaultsProvider`].
89    fn bootstrap_project_with_provider<P: AsRef<Path>>(
90        workspace: P,
91        force: bool,
92        use_home_dir: bool,
93        defaults_provider: &dyn ConfigDefaultsProvider,
94    ) -> Result<Vec<String>> {
95        let workspace = workspace.as_ref();
96        let config_file_name = defaults_provider.config_file_name().to_string();
97        let (config_path, gitignore_path) =
98            determine_bootstrap_targets(workspace, use_home_dir, &config_file_name, defaults_provider)?;
99        let vtcode_readme_path = workspace.join(".vtcode").join("README.md");
100        let home_targets = use_home_dir && config_path != workspace.join(&config_file_name);
101        if home_targets {
102            ensure_private_parent_dir(&config_path)?;
103            ensure_private_parent_dir(&gitignore_path)?;
104        } else {
105            ensure_parent_dir(&config_path)?;
106            ensure_parent_dir(&gitignore_path)?;
107        }
108        ensure_parent_dir(&vtcode_readme_path)?;
109
110        let mut created_files = Vec::new();
111
112        if !config_path.exists() || force {
113            let config_content = Self::default_vtcode_toml_template();
114
115            fs::write(&config_path, config_content)
116                .with_context(|| format!("Failed to write config file: {}", config_path.display()))?;
117
118            if let Some(file_name) = config_path.file_name().and_then(|name| name.to_str()) {
119                created_files.push(file_name.to_string());
120            }
121        }
122
123        if !gitignore_path.exists() || force {
124            let gitignore_content = Self::default_vtcode_gitignore();
125            fs::write(&gitignore_path, gitignore_content)
126                .with_context(|| format!("Failed to write gitignore file: {}", gitignore_path.display()))?;
127
128            if let Some(file_name) = gitignore_path.file_name().and_then(|name| name.to_str()) {
129                created_files.push(file_name.to_string());
130            }
131        }
132
133        if !vtcode_readme_path.exists() || force {
134            let vtcode_readme = Self::default_vtcode_readme_template();
135            fs::write(&vtcode_readme_path, vtcode_readme)
136                .with_context(|| format!("Failed to write VT Code README: {}", vtcode_readme_path.display()))?;
137            created_files.push(".vtcode/README.md".to_string());
138        }
139
140        Ok(created_files)
141    }
142
143    /// Generate the default `vtcode.toml` template used by bootstrap helpers.
144    fn default_vtcode_toml_template() -> String {
145        include_str!("../../data/default_config.toml").to_owned()
146    }
147
148    fn default_vtcode_gitignore() -> String {
149        r#"# Security-focused exclusions
150.env, .env.local, secrets/, .aws/, .ssh/
151
152# Development artifacts
153target/, build/, dist/, node_modules/, vendor/
154
155# Database files
156*.db, *.sqlite, *.sqlite3
157
158# Binary files
159*.exe, *.dll, *.so, *.dylib, *.bin
160
161# IDE files (comprehensive)
162.vscode/, .idea/, *.swp, *.swo
163"#
164        .to_string()
165    }
166
167    fn default_vtcode_readme_template() -> &'static str {
168        "# VT Code Workspace Files\n\n- Put always-on repository guidance in `AGENTS.md`.\n- Put path-scoped prompt rules in `.vtcode/rules/*.md` using YAML frontmatter.\n- Keep authoring notes and other workspace docs outside `.vtcode/rules/` so they are not loaded into prompt memory.\n"
169    }
170
171    /// Create sample configuration file
172    pub fn create_sample_config<P: AsRef<Path>>(output: P) -> Result<()> {
173        let output = output.as_ref();
174        let config_content = Self::default_vtcode_toml_template();
175
176        fs::write(output, config_content)
177            .with_context(|| format!("Failed to write config file: {}", output.display()))?;
178
179        Ok(())
180    }
181}
182
183#[cfg(test)]
184mod tests;