Skip to content

Commit

Permalink
Merge pull request #1 from creepersaur/init-files-dir
Browse files Browse the repository at this point in the history
Init files dir
  • Loading branch information
creepersaur authored Sep 11, 2024
2 parents 6dd9f46 + 58cc6b5 commit 09cd925
Show file tree
Hide file tree
Showing 7 changed files with 221 additions and 142 deletions.
139 changes: 82 additions & 57 deletions src/filesystem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ use colored::Colorize;
use fs::File;
use serde_json::json;
use std::env;
use std::ffi::OsStr;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use toml::Table;
use unescape::unescape;

use crate::CWD;
use crate::{get::GLOBAL_DATA, ROOT};

#[derive(Debug, Clone, PartialEq)]
Expand Down Expand Up @@ -52,9 +54,7 @@ pub fn get_tree(root: &str) -> Vec<FileTree> {
}

pub fn get_root_files(root: &str) -> Vec<FileTree> {
let cwd = get_cwd();
let cwd_path = PathBuf::from(cwd);
let game = cwd_path.join(root);
let game = CWD.join(root);
get_tree(game.to_str().expect("Failed to get root."))
}

Expand All @@ -76,14 +76,8 @@ pub fn get_files(path: &str) -> Result<Vec<(PathBuf, bool)>, ()> {
Ok(children)
}

pub fn get_cwd() -> String {
let cwd = env::current_dir()
.expect("Failed to get current working directory.")
.to_str()
.expect("Failed to convert cwd to str.")
.to_owned();

cwd
pub fn get_cwd() -> PathBuf {
env::current_dir().expect("Failed to get current working directory.")
}

pub fn write_file(path: String, contents: String, file_type: String) {
Expand Down Expand Up @@ -139,20 +133,7 @@ pub fn write_file(path: String, contents: String, file_type: String) {
));
}

if let Ok(mut new_file) = File::create(&new_file_path) {
new_file
.write_all(contents.as_bytes())
.expect("Failed to write to file.")
} else {
println!(
"{}",
format!(
"{} {}",
"Failed to create file:".red(),
new_file_path.to_str().unwrap().purple()
)
)
}
create_file(&new_file_path, &contents);

let data = match GLOBAL_DATA.lock() {
Ok(guard) => guard,
Expand Down Expand Up @@ -185,45 +166,89 @@ fn alter_tree(x: &mut Vec<FileTree>, new_path: String, contents: String) {
}
}

pub fn write_sourcemap(data: String, game_name: String) {
pub fn write_sourcemap(data: String) {
let sourcemap = format!("{}{data}{}", "{", "}");

if let Ok(mut new_file) = File::create("sourcemap.json") {
new_file
.write_all(sourcemap.as_bytes())
.expect("Failed to write to file.")
} else {
println!(
"{}",
format!(
"{} {}",
"Failed to create file:".red(),
"sourcemap.json".purple()
)
)
}
create_file(
&"sourcemap.json",
&sourcemap
);
}

pub fn write_project(game_name: String) {
let project = format!(
r#"{{
"name": "{game_name}",
"tree": {{
"$className": "DataModel"
}}
}}"#
"name": "{game_name}",
"tree": {{
"$className": "DataModel"
}}
}}"#
);

if let Ok(mut new_file) = File::create("default.project.json") {
new_file
.write_all(project.as_bytes())
.expect("Failed to write to file.")
} else {
create_file(
&"default.project.json",
&project
)
}

pub trait StrPath: AsRef<OsStr> {
fn get_path(&self) -> PathBuf {
PathBuf::from(&self)
}

fn get_bytes(&self) -> &[u8] {
return &[];
}
}

impl StrPath for String {
fn get_bytes(&self) -> &[u8] {
&self.as_bytes()
}
}

impl StrPath for &str {
fn get_bytes(&self) -> &[u8] {
&self.as_bytes()
}
}

impl StrPath for PathBuf {}

pub fn create_file(path: &impl StrPath, content: &impl StrPath) {
let file_path = path.get_path();
let file_name = file_path
.file_name()
.expect("Failed to get file_name: create_file().")
.to_str()
.unwrap();

if let Err(out) = File::create(&file_path)
.expect(format!("Failed to create `{}`.", file_name).as_str())
.write_all(content.get_bytes())
{
println!(
"{}",
format!(
"{} {}",
"Failed to create file:".red(),
"default.project.json".purple()
)
)
"{} Failed to write to: {}.",
"[ERROR]".red(),
format!("`{}`", file_name).purple()
);

println!("{}", out.to_string().dimmed());
}
}

pub fn build_dir(path: impl StrPath) {
let build_path = path.get_path();
let mut builder = fs::DirBuilder::new();
builder.recursive(true);

if let Err(out) = builder.create(&build_path) {
println!(
"{} Failed to build directory: {}.",
"[ERROR]".red(),
format!("`{}`", build_path.display()).purple()
);

println!("{}", out.to_string().dimmed());
}
}
50 changes: 50 additions & 0 deletions src/init.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
use colored::Colorize;

use super::filesystem as fs;

