From e0441420ac9d5deee4c8c8423b20258ab2f01f60 Mon Sep 17 00:00:00 2001 From: Teddy Wing Date: Mon, 22 Oct 2018 21:02:02 +0200 Subject: initialize_trial_start(): Don't rewrite the file if it already exists The `File::open` function will truncate the file if it exists already: > This function will create a file if it does not exist, and will > truncate it if it does. (https://doc.rust-lang.org/std/fs/struct.File.html#method.create) We don't want this behaviour, as the file should only be created & initialised a single time. The trial timestamp should always correspond to the first trial launch of the program. It doesn't do us any good if the file is overwritten by DomeKey and updates the trial start time to a more current value. Thanks to 'sarnold' (https://stackoverflow.com/users/377270/sarnold) on Stack Overflow for the clean pattern matching code to match the `std::io::ErrorKind::AlreadyExists` error: https://stackoverflow.com/questions/28491759/matching-on-a-specific-error-type/43884600#43884600 --- src/trial.rs | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) (limited to 'src/trial.rs') diff --git a/src/trial.rs b/src/trial.rs index 238ac13..67bf795 100644 --- a/src/trial.rs +++ b/src/trial.rs @@ -1,5 +1,5 @@ -use std::fs::File; -use std::io::Write; +use std::fs::OpenOptions; +use std::io::{self, Write}; use std::result; use chrono::{DateTime, FixedOffset, Local, TimeZone}; @@ -26,7 +26,15 @@ fn initialize_trial_start() -> Result<()> { .chain_err(|| "failed to get XDG base directories")?; let trial_path = xdg_dirs.place_data_file("trial") .chain_err(|| "failed to get trial file path")?; - let mut trial_file = File::create(trial_path) + let mut trial_file = match OpenOptions::new() + .write(true) + .create_new(true) + .open(trial_path) + { + Ok(f) => Ok(f), + Err(ref e) if e.kind() == io::ErrorKind::AlreadyExists => return Ok(()), + Err(e) => Err(e), + } .chain_err(|| "failed to create trial file")?; write!(&mut trial_file, "{}", encoded_time) -- cgit v1.2.3