Dough Git

clove/code4dyslexia

src/python_source.rs

back to src

// src/python_source.rs

use std::io::Write;
use std::process::{Command, Stdio};

use serde_json::Value;

use crate::adapter_protocol::{decode, request, runtime};
use crate::config::Effective;
use crate::language::{Analysis, Diagnostic};

const ADAPTER: &str = include_str!("python_adapter.py");

pub fn generated_header(source: &str, path: &str) -> bool {
    let path_comment = format!("# {path}");
    source.trim_start_matches('\u{feff}')
    .lines()
    .map(str::trim)
    .take_while(|line| line.is_empty() || line.starts_with('#'))
    .any(|line| {
        if line == path_comment {
            return false;
        }

        let line = line.to_ascii_lowercase();
        ["@generated", "auto-generated", "autogenerated", "automatically generated", "do not edit"]
        .iter().any(|marker| line.contains(marker))
        })
}

fn response(request: &Value) -> Result<Value, Diagnostic> {
    let mut child = Command::new("python3")
    .args(["-I", "-S", "-c", ADAPTER])
    .stdin(Stdio::piped())
    .stdout(Stdio::piped())
    .stderr(Stdio::piped())
    .spawn()
    .map_err(|error| runtime(format!("Python support needs python3 on PATH: {error}")))?;

    let mut stdin = child.stdin.take().expect("piped Python input");
    let write = stdin.write_all(request.to_string().as_bytes());
    drop(stdin);
    let output = child.wait_with_output().map_err(|error| runtime(error.to_string()))?;

    if !output.status.success() {
        return Err(runtime(format!("Python adapter failed: {}", String::from_utf8_lossy(&output.stderr).trim())));
    }

    write.map_err(|error| runtime(error.to_string()))?;
    serde_json::from_slice(&output.stdout).map_err(|error| runtime(error.to_string()))
}

pub fn analyze<'source>(
    source: &'source str,
    path: &str,
    settings: &Effective,
    naming: bool,
) -> Result<Analysis<'source>, Diagnostic> {
    let answer = response(&request(source, path, settings, naming))?;
    decode(source, settings, &answer)
}