Browse Source

Add handling of files with missing newline at end

master
Schneider 2 years ago
parent
commit
88ad30c3fa
Signed by: schneider GPG Key ID: 3F50B02A50039F3B
  1. 5
      src/app.rs
  2. 22
      src/gitignore.rs
  3. 1
      src/main.rs

5
src/app.rs

@ -107,7 +107,10 @@ fn add(glob: &str, local: bool) -> Result<()> {
info!("Working with git root in {:?}", root);
let mut file_path = PathBuf::from(&root);
if local {
let override_path = std::env::var("GITIG_OVERRIDE_PATH").ok();
if let Some(override_path) = override_path {
file_path = PathBuf::from(override_path);
} else if local {
file_path.push(".git/info/exclude")
} else {
file_path.push(".gitignore");

22
src/gitignore.rs

@ -28,7 +28,6 @@ impl Gitignore {
/// # Errors
///
/// - `ErrorKind::NoGitRootFound` when there was .gitignore file found at the default location
///
pub fn from_default_path() -> Result<Self> {
let mut path = git_dir()?.ok_or(ErrorKind::NoGitRootFound)?;
path.push(".gitignore");
@ -40,11 +39,30 @@ impl Gitignore {
use std::io::prelude::*;
let mut file = OpenOptions::new()
.write(true)
.read(true)
.append(true)
.create(true)
.open(&self.path)
.chain_err(|| "Error while opening gitignore file")?;
writeln!(file, "{}", line).chain_err(|| "Error while writing line to gitignore")?;
let file_len = file.stream_len()?;
let newline = if file_len > 0 {
file.seek(std::io::SeekFrom::End(-1))?;
let mut buf: Vec<u8> = vec![0; 1];
file.read_exact(&mut buf)?;
if buf[0] == '\n' as u8 {
// The last line already ends with a newline
""
} else {
// Add a newline if the last line doesn't end with one
"\n"
}
} else {
// The file is empty, so we don't need a newline
""
};
writeln!(file, "{}{}", newline, line)
.chain_err(|| "Error while writing line to gitignore")?;
Ok(())
}

1
src/main.rs

@ -29,6 +29,7 @@ This project used [rust-cli-boilerplate](https://github.com/ssokolow/rust-cli-bo
clippy::wildcard_imports,
clippy::integer_arithmetic
)]
#![feature(seek_stream_len)]
#[macro_use]
extern crate error_chain;

Loading…
Cancel
Save