Skip to content

Commit

Permalink
Normalize "\r\n" to "\n" to ensure ^ and $ match line boundaries
Browse files Browse the repository at this point in the history
The regex crate only considers "\n" a line boundary, so ^ and $ don't
match "\r\n". This can be a problem if code is checked out on Windows
and Git helpfully rewrites your "\n" to "\r\n". I ran into this
problem when testing GitHub Actions on the textwrap repository.

See rust-lang/regex#244.
  • Loading branch information
mgeisler committed Jul 3, 2020
1 parent e12058f commit 91a9a41
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 2 deletions.
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,6 @@ toml = "0.5"
url = "2.0"
itertools = "0.9"
regex = "1.1"

[dev-dependencies]
tempfile = "3.1"
18 changes: 18 additions & 0 deletions src/contains_regex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,4 +118,22 @@ mod tests {
)
}

#[test]
fn line_boundaries() {
// The regex crate doesn't treat \r\n as a line boundary
// (https://github.com/rust-lang/regex/issues/244), so
// version-sync makes sure to normalize \r\n to \n when
// reading files.
use std::io::Write;
let mut file = tempfile::NamedTempFile::new().unwrap();

println!("Path: {}", file.path().to_str().unwrap());

file.write_all(b"first line\r\nsecond line\r\nthird line\r\n")
.unwrap();
assert_eq!(
check_contains_regex(file.path().to_str().unwrap(), "^second line$", "", ""),
Ok(())
)
}
}
6 changes: 4 additions & 2 deletions src/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,14 @@ use semver_parser::version::Version;
/// The common result type, our errors will be simple strings.
pub type Result<T> = result::Result<T, String>;

/// Return all data from `path`.
/// Return all data from `path`. Line boundaries are normalized from
/// "\r\n" to "\n" to make sure "^" and "$" will match them. See
/// https://github.com/rust-lang/regex/issues/244 for details.
pub fn read_file(path: &str) -> io::Result<String> {
let mut file = File::open(path)?;
let mut buf = String::new();
file.read_to_string(&mut buf)?;
Ok(buf)
Ok(buf.replace("\r\n", "\n"))
}

/// Indent every line in text by four spaces.
Expand Down

0 comments on commit 91a9a41

Please sign in to comment.