ars-cm 0.2.1

fast commit message for jira tickets.
use std::ffi::CString;
use std::fs::OpenOptions;
use std::io::Read;
use std::os::unix::io::AsRawFd;
use std::process::{Command, Stdio};

use nix::{ioctl_write_ptr_bad, libc};

use crate::git;

pub fn exec() {
    let ticket_result = git::get_ticket_id();

    if ticket_result.is_err() {
        return eprintln!("{}", ticket_result.err().unwrap());
    }

    let ticket_id = ticket_result.ok().unwrap();


    let pts = &mut "".to_string();

    Command::new("/usr/bin/tty")
        .stdout(Stdio::piped())
        .spawn()
        .unwrap()
        .stdout
        .unwrap()
        .read_to_string(pts)
        .unwrap();

    let pts = pts.trim();

    let pty_file = OpenOptions::new()
        .append(true)
        .open(pts)
        .unwrap();

    ioctl_write_ptr_bad!(inner_pty_write, libc::TIOCSTI, libc::c_char);

    let result = String::from("git commit -m \"");
    let result = format!("{}{} \"", result, ticket_id);

    let mut input: Vec<u8> = vec![];
    for r in result.as_bytes() {
        input.push(*r);
    }

    let cs = CString::new(input).unwrap();

    let len = cs.as_bytes().len();
    let ptr = cs.as_ptr();

    for u_index in 0..len {
        let i_index: isize = u_index
            .try_into()
            .unwrap();

        unsafe { inner_pty_write(pty_file.as_raw_fd(), ptr.offset(i_index)).unwrap(); }
    }
}