Add update hook

This commit is contained in:
2025-10-25 21:34:13 +08:00
parent a2edf22954
commit fb9c58f4ae
2 changed files with 55 additions and 1 deletions

View File

@@ -10,6 +10,7 @@ use axum::{
Router, Router,
}; };
use std::sync::Arc; use std::sync::Arc;
use tokio::process::Command;
use tokio::sync::RwLock; use tokio::sync::RwLock;
use tower_http::services::ServeDir; use tower_http::services::ServeDir;
@@ -34,6 +35,7 @@ async fn main() {
let app = Router::new() let app = Router::new()
.route("/", get(index_handler)) .route("/", get(index_handler))
.route("/update", get(update_handler))
.route("/:page", get(all_handler)) .route("/:page", get(all_handler))
.nest("/p", p_router) .nest("/p", p_router)
.with_state(app_state); .with_state(app_state);
@@ -87,6 +89,58 @@ async fn post_handler(
} }
} }
async fn update_handler(State(state): State<AppState>) -> impl IntoResponse {
// Run git pull --autostash
let output = Command::new("git")
.arg("pull")
.arg("--autostash")
.output()
.await;
match output {
Ok(output) => {
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
eprintln!("Git pull failed: {}", stderr);
return (
StatusCode::INTERNAL_SERVER_ERROR,
format!("Git pull failed: {}", stderr),
)
.into_response();
}
let stdout = String::from_utf8_lossy(&output.stdout);
println!("Git pull output: {}", stdout);
// Refresh posts
let mut manager = state.post_manager.write().await;
match manager.refresh_posts() {
Ok(_) => {
println!("Successfully refreshed log pages");
(StatusCode::OK, "Update successful: pulled changes and refreshed log pages")
.into_response()
}
Err(e) => {
eprintln!("Failed to refresh posts: {}", e);
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Failed to refresh posts: {}", e),
)
.into_response()
}
}
}
Err(e) => {
eprintln!("Failed to execute git pull: {}", e);
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Failed to execute git pull: {}", e),
)
.into_response()
}
}
}
async fn render_template(template_name: &str, state: &AppState) -> Result<String, String> { async fn render_template(template_name: &str, state: &AppState) -> Result<String, String> {
let template_path = format!("templates/{}", template_name); let template_path = format!("templates/{}", template_name);

View File

@@ -132,7 +132,7 @@ impl PostManager {
Ok(result) Ok(result)
} }
fn refresh_posts(&mut self) -> Result<(), String> { pub fn refresh_posts(&mut self) -> Result<(), String> {
self.posts.clear(); self.posts.clear();
// Get timestamps from git history // Get timestamps from git history