tabby 0.0.6

A fast, lightweight windows powershell tab completion library.
Documentation
use std::{fs::read_to_string, io::Write};

use crate::Completer;
use anyhow::Result;
use std::fs::OpenOptions;

pub const POWERSHELL_SETUP: &str = r#"
# <cli-name> tab completion
Register-ArgumentCompleter -Native -CommandName <cli-name> -ScriptBlock {
    param($wordToComplete, $commandAst, $cursorPosition)
        [Console]::InputEncoding = [Console]::OutputEncoding = $OutputEncoding = [System.Text.Utf8Encoding]::new()
        $Local:word = $wordToComplete.Replace('"', '""')
        $Local:ast = $commandAst.ToString().Replace('"', '""')
        <cli-name>.exe complete --word="$Local:word" --commandline "$Local:ast" --position $cursorPosition | ForEach-Object {
            [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)
        }
}"#;

pub fn verify_setup(completer: &Completer) -> Result<bool> {
    let mut profile_string: String = String::new();

    let user_profile = home::home_dir()
        .unwrap()
        .join("Documents/WindowsPowerShell/Microsoft.PowerShell_profile.ps1");

    let global_profile = home::home_dir()
        .unwrap()
        .join("Documents/WindowsPowerShell/profile.ps1");

    profile_string.push_str(&read_to_string(user_profile)?);

    profile_string.push_str(&read_to_string(global_profile)?);

    if profile_string.contains(
        format!(
            "Register-ArgumentCompleter -Native -CommandName {} -ScriptBlock",
            &completer.completion_data.cli_name
        )
        .as_str(),
    ) {
        return Ok(true);
    } else {
        return Ok(false);
    }
}

pub fn install(completer: &Completer) -> Result<()> {
    let global_profile = home::home_dir()
        .unwrap()
        .join("Documents/WindowsPowerShell/profile.ps1");

    let setup_completer =
        POWERSHELL_SETUP.replace("<cli-name>", &completer.completion_data.cli_name);

    let mut profile = OpenOptions::new()
        .write(true)
        .append(true)
        .open(global_profile)?;

    profile.write(setup_completer.as_bytes())?;

    Ok(())
}