Merge pull request #162 from dbrgn/show-dirs

Implement new --show-dirs command
This commit is contained in:
Danilo Bargen 2021-02-05 00:32:20 +01:00 committed by GitHub
commit 663926cc0e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
11 changed files with 121 additions and 33 deletions

View file

@ -15,7 +15,7 @@ jobs:
strategy:
matrix:
platform: [ubuntu-latest, macos-latest, windows-latest]
rust: [1.40.0, stable]
rust: [1.41.1, stable]
runs-on: ${{ matrix.platform }}
steps:
- uses: actions/checkout@v2
@ -45,7 +45,7 @@ jobs:
- uses: actions/checkout@v2
- uses: actions-rs/toolchain@v1
with:
toolchain: 1.46.0
toolchain: 1.41.1
components: clippy
override: true
- uses: actions-rs/clippy-check@v1

View file

@ -6,7 +6,7 @@ _tealdeer()
_init_completion || return
case $prev in
-h|--help|-v|--version|-l|--list|-u|--update|-c|--clear-cache|-p|--pager|-m|--markdown|--config-path|--seed-config|-q|--quiet)
-h|--help|-v|--version|-l|--list|-u|--update|-c|--clear-cache|-p|--pager|-m|--markdown|--show-paths|--seed-config|-q|--quiet)
return
;;
-f|--render)

View file

@ -8,7 +8,7 @@ the config file can be done manually or with the help of `tldr`:
The configuration file path follows OS conventions. It can be queried with the
following command:
$ tldr --config-path
$ tldr --show-paths
On Linux, this will usually be `~/.config/tealdeer/config.toml`.

View file

@ -13,7 +13,7 @@ complete -c tldr -s c -l clear-cache -d 'Clear the local cache.' -f
complete -c tldr -s p -l pager -d 'Use a pager to page output.' -f
complete -c tldr -s m -l markdown -d 'Display the raw markdown instead of rendering it.' -f
complete -c tldr -s q -l quiet -d 'Suppress informational messages.' -f
complete -c tldr -l config-path -d 'Show config file path.' -f
complete -c tldr -l show-paths -d 'Show file and directory paths used by tealdeer.' -f
complete -c tldr -l seed-config -d 'Create a basic config.' -f
complete -c tldr -l color -d 'Controls when to use color.' -xa 'always auto never'

View file

