summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 64f6112f84085e7499efb95c09893df2a7ae2dc2 (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
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
use std::{
    ffi::OsStr,
    io::{Read, Write},
    os::unix::ffi::OsStrExt,
    path::Path,
};

use repo2markdown::{normalizer::Normalizer, renderer::render};

fn main() {
    println!("Hello, world!");
}

const DEFAULT_PROJECT_NAME: &str = "Project Outline";

pub fn run<R: Read, W: Write>(
    mut input: R,
    mut output: W,
    root: &Path,
    origin_base: &Path,
    project_name: Option<&str>,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut buf = Vec::new();
    input.read_to_end(&mut buf)?;

    let mut owned = Vec::new();
    let normalizer = Normalizer::new(root, origin_base)?;

    for segment in buf.split(|b| *b == 0) {
        if segment.is_empty() {
            continue;
        }

        let path = Path::new(OsStr::from_bytes(segment));
        let normalized_path = normalizer.normalize(path)?;
        let bytes = std::fs::read(normalized_path.absolute)?;

        owned.push((normalized_path.relative, bytes));
    }

    // convert to expected renderer input
    let refs: Vec<(&Path, &[u8])> = owned
        .iter()
        .map(|(p, b)| (p.as_path(), b.as_slice()))
        .collect();

    let project_name = project_name.unwrap_or_else(|| derive_project_name(root));
    let rendered = render(project_name, &refs)?;
    output.write_all(rendered.as_bytes())?;
    Ok(())
}

fn derive_project_name(root: &Path) -> &str {
    if let Some(os_str_name) = root.file_name()
        && let Some(name) = os_str_name.to_str()
    {
        name
    } else {
        DEFAULT_PROJECT_NAME
    }
}

#[cfg(test)]
mod tests {
    use std::ffi::OsStr;
    use std::fs;
    use std::io::Cursor;
    use std::os::unix::ffi::OsStrExt;
    use std::path::Path;

    use tempfile::tempdir;

    use super::{DEFAULT_PROJECT_NAME, derive_project_name, run};

    fn paths_to_null_sep_bytes(file_paths: &[&Path]) -> Vec<u8> {
        let mut output = Vec::new();
        for path in file_paths {
            output.extend(path.as_os_str().as_encoded_bytes());
            output.push(0);
        }
        output
    }

    #[test]
    fn cli_with_empty_input_produces_empty_project_with_specified_project_name() {
        let temp_dir = tempdir().unwrap();
        let input = Cursor::new(b"");
        let mut output = Vec::new();
        let root = temp_dir.path();
        let origin_base = temp_dir.path();

        run(input, &mut output, root, origin_base, Some("Project name")).unwrap();

        assert_eq!(String::from_utf8(output).unwrap(), "# Project name\n");
    }

    #[test]
    fn cli_reads_single_file_from_stdin() {
        let temp_dir = tempdir().unwrap();
        let origin_base = temp_dir.path();
        let input = Cursor::new(b"test_main.rs\0");
        let mut output = Vec::new();
        let root = temp_dir.path();

        fs::write(origin_base.join("test_main.rs"), "fn main() {}").unwrap();

        run(input, &mut output, root, origin_base, None).unwrap();

        let output_str = String::from_utf8(output).unwrap();

        assert!(output_str.contains("### \"test_main.rs\""));
        assert!(output_str.contains("fn main() {}"));
    }

    #[test]
    fn cli_reads_multiple_files_in_order() {
        let temp_dir = tempdir().unwrap();
        let origin_base = temp_dir.path();
        let input = Cursor::new(b"a.rs\0b.rs\0");
        let mut output = Vec::new();
        let root = temp_dir.path();

        fs::write(origin_base.join("a.rs"), "A").unwrap();
        fs::write(origin_base.join("b.rs"), "B").unwrap();

        run(input, &mut output, root, origin_base, None).unwrap();

        let output = String::from_utf8(output).unwrap();

        let a_pos = output.find("a.rs").unwrap();
        let b_pos = output.find("b.rs").unwrap();

        assert!(a_pos < b_pos);
    }

    #[test]
    fn cli_normalizes_paths_before_rendering() {
        let temp_dir = tempdir().unwrap();
        let origin_base = temp_dir.path();
        let input = Cursor::new(b"test/./main.rs\0");
        let mut output = Vec::new();
        let root = temp_dir.path();

        let write_dir = temp_dir.path().join("test");
        fs::create_dir_all(&write_dir).unwrap();
        fs::write(write_dir.join("main.rs"), "fn main() {}").unwrap();

        run(input, &mut output, root, origin_base, None).unwrap();

        let output = String::from_utf8(output).unwrap();

        assert!(output.contains("### \"test/main.rs\""));
    }

    #[test]
    fn cli_reads_from_origin_but_outputs_relative_to_root() {
        let temp_dir = tempdir().unwrap();
        let origin_base = temp_dir.path().join("sandbox/src");
        let input = Cursor::new(b"main.rs\0");
        let mut output = Vec::new();
        let root = temp_dir.path().join("project");

        fs::create_dir_all(&origin_base).unwrap();
        fs::write(origin_base.join("main.rs"), "fn main() {}").unwrap();

        run(input, &mut output, &root, &origin_base, None).unwrap();

        let output = String::from_utf8(output).unwrap();

        // Must contain file content → proves correct reading
        assert!(output.contains("fn main() {}"));

        // Must contain normalized path → proves normalization applied
        assert!(output.contains("sandbox/src/main.rs"));
    }

    #[test]
    fn cli_ignores_origin_when_input_path_is_absolute() {
        let temp_dir1 = tempdir().unwrap();
        let temp_dir2 = tempdir().unwrap();
        let origin_base = temp_dir2.path();
        let filepath = temp_dir1.path().join("test_main.rs");
        let input = Cursor::new(paths_to_null_sep_bytes(&[&filepath]));
        let mut output = Vec::new();
        let root = temp_dir2.path();
        fs::write(&filepath, "fn main() {}").unwrap();

        run(input, &mut output, root, origin_base, None).unwrap();

        let output = String::from_utf8(output).unwrap();

        // Must contain file content → proves correct reading
        assert!(output.contains("fn main() {}"));
    }

    #[test]
    fn project_name_is_derived_from_root_by_default_even_if_directory_does_not_exist() {
        let temp_dir = tempdir().unwrap();
        let origin_base = temp_dir.path();
        let input = Cursor::new(b"");
        let mut output = Vec::new();
        let root = temp_dir.path().join("repo2markdown");

        run(input, &mut output, &root, origin_base, None).unwrap();

        let output_str = String::from_utf8(output).unwrap();

        assert_eq!(output_str, "# repo2markdown\n");
    }

    #[test]
    fn project_name_fallsback_to_default_if_root_is_filesystem_root() {
        assert_eq!(derive_project_name(Path::new("/")), DEFAULT_PROJECT_NAME);
    }

    #[test]
    fn project_name_fallsback_if_root_ending_is_not_utf8() {
        let root = Path::new(OsStr::from_bytes(b"/root/fd\xC3"));
        assert_eq!(derive_project_name(root), DEFAULT_PROJECT_NAME);
    }

    #[test]
    fn deriving_project_name_from_root_ignores_trailing_slash() {
        let root = Path::new("/root/repo2markdown/");
        assert_eq!(derive_project_name(root), "repo2markdown");
    }
}