Skip to main content

changepacks_cli/
context.rs

1use crate::finders::get_finders;
2use anyhow::{Context, Result};
3use changepacks_core::Config;
4use changepacks_core::ProjectFinder;
5use changepacks_utils::{find_current_git_repo, find_project_dirs, get_changepacks_config};
6use std::path::PathBuf;
7
8/// Shared setup context for all CLI commands.
9///
10/// Contains git repository path, loaded config, and initialized project finders.
11/// Instantiated once per command to avoid repetitive setup code.
12pub struct CommandContext {
13    /// Root path of the git repository
14    pub repo_root_path: PathBuf,
15    /// Loaded configuration from `.changepacks/config.json`
16    pub config: Config,
17    /// Project finders for all supported languages
18    pub project_finders: Vec<Box<dyn ProjectFinder>>,
19}
20
21impl CommandContext {
22    /// # Errors
23    /// Returns error if finding git repository or discovering projects fails.
24    pub async fn new(remote: bool) -> Result<Self> {
25        let current_dir = std::env::current_dir()?;
26        let repo = find_current_git_repo(&current_dir)?;
27        let repo_root_path = repo
28            .work_dir()
29            .context("Not a git working directory. Ensure you are inside a git repository.")?
30            .to_path_buf();
31        let config = get_changepacks_config(&current_dir).await?;
32        let mut project_finders = get_finders();
33        find_project_dirs(&repo, &mut project_finders, &config, remote).await?;
34
35        Ok(Self {
36            repo_root_path,
37            config,
38            project_finders,
39        })
40    }
41
42    /// # Errors
43    /// Returns error if retrieving the current directory fails.
44    pub fn current_dir() -> Result<PathBuf> {
45        Ok(std::env::current_dir()?)
46    }
47}