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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
//! `linurgy` provides an interface for manipulating multiple newlines in text.
//! Interaction with this library happens through 
//! [`LinurgyBuilder`](struct.LinurgyBuilder.html).
//!
//! # Examples
//!
//! Read stdin and for each empty line, append an extra line to stdout.
//! ```rust
//! # use linurgy::LinurgyBuilder;
//! LinurgyBuilder::new()
//!     .set_newline_trigger(1)
//!     .set_new_text("\n")
//!     .run();
//! ```
//! 
//! Read from one buffer, remove all empty lines, and output to another buffer.
//! ```rust
//! # use linurgy::{LinurgyBuilder, Input, Output, EditType};
//! let input = String::from("Remove\n\nEvery\n\nEmpty\n\nLine\n");
//! let mut output = String::new();
//! 
//! LinurgyBuilder::new()
//!     .set_input(Input::Buffer(&input))
//!     .set_output(Output::Buffer(&mut output))
//!     .set_newline_trigger(1)
//!     .set_edit_type(EditType::Replace)
//!     .set_new_text("")
//!     .run();
//! 
//! assert_eq!("Remove\nEvery\nEmpty\nLine\n", &output);
//! ```

use std::io::{self, Write};
use std::fs;

/// Type of input stream to edit
pub enum Input<'a> {
    /// Basic line by line read from stdin
    StdIn,

    /// Read from a given filename
    File(&'a str),

    /// Read from a string
    Buffer(&'a str),
}

/// Type of output stream to write edits to
pub enum Output<'b> {
    /// Basic line by line output to stdout
    StdOut,

    /// Write to a given filename
    File(&'b str),

    /// Write to a given `String` buffer
    Buffer(&'b mut String),
}

/// Which action to implement when editing newlines
pub enum EditType {
    /// New edits will appear after newlines
    Append,

    /// New edits will appear before newlines
    Insert,

    /// New edits will appear instead of newlines
    Replace,
}

struct Editor<'c> {
    newline_count_trigger: u8,
    new_text: &'c str,
    edit_type: EditType,
    current_count: u8,
    buffer: String
}

impl<'c> Default for Editor<'c> {
    fn default() -> Self {
        Editor {
            newline_count_trigger: 2,
            new_text: "-------\n",
            edit_type: EditType::Append,
            current_count: 0,
            buffer: String::new(),
        }
    }
}

impl<'c> Editor<'c> {
    fn add_line(&mut self, line: &str) {
        self.buffer += line;
        if line == "\n" {
            self.current_count += 1;
            if self.current_count == self.newline_count_trigger {
                self.current_count = 0;
                match &self.edit_type {
                    EditType::Append => self.buffer += self.new_text,
                    EditType::Insert => {
                        self.buffer.insert_str(0, self.new_text);
                    }
                    EditType::Replace => {
                        self.buffer.replace_range(.., self.new_text);
                    }
                }
            }
        } else {
            // line contains text
            self.current_count = 0;
        }
    }

    fn try_output(&mut self) -> Option<String> {
        if self.current_count == 0 {
            Some(self.buffer.drain(..).collect())
        } else {
            None
        }
    }

    fn get_remaining_output(&mut self) -> Option<String> {
        if !self.buffer.is_empty() {
            Some(self.buffer.drain(..).collect())
        } else {
            None
        }
    }
}

/// Use this to prepare and execute linurgy editing on a stream.
///
/// A linurgy consists of an [`Input`](enum.Input.html), which will be read
/// line by line, edited by user defined rules, and then streamed into an
/// [`Output`](enum.Output.html).
pub struct LinurgyBuilder<'a, 'b, 'c> {
    input:  Input<'a>,
    output: Output<'b>,
    editor: Editor<'c>,
    file: Option<fs::File>,
}

impl Default for LinurgyBuilder<'_, '_, '_> {
    fn default() -> Self {
        LinurgyBuilder {
            input: Input::StdIn,
            output: Output::StdOut,
            editor: Editor::default(),
            file: None,
        }
    }
}

