Skip to content

Commit

Permalink
优化日志的注册逻辑
Browse files Browse the repository at this point in the history
  • Loading branch information
ityuany committed Jan 31, 2025
1 parent 78896c6 commit a9b2e30
Show file tree
Hide file tree
Showing 7 changed files with 119 additions and 143 deletions.
124 changes: 91 additions & 33 deletions crates/cli/src/execute_cli.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
use std::env::current_exe;
use std::{fs, ops::Not};

use clap::CommandFactory;
use colored::*;
use snm_config::snm_config::SnmConfig;
use snm_pm::pm::PackageManager;
use snm_utils::exec::exec_cli;
use tracing::trace;

use crate::cli::SnmCli;
use crate::fig::fig_spec_impl;
use crate::manage_command::NodeManageCommands;
use crate::snm_command::SnmCommands;

Expand Down Expand Up @@ -51,39 +53,95 @@ pub async fn execute_cli(cli: SnmCli, snm_config: SnmConfig) -> anyhow::Result<(
exec_cli(&commands, &vec![], false)?;
}

SnmCommands::FigSpec => {
fig_spec_impl()?;
}
SnmCommands::SetUp => {
let exe = current_exe()?;
let exe_dir = exe.parent().unwrap();

const SHIM_TARGETS: &[&str] = &["npm", "npx", "yarn", "pnpm", "pnpx", "node"];

#[cfg(windows)]
let source = exe_dir.join("snm-shim.exe");
#[cfg(not(windows))]
let source = exe_dir.join("snm-shim");

// let source = exe_dir.join("snm-shim");
for target in SHIM_TARGETS {
// let target = exe_dir.join(target);
#[cfg(windows)]
let target = exe_dir.join(format!("{}.exe", target));
#[cfg(not(windows))]
let target = exe_dir.join(target);
if target.try_exists()? {
std::fs::remove_file(&target)?;
}
#[cfg(unix)]
{
std::os::unix::fs::symlink(&source, &target)?;
}
#[cfg(windows)]
{
std::os::windows::fs::symlink_file(&source, &target)?;
}
}
setup_fig()?;
setup_symlink()?;
}
}

Ok(())
}

fn setup_fig() -> anyhow::Result<()> {
let mut output = Vec::new();
clap_complete::generate(
clap_complete_fig::Fig,
&mut SnmCli::command(),
"snm",
&mut output,
);
let mut output_string = String::from_utf8(output).unwrap();

output_string = output_string.replace("const completion: Fig.Spec = {", "const completion = {");

if let Some(home) = dirs::home_dir() {
let dir = home.join(".fig").join("autocomplete").join("build");

if dir.exists().not() {
fs::create_dir_all(&dir)
.expect(format!("fig_spec_impl create_dir_all error {:?}", &dir.display()).as_str());
}

let spec_path_buf = dir.join("snm.js");

if spec_path_buf.exists() {
fs::remove_file(&spec_path_buf).expect(
format!(
"fig_spec_impl remove_file error {:?}",
&spec_path_buf.display()
)
.as_str(),
);
}

fs::write(&spec_path_buf, &output_string)?;

let message = format!(
r##"
🎉 Fig spec file create successful.
🔔 Now ! Fig rename to {}
{}
"##,
"Amazon Q".green().bold(),
"Powered by snm".bright_black(),
);

eprintln!("{message}");
}

Ok(())
}

fn setup_symlink() -> anyhow::Result<()> {
let exe = current_exe()?;
let exe_dir = exe.parent().unwrap();

const SHIM_TARGETS: &[&str] = &["npm", "npx", "yarn", "pnpm", "pnpx", "node"];

#[cfg(windows)]
let source = exe_dir.join("snm-shim.exe");
#[cfg(not(windows))]
let source = exe_dir.join("snm-shim");

// let source = exe_dir.join("snm-shim");
for target in SHIM_TARGETS {
// let target = exe_dir.join(target);
#[cfg(windows)]
let target = exe_dir.join(format!("{}.exe", target));
#[cfg(not(windows))]
let target = exe_dir.join(target);
if target.try_exists()? {
std::fs::remove_file(&target)?;
}
#[cfg(unix)]
{
std::os::unix::fs::symlink(&source, &target)?;
}
#[cfg(windows)]
{
std::os::windows::fs::symlink_file(&source, &target)?;
}
}

Expand Down
59 changes: 0 additions & 59 deletions crates/cli/src/fig.rs

This file was deleted.

20 changes: 2 additions & 18 deletions crates/cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,33 +3,17 @@ use std::env::current_dir;
use clap::Parser;
use cli::SnmCli;
use snm_config::snm_config::SnmConfig;
use snm_utils::consts::SNM_PREFIX;
use snm_utils::{consts::SNM_PREFIX, log::init_snm_log};
use tracing::trace;
use tracing_subscriber::{fmt, layer::SubscriberExt, util::SubscriberInitExt, EnvFilter, Layer};

mod cli;
mod execute_cli;
mod fig;
mod manage_command;
mod snm_command;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
if let Some(home) = dirs::home_dir() {
let file = std::fs::File::create(home.join("snm.log"))?;

let file_layer = fmt::layer()
.with_writer(file)
.with_filter(EnvFilter::from_env("SNM_LOG"));

// 创建控制台写入器
let stdout_layer = fmt::layer().with_filter(EnvFilter::from_env("SNM_LOG"));

tracing_subscriber::registry()
.with(file_layer)
.with(stdout_layer)
.try_init()?;
}
init_snm_log()?;

trace!("Start snm");

Expand Down
15 changes: 0 additions & 15 deletions crates/cli/src/snm_command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,6 @@ pub enum SnmCommands {
)]
Install(InstallArgs),

