feat(homeserver): support relative storage path in config file

This commit is contained in:
nazeh
2025-01-22 20:33:32 +03:00
parent 130eca3b2d
commit 4ecd587806
3 changed files with 35 additions and 3 deletions

1
.gitignore vendored
View File

@@ -1,2 +1,3 @@
target/
config.toml
storage/

View File

@@ -3,7 +3,9 @@
[database]
# Storage directory Defaults to <System's Data Directory>
# storage = ""
#
# Storage path can be relative or absolute.
storage = "./storage/"
[io]
# The port number to run an HTTP (clear text) server on.

View File

@@ -5,6 +5,7 @@ use pkarr::Keypair;
use serde::{Deserialize, Serialize};
use std::{
fmt::Debug,
fs,
net::{IpAddr, SocketAddr},
path::{Path, PathBuf},
time::Duration,
@@ -104,11 +105,26 @@ impl Config {
/// Load the config from a file.
pub async fn load(path: impl AsRef<Path>) -> Result<Config> {
let s = tokio::fs::read_to_string(path.as_ref())
let config_file_path = path.as_ref();
let s = tokio::fs::read_to_string(config_file_path)
.await
.with_context(|| format!("failed to read {}", path.as_ref().to_string_lossy()))?;
Config::try_from_str(&s)
let mut config = Config::try_from_str(&s)?;
// support relative path.
if config.storage.is_relative() {
config.storage = config_file_path
.parent()
.unwrap_or_else(|| Path::new("."))
.join(config.storage.clone());
}
fs::create_dir_all(&config.storage)?;
config.storage = config.storage.canonicalize()?;
Ok(config)
}
/// Test configurations
@@ -268,6 +284,19 @@ mod tests {
)
}
#[tokio::test]
async fn config_load() {
let crate_dir = std::env::current_dir().unwrap();
let config_file_path = crate_dir.join("./src/config.example.toml");
let canonical_file_path = config_file_path.canonicalize().unwrap();
let config = Config::load(canonical_file_path).await.unwrap();
assert!(config
.storage
.ends_with("pubky-homeserver/src/storage/homeserver"));
}
#[test]
fn config_test() {
let testnet = Testnet::new(3).unwrap();