Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inline multiple config files into options sources. #20549

Merged
merged 7 commits into from
Feb 17, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/rust/engine/client/src/client_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ async fn test_client_fingerprint_mismatch() {
None,
true,
false,
None,
)
.unwrap();
let error = pantsd::find_pantsd(&build_root, &options_parser)
Expand Down
2 changes: 1 addition & 1 deletion src/rust/engine/client/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ async fn execute(start: SystemTime) -> Result<i32, String> {
let (env, dropped) = Env::capture_lossy();
let env_items = (&env).into();
let argv = env::args().collect::<Vec<_>>();
let options_parser = OptionParser::new(Args::argv(), env, None, true, false)?;
let options_parser = OptionParser::new(Args::argv(), env, None, true, false, None)?;

let use_pantsd = options_parser.parse_bool(&option_id!("pantsd"), true)?;
if !use_pantsd.value {
Expand Down
4 changes: 2 additions & 2 deletions src/rust/engine/options/src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,10 +143,10 @@ impl OptionsSource for Args {
self.get_list(id, parse_string_list)
}

fn get_dict(&self, id: &OptionId) -> Result<Option<Vec<DictEdit>>, String> {
fn get_dict(&self, id: &OptionId) -> Result<Option<DictEdit>, String> {
match self.find_flag(Self::arg_names(id, Negate::False))? {
Some((name, ref value, _)) => parse_dict(value)
.map(|e| Some(vec![e]))
.map(|e| Some(e))
.map_err(|e| e.render(name)),
None => Ok(None),
}
Expand Down
225 changes: 86 additions & 139 deletions src/rust/engine/options/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
// Licensed under the Apache License, Version 2.0 (see LICENSE).

use std::collections::{HashMap, HashSet};
use std::ffi::OsString;
use std::fs;
use std::path::Path;

Expand Down Expand Up @@ -216,133 +215,16 @@ fn toml_table_to_dict(table: &Value) -> HashMap<String, Val> {
}
}

#[derive(Clone)]
struct ConfigSource {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We get rid of ConfigSource entirely, and fold its functionality directly into Config below, since they are now one-to-one.

#[allow(dead_code)]
path: Option<OsString>,
config: Value,
}

impl ConfigSource {
fn option_name(id: &OptionId) -> String {
id.name("_", NameTransform::None)
}

fn get_value(&self, id: &OptionId) -> Option<&Value> {
self.config
.get(id.scope())
.and_then(|table| table.get(Self::option_name(id)))
}

fn get_list<T: FromValue>(
&self,
id: &OptionId,
parse_list: fn(&str) -> Result<Vec<ListEdit<T>>, ParseError>,
) -> Result<Vec<ListEdit<T>>, String> {
let mut list_edits = vec![];
if let Some(table) = self.config.get(id.scope()) {
let option_name = Self::option_name(id);
if let Some(value) = table.get(&option_name) {
match value {
Value::Table(sub_table) => {
if sub_table.is_empty()
|| !sub_table.keys().collect::<HashSet<_>>().is_subset(
&["add".to_owned(), "remove".to_owned()]
.iter()
.collect::<HashSet<_>>(),
)
{
return Err(format!(
"Expected {option_name} to contain an 'add' element, a 'remove' element or both but found: {sub_table:?}"
));
}
if let Some(add) = sub_table.get("add") {
list_edits.push(ListEdit {
action: ListEditAction::Add,
items: T::extract_list(&format!("{option_name}.add"), add)?,
})
}
if let Some(remove) = sub_table.get("remove") {
list_edits.push(ListEdit {
action: ListEditAction::Remove,
items: T::extract_list(&format!("{option_name}.remove"), remove)?,
})
}
}
Value::String(v) => {
list_edits.extend(parse_list(v).map_err(|e| e.render(option_name))?);
}
value => list_edits.push(ListEdit {
action: ListEditAction::Replace,
items: T::extract_list(&option_name, value)?,
}),
}
}
}
Ok(list_edits)
}

fn get_dict(&self, id: &OptionId) -> Result<Option<DictEdit>, String> {
if let Some(table) = self.config.get(id.scope()) {
let option_name = Self::option_name(id);
if let Some(value) = table.get(&option_name) {
match value {
Value::Table(sub_table) => {
if let Some(add) = sub_table.get("add") {
if sub_table.len() == 1 && add.is_table() {
return Ok(Some(DictEdit {
action: DictEditAction::Add,
items: toml_table_to_dict(add),
}));
}
}
return Ok(Some(DictEdit {
action: DictEditAction::Replace,
items: toml_table_to_dict(value),
}));
}
Value::String(v) => {
return Ok(Some(parse_dict(v).map_err(|e| e.render(option_name))?));
}
_ => {
return Err(format!(
"Expected {option_name} to be a toml table or Python dict, but given {value}."
));
}
}
}
}
Ok(None)
}
}

#[derive(Clone)]
pub(crate) struct Config {
sources: Vec<ConfigSource>,
value: Value,
}

impl Config {
pub(crate) fn parse<P: AsRef<Path>>(
files: &[P],
seed_values: &InterpolationMap,
) -> Result<Config, String> {
let mut sources = vec![];
for file in files {
sources.push(Self::parse_source(file, seed_values)?);
}
Ok(Config { sources })
}

pub(crate) fn merge(self, other: Config) -> Config {
Config {
sources: self.sources.into_iter().chain(other.sources).collect(),
}
}

fn parse_source<P: AsRef<Path>>(
file: P,
seed_values: &InterpolationMap,
) -> Result<ConfigSource, String> {
) -> Result<Config, String> {
let config_contents = fs::read_to_string(&file).map_err(|e| {
format!(
"Failed to read config file {}: {}",
Expand Down Expand Up @@ -419,29 +301,100 @@ impl Config {
};

let new_table = Table::from_iter(new_sections?);
Ok(ConfigSource {
path: Some(file.as_ref().as_os_str().into()),
config: Value::Table(new_table),
Ok(Self {
value: Value::Table(new_table),
})
}

fn option_name(id: &OptionId) -> String {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved from ConfigSource

id.name("_", NameTransform::None)
}

fn get_value(&self, id: &OptionId) -> Option<&Value> {
self.sources
.iter()
.rev()
.find_map(|source| source.get_value(id))
self.value
.get(id.scope())
.and_then(|table| table.get(Self::option_name(id)))
}

fn get_list<T: FromValue>(
&self,
id: &OptionId,
parse_list: fn(&str) -> Result<Vec<ListEdit<T>>, ParseError>,
) -> Result<Option<Vec<ListEdit<T>>>, String> {
let mut edits: Vec<ListEdit<T>> = vec![];
for source in self.sources.iter() {
edits.append(&mut source.get_list(id, parse_list)?);
let mut list_edits = vec![];
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved from ConfigSource

if let Some(table) = self.value.get(id.scope()) {
let option_name = Self::option_name(id);
if let Some(value) = table.get(&option_name) {
match value {
Value::Table(sub_table) => {
if sub_table.is_empty()
|| !sub_table.keys().collect::<HashSet<_>>().is_subset(
&["add".to_owned(), "remove".to_owned()]
.iter()
.collect::<HashSet<_>>(),
)
{
return Err(format!(
"Expected {option_name} to contain an 'add' element, a 'remove' element or both but found: {sub_table:?}"
));
}
if let Some(add) = sub_table.get("add") {
list_edits.push(ListEdit {
action: ListEditAction::Add,
items: T::extract_list(&format!("{option_name}.add"), add)?,
})
}
if let Some(remove) = sub_table.get("remove") {
list_edits.push(ListEdit {
action: ListEditAction::Remove,
items: T::extract_list(&format!("{option_name}.remove"), remove)?,
})
}
}
Value::String(v) => {
list_edits.extend(parse_list(v).map_err(|e| e.render(option_name))?);
}
value => list_edits.push(ListEdit {
action: ListEditAction::Replace,
items: T::extract_list(&option_name, value)?,
}),
}
}
}
Ok(Some(list_edits))
}

fn get_dict(&self, id: &OptionId) -> Result<Option<DictEdit>, String> {
if let Some(table) = self.value.get(id.scope()) {
let option_name = Self::option_name(id);
if let Some(value) = table.get(&option_name) {
match value {
Value::Table(sub_table) => {
if let Some(add) = sub_table.get("add") {
if sub_table.len() == 1 && add.is_table() {
return Ok(Some(DictEdit {
action: DictEditAction::Add,
items: toml_table_to_dict(add),
}));
}
}
return Ok(Some(DictEdit {
action: DictEditAction::Replace,
items: toml_table_to_dict(value),
}));
}
Value::String(v) => {
return Ok(Some(parse_dict(v).map_err(|e| e.render(option_name))?));
}
_ => {
return Err(format!(
"Expected {option_name} to be a toml table or Python dict, but given {value}."
));
}
}
}
}
Ok(Some(edits))
Ok(None)
}
}

Expand Down Expand Up @@ -482,13 +435,7 @@ impl OptionsSource for Config {
self.get_list(id, parse_string_list)
}

fn get_dict(&self, id: &OptionId) -> Result<Option<Vec<DictEdit>>, String> {
let mut edits = vec![];
for source in self.sources.iter() {
if let Some(edit) = source.get_dict(id)? {
edits.push(edit);
}
}
Ok(if edits.is_empty() { None } else { Some(edits) })
fn get_dict(&self, id: &OptionId) -> Result<Option<DictEdit>, String> {
self.get_dict(id)
}
}
Loading
Loading