Save default server URL in the config directory

This commit is contained in:
Marcin Kulik
2023-12-28 15:39:25 +01:00
parent 024500254d
commit 52e7bfe067
2 changed files with 27 additions and 12 deletions

View File

@@ -1,6 +1,7 @@
use anyhow::{anyhow, Result};
use serde::Deserialize;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
#[derive(Debug, Deserialize)]
@@ -54,8 +55,6 @@ pub struct Play {
impl Config {
pub fn new(server_url: Option<String>) -> Result<Self> {
let user_config_file = home()?.join("config.toml");
let mut config = config::Config::builder()
.set_default("server.url", None::<Option<String>>)?
.set_default("api.url", None::<Option<String>>)?
@@ -67,7 +66,10 @@ impl Config {
.set_default("cmd.play.step_key", ".")?
.set_default("cmd.play.next_marker_key", "]")?
.add_source(
config::File::with_name(&user_config_file.to_string_lossy()).required(false),
config::File::with_name(&user_defaults_path()?.to_string_lossy()).required(false),
)
.add_source(
config::File::with_name(&user_config_path()?.to_string_lossy()).required(false),
)
.add_source(config::Environment::with_prefix("asciinema").separator("_"));
@@ -83,6 +85,18 @@ impl Config {
}
}
pub fn save_default_server_url(url: &str) -> Result<()> {
let path = user_defaults_path()?;
if let Some(dir) = path.parent() {
fs::create_dir_all(dir)?;
}
fs::write(path, format!("[server]\nurl = \"{url}\"\n"))?;
Ok(())
}
pub fn home() -> Result<PathBuf> {
env::var("ASCIINEMA_CONFIG_HOME")
.map(PathBuf::from)
@@ -90,3 +104,11 @@ pub fn home() -> Result<PathBuf> {
.or(env::var("HOME").map(|home| Path::new(&home).join(".config").join("asciinema")))
.map_err(|_| anyhow!("need $HOME or $XDG_CONFIG_HOME or $ASCIINEMA_CONFIG_HOME"))
}
fn user_config_path() -> Result<PathBuf> {
Ok(home()?.join("config.toml"))
}
fn user_defaults_path() -> Result<PathBuf> {
Ok(home()?.join("defaults.toml"))
}

View File

@@ -5,7 +5,6 @@ use std::{env, fs, io::ErrorKind, path::Path, path::PathBuf};
use uuid::Uuid;
const DEFAULT_SERVER_URL: &str = "https://asciinema.org";
const DEFAULT_SERVER_URL_FILENAME: &str = "default-server-url";
const INSTALL_ID_FILENAME: &str = "install-id";
pub fn get_install_id() -> Result<String> {
@@ -46,18 +45,12 @@ fn read_legacy_install_id() -> Result<Option<String>> {
}
pub fn get_server_url(server_url: Option<&String>) -> Result<Url> {
let mut url = server_url.cloned();
if url.is_none() {
url = read_state_file(DEFAULT_SERVER_URL_FILENAME)?;
}
match url {
match server_url {
Some(url) => Ok(Url::parse(&url)?),
None => {
let url = Url::parse(&ask_for_server_url()?)?;
write_state_file(DEFAULT_SERVER_URL_FILENAME, url.as_ref())?;
config::save_default_server_url(url.as_ref())?;
Ok(url)
}