pub fn initialize(args: Vec<String>) {
let mut root = "game";
if args.len() > 2 {
if args[2] == "src" {
root = "src";
}
}

fs::create_file(
&"creeper.toml",
&format!(r#"
# Your root/src directory.
root = "{root}"
# The port to host the sever at.
port = 8080
# Enable two_way_sync on the following (array)
two_way_sync = [
"ServerStorage",
"ServerScriptService"
]
# Should include descendants when syncing back?
two_way_descendants = true
"#,)
);

fs::build_dir(format!("{root}/ServerScriptService/server"));
fs::build_dir(format!("{root}/StarterPlayerScripts/client"));
fs::build_dir(format!("{root}/ReplicatedStorage/shared"));

fs::create_file(
&format!("{root}/ServerScriptService/server/hello.server.luau"),
&r#"print("Hello from CreeperCLI! (server)")"#
);

fs::create_file(
&"sourcemap.json",
&r#"["Will be replaced when the plugin connects."]"#
);

fs::create_file(
&"default.project.json",
&r#"["Will be replaced when the plugin connects."]"#
);

println!("{} 👍", "Successfully initialized CreeperCLI project!".green());
}
71 changes: 13 additions & 58 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,78 +1,33 @@
use colored::Colorize;
use lazy_static::lazy_static;
use std::{env, io::stdin, path::Path, sync::Mutex};
use filesystem::get_cwd;
use server::run_server;
use std::mem::drop;
use colored::Colorize;
use std::{env, path::PathBuf, sync::Mutex};

mod sourcemap;
mod filesystem;
mod get;
mod post;
mod server;
mod settings;
mod update;
mod run_server;
mod init;

lazy_static! {
// pub static ref DIRECTORIES: Mutex<Table> = Mutex::new(Table::new());
pub static ref ROOT: Mutex<String> = Mutex::new("game".to_string());
pub static ref CWD: PathBuf = filesystem::get_cwd();
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
let cwd = get_cwd();

let args: Vec<String> = env::args().collect();
if args.len() > 1 && args[1] == "update" {
update::update_cli().expect("Failed to update CreeperCLI.");
return Ok(())
}

let mut port: u16 = 8080;

if let Ok(settings) = settings::get_settings(&cwd) {
for (name, value) in settings.iter() {
match name.to_lowercase().as_str() {
"port" => port = value.as_integer().unwrap_or(8080) as u16,
"root" => {
let mut data = match ROOT.lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(), // Recover from poisoned mutex
};
*data = value.as_str().unwrap_or("game").to_string();
drop(data);
},
_ => {}
}
if args.len() > 1 {
match args[1].as_str() {
"update" => update::update_cli().expect("Failed to update CreeperCLI."),
"init" => init::initialize(args),
_ => println!("{} Could not find command `{}`.", "[NO_COMMAND]".red(), args[1])
}
} else {
run_server::start().await
}

let root = match ROOT.lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner()
};
let game_dir = format!("{}//{}", &cwd, *root);

let path = Path::new(game_dir.as_str());
if !(path.exists() && path.is_dir()) {
println!(
"{} {} {}",
"YOU MUST HAVE A".red(),
format!("`{}`",root).purple(),
"DIRECTORY IN THE WORKING DIRECTORY.".red()
);
stdin()
.read_line(&mut String::new())
.expect("Failed to read_line.");
return Ok(());
}

drop(root);

println!(
"{} {}",
"Running server at:".bold().green(),
format!("http://localhost:{}", port).purple()
);
Ok(run_server(port).await.expect("Failed to run server!"))
Ok(())
}
18 changes: 9 additions & 9 deletions src/post.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use serde_json::{json, Value};
use std::mem::drop;

use crate::{
filesystem::{self, get_cwd},
filesystem,
get::map_tree,
settings::get_settings,
ROOT,
Expand All @@ -29,14 +29,18 @@ pub async fn post(body: String) -> impl Responder {
};
let files = filesystem::get_root_files(root.as_str());
drop(root);

let game_name = data[2].to_string();
filesystem::write_project(
game_name[1..game_name.len() - 1].to_string()
);

return HttpResponse::Ok()
.append_header((header::CONTENT_TYPE, "application/json"))
.body(map_tree(files));
},
"__SETTINGS__" => {
let cwd = get_cwd();
if let Ok(settings) = get_settings(&cwd) {
if let Ok(settings) = get_settings() {
let json = json!(settings).to_string();

return HttpResponse::Ok().body(json);
Expand All @@ -60,13 +64,9 @@ pub async fn post(body: String) -> impl Responder {
return HttpResponse::Ok().body(r#"{"File added": "SUCCESS"}"#);
},
"__SOURCEMAP__" => {
let data = [
data[1].to_string(),
data[2].to_string()
];
let data = data[1].to_string();
filesystem::write_sourcemap(
data[0][1..data[0].len() - 1].to_string(),
data[1][1..data[1].len() - 1].to_string()
data[1..data.len() - 1].to_string(),
)
}
_ => {}
Expand Down
Loading

0 comments on commit 09cd925

Please sign in to comment.