aboutsummaryrefslogtreecommitdiff
path: root/mingling_core/src/comp/comp_ctx.rs
blob: 04ef853fd1525ba94e501f412b0429de83f7302e (plain) (blame)
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
use crate::{COMPLETION_SUBCOMMAND, Program, ProgramCollect};

impl<C> Program<C>
where
    C: ProgramCollect<Enum = C>,
{
    /// Checks whether the program is currently in a completion mode.
    ///
    /// This is determined by checking if the special completion subcommand
    /// (defined by [`COMPLETION_SUBCOMMAND`]) appears among the parsed arguments.
    /// When `true`, the program should generate shell completions instead of
    /// running its normal execution path.
    ///
    /// # Returns
    ///
    /// `true` if the program is in completion mode, `false` otherwise.
    ///
    /// # Example
    ///
    /// ```
    /// # #[cfg(feature = "comp")] {
    /// # use mingling_core::MockProgramCollect as ThisProgram;
    /// use mingling_core::Program;
    ///
    /// let completing = Program::<ThisProgram>::new_with_args(["my_prog", "__comp"]).is_completing();
    /// assert!(completing);
    ///
    /// let not_completing = Program::<ThisProgram>::new_with_args(["my_prog", "run"]).is_completing();
    /// assert!(!not_completing);
    /// # }
    /// ```
    #[must_use]
    pub fn is_completing(&self) -> bool {
        // Check if the first argument (args[1]) is the completion subcommand
        self.args
            .get(1)
            .is_some_and(|arg| arg == COMPLETION_SUBCOMMAND)
    }
}

#[cfg(test)]
mod tests {
    use crate::MockProgramCollect;

    use super::*;

    #[test]
    fn test_is_completing_with_comp_subcommand() {
        let program: Program<MockProgramCollect> =
            Program::new_with_args(["program", "__comp", "some", "args"]);
        assert!(program.is_completing());
    }

    #[test]
    fn test_is_completing_with_normal_subcommand() {
        let program: Program<MockProgramCollect> =
            Program::new_with_args(["program", "normal", "cmd"]);
        assert!(!program.is_completing());
    }

    #[test]
    fn test_is_completing_with_no_args() {
        let program: Program<MockProgramCollect> = Program::new_with_args(["program"]);
        assert!(!program.is_completing());
    }
}