@ -13,7 +13,7 @@ use tar::Archive;
use walkdir::{DirEntry, WalkDir};
use crate::error::TealdeerError::{self, CacheError, UpdateError};
use crate::types::OsType;
use crate::types::{OsType, PathSource};
#[derive(Debug)]
pub struct Cache {
@ -33,14 +33,14 @@ impl Cache {
}
/// Return the path to the cache directory.
fn get_cache_dir() -> Result<PathBuf, TealdeerError> {
pub fn get_cache_dir() -> Result<(PathBuf, PathSource), TealdeerError> {
// Allow overriding the cache directory by setting the
// $TEALDEER_CACHE_DIR env variable.
if let Ok(value) = env::var("TEALDEER_CACHE_DIR") {
let path = PathBuf::from(value);
if path.exists() && path.is_dir() {
return Ok(path);
return Ok((path, PathSource::EnvVar));
} else {
return Err(CacheError(
"Path specified by $TEALDEER_CACHE_DIR \
@ -52,7 +52,7 @@ impl Cache {
// Otherwise, fall back to user cache directory.
match get_app_root(AppDataType::UserCache, &crate::APP_INFO) {
Ok(dirs) => Ok(dirs),
Ok(dirs) => Ok((dirs, PathSource::OsConvention)),
Err(_) => Err(CacheError(
"Could not determine user cache directory.".into(),
)),
@ -94,7 +94,7 @@ impl Cache {
let mut archive = Self::decompress(&bytes[..]);
// Determine paths
let cache_dir = Self::get_cache_dir()?;
let (cache_dir, _) = Self::get_cache_dir()?;
// Make sure that cache directory exists
debug!("Ensure cache directory {:?} exists", &cache_dir);
@ -119,7 +119,7 @@ impl Cache {
/// Return the duration since the cache directory was last modified.
pub fn last_update() -> Option<Duration> {
if let Ok(cache_dir) = Self::get_cache_dir() {
if let Ok((cache_dir, _)) = Self::get_cache_dir() {
if let Ok(metadata) = fs::metadata(cache_dir.join("tldr-master")) {
if let Ok(mtime) = metadata.modified() {
let now = SystemTime::now();
@ -161,7 +161,7 @@ impl Cache {
// Get cache dir
let cache_dir = match Self::get_cache_dir() {
Ok(cache_dir) => cache_dir.join("tldr-master"),
Ok((cache_dir, _)) => cache_dir.join("tldr-master"),
Err(e) => {
log::error!("Could not get cache directory: {}", e);
return None;
@ -194,7 +194,7 @@ impl Cache {
/// Return the available pages.
pub fn list_pages(&self) -> Result<Vec<String>, TealdeerError> {
// Determine platforms directory and platform
let cache_dir = Self::get_cache_dir()?;
let (cache_dir, _) = Self::get_cache_dir()?;
let platforms_dir = cache_dir.join("tldr-master").join("pages");
let platform_dir = self.get_platform_dir();
@ -243,7 +243,7 @@ impl Cache {
/// Delete the cache directory.
pub fn clear() -> Result<(), TealdeerError> {
let path = Self::get_cache_dir()?;
let (path, _) = Self::get_cache_dir()?;
if path.exists() && path.is_dir() {
fs::remove_dir_all(&path).map_err(|_| {
CacheError(format!(

View file

@ -10,6 +10,7 @@ use log::debug;
use serde_derive::{Deserialize, Serialize};
use crate::error::TealdeerError::{self, ConfigError};
use crate::types::PathSource;
pub const CONFIG_FILE_NAME: &str = "config.toml";
pub const MAX_CACHE_AGE: Duration = Duration::from_secs(2_592_000); // 30 days
@ -234,7 +235,7 @@ impl Config {
debug!("Loading config");
// Determine path
let config_file_path = get_config_path()
let (config_file_path, _) = get_config_path()
.map_err(|e| ConfigError(format!("Could not determine config path: {}", e)))?;
// Load raw config
@ -276,16 +277,16 @@ impl Config {
///
/// Note that this function does not verify whether the directory at that
/// location exists, or is a directory.
pub fn get_config_dir() -> Result<PathBuf, TealdeerError> {
pub fn get_config_dir() -> Result<(PathBuf, PathSource), TealdeerError> {
// Allow overriding the config directory by setting the
// $TEALDEER_CONFIG_DIR env variable.
if let Ok(value) = env::var("TEALDEER_CONFIG_DIR") {
return Ok(PathBuf::from(value));
return Ok((PathBuf::from(value), PathSource::EnvVar));
};
// Otherwise, fall back to the user config directory.
match get_app_root(AppDataType::UserConfig, &crate::APP_INFO) {
Ok(dirs) => Ok(dirs),
Ok(dirs) => Ok((dirs, PathSource::OsConvention)),
Err(_) => Err(ConfigError(
"Could not determine the user config directory.".into(),
)),
@ -296,15 +297,15 @@ pub fn get_config_dir() -> Result<PathBuf, TealdeerError> {
///
/// Note that this function does not verify whether the file at that location
/// exists, or is a file.
pub fn get_config_path() -> Result<PathBuf, TealdeerError> {
let config_dir = get_config_dir()?;
pub fn get_config_path() -> Result<(PathBuf, PathSource), TealdeerError> {
let (config_dir, source) = get_config_dir()?;
let config_file_path = config_dir.join(CONFIG_FILE_NAME);
Ok(config_file_path)
Ok((config_file_path, source))
}
/// Create default config file.
pub fn make_default_config() -> Result<PathBuf, TealdeerError> {
let config_dir = get_config_dir()?;
let (config_dir, _) = get_config_dir()?;
// Ensure that config directory exists
if !config_dir.exists() {

View file

@ -42,7 +42,7 @@ mod tokenizer;
mod types;
use crate::cache::Cache;
use crate::config::{get_config_path, make_default_config, Config, MAX_CACHE_AGE};
use crate::config::{get_config_dir, get_config_path, make_default_config, Config, MAX_CACHE_AGE};
use crate::dedup::Dedup;
use crate::error::TealdeerError::{CacheError, ConfigError, UpdateError};
use crate::formatter::print_lines;
@ -61,7 +61,6 @@ const ARCHIVE_URL: &str = "https://github.com/tldr-pages/tldr/archive/master.tar
const PAGER_COMMAND: &str = "less -R";
#[derive(Debug, Deserialize)]
#[allow(clippy::struct_excessive_bools)]
struct Args {
arg_command: Option<Vec<String>>,
flag_help: bool,
@ -73,6 +72,7 @@ struct Args {
flag_clear_cache: bool,
flag_pager: bool,
flag_quiet: bool,
flag_show_paths: bool,
flag_config_path: bool,
flag_seed_config: bool,
flag_markdown: bool,
@ -179,10 +179,10 @@ fn update_cache(cache: &Cache, quietly: bool) {
}
}
/// Show the config path
/// Show the config path (DEPRECATED)
fn show_config_path() {
match get_config_path() {
Ok(config_file_path) => {
Ok((config_file_path, _)) => {
println!("Config path is: {}", config_file_path.to_str().unwrap());
}
Err(ConfigError(msg)) => {
@ -196,6 +196,45 @@ fn show_config_path() {
}
}
/// Show file paths
fn show_paths() {
let config_dir = get_config_dir().map_or_else(
|e| format!("[Error: {}]", e),
|(mut path, source)| {
path.push(""); // Trailing path separator
match path.to_str() {
Some(path) => format!("{} ({})", path, source),
None => "[Invalid]".to_string(),
}
},
);
let config_path = get_config_path().map_or_else(
|e| format!("[Error: {}]", e),
|(path, _)| path.to_str().unwrap_or("[Invalid]").to_string(),
);
let cache_dir = Cache::get_cache_dir().map_or_else(
|e| format!("[Error: {}]", e),
|(mut path, source)| {
path.push(""); // Trailing path separator
match path.to_str() {
Some(path) => format!("{} ({})", path, source),
None => "[Invalid]".to_string(),
}
},
);
let pages_dir = Cache::get_cache_dir()
.map(|(path, _)| path.join("tldr-master"))
.map(|mut path| {
path.push(""); // Trailing path separator
path.to_str().unwrap_or("[Invalid]").to_string()
})
.unwrap_or_else(|e| format!("[Error: {}]", e));
println!("Config dir: {}", config_dir);
println!("Config path: {}", config_path);
println!("Cache dir: {}", cache_dir);
println!("Pages dir: {}", pages_dir);
}
/// Create seed config file and exit
fn create_config_and_exit() {
match make_default_config() {
@ -315,8 +354,12 @@ fn main() {
// Show config file and path, pass through
if args.flag_config_path {
eprintln!("Warning: The --config-path flag is deprecated, use --show-paths instead");
show_config_path();
}
if args.flag_show_paths {
show_paths();
}
// Create a basic config and exit
if args.flag_seed_config {
@ -450,7 +493,8 @@ fn main() {
}
// Some flags can be run without a command.
if !(args.flag_update || args.flag_clear_cache || args.flag_config_path) {
if !(args.flag_update || args.flag_clear_cache || args.flag_config_path || args.flag_show_paths)
{
eprintln!("{}", USAGE);
process::exit(1);
}

View file

@ -1,4 +1,4 @@
//! Types used in the client.
//! Shared types used in tealdeer.
use std::fmt;
@ -101,6 +101,31 @@ impl LineType {
}
}
/// The reason why a certain path (e.g. config path or cache dir) was chosen.
#[derive(Debug, PartialEq)]
pub enum PathSource {
/// OS convention (e.g. XDG on Linux)
OsConvention,
/// Env variable (TEALDEER_*)
EnvVar,
/// Config file variable
ConfigVar,
}
impl fmt::Display for PathSource {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}",
match self {
Self::OsConvention => "OS convention",
Self::EnvVar => "env variable",
Self::ConfigVar => "config file variable",
}
)
}
}
#[cfg(test)]
mod test {
use super::LineType;

View file

@ -16,7 +16,8 @@ Options:
-p --pager Use a pager to page output
-m --markdown Display the raw markdown instead of rendering it
-q --quiet Suppress informational messages
--config-path Show config file path
--show-paths Show file and directory paths used by tealdeer
--config-path Show config file path (deprecated)
--seed-config Create a basic config
--color <when> Control when to use color [always, auto, never] [default: auto]

View file

@ -202,22 +202,39 @@ fn test_setup_seed_config() {
}
#[test]
fn test_show_config_path() {
fn test_show_paths() {
let testenv = TestEnv::new();
testenv
.command()
.args(&["--config-path"])
.args(&["--show-paths"])
.assert()
.success()
.stdout(contains(format!(
"Config path is: {}",
"Config dir: {}",
testenv.config_dir.path().to_str().unwrap(),
)))
.stdout(contains(format!(
"Config path: {}",
testenv
.config_dir
.path()
.join("config.toml")
.to_str()
.unwrap(),
)))
.stdout(contains(format!(
"Cache dir: {}",
testenv.cache_dir.path().to_str().unwrap(),
)))
.stdout(contains(format!(
"Pages dir: {}",
testenv
.cache_dir
.path()
.join("tldr-master")
.to_str()
.unwrap(),
)));
}

View file

@ -23,7 +23,7 @@ _tealdeer() {
"($I -p --pager)"{-p,--pager}"[Use a pager to page output]"
"($I -m --markdown)"{-m,--markdown}"[Display the raw markdown instead of rendering it]"
"($I -q --quiet)"{-q,--quiet}"[Suppress informational messages]"
"($I)--config-path[Show config file path]"
"($I)--show-paths[Show file and directory paths used by tealdeer]"
"($I)--seed-config[Create a basic config]"
"($I)--color[Controls when to use color]:when:((
always