Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ Pre-complied binaries for following platforms are available in [Releases page](h
- Support all options and rmate.rc settings described in [Ruby implementation](https://github.com/textmate/rmate).
- Create backups of local files to avoid corrupting your files if any io/network operations go wrong.
- Verbose logging of operation (use `-v` one or more times).
- Open a file that does not exist yet as an empty buffer; the file is created when you first save it. Use `-c`/`--create` to create it when opening.

### Demo
[![the screencat](https://asciinema.org/a/fqgvpm9yPdDFAZ11f8uY1DF26.svg)](https://asciinema.org/a/fqgvpm9yPdDFAZ11f8uY1DF26).
73 changes: 51 additions & 22 deletions src/file_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use std::fs::File;
use std::fs::{canonicalize, metadata, Metadata};
use std::hash::{Hash, Hasher};
use std::io::{BufRead, BufReader, BufWriter, Error, ErrorKind, Read, Seek, SeekFrom, Write};
use std::path::Path;
use std::path::{Path, PathBuf};
use std::time::Instant;
use std::{cmp, format};
use std::{fs, io};
Expand Down Expand Up @@ -139,7 +139,8 @@ pub(crate) fn write_to_disk(
backup_fn.push("~");
backup_fn_canon.set_file_name(&backup_fn);

let mut can_backup = true;
// There is nothing to back up if the file does not exist yet.
let mut can_backup = fn_canon.exists();
let mut no_backup_tries = 0;
while backup_fn_canon.is_file() {
if no_backup_tries < settings::NO_TRIES_CREATE_BACKUP_FN {
Expand Down Expand Up @@ -176,6 +177,7 @@ pub(crate) fn write_to_disk(
let fn_canon = opened_buffer.canon_path.as_path();
let fp = fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(fn_canon)
.map_err(|e| Error::other(format!("{}: {:?}", fn_canon.to_string_lossy(), e)))?;
Expand Down Expand Up @@ -248,25 +250,24 @@ pub(crate) fn get_requested_buffers(

// Iterate over all files and create bookkeeping info
for (idx, file) in settings.files.iter().enumerate() {
#[allow(clippy::if_not_else)]
let filename_canon = if !settings.create {
canonicalize(file).map_err(|e| e.to_string())?
} else {
let r = canonicalize(file);
match r {
Err(e) => match e.kind() {
ErrorKind::NotFound => {
info!("Creating new empty file: {:?}", &file.display());
let _r = File::create(file).map_err(|e| e.to_string())?;
canonicalize(file).map_err(|e| e.to_string())?
}
_ => return Err(e.to_string()),
},
Ok(fc) => {
let filename_canon = match canonicalize(file) {
Ok(fc) => {
if settings.create {
warn!("File already exists: {:?}", &fc.display());
fc
}
fc
}
Err(e) if e.kind() == ErrorKind::NotFound && settings.create => {
info!("Creating new empty file: {:?}", &file.display());
let _r = File::create(file).map_err(|e| e.to_string())?;
canonicalize(file).map_err(|e| e.to_string())?
}
// Like the Ruby rmate, open a missing file as an empty buffer;
// the file is created when the editor saves it.
Err(e) if e.kind() == ErrorKind::NotFound => {
canonicalize_missing(file).map_err(|e| e.to_string())?
}
Err(e) => return Err(e.to_string()),
};

#[allow(clippy::needless_late_init)]
Expand All @@ -290,11 +291,22 @@ pub(crate) fn get_requested_buffers(
None
};

let md = metadata(&filename_canon).map_err(|e| e.to_string())?;
if md.is_dir() {
let md = if filename_canon.exists() {
Some(metadata(&filename_canon).map_err(|e| e.to_string())?)
} else {
info!(
"{} does not exist yet, it will be created on save",
filename_canon.display()
);
None
};
if md.as_ref().is_some_and(Metadata::is_dir) {
return Err("openning directory not supported".to_string());
}
let canwrite = is_writable(&filename_canon, &md);
// A missing file is checked for write access when it is saved.
let canwrite = md
.as_ref()
.is_none_or(|md| is_writable(&filename_canon, md));
// Show a warning even though user has used the --force flag.
if !canwrite && settings.force {
warn!("{} is readonly!", filename_canon.display());
Expand All @@ -312,7 +324,7 @@ pub(crate) fn get_requested_buffers(
disp_name.push(":");
disp_name.push(file_name_string);

let filesize = md.len();
let filesize = md.as_ref().map_or(0, Metadata::len);
let rand_temp_file = tempfile::tempfile().map_err(|e| e.to_string())?;

let mut hasher = DefaultHasher::new();
Expand Down Expand Up @@ -343,6 +355,23 @@ pub(crate) fn get_requested_buffers(
Ok(buffers)
}

// Canonicalize the path of a file that does not exist yet: its parent
// directory must exist.
fn canonicalize_missing<P: AsRef<Path>>(p: P) -> io::Result<PathBuf> {
let p = p.as_ref();
let file_name = p.file_name().ok_or_else(|| {
Error::new(
ErrorKind::InvalidInput,
"no valid file name found in input argument",
)
})?;
let parent = match p.parent() {
Some(dir) if !dir.as_os_str().is_empty() => dir,
_ => Path::new("."),
};
Ok(canonicalize(parent)?.join(file_name))
}

// Check if file is writable by user
// metadata.permissions.readonly() checks all bits of file,
// regradless of which user is trying to write to it.
Expand Down
2 changes: 0 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@ use structopt::StructOpt;
// workflow that each step in release.yml calls it with different input parameters.
// TODO: Investigate the type (u64, u32, ...) that file IO functions (such as fs::copy) return on other platforms.
// We can then remove clippy::cast_possible_truncation from file_handler.rs
// TODO: Flip how the setting for creating non-existing files work so by default it doesn't create
// new empty files.<18-07-22, hamid> //

fn main() -> Result<(), String> {
// Read settings from cmd line arguments
Expand Down
11 changes: 8 additions & 3 deletions src/remote_editor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use log::{debug, info, trace};
use socket2::{Domain, Type};
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader, BufWriter, Error, ErrorKind, Write};
use std::io::{self, BufRead, BufReader, BufWriter, Error, ErrorKind, Read, Write};
use std::net::{IpAddr, Ipv4Addr};

pub(crate) fn connect_to_editor(
Expand Down Expand Up @@ -101,8 +101,13 @@ pub(crate) fn open_file_in_remote(
writeln!(&mut buf_writer, "data: {}", opened_buffer.size).map_err(|e| e.to_string())?;
buf_writer.flush().map_err(|e| e.to_string())?;

// Read file from disk and send it over the socket
let fp = File::open(&opened_buffer.canon_path).map_err(|e| e.to_string())?;
// Read file from disk and send it over the socket.
// A file that does not exist yet is sent as empty.
let fp: Box<dyn Read> = if opened_buffer.canon_path.exists() {
Box::new(File::open(&opened_buffer.canon_path).map_err(|e| e.to_string())?)
} else {
Box::new(io::empty())
};
let mut buf_reader = BufReader::with_capacity(bsize, fp);
debug!(
"-> Opening {} (size: {} bytes).",
Expand Down
3 changes: 2 additions & 1 deletion src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ pub(crate) struct Settings {
#[structopt(short, long)]
pub force: bool,

/// Create a new file if the given file name does not exist
/// Create a missing file when opening it.
/// Without this flag, a missing file is created when it is first saved
#[structopt(short, long)]
pub create: bool,

Expand Down