This commit is contained in:
thek4n 2026-02-21 09:00:18 +03:00
parent a4f64226b6
commit 45a8c4ea08
3 changed files with 171 additions and 9 deletions

127
Cargo.lock generated
View File

@ -17,6 +17,56 @@ dependencies = [
"memchr", "memchr",
] ]
[[package]]
name = "anstream"
version = "0.6.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a"
dependencies = [
"anstyle",
"anstyle-parse",
"anstyle-query",
"anstyle-wincon",
"colorchoice",
"is_terminal_polyfill",
"utf8parse",
]
[[package]]
name = "anstyle"
version = "1.0.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5192cca8006f1fd4f7237516f40fa183bb07f8fbdfedaa0036de5ea9b0b45e78"
[[package]]
name = "anstyle-parse"
version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2"
dependencies = [
"utf8parse",
]
[[package]]
name = "anstyle-query"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "anstyle-wincon"
version = "3.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
dependencies = [
"anstyle",
"once_cell_polyfill",
"windows-sys 0.61.2",
]
[[package]] [[package]]
name = "async-trait" name = "async-trait"
version = "0.1.89" version = "0.1.89"
@ -138,6 +188,52 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]]
name = "clap"
version = "4.5.60"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2797f34da339ce31042b27d23607e051786132987f595b02ba4f6a6dffb7030a"
dependencies = [
"clap_builder",
"clap_derive",
]
[[package]]
name = "clap_builder"
version = "4.5.60"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24a241312cea5059b13574bb9b3861cabf758b879c15190b37b6d6fd63ab6876"
dependencies = [
"anstream",
"anstyle",
"clap_lex",
"strsim",
]
[[package]]
name = "clap_derive"
version = "4.5.55"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a92793da1a46a5f2a02a6f4c46c6496b28c43638adea8306fcb0caa1634f24e5"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "clap_lex"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a822ea5bc7590f9d40f1ba12c0dc3c2760f3482c6984db1573ad11031420831"
[[package]]
name = "colorchoice"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75"
[[package]] [[package]]
name = "crc32fast" name = "crc32fast"
version = "1.5.0" version = "1.5.0"
@ -341,6 +437,12 @@ version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
[[package]]
name = "heck"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]] [[package]]
name = "http" name = "http"
version = "1.4.0" version = "1.4.0"
@ -452,6 +554,12 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "is_terminal_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
[[package]] [[package]]
name = "itoa" name = "itoa"
version = "1.0.17" version = "1.0.17"
@ -542,6 +650,7 @@ name = "mdpreview"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"axum", "axum",
"clap",
"futures", "futures",
"notify", "notify",
"pulldown-cmark", "pulldown-cmark",
@ -637,6 +746,12 @@ version = "1.21.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
[[package]]
name = "once_cell_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
[[package]] [[package]]
name = "onig" name = "onig"
version = "6.5.1" version = "6.5.1"
@ -945,6 +1060,12 @@ dependencies = [
"windows-sys 0.60.2", "windows-sys 0.60.2",
] ]
[[package]]
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]] [[package]]
name = "syn" name = "syn"
version = "2.0.116" version = "2.0.116"
@ -1192,6 +1313,12 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
[[package]]
name = "utf8parse"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]] [[package]]
name = "valuable" name = "valuable"
version = "0.1.1" version = "0.1.1"

View File

@ -1,7 +1,16 @@
[package] [package]
name = "mdpreview" name = "mdpreview"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2024"
authors = ["Vladislav Kan <thek4n@yandex.ru>"]
[profile.release]
opt-level = "z" # Оптимизация именно по размеру (z > s)
lto = true # Link Time Optimization: объединяет и оптимизирует весь код целиком
codegen-units = 1 # Уменьшает количество параллельных единиц компиляции, позволяя лучше оптимизировать
panic = "abort" # Отключает механизм развертывания стека при панике (экономит много места)
strip = true # Автоматически удаляет символы отладки (доступно в стабильной версии Rust 1.59+)
[dependencies] [dependencies]
pulldown-cmark = "0.9" pulldown-cmark = "0.9"
@ -13,3 +22,4 @@ syntect = "5.0"
notify = "6.1" notify = "6.1"
tokio-stream = { version = "0.1", features = ["sync"] } tokio-stream = { version = "0.1", features = ["sync"] }
futures = "0.3" futures = "0.3"
clap = { version = "4.5", features = ["derive"] }

View File

