tree_sitter_cli/
input.rs

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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
use std::{
    fs,
    io::{Read, Write},
    path::{Path, PathBuf},
    sync::{
        atomic::{AtomicUsize, Ordering},
        mpsc, Arc,
    },
};

use anyhow::{anyhow, bail, Context, Result};
use glob::glob;

use crate::test::{parse_tests, TestEntry};

pub enum CliInput {
    Paths(Vec<PathBuf>),
    Test {
        name: String,
        contents: Vec<u8>,
        languages: Vec<Box<str>>,
    },
    Stdin(Vec<u8>),
}

pub fn get_input(
    paths_file: Option<&Path>,
    paths: Option<Vec<PathBuf>>,
    test_number: Option<u32>,
    cancellation_flag: &Arc<AtomicUsize>,
) -> Result<CliInput> {
    if let Some(paths_file) = paths_file {
        return Ok(CliInput::Paths(
            fs::read_to_string(paths_file)
                .with_context(|| format!("Failed to read paths file {}", paths_file.display()))?
                .trim()
                .lines()
                .map(PathBuf::from)
                .collect::<Vec<_>>(),
        ));
    }

    if let Some(test_number) = test_number {
        let current_dir = std::env::current_dir().unwrap();
        let test_dir = current_dir.join("test").join("corpus");

        if !test_dir.exists() {
            return Err(anyhow!(
                "Test corpus directory not found in current directory, see https://tree-sitter.github.io/tree-sitter/creating-parsers/5-writing-tests"
            ));
        }

        let test_entry = parse_tests(&test_dir)?;
        let mut test_num = 0;
        let Some((name, contents, languages)) =
            get_test_info(&test_entry, test_number.max(1) - 1, &mut test_num)
        else {
            return Err(anyhow!("Failed to fetch contents of test #{test_number}"));
        };

        return Ok(CliInput::Test {
            name,
            contents,
            languages,
        });
    }

    if let Some(paths) = paths {
        let mut result = Vec::new();

        let mut incorporate_path = |path: PathBuf, positive| {
            if positive {
                result.push(path);
            } else if let Some(index) = result.iter().position(|p| *p == path) {
                result.remove(index);
            }
        };

        for mut path in paths {
            let mut positive = true;
            if path.starts_with("!") {
                positive = false;
                path = path.strip_prefix("!").unwrap().to_path_buf();
            }

            if path.exists() {
                incorporate_path(path, positive);
            } else {
                let Some(path_str) = path.to_str() else {
                    bail!("Invalid path: {}", path.display());
                };
                let paths =
                    glob(path_str).with_context(|| format!("Invalid glob pattern {path:?}"))?;
                for path in paths {
                    incorporate_path(path?, positive);
                }
            }
        }

        if result.is_empty() {
            return Err(anyhow!(
                "No files were found at or matched by the provided pathname/glob"
            ));
        }

        return Ok(CliInput::Paths(result));
    }

    let reader_flag = cancellation_flag.clone();
    let (tx, rx) = mpsc::channel();

    // Spawn a thread to read from stdin, until ctrl-c or EOF is received
    std::thread::spawn(move || {
        let mut input = Vec::new();
        let stdin = std::io::stdin();
        let mut handle = stdin.lock();

        // Read in chunks, so we can check the ctrl-c flag
        loop {
            if reader_flag.load(Ordering::Relaxed) == 1 {
                break;
            }
            let mut buffer = [0; 1024];
            match handle.read(&mut buffer) {
                Ok(0) | Err(_) => break,
                Ok(n) => input.extend_from_slice(&buffer[..n]),
            }
        }

        // Signal to the main thread that we're done
        tx.send(input).ok();
    });

    loop {
        // If we've received a ctrl-c signal, exit
        if cancellation_flag.load(Ordering::Relaxed) == 1 {
            bail!("\n");
        }

        // If we're done receiving input from stdin, return it
        if let Ok(input) = rx.try_recv() {
            return Ok(CliInput::Stdin(input));
        }

        std::thread::sleep(std::time::Duration::from_millis(50));
    }
}

#[allow(clippy::type_complexity)]
pub fn get_test_info(
    test_entry: &TestEntry,
    target_test: u32,
    test_num: &mut u32,
) -> Option<(String, Vec<u8>, Vec<Box<str>>)> {
    match test_entry {
        TestEntry::Example {
            name,
            input,
            attributes,
            ..
        } => {
            if *test_num == target_test {
                return Some((name.clone(), input.clone(), attributes.languages.clone()));
            }
            *test_num += 1;
        }
        TestEntry::Group { children, .. } => {
            for child in children {
                if let Some((name, input, languages)) = get_test_info(child, target_test, test_num)
                {
                    return Some((name, input, languages));
                }
            }
        }
    }

    None
}

/// Writes `contents` to a temporary file and returns the path to that file.
pub fn get_tmp_source_file(contents: &[u8]) -> Result<PathBuf> {
    let parse_path = std::env::temp_dir().join(".tree-sitter-temp");
    let mut parse_file = std::fs::File::create(&parse_path)?;
    parse_file.write_all(contents)?;

    Ok(parse_path)
}