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
#![deprecated(since = "0.1.1", note = "please use the `version-sync` crate instead")]
extern crate pulldown_cmark;
extern crate toml;
extern crate semver_parser;

use std::fs::File;
use std::io::Read;
use std::result;

use pulldown_cmark::{Parser, Event, Tag};
use semver_parser::range::parse as parse_request;
use semver_parser::range::{VersionReq, Op};
use semver_parser::version::Version;
use semver_parser::version::parse as parse_version;
use toml::Value;

/// The common result type, our errors will be simple strings.
type Result<T> = result::Result<T, String>;

/// A fenced code block.
#[derive(Debug, Clone, PartialEq, Eq)]
struct CodeBlock<'a> {
    /// Text between the fences.
    content: &'a str,
    /// Line number starting with 1.
    first_line: usize,
}

impl<'a> CodeBlock<'a> {
    /// Contruct a new code block from text[start..end]. This only
    /// works for fenced code blocks. The `start` index must be the
    /// first line of data in the code block, `end` must be right
    /// after the final newline of a fenced code block.
    fn new(text: &'a str, start: usize, end: usize) -> CodeBlock {
        // A code block with no closing fence is reported as being
        // closed at the end of the file. In that case, we cannot be
        // sure to find a final newline.
        let last_nl = match text[..end - 1].rfind('\n') {
            Some(i) => i + 1,
            None => start,
        };
        let first_line = 1 + text[..start].lines().count();
        CodeBlock {
            content: &text[start..last_nl],
            first_line: first_line,
        }
    }
}

/// Return all data from `path`.
fn read_file(path: &str) -> std::io::Result<String> {
    let mut file = File::open(path)?;
    let mut buf = String::new();
    file.read_to_string(&mut buf)?;
    Ok(buf)
}

/// Indent every line in text by four spaces.
fn indent(text: &str) -> String {
    text.lines()
        .map(|line| String::from("    ") + line)
        .collect::<Vec<_>>()
        .join("\n")
}

/// Verify that the version range request matches the given version.
fn version_matches_request(version: &Version, request: &VersionReq) -> Result<()> {
    if request.predicates.len() != 1 {
        // Can only handle simple dependencies
        return Ok(());
    }

    let pred = &request.predicates[0];
    match pred.op {
        Op::Tilde | Op::Compatible => {
            if pred.major != version.major {
                return Err(format!(
                    "expected major version {}, found {}",
                    version.major,
                    pred.major,
                ));
            }
            if let Some(minor) = pred.minor {
                if minor != version.minor {
                    return Err(format!("expected minor version {}, found {}",
                                       version.minor,
                                       minor));
                }
            }
            if let Some(patch) = pred.patch {
                if patch != version.patch {
                    return Err(format!("expected patch version {}, found {}",
                                       version.patch,
                                       patch));
                }
            }
        }
        _ => return Ok(()), // We cannot check other operators.
    }

    Ok(())
}

/// Extract a dependency on the given package from a TOML code block.
fn extract_version_request(pkg_name: &str, block: &str) -> Result<VersionReq> {
    match block.parse::<Value>() {
        Ok(value) => {
            let version = value
                .get("dependencies")
                .or_else(|| value.get("dev-dependencies"))
                .and_then(|deps| deps.get(pkg_name))
                .and_then(|dep| dep.get("version").or_else(|| Some(dep)))
                .and_then(|version| version.as_str());
            match version {
                Some(version) => {
                    parse_request(version)
                        .map_err(|err| format!("could not parse dependency: {}", err))
                }
                None => Err(format!("no dependency on {}", pkg_name)),
            }
        }
        Err(err) => Err(format!("TOML parse error: {}", err)),
    }
}

/// Check if a code block language line says the block is TOML code.
fn is_toml_block(lang: &str) -> bool {
    // Split the language line as LangString::parse from rustdoc:
    // https://github.com/rust-lang/rust/blob/1.20.0/src/librustdoc/html/markdown.rs#L922
    lang.split(|c: char| !(c == '_' || c == '-' || c.is_alphanumeric()))
        .any(|token| token.trim() == "toml")
}

/// Find all TOML code blocks in a Markdown text.
fn find_toml_blocks(text: &str) -> Vec<CodeBlock> {
    let mut parser = Parser::new(text);
    let mut code_blocks = Vec::new();
    let mut start = 0;
    // A normal for-loop doesn't work since that would borrow the
    // parser mutably for the duration of the loop body, preventing us
    // from calling get_offset later.
    while let Some(event) = parser.next() {
        match event {
            Event::Start(Tag::CodeBlock(_)) => {
                start = parser.get_offset();
            }
            Event::End(Tag::CodeBlock(lang)) => {
                // Only fenced code blocks have language information.
                if is_toml_block(&lang) {
                    let end = parser.get_offset();
                    code_blocks.push(CodeBlock::new(text, start, end));
                }
            }
            _ => {}
        }
    }

    code_blocks
}

