forked from devlive-community/codeforge
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod.rs
More file actions
339 lines (289 loc) · 11 KB
/
mod.rs
File metadata and controls
339 lines (289 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
use crate::config::get_app_config_internal;
use log::{debug, info};
use serde::{Deserialize, Serialize};
use std::format;
use std::path::PathBuf;
// 通用结构定义
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ExecutionResult {
pub success: bool,
pub stdout: String,
pub stderr: String,
pub execution_time: u128,
pub timestamp: u64,
pub language: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CodeExecutionRequest {
pub code: String,
pub language: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct LanguageInfo {
pub installed: bool,
pub version: String,
pub path: String,
pub language: String,
}
// 插件配置结构
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PluginConfig {
pub enabled: bool, // 插件是否启用
pub execute_home: Option<String>, // 插件的执行路径
pub extension: String, // 插件支持的文件扩展名
pub language: String, // 插件所属语言
pub before_compile: Option<String>, // 插件在编译前执行的命令
pub after_compile: Option<String>, // 插件在编译完成后执行的命令
pub run_command: Option<String>, // 插件执行的命令,例如 "python2 $filename"
pub template: Option<String>, // 插件的模板
pub timeout: Option<u64>, // 插件的超时时间
}
// 语言插件接口
pub trait LanguagePlugin: Send + Sync {
// 获取插件优先级
fn get_order(&self) -> i32 {
0
}
// 获取插件名称
fn get_language_name(&self) -> &'static str;
// 获取插件唯一标记
fn get_language_key(&self) -> &'static str;
// 获取插件支持的文件扩展名
fn get_file_extension(&self) -> String;
// 获取执行目录
fn get_execute_home(&self) -> Option<PathBuf> {
self.get_config()
.and_then(|config| config.execute_home.clone())
.filter(|path| !path.trim().is_empty()) // 过滤掉空字符串和只有空白字符的字符串
.map(PathBuf::from)
}
// 获取超时时间
fn get_timeout(&self) -> u64 {
self.get_config()
.map(|config| config.timeout.unwrap_or(30))
.unwrap_or(30)
}
// 获取插件支持的命令
fn get_command(&self, file_path: Option<&str>) -> String {
if let Some(config) = self.get_config() {
if let Some(run_cmd) = &config.run_command {
return if let Some(path) = file_path {
if self.get_execute_home().is_some() {
// 如果有执行主目录,在整个命令前面加 ./
let cmd_with_file = run_cmd.replace("$filename", path);
if cmd_with_file.starts_with("./") {
cmd_with_file
} else {
format!("./{}", cmd_with_file)
}
} else {
run_cmd.replace("$filename", path)
}
} else {
let base_cmd = run_cmd
.split_whitespace()
.next()
.unwrap_or(&config.language)
.to_string();
if self.get_execute_home().is_some() && !base_cmd.starts_with("./") {
format!("./{}", base_cmd)
} else {
base_cmd
}
};
}
}
self.get_default_command()
}
// 获取插件配置
fn get_config(&self) -> Option<PluginConfig> {
// 获取全局应用配置
if let Ok(app_config) = get_app_config_internal() {
// 检查是否有插件配置
if let Some(ref plugins) = app_config.plugins {
// 根据当前插件的语言名称过滤配置
let language_name = self.get_language_key();
// 查找匹配的插件配置
let found_config = plugins
.iter()
.find(|config| config.language == language_name)
.cloned();
debug!(
"执行代码 -> 获取插件 [ {} ] 配置 {:?}",
language_name, found_config
);
return found_config;
}
}
// 如果没有找到配置,返回默认配置
debug!(
"执行代码 -> 插件 [ {} ] 未找到配置,使用默认配置",
self.get_language_key()
);
Some(self.get_default_config())
}
// 检查插件是否启用
#[allow(dead_code)]
fn is_enabled(&self) -> bool {
self.get_config()
.map(|config| config.enabled)
.unwrap_or(false)
}
fn get_version_args(&self) -> Vec<&'static str>;
fn get_execute_args(&self, file_path: &str) -> Vec<String> {
if let Some(config) = self.get_config() {
if let Some(run_cmd) = &config.run_command {
// 替换 $filename 后分割,跳过第一个元素(命令本身)
let full_cmd = run_cmd.replace("$filename", file_path);
return full_cmd
.split_whitespace()
.skip(1) // 跳过命令部分,只返回参数
.map(|s| s.to_string())
.collect();
}
}
// 默认情况下,文件路径就是唯一的参数
vec![file_path.to_string()]
}
fn get_path_command(&self) -> String;
// 构建默认配置
fn get_default_config(&self) -> PluginConfig;
// 获取默认命令
fn get_default_command(&self) -> String;
// 预执行钩子
fn pre_execute_hook(&self, code: &str) -> Result<String, String> {
info!(
"执行代码 -> 插件 [ {} ] 处理 pre_execute_hook 开始",
self.get_language_key()
);
if let Some(config) = self.get_config() {
// 1. 处理 before_compile 命令(直接在 Rust 中处理)
if let Some(before_cmd) = &config.before_compile {
info!(
"执行代码 -> 插件 [ {} ] 处理 pre_execute_hook 处理环境变量: {}",
self.get_language_key(),
before_cmd
);
self.handle_environment_setup(before_cmd)?;
}
// 2. 切换到 execute_home 目录
if let Some(execute_home) = self.get_execute_home() {
info!(
"执行代码 -> 插件 [ {} ] 处理 pre_execute_hook 切换到执行目录 {}",
self.get_language_key(),
execute_home.display()
);
std::env::set_current_dir(&execute_home)
.map_err(|e| format!("切换目录失败: {}", e))?;
}
}
info!(
"执行代码 -> 插件 [ {} ] 处理 pre_execute_hook 结束",
self.get_language_key()
);
Ok(code.to_string())
}
fn handle_environment_setup(&self, command: &str) -> Result<(), String> {
// 处理 export 命令(Unix/Linux/macOS)
if command.starts_with("export ") {
return self.handle_export_command(command);
}
// 处理 set 命令(Windows)
if command.starts_with("set ") {
return self.handle_set_command(command);
}
// 处理其他通用环境设置
self.execute_cross_platform_command(command)
}
fn handle_export_command(&self, command: &str) -> Result<(), String> {
if let Some(env_part) = command.strip_prefix("export ") {
if let Some((key, value)) = env_part.split_once("=") {
let value = value.trim_matches('"').trim_matches('\'');
let expanded_value = self.expand_env_vars(value);
let key = key.trim();
// 先记录日志,再设置环境变量
info!("设置环境变量 {}={}", key, expanded_value);
// 使用 unsafe 块设置环境变量
unsafe {
std::env::set_var(key, expanded_value);
}
}
}
Ok(())
}
fn handle_set_command(&self, command: &str) -> Result<(), String> {
if let Some(env_part) = command.strip_prefix("set ") {
if let Some((key, value)) = env_part.split_once("=") {
let value = value.trim_matches('"').trim_matches('\'');
let expanded_value = self.expand_env_vars(value);
let key = key.trim();
// 先记录日志,再设置环境变量
info!("设置环境变量 {}={}", key, expanded_value);
// 使用 unsafe 块设置环境变量
unsafe {
std::env::set_var(key, expanded_value);
}
}
}
Ok(())
}
fn expand_env_vars(&self, value: &str) -> String {
let mut result = value.to_string();
// 处理 Unix 风格的环境变量 $VAR
if result.contains("$PATH") {
if let Ok(current_path) = std::env::var("PATH") {
result = result.replace("$PATH", ¤t_path);
}
}
// 处理 Windows 风格的环境变量 %VAR%
if result.contains("%PATH%") {
if let Ok(current_path) = std::env::var("PATH") {
result = result.replace("%PATH%", ¤t_path);
}
}
result
}
fn execute_cross_platform_command(&self, command: &str) -> Result<(), String> {
let output = if cfg!(target_os = "windows") {
std::process::Command::new("cmd")
.args(["/C", command])
.output()
} else {
std::process::Command::new("sh")
.args(["-c", command])
.output()
};
let output = output.map_err(|e| format!("执行命令失败: {}", e))?;
if !output.status.success() {
return Err(format!(
"命令执行失败: {}",
String::from_utf8_lossy(&output.stderr)
));
}
Ok(())
}
// 后执行钩子
fn post_execute_hook(&self, result: &mut ExecutionResult) -> Result<(), String> {
info!(
"执行代码 -> 插件 [ {} ] 处理 post_execute_hook 开始",
self.get_language_key()
);
if result.success && result.stdout.is_empty() && result.stderr.is_empty() {
result.stdout = String::from("END-NO-OUTPUT");
result.stderr = String::from("END-NO-OUTPUT");
}
info!(
"执行代码 -> 插件 [ {} ] 处理 post_execute_hook 结束",
self.get_language_key()
);
Ok(())
}
}
// 重新导出子模块
pub mod go;
pub mod java;
pub mod manager;
pub mod nodejs;
pub mod python2;
pub mod python3;
pub use manager::PluginManager;