Skip to content

Commit

Permalink
renaming
Browse files Browse the repository at this point in the history
  • Loading branch information
eatenpancreas committed Jul 2, 2024
1 parent 46bef10 commit b8cc3ab
Show file tree
Hide file tree
Showing 18 changed files with 345 additions and 106 deletions.
2 changes: 1 addition & 1 deletion mkprov/commands/area.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ pub struct CmdArgs {

pub fn run(args: CmdArgs) {
let cfg = Config::current();
let mut file = PdxFile::pull(&cfg, "map/", &"area.txt");
let mut file = PdxFile::pull(&cfg, "map/", &"area.txt").unwrap();

let mut areas = file.contents.get_child_objects_mut();

Expand Down
2 changes: 1 addition & 1 deletion mkprov/commands/copy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ pub struct CmdArgs {
pub fn run(args: CmdArgs) {
let cfg = Config::current();
let from = PdxFile::inspect(&cfg, "history/provinces/", &Id(args.from_id)).unwrap();
let mut file = PdxFile::pull(&cfg, "history/provinces/", &Id(args.to_id));
let mut file = PdxFile::pull(&cfg, "history/provinces/", &Id(args.to_id)).unwrap();

file.contents = from;

Expand Down
2 changes: 1 addition & 1 deletion mkprov/commands/own.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ pub struct CmdArgs {

pub fn run(args: CmdArgs) {
let cfg = Config::current();
let mut file = PdxFile::pull(&cfg, "history/provinces/", &Id(args.id));
let mut file = PdxFile::pull(&cfg, "history/provinces/", &Id(args.id)).unwrap();

let tag = args.tag.to_uppercase();

Expand Down
44 changes: 43 additions & 1 deletion mkprov/commands/rename.rs
Original file line number Diff line number Diff line change
@@ -1 +1,43 @@
//TODO
//TODO


use clap::Args;
use paradox_file::{Config, PdxFile, YmlFile};
use crate::common::Id;

#[derive(Debug, Args)]
pub struct CmdArgs {
/// province ID
#[arg(short, long)]
id: u16,

/// Rename province to
#[arg(short, long)]
to: String,

// rename capital to
#[arg(short, long)]
capital: Option<String>,

// priority(?) of province localisation
#[arg(short, long)]
priority: Option<u8>
}

pub fn run(args: CmdArgs) {
let cfg = Config::current();
let mut yml = YmlFile::load_localisation(&cfg).unwrap();
yml.replace_or_add_key_name(args.id, args.to.clone(), args.priority);

let mut file = PdxFile::pull(&cfg, "history/provinces/", &Id(args.id)).unwrap();

if let Some(capital) = args.capital {
if !file.contents.mutate_kv("capital",
|kv| kv.set_value(capital.clone())) {
file.contents.insert_kv(0,"capital", capital.clone())
}
}

file.rename_prov_name(args.id, args.to).unwrap();
file.save();
}
23 changes: 10 additions & 13 deletions mkprov/common/files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,19 @@ use paradox_file::{AsFilename};
pub struct Id(pub u16);

impl AsFilename for Id {
fn as_filename(&self, dir: &PathBuf) -> Option<String> {
if let Some(Ok(entry)) = find_id(dir, self.0) {
let os = entry.file_name();
os.to_str().and_then(|x| Some(x.to_string()))
} else {
None
fn as_filename(&self, dir: &PathBuf) -> io::Result<String> {
let entry = find_id(dir, self.0)?;
let os = entry.file_name();
match os.to_str() {
Some(osstr) => Ok(osstr.to_string()),
None => Err(io::Error::new(io::ErrorKind::Unsupported,
"Could not parse filename"))
}
}
}

fn find_id(dir: &PathBuf, id: u16) -> Option<io::Result<DirEntry>> {
let read = fs::read_dir(dir);
if read.is_err() {
return None;
}
let mut read = read.unwrap();
fn find_id(dir: &PathBuf, id: u16) -> io::Result<DirEntry> {
let mut read = fs::read_dir(dir)?;
let id = format!("{id} -");

read.find(|dir_entry| {
Expand All @@ -35,5 +32,5 @@ fn find_id(dir: &PathBuf, id: u16) -> Option<io::Result<DirEntry>> {
} else {
false
}
})
}).unwrap_or(Err(io::Error::new(io::ErrorKind::NotFound, "Could not find Id")))
}
34 changes: 19 additions & 15 deletions mkprov/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,11 @@ mod commands {
pub mod copy;
pub mod area;
pub mod safe_make_provs;
pub mod rename;
}

use crate::commands::{area, config, copy, definition_list, list, own, safe_make_provs};
use clap::{Parser, Subcommand};
use commands as cmd;

/// Simple program to make a list of provinces
#[derive(Parser, Debug)]
Expand All @@ -24,29 +25,32 @@ struct Args {
#[derive(Debug, Subcommand)]
enum Command {
/// Makes a list of non-owned, basic provinces in MOD/history/provinces.
SafeMakeProvs(safe_make_provs::CmdArgs),
SafeMakeProvs(cmd::safe_make_provs::CmdArgs),
/// Makes a simple list province id's for use in area.txt, default.map, etc.
List(list::CmdArgs),
List(cmd::list::CmdArgs),
/// Makes a list of provinces for use in definition.csv, picking random colors and iterating through them.
DefinitionList(definition_list::CmdArgs),
DefinitionList(cmd::definition_list::CmdArgs),
/// Converts a province to an owner tag.
Own(own::CmdArgs),
Own(cmd::own::CmdArgs),
/// Changes project configs.
Config(config::CmdArgs),
Config(cmd::config::CmdArgs),
/// Copies a province defines to another
Copy(copy::CmdArgs),
Copy(cmd::copy::CmdArgs),
/// Gets the area from one province and puts it in the other
Area(area::CmdArgs),
Area(cmd::area::CmdArgs),
/// Renames a province
Rename(cmd::rename::CmdArgs),
}

fn main() {
match Args::parse().command {
Command::SafeMakeProvs(args) => safe_make_provs::run(args),
Command::List(args) => list::run(args),
Command::DefinitionList(args) => definition_list::run(args),
Command::Own(args) => own::run(args),
Command::Config(args) => config::run(args),
Command::Copy(args) => copy::run(args),
Command::Area(args) => area::run(args),
Command::SafeMakeProvs(args) => cmd::safe_make_provs::run(args),
Command::List(args) => cmd::list::run(args),
Command::DefinitionList(args) => cmd::definition_list::run(args),
Command::Own(args) => cmd::own::run(args),
Command::Config(args) => cmd::config::run(args),
Command::Copy(args) => cmd::copy::run(args),
Command::Area(args) => cmd::area::run(args),
Command::Rename(args) => cmd::rename::run(args),
};
}
5 changes: 4 additions & 1 deletion paradox_file/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,7 @@ thiserror = "1.0.61"
clap = { version = "4.5.4", features = ["derive"] }
rand = "0.9.0-alpha.1"
serde = { version = "1.0.203", features = ["derive"] }
toml = "0.8.14"
toml = "0.8.14"
encoding_rs_io = "0.1.7"
encoding_rs = "0.8.34"
codepage = "0.1.1"
4 changes: 2 additions & 2 deletions paradox_file/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ pub struct Config {

impl Config {
pub fn current() -> Config {
let pbuf = current_config_file();
let path = pbuf.as_path();
let p_buf = current_config_file();
let path = p_buf.as_path();
if let Ok(true) = path.try_exists() {
let file = String::from_utf8(fs::read(path).unwrap()).unwrap();
toml::from_str(file.as_str()).unwrap()
Expand Down
30 changes: 30 additions & 0 deletions paradox_file/files/as_filename.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
use std::fmt::{Debug, Display};
use std::io;
use std::path::PathBuf;

pub trait AsFilename: Debug {
fn as_filename(&self, dir: &PathBuf) -> io::Result<String>;
}

impl AsFilename for &str {
fn as_filename(&self, dir: &PathBuf) -> io::Result<String> {
as_filename_inner(self, dir)
}
}

#[derive(Debug)]
pub(crate) struct Filename(pub(crate) String);

impl AsFilename for Filename {
fn as_filename(&self, dir: &PathBuf) -> io::Result<String> {
as_filename_inner(&self.0, dir)
}
}

fn as_filename_inner<T: Display>(from: &T, dir: &PathBuf) -> io::Result<String> {
match dir.to_str() {
None => Err(io::Error::new(io::ErrorKind::Unsupported,
"Could not parse filename")),
Some(dir) => Ok(format!("{dir}/{from}"))
}
}
83 changes: 51 additions & 32 deletions paradox_file/files/mod.rs
Original file line number Diff line number Diff line change
@@ -1,57 +1,76 @@
mod pdx;
mod yml;
mod as_filename;

pub use pdx::*;
use std::fmt::Debug;
use std::fs;
pub use as_filename::*;
pub use yml::*;

use std::fmt::{Debug, Display};
use std::{fs, io};
use std::ffi::OsStr;
use std::io::{ErrorKind, Read};
use std::path::PathBuf;

pub trait AsFilename: Debug {
fn as_filename(&self, dir: &PathBuf) -> Option<String>;
}

impl AsFilename for &str {
fn as_filename(&self, dir: &PathBuf) -> Option<String> {
Some(format!("{}/{self}", dir.to_str()?))
}
pub(crate) struct LocalFile {
path: PathBuf
}

#[derive(Debug)]
pub(crate) struct Filename(String);

impl AsFilename for Filename {
fn as_filename(&self, dir: &PathBuf) -> Option<String> {
Some(format!("{}/{}", dir.to_str()?, self.0))
impl LocalFile {
pub(crate) fn get_filename<T: AsFilename>(
base_path: &str, sub_directory: &str, filename: &T
) -> io::Result<Filename> {
Ok(Filename(Self::get_name_inner(&mut PathBuf::from(base_path), sub_directory, filename)?))
}
}

pub(crate) struct LocalFile {
path: String
}
pub(crate) fn convert_name(&mut self, convert_name: impl Fn(&OsStr) -> String) -> io::Result<()> {
let prev = self.path.clone();

impl LocalFile {
pub(crate) fn get_filename<T: AsFilename>(base_path: &str, sub_directory: &str, filename: &T) -> Option<Filename> {
Self::get_name_inner(&mut PathBuf::from(base_path), sub_directory, filename)
.and_then(|f| Some(Filename(f)))
let filename = self.path.file_name().ok_or(
io::Error::new(ErrorKind::InvalidData, "Filename could not be read")
)?;
self.path.pop();
self.path.push(convert_name(filename));

fs::rename(prev, &self.path)
}

fn get_name_inner<T: AsFilename>(path: &mut PathBuf, sub_directory: &str, filename: &T) -> Option<String> {
fn get_name_inner<T: AsFilename>(
path: &mut PathBuf, sub_directory: &str, filename: &T
) -> io::Result<String> {
path.push(sub_directory);

filename.as_filename(&path)
}

pub(crate) fn get_file<T: AsFilename>(base_path: &str, sub_directory: &str, filename: &T) -> Option<LocalFile> {
let mut pb = &mut PathBuf::from(base_path);
pub(crate) fn get_file<T: AsFilename>(
base_path: &str, sub_directory: &str, filename: &T
) -> io::Result<LocalFile> {
let mut pb = PathBuf::from(base_path);
let name = Self::get_name_inner(&mut pb, sub_directory, filename)?;

pb.push(name);
Some(LocalFile {
path: pb.to_str()?.to_string()
pb.push(&name);

Ok(LocalFile {
path: pb
})
}

pub fn get_contents(&self) -> Option<String> {
Some(String::from_utf8(fs::read(&self.path).unwrap()).unwrap())
pub fn get_contents(&self) -> io::Result<String> {
let reads = fs::read(&self.path)?;
match String::from_utf8(reads.clone()) {
Ok(o) => Ok(o),
Err(_) => {
// utf8 didn't work. string is probably in ANSI

if let Some(encoding) = codepage::to_encoding(850) {
let (str, _, ok) = encoding.decode(reads.as_slice());
if ok { return Ok(str.to_string()) }
}

Err(io::Error::new(ErrorKind::Unsupported, "File was not encoded in utf8 or ANSI"))
}
}
}

pub fn write_contents(&self, contents: &String) -> bool {
Expand Down
Loading

0 comments on commit b8cc3ab

Please sign in to comment.