/// Check dependencies in Markdown code blocks.
///
/// This function finds all TOML code blocks in `path` and looks for
/// dependencies on `pkg_name` in those blocks. A code block fails the
/// check if it has a dependency on `pkg_name` that doesn't match
/// `pkg_version`, or if it has no dependency on `pkg_name` at all.
/// Code blocks also fails the check if they cannot be parsed as TOML.
///
/// # Errors
///
/// If any block failed the check, an `Err` is returned that can be
/// used to make a test fail or pass.
pub fn check_markdown_deps(path: &str, pkg_name: &str, pkg_version: &str) -> Result<()> {
    let text = read_file(path)
        .map_err(|err| format!("could not read {}: {}", path, err))?;
    let version = parse_version(pkg_version)
        .map_err(|err| format!("bad package version {:?}: {}", pkg_version, err))?;

    println!("Checking code blocks in {}...", path);
    let mut failed = false;
    for block in find_toml_blocks(&text) {
        let result = extract_version_request(pkg_name, block.content)
            .and_then(|request| version_matches_request(&version, &request));
        match result {
            Err(err) => {
                failed = true;
                println!("{} (line {}) ... {} in", path, block.first_line, err);
                println!("{}\n", indent(block.content));
            }
            Ok(()) => println!("{} (line {}) ... ok", path, block.first_line),
        }
    }

    if failed {
        return Err(format!("dependency errors in {}", path));
    }
    Ok(())
}