@ -5,8 +5,9 @@ use axum::{
http::{StatusCode, HeaderMap, header}, http::{StatusCode, HeaderMap, header},
response::{Html, Sse, IntoResponse}, response::{Html, Sse, IntoResponse},
}; };
use pulldown_cmark::{Parser, Options, html, Event, Tag, CodeBlockKind}; use std::net::{SocketAddr, ToSocketAddrs};
use std::net::SocketAddr; use pulldown_cmark::{Options, html, Event, Tag, CodeBlockKind};
use pulldown_cmark;
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::Arc; use std::sync::Arc;
use tokio::fs; use tokio::fs;
@ -22,10 +23,27 @@ use syntect::highlighting::ThemeSet;
use syntect::html::{styled_line_to_highlighted_html, IncludeBackground}; use syntect::html::{styled_line_to_highlighted_html, IncludeBackground};
use syntect::parsing::SyntaxSet; use syntect::parsing::SyntaxSet;
use clap::Parser;
use std::io;
// Загрузка шаблонов при компиляции // Загрузка шаблонов при компиляции
const TEMPLATE_FILE: &str = include_str!("../templates/file.html"); const TEMPLATE_FILE: &str = include_str!("../templates/file.html");
const TEMPLATE_DIR: &str = include_str!("../templates/dir.html"); const TEMPLATE_DIR: &str = include_str!("../templates/dir.html");
#[derive(clap::Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Args {
/// Host to listen
#[arg(long, default_value_t = String::from("localhost"))]
host: String,
/// Port to listen
#[arg(short, long, default_value_t = 8000)]
port: u16,
}
#[derive(Clone)] #[derive(Clone)]
struct AppState { struct AppState {
syntax_set: Arc<SyntaxSet>, syntax_set: Arc<SyntaxSet>,
@ -35,9 +53,9 @@ struct AppState {
#[tokio::main] #[tokio::main]
async fn main() { async fn main() {
let args = Args::parse();
tracing_subscriber::fmt::init(); tracing_subscriber::fmt::init();
println!("Загрузка баз синтаксисов и тем...");
let ss = SyntaxSet::load_defaults_newlines(); let ss = SyntaxSet::load_defaults_newlines();
let ts = ThemeSet::load_defaults(); let ts = ThemeSet::load_defaults();
@ -60,14 +78,23 @@ async fn main() {
.route("/events/*path", get(sse_handler)) .route("/events/*path", get(sse_handler))
.with_state(state); .with_state(state);
let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); let addr = resolve_addr(&args.host, args.port).unwrap();
println!("Сервер запущен на http://{}", addr); println!("Сервер запущен на http://{}", addr);
println!("Пример: http://127.0.0.1:3000/files/readme.md");
let listener = tokio::net::TcpListener::bind(addr).await.unwrap(); let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
axum::serve(listener, app).await.unwrap(); axum::serve(listener, app).await.unwrap();
} }
fn resolve_addr(host: &str, port: u16) -> io::Result<SocketAddr> {
let addr_str = format!("{}:{}", host, port);
addr_str
.to_socket_addrs()?
.next()
.ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "Не удалось разрешить адрес"))
}
async fn root() -> Result<Html<String>, StatusCode> { async fn root() -> Result<Html<String>, StatusCode> {
render_directory_index(&PathBuf::from("./notes"), "").await render_directory_index(&PathBuf::from("./notes"), "").await
} }
@ -293,8 +320,6 @@ async fn run_file_watcher(state: AppState) {
return; return;
} }
println!("Watcher запущен для директории: {:?}", watch_path);
while let Some(path) = rx_fs.recv().await { while let Some(path) = rx_fs.recv().await {
if let Some(path_str) = path.to_str() { if let Some(path_str) = path.to_str() {
let _ = state.tx.send(path_str.to_string()); let _ = state.tx.send(path_str.to_string());
@ -312,7 +337,7 @@ fn markdown_to_html(markdown: &str, ss: &SyntaxSet, ts: &ThemeSet, _file_path: &
options.insert(Options::ENABLE_TASKLISTS); options.insert(Options::ENABLE_TASKLISTS);
options.insert(Options::ENABLE_SMART_PUNCTUATION); options.insert(Options::ENABLE_SMART_PUNCTUATION);
let parser = Parser::new_ext(markdown, options); let parser = pulldown_cmark::Parser::new_ext(markdown, options);
let mut processed_events: Vec<Event> = Vec::new(); let mut processed_events: Vec<Event> = Vec::new();
let mut in_code_block = false; let mut in_code_block = false;