mirror of
https://github.com/nushell/nushell.git
synced 2025-08-09 03:34:58 +02:00
Merge branch 'master' into build-warnings
# Conflicts: # src/commands/config.rs
This commit is contained in:
@ -1,16 +1,17 @@
|
||||
use crate::prelude::*;
|
||||
|
||||
use crate::commands::WholeStreamCommand;
|
||||
use crate::errors::ShellError;
|
||||
use crate::data::{config, Value};
|
||||
use crate::errors::ShellError;
|
||||
use crate::parser::hir::SyntaxType;
|
||||
use crate::parser::registry::{self};
|
||||
use crate::prelude::*;
|
||||
use std::iter::FromIterator;
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub struct Config;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct ConfigArgs {
|
||||
load: Option<Tagged<PathBuf>>,
|
||||
set: Option<(Tagged<String>, Tagged<Value>)>,
|
||||
get: Option<Tagged<String>>,
|
||||
clear: Tagged<bool>,
|
||||
@ -25,6 +26,7 @@ impl WholeStreamCommand for Config {
|
||||
|
||||
fn signature(&self) -> Signature {
|
||||
Signature::build("config")
|
||||
.named("load", SyntaxType::Path)
|
||||
.named("set", SyntaxType::Any)
|
||||
.named("get", SyntaxType::Any)
|
||||
.named("remove", SyntaxType::Any)
|
||||
@ -47,6 +49,7 @@ impl WholeStreamCommand for Config {
|
||||
|
||||
pub fn config(
|
||||
ConfigArgs {
|
||||
load,
|
||||
set,
|
||||
get,
|
||||
clear,
|
||||
@ -55,7 +58,15 @@ pub fn config(
|
||||
}: ConfigArgs,
|
||||
RunnableContext { name, .. }: RunnableContext,
|
||||
) -> Result<OutputStream, ShellError> {
|
||||
let mut result = crate::data::config::config(name)?;
|
||||
let name_span = name;
|
||||
|
||||
let configuration = if let Some(supplied) = load {
|
||||
Some(supplied.item().clone())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let mut result = crate::data::config::read(name_span, &configuration)?;
|
||||
|
||||
if let Some(v) = get {
|
||||
let key = v.to_string();
|
||||
@ -63,15 +74,27 @@ pub fn config(
|
||||
.get(&key)
|
||||
.ok_or_else(|| ShellError::string(&format!("Missing key {} in config", key)))?;
|
||||
|
||||
return Ok(
|
||||
stream![value.clone()].into(), // futures::stream::once(futures::future::ready(ReturnSuccess::Value(value.clone()))).into(),
|
||||
);
|
||||
let mut results = VecDeque::new();
|
||||
|
||||
match value {
|
||||
Tagged {
|
||||
item: Value::Table(list),
|
||||
..
|
||||
} => {
|
||||
for l in list {
|
||||
results.push_back(ReturnSuccess::value(l.clone()));
|
||||
}
|
||||
}
|
||||
x => results.push_back(ReturnSuccess::value(x.clone())),
|
||||
}
|
||||
|
||||
return Ok(results.to_output_stream());
|
||||
}
|
||||
|
||||
if let Some((key, value)) = set {
|
||||
result.insert(key.to_string(), value.clone());
|
||||
|
||||
config::write_config(&result)?;
|
||||
config::write(&result, &configuration)?;
|
||||
|
||||
return Ok(stream![Tagged::from_simple_spanned_item(
|
||||
Value::Row(result.into()),
|
||||
@ -87,7 +110,7 @@ pub fn config(
|
||||
{
|
||||
result.clear();
|
||||
|
||||
config::write_config(&result)?;
|
||||
config::write(&result, &configuration)?;
|
||||
|
||||
return Ok(stream![Tagged::from_simple_spanned_item(
|
||||
Value::Row(result.into()),
|
||||
@ -101,7 +124,7 @@ pub fn config(
|
||||
tag: Tag { span, .. },
|
||||
} = path
|
||||
{
|
||||
let path = config::config_path()?;
|
||||
let path = config::default_path_for(&configuration)?;
|
||||
|
||||
return Ok(stream![Tagged::from_simple_spanned_item(
|
||||
Value::Primitive(Primitive::Path(path)),
|
||||
@ -115,7 +138,7 @@ pub fn config(
|
||||
|
||||
if result.contains_key(&key) {
|
||||
result.swap_remove(&key);
|
||||
config::write_config(&result)?;
|
||||
config::write(&result, &configuration)?;
|
||||
} else {
|
||||
return Err(ShellError::string(&format!(
|
||||
"{} does not exist in config",
|
||||
|
@ -558,6 +558,7 @@ impl Value {
|
||||
Value::Primitive(Primitive::Decimal(x)) => Ok(format!("{}", x)),
|
||||
Value::Primitive(Primitive::Int(x)) => Ok(format!("{}", x)),
|
||||
Value::Primitive(Primitive::Bytes(x)) => Ok(format!("{}", x)),
|
||||
Value::Primitive(Primitive::Path(x)) => Ok(format!("{}", x.display())),
|
||||
// TODO: this should definitely be more general with better errors
|
||||
other => Err(ShellError::string(format!(
|
||||
"Expected string, got {:?}",
|
||||
|
@ -11,52 +11,60 @@ use std::fs::{self, OpenOptions};
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
const APP_INFO: AppInfo = AppInfo {
|
||||
name: "nu",
|
||||
author: "nu shell developers",
|
||||
};
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
struct Config {
|
||||
#[serde(flatten)]
|
||||
extra: IndexMap<String, Tagged<Value>>,
|
||||
}
|
||||
|
||||
pub(crate) fn config_path() -> Result<PathBuf, ShellError> {
|
||||
let location = app_root(AppDataType::UserConfig, &APP_INFO)
|
||||
.map_err(|err| ShellError::string(&format!("Couldn't open config file:\n{}", err)))?;
|
||||
pub const APP_INFO: AppInfo = AppInfo {
|
||||
name: "nu",
|
||||
author: "nu shell developers",
|
||||
};
|
||||
|
||||
Ok(location.join("config.toml"))
|
||||
pub fn config_path() -> Result<PathBuf, ShellError> {
|
||||
let path = app_root(AppDataType::UserConfig, &APP_INFO)
|
||||
.map_err(|err| ShellError::string(&format!("Couldn't open config path:\n{}", err)))?;
|
||||
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
pub(crate) fn write_config(config: &IndexMap<String, Tagged<Value>>) -> Result<(), ShellError> {
|
||||
let location = app_root(AppDataType::UserConfig, &APP_INFO)
|
||||
.map_err(|err| ShellError::string(&format!("Couldn't open config file:\n{}", err)))?;
|
||||
|
||||
let filename = location.join("config.toml");
|
||||
touch(&filename)?;
|
||||
|
||||
let contents =
|
||||
value_to_toml_value(&Value::Row(Dictionary::new(config.clone())).tagged_unknown())?;
|
||||
|
||||
let contents = toml::to_string(&contents)?;
|
||||
|
||||
fs::write(&filename, &contents)?;
|
||||
|
||||
Ok(())
|
||||
pub fn default_path() -> Result<PathBuf, ShellError> {
|
||||
default_path_for(&None)
|
||||
}
|
||||
|
||||
pub(crate) fn config(span: impl Into<Span>) -> Result<IndexMap<String, Tagged<Value>>, ShellError> {
|
||||
let span = span.into();
|
||||
pub fn default_path_for(file: &Option<PathBuf>) -> Result<PathBuf, ShellError> {
|
||||
let filename = &mut config_path()?;
|
||||
let filename = match file {
|
||||
None => {
|
||||
filename.push("config.toml");
|
||||
filename
|
||||
}
|
||||
Some(file) => {
|
||||
filename.push(file);
|
||||
filename
|
||||
}
|
||||
};
|
||||
|
||||
let location = app_root(AppDataType::UserConfig, &APP_INFO)
|
||||
.map_err(|err| ShellError::string(&format!("Couldn't open config file:\n{}", err)))?;
|
||||
Ok(filename.clone())
|
||||
}
|
||||
|
||||
pub fn read(
|
||||
span: impl Into<Span>,
|
||||
at: &Option<PathBuf>,
|
||||
) -> Result<IndexMap<String, Tagged<Value>>, ShellError> {
|
||||
let filename = default_path()?;
|
||||
|
||||
let filename = match at {
|
||||
None => filename,
|
||||
Some(ref file) => file.clone(),
|
||||
};
|
||||
|
||||
let filename = location.join("config.toml");
|
||||
touch(&filename)?;
|
||||
|
||||
trace!("config file = {}", filename.display());
|
||||
|
||||
let span = span.into();
|
||||
let contents = fs::read_to_string(filename)
|
||||
.map(|v| v.simple_spanned(span))
|
||||
.map_err(|err| ShellError::string(&format!("Couldn't read config file:\n{}", err)))?;
|
||||
@ -75,6 +83,34 @@ pub(crate) fn config(span: impl Into<Span>) -> Result<IndexMap<String, Tagged<Va
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn config(span: impl Into<Span>) -> Result<IndexMap<String, Tagged<Value>>, ShellError> {
|
||||
read(span, &None)
|
||||
}
|
||||
|
||||
pub fn write(
|
||||
config: &IndexMap<String, Tagged<Value>>,
|
||||
at: &Option<PathBuf>,
|
||||
) -> Result<(), ShellError> {
|
||||
let filename = &mut default_path()?;
|
||||
let filename = match at {
|
||||
None => filename,
|
||||
Some(file) => {
|
||||
filename.pop();
|
||||
filename.push(file);
|
||||
filename
|
||||
}
|
||||
};
|
||||
|
||||
let contents =
|
||||
value_to_toml_value(&Value::Row(Dictionary::new(config.clone())).tagged_unknown())?;
|
||||
|
||||
let contents = toml::to_string(&contents)?;
|
||||
|
||||
fs::write(&filename, &contents)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// A simple implementation of `% touch path` (ignores existing files)
|
||||
fn touch(path: &Path) -> io::Result<()> {
|
||||
match OpenOptions::new().create(true).write(true).open(path) {
|
||||
|
@ -16,6 +16,11 @@ pub struct TableView {
|
||||
entries: Vec<Vec<(String, &'static str)>>,
|
||||
}
|
||||
|
||||
enum TableMode {
|
||||
Light,
|
||||
Normal,
|
||||
}
|
||||
|
||||
impl TableView {
|
||||
fn merge_descriptors(values: &[Tagged<Value>]) -> Vec<String> {
|
||||
let mut ret = vec![];
|
||||
@ -198,15 +203,36 @@ impl RenderView for TableView {
|
||||
}
|
||||
|
||||
let mut table = Table::new();
|
||||
table.set_format(
|
||||
FormatBuilder::new()
|
||||
.column_separator('│')
|
||||
.separator(LinePosition::Top, LineSeparator::new('━', '┯', ' ', ' '))
|
||||
.separator(LinePosition::Title, LineSeparator::new('─', '┼', ' ', ' '))
|
||||
.separator(LinePosition::Bottom, LineSeparator::new('━', '┷', ' ', ' '))
|
||||
.padding(1, 1)
|
||||
.build(),
|
||||
);
|
||||
|
||||
let table_mode = crate::data::config::config(Span::unknown())?
|
||||
.get("table_mode")
|
||||
.map(|s| match s.as_string().unwrap().as_ref() {
|
||||
"light" => TableMode::Light,
|
||||
_ => TableMode::Normal,
|
||||
})
|
||||
.unwrap_or(TableMode::Normal);
|
||||
|
||||
match table_mode {
|
||||
TableMode::Light => {
|
||||
table.set_format(
|
||||
FormatBuilder::new()
|
||||
.separator(LinePosition::Title, LineSeparator::new('─', '─', ' ', ' '))
|
||||
.padding(1, 1)
|
||||
.build(),
|
||||
);
|
||||
}
|
||||
_ => {
|
||||
table.set_format(
|
||||
FormatBuilder::new()
|
||||
.column_separator('│')
|
||||
.separator(LinePosition::Top, LineSeparator::new('━', '┯', ' ', ' '))
|
||||
.separator(LinePosition::Title, LineSeparator::new('─', '┼', ' ', ' '))
|
||||
.separator(LinePosition::Bottom, LineSeparator::new('━', '┷', ' ', ' '))
|
||||
.padding(1, 1)
|
||||
.build(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let header: Vec<Cell> = self
|
||||
.headers
|
||||
|
@ -28,6 +28,7 @@ pub use crate::parser::parse::token_tree_builder::TokenTreeBuilder;
|
||||
pub use crate::plugin::{serve_plugin, Plugin};
|
||||
pub use crate::utils::{AbsoluteFile, AbsolutePath, RelativePath};
|
||||
pub use cli::cli;
|
||||
pub use data::config::{APP_INFO, config_path};
|
||||
pub use data::base::{Primitive, Value};
|
||||
pub use data::dict::{Dictionary, TaggedDictBuilder};
|
||||
pub use data::meta::{Span, Tag, Tagged, TaggedItem};
|
||||
|
@ -328,7 +328,7 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut ConfigDeserializer<'de> {
|
||||
let type_name = std::any::type_name::<V::Value>();
|
||||
let tagged_val_name = std::any::type_name::<Tagged<Value>>();
|
||||
|
||||
if name == tagged_val_name {
|
||||
if type_name == tagged_val_name {
|
||||
return visit::<Tagged<Value>, _>(value.val, name, fields, visitor);
|
||||
}
|
||||
|
||||
@ -467,3 +467,27 @@ impl<'a, 'de: 'a> de::SeqAccess<'de> for StructDeserializer<'a, 'de> {
|
||||
return Some(self.fields.len());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::any::type_name;
|
||||
#[test]
|
||||
fn check_type_name_properties() {
|
||||
// This ensures that certain properties for the
|
||||
// std::any::type_name function hold, that
|
||||
// this code relies on. The type_name docs explicitly
|
||||
// mention that the actual format of the output
|
||||
// is unspecified and change is likely.
|
||||
// This test makes sure that such change is detected
|
||||
// by this test failing, and not things silently breaking.
|
||||
// Specifically, we rely on this behaviour further above
|
||||
// in the file to special case Tagged<Value> parsing.
|
||||
let tuple = type_name::<()>();
|
||||
let tagged_tuple = type_name::<Tagged<()>>();
|
||||
let tagged_value = type_name::<Tagged<Value>>();
|
||||
assert!(tuple != tagged_tuple);
|
||||
assert!(tuple != tagged_value);
|
||||
assert!(tagged_tuple != tagged_value);
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user