Skip to content

Commit

Permalink
refactor(backend): refactor imports
Browse files Browse the repository at this point in the history
  • Loading branch information
SARDONYX-sard committed Nov 3, 2023
1 parent 77f216b commit b7e0461
Show file tree
Hide file tree
Showing 9 changed files with 86 additions and 93 deletions.
15 changes: 3 additions & 12 deletions dar2oar_cli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use clap::{arg, Parser};
use dar2oar_core::{
convert_dar_to_oar,
fs::{async_closure::AsyncClosure, parallel, ConvertOptions},
read_mapping_table,
get_mapping_table,
};
use std::fs::File;
use std::{path::PathBuf, str::FromStr};
Expand Down Expand Up @@ -51,22 +51,13 @@ pub async fn run_cli(args: Args) -> anyhow::Result<()> {
.with_max_level(Level::from_str(&args.log_level).unwrap_or(Level::ERROR))
.init();

macro_rules! read_table {
($path:expr) => {
match $path {
Some(table_path) => read_mapping_table(table_path).await.ok(),
None => None,
}
};
}

let config = ConvertOptions {
dar_dir: args.src,
oar_dir: args.dist.map(|dist| PathBuf::from(&dist)),
mod_name: args.name.as_deref(),
author: args.author.as_deref(),
section_table: read_table!(args.mapping_file),
section_1person_table: read_table!(args.mapping_1person_file),
section_table: get_mapping_table(args.mapping_file).await,
section_1person_table: get_mapping_table(args.mapping_1person_file).await,
hide_dar: args.hide_dar,
};

Expand Down
11 changes: 11 additions & 0 deletions dar2oar_core/src/fs/mapping_table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,17 @@ use std::collections::HashMap;
use std::path::Path;
use tokio::{fs::File, io::AsyncReadExt};

/// Get mapping table from path
pub async fn get_mapping_table(
mapping_path: Option<impl AsRef<Path>>,
) -> Option<HashMap<String, String>> {
match mapping_path {
Some(table_path) => read_mapping_table(table_path).await.ok(),
None => None,
}
}

/// Try to read mapping table from path
pub async fn read_mapping_table(
table_path: impl AsRef<Path>,
) -> anyhow::Result<HashMap<String, String>> {
Expand Down
56 changes: 2 additions & 54 deletions dar2oar_core/src/fs/mod.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
mod mapping_table;
mod sequential;
mod section_writer;

pub mod async_closure;
pub mod parallel;
pub mod path_changer;

use crate::conditions::{ConditionsConfig, MainConfig};
use crate::error::{ConvertError, Result};
use async_walkdir::WalkDir;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use tokio::fs;
use tokio::io::{self, AsyncReadExt, AsyncWriteExt};
use tokio_stream::StreamExt;
use tracing::trace;

pub use mapping_table::read_mapping_table;
pub use mapping_table::{get_mapping_table, read_mapping_table};
pub use sequential::convert_dar_to_oar;

#[derive(Debug, Default)]
Expand Down Expand Up @@ -56,57 +55,6 @@ pub enum ConvertedReport {
Unhide3rdPerson,
}

async fn read_file<P>(file_path: P) -> io::Result<String>
where
P: AsRef<Path>,
{
let mut file = fs::File::open(file_path).await?;
let mut content = String::new();
file.read_to_string(&mut content).await?;
Ok(content)
}

async fn write_json_to<T>(target_path: impl AsRef<Path>, value: &T) -> Result<()>
where
T: ?Sized + serde::Serialize,
{
let mut config_file = fs::File::create(target_path).await?;
let json = serde_json::to_string_pretty(value)?;
config_file.write_all(json.as_bytes()).await?;
Ok(())
}

async fn write_section_config<P>(oar_dir: P, config_json: ConditionsConfig) -> Result<()>
where
P: AsRef<Path>,
{
write_json_to(oar_dir.as_ref().join("config.json"), &config_json).await
}

/// If it exists, do nothing. (This behavior is intended to facilitate the creation of config files
/// for 1st_person and 3rd_person.)
async fn write_name_space_config<P>(
oar_name_space_path: P,
mod_name: &str,
author: Option<&str>,
) -> Result<()>
where
P: AsRef<Path>,
{
let target_file = oar_name_space_path.as_ref().join("config.json");
if target_file.exists() {
return Ok(());
}

let config_json = MainConfig {
name: mod_name,
author: author.unwrap_or_default(),
..Default::default()
};
fs::create_dir_all(&oar_name_space_path).await?;
write_json_to(target_file, &config_json).await
}

/// # Returns
/// Report which dirs have been shown
///
Expand Down
5 changes: 2 additions & 3 deletions dar2oar_core/src/fs/parallel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@ use crate::condition_parser::parse_dar2oar;
use crate::conditions::ConditionsConfig;
use crate::error::{ConvertError, Result};
use crate::fs::path_changer::parse_dar_path;
use crate::fs::{
read_file, write_name_space_config, write_section_config, ConvertOptions, ConvertedReport,
};
use crate::fs::section_writer::{read_file, write_name_space_config, write_section_config};
use crate::fs::{ConvertOptions, ConvertedReport};
use anyhow::Context as _;
use jwalk::WalkDir;
use std::future::Future;
Expand Down
58 changes: 58 additions & 0 deletions dar2oar_core/src/fs/section_writer.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
use crate::conditions::{ConditionsConfig, MainConfig};
use crate::error::Result;
use std::path::Path;
use tokio::{
fs,
io::{self, AsyncReadExt, AsyncWriteExt},
};

pub(crate) async fn read_file<P>(file_path: P) -> io::Result<String>
where
P: AsRef<Path>,
{
let mut file = fs::File::open(file_path).await?;
let mut content = String::new();
file.read_to_string(&mut content).await?;
Ok(content)
}

async fn write_json_to<T>(target_path: impl AsRef<Path>, value: &T) -> Result<()>
where
T: ?Sized + serde::Serialize,
{
let mut config_file = fs::File::create(target_path).await?;
let json = serde_json::to_string_pretty(value)?;
config_file.write_all(json.as_bytes()).await?;
Ok(())
}

pub(crate) async fn write_section_config<P>(oar_dir: P, config_json: ConditionsConfig) -> Result<()>
where
P: AsRef<Path>,
{
write_json_to(oar_dir.as_ref().join("config.json"), &config_json).await
}

/// If it exists, do nothing. (This behavior is intended to facilitate the creation of config files
/// for 1st_person and 3rd_person.)
pub(crate) async fn write_name_space_config<P>(
oar_name_space_path: P,
mod_name: &str,
author: Option<&str>,
) -> Result<()>
where
P: AsRef<Path>,
{
let target_file = oar_name_space_path.as_ref().join("config.json");
if target_file.exists() {
return Ok(());
}

let config_json = MainConfig {
name: mod_name,
author: author.unwrap_or_default(),
..Default::default()
};
fs::create_dir_all(&oar_name_space_path).await?;
write_json_to(target_file, &config_json).await
}
5 changes: 2 additions & 3 deletions dar2oar_core/src/fs/sequential.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@ use crate::condition_parser::parse_dar2oar;
use crate::conditions::ConditionsConfig;
use crate::error::{ConvertError, Result};
use crate::fs::path_changer::parse_dar_path;
use crate::fs::{
read_file, write_name_space_config, write_section_config, ConvertOptions, ConvertedReport,
};
use crate::fs::section_writer::{read_file, write_name_space_config, write_section_config};
use crate::fs::{ConvertOptions, ConvertedReport};
use async_walkdir::WalkDir;
use core::future::Future;
use std::path::Path;
Expand Down
2 changes: 1 addition & 1 deletion dar2oar_core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ mod values;
pub mod error;
pub mod fs;

pub use crate::fs::{convert_dar_to_oar, read_mapping_table};
pub use crate::fs::{convert_dar_to_oar, get_mapping_table, read_mapping_table};
23 changes: 6 additions & 17 deletions src-tauri/src/convert_option.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use std::{collections::HashMap, path::Path};

use dar2oar_core::{fs::ConvertOptions, read_mapping_table};
use dar2oar_core::{fs::ConvertOptions, get_mapping_table};
use serde::{Deserialize, Serialize};
use std::path::Path;

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
Expand All @@ -10,20 +9,13 @@ pub(crate) struct GuiConverterOptions<'a> {
pub(crate) oar_dir: Option<&'a str>,
pub(crate) mod_name: Option<&'a str>,
pub(crate) mod_author: Option<&'a str>,
pub(crate) mapping_path: Option<String>,
pub(crate) mapping_1person_path: Option<String>,
pub(crate) mapping_path: Option<&'a str>,
pub(crate) mapping_1person_path: Option<&'a str>,
pub(crate) log_level: Option<String>,
pub(crate) run_parallel: Option<bool>,
pub(crate) hide_dar: Option<bool>,
}

async fn try_get_mapping_table(mapping_path: Option<&str>) -> Option<HashMap<String, String>> {
match mapping_path {
Some(table_path) => read_mapping_table(table_path).await.ok(),
None => None,
}
}

#[async_trait::async_trait]
pub(crate) trait AsyncFrom<T> {
async fn async_from(options: T) -> Self;
Expand All @@ -49,16 +41,13 @@ impl<'a> AsyncFrom<GuiConverterOptions<'a>> for ConvertOptions<'a, &'a str> {
false => Some(Path::new(dist).to_path_buf()),
});

let section_table = try_get_mapping_table(mapping_path.as_deref()).await;
let section_1person_table = try_get_mapping_table(mapping_1person_path.as_deref()).await;

Self {
dar_dir,
oar_dir,
mod_name,
author,
section_table,
section_1person_table,
section_table: get_mapping_table(mapping_path).await,
section_1person_table: get_mapping_table(mapping_1person_path).await,
hide_dar: hide_dar.unwrap_or(false),
}
}
Expand Down
4 changes: 1 addition & 3 deletions src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,8 @@ mod convert_option;
mod logging;
mod runner;

use crate::runner::run_tauri;

fn main() -> std::io::Result<()> {
run_tauri().map_err(|err| {
crate::runner::run_tauri().map_err(|err| {
tracing::error!("Error: {}", err);
std::process::exit(1);
})
Expand Down

0 comments on commit b7e0461

Please sign in to comment.