impl<'a, 'b, 'c> LinurgyBuilder<'a, 'b, 'c> {
    /// Instantiate a new builder with default values.
    /// - Input: [`Input::StdIn`](enum.Input.html#variant.StdIn),
    /// - Output: [`Output::StdOut`](enum.Output.html#variant.StdOut),
    /// - Newline count trigger: 2,
    /// - New text : "-------\n",
    /// - EditType: [`EditType::Append`](enum.EditType.html#variant.Append)
    ///
    /// This will read from `stdin`,
    /// add dashes after 2 empty lines, and write to `stdout`.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the input source to read text from.
    ///
    /// # Examples
    /// Using an in-memory [`Buffer`](enum.Input.html#variant.Buffer)
    /// ```rust
    /// # use linurgy::{LinurgyBuilder, Input};
    /// let text = String::from("Sample text\n\n\n");
    /// let mut linurgy = LinurgyBuilder::new();
    ///
    /// linurgy.set_input(Input::Buffer(&text));
    /// ```
    /// Read from a [`File`](enum.Input.html#variant.File)
    /// ```rust
    /// # use linurgy::{LinurgyBuilder, Input};
    /// let mut linurgy = LinurgyBuilder::new();
    /// 
    /// linurgy.set_input(Input::File("filename.txt"));
    /// ```
    pub fn set_input(&mut self, input: Input<'a>) -> &mut Self {
        self.input = input;
        self
    }

    /// Set the output stream to write to.
    ///
    /// # Examples
    /// Using an in-memory [`Buffer`](enum.Output.html#variant.Buffer)
    /// ```rust
    /// # use linurgy::{LinurgyBuilder, Output};
    /// let mut buffer = String::new();
    /// let mut linurgy = LinurgyBuilder::new();
    ///
    /// linurgy.set_output(Output::Buffer(&mut buffer));
    /// ```
    /// Write straight to a [`File`](enum.Output.html#variant.File)
    /// ```rust
    /// # use linurgy::{LinurgyBuilder, Output};
    /// let mut linurgy = LinurgyBuilder::new();
    /// 
    /// linurgy.set_output(Output::File("filename.txt"));
    /// ```
    pub fn set_output(&mut self, output: Output<'b>) -> &mut Self {
        self.output = output;
        self
    }

    /// Set the newline count to trigger editing.
    ///
    /// # Example
    /// Add edit string after every 5 empty lines
    /// ```rust
    /// # use linurgy::{LinurgyBuilder};
    /// let mut linurgy = LinurgyBuilder::new();
    /// linurgy.set_newline_trigger(5);
    /// ```
    pub fn set_newline_trigger(&mut self, count: u8) -> &mut Self {
        self.editor.newline_count_trigger = count;
        self
    }

    /// Set the text that will be used when the newline trigger is reached.
    ///
    /// # Example
    /// Add a line of dots after every empty line
    /// ```rust
    /// # use linurgy::{LinurgyBuilder};
    /// let mut linurgy = LinurgyBuilder::new();
    /// let new_text = format!("{}\n", ". ".repeat(25));
    /// 
    /// linurgy.set_newline_trigger(1);
    /// linurgy.set_new_text(&new_text);
    /// ```
    pub fn set_new_text(&mut self, new_text: &'c str) -> &mut Self {
        self.editor.new_text = new_text;
        self
    }

    /// Set how new text is added after the newline trigger is reached.
    ///
    /// # Example
    /// Replace double empty lines with a line of dashes
    /// ```rust
    /// # use linurgy::{LinurgyBuilder, EditType};
    /// let mut linurgy = LinurgyBuilder::new();
    /// linurgy.set_edit_type(EditType::Replace);
    /// ```
    pub fn set_edit_type(&mut self, edit_type: EditType) -> &mut Self {
        self.editor.edit_type = edit_type;
        self
    }

    /// Execute the linurgy edits on the specified input stream.
    ///
    /// This function will block until the input stream is exhausted.
    /// If the input stream is [`Input::StdIn`](enum.Input.html#varient.StdIn),
    /// then `stdin` will be locked while this function runs.
    /// If `stdin` is locked elsewhere, this function will block until it
    /// becomes available again.
    ///
    /// # Panics
    /// This function will panic if the input file in unable to be opened
    /// or read from, 
    /// or if the output file is unable to be created or written to.
    ///
    /// # Examples
    /// Execute default behaviour and add dashes to 
    /// double newlines from `stdin`
    /// ```rust
    /// # use linurgy::LinurgyBuilder;
    /// LinurgyBuilder::new().run();
    /// ```
    ///
    /// This will panic if "not-a-file" does not exist
    /// ```rust,should_panic
    /// # use linurgy::{LinurgyBuilder, Input};
    /// LinurgyBuilder::new()
    ///     .set_input(Input::File("not-a-file"))
    ///     .run();
    /// ```
    pub fn run(&mut self) -> &mut Self {
        if let Output::File(path) = &self.output {
            self.file = Some(fs::File::create(path).expect("Create file"))
        }

        match self.input {
            Input::StdIn => {
                let stdin = io::stdin();
                let reader = stdin.lock();
                self.process(reader);
            }
            Input::File(name) => {
                let file = fs::File::open(name).expect("Unable to open file");
                let reader = io::BufReader::new(file);
                self.process(reader);
            }
            Input::Buffer(buffer) => {
                let reader = io::Cursor::new(buffer);
                self.process(reader);
            }
        }

        self
    }