// #[command(about = "Alias to snm install --frozen-lockfile.")]
// C(InstallArgs),
// #[command(about = "Add a package and any packages that it depends on.")]
// Add(AddArgs),
#[command(
visible_aliases=["un"],
about = "Remove a package.",
Expand All @@ -26,23 +22,12 @@ pub enum SnmCommands {
#[command(about = "Run a command.")]
Run(RunArgs),

// #[command(about = "Hot load a package, and runs whatever default command binary it exposes..")]
// X(XArgs),

// #[command(about = "Run a command from a local package.")]
// E(EArgs),

// #[command(about = "Run some script.")]
// R(RArgs),
#[command(about = "Manage node versions.")]
Node {
#[command(subcommand)]
command: NodeManageCommands,
},

#[command(about = "write fig spec to autocomplete build directory.")]
FigSpec,

#[command(name = "setup", about = "Setup snm.")]
SetUp,
}
19 changes: 2 additions & 17 deletions crates/snm_shim/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,29 +4,14 @@ use anyhow::bail;
use node_shim::load_node;
use pm_shim::load_pm;
use snm_config::snm_config::SnmConfig;
use snm_utils::{consts::SNM_PREFIX, trace_if};
use snm_utils::{consts::SNM_PREFIX, log::init_snm_log, trace_if};
use tracing::trace;
use tracing_subscriber::{fmt, layer::SubscriberExt, util::SubscriberInitExt, EnvFilter, Layer};
mod node_shim;
mod pm_shim;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
if let Some(home) = dirs::home_dir() {
let file = std::fs::File::create(home.join("snm_shim.log"))?;

let file_layer = fmt::layer()
.with_writer(file)
.with_filter(EnvFilter::from_env("SNM_LOG"));

// 创建控制台写入器
let stdout_layer = fmt::layer().with_filter(EnvFilter::from_env("SNM_LOG"));

tracing_subscriber::registry()
.with(file_layer)
.with(stdout_layer)
.try_init()?;
}
init_snm_log()?;

trace!("Start snm_shim");

Expand Down
4 changes: 3 additions & 1 deletion crates/snm_utils/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,10 @@ serde_json = "1.0.114"
tar = "0.4.40"
termcolor = "1.4.1"
thiserror = "1.0.58"
tracing = { workspace = true }
wait-timeout = { workspace = true }
which = { workspace = true }
xz2 = { version = "0.1.7", features = ["static"] }
zip = "2.1.3"
dirs = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
21 changes: 21 additions & 0 deletions crates/snm_utils/src/log.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use tracing_subscriber::{fmt, layer::SubscriberExt, util::SubscriberInitExt, EnvFilter, Layer};

Check failure on line 1 in crates/snm_utils/src/log.rs

View workflow job for this annotation

GitHub Actions / Unit testing (ubuntu-latest, x86_64-unknown-linux-musl)

unresolved import `tracing_subscriber::EnvFilter`

Check failure on line 1 in crates/snm_utils/src/log.rs

View workflow job for this annotation

GitHub Actions / Unit testing (windows-latest, x86_64-pc-windows-msvc)

unresolved import `tracing_subscriber::EnvFilter`

Check failure on line 1 in crates/snm_utils/src/log.rs

View workflow job for this annotation

GitHub Actions / Unit testing (windows-latest, i686-pc-windows-msvc)

unresolved import `tracing_subscriber::EnvFilter`

Check failure on line 1 in crates/snm_utils/src/log.rs

View workflow job for this annotation

GitHub Actions / Unit testing (macos-14, aarch64-apple-darwin)

unresolved import `tracing_subscriber::EnvFilter`

Check failure on line 1 in crates/snm_utils/src/log.rs

View workflow job for this annotation

GitHub Actions / Unit testing (macos-13, x86_64-apple-darwin)

unresolved import `tracing_subscriber::EnvFilter`

#[macro_export]
macro_rules! trace_if {
// 闭包形式,直接执行闭包内的代码
Expand All @@ -13,3 +15,22 @@ macro_rules! trace_if {
}
};
}

pub fn init_snm_log() -> anyhow::Result<()> {
if let Some(home) = dirs::home_dir() {
let file = std::fs::File::create(home.join("snm.log"))?;

let file_layer = fmt::layer()
.with_writer(file)
.with_filter(EnvFilter::from_env("SNM_LOG"));

// 创建控制台写入器
let stdout_layer = fmt::layer().with_filter(EnvFilter::from_env("SNM_LOG"));

tracing_subscriber::registry()
.with(file_layer)
.with(stdout_layer)
.try_init()?;
}
Ok(())
}

0 comments on commit a9b2e30

Please sign in to comment.