Skip to content

Commit

Permalink
Add benchmark plugin and update various configurations
Browse files Browse the repository at this point in the history
- Introduced .gitignore for benchmark plugin to exclude target and node_modules.
- Created Cargo.toml for benchmark plugin with necessary dependencies.
- Updated .cargo/config.toml to comment out RUST_BACKTRACE.
- Removed unused fontawesome module from extensions.
- Modified template.yaml to include git_repo in post-processing.
- Updated CLI commands for starting the server.
- Enhanced error handling in various extensions by including location information.
- Added new constants for template and HTML file names in consts.rs.
- Updated README with new server command usage.
  • Loading branch information
erhanbaris committed Dec 25, 2024
1 parent 4f537e0 commit d18bcbe
Show file tree
Hide file tree
Showing 43 changed files with 811 additions and 402 deletions.
2 changes: 1 addition & 1 deletion .cargo/config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@
rustflags = []

[env]
RUST_BACKTRACE = "1"
# RUST_BACKTRACE = "1"
2 changes: 1 addition & 1 deletion .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
"kind": "bin"
}
},
"args": [],
"args": ["--path", "/Users/erhanbaris/Downloads/pi_tc/", "deploy"],
"cwd": "${workspaceFolder}"
},
{
Expand Down
3 changes: 1 addition & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ name = "timug"
path = "src/main.rs"

[dependencies]
anyhow = "1.0.93"
chrono = "0.4.38"
clap = { version = "4.5.23", features = ["derive"] }
console = "0.15.8"
Expand All @@ -32,7 +31,6 @@ serde = { version = "1.0.215", features = ["derive", "rc"] }
serde_json = "1.0.133"
serde_yaml = "0.9"
subprocess = "0.2.9"
thiserror = "2.0.3"
unidecode = "0.3.0"
urlencoding = "2.1.3"
rust-embed="8.5.0"
Expand All @@ -43,6 +41,7 @@ tower-http = { version = "0.6.2", features = ["fs", "trace"] }
notify = "7.0.0"
log = "0.4.22"
env_logger = "0.11.6"
snafu = "0.8.5"

[dev-dependencies]
tempfile = "3.14.0"
3 changes: 3 additions & 0 deletions plugins/benchmark/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
target
node_modules
.wrangler
10 changes: 10 additions & 0 deletions plugins/benchmark/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
[package]
name = "benchmark"
version = "0.1.0"
edition = "2021"
authors = [ "Erhan BARIS <[email protected]>" ]

[dependencies]
lipsum = "0.9.1"
rand = "0.8.5"
rand_hc = "0.3.2"
43 changes: 43 additions & 0 deletions plugins/benchmark/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
use std::fs::File;
use std::io::Write;
use std::path::Path;

use lipsum::{lipsum, lipsum_with_rng, lipsum_words_with_rng};
use rand::prelude::*;

use rand::seq::SliceRandom;

fn main() {
let lorem_tags = lipsum_with_rng(rand::thread_rng(), 20).replace(",", "").replace(".", "");
let tags = lorem_tags.split(' ').collect::<Vec<_>>();
let posts_path = Path::new("/Users/erhanbaris/Downloads/pi_tc/posts");


for i in 0..1_000 {
let title = lipsum_with_rng(rand::thread_rng(), rand::thread_rng().gen_range(5..12));
let description = lipsum_words_with_rng(rand::thread_rng(), 1000);
let mut post_tags = Vec::new();

for _ in 0..rand::thread_rng().gen_range(5..12) {
if let Some(tag) = tags.choose(&mut rand::thread_rng()) {
post_tags.push(tag);
}
}

let slug = title.to_lowercase().replace(" ", "-").replace(",", "").replace(".", "");

let mut file = File::create(posts_path.join(format!("{}.md", i))).unwrap();
let content = format!("---
title: {}
slug: {}
lang: en
date: 2024-12-10 17:07:45
tags:
{}
---
{}
", title, slug, post_tags.iter().map(|tag| format!(" - {}\r\n", tag)).collect::<Vec<String>>().join(""), description);

file.write_all(content.as_bytes()).unwrap();
}
}
6 changes: 3 additions & 3 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,9 @@ The command will generate static files and copy them to the **public** directory

### Live preview
```bash
timug start
timug --path /home/user/my_blog/ start
timug --path /home/user/my_blog/ start 9090 # For custom port
timug server
timug --path /home/user/my_blog/ server
timug --path /home/user/my_blog/ server 9090 # For custom port
```
It will start a local server and you can preview your blog on your browser.

Expand Down
67 changes: 39 additions & 28 deletions src/application.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::cli::TemplateCommand;
use crate::config::TimugConfig;
use crate::consts::{ExamplesAssets, TemplateAssets, ASSETS_PATH, CONFIG_FILE_NAME, DEFAULT_DEPLOYMENT_FOLDER, DEFAULT_LANGUAGE, DEFAULT_THEME, PAGES_PATH, POSTS_PATH, ROCKET, TEMPLATES_PATH};
use crate::context::{build_context, get_context};
use crate::error::{CanceledByTheUserSnafu, CannotOverwriteConfigSnafu, CouldNotGetAbsolutePathSnafu, FileCreationFailedSnafu, NoCurrentDirSnafu, WriteSnafu, YamlSerializationFailedSnafu};
use crate::server::start_webserver;
use crate::tools::{get_slug, inner_deploy_pages};

Expand All @@ -12,24 +13,25 @@ use std::{
};

use console::{style, Term};
use snafu::{ensure, ResultExt};

fn initialize(path: Option<PathBuf>, draft: bool) -> anyhow::Result<()> {
fn initialize(path: Option<PathBuf>, draft: bool) -> crate::Result<()> {
build_context(path, draft)?;
Ok(())
}

pub fn start_create_new_project(project_path: Option<PathBuf>) -> anyhow::Result<()> {
pub fn start_create_new_project(project_path: Option<PathBuf>) -> crate::Result<()> {
let project_path = if let Some(path) = project_path {
path
} else {
std::env::current_dir()?
std::env::current_dir().context(NoCurrentDirSnafu)?
};

let terminal = Term::stdout();
let mut config = TimugConfig::default();

// Get full path
let path = std::path::absolute(project_path.clone())?;
let path = std::path::absolute(project_path.clone()).context(CouldNotGetAbsolutePathSnafu { path: project_path.clone() })?;

config.lang = DEFAULT_LANGUAGE.to_string();
config.theme = DEFAULT_THEME.to_string();
Expand All @@ -40,9 +42,7 @@ pub fn start_create_new_project(project_path: Option<PathBuf>) -> anyhow::Result
if std::fs::exists(&config_path).unwrap_or_default() {
// Config is already exists

if log::max_level() == log::LevelFilter::Off {
return Err(anyhow::anyhow!("Log disabled. Can't overwrite config file."));
}
ensure!(log::max_level() != log::LevelFilter::Off, CannotOverwriteConfigSnafu);

log::info!("\"{}\" already created.\r\n", config_path.display());
log::info!("Do you want to overwrite it?");
Expand All @@ -51,17 +51,23 @@ pub fn start_create_new_project(project_path: Option<PathBuf>) -> anyhow::Result

match answer {
Ok('Y') | Ok('y') => (),
_ => return Err(anyhow::anyhow!("Canceled by the user")),
_ => {
return CanceledByTheUserSnafu
.fail()
.map_err(::core::convert::Into::into)
}
}
}

// Create path, if need it
let _ = create_dir(&config.blog_path);
let mut config_file = File::create(&config_path)?;
let mut config_file = File::create(&config_path).context(FileCreationFailedSnafu { path: config_path.clone() })?;

let config_string = serde_yaml::to_string(&config)?;
let config_string = serde_yaml::to_string(&config).context(YamlSerializationFailedSnafu)?;

config_file.write_all(config_string.as_bytes())?;
config_file
.write_all(config_string.as_bytes())
.context(WriteSnafu { path: config_path })?;

let template_path = config.blog_path.join(TEMPLATES_PATH).join(DEFAULT_THEME);
let posts_path = config.blog_path.join(POSTS_PATH);
Expand All @@ -74,15 +80,17 @@ pub fn start_create_new_project(project_path: Option<PathBuf>) -> anyhow::Result

for file_name in TemplateAssets::iter() {
if let Some(file_content) = TemplateAssets::get(&file_name) {
let mut file = File::create(template_path.join(file_name.to_string()))?;
file.write_all(&file_content.data)?;
let mut file = File::create(template_path.join(file_name.to_string())).context(FileCreationFailedSnafu { path: template_path.join(file_name.to_string()) })?;
file.write_all(&file_content.data)
.context(WriteSnafu { path: template_path.join(file_name.to_string()) })?;
}
}

for file_name in ExamplesAssets::iter() {
if let Some(file_content) = ExamplesAssets::get(&file_name) {
let mut file = File::create(posts_path.join(file_name.to_string()))?;
file.write_all(&file_content.data)?;
let mut file = File::create(posts_path.join(file_name.to_string())).context(FileCreationFailedSnafu { path: posts_path.join(file_name.to_string()) })?;
file.write_all(&file_content.data)
.context(WriteSnafu { path: posts_path.join(file_name.to_string()) })?;
}
}

Expand All @@ -94,7 +102,7 @@ pub fn start_create_new_project(project_path: Option<PathBuf>) -> anyhow::Result
Ok(())
}

pub fn start_server(path: Option<PathBuf>, port: Option<u16>, draft: bool) -> anyhow::Result<()> {
pub fn start_server(path: Option<PathBuf>, port: Option<u16>, draft: bool) -> crate::Result<()> {
initialize(path.clone(), draft)?;
log::info!("Building...");
inner_deploy_pages()?;
Expand All @@ -103,22 +111,22 @@ pub fn start_server(path: Option<PathBuf>, port: Option<u16>, draft: bool) -> an
Ok(())
}

pub fn start_deploy_pages(path: Option<PathBuf>, draft: bool) -> anyhow::Result<()> {
pub fn start_deploy_pages(path: Option<PathBuf>, draft: bool) -> crate::Result<()> {
initialize(path.clone(), draft)?;
inner_deploy_pages()
}

pub fn create_page(path: Option<PathBuf>, title: String, draft: bool) -> anyhow::Result<()> {
pub fn create_page(path: Option<PathBuf>, title: String, draft: bool) -> crate::Result<()> {
create_new(path, title, draft, PAGES_PATH)
}

pub fn create_post(path: Option<PathBuf>, title: String, draft: bool) -> anyhow::Result<()> {
pub fn create_post(path: Option<PathBuf>, title: String, draft: bool) -> crate::Result<()> {
create_new(path, title, draft, POSTS_PATH)
}

fn create_new(path: Option<PathBuf>, title: String, draft: bool, folder: &str) -> anyhow::Result<()> {
fn create_new(path: Option<PathBuf>, title: String, draft: bool, folder: &str) -> crate::Result<()> {
initialize(path.clone(), draft)?;
let ctx = get_context();
let ctx = get_context(snafu::location!())?;
let slug = get_slug(&title);
let date = chrono::offset::Local::now().format("%Y-%m-%d %H:%M:%S");
let path = ctx
Expand All @@ -145,31 +153,34 @@ tags:
false => "",
}
);
let mut file = File::create(path)?;
file.write_all(content.as_bytes())?;
let mut file = File::create(&path).context(FileCreationFailedSnafu { path: path.clone() })?;
file.write_all(content.as_bytes())
.context(WriteSnafu { path })?;
Ok(())
}

pub fn execute_template(path: Option<PathBuf>, command: TemplateCommand) -> anyhow::Result<()> {
pub fn execute_template(path: Option<PathBuf>, command: TemplateCommand) -> crate::Result<()> {
initialize(path.clone(), false)?;
let ctx = get_context();
let ctx = get_context(snafu::location!())?;
let template_path = ctx
.config
.blog_path
.join(TEMPLATES_PATH)
.join(DEFAULT_THEME);

match command {
TemplateCommand::Update => {
TemplateCommand::Upgrade => {
for file_name in TemplateAssets::iter() {
if let Some(file_content) = TemplateAssets::get(&file_name) {
let mut file = File::create(template_path.join(file_name.to_string()))?;
file.write_all(&file_content.data)?;
let mut file = File::create(template_path.join(file_name.to_string())).context(FileCreationFailedSnafu { path: template_path.join(file_name.to_string()) })?;
file.write_all(&file_content.data)
.context(WriteSnafu { path: template_path.join(file_name.to_string()) })?;
}
}

log::warn!("Template updated.");
}
TemplateCommand::Deploy => {}
};
Ok(())
}
10 changes: 7 additions & 3 deletions src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,13 @@ pub enum CreateType {

#[derive(Clone, Debug, ValueEnum)]
pub enum TemplateCommand {
/// Update template
/// Upgrade template to latest version
#[value()]
Update,
Upgrade,

/// Deploy template
#[value()]
Deploy,
}

#[derive(Debug, Subcommand)]
Expand All @@ -79,7 +83,7 @@ pub enum Commands {
},

/// Start development server with live update
Start {
Server {
port: Option<u16>,

/// Render draft posts
Expand Down
5 changes: 5 additions & 0 deletions src/consts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ pub const POSTS_PATH: &str = "posts";
pub const PAGES_PATH: &str = "pages";
pub const ASSETS_PATH: &str = "assets";
pub const CONFIG_FILE_NAME: &str = "timug.yaml";
pub const TEMPLATE_FILE_NAME: &str = "template.yaml";

pub const PAGE_HTML: &str = "page.html";
pub const POST_HTML: &str = "post.html";
pub const POSTS_HTML: &str = "posts.html";

pub const ROCKET: Emoji<'_, '_> = Emoji("🚀 ", ":-)");
pub const SPARKLE: Emoji<'_, '_> = Emoji("✨ ", "#");
Loading

0 comments on commit d18bcbe

Please sign in to comment.