    fn process(&mut self, reader: impl io::BufRead) {
        for line in reader.lines() {
            let line = line.unwrap() + "\n";
            self.editor.add_line(&line);
            let edited_text = self.editor.try_output();
            self.write(edited_text);
        }

        let edited_text = self.editor.get_remaining_output();
        self.write(edited_text);
    }

    fn write(&mut self, edited_text: Option<String>) {
        if let Some(text) = edited_text {
            match self.output {
                Output::StdOut => print!("{}", &text),
                Output::File(_) => {
                    if let Some(file) = &mut self.file {
                        file.write_all(&text.as_bytes())
                            .expect("Write to file")
                    }
                }
                Output::Buffer(ref mut buffer) => buffer.push_str(&text),
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn default_editor() {
        let editor = Editor::default();
        assert_eq!(2, editor.newline_count_trigger);
        assert_eq!(0, editor.current_count);
        assert_eq!("", editor.buffer);
        assert_eq!("-------\n", editor.new_text);
        if let EditType::Append = editor.edit_type {
            assert!(true);
        } else {
            assert!(false, "Correct type not implemented");
        }
    }

    #[test]
    fn default_linurgy_builder() {
        let lb = LinurgyBuilder::new();
        let editor = Editor::default();
        if let Input::StdIn = lb.input {
            assert!(true);
        } else {
            assert!(false, "Correct type not implemented");
        }

        if let Output::StdOut = lb.output {
            assert!(true);
        } else {
            assert!(false, "Correct type not implemented");
        }

        assert_eq!(editor.new_text, lb.editor.new_text);
    }

    #[test]
    fn linurgy_set_input() {
        let buffer = String::from("Test builder");
        let mut lb = LinurgyBuilder::new();

        lb.set_input(Input::Buffer(&buffer));
        match lb.input {
            Input::Buffer(text) => assert_eq!(&buffer, text),
            _ => assert!(false, "Correct type not implemented"),
        }
        
        lb.set_input(Input::File("filename"));
        match lb.input {
            Input::File(text) => assert_eq!("filename", text),
            _ => assert!(false, "Correct type not implemented"),
        }

        lb.set_input(Input::StdIn);
        match lb.input {
            Input::StdIn => assert!(true),
            _ => assert!(false, "Correct type not implemented"),
        }
    }

    #[test]
    fn linurgy_set_output() {
        let mut buffer = String::from("Test builder");
        let mut buffer2 = String::from("Test builder");
        let mut lb = LinurgyBuilder::new();

        lb.set_output(Output::Buffer(&mut buffer));
        match lb.output {
            Output::Buffer(ref text) => assert_eq!(&&mut buffer2, text),
            _ => assert!(false, "Correct type not implemented"),
        }
        
        lb.set_output(Output::File("filename"));
        match lb.output {
            Output::File(text) => assert_eq!("filename", text),
            _ => assert!(false, "Correct type not implemented"),
        }

        lb.set_output(Output::StdOut);
        match lb.output {
            Output::StdOut => assert!(true),
            _ => assert!(false, "Correct type not implemented"),
        }
    }

    #[test]
    fn linurgy_set_newline_trigger() {
        let mut lb = LinurgyBuilder::new();
        
        lb.set_newline_trigger(5);
        assert_eq!(5, lb.editor.newline_count_trigger);
    }

    #[test]
    fn linurgy_set_new_text() {
        let mut lb = LinurgyBuilder::new();
        
        lb.set_new_text("cheese");
        assert_eq!("cheese", lb.editor.new_text);
    }

    #[test]
    fn linurgy_set_edit_type() {
        let mut lb = LinurgyBuilder::new();
        
        lb.set_edit_type(EditType::Insert);
        if let EditType::Insert = lb.editor.edit_type {
            assert!(true);
        } else {
            assert!(false, "Correct type not implemented");
        }
    }

    #[test]
    fn editor_add_line() {
        let mut ed = Editor::default();

        let line = String::from("test text\n");
        ed.add_line(&line);
        assert_eq!("test text\n", ed.buffer);
        assert_eq!(0, ed.current_count);

        let line = String::from(" more\n");
        ed.add_line(&line);
        assert_eq!("test text\n more\n", ed.buffer);
        assert_eq!(0, ed.current_count);

        let line = String::from("\n");
        ed.add_line(&line);
        assert_eq!("test text\n more\n\n", ed.buffer);
        assert_eq!(1, ed.current_count);

        let line = String::from("\n");
        ed.add_line(&line);
        assert_eq!("test text\n more\n\n\n-------\n", ed.buffer);
        assert_eq!(0, ed.current_count);
    }

    #[test]
    fn editor_add_line_with_diff_edit_type() {
        let mut ed = Editor::default();
        ed.edit_type = EditType::Insert;

        let line = String::from("\n");
        ed.add_line(&line);
        ed.add_line(&line);
        assert_eq!("-------\n\n\n", ed.buffer);

        let mut ed = Editor::default();
        ed.edit_type = EditType::Replace;

        let line = String::from("\n");
        ed.add_line(&line);
        ed.add_line(&line);
        assert_eq!("-------\n", ed.buffer);
    }

    #[test]
    fn editor_try_output() {
        let mut ed = Editor::default();
        assert_eq!(Some(String::from("")), ed.try_output());

        let line = String::from("\n");
        ed.add_line(&line);
        assert_eq!(None, ed.try_output());

        ed.add_line(&line);
        assert_eq!(Some(String::from("\n\n-------\n")), ed.try_output());
        assert_eq!(Some(String::from("")), ed.try_output());

        let line = String::from("test\n");
        ed.add_line(&line);
        assert_eq!(Some(String::from("test\n")), ed.try_output());
    }

    #[test]
    fn linurgy_write() {
        let mut output = String::new();
        let mut lb = LinurgyBuilder::new();
        lb.set_output(Output::Buffer(&mut output));

        let test_line = None;
        lb.write(test_line);
        assert_eq!("", output);

        let mut output = String::new();
        let mut lb = LinurgyBuilder::new();
        lb.set_output(Output::Buffer(&mut output));

        let test_line = Some(String::from("testline\n"));
        lb.write(test_line);
        assert_eq!("testline\n", output);

        let mut output = String::new();
        let mut lb = LinurgyBuilder::new();
        lb.set_output(Output::Buffer(&mut output));

        let test_line = Some(String::from("testline\n"));
        lb.write(test_line);
        let test_line = Some(String::from("testline\n"));
        lb.write(test_line);
        assert_eq!("testline\ntestline\n", output);
    }

    #[test]
    fn linurgy_process() {
        let mut output = String::new();
        let mut lb = LinurgyBuilder::new();
        lb.set_output(Output::Buffer(&mut output));

        let input = String::from("test\nlines\n");
        let reader = io::Cursor::new(&input);
        lb.process(reader);
        assert_eq!("test\nlines\n", &output);

        let mut output = String::new();
        let mut lb = LinurgyBuilder::new();
        lb.set_output(Output::Buffer(&mut output));

        let input = String::from("\n\n");
        let reader = io::Cursor::new(&input);
        lb.process(reader);
        assert_eq!("\n\n-------\n", &output);

        let mut output = String::new();
        let mut lb = LinurgyBuilder::new();
        lb.set_output(Output::Buffer(&mut output));

        let input = String::from("\n\n test post text\n\n");
        let reader = io::Cursor::new(&input);
        lb.process(reader);
        assert_eq!("\n\n-------\n test post text\n\n", &output);
    }

    #[test]
    fn linurgy_run() {
        let input = String::from("test\nlines\n");
        let mut output = String::new();
        let mut lb = LinurgyBuilder::new();
        lb.set_input(Input::Buffer(&input));
        lb.set_output(Output::Buffer(&mut output));
        lb.run();
        assert_eq!("test\nlines\n", &output);
    }
}