/// Assert that dependencies on the current package are up to date.
///
/// The macro will call [`check_markdown_deps`] on the file name given
/// in order to check that the TOML examples found all depend on a
/// current version of your package. The package name is automatically
/// taken from the `$CARGO_PKG_NAME` environment variable and the
/// version is taken from `$CARGO_PKG_VERSION`. These environment
/// variables are automatically set by Cargo when compiling your
/// crate.
///
/// # Usage
///
/// The typical way to use this macro is from an integration test:
///
/// ```rust,no_run
/// #[macro_use]
/// extern crate check_versions;
///
/// #[test]
/// # fn fake_hidden_test_case() {}
/// # // The above function ensures test_readme_deps is compiled.
/// fn test_readme_deps() {
///     assert_markdown_deps_updated!("README.md");
/// }
///
/// # fn main() {}
/// ```
///
/// Tests are run with the current directory set to directory where
/// your `Cargo.toml` file is, so this will find a `README.md` file
/// next to your `Cargo.toml` file.
///
/// # Panics
///
/// If any TOML code block fails the check, `panic!` will be invoked.
///
/// [`check_markdown_deps`]: fn.check_markdown_deps.html
#[macro_export]
macro_rules! assert_markdown_deps_updated {
    ($path:expr) => {
        let pkg_name = env!("CARGO_PKG_NAME");
        let pkg_version = env!("CARGO_PKG_VERSION");
        if let Err(err) = $crate::check_markdown_deps($path, pkg_name, pkg_version) {
            panic!(err);
        }
    }
}

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

    #[test]
    fn code_block_new() {
        let text = "Preceding text.\n\
                    ```\n\
                    foo\n\
                    ```\n\
                    Trailing text";
        let start = text.find("```\n").unwrap() + 4;
        let end = text.rfind("```\n").unwrap() + 4;
        assert_eq!(CodeBlock::new(text, start, end),
                   CodeBlock { content: "foo\n", first_line: 3 });
    }

    #[test]
    fn is_toml_block_simple() {
        assert!(!is_toml_block("rust"))
    }

    #[test]
    fn is_toml_block_comma() {
        assert!(is_toml_block("foo,toml"))
    }

    mod test_version_matches_request {
        use super::*;

        #[test]
        fn implicit_compatible() {
            let version = parse_version("1.2.3").unwrap();
            let request = parse_request("1.2.3").unwrap();
            assert_eq!(version_matches_request(&version, &request), Ok(()));
        }

        #[test]
        fn compatible() {
            let version = parse_version("1.2.3").unwrap();
            let request = parse_request("^1.2.3").unwrap();
            assert_eq!(version_matches_request(&version, &request), Ok(()));
        }

        #[test]
        fn tilde() {
            let version = parse_version("1.2.3").unwrap();
            let request = parse_request("~1.2.3").unwrap();
            assert_eq!(version_matches_request(&version, &request), Ok(()));
        }

        #[test]
        fn no_patch() {
            let version = parse_version("1.2.3").unwrap();
            let request = parse_request("1.2").unwrap();
            assert_eq!(version_matches_request(&version, &request), Ok(()));
        }

        #[test]
        fn no_minor() {
            let version = parse_version("1.2.3").unwrap();
            let request = parse_request("1").unwrap();
            assert_eq!(version_matches_request(&version, &request), Ok(()));
        }

        #[test]
        fn multiple_predicates() {
            let version = parse_version("1.2.3").unwrap();
            let request = parse_request(">= 1.2.3, < 2.0").unwrap();
            assert_eq!(version_matches_request(&version, &request), Ok(()));
        }

        #[test]
        fn unhandled_operator() {
            let version = parse_version("1.2.3").unwrap();
            let request = parse_request("< 2.0").unwrap();
            assert_eq!(version_matches_request(&version, &request), Ok(()));
        }

        #[test]
        fn bad_major() {
            let version = parse_version("2.0.0").unwrap();
            let request = parse_request("1.2.3").unwrap();
            assert_eq!(version_matches_request(&version, &request),
                       Err(String::from("expected major version 2, found 1")));
        }

        #[test]
        fn bad_minor() {
            let version = parse_version("1.3.0").unwrap();
            let request = parse_request("1.2.3").unwrap();
            assert_eq!(version_matches_request(&version, &request),
                       Err(String::from("expected minor version 3, found 2")));
        }

        #[test]
        fn bad_patch() {
            let version = parse_version("1.2.4").unwrap();
            let request = parse_request("1.2.3").unwrap();
            assert_eq!(version_matches_request(&version, &request),
                       Err(String::from("expected patch version 4, found 3")));
        }
    }

    mod test_extract_version_request {
        use super::*;

        #[test]
        fn simple() {
            let block = "[dependencies]\n\
                         foobar = '1.5'";
            let request = extract_version_request("foobar", block);
            assert_eq!(request.unwrap().predicates,
                       parse_request("1.5").unwrap().predicates);
        }

        #[test]
        fn table() {
            let block = "[dependencies]\n\
                         foobar = { version = '1.5', default-features = false }";
            let request = extract_version_request("foobar", block);
            assert_eq!(request.unwrap().predicates,
                       parse_request("1.5").unwrap().predicates);
        }

        #[test]
        fn dev_dependencies() {
            let block = "[dev-dependencies]\n\
                         foobar = '1.5'";
            let request = extract_version_request("foobar", block);
            assert_eq!(request.unwrap().predicates,
                       parse_request("1.5").unwrap().predicates);
        }

        #[test]
        fn bad_version() {
            let block = "[dependencies]\n\
                         foobar = '1.5.bad'";
            let request = extract_version_request("foobar", block);
            assert_eq!(request.unwrap_err(),
                       "could not parse dependency: Extra junk after valid predicate: .bad");
        }

        #[test]
        fn missing_dependency() {
            let block = "[dependencies]\n\
                         baz = '1.5.8'";
            let request = extract_version_request("foobar", block);
            assert_eq!(request.unwrap_err(), "no dependency on foobar");
        }

        #[test]
        fn empty() {
            let request = extract_version_request("foobar", "");
            assert_eq!(request.unwrap_err(), "no dependency on foobar");
        }

        #[test]
        fn bad_toml() {
            let block = "[dependencies]\n\
                         foobar = 1.5.8";
            let request = extract_version_request("foobar", block);
            assert_eq!(request.unwrap_err(),
                       "TOML parse error: expected newline, found a period at line 2");
        }
    }

    mod test_find_toml_blocks {
        use super::*;

        #[test]
        fn empty() {
            assert_eq!(find_toml_blocks(""), vec![]);
        }

        #[test]
        fn indented_block() {
            assert_eq!(find_toml_blocks("    code block\n"), vec![]);
        }

        #[test]
        fn single() {
            assert_eq!(find_toml_blocks("```toml\n```"),
                       vec![CodeBlock { content: "", first_line: 2 }]);
        }

        #[test]
        fn no_close_fence() {
            assert_eq!(find_toml_blocks("```toml\n"),
                       vec![CodeBlock { content: "", first_line: 2 }]);
        }
    }

    mod test_check_markdown_deps {
        use super::*;

        #[test]
        fn bad_path() {
            let no_such_file = if cfg!(unix) {
                "No such file or directory (os error 2)"
            } else {
                "The system cannot find the file specified. (os error 2)"
            };
            let errmsg = format!("could not read no-such-file.md: {}", no_such_file);
            assert_eq!(check_markdown_deps("no-such-file.md", "foobar", "1.2.3"),
                       Err(errmsg));
        }

        #[test]
        fn bad_pkg_version() {
            // This uses the README.md file from this crate.
            assert_eq!(check_markdown_deps("README.md", "foobar", "1.2"),
                       Err(String::from("bad package version \"1.2\": \
                                         Expected dot")));
        }
    }
}