Skip to content

Commit

Permalink
feat: stora förändringar, och liten cli
Browse files Browse the repository at this point in the history
  • Loading branch information
vincent-thomas committed Sep 18, 2023
1 parent 04543e9 commit 90a9217
Show file tree
Hide file tree
Showing 24 changed files with 319 additions and 164 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "clier"
version = "0.3.3"
version = "0.4.0"
edition = "2021"
authors = ["Vincent Thomas"]
description = "A cli parser and framework for rust"
Expand All @@ -15,4 +15,4 @@ serde_json = "1.0.106"
thiserror = "1.0.48"

[dev-dependencies]
cargo-watch = "8.4.1"
cargo-watch = "8.4.1"
3 changes: 3 additions & 0 deletions clier.config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"command_dir": "./src/app/commands"
}
24 changes: 6 additions & 18 deletions doc/demo_output.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,10 @@ Argv {
"command",
"subcommand",
],
flags: [
(
"test",
"value",
),
(
"production",
"false",
),
(
"help",
"true",
),
(
"try-me",
"false",
),
],
flags: {
"test": "value",
"production": "false",
"help": "true",
"try-me": "false",
},
}
4 changes: 2 additions & 2 deletions examples/parser.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use clier::Clier;

fn main() {
let cli = Clier::parse().args;
println!("{:#?}", cli);
let args = Clier::parse().args;
println!("{:#?}", args);
}
2 changes: 1 addition & 1 deletion examples/simple.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ fn main() -> ExitCode {
};
let clier = Clier::parse();

let exit_code = clier.meta(meta).add_command(test_command()).run();
let exit_code = clier.meta(&meta).add_command(test_command()).run();
exit_code.unwrap()
}

Expand Down
3 changes: 1 addition & 2 deletions rustfmt.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,4 @@ merge_imports = false
use_small_heuristics = "Max"
tab_spaces = 2
trailing_comma = "Never"
imports_granularity = "Crate"
group_imports = "One"
imports_granularity = "Module"
26 changes: 0 additions & 26 deletions src/_main.rs

This file was deleted.

58 changes: 49 additions & 9 deletions src/app/commands/generate.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,54 @@
use std::fs;
use std::io::ErrorKind;

use clier::command::{CmdArgs, Command};
use clier::hooks::Flag;
use clier::hooks::{use_flag, use_flags, Flag};

use crate::app::generators::{get_config, CommandGenerator};

