Compare commits

...

1 Commits

Author SHA1 Message Date
Arthur Petukhovsky
17419b8a62 Add arg to override config in zenith_cli 2022-01-25 14:28:55 +00:00
4 changed files with 59 additions and 14 deletions

View File

@@ -189,20 +189,26 @@ impl LocalEnv {
} }
/// Locate and load config /// Locate and load config
pub fn load_config() -> anyhow::Result<Self> { pub fn load_config(override_config: Option<&str>) -> anyhow::Result<Self> {
let repopath = base_path(); let repopath = base_path();
if !repopath.exists() { let config_path = if let Some(override_config) = override_config {
bail!( PathBuf::from(override_config)
"Zenith config is not found in {}. You need to run 'zenith init' first", } else {
repopath.to_str().unwrap() if !repopath.exists() {
); bail!(
} "Zenith config is not found in {}. You need to run 'zenith init' first",
repopath.to_str().unwrap()
// TODO: check that it looks like a zenith repository );
}
// TODO: check that it looks like a zenith repository
repopath.join("config")
};
// load and parse file // load and parse file
let config = fs::read_to_string(repopath.join("config"))?; let config = fs::read_to_string(config_path)?;
let mut env: LocalEnv = toml::from_str(config.as_str())?; let mut env: LocalEnv = toml::from_str(config.as_str())?;
env.base_data_dir = repopath; env.base_data_dir = repopath;

View File

@@ -21,6 +21,7 @@ types-psycopg2 = "^2.9.6"
boto3 = "^1.20.40" boto3 = "^1.20.40"
boto3-stubs = "^1.20.40" boto3-stubs = "^1.20.40"
moto = {version = "^3.0.0", extras = ["server"]} moto = {version = "^3.0.0", extras = ["server"]}
toml = "^0.10.2"
[tool.poetry.dev-dependencies] [tool.poetry.dev-dependencies]
yapf = "==0.31.0" yapf = "==0.31.0"

View File

@@ -19,6 +19,7 @@ import subprocess
import time import time
import filecmp import filecmp
import tempfile import tempfile
import toml
from contextlib import closing from contextlib import closing
from pathlib import Path from pathlib import Path
@@ -372,7 +373,6 @@ class MockS3Server:
def kill(self): def kill(self):
self.subprocess.kill() self.subprocess.kill()
class ZenithEnvBuilder: class ZenithEnvBuilder:
""" """
Builder object to create a Zenith runtime environment Builder object to create a Zenith runtime environment
@@ -502,6 +502,9 @@ class ZenithEnv:
self.port_distributor = config.port_distributor self.port_distributor = config.port_distributor
self.s3_mock_server = config.s3_mock_server self.s3_mock_server = config.s3_mock_server
# If specified, this config will be passed for all zenith_cli calls
self.override_config: Optional[Dict] = None
self.postgres = PostgresFactory(self) self.postgres = PostgresFactory(self)
self.safekeepers: List[Safekeeper] = [] self.safekeepers: List[Safekeeper] = []
@@ -599,9 +602,22 @@ sync = false # Disable fsyncs to make the tests go faster
assert type(arguments) == list assert type(arguments) == list
if self.override_config is not None:
tmp_config = tempfile.NamedTemporaryFile(mode='w+')
tmp_config.write(toml.dumps(self.override_config))
tmp_config.flush()
log.info('Using overriden config to run next command!')
log.info(f'Config: {toml.dumps(self.override_config)}')
else:
tmp_config = None
bin_zenith = os.path.join(str(zenith_binpath), 'zenith') bin_zenith = os.path.join(str(zenith_binpath), 'zenith')
args = [bin_zenith] + arguments args = [bin_zenith]
if tmp_config is not None:
args += ['--override-config', tmp_config.name]
args += arguments
log.info('Running command "{}"'.format(' '.join(args))) log.info('Running command "{}"'.format(' '.join(args)))
log.info(f'Running in "{self.repo_dir}"') log.info(f'Running in "{self.repo_dir}"')
@@ -637,9 +653,21 @@ sync = false # Disable fsyncs to make the tests go faster
log.info(msg) log.info(msg)
raise Exception(msg) from exc raise Exception(msg) from exc
finally:
if tmp_config is not None:
tmp_config.close()
return res return res
def read_toml_config(self) -> Dict:
"""
Read the config file from the repo directory.
Returns a dictionary of the config file.
"""
with open(os.path.join(str(self.repo_dir), 'config')) as f:
return toml.load(f)
@cached_property @cached_property
def auth_keys(self) -> AuthKeys: def auth_keys(self) -> AuthKeys:
pub = (Path(self.repo_dir) / 'auth_public_key.pem').read_bytes() pub = (Path(self.repo_dir) / 'auth_public_key.pem').read_bytes()

View File

@@ -112,6 +112,13 @@ fn main() -> Result<()> {
let matches = App::new("Zenith CLI") let matches = App::new("Zenith CLI")
.setting(AppSettings::ArgRequiredElseHelp) .setting(AppSettings::ArgRequiredElseHelp)
.version(GIT_VERSION) .version(GIT_VERSION)
.arg(
Arg::with_name("override-config")
.long("override-config")
.takes_value(true)
.help("Override the default configuration file")
.required(false)
)
.subcommand( .subcommand(
SubCommand::with_name("init") SubCommand::with_name("init")
.about("Initialize a new Zenith repository") .about("Initialize a new Zenith repository")
@@ -220,8 +227,11 @@ fn main() -> Result<()> {
let subcmd_result = if sub_name == "init" { let subcmd_result = if sub_name == "init" {
handle_init(sub_args) handle_init(sub_args)
} else { } else {
// all other commands need an existing config // all other commands need an existing config, which is found in base directory,
let env = match LocalEnv::load_config() { // or can be overridden with --override-config
let override_config = matches.value_of("override-config");
let env = match LocalEnv::load_config(override_config) {
Ok(conf) => conf, Ok(conf) => conf,
Err(e) => { Err(e) => {
eprintln!("Error loading config: {}", e); eprintln!("Error loading config: {}", e);