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

refactor(providers): improve cable provider files loading sequence #254

Merged
merged 1 commit into from
Jan 8, 2025
Merged
Changes from all commits
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
49 changes: 32 additions & 17 deletions crates/television/cable.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
use std::path::PathBuf;

use rustc_hash::FxHashMap;

use color_eyre::Result;
use television_channels::cable::{CableChannelPrototype, CableChannels};
use tracing::debug;
use tracing::{debug, error};

use crate::config::get_config_dir;

Expand Down Expand Up @@ -45,30 +47,43 @@ pub fn load_cable_channels() -> Result<CableChannels> {
let files = std::fs::read_dir(&config_dir)?;

// filter the files that match the pattern
let file_paths = files
let mut file_paths: Vec<PathBuf> = files
.filter_map(|f| f.ok().map(|f| f.path()))
.filter(|p| is_cable_file_format(p) && p.is_file());

let user_defined_prototypes = file_paths.fold(Vec::new(), |mut acc, p| {
let r: ChannelPrototypes = toml::from_str(
&std::fs::read_to_string(p)
.expect("Unable to read configuration file"),
)
.unwrap_or_default();
acc.extend(r.prototypes);
acc
});

// If no user defined prototypes are found, write the default prototypes for the current
.filter(|p| is_cable_file_format(p) && p.is_file())
.collect();

debug!("Found cable channel files: {:?}", file_paths);

// If no cable provider files are found, write the default provider for the current
// platform to the config directory
if user_defined_prototypes.is_empty() {
if file_paths.is_empty() {
debug!("No user defined cable channels found");
// write the default cable channels to the config directory
let default_channels_path =
config_dir.join(DEFAULT_CABLE_CHANNELS_FILE_NAME);
std::fs::write(default_channels_path, DEFAULT_CABLE_CHANNELS)?;
std::fs::write(&default_channels_path, DEFAULT_CABLE_CHANNELS)?;
file_paths.push(default_channels_path);
}

let user_defined_prototypes = file_paths.iter().fold(
Vec::<CableChannelPrototype>::new(),
|mut acc, p| {
match toml::from_str::<ChannelPrototypes>(
&std::fs::read_to_string(p)
.expect("Unable to read configuration file"),
) {
Ok(prototypes) => acc.extend(prototypes.prototypes),
Err(e) => {
error!(
"Failed to parse cable channel file {:?}: {}",
p, e
);
}
}
acc
},
);

debug!("Loaded cable channels: {:?}", user_defined_prototypes);

let mut cable_channels = FxHashMap::default();
Expand Down
Loading