pub fn generate_command() -> Command {
Command::new("generate", "Generates parts of program", command)
.usage("generate [--flags=value]")
.flags(vec![Flag::new("test", "testing".to_string())])
Command::new("generate", "Generates parts of program", command)
.usage("generate [--flags=value]")
.flags(vec![Flag::new("type", "type of thing to generate".to_string()).short('t')])
}
fn command(_args: CmdArgs) -> i32 {
// let flags = use_flags(&args);
// let result = CommandGenerator::generate();
// println!("{:?}", flags);
0

fn command(args: CmdArgs) -> i32 {
let flags = use_flags(&args);
let t = flags.get("type").unwrap().clone();

if t.as_str() == "command" {
let config = get_config();

if let Err(err) = fs::create_dir(&config.command_dir) {
if err.kind() != ErrorKind::AlreadyExists {
println!("Unknown error: {}", err.kind());
std::process::exit(1);
}
}

let command_name = match use_flag("name", Some('n'), &args.args.flags).value {
Some(value) => value,
None => {
eprintln!("flag name, is required");
std::process::exit(1);
}
};
let description =
use_flag("desc", Some('d'), &args.args.flags).value.unwrap_or("todo...".to_string());
let file_writing = CommandGenerator::generate(config.clone(), &command_name, description);

match file_writing {
Ok(_) => {
println!(
"command {} written at {}/{}.rs",
command_name, &config.command_dir, &command_name
);
println!("Note: This tool doesn't add the command to the main.rs file, coming soon...");
}
Err(err) => println!("Unknown Error: {}", err),
}
} else if t.as_str() == "flag" {
println!("Generating flags");
};
0
}
1 change: 1 addition & 0 deletions src/app/commands/mod.rs
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
pub mod generate;
pub mod new;
22 changes: 22 additions & 0 deletions src/app/commands/new.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
use clier::{
command::{CmdArgs, Command},
hooks::{use_flags, Flag},
};

use crate::app::generators::ProjectGenerator;

const NAME: &str = "new";
const DESCRIPTION: &str = "todo...";

pub fn new_command() -> Command {
Command::new(NAME, DESCRIPTION, command).flags(vec![
Flag::new("name", "Name of the project".to_string()).short('n'),
Flag::new("desc", "Description".to_string()).short('d'),
])
}

fn command(args: CmdArgs) -> i32 {
let flags = use_flags(&args);
ProjectGenerator::generate(flags.get("name").unwrap(), flags.get("desc").unwrap());
0
}
52 changes: 32 additions & 20 deletions src/app/generators/command.rs
Original file line number Diff line number Diff line change
@@ -1,27 +1,39 @@
use super::Generator;
use serde::{Deserialize, Serialize};
use std::io::prelude::*;
use super::Config;
use std::{fs::File, io::Write};

pub struct CommandGenerator;

#[derive(Serialize, Deserialize, Debug, Clone)]
struct Config {
command_dir: Box<str>,
}
impl CommandGenerator {
pub fn generate(
config: Config,
name: impl Into<String>,
description: impl Into<String>,
) -> Result<(), std::io::Error> {
let name = name.into();
let description = description.into();

let file_path = format!("{}/{}.rs", &config.command_dir, name);
let mut file = File::create(file_path).unwrap();
let file_writing = file.write_all(
format!(
"use clier::command::{{CmdArgs, Command}};
const NAME: &'static str = \"{name}\";
const DESCRIPTION: &'static str = \"{description}\";
impl Generator for CommandGenerator {
fn generate() -> Result<(), ()> {
let path = CommandGenerator::find_path().unwrap();
let mut config = String::from("");
let _ = std::fs::File::open(path)
.unwrap()
.read_to_string(&mut config)
.expect("Could not read file");
pub fn {name}_command() -> Command {{
Command::new(NAME, DESCRIPTION, command)
}}
let config: Config = serde_json::from_str(&config).unwrap();
let dir = config.clone().command_dir;
fn command(args: CmdArgs) -> i32 {{
println!(\"Hello World\");
0
}}
",
)
.as_bytes(),
);

println!("{dir}");
Ok(())
}
file_writing
}
}
64 changes: 34 additions & 30 deletions src/app/generators/mod.rs
Original file line number Diff line number Diff line change
@@ -1,37 +1,41 @@
pub mod command;
use std::{
fs::{read_dir, DirEntry, File},
io::BufReader,
path::Path,
};

use std::{env::current_dir, path::PathBuf};
use serde::{Deserialize, Serialize};
mod command;
pub use command::*;
mod project;
pub use project::*;

pub trait Generator {
fn generate() -> Result<(), ()>;
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Config {
pub command_dir: String,
}

fn find_path() -> Result<PathBuf, ()> {
let path = current_dir().unwrap();
let mut item: Option<PathBuf> = None;
path.ancestors().for_each(|v| {
for dir in v.read_dir().into_iter() {
for file in dir.into_iter().flatten() {
if file.file_name() == "clier.config.json" {
item = Some(file.path());
}
}
}
});
pub fn get_config() -> Config {
let dir = read_dir(".").unwrap();
let mut config_file: Option<DirEntry> = None;

let mut right = false;
for i in dir {
if config_file.is_some() {
break;
}
let i = i.unwrap();
if i.file_name() == "clier.config.json" {
config_file = Some(i);
}
}

for i in
item.clone().into_iter().next().unwrap().parent().unwrap().read_dir().unwrap().flatten()
{
if i.file_name() == "Cargo.toml" {
right = true;
}
}
let Some(file_config) = config_file else {
eprintln!("clier.config.json could not be found");
std::process::exit(1);
};

if right {
item.ok_or(())
} else {
Err(())
}
}
let file = File::open(Path::new(&file_config.path())).unwrap();
let reader = BufReader::new(file);

serde_json::from_reader(reader).unwrap()
}
41 changes: 41 additions & 0 deletions src/app/generators/project.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
use std::fs::{create_dir, File};
use std::io::Write;
use std::path::Path;

pub struct ProjectGenerator;

const PKG_VERSION: &str = env!("CARGO_PKG_VERSION");

impl ProjectGenerator {
pub fn generate(name: impl Into<String>, description: impl Into<String>) {
let name = name.into();
let description = description.into();
let path = Path::new(&name);

if !path.exists() {
let _ = create_dir(path);
}

let _ = create_dir(path.join("src"));

let _ = File::create(path.join("Cargo.toml")).unwrap().write_all(
format!(
"
[package]
name = \"{name}\"
version = \"0.0.1\"
edition = \"2021\"
description = \"{description}\"
[dependencies]
clier = \"{PKG_VERSION}\"
",
)
.as_bytes(),
);

let _ = File::create(path.join("src/main.rs"))
.unwrap()
.write_all(include_bytes!("../../../examples/parser.rs"));
}
}
Loading

0 comments on commit 90a9217

Please sign in to comment.