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
// git-dit - the distributed issue tracker for git
// Copyright (C) 2016, 2017 Matthias Beyer <mail@beyermatthias.de>
// Copyright (C) 2016, 2017 Julian Ganz <neither@nut.email>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

//! Line processing utilities
//!


/// Quotation wrapper for iterators over strings
///
/// This iterator wrapps an iterator over lines as string-like items. It
/// returns the lines prefixed with a quotation.
///
#[derive(Debug)]
pub struct Quoted<I, S>(I)
    where I: Iterator<Item = S>,
          S: AsRef<str>;

impl<I, J, S> From<I> for Quoted<J, S>
    where I: IntoIterator<Item = S, IntoIter = J>,
          J: Iterator<Item = S>,
          S: AsRef<str>
{
    fn from(lines: I) -> Self {
        Quoted(lines.into_iter())
    }
}

impl<I, S> Iterator for Quoted<I, S>
    where I: Iterator<Item = S>,
          S: AsRef<str>
{
    type Item = String;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next().map(|l| {
            let line = l.as_ref();
            match line.is_empty() {
                true  => String::from(">"),
                false => format!("> {}", line),
            }
        })
    }
}


/// An Iterator type which iterates over String objects, used to strip
/// whitespace from an iterator over String.
///
pub struct StripWhiteSpaceLeftIter<I, S>(I)
    where I: Iterator<Item = S> + Sized,
          S: AsRef<str>;

impl<I, J, S> From<I> for StripWhiteSpaceLeftIter<J, S>
    where I: IntoIterator<Item = S, IntoIter = J>,
          J: Iterator<Item = S>,
          S: AsRef<str>
{
    fn from(lines: I) -> Self {
        StripWhiteSpaceLeftIter(lines.into_iter())
    }
}

impl<'a, I, S> Iterator for StripWhiteSpaceLeftIter<I, S>
    where I: Iterator<Item = S> + Sized,
          S: AsRef<str>
{
    type Item = String;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next().map(|s| String::from(s.as_ref().trim_left()))
    }
}


/// An Iterator type which iterates over String objects, used to strip
/// whitespace from an iterator over String.
///
pub struct StripWhiteSpaceRightIter<I, S>(I)
    where I: Iterator<Item = S> + Sized,
          S: AsRef<str>;

impl<I, J, S> From<I> for StripWhiteSpaceRightIter<J, S>
    where I: IntoIterator<Item = S, IntoIter = J>,
          J: Iterator<Item = S>,
          S: AsRef<str>
{
    fn from(lines: I) -> Self {
        StripWhiteSpaceRightIter(lines.into_iter())
    }
}

impl<'a, I, S> Iterator for StripWhiteSpaceRightIter<I, S>
    where I: Iterator<Item = S> + Sized,
          S: AsRef<str>
{
    type Item = String;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next().map(|s| String::from(s.as_ref().trim_right()))
    }
}


/// An iterator type for removing comment lines
///
/// Given an iterator over the lines of a message in the form of strings, this
/// iterator will remove all lines starting with a "#".
///
pub struct WithoutCommentsIter<I, S>(I)
    where I: Iterator<Item = S> + Sized,
          S: AsRef<str>;

impl<I, J, S> From<I> for WithoutCommentsIter<J, S>
    where I: IntoIterator<Item = S, IntoIter = J>,
          J: Iterator<Item = S>,
          S: AsRef<str>
{
    fn from(lines: I) -> Self {
        WithoutCommentsIter(lines.into_iter())
    }
}

impl<I, S> Iterator for WithoutCommentsIter<I, S>
    where I: Iterator<Item = S> + Sized,
          S: AsRef<str>
{
    type Item = S;

    fn next(&mut self) -> Option<Self::Item> {
        while let Some(next) = self.0.next() {
            // we do not trim whitespace here, because of code blocks in the message which might
            // have a "#" at the beginning
            if !next.as_ref().starts_with("#") {
                return Some(next)
            }
        }
        None
    }
}


/// Iterator adapter for removing blank lines from the end of a sequence
///
/// This iterator wraps an iterator over lines and forwards all lines from the
/// wrapped iterator except trailing blank lines.
///
pub struct TrailingBlankTrimmer<I, S>
    where I: Iterator<Item = S> + Sized,
          S: AsRef<str> + Default
{
    inner: ::std::iter::Peekable<I>,
    // counter for blanks
    blanks: usize,
}

impl<I, J, S> From<I> for TrailingBlankTrimmer<J, S>
    where I: IntoIterator<Item = S, IntoIter = J>,
          J: Iterator<Item = S>,
          S: AsRef<str> + Default
{
    fn from(lines: I) -> Self {
        TrailingBlankTrimmer { inner: lines.into_iter().peekable(), blanks: 0 }
    }
}

impl<I, S> Iterator for TrailingBlankTrimmer<I, S>
    where I: Iterator<Item = S>,
          S: AsRef<str> + Default
{
    type Item = S;

    fn next(&mut self) -> Option<Self::Item> {
        if self.blanks > 0 {
            // If we recorded any blank lines, we return them.
            self.blanks = self.blanks - 1;
            return Some(S::default());
        }

        // Record and consume blank lines
        while self
            .inner
            .peek()
            .map(AsRef::as_ref)
            .map(str::is_empty)
            .unwrap_or_else(|| {
                // We reached the end of input and don't want to return any more
                // lines.
                self.blanks = 0;
                false
            })
        {
            self.blanks = self.blanks + 1;
            self.inner.next();
        }

        if self.blanks > 0 {
            // If we recorded any blank lines, we return them.
            self.blanks = self.blanks - 1;
            Some(S::default())
        } else {
            self.inner.next()
        }
    }
}


/// Convenience iterator for stripping things from a message
///
/// This iterator strips comments, trailing whitespace in each line and trailing
/// blank lines.
///
pub type StrippingIter<I, S> = TrailingBlankTrimmer<
    StripWhiteSpaceRightIter<
        WithoutCommentsIter<I, S>,
    S>,
String>;




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

    #[test]
    fn quoted_lines() {
        let mut lines = Quoted::from(vec!["foo", "bar", "", "baz"]);
        assert_eq!(lines.next().expect("Premature end of input"), "> foo");
        assert_eq!(lines.next().expect("Premature end of input"), "> bar");
        assert_eq!(lines.next().expect("Premature end of input"), ">");
        assert_eq!(lines.next().expect("Premature end of input"), "> baz");
        assert!(!lines.next().is_some());
    }

    #[test]
    fn left_stripped_lines() {
        let mut lines = StripWhiteSpaceLeftIter::from(vec!["foo  ", "  bar", "  ", ""]);
        assert_eq!(lines.next().expect("Premature end of input"), "foo  ");
        assert_eq!(lines.next().expect("Premature end of input"), "bar");
        assert_eq!(lines.next().expect("Premature end of input"), "");
        assert_eq!(lines.next().expect("Premature end of input"), "");
        assert!(!lines.next().is_some());
    }

    #[test]
    fn right_stripped_lines() {
        let mut lines = StripWhiteSpaceRightIter::from(vec!["foo  ", "  bar", "  ", ""]);
        assert_eq!(lines.next().expect("Premature end of input"), "foo");
        assert_eq!(lines.next().expect("Premature end of input"), "  bar");
        assert_eq!(lines.next().expect("Premature end of input"), "");
        assert_eq!(lines.next().expect("Premature end of input"), "");
        assert!(!lines.next().is_some());
    }

    #[test]
    fn lines_without_comments() {
        let mut lines = WithoutCommentsIter::from(vec!["foo", "# bar", "#", ""]);
        assert_eq!(lines.next().expect("Premature end of input"), "foo");
        assert_eq!(lines.next().expect("Premature end of input"), "");
        assert!(!lines.next().is_some());
    }

    #[test]
    fn trailing_blank_trimmer() {
        let mut lines = TrailingBlankTrimmer::from(vec!["", "foo", "bar", "", "baz", "", ""]);
        assert_eq!(lines.next().expect("Premature end of input"), "");
        assert_eq!(lines.next().expect("Premature end of input"), "foo");
        assert_eq!(lines.next().expect("Premature end of input"), "bar");
        assert_eq!(lines.next().expect("Premature end of input"), "");
        assert_eq!(lines.next().expect("Premature end of input"), "baz");
        assert!(!lines.next().is_some());
    }
}