exa/src/options/version.rs
Benjamin Sago ed59428cbc Replace Misfire with a testable OptionsResult
This was meant to be a small change, but it spiralled into a big one.

The original intention was to separate OptionsResult and OptionsError. With these types separated, the Help and Version variants can only be returned from the Options::parse function, and the later option-parsing functions can only return success or errors.

Also, Misfire was a silly name.

As a side-effect of Options::parse returning OptionsResult instead of Result<Options, Misfire>, we could no longer use unwrap() or unwrap_err() to get the contents out. This commit makes OptionsResult into a value type, and Options::parse a pure function. It feels like it should be one, having its return value entirely dependent on its arguments, but it also loaded locales and time zones. These parts have been moved into lazy_static references, and the code still passes tests without much change.

OptionsResult isn't PartialEq yet, because the file colouring uses a Box internally.
2020-10-12 23:47:36 +01:00

64 lines
1.6 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! Printing the version string.
//!
//! The code that works out which string to print is done in `build.rs`.
use std::fmt;
use crate::options::flags;
use crate::options::parser::MatchedFlags;
#[derive(PartialEq, Debug, Copy, Clone)]
pub struct VersionString;
// There were options here once, but there arent anymore!
impl VersionString {
/// Determines how to show the version, if at all, based on the users
/// command-line arguments. This one works backwards from the other
/// deduce functions, returning Err if help needs to be shown.
///
/// Like --help, this doesnt check for errors.
pub fn deduce(matches: &MatchedFlags) -> Option<Self> {
if matches.count(&flags::VERSION) > 0 {
Some(Self)
}
else {
None
}
}
}
impl fmt::Display for VersionString {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "{}", include!(concat!(env!("OUT_DIR"), "/version_string.txt")))
}
}
#[cfg(test)]
mod test {
use crate::options::{Options, OptionsResult};
use std::ffi::OsString;
fn os(input: &'static str) -> OsString {
let mut os = OsString::new();
os.push(input);
os
}
#[test]
fn version() {
let args = [ os("--version") ];
let opts = Options::parse(&args, &None);
assert!(matches!(opts, OptionsResult::Version(_)));
}
#[test]
fn version_with_file() {
let args = [ os("--version"), os("me") ];
let opts = Options::parse(&args, &None);
assert!(matches!(opts, OptionsResult::Version(_)));
}
}