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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
use std::path::Path;
use std::path::PathBuf;

use std::str::Lines;

use std::fs;
use std::io;
use std::env;

#[derive(Debug)]
struct TangleError {
    report: String,
}

impl TangleError {
    fn new (report: &str) -> Self {
        TangleError {
            report: report.to_string (),
        }
    }
}

fn property_line_p (line: &str) -> bool {
    line .trim_start () .starts_with ("#+property:")
}

fn find_destination_in_property_line (
    line: &str,
) -> Option <String> {
    let mut words = line.split_whitespace ();
    while let Some (word) = words.next () {
        if word == "tangle" || word == ":tangle" {
            if let Some (destination) = words.next () {
                return Some (destination.to_string ())
            }
        }
    }
    None
}

fn find_destination (string: &str) -> Option <String> {
    for line in string.lines () {
        if property_line_p (line) {
            let destination =
                find_destination_in_property_line (line);
            if destination. is_some () {
                return destination;
            }
        }
    }
    None
}

#[test]
fn test_find_destination () {
    let example = "#+property: tangle lib.rs";
    let destination = find_destination (example) .unwrap ();
    assert_eq! (destination, "lib.rs");

    let example = "#+property: header-args :tangle lib.rs";
    let destination = find_destination (example) .unwrap ();
    assert_eq! (destination, "lib.rs");
}

fn block_begin_line_p (line: &str) -> bool {
    line .trim_start () .starts_with ("#+begin_src")
}

fn block_end_line_p (line: &str) -> bool {
    line .trim_start () .starts_with ("#+end_src")
}

fn block_indentation (line: &str) -> usize {
    let mut indentation = 0;
    for ch in line.chars () {
        if ch == ' ' {
            indentation += 1;
        } else {
            return indentation;
        }
    }
    0
}

    fn line_trim_indentation <'a> (
        mut line: &'a str,
        indentation: usize,
    ) -> &'a str {
        let mut counter = 0;
        while counter < indentation {
            if line.starts_with (' ') {
                counter += 1;
                line = &line[1..];
            } else {
                return line;
            }
        }
        line
    }

fn tangle_collect (
    result: &mut String,
    lines: &mut Lines,
    indentation: usize,
) -> Result <(), TangleError> {
    for line in lines {
        if block_end_line_p (line) {
            result.push ('\n');
            return Ok (());
        } else {
            let line = line_trim_indentation (
                line, indentation);
            result.push_str (line);
            result.push ('\n');
        }
    }
    let error = TangleError::new ("block_end mismatch");
    Err (error)
}

fn tangle (string: &str) -> Result <String, TangleError> {
    let mut result = String::new ();
    let mut lines = string.lines ();
    while let Some (line) = lines.next () {
        if block_begin_line_p (line) {
            tangle_collect (
                &mut result,
                &mut lines,
                block_indentation (line))?;
        }
    }
    result.pop ();
    Ok (result)
}

#[test]
fn test_tangle () {
    let example = format! (
        "{}\n{}\n{}\n{}\n",
        "#+begin_src rust",
        "hi",
        "hi",
        "#+end_src",
    );
    let expect = format! (
        "{}\n{}\n",
        "hi",
        "hi",
    );
    let result = tangle (&example) .unwrap ();
    assert_eq! (expect, result);

    let example = format! (
        "{}\n{}\n{}\n{}\n",
        "    #+begin_src rust",
        "    hi",
        "    hi",
        "    #+end_src",
    );
    let expect = format! (
        "{}\n{}\n",
        "hi",
        "hi",
    );
    let result = tangle (&example) .unwrap ();
    assert_eq! (expect, result);

    let example = format! (
        "{}\n{}\n{}\n{}\n",
        "#+begin_src rust",
        "    hi",
        "    hi",
        "#+end_src",
    );
    let expect = format! (
        "{}\n{}\n",
        "    hi",
        "    hi",
    );
    let result = tangle (&example) .unwrap ();
    assert_eq! (expect, result);
}

fn good_path_p (path: &Path) -> bool {
    for component in path.iter () {
        if let Some (string) = component.to_str () {
            if string.starts_with ('.') {
                if ! string .chars () .all (|x| x == '.') {
                    return false;
                }
            }
        } else {
            return false;
        }
    }
    true
}

pub fn org_file_p (file: &Path) -> bool {
    if let Some (os_string) = file.extension () {
        if let Some (string) = os_string.to_str () {
            string == "org"
        } else {
            false
        }
    } else {
        false
    }
}

pub fn file_tangle (file: &Path) -> io::Result <()> {
    if ! org_file_p (file) {
        return Ok (());
    }
    let string = fs::read_to_string (file)?;
    if let Some (destination) = find_destination (&string) {
        let result = tangle (&string) .unwrap ();
        let mut destination_path = PathBuf::new ();
        destination_path.push (file);
        destination_path.pop ();
        destination_path.push (destination);
        println! (
            "- tangle : {:?} => {:?}",
            file.canonicalize ()?,
            destination_path.canonicalize ()?);
        fs::write (&destination_path, result)
    } else {
        Ok (())
    }
}

pub fn dir_tangle (dir: &Path) -> io::Result <()> {
    for entry in dir.read_dir ()? {
        if let Ok (entry) = entry {
            if good_path_p (&entry.path ()) {
                if entry.file_type ()? .is_file () {
                    file_tangle (&entry.path ())?
                }
            }
        }
    }
    Ok (())
}

pub fn dir_tangle_rec (dir: &Path) -> io::Result <()> {
    for entry in dir.read_dir ()? {
        if let Ok (entry) = entry {
            if good_path_p (&entry.path ()) {
                if entry.file_type ()? .is_file () {
                    file_tangle (&entry.path ())?
                } else if entry.file_type ()? .is_dir () {
                    dir_tangle_rec (&entry.path ())?
                }
            }
        }
    }
    Ok (())
}

pub fn absolute_lize (path: &Path) -> PathBuf {
    if path.is_relative () {
        let mut absolute_path = env::current_dir () .unwrap ();
        absolute_path.push (path);
        absolute_path
    } else {
        path.to_path_buf ()
    }
}

pub fn tangle_all_before_build () -> io::Result <()> {
    let path = Path::new (".");
    let current_dir = env::current_dir () .unwrap ();
    println! ("- org_tangle_engine");
    println! ("  tangle_all_before_build");
    println! ("  current_dir : {:?}", current_dir);
    let path = absolute_lize (&path);
    dir_tangle_rec (&path)
}