Skip to content

Commit

Permalink
restructure
Browse files Browse the repository at this point in the history
  • Loading branch information
oneElectron committed Nov 24, 2023
1 parent cb1860e commit fba4dbb
Show file tree
Hide file tree
Showing 7 changed files with 137 additions and 113 deletions.
16 changes: 16 additions & 0 deletions main.tex
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
\documentclass{article}
\usepackage[utf8]{inputenc}

\title{Title}
\author{Author}
\date{September 2022}

\begin{document}

\maketitle

\newpage

\section{Introduction}

\end{document}
38 changes: 22 additions & 16 deletions src/info.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::prelude::*;
use console::style;
use serde::Deserialize;
use std::path::PathBuf;
use std::path::{Path, PathBuf};

#[derive(Deserialize)]
pub struct TemplateInfo {
Expand All @@ -10,6 +10,7 @@ pub struct TemplateInfo {
pub id: Option<i64>,
pub website: Option<String>,
pub author: Option<String>,
pub excluded_files: Option<Vec<String>>,
}

impl std::fmt::Display for TemplateInfo {
Expand All @@ -29,26 +30,31 @@ impl std::fmt::Display for TemplateInfo {
}
}

pub fn template_info(name: String, search_path: Option<PathBuf>, disable_os_search: bool) -> crate::info::TemplateInfo {
let path_to_templates = resolve_template(&name, disable_os_search, &search_path);
impl TemplateInfo {
pub fn from_path(path: &Path) -> Self {
let path = if path.file_name().unwrap().to_string_lossy() == "itex-info.toml" {
path.to_owned()
} else {
path.to_owned().join("itex-info.toml")
};

get_template_info(path_to_templates)
}
let toml_str = std::fs::read_to_string(path);
if toml_str.is_err() {
println!("{}", style("Could not find info for template").red().bold());
exit!(0);
}
let toml_str = toml_str.unwrap();

fn get_template_info(template_path: PathBuf) -> TemplateInfo {
let mut path = template_path.clone();
path.push("itex-info.toml");
let toml_str: Result<TemplateInfo, toml::de::Error> = toml::from_str(toml_str.as_str());

let toml_str = std::fs::read_to_string(path);
if toml_str.is_err() {
println!("{}", style("Could not find info for template").red().bold());
exit!(0);
unwrap_result!(toml_str, "Failed to parse toml")
}
let toml_str = toml_str.unwrap();
}

let data: TemplateInfo = toml::from_str(toml_str.as_str()).unwrap();
pub fn template_info(name: String, search_path: Option<PathBuf>, disable_os_search: bool) -> crate::info::TemplateInfo {
let path_to_templates = resolve_template(&name, disable_os_search, &search_path);

data
TemplateInfo::from_path(&path_to_templates)
}

#[cfg(test)]
Expand All @@ -58,7 +64,7 @@ mod test {

#[test]
fn toml_file() {
let output = get_template_info(PathBuf::from("test_resources/default"));
let output = TemplateInfo::from_path(&PathBuf::from("test_resources/default"));

assert_eq!(output.name, "Default".to_string());
assert_eq!(output.description.unwrap(), "The default template.".to_string());
Expand Down
62 changes: 32 additions & 30 deletions src/init/files.rs
Original file line number Diff line number Diff line change
@@ -1,48 +1,50 @@
use log::trace;
use std::{fs, fs::read_dir, path::Path, path::PathBuf};
use crate::prelude::*;
use std::path::PathBuf;

#[allow(dead_code)]
pub enum CopyFilesExitCode {
SomeFilesExist,
AllFilesExist,
Other,
}

pub fn copy_files(from: PathBuf, to: &Path, dry_run: bool) -> Result<isize, CopyFilesExitCode> {
let template_files = read_dir(from).expect("could not find template folder");
pub fn copy_files(from: PathBuf, dry_run: bool, info: &crate::info::TemplateInfo) -> Result<(), CopyFilesExitCode> {
let template_folder = std::fs::read_dir(from);
let template_folder = unwrap_result!(template_folder, "Could not read from templates folder");

let mut end: bool = false;
let pwd = std::env::current_dir().unwrap();

for file in template_files {
let file = file.unwrap().path();
for file in template_folder {
let file = unwrap_result!(file, "Could not read file");

let pwd = to.to_owned().clone();

if dry_run && pwd.with_file_name(file.file_name().unwrap().to_str().unwrap()).exists() {
println!("file exists: {}", file.file_name().unwrap().to_str().unwrap());
end = true;
if should_ignore_file(file.file_name().to_string_lossy().to_string(), info) {
continue;
}

trace!(
"pwd = {}",
pwd.clone()
.with_file_name(file.clone().file_name().unwrap().to_str().unwrap())
.to_str()
.unwrap()
);

if file.clone().file_name().unwrap().to_str().unwrap() != "itex-info.toml"
&& file.clone().file_name().unwrap().to_str().unwrap() != "Makefile"
&& !dry_run
&& fs::copy(&file, pwd.with_file_name(file.file_name().unwrap().to_str().unwrap())).is_err()
{
println!("Error copying file");
let file_path = pwd.clone().join(file.file_name());

log::trace!("Copying file: {}, is dry run: {}", file.file_name().to_string_lossy(), dry_run);

if dry_run && file_path.exists() {
return Err(CopyFilesExitCode::SomeFilesExist);
} else {
unwrap_result!(std::fs::copy(file.path(), file_path.clone()), "Could not copy file");
}
}

if end {
return Err(CopyFilesExitCode::SomeFilesExist);
Ok(())
}

fn should_ignore_file(filename: String, info: &TemplateInfo) -> bool {
let filename = filename.trim().to_owned();
if &filename == "itex-info.toml" {
return true;
}

if let Some(excluded_files) = info.excluded_files.clone() {
if excluded_files.contains(&filename) {
return true;
}
}

Ok(0)
false
}
67 changes: 9 additions & 58 deletions src/init/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ mod files;

use crate::prelude::*;
use console::style;
use log::trace;
use std::{fs, path::PathBuf, string::String};
use std::path::PathBuf;

const ITEX_BUILD_FILE: &str = r#"tex_filename = "main.tex"
draft_mode = false
Expand All @@ -14,7 +13,7 @@ output_dir = "./out"
pub fn init(name: String, output_path: PathBuf, search_path: Option<PathBuf>, disable_os_search: bool) {
let path_to_templates = resolve_template(&name, disable_os_search, &search_path);

trace!("template path = {}", path_to_templates.to_str().unwrap());
log::trace!("template path = {}", path_to_templates.to_str().unwrap());

if !path_to_templates.is_dir() {
println!("{}", style("Could not find a template with the name provided").red().bold());
Expand All @@ -24,48 +23,35 @@ pub fn init(name: String, output_path: PathBuf, search_path: Option<PathBuf>, di

let path_to_templates = PathBuf::from(path_to_templates.to_str().unwrap().trim());

let template_info = TemplateInfo::from_path(&path_to_templates);

let mut pwd = output_path.clone();

pwd.push("file.txt");

trace!("output dir = {}", pwd.clone().to_str().unwrap());
log::trace!("output dir = {}", pwd.clone().to_str().unwrap());

// dry run: find any files in the current folder that will conflict with the template files
match files::copy_files(path_to_templates.clone(), &pwd, true) {
match files::copy_files(path_to_templates.clone(), true, &template_info) {
Err(files::CopyFilesExitCode::SomeFilesExist) => {
println!("Remove these files before running itex");
exit!(0);
}
Err(files::CopyFilesExitCode::AllFilesExist) => {
println!("All of the files in the template listed exist in this folder already");
println!("All files exist, have you run itex init before?");
exit!(0);
}
_ => {}
}

// copy template to current directory
if files::copy_files(path_to_templates, &pwd, false).is_err() {
println!("Unexpected error")
if files::copy_files(path_to_templates, false, &template_info).is_err() {
println!("Unexpected error");
}

create_build_file(output_path.clone());
}

pub fn list_template_names(search_path: Option<PathBuf>, disable_os_search: bool) {
let template_folder = resolve_templates_folder(disable_os_search, &search_path);

println!("available template names:");
for folder in fs::read_dir(template_folder).unwrap() {
let filename = folder.unwrap().file_name();
let filename = filename.to_string_lossy();

if filename.ends_with(".toml") {
continue;
}
println!(" {}", filename);
}
}

pub fn create_build_file(path: PathBuf) {
let mut path = path;
path.push("itex-build.toml");
Expand All @@ -76,38 +62,3 @@ pub fn create_build_file(path: PathBuf) {
}
}
}

#[cfg(test)]
mod tests {
use std::path::PathBuf;

fn cleanup_folder(path: PathBuf) {
let dir = std::fs::read_dir(path).unwrap();
for file in dir {
if file.as_ref().unwrap().path().file_name().unwrap() == ".gitignore" {
continue;
}
std::fs::remove_file(file.unwrap().path()).unwrap_or_else(|_| {});
}
}

#[test]
fn default_config() {
let mut out_dir = PathBuf::from("test_resources/test_cases/init/default_config/");
assert!(!PathBuf::from("./test_resources/test_cases/init/default_config/main.tex").exists());
cleanup_folder(out_dir.parent().unwrap().to_path_buf());

super::init("default".to_string(), out_dir.clone(), None, true);

out_dir.push("itex-build.toml");
assert!(out_dir.is_file());
assert!(out_dir.with_file_name("main.tex").is_file());
assert!(!out_dir.with_file_name("itex-info.toml").is_file());
cleanup_folder(out_dir.parent().unwrap().to_path_buf());
}

#[test]
fn list_templates() {
super::list_template_names(None, true);
}
}
50 changes: 50 additions & 0 deletions src/list.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
use crate::prelude::*;
use std::path::PathBuf;

pub struct TemplateList {
pub names: Vec<String>,
}

impl std::fmt::Display for TemplateList {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "{}", console::style("Templates available:").green().bright()).unwrap();
for name in &self.names {
writeln!(f, " {}", name).unwrap();
}

std::fmt::Result::Ok(())
}
}

impl TemplateList {
pub fn from_path(search_path: Option<PathBuf>, disable_os_search: bool) -> Self {
let template_folder = resolve_templates_folder(disable_os_search, &search_path);

let mut template_names: Vec<String> = vec![];
for folder in std::fs::read_dir(template_folder).unwrap() {
let filename = folder.unwrap().file_name();
let filename = filename.to_string_lossy();

if filename.ends_with(".toml") {
continue;
}

template_names.push(filename.to_string());
}
TemplateList { names: template_names }
}
}

pub fn list(search_path: Option<PathBuf>, disable_os_search: bool) {
let template_list = TemplateList::from_path(search_path, disable_os_search);

print!("{}", template_list);
}

#[cfg(test)]
mod tests {
#[test]
fn list_templates() {
super::TemplateList::from_path(None, true);
}
}
11 changes: 6 additions & 5 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ mod cli;
mod count;
mod info;
mod init;
mod list;
mod macros;
mod path;
mod prelude;
Expand Down Expand Up @@ -44,7 +45,7 @@ fn main() {
log::trace!("search_path = {:?}", search_path);
log::trace!("disable_os_search = {}", disable_os_search);

init(name, output_path.clone(), search_path, disable_os_search);
init::init(name, output_path.clone(), search_path, disable_os_search);

output_path.push("out");
if !output_path.is_dir() && std::fs::create_dir(output_path).is_err() {
Expand All @@ -55,7 +56,7 @@ fn main() {
cli::Commands::List {
disable_os_search,
search_path,
} => init::list_template_names(search_path, disable_os_search),
} => list::list(search_path, disable_os_search),

cli::Commands::Info {
name,
Expand All @@ -70,7 +71,7 @@ fn main() {
cli::Commands::Build { debug, draft, path } => {
let og_path = path::change_to_itex_path(path);

build(debug, draft, None);
build::build(debug, draft, None);

std::env::set_current_dir(og_path).unwrap();
}
Expand All @@ -87,7 +88,7 @@ fn main() {
cli::Commands::Count { path } => {
let og_path = path::change_to_itex_path(path);

count();
count::count();

let e = std::env::set_current_dir(og_path);
unwrap_result!(e, "Failed to set current directory back");
Expand All @@ -96,7 +97,7 @@ fn main() {
cli::Commands::Clean { path } => {
let og_path = path::change_to_itex_path(path);

clean(std::env::current_dir().unwrap(), &Settings::from_global());
clean::clean(std::env::current_dir().unwrap(), &Settings::from_global());

let e = std::env::set_current_dir(og_path);
unwrap_result!(e, "Failed to set current directory back");
Expand Down
Loading

0 comments on commit fba4dbb

Please sign in to comment.