Improve API by introducing a PlatformType struct

This commit is contained in:
Danilo Bargen 2021-12-06 00:31:58 +01:00
commit 4a92bed585
3 changed files with 75 additions and 49 deletions

View file

@ -16,7 +16,7 @@ use zip::ZipArchive;
use crate::{ use crate::{
error::TealdeerError::{self, CacheError, UpdateError}, error::TealdeerError::{self, CacheError, UpdateError},
types::{PathSource, PlatformType}, types::{PathSource, PlatformStrategy, PlatformType},
}; };
static CACHE_DIR_ENV_VAR: &str = "TEALDEER_CACHE_DIR"; static CACHE_DIR_ENV_VAR: &str = "TEALDEER_CACHE_DIR";
@ -27,7 +27,7 @@ static TLDR_OLD_PAGES_DIR: &str = "tldr-master";
#[derive(Debug)] #[derive(Debug)]
pub struct Cache { pub struct Cache {
url: String, url: String,
platform: PlatformType, platform: PlatformStrategy,
} }
#[derive(Debug)] #[derive(Debug)]
@ -64,7 +64,7 @@ pub enum CacheFreshness {
} }
impl Cache { impl Cache {
pub fn new<S>(url: S, platform: PlatformType) -> Self pub fn new<S>(url: S, platform: PlatformStrategy) -> Self
where where
S: Into<String>, S: Into<String>,
{ {
@ -196,7 +196,7 @@ impl Cache {
/// Return the platform directory. /// Return the platform directory.
fn get_platform_dir(&self) -> &'static str { fn get_platform_dir(&self) -> &'static str {
match self.platform { match self.platform.platform_type {
PlatformType::Linux { .. } => "linux", PlatformType::Linux { .. } => "linux",
PlatformType::OsX { .. } => "osx", PlatformType::OsX { .. } => "osx",
PlatformType::SunOs { .. } => "sunos", PlatformType::SunOs { .. } => "sunos",
@ -305,7 +305,7 @@ impl Cache {
let mut pages = WalkDir::new(platforms_dir) let mut pages = WalkDir::new(platforms_dir)
.min_depth(1) // Skip root directory .min_depth(1) // Skip root directory
.into_iter() .into_iter()
.filter_entry(|e| self.platform.is_all() || should_walk(e)) // Filter out pages for other architectures .filter_entry(|e| self.platform.list_all || should_walk(e)) // Filter out pages for other architectures
.filter_map(Result::ok) // Convert results to options, filter out errors .filter_map(Result::ok) // Convert results to options, filter out errors
.filter_map(|e| { .filter_map(|e| {
let path = e.path(); let path = e.path();

View file

@ -40,7 +40,7 @@ use crate::{
error::TealdeerError::ConfigError, error::TealdeerError::ConfigError,
extensions::Dedup, extensions::Dedup,
output::print_page, output::print_page,
types::{ColorOptions, PlatformType}, types::{ColorOptions, PlatformStrategy, PlatformType},
utils::{print_error, print_warning}, utils::{print_error, print_warning},
}; };
@ -89,7 +89,7 @@ struct Args {
hide_possible_values = true, hide_possible_values = true,
hide_default_value = true, hide_default_value = true,
)] )]
platform: PlatformType, platform: PlatformStrategy,
/// Deprecated alias of `platform` /// Deprecated alias of `platform`
#[clap( #[clap(
@ -101,7 +101,7 @@ struct Args {
hide_possible_values = true, hide_possible_values = true,
hide_default_value = true, hide_default_value = true,
)] )]
os: PlatformType, os: PlatformStrategy,
/// Override the language /// Override the language
#[clap(short = 'L', long = "language")] #[clap(short = 'L', long = "language")]
@ -406,8 +406,8 @@ fn main() {
"The -m / --markdown flag is deprecated, use -r / --raw instead", "The -m / --markdown flag is deprecated, use -r / --raw instead",
); );
} }
let default_platform = PlatformType::current(false); let default_platform = PlatformType::current();
if args.os != default_platform { if args.os.platform_type != default_platform || args.os.list_all {
print_warning( print_warning(
enable_styles, enable_styles,
"The -o / --os flag is deprecated, use -p / --platform instead", "The -o / --os flag is deprecated, use -p / --platform instead",

View file

@ -2,40 +2,79 @@
use std::{fmt, str}; use std::{fmt, str};
use serde_derive::{Deserialize, Serialize}; use serde::Deserialize;
#[derive(Debug, Eq, PartialEq, Copy, Clone, Serialize, Deserialize)] /// The platform types supported by tldr.
#[serde(rename_all = "lowercase")] #[derive(Debug, Eq, PartialEq, Copy, Clone)]
#[allow(dead_code)] #[allow(dead_code)]
pub enum PlatformType { pub enum PlatformType {
Linux { all: bool }, Linux,
OsX { all: bool }, OsX,
SunOs { all: bool }, SunOs,
Windows { all: bool }, Windows,
} }
impl fmt::Display for PlatformType { impl fmt::Display for PlatformType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self { match self {
Self::Linux { .. } => write!(f, "Linux"), Self::Linux => write!(f, "Linux"),
Self::OsX { .. } => write!(f, "macOS / BSD"), Self::OsX => write!(f, "macOS / BSD"),
Self::SunOs { .. } => write!(f, "SunOS"), Self::SunOs => write!(f, "SunOS"),
Self::Windows { .. } => write!(f, "Windows"), Self::Windows => write!(f, "Windows"),
} }
} }
} }
impl str::FromStr for PlatformType { /// The platform lookup strategy.
///
/// Includes both the platform type, as well as
#[derive(Debug, Copy, Clone)]
pub struct PlatformStrategy {
/// The platform type that should be looked up.
pub platform_type: PlatformType,
/// Flag indicating whether all pages should be listed or not. This is only
/// used when the special platform type `all` is specified by the user.
pub list_all: bool,
}
impl PlatformStrategy {
pub fn new(platform_type: PlatformType) -> Self {
Self {
platform_type,
list_all: false,
}
}
/// Return a `PlatformStrategy` containing the current platform as the
/// target platform type.
pub fn current() -> Self {
Self {
platform_type: PlatformType::current(),
list_all: false,
}
}
/// Like `current()`, but when listing the pages, return the pages for all
/// platforms, not just for the current platform.
pub fn all() -> Self {
Self {
platform_type: PlatformType::current(),
list_all: true,
}
}
}
impl str::FromStr for PlatformStrategy {
type Err = String; type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> { fn from_str(s: &str) -> Result<Self, Self::Err> {
match s { match s {
"linux" => Ok(Self::Linux { all: false }), "linux" => Ok(PlatformStrategy::new(PlatformType::Linux)),
"osx" | "macos" => Ok(Self::OsX { all: false }), "osx" | "macos" => Ok(PlatformStrategy::new(PlatformType::OsX)),
"windows" => Ok(Self::Windows { all: false }), "windows" => Ok(PlatformStrategy::new(PlatformType::Windows)),
"sunos" => Ok(Self::SunOs { all: false }), "sunos" => Ok(PlatformStrategy::new(PlatformType::SunOs)),
"current" => Ok(PlatformType::current(false)), "current" => Ok(PlatformStrategy::current()),
"all" => Ok(PlatformType::current(true)), "all" => Ok(PlatformStrategy::all()),
other => Err(format!( other => Err(format!(
"Unknown platform: {}. Possible values: linux, macos, osx, windows, sunos, current, all", "Unknown platform: {}. Possible values: linux, macos, osx, windows, sunos, current, all",
other other
@ -46,8 +85,8 @@ impl str::FromStr for PlatformType {
impl PlatformType { impl PlatformType {
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
pub fn current(all: bool) -> Self { pub fn current() -> Self {
Self::Linux { all } Self::Linux
} }
#[cfg(any( #[cfg(any(
@ -57,13 +96,13 @@ impl PlatformType {
target_os = "openbsd", target_os = "openbsd",
target_os = "dragonfly" target_os = "dragonfly"
))] ))]
pub fn current(all: bool) -> Self { pub fn current() -> Self {
Self::OsX { all } Self::OsX
} }
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
pub fn current(all: bool) -> Self { pub fn current() -> Self {
Self::Windows { all } Self::Windows
} }
#[cfg(not(any( #[cfg(not(any(
@ -75,21 +114,8 @@ impl PlatformType {
target_os = "dragonfly", target_os = "dragonfly",
target_os = "windows" target_os = "windows"
)))] )))]
pub fn current(all: bool) -> Self { pub fn current() -> Self {
Self::Other { all } Self::Other
}
/// Return whether or not the `all` flag is set.
///
/// This flag is only relevant when listing pages: When `all` is set to
/// `true`, then the pages for all platforms should be listed.
pub fn is_all(self) -> bool {
match self {
Self::Linux { all }
| Self::OsX { all }
| Self::SunOs { all }
| Self::Windows { all } => all,
}
} }
} }