repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/widgets/highlight.rs
crates/netpurr/src/widgets/highlight.rs
use std::collections::BTreeMap; use eframe::epaint::text::{LayoutJob, TextFormat}; use egui::{Color32, Ui}; use regex::Regex; use netpurr_core::data::environment::EnvironmentItemValue; pub fn highlight_template( mut text: &str, size: f32, ui: &Ui, envs: BTreeMap<String, EnvironmentItemValue>, ) -> LayoutJob { let re = Regex::new(r"\{\{.*?}}").unwrap(); let mut job = LayoutJob::default(); let font_id = egui::FontId::monospace(size); let not_found_format; let found_format; let normal_format = TextFormat::simple(font_id.clone(), ui.visuals().text_color().clone()); if ui.visuals().dark_mode { not_found_format = TextFormat::simple(font_id.clone(), Color32::RED); found_format = TextFormat::simple(font_id.clone(), Color32::GREEN); } else { not_found_format = TextFormat::simple(font_id.clone(), Color32::DARK_RED); found_format = TextFormat::simple(font_id.clone(), Color32::BLUE); } let mut start = 0; for x in re.find_iter(text) { job.append(&text[start..x.range().start], 0.0, normal_format.clone()); let key = x.as_str().trim_start_matches("{{").trim_end_matches("}}"); if envs.contains_key(key) { job.append( &text[x.range().start..x.range().end], 0.0, found_format.clone(), ); } else { job.append( &text[x.range().start..x.range().end], 0.0, not_found_format.clone(), ); } start = x.range().end } job.append(&text[start..text.len()], 0.0, normal_format.clone()); job }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/widgets/syntax.rs
crates/netpurr/src/widgets/syntax.rs
use std::collections::BTreeSet; use egui_code_editor::Syntax; pub fn js_syntax() -> Syntax { Syntax { language: "JavaScript", case_sensitive: true, comment: "//", comment_multiline: ["/*", "*/"], hyperlinks: Default::default(), keywords: BTreeSet::from([ // ES3 Keywords "break", "case", "catch", "continue", "default", "delete", "do", "else", "finally", "for", "function", "if", "in", "instanceof", "new", "return", "switch", "this", "throw", "try", "typeof", "var", "void", "while", "with", // ES5 Keywords "break", "case", "catch", "continue", "debugger", "default", "delete", "do", "else", "finally", "for", "function", "if", "in", "instanceof", "new", "return", "switch", "this", "throw", "try", "typeof", "var", "void", "while", "with", // ES6/ES2015 Keywords "class", "const", "export", "extends", "import", "super", "let", "yield", "async", "await", // Reserved Words for Future Use "enum", ]), types: BTreeSet::from([ "undefined", "null", "boolean", "number", "string", "object", "function", "symbol", ]), special: BTreeSet::from(["Self", "static", "true", "false"]), } } pub fn log_syntax() -> Syntax { Syntax { language: "Log", case_sensitive: false, comment: "//", comment_multiline: ["/*", "*/"], hyperlinks: Default::default(), keywords: BTreeSet::from(["log", "Info", "Warn", "Error"]), types: BTreeSet::from([]), special: BTreeSet::from([]), } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/widgets/empty_container.rs
crates/netpurr/src/widgets/empty_container.rs
use eframe::emath::{Align2, pos2, Rect, vec2, Vec2}; use eframe::epaint::Stroke; use egui::{Id, Response, Shape, Ui}; /// A region that can be resized by dragging the bottom right corner. #[derive(Clone, Copy, Debug)] #[must_use = "You should call .show()"] pub struct EmptyContainer { id: Option<Id>, id_source: Option<Id>, default_size: Vec2, with_stroke: bool, } impl Default for EmptyContainer { fn default() -> Self { Self { id: None, id_source: None, default_size: vec2(320.0, 128.0), with_stroke: true, } } } impl EmptyContainer { /// Assign an explicit and globally unique id. #[inline] pub fn id(mut self, id: Id) -> Self { self.id = Some(id); self } /// A source for the unique [`Id`], e.g. `.id_source("second_resize_area")` or `.id_source(loop_index)`. #[inline] pub fn id_source(mut self, id_source: impl std::hash::Hash) -> Self { self.id_source = Some(Id::new(id_source)); self } /// Preferred / suggested width. Actual width will depend on contents. /// /// Examples: /// * if the contents is text, this will decide where we break long lines. /// * if the contents is a canvas, this decides the width of it, /// * if the contents is some buttons, this is ignored and we will auto-size. #[inline] pub fn default_width(mut self, width: f32) -> Self { self.default_size.x = width; self } /// Preferred / suggested height. Actual height will depend on contents. /// /// Examples: /// * if the contents is a [`ScrollArea`] then this decides the maximum size. /// * if the contents is a canvas, this decides the height of it, /// * if the contents is text and buttons, then the `default_height` is ignored /// and the height is picked automatically.. #[inline] pub fn default_height(mut self, height: f32) -> Self { self.default_size.y = height; self } #[inline] pub fn default_size(mut self, default_size: impl Into<Vec2>) -> Self { self.default_size = default_size.into(); self } #[inline] pub fn with_stroke(mut self, with_stroke: bool) -> Self { self.with_stroke = with_stroke; self } } struct Prepared { id: Id, content_ui: Ui, } impl EmptyContainer { fn begin(&mut self, ui: &mut Ui) -> Prepared { let position = ui.available_rect_before_wrap().min; let id = self.id.unwrap_or_else(|| { let id_source = self.id_source.unwrap_or_else(|| Id::new("resize")); ui.make_persistent_id(id_source) }); let inner_rect = Rect::from_min_size(position, self.default_size); let mut content_clip_rect = inner_rect.expand(ui.visuals().clip_rect_margin); content_clip_rect = content_clip_rect.intersect(ui.clip_rect()); // Respect parent region let mut content_ui = ui.child_ui(inner_rect, *ui.layout()); content_ui.set_clip_rect(content_clip_rect); Prepared { id, content_ui } } pub fn show<R>(mut self, ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> R { let mut prepared = self.begin(ui); let ret = add_contents(&mut prepared.content_ui); self.end(ui, prepared); ret } fn end(self, ui: &mut Ui, prepared: Prepared) { let Prepared { id, content_ui } = prepared; ui.advance_cursor_after_rect(Rect::from_min_size( content_ui.min_rect().min, self.default_size, )); // ------------------------------ if self.with_stroke { let rect = Rect::from_min_size(content_ui.min_rect().left_top(), self.default_size); let rect = rect.expand(2.0); // breathing room for content ui.painter().add(Shape::rect_stroke( rect, 3.0, ui.visuals().widgets.noninteractive.bg_stroke, )); } } } pub fn paint_resize_corner(ui: &Ui, response: &Response) { let stroke = ui.style().interact(response).fg_stroke; paint_resize_corner_with_style(ui, &response.rect, stroke, Align2::RIGHT_BOTTOM); } pub fn paint_resize_corner_with_style( ui: &Ui, rect: &Rect, stroke: impl Into<Stroke>, corner: Align2, ) { let painter = ui.painter(); let cp = painter.round_pos_to_pixels(corner.pos_in_rect(rect)); let mut w = 2.0; let stroke = stroke.into(); while w <= rect.width() && w <= rect.height() { painter.line_segment( [ pos2(cp.x - w * corner.x().to_sign(), cp.y), pos2(cp.x, cp.y - w * corner.y().to_sign()), ], stroke, ); w += 4.0; } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/widgets/mod.rs
crates/netpurr/src/widgets/mod.rs
mod empty_container; pub mod highlight; pub mod highlight_template; pub mod matrix_label; pub mod syntax;
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/widgets/highlight_template.rs
crates/netpurr/src/widgets/highlight_template.rs
use std::collections::BTreeMap; use eframe::emath::pos2; use egui::{ Context, EventFilter, Id, Key, Pos2, Response, RichText, TextBuffer, TextEdit, Ui, Widget, }; use egui::ahash::HashSet; use egui::text::{CCursor, CCursorRange, CursorRange}; use egui::text_edit::TextEditState; use serde::{Deserialize, Serialize}; use netpurr_core::data::environment::EnvironmentItemValue; use crate::panels::VERTICAL_GAP; use crate::utils; use crate::utils::popup_widget; use crate::widgets::highlight::highlight_template; pub struct HighlightTemplate<'t> { enable: bool, all_space: bool, size: f32, envs: BTreeMap<String, EnvironmentItemValue>, content: &'t mut dyn TextBuffer, popup_id: String, multiline: bool, filter: HashSet<String>, quick_render: bool, } impl HighlightTemplate<'_> { fn find_prompt(&self, input_string: String) -> Option<(String)> { if let Some(start_index) = input_string.rfind("{{") { if let Some(_) = input_string[start_index + 2..].find("}}") { None } else { let result = &input_string[(start_index + 2)..]; Some(result.to_string()) } } else { None } } fn popup(self, ui: &mut Ui, suggest_position: Pos2, response: Response) -> Option<Response> { let popup_id = ui.make_persistent_id(self.popup_id.clone()); let mut popup_open = false; ui.memory_mut(|mem| { if mem.is_popup_open(popup_id) { popup_open = true } }); if !popup_open && !response.has_focus() { return Some(response.clone()); } HTSState::load(ui.ctx(), response.id).map(|hts_state| { hts_state.cursor_range.map(|c| { let len = self.content.as_str().len(); if len <= 1 || c.primary.ccursor.index > len { return; } let before_cursor_text: &String = &self .content .as_str() .chars() .take(c.primary.ccursor.index) .collect(); let after_cursor_text:&String = &self.content.as_str().chars().skip(c.primary.ccursor.index).collect(); if !(after_cursor_text.starts_with(" ")||after_cursor_text.starts_with("\n")){ return; } let prompt_option = self.find_prompt(before_cursor_text.to_string()); if prompt_option.is_some() && self.envs.clone().len() > 0 { let prompt = prompt_option.unwrap_or_default(); ui.memory_mut(|mem| mem.open_popup(popup_id)); let popup_response = popup_widget( ui, popup_id, &response, pos2( suggest_position.x + (c.primary.rcursor.column as f32) * (self.size / 2.0 + 1.0), suggest_position.y + (c.primary.rcursor.row as f32) * (self.size / 2.0 + 1.0) + 16.0, ), |ui| self.render_popup(&response, popup_id, c, prompt, ui), ); let mut tab = false; ui.ctx().input(|i| { if i.key_pressed(Key::Tab) { tab = true; } }); if tab { if let Some(Some(first)) = &popup_response { first.request_focus(); } } } else { ui.memory_mut(|mem| { if mem.is_popup_open(popup_id) { mem.close_popup() } }); } }); }); None } fn render_popup( self, response: &Response, popup_id: Id, c: CursorRange, prompt: String, ui: &mut Ui, ) -> Option<Response> { let mut hovered_label_key = None; let mut first_response = None; ui.horizontal(|ui| { egui::ScrollArea::vertical() .max_width(150.0) .max_height(400.0) .show(ui, |ui| { ui.vertical(|ui| { for (index, (key, _)) in self.envs.clone().iter().enumerate() { if !key.starts_with(prompt.as_str()) { continue; } let label = utils::select_label(ui, RichText::new(key.as_str()).strong()); if label.hovered() { hovered_label_key = Some(key.clone()); } if index == 0 { first_response = Some(label.clone()); } if label.clicked() { self.content.insert_text( (key[prompt.len()..].to_string() + "}}").as_str(), c.primary.ccursor.index, ); ui.memory_mut(|mem| mem.toggle_popup(popup_id)); let mut tes = TextEditState::load(ui.ctx(), response.id).unwrap(); tes.cursor.set_char_range(Some(CCursorRange { primary: CCursor { index: self.content.as_str().len(), prefer_next_row: false, }, secondary: CCursor { index: self.content.as_str().len(), prefer_next_row: false, }, })); tes.store(ui.ctx(), response.id); response.request_focus(); } } }); }); hovered_label_key.clone().map(|key| { ui.separator(); ui.vertical(|ui| { ui.horizontal_wrapped(|ui| { ui.strong("VALUE"); ui.label(self.envs.get(&key).unwrap().value.clone()) }); ui.add_space(VERTICAL_GAP); ui.horizontal(|ui| { ui.strong("TYPE"); ui.label(self.envs.get(&key).unwrap().value_type.to_string()) }); ui.add_space(VERTICAL_GAP); ui.horizontal(|ui| { ui.strong("SCOPE"); ui.label(self.envs.get(&key).unwrap().scope.clone()) }); }); }); }); first_response } } impl Widget for HighlightTemplate<'_> { fn ui(self, ui: &mut Ui) -> Response { let mut layouter = |ui: &Ui, string: &str, wrap_width: f32| { let layout_job = highlight_template(string, self.size, ui, self.envs.clone()); ui.fonts(|f| f.layout_job(layout_job)) }; let filtered_string: String = self .content .as_str() .chars() .filter(|c| !self.filter.contains(c.to_string().as_str())) .collect(); self.content.replace_with(filtered_string.as_str()); let mut text_edit = TextEdit::singleline(self.content).layouter(&mut layouter); if self.multiline { text_edit = TextEdit::multiline(self.content).layouter(&mut layouter); } if self.all_space { text_edit = text_edit.desired_width(f32::INFINITY); } if !self.enable { ui.set_enabled(false); } let mut output = text_edit.show(ui); ui.set_enabled(true); let mut response = output.response.clone(); let text = netpurr_core::utils::replace_variable( self.content.as_str().to_string(), self.envs.clone(), ); if response.hovered() && text.len() > 0 && text != self.content.as_str() &&self.quick_render { response = response.on_hover_text(text); } output.cursor_range.map(|c| { let hts_state = HTSState { cursor_range: Some(c.clone()), }; hts_state.store(ui.ctx(), response.id); }); if let Some(value) = self.popup(ui, output.galley_pos.clone(), response.clone()) { return value; } ui.memory_mut(|mem| { mem.set_focus_lock_filter( response.id, EventFilter { tab: true, horizontal_arrows: true, vertical_arrows: true, escape: true, }, ); }); response } } pub struct HighlightTemplateSinglelineBuilder { enable: bool, all_space: bool, size: f32, multiline: bool, quick_render: bool, filter: HashSet<String>, envs: BTreeMap<String, EnvironmentItemValue>, } impl Default for HighlightTemplateSinglelineBuilder { fn default() -> Self { HighlightTemplateSinglelineBuilder { enable: true, all_space: true, size: 12.0, multiline: false, quick_render: true, filter: Default::default(), envs: BTreeMap::default(), } } } impl HighlightTemplateSinglelineBuilder { pub fn enable(&mut self, enable: bool) -> &mut HighlightTemplateSinglelineBuilder { self.enable = enable; self } pub fn all_space(&mut self, all_space: bool) -> &mut HighlightTemplateSinglelineBuilder { self.all_space = all_space; self } pub fn size(&mut self, size: f32) -> &mut HighlightTemplateSinglelineBuilder { self.size = size; self } pub fn envs( &mut self, envs: BTreeMap<String, EnvironmentItemValue>, ) -> &mut HighlightTemplateSinglelineBuilder { self.envs = envs; self } pub fn multiline(&mut self) -> &mut HighlightTemplateSinglelineBuilder { self.multiline = true; self } pub fn quick_render(&mut self, render:bool) -> &mut HighlightTemplateSinglelineBuilder { self.quick_render = render; self } pub fn filter(&mut self, filter: HashSet<String>) -> &mut HighlightTemplateSinglelineBuilder { self.filter = filter; self } pub fn build<'t>(&'t self, id: String, content: &'t mut dyn TextBuffer) -> HighlightTemplate { HighlightTemplate { enable: self.enable, all_space: self.all_space, size: self.size, envs: self.envs.clone(), content, popup_id: id, quick_render: self.quick_render, multiline: self.multiline, filter: self.filter.clone(), } } } #[derive(Clone, Default, Serialize, Deserialize)] struct HTSState { cursor_range: Option<CursorRange>, } impl HTSState { pub fn load(ctx: &Context, id: Id) -> Option<Self> { ctx.data_mut(|d| d.get_persisted(id)) } pub fn store(self, ctx: &Context, id: Id) { ctx.data_mut(|d| d.insert_persisted(id, self)); } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/windows/import_windows.rs
crates/netpurr/src/windows/import_windows.rs
use std::fs::File; use std::io::Read; use std::path::PathBuf; use egui::{Direction, Layout, Ui}; use strum::IntoEnumIterator; use strum_macros::{Display, EnumIter, EnumString}; use netpurr_core::data::workspace_data::WorkspaceData; use crate::data::config_data::ConfigData; use crate::data::export::{Export, ExportType}; use crate::import::openapi::OpenApi; use crate::import::postman::Postman; use crate::operation::operation::Operation; use crate::operation::windows::{Window, WindowSetting}; use crate::utils; #[derive(Default)] pub struct ImportWindows { open: bool, select_type: ImportType, raw: String, picked_path: Option<PathBuf>, } #[derive(EnumIter, EnumString, Display, PartialEq, Clone)] enum ImportType { File, Raw, } impl Default for ImportType { fn default() -> Self { ImportType::File } } impl Window for ImportWindows { fn window_setting(&self) -> WindowSetting { WindowSetting::new("IMPORT") .modal(true) .max_width(500.0) .max_height(400.0) } fn set_open(&mut self, open: bool) { self.open = open } fn get_open(&self) -> bool { self.open } fn render( &mut self, ui: &mut Ui, config_data: &mut ConfigData, workspace_data: &mut WorkspaceData, operation: Operation, ) { ui.horizontal(|ui| { for import_type in ImportType::iter() { ui.selectable_value( &mut self.select_type, import_type.clone(), import_type.to_string(), ); } }); ui.separator(); match self.select_type { ImportType::File => { ui.with_layout(Layout::centered_and_justified(Direction::TopDown), |ui| { ui.label("Drag and drop Netpurr data or any of the formats below"); }); ui.with_layout(Layout::centered_and_justified(Direction::TopDown), |ui| { ui.label("Postman / OpenAPI"); ui.label("OR"); if ui.button("Upload Files").clicked() { if let Some(path) = rfd::FileDialog::new().pick_file() { if path.is_dir() { operation .add_error_toast("Plural files or folder are not supported"); } else { self.picked_path = Some(path.clone()); } } } }); self.preview_files_being_dropped(ui.ctx()); // Collect dropped files: ui.ctx().input(|i| { if !i.raw.dropped_files.is_empty() { if i.raw.dropped_files.len() > 1 { operation.add_error_toast("Plural files or folder are not supported"); } else { i.raw.dropped_files.clone().first().map(|d| { d.path.clone().map(|path| { if path.is_dir() { operation.add_error_toast( "Plural files or folder are not supported", ); } else { self.picked_path = Some(path.clone()); } }); }); } }; }); match self.process_file(workspace_data, &operation) { Ok(_) => {} Err(e) => { operation.add_error_toast(e.to_string()); } } } ImportType::Raw => { egui::ScrollArea::vertical() .max_height(400.0) .show(ui, |ui| { utils::text_edit_multiline_justify(ui, &mut self.raw); if ui.button("Continue").clicked() { match self.process_raw(self.raw.clone(), workspace_data, &operation) { Ok(_) => {} Err(e) => operation.add_error_toast(e.to_string()), } } }); } } } } impl ImportWindows { fn process_raw( &mut self, mut content: String, workspace_data: &mut WorkspaceData, operation: &Operation, ) -> anyhow::Result<()> { content = content.trim_start().to_string(); if content.starts_with("{") { let export_result = serde_json::from_str::<Export>(content.as_str()); match export_result { Ok(export) => { Self::process_export(content, workspace_data, operation, export); } Err(_) => { Self::import_final(content, operation); } } } else { let export_result = serde_yaml::from_str::<Export>(content.as_str()); match export_result { Ok(export) => { Self::process_export(content, workspace_data, operation, export); } Err(_) => { Self::import_final(content, operation); } } } Ok(()) } fn process_export( content: String, workspace_data: &mut WorkspaceData, operation: &Operation, export: Export, ) { match export.export_type { ExportType::Collection => { export.collection.map(|c| { let new_name = workspace_data.import_collection(c); operation .add_success_toast(format!("Import collections `{}` success.", new_name)); }); } ExportType::Request => {} ExportType::Environment => {} ExportType::None => { if export.openapi.is_some() { Self::import_openapi(content, workspace_data, operation) } else if export.info.is_some() { Self::import_postman(content, workspace_data, operation); } } } } fn import_postman(content: String, workspace_data: &mut WorkspaceData, operation: &Operation) { let postman_result = Postman::try_import(content.clone()); match postman_result { Ok(postman) => match postman.to_collection() { Ok(collection) => { let new_name = workspace_data.import_collection(collection); operation .add_success_toast(format!("Import collections `{}` success.", new_name)); } Err(_) => Self::import_final(content, operation), }, Err(_) => Self::import_final(content, operation), } } fn import_openapi(content: String, workspace_data: &mut WorkspaceData, operation: &Operation) { let openapi_result = OpenApi::try_import(content.clone()); match openapi_result { Ok(openapi) => match openapi.to_collection() { Ok(collection) => { // openapi导入不需要导入请求 collection.folder.borrow_mut().requests.clear(); collection.folder.borrow_mut().folders.clear(); let new_name = workspace_data.import_collection(collection); operation .add_success_toast(format!("Import collections `{}` success.", new_name)); } Err(_) => Self::import_final(content, operation), }, Err(_) => Self::import_final(content, operation), } } fn import_final(content: String, operation: &Operation) { operation.add_error_toast("Error while importing: format not recognized"); } fn process_file( &mut self, workspace_data: &mut WorkspaceData, operation: &Operation, ) -> anyhow::Result<()> { if let Some(path) = &self.picked_path { let mut file = File::open(path)?; let mut content = String::new(); file.read_to_string(&mut content)?; self.process_raw(content, workspace_data, operation)?; } self.picked_path = None; Ok(()) } fn preview_files_being_dropped(&self, ctx: &egui::Context) { use egui::*; use std::fmt::Write as _; if !ctx.input(|i| i.raw.hovered_files.is_empty()) { let text = ctx.input(|i| { let mut text = "Dropping files:\n".to_owned(); if i.raw.hovered_files.len() > 1 { text = "Plural files or folder are not supported".to_owned(); } else { let file_option = i.raw.hovered_files.first(); match file_option { None => {} Some(file) => { if let Some(path) = &file.path { write!(text, "\n{}", path.display()).ok(); } else if !file.mime.is_empty() { write!(text, "\n{}", file.mime).ok(); } else { text += "\n???"; } } } } text }); let painter = ctx.layer_painter(LayerId::new(Order::Foreground, Id::new("file_drop_target"))); let screen_rect = ctx.screen_rect(); painter.rect_filled(screen_rect, 0.0, Color32::from_black_alpha(192)); painter.text( screen_rect.center(), Align2::CENTER_CENTER, text, TextStyle::Heading.resolve(&ctx.style()), Color32::WHITE, ); } } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/windows/test_script_windows.rs
crates/netpurr/src/windows/test_script_windows.rs
use egui::Ui; use poll_promise::Promise; use netpurr_core::data::workspace_data::WorkspaceData; use netpurr_core::script::{Context, ScriptScope}; use crate::data::config_data::ConfigData; use crate::operation::operation::Operation; use crate::operation::windows::{Window, WindowSetting}; use crate::utils; #[derive(Default)] pub struct TestScriptWindows { test_windows_open: bool, script_scopes: Vec<ScriptScope>, context: Option<Context>, run_result: Option<Promise<Result<Context, anyhow::Error>>>, } impl Window for TestScriptWindows { fn window_setting(&self) -> WindowSetting { WindowSetting::new("TEST SCRIPT") .modal(true) .max_width(500.0) .min_height(400.0) .max_height(400.0) .collapsible(false) .resizable(true) } fn set_open(&mut self, open: bool) { self.test_windows_open = open; } fn get_open(&self) -> bool { self.test_windows_open } fn render( &mut self, ui: &mut Ui, _: &mut ConfigData, _: &mut WorkspaceData, operation: Operation, ) { ui.vertical(|ui| match &self.run_result { None => { if ui.button("Run Script").clicked() { if let Some(context) = &self.context { self.run_result = Some(operation.run_script(self.script_scopes.clone(), context.clone())); } } ui.separator(); } Some(result) => { ui.add_enabled_ui(false, |ui| { ui.button("Run Script"); ui.separator(); }); match result.ready() { None => { ui.ctx().request_repaint(); } Some(js_run_result) => match js_run_result { Ok(new_context) => { Self::render_logs(ui, new_context); } Err(e) => { ui.strong("Run Error:"); let mut msg = e.to_string(); utils::text_edit_multiline_justify(ui, &mut msg); } }, } } }); } } impl TestScriptWindows { pub fn with(mut self, script_scopes: Vec<ScriptScope>, context: Context) -> Self { self.test_windows_open = true; self.script_scopes = script_scopes; self.context = Some(context); self.run_result = None; self } } impl TestScriptWindows { fn render_logs(ui: &mut Ui, new_context: &Context) { let theme = egui_extras::syntax_highlighting::CodeTheme::from_memory(ui.ctx()); let mut layouter = |ui: &Ui, string: &str, wrap_width: f32| { let mut layout_job = egui_extras::syntax_highlighting::highlight(ui.ctx(), &theme, string, "log"); layout_job.wrap.max_width = wrap_width; ui.fonts(|f| f.layout_job(layout_job)) }; if new_context.logger.logs.len() > 0 { ui.strong("Output Log:"); ui.push_id("log_info", |ui| { egui::ScrollArea::vertical() .min_scrolled_height(300.0) .max_height(400.0) .show(ui, |ui| { for log in new_context.logger.logs.iter() { let mut content = format!("> {}", log.show()); egui::TextEdit::multiline(&mut content) .font(egui::TextStyle::Monospace) .code_editor() .desired_rows(1) .lock_focus(true) .desired_width(f32::INFINITY) .layouter(&mut layouter) .show(ui); } }); }); } } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/windows/request_close_windows.rs
crates/netpurr/src/windows/request_close_windows.rs
use egui::Ui; use netpurr_core::data::workspace_data::WorkspaceData; use crate::data::config_data::ConfigData; use crate::operation::operation::Operation; use crate::operation::windows::{Window, WindowSetting}; use crate::panels::VERTICAL_GAP; use crate::windows::save_windows::SaveWindows; #[derive(Default)] pub struct RequestCloseWindows { windows_open: bool, crt_id: String, tab_name: String, } impl Window for RequestCloseWindows { fn window_setting(&self) -> WindowSetting { WindowSetting::new("DO YOU WANT TO SAVE?") .modal(true) .max_width(400.0) .min_height(400.0) .max_height(400.0) .collapsible(false) .resizable(true) } fn set_open(&mut self, open: bool) { self.windows_open = open; } fn get_open(&self) -> bool { self.windows_open } fn render( &mut self, ui: &mut Ui, _: &mut ConfigData, workspace_data: &mut WorkspaceData, operation: Operation, ) { ui.label(format!("This tab `{}` has unsaved changes which will be lost if you choose to close it. Save these changes to avoid losing your work.", self.tab_name)); ui.add_space(VERTICAL_GAP); ui.horizontal(|ui| { if ui.button("Don't Save").clicked() { workspace_data.close_crt(self.crt_id.clone()); self.set_open(false); } if ui.button("Cancel").clicked() { self.set_open(false); } ui.add_space(ui.available_width() - 100.0); if ui.button("Save change").clicked() { self.save_tab(workspace_data, &operation); self.set_open(false); } }); } } impl RequestCloseWindows { pub fn with(mut self, crt_id: String, tab_name: String) -> Self { self.windows_open = true; self.crt_id = crt_id; self.tab_name = tab_name; self } } impl RequestCloseWindows { pub fn set_and_render( &mut self, ui: &mut Ui, operation: &Operation, workspace_data: &mut WorkspaceData, ) { operation.lock_ui("request_close".to_string(), self.windows_open); let mut windows_open = self.windows_open; egui::Window::new("DO YOU WANT TO SAVE?") .default_open(true) .max_width(400.0) .min_height(400.0) .max_height(400.0) .collapsible(false) .resizable(true) .open(&mut windows_open) .show(ui.ctx(), |ui| { ui.label(format!("This tab `{}` has unsaved changes which will be lost if you choose to close it. Save these changes to avoid losing your work.", self.tab_name)); ui.add_space(VERTICAL_GAP); ui.horizontal(|ui| { if ui.button("Don't Save").clicked() { workspace_data.close_crt(self.crt_id.clone()); self.windows_open = false; } if ui.button("Cancel").clicked() { self.windows_open = false; } ui.add_space(ui.available_width() - 100.0); if ui.button("Save change").clicked() { self.save_tab(workspace_data, operation); self.windows_open = false; } }); }); if self.windows_open { self.windows_open = windows_open; } } fn save_tab(&self, workspace_data: &mut WorkspaceData, operation: &Operation) { let crt_option = workspace_data.get_crt_cloned(self.crt_id.clone()); crt_option.map(|crt| match &crt.collection_path { None => { operation.add_window(Box::new(SaveWindows::default().with( crt.record.clone(), None, false, ))); } Some(collection_path) => { workspace_data.save_crt(self.crt_id.clone(), collection_path.clone(), |_| {}); operation.add_success_toast("Save success."); } }); } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/windows/save_windows.rs
crates/netpurr/src/windows/save_windows.rs
use std::cell::RefCell; use std::collections::BTreeMap; use std::rc::Rc; use egui::{Align, Button, Layout, ScrollArea, Ui}; use netpurr_core::data::collections::{Collection, CollectionFolder}; use netpurr_core::data::record::Record; use netpurr_core::data::workspace_data::WorkspaceData; use crate::data::config_data::ConfigData; use crate::operation::operation::Operation; use crate::operation::windows::{Window, WindowSetting}; use crate::panels::VERTICAL_GAP; use crate::utils; #[derive(Default)] pub struct SaveWindows { save_windows_open: bool, record: Record, select_collection_path: Option<String>, add_collection: bool, add_folder: bool, add_name: String, title: String, id: String, edit: bool, old_name: String, record_name:String, record_desc:String, } impl Window for SaveWindows { fn window_setting(&self) -> WindowSetting { WindowSetting::new(self.title.clone()) .max_width(500.0) .default_height(400.0) .collapsible(false) .resizable(true) } fn set_open(&mut self, open: bool) { self.save_windows_open = open; } fn get_open(&self) -> bool { self.save_windows_open } fn render( &mut self, ui: &mut Ui, _: &mut ConfigData, workspace_data: &mut WorkspaceData, operation: Operation, ) { ui.label("Requests in Netpurr are saved in collections (a group of requests)."); ui.add_space(VERTICAL_GAP); ui.label("Request name"); self.record_name = self.record.name(); self.record_desc = self.record.desc(); utils::text_edit_singleline_filter_justify(ui, &mut self.record_name); self.record.set_name(self.record_name.clone()); ui.add_space(VERTICAL_GAP); ui.label("Request description (Optional)"); utils::text_edit_multiline_justify(ui, &mut self.record_desc); self.record.set_desc(self.record_desc.clone()); ui.add_space(VERTICAL_GAP); if !self.edit { ui.label("Select a collection or folder to save to:"); ui.add_space(VERTICAL_GAP); self.render(workspace_data, ui); ui.add_space(VERTICAL_GAP); } self.render_save_bottom_panel(workspace_data, ui); } } impl SaveWindows { pub fn with(mut self, record: Record, default_path: Option<String>, edit: bool) -> Self { self.save_windows_open = true; self.record = record; self.old_name = self.record.name(); if self.record.name() == "" { self.record.set_name(self.record.base_url()); } else { self.record.set_name(self.record.name()); } self.add_folder = false; self.add_collection = false; self.add_name = "".to_string(); self.edit = edit; match &default_path { None => { self.title = "SAVE REQUEST".to_string(); } Some(_) => { if !edit { self.title = "SAVE AS REQUEST".to_string(); } else { self.title = "EDIT REQUEST".to_string(); } } } self.select_collection_path = default_path.clone(); self.id = default_path.clone().unwrap_or("new".to_string()); self } fn render(&mut self, workspace_data: &mut WorkspaceData, ui: &mut Ui) { ui.vertical(|ui| { ui.horizontal(|ui| match &self.select_collection_path { None => { ui.label("All Collections"); ui.with_layout(Layout::right_to_left(Align::Center), |ui| { if ui.link("+ Create Collection").clicked() { self.add_collection = true; }; }); } Some(name) => { if ui.link(format!("{} {}",egui_phosphor::regular::ARROW_LEFT, name)).clicked() { self.add_folder = false; self.add_collection = false; let paths: Vec<&str> = name.split("/").collect(); if paths.len() == 1 { self.select_collection_path = None; } else { let new_paths = &paths[0..paths.len() - 1]; self.select_collection_path = Some(new_paths.join("/")); } } ui.with_layout(Layout::right_to_left(Align::Center), |ui| { if ui.link("+ Create Folder").clicked() { self.add_folder = true; }; }); } }); ui.add_space(VERTICAL_GAP); if self.add_collection { self.add_folder = false; self.render_add_collection(workspace_data, ui); } if self.add_folder { self.add_collection = false; self.render_add_folder(workspace_data, ui); } self.render_list(workspace_data, ui); }); } fn render_list(&mut self, workspace_data: &mut WorkspaceData, ui: &mut Ui) { ScrollArea::vertical().max_height(200.0).show(ui, |ui| { match self.select_collection_path.clone() { None => { for (name, collection) in workspace_data.get_collections().iter() { if utils::select_label(ui, name).clicked() { self.add_folder = false; self.add_collection = false; self.select_collection_path = Some(collection.folder.borrow().name.to_string()); } } } Some(path) => { workspace_data .get_folder_with_path(path.clone()) .1 .map(|cf| { for (name, cf_child) in cf.borrow().folders.iter() { if utils::select_label(ui, name.clone()).clicked() { self.add_folder = false; self.add_collection = false; self.select_collection_path = Some(path.clone() + "/" + cf_child.borrow().name.as_str()) } } ui.set_enabled(false); for (_, hr) in cf.borrow().requests.iter() { utils::select_label( ui, utils::build_rest_ui_header(hr.clone(), None, ui), ); } }); } } }); } fn render_add_folder(&mut self, workspace_data: &mut WorkspaceData, ui: &mut Ui) { ui.horizontal(|ui| { match &self.select_collection_path { None => {} Some(path) => { let (_, option) = workspace_data.get_folder_with_path(path.clone()); match option { None => {} Some(folder) => { if folder.borrow().folders.contains_key(self.add_name.as_str()) { ui.set_enabled(false); } } } } } if ui.button("+").clicked() { match &self.select_collection_path { None => {} Some(path) => { let (collection_name, option) = workspace_data.get_folder_with_path(path.clone()); match option { None => {} Some(folder) => { workspace_data.collection_insert_folder( folder.clone(), Rc::new(RefCell::new(CollectionFolder { name: self.add_name.to_string(), parent_path: path.clone(), desc: "".to_string(), auth: Default::default(), is_root: false, requests: Default::default(), folders: Default::default(), pre_request_script: "".to_string(), test_script: "".to_string(), testcases: Default::default(), })), ); } } } } self.add_name = "".to_string(); self.add_folder = false; } utils::text_edit_singleline_filter_justify(ui, &mut self.add_name); }); } fn render_add_collection(&mut self, workspace_data: &mut WorkspaceData, ui: &mut Ui) { ui.horizontal(|ui| { if workspace_data .get_collections() .contains_key(self.add_name.as_str()) { ui.add_enabled(false, Button::new("+")); } else { if ui.button("+").clicked() { workspace_data.add_collection(Collection { folder: Rc::new(RefCell::new(CollectionFolder { name: self.add_name.clone(), parent_path: ".".to_string(), desc: "".to_string(), auth: Default::default(), is_root: true, requests: Default::default(), folders: BTreeMap::default(), pre_request_script: "".to_string(), test_script: "".to_string(), testcases: Default::default(), })), ..Default::default() }); self.add_name = "".to_string(); self.add_collection = false; } } utils::text_edit_singleline_filter_justify(ui, &mut self.add_name); }); } fn render_save_bottom_panel(&mut self, workspace_data: &mut WorkspaceData, ui: &mut Ui) { egui::TopBottomPanel::bottom("save_bottom_panel_".to_string() + self.id.as_str()) .resizable(false) .min_height(0.0) .show_inside(ui, |ui| { ui.add_space(VERTICAL_GAP); ui.with_layout(Layout::right_to_left(Align::Center), |ui| { match &self.select_collection_path { None => { ui.add_enabled_ui(false, |ui| { ui.button("Save"); }); } Some(collection_path) => { let mut ui_enable = true; if self.record.name().is_empty() { ui_enable = false; } let button_name = "Save to ".to_string() + collection_path.split("/").last().unwrap_or_default(); let (_, option) = workspace_data.get_folder_with_path(collection_path.clone()); match &option { None => {} Some(cf) => { if self.edit && self.old_name == self.record.name() { ui_enable = true; } else { if cf .borrow() .requests .contains_key(self.record.name().as_str()) { ui_enable = false; } } } } ui.add_enabled_ui(ui_enable, |ui| { if ui.button(button_name).clicked() { match &option { None => {} Some(cf) => { if self.edit { workspace_data.collection_remove_http_record( cf.clone(), self.old_name.clone(), ) } workspace_data.collection_insert_record( cf.clone(), self.record.clone(), ); workspace_data.update_crt_old_name_to_new_name( collection_path.clone(), self.old_name.clone(), self.record.name(), ); } } self.save_windows_open = false; } }); if ui.button("Cancel").clicked() { self.save_windows_open = false; } } } }); }); } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/windows/new_collection_windows.rs
crates/netpurr/src/windows/new_collection_windows.rs
use std::cell::RefCell; use std::default::Default; use std::rc::Rc; use egui::{Align, Button, Checkbox, Layout, TextEdit, Ui, Widget}; use egui_extras::{Column, TableBuilder}; use strum::IntoEnumIterator; use strum_macros::{Display, EnumIter, EnumString}; use netpurr_core::data::auth::{Auth, AuthType}; use netpurr_core::data::collections::{Collection, CollectionFolder}; use netpurr_core::data::environment::EnvironmentItem; use netpurr_core::data::workspace_data::WorkspaceData; use crate::data::config_data::ConfigData; use crate::operation::operation::Operation; use crate::operation::windows::{Window, WindowSetting}; use crate::panels::auth_panel::AuthPanel; use crate::panels::request_pre_script_panel::RequestPreScriptPanel; use crate::panels::test_script_panel::TestScriptPanel; use crate::panels::VERTICAL_GAP; use crate::utils; use crate::utils::HighlightValue; #[derive(Default)] pub struct NewCollectionWindows { title_name: String, new_select_env_item: EnvironmentItem, new_collection_windows_open: bool, new_collection: Collection, old_collection_name: Option<String>, old_folder_name: Option<String>, folder: Rc<RefCell<CollectionFolder>>, parent_folder: Option<Rc<RefCell<CollectionFolder>>>, new_collection_content_type: NewCollectionContentType, auth_panel: AuthPanel, request_pre_script_panel: RequestPreScriptPanel, test_script_panel: TestScriptPanel, search_input: String, } #[derive(Clone, EnumString, EnumIter, PartialEq, Display)] enum NewCollectionContentType { Description, Authorization, Variables, } impl Default for NewCollectionContentType { fn default() -> Self { NewCollectionContentType::Description } } impl Window for NewCollectionWindows { fn window_setting(&self) -> WindowSetting { WindowSetting::new(self.title_name.clone()) .modal(true) .max_width(800.0) .min_width(500.0) .max_height(600.0) .collapsible(false) .resizable(true) } fn set_open(&mut self, open: bool) { self.new_collection_windows_open = open; } fn get_open(&self) -> bool { self.new_collection_windows_open } fn render( &mut self, ui: &mut Ui, config_data: &mut ConfigData, workspace_data: &mut WorkspaceData, operation: Operation, ) { ui.label("Name"); utils::text_edit_singleline_filter_justify(ui, &mut self.folder.borrow_mut().name); let parent_auth = workspace_data.get_path_parent_auth(self.folder.borrow().parent_path.clone()); ui.horizontal(|ui| { for x in NewCollectionContentType::iter() { if x == NewCollectionContentType::Variables && self.parent_folder.is_some() { continue; } ui.selectable_value( &mut self.new_collection_content_type, x.clone(), utils::build_with_count_ui_header( x.to_string(), NewCollectionWindows::get_count( self.folder.clone(), x, &parent_auth, self.new_collection.envs.items.len(), ), ui, ), ); } }); ui.add_space(VERTICAL_GAP); match &self.new_collection_content_type { NewCollectionContentType::Description => { self.build_desc(ui); } NewCollectionContentType::Authorization => { self.build_auth(ui); } NewCollectionContentType::Variables => { self.build_variables(ui); } } self.bottom_panel(workspace_data, ui); } } impl NewCollectionWindows { fn get_count( cf: Rc<RefCell<CollectionFolder>>, panel_enum: NewCollectionContentType, parent_auth: &Auth, vars: usize, ) -> HighlightValue { match panel_enum { NewCollectionContentType::Description => { if cf.borrow().desc.is_empty() { HighlightValue::None } else { HighlightValue::Has } } NewCollectionContentType::Authorization => { match cf.borrow().auth.get_final_type(parent_auth.clone()) { AuthType::InheritAuthFromParent => HighlightValue::None, AuthType::NoAuth => HighlightValue::None, AuthType::BearerToken => HighlightValue::Has, AuthType::BasicAuth => HighlightValue::Has, } } NewCollectionContentType::Variables => HighlightValue::Usize(vars), } } pub fn with_open_collection(mut self, collection: Option<Collection>) -> Self { self.new_collection_windows_open = true; match collection { None => { self.new_collection = Collection::default(); self.new_collection.folder.borrow_mut().is_root = true; self.new_collection.folder.borrow_mut().parent_path = ".".to_string(); self.title_name = "CREATE A NEW COLLECTION".to_string(); } Some(collection) => { self.new_collection = collection.duplicate(collection.folder.borrow().name.clone()); self.old_collection_name = Some(self.new_collection.folder.borrow().name.clone()); self.title_name = "EDIT COLLECTION".to_string(); } } self.new_collection_content_type = NewCollectionContentType::Description; self.folder = self.new_collection.folder.clone(); self.parent_folder = None; self } pub fn with_open_folder( mut self, collection: Collection, parent_folder: Rc<RefCell<CollectionFolder>>, folder: Option<Rc<RefCell<CollectionFolder>>>, ) -> Self { self.new_collection_windows_open = true; match folder { None => { self.new_collection = collection; self.title_name = "CREATE A NEW FOLDER".to_string(); self.folder = Rc::new(RefCell::new(CollectionFolder::default())); } Some(cf) => { self.new_collection = collection; self.old_folder_name = Some(cf.borrow().name.clone()); self.title_name = "EDIT FOLDER".to_string(); self.folder = Rc::new(RefCell::new( cf.borrow().duplicate(cf.borrow().name.clone()), )); } } self.parent_folder = Some(parent_folder.clone()); self.new_collection_content_type = NewCollectionContentType::Description; self } fn build_variables(&mut self, ui: &mut Ui) { ui.label("These variables are specific to this collection and its requests. "); ui.add_space(VERTICAL_GAP); ui.separator(); ui.add_space(VERTICAL_GAP); let mut delete_index = None; ui.push_id("new_collection_environment_table", |ui| { let table = TableBuilder::new(ui) .resizable(false) .cell_layout(Layout::left_to_right(Align::Center)) .column(Column::auto()) .column(Column::exact(20.0)) .column(Column::initial(200.0).range(40.0..=300.0)) .column(Column::remainder()) .max_scroll_height(400.0); table .header(20.0, |mut header| { header.col(|ui| { ui.strong(""); }); header.col(|ui| { ui.strong(""); }); header.col(|ui| { ui.strong("VARIABLE"); }); header.col(|ui| { ui.strong("VALUE"); }); }) .body(|mut body| { for (index, item) in self.new_collection.envs.items.iter_mut().enumerate() { body.row(18.0, |mut row| { row.col(|ui| { ui.checkbox(&mut item.enable, ""); }); row.col(|ui| { if ui.button("x").clicked() { delete_index = Some(index) } }); row.col(|ui| { ui.text_edit_singleline(&mut item.key); }); row.col(|ui| { TextEdit::singleline(&mut item.value) .desired_width(f32::INFINITY) .ui(ui); }); }); } body.row(18.0, |mut row| { row.col(|ui| { ui.add_enabled( false, Checkbox::new(&mut self.new_select_env_item.enable, ""), ); }); row.col(|ui| { ui.add_enabled(false, Button::new("x")); }); row.col(|ui| { ui.text_edit_singleline(&mut self.new_select_env_item.key); }); row.col(|ui| { TextEdit::singleline(&mut self.new_select_env_item.value) .desired_width(f32::INFINITY) .ui(ui); }); }); }); }); if delete_index.is_some() { self.new_collection.envs.items.remove(delete_index.unwrap()); } if self.new_select_env_item.key != "" || self.new_select_env_item.value != "" { self.new_select_env_item.enable = true; self.new_collection .envs .items .push(self.new_select_env_item.clone()); self.new_select_env_item.key = "".to_string(); self.new_select_env_item.value = "".to_string(); self.new_select_env_item.enable = false; } } fn build_auth(&mut self, ui: &mut Ui) { ui.label("This authorization method will be used for every request in this collection. You can override this by specifying one in the request."); ui.add_space(VERTICAL_GAP); ui.separator(); ui.add_space(VERTICAL_GAP); self.auth_panel .set_collection_folder(self.new_collection.clone(), self.folder.clone()); self.auth_panel .set_and_render(ui, &mut self.folder.borrow_mut().auth); } fn build_desc(&mut self, ui: &mut Ui) { ui.label("This description will show in your collection’s documentation, along with the descriptions of its folders and requests."); ui.add_space(VERTICAL_GAP); ui.separator(); ui.add_space(VERTICAL_GAP); utils::text_edit_multiline_justify(ui, &mut self.folder.borrow_mut().desc); ui.add_space(VERTICAL_GAP); } fn bottom_panel(&mut self, workspace_data: &mut WorkspaceData, ui: &mut Ui) { egui::TopBottomPanel::bottom("new_collection_bottom_panel") .resizable(false) .min_height(0.0) .show_inside(ui, |ui| { ui.add_space(VERTICAL_GAP); ui.with_layout(Layout::right_to_left(Align::Center), |ui| { if ui.button("Cancel").clicked() { self.new_collection_windows_open = false; } let name = self.new_collection.folder.borrow().name.clone(); if name != "" { match &self.parent_folder { None => match &self.old_collection_name { None => { if workspace_data .get_collections() .contains_key(self.folder.borrow().name.as_str()) { ui.set_enabled(false) } } Some(old_name) => { if old_name != self.folder.borrow().name.as_str() && workspace_data .get_collections() .contains_key(self.folder.borrow().name.as_str()) { ui.set_enabled(false); } } }, Some(parent_folder) => match &self.old_folder_name { None => { if parent_folder .borrow() .folders .contains_key(self.folder.borrow().name.as_str()) { ui.set_enabled(false); } } Some(old_name) => { if old_name != self.folder.borrow().name.as_str() && parent_folder .borrow() .folders .contains_key(self.folder.borrow().name.as_str()) { ui.set_enabled(false); } } }, } if ui.button("Save").clicked() { self.new_collection_windows_open = false; let parent_folder = self.parent_folder.clone(); match parent_folder { None => { // means save collection self.save_collection(workspace_data); } Some(parent_folder) => { // means save folder self.save_folder(workspace_data, parent_folder); } } } ui.set_enabled(true); } else { ui.set_enabled(false); ui.button("Save"); ui.set_enabled(true); } }); }); } fn save_folder( &mut self, workspace_data: &mut WorkspaceData, parent_folder: Rc<RefCell<CollectionFolder>>, ) { match &self.old_folder_name { None => { // means add new folder workspace_data.add_folder(parent_folder.clone(), self.folder.clone()); } Some(old_name) => { // means edit old folder workspace_data.update_folder_info( old_name.clone(), parent_folder.clone(), self.folder.clone(), ); } } } fn save_collection(&mut self, workspace_data: &mut WorkspaceData) { match &self.old_collection_name { None => { // means add new collection workspace_data.add_collection(self.new_collection.clone()); } Some(old_name) => { // means edit old collection workspace_data .update_collection_info(old_name.clone(), self.new_collection.clone()); } } } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/windows/mod.rs
crates/netpurr/src/windows/mod.rs
pub mod cookies_windows; pub mod environment_windows; pub mod import_windows; pub mod manager_testcase_window; pub mod new_collection_windows; pub mod request_close_windows; pub mod save_crt_windows; pub mod save_windows; pub mod test_script_windows; pub mod view_json_windows; pub mod workspace_windows;
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/windows/cookies_windows.rs
crates/netpurr/src/windows/cookies_windows.rs
use std::collections::BTreeSet; use eframe::emath::Align; use egui::{Button, Layout, ScrollArea, Ui}; use netpurr_core::data::cookies_manager::Cookie; use netpurr_core::data::workspace_data::WorkspaceData; use crate::data::config_data::ConfigData; use crate::operation::operation::Operation; use crate::operation::windows::{Window, WindowSetting}; use crate::panels::VERTICAL_GAP; use crate::utils; pub struct CookiesWindows { cookies_windows_open: bool, new_cookie_name: String, new_key_name: String, select_domain_name: Option<String>, select_key_name: Option<String>, select_content: String, new_cookie_names: BTreeSet<String>, } impl Default for CookiesWindows { fn default() -> Self { CookiesWindows { cookies_windows_open: false, new_cookie_name: "".to_string(), new_key_name: "".to_string(), select_domain_name: None, select_key_name: None, select_content: "".to_string(), new_cookie_names: Default::default(), } } } impl Window for CookiesWindows { fn window_setting(&self) -> WindowSetting { WindowSetting::new("MANAGE COOKIES") .max_width(500.0) .min_height(400.0) .max_height(400.0) .collapsible(false) .resizable(true) .modal(true) } fn set_open(&mut self, open: bool) { self.cookies_windows_open = open; } fn get_open(&self) -> bool { self.cookies_windows_open } fn render( &mut self, ui: &mut Ui, _: &mut ConfigData, workspace_data: &mut WorkspaceData, operation: Operation, ) { ui.vertical(|ui| { ui.add_space(VERTICAL_GAP); self.render_add(workspace_data, ui); ui.add_space(VERTICAL_GAP); ui.separator(); self.render_domain_list(workspace_data, ui); ui.add_space(VERTICAL_GAP); ui.separator(); self.render_key_list(workspace_data, &operation, ui); ui.add_space(VERTICAL_GAP); ui.separator(); self.render_content(workspace_data, &operation, ui); }); } } impl CookiesWindows { fn render_add(&mut self, workspace_data: &mut WorkspaceData, ui: &mut Ui) { ui.label("Add a cookie domain."); ui.horizontal(|ui| { utils::text_edit_singleline_justify(ui, &mut self.new_cookie_name); if self.new_cookie_name == "" || workspace_data.cookies_contain_domain(self.new_cookie_name.clone()) { ui.set_enabled(false); } if ui.button("Add").clicked() { self.new_cookie_names.insert(self.new_cookie_name.clone()); self.new_cookie_name = "".to_string(); } ui.set_enabled(true); }); } fn render_domain_list(&mut self, workspace_data: &mut WorkspaceData, ui: &mut Ui) { ui.horizontal(|ui| { let mut names = workspace_data.get_cookie_domains(); for new_names in self.new_cookie_names.iter() { names.push(new_names.clone()); } for name in names { let response = ui.selectable_value( &mut self.select_domain_name, Some(name.to_string()), name.as_str(), ); if response.clicked() { self.select_key_name = None; } response.context_menu(|ui| { if ui.button("Remove").clicked() { workspace_data.remove_cookie_domain(name.clone()); self.new_cookie_names.remove(name.as_str()); ui.close_menu(); } }); } }); } fn render_key_list( &mut self, workspace_data: &mut WorkspaceData, operation: &Operation, ui: &mut Ui, ) { ScrollArea::vertical() .max_height(200.0) .show(ui, |ui| match &self.select_domain_name { None => {} Some(domain) => { ui.horizontal(|ui| { if self.new_key_name == "" || workspace_data.cookies_contain_domain_key( domain.clone(), self.new_key_name.clone(), ) { ui.add_enabled(false, Button::new("+")); } else { if ui.button("+").clicked() { match workspace_data.add_domain_cookies(Cookie { name: self.new_key_name.clone(), value: "NONE".to_string(), domain: domain.clone(), path: "/".to_string(), expires: "".to_string(), max_age: "".to_string(), raw: format!( "{}={}; path=/; domain={}", self.new_key_name, "NONE", domain ), http_only: false, secure: false, }) { Ok(_) => { self.new_cookie_names.remove(domain.as_str()); } Err(err) => { operation.add_error_toast(err); } } self.new_key_name = "".to_string(); } } utils::text_edit_singleline_filter_justify(ui, &mut self.new_key_name); }); let option_cookies = workspace_data.get_domain_cookies(domain.to_string()); match option_cookies { None => {} Some(cookies) => { for (name, c) in cookies.iter() { ui.vertical(|ui| { let response = utils::select_value( ui, &mut self.select_key_name, Some(name.clone()), name, ); if response.clicked() { self.select_domain_name.clone().map(|domain| { self.select_content = c.raw.clone(); }); } response.context_menu(|ui| { if ui.button("Remove").clicked() { workspace_data.remove_cookie_domain_path_name( domain.to_string(), c.path.clone(), name.clone(), ); ui.close_menu(); } }); }); } } } } }); } fn render_content( &mut self, workspace_data: &mut WorkspaceData, operation: &Operation, ui: &mut Ui, ) { match &self.select_domain_name { None => {} Some(domain) => { let option_map = workspace_data.get_domain_cookies(domain.to_string()); option_map.map(|map| match &self.select_key_name { None => {} Some(key) => { let cookie = map.get(key); cookie.map(|c| { utils::text_edit_multiline_justify(ui, &mut self.select_content); ui.add_space(VERTICAL_GAP); ui.with_layout(Layout::right_to_left(Align::TOP), |ui| { let new_cookie = Cookie::from_raw(self.select_content.clone()); if ui.button("Remove").clicked() { workspace_data.remove_cookie_domain_path_name( domain.clone(), c.path.clone(), key.clone(), ); } if ui.button("Save").clicked() { match workspace_data.update_domain_cookies( new_cookie, c.domain.clone(), c.name.clone(), ) { Ok(_) => { operation.add_success_toast("Update cookie success."); } Err(err) => { operation.add_error_toast(err); } } } ui.set_enabled(true); }); }); } }); } } } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/windows/manager_testcase_window.rs
crates/netpurr/src/windows/manager_testcase_window.rs
use std::collections::{BTreeMap, HashMap}; use egui::{Color32, RichText, Ui}; use serde_json::Value; use egui_code_editor::{CodeEditor, ColorTheme}; use netpurr_core::data::collections::Testcase; use netpurr_core::data::workspace_data::WorkspaceData; use crate::data::config_data::ConfigData; use crate::operation::operation::Operation; use crate::operation::windows::{Window, WindowSetting}; use crate::panels::test_script_panel::CrtOrFolder; use crate::utils; use crate::widgets::syntax::js_syntax; #[derive(Default)] pub struct ManagerTestcaseWindows { open: bool, crt_or_folder: Option<CrtOrFolder>, select: Option<String>, new_case_name: String, source: String, message: RichText, } impl ManagerTestcaseWindows { pub fn with_crt_or_folder(mut self, crt_or_folder: CrtOrFolder) -> Self { self.crt_or_folder = Some(crt_or_folder); self } } impl Window for ManagerTestcaseWindows { fn window_setting(&self) -> WindowSetting { WindowSetting::new("MANAGER TESTCASE") .modal(true) .min_width(800.0) .max_width(800.0) .max_height(400.0) } fn set_open(&mut self, open: bool) { self.open = open } fn get_open(&self) -> bool { self.open } fn render( &mut self, ui: &mut Ui, config_data: &mut ConfigData, workspace_data: &mut WorkspaceData, operation: Operation, ) { let mut testcases = BTreeMap::new(); if let Some(crt_or_folder) = &self.crt_or_folder { match crt_or_folder { CrtOrFolder::CRT(crt_id) => { testcases = workspace_data .must_get_crt(crt_id.clone()) .record .testcase() } CrtOrFolder::Folder(folder) => { testcases = folder.borrow().testcases.clone(); } } egui::panel::SidePanel::left("manager_testcase_left") .max_width(200.0) .show_inside(ui, |ui| { ui.vertical(|ui| { ui.horizontal(|ui| { ui.text_edit_singleline(&mut self.new_case_name); ui.add_enabled_ui( !testcases.contains_key(self.new_case_name.as_str()), |ui| { if ui.button("+").clicked() { if !self.new_case_name.is_empty() { testcases.insert( self.new_case_name.clone(), Testcase { entry_name: "".to_string(), name: self.new_case_name.clone(), value: Default::default(), parent_path: vec![], }, ); } self.new_case_name.clear(); } }, ); }); let mut remove_name_op = None; let testcases_clone = testcases.clone(); for (name, testcase) in testcases_clone.iter() { let select_value = utils::select_value( ui, &mut self.select, Some(name.clone()), name.clone(), ); if select_value.clicked() { self.source = serde_json::to_string_pretty(&testcase.value).unwrap(); }; select_value.context_menu(|ui| { if ui.button("Remove").clicked() { remove_name_op = Some(name); ui.close_menu(); } }); } if let Some(remove_name) = remove_name_op { testcases.remove(remove_name); }; }) }); ui.label(self.message.clone()); let mut code_editor = CodeEditor::default() .id_source("testcase_code_editor") .with_rows(12) .with_ui_fontsize(ui) .with_syntax(js_syntax()) .with_numlines(true); if ui.visuals().dark_mode { code_editor = code_editor.with_theme(ColorTheme::GRUVBOX) } else { code_editor = code_editor.with_theme(ColorTheme::GRUVBOX_LIGHT) } if let Some(select) = &self.select { egui::ScrollArea::vertical() .max_height(400.0) .show(ui, |ui| { if code_editor.show(ui, &mut self.source).response.changed() { match serde_json::from_str::<HashMap<String, Value>>(&self.source) { Ok(testcase_value) => { self.message = RichText::new("Auto save success.") .color(Color32::DARK_GREEN); self.source = serde_json::to_string_pretty(&testcase_value).unwrap(); testcases.insert( select.to_string(), Testcase { entry_name: "".to_string(), name: select.to_string(), value: testcase_value, parent_path: vec![], }, ); } Err(e) => { self.message = RichText::new(e.to_string()).color(Color32::DARK_RED); } } } }); } else { let mut text = "Select one testcase to edit, the testcase format is `json`.".to_string(); code_editor.show(ui, &mut text); }; match crt_or_folder { CrtOrFolder::CRT(crt_id) => { workspace_data.must_get_mut_crt(crt_id.clone(), |crt| { crt.record.set_testcases(testcases.clone()); }); } CrtOrFolder::Folder(folder) => { folder.borrow_mut().testcases = testcases.clone(); } }; } } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/windows/workspace_windows.rs
crates/netpurr/src/windows/workspace_windows.rs
use std::path::PathBuf; use egui::{Spinner, Ui, Widget}; use poll_promise::Promise; use rustygit::Repository; use netpurr_core::data::workspace_data::WorkspaceData; use crate::data::config_data::ConfigData; use crate::data::workspace::Workspace; use crate::operation::operation::Operation; use crate::operation::windows::{Window, WindowSetting}; use crate::panels::HORIZONTAL_GAP; use crate::utils; #[derive(Default)] pub struct WorkspaceWindows { windows_open: bool, current_workspace: Option<String>, current_workspace_git_repo_name: String, current_workspace_git_repo: Option<PathBuf>, current_branch_list: Vec<String>, user_git_branch: String, user_git_remote_url: String, git_branch: Option<String>, git_remote_url: Option<String>, git_remote_edit: bool, new_workspace_name: String, sync_promise: Option<Promise<rustygit::types::Result<()>>>, force_pull_promise: Option<Promise<rustygit::types::Result<()>>>, force_push_promise: Option<Promise<rustygit::types::Result<()>>>, status: String, } impl Window for WorkspaceWindows { fn window_setting(&self) -> WindowSetting { WindowSetting::new("MANAGE WORKSPACE") .modal(true) .default_width(500.0) .default_height(300.0) .collapsible(false) .resizable(true) } fn set_open(&mut self, open: bool) { self.windows_open = open; } fn get_open(&self) -> bool { self.windows_open } fn render( &mut self, ui: &mut Ui, config_data: &mut ConfigData, _: &mut WorkspaceData, operation: Operation, ) { self.render_left_panel(ui, config_data); let option_workspace = config_data .workspaces() .get(self.current_workspace.clone().unwrap_or_default().as_str()); option_workspace.map(|workspace| { self.update(workspace, &operation); ui.horizontal(|ui| { ui.add_space(HORIZONTAL_GAP); egui::ScrollArea::vertical() .max_width(500.0) .min_scrolled_height(500.0) .show(ui, |ui| { ui.vertical(|ui| { ui.horizontal(|ui| { ui.strong("Name: "); let mut name = workspace.name.as_str(); utils::text_edit_singleline_justify(ui, &mut name); }); ui.horizontal(|ui| { ui.strong("Path: "); let mut path = workspace.path.to_str().unwrap_or(""); utils::text_edit_singleline_justify(ui, &mut path); }); ui.separator(); match &self.current_workspace_git_repo { None => { if ui.button("Enable Git").clicked() { operation.git().enable_git(&workspace.path); } } Some(_) => { self.render_branch(ui, &operation, &workspace.path); self.render_remote(ui, &operation, &workspace.path); if self.git_branch.is_some() && self.git_remote_url.is_some() { ui.horizontal(|ui| { let lock = self.sync_promise.is_some() || self.force_pull_promise.is_some() || self.force_push_promise.is_some(); ui.add_enabled_ui(!lock, |ui| { self.sync_button(ui, workspace, &operation); self.force_pull_button(ui, workspace, &operation); self.force_push(ui, workspace, &operation); }); }); } } } ui.separator(); ui.label(self.status.clone()) }); }) }); }); } } impl WorkspaceWindows { fn force_push(&mut self, ui: &mut Ui, workspace: &Workspace, operation: &Operation) { let button = ui.button("Force Push"); button.clone().on_hover_text( "Force local push to remote, used when synchronization conflicts occur.", ); if button.clicked() { self.status = "Waiting ...".to_string(); self.force_push_promise = Some( operation .git() .git_force_push_promise(workspace.path.clone()), ); } if let Some(promise) = &self.force_push_promise { Spinner::new().ui(ui); if let Some(result) = promise.ready() { match result { Ok(_) => self.status = "Force Push Success.".to_string(), Err(e) => { self.status = format!("Force Push Failed: {}", e.to_string()); } } self.force_push_promise = None; } } } fn force_pull_button(&mut self, ui: &mut Ui, workspace: &Workspace, operation: &Operation) { let button = ui.button("Force Pull"); button.clone().on_hover_text( "Force the remote data to be pulled down, ignore local submission, and be used when synchronization conflicts occur.", ); if button.clicked() { self.status = "Waiting ...".to_string(); self.force_pull_promise = Some( operation .git() .git_force_pull_promise(workspace.path.clone()), ); } if let Some(promise) = &self.force_pull_promise { Spinner::new().ui(ui); if let Some(result) = promise.ready() { match result { Ok(_) => self.status = "Force Pull Success.".to_string(), Err(e) => { self.status = format!("Force Pull Failed: {}", e.to_string()); } } self.force_pull_promise = None; } } } fn sync_button(&mut self, ui: &mut Ui, workspace: &Workspace, operation: &Operation) { let button = ui.button("Sync"); button.clone().on_hover_text( "Synchronize data to remote git, it will automatically `commit`, `rebase` and `push`", ); if button.clicked() { self.status = "Waiting ...".to_string(); self.sync_promise = Some(operation.git().git_sync_promise(workspace.path.clone())); } if let Some(promise) = &self.sync_promise { Spinner::new().ui(ui); if let Some(result) = promise.ready() { match result { Ok(_) => self.status = "Sync Success.".to_string(), Err(e) => { self.status = format!("Sync Failed: {}", e.to_string()); } } self.sync_promise = None; } } } fn render_left_panel(&mut self, ui: &mut Ui, config_data: &mut ConfigData) { egui::SidePanel::left("workspace_left_panel") .default_width(150.0) .width_range(80.0..=200.0) .show_inside(ui, |ui| { egui::ScrollArea::vertical().show(ui, |ui| { ui.horizontal(|ui| { if config_data .workspaces() .contains_key(self.new_workspace_name.as_str()) { ui.add_enabled_ui(false, |ui| { ui.button("+"); }); } else { if ui.button("+").clicked() { config_data.new_workspace(self.new_workspace_name.clone()); } } utils::text_edit_singleline_filter_justify( ui, &mut self.new_workspace_name, ); }); for (name, _) in config_data.workspaces().iter() { if utils::select_value( ui, &mut self.current_workspace, Some(name.to_string()), name.to_string(), ) .clicked() { self.user_git_branch = "main".to_string(); self.user_git_remote_url = "".to_string(); self.git_branch = None; self.git_remote_url = None; self.current_workspace_git_repo = None; self.current_workspace_git_repo_name = "".to_string(); self.status = "".to_string(); } } }); }); } fn render_remote(&mut self, ui: &mut Ui, operation: &Operation, path: &PathBuf) { ui.horizontal(|ui| { ui.strong("Git Origin Url:"); if !self.git_remote_edit { if ui.button("⚙").clicked() { self.git_remote_edit = true; self.git_remote_url.clone().map(|r| { self.user_git_remote_url = r.clone(); }); } ui.label(&self.user_git_remote_url); } else { if ui.button("✔").clicked() { self.git_remote_edit = false; if self.user_git_remote_url != "" { operation.git().update_remote(path, self.user_git_remote_url.clone()); } } utils::text_edit_singleline_justify(ui, &mut self.user_git_remote_url) .on_hover_text("Since Netpurr uses local git tools, it is recommended to use `ssh` to set the git address to prevent errors."); } }); } fn render_branch(&mut self, ui: &mut Ui, operation: &Operation, path: &PathBuf) { match &self.git_branch { None => { ui.horizontal(|ui| { ui.strong("Git Branch"); utils::text_edit_singleline_filter_justify(ui, &mut self.user_git_branch); }); if ui.button("Create Branch").clicked() { operation .git() .create_branch(path, self.user_git_branch.clone()); }; } Some(branch_name) => { ui.horizontal(|ui| { ui.strong("Switch Git Branch:"); egui::ComboBox::from_id_source("branch") .selected_text(branch_name) .show_ui(ui, |ui| { ui.style_mut().wrap = Some(false); ui.set_min_width(60.0); for select_branch in &self.current_branch_list { if ui .selectable_value( &mut self.user_git_branch, select_branch.clone(), select_branch.to_string(), ) .clicked() { operation .git() .switch_branch(path, self.user_git_branch.clone()); } } }); }); ui.horizontal(|ui| { utils::text_edit_singleline_filter(ui, &mut self.user_git_branch); let button = ui.button("Create Local Branch"); button.clone().on_hover_text("Create a local branch. The local branch and the remote branch have a one-to-one correspondence."); if button.clicked() { operation.git().create_branch(path, self.user_git_branch.clone()); }; }); } } } pub fn with_open(mut self, current_workspace: Option<String>) -> Self { self.windows_open = true; self.user_git_branch = "main".to_string(); self.current_workspace = current_workspace; self } fn update(&mut self, workspace: &Workspace, operation: &Operation) { if self.current_workspace_git_repo_name != self.current_workspace.clone().unwrap_or_default() { if operation.git().if_enable_git(&workspace.path) { self.current_workspace_git_repo = Some(workspace.path.clone()); } else { self.current_workspace_git_repo = None; } } match &self.current_workspace_git_repo { None => {} Some(repo_path) => { let repo = Repository::new(repo_path); if let Ok(branches) = repo.list_branches() { self.current_branch_list = branches.clone(); if let Ok(head) = repo.cmd_out(["branch", "--show-current"]) { if head.len() > 0 { let branch = head[0].to_string(); if branches.contains(&branch) { self.git_branch = Some(branch); } } } } if let Ok(remote) = repo.cmd_out(["remote", "get-url", "origin"]) { if remote.len() > 0 { self.git_remote_url = Some(remote[0].clone()); if self.user_git_remote_url == "" { self.user_git_remote_url = remote[0].clone(); } } } } } } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/windows/environment_windows.rs
crates/netpurr/src/windows/environment_windows.rs
use egui::{Align, Button, Checkbox, Layout, ScrollArea, TextEdit, Ui, Widget}; use egui_extras::{Column, TableBuilder}; use netpurr_core::data::environment::{ENVIRONMENT_GLOBALS, EnvironmentConfig, EnvironmentItem}; use netpurr_core::data::workspace_data::WorkspaceData; use crate::data::config_data::ConfigData; use crate::operation::operation::Operation; use crate::operation::windows::{Window, WindowSetting}; use crate::panels::{HORIZONTAL_GAP, VERTICAL_GAP}; use crate::utils; #[derive(Default)] pub struct EnvironmentWindows { environment_windows_open: bool, select_env: Option<String>, select_env_config: EnvironmentConfig, select_env_name: String, new_select_env_item: EnvironmentItem, } impl Window for EnvironmentWindows { fn window_setting(&self) -> WindowSetting { WindowSetting::new("MANAGE ENVIRONMENTS") .modal(true) .default_width(500.0) .default_height(300.0) .collapsible(false) .resizable(true) } fn set_open(&mut self, open: bool) { self.environment_windows_open = open } fn get_open(&self) -> bool { self.environment_windows_open } fn render( &mut self, ui: &mut Ui, _: &mut ConfigData, workspace_data: &mut WorkspaceData, operation: Operation, ) { if self.select_env.is_none() { self.env_list(workspace_data, ui); } else { self.select_modify(ui); } self.env_bottom(workspace_data, ui); } } impl EnvironmentWindows { fn env_list(&mut self, workspace_data: &mut WorkspaceData, ui: &mut Ui) { ui.label("An environment is a set of variables that allow you to switch the context of your requests. Environments can be shared between multiple workspaces."); ui.add_space(VERTICAL_GAP); ScrollArea::vertical().show(ui, |ui| { for (name, e) in workspace_data.get_env_configs().iter() { if name == ENVIRONMENT_GLOBALS { continue; } ui.horizontal(|ui| { ui.add_space(HORIZONTAL_GAP * 3.0); utils::left_right_panel( ui, "env_".to_string() + name.as_str(), |ui| { if ui.hyperlink(name).clicked() { self.select_env = Some(name.clone()); self.select_env_config = e.clone(); self.select_env_name = name.clone(); } }, |ui| { ui.horizontal(|ui| { if ui.button("📋").clicked() { workspace_data.add_env(name.to_string() + " Copy", e.clone()); }; ui.button("⬇"); if ui.button("🗑").clicked() { workspace_data.remove_env(name.to_string()); } }); }, ); }); } }); } fn select_modify(&mut self, ui: &mut Ui) { if self.select_env_name == ENVIRONMENT_GLOBALS { ui.label("Global variables for a workspace are a set of variables that are always available within the scope of that workspace. They can be viewed and edited by anyone in that workspace."); } else { ui.strong("Environment Name"); TextEdit::singleline(&mut self.select_env_name) .desired_width(f32::INFINITY) .ui(ui); } ui.add_space(VERTICAL_GAP); let mut delete_index = None; ui.push_id("environment_table", |ui| { let table = TableBuilder::new(ui) .resizable(false) .cell_layout(Layout::left_to_right(Align::Center)) .column(Column::auto()) .column(Column::exact(20.0)) .column(Column::initial(200.0).range(40.0..=300.0)) .column(Column::remainder()) .max_scroll_height(400.0); table .header(20.0, |mut header| { header.col(|ui| { ui.strong(""); }); header.col(|ui| { ui.strong(""); }); header.col(|ui| { ui.strong("VARIABLE"); }); header.col(|ui| { ui.strong("VALUE"); }); }) .body(|mut body| { for (index, item) in self.select_env_config.items.iter_mut().enumerate() { body.row(18.0, |mut row| { row.col(|ui| { ui.checkbox(&mut item.enable, ""); }); row.col(|ui| { if ui.button("x").clicked() { delete_index = Some(index) } }); row.col(|ui| { ui.text_edit_singleline(&mut item.key); }); row.col(|ui| { TextEdit::singleline(&mut item.value) .desired_width(f32::INFINITY) .ui(ui); }); }); } body.row(18.0, |mut row| { row.col(|ui| { ui.add_enabled( false, Checkbox::new(&mut self.new_select_env_item.enable, ""), ); }); row.col(|ui| { ui.add_enabled(false, Button::new("x")); }); row.col(|ui| { ui.text_edit_singleline(&mut self.new_select_env_item.key); }); row.col(|ui| { TextEdit::singleline(&mut self.new_select_env_item.value) .desired_width(f32::INFINITY) .ui(ui); }); }); }); }); if delete_index.is_some() { self.select_env_config.items.remove(delete_index.unwrap()); } if self.new_select_env_item.key != "" || self.new_select_env_item.value != "" { self.new_select_env_item.enable = true; self.select_env_config .items .push(self.new_select_env_item.clone()); self.new_select_env_item.key = "".to_string(); self.new_select_env_item.value = "".to_string(); self.new_select_env_item.enable = false; } } fn env_bottom(&mut self, workspace_data: &mut WorkspaceData, ui: &mut Ui) { egui::TopBottomPanel::bottom("environment_bottom_panel") .resizable(false) .min_height(0.0) .show_inside(ui, |ui| { ui.add_space(VERTICAL_GAP); ui.with_layout(Layout::right_to_left(Align::Center), |ui| { if self.select_env.is_none() { if ui.button("Add").clicked() { self.select_env = Some("".to_string()); self.select_env_config = EnvironmentConfig::default(); self.select_env_name = "".to_string(); } ui.button("Import"); if ui.button("Globals").clicked() { let data = workspace_data.get_env(ENVIRONMENT_GLOBALS.to_string()); self.select_env = Some(ENVIRONMENT_GLOBALS.to_string()); self.select_env_config = data.unwrap_or(EnvironmentConfig::default()); self.select_env_name = ENVIRONMENT_GLOBALS.to_string(); }; } else { if ui.button("Update").clicked() { if self.select_env_name != "" { workspace_data.remove_env(self.select_env.clone().unwrap()); workspace_data.add_env( self.select_env_name.clone(), self.select_env_config.clone(), ); self.select_env = None; } } if ui.button("Cancel").clicked() { self.select_env = None } } }); }); } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/windows/view_json_windows.rs
crates/netpurr/src/windows/view_json_windows.rs
use egui::{Align, Button, Layout, Ui}; use serde_json::Value; use egui_json_tree::{DefaultExpand, JsonTree}; use netpurr_core::data::workspace_data::WorkspaceData; use crate::data::config_data::ConfigData; use crate::operation::operation::Operation; use crate::operation::windows::{Window, WindowSetting}; #[derive(Default)] pub struct ViewJsonWindows { open: bool, json: String, search_input: String, id: String, } impl ViewJsonWindows { pub fn with_json(mut self, json: String, id: String) -> Self { self.json = json; self.id = id; self } } impl Window for ViewJsonWindows { fn window_setting(&self) -> WindowSetting { WindowSetting::new_with_id("VIEW JSON TREE", self.id.clone()) .max_height(500.0) .max_width(500.0) } fn set_open(&mut self, open: bool) { self.open = open; } fn get_open(&self) -> bool { self.open } fn render( &mut self, ui: &mut Ui, config_data: &mut ConfigData, workspace_data: &mut WorkspaceData, operation: Operation, ) { match serde_json::from_str::<Value>(self.json.as_str()) { Ok(value) => { ui.label("Search:"); let (text_edit_response, clear_button_response) = ui .horizontal(|ui| { let text_edit_response = ui.text_edit_singleline(&mut self.search_input); let clear_button_response = ui.button("Clear"); (text_edit_response, clear_button_response) }) .inner; egui::ScrollArea::vertical() .max_height(600.0) .show(ui, |ui| { let response = JsonTree::new( "json_tree_".to_string() + self.window_setting().id(), &value, ) .default_expand(DefaultExpand::SearchResults(&self.search_input)) .response_callback(|response, pointer| { response.context_menu(|ui| { ui.with_layout(Layout::top_down_justified(Align::LEFT), |ui| { ui.set_width(150.0); if !pointer.is_empty() && ui .add(Button::new("Copy property path").frame(false)) .clicked() { operation.add_success_toast("Copy path success."); ui.output_mut(|o| o.copied_text = pointer.clone()); ui.close_menu(); } if ui.add(Button::new("Copy contents").frame(false)).clicked() { if let Some(val) = value.pointer(pointer) { if let Ok(pretty_str) = serde_json::to_string_pretty(val) { ui.output_mut(|o| o.copied_text = pretty_str); operation .add_success_toast("Copy contents success."); } } ui.close_menu(); } }); }); }) .show(ui); if text_edit_response.changed() { response.reset_expanded(ui); } if clear_button_response.clicked() { self.search_input.clear(); response.reset_expanded(ui); } ui.horizontal(|ui| { if ui.button("Reset expanded").clicked() { response.reset_expanded(ui); } if ui.button("Copy json").clicked() { ui.output_mut(|o| o.copied_text = self.json.clone()); operation.add_success_toast("Copy json success."); } }); }); } Err(_) => { ui.label("Error Json Format"); } }; } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/windows/save_crt_windows.rs
crates/netpurr/src/windows/save_crt_windows.rs
use std::cell::RefCell; use std::collections::BTreeMap; use std::rc::Rc; use chrono::format::format; use egui::{Align, Button, Layout, ScrollArea, Ui}; use netpurr_core::data::collections::{Collection, CollectionFolder}; use netpurr_core::data::workspace_data::WorkspaceData; use crate::data::config_data::ConfigData; use crate::operation::operation::Operation; use crate::operation::windows::{Window, WindowSetting}; use crate::panels::VERTICAL_GAP; use crate::utils; #[derive(Default)] pub struct SaveCRTWindows { save_windows_open: bool, crt_id: String, save_name: String, save_desc: String, select_collection_path: Option<String>, add_collection: bool, add_folder: bool, add_name: String, id: String, } impl Window for SaveCRTWindows { fn window_setting(&self) -> WindowSetting { WindowSetting::new("SAVE REQUEST") .max_width(500.0) .default_height(400.0) .collapsible(false) .resizable(true) } fn set_open(&mut self, open: bool) { self.save_windows_open = open; } fn get_open(&self) -> bool { self.save_windows_open } fn render( &mut self, ui: &mut Ui, _: &mut ConfigData, workspace_data: &mut WorkspaceData, operation: Operation, ) { ui.label("Requests in Netpurr are saved in collections (a group of requests)."); ui.add_space(VERTICAL_GAP); ui.label("Request name"); utils::text_edit_singleline_filter_justify(ui, &mut self.save_name); ui.add_space(VERTICAL_GAP); ui.label("Request description (Optional)"); utils::text_edit_multiline_justify(ui, &mut self.save_desc); ui.add_space(VERTICAL_GAP); ui.label("Select a collection or folder to save to:"); ui.add_space(VERTICAL_GAP); self.render(workspace_data, ui); ui.add_space(VERTICAL_GAP); self.render_save_bottom_panel(workspace_data, &operation, ui); } } impl SaveCRTWindows { pub fn with(mut self, crt_id: String, collection_path: Option<String>) -> Self { self.save_windows_open = true; self.crt_id = crt_id; self.add_folder = false; self.add_collection = false; self.add_name = "".to_string(); self.select_collection_path = collection_path; self } fn render(&mut self, workspace_data: &mut WorkspaceData, ui: &mut Ui) { ui.vertical(|ui| { ui.horizontal(|ui| match &self.select_collection_path { None => { ui.label("All Collections"); ui.with_layout(Layout::right_to_left(Align::Center), |ui| { if ui.link("+ Create Collection").clicked() { self.add_collection = true; }; }); } Some(name) => { if ui.link(format!("{} {}",egui_phosphor::regular::ARROW_LEFT, name)).clicked() { self.add_folder = false; self.add_collection = false; let paths: Vec<&str> = name.split("/").collect(); if paths.len() == 1 { self.select_collection_path = None; } else { let new_paths = &paths[0..paths.len() - 1]; self.select_collection_path = Some(new_paths.join("/")); } } ui.with_layout(Layout::right_to_left(Align::Center), |ui| { if ui.link("+ Create Folder").clicked() { self.add_folder = true; }; }); } }); ui.add_space(VERTICAL_GAP); if self.add_collection { self.add_folder = false; self.render_add_collection(workspace_data, ui); } if self.add_folder { self.add_collection = false; self.render_add_folder(workspace_data, ui); } self.render_list(workspace_data, ui); }); } fn render_list(&mut self, workspace_data: &mut WorkspaceData, ui: &mut Ui) { ScrollArea::vertical().max_height(200.0).show(ui, |ui| { match self.select_collection_path.clone() { None => { for (name, collection) in workspace_data.get_collections().iter() { if utils::select_label(ui, name).clicked() { self.add_folder = false; self.add_collection = false; self.select_collection_path = Some(collection.folder.borrow().name.to_string()); } } } Some(path) => { workspace_data .get_folder_with_path(path.clone()) .1 .map(|cf| { for (name, cf_child) in cf.borrow().folders.iter() { if utils::select_label(ui, name.clone()).clicked() { self.add_folder = false; self.add_collection = false; self.select_collection_path = Some(path.clone() + "/" + cf_child.borrow().name.as_str()) } } ui.set_enabled(false); for (_, hr) in cf.borrow().requests.iter() { utils::select_label( ui, utils::build_rest_ui_header(hr.clone(), None, ui), ); } }); } } }); } fn render_add_folder(&mut self, workspace_data: &mut WorkspaceData, ui: &mut Ui) { ui.horizontal(|ui| { match &self.select_collection_path { None => {} Some(path) => { let (_, option) = workspace_data.get_folder_with_path(path.clone()); match option { None => {} Some(folder) => { if folder.borrow().folders.contains_key(self.add_name.as_str()) { ui.set_enabled(false); } } } } } if ui.button("+").clicked() { match &self.select_collection_path { None => {} Some(path) => { let (_, option) = workspace_data.get_folder_with_path(path.clone()); match option { None => {} Some(folder) => { workspace_data.collection_insert_folder( folder.clone(), Rc::new(RefCell::new(CollectionFolder { name: self.add_name.to_string(), parent_path: path.clone(), desc: "".to_string(), auth: Default::default(), is_root: false, requests: Default::default(), folders: Default::default(), pre_request_script: "".to_string(), test_script: "".to_string(), testcases: Default::default(), })), ); } } } } self.add_name = "".to_string(); self.add_folder = false; } utils::text_edit_singleline_filter_justify(ui, &mut self.add_name); }); } fn render_add_collection(&mut self, workspace_data: &mut WorkspaceData, ui: &mut Ui) { ui.horizontal(|ui| { if workspace_data .get_collections() .contains_key(self.add_name.as_str()) { ui.add_enabled(false, Button::new("+")); } else { if ui.button("+").clicked() { workspace_data.add_collection(Collection { folder: Rc::new(RefCell::new(CollectionFolder { name: self.add_name.clone(), parent_path: ".".to_string(), desc: "".to_string(), auth: Default::default(), is_root: true, requests: Default::default(), folders: BTreeMap::default(), pre_request_script: "".to_string(), test_script: "".to_string(), testcases: Default::default(), })), ..Default::default() }); self.add_name = "".to_string(); self.add_collection = false; } } utils::text_edit_singleline_filter_justify(ui, &mut self.add_name); }); } fn render_save_bottom_panel( &mut self, workspace_data: &mut WorkspaceData, operation: &Operation, ui: &mut Ui, ) { egui::TopBottomPanel::bottom("save_bottom_panel_".to_string() + self.id.as_str()) .resizable(false) .min_height(0.0) .show_inside(ui, |ui| { ui.add_space(VERTICAL_GAP); ui.with_layout(Layout::right_to_left(Align::Center), |ui| { match &self.select_collection_path { None => { ui.add_enabled_ui(false, |ui| { ui.button("Save"); }); } Some(collection_path) => { let mut ui_enable = true; if self.save_name.is_empty() { ui_enable = false; } let button_name = "Save to ".to_string() + collection_path.split("/").last().unwrap_or_default(); let (_, option) = workspace_data.get_folder_with_path(collection_path.clone()); match &option { None => {} Some(cf) => { if cf.borrow().requests.contains_key(self.save_name.as_str()) { ui_enable = false; } } } ui.add_enabled_ui(ui_enable, |ui| { if ui.button(button_name).clicked() { workspace_data.save_crt( self.crt_id.clone(), collection_path.clone(), |record| { record.set_name(self.save_name.clone()); record.set_desc(self.save_desc.clone()); }, ); operation.add_success_toast("Save success."); self.save_windows_open = false; } }); if ui.button("Cancel").clicked() { self.save_windows_open = false; } } } }); }); } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/panels/websocket_event_panel.rs
crates/netpurr/src/panels/websocket_event_panel.rs
use std::collections::BTreeMap; use chrono::format::StrftimeItems; use eframe::emath::Align; use egui::{Layout, RichText, Ui}; use egui_extras::{Column, TableBuilder}; use strum::IntoEnumIterator; use strum_macros::{Display, EnumIter, EnumString}; use netpurr_core::data::central_request_data::CentralRequestItem; use netpurr_core::data::cookies_manager::Cookie; use netpurr_core::data::http::Response; use netpurr_core::data::test::TestResult; use netpurr_core::data::websocket::{WebSocketMessage, WebSocketStatus}; use netpurr_core::data::workspace_data::WorkspaceData; use crate::operation::operation::Operation; use crate::panels::response_cookies_panel::ResponseCookiesPanel; use crate::panels::response_headers_panel::ResponseHeadersPanel; use crate::panels::response_log_panel::ResponseLogPanel; use crate::utils; use crate::utils::HighlightValue; #[derive(Default)] pub struct WebsocketEventPanel { open_panel_enum: ResponsePanelEnum, response_headers_panel: ResponseHeadersPanel, response_cookies_panel: ResponseCookiesPanel, response_log_panel: ResponseLogPanel, } #[derive(Clone, EnumIter, EnumString, Display, PartialEq)] enum ResponsePanelEnum { Event, Cookies, Headers, Logs, } impl Default for ResponsePanelEnum { fn default() -> Self { ResponsePanelEnum::Event } } impl WebsocketEventPanel { pub fn set_and_render( &mut self, ui: &mut Ui, operation: &Operation, workspace_data: &mut WorkspaceData, crt_id: String, ) { let crt = workspace_data.must_get_crt(crt_id.clone()); let cookies = workspace_data .get_url_cookies(crt.record.must_get_rest().request.get_url_with_schema()); match &crt.record.must_get_websocket().session { None => { ui.strong("Response"); ui.separator(); ui.centered_and_justified(|ui| { ui.label("Hit the Connect button to connect websocket server"); }); } Some(session) => match session.get_status() { WebSocketStatus::Connect => { self.build_ready_panel(operation, workspace_data, crt_id, ui, &crt, cookies); } WebSocketStatus::Connecting => { ui.centered_and_justified(|ui| { ui.label("Connecting..."); }); } WebSocketStatus::Disconnect => {} WebSocketStatus::ConnectError(e) => { ui.centered_and_justified(|ui| { ui.label(e); }); } WebSocketStatus::SendError(_) => {} WebSocketStatus::SendSuccess => {} }, } } fn get_count( response: &Response, cookies: &BTreeMap<String, Cookie>, test_result: &TestResult, panel_enum: ResponsePanelEnum, ) -> HighlightValue { match panel_enum { ResponsePanelEnum::Event => HighlightValue::None, ResponsePanelEnum::Cookies => HighlightValue::Usize(cookies.len()), ResponsePanelEnum::Headers => HighlightValue::Usize(response.headers.iter().count()), ResponsePanelEnum::Logs => HighlightValue::Usize(response.logger.logs.len()), } } fn build_ready_panel( &mut self, operation: &Operation, workspace_data: &mut WorkspaceData, crt_id: String, ui: &mut Ui, data: &CentralRequestItem, cookies: BTreeMap<String, Cookie>, ) { utils::left_right_panel( ui, "response".to_string(), |ui| { ui.horizontal(|ui| { for response_panel_enum in ResponsePanelEnum::iter() { ui.selectable_value( &mut self.open_panel_enum, response_panel_enum.clone(), utils::build_with_count_ui_header( response_panel_enum.to_string(), WebsocketEventPanel::get_count( &data.record.must_get_rest().response, &cookies, &data.test_result, response_panel_enum, ), ui, ), ); } }); }, |ui| { ui.horizontal(|ui| { ui.label("Status:"); ui.label( RichText::new(data.record.must_get_rest().response.status.to_string()) .color(ui.visuals().warn_fg_color) .strong(), ); ui.label("Time:"); ui.label( RichText::new( data.record .must_get_rest() .response .elapsed_time .to_string() + "ms", ) .color(ui.visuals().warn_fg_color) .strong(), ); ui.label("Size:"); ui.label( RichText::new(data.record.must_get_rest().response.body.get_byte_size()) .color(ui.visuals().warn_fg_color) .strong(), ); }); }, ); ui.separator(); let crt = workspace_data.must_get_crt(crt_id.clone()); match self.open_panel_enum { ResponsePanelEnum::Event => { self.render_event(ui, workspace_data, operation, crt_id); } ResponsePanelEnum::Cookies => { self.response_cookies_panel.set_and_render(ui, &cookies); } ResponsePanelEnum::Headers => { self.response_headers_panel .set_and_render(ui, &crt.record.must_get_rest().response); } ResponsePanelEnum::Logs => { self.response_log_panel .set_and_render(ui, &crt.record.must_get_rest().response); } } } fn render_event( &self, ui: &mut Ui, workspace_data: &mut WorkspaceData, operation: &Operation, crt_id: String, ) { match &workspace_data .must_get_crt(crt_id) .record .must_get_websocket() .session { None => {} Some(session) => { let available_width = ui.available_width(); let table = TableBuilder::new(ui) .resizable(false) .cell_layout(Layout::left_to_right(Align::Center)) .column(Column::exact(50.0)) .column(Column::initial(available_width - 200.0).range(300.0..=1000.0)) .column(Column::remainder()) .max_scroll_height(100.0); table .striped(true) .header(20.0, |mut header| { header.col(|ui| { ui.strong(""); }); header.col(|ui| { ui.strong("Data"); }); header.col(|ui| { ui.strong("Time"); }); }) .body(|mut body| { for (index, message) in session.get_messages().iter().rev().enumerate() { let mut flag = "Send"; let mut text = "".to_string(); let mut time = "".to_string(); match message { WebSocketMessage::Send(d, msg_type, msg) => { flag = "Send"; text = msg.to_string(); time = d .format_with_items(StrftimeItems::new("%H:%M:%S")) .to_string(); } WebSocketMessage::Receive(d, msg_type, msg) => { flag = "Receive"; text = msg.to_string(); time = d .format_with_items(StrftimeItems::new("%H:%M:%S")) .to_string(); } } body.row(18.0, |mut row| { row.col(|ui| { ui.label(flag); }); row.col(|ui| { ui.label(text.replace("\n", "")); }); row.col(|ui| { ui.label(time); }); }); } }); } } } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/panels/request_body_panel.rs
crates/netpurr/src/panels/request_body_panel.rs
use egui::{Ui, Widget}; use serde_json::Value; use strum::IntoEnumIterator; use uuid::Uuid; use netpurr_core::data::http::{BodyRawType, BodyType}; use netpurr_core::data::workspace_data::WorkspaceData; use crate::operation::operation::Operation; use crate::panels::{HORIZONTAL_GAP, VERTICAL_GAP}; use crate::panels::request_body_form_data_panel::RequestBodyFormDataPanel; use crate::panels::request_body_xxx_form_panel::RequestBodyXXXFormPanel; use crate::utils; use crate::utils::HighlightValue; use crate::utils::openapi_help::OpenApiHelp; use crate::widgets::highlight_template::HighlightTemplateSinglelineBuilder; use crate::windows::view_json_windows::ViewJsonWindows; #[derive(Default)] pub struct RequestBodyPanel { request_body_form_data_panel: RequestBodyFormDataPanel, request_body_xxx_form_panel: RequestBodyXXXFormPanel, } impl RequestBodyPanel { pub fn set_and_render( &mut self, ui: &mut Ui, operation: &Operation, workspace_data: &mut WorkspaceData, crt_id: String, ) { let envs = workspace_data.get_crt_envs(crt_id.clone()); let mut crt = workspace_data.must_get_crt(crt_id.clone()); ui.horizontal_wrapped(|ui| { ui.add_space(HORIZONTAL_GAP); for x in BodyType::iter() { crt = workspace_data.must_get_mut_crt(crt_id.clone(), |crt| { utils::selectable_check( ui, &mut crt.record.must_get_mut_rest().request.body.body_type, x.clone(), x.to_string(), ); }); } }); ui.horizontal(|ui| { if crt.record.must_get_rest().request.body.body_type == BodyType::RAW { egui::ComboBox::from_id_source("body_raw_type") .selected_text( crt.record .must_get_rest() .request .body .body_raw_type .clone() .to_string(), ) .show_ui(ui, |ui| { ui.style_mut().wrap = Some(false); ui.set_min_width(60.0); for body_raw_type in BodyRawType::iter() { crt = workspace_data.must_get_mut_crt(crt_id.clone(), |crt| { ui.selectable_value( &mut crt.record.must_get_mut_rest().request.body.body_raw_type, body_raw_type.clone(), body_raw_type.to_string(), ); }); } }); if crt.record.must_get_rest().request.body.body_raw_type == BodyRawType::JSON { if ui.button("Pretty").clicked() { let json = crt.record.must_get_rest().request.body.body_str.clone(); let value = serde_json::from_str::<Value>(&json); match value { Ok(v) => { let pretty_json = serde_json::to_string_pretty(&v); match pretty_json { Ok(pretty_json_str) => { crt = workspace_data.must_get_mut_crt( crt_id.clone(), |crt| { crt.record .must_get_mut_rest() .request .body .body_str = pretty_json_str; }, ); } Err(_) => {} } } Err(_) => {} } } let render_text = netpurr_core::utils::replace_variable( crt.record.must_get_rest().request.body.body_str.clone(), envs.clone(), ); ui.button("Render").on_hover_text(render_text); } if let Some(operation_id) = crt.record.must_get_rest().operation_id.clone() { if ui.button("Generate Schema").clicked() { if let Some(collection) = workspace_data.get_collection(crt.collection_path.clone()) { if let Some(openapi) = collection.openapi { let openapi_help = OpenApiHelp { openapi }; let schema_value = openapi_help.gen_openapi_schema(operation_id); match schema_value { None => {} Some(value) => { operation.add_success_toast("Generate schema success"); operation.add_window(Box::new( ViewJsonWindows::default().with_json( serde_json::to_string(&value).unwrap(), Uuid::new_v4().to_string(), ), )) } } } } } } } }); ui.add_space(VERTICAL_GAP); ui.push_id("request_body_select_type", |ui| { match crt.record.must_get_rest().request.body.body_type { BodyType::NONE => { ui.label("This request does not have a body"); } BodyType::FROM_DATA => { self.request_body_form_data_panel .set_and_render(ui, workspace_data, crt_id) } BodyType::X_WWW_FROM_URLENCODED => { self.request_body_xxx_form_panel .set_and_render(ui, workspace_data, crt_id) } BodyType::RAW => { ui.push_id("request_body", |ui| { egui::ScrollArea::vertical() .max_height(ui.available_height() - 30.0) .show(ui, |ui| { crt = workspace_data.must_get_mut_crt(crt_id.clone(), |crt| { HighlightTemplateSinglelineBuilder::default() .multiline() .quick_render(false) .envs(envs) .all_space(true) .build( "request_body".to_string(), &mut crt .record .must_get_mut_rest() .request .body .body_str, ) .ui(ui); }); }); }); } BodyType::BINARY => { let mut button_name = utils::build_with_count_ui_header( "Select File".to_string(), HighlightValue::None, ui, ); if crt.record.must_get_rest().request.body.body_file != "" { button_name = utils::build_with_count_ui_header( "Select File".to_string(), HighlightValue::Usize(1), ui, ); } ui.horizontal(|ui| { if ui.button(button_name).clicked() { if let Some(path) = rfd::FileDialog::new().pick_file() { crt = workspace_data.must_get_mut_crt(crt_id.clone(), |crt| { crt.record.must_get_mut_rest().request.body.body_file = path.display().to_string(); }); } } let mut path = crt.record.must_get_rest().request.body.body_file.clone(); utils::text_edit_singleline_justify(ui, &mut path); }); } } }); } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/panels/response_panel.rs
crates/netpurr/src/panels/response_panel.rs
use std::collections::BTreeMap; use egui::{Color32, RichText, Ui}; use strum::IntoEnumIterator; use strum_macros::{Display, EnumIter, EnumString}; use netpurr_core::data::cookies_manager::Cookie; use netpurr_core::data::http::{Response, ResponseStatus}; use netpurr_core::data::test::{TestResult, TestStatus}; use netpurr_core::data::workspace_data::WorkspaceData; use netpurr_core::runner::TestRunResult; use crate::operation::operation::Operation; use crate::panels::response_body_panel::ResponseBodyPanel; use crate::panels::response_cookies_panel::ResponseCookiesPanel; use crate::panels::response_headers_panel::ResponseHeadersPanel; use crate::panels::response_log_panel::ResponseLogPanel; use crate::panels::test_result_panel::TestResultPanel; use crate::utils; use crate::utils::HighlightValue; #[derive(Default)] pub struct ResponsePanel { open_panel_enum: ResponsePanelEnum, response_body_panel: ResponseBodyPanel, response_headers_panel: ResponseHeadersPanel, response_cookies_panel: ResponseCookiesPanel, response_log_panel: ResponseLogPanel, test_result_panel: TestResultPanel, } #[derive(Clone, EnumIter, EnumString, Display, PartialEq)] enum ResponsePanelEnum { Body, Cookies, Headers, Logs, TestResult, } impl Default for ResponsePanelEnum { fn default() -> Self { ResponsePanelEnum::Body } } impl ResponsePanel { pub fn render_with_crt( &mut self, ui: &mut Ui, operation: &Operation, workspace_data: &mut WorkspaceData, crt_id: String, ) { let crt = workspace_data.must_get_crt(crt_id.clone()); let cookies = workspace_data .get_url_cookies(crt.record.must_get_rest().request.get_url_with_schema()); match crt.record.must_get_rest().status { ResponseStatus::None => { ui.strong("Response"); ui.separator(); ui.centered_and_justified(|ui| { ui.label("Hit the Send button to get a response"); }); } ResponseStatus::Pending => { ui.centered_and_justified(|ui| { ui.label("Loading..."); }); } ResponseStatus::Ready => { self.build_ready_panel( operation, ui, &crt.record.must_get_rest().response, &crt.test_result, cookies, ); } ResponseStatus::Error => { ui.centered_and_justified(|ui| { ui.label("Could not get any response"); }); } } } pub fn render_with_test( &mut self, ui: &mut Ui, operation: &Operation, workspace_data: &mut WorkspaceData, test_run_result: &TestRunResult, ) { match &test_run_result.response { None => {} Some(response) => { let cookies = workspace_data.get_url_cookies(test_run_result.request.get_url_with_schema()); self.build_ready_panel( operation, ui, response, &test_run_result.test_result, cookies, ); } } } fn get_count( response: &Response, cookies: &BTreeMap<String, Cookie>, test_result: &TestResult, panel_enum: ResponsePanelEnum, ) -> HighlightValue { match panel_enum { ResponsePanelEnum::Body => HighlightValue::None, ResponsePanelEnum::Cookies => HighlightValue::Usize(cookies.len()), ResponsePanelEnum::Headers => HighlightValue::Usize(response.headers.iter().count()), ResponsePanelEnum::Logs => HighlightValue::Usize(response.logger.logs.len()), ResponsePanelEnum::TestResult => match test_result.status { TestStatus::None => HighlightValue::None, TestStatus::PASS => HighlightValue::String( format!( "{}/{}", test_result.test_info_list.len(), test_result.test_info_list.len() ), Color32::DARK_GREEN, ), TestStatus::FAIL => HighlightValue::String( format!( "{}/{}", test_result .test_info_list .iter() .filter(|i| i.status == TestStatus::PASS) .count(), test_result.test_info_list.len() ), Color32::RED, ), TestStatus::WAIT => HighlightValue::None, TestStatus::SKIP => HighlightValue::None, TestStatus::RUNNING => HighlightValue::None }, } } fn build_ready_panel( &mut self, operation: &Operation, ui: &mut Ui, response: &Response, test_result: &TestResult, cookies: BTreeMap<String, Cookie>, ) { ui.horizontal(|ui| { ui.label("Status:"); ui.label( RichText::new(response.status.to_string()) .color(ui.visuals().warn_fg_color) .strong(), ); ui.label("Time:"); ui.label( RichText::new(response.elapsed_time.to_string() + "ms") .color(ui.visuals().warn_fg_color) .strong(), ); ui.label("Size:"); ui.label( RichText::new(response.body.get_byte_size()) .color(ui.visuals().warn_fg_color) .strong(), ); }); ui.horizontal(|ui| { for response_panel_enum in ResponsePanelEnum::iter() { ui.selectable_value( &mut self.open_panel_enum, response_panel_enum.clone(), utils::build_with_count_ui_header( response_panel_enum.to_string(), ResponsePanel::get_count( response, &cookies, test_result, response_panel_enum, ), ui, ), ); } }); ui.separator(); match self.open_panel_enum { ResponsePanelEnum::Body => { self.response_body_panel .set_and_render(ui, operation, response); } ResponsePanelEnum::Cookies => { self.response_cookies_panel.set_and_render(ui, &cookies); } ResponsePanelEnum::Headers => { self.response_headers_panel.set_and_render(ui, response); } ResponsePanelEnum::Logs => { self.response_log_panel.set_and_render(ui, response); } ResponsePanelEnum::TestResult => { self.test_result_panel.set_and_render(ui, test_result); } } } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/panels/request_params_panel.rs
crates/netpurr/src/panels/request_params_panel.rs
use std::collections::BTreeMap; use eframe::emath::Align; use egui::{Button, Checkbox, Layout, TextEdit, Ui, Widget}; use egui_extras::{Column, TableBody, TableBuilder}; use netpurr_core::data::central_request_data::CentralRequestItem; use netpurr_core::data::environment::EnvironmentItemValue; use netpurr_core::data::http::{LockWith, QueryParam}; use netpurr_core::data::workspace_data::WorkspaceData; use crate::widgets::highlight_template::HighlightTemplateSinglelineBuilder; #[derive(Default)] pub struct RequestParamsPanel { new_query_param: QueryParam, } impl RequestParamsPanel { pub fn set_and_render( &mut self, ui: &mut Ui, workspace_data: &mut WorkspaceData, crt_id: String, ) { let envs = workspace_data.get_crt_envs(crt_id.clone()); workspace_data.must_get_mut_crt(crt_id.clone(), |crt| { self.render_query_params(ui, &envs, crt); let get_path_variable_keys = crt.record.must_get_rest().request.get_path_variable_keys(); if !get_path_variable_keys.is_empty() { self.render_path_variables(ui, &envs, crt); } }); } fn render_query_params( &mut self, ui: &mut Ui, envs: &BTreeMap<String, EnvironmentItemValue>, crt: &mut CentralRequestItem, ) { ui.label("Query Params"); let mut delete_index = None; ui.push_id("query_params_table", |ui| { let table = TableBuilder::new(ui) .resizable(false) .cell_layout(Layout::left_to_right(Align::Center)) .column(Column::auto()) .column(Column::exact(20.0)) .column(Column::initial(200.0).range(40.0..=300.0)) .column(Column::initial(200.0).range(40.0..=300.0)) .column(Column::remainder()) .max_scroll_height(100.0); table .header(20.0, |mut header| { header.col(|ui| { ui.strong(""); }); header.col(|ui| { ui.strong(""); }); header.col(|ui| { ui.strong("KEY"); }); header.col(|ui| { ui.strong("VALUE"); }); header.col(|ui| { ui.strong("DESCRIPTION"); }); }) .body(|mut body| { delete_index = self.build_query_params_body(crt, &envs, &mut body); self.build_new_query_params_body(envs, body); }); }); if delete_index.is_some() { crt.record .must_get_mut_rest() .request .params .remove(delete_index.unwrap()); } if self.new_query_param.key != "" || self.new_query_param.value != "" || self.new_query_param.desc != "" { self.new_query_param.enable = true; crt.record .must_get_mut_rest() .request .params .push(self.new_query_param.clone()); self.new_query_param.key = "".to_string(); self.new_query_param.value = "".to_string(); self.new_query_param.desc = "".to_string(); self.new_query_param.enable = false; } } fn render_path_variables( &mut self, ui: &mut Ui, envs: &BTreeMap<String, EnvironmentItemValue>, crt: &mut CentralRequestItem, ) { ui.label("Path Variables"); ui.push_id("path_variables_table", |ui| { let table = TableBuilder::new(ui) .resizable(false) .cell_layout(Layout::left_to_right(Align::Center)) .column(Column::auto()) .column(Column::exact(20.0)) .column(Column::initial(200.0).range(40.0..=300.0)) .column(Column::initial(200.0).range(40.0..=300.0)) .column(Column::remainder()) .max_scroll_height(100.0); table .header(20.0, |mut header| { header.col(|ui| { ui.strong(""); }); header.col(|ui| { ui.strong(""); }); header.col(|ui| { ui.strong("KEY"); }); header.col(|ui| { ui.strong("VALUE"); }); header.col(|ui| { ui.strong("DESCRIPTION"); }); }) .body(|mut body| { self.build_path_variables_body(crt, &envs, &mut body); }); }); } } impl RequestParamsPanel { fn build_query_params_body( &self, data: &mut CentralRequestItem, envs: &BTreeMap<String, EnvironmentItemValue>, body: &mut TableBody, ) -> Option<usize> { let mut delete_index = None; for (index, param) in data .record .must_get_mut_rest() .request .params .iter_mut() .enumerate() { body.row(18.0, |mut row| { row.col(|ui| { ui.add_enabled( param.lock_with == LockWith::NoLock, Checkbox::new(&mut param.enable, ""), ); }); row.col(|ui| { if ui .add_enabled(param.lock_with == LockWith::NoLock, Button::new("x")) .clicked() { delete_index = Some(index) } }); row.col(|ui| { HighlightTemplateSinglelineBuilder::default() .envs(envs.clone()) .enable(param.lock_with == LockWith::NoLock) .all_space(false) .build( "request_parmas_key_".to_string() + index.to_string().as_str(), &mut param.key, ) .ui(ui); }); row.col(|ui| { HighlightTemplateSinglelineBuilder::default() .envs(envs.clone()) .enable(param.lock_with == LockWith::NoLock) .all_space(false) .build( "request_parmas_value_".to_string() + index.to_string().as_str(), &mut param.value, ) .ui(ui); }); row.col(|ui| { ui.add_enabled( param.lock_with == LockWith::NoLock, TextEdit::singleline(&mut param.desc).desired_width(f32::INFINITY), ); }); }); } delete_index } fn build_path_variables_body( &self, data: &mut CentralRequestItem, envs: &BTreeMap<String, EnvironmentItemValue>, body: &mut TableBody, ) { for (index, path_variable) in data .record .must_get_mut_rest() .request .path_variables .iter_mut() .enumerate() { body.row(18.0, |mut row| { row.col(|ui| { let mut enable = true; ui.add_enabled(false, Checkbox::new(&mut enable, "")); }); row.col(|ui| { ui.add_enabled(false, Button::new("x")); }); row.col(|ui| { HighlightTemplateSinglelineBuilder::default() .envs(envs.clone()) .enable(false) .all_space(false) .build( "path_variable_key_".to_string() + index.to_string().as_str(), &mut path_variable.key, ) .ui(ui); }); row.col(|ui| { HighlightTemplateSinglelineBuilder::default() .envs(envs.clone()) .enable(true) .all_space(false) .build( "path_variable_value_".to_string() + index.to_string().as_str(), &mut path_variable.value, ) .ui(ui); }); row.col(|ui| { TextEdit::singleline(&mut path_variable.desc) .desired_width(f32::INFINITY) .ui(ui); }); }); } } fn build_new_query_params_body( &mut self, envs: &BTreeMap<String, EnvironmentItemValue>, mut body: TableBody, ) { body.row(18.0, |mut row| { row.col(|ui| { ui.add_enabled(false, Checkbox::new(&mut self.new_query_param.enable, "")); }); row.col(|ui| { ui.add_enabled(false, Button::new("x")); }); row.col(|ui| { HighlightTemplateSinglelineBuilder::default() .envs(envs.clone()) .all_space(false) .enable(self.new_query_param.lock_with == LockWith::NoLock) .build( "request_params_key_new".to_string(), &mut self.new_query_param.key, ) .ui(ui); }); row.col(|ui| { HighlightTemplateSinglelineBuilder::default() .envs(envs.clone()) .all_space(false) .enable(self.new_query_param.lock_with == LockWith::NoLock) .build( "request_params_value_new".to_string(), &mut self.new_query_param.value, ) .ui(ui); }); row.col(|ui| { ui.add_enabled_ui(self.new_query_param.lock_with == LockWith::NoLock, |ui| { TextEdit::singleline(&mut self.new_query_param.desc) .desired_width(f32::INFINITY) .ui(ui); }); }); }); } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/panels/bottom_panel.rs
crates/netpurr/src/panels/bottom_panel.rs
use egui::{Response, Ui, WidgetText}; use poll_promise::Promise; use netpurr_core::data::workspace_data::WorkspaceData; use crate::data::config_data::ConfigData; use crate::operation::operation::Operation; use crate::panels::VERTICAL_GAP; use crate::utils; #[derive(Default)] pub struct BottomPanel { sync_promise: Option<Promise<rustygit::types::Result<()>>>, } impl BottomPanel { pub fn render( &mut self, ui: &mut Ui, workspace_data: &mut WorkspaceData, operation: Operation, config_data: &mut ConfigData, ) { ui.add_enabled_ui(!operation.get_ui_lock(), |ui| { ui.add_space(VERTICAL_GAP); ui.horizontal(|ui| { // egui::ComboBox::from_id_source("workspace") // .selected_text("Workspace: ".to_string() + self.current_workspace.as_str()) // .show_ui(ui, |ui| { // ui.style_mut().wrap = Some(false); // ui.set_min_width(60.0); // if ui.button("⚙ Manage Workspace").clicked() { // config_data.refresh_workspaces(); // let current_workspace = config_data.select_workspace().to_string(); // operation.add_window(Box::new( // WorkspaceWindows::default().with_open(current_workspace), // )); // } // for (name, _) in config_data.workspaces().iter() { // ui.selectable_value( // &mut self.current_workspace, // name.to_string(), // name.to_string(), // ); // } // }); config_data.select_workspace().map(|select_workspace|{ if let Some(workspace) = config_data .mut_workspaces() .get_mut(select_workspace.as_str()) { if workspace.if_enable_git() { ui.label("Git"); ui.separator(); if self.sync_promise.is_some() { ui.add_enabled_ui(false, |ui| ui.button(egui_phosphor::regular::ARROW_CLOCKWISE)); } else { if ui.button(egui_phosphor::regular::ARROW_CLOCKWISE).clicked() { self.sync_promise = Some(operation.git().git_sync_promise(workspace.path.clone())); } } } } match &self.sync_promise { None => {} Some(result) => match result.ready() { None => { ui.ctx().request_repaint(); } Some(result) => { if result.is_ok() { operation.add_success_toast("Sync Success!") } else { operation.add_error_toast("Sync Failed!") } self.sync_promise = None; workspace_data.reload_data(select_workspace.clone()); } }, } }); // if self.current_workspace != config_data.select_workspace() { // config_data.set_select_workspace(self.current_workspace.clone()); // workspace_data.load_all(self.current_workspace.clone()); // } utils::add_right_space(ui, 280.0); ui.label("Made with jincheng.zhang@thoughtworks.com"); }); }); } pub fn selectable_value( &mut self, ui: &mut Ui, workspace_data: &mut WorkspaceData, selected_value: Option<String>, text: impl Into<WidgetText>, ) -> Response { let mut response = ui.selectable_label(workspace_data.get_env_select() == selected_value, text); if response.clicked() && workspace_data.get_env_select() != selected_value { workspace_data.set_env_select(selected_value); response.mark_changed(); } response } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/panels/response_cookies_panel.rs
crates/netpurr/src/panels/response_cookies_panel.rs
use std::collections::BTreeMap; use netpurr_core::data::cookies_manager::Cookie; #[derive(Default)] pub struct ResponseCookiesPanel {} impl ResponseCookiesPanel { pub fn set_and_render(&mut self, ui: &mut egui::Ui, cookies: &BTreeMap<String, Cookie>) { ui.label("Cookies"); egui::Grid::new("response_cookies_grid") .striped(true) .min_col_width(50.0) .max_col_width(ui.available_width() / 4.0) .num_columns(7) .show(ui, |ui| { ui.strong("Name"); ui.strong("Value"); ui.strong("Domain"); ui.strong("Path"); ui.strong("Expires"); ui.strong("HttpOnly"); ui.strong("Secure"); ui.end_row(); for (_, cookie) in cookies { ui.label(cookie.name.clone()); ui.label(cookie.value.clone()); ui.label(cookie.domain.clone()); ui.label(cookie.path.clone()); ui.label(cookie.expires.clone()); ui.label(cookie.http_only.to_string()); ui.label(cookie.secure.to_string()); ui.end_row(); } }); } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/panels/openapi_editor_panel.rs
crates/netpurr/src/panels/openapi_editor_panel.rs
use egui::{TextEdit, Ui, Widget}; use netpurr_core::data::workspace_data::WorkspaceData; use crate::data::config_data::ConfigData; #[derive(Default)] pub struct OpenApiEditorPanel { source: String, collection_name: String, } impl OpenApiEditorPanel { pub fn render( &mut self, workspace_data: &mut WorkspaceData, config_data: &mut ConfigData, ui: &mut Ui, ) { egui::ScrollArea::vertical() .max_height(ui.available_height() - 30.0) .show(ui, |ui| { let collection_name = config_data.select_collection().unwrap_or_default(); let collection = workspace_data.get_collection_by_name(collection_name.clone()); if self.collection_name != collection_name { self.collection_name = collection_name.clone(); self.source = collection .map(|c| serde_yaml::to_string(&c.openapi).unwrap_or_default()) .unwrap_or_default(); } let theme = egui_extras::syntax_highlighting::CodeTheme::from_memory(ui.ctx()); let mut layouter = |ui: &Ui, string: &str, wrap_width: f32| { let mut layout_job = egui_extras::syntax_highlighting::highlight( ui.ctx(), &theme, string, "yaml", ); layout_job.wrap.max_width = wrap_width; ui.fonts(|f| f.layout_job(layout_job)) }; TextEdit::multiline(&mut self.source) .font(egui::TextStyle::Monospace) // for cursor height .code_editor() .desired_rows(10) .lock_focus(true) .desired_width(f32::INFINITY) .layouter(&mut layouter) .ui(ui) }); } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/panels/response_body_panel.rs
crates/netpurr/src/panels/response_body_panel.rs
use egui::{Image, TextBuffer}; use uuid::Uuid; use netpurr_core::data::http::{Header, Response}; use crate::operation::operation::Operation; use crate::windows::view_json_windows::ViewJsonWindows; #[derive(Default)] pub struct ResponseBodyPanel {} impl ResponseBodyPanel { pub fn set_and_render( &mut self, ui: &mut egui::Ui, operation: &Operation, response: &Response, ) { let theme = egui_extras::syntax_highlighting::CodeTheme::from_memory(ui.ctx()); let mut layouter = |ui: &egui::Ui, string: &str, wrap_width: f32| { let mut layout_job = egui_extras::syntax_highlighting::highlight( ui.ctx(), &theme, string, ResponseBodyPanel::get_language(response).as_str(), ); layout_job.wrap.max_width = wrap_width; ui.fonts(|f| f.layout_job(layout_job)) }; match self.get_response_content_type(response) { None => {} Some(content_type) => { if content_type.value.starts_with("image") { let image = Image::from_bytes( response.request.get_url_with_schema(), response.body.to_vec(), ); ui.add(image); } else { match String::from_utf8(response.body.to_vec()) { Ok(s) => { ui.horizontal(|ui| { let tooltip = "Click to copy the response body"; if ui.button("📋").on_hover_text(tooltip).clicked() { ui.output_mut(|o| o.copied_text = s.to_owned()); operation.add_success_toast("Copy success"); } if content_type.value.contains("json") { if ui.button("View Json Tree").clicked() { operation.add_window(Box::new( ViewJsonWindows::default() .with_json(s.clone(), Uuid::new_v4().to_string()), )) } } }); let mut content = s; ui.push_id("response_body", |ui| { egui::ScrollArea::vertical().show(ui, |ui| { ui.add( egui::TextEdit::multiline(&mut content) .font(egui::TextStyle::Monospace) // for cursor height .code_editor() .desired_rows(12) .lock_focus(true) .desired_width(f32::INFINITY) .layouter(&mut layouter), ); }); }); } Err(e) => { ui.centered_and_justified(|ui| { ui.label("Error String"); }); } } } } } } pub fn get_response_content_type(&self, response: &Response) -> Option<Header> { response .headers .iter() .find(|h| h.key.to_lowercase() == "content-type") .cloned() } fn get_language(response: &Response) -> String { match response.headers.iter().find(|h| h.key == "content-type") { None => "json".to_string(), Some(content_type_header) => { let content_type = content_type_header.value.clone(); if content_type.contains("json") { return "json".to_string(); } else if content_type.contains("html") { return "html".to_string(); } else if content_type.contains("js") { return "js".to_string(); } else if content_type.contains("xml") { return "xml".to_string(); } else { "json".to_string() } } } } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/panels/manager_testcase_panel.rs
crates/netpurr/src/panels/manager_testcase_panel.rs
use std::collections::{BTreeMap, HashMap}; use eframe::epaint::Color32; use egui::{RichText, Ui}; use serde_json::Value; use egui_code_editor::{CodeEditor, ColorTheme}; use netpurr_core::data::collections::Testcase; use netpurr_core::data::workspace_data::{TestItem, WorkspaceData}; use crate::utils; use crate::widgets::syntax::js_syntax; #[derive(Default)] pub struct ManagerTestcasePanel { open: bool, select: Option<String>, new_case_name: String, source: String, message: RichText, test_item: Option<TestItem>, old_test_item_name: String, need_edit_name:Option<String>, edit_name:String, need_focus_edit:bool, } impl ManagerTestcasePanel { pub fn clear(&mut self) { self.source = "".to_string(); self.select = None; self.test_item = None; self.need_edit_name = None; } pub fn render(&mut self, ui: &mut Ui, workspace_data: &mut WorkspaceData, test_item: TestItem) { let mut testcases = BTreeMap::new(); let mut is_change = false; let mut test_item_name = "".to_string(); match &test_item { TestItem::Record(_, folder, record_name) => { testcases = folder.borrow().requests[record_name].testcase(); test_item_name = format!("{}/{}", folder.borrow().get_path(), record_name); } TestItem::Folder(_, folder) => { testcases = folder.borrow().testcases.clone(); test_item_name = folder.borrow().get_path(); } } if self.old_test_item_name != test_item_name { self.clear(); self.old_test_item_name = test_item_name; } egui::panel::SidePanel::left("manager_testcase_left") .max_width(150.0) .show_inside(ui, |ui| { ui.vertical(|ui| { ui.horizontal(|ui| { ui.text_edit_singleline(&mut self.new_case_name); ui.add_enabled_ui( !testcases.contains_key(self.new_case_name.as_str()), |ui| { if ui.button("+").clicked() { if !self.new_case_name.is_empty() { testcases.insert( self.new_case_name.clone(), Testcase { entry_name: "".to_string(), name: self.new_case_name.clone(), value: Default::default(), parent_path: vec![], }, ); is_change = true; } self.new_case_name.clear(); } }, ); }); let mut remove_name_op = None; let testcases_clone = testcases.clone(); egui::scroll_area::ScrollArea::vertical() .max_height(ui.available_height()) .show(ui,|ui|{ for (name, testcase) in testcases_clone.iter() { if self.need_edit_name == Some(name.to_string()){ let editor = ui.text_edit_singleline(&mut self.edit_name); if self.need_focus_edit{ editor.request_focus(); self.need_focus_edit = false; } if editor.lost_focus(){ if !self.edit_name.is_empty()&&!testcases.contains_key(self.edit_name.as_str()){ let mut new_testcase = testcase.clone(); new_testcase.name = self.edit_name.clone(); testcases.insert(self.edit_name.clone(),new_testcase); self.need_edit_name = None; remove_name_op = Some(name); is_change = true; } } }else { let select_value = utils::select_value( ui, &mut self.select, Some(name.clone()), name.clone(), ); if select_value.clicked() { self.source = serde_json::to_string_pretty(&testcase.value).unwrap(); }; select_value.context_menu(|ui| { if ui.button("Rename").clicked() { self.need_edit_name = Some(name.to_string()); self.edit_name = name.to_string(); self.need_focus_edit = true; ui.close_menu(); } if ui.button("Remove").clicked() { remove_name_op = Some(name); ui.close_menu(); is_change = true; } }); } } }); if let Some(remove_name) = remove_name_op { testcases.remove(remove_name); }; }) }); ui.label(self.message.clone()); let mut code_editor = CodeEditor::default() .id_source(format!("{}:{}","testcase_code_editor",self.select.clone().unwrap_or_default())) .with_rows(25) .with_ui_fontsize(ui) .with_syntax(js_syntax()) .with_numlines(true); if ui.visuals().dark_mode { code_editor = code_editor.with_theme(ColorTheme::GRUVBOX) } else { code_editor = code_editor.with_theme(ColorTheme::GRUVBOX_LIGHT) } if let Some(select) = &self.select { egui::ScrollArea::vertical() .min_scrolled_height(200.0) .max_height(400.0) .show(ui, |ui| { let text_edit_output= code_editor.show(ui, &mut self.source); if text_edit_output.response.lost_focus(){ match serde_json::from_str::<HashMap<String, Value>>(&self.source) { Ok(testcase_value) => { self.source = serde_json::to_string_pretty(&testcase_value).unwrap(); } Err(_)=>{ } } } if text_edit_output.response.changed() { match serde_json::from_str::<HashMap<String, Value>>(&self.source) { Ok(testcase_value) => { self.message = RichText::new("Auto save success.").color(Color32::DARK_GREEN); is_change = true; testcases.insert( select.to_string(), Testcase { entry_name: "".to_string(), name: select.to_string(), value: testcase_value, parent_path: vec![], }, ); } Err(e) => { self.message = RichText::new(e.to_string()).color(Color32::DARK_RED); } } } }); } else { let mut text = "Select one testcase to edit, the testcase format is `json`.".to_string(); code_editor.show(ui, &mut text); }; match &test_item { TestItem::Record(_, folder, record_name) => { folder .borrow_mut() .requests .get_mut(record_name) .unwrap() .set_testcases(testcases.clone()); if is_change { workspace_data.save_record(folder.clone(), record_name.clone()); } } TestItem::Folder(_, folder) => { folder.borrow_mut().testcases = testcases.clone(); if is_change { workspace_data.save_folder(folder.clone()) } } }; } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/panels/auth_panel.rs
crates/netpurr/src/panels/auth_panel.rs
use std::cell::RefCell; use std::collections::BTreeMap; use std::rc::Rc; use egui::{Ui, Widget}; use strum::IntoEnumIterator; use netpurr_core::data::auth::{Auth, AuthType}; use netpurr_core::data::collections::{Collection, CollectionFolder}; use netpurr_core::data::environment::EnvironmentItemValue; use crate::panels::{HORIZONTAL_GAP, VERTICAL_GAP}; use crate::widgets::highlight_template::HighlightTemplateSinglelineBuilder; #[derive(Default)] pub struct AuthPanel { envs: BTreeMap<String, EnvironmentItemValue>, collection: Option<Collection>, folder: Option<Rc<RefCell<CollectionFolder>>>, parent_auth: Option<Auth>, name: String, no_inherit: bool, } impl AuthPanel { pub fn set_envs( &mut self, envs: BTreeMap<String, EnvironmentItemValue>, parent_auth: Option<Auth>, ) { self.envs = envs; self.parent_auth = parent_auth } pub fn set_collection_folder( &mut self, collection: Collection, folder: Rc<RefCell<CollectionFolder>>, ) { self.envs = collection.build_envs(); self.collection = Some(collection); self.name = folder.borrow().name.clone(); self.no_inherit = folder.borrow().is_root; self.folder = Some(folder); } fn auth_left(&mut self, data: &mut Auth, ui: &mut Ui) { egui::SidePanel::left(self.name.clone() + "auth_left") .resizable(true) .show_separator_line(true) .show_inside(ui, |ui| { ui.strong("AUTH"); ui.add_space(VERTICAL_GAP); ui.label("The authorization header will be automatically generated when you send the request. "); ui.add_space(VERTICAL_GAP); egui::ComboBox::from_id_source("auth_type") .selected_text(data.auth_type.to_string()) .show_ui(ui, |ui| { ui.style_mut().wrap = Some(false); ui.set_min_width(60.0); for x in AuthType::iter() { if self.no_inherit && x == AuthType::InheritAuthFromParent { continue; } ui.selectable_value(&mut data.auth_type, x.clone(), x.to_string()); } }); ui.add_space(VERTICAL_GAP); }); } fn auth_right(&mut self, data: &mut Auth, ui: &mut Ui) { egui::SidePanel::right(self.name.clone() + "auth_right") .resizable(true) .show_separator_line(false) .min_width(ui.available_width() - HORIZONTAL_GAP * 2.0) .show_inside(ui, |ui| match data.auth_type { AuthType::NoAuth => { ui.centered_and_justified(|ui| { ui.add_space(VERTICAL_GAP * 5.0); ui.label("This request does not use any authorization. "); ui.add_space(VERTICAL_GAP * 5.0); }); } AuthType::BearerToken => { ui.add_space(VERTICAL_GAP * 5.0); ui.horizontal(|ui| { ui.add_space(HORIZONTAL_GAP); ui.label("Token:"); HighlightTemplateSinglelineBuilder::default() .envs(self.envs.clone()) .build("token".to_string(), &mut data.bearer_token) .ui(ui); ui.add_space(HORIZONTAL_GAP); }); ui.add_space(VERTICAL_GAP * 5.0); } AuthType::BasicAuth => { ui.add_space(VERTICAL_GAP * 2.0); ui.horizontal(|ui| { ui.add_space(HORIZONTAL_GAP); ui.label("Username:"); HighlightTemplateSinglelineBuilder::default() .envs(self.envs.clone()) .build("username".to_string(), &mut data.basic_username) .ui(ui); }); ui.add_space(VERTICAL_GAP); ui.horizontal(|ui| { ui.add_space(HORIZONTAL_GAP); ui.label("Password: "); HighlightTemplateSinglelineBuilder::default() .envs(self.envs.clone()) .build("password".to_string(), &mut data.basic_password) .ui(ui); }); ui.add_space(VERTICAL_GAP * 2.0); } AuthType::InheritAuthFromParent => { ui.add_space(VERTICAL_GAP); ui.label("This request is not inheriting any authorization helper at the moment. Save it in a collection to use the parent's authorization helper."); ui.add_space(VERTICAL_GAP); self.parent_auth.clone().map(|parent_auth| { match parent_auth.auth_type { AuthType::InheritAuthFromParent => {} AuthType::NoAuth => { ui.centered_and_justified(|ui| { ui.add_space(VERTICAL_GAP * 5.0); ui.label("This request does not use any authorization. "); ui.add_space(VERTICAL_GAP * 5.0); }); } AuthType::BearerToken => { ui.add_space(VERTICAL_GAP * 5.0); ui.horizontal(|ui| { ui.add_space(HORIZONTAL_GAP); ui.label("Token:"); ui.label(netpurr_core::utils::replace_variable(parent_auth.bearer_token.clone(), self.envs.clone())); ui.add_space(HORIZONTAL_GAP); }); ui.add_space(VERTICAL_GAP * 5.0); } AuthType::BasicAuth => { ui.add_space(VERTICAL_GAP * 2.0); ui.horizontal(|ui| { ui.add_space(HORIZONTAL_GAP); ui.label("Username:"); ui.label(netpurr_core::utils::replace_variable(parent_auth.basic_username.clone(), self.envs.clone())); }); ui.add_space(VERTICAL_GAP); ui.horizontal(|ui| { ui.add_space(HORIZONTAL_GAP); ui.label("Password: "); ui.label(netpurr_core::utils::replace_variable(parent_auth.basic_password.clone(), self.envs.clone())); }); ui.add_space(VERTICAL_GAP * 2.0); } } }); } }); } pub(crate) fn set_and_render(&mut self, ui: &mut Ui, data: &mut Auth) { ui.horizontal(|ui| { self.auth_left(data, ui); self.auth_right(data, ui); }); } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/panels/websocket_content_panel.rs
crates/netpurr/src/panels/websocket_content_panel.rs
use egui::{Ui, Widget}; use strum::IntoEnumIterator; use netpurr_core::data::websocket::MessageType; use netpurr_core::data::workspace_data::WorkspaceData; use crate::operation::operation::Operation; use crate::panels::{HORIZONTAL_GAP, VERTICAL_GAP}; use crate::widgets::highlight_template::HighlightTemplateSinglelineBuilder; #[derive(Default)] pub struct WebsocketContentPanel {} impl WebsocketContentPanel { pub fn set_and_render( &mut self, ui: &mut Ui, operation: &Operation, workspace_data: &mut WorkspaceData, crt_id: String, ) { let envs = workspace_data.get_crt_envs(crt_id.clone()); let mut crt = workspace_data.must_get_crt(crt_id.clone()); ui.horizontal(|ui| { ui.add_space(HORIZONTAL_GAP); for x in MessageType::iter() { crt = workspace_data.must_get_mut_crt(crt_id.clone(), |crt| { ui.selectable_value( &mut crt.record.must_get_mut_websocket().select_message_type, x.clone(), x.to_string(), ); }); } }); ui.add_space(VERTICAL_GAP); match crt.record.must_get_mut_websocket().select_message_type { MessageType::Text => {} MessageType::Binary => {} } ui.horizontal(|ui| { egui::SidePanel::right("websocket_content_right_".to_string()) .resizable(true) .min_width(100.0) .show_separator_line(false) .show_inside(ui, |ui| { let connected = crt.record.must_get_websocket().connected(); ui.add_enabled_ui(connected, |ui| { if ui.button("Send").clicked() { if let Some(session) = &crt.record.must_get_websocket().session { session.send_message( crt.record.must_get_websocket().select_message_type.clone(), crt.record.must_get_websocket().retain_content.clone(), ) } } }); }); egui::SidePanel::left("websocket_content_left_".to_string()) .resizable(true) .min_width(ui.available_width() - HORIZONTAL_GAP * 2.0) .show_inside(ui, |ui| { ui.push_id("websocket_content", |ui| { egui::ScrollArea::vertical() .max_height(400.0) .min_scrolled_height(300.0) .show(ui, |ui| { crt = workspace_data.must_get_mut_crt(crt_id.clone(), |crt| { HighlightTemplateSinglelineBuilder::default() .multiline() .envs(envs) .all_space(true) .build( "request_body".to_string(), &mut crt.record.must_get_mut_websocket().retain_content, ) .ui(ui); }); }); }); }); }); } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/panels/response_headers_panel.rs
crates/netpurr/src/panels/response_headers_panel.rs
use netpurr_core::data::http::Response; #[derive(Default)] pub struct ResponseHeadersPanel {} impl ResponseHeadersPanel { pub fn set_and_render(&mut self, ui: &mut egui::Ui, response: &Response) { ui.label("Headers"); egui::Grid::new("response_headers_grid") .striped(true) .min_col_width(100.0) .max_col_width(ui.available_width()) .num_columns(2) .show(ui, |ui| { ui.strong("Key"); ui.strong("Value"); ui.end_row(); for header in response.headers.iter() { ui.label(header.key.clone()); ui.label(header.value.clone()); ui.end_row(); } }); } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/panels/websocket_panel.rs
crates/netpurr/src/panels/websocket_panel.rs
use eframe::epaint::ahash::HashSet; use egui::{Ui, Widget}; use strum::IntoEnumIterator; use strum_macros::{Display, EnumIter, EnumString}; use url::Url; use netpurr_core::data::auth::{Auth, AuthType}; use netpurr_core::data::http::HttpRecord; use netpurr_core::data::websocket::WebSocketStatus; use netpurr_core::data::workspace_data::WorkspaceData; use crate::data::config_data::ConfigData; use crate::operation::operation::Operation; use crate::panels::auth_panel::AuthPanel; use crate::panels::HORIZONTAL_GAP; use crate::panels::request_headers_panel::RequestHeadersPanel; use crate::panels::request_params_panel::RequestParamsPanel; use crate::panels::request_pre_script_panel::RequestPreScriptPanel; use crate::panels::websocket_content_panel::WebsocketContentPanel; use crate::panels::websocket_event_panel::WebsocketEventPanel; use crate::utils; use crate::utils::HighlightValue; use crate::widgets::highlight_template::HighlightTemplateSinglelineBuilder; use crate::windows::save_crt_windows::SaveCRTWindows; #[derive(Default)] pub struct WebSocketPanel { websocket_content_panel: WebsocketContentPanel, open_request_panel_enum: RequestPanelEnum, request_params_panel: RequestParamsPanel, auth_panel: AuthPanel, request_headers_panel: RequestHeadersPanel, request_pre_script_panel: RequestPreScriptPanel, websocket_event_panel: WebsocketEventPanel, } #[derive(Clone, EnumIter, EnumString, Display, PartialEq)] enum RequestPanelEnum { Content, Params, Authorization, Headers, } impl Default for RequestPanelEnum { fn default() -> Self { RequestPanelEnum::Content } } impl WebSocketPanel { pub fn set_and_render( &mut self, ui: &mut Ui, operation: &Operation, config_data: &mut ConfigData, workspace_data: &mut WorkspaceData, crt_id: String, ) { let envs = workspace_data.get_crt_envs(crt_id.clone()); let parent_auth = workspace_data.get_crt_parent_auth(crt_id.clone()); workspace_data.must_get_mut_crt(crt_id.clone(), |crt| { crt.record .must_get_mut_rest() .sync_everytime(envs.clone(), parent_auth.clone()); }); ui.vertical(|ui| { ui.horizontal(|ui| { self.render_editor_right_panel( operation, config_data, workspace_data, crt_id.clone(), ui, ); self.render_editor_left_panel(workspace_data, crt_id.clone(), ui); }); ui.separator(); self.render_middle_select(operation, workspace_data, crt_id.clone(), ui); }); ui.separator(); self.render_request_open_panel(ui, operation, workspace_data, crt_id.clone()); self.websocket_event_panel .set_and_render(ui, operation, workspace_data, crt_id.clone()); self.toast_event(operation, workspace_data, &crt_id); } fn get_count( hr: &HttpRecord, panel_enum: RequestPanelEnum, parent_auth: &Auth, ) -> HighlightValue { match panel_enum { RequestPanelEnum::Params => { HighlightValue::Usize(hr.request.params.iter().filter(|i| i.enable).count()) } RequestPanelEnum::Authorization => { match hr.request.auth.get_final_type(parent_auth.clone()) { AuthType::InheritAuthFromParent => HighlightValue::None, AuthType::NoAuth => HighlightValue::None, AuthType::BearerToken => HighlightValue::Has, AuthType::BasicAuth => HighlightValue::Has, } } RequestPanelEnum::Headers => { HighlightValue::Usize(hr.request.headers.iter().filter(|i| i.enable).count()) } RequestPanelEnum::Content => HighlightValue::None, } } fn render_editor_right_panel( &mut self, operation: &Operation, config_data: &mut ConfigData, workspace_data: &mut WorkspaceData, crt_id: String, ui: &mut Ui, ) { let (pre_request_parent_script_scopes, mut test_parent_script_scopes) = workspace_data.get_crt_parent_scripts(crt_id.clone()); let envs = workspace_data.get_crt_envs(crt_id.clone()); let mut crt = workspace_data.must_get_crt(crt_id.clone()); egui::SidePanel::right("editor_right_panel") .resizable(false) .show_inside(ui, |ui| { ui.horizontal(|ui| { ui.add_space(HORIZONTAL_GAP); let mut connect = false; let mut lock = false; match &crt.record.must_get_websocket().session { None => { connect = false; } Some(session) => match session.get_status() { WebSocketStatus::Connect => { connect = true; } WebSocketStatus::Connecting => { lock = true; } WebSocketStatus::Disconnect => { connect = false; } WebSocketStatus::ConnectError(_) => { connect = false; } WebSocketStatus::SendError(_) => { connect = false; } WebSocketStatus::SendSuccess => { connect = true; } }, } ui.add_enabled_ui(!lock, |ui| { if !connect { if ui.button("Connect").clicked() { match Url::parse(crt.record.raw_url().as_str()) { Ok(url) => { crt = workspace_data.must_get_mut_crt( crt_id.clone(), |crt| { crt.record.must_get_mut_websocket().session = Some(operation.connect_websocket_with_script( crt.record.must_get_rest().request.clone(), envs, pre_request_parent_script_scopes, test_parent_script_scopes, )); }, ); } Err(e) => operation.add_error_toast(e.to_string()), } crt.record.must_get_websocket(); } } else { if ui.button("Disconnect").clicked() { if let Some(session) = &crt.record.must_get_websocket().session { session.disconnect(); } } } }); if ui.button("Save").clicked() { match &crt.collection_path { None => { operation.add_window(Box::new(SaveCRTWindows::default().with( crt.id.clone(), config_data.select_collection().clone(), ))); } Some(collection_path) => { workspace_data.save_crt( crt.id.clone(), collection_path.clone(), |_| {}, ); operation.add_success_toast("Save success."); crt = workspace_data.must_get_mut_crt(crt_id.clone(), |crt| { crt.set_baseline(); }); } } } }); }); } fn toast_event( &self, operation: &Operation, workspace_data: &mut WorkspaceData, crt_id: &String, ) { workspace_data.must_get_mut_crt(crt_id.clone(), |crt| { if let Some(session) = &crt.record.must_get_websocket().session { if let Some(event) = session.next_event() { match event { WebSocketStatus::Connect => { crt.record.must_get_mut_rest().response = session.get_response(); operation.add_success_toast("Connected") } WebSocketStatus::Connecting => {} WebSocketStatus::Disconnect => operation.add_success_toast("Disconnected"), WebSocketStatus::ConnectError(e) => { operation.add_error_toast(e.to_string()) } WebSocketStatus::SendError(e) => operation.add_error_toast(e.to_string()), WebSocketStatus::SendSuccess => { operation.add_success_toast("Send message success.") } } } } }); } fn render_editor_left_panel( &self, workspace_data: &mut WorkspaceData, cursor: String, ui: &mut Ui, ) { let envs = workspace_data.get_crt_envs(cursor.clone()); workspace_data.must_get_mut_crt(cursor.clone(), |crt| { egui::SidePanel::left("editor_left_panel") .min_width(ui.available_width() - HORIZONTAL_GAP) .show_separator_line(false) .resizable(false) .show_inside(ui, |ui| { ui.horizontal(|ui| { let mut filter: HashSet<String> = HashSet::default(); filter.insert(" ".to_string()); ui.centered_and_justified(|ui| { let raw_url_text_edit = HighlightTemplateSinglelineBuilder::default() .filter(filter) .envs(envs.clone()) .all_space(false) .build( cursor.clone() + "url", &mut crt.record.must_get_mut_rest().request.raw_url, ) .ui(ui); if raw_url_text_edit.has_focus() { crt.record.must_get_mut_rest().sync_raw_url(); } else { crt.record.must_get_mut_rest().build_raw_url(); } }); }); }); }); } fn render_request_open_panel( &mut self, ui: &mut Ui, operation: &Operation, workspace_data: &mut WorkspaceData, crt_id: String, ) { let mut crt = workspace_data.must_get_crt(crt_id.clone()); let envs = workspace_data.get_crt_envs(crt_id.clone()); let (pre_request_parent_script_scopes, _) = workspace_data.get_crt_parent_scripts(crt_id.clone()); match self.open_request_panel_enum { RequestPanelEnum::Params => { self.request_params_panel .set_and_render(ui, workspace_data, crt_id.clone()) } RequestPanelEnum::Authorization => { let mut parent_auth = None; match &crt.collection_path { None => {} Some(collection_path) => { parent_auth = Some(workspace_data.get_collection_auth(collection_path.clone())); } } self.auth_panel.set_envs(envs.clone(), parent_auth); { crt = workspace_data.must_get_mut_crt(crt_id.clone(), |crt| { self.auth_panel .set_and_render(ui, &mut crt.record.must_get_mut_rest().request.auth); }); } } RequestPanelEnum::Headers => { self.request_headers_panel .set_and_render(ui, workspace_data, crt_id.clone()) } RequestPanelEnum::Content => self.websocket_content_panel.set_and_render( ui, operation, workspace_data, crt_id.clone(), ), } } fn render_middle_select( &mut self, operation: &Operation, workspace_data: &mut WorkspaceData, crt_id: String, ui: &mut Ui, ) { let mut crt = workspace_data.must_get_crt(crt_id.clone()); let parent_auth = workspace_data.get_crt_parent_auth(crt_id.clone()); utils::left_right_panel( ui, "rest_middle_select_label".to_string(), |ui| { ui.horizontal(|ui| { for x in RequestPanelEnum::iter() { ui.selectable_value( &mut self.open_request_panel_enum, x.clone(), utils::build_with_count_ui_header( x.to_string(), Self::get_count(crt.record.must_get_rest(), x, &parent_auth), ui, ), ); } }); }, |ui| { }, ); } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/panels/selected_workspace_panel.rs
crates/netpurr/src/panels/selected_workspace_panel.rs
use eframe::emath::Align; use egui::{Layout, Ui}; use netpurr_core::data::workspace_data::WorkspaceData; use crate::data::config_data::ConfigData; use crate::operation::operation::Operation; use crate::panels::HORIZONTAL_GAP; use crate::utils; use crate::widgets::matrix_label::{MatrixLabel, MatrixLabelType}; use crate::windows::workspace_windows::WorkspaceWindows; #[derive(Default)] pub struct SelectedWorkspacePanel { current_workspace: Option<String>, selected_type: Option<String>, } impl SelectedWorkspacePanel { pub fn set_and_render( &mut self, ui: &mut Ui, operation: &Operation, workspace_data: &mut WorkspaceData, config_data: &mut ConfigData, ) { egui::SidePanel::left("selected_workspace_left_panel") .resizable(false) .show_inside(ui, |ui| { self.render_left(ui, workspace_data, config_data, operation); }); egui::CentralPanel::default().show_inside(ui, |ui| { ui.strong("COLLECTIONS"); if self.selected_type.is_some() && self.current_workspace.is_some() { ui.horizontal_wrapped(|ui| { MatrixLabel::new(MatrixLabelType::Add).render( ui, workspace_data, config_data, operation, ); ui.add_space(HORIZONTAL_GAP * 4.0); let mut collection_names: Vec<String> = workspace_data.get_collection_names().into_iter().collect(); collection_names.sort(); for name in collection_names { MatrixLabel::new(MatrixLabelType::Collection(name.to_string())).render( ui, workspace_data, config_data, operation, ); ui.add_space(HORIZONTAL_GAP * 4.0); } }); } }); } fn render_left( &mut self, ui: &mut Ui, workspace_data: &mut WorkspaceData, config_data: &mut ConfigData, operation: &Operation, ) { egui::TopBottomPanel::top("workspace_top_panel") .exact_height(ui.available_height() / 2.0) .show_inside(ui, |ui| { ui.vertical(|ui| { ui.strong(format!("WORKSPACES({})", config_data.workspaces().len())); egui::ScrollArea::vertical() .max_height(f32::INFINITY) .show(ui, |ui| { ui.with_layout(Layout::top_down_justified(Align::Center), |ui| { if ui.button("⚙ Manage Workspace").clicked() { config_data.refresh_workspaces(); operation.add_window(Box::new( WorkspaceWindows::default() .with_open(config_data.select_workspace()), )); } }); let workspaces = config_data.workspaces().clone(); for (name, _) in workspaces.iter() { if self.current_workspace.is_none() { self.current_workspace = Some(name.clone()); config_data.set_select_workspace(Some(name.clone())); workspace_data.load_all(name.clone()); } if utils::select_value( ui, &mut self.current_workspace, Some(name.to_string()), name.to_string(), ) .clicked() { config_data.set_select_workspace(Some(name.clone())); workspace_data.load_all(name.clone()); } } }); }); }); egui::CentralPanel::default().show_inside(ui, |ui| { if self.selected_type.is_none() { self.selected_type = Some("Collections".to_string()) } utils::select_value( ui, &mut self.selected_type, Some("Collections".to_string()), format!( "Collections({})", workspace_data.get_collection_names().len() ), ); }); } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/panels/rest_panel.rs
crates/netpurr/src/panels/rest_panel.rs
use egui::{Button, Ui, Widget}; use egui::ahash::HashSet; use poll_promise::Promise; use strum::IntoEnumIterator; use strum_macros::{Display, EnumIter, EnumString}; use netpurr_core::data::auth::{Auth, AuthType}; use netpurr_core::data::http::{BodyType, HttpRecord, LockWith, Method}; use netpurr_core::data::test::TestStatus; use netpurr_core::data::workspace_data::WorkspaceData; use netpurr_core::runner::{RunRequestInfo, TestRunError, TestRunResult}; use crate::data::config_data::ConfigData; use crate::operation::operation::Operation; use crate::panels::auth_panel::AuthPanel; use crate::panels::HORIZONTAL_GAP; use crate::panels::request_body_panel::RequestBodyPanel; use crate::panels::request_headers_panel::RequestHeadersPanel; use crate::panels::request_params_panel::RequestParamsPanel; use crate::panels::request_pre_script_panel::RequestPreScriptPanel; use crate::panels::test_script_panel::TestScriptPanel; use crate::utils; use crate::utils::HighlightValue; use crate::widgets::highlight_template::HighlightTemplateSinglelineBuilder; use crate::windows::save_crt_windows::SaveCRTWindows; #[derive(Default)] pub struct RestPanel { open_request_panel_enum: RequestPanelEnum, request_params_panel: RequestParamsPanel, auth_panel: AuthPanel, request_headers_panel: RequestHeadersPanel, request_body_panel: RequestBodyPanel, request_pre_script_panel: RequestPreScriptPanel, test_script_panel: TestScriptPanel, send_promise: Option<Promise<Result<TestRunResult, TestRunError>>>, } #[derive(Clone, EnumIter, EnumString, Display, PartialEq)] enum RequestPanelEnum { Params, Authorization, Headers, Body, } impl Default for RequestPanelEnum { fn default() -> Self { RequestPanelEnum::Params } } impl RestPanel { pub fn set_and_render( &mut self, ui: &mut Ui, operation: &Operation, config_data: &mut ConfigData, workspace_data: &mut WorkspaceData, crt_id: String, ) { let envs = workspace_data.get_crt_envs(crt_id.clone()); let parent_auth = workspace_data.get_crt_parent_auth(crt_id.clone()); workspace_data.must_get_mut_crt(crt_id.clone(), |crt| { crt.record .must_get_mut_rest() .sync_everytime(envs.clone(), parent_auth.clone()); }); ui.vertical(|ui| { ui.horizontal(|ui| { self.render_editor_right_panel( operation, config_data, workspace_data, crt_id.clone(), ui, ); self.render_editor_left_panel(workspace_data, crt_id.clone(), ui); }); ui.separator(); self.render_middle_select(operation, workspace_data, crt_id.clone(), ui); ui.separator(); }); self.send_promise(ui, workspace_data, operation, crt_id.clone()); egui::ScrollArea::horizontal().show(ui, |ui| { self.render_request_open_panel(ui, operation, workspace_data, crt_id.clone()); }); } fn get_count( hr: &HttpRecord, panel_enum: RequestPanelEnum, parent_auth: &Auth, ) -> HighlightValue { match panel_enum { RequestPanelEnum::Params => { HighlightValue::Usize(hr.request.params.iter().filter(|i| i.enable).count()) } RequestPanelEnum::Authorization => { match hr.request.auth.get_final_type(parent_auth.clone()) { AuthType::InheritAuthFromParent => HighlightValue::None, AuthType::NoAuth => HighlightValue::None, AuthType::BearerToken => HighlightValue::Has, AuthType::BasicAuth => HighlightValue::Has, } } RequestPanelEnum::Headers => { HighlightValue::Usize(hr.request.headers.iter().filter(|i| i.enable).count()) } RequestPanelEnum::Body => match hr.request.body.body_type { BodyType::NONE => HighlightValue::None, BodyType::FROM_DATA => HighlightValue::Usize(hr.request.body.body_form_data.len()), BodyType::X_WWW_FROM_URLENCODED => { HighlightValue::Usize(hr.request.body.body_xxx_form.len()) } BodyType::RAW => { if hr.request.body.body_str != "" { HighlightValue::Has } else { HighlightValue::None } } BodyType::BINARY => { if hr.request.body.body_file != "" { HighlightValue::Has } else { HighlightValue::None } } }, } } fn render_editor_right_panel( &mut self, operation: &Operation, config_data: &mut ConfigData, workspace_data: &mut WorkspaceData, crt_id: String, ui: &mut Ui, ) { let mut send_rest = None; let envs = workspace_data.get_crt_envs(crt_id.clone()); let parent_auth = workspace_data.get_crt_parent_auth(crt_id.clone()); let mut crt = workspace_data.must_get_crt(crt_id.clone()); egui::SidePanel::right("editor_right_panel") .resizable(false) .show_inside(ui, |ui| { ui.horizontal(|ui| { ui.add_space(HORIZONTAL_GAP); if self.send_promise.is_some() { ui.add_enabled(false, Button::new("Send")); } else { if ui.button("Send").clicked() { crt = workspace_data.must_get_mut_crt(crt_id.clone(), |crt| { crt.record .must_get_mut_rest() .prepare_send(envs.clone(), parent_auth.clone()); }); let send_response = operation.send_rest_with_script_promise(RunRequestInfo { shared_map: Default::default(), collection_path: crt.collection_path.clone(), request_name: crt.get_tab_name(), request: crt.record.must_get_rest().request.clone(), envs: envs.clone(), pre_request_scripts: vec![], test_scripts: vec![], testcase: Default::default(), }); self.send_promise = Some(send_response); send_rest = Some(crt.record.clone()); } } if ui.button("Save").clicked() { match &crt.collection_path { None => { operation.add_window(Box::new(SaveCRTWindows::default().with( crt.id.clone(), config_data.select_collection().clone(), ))); } Some(collection_path) => { workspace_data.save_crt( crt.id.clone(), collection_path.clone(), |_| {}, ); operation.add_success_toast("Save success."); crt = workspace_data.must_get_mut_crt(crt_id.clone(), |crt| { crt.set_baseline(); }); } } } }); }); send_rest.map(|r| { workspace_data.history_record(r); }); } fn render_editor_left_panel( &self, workspace_data: &mut WorkspaceData, cursor: String, ui: &mut Ui, ) { let envs = workspace_data.get_crt_envs(cursor.clone()); workspace_data.must_get_mut_crt(cursor.clone(), |crt| { let mut min_width = ui.available_width() - HORIZONTAL_GAP; if min_width < HORIZONTAL_GAP { min_width = HORIZONTAL_GAP } egui::SidePanel::left("editor_left_panel") .min_width(min_width) .show_separator_line(false) .resizable(false) .show_inside(ui, |ui| { ui.horizontal(|ui| { egui::ComboBox::from_id_source("method") .selected_text(crt.record.method()) .show_ui(ui, |ui| { ui.style_mut().wrap = Some(false); ui.set_min_width(60.0); for x in Method::iter() { ui.selectable_value( &mut crt.record.must_get_mut_rest().request.method, x.clone(), x.to_string(), ); } }); let mut filter: HashSet<String> = HashSet::default(); filter.insert(" ".to_string()); ui.centered_and_justified(|ui| { let raw_url_text_edit = HighlightTemplateSinglelineBuilder::default() .filter(filter) .envs(envs.clone()) .all_space(false) .build( cursor.clone() + "url", &mut crt.record.must_get_mut_rest().request.raw_url, ) .ui(ui); if raw_url_text_edit.has_focus() { crt.record.must_get_mut_rest().sync_raw_url(); } else { crt.record.must_get_mut_rest().build_raw_url(); } }); }); }); }); } fn render_request_open_panel( &mut self, ui: &mut Ui, operation: &Operation, workspace_data: &mut WorkspaceData, crt_id: String, ) { let mut crt = workspace_data.must_get_crt(crt_id.clone()); let envs = workspace_data.get_crt_envs(crt_id.clone()); let (pre_request_parent_script_scopes, _) = workspace_data.get_crt_parent_scripts(crt_id.clone()); match self.open_request_panel_enum { RequestPanelEnum::Params => { self.request_params_panel .set_and_render(ui, workspace_data, crt_id.clone()); } RequestPanelEnum::Authorization => { let mut parent_auth = None; match &crt.collection_path { None => {} Some(collection_path) => { parent_auth = Some(workspace_data.get_collection_auth(collection_path.clone())); } } self.auth_panel.set_envs(envs.clone(), parent_auth); { crt = workspace_data.must_get_mut_crt(crt_id.clone(), |crt| { self.auth_panel .set_and_render(ui, &mut crt.record.must_get_mut_rest().request.auth); }); } } RequestPanelEnum::Headers => { self.request_headers_panel .set_and_render(ui, workspace_data, crt_id.clone()); } RequestPanelEnum::Body => self.request_body_panel.set_and_render( ui, operation, workspace_data, crt_id.clone(), ), } } fn send_promise( &mut self, ui: &mut Ui, workspace_data: &mut WorkspaceData, operation: &Operation, crt_id: String, ) { if let Some(promise) = &self.send_promise { if let Some(result) = promise.ready() { workspace_data.save_cookies(); workspace_data.must_get_mut_crt(crt_id.clone(), |crt| match result { Ok(test_run_result) => { test_run_result .request .headers .iter() .filter(|h| h.lock_with != LockWith::NoLock) .for_each(|h| { crt.record .must_get_mut_rest() .request .headers .push(h.clone()); }); match &test_run_result.response { None => { crt.record.must_get_mut_rest().error(); operation.add_error_toast("Send request failed: Response is none".to_string()); } Some(response) => { crt.record.must_get_mut_rest().response = response.clone(); crt.record.must_get_mut_rest().ready(); operation.add_success_toast("Send request success"); crt.test_result = test_run_result.test_result.clone(); match test_run_result.test_result.status { TestStatus::None => {} TestStatus::PASS => { operation.add_success_toast("Test success."); } TestStatus::FAIL => { operation.add_error_toast("Test failed."); } TestStatus::WAIT => {} TestStatus::SKIP => {} TestStatus::RUNNING => {} } } } } Err(e) => { crt.record.must_get_mut_rest().error(); operation.add_error_toast(format!( "Send request failed: {}", e.error.to_string() )); } }); self.send_promise = None; } else { ui.ctx().request_repaint(); workspace_data.must_get_mut_crt(crt_id.clone(), |crt| { crt.record.must_get_mut_rest().pending() }); } } } fn render_middle_select( &mut self, operation: &Operation, workspace_data: &mut WorkspaceData, crt_id: String, ui: &mut Ui, ) { let mut crt = workspace_data.must_get_crt(crt_id.clone()); let parent_auth = workspace_data.get_crt_parent_auth(crt_id.clone()); egui::scroll_area::ScrollArea::horizontal().show(ui, |ui| { ui.horizontal(|ui| { for x in RequestPanelEnum::iter() { ui.selectable_value( &mut self.open_request_panel_enum, x.clone(), utils::build_with_count_ui_header( x.to_string(), RestPanel::get_count(crt.record.must_get_rest(), x, &parent_auth), ui, ), ); } }); }); } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/panels/test_group_panel.rs
crates/netpurr/src/panels/test_group_panel.rs
use std::cell::RefCell; use std::fmt::format; use std::rc::Rc; use egui::{ScrollArea, Ui}; use netpurr_core::data::collections::CollectionFolder; use netpurr_core::data::workspace_data::{TestItem, WorkspaceData}; use crate::data::config_data::ConfigData; use crate::operation::operation::Operation; use crate::utils; #[derive(Default)] pub struct TestGroupPanel { collection_name: String, selected_test_item_name: String, selected_test_item: Option<TestItem>, } impl TestGroupPanel { pub fn render( &mut self, operation: &Operation, workspace_data: &mut WorkspaceData, config_data: &mut ConfigData, ui: &mut Ui, ) { if workspace_data.selected_test_item.is_none(){ self.selected_test_item = None; } if self.selected_test_item.is_none() { self.selected_test_item = workspace_data.selected_test_item.clone(); } let collection_name = config_data.select_collection().unwrap_or_default(); if self.collection_name != collection_name { self.collection_name = collection_name.clone(); workspace_data.selected_test_item = None } workspace_data .get_collection_by_name(self.collection_name.clone()) .map(|collection| { let mut name = "".to_string(); match &self.selected_test_item { None => { name = collection.folder.borrow().name.clone(); workspace_data.selected_test_item = Some(TestItem::Folder( self.collection_name.clone(), collection.folder.clone(), )); } Some(test_item) => match test_item { TestItem::Folder(_, f) => { name = f.borrow().get_path(); } TestItem::Record(_, f, _) => { name = f.borrow().get_path(); } }, } ui.label("Select Test Group"); if ui.link(format!("{} {} {}",egui_phosphor::regular::ARROW_LEFT,egui_phosphor::regular::FOLDER, name)).clicked() { let paths: Vec<&str> = name.split("/").collect(); if paths.len() > 1 { let new_paths = &paths[0..paths.len() - 1]; if let (_, Some(folder)) = workspace_data.get_folder_with_path(new_paths.join("/")) { self.selected_test_item = Some(TestItem::Folder( self.collection_name.clone(), folder.clone(), )); } } } ui.separator(); self.render_list(workspace_data, ui); }); } fn render_list(&mut self, workspace_data: &mut WorkspaceData, ui: &mut Ui) { ScrollArea::vertical() .max_height(ui.available_height() - 30.0) .show(ui, |ui| match self.selected_test_item.clone() { None => {} Some(test_item) => match test_item { TestItem::Folder(collection_name, folder) => { self.render_folder(workspace_data, ui, collection_name, folder); } TestItem::Record(collection_name, folder, _) => { self.render_folder(workspace_data, ui, collection_name, folder); } }, }); } fn render_folder( &mut self, workspace_data: &mut WorkspaceData, ui: &mut Ui, collection_name: String, folder: Rc<RefCell<CollectionFolder>>, ) { let label = utils::select_value( ui, &mut self.selected_test_item_name, folder.borrow().get_path(), format!("{} ../{}",egui_phosphor::regular::FOLDER,folder.borrow().name.clone()), ); if label.clicked() { workspace_data.selected_test_item = Some(TestItem::Folder(collection_name.clone(), folder.clone())); } if label.double_clicked() { let path = folder.borrow().get_path(); let count = path.split("/").count(); if count>1 { let parent_paths: Vec<&str> = path.split("/").take(count - 1).collect(); let parent_path = parent_paths.join("/"); let (_, parent_folder) = workspace_data.get_folder_with_path(parent_path); parent_folder.map(|p| { self.selected_test_item = Some(TestItem::Folder(collection_name.clone(), p.clone())); }); } } for (name, cf_child) in folder.borrow().folders.iter() { let label = utils::select_value( ui, &mut self.selected_test_item_name, cf_child.borrow().get_path(), format!("{} {}",egui_phosphor::regular::FOLDER,name.clone()), ); if label.clicked() { workspace_data.selected_test_item = Some(TestItem::Folder(collection_name.clone(), cf_child.clone())); } if label.double_clicked() { self.selected_test_item = Some(TestItem::Folder(collection_name.clone(), cf_child.clone())); } } for (_, hr) in folder.borrow().requests.iter() { let label = utils::select_value( ui, &mut self.selected_test_item_name, format!("{}/{}", folder.borrow().get_path(), hr.name()), utils::build_rest_ui_header(hr.clone(), None, ui), ); if label.clicked() { workspace_data.selected_test_item = Some(TestItem::Record( collection_name.clone(), folder.clone(), hr.name(), )); } if label.double_clicked() { self.selected_test_item = Some(TestItem::Record( collection_name.clone(), folder.clone(), hr.name(), )); } } } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/panels/mod.rs
crates/netpurr/src/panels/mod.rs
pub mod auth_panel; pub mod bottom_panel; pub mod collection_panel; pub mod history_panel; pub mod left_panel; pub mod manager_testcase_panel; pub mod openapi_editor_panel; pub mod openapi_show_request_panel; pub mod request_body_form_data_panel; pub mod request_body_panel; pub mod request_body_xxx_form_panel; pub mod request_headers_panel; pub mod request_params_panel; pub mod request_pre_script_panel; pub mod response_body_panel; pub mod response_cookies_panel; pub mod response_headers_panel; pub mod response_log_panel; pub mod response_panel; pub mod rest_panel; pub mod selected_collection_panel; pub mod selected_workspace_panel; pub mod test_editor_panel; pub mod test_group_panel; pub mod test_result_panel; pub mod test_script_panel; pub mod top_panel; pub mod websocket_content_panel; pub mod websocket_event_panel; pub mod websocket_panel; pub const HORIZONTAL_GAP: f32 = 8.0; pub const VERTICAL_GAP: f32 = 8.0;
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/panels/test_script_panel.rs
crates/netpurr/src/panels/test_script_panel.rs
use std::cell::RefCell; use std::ops::Add; use std::rc::Rc; use egui::Ui; use prettify_js::prettyprint; use egui_code_editor::{CodeEditor, ColorTheme, Prompt}; use netpurr_core::data::collections::CollectionFolder; use netpurr_core::data::workspace_data::{TestItem, WorkspaceData}; use crate::widgets::syntax::js_syntax; #[derive(Default)] pub struct TestScriptPanel {} #[derive(Clone)] pub enum CrtOrFolder { CRT(String), Folder(Rc<RefCell<CollectionFolder>>), } impl TestScriptPanel { pub fn set_and_render( &mut self, ui: &mut Ui, workspace_data: &mut WorkspaceData, test_item: TestItem, ) { let mut script = "".to_string(); match &test_item { TestItem::Folder(_, folder) => { script = folder.borrow().test_script.clone(); } TestItem::Record(_, folder, record_name) => { folder .borrow() .requests .get(record_name.as_str()) .map(|record| script = record.test_script()); } } let compare_script = script.clone(); egui::panel::SidePanel::left("manager_testcase_left") .max_width(150.0) .show_inside(ui, |ui| { ui.label("Test scripts are written in JavaScript, and are run after the response is received."); ui.separator(); ui.horizontal(|ui| { egui::ScrollArea::vertical() .min_scrolled_height(250.0) .id_source("test_manager_test_script_snippets") .show(ui, |ui| { ui.vertical(|ui| { ui.strong("SNIPPETS"); if ui.link("Test Example").clicked() { script = script.clone().add(r#"let response = netpurr.resp(); console.log(response); netpurr.test("This is a test example",function(){ // assert("expect", "actual"); assert("test",response.json.cookies.freeform); }); "#) } if ui.link("Status is 200").clicked(){ script = script.clone().add(r#" let response = netpurr.resp(); netpurr.test("Response status is 200",function(){ assert(200,response.status); }); "#) } if ui.link("Log info message").clicked() { script = script.clone().add("\nconsole.log(\"info1\",\"info2\");"); } if ui.link("Log warn message").clicked() { script = script.clone().add("\nconsole.warn(\"info1\",\"info2\");"); } if ui.link("Log error message").clicked() { script = script.clone().add("\nconsole.error(\"error1\",\"error2\");"); } if ui.link("Get a variable").clicked() { script = script.clone().add("\nnetpurr.get_env(\"variable_key\");"); } if ui.link("Set a variable").clicked() { script = script.clone().add("\nnetpurr.set_env(\"variable_key\",\"variable_value\");"); } if ui.link("Get a shared").clicked() { script = script.clone().add("\nnetpurr.get_shared(\"shared_key\");"); } if ui.link("Wait a shared").clicked() { script = script.clone().add("\nawait netpurr.wait_shared(\"shared_key\");"); } if ui.link("Set a shared").clicked() { script = script.clone().add("\nnetpurr.set_shared(\"shared_key\",\"shared_value\");"); } if ui.link("Sleep").clicked() { script = script.clone().add("\nawait sleep(1000);"); } if ui.link("Get response").clicked() { script = script.clone().add("\nlet response = netpurr.resp();\nconsole.log(response)"); } }); }); }); }); egui::ScrollArea::vertical() .max_height(ui.available_height()-30.0) .id_source("test_manager_test_script") .show(ui, |ui| { let prompt_yaml = include_str!("../../prompt/js.yaml"); let mut code_editor = CodeEditor::default() .id_source("test_code_editor") .with_rows(25) .with_ui_fontsize(ui) .with_prompt(Prompt::from_str(prompt_yaml)) .with_syntax(js_syntax()) .with_numlines(true); if ui.visuals().dark_mode { code_editor = code_editor.with_theme(ColorTheme::GRUVBOX) } else { code_editor = code_editor.with_theme(ColorTheme::GRUVBOX_LIGHT) } let response = code_editor.show(ui, &mut script).response; if response.lost_focus(){ let (pretty, _) = prettyprint(script.as_str()); script = pretty; } }); if compare_script != script { match &test_item { TestItem::Folder(_, folder) => { folder.borrow_mut().test_script = script.clone(); workspace_data.save_folder(folder.clone()); } TestItem::Record(_, folder, record_name) => { folder .borrow_mut() .requests .get_mut(record_name.as_str()) .map(|record| { record.set_test_script(script.clone()); }); workspace_data.save_record(folder.clone(), record_name.clone()); } } } } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/panels/request_pre_script_panel.rs
crates/netpurr/src/panels/request_pre_script_panel.rs
use std::ops::Add; use egui::Ui; use prettify_js::prettyprint; use egui_code_editor::{CodeEditor, ColorTheme, Prompt}; use netpurr_core::data::workspace_data::{TestItem, WorkspaceData}; use crate::widgets::syntax::js_syntax; #[derive(Default)] pub struct RequestPreScriptPanel {} impl RequestPreScriptPanel { pub fn set_and_render( &mut self, ui: &mut Ui, workspace_data: &mut WorkspaceData, test_item: TestItem, ) { let mut script = "".to_string(); match &test_item { TestItem::Folder(_, folder) => { script = folder.borrow().pre_request_script.clone(); } TestItem::Record(_, folder, record_name) => { folder .borrow() .requests .get(record_name.as_str()) .map(|record| script = record.pre_request_script()); } } let compare_script = script.clone(); egui::panel::SidePanel::left("manager_testcase_left") .max_width(150.0) .show_inside(ui, |ui| { ui.label("Pre-request scripts are written in JavaScript, and are run before the request is sent."); ui.separator(); ui.horizontal(|ui| { egui::ScrollArea::vertical().min_scrolled_height(250.0) .id_source("test_manager_pre_request_script_snippets") .show(ui, |ui| { ui.vertical(|ui| { ui.strong("SNIPPETS"); if ui.link("Get testcase info").clicked() { script = script.clone().add("\nlet value = netpurr.get_testcase().key;"); } if ui.link("Log info message").clicked() { script = script.clone().add("\nconsole.log(\"info1\",\"info2\");"); } if ui.link("Log warn message").clicked() { script = script.clone().add("\nconsole.warn(\"info1\",\"info2\");"); } if ui.link("Log error message").clicked() { script = script.clone().add("\nconsole.error(\"error1\",\"error2\");"); } if ui.link("Get a variable").clicked() { script = script.clone().add("\nnetpurr.get_env(\"variable_key\");"); } if ui.link("Set a variable").clicked() { script = script.clone().add("\nnetpurr.set_env(\"variable_key\",\"variable_value\");"); } if ui.link("Add a header").clicked() { script = script.clone().add("\nnetpurr.add_header(\"header_key\",\"header_value\");"); } if ui.link("Add a params").clicked() { script = script.clone().add("\nnetpurr.add_params(\"params_key\",\"params_value\");"); } if ui.link("Get a shared").clicked() { script = script.clone().add("\nnetpurr.get_shared(\"shared_key\");"); } if ui.link("Wait a shared").clicked() { script = script.clone().add("\nawait netpurr.wait_shared(\"shared_key\");"); } if ui.link("Set a shared").clicked() { script = script.clone().add("\nnetpurr.set_shared(\"shared_key\",\"shared_value\");"); } if ui.link("Sleep").clicked() { script = script.clone().add("\nawait sleep(1000);"); } if ui.link("Fetch a http request").clicked() { script = script.clone().add( r#"let request = { "method":"post", "url":"http://www.httpbin.org/post", "headers":[{ "name":"name", "value":"value" }], "body":"body" } let response = await fetch(request); console.log(response)"#) } }); }); }); }); ui.push_id("pre_request_script", |ui| { egui::ScrollArea::vertical() .min_scrolled_height(ui.available_height()-30.0) .id_source("test_manager_pre_request_script") .show(ui, |ui| { let prompt_yaml = include_str!("../../prompt/js.yaml"); let mut code_editor = CodeEditor::default() .id_source("request_pre_script_code_editor") .with_rows(25) .with_ui_fontsize(ui) .with_syntax(js_syntax()) .with_prompt(Prompt::from_str(prompt_yaml)) .with_numlines(true); if ui.visuals().dark_mode { code_editor = code_editor.with_theme(ColorTheme::GRUVBOX) } else { code_editor = code_editor.with_theme(ColorTheme::GRUVBOX_LIGHT) } let response = code_editor.show(ui, &mut script).response; if response.lost_focus(){ let (pretty, _) = prettyprint(script.as_str()); script = pretty; } }); }); if compare_script != script { match &test_item { TestItem::Folder(_, folder) => { folder.borrow_mut().pre_request_script = script.clone(); workspace_data.save_folder(folder.clone()); } TestItem::Record(_, folder, record_name) => { folder .borrow_mut() .requests .get_mut(record_name.as_str()) .map(|record| { record.set_pre_request_script(script.clone()); }); workspace_data.save_record(folder.clone(), record_name.clone()); } } } } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/panels/request_body_xxx_form_panel.rs
crates/netpurr/src/panels/request_body_xxx_form_panel.rs
use std::collections::BTreeMap; use eframe::emath::Align; use egui::{Button, Checkbox, Layout, TextBuffer, TextEdit, Widget}; use egui_extras::{Column, TableBody, TableBuilder}; use netpurr_core::data::central_request_data::CentralRequestItem; use netpurr_core::data::environment::EnvironmentItemValue; use netpurr_core::data::http::MultipartData; use netpurr_core::data::workspace_data::WorkspaceData; use crate::widgets::highlight_template::HighlightTemplateSinglelineBuilder; #[derive(Default)] pub struct RequestBodyXXXFormPanel { new_form: MultipartData, } impl RequestBodyXXXFormPanel { pub fn set_and_render( &mut self, ui: &mut egui::Ui, workspace_data: &mut WorkspaceData, crt_id: String, ) { let envs = workspace_data.get_crt_envs(crt_id.clone()); workspace_data.must_get_mut_crt(crt_id.clone(), |crt| { let mut delete_index = None; let table = TableBuilder::new(ui) .resizable(false) .cell_layout(Layout::left_to_right(Align::Center)) .column(Column::auto()) .column(Column::exact(20.0)) .column(Column::initial(200.0).range(40.0..=300.0)) .column(Column::initial(200.0).range(40.0..=300.0)) .column(Column::remainder()) .max_scroll_height(100.0); table .header(20.0, |mut header| { header.col(|ui| { ui.strong(""); }); header.col(|ui| { ui.strong(""); }); header.col(|ui| { ui.strong("KEY"); }); header.col(|ui| { ui.strong("VALUE"); }); header.col(|ui| { ui.strong("DESCRIPTION"); }); }) .body(|mut body| { delete_index = self.build_body(crt, &envs, &mut body); self.build_new_body(envs, body); }); if delete_index.is_some() { crt.record .must_get_mut_rest() .request .body .body_xxx_form .remove(delete_index.unwrap()); } if self.new_form.key != "" || self.new_form.value != "" || self.new_form.desc != "" { self.new_form.enable = true; crt.record .must_get_mut_rest() .request .body .body_xxx_form .push(self.new_form.clone()); self.new_form.key = "".to_string(); self.new_form.value = "".to_string(); self.new_form.desc = "".to_string(); self.new_form.enable = false; } }); } } impl RequestBodyXXXFormPanel { fn build_body( &self, data: &mut CentralRequestItem, envs: &BTreeMap<String, EnvironmentItemValue>, mut body: &mut TableBody, ) -> Option<usize> { let mut delete_index: Option<usize> = None; for (index, param) in data .record .must_get_mut_rest() .request .body .body_xxx_form .iter_mut() .enumerate() { body.row(18.0, |mut row| { row.col(|ui| { ui.checkbox(&mut param.enable, ""); }); row.col(|ui| { if ui.button("x").clicked() { delete_index = Some(index) } }); row.col(|ui| { HighlightTemplateSinglelineBuilder::default() .envs(envs.clone()) .all_space(false) .build( "request_body_key_".to_string() + index.to_string().as_str(), &mut param.key, ) .ui(ui); }); row.col(|ui| { HighlightTemplateSinglelineBuilder::default() .envs(envs.clone()) .all_space(false) .build( "request_body_value_".to_string() + index.to_string().as_str(), &mut param.value, ) .ui(ui); }); row.col(|ui| { TextEdit::singleline(&mut param.desc) .desired_width(f32::INFINITY) .ui(ui); }); }); } delete_index } fn build_new_body( &mut self, envs: BTreeMap<String, EnvironmentItemValue>, mut body: TableBody, ) { body.row(18.0, |mut row| { row.col(|ui| { ui.add_enabled(false, Checkbox::new(&mut self.new_form.enable, "")); }); row.col(|ui| { ui.add_enabled(false, Button::new("x")); }); row.col(|ui| { HighlightTemplateSinglelineBuilder::default() .envs(envs.clone()) .all_space(false) .build("request_body_key_new".to_string(), &mut self.new_form.key) .ui(ui); }); row.col(|ui| { HighlightTemplateSinglelineBuilder::default() .envs(envs) .all_space(false) .build( "request_body_value_new".to_string(), &mut self.new_form.value, ) .ui(ui); }); row.col(|ui| { TextEdit::singleline(&mut self.new_form.desc) .desired_width(f32::INFINITY) .ui(ui); }); }); } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/panels/openapi_show_request_panel.rs
crates/netpurr/src/panels/openapi_show_request_panel.rs
use std::cell::RefCell; use std::collections::BTreeMap; use std::rc::Rc; use egui::{CollapsingHeader, Response, Ui}; use uuid::Uuid; use netpurr_core::data::central_request_data::CentralRequestItem; use netpurr_core::data::collections::{Collection, CollectionFolder}; use netpurr_core::data::record::Record; use netpurr_core::data::workspace_data::WorkspaceData; use crate::import::openapi::OpenApi; use crate::operation::operation::Operation; use crate::utils; use crate::utils::openapi_help::OpenApiHelp; #[derive(Default)] pub struct OpenApiShowRequestPanel {} impl OpenApiShowRequestPanel { pub fn render( &self, ui: &mut Ui, workspace_data: &mut WorkspaceData, operation: &Operation, collection: Collection, ) { if let Some(source_openapi) = collection.openapi.clone() { let openapi = OpenApi { openapi_help: OpenApiHelp { openapi: source_openapi, }, }; if let Ok(collection) = openapi.to_collection() { let folders = collection.folder.borrow().folders.clone(); for (cf_name, cf) in folders.iter() { self.set_openapi_folder( ui, operation, workspace_data, collection.clone(), collection.folder.clone(), cf.clone(), format!("{}/{}", collection.folder.borrow().name, cf_name.clone()), ); } } } } fn set_openapi_folder( &self, ui: &mut Ui, operation: &Operation, workspace_data: &mut WorkspaceData, collection: Collection, parent_folder: Rc<RefCell<CollectionFolder>>, folder: Rc<RefCell<CollectionFolder>>, path: String, ) { let folder_name = folder.borrow().name.clone(); let response = CollapsingHeader::new(folder_name.clone()) .default_open(false) .show(ui, |ui| { let folders = folder.borrow().folders.clone(); for (name, cf) in folders.iter() { self.set_openapi_folder( ui, operation, workspace_data, collection.clone(), parent_folder.clone(), cf.clone(), format!("{}/{}", path, name), ) } let requests = folder.borrow().requests.clone(); self.render_openapi_request( ui, operation, workspace_data, collection.folder.borrow().name.clone(), path.clone(), requests, ); }) .header_response; } fn render_openapi_request( &self, ui: &mut Ui, operation: &Operation, workspace_data: &mut WorkspaceData, collection_name: String, path: String, requests: BTreeMap<String, Record>, ) { for (_, record) in requests.iter() { let lb = utils::build_rest_ui_header(record.clone(), None, ui); let button = ui.button(lb); button.context_menu(|ui| { if ui.button("Add to request").clicked() { workspace_data.add_crt(CentralRequestItem { id: Uuid::new_v4().to_string(), collection_path: None, record: record.clone(), ..Default::default() }); ui.close_menu(); } }); self.popup_openapi_request_item( operation, workspace_data, collection_name.clone(), button, &record, path.clone(), ) } } fn popup_openapi_request_item( &self, operation: &Operation, workspace_data: &mut WorkspaceData, collection_name: String, response: Response, record: &Record, path: String, ) { } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/panels/request_headers_panel.rs
crates/netpurr/src/panels/request_headers_panel.rs
use std::collections::BTreeMap; use eframe::emath::Align; use egui::{Button, Checkbox, Layout, TextEdit, Widget}; use egui_extras::{Column, TableBody, TableBuilder}; use netpurr_core::data::central_request_data::CentralRequestItem; use netpurr_core::data::environment::EnvironmentItemValue; use netpurr_core::data::http::{Header, LockWith}; use netpurr_core::data::workspace_data::WorkspaceData; use crate::widgets::highlight_template::HighlightTemplateSinglelineBuilder; #[derive(Default)] pub struct RequestHeadersPanel { new_header: Header, } impl RequestHeadersPanel { pub fn set_and_render( &mut self, ui: &mut egui::Ui, workspace_data: &mut WorkspaceData, crt_id: String, ) { let envs = workspace_data.get_crt_envs(crt_id.clone()); workspace_data.must_get_mut_crt(crt_id.clone(), |crt| { ui.label("Headers"); let mut delete_index = None; ui.push_id("request_headers_table", |ui| { let table = TableBuilder::new(ui) .resizable(false) .cell_layout(Layout::left_to_right(Align::Center)) .column(Column::auto()) .column(Column::exact(20.0)) .column(Column::initial(200.0).range(40.0..=300.0)) .column(Column::initial(200.0).range(40.0..=300.0)) .column(Column::remainder()) .max_scroll_height(100.0); table .header(20.0, |mut header| { header.col(|ui| { ui.strong(""); }); header.col(|ui| { ui.strong(""); }); header.col(|ui| { ui.strong("KEY"); }); header.col(|ui| { ui.strong("VALUE"); }); header.col(|ui| { ui.strong("DESCRIPTION"); }); }) .body(|mut body| { delete_index = self.build_body(crt, &envs, &mut body); self.build_new_body(envs, body); }); }); if delete_index.is_some() { crt.record .must_get_mut_rest() .request .headers .remove(delete_index.unwrap()); } if self.new_header.key != "" || self.new_header.value != "" || self.new_header.desc != "" { self.new_header.enable = true; crt.record .must_get_mut_rest() .request .headers .push(self.new_header.clone()); self.new_header.key = "".to_string(); self.new_header.value = "".to_string(); self.new_header.desc = "".to_string(); self.new_header.enable = false; } }); } fn build_body( &self, data: &mut CentralRequestItem, envs: &BTreeMap<String, EnvironmentItemValue>, mut body: &mut TableBody, ) -> Option<usize> { let mut delete_index = None; for (index, header) in data .record .must_get_mut_rest() .request .headers .iter_mut() .enumerate() { body.row(18.0, |mut row| { row.col(|ui| { ui.add_enabled( header.lock_with == LockWith::NoLock, Checkbox::new(&mut header.enable, ""), ); }); row.col(|ui| { if ui .add_enabled(header.lock_with == LockWith::NoLock, Button::new("x")) .clicked() { delete_index = Some(index) } }); row.col(|ui| { HighlightTemplateSinglelineBuilder::default() .envs(envs.clone()) .enable(header.lock_with == LockWith::NoLock) .all_space(false) .build( "request_header_key_".to_string() + index.to_string().as_str(), &mut header.key, ) .ui(ui); }); row.col(|ui| { HighlightTemplateSinglelineBuilder::default() .envs(envs.clone()) .enable(header.lock_with == LockWith::NoLock) .all_space(false) .build( "request_header_value_".to_string() + index.to_string().as_str(), &mut header.value, ) .ui(ui); }); row.col(|ui| { ui.add_enabled( header.lock_with == LockWith::NoLock, TextEdit::singleline(&mut header.desc).desired_width(f32::INFINITY), ); }); }); } delete_index } fn build_new_body( &mut self, envs: BTreeMap<String, EnvironmentItemValue>, mut body: TableBody, ) { body.row(18.0, |mut row| { row.col(|ui| { ui.add_enabled(false, Checkbox::new(&mut self.new_header.enable, "")); }); row.col(|ui| { ui.add_enabled(false, Button::new("x")); }); row.col(|ui| { HighlightTemplateSinglelineBuilder::default() .envs(envs.clone()) .enable(self.new_header.lock_with == LockWith::NoLock) .all_space(false) .build( "request_header_key_new".to_string(), &mut self.new_header.key, ) .ui(ui); }); row.col(|ui| { HighlightTemplateSinglelineBuilder::default() .envs(envs.clone()) .enable(self.new_header.lock_with == LockWith::NoLock) .all_space(false) .build( "request_header_value_new".to_string(), &mut self.new_header.value, ) .ui(ui); }); row.col(|ui| { ui.add_enabled_ui(self.new_header.lock_with == LockWith::NoLock, |ui| { TextEdit::singleline(&mut self.new_header.desc) .desired_width(f32::INFINITY) .ui(ui); }); }); }); } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/panels/request_body_form_data_panel.rs
crates/netpurr/src/panels/request_body_form_data_panel.rs
use std::collections::BTreeMap; use eframe::emath::Align; use egui::{Button, Checkbox, Layout, TextBuffer, TextEdit, Widget}; use egui_extras::{Column, TableBody, TableBuilder, TableRow}; use strum::IntoEnumIterator; use netpurr_core::data::central_request_data::CentralRequestItem; use netpurr_core::data::environment::EnvironmentItemValue; use netpurr_core::data::http::{MultipartData, MultipartDataType}; use netpurr_core::data::workspace_data::WorkspaceData; use crate::utils; use crate::utils::HighlightValue; use crate::widgets::highlight_template::HighlightTemplateSinglelineBuilder; #[derive(Default)] pub struct RequestBodyFormDataPanel { new_form: MultipartData, } impl RequestBodyFormDataPanel { pub fn set_and_render( &mut self, ui: &mut egui::Ui, workspace_data: &mut WorkspaceData, crt_id: String, ) { let envs = workspace_data.get_crt_envs(crt_id.clone()); workspace_data.must_get_mut_crt(crt_id.clone(), |crt| { let mut delete_index = None; let table = TableBuilder::new(ui) .resizable(false) .cell_layout(Layout::left_to_right(Align::Center)) .column(Column::auto()) .column(Column::exact(20.0)) .column(Column::exact(100.0)) .column(Column::initial(200.0).range(40.0..=300.0)) .column(Column::initial(200.0).range(40.0..=300.0)) .column(Column::remainder()) .max_scroll_height(100.0); table.header(20.0, self.build_header()).body(|mut body| { delete_index = self.build_body(crt, &mut body, envs.clone()); self.build_new_body(body, envs.clone()); }); if delete_index.is_some() { crt.record .must_get_mut_rest() .request .body .body_form_data .remove(delete_index.unwrap()); } if self.new_form.key != "" || self.new_form.value != "" || self.new_form.desc != "" { self.new_form.enable = true; crt.record .must_get_mut_rest() .request .body .body_form_data .push(self.new_form.clone()); self.new_form.key = "".to_string(); self.new_form.value = "".to_string(); self.new_form.desc = "".to_string(); self.new_form.enable = false; } }); } fn build_header(&self) -> fn(TableRow) { |mut header| { header.col(|ui| { ui.strong(""); }); header.col(|ui| { ui.strong(""); }); header.col(|ui| { ui.strong("TYPE"); }); header.col(|ui| { ui.strong("KEY"); }); header.col(|ui| { ui.strong("VALUE"); }); header.col(|ui| { ui.strong("DESCRIPTION"); }); } } fn build_body( &self, data: &mut CentralRequestItem, mut body: &mut TableBody, envs: BTreeMap<String, EnvironmentItemValue>, ) -> Option<usize> { let mut delete_index: Option<usize> = None; for (index, param) in data .record .must_get_mut_rest() .request .body .body_form_data .iter_mut() .enumerate() { body.row(18.0, |mut row| { row.col(|ui| { ui.checkbox(&mut param.enable, ""); }); row.col(|ui| { if ui.button("x").clicked() { delete_index = Some(index) } }); row.col(|ui| { egui::ComboBox::from_id_source( "form_data_type_".to_string() + index.to_string().as_str(), ) .selected_text(param.data_type.to_string()) .show_ui(ui, |ui| { ui.style_mut().wrap = Some(false); ui.set_min_width(60.0); for x in MultipartDataType::iter() { ui.selectable_value(&mut param.data_type, x.clone(), x.to_string()); } }); }); row.col(|ui| { HighlightTemplateSinglelineBuilder::default() .envs(envs.clone()) .all_space(false) .build("request_body_from_data_key".to_string(), &mut param.key) .ui(ui); }); row.col(|ui| { if param.data_type == MultipartDataType::TEXT { HighlightTemplateSinglelineBuilder::default() .envs(envs.clone()) .all_space(false) .build("request_body_from_data_value".to_string(), &mut param.value) .ui(ui); } else { let mut button_name = utils::build_with_count_ui_header( "Select File".to_string(), HighlightValue::None, ui, ); if param.value != "" { button_name = utils::build_with_count_ui_header( "Select File".to_string(), HighlightValue::Usize(1), ui, ); } if ui.button(button_name).clicked() { if let Some(path) = rfd::FileDialog::new().pick_file() { param.value = path.display().to_string(); } } } }); row.col(|ui| { TextEdit::singleline(&mut param.desc) .desired_width(f32::INFINITY) .ui(ui); }); }); } delete_index } fn build_new_body( &mut self, mut body: TableBody, envs: BTreeMap<String, EnvironmentItemValue>, ) { body.row(18.0, |mut row| { row.col(|ui| { ui.add_enabled(false, Checkbox::new(&mut self.new_form.enable, "")); }); row.col(|ui| { ui.add_enabled(false, Button::new("x")); }); row.col(|ui| { egui::ComboBox::from_id_source("form_data_type") .selected_text(self.new_form.data_type.to_string()) .show_ui(ui, |ui| { ui.style_mut().wrap = Some(false); ui.set_min_width(60.0); for x in MultipartDataType::iter() { ui.selectable_value( &mut self.new_form.data_type, x.clone(), x.to_string(), ); } }); }); row.col(|ui| { HighlightTemplateSinglelineBuilder::default() .envs(envs.clone()) .all_space(false) .build( "request_body_from_data_new_key".to_string(), &mut self.new_form.key, ) .ui(ui); }); row.col(|ui| { if self.new_form.data_type == MultipartDataType::TEXT { HighlightTemplateSinglelineBuilder::default() .envs(envs.clone()) .all_space(false) .build( "request_body_from_data_new_value".to_string(), &mut self.new_form.value, ) .ui(ui); } else { if ui.button("Select File").clicked() { if let Some(path) = rfd::FileDialog::new().pick_file() { self.new_form.value = path.display().to_string() } } } }); row.col(|ui| { TextEdit::singleline(&mut self.new_form.desc) .desired_width(f32::INFINITY) .ui(ui); }); }); } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/panels/response_log_panel.rs
crates/netpurr/src/panels/response_log_panel.rs
use netpurr_core::data::http::Response; #[derive(Default)] pub struct ResponseLogPanel {} impl ResponseLogPanel { pub fn set_and_render(&mut self, ui: &mut egui::Ui, response: &Response) { let theme = egui_extras::syntax_highlighting::CodeTheme::from_memory(ui.ctx()); let mut layouter = |ui: &egui::Ui, string: &str, wrap_width: f32| { let mut layout_job = egui_extras::syntax_highlighting::highlight(ui.ctx(), &theme, string, "js"); layout_job.wrap.max_width = wrap_width; ui.fonts(|f| f.layout_job(layout_job)) }; ui.push_id("log_info", |ui| { egui::ScrollArea::vertical() .max_height(ui.available_height() - 30.0) .show(ui, |ui| { for (index, log) in response.logger.logs.iter().enumerate() { let mut content = format!("> {}", log.show()); egui::TextEdit::multiline(&mut content) .layouter(&mut layouter) .lock_focus(true) .desired_rows(1) .frame(true) .desired_width(f32::MAX) .show(ui); } }); }); } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/panels/test_editor_panel.rs
crates/netpurr/src/panels/test_editor_panel.rs
use std::cell::RefCell; use std::ops::Deref; use std::path::PathBuf; use std::rc::Rc; use std::sync::{Arc, RwLock}; use eframe::epaint::{Color32, FontFamily, FontId}; use egui::{Align, FontSelection, RichText, Style, Ui}; use egui::text::LayoutJob; use log::info; use poll_promise::Promise; use strum::IntoEnumIterator; use strum_macros::{Display, EnumIter}; use egui_toast::Toast; use netpurr_core::data::collections::{CollectionFolder, Testcase}; use netpurr_core::data::record::Record; use netpurr_core::data::test::TestStatus; use netpurr_core::data::workspace_data::{TestItem, WorkspaceData}; use netpurr_core::runner::{TestGroupRunResults, TestRunResult}; use netpurr_core::runner::test::{ResultTreeCase, ResultTreeFolder, ResultTreeRequest}; use crate::operation::operation::Operation; use crate::panels::manager_testcase_panel::ManagerTestcasePanel; use crate::panels::request_pre_script_panel::RequestPreScriptPanel; use crate::panels::test_script_panel::TestScriptPanel; use crate::utils; use crate::utils::HighlightValue; #[derive(Default)] pub struct TestEditorPanel { manager_testcase_panel: ManagerTestcasePanel, request_pre_script_panel: RequestPreScriptPanel, test_script_panel: TestScriptPanel, test_group_run_result: Option<Arc<RwLock<TestGroupRunResults>>>, run_promise: Option<Promise<()>>, collection_path: String, parent_testcase_list: Vec<Testcase>, parent_paths: Vec<String>, open_panel_enum:Panel, fast:bool, } #[derive(Display)] enum TitleType{ Testcase, Request, Assert, Group } #[derive(EnumIter,Display,Clone,PartialEq)] enum Panel{ Runner, Testcase, PreRequestScript, TestScript, } impl Default for Panel{ fn default() -> Self { Panel::Runner } } impl TestEditorPanel { pub fn render( &mut self, operation: &Operation, workspace_data: &mut WorkspaceData, ui: &mut Ui, ) { if let Some(p) = &self.run_promise { if p.ready().is_some() { //这里应该是测试完毕了 operation.add_success_toast("Test all right"); self.run_promise = None } } if self.run_promise.is_some() { ui.ctx().request_repaint(); } workspace_data.selected_test_item.clone().map(|test_item| { self.render_test_item_folder(operation, workspace_data, ui, test_item.clone()); ui.horizontal(|ui|{ for panel in Panel::iter() { let layout_job = self.build_panel_title(&panel,workspace_data,ui); ui.selectable_value( &mut self.open_panel_enum, panel.clone(), layout_job ); } }); ui.separator(); match self.open_panel_enum { Panel::Runner => { match &test_item { TestItem::Folder(collection_name, folder) => { self.render_select_testcase(workspace_data, ui); self.render_run_folder( operation, workspace_data, ui, collection_name.clone(), &folder, ); self.render_result_tree(workspace_data, ui, folder.clone()); } TestItem::Record(collection_name, folder,record_name) => { self.render_select_testcase(workspace_data, ui); let record = folder.borrow().requests[record_name].clone(); self.render_run_record( operation, workspace_data, ui, collection_name.clone(), folder.clone(), record, ); self.render_result_record(workspace_data, ui,folder,record_name); } } } Panel::Testcase => { self.render_manager_testcase(workspace_data, ui, test_item.clone()); } Panel::PreRequestScript => { ui.strong("Pre-request Script:"); self.request_pre_script_panel .set_and_render(ui, workspace_data, test_item.clone()); } Panel::TestScript => { ui.strong("Test Script:"); self.test_script_panel .set_and_render(ui, workspace_data, test_item.clone()) } } }); } fn build_panel_title(&self,panel:&Panel,workspace_data: &mut WorkspaceData,ui: &mut Ui)->LayoutJob{ return match &workspace_data.selected_test_item { None => { utils::build_with_count_ui_header(panel.to_string(), HighlightValue::None, ui) } Some(test_item) => { match panel { Panel::Runner => { utils::build_with_count_ui_header(panel.to_string(), HighlightValue::None, ui) } Panel::Testcase => { match test_item { TestItem::Folder(_, f) => { utils::build_with_count_ui_header(panel.to_string(), HighlightValue::Usize(f.borrow().testcases.len()), ui) } TestItem::Record(_, f, r) => { let size = f.borrow().requests.get(r).unwrap().testcase().len(); utils::build_with_count_ui_header(panel.to_string(), HighlightValue::Usize(size), ui) } } } Panel::PreRequestScript => { match test_item { TestItem::Folder(_, f) => { if f.borrow().pre_request_script.trim().is_empty() { utils::build_with_count_ui_header(panel.to_string(), HighlightValue::None, ui) } else { utils::build_with_count_ui_header(panel.to_string(), HighlightValue::Has, ui) } } TestItem::Record(_, f, r) => { if f.borrow().requests.get(r).unwrap().pre_request_script().trim().is_empty() { utils::build_with_count_ui_header(panel.to_string(), HighlightValue::None, ui) } else { utils::build_with_count_ui_header(panel.to_string(), HighlightValue::Has, ui) } } } } Panel::TestScript => { match test_item { TestItem::Folder(_, f) => { if f.borrow().test_script.trim().is_empty() { utils::build_with_count_ui_header(panel.to_string(), HighlightValue::None, ui) } else { utils::build_with_count_ui_header(panel.to_string(), HighlightValue::Has, ui) } } TestItem::Record(_, f, r) => { if f.borrow().requests.get(r).unwrap().test_script().trim().is_empty() { utils::build_with_count_ui_header(panel.to_string(), HighlightValue::None, ui) } else { utils::build_with_count_ui_header(panel.to_string(), HighlightValue::Has, ui) } } } } } } } } fn export_report(&self,path:PathBuf){ self.test_group_run_result.clone().map(|result|{ result.read().unwrap().export(path); }); } fn render_test_item_folder( &mut self, operation: &Operation, workspace_data: &mut WorkspaceData, ui: &mut Ui, test_item: TestItem, ) { match &test_item { TestItem::Folder(collection_name, folder) => { if self.collection_path != folder.borrow().get_path() { self.init(workspace_data, folder.borrow().get_path()); } ui.heading(format!("{} {}",egui_phosphor::regular::FOLDER,folder.borrow().get_path().clone())); ui.separator(); } TestItem::Record(collection_name, folder, record_name) => { let record_path = format!("{}/{}", folder.borrow().get_path(), record_name); if self.collection_path != record_path { self.init(workspace_data, record_path); } ui.heading(format!("{} {} : {}",egui_phosphor::regular::FILE_TEXT, folder.borrow().get_path(), record_name)); ui.separator(); } } } fn render_result_record(&mut self, workspace_data: &mut WorkspaceData, ui: &mut Ui,folder:&Rc<RefCell<CollectionFolder>>,record_name: &String) { if let Some(test_group_run_result) = self.test_group_run_result.clone() { for (name, result) in test_group_run_result.read().unwrap().results.iter() { if !name.contains(record_name.as_str()){ continue; } let mut status = TestStatus::PASS; match result { Ok(result) => status = result.test_result.status.clone(), Err(err) => { status = TestStatus::FAIL; } } let title = self.render_test_title( ui, TitleType::Request, name.to_string(), status, ); let collapsing = utils::open_collapsing(ui,title,|ui|{ match &result { Ok(result) => { for test_info in result.test_result.test_info_list.iter() { let test_info_title = self.render_test_title( ui, TitleType::Assert, test_info.name.clone(), test_info.status.clone(), ); ui.label(test_info_title); } } Err(err) => { ui.label(err.error.clone()); } } }); if collapsing.header_response.clicked(){ match &result { Ok(result) => { workspace_data.selected_test_run_result = Some(result.clone()); } Err(err) => { if err.response.is_some() { workspace_data.selected_test_run_result = Some(TestRunResult { request: err.request.clone(), response: err.response.clone(), test_result: Default::default(), collection_path: err.collection_path.clone(), request_name: err.request_name.clone(), testcase: Default::default(), }); } } } } } } } fn render_result_tree( &mut self, workspace_data: &mut WorkspaceData, ui: &mut Ui, folder: Rc<RefCell<CollectionFolder>>, ) { egui::ScrollArea::vertical().max_height(ui.available_height()-30.0).show(ui,|ui|{ if let Some(test_group_run_result) = self.test_group_run_result.clone() { let mut testcase_paths = vec![]; if let Some(pt) = self.build_parent_testcase() { testcase_paths = pt.get_testcase_path(); } let result_tree = ResultTreeFolder::create( folder.clone(), testcase_paths, test_group_run_result.read().unwrap().deref().clone(), ); self.render_tree_folder(ui, workspace_data, &result_tree); } }); } fn render_run_folder( &mut self, operation: &Operation, workspace_data: &mut WorkspaceData, ui: &mut Ui, collection_name: String, folder: &Rc<RefCell<CollectionFolder>>, ) { ui.horizontal(|ui|{ ui.checkbox(&mut self.fast,"Parallel Test"); if self.run_promise.is_none() { if ui.button("Run Test").clicked() { let test_group_run_result = Arc::new(RwLock::new(TestGroupRunResults::default())); self.test_group_run_result = Some(test_group_run_result.clone()); self.run_test_group( self.fast, workspace_data, operation, test_group_run_result, collection_name.clone(), folder.borrow().get_path(), self.build_parent_testcase(), folder.clone(), ); } ui.add_enabled_ui(self.test_group_run_result.is_some(),|ui|{ if ui.button("Export Report").clicked(){ if let Some(path) = rfd::FileDialog::new() .add_filter("html",&["html"]) .set_title("Export Report") .set_file_name("report") .save_file() { info!("export report path: {:?}",path); self.export_report(path); } } }); }else{ if ui.button("Stop Test").clicked() { match &self.test_group_run_result { None => {} Some(r) => { r.write().unwrap().stop(); } } self.run_promise.take().unwrap().abort(); } } }); } fn render_run_record( &mut self, operation: &Operation, workspace_data: &mut WorkspaceData, ui: &mut Ui, collection_name: String, parent_folder: Rc<RefCell<CollectionFolder>>, record: Record, ) { ui.add_enabled_ui(self.run_promise.is_none(), |ui| { if ui.button("Run Test").clicked() { let test_group_run_result = Arc::new(RwLock::new(TestGroupRunResults::default())); self.test_group_run_result = Some(test_group_run_result.clone()); self.run_test_record( workspace_data, operation, test_group_run_result, collection_name, parent_folder.borrow().get_path(), self.build_parent_testcase(), record.clone(), ); } }); } fn render_manager_testcase( &mut self, workspace_data: &mut WorkspaceData, ui: &mut Ui, test_item: TestItem, ) { ui.strong("Edit Self Testcase:"); egui::ScrollArea::neither() .id_source("manager_testcase_scroll") .max_height(ui.available_height()-30.0) .show(ui, |ui| { self.manager_testcase_panel .render(ui, workspace_data, test_item) }); } fn render_select_testcase(&mut self, workspace_data: &mut WorkspaceData, ui: &mut Ui) { ui.strong("Select Parent Testcase:"); ui.horizontal_wrapped(|ui| { for (index, parent_path) in self.parent_paths.iter().enumerate() { let (_, folder_op) = workspace_data.get_folder_with_path(parent_path.clone()); if let Some(folder) = folder_op { let mut testcases = folder.borrow().testcases.clone(); if testcases.is_empty() { let testcase = Testcase::default(); testcases.insert(testcase.name.clone(), testcase); } egui::ComboBox::from_id_source(format!("testcase-{}", parent_path)) .selected_text(self.parent_testcase_list[index].clone().get_path()) .show_ui(ui, |ui| { ui.style_mut().wrap = Some(false); ui.set_min_width(60.0); for (name, testcase) in testcases.iter() { let testcase_path = format!("{}:{}", folder.borrow().name, name); let mut response = ui.selectable_label( self.parent_testcase_list[index].get_path().as_str() == testcase_path.as_str(), testcase_path.clone(), ); if response.clicked() { let mut new_testcase = testcase.clone(); new_testcase.entry_name = folder.borrow().name.clone(); self.parent_testcase_list[index] = new_testcase; response.mark_changed(); } } }); } } }); } fn init(&mut self, workspace_data: &mut WorkspaceData, collection_path: String) { self.collection_path = collection_path.clone(); self.parent_testcase_list.clear(); self.parent_paths.clear(); let collection_path_split: Vec<String> = collection_path.split("/").map(|s| s.to_string()).collect(); for index in 0..collection_path_split.len() { if index == collection_path_split.len() || index == 0 { continue; } let path: Vec<String> = collection_path_split.iter().take(index).cloned().collect(); let path_join = path.join("/"); self.parent_paths.push(path_join.clone()); let (_, folder_op) = workspace_data.get_folder_with_path(path_join.clone()); if let Some(folder) = folder_op { let mut testcases = folder.borrow().testcases.clone(); if testcases.is_empty() { let testcase = Testcase::default(); testcases.insert(testcase.name.clone(), testcase); } let mut select_testcase = testcases.first_entry().unwrap().get().clone(); select_testcase.entry_name = folder.borrow().name.clone(); self.parent_testcase_list.push(select_testcase) } } } fn build_parent_testcase(&self) -> Option<Testcase> { let mut merge_testcase: Option<Testcase> = None; for testcase in self.parent_testcase_list.iter() { match &merge_testcase { Some(t) => { let mut next_testcase = testcase.clone(); next_testcase.merge(testcase.entry_name.clone(), t); merge_testcase = Some(next_testcase); } None => { merge_testcase = Some(testcase.clone()); } } } merge_testcase } fn render_tree_case( &self, ui: &mut Ui, workspace_data: &mut WorkspaceData, result_tree_case: &ResultTreeCase, ) { let title = self.render_test_title( ui, TitleType::Testcase, format!( "{} ({}/{})", result_tree_case.name.clone(), result_tree_case.get_success_count(), result_tree_case.get_total_count() ), result_tree_case.status.clone(), ); utils::open_collapsing(ui, title, |child_ui| { for (name, rf) in result_tree_case.folders.iter() { self.render_tree_folder(child_ui, workspace_data, rf) } for request_tree_request in result_tree_case.requests.iter() { self.render_test_request(child_ui, workspace_data, request_tree_request); } }); } fn render_tree_folder( &self, ui: &mut Ui, workspace_data: &mut WorkspaceData, result_tree_folder: &ResultTreeFolder, ) { let title = self.render_test_title( ui, TitleType::Group, format!( "{} ({}/{})", result_tree_folder.name.clone(), result_tree_folder.get_success_count(), result_tree_folder.get_total_count() ), result_tree_folder.status.clone(), ); utils::open_collapsing(ui, title, |child_ui| { for (_, case) in result_tree_folder.cases.iter() { self.render_tree_case(child_ui, workspace_data, case); } }); } fn render_test_request( &self, ui: &mut Ui, workspace_data: &mut WorkspaceData, request_tree_request: &ResultTreeRequest, ) { let request_title = self.render_test_title( ui, TitleType::Request, request_tree_request.name.clone(), request_tree_request.status.clone(), ); if ui .collapsing(request_title, |ui| { // 增加测试的信息 if let Some(r) = &request_tree_request.result { match r { Ok(tr) => { for test_info in tr.test_result.test_info_list.iter() { let test_info_title = self.render_test_title( ui, TitleType::Assert, test_info.name.clone(), test_info.status.clone(), ); ui.collapsing(test_info_title, |ui| { for tar in test_info.results.iter() { let test_assert_title = self.render_test_title( ui, TitleType::Assert, tar.msg.clone(), tar.assert_result.clone(), ); ui.label(test_assert_title); } }); } } Err(te) => { let test_info_title = self.render_test_title( ui, TitleType::Assert, te.error.clone(), TestStatus::FAIL.clone(), ); ui.label(test_info_title); } } } }) .header_response .clicked() { if let Some(r) = &request_tree_request.result { match r { Ok(test_result) => { workspace_data.selected_test_run_result = Some(test_result.clone()) } Err(err) => { if err.response.is_some() { workspace_data.selected_test_run_result = Some(TestRunResult { request: err.request.clone(), response: err.response.clone(), test_result: Default::default(), collection_path: err.collection_path.clone(), request_name: err.request_name.clone(), testcase: Default::default(), }); } } } } }; } fn render_test_title(&self, ui: &mut Ui,title_type:TitleType, name: String, status: TestStatus) -> LayoutJob { let style = Style::default(); let mut request_test_result_name_layout_job = LayoutJob::default(); let mut rich_text = RichText::new(status.clone().to_string()) .color(Color32::WHITE) .font(FontId { size: 14.0, family: FontFamily::Monospace, }); match status { TestStatus::None => { rich_text = rich_text.background_color(ui.visuals().extreme_bg_color) } TestStatus::PASS => rich_text = rich_text.background_color(Color32::DARK_GREEN), TestStatus::FAIL => rich_text = rich_text.background_color(Color32::DARK_RED), TestStatus::WAIT => rich_text = rich_text.background_color(Color32::DARK_GRAY), TestStatus::SKIP => rich_text = rich_text.background_color(Color32::GRAY), TestStatus::RUNNING => rich_text = rich_text.background_color(Color32::DARK_BLUE), }; rich_text.append_to( &mut request_test_result_name_layout_job, &style, FontSelection::Default, Align::Center, ); RichText::new(" ").append_to( &mut request_test_result_name_layout_job, &style, FontSelection::Default, Align::Center, ); let mut rich_text = RichText::new(title_type.to_string()) .color(Color32::WHITE) .font(FontId { size: 12.0, family: FontFamily::Monospace, }); match title_type { TitleType::Testcase => rich_text = rich_text.background_color(Color32::DARK_GRAY), TitleType::Request => rich_text = rich_text.background_color(Color32::GRAY), TitleType::Assert => rich_text = rich_text.color(Color32::DARK_GRAY).background_color(Color32::LIGHT_GRAY), TitleType::Group => rich_text = rich_text.background_color(Color32::BLACK), } rich_text.append_to( &mut request_test_result_name_layout_job, &style, FontSelection::Default, Align::Center, ); RichText::new(" ").append_to( &mut request_test_result_name_layout_job, &style, FontSelection::Default, Align::Center, ); RichText::new(name.as_str()).append_to( &mut request_test_result_name_layout_job, &style, FontSelection::Default, Align::Center, ); request_test_result_name_layout_job } fn run_test_group( &mut self, fast:bool, workspace_data: &mut WorkspaceData, operation: &Operation, test_group_run_result: Arc<RwLock<TestGroupRunResults>>, collection_name: String, collection_path: String, parent_testcase: Option<Testcase>, folder: Rc<RefCell<CollectionFolder>>, ) { let envs = workspace_data .get_build_envs(workspace_data.get_collection(Some(collection_name.clone()))); let script_tree = workspace_data.get_script_tree(collection_path.clone()); self.run_promise = Some(operation.run_test_group_promise( fast, envs, script_tree, test_group_run_result, collection_path, parent_testcase, folder, )); } fn run_test_record( &mut self, workspace_data: &mut WorkspaceData, operation: &Operation, test_group_run_result: Arc<RwLock<TestGroupRunResults>>, collection_name: String, collection_path: String, parent_testcase: Option<Testcase>, record: Record, ) { let envs = workspace_data .get_build_envs(workspace_data.get_collection(Some(collection_name.clone()))); let script_tree = workspace_data.get_script_tree(collection_path.clone()); self.run_promise = Some(operation.run_test_record_promise( envs, script_tree, test_group_run_result, collection_path, parent_testcase, record, )); } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/panels/test_result_panel.rs
crates/netpurr/src/panels/test_result_panel.rs
use eframe::epaint::FontFamily; use egui::{Color32, FontId, TextFormat}; use egui::text::LayoutJob; use netpurr_core::data::test::{TestResult, TestStatus}; use crate::panels::HORIZONTAL_GAP; #[derive(Default)] pub struct TestResultPanel {} impl TestResultPanel { pub fn set_and_render(&mut self, ui: &mut egui::Ui, test_result: &TestResult) { ui.push_id("test_info", |ui| { egui::ScrollArea::vertical().show(ui, |ui| { for test_info in test_result.test_info_list.iter() { ui.horizontal(|ui| { ui.add_space(HORIZONTAL_GAP * 2.0); ui.label(Self::build_status_job(test_info.status.clone())); ui.separator(); ui.vertical(|ui| { ui.label(test_info.name.clone()); for tar in test_info.results.iter() { ui.horizontal(|ui| { ui.add_space(HORIZONTAL_GAP * 2.0); ui.separator(); ui.label(Self::build_status_job(tar.assert_result.clone())); ui.label(tar.msg.to_string()); }); } }); }); } }); }); } fn build_status_job(status: TestStatus) -> LayoutJob { let mut job = LayoutJob::default(); let text_format = match status { TestStatus::FAIL => TextFormat { color: Color32::WHITE, background: Color32::DARK_RED, font_id: FontId { size: 14.0, family: FontFamily::Monospace, }, ..Default::default() }, _ => TextFormat { color: Color32::WHITE, background: Color32::DARK_GREEN, font_id: FontId { size: 14.0, family: FontFamily::Monospace, }, ..Default::default() }, }; job.append(status.to_string().as_str(), 0.0, text_format); job } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/panels/top_panel.rs
crates/netpurr/src/panels/top_panel.rs
use egui::Ui; use poll_promise::Promise; use strum::IntoEnumIterator; use netpurr_core::data::workspace_data::{EditorModel, WorkspaceData}; use crate::data::config_data::ConfigData; use crate::operation::operation::Operation; use crate::panels::{HORIZONTAL_GAP, VERTICAL_GAP}; use crate::utils; use crate::windows::import_windows::ImportWindows; #[derive(Default)] pub struct TopPanel { current_workspace: String, sync_promise: Option<Promise<rustygit::types::Result<()>>>, } impl TopPanel { pub fn render( &mut self, ui: &mut Ui, workspace_data: &mut WorkspaceData, operation: Operation, config_data: &mut ConfigData, ) { ui.add_enabled_ui(!operation.get_ui_lock(), |ui| { // The top panel is often a good place for a menu bar: // egui::menu::bar(ui, |ui| { // ui.menu_button("File", |ui| { // if ui.button("New...").clicked() {} // if ui.button("Import...").clicked() { // operation.add_window(Box::new(ImportWindows::default())) // } // if ui.button("Exit").clicked() { // ui.ctx().send_viewport_cmd(egui::ViewportCommand::Close); // } // }); // ui.menu_button("View", |ui| { // if ui.button("Zoom In").clicked() {} // if ui.button("Zoom Out").clicked() {} // }); // egui::widgets::global_dark_light_mode_buttons(ui); // }); egui::SidePanel::left("top_left_panel") .show_separator_line(false) .show_inside(ui, |ui| { ui.vertical(|ui| { ui.add_space(VERTICAL_GAP); ui.horizontal(|ui| { ui.add_space(HORIZONTAL_GAP); if ui.button("Import").clicked() { operation.add_window(Box::new(ImportWindows::default())) } }); ui.add_space(VERTICAL_GAP); }); }); egui::CentralPanel::default().show_inside(ui, |ui| { ui.horizontal(|ui| { utils::add_left_space(ui, ui.available_width() / 2.0 - 80.0); for editor_model in EditorModel::iter() { ui.selectable_value( &mut workspace_data.editor_model, editor_model.clone(), editor_model.to_string(), ); } }); }); }); } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/panels/left_panel.rs
crates/netpurr/src/panels/left_panel.rs
use eframe::emath::Align; use egui::{Label, Layout, Link, RichText, ScrollArea, Sense, Ui, Widget}; use netpurr_core::data::environment::ENVIRONMENT_GLOBALS; use netpurr_core::data::workspace_data::{EditorModel, WorkspaceData}; use crate::data::config_data::ConfigData; use crate::operation::operation::Operation; use crate::panels::collection_panel::CollectionPanel; use crate::panels::history_panel::HistoryPanel; use crate::panels::openapi_show_request_panel::OpenApiShowRequestPanel; use crate::panels::test_group_panel::TestGroupPanel; use crate::panels::VERTICAL_GAP; use crate::windows::cookies_windows::CookiesWindows; use crate::windows::environment_windows::EnvironmentWindows; use crate::windows::new_collection_windows::NewCollectionWindows; #[derive(PartialEq, Eq)] enum Panel { Template, History, Collection, } impl Default for Panel { fn default() -> Self { Self::Collection } } #[derive(Default)] pub struct MyLeftPanel { history_panel: HistoryPanel, open_api_show_request_panel: OpenApiShowRequestPanel, collection_panel: CollectionPanel, test_group_panel: TestGroupPanel, open_panel: Panel, filter: String, environment: String, } const NO_ENVIRONMENT: &str = "No Environment"; impl MyLeftPanel { pub fn set_and_render( &mut self, ui: &mut egui::Ui, operation: &Operation, workspace_data: &mut WorkspaceData, config_data: &mut ConfigData, ) { let collection = workspace_data .get_collection_by_name(config_data.select_collection().unwrap_or_default()); egui::TopBottomPanel::top("left_top_panel") .resizable(false) .show_inside(ui, |ui| { ui.horizontal(|ui| { if Label::new(RichText::new(egui_phosphor::regular::ARROW_LEFT).heading()).sense(Sense::click()).ui(ui).clicked() { config_data.set_select_collection(None); } ui.separator(); if Link::new(RichText::new(format!("{} {}",egui_phosphor::regular::ARCHIVE_BOX,config_data.select_collection().unwrap_or_default())).heading()).ui(ui).clicked() { operation.add_window(Box::new( NewCollectionWindows::default().with_open_collection(collection), )); } }); ui.separator(); egui::ComboBox::from_id_source("environment") .width(ui.available_width()) .selected_text( workspace_data .get_env_select() .map(|name| "Environment: ".to_string() + name.as_str()) .unwrap_or(NO_ENVIRONMENT.to_string()), ) .show_ui(ui, |ui| { ui.style_mut().wrap = Some(false); ui.set_min_width(60.0); if ui.button("⚙ Manage Environment").clicked() { operation.add_window(Box::new(EnvironmentWindows::default())); } match workspace_data.get_env_select() { None => { self.environment = NO_ENVIRONMENT.to_string(); } Some(env) => { self.environment = env; } } ui.selectable_value( &mut self.environment, NO_ENVIRONMENT.to_string(), NO_ENVIRONMENT.to_string(), ); for (name, _) in &workspace_data.get_env_configs() { if name == ENVIRONMENT_GLOBALS { continue; } ui.selectable_value(&mut self.environment, name.clone(), name.clone()); } }); ui.with_layout(Layout::top_down_justified(Align::Center), |ui| { if ui.button("Manager Cookies").clicked() { operation.add_window(Box::new(CookiesWindows::default())); } }); ui.add_space(VERTICAL_GAP / 8.0); }); egui::CentralPanel::default().show_inside(ui, |ui| match workspace_data.editor_model { EditorModel::Request => { self.render_request_panel(operation, workspace_data, config_data, ui); } EditorModel::Test => { self.test_group_panel .render(operation, workspace_data, config_data, ui); } EditorModel::Design => {} }); if self.environment == NO_ENVIRONMENT { workspace_data.set_env_select(None); } else { workspace_data.set_env_select(Some(self.environment.to_string())); } } fn render_request_panel( &mut self, operation: &Operation, workspace_data: &mut WorkspaceData, config_data: &mut ConfigData, ui: &mut Ui, ) { ui.horizontal(|ui| { ui.selectable_value(&mut self.open_panel, Panel::Collection, "Collection"); ui.selectable_value(&mut self.open_panel, Panel::Template, "Template"); ui.selectable_value(&mut self.open_panel, Panel::History, "History"); }); ScrollArea::vertical().show(ui, |ui| match self.open_panel { Panel::Template => { config_data.select_collection().map(|collection_name| { workspace_data .get_collection_by_name(collection_name) .map(|collection| { self.open_api_show_request_panel.render( ui, workspace_data, operation, collection, ) }) }); } Panel::Collection => { self.collection_panel.set_and_render( ui, operation, workspace_data, config_data.select_collection().unwrap_or_default(), ); } Panel::History => { self.history_panel.set_and_render(ui, workspace_data); } }); } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/panels/collection_panel.rs
crates/netpurr/src/panels/collection_panel.rs
use std::cell::RefCell; use std::collections::BTreeMap; use std::rc::Rc; use egui::{CollapsingHeader, Response, Ui}; use uuid::Uuid; use netpurr_core::data::central_request_data::CentralRequestItem; use netpurr_core::data::collections::{Collection, CollectionFolder}; use netpurr_core::data::http::{HttpRecord, Request}; use netpurr_core::data::record::Record; use netpurr_core::data::workspace_data::WorkspaceData; use crate::operation::operation::Operation; use crate::utils; use crate::windows::new_collection_windows::NewCollectionWindows; use crate::windows::save_crt_windows::SaveCRTWindows; use crate::windows::save_windows::SaveWindows; #[derive(Default)] pub struct CollectionPanel {} impl CollectionPanel { pub fn set_and_render( &mut self, ui: &mut Ui, operation: &Operation, workspace_data: &mut WorkspaceData, collection_name: String, ) { workspace_data .get_collection_by_name(collection_name.clone()) .map(|collection| { if ui.link("+ New Folder").clicked() { operation.add_window(Box::new( NewCollectionWindows::default().with_open_folder( collection.clone(), collection.folder.clone(), None, ), )); }; let folders = collection.folder.borrow().folders.clone(); for (cf_name, cf) in folders.iter() { self.set_folder( ui, operation, workspace_data, collection.clone(), collection.folder.clone(), cf.clone(), format!("{}/{}", collection_name, cf_name.clone()), ); } let requests = collection.folder.borrow().requests.clone(); self.render_request( ui, operation, workspace_data, collection_name.to_string(), collection_name.to_string(), requests, ); }); } fn set_folder( &mut self, ui: &mut Ui, operation: &Operation, workspace_data: &mut WorkspaceData, collection: Collection, parent_folder: Rc<RefCell<CollectionFolder>>, folder: Rc<RefCell<CollectionFolder>>, path: String, ) { let folder_name = folder.borrow().name.clone(); let response = CollapsingHeader::new(format!("{} {}",egui_phosphor::regular::FOLDER,folder_name)) .default_open(false) .show(ui, |ui| { let folders = folder.borrow().folders.clone(); for (name, cf) in folders.iter() { self.set_folder( ui, operation, workspace_data, collection.clone(), folder.clone(), cf.clone(), format!("{}/{}", path, name), ) } let requests = folder.borrow().requests.clone(); self.render_request( ui, operation, workspace_data, collection.folder.borrow().name.clone(), path.clone(), requests, ); }) .header_response; self.popup_folder_item( operation, workspace_data, collection, parent_folder, folder, folder_name, response, ); } fn popup_folder_item( &mut self, operation: &Operation, workspace_data: &mut WorkspaceData, collection: Collection, parent_folder: Rc<RefCell<CollectionFolder>>, folder: Rc<RefCell<CollectionFolder>>, folder_name: String, response: Response, ) { response.context_menu(|ui| { if utils::select_label(ui, "Edit").clicked() { operation.add_window(Box::new(NewCollectionWindows::default().with_open_folder( collection.clone(), parent_folder.clone(), Some(folder.clone()), ))); ui.close_menu(); } if utils::select_label(ui, "Add Folder").clicked() { operation.add_window(Box::new(NewCollectionWindows::default().with_open_folder( collection.clone(), folder.clone(), None, ))); ui.close_menu(); } if utils::select_label(ui, "Add Request").clicked() { let crt = CentralRequestItem{ id: Uuid::new_v4().to_string(), collection_path: None, record: Record::Rest(HttpRecord{ name: "New Request".to_string(), desc: "".to_string(), request: Request{ method: Default::default(), schema: Default::default(), raw_url: "http://www.httpbin.org/get".to_string(), base_url: "www.httpbin.org/get".to_string(), path_variables: vec![], params: vec![], headers: vec![], body: Default::default(), auth: Default::default(), }, .. Default::default() }), test_result: Default::default(), modify_baseline: "".to_string(), }; workspace_data.add_crt(crt.clone()); operation.add_window(Box::new(SaveCRTWindows::default().with( crt.id.clone(), Some(folder.borrow().get_path()), ))); workspace_data.set_crt_select_id(Some(crt.id.clone())); ui.close_menu(); } if utils::select_label(ui, "Duplicate").clicked() { let new_name = utils::build_copy_name( folder_name.clone(), parent_folder .borrow() .folders .iter() .map(|(k, _)| k.clone()) .collect(), ); let new_folder = Rc::new(RefCell::new(folder.borrow().duplicate(new_name))); workspace_data.collection_insert_folder(parent_folder.clone(), new_folder.clone()); ui.close_menu(); } if utils::select_label(ui, "Remove").clicked() { workspace_data.remove_folder(parent_folder, folder_name.clone()); ui.close_menu(); } }); } fn popup_request_item( &mut self, operation: &Operation, workspace_data: &mut WorkspaceData, collection_name: String, response: Response, record: &Record, path: String, ) { response.context_menu(|ui| { if utils::select_label(ui, "Open in New Table").clicked() { let mut crt_id = path.clone() + "/" + record.name().as_str(); if workspace_data.contains_crt_id(crt_id.clone()) { crt_id = utils::build_copy_name(crt_id.clone(), workspace_data.get_crt_id_set()); } workspace_data.add_crt(CentralRequestItem { id: crt_id, collection_path: Some(path.clone()), record: record.clone(), ..Default::default() }); ui.close_menu(); } if utils::select_label(ui, "Save as").clicked() { operation.add_window(Box::new(SaveWindows::default().with( record.clone(), Some(path.clone()), false, ))); ui.close_menu(); } if utils::select_label(ui, "Edit").clicked() { operation.add_window(Box::new(SaveWindows::default().with( record.clone(), Some(path.clone()), true, ))); ui.close_menu(); } if utils::select_label(ui, "Duplicate").clicked() { let (_, folder) = workspace_data.get_folder_with_path(path.clone()); folder.map(|f| { let cf = f.borrow().clone(); let request = cf.requests.get(record.name().as_str()); request.map(|r| { let mut new_request = r.clone(); let name = new_request.name(); let new_name = utils::build_copy_name( name, f.borrow().requests.iter().map(|(k, v)| k.clone()).collect(), ); new_request.set_name(new_name.to_string()); workspace_data.collection_insert_record(f.clone(), new_request); }); }); ui.close_menu(); } if utils::select_label(ui, "Remove").clicked() { let (_, folder) = workspace_data.get_folder_with_path(path.clone()); folder.map(|f| { workspace_data.collection_remove_http_record(f.clone(), record.name()); }); ui.close_menu(); } }); } fn render_request( &mut self, ui: &mut Ui, operation: &Operation, workspace_data: &mut WorkspaceData, collection_name: String, path: String, requests: BTreeMap<String, Record>, ) { for (_, record) in requests.iter() { let lb = utils::build_rest_ui_header(record.clone(), None, ui); let button = ui.button(lb); if button.clicked() { workspace_data.add_crt(CentralRequestItem { id: path.clone() + "/" + record.name().as_str(), collection_path: Some(path.clone()), record: record.clone(), ..Default::default() }) } self.popup_request_item( operation, workspace_data, collection_name.clone(), button, &record, path.clone(), ) } } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/panels/selected_collection_panel.rs
crates/netpurr/src/panels/selected_collection_panel.rs
use eframe::emath::Align; use egui::{Color32, FontSelection, Label, RichText, Style, Ui, Widget}; use netpurr_core::data::record::Record; use netpurr_core::data::workspace_data::{EditorModel, WorkspaceData}; use crate::data::config_data::ConfigData; use crate::operation::operation::Operation; use crate::panels::left_panel::MyLeftPanel; use crate::panels::openapi_editor_panel::OpenApiEditorPanel; use crate::panels::openapi_show_request_panel::OpenApiShowRequestPanel; use crate::panels::response_panel::ResponsePanel; use crate::panels::rest_panel::RestPanel; use crate::panels::test_editor_panel::TestEditorPanel; use crate::panels::websocket_panel::WebSocketPanel; use crate::utils; use crate::windows::request_close_windows::RequestCloseWindows; #[derive(Default)] pub struct SelectedCollectionPanel { rest_panel: RestPanel, left_panel: MyLeftPanel, web_socket_panel: WebSocketPanel, response_panel: ResponsePanel, select_crt_id: Option<String>, openapi_panel: OpenApiShowRequestPanel, openapi_editor_panel: OpenApiEditorPanel, test_editor_panel: TestEditorPanel, } #[derive(PartialEq, Eq, Clone)] enum PanelEnum { RequestId(Option<String>), } impl Default for PanelEnum { fn default() -> Self { PanelEnum::RequestId(None) } } impl SelectedCollectionPanel { pub fn set_and_render( &mut self, ui: &mut Ui, operation: &Operation, workspace_data: &mut WorkspaceData, config_data: &mut ConfigData, ) { egui::SidePanel::left("selected_collection_left_panel") .default_width(220.0) .resizable(false) .show_inside(ui, |ui| { ui.add_enabled_ui(!operation.get_ui_lock(), |ui| { self.left_panel .set_and_render(ui, operation, workspace_data, config_data); }); }); egui::SidePanel::right("selected_collection_right_response") .min_width(ui.available_width() / 4.0) .max_width(ui.available_width() / 2.0) .show_inside(ui, |ui| { ui.add_enabled_ui(!operation.get_ui_lock(), |ui| { match workspace_data.editor_model { EditorModel::Request => { self.render_request_response_panel(operation, workspace_data, ui); } EditorModel::Test => { self.render_test_response_panel(operation, workspace_data, ui); } EditorModel::Design => { workspace_data .get_collection_by_name( config_data.select_collection().unwrap_or_default(), ) .map(|c| { egui::scroll_area::ScrollArea::vertical() .max_height(ui.available_height() - 30.0) .show(ui, |ui| { self.openapi_panel.render( ui, workspace_data, operation, c, ) }); }); } } }); }); egui::CentralPanel::default().show_inside(ui, |ui| match workspace_data.editor_model { EditorModel::Request => { self.render_request_panel(operation, config_data, workspace_data, ui); } EditorModel::Test => { self.test_editor_panel.render(operation, workspace_data, ui); } EditorModel::Design => { self.openapi_editor_panel .render(workspace_data, config_data, ui) } }); workspace_data.get_env_select().map(|s| { if !workspace_data.get_env_configs().contains_key(s.as_str()) { workspace_data.set_env_select(None) } }); } fn render_test_response_panel( &mut self, operation: &Operation, workspace_data: &mut WorkspaceData, ui: &mut Ui, ) { match &workspace_data.selected_test_run_result.clone() { None => {} Some(test_run_result) => { self.response_panel.render_with_test( ui, operation, workspace_data, test_run_result, ); } } } fn render_request_response_panel( &mut self, operation: &Operation, workspace_data: &mut WorkspaceData, ui: &mut Ui, ) { match &workspace_data.get_crt_select_id() { None => {} Some(crt_id) => { self.response_panel .render_with_crt(ui, operation, workspace_data, crt_id.clone()); } } } fn render_request_panel( &mut self, operation: &Operation, config_data: &mut ConfigData, workspace_data: &mut WorkspaceData, ui: &mut Ui, ) { ui.vertical(|ui| { self.central_request_table(workspace_data,config_data, operation, ui); }); ui.separator(); match &workspace_data.get_crt_select_id() { Some(crt_id) => { // ui.horizontal(|ui| { // ui.add_space(HORIZONTAL_GAP); // self.render_name_label(workspace_data, crt_id.clone(), ui); // }); // ui.separator(); match workspace_data.must_get_crt(crt_id.clone()).record { Record::Rest(_) => { self.rest_panel.set_and_render( ui, operation, config_data, workspace_data, crt_id.clone(), ); } Record::WebSocket(_) => { self.web_socket_panel.set_and_render( ui, operation, config_data, workspace_data, crt_id.clone(), ); } } } _ => {} } } fn central_request_table( &mut self, workspace_data: &mut WorkspaceData, config_data: &mut ConfigData, operation: &Operation, ui: &mut Ui, ) { ui.horizontal_wrapped(|ui| { let data_list = workspace_data.get_crt_id_list(); for request_id in data_list.iter() { let request_data_option = workspace_data.get_crt_cloned(request_id.to_string()); match &request_data_option { None => { continue; } Some(request_data) => { match &request_data.collection_path{ None => {} Some(cp) => { if let Some(cname) = config_data.select_collection(){ if !cp.starts_with(format!("{}/",cname).as_str()){ //不是这个collection的crt过滤下不显示了 continue; } }; } } let mut lb = utils::build_rest_ui_header(request_data.record.clone(), Some(15), ui); let style = Style::default(); if request_data.collection_path.is_none(){ RichText::new(" * ") .color(Color32::LIGHT_GRAY) .append_to(&mut lb, &style, FontSelection::Default, Align::Center); } if request_data.is_modify() { RichText::new(" ●") .color(Color32::RED) .append_to(&mut lb, &style, FontSelection::Default, Align::Center); } self.select_crt_id = workspace_data.get_crt_select_id(); let response = ui.selectable_value( &mut self.select_crt_id, Some(request_data.id.clone()), lb, ); if response.clicked() { workspace_data.set_crt_select_id(self.select_crt_id.clone()); } response.context_menu(|ui| { if ui.button("Duplicate Tab").clicked() { workspace_data.duplicate_crt(request_data.id.clone()); ui.close_menu(); } ui.separator(); if ui.button("Close").clicked() { if !request_data.is_modify() { workspace_data.close_crt(request_data.id.clone()); } else { operation.add_window(Box::new( RequestCloseWindows::default().with( request_data.id.clone(), request_data.get_tab_name(), ), )) } ui.close_menu(); } if ui.button("Force Close").clicked() { workspace_data.close_crt(request_data.id.clone()); ui.close_menu(); } if ui.button("Force Close Other Tabs").clicked() { workspace_data.close_other_crt(request_data.id.clone()); ui.close_menu(); } if ui.button("Force Close All Tabs").clicked() { workspace_data.close_all_crt(); ui.close_menu(); } }); } } } ui.menu_button("+", |ui| { if ui.button("New Rest").clicked() { workspace_data.add_new_rest_crt(); ui.close_menu(); } if ui.button("New WebSocket").clicked() { workspace_data.add_new_websocket_crt(); ui.close_menu(); } }); if ui.button("...").clicked() {} }); let crt_list = workspace_data.get_crt_id_list(); if crt_list.len() == 0 { workspace_data.add_new_rest_crt(); } let crt_list = workspace_data.get_crt_id_list(); if self.select_crt_id.is_none() { workspace_data.set_crt_select_id(crt_list.get(0).cloned()); } } fn render_name_label( &mut self, workspace_data: &mut WorkspaceData, crt_id: String, ui: &mut Ui, ) { let crt = workspace_data.must_get_crt(crt_id.clone()); let tab_name = crt.get_tab_name(); match &crt.collection_path { None => { ui.horizontal(|ui| { ui.strong(tab_name); }); } Some(collection_path) => { ui.horizontal(|ui| { Label::new( RichText::new(collection_path) .strong() .background_color(ui.visuals().extreme_bg_color), ) .ui(ui); ui.strong(tab_name); }); } } } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/panels/history_panel.rs
crates/netpurr/src/panels/history_panel.rs
use egui::CollapsingHeader; use netpurr_core::data::central_request_data::CentralRequestItem; use netpurr_core::data::workspace_data::WorkspaceData; use crate::utils; #[derive(Default)] pub struct HistoryPanel {} impl HistoryPanel { pub fn set_and_render(&mut self, ui: &mut egui::Ui, workspace_data: &mut WorkspaceData) { for (date, date_history_data) in workspace_data.get_history_group().iter().rev() { CollapsingHeader::new(date.to_string()) .default_open(false) .show(ui, |ui| { for history_rest_item in date_history_data.history_list.iter().rev() { let lb = utils::build_rest_ui_header(history_rest_item.record.clone(), None, ui); let button = ui.button(lb); if button.clicked() { workspace_data.add_crt(CentralRequestItem { id: history_rest_item.id.clone(), collection_path: None, record: history_rest_item.record.clone(), ..Default::default() }) } } }); } } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/data/workspace.rs
crates/netpurr/src/data/workspace.rs
use std::path::PathBuf; use rustygit::Repository; #[derive(Clone, PartialEq, Eq, Debug)] pub struct Workspace { pub name: String, pub path: PathBuf, pub enable_git: Option<bool>, pub remote_url: Option<String>, } impl Workspace { pub fn if_enable_git(&mut self) -> bool { if let Some(git) = self.enable_git { return git; } let repo = Repository::new(self.path.clone()); match repo.cmd(["status"]) { Ok(_) => { self.enable_git = Some(true); true } Err(_) => false, } } pub fn has_remote_url(&mut self) -> bool { if let Some(url) = &self.remote_url { return true; } let repo = Repository::new(self.path.clone()); if let Ok(remote) = repo.cmd_out(["remote", "get-url", "origin"]) { if remote.len() > 0 { self.remote_url = Some(remote[0].clone()); return true; } else { return false; } } false } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/data/mod.rs
crates/netpurr/src/data/mod.rs
use std::fmt::Display; use std::io::{Read, Write}; use std::str::FromStr; use base64::Engine; use egui::TextBuffer; use serde::{Deserialize, Serialize}; use strum::IntoEnumIterator; pub mod config_data; pub mod export; pub mod workspace;
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/data/export.rs
crates/netpurr/src/data/export.rs
use serde::{Deserialize, Serialize}; use netpurr_core::data::collections::Collection; #[derive(Default, Clone, Debug, Serialize, Deserialize)] #[serde(default)] pub struct Export { pub openapi: Option<String>, pub info: Option<PostmanInfo>, pub export_type: ExportType, pub collection: Option<Collection>, } #[derive(Default, Clone, Debug, Serialize, Deserialize)] #[serde(default)] pub struct PostmanInfo { pub _postman_id: Option<String>, pub name: Option<String>, pub schema: Option<String>, } #[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)] pub enum ExportType { None, Collection, Request, Environment, } impl Default for ExportType { fn default() -> Self { ExportType::None } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/data/config_data.rs
crates/netpurr/src/data/config_data.rs
use std::collections::BTreeMap; use std::fs; use std::fs::File; use std::io::{Error, Read, Write}; use std::path::Path; use serde::{Deserialize, Serialize}; use crate::APP_NAME; use crate::data::workspace::Workspace; #[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)] #[serde(default)] pub struct ConfigData { select_workspace: Option<String>, select_collection: Option<String>, #[serde(skip, default)] workspaces: BTreeMap<String, Workspace>, } impl Default for ConfigData { fn default() -> Self { let mut workspaces = BTreeMap::default(); workspaces.insert( "default".to_string(), Workspace { name: "default".to_string(), path: dirs::home_dir() .unwrap_or(Path::new("/home").to_path_buf()) .join(APP_NAME) .join("workspaces") .join("default"), enable_git: None, remote_url: None, }, ); ConfigData { select_workspace: None, select_collection: None, workspaces, } } } impl ConfigData { pub fn load() -> Self { let mut config_data = if let Some(home_dir) = dirs::home_dir() { let config_path = home_dir.join(APP_NAME).join("config.json"); match File::open(config_path) { Ok(mut file) => { let mut content = String::new(); match file.read_to_string(&mut content) { Ok(_) => { let result: serde_json::Result<Self> = serde_json::from_str(content.as_str()); result.unwrap_or_else(|_| Self::default()) } Err(_) => Self::default(), } } Err(_) => Self::default(), } } else { Self::default() }; config_data.refresh_workspaces(); config_data } pub fn new_workspace(&mut self, name: String) { if let Some(home_dir) = dirs::home_dir() { let workspaces_path = home_dir.join(APP_NAME).join("workspaces").join(name); fs::create_dir_all(workspaces_path); self.refresh_workspaces(); } } pub fn refresh_workspaces(&mut self) { self.workspaces.clear(); if let Some(home_dir) = dirs::home_dir() { let workspaces_path = home_dir.join(APP_NAME).join("workspaces"); if let Ok(entries) = fs::read_dir(workspaces_path) { for entry in entries { if let Ok(entry) = entry { if entry.path().is_dir() { if let Some(file_name) = entry.file_name().to_str() { self.workspaces.insert( file_name.to_string(), Workspace { name: file_name.to_string(), path: entry.path(), enable_git: None, remote_url: None, }, ); } } } } } } } pub fn select_workspace(&self) -> Option<String> { self.select_workspace.clone() } pub fn select_collection(&self) -> Option<String> { self.select_collection.clone() } pub fn set_select_workspace(&mut self, select_workspace: Option<String>) { self.select_workspace = select_workspace; self.save(); } pub fn set_select_collection(&mut self, collection: Option<String>) { self.select_collection = collection; self.save(); } pub fn set_select_workspace_collection( &mut self, select_workspace: Option<String>, collection: Option<String>, ) { self.select_workspace = select_workspace; self.select_collection = collection; self.save(); } fn save(&self) -> Result<(), Error> { let json = serde_json::to_string(self)?; if let Some(home_dir) = dirs::home_dir() { let config_path = home_dir.join(APP_NAME).join("config.json"); let mut file = File::create(config_path.clone())?; file.write_all(json.as_bytes())?; } Ok(()) } pub fn workspaces(&self) -> &BTreeMap<String, Workspace> { &self.workspaces } pub fn mut_workspaces(&mut self) -> &mut BTreeMap<String, Workspace> { &mut self.workspaces } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/import/postman.rs
crates/netpurr/src/import/postman.rs
use std::cell::RefCell; use std::collections::BTreeMap; use std::rc::Rc; use std::str::FromStr; use anyhow::anyhow; use serde::{Deserialize, Serialize}; use netpurr_core::data::auth::{Auth, AuthType}; use netpurr_core::data::collections::{Collection, CollectionFolder}; use netpurr_core::data::environment::{EnvironmentConfig, EnvironmentItem, EnvironmentValueType}; use netpurr_core::data::http::{ BodyRawType, Header, HttpBody, HttpRecord, Method, MultipartData, MultipartDataType, PathVariables, QueryParam, Request, RequestSchema, }; use netpurr_core::data::record::Record; #[derive(Serialize, Deserialize, Default, Clone)] #[serde(default)] pub struct Postman { info: PostmanInfo, item: Vec<PostmanItemGroup>, event: Vec<PostmanEvent>, variable: Vec<PostmanVariable>, auth: PostmanAuth, } impl Postman { pub fn try_import(json: String) -> serde_json::Result<Postman> { serde_json::from_str(json.as_str()) } pub fn to_collection(&self) -> anyhow::Result<Collection> { if self.info.name.is_empty() { Err(anyhow!("not postman")) } else { let collection = Collection { envs: EnvironmentConfig { items: self.variable.iter().map(|v| v.to()).collect(), }, openapi: None, folder: Rc::new(RefCell::new(CollectionFolder { name: self.info.name.clone(), parent_path: ".".to_string(), desc: self.info.description.clone(), auth: self.auth.to(), is_root: true, requests: PostmanItemGroup::gen_requests(self.item.clone()), folders: PostmanItemGroup::gen_folders(self.item.clone()), pre_request_script: "".to_string(), test_script: "".to_string(), testcases: Default::default(), })), }; Ok(collection) } } } #[derive(Serialize, Deserialize, Default, Clone)] #[serde(default)] pub struct PostmanInfo { name: String, description: String, } #[derive(Serialize, Deserialize, Default, Clone)] #[serde(default)] pub struct PostmanItemGroup { name: String, description: String, variable: Vec<PostmanVariable>, item: Vec<PostmanItemGroup>, request: PostmanRequest, event: Vec<PostmanEvent>, auth: PostmanAuth, } impl PostmanItemGroup { pub fn gen_requests(pgs: Vec<PostmanItemGroup>) -> BTreeMap<String, Record> { let http_records: Vec<Record> = pgs .iter() .filter(|p| p.item.is_empty()) .map(|p| { Record::Rest(HttpRecord { name: p.name.to_string(), desc: p.description.to_string(), request: Request { method: Method::from_str(p.request.method.to_uppercase().as_str()) .unwrap_or_default(), schema: RequestSchema::from_str( p.request.url.protocol.to_uppercase().as_str(), ) .unwrap_or_default(), raw_url: p.request.url.raw.clone(), base_url: "".to_string(), path_variables: p .request .url .variable .iter() .map(|v| PathVariables { key: v.key.clone(), value: v.value.clone(), desc: v.description.clone(), }) .collect(), params: p .request .url .query .iter() .map(|q| QueryParam { key: q.key.clone(), value: q.value.clone(), desc: q.description.clone(), lock_with: Default::default(), enable: !q.disabled, }) .collect(), headers: p .request .header .iter() .map(|h| Header { key: h.key.clone(), value: h.value.clone(), desc: h.description.clone(), enable: !h.disabled, lock_with: Default::default(), }) .collect(), body: p.request.body.to(), auth: p.auth.to(), }, ..Default::default() }) }) .collect(); let mut result = BTreeMap::default(); for http_record in http_records.iter() { let mut record_clone = http_record.clone(); record_clone.must_get_mut_rest().request.parse_raw_url(); result.insert(http_record.name(), record_clone); } result } pub fn gen_folders( pgs: Vec<PostmanItemGroup>, ) -> BTreeMap<String, Rc<RefCell<CollectionFolder>>> { let folders: Vec<CollectionFolder> = pgs .iter() .filter(|p| !p.item.is_empty()) .map(|p| CollectionFolder { name: p.name.clone(), parent_path: "".to_string(), desc: p.description.clone(), auth: p.auth.to(), is_root: false, requests: PostmanItemGroup::gen_requests(p.item.clone()), folders: PostmanItemGroup::gen_folders(p.item.clone()), pre_request_script: "".to_string(), test_script: "".to_string(), testcases: Default::default(), }) .collect(); let mut result = BTreeMap::default(); for folder in folders.iter() { result.insert(folder.name.clone(), Rc::new(RefCell::new(folder.clone()))); } result } } #[derive(Serialize, Deserialize, Default, Clone)] #[serde(default)] pub struct PostmanVariable { key: String, value: String, name: String, description: String, disabled: bool, system: bool, } impl PostmanVariable { fn to(&self) -> EnvironmentItem { EnvironmentItem { enable: !self.disabled, key: self.key.clone(), value: self.value.clone(), desc: self.description.clone(), value_type: EnvironmentValueType::String, } } } #[derive(Serialize, Deserialize, Default, Clone)] #[serde(default)] pub struct PostmanRequest { auth: PostmanAuth, proxy: PostmanProxy, method: String, description: String, header: Vec<PostmanHeader>, body: PostmanBody, url: PostmanUrl, } #[derive(Serialize, Deserialize, Default, Clone)] #[serde(default)] pub struct PostmanProxy { #[serde(alias = "match")] proxy_match: String, host: String, port: i32, tunnel: bool, disabled: bool, } #[derive(Serialize, Deserialize, Default, Clone)] #[serde(default)] pub struct PostmanBody { mode: String, raw: String, urlencoded: Vec<PostmanUrlEncodedParameter>, formdata: Vec<PostmanFormParameter>, file: PostmanFile, disabled: bool, } impl PostmanBody { pub fn to(&self) -> HttpBody { let mut http_body = HttpBody::default(); match self.mode.as_str() { "raw" => { http_body.body_raw_type = BodyRawType::JSON; http_body.body_str = self.raw.clone() } "urlencoded" => { for parameter in self.urlencoded.iter() { http_body.body_xxx_form.push(MultipartData { data_type: MultipartDataType::TEXT, key: parameter.key.clone(), value: parameter.value.clone(), desc: parameter.description.clone(), lock_with: Default::default(), enable: !parameter.disabled, }); } } "formdata" => { for parameter in self.formdata.iter() { let mut value = parameter.value.clone(); if parameter.form_type == "file" { value = parameter.src.clone(); } http_body.body_form_data.push(MultipartData { data_type: MultipartDataType::from_str( parameter.form_type.to_uppercase().as_str(), ) .unwrap_or_default(), key: parameter.key.clone(), value, desc: parameter.description.clone(), lock_with: Default::default(), enable: !parameter.disabled, }) } } "file" => http_body.body_file = self.file.src.clone(), _ => {} } http_body } } #[derive(Serialize, Deserialize, Default, Clone)] #[serde(default)] pub struct PostmanFile { src: String, content: String, } #[derive(Serialize, Deserialize, Default, Clone)] #[serde(default)] pub struct PostmanUrlEncodedParameter { key: String, value: String, disabled: bool, description: String, } #[derive(Serialize, Deserialize, Default, Clone)] #[serde(default)] pub struct PostmanFormParameter { key: String, src: String, value: String, disabled: bool, #[serde(alias = "type")] form_type: String, #[serde(alias = "contentType")] content_type: String, description: String, } #[derive(Serialize, Deserialize, Default, Clone)] #[serde(default)] pub struct PostmanAuth { #[serde(alias = "type")] auth_type: String, apikey: Vec<PostmanAuthAttribute>, awsv4: Vec<PostmanAuthAttribute>, basic: Vec<PostmanAuthAttribute>, bearer: Vec<PostmanAuthAttribute>, digest: Vec<PostmanAuthAttribute>, edgegrid: Vec<PostmanAuthAttribute>, hawk: Vec<PostmanAuthAttribute>, ntlm: Vec<PostmanAuthAttribute>, oauth1: Vec<PostmanAuthAttribute>, oauth2: Vec<PostmanAuthAttribute>, } impl PostmanAuth { pub fn to(&self) -> Auth { let auth_type = match self.auth_type.as_str() { "bearer" => AuthType::BearerToken, "basic" => AuthType::BasicAuth, "noauth" => AuthType::NoAuth, _ => AuthType::InheritAuthFromParent, }; let basic_username = self .basic .iter() .find(|a| a.key == "username") .cloned() .unwrap_or_default() .value .clone(); let basic_password = self .basic .iter() .find(|a| a.key == "password") .cloned() .unwrap_or_default() .value .clone(); let bearer_token = self .basic .iter() .find(|a| a.key == "token") .cloned() .unwrap_or_default() .value .clone(); Auth { auth_type, basic_username, basic_password, bearer_token, } } } #[derive(Serialize, Deserialize, Default, Clone)] #[serde(default)] pub struct PostmanAuthAttribute { key: String, value: String, } #[derive(Serialize, Deserialize, Default, Clone)] #[serde(default)] pub struct PostmanHeader { key: String, disabled: bool, value: String, description: String, } #[derive(Serialize, Deserialize, Default, Clone)] #[serde(default)] pub struct PostmanUrl { raw: String, protocol: String, host: Vec<String>, path: Vec<String>, query: Vec<PostmanQuery>, port: String, variable: Vec<PostmanVariable>, } #[derive(Serialize, Deserialize, Default, Clone)] #[serde(default)] pub struct PostmanQuery { key: String, value: String, disabled: bool, description: String, } #[derive(Serialize, Deserialize, Default, Clone)] #[serde(default)] pub struct PostmanEvent { listen: String, disabled: bool, }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/import/mod.rs
crates/netpurr/src/import/mod.rs
pub mod openapi; pub mod postman;
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr/src/import/openapi.rs
crates/netpurr/src/import/openapi.rs
use std::cell::RefCell; use std::collections::{BTreeMap, HashMap}; use std::rc::Rc; use std::string::ToString; use anyhow::anyhow; use base64::Engine; use base64::engine::general_purpose; use openapiv3::{ MediaType, OpenAPI, Operation, Parameter, ReferenceOr, RequestBody, SchemaKind, Server, StringFormat, Tag, Type, VariantOrUnknownOrEmpty, }; use regex::Regex; use netpurr_core::data::auth::Auth; use netpurr_core::data::collections::{Collection, CollectionFolder}; use netpurr_core::data::environment::{EnvironmentConfig, EnvironmentItem}; use netpurr_core::data::http::{ BodyRawType, BodyType, Header, HttpBody, HttpRecord, Method, MultipartData, MultipartDataType, QueryParam, Request, RequestSchema, }; use netpurr_core::data::record::Record; use crate::utils::openapi_help::{GetItem, OpenApiHelp}; const DEFAULT_TAG: &str = "Default"; pub struct OpenApi { pub(crate) openapi_help: OpenApiHelp, } pub struct OpenApiOperation { operation: Operation, method: Method, path: String, } impl OpenApi { pub fn try_import(content: String) -> anyhow::Result<OpenApi> { if content.starts_with("{") { return match serde_json::from_str::<OpenAPI>(content.as_str()) { Ok(openapi) => Ok(OpenApi { openapi_help: OpenApiHelp { openapi }, }), Err(e) => Err(anyhow!(e)), }; } else { return match serde_yaml::from_str::<OpenAPI>(content.as_str()) { Ok(openapi) => Ok(OpenApi { openapi_help: OpenApiHelp { openapi }, }), Err(e) => Err(anyhow!(e)), }; } } pub fn to_collection(&self) -> anyhow::Result<Collection> { if self.openapi_help.openapi.info.title.is_empty() { return Err(anyhow!("not postman")); } let mut tag_map: HashMap<String, Vec<OpenApiOperation>> = HashMap::new(); tag_map.insert(DEFAULT_TAG.to_string(), vec![]); for (path, ref_path_item) in self.openapi_help.openapi.paths.iter() { if let Some(path_item) = ref_path_item.as_item() { if let Some(get) = path_item.get.clone() { Self::group_operation(&mut tag_map, path.clone(), Method::GET, get); } if let Some(put) = path_item.put.clone() { Self::group_operation(&mut tag_map, path.clone(), Method::PUT, put); } if let Some(delete) = path_item.delete.clone() { Self::group_operation(&mut tag_map, path.clone(), Method::DELETE, delete); } if let Some(post) = path_item.post.clone() { Self::group_operation(&mut tag_map, path.clone(), Method::POST, post); } if let Some(patch) = path_item.patch.clone() { Self::group_operation(&mut tag_map, path.clone(), Method::PATCH, patch); } if let Some(options) = path_item.options.clone() { Self::group_operation(&mut tag_map, path.clone(), Method::OPTIONS, options); } if let Some(head) = path_item.head.clone() { Self::group_operation(&mut tag_map, path.clone(), Method::HEAD, head); } } } let server = self.openapi_help.openapi.servers.get(0); let host = server .unwrap_or(&Server { url: "http://localhost:8080".to_string(), description: None, variables: None, extensions: Default::default(), }) .url .clone(); let host_schema: Vec<&str> = host.split("://").collect(); let mut host_value = host.clone(); if host_schema.len() >= 2 { host_value = host_schema[1].to_string(); } let schema = RequestSchema::try_from(host_schema[0].to_uppercase().as_str()).unwrap_or_default(); let collection = Collection { envs: EnvironmentConfig { items: vec![EnvironmentItem { enable: true, key: "server_host".to_string(), value: host_value, desc: "".to_string(), value_type: Default::default(), }], }, openapi: Some(self.openapi_help.openapi.clone()), folder: Rc::new(RefCell::new(CollectionFolder { name: self.openapi_help.openapi.info.title.to_string(), parent_path: ".".to_string(), desc: self .openapi_help .openapi .info .description .clone() .unwrap_or_default(), auth: Default::default(), is_root: true, requests: Default::default(), folders: self.gen_folders(tag_map, self.openapi_help.openapi.tags.clone()), pre_request_script: "".to_string(), test_script: "".to_string(), testcases: Default::default(), })), }; Ok(collection) } fn group_operation( tag_map: &mut HashMap<String, Vec<OpenApiOperation>>, path: String, method: Method, op: Operation, ) { if op.tags.is_empty() { let mut operations = tag_map.get_mut(DEFAULT_TAG).unwrap(); operations.push(OpenApiOperation { operation: op.clone(), method, path, }) } else { let tag_name = op.tags.get(0).unwrap(); if !tag_map.contains_key(tag_name) { tag_map.insert(tag_name.to_string(), vec![]); } let mut operations = tag_map.get_mut(tag_name).unwrap(); operations.push(OpenApiOperation { operation: op.clone(), method, path, }) } } pub fn gen_folders( &self, tag_map: HashMap<String, Vec<OpenApiOperation>>, tags: Vec<Tag>, ) -> BTreeMap<String, Rc<RefCell<CollectionFolder>>> { let mut openapi_tags: HashMap<String, Tag> = HashMap::new(); for tag in tags.iter() { openapi_tags.insert(tag.name.clone(), tag.clone()); } let folders: Vec<CollectionFolder> = tag_map .iter() .map(|(name, records)| CollectionFolder { name: name.clone(), parent_path: "".to_string(), desc: openapi_tags .get(name) .cloned() .unwrap_or_default() .description .unwrap_or_default(), auth: Default::default(), is_root: false, requests: self.gen_requests(records, RequestSchema::HTTP), folders: Default::default(), pre_request_script: "".to_string(), test_script: "".to_string(), testcases: Default::default(), }) .collect(); let mut result = BTreeMap::default(); for folder in folders.iter() { result.insert(folder.name.clone(), Rc::new(RefCell::new(folder.clone()))); } result } pub fn gen_requests( &self, operations: &Vec<OpenApiOperation>, schema: RequestSchema, ) -> BTreeMap<String, Record> { let http_records: Vec<Record> = operations .iter() .map(|op| { Record::Rest(HttpRecord { name: op.operation.summary.clone().unwrap_or( format!("{} {}", op.method.clone(), op.path.clone()).replace("/", "_"), ), desc: op.operation.description.clone().unwrap_or_default(), operation_id: op.operation.operation_id.clone(), request: Request { method: op.method.clone(), schema: schema.clone(), raw_url: Self::gen_raw_path(op, schema.to_string().to_lowercase()), base_url: "".to_string(), path_variables: vec![], params: op .operation .parameters .iter() .map(|q| q.as_item()) .filter(|q| q.is_some()) .map(|q| q.unwrap()) .filter(|q| match q { Parameter::Query { .. } => true, _ => false, }) .map(|q| QueryParam { key: q.clone().parameter_data().name.clone(), value: "".to_string(), desc: q.clone().parameter_data().description.unwrap_or_default(), lock_with: Default::default(), enable: true, }) .collect(), headers: op .operation .parameters .iter() .map(|q| q.as_item()) .filter(|q| q.is_some()) .map(|q| q.unwrap()) .filter(|q| match q { Parameter::Header { .. } => true, _ => false, }) .map(|q| Header { key: q.clone().parameter_data().name.clone(), value: "".to_string(), desc: q.clone().parameter_data().description.unwrap_or_default(), lock_with: Default::default(), enable: true, }) .collect(), body: self.gen_http_body(op.operation.request_body.clone()), auth: Auth::default(), }, ..Default::default() }) }) .collect(); let mut result = BTreeMap::default(); for http_record in http_records.iter() { let mut record_clone = http_record.clone(); record_clone.must_get_mut_rest().request.parse_raw_url(); result.insert(http_record.name(), record_clone); } result } fn gen_http_body(&self, option: Option<ReferenceOr<RequestBody>>) -> HttpBody { let mut body = HttpBody::default(); match option { None => body, Some(rr) => { if let Some(r) = rr.get_item(&self.openapi_help.openapi) { for (name, mt) in r.content.iter() { match name.to_lowercase().as_str() { "application/json" => { body.body_type = BodyType::RAW; body.body_raw_type = BodyRawType::JSON; match mt.schema.clone() { None => {} Some(rs) => { if let Some(s) = rs.get_item(&self.openapi_help.openapi) { let json = self.openapi_help.gen_schema(s); match json { None => {} Some(s) => { body.body_str = serde_json::to_string_pretty(&s).unwrap(); body.base64 = general_purpose::STANDARD .encode(body.body_str.clone()) .to_string() } } } } } } "multipart/form-data" => { body.body_type = BodyType::FROM_DATA; Self::gen_multipart_body(&mut body, mt); } _ => {} } } } return body; } } } fn gen_multipart_body(body: &mut HttpBody, mt: &MediaType) { match mt.schema.clone() { None => {} Some(rs) => match rs.as_item() { None => {} Some(s) => match s.schema_kind.clone() { SchemaKind::Type(t) => match t { Type::Object(o) => { for (name, rs) in o.properties.iter() { match rs.as_item() { None => {} Some(s) => match s.schema_kind.clone() { SchemaKind::Type(t) => match t { Type::String(s) => match s.format { VariantOrUnknownOrEmpty::Item(sf) => match sf { StringFormat::Binary => { body.body_form_data.push(MultipartData { data_type: MultipartDataType::FILE, key: name.clone(), value: "".to_string(), desc: "".to_string(), lock_with: Default::default(), enable: false, }) } _ => body.body_form_data.push(MultipartData { data_type: MultipartDataType::TEXT, key: name.clone(), value: "".to_string(), desc: "".to_string(), lock_with: Default::default(), enable: false, }), }, _ => {} }, _ => {} }, _ => {} }, } } } _ => {} }, _ => {} }, }, } } fn gen_raw_path(op: &OpenApiOperation, protocol: String) -> String { let head = protocol + "://{{server_host}}"; let re = Regex::new(r"\{([^{}]+)}").unwrap(); let replaced_path = re.replace_all(op.path.as_str(), ":$1"); return format!("{}{}", head, replaced_path); } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr_core/src/lib.rs
crates/netpurr_core/src/lib.rs
extern crate core; pub mod data; pub mod persistence; pub mod runner; pub mod script; pub mod utils; pub const APP_NAME: &str = "Netpurr";
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr_core/src/persistence.rs
crates/netpurr_core/src/persistence.rs
use std::fmt::Display; use std::fs; use std::fs::File; use std::io::{Read, Write}; use std::path::PathBuf; use std::string::ToString; use log::error; use serde::de::DeserializeOwned; use serde::Serialize; use crate::APP_NAME; pub const PERSISTENCE_EXTENSION_RAW: &str = "yaml"; pub const PERSISTENCE_EXTENSION: &str = ".yaml"; pub fn get_persistence_path(path: &str) -> String { return format!("{}{}", path, PERSISTENCE_EXTENSION); } pub trait PersistenceItem { fn save<T: Serialize>(&self, path: PathBuf, key: String, data: &T); fn load<T: DeserializeOwned + std::fmt::Debug>(&self, path: PathBuf) -> Option<T>; fn load_list(&self, path: PathBuf) -> Vec<PathBuf>; fn remove(&self, path: PathBuf, key: String); fn rename(&self, old_path: PathBuf, new_path: PathBuf); fn remove_dir(&self, path: PathBuf); fn get_workspace_dir(&self) -> PathBuf; fn set_workspace(&mut self, workspace: String); } #[derive(Clone, PartialEq, Eq, Debug)] pub struct Persistence { root: PathBuf, workspace: String, } impl Default for Persistence { fn default() -> Self { Persistence { root: dirs::home_dir().expect("find home dir error"), workspace: "default".to_string(), } } } impl Persistence { pub fn encode(key: String) -> String { key.as_str() .replace(".", "%dot") .trim_start_matches("/") .to_string() } pub fn decode(key: String) -> String { key.as_str().replace("%dot", ".") } pub fn decode_with_file_name(key: String) -> String { Persistence::decode(key.trim_end_matches(PERSISTENCE_EXTENSION).to_string()) } } impl PersistenceItem for Persistence { fn save<T: Serialize>(&self, path: PathBuf, key: String, data: &T) { let save_key = Persistence::encode(key); let workspace_dir = self.get_workspace_dir(); let mut rel_path = path.clone(); if !rel_path.starts_with(workspace_dir.clone()) { rel_path = workspace_dir.join(rel_path.clone()); } match serde_yaml::to_string(data) { Ok(yaml_str) => { let mut yaml_path = rel_path.join(save_key); yaml_path.set_extension(PERSISTENCE_EXTENSION_RAW); yaml_path.parent().map(|s| { if fs::create_dir_all(s.clone()).is_err() { error!("create_dir_all {:?} failed", rel_path); } }); let mut file_result = File::create(yaml_path.clone()); match file_result { Ok(mut file) => { if file.write_all(yaml_str.as_bytes()).is_err() { error!("write_all failed"); } } Err(_) => { error!("create_file {:?} failed", yaml_path); } } } Err(_) => { error!("serde_yaml::to_string failed"); } } } fn load<T: DeserializeOwned + std::fmt::Debug>(&self, path: PathBuf) -> Option<T> { let workspace_dir = self.get_workspace_dir(); let mut rel_path = path.clone(); if !rel_path.starts_with(workspace_dir.clone()) { rel_path = workspace_dir.join(rel_path.clone()); } match File::open(rel_path.clone()) { Ok(mut file) => { let mut content = String::new(); match file.read_to_string(&mut content) { Ok(_) => { let result: serde_yaml::Result<T> = serde_yaml::from_str(content.as_str()); match result { Ok(t) => Some(t), Err(_) => { error!("load {:?} failed: {:?}", path, result.unwrap_err()); None } } } Err(_) => { error!("read_to_string {:?} failed", rel_path); None } } } Err(_) => { error!("open {:?} failed", rel_path); None } } } fn load_list(&self, path: PathBuf) -> Vec<PathBuf> { let mut result = vec![]; let workspace_dir = self.get_workspace_dir(); let mut rel_path = path.clone(); if !rel_path.starts_with(workspace_dir.clone()) { rel_path = workspace_dir.join(rel_path.clone()); } let dir_path = workspace_dir.join(path); if let Ok(entries) = fs::read_dir(dir_path) { for entry in entries { if let Ok(entry) = entry { result.push(entry.path().to_path_buf()); } } } result } fn remove(&self, path: PathBuf, key: String) { let save_key = Persistence::encode(key); let workspace_dir = self.get_workspace_dir(); let mut rel_path = path.clone(); if !rel_path.starts_with(workspace_dir.clone()) { rel_path = workspace_dir.join(rel_path.clone()); } let mut json_path = rel_path.join(save_key); json_path.set_extension(PERSISTENCE_EXTENSION_RAW); if fs::remove_file(json_path.clone()).is_err() { error!("remove_file {:?} failed", json_path) } } fn rename(&self, old_path: PathBuf, new_path: PathBuf) { let workspace_dir = self.get_workspace_dir(); let mut rel_old_path = old_path.clone(); if !rel_old_path.starts_with(workspace_dir.clone()) { rel_old_path = workspace_dir.join(rel_old_path.clone()); } let mut rel_new_path = new_path.clone(); if !rel_new_path.starts_with(workspace_dir.clone()) { rel_new_path = workspace_dir.join(rel_new_path.clone()); } if fs::rename(rel_old_path.clone(), rel_new_path.clone()).is_err() { error!("rename {:?} to {:?} failed", rel_old_path, rel_new_path); } } fn remove_dir(&self, path: PathBuf) { let workspace_dir = self.get_workspace_dir(); let mut rel_path = path.clone(); if !rel_path.starts_with(workspace_dir.clone()) { rel_path = workspace_dir.join(rel_path.clone()); } if fs::remove_dir_all(rel_path.clone()).is_err() { error!("remove_dir {:?} failed", rel_path) } } fn get_workspace_dir(&self) -> PathBuf { return self .root .clone() .join(APP_NAME) .join("workspaces") .join(self.workspace.clone()); } fn set_workspace(&mut self, workspace: String) { self.workspace = workspace; } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr_core/src/utils.rs
crates/netpurr_core/src/utils.rs
use std::collections::{BTreeMap, HashSet}; use std::str::FromStr; use regex::Regex; use crate::data::environment::{EnvironmentItemValue, EnvironmentValueType}; use crate::data::environment_function::{EnvFunction, get_env_result}; pub fn replace_variable(content: String, envs: BTreeMap<String, EnvironmentItemValue>) -> String { let re = Regex::new(r"\{\{.*?}}").unwrap(); let mut result = content.clone(); loop { let temp = result.clone(); let find = re.find_iter(temp.as_str()).next(); match find { None => break, Some(find_match) => { let key = find_match .as_str() .trim_start_matches("{{") .trim_end_matches("}}") .trim_start() .trim_end(); let v = envs.get(key); match v { None => result.replace_range(find_match.range(), "{UNKNOWN}"), Some(etv) => match etv.value_type { EnvironmentValueType::String => { result.replace_range(find_match.range(), etv.value.as_str()) } EnvironmentValueType::Function => { let env_func = EnvFunction::from_str(etv.value.as_str()); match env_func { Ok(f) => result .replace_range(find_match.range(), get_env_result(f).as_str()), Err(_) => { result.replace_range(find_match.range(), "{UNKNOWN}"); } } } }, } } } } result } pub fn build_copy_name(mut name: String, names: HashSet<String>) -> String { name = name .splitn(2, "Copy") .next() .unwrap_or_default() .trim() .to_string(); let mut index = 2; let mut new_name = name.clone(); while (names.contains(new_name.as_str())) { new_name = format!("{} Copy {}", name.clone(), index); index += 1; } return new_name; }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr_core/src/runner/test.rs
crates/netpurr_core/src/runner/test.rs
use std::cell::RefCell; use std::collections::BTreeMap; use std::rc::Rc; use serde::{Deserialize, Serialize}; use crate::data::collections::{CollectionFolder, Testcase}; use crate::data::test::TestStatus; use crate::runner::{TestGroupRunResults, TestRunError, TestRunResult}; #[derive(Default, Clone, Serialize, Deserialize)] pub struct ResultTreeFolder { pub status: TestStatus, pub name: String, pub cases: BTreeMap<String, ResultTreeCase>, } #[derive(Default, Clone, Serialize, Deserialize)] pub struct ResultTreeCase { pub status: TestStatus, pub name: String, pub folders: BTreeMap<String, ResultTreeFolder>, pub requests: Vec<ResultTreeRequest>, } impl ResultTreeCase { pub fn get_success_count(&self) -> i32 { let mut success_count = 0; for r in self.requests.iter() { if r.status == TestStatus::PASS { success_count = success_count + 1; } } for (_, f) in self.folders.iter() { success_count += f.get_success_count(); } success_count } pub fn get_total_count(&self) -> i32 { let mut success_count = 0; for r in self.requests.iter() { success_count = success_count + 1; } for (_, f) in self.folders.iter() { success_count += f.get_total_count(); } success_count } } impl ResultTreeFolder { pub fn create( folder: Rc<RefCell<CollectionFolder>>, testcase_paths: Vec<String>, results: TestGroupRunResults, ) -> Self { let mut folder_status = TestStatus::WAIT; let mut testcases = folder.borrow().testcases.clone(); let folder_name = folder.borrow().name.clone(); if testcases.is_empty() { let testcase = Testcase::default(); testcases.insert(testcase.name.clone(), testcase); } let mut new_result_tree_folder = ResultTreeFolder { status: folder_status.clone(), name: folder.borrow().name.clone(), cases: Default::default(), }; folder_status = TestStatus::PASS; for (folder_testcase_name, folder_testcase) in testcases.iter() { let mut case_status = TestStatus::WAIT; let mut case_folders = BTreeMap::new(); let mut case_requests = vec![]; case_status = TestStatus::PASS; let mut new_folder_testcase_nodes = testcase_paths.clone(); new_folder_testcase_nodes.push(format!("{}:{}", folder_name, folder_testcase_name)); for (name, f) in folder.borrow().folders.iter() { let child_folder = ResultTreeFolder::create( f.clone(), new_folder_testcase_nodes.clone(), results.clone(), ); match &child_folder.status { TestStatus::None => {} TestStatus::WAIT => case_status = TestStatus::WAIT, TestStatus::PASS => {} TestStatus::FAIL => case_status = TestStatus::FAIL, TestStatus::SKIP => case_status = TestStatus::SKIP, TestStatus::RUNNING => case_status = TestStatus::WAIT, } case_folders.insert(name.to_string(), child_folder); } for (request_name, record) in folder.borrow().requests.iter() { let mut record_testcases = record.testcase().clone(); if record_testcases.is_empty() { let testcase = Testcase::default(); record_testcases.insert(testcase.name.clone(), testcase); } for (request_testcase_name, _) in record_testcases.iter() { let mut request_testcase_path = new_folder_testcase_nodes.clone(); request_testcase_path .push(format!("{}:{}", request_name, request_testcase_name)); let result = results.find(request_testcase_path); let mut request_status = TestStatus::WAIT; match &result { None => { case_status = TestStatus::WAIT; } Some(rr) => match rr { Ok(r) => { request_status = r.test_result.status.clone(); if request_status == TestStatus::FAIL { case_status = TestStatus::FAIL; }else if request_status == TestStatus::RUNNING { case_status = TestStatus::RUNNING; } } Err(e) => { request_status = TestStatus::FAIL; case_status = TestStatus::FAIL; } }, } case_requests.push(ResultTreeRequest { name: format!("{}:{}", request_name, request_testcase_name), status: request_status, result: result.clone(), }); } } let result_tree_case = ResultTreeCase { status: case_status.clone(), name: folder_testcase.name.to_string(), folders: case_folders.clone(), requests: case_requests.clone(), }; new_result_tree_folder .cases .insert(folder_testcase.name.to_string(), result_tree_case); match &case_status { TestStatus::None => {} TestStatus::WAIT => folder_status = TestStatus::WAIT, TestStatus::PASS => {} TestStatus::FAIL => folder_status = TestStatus::FAIL, TestStatus::SKIP => folder_status = TestStatus::SKIP, TestStatus::RUNNING => folder_status = TestStatus::WAIT } } new_result_tree_folder.status = folder_status.clone(); new_result_tree_folder } pub fn get_success_count(&self) -> i32 { let mut success_count = 0; for (_, case) in self.cases.iter() { for r in case.requests.iter() { if r.status == TestStatus::PASS { success_count = success_count + 1; } } for (_, f) in case.folders.iter() { success_count += f.get_success_count(); } } success_count } pub fn get_total_count(&self) -> i32 { let mut success_count = 0; for (_, case) in self.cases.iter() { for r in case.requests.iter() { success_count = success_count + 1; } for (_, f) in case.folders.iter() { success_count += f.get_total_count(); } } success_count } } #[derive(Default, Clone, Serialize, Deserialize)] pub struct ResultTreeRequest { pub name: String, pub status: TestStatus, pub result: Option<Result<TestRunResult, TestRunError>>, }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr_core/src/runner/rest.rs
crates/netpurr_core/src/runner/rest.rs
use std::collections::{BTreeMap, HashMap}; use std::path::Path; use std::str::FromStr; use std::sync::Arc; use std::time::Instant; use anyhow::anyhow; use log::info; use reqwest::{Body, Client, multipart}; use reqwest::header::CONTENT_TYPE; use reqwest::Method; use reqwest::multipart::Part; use tokio::fs::File; use tokio_tungstenite::tungstenite::http::Uri; use tokio_util::codec::{BytesCodec, FramedRead}; use crate::data::environment::EnvironmentItemValue; use crate::data::http; use crate::data::http::{ BodyRawType, BodyType, Header, HttpBody, LockWith, MultipartDataType, PathVariables, QueryParam, }; use crate::data::logger::Logger; #[derive(Default, Clone, PartialEq, Eq, Debug)] pub struct RestSender {} impl RestSender { pub async fn reqwest_async_send( request: http::Request, client: Client, ) -> anyhow::Result<(http::Request, http::Response)> { let reqwest_request = Self::build_reqwest_request(request.clone()).await?; let mut new_request = request.clone(); for (hn, hv) in reqwest_request.headers().iter() { info!( "set header {}:{}", hn.as_str(), hv.to_str().unwrap_or_default() ); if new_request .headers .iter() .find(|h| { h.key.to_lowercase() == hn.to_string().to_lowercase() && h.value == hv.to_str().unwrap_or("") }) .is_none() { new_request.headers.push(Header { key: hn.to_string(), value: hv.to_str().unwrap_or("").to_string(), desc: "auto gen".to_string(), enable: true, lock_with: LockWith::LockWithAuto, }) } } let start_time = Instant::now(); let reqwest_response = client.execute(reqwest_request).await?; let total_time = start_time.elapsed(); Ok(( new_request, http::Response { request: request.clone(), headers: Header::new_from_map(reqwest_response.headers()), status: reqwest_response.status().as_u16(), status_text: reqwest_response.status().to_string(), elapsed_time: total_time.as_millis(), logger: Logger::default(), body: Arc::new(HttpBody::new(reqwest_response.bytes().await?.to_vec())), }, )) } pub async fn build_reqwest_request(request: http::Request) -> anyhow::Result<reqwest::Request> { let client = Client::new(); let method = Method::from_str(request.method.to_string().to_uppercase().as_str()) .unwrap_or_default(); let _ = Uri::try_from(request.get_url_with_schema())?; let mut builder = client.request(method, request.get_url_with_schema()); for header in request.headers.iter().filter(|h| h.enable) { builder = builder.header(header.key.clone(), header.value.clone()); } let query: Vec<(String, String)> = request .params .iter() .filter(|q| q.enable) .map(|p| (p.key.clone(), p.value.clone())) .collect(); builder = builder.query(&query); match request.body.body_type { BodyType::NONE => {} BodyType::FROM_DATA => { let mut form = multipart::Form::new(); for md in request.body.body_form_data.iter().filter(|md| md.enable) { match md.data_type { MultipartDataType::FILE => { let path = Path::new(md.value.as_str()); let content_type = mime_guess::from_path(path); // read file body stream let file = File::open(path).await?; let stream = FramedRead::new(file, BytesCodec::new()); let file_body = Body::wrap_stream(stream); //make form part of file let fname = path .file_name() .unwrap() .to_os_string() .into_string() .ok() .unwrap(); let some_file = Part::stream(file_body).file_name(fname).mime_str( content_type.first_or_octet_stream().to_string().as_str(), )?; form = form.part(md.key.clone(), some_file); } MultipartDataType::TEXT => { form = form.text(md.key.clone(), md.value.clone()); } } } builder = builder.multipart(form); } BodyType::X_WWW_FROM_URLENCODED => { let mut params = HashMap::new(); for md in request.body.body_xxx_form.iter().filter(|md| md.enable) { params.insert(md.key.clone(), md.value.clone()); } builder = builder.form(&params); } BodyType::RAW => { let content_type = request .headers .iter() .filter(|h| h.key.to_lowercase() == "content-type") .last(); match request.body.body_raw_type { BodyRawType::TEXT => { if content_type.is_none() { builder = builder.header(CONTENT_TYPE, "text/plain"); } builder = builder.body(request.body.body_str); } BodyRawType::JSON => { if content_type.is_none() { builder = builder.header(CONTENT_TYPE, "application/json"); } builder = builder.body(request.body.body_str); } BodyRawType::HTML => { if content_type.is_none() { builder = builder.header(CONTENT_TYPE, "text/html"); } builder = builder.body(request.body.body_str); } BodyRawType::XML => { if content_type.is_none() { builder = builder.header(CONTENT_TYPE, "application/xml"); } builder = builder.body(request.body.body_str); } BodyRawType::JavaScript => { if content_type.is_none() { builder = builder.header(CONTENT_TYPE, "application/javascript"); } builder = builder.body(request.body.body_str); } } } BodyType::BINARY => { let path = Path::new(request.body.body_file.as_str()); let content_type = mime_guess::from_path(path); builder = builder.header( CONTENT_TYPE, content_type.first_or_octet_stream().to_string(), ); let file = File::open(path).await?; let stream = FramedRead::new(file, BytesCodec::new()); let body = Body::wrap_stream(stream); builder = builder.body(body); } } match builder.build() { Ok(r) => Ok(r), Err(e) => Err(anyhow!(e)), } } pub(crate) fn build_request( request: http::Request, envs: BTreeMap<String, EnvironmentItemValue>, ) -> http::Request { let mut build_request = request.clone(); build_request.params = Self::build_query_params(request.params.clone(), &envs); build_request.base_url = Self::build_base_url( request.base_url.clone(), request.path_variables.clone(), &envs, ); build_request.headers = Self::build_header(request.headers.clone(), &envs); build_request.body.body_str = crate::utils::replace_variable(build_request.body.body_str, envs.clone()); for md in build_request.body.body_xxx_form.iter_mut() { md.key = crate::utils::replace_variable(md.key.clone(), envs.clone()); md.value = crate::utils::replace_variable(md.value.clone(), envs.clone()); } for md in build_request.body.body_form_data.iter_mut() { md.key = crate::utils::replace_variable(md.key.clone(), envs.clone()); md.value = crate::utils::replace_variable(md.value.clone(), envs.clone()); } build_request } fn build_header( headers: Vec<Header>, envs: &BTreeMap<String, EnvironmentItemValue>, ) -> Vec<Header> { headers .iter() .filter(|h| h.enable) .map(|h| Header { key: h.key.clone(), value: crate::utils::replace_variable(h.value.clone(), envs.clone()), desc: h.desc.clone(), enable: h.enable, lock_with: h.lock_with.clone(), }) .collect() } fn build_query_params( query_params: Vec<QueryParam>, envs: &BTreeMap<String, EnvironmentItemValue>, ) -> Vec<QueryParam> { query_params .iter() .filter(|q| q.enable) .map(|q| QueryParam { key: q.key.clone(), value: crate::utils::replace_variable(q.value.clone(), envs.clone()), desc: q.desc.clone(), enable: q.enable, lock_with: q.lock_with.clone(), }) .collect() } fn build_base_url( mut base_url: String, path_variables: Vec<PathVariables>, envs: &BTreeMap<String, EnvironmentItemValue>, ) -> String { base_url = crate::utils::replace_variable(base_url, envs.clone()); let build_path_variables: Vec<PathVariables> = path_variables .iter() .map(|p| PathVariables { key: p.key.clone(), value: crate::utils::replace_variable(p.value.clone(), envs.clone()), desc: p.desc.clone(), }) .collect(); let build_base_url: Vec<String> = base_url .split("/") .map(|part| { if part.starts_with(":") { let variable = &part[1..]; build_path_variables .iter() .find(|v| v.key == variable) .cloned() .unwrap_or_default() .value } else { part.to_string() } }) .collect(); build_base_url.join("/") } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr_core/src/runner/websocket.rs
crates/netpurr_core/src/runner/websocket.rs
use std::sync::{Arc, mpsc, Mutex}; use std::sync::mpsc::{Receiver, Sender}; use base64::Engine; use base64::engine::general_purpose; use chrono::Local; use deno_core::futures::{SinkExt, StreamExt}; use tokio_tungstenite::connect_async; use tokio_tungstenite::tungstenite::client::IntoClientRequest; use tokio_tungstenite::tungstenite::Message; use crate::data::http::Request; use crate::data::websocket::{MessageType, WebSocketMessage, WebSocketSession}; use crate::data::websocket::WebSocketStatus::{Connect, ConnectError, Connecting, SendError}; #[derive(Default, Clone, PartialEq, Eq, Debug)] pub struct WebSocketSender {} impl WebSocketSender { pub fn connect(request: Request) -> WebSocketSession { let (sender, receiver): (Sender<Message>, Receiver<Message>) = mpsc::channel(); let mut session = WebSocketSession { state: Arc::new(Mutex::new(Default::default())), sender, }; session.set_status(Connecting); let copy_session = session.clone(); let _ = poll_promise::Promise::spawn_thread("ws", || { let runtime = tokio::runtime::Builder::new_multi_thread() .worker_threads(2) .enable_all() .build() .unwrap(); runtime.block_on(Self::async_connect(copy_session, request, receiver)) }); session } async fn async_connect<R>( mut session: WebSocketSession, request: R, receiver: Receiver<Message>, ) where R: IntoClientRequest + Unpin, { match connect_async(request).await { Ok((ws_stream, response)) => { session.set_response(response); session.set_status(Connect); let (mut tx, rx) = ws_stream.split(); let copy_session = session.clone(); tokio::spawn(async move { let mut incoming = rx.map(Result::unwrap); while let Some(message) = incoming.next().await { if copy_session.get_status() != Connect { break; } match message { Message::Text(text) => copy_session.add_message( WebSocketMessage::Receive(Local::now(), MessageType::Text, text), ), Message::Binary(b) => { copy_session.add_message(WebSocketMessage::Receive( Local::now(), MessageType::Binary, general_purpose::STANDARD.encode(b), )) } _ => {} } } }); loop { if session.get_status() != Connect { break; } let message = receiver.recv().unwrap(); match tx.send(message).await { Ok(_) => {} Err(e) => { session.set_status(SendError(e.to_string())); break; } }; } } Err(e) => { session.set_status(ConnectError(e.to_string())); } } } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr_core/src/runner/html_report.rs
crates/netpurr_core/src/runner/html_report.rs
use serde::{Serialize, Deserialize}; #[derive(Serialize, Deserialize)] pub struct HtmlReport { #[serde(rename = "testPass")] pub test_pass: usize, #[serde(rename = "testSkip")] pub test_skip: usize, #[serde(rename = "totalTime")] pub total_time: String, #[serde(rename = "testAll")] pub test_all: usize, #[serde(rename = "beginTime")] pub begin_time: String, #[serde(rename = "testResult")] pub test_result: Vec<HtmlReportTestResult>, #[serde(rename = "testFail")] pub test_fail: usize, #[serde(rename = "testName")] pub test_name: String, } #[derive(Serialize, Deserialize)] pub struct HtmlReportTestResult { #[serde(rename = "log")] pub log: Vec<String>, #[serde(rename = "methodName")] pub method_name: String, #[serde(rename = "description")] pub description: String, #[serde(rename = "className")] pub class_name: String, #[serde(rename = "spendTime")] pub spend_time: String, #[serde(rename = "status")] pub status: String, }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr_core/src/runner/mod.rs
crates/netpurr_core/src/runner/mod.rs
use std::cell::RefCell; use std::collections::{BTreeMap, HashMap}; use std::fmt::Debug; use std::fs::File; use std::io::Write; use std::path::PathBuf; use std::rc::Rc; use std::str::FromStr; use std::sync::{Arc, RwLock}; use std::thread; use std::time::Duration; use anyhow::Error; use async_recursion::async_recursion; use chrono::Local; use deno_core::futures::future::join_all; use deno_core::futures::FutureExt; use log::{info, log}; use poll_promise::Promise; use rayon::{Scope, ThreadPool, ThreadPoolBuilder}; use reqwest::Client; use serde::{Deserialize, Serialize}; use reqwest_cookie_store::CookieStoreMutex; use rest::RestSender; use crate::data::collections::{CollectionFolder, CollectionFolderOnlyRead, Testcase}; use crate::data::environment::EnvironmentItemValue; use crate::data::http::{Request, Response}; use crate::data::logger::Logger; use crate::data::record::Record; use crate::data::test::{TestResult, TestStatus}; use crate::data::websocket::WebSocketSession; use crate::runner; use crate::runner::html_report::{HtmlReport, HtmlReportTestResult}; use crate::runner::websocket::WebSocketSender; use crate::script::{Context, JsResponse, ScriptRuntime, ScriptScope, ScriptTree, SharedMap, SkipError}; mod rest; pub mod test; mod websocket; mod html_report; #[derive(Clone)] pub struct Runner { script_runtime: ScriptRuntime, client: Client, } #[derive(Clone, Debug)] pub struct RunRequestInfo { pub shared_map:SharedMap, pub collection_path: Option<String>, pub request_name: String, pub request: Request, pub envs: BTreeMap<String, EnvironmentItemValue>, pub pre_request_scripts: Vec<ScriptScope>, pub test_scripts: Vec<ScriptScope>, pub testcase: Testcase, } #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct TestRunResult { pub request: Request, pub response: Option<Response>, pub test_result: TestResult, pub collection_path: Option<String>, pub request_name: String, pub testcase: Testcase, } #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct TestRunError { pub request: Request, pub response: Option<Response>, pub collection_path: Option<String>, pub request_name: String, pub testcase: Testcase, pub error: String, } impl Runner { pub fn new(cookie_store: Arc<CookieStoreMutex>) -> Self { Runner { script_runtime: Default::default(), client: Client::builder() .danger_accept_invalid_certs(true) .cookie_provider(cookie_store) .trust_dns(true) .tcp_nodelay(true) .timeout(Duration::from_secs(60)) .build() .unwrap_or_default(), } } pub fn run_script( &self, scripts: Vec<ScriptScope>, context: Context, ) -> Promise<anyhow::Result<Context>> { self.script_runtime.run_block(scripts, context) } pub fn connect_websocket_with_script( &self, run_request_info: RunRequestInfo, ) -> WebSocketSession { WebSocketSender::connect(run_request_info.request) } pub async fn send_rest_with_script_async( run_request_info: RunRequestInfo, client: Client, ) -> Result<TestRunResult, TestRunError> { info!("start send_rest_with_script_async:{:?}",run_request_info); let shared_map = run_request_info.shared_map; let mut logger = Logger::default(); let mut default_context = Context { scope_name: "".to_string(), request: run_request_info.request.clone(), envs: run_request_info.envs.clone(), testcase: run_request_info.testcase.clone(), shared_map, ..Default::default() }; default_context .logger .add_info("System".to_string(), format!("Testcase: \n{}",serde_yaml::to_string(&default_context.testcase).unwrap())); default_context .logger .add_info("System".to_string(), format!("Envs: \n{}",serde_yaml::to_string(&default_context.envs).unwrap())); let mut pre_request_context_result = Ok(default_context.clone()); if run_request_info.pre_request_scripts.len() > 0 { default_context .logger .add_info("System".to_string(), "Run pre-request-scripts".to_string()); pre_request_context_result = ScriptRuntime::run_async(run_request_info.pre_request_scripts, default_context) .await; } match pre_request_context_result { Ok(pre_request_context) => { for log in pre_request_context.logger.logs.iter() { logger.logs.push(log.clone()); } logger.add_info("System".to_string(),format!("Envs: \n{}",serde_yaml::to_string(&pre_request_context.envs).unwrap())); let build_request = RestSender::build_request( pre_request_context.request.clone(), pre_request_context.envs.clone(), ); logger.add_info( "Fetch".to_string(), format!("start fetch request: \n{}", serde_yaml::to_string(&build_request).unwrap()), ); match RestSender::reqwest_async_send(build_request, client).await { Ok((after_request, response)) => { let mut after_response = response; logger.add_info( "Fetch".to_string(), "get response".to_string(), ); after_response.logger = logger; let mut test_result: TestResult = Default::default(); let mut test_context = pre_request_context.clone(); test_context.response = JsResponse::from_data_response(after_response.clone()); test_context.logger = Logger::default(); if run_request_info.test_scripts.len() > 0 { after_response .logger .add_info("System".to_string(), "Run Test-script".to_string()); pre_request_context_result = ScriptRuntime::run_async( run_request_info.test_scripts, test_context, ) .await; match pre_request_context_result { Ok(test_context) => { for log in test_context.logger.logs.iter() { after_response.logger.logs.push(log.clone()); } test_result = test_context.test_result.clone(); } Err(e) => { if e.to_string().contains("TestSkip"){ test_result.status = TestStatus::SKIP; for test_info in test_result.test_info_list.iter_mut() { test_info.status = TestStatus::SKIP; } } else { return Err(TestRunError { request: after_request, response: Some(after_response), collection_path: run_request_info.collection_path.clone(), request_name: run_request_info.request_name, testcase: run_request_info.testcase.clone(), error: e.to_string(), }); } } } } Ok(TestRunResult { request: after_request, response: Some(after_response), test_result, collection_path: run_request_info.collection_path.clone(), request_name: run_request_info.request_name.clone(), testcase: run_request_info.testcase.clone(), }) } Err(e) => Err(TestRunError { request: run_request_info.request.clone(), response: None, collection_path: run_request_info.collection_path.clone(), request_name: run_request_info.request_name, testcase: run_request_info.testcase.clone(), error: e.to_string(), }), } } Err(e) => { if e.to_string().contains("TestSkip"){ let mut test_result = TestResult::default(); test_result.status = TestStatus::SKIP; Ok(TestRunResult { request: run_request_info.request.clone(), response: None, test_result, collection_path: run_request_info.collection_path.clone(), request_name: run_request_info.request_name.clone(), testcase: run_request_info.testcase.clone(), }) } else { Err(TestRunError { request: run_request_info.request.clone(), response: None, collection_path: run_request_info.collection_path.clone(), request_name: run_request_info.request_name, testcase: run_request_info.testcase.clone(), error: e.to_string(), }) } }, } } pub fn send_rest_with_script_promise( &self, mut run_request_info: RunRequestInfo, ) -> Promise<Result<TestRunResult, TestRunError>> { let client = self.client.clone(); run_request_info.shared_map = SharedMap::default(); Promise::spawn_thread("send_with_script", move || { let runtime = tokio::runtime::Builder::new_current_thread() .enable_all() .build() .unwrap(); runtime.block_on(Self::send_rest_with_script_async( run_request_info, client )) }) } pub fn run_test_group_promise( &self, fast:bool, envs: BTreeMap<String, EnvironmentItemValue>, script_tree: ScriptTree, test_group_run_result: Arc<RwLock<TestGroupRunResults>>, collection_path: String, parent_testcase: Option<Testcase>, folder: Rc<RefCell<CollectionFolder>>, ) -> Promise<()> { let client = self.client.clone(); let folder_only_read = CollectionFolderOnlyRead::from(folder); let run_request_infos = Self::get_test_group_jobs(envs,script_tree,collection_path,parent_testcase,folder_only_read); Promise::spawn_thread("send_with_script", move || { Self::run_test_group_jobs(client,run_request_infos,test_group_run_result.clone(),fast); }) } pub fn run_test_record_promise( &self, envs: BTreeMap<String, EnvironmentItemValue>, script_tree: ScriptTree, test_group_run_result: Arc<RwLock<TestGroupRunResults>>, collection_path: String, parent_testcase: Option<Testcase>, record: Record, ) -> Promise<()> { let client = self.client.clone(); Promise::spawn_thread("send_with_script", move || { let runtime = tokio::runtime::Builder::new_current_thread() .enable_all() .build() .unwrap(); runtime.block_on(async { Self::run_test_record_async( client.clone(), envs.clone(), script_tree.clone(), parent_testcase, test_group_run_result.clone(), collection_path.clone(), record.clone(), ) .await }) }) } async fn run_test_record_async( client: Client, envs: BTreeMap<String, EnvironmentItemValue>, script_tree: ScriptTree, testcase: Option<Testcase>, test_group_run_result: Arc<RwLock<TestGroupRunResults>>, collection_path: String, record: Record, ) { let mut run_request_infos = vec![]; // 每个文件夹的shared_map是隔离的 let shared_map = SharedMap::default(); let mut record_testcases = record.testcase().clone(); if record_testcases.is_empty() { let mut testcase = Testcase::default(); record_testcases.insert(testcase.name.clone(), testcase); } for (_, request_testcase) in record_testcases.iter() { let mut record_pre_request_parent_script_scopes = script_tree .get_pre_request_parent_script_scope(collection_path.clone()) .clone(); let scope = format!("{}/{}", collection_path.clone(), record.name()); if record.pre_request_script() != "" { record_pre_request_parent_script_scopes.push(ScriptScope { scope: scope.clone(), script: record.pre_request_script(), }); } let mut record_test_parent_script_scopes = script_tree .get_test_parent_script_scope(collection_path.clone()) .clone(); if record.test_script() != "" { record_test_parent_script_scopes.push(ScriptScope { scope: scope.clone(), script: record.test_script(), }); } let mut new_request_testcase = request_testcase.clone(); testcase.clone().map(|t| { new_request_testcase.merge(record.name(), &t); }); let run_request_info = RunRequestInfo { shared_map:shared_map.clone(), collection_path: Some(collection_path.clone()), request_name: record.name(), request: record.must_get_rest().request.clone(), envs: envs.clone(), pre_request_scripts: record_pre_request_parent_script_scopes, test_scripts: record_test_parent_script_scopes, testcase: new_request_testcase.clone(), }; run_request_infos.push(run_request_info) } let mut jobs = vec![]; for run_request_info in run_request_infos.iter() { let _client = client.clone(); let _run_request_info = run_request_info.clone(); let _shared_map = shared_map.clone(); jobs.push(Self::send_rest_with_script_async( _run_request_info, _client )); } let results = join_all(jobs).await; test_group_run_result.write().unwrap().add_results(results); } pub fn run_test_group_jobs(client: Client,run_request_infos:Vec<RunRequestInfo>, test_group_run_result: Arc<RwLock<TestGroupRunResults>>,fast:bool){ let pool = ThreadPoolBuilder::new().num_threads(20).build().unwrap(); if fast { pool.scope(|scope| { for run_request_info in run_request_infos { let _client = client.clone(); let _test_group_run_result = test_group_run_result.clone(); Self::run_one_job(_client, _test_group_run_result, scope, run_request_info.clone()); } }); }else{ let mut groups:HashMap<String,Vec<RunRequestInfo>> = HashMap::new(); run_request_infos.iter().for_each(|r|{ let key = r.testcase.parent_path.join("/"); if !groups.contains_key(key.as_str()){ groups.insert(key.clone(),vec![]); } groups.get_mut(key.as_str()).unwrap().push(r.clone()); }); groups.iter().for_each(|(_,rs)|{ pool.scope(|scope| { for run_request_info in rs { let _client = client.clone(); let _test_group_run_result = test_group_run_result.clone(); Self::run_one_job(_client, _test_group_run_result, scope, run_request_info.clone()); } }); }) } info!("all test_jobs finish"); } fn run_one_job(client: Client, test_group_run_result: Arc<RwLock<TestGroupRunResults>>, scope: &Scope, run_request_info: RunRequestInfo) { if test_group_run_result.read().unwrap().stop_flag{ return; } scope.spawn(move |_| { let runtime = tokio::runtime::Builder::new_current_thread() .enable_all() .build() .unwrap(); let mut test_result =TestResult::default(); test_result.status = TestStatus::RUNNING; test_group_run_result.write().unwrap().add_result(Ok(TestRunResult{ request: run_request_info.request.clone(), response: None, test_result, collection_path: run_request_info.collection_path.clone(), request_name: run_request_info.request_name.clone(), testcase: run_request_info.testcase.clone(), })); runtime.block_on(async { let result = Self::send_rest_with_script_async( run_request_info.clone(), client ).await; info!("job finish:{:?}",result); test_group_run_result.write().unwrap().add_result(result); }); }) } pub fn get_test_group_jobs( envs: BTreeMap<String, EnvironmentItemValue>, script_tree: ScriptTree, collection_path: String, parent_testcase: Option<Testcase>, folder: CollectionFolderOnlyRead, )->Vec<RunRequestInfo>{ let mut run_request_infos =vec![]; let mut testcases = folder.testcases.clone(); if testcases.is_empty() { let testcase = Testcase::default(); testcases.insert(testcase.name.clone(), testcase); } for (_, testcase) in testcases.iter() { let mut root_testcase = testcase.clone(); if let Some(parent) = &parent_testcase { root_testcase.merge(folder.name.clone(), parent); } else { root_testcase.entry_name = folder.name.clone(); } let mut result = Self::_get_test_group_jobs( envs.clone(), script_tree.clone(), root_testcase, collection_path.clone(), folder.clone(), ); run_request_infos.append(&mut result); } return run_request_infos; } fn _get_test_group_jobs( envs: BTreeMap<String, EnvironmentItemValue>, script_tree: ScriptTree, testcase: Testcase, collection_path: String, folder: CollectionFolderOnlyRead, )->Vec<RunRequestInfo> { let mut run_request_infos = vec![]; // 每个文件夹的shared_map是隔离的 let shared_map = SharedMap::default(); for (name, child_folder) in folder.folders.iter() { let mut child_testcases = child_folder.testcases.clone(); if child_testcases.is_empty() { let mut testcase = Testcase::default(); child_testcases.insert(testcase.name.clone(), testcase); } for (name, child_testcase) in child_testcases.iter() { let mut merge_testcase = child_testcase.clone(); merge_testcase.merge(child_folder.name.clone(), &testcase); let mut result = Self::_get_test_group_jobs( envs.clone(), script_tree.clone(), merge_testcase, collection_path.clone() + "/" + name, child_folder.clone(), ); run_request_infos.append(&mut result); } } for (name, record) in folder.requests.iter() { let mut record_testcases = record.testcase().clone(); if record_testcases.is_empty() { let mut testcase = Testcase::default(); record_testcases.insert(testcase.name.clone(), testcase); } for (_, request_testcase) in record_testcases.iter() { let mut record_pre_request_parent_script_scopes = script_tree .get_pre_request_parent_script_scope(folder.get_path()) .clone(); let scope = format!("{}/{}", collection_path.clone(), name); if record.pre_request_script() != "" { record_pre_request_parent_script_scopes.push(ScriptScope { scope: scope.clone(), script: record.pre_request_script(), }); } let mut record_test_parent_script_scopes = script_tree .get_test_parent_script_scope(folder.get_path()) .clone(); if record.test_script() != "" { record_test_parent_script_scopes.push(ScriptScope { scope: scope.clone(), script: record.test_script(), }); } let mut new_request_testcase = request_testcase.clone(); new_request_testcase.merge(record.name(), &testcase); let run_request_info = RunRequestInfo { shared_map:shared_map.clone(), collection_path: Some(collection_path.clone()), request_name: record.name(), request: record.must_get_rest().request.clone(), envs: envs.clone(), pre_request_scripts: record_pre_request_parent_script_scopes, test_scripts: record_test_parent_script_scopes, testcase: new_request_testcase.clone(), }; run_request_infos.push(run_request_info) } } return run_request_infos } } #[derive(Default, Clone)] pub struct TestGroupRunResults { pub stop_flag:bool, pub results: HashMap<String, Result<TestRunResult, TestRunError>>, } impl TestGroupRunResults { pub fn stop(&mut self){ self.stop_flag = true; } pub fn restart(&mut self){ self.stop_flag = false; } pub fn add_result(&mut self, result: Result<TestRunResult, TestRunError>) { match &result { Ok(r) => { let key = r.testcase.get_testcase_path().join("/"); self.results.insert(key, result.clone()); } Err(e) => { let key = e.testcase.get_testcase_path().join("/"); self.results.insert(key, result.clone()); } }; } pub fn add_results(&mut self, results: Vec<Result<TestRunResult, TestRunError>>) { for result in results.iter() { self.add_result(result.clone()); } } pub fn find(&self, testcase_path: Vec<String>) -> Option<Result<TestRunResult, TestRunError>> { let key = testcase_path.join("/"); return self.results.get(key.as_str()).cloned(); } pub fn get_test_count(&self,status:TestStatus)->usize{ self.results.iter() .filter(|(_,r)|{ return match r { Ok(t) => { t.test_result.status == status } Err(_) => { false } } }).count() } pub fn export(&self,path:PathBuf){ info!("{}",self.results.len()); let report_template = include_str!("../../report/template"); let report = HtmlReport{ test_pass: self.get_test_count(TestStatus::PASS), test_skip: self.get_test_count(TestStatus::SKIP), total_time: "".to_string(), test_all: self.results.len(), begin_time: Local::now().format("%Y-%m-%d %H:%M:%S").to_string(), test_result: self.results.iter().map(|(name,r)|{ HtmlReportTestResult{ log: match r { Ok(t) => { t.test_result.test_info_list.iter().map(|i|{ serde_json::to_string(i).unwrap() }).collect() } Err(e) => { vec![e.error.clone()] } }, method_name: match r { Ok(t) => { t.testcase.name.clone() } Err(e) => { e.testcase.name.clone() } }, description: name.clone(), class_name: match r { Ok(t) => { t.testcase.parent_path.join("/") } Err(e) => { e.testcase.parent_path.join("/") } }, spend_time: match r { Ok(t) => { match &t.response { None => {"-".to_string()} Some(r) => {format!("{}ms",r.elapsed_time)} } } Err(e) => { match &e.response { None => {"-".to_string()} Some(r) => {format!("{}ms",r.elapsed_time)} } } } , status:match r { Ok(t) => { t.test_result.status.to_string() } Err(e) => { TestStatus::FAIL.to_string() } } , } }).collect(), test_fail: self.get_test_count(TestStatus::FAIL), test_name: "Test".to_string(), }; let json = serde_json::to_string(&report).unwrap(); let html = report_template.replace("${resultData}",&json); let mut file = File::create(path).unwrap(); file.write_all(html.as_bytes()).unwrap(); } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr_core/src/script/mod.rs
crates/netpurr_core/src/script/mod.rs
use std::cell::RefCell; use std::cmp::max; use std::collections::{BTreeMap, HashMap}; use std::error; use std::fmt::{Display, Formatter}; use std::ops::Deref; use std::path::Path; use std::rc::Rc; use std::str::FromStr; use std::sync::{Arc, RwLock}; use std::time::Duration; use anyhow::Error; use deno_core::{ExtensionBuilder, FsModuleLoader, ModuleCodeString, Op, op2, OpState}; use deno_core::{JsRuntime, PollEventLoopOptions}; use deno_core::url::Url; use jieba_rs::{Jieba, Keyword, KeywordExtract, TextRank, TfIdf}; use poll_promise::Promise; use reqwest::{Client, Method}; use reqwest::header::{HeaderMap, HeaderName, HeaderValue}; use serde::{Deserialize, Serialize}; use tokio::time::sleep; use crate::data::collections::Testcase; use crate::data::environment::{EnvironmentItemValue, EnvironmentValueType}; use crate::data::http; use crate::data::http::{Header, LockWith, QueryParam, Request}; use crate::data::logger::Logger; use crate::data::test::TestResult; #[derive(Default, Clone)] pub struct ScriptRuntime {} #[derive(Clone, Default)] pub struct Context { pub scope_name: String, pub request: Request, pub response: JsResponse, pub envs: BTreeMap<String, EnvironmentItemValue>, pub testcase: Testcase, pub shared_map: SharedMap, pub logger: Logger, pub test_result: TestResult, } #[derive(Default, Clone,Debug)] pub struct SharedMap { map: Arc<RwLock<BTreeMap<String, String>>>, } impl Deref for SharedMap { type Target = Arc<RwLock<BTreeMap<String, String>>>; fn deref(&self) -> &Self::Target { &self.map } } #[derive(Default, Clone,Debug)] pub struct ScriptScope { pub script: String, pub scope: String, } #[derive(Default, Clone)] pub struct ScriptTree { pub pre_request_parent_script_scopes: BTreeMap<String, Vec<ScriptScope>>, pub test_parent_script_scopes: BTreeMap<String, Vec<ScriptScope>>, } impl ScriptRuntime { pub fn run_block( &self, scripts: Vec<ScriptScope>, context: Context, ) -> Promise<anyhow::Result<Context>> { Promise::spawn_thread("script", || { let runtime = tokio::runtime::Builder::new_current_thread() .enable_all() .build() .unwrap(); runtime.block_on(ScriptRuntime::run_async(scripts, context)) }) } pub async fn run_async( scripts: Vec<ScriptScope>, mut context: Context, ) -> anyhow::Result<Context> { for script_scope in scripts.iter() { context.scope_name = script_scope.scope.clone(); let step_context = ScriptRuntime::run_js(script_scope.script.clone(), context.clone()).await?; context.envs = step_context.envs.clone(); context.request = step_context.request.clone(); context.logger = step_context.logger.clone(); context.shared_map = step_context.shared_map.clone(); context.test_result = step_context.test_result.clone(); } Ok(context) } fn build_js_runtime() -> JsRuntime { let runjs_extension = ExtensionBuilder::default() .ops(vec![ op_set_env::DECL, op_get_env::DECL, op_add_params::DECL, op_add_header::DECL, op_log::DECL, op_error::DECL, op_warn::DECL, op_http_fetch::DECL, op_get_shared::DECL, op_set_shared::DECL, op_wait_shared::DECL, op_response::DECL, op_open_test::DECL, op_close_test::DECL, op_append_assert::DECL, op_sleep::DECL, op_get_testcase::DECL, op_test_skip::DECL, op_equal::DECL, op_nlp_keywords::DECL, op_nlp_tags::DECL, op_nlp_tag_filter::DECL, op_nlp_similarity::DECL ]) .build(); return JsRuntime::new(deno_core::RuntimeOptions { module_loader: Some(Rc::new(FsModuleLoader)), extensions: vec![runjs_extension], ..Default::default() }); } async fn run_js(js: String, context: Context) -> anyhow::Result<Context> { let mut js_runtime = Self::build_js_runtime(); js_runtime.op_state().borrow_mut().put(context); let runtime_init_code = include_str!("resource/runtime.js"); js_runtime .execute_script_static("[runjs:runtime.js]", runtime_init_code) .unwrap(); let temp = Url::from_file_path(Path::new("/netpurr/pre-request-script.js")).unwrap(); let mod_id = js_runtime .load_main_module(&temp, Some(ModuleCodeString::from(js))) .await?; let result = js_runtime.mod_evaluate(mod_id); js_runtime .run_event_loop(PollEventLoopOptions::default()) .await?; result.await?; let op_state = js_runtime.op_state(); let new_context = op_state .borrow() .try_borrow::<Context>() .ok_or(anyhow::Error::msg("get context error"))? .clone(); Ok(new_context) } } #[op2(fast)] fn op_set_shared(state: &mut OpState, #[string] key: String, #[string] value: String) { let context = state.try_borrow_mut::<Context>(); match context { None => {} Some(c) => { c.shared_map .write() .unwrap() .insert(key.clone(), value.clone()); c.logger.add_info( c.scope_name.clone(), format!("set shared: `{}` as `{}`", key, value), ); } } } #[op2(async)] async fn op_sleep(#[bigint] time: u64) -> anyhow::Result<()> { sleep(Duration::from_millis(time)).await; Ok(()) } #[op2(async)] #[string] async fn op_wait_shared( state: Rc<RefCell<OpState>>, #[string] key: String, ) -> anyhow::Result<String> { let mut _state = state.borrow_mut(); let mut count = 0; let context = _state.try_borrow_mut::<Context>(); match context { None => { return Err(Error::msg("context is none")); } Some(c) => loop { let value = c.shared_map.read().unwrap().get(key.as_str()).cloned(); match value { None => { sleep(Duration::from_millis(100)).await; count = count + 1; if count > 100 { c.logger.add_error( c.scope_name.clone(), format!("get shared `{}` failed", key), ); return Err(Error::msg(format!("get shared value:{} time out", key))); } } Some(v) => { c.logger.add_info( c.scope_name.clone(), format!("get shared: `{}` as `{}`", key, v), ); return Ok(v.clone()); } } }, } } #[op2] #[string] fn op_get_shared(state: &mut OpState, #[string] key: String) -> String { let context = state.try_borrow_mut::<Context>(); match context { None => "".to_string(), Some(c) => match c.shared_map.read().unwrap().get(key.as_str()).cloned() { None => { c.logger .add_error(c.scope_name.clone(), format!("get shared `{}` failed", key)); "\"\"".to_string() } Some(v) => { c.logger.add_info( c.scope_name.clone(), format!("get shared: `{}` as `{}`", key, v), ); v.clone() } }, } } #[op2] #[string] fn op_get_testcase(state: &mut OpState) -> anyhow::Result<String> { let context = state.try_borrow_mut::<Context>(); match context { None => Err(Error::msg("context is none")), Some(c) => { let json = serde_json::to_string(&c.testcase.value).unwrap(); Ok(json) } } } #[op2(fast)] fn op_set_env(state: &mut OpState, #[string] key: String, #[string] value: String) { let context = state.try_borrow_mut::<Context>(); match context { None => {} Some(c) => { c.envs.insert( key.clone(), EnvironmentItemValue { value: value.clone(), scope: "Script".to_string(), value_type: EnvironmentValueType::String, }, ); c.logger.add_info( c.scope_name.clone(), format!("set env: `{}` as `{}`", key, value), ); } } } #[op2] #[string] fn op_get_env(state: &mut OpState, #[string] key: String) -> String { let context = state.try_borrow_mut::<Context>(); match context { None => "".to_string(), Some(c) => match c.envs.get(key.as_str()).cloned() { None => { c.logger .add_error(c.scope_name.clone(), format!("get env `{}` failed", key)); "".to_string() } Some(v) => v.value.clone(), }, } } #[op2(fast)] fn op_add_header(state: &mut OpState, #[string] key: String, #[string] value: String) { let context = state.try_borrow_mut::<Context>(); match context { None => {} Some(c) => { c.request.headers.push(Header { key: key.clone(), value: value.clone(), enable: true, lock_with: LockWith::LockWithScript, desc: "build with script".to_string(), ..Default::default() }); c.logger.add_info( c.scope_name.clone(), format!("add header: `{}` as `{}`", key, value), ); } } } #[op2(fast)] fn op_add_params(state: &mut OpState, #[string] key: String, #[string] value: String) { let context = state.try_borrow_mut::<Context>(); match context { None => {} Some(c) => { c.request.params.push(QueryParam { key: key.clone(), value: value.clone(), enable: true, lock_with: LockWith::LockWithScript, desc: "build with script".to_string(), ..Default::default() }); c.logger.add_info( c.scope_name.clone(), format!("add params: `{}` as `{}`", key, value), ); } } } #[op2(fast)] fn op_log(state: &mut OpState, #[string] msg: String) { let context = state.try_borrow_mut::<Context>(); match context { None => {} Some(c) => c.logger.add_info(c.scope_name.clone(), msg), } } #[op2(fast)] fn op_error(state: &mut OpState, #[string] msg: String) { let context = state.try_borrow_mut::<Context>(); match context { None => {} Some(c) => c.logger.add_error(c.scope_name.clone(), msg), } } #[op2(fast)] fn op_warn(state: &mut OpState, #[string] msg: String) { let context = state.try_borrow_mut::<Context>(); match context { None => {} Some(c) => c.logger.add_warn(c.scope_name.clone(), msg), } } #[derive(Default, Serialize, Deserialize, Clone)] #[serde(default)] pub struct JsRequest { method: String, url: String, headers: Vec<JsHeader>, body: String, } #[derive(Default, Serialize, Deserialize, Clone)] pub struct JsHeader { name: String, value: String, } #[derive(Default, Serialize, Deserialize, Clone)] pub struct JsResponse { status: u16, headers: Vec<JsHeader>, text: String, } impl JsResponse { pub fn from_data_response(response: http::Response) -> Self { Self { status: response.status, headers: response .headers .iter() .map(|h| JsHeader { name: h.key.clone(), value: h.value.clone(), }) .collect(), text: String::from_utf8(response.body.to_vec()).unwrap_or("".to_string()), } } } #[op2(async)] #[serde] async fn op_http_fetch(#[serde] request: JsRequest) -> anyhow::Result<JsResponse> { let method_enum = Method::from_str(request.method.to_uppercase().as_str())?; let mut request_headers = HeaderMap::new(); for header in request.headers.iter() { request_headers.insert( HeaderName::from_str(header.value.as_str())?, HeaderValue::from_str(header.value.as_str())?, ); } let response = Client::builder() .build()? .request(method_enum, request.url) .headers(request_headers) .body(request.body) .send() .await?; let status = response.status().as_u16(); let mut response_headers: Vec<JsHeader> = vec![]; for (header_name, header_value) in response.headers().iter() { response_headers.push(JsHeader { name: header_name.to_string(), value: header_value.to_str()?.to_string(), }); } let text = response.text().await?.clone(); let result = JsResponse { status, text, headers: response_headers, }; Ok(result) } #[op2] #[serde] fn op_response(state: &mut OpState) -> JsResponse { let context = state.try_borrow_mut::<Context>(); match context { None => JsResponse::default(), Some(c) => c.response.clone(), } } #[op2(fast)] fn op_open_test(state: &mut OpState, #[string] test_name: String) { let context = state.try_borrow_mut::<Context>(); match context { None => {} Some(c) => c.test_result.open(test_name), } } #[op2(fast)] fn op_close_test(state: &mut OpState, #[string] test_name: String) { let context = state.try_borrow_mut::<Context>(); match context { None => {} Some(c) => c.test_result.close(test_name), } } #[op2(fast)] fn op_append_assert(state: &mut OpState, result: bool, #[string] msg: String) { let context = state.try_borrow_mut::<Context>(); match context { None => {} Some(c) => c.test_result.append(result, msg), } } #[op2] fn op_equal(#[serde] a:serde_json::Value, #[serde] b:serde_json::Value) -> bool { return a==b; } #[op2(fast)] fn op_test_skip()-> anyhow::Result<()> { Err(Error::from(SkipError {})) } #[op2] #[serde] fn op_nlp_keywords(#[string] source:String, #[bigint] k:usize) -> Vec<String> { _nlp_keywords(source,k) } fn _nlp_keywords(source:String, k:usize) -> Vec<String> { let jieba = Jieba::new(); let keyword_extractor = TfIdf::default(); keyword_extractor.extract_keywords( &jieba, source.as_str(), k, vec![String::from("ns"),String::from("nz"), String::from("n"), String::from("vn"), String::from("v"),String::from("m")], ).iter().map(|k|{ k.keyword.clone() }).collect() } #[op2] #[serde] fn op_nlp_tags(#[string] source:String)->Vec<JSTag>{ let jieba = Jieba::new(); jieba.tag(source.as_str(), true).iter().map(|t|{ JSTag{ word:t.word.to_string(), tag:t.tag.to_string() } }).collect() } #[op2] #[serde] fn op_nlp_tag_filter(#[string] source:String,#[serde] tags:Vec<String>)->Vec<String>{ _nlp_tag_filter(source,tags) } fn _nlp_tag_filter(source:String,tags:Vec<String>)->Vec<String>{ let jieba = Jieba::new(); jieba.tag(source.as_str(), true).iter().map(|t|{ JSTag{ word:t.word.to_string(), tag:t.tag.to_string() } }).filter(|t|{ tags.contains(&t.tag) }).map(|t|{ t.word }).collect() } #[op2(fast)] fn op_nlp_similarity(#[string]word1:String, #[string]word2:String)->f32{ let word1 = _nlp_keywords(word1,10); let word2 = _nlp_keywords(word2,10); _op_nlp_similarity(word1,word2) } fn _op_nlp_similarity(words1:Vec<String>, words2:Vec<String>)->f32{ // 建立倒排索引 let mut index = HashMap::new(); for word in words1.iter() { index.entry(word).or_insert(vec![]).push(1); } for word in words2.iter() { index.entry(word).or_insert(vec![]).push(1); } // 统计共有关键词数量 let mut count = 0; for (word, docs) in index { if docs.len()>=2 { count += 1; } } (count as f32) / (words1.len().min(words2.len()) as f32) } #[derive(Debug, Clone, PartialEq, Eq, Hash,Serialize,Deserialize)] pub struct JSTag { /// Word pub word: String, /// Word tag pub tag: String, } #[derive(Debug)] pub struct SkipError { } impl Display for SkipError { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "{}","TestSkip") } } impl error::Error for SkipError {} impl ScriptTree { pub fn add_pre_request_parent_script_scope(&mut self, path: String, scopes: Vec<ScriptScope>) { self.pre_request_parent_script_scopes.insert(path, scopes); } pub fn add_test_parent_script_scope(&mut self, path: String, scopes: Vec<ScriptScope>) { self.test_parent_script_scopes.insert(path, scopes); } pub fn get_pre_request_parent_script_scope(&self, path: String) -> Vec<ScriptScope> { self.pre_request_parent_script_scopes .get(path.as_str()) .cloned() .unwrap_or_default() } pub fn get_test_parent_script_scope(&self, path: String) -> Vec<ScriptScope> { self.test_parent_script_scopes .get(path.as_str()) .cloned() .unwrap_or_default() } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr_core/src/data/test.rs
crates/netpurr_core/src/data/test.rs
use serde::{Deserialize, Serialize}; use strum_macros::Display; #[derive(Default, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)] pub struct TestResult { pub status: TestStatus, open_test: Option<String>, append: Vec<TestAssertResult>, pub test_info_list: Vec<TestInfo>, } #[derive(Default, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)] pub struct TestInfo { pub name: String, pub results: Vec<TestAssertResult>, pub status: TestStatus, } #[derive(Default, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)] pub struct TestAssertResult { pub assert_result: TestStatus, pub msg: String, } impl TestResult { pub fn open(&mut self, name: String) { self.open_test = Some(name); } pub fn close(&mut self, name: String) { self.open_test = None; let mut status = TestStatus::PASS; for tar in self.append.iter() { if tar.assert_result != TestStatus::PASS { status = TestStatus::FAIL; break; } } self.test_info_list.push(TestInfo { name, results: self.append.clone(), status, }); self.append.clear(); self.status = TestStatus::PASS; for ti in self.test_info_list.iter() { if ti.status == TestStatus::FAIL { self.status = TestStatus::FAIL; break; } } } pub fn append(&mut self, assert_result: bool, msg: String) { if assert_result { self.append.push(TestAssertResult { assert_result: TestStatus::PASS, msg, }); } else { self.append.push(TestAssertResult { assert_result: TestStatus::FAIL, msg, }); } } } #[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize, Display)] pub enum TestStatus { None, WAIT, RUNNING, PASS, FAIL, SKIP } impl Default for TestStatus { fn default() -> Self { TestStatus::None } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr_core/src/data/environment.rs
crates/netpurr_core/src/data/environment.rs
use std::collections::BTreeMap; use std::io::Error; use std::path::Path; use serde::{Deserialize, Serialize}; use strum::IntoEnumIterator; use strum_macros::Display; use crate::data::collections::Collection; use crate::data::environment_function::EnvFunction; use crate::persistence::{ get_persistence_path, Persistence, PersistenceItem, }; #[derive(Default, Clone, PartialEq, Eq, Debug)] pub struct Environment { persistence: Persistence, data: BTreeMap<String, EnvironmentConfig>, status: EnvironmentStatus, } impl Environment { pub fn select(&self) -> Option<String> { self.status.select.clone() } pub fn set_select(&mut self, select: Option<String>) { self.status.select = select; self.persistence.save( Path::new("environment").to_path_buf(), "status".to_string(), &self.status, ); } pub fn get_variable_hash_map( &self, collection: Option<Collection>, ) -> BTreeMap<String, EnvironmentItemValue> { self.status.select.clone().map_or_else( || { let mut result = BTreeMap::default(); self.get(ENVIRONMENT_GLOBALS.to_string()).map(|e| { for et in e.items.iter().filter(|i| i.enable) { result.insert( et.key.clone(), EnvironmentItemValue { value: et.value.clone(), scope: ENVIRONMENT_GLOBALS.to_string(), value_type: et.value_type.clone(), }, ); } }); collection.clone().map(|c| { for et in c.envs.items.iter().filter(|item| item.enable) { result.insert( et.key.clone(), EnvironmentItemValue { value: et.value.clone(), scope: c.folder.borrow().name.clone() + " Collection", value_type: et.value_type.clone(), }, ); } }); for ef in EnvFunction::iter() { result.insert( "$".to_string() + ef.to_string().as_str(), EnvironmentItemValue { value: ef.to_string(), scope: "Global".to_string(), value_type: EnvironmentValueType::Function, }, ); } result }, |s| { let mut result = BTreeMap::default(); self.get(ENVIRONMENT_GLOBALS.to_string()).map(|e| { for et in e.items.iter().filter(|i| i.enable) { result.insert( et.key.clone(), EnvironmentItemValue { value: et.value.clone(), scope: ENVIRONMENT_GLOBALS.to_string(), value_type: et.value_type.clone(), }, ); } }); self.get(s.clone()).map(|e| { for et in e.items.iter().filter(|i| i.enable) { result.insert( et.key.clone(), EnvironmentItemValue { value: et.value.clone(), scope: s.clone(), value_type: et.value_type.clone(), }, ); } }); collection.clone().map(|c| { for et in c.envs.items.iter().filter(|item| item.enable) { result.insert( et.key.clone(), EnvironmentItemValue { value: et.value.clone(), scope: c.folder.borrow().name.clone() + " Collection", value_type: et.value_type.clone(), }, ); } }); for ef in EnvFunction::iter() { result.insert( "$".to_string() + ef.to_string().as_str(), EnvironmentItemValue { value: ef.to_string(), scope: "Global".to_string(), value_type: EnvironmentValueType::Function, }, ); } result }, ) } pub fn load_all(&mut self, workspace: String) -> Result<(), Error> { self.persistence.set_workspace(workspace); self.data.clear(); self.status = EnvironmentStatus::default(); for key in self .persistence .load_list(Path::new("environment/data").to_path_buf()) .iter() { if let Some(key_os) = key.file_name() { if let Some(key_name) = key_os.to_str() { if let Some(environment_config) = self.persistence.load(key.clone()) { self.data.insert( Persistence::decode_with_file_name(key_name.to_string()), environment_config, ); } } } } let status = self .persistence .load(Path::new(get_persistence_path("environment/status").as_str()).to_path_buf()); status.map(|s| { self.status = s; }); Ok(()) } pub fn get(&self, key: String) -> Option<EnvironmentConfig> { self.data.get(key.as_str()).cloned() } pub fn get_data(&self) -> BTreeMap<String, EnvironmentConfig> { self.data.clone() } pub fn insert(&mut self, key: String, value: EnvironmentConfig) { self.data.insert(key.clone(), value.clone()); self.persistence.save( Path::new("environment/data").to_path_buf(), key.clone(), &value, ); } pub fn remove(&mut self, key: String) { self.data.remove(key.as_str()); self.persistence .remove(Path::new("environment").to_path_buf(), key.clone()); } } #[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize, Display)] pub enum EnvironmentValueType { String, Function, } impl Default for EnvironmentValueType { fn default() -> Self { EnvironmentValueType::String } } #[derive(Default, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)] #[serde(default)] pub struct EnvironmentStatus { select: Option<String>, } pub const ENVIRONMENT_GLOBALS: &str = "__Globals__"; #[derive(Default, Clone,Deserialize,Serialize,Debug)] pub struct EnvironmentItemValue { pub value: String, pub scope: String, pub value_type: EnvironmentValueType, } #[derive(Default, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)] #[serde(default)] pub struct EnvironmentConfig { pub items: Vec<EnvironmentItem>, } #[derive(Default, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)] #[serde(default)] pub struct EnvironmentItem { pub enable: bool, pub key: String, pub value: String, pub desc: String, pub value_type: EnvironmentValueType, }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr_core/src/data/http.rs
crates/netpurr_core/src/data/http.rs
use std::collections::BTreeMap; use std::path::Path; use std::str::FromStr; use std::sync::Arc; use base64::Engine; use base64::engine::general_purpose; use reqwest::header::HeaderMap; use serde::{Deserialize, Serialize}; use strum_macros::{Display, EnumIter, EnumString}; use tokio_tungstenite::tungstenite::client::IntoClientRequest; use tokio_tungstenite::tungstenite::Error; use tokio_tungstenite::tungstenite::error::UrlError; use tokio_tungstenite::tungstenite::handshake::client::generate_key; use tokio_tungstenite::tungstenite::http::Uri; use crate::data::auth::Auth; use crate::data::collections::Testcase; use crate::data::environment::EnvironmentItemValue; use crate::data::logger::Logger; #[derive(Default, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)] #[serde(default)] pub struct HttpRecord { pub name: String, pub desc: String, pub request: Request, #[serde(skip)] pub response: Response, pub status: ResponseStatus, pub pre_request_script: String, pub test_script: String, pub testcases: BTreeMap<String, Testcase>, pub operation_id: Option<String>, } impl HttpRecord { pub fn pending(&mut self) { self.status = ResponseStatus::Pending; } pub fn ready(&mut self) { self.status = ResponseStatus::Ready; } pub fn none(&mut self) { self.status = ResponseStatus::None; } pub fn error(&mut self) { self.status = ResponseStatus::Error; } pub fn compute_signature(&self) -> String { format!( "Request:[{}] TestScript:[{}] PreRequestScript:[{}]", self.request.compute_signature(), self.test_script.clone(), self.pre_request_script.clone() ) } } #[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)] pub enum ResponseStatus { None, Pending, Ready, Error, } impl Default for ResponseStatus { fn default() -> Self { ResponseStatus::None } } #[derive(Default, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)] #[serde(default)] pub struct Request { pub method: Method, pub schema: RequestSchema, pub raw_url: String, pub base_url: String, pub path_variables: Vec<PathVariables>, pub params: Vec<QueryParam>, pub headers: Vec<Header>, pub body: HttpBody, pub auth: Auth, } impl IntoClientRequest for Request { fn into_client_request( self, ) -> tokio_tungstenite::tungstenite::Result< tokio_tungstenite::tungstenite::handshake::client::Request, > { let uri = self.raw_url.as_str().parse::<Uri>()?; let authority = uri .authority() .ok_or(Error::Url(UrlError::NoHostName))? .as_str(); let host = authority .find('@') .map(|idx| authority.split_at(idx + 1).1) .unwrap_or_else(|| authority); if host.is_empty() { return Err(Error::Url(UrlError::EmptyHostName)); } let req = tokio_tungstenite::tungstenite::handshake::client::Request::builder() .method("GET") .header("Host", host) .header("Connection", "Upgrade") .header("Upgrade", "websocket") .header("Sec-WebSocket-Version", "13") .header("Sec-WebSocket-Key", generate_key()) .uri(uri) .body(())?; Ok(req) } } #[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize, Display, EnumString)] pub enum RequestSchema { HTTP, HTTPS, WS, WSS, } impl Default for RequestSchema { fn default() -> Self { RequestSchema::HTTP } } impl Request { pub fn fix_base_url(&mut self) { let base_list: Vec<&str> = self.base_url.split("://").collect(); if base_list.len() >= 2 { self.base_url = base_list[1].to_string(); } } pub fn sync_header(&mut self, envs: BTreeMap<String, EnvironmentItemValue>, parent_auth: Auth) { // build auto header self.auth .build_head(&mut self.headers, envs.clone(), parent_auth); match self.body.body_type { BodyType::NONE => {} BodyType::FROM_DATA => { self.set_request_content_type("multipart/form-data".to_string()); } BodyType::X_WWW_FROM_URLENCODED => { self.set_request_content_type("application/x-www-form-urlencoded".to_string()); } BodyType::RAW => match self.body.body_raw_type { BodyRawType::TEXT => self.set_request_content_type("text/plain".to_string()), BodyRawType::JSON => self.set_request_content_type("application/json".to_string()), BodyRawType::HTML => self.set_request_content_type("text/html".to_string()), BodyRawType::XML => self.set_request_content_type("application/xml".to_string()), BodyRawType::JavaScript => { self.set_request_content_type("application/javascript".to_string()) } }, BodyType::BINARY => { let path = Path::new(&self.body.body_file); let content_type = mime_guess::from_path(path); self.set_request_content_type(content_type.first_or_octet_stream().to_string()); } } } pub fn get_url_with_schema(&self) -> String { format!( "{}://{}", self.schema.to_string().to_lowercase(), self.base_url ) } pub fn get_path_variable_keys(&self) -> Vec<String> { let mut keys = vec![]; for url_part in self.base_url.split("/") { if url_part.starts_with(":") { keys.push(url_part[1..].to_string()); } } keys } pub fn build_raw_url(&mut self) { let mut params = vec![]; for q in self.params.iter().filter(|q| q.enable) { params.push(format!("{}={}", q.key, q.value)) } if !params.is_empty() { self.raw_url = format!("{}?{}", self.get_url_with_schema(), params.join("&")) } else { self.raw_url = self.get_url_with_schema(); } } pub fn parse_raw_url(&mut self) { let raw_url_split: Vec<&str> = self.raw_url.splitn(2, "://").collect(); let mut schema_str = "http"; let mut params_url = ""; if raw_url_split.len() >= 2 { schema_str = raw_url_split[0]; params_url = raw_url_split[1]; } else { params_url = self.raw_url.as_str(); } self.schema = RequestSchema::from_str(schema_str.to_uppercase().as_str()).unwrap_or_default(); let params_url_split: Vec<&str> = params_url.splitn(2, "?").collect(); self.base_url = params_url_split[0].to_string(); params_url_split.get(1).map(|params| { self.params.retain(|q| !q.enable); let mut retain_params: Vec<QueryParam> = self.params.clone(); self.params.clear(); for pair_str in params.split("&") { let pair_list: Vec<&str> = pair_str.splitn(2, "=").collect(); if pair_list.len() == 2 { let key = pair_list[0]; let value = pair_list[1]; self.params.push(QueryParam { key: key.to_string(), value: value.to_string(), desc: "".to_string(), lock_with: Default::default(), enable: true, }) } } retain_params.retain(|rp| self.params.iter().find(|p| p.key == rp.key).is_none()); self.params.append(&mut retain_params); }); let path_variables = self.get_path_variable_keys(); for path_variable in path_variables.iter() { if self .path_variables .iter() .find(|p| p.key == path_variable.clone()) .is_none() { self.path_variables.push(PathVariables { key: path_variable.to_string(), value: "".to_string(), desc: "".to_string(), }) } } self.path_variables .retain(|p| path_variables.contains(&p.key)); } pub fn compute_signature(&self) -> String { let path_variables: Vec<String> = self .path_variables .iter() .map(|p| p.compute_signature()) .collect(); let params: Vec<String> = self .params .iter() .filter(|q| q.lock_with == LockWith::NoLock) .map(|q| q.compute_signature()) .collect(); let headers: Vec<String> = self .headers .iter() .filter(|h| h.lock_with == LockWith::NoLock) .map(|h| h.compute_signature()) .collect(); format!( "Schema:{} Method:{} BaseUrl:{} PathVariables:[{}] Params:[{}] Headers:[{}] Body:{} Auth:{}", self.schema, self.method, self.base_url, path_variables.join(";"), params.join(";"), headers.join(";"), self.body.compute_signature(), self.auth.compute_signature() ) } pub fn clear_lock_with(&mut self) { self.params.retain(|s| s.lock_with == LockWith::NoLock); self.headers.retain(|s| s.lock_with == LockWith::NoLock); self.body .body_form_data .retain(|s| s.lock_with == LockWith::NoLock); self.body .body_xxx_form .retain(|s| s.lock_with == LockWith::NoLock); } pub fn remove_request_content_type(&mut self) { self.headers .retain(|h| h.key.to_lowercase() != "content-type" || h.lock_with != LockWith::NoLock); } pub fn set_request_content_type(&mut self, value: String) { let mut find = false; for header in self.headers.iter_mut() { if header.key.to_lowercase() == "content-type" { find = true; if !header.value.contains(value.as_str()) { header.value = value.clone(); } } } if !find { self.headers.push(Header { key: "content-type".to_string(), value, desc: "".to_string(), enable: true, lock_with: LockWith::NoLock, }); } } } impl HttpRecord { pub fn sync_everytime( &mut self, envs: BTreeMap<String, EnvironmentItemValue>, parent_auth: Auth, ) { self.request.fix_base_url(); self.request.sync_header(envs, parent_auth); } pub fn build_raw_url(&mut self) { self.request.build_raw_url(); } pub fn sync_raw_url(&mut self) { self.request.parse_raw_url(); } pub fn prepare_send( &mut self, envs: BTreeMap<String, EnvironmentItemValue>, parent_auth: Auth, ) { self.request.clear_lock_with(); self.sync_everytime(envs, parent_auth); self.sync_raw_url(); } pub fn get_response_content_type(&self) -> Option<Header> { self.response .headers .iter() .find(|h| h.key.to_lowercase() == "content-type") .cloned() } pub fn set_request_content_type(&mut self, value: String) { self.request.set_request_content_type(value); } pub fn remove_request_content_type(&mut self) { self.request.remove_request_content_type(); } } #[derive(Clone, EnumIter, EnumString, Display, PartialEq, Eq, Debug, Serialize, Deserialize)] pub enum BodyRawType { TEXT, JSON, HTML, XML, JavaScript, } impl Default for BodyRawType { fn default() -> Self { BodyRawType::JSON } } #[derive(Clone, EnumIter, EnumString, Display, PartialEq, Eq, Debug, Serialize, Deserialize)] pub enum BodyType { NONE, FROM_DATA, X_WWW_FROM_URLENCODED, RAW, BINARY, } impl Default for BodyType { fn default() -> Self { BodyType::NONE } } #[derive(Default, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)] #[serde(default)] pub struct QueryParam { pub key: String, pub value: String, pub desc: String, pub lock_with: LockWith, pub enable: bool, } impl QueryParam { pub fn compute_signature(&self) -> String { format!( "Key:{} Value:{} Desc:{} Enable:{}", self.key, self.value, self.desc, self.enable ) } } #[derive(Default, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)] #[serde(default)] pub struct PathVariables { pub key: String, pub value: String, pub desc: String, } impl PathVariables { pub fn compute_signature(&self) -> String { format!("Key:{} Value:{} Desc:{}", self.key, self.value, self.desc) } } #[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)] pub enum LockWith { LockWithScript, LockWithAuto, NoLock, } impl Default for LockWith { fn default() -> Self { LockWith::NoLock } } #[derive(Default, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)] #[serde(default)] pub struct MultipartData { pub data_type: MultipartDataType, pub key: String, pub value: String, pub desc: String, pub lock_with: LockWith, pub enable: bool, } impl MultipartData { pub fn compute_signature(&self) -> String { format!( "Key:{} Value:{} Desc:{} Enable:{}", self.key, self.value, self.desc, self.enable ) } } #[derive(Clone, PartialEq, Eq, Debug, Display, EnumIter, EnumString, Serialize, Deserialize)] pub enum MultipartDataType { FILE, TEXT, } impl Default for MultipartDataType { fn default() -> Self { MultipartDataType::TEXT } } #[derive(Default, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)] #[serde(default)] pub struct Header { pub key: String, pub value: String, pub desc: String, pub enable: bool, pub lock_with: LockWith, } impl Header { pub fn new_from_map(headers: &HeaderMap) -> Vec<Header> { let mut result = vec![]; for (key, value) in headers.iter() { result.push(Header { key: key.to_string(), value: value.to_str().unwrap_or("").to_string(), desc: "".to_string(), enable: true, lock_with: LockWith::NoLock, }) } result } pub fn compute_signature(&self) -> String { format!( "Key:{} Value:{} Desc:{} Enable:{}", self.key, self.value, self.desc, self.enable ) } } #[derive(Default, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)] #[serde(default)] pub struct Response { #[serde(skip)] pub request: Request, pub body: Arc<HttpBody>, pub headers: Vec<Header>, pub status: u16, pub status_text: String, pub elapsed_time: u128, #[serde(skip)] pub logger: Logger, } #[derive(Default, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)] #[serde(default)] pub struct HttpBody { pub base64: String, pub size: usize, pub body_str: String, pub body_file: String, pub body_type: BodyType, pub body_raw_type: BodyRawType, pub body_form_data: Vec<MultipartData>, pub body_xxx_form: Vec<MultipartData>, } impl HttpBody { pub fn compute_signature(&self) -> String { let body_form_data: Vec<String> = self .body_form_data .iter() .filter(|b| b.lock_with == LockWith::NoLock) .map(|b| b.compute_signature()) .collect(); let body_xxx_form: Vec<String> = self .body_xxx_form .iter() .filter(|b| b.lock_with == LockWith::NoLock) .map(|b| b.compute_signature()) .collect(); format!( "BodyStr:{} BodyFile:{} BodyType:{} BodyRawType:{} FormData:[{}] XXXForm:[{}]", self.body_str, self.body_file, self.body_type, self.body_raw_type, body_form_data.join(";"), body_xxx_form.join(";") ) } pub fn to_vec(&self) -> Vec<u8> { general_purpose::STANDARD .decode(&self.base64) .unwrap_or_default() } pub fn get_byte_size(&self) -> String { if self.size > 1000000 { return (self.size / 1000000).to_string() + " MB"; } else if self.size > 1000 { return (self.size / 1000).to_string() + " KB"; } else { return self.size.to_string() + " B"; } } pub fn new(bytes: Vec<u8>) -> Self { Self { base64: general_purpose::STANDARD.encode(&bytes).to_string(), size: bytes.len(), body_str: "".to_string(), body_file: "".to_string(), body_type: Default::default(), body_raw_type: Default::default(), body_form_data: vec![], body_xxx_form: vec![], } } } #[derive(Debug, Display, PartialEq, EnumString, EnumIter, Clone, Eq, Serialize, Deserialize)] pub enum Method { POST, GET, PUT, PATCH, DELETE, COPY, HEAD, OPTIONS, LINK, UNLINK, PURGE, LOCK, UNLOCK, PROPFIND, VIEW, } impl Default for Method { fn default() -> Self { Method::GET } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr_core/src/data/central_request_data.rs
crates/netpurr_core/src/data/central_request_data.rs
use std::collections::{BTreeMap, HashMap}; use std::path::Path; use serde::{Deserialize, Serialize}; use uuid::Uuid; use crate::data::record::Record; use crate::data::record::Record::{Rest, WebSocket}; use crate::data::test::TestResult; use crate::data::websocket::WebSocketRecord; use crate::persistence::{get_persistence_path, Persistence, PersistenceItem}; #[derive(Default, Clone, Debug)] pub struct CentralRequestDataList { pub select_id: Option<String>, pub data_list: Vec<String>, pub data_map: BTreeMap<String, CentralRequestItem>, persistence: Persistence, } impl CentralRequestDataList { pub fn load_all(&mut self, workspace: String) { self.persistence.set_workspace(workspace); self.data_list.clear(); self.select_id = None; self.data_map.clear(); let result: Option<CentralRequestDataListSaved> = self .persistence .load(Path::new(get_persistence_path("requests/data").as_str()).to_path_buf()); match result { Some(mut c) => { match &c.select_id { None => {} Some(id) => { if !c.data_map.contains_key(id.as_str()) { c.select_id = None; } } } self.data_map = c.data_map; self.select_id = c.select_id; for (_, crt) in self.data_map.iter() { self.data_list.push(crt.id.clone()); } } None => {} } } pub fn clear(&mut self) { self.data_map.clear(); self.data_list.clear(); self.persistence.save( Path::new("requests").to_path_buf(), "data".to_string(), &CentralRequestDataListSaved { select_id: self.select_id.clone(), data_map: self.data_map.clone(), }, ); } pub fn remove(&mut self, id: String) { self.data_map.remove(id.as_str()); self.data_list .clone() .iter() .enumerate() .find(|(_, list_id)| list_id.as_str() == id) .map(|(index, _)| self.data_list.remove(index)); self.persistence.save( Path::new("requests").to_path_buf(), "data".to_string(), &CentralRequestDataListSaved { select_id: self.select_id.clone(), data_map: self.data_map.clone(), }, ); } pub fn add_new_rest(&mut self) { let id = Uuid::new_v4().to_string(); let crt = CentralRequestItem { id: id.clone(), collection_path: None, record: Rest(Default::default()), ..Default::default() }; self.add_crt(crt); } pub fn add_new_websocket(&mut self) { let id = Uuid::new_v4().to_string(); let crt = CentralRequestItem { id: id.clone(), collection_path: None, record: WebSocket(WebSocketRecord::default()), ..Default::default() }; self.add_crt(crt); } pub fn select(&mut self, id: String) { self.select_id = Some(id) } pub fn add_crt(&mut self, mut crt: CentralRequestItem) { crt.set_baseline(); if !self.data_map.contains_key(crt.id.as_str()) { self.data_map.insert(crt.id.clone(), crt.clone()); self.data_list.push(crt.id.clone()) } self.select(crt.id.clone()); self.save(); } fn save(&self) { self.persistence.save( Path::new("requests").to_path_buf(), "data".to_string(), &CentralRequestDataListSaved { select_id: self.select_id.clone(), data_map: self.data_map.clone(), }, ); } pub fn auto_save(&self) { self.save(); } pub fn update_old_id_to_new(&mut self, old_id: String, path: String, new_name: String) { let new_id = format!("{}/{}", path, new_name); for (index, id) in self.data_list.iter().enumerate() { if id == old_id.as_str() { self.data_list[index] = new_id.clone(); break; } } let old_crt = self.data_map.remove(old_id.as_str()); old_crt.map(|mut crt| { crt.record.set_name(new_name.clone()); crt.id = new_id.clone(); self.data_map.insert(new_id.clone(), crt); }); if self.select_id == Some(old_id.clone()) { self.select_id = Some(new_id.clone()); } } pub fn update_old_name_to_new_name( &mut self, path: String, old_name: String, new_name: String, ) { let old_id = format!("{}/{}", path, old_name); self.update_old_id_to_new(old_id, path, new_name) } } #[derive(Default, Clone, Debug, Deserialize, Serialize)] #[serde(default)] pub struct CentralRequestItem { pub id: String, pub collection_path: Option<String>, pub record: Record, pub test_result: TestResult, pub modify_baseline: String, } impl CentralRequestItem { pub fn get_tab_name(&self) -> String { self.record.get_tab_name() } pub fn set_baseline(&mut self) { self.modify_baseline = self.compute_signature(); } fn compute_signature(&self) -> String { self.record.compute_signature() } pub fn is_modify(&self) -> bool { let now_sign = self.compute_signature(); now_sign != self.modify_baseline } } #[derive(Default, Clone, Debug, Deserialize, Serialize)] #[serde(default)] struct CentralRequestDataListSaved { pub select_id: Option<String>, pub data_map: BTreeMap<String, CentralRequestItem>, }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr_core/src/data/logger.rs
crates/netpurr_core/src/data/logger.rs
use chrono::{DateTime, Local}; use serde::{Deserialize, Serialize}; #[derive(Default, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)] pub struct Logger { pub logs: Vec<Log>, } impl Logger { pub fn add_info(&mut self, scope: String, msg: String) { self.logs.push(Log { level: LogLevel::Info, time: Local::now(), msg, scope, }) } pub fn add_error(&mut self, scope: String, msg: String) { self.logs.push(Log { level: LogLevel::Error, time: Local::now(), msg, scope, }) } pub fn add_warn(&mut self, scope: String, msg: String) { self.logs.push(Log { level: LogLevel::Warn, time: Local::now(), msg, scope, }) } } #[derive(Default, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)] pub struct Log { pub level: LogLevel, pub time: DateTime<Local>, pub msg: String, pub scope: String, } impl Log { pub fn show(&self) -> String { format!( "{} {:?} [{}] {}", self.time.format("%H:%M:%S").to_string(), self.level, self.scope, self.msg ) } } #[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)] pub enum LogLevel { Info, Warn, Error, } impl Default for LogLevel { fn default() -> Self { LogLevel::Info } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr_core/src/data/websocket.rs
crates/netpurr_core/src/data/websocket.rs
use std::ops::{Deref, DerefMut}; use std::sync::{Arc, Mutex}; use std::sync::mpsc::Sender; use base64::Engine; use base64::engine::general_purpose; use chrono::{DateTime, Local}; use serde::{Deserialize, Serialize}; use strum_macros::{Display, EnumIter, EnumString}; use tokio_tungstenite::tungstenite::Message; use crate::data::http::{Header, HttpRecord, Request, RequestSchema, Response}; #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(default)] pub struct WebSocketRecord { pub http_record: HttpRecord, pub select_message_type: MessageType, pub retain_content: String, pub history_send_messages: Vec<(MessageType, String)>, #[serde(skip)] pub session: Option<WebSocketSession>, } impl Default for WebSocketRecord { fn default() -> Self { WebSocketRecord { http_record: HttpRecord { name: "".to_string(), desc: "".to_string(), request: Request { method: Default::default(), schema: RequestSchema::WS, raw_url: "".to_string(), base_url: "".to_string(), path_variables: vec![], params: vec![], headers: vec![], body: Default::default(), auth: Default::default(), }, response: Default::default(), status: Default::default(), pre_request_script: "".to_string(), test_script: "".to_string(), testcases: Default::default(), operation_id: None, }, select_message_type: Default::default(), retain_content: "".to_string(), history_send_messages: vec![], session: None, } } } impl WebSocketRecord { pub fn compute_signature(&self) -> String { format!( "HttpRecord:{} History:{}", self.http_record.compute_signature(), self.history_send_messages.len() ) } pub fn connected(&self) -> bool { match &self.session { None => false, Some(session) => match session.get_status() { WebSocketStatus::Connect => true, WebSocketStatus::Connecting => false, WebSocketStatus::Disconnect => false, WebSocketStatus::ConnectError(_) => false, WebSocketStatus::SendError(_) => false, WebSocketStatus::SendSuccess => true, }, } } } #[derive(Default, Clone, Debug)] pub struct SessionState { status: WebSocketStatus, response: Response, messages: Messages, events: Vec<WebSocketStatus>, } #[derive(Default, Clone, Debug)] pub struct Messages { inner: Vec<WebSocketMessage>, } impl DerefMut for Messages { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.inner } } impl Deref for Messages { type Target = Vec<WebSocketMessage>; fn deref(&self) -> &Self::Target { &self.inner } } #[derive(Clone, Debug)] pub enum WebSocketMessage { Send(DateTime<Local>, MessageType, String), Receive(DateTime<Local>, MessageType, String), } #[derive(Clone, Debug, PartialEq)] pub enum WebSocketStatus { Connect, Connecting, Disconnect, ConnectError(String), SendError(String), SendSuccess, } impl Default for WebSocketStatus { fn default() -> Self { WebSocketStatus::Disconnect } } #[derive(Clone, Debug)] pub struct WebSocketSession { pub state: Arc<Mutex<SessionState>>, pub sender: Sender<Message>, } impl WebSocketSession { pub fn get_messages(&self) -> Messages { self.state.lock().unwrap().messages.clone() } pub fn add_message(&self, message: WebSocketMessage) { self.state.lock().unwrap().messages.push(message.clone()); if let WebSocketMessage::Send(_, msg_type, text) = message { match msg_type { MessageType::Text => { self.sender.send(Message::Text(text)); } MessageType::Binary => match general_purpose::STANDARD.decode(text) { Ok(b) => { self.sender.send(Message::Binary(b)); } Err(e) => self.add_event(WebSocketStatus::SendError(e.to_string())), }, } } } pub fn send_message(&self, msg_type: MessageType, msg: String) { self.add_message(WebSocketMessage::Send(Local::now(), msg_type, msg)); self.add_event(WebSocketStatus::SendSuccess) } pub fn disconnect(&self) { self.set_status(WebSocketStatus::Disconnect) } pub fn get_status(&self) -> WebSocketStatus { self.state.lock().unwrap().status.clone() } pub fn set_status(&self, status: WebSocketStatus) { self.state.lock().unwrap().status = status.clone(); self.add_event(status.clone()) } pub fn get_response(&self) -> Response { self.state.lock().unwrap().response.clone() } pub fn set_response( &self, response: tokio_tungstenite::tungstenite::handshake::client::Response, ) { let http_response = Response { request: Default::default(), body: Arc::new(Default::default()), headers: response .headers() .iter() .map(|(name, value)| Header { key: name.to_string(), value: value.to_str().unwrap_or_default().to_string(), desc: "".to_string(), enable: true, lock_with: Default::default(), }) .collect(), status: response.status().as_u16(), status_text: "".to_string(), elapsed_time: 0, logger: Default::default(), }; self.state.lock().unwrap().response = http_response; } pub fn next_event(&self) -> Option<WebSocketStatus> { self.state.lock().unwrap().events.pop() } pub fn add_event(&self, web_socket_status: WebSocketStatus) { self.state .lock() .unwrap() .events .insert(0, web_socket_status) } } #[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize, EnumIter, EnumString, Display)] pub enum MessageType { Text, Binary, } impl Default for MessageType { fn default() -> Self { MessageType::Text } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr_core/src/data/environment_function.rs
crates/netpurr_core/src/data/environment_function.rs
use std::time::{SystemTime, UNIX_EPOCH}; use rand::Rng; use strum_macros::{Display, EnumIter, EnumString}; use uuid::Uuid; #[derive(EnumIter, EnumString, Display)] pub enum EnvFunction { RandomInt, UUID, Timestamp, } pub fn get_env_result(name: EnvFunction) -> String { match name { EnvFunction::RandomInt => { let i: i32 = rand::thread_rng().gen_range(0..i32::MAX); i.to_string() } EnvFunction::UUID => Uuid::new_v4().to_string(), EnvFunction::Timestamp => { let current_time = SystemTime::now(); let timestamp = current_time .duration_since(UNIX_EPOCH) .expect("Time went backwards"); let timestamp_seconds = timestamp.as_secs(); timestamp_seconds.to_string() } } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr_core/src/data/collections.rs
crates/netpurr_core/src/data/collections.rs
use std::cell::RefCell; use std::collections::{BTreeMap, HashMap}; use std::path::{Path, PathBuf}; use std::rc::Rc; use openapiv3::OpenAPI; use serde::{Deserialize, Serialize}; use serde_json::Value; use crate::data::auth::{Auth, AuthType}; use crate::data::environment::{EnvironmentConfig, EnvironmentItemValue}; use crate::data::record::Record; use crate::persistence::{ get_persistence_path, Persistence, PERSISTENCE_EXTENSION, PersistenceItem, }; use crate::script::ScriptScope; #[derive(Default, Clone, Debug)] pub struct Collections { persistence: Persistence, pub data: BTreeMap<String, Collection>, } impl Collections { pub fn load_all(&mut self, workspace: String) { self.data.clear(); self.persistence.set_workspace(workspace); for collection_file in self .persistence .load_list(Path::new("collections").to_path_buf()) .iter() { if collection_file.is_file() { let mut collection = Collection::default(); collection.load( self.persistence.clone(), Path::new("collections").to_path_buf(), collection_file.clone(), ); if collection.folder.borrow().name != "" { self.data .insert(collection.folder.borrow().name.clone(), collection.clone()); } } } } pub fn add_collection(&mut self, collection: Collection) { collection .folder .borrow_mut() .fix_path_recursion(".".to_string()); self.data .insert(collection.folder.borrow().name.clone(), collection.clone()); collection.save_recursively( self.persistence.clone(), Path::new("collections").to_path_buf(), ); } pub fn add_record(&mut self, folder: Rc<RefCell<CollectionFolder>>, record: Record) { folder .borrow_mut() .requests .insert(record.name(), record.clone()); self.persistence.save( Path::new("collections") .join(folder.borrow().parent_path.as_str()) .join(folder.borrow().name.as_str()), record.name(), &record, ); } pub fn save_record(&mut self, folder: Rc<RefCell<CollectionFolder>>, record_name: String) { let path = Path::new("collections") .join(folder.borrow().parent_path.as_str()) .join(folder.borrow().name.as_str()); folder .borrow_mut() .requests .get(record_name.as_str()) .map(|record| { self.persistence.save(path, record.name(), record); }); } pub fn remove_http_record(&mut self, folder: Rc<RefCell<CollectionFolder>>, name: String) { folder.borrow_mut().requests.remove(name.as_str()); self.persistence.remove( Path::new("collections") .join(folder.borrow().parent_path.as_str()) .join(folder.borrow().name.as_str()), name.clone(), ) } pub fn add_folder( &mut self, parent_folder: Rc<RefCell<CollectionFolder>>, folder: Rc<RefCell<CollectionFolder>>, ) { parent_folder .borrow_mut() .folders .insert(folder.borrow().name.clone(), folder.clone()); folder.borrow_mut().fix_path_recursion( parent_folder.borrow().parent_path.clone() + "/" + parent_folder.borrow().name.as_str(), ); folder.borrow().save_recursively( self.persistence.clone(), Path::new("collections") .join(folder.borrow().parent_path.as_str()) .to_path_buf(), ); } pub fn save_folder(&self, folder: Rc<RefCell<CollectionFolder>>) { folder.borrow().save_info( self.persistence.clone(), Path::new("collections") .join(folder.borrow().parent_path.clone()) .join(folder.borrow().name.clone()) .to_path_buf(), ); } pub fn update_folder_info( &self, old_folder_name: String, parent_folder: Rc<RefCell<CollectionFolder>>, folder: Rc<RefCell<CollectionFolder>>, ) { let parent_path = folder.borrow().parent_path.clone(); folder.borrow_mut().fix_path_recursion(parent_path); parent_folder .borrow_mut() .folders .remove(old_folder_name.as_str()); let new_folder_name = folder.borrow().name.clone(); parent_folder .borrow_mut() .folders .insert(new_folder_name.clone(), folder.clone()); // rename folder self.persistence.rename( Path::new("collections") .join(folder.borrow().parent_path.clone()) .join(old_folder_name.clone()), Path::new("collections") .join(folder.borrow().parent_path.clone()) .join(new_folder_name.clone()), ); // add new @info folder.borrow().save_info( self.persistence.clone(), Path::new("collections") .join(folder.borrow().parent_path.clone()) .join(folder.borrow().name.clone()) .to_path_buf(), ); } pub fn remove_collection(&mut self, collection_name: String) { self.data.remove(collection_name.as_str()); self.persistence .remove_dir(Path::new("collections").join(collection_name.clone())); self.persistence.remove( Path::new("collections").to_path_buf(), collection_name + "@info", ); } pub fn update_collection_info(&mut self, old_collection_name: String, collection: Collection) { collection .folder .borrow_mut() .fix_path_recursion(".".to_string()); self.data.remove(old_collection_name.as_str()); let new_collection_name = collection.folder.borrow().name.clone(); self.data .insert(new_collection_name.clone(), collection.clone()); // remove old @info self.persistence.remove( Path::new("collections").to_path_buf(), old_collection_name + "@info", ); // add new @info collection.save_info( self.persistence.clone(), Path::new("collections").to_path_buf(), ); // update new folder @info collection.folder.borrow().save_info( self.persistence.clone(), Path::new("collections") .join(collection.folder.borrow().name.clone()) .to_path_buf(), ); } pub fn remove_folder(&self, parent_folder: Rc<RefCell<CollectionFolder>>, name: String) { parent_folder.borrow_mut().folders.remove(name.as_str()); self.persistence.remove_dir( Path::new("collections") .join(parent_folder.borrow().parent_path.as_str()) .join(parent_folder.borrow().name.as_str()) .join(name.as_str()), ); } pub fn get_data(&self) -> BTreeMap<String, Collection> { self.data.clone() } pub fn get_path_scripts(&self, path: String) -> (Vec<ScriptScope>, Vec<ScriptScope>) { let mut name_builder = Vec::new(); let mut pre_scripts = Vec::new(); let mut test_scripts = Vec::new(); for path_part in path.split("/") { name_builder.push(path_part); self.get_folder_with_path(name_builder.join("/")) .1 .map(|f| { test_scripts.push(ScriptScope { script: f.borrow().test_script.clone(), scope: name_builder.join("/"), }); pre_scripts.push(ScriptScope { script: f.borrow().pre_request_script.clone(), scope: name_builder.join("/"), }); }); } (pre_scripts, test_scripts) } pub fn get_auth(&self, path: String) -> Auth { let (_, of) = self.get_folder_with_path(path.clone()); let binding = path.clone(); let paths: Vec<&str> = binding.split("/").collect(); let mut auth; match of { None => { auth = Auth { auth_type: Default::default(), basic_username: "".to_string(), basic_password: "".to_string(), bearer_token: "".to_string(), } } Some(a) => auth = a.borrow().auth.clone(), }; if paths.len() == 1 || auth.auth_type != AuthType::InheritAuthFromParent { auth } else { self.get_auth(paths[0..paths.len() - 1].join("/")) } } pub fn get_folder_with_path( &self, path: String, ) -> (String, Option<Rc<RefCell<CollectionFolder>>>) { let collection_paths: Vec<&str> = path.split("/").collect(); let collection_name = &collection_paths[0].to_string(); return match self.data.get(collection_name) { None => (collection_name.to_string(), None), Some(collection) => { let mut folder = collection.folder.clone(); let folder_paths = &collection_paths[1..]; for folder_name in folder_paths.iter() { let binding = folder.borrow().folders.get(folder_name.to_owned()).cloned(); match binding { None => { return (collection_name.to_string(), None); } Some(get_folder) => { folder = get_folder.clone(); } } } (collection_name.to_string(), Some(folder)) } }; } } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(default)] pub struct Collection { pub envs: EnvironmentConfig, pub openapi: Option<OpenAPI>, pub folder: Rc<RefCell<CollectionFolder>>, } impl Default for Collection { fn default() -> Self { Collection { envs: Default::default(), openapi: None, folder: Rc::new(RefCell::new(CollectionFolder { name: "".to_string(), parent_path: "".to_string(), desc: "".to_string(), auth: Auth { auth_type: AuthType::NoAuth, basic_username: "".to_string(), basic_password: "".to_string(), bearer_token: "".to_string(), }, is_root: true, requests: Default::default(), folders: Default::default(), pre_request_script: "".to_string(), test_script: "".to_string(), testcases: Default::default(), })), } } } impl Collection { pub fn duplicate(&self, name: String) -> Self { let json = serde_json::to_string(self).unwrap(); let dup: Self = serde_json::from_str(json.as_str()).unwrap(); dup.folder.borrow_mut().name = name; dup } fn to_save_data(&self) -> SaveCollection { SaveCollection { envs: self.envs.clone(), openapi: self.openapi.clone(), } } pub fn build_envs(&self) -> BTreeMap<String, EnvironmentItemValue> { let mut result = BTreeMap::default(); for item in self.envs.items.iter().filter(|i| i.enable) { result.insert( item.key.clone(), EnvironmentItemValue { value: item.value.to_string(), scope: self.folder.borrow().name.clone() + " Collection", value_type: item.value_type.clone(), }, ); } result } fn save_info(&self, persistence: Persistence, path: PathBuf) { let save_data = self.to_save_data(); persistence.save( path.clone(), self.folder.borrow().name.clone() + "@info", &save_data, ); } fn save_recursively(&self, persistence: Persistence, path: PathBuf) { self.save_info(persistence.clone(), path.clone()); self.folder .borrow() .save_recursively(persistence, path.clone()); } fn load(&mut self, persistence: Persistence, dir_path: PathBuf, file_path: PathBuf) { file_path.clone().file_name().map(|file_name_os| { file_name_os.to_str().map(|file_name| { if file_name.ends_with(get_persistence_path("@info").as_str()) { file_name.split("@info").next().map(|folder_name| { let collection: Option<Collection> = persistence.load(file_path); collection.map(|c| { self.envs = c.envs; self.openapi = c.openapi; let mut folder = CollectionFolder::default(); folder.load(persistence, dir_path.join(folder_name)); self.folder = Rc::new(RefCell::new(folder)); }); }); } }) }); } } #[derive(Default, Clone, Debug, Serialize, Deserialize)] #[serde(default)] pub struct CollectionFolder { pub name: String, pub parent_path: String, pub desc: String, pub auth: Auth, pub is_root: bool, pub requests: BTreeMap<String, Record>, pub folders: BTreeMap<String, Rc<RefCell<CollectionFolder>>>, pub pre_request_script: String, pub test_script: String, pub testcases: BTreeMap<String, Testcase>, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] #[serde(default)] pub struct Testcase { pub entry_name: String, pub name: String, pub value: HashMap<String, Value>, pub parent_path: Vec<String>, } impl Default for Testcase { fn default() -> Self { Testcase { entry_name: "".to_string(), name: "Default Testcase".to_string(), value: Default::default(), parent_path: vec![], } } } impl Testcase { pub fn merge(&mut self, entry_name: String, parent: &Testcase) { for (key, value) in parent.value.iter() { self.value.insert(key.clone(), value.clone()); } self.entry_name = entry_name; self.parent_path = parent.parent_path.clone(); self.parent_path .push(format!("{}:{}", parent.entry_name, parent.name)); } pub fn get_testcase_path(&self) -> Vec<String> { let mut paths = self.parent_path.clone(); paths.push(self.get_path()); paths } pub fn get_path(&self) -> String { format!("{}:{}", self.entry_name, self.name) } } #[derive(Default, Clone, Debug, Serialize, Deserialize)] #[serde(default)] pub struct CollectionFolderOnlyRead { pub name: String, pub parent_path: String, pub desc: String, pub auth: Auth, pub is_root: bool, pub requests: BTreeMap<String, Record>, pub folders: BTreeMap<String, CollectionFolderOnlyRead>, pub pre_request_script: String, pub test_script: String, pub testcases: BTreeMap<String, Testcase>, } impl CollectionFolderOnlyRead { pub fn get_path(&self) -> String { format!("{}/{}", self.parent_path, self.name) .trim_start_matches("./") .to_string() } } #[derive(Default, Clone, PartialEq, Debug, Serialize, Deserialize)] #[serde(default)] pub struct SaveCollection { pub envs: EnvironmentConfig, pub openapi: Option<OpenAPI>, } #[derive(Default, Clone, PartialEq, Debug, Serialize, Deserialize)] #[serde(default)] pub struct SaveCollectionFolder { pub desc: String, pub auth: Auth, pub is_root: bool, pub pre_request_script: String, pub test_script: String, pub testcases: BTreeMap<String, Testcase>, } impl CollectionFolderOnlyRead { pub fn from(folder: Rc<RefCell<CollectionFolder>>) -> Self { let json = serde_json::to_string(&folder).unwrap(); serde_json::from_str(json.as_str()).unwrap() } } impl CollectionFolder { pub fn duplicate(&self, new_name: String) -> Self { let json = serde_json::to_string(self).unwrap(); let mut dup: Self = serde_json::from_str(json.as_str()).unwrap(); dup.name = new_name; dup } pub fn to_save_data(&self) -> SaveCollectionFolder { SaveCollectionFolder { desc: self.desc.clone(), auth: self.auth.clone(), is_root: self.is_root.clone(), pre_request_script: self.pre_request_script.clone(), test_script: self.test_script.clone(), testcases: self.testcases.clone(), } } pub fn load(&mut self, persistence: Persistence, path: PathBuf) { let collection_folder: Option<CollectionFolder> = persistence.load(path.join(get_persistence_path("folder@info")).to_path_buf()); let path_str = path.to_str().unwrap_or_default().trim_start_matches( persistence .get_workspace_dir() .join("collections") .to_str() .unwrap_or_default(), ); let path_split: Vec<&str> = path_str.split("/").collect(); let name = path_split[path_split.len() - 1].to_string(); let mut parent_path = path_split[1..path_split.len() - 1].join("/"); if parent_path.is_empty() { parent_path = ".".to_string(); } collection_folder.map(|cf| { self.name = name; self.parent_path = parent_path; self.desc = cf.desc; self.auth = cf.auth; self.is_root = cf.is_root; self.pre_request_script = cf.pre_request_script; self.test_script = cf.test_script; self.testcases = cf.testcases; }); for item in persistence.load_list(path.clone()).iter() { if item.is_file() { item.to_str().map(|name| { if name.ends_with(PERSISTENCE_EXTENSION) && !name.ends_with(get_persistence_path("folder@info").as_str()) { let request: Option<Record> = persistence.load(item.clone()); request.map(|r| { self.requests.insert(r.name(), r); }); } }); } else if item.is_dir() { let mut child_folder = CollectionFolder::default(); child_folder.load(persistence.clone(), item.clone()); self.folders.insert( child_folder.name.clone(), Rc::new(RefCell::new(child_folder)), ); } } } pub fn save_info(&self, persistence: Persistence, path: PathBuf) { let save_data = self.to_save_data(); persistence.save(path.clone(), "folder@info".to_string(), &save_data); } pub fn save_recursively(&self, persistence: Persistence, path: PathBuf) { let path = Path::new(&path).join(self.name.clone()).to_path_buf(); for (name, request) in self.requests.iter() { persistence.save(path.clone(), name.clone(), request); } for (_, folder) in self.folders.iter() { folder .borrow() .save_recursively(persistence.clone(), path.clone()); } self.save_info(persistence.clone(), path.clone()); } pub fn fix_path_recursion(&mut self, parent_path: String) { self.parent_path = parent_path; for (_, f) in self.folders.iter_mut() { f.borrow_mut() .fix_path_recursion(self.parent_path.clone() + "/" + self.name.as_str()); } } pub fn get_path(&self) -> String { format!("{}/{}", self.parent_path, self.name) .trim_start_matches("./") .to_string() } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr_core/src/data/history.rs
crates/netpurr_core/src/data/history.rs
use std::collections::BTreeMap; use std::io::Error; use std::path::Path; use std::str::FromStr; use chrono::{DateTime, Local, NaiveDate, Utc}; use serde::{Deserialize, Serialize}; use uuid::Uuid; use crate::data::record::Record; use crate::persistence::{Persistence, PersistenceItem}; #[derive(Default, Clone, Debug)] pub struct HistoryDataList { persistence: Persistence, date_group: BTreeMap<NaiveDate, DateGroupHistoryList>, } impl HistoryDataList { pub fn load_all(&mut self, workspace: String) -> Result<(), Error> { self.date_group.clear(); self.persistence.set_workspace(workspace); for date_dir in self .persistence .load_list(Path::new("history").to_path_buf()) .iter() { if let Some(date) = date_dir.file_name() { if let Some(date_name) = date.to_str() { if let Ok(naive_date) = NaiveDate::from_str(date_name) { let mut date_group_history_list = DateGroupHistoryList::default(); for item_path in self.persistence.load_list(date_dir.clone()).iter() { if let Some(history_rest_item) = self.persistence.load(item_path.clone()) { date_group_history_list.history_list.push(history_rest_item); } } date_group_history_list .history_list .sort_by(|a, b| b.record_date.cmp(&a.record_date)); self.date_group.insert(naive_date, date_group_history_list); } } } } Ok(()) } pub fn get_group(&self) -> &BTreeMap<NaiveDate, DateGroupHistoryList> { &self.date_group } pub fn record(&mut self, mut record: Record) { record.set_name("".to_string()); record.set_desc("".to_string()); let today = Local::now().naive_local().date(); if !self.date_group.contains_key(&today) { self.date_group.insert( today, DateGroupHistoryList { history_list: vec![], }, ); } let hrt = HistoryRestItem { id: Uuid::new_v4().to_string(), record_date: Local::now().with_timezone(&Utc), record, }; self.date_group .get_mut(&today) .map(|g| g.history_list.push(hrt.clone())); self.persistence.save( Path::new("history").join(today.to_string()), hrt.id.clone(), &hrt, ); } } #[derive(Default, Clone, Debug, Serialize, Deserialize)] #[serde(default)] pub struct HistoryRestItem { pub id: String, pub record_date: DateTime<Utc>, pub record: Record, } #[derive(Default, Clone, Debug)] pub struct DateGroupHistoryList { pub history_list: Vec<HistoryRestItem>, }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr_core/src/data/auth.rs
crates/netpurr_core/src/data/auth.rs
use std::collections::BTreeMap; use base64::Engine; use base64::engine::general_purpose; use serde::{Deserialize, Serialize}; use strum_macros::{Display, EnumIter, EnumString}; use crate::data::environment::EnvironmentItemValue; use crate::data::http::{Header, LockWith}; use crate::utils; #[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize, Default)] #[serde(default)] pub struct Auth { pub auth_type: AuthType, pub basic_username: String, pub basic_password: String, pub bearer_token: String, } #[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize, EnumIter, EnumString, Display)] pub enum AuthType { InheritAuthFromParent, NoAuth, BearerToken, BasicAuth, } impl Auth { pub fn compute_signature(&self) -> String { format!( "Type:{} BasicUsername:{} BasicPassword:{} BearerToken:{}", self.auth_type, self.basic_username, self.basic_password, self.bearer_token ) } pub fn get_final_type(&self, auth: Auth) -> AuthType { match self.auth_type { AuthType::NoAuth => AuthType::NoAuth, AuthType::BearerToken => AuthType::BearerToken, AuthType::BasicAuth => AuthType::BasicAuth, AuthType::InheritAuthFromParent => auth.get_final_type(Auth { auth_type: AuthType::NoAuth, basic_username: "".to_string(), basic_password: "".to_string(), bearer_token: "".to_string(), }), } } pub fn build_head( &self, headers: &mut Vec<Header>, envs: BTreeMap<String, EnvironmentItemValue>, auth: Auth, ) { let mut header = Header { key: "Authorization".to_string(), value: "".to_string(), desc: "auto gen".to_string(), enable: true, lock_with: LockWith::LockWithAuto, }; headers.retain(|h| { !(h.key.to_lowercase() == "authorization" && h.lock_with != LockWith::NoLock) }); match self.auth_type { AuthType::NoAuth => {} AuthType::BearerToken => { header.value = "Bearer ".to_string() + utils::replace_variable(self.bearer_token.clone(), envs.clone()).as_str(); headers.push(header) } AuthType::BasicAuth => { let encoded_credentials = general_purpose::STANDARD.encode(format!( "{}:{}", utils::replace_variable(self.basic_username.clone(), envs.clone()), utils::replace_variable(self.basic_password.clone(), envs.clone()) )); header.value = "Basic ".to_string() + encoded_credentials.as_str(); headers.push(header) } AuthType::InheritAuthFromParent => auth.build_head( headers, envs, Auth { auth_type: AuthType::NoAuth, basic_username: "".to_string(), basic_password: "".to_string(), bearer_token: "".to_string(), }, ), } } } impl Default for AuthType { fn default() -> Self { AuthType::InheritAuthFromParent } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr_core/src/data/record.rs
crates/netpurr_core/src/data/record.rs
use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; use crate::data::collections::Testcase; use crate::data::http::HttpRecord; use crate::data::websocket::WebSocketRecord; #[derive(Clone, Debug, Deserialize, Serialize)] pub enum Record { Rest(HttpRecord), WebSocket(WebSocketRecord), } impl Record { pub fn set_pre_request_script(&mut self, script: String) { match self { Record::Rest(rest) => rest.pre_request_script = script, Record::WebSocket(websocket) => websocket.http_record.pre_request_script = script, } } pub fn set_test_script(&mut self, script: String) { match self { Record::Rest(rest) => rest.test_script = script, Record::WebSocket(websocket) => websocket.http_record.test_script = script, } } pub fn set_testcases(&mut self, testcases: BTreeMap<String, Testcase>) { match self { Record::Rest(rest) => rest.testcases = testcases, Record::WebSocket(websocket) => {} } } pub fn pre_request_script(&self) -> String { match self { Record::Rest(rest) => rest.pre_request_script.clone(), Record::WebSocket(websocket) => websocket.http_record.pre_request_script.clone(), } } pub fn test_script(&self) -> String { match self { Record::Rest(rest) => rest.test_script.clone(), Record::WebSocket(websocket) => websocket.http_record.test_script.clone(), } } pub fn testcase(&self) -> BTreeMap<String, Testcase> { match self { Record::Rest(rest) => rest.testcases.clone(), Record::WebSocket(websocket) => BTreeMap::new(), } } pub fn must_get_rest(&self) -> &HttpRecord { match self { Record::Rest(rest) => rest, Record::WebSocket(websocket) => &websocket.http_record, } } pub fn must_get_mut_rest(&mut self) -> &mut HttpRecord { match self { Record::Rest(rest) => rest, Record::WebSocket(websocket) => &mut websocket.http_record, } } pub fn must_get_websocket(&self) -> &WebSocketRecord { match self { Record::Rest(_) => panic!("not websocket"), Record::WebSocket(websocket) => websocket, } } pub fn must_get_mut_websocket(&mut self) -> &mut WebSocketRecord { match self { Record::Rest(_) => panic!("not websocket"), Record::WebSocket(websocket) => websocket, } } pub fn desc(&self) -> String { match self { Record::Rest(rest) => rest.desc.clone(), Record::WebSocket(websocket) => websocket.http_record.desc.clone(), } } pub fn set_desc(&mut self, desc: String) { match self { Record::Rest(rest) => rest.desc = desc, Record::WebSocket(websocket) => websocket.http_record.desc = desc, } } pub fn name(&self) -> String { match self { Record::Rest(rest) => rest.name.clone(), Record::WebSocket(websocket) => websocket.http_record.name.clone(), } } pub fn method(&self) -> String { match self { Record::Rest(rest) => rest.request.method.to_string(), Record::WebSocket(websocket) => "WS".to_string(), } } pub fn base_url(&self) -> String { match self { Record::Rest(rest) => rest.request.base_url.to_string(), Record::WebSocket(websocket) => websocket.http_record.request.base_url.to_string(), } } pub fn raw_url(&self) -> String { match self { Record::Rest(rest) => rest.request.raw_url.to_string(), Record::WebSocket(websocket) => websocket.http_record.request.raw_url.to_string(), } } pub fn set_name(&mut self, name: String) { match self { Record::Rest(rest) => rest.name = name, Record::WebSocket(websocket) => websocket.http_record.name = name, } } pub fn get_tab_name(&self) -> String { if self.name() != "" { self.name() } else { if self.base_url() == "" { "Untitled Request".to_string() } else { self.base_url() } } } pub fn compute_signature(&self) -> String { match self { Record::Rest(rest) => rest.compute_signature(), Record::WebSocket(websocket) => websocket.compute_signature(), } } } impl Default for Record { fn default() -> Self { Record::Rest(HttpRecord::default()) } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr_core/src/data/mod.rs
crates/netpurr_core/src/data/mod.rs
pub mod auth; pub mod central_request_data; pub mod collections; pub mod cookies_manager; pub mod environment; pub mod environment_function; pub mod history; pub mod http; pub mod logger; pub mod record; pub mod test; pub mod websocket; pub mod workspace_data;
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr_core/src/data/workspace_data.rs
crates/netpurr_core/src/data/workspace_data.rs
use std::cell::RefCell; use std::collections::{BTreeMap, HashSet}; use std::rc::Rc; use chrono::NaiveDate; use log::error; use strum_macros::{Display, EnumIter}; use uuid::Uuid; use crate::data::auth::{Auth, AuthType}; use crate::data::central_request_data::{CentralRequestDataList, CentralRequestItem}; use crate::data::collections::{Collection, CollectionFolder, Collections}; use crate::data::cookies_manager::{Cookie, CookiesManager}; use crate::data::environment::{Environment, EnvironmentConfig, EnvironmentItemValue}; use crate::data::history::{DateGroupHistoryList, HistoryDataList}; use crate::data::record::Record; use crate::runner::TestRunResult; use crate::script::{ScriptScope, ScriptTree}; use crate::utils; #[derive(Default, Clone, Debug)] pub struct WorkspaceData { pub workspace_name: String, pub editor_model: EditorModel, pub selected_test_item: Option<TestItem>, pub selected_test_run_result: Option<TestRunResult>, cookies_manager: RefCell<CookiesManager>, central_request_data_list: RefCell<CentralRequestDataList>, history_data_list: RefCell<HistoryDataList>, environment: RefCell<Environment>, collections: RefCell<Collections>, } #[derive(Clone, Debug)] pub enum TestItem { Folder(String, Rc<RefCell<CollectionFolder>>), Record(String, Rc<RefCell<CollectionFolder>>, String), } #[derive(Display, PartialEq, EnumIter, Clone, Debug)] pub enum EditorModel { Request, Test, Design, } impl Default for EditorModel { fn default() -> Self { EditorModel::Request } } //collections impl WorkspaceData { pub fn get_collection(&self, option_path: Option<String>) -> Option<Collection> { let path = option_path?; let collection_name = path.splitn(2, "/").next()?; self.collections.borrow().data.get(collection_name).cloned() } pub fn get_collection_by_name(&self, name: String) -> Option<Collection> { self.collections.borrow().data.get(name.as_str()).cloned() } pub fn get_folder_with_path( &self, path: String, ) -> (String, Option<Rc<RefCell<CollectionFolder>>>) { self.collections.borrow().get_folder_with_path(path) } pub fn collection_insert_record(&self, folder: Rc<RefCell<CollectionFolder>>, record: Record) { self.collections.borrow_mut().add_record(folder, record) } pub fn collection_remove_http_record( &self, folder: Rc<RefCell<CollectionFolder>>, collection_name: String, ) { self.collections .borrow_mut() .remove_http_record(folder, collection_name) } pub fn collection_insert_folder( &self, parent_folder: Rc<RefCell<CollectionFolder>>, folder: Rc<RefCell<CollectionFolder>>, ) { self.collections .borrow_mut() .add_folder(parent_folder, folder) } pub fn get_collection_auth(&self, path: String) -> Auth { self.collections.borrow().get_auth(path) } pub fn get_collection_names(&self) -> HashSet<String> { self.collections .borrow() .get_data() .iter() .map(|(k, _)| k.to_string()) .collect() } // will be saved recursively pub fn add_collection(&self, collection: Collection) { self.collections.borrow_mut().add_collection(collection) } pub fn import_collection(&self, mut collection: Collection) -> String { let new_name = utils::build_copy_name( collection.folder.borrow().name.clone(), self.get_collection_names(), ); collection.folder.borrow_mut().name = new_name.clone(); self.add_collection(collection.clone()); new_name } pub fn remove_collection(&self, collection_name: String) { self.collections .borrow_mut() .remove_collection(collection_name) } pub fn update_collection_info(&self, old_collection_name: String, collection: Collection) { self.collections .borrow_mut() .update_collection_info(old_collection_name, collection) } pub fn add_folder( &self, parent_folder: Rc<RefCell<CollectionFolder>>, folder: Rc<RefCell<CollectionFolder>>, ) { self.collections .borrow_mut() .add_folder(parent_folder, folder); } pub fn update_folder_info( &self, old_folder_name: String, parent_folder: Rc<RefCell<CollectionFolder>>, folder: Rc<RefCell<CollectionFolder>>, ) { self.collections .borrow_mut() .update_folder_info(old_folder_name, parent_folder, folder) } pub fn save_folder(&self, folder: Rc<RefCell<CollectionFolder>>) { self.collections.borrow_mut().save_folder(folder) } pub fn add_record(&self, folder: Rc<RefCell<CollectionFolder>>, record: Record) { self.collections.borrow_mut().add_record(folder, record) } pub fn save_record(&self, folder: Rc<RefCell<CollectionFolder>>, record_name: String) { self.collections .borrow_mut() .save_record(folder, record_name) } pub fn remove_folder(&self, parent_folder: Rc<RefCell<CollectionFolder>>, name: String) { self.collections .borrow_mut() .remove_folder(parent_folder, name) } pub fn get_collections(&self) -> BTreeMap<String, Collection> { self.collections.borrow().data.clone() } pub fn get_cookies_manager(&self) -> CookiesManager { self.cookies_manager.borrow().clone() } } //env impl WorkspaceData { pub fn get_build_envs( &self, collection: Option<Collection>, ) -> BTreeMap<String, EnvironmentItemValue> { self.environment.borrow().get_variable_hash_map(collection) } pub fn get_env_select(&self) -> Option<String> { self.environment.borrow().select() } pub fn set_env_select(&self, select: Option<String>) { self.environment.borrow_mut().set_select(select) } pub fn get_env_configs(&self) -> BTreeMap<String, EnvironmentConfig> { self.environment.borrow().get_data() } pub fn get_env(&self, key: String) -> Option<EnvironmentConfig> { self.environment.borrow().get(key) } pub fn add_env(&self, key: String, value: EnvironmentConfig) { self.environment.borrow_mut().insert(key, value) } pub fn remove_env(&self, key: String) { self.environment.borrow_mut().remove(key) } } // history impl WorkspaceData { pub fn get_history_group(&self) -> BTreeMap<NaiveDate, DateGroupHistoryList> { self.history_data_list.borrow().get_group().clone() } pub fn history_record(&self, record: Record) { self.history_data_list.borrow_mut().record(record); } } // cookie impl WorkspaceData { pub fn get_url_cookies(&self, url: String) -> BTreeMap<String, Cookie> { self.cookies_manager.borrow().get_url_cookies(url) } pub fn save_cookies(&self) { self.cookies_manager.borrow().save() } pub fn cookies_contain_domain(&self, domain: String) -> bool { self.cookies_manager.borrow().contain_domain(domain) } pub fn cookies_contain_domain_key(&self, domain: String, key: String) -> bool { self.cookies_manager .borrow() .contain_domain_key(domain, key) } pub fn add_domain_cookies(&self, cookie: Cookie) -> Result<(), String> { self.cookies_manager.borrow_mut().add_domain_cookies(cookie) } pub fn get_cookie_domains(&self) -> Vec<String> { self.cookies_manager.borrow().get_cookie_domains() } pub fn get_domain_cookies(&self, domain: String) -> Option<BTreeMap<String, Cookie>> { self.cookies_manager.borrow().get_domain_cookies(domain) } pub fn remove_cookie_domain(&self, domain: String) { self.cookies_manager.borrow().remove_domain(domain) } pub fn remove_cookie_domain_path_name(&mut self, domain: String, path: String, name: String) { self.cookies_manager .borrow() .remove_domain_path_name(domain, path, name) } pub fn update_domain_cookies( &self, cookie: Cookie, domain: String, name: String, ) -> Result<(), String> { self.cookies_manager .borrow_mut() .update_domain_cookies(cookie, domain, name) } } // crt impl WorkspaceData { pub fn save_crt( &mut self, crt_id: String, collection_path: String, modify_record: impl FnOnce(&mut Record), ) { let mut new_name_option = None; self.central_request_data_list .borrow_mut() .data_map .get_mut(crt_id.as_str()) .map(|crt| { let (_, cf_option) = self.get_folder_with_path(collection_path.clone()); cf_option.map(|cf| { crt.collection_path = Some(collection_path.clone()); let mut record = crt.record.clone(); modify_record(&mut record); new_name_option = Some(record.name()); cf.borrow().requests.get(&record.name()).map(|old| { record.set_testcases(old.testcase()); record.set_test_script(old.test_script()); record.set_pre_request_script(old.pre_request_script()); }); self.collection_insert_record(cf.clone(), record); crt.set_baseline(); }); }); new_name_option.map(|new_name| { self.central_request_data_list .borrow_mut() .update_old_id_to_new(crt_id, collection_path.clone(), new_name.clone()); }); } pub fn must_get_mut_crt( &self, id: String, call: impl FnOnce(&mut CentralRequestItem), ) -> CentralRequestItem { match self .central_request_data_list .borrow_mut() .data_map .get_mut(id.as_str()) { None => { error!("get crt:{} error", id) } Some(crt) => call(crt), } self.must_get_crt(id) } pub fn get_crt_envs(&self, id: String) -> BTreeMap<String, EnvironmentItemValue> { let crt = self.must_get_crt(id); self.get_build_envs(self.get_collection(crt.collection_path.clone())) } pub fn get_path_parent_auth(&self, path: String) -> Auth { self.get_collection_auth(path) } pub fn get_crt_parent_auth(&self, id: String) -> Auth { let crt = self.must_get_crt(id); match &crt.collection_path { None => Auth { auth_type: AuthType::NoAuth, basic_username: "".to_string(), basic_password: "".to_string(), bearer_token: "".to_string(), }, Some(collection_path) => self.get_collection_auth(collection_path.clone()), } } pub fn get_path_parent_scripts(&self, path: String) -> (Vec<ScriptScope>, Vec<ScriptScope>) { self.collections.borrow().get_path_scripts(path.clone()) } pub fn get_crt_parent_scripts(&self, id: String) -> (Vec<ScriptScope>, Vec<ScriptScope>) { let crt = self.must_get_crt(id); let mut pre_request_script_scopes = Vec::new(); let mut test_script_scopes = Vec::new(); match &crt.collection_path { None => {} Some(collection_path) => { (pre_request_script_scopes, test_script_scopes) = self .collections .borrow() .get_path_scripts(collection_path.clone()) } } (pre_request_script_scopes, test_script_scopes) } pub fn get_parent_scripts( &self, collection_path: String, ) -> (Vec<ScriptScope>, Vec<ScriptScope>) { return self .collections .borrow() .get_path_scripts(collection_path.clone()); } pub fn get_script_tree(&self, collection_path: String) -> ScriptTree { let mut script_tree = ScriptTree::default(); if let (_, Some(folder)) = self.get_folder_with_path(collection_path) { self._get_script_tree(folder.clone(), &mut script_tree); } script_tree } fn _get_script_tree( &self, folder: Rc<RefCell<CollectionFolder>>, script_tree: &mut ScriptTree, ) { let path = folder.borrow().get_path(); let (pre_request_parent_script_scopes, test_parent_script_scopes) = self.get_parent_scripts(path.clone()); script_tree .add_pre_request_parent_script_scope(path.clone(), pre_request_parent_script_scopes); script_tree.add_test_parent_script_scope(path.clone(), test_parent_script_scopes); for (_, child_folder) in folder.borrow().folders.iter() { self._get_script_tree(child_folder.clone(), script_tree); } } pub fn get_crt_select_id(&self) -> Option<String> { self.central_request_data_list.borrow().select_id.clone() } pub fn set_crt_select_id(&self, select_id: Option<String>) { self.central_request_data_list.borrow_mut().select_id = select_id; } pub fn get_crt_id_list(&self) -> Vec<String> { self.central_request_data_list.borrow().data_list.clone() } pub fn get_crt_id_set(&self) -> HashSet<String> { let mut hashset = HashSet::new(); for id in self.get_crt_id_list() { hashset.insert(id); } hashset } pub fn get_crt_cloned(&self, id: String) -> Option<CentralRequestItem> { self.central_request_data_list .borrow() .data_map .get(id.as_str()) .cloned() } pub fn must_get_crt(&self, id: String) -> CentralRequestItem { self.central_request_data_list .borrow() .data_map .get(id.as_str()) .cloned() .unwrap_or_else(|| { error!("get crt {} error", id); CentralRequestItem::default() }) } pub fn auto_save_crd(&self) { self.central_request_data_list.borrow().auto_save(); } pub fn add_crt(&self, crt: CentralRequestItem) { self.central_request_data_list.borrow_mut().add_crt(crt); } pub fn close_all_crt(&self) { self.central_request_data_list.borrow_mut().clear(); self.set_crt_select_id(None); } pub fn close_other_crt(&self, id: String) { let retain = self.must_get_crt(id.clone()).clone(); self.central_request_data_list.borrow_mut().clear(); self.add_crt(retain); self.set_crt_select_id(Some(id.clone())); } pub fn close_crt(&self, id: String) { self.central_request_data_list .borrow_mut() .remove(id.clone()); if let Some(select_id) = self.get_crt_select_id() { if select_id == id { self.set_crt_select_id(None); } } } pub fn duplicate_crt(&self, id: String) { let mut duplicate = self.must_get_crt(id).clone(); duplicate.id = Uuid::new_v4().to_string(); duplicate.collection_path = None; self.add_crt(duplicate); } pub fn add_new_rest_crt(&self) { self.central_request_data_list.borrow_mut().add_new_rest(); } pub fn add_new_websocket_crt(&self) { self.central_request_data_list .borrow_mut() .add_new_websocket(); } pub fn contains_crt_id(&self, crt_id: String) -> bool { self.central_request_data_list .borrow() .data_map .contains_key(crt_id.as_str()) } pub fn update_crt_old_name_to_new_name( &self, path: String, old_name: String, new_name: String, ) { self.central_request_data_list .borrow_mut() .update_old_name_to_new_name(path, old_name, new_name); } } impl WorkspaceData { pub fn load_all(&mut self, workspace: String) { self.workspace_name = workspace.clone(); self.editor_model = EditorModel::Request; self.selected_test_item = None; self.central_request_data_list .borrow_mut() .load_all(workspace.clone()); self.history_data_list .borrow_mut() .load_all(workspace.clone()); self.environment.borrow_mut().load_all(workspace.clone()); self.collections.borrow_mut().load_all(workspace.clone()); self.cookies_manager .borrow_mut() .load_all(workspace.clone()) } pub fn reload_data(&mut self, workspace: String) { self.history_data_list .borrow_mut() .load_all(workspace.clone()); self.environment.borrow_mut().load_all(workspace.clone()); self.collections.borrow_mut().load_all(workspace.clone()); self.cookies_manager .borrow_mut() .load_all(workspace.clone()) } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/netpurr_core/src/data/cookies_manager.rs
crates/netpurr_core/src/data/cookies_manager.rs
use std::collections::{BTreeMap, BTreeSet}; use std::fs::File; use std::sync::Arc; use log::error; use serde::{Deserialize, Serialize}; use url::Url; use cookie_store::CookieDomain; use reqwest_cookie_store::{CookieStoreMutex, RawCookie}; use crate::persistence::{Persistence, PersistenceItem}; #[derive(Default, Clone, Debug)] pub struct CookiesManager { persistence: Persistence, pub cookie_store: Arc<CookieStoreMutex>, } impl CookiesManager { pub fn load_all(&mut self, workspace: String) { self.persistence.set_workspace(workspace); let cookie_store = { if let Ok(file) = File::open(self.persistence.get_workspace_dir().join("cookies.json")) .map(std::io::BufReader::new) { // use re-exported version of `CookieStore` for crate compatibility reqwest_cookie_store::CookieStore::load_json(file) .unwrap_or(reqwest_cookie_store::CookieStore::default()) } else { reqwest_cookie_store::CookieStore::default() } }; let cookie_store = CookieStoreMutex::new(cookie_store); self.cookie_store = Arc::new(cookie_store); } pub fn save(&self) { match self.cookie_store.lock() { Ok(store) => { let mut writer = File::create(self.persistence.get_workspace_dir().join("cookies.json")) .map(std::io::BufWriter::new) .unwrap(); match store.save_incl_expired_and_nonpersistent_json(&mut writer) { Ok(_) => {} Err(err) => { error!("{}", err) } } } Err(err) => { error!("{}", err) } } } pub fn contain_domain(&self, domain: String) -> bool { match self.cookie_store.lock() { Ok(store) => store .iter_any() .find(|c| { c.domain == CookieDomain::HostOnly(domain.clone()) || c.domain == CookieDomain::Suffix(domain.clone()) }) .is_some(), Err(_) => false, } } pub fn contain_domain_key(&self, domain: String, key: String) -> bool { match self.cookie_store.lock() { Ok(store) => store .iter_any() .find(|c| c.domain() == Some(domain.as_str()) && c.name() == key.as_str()) .is_some(), Err(_) => false, } } pub fn get_url_cookies(&self, mut url: String) -> BTreeMap<String, Cookie> { let mut result = BTreeMap::new(); let url_parse = Url::parse(url.as_str()); match url_parse { Ok(url_parse_ok) => match self.cookie_store.lock() { Ok(store) => { store .matches(&url_parse_ok) .iter() .map(|c| Cookie { name: c.name().to_string(), value: c.value().to_string(), domain: c.domain().unwrap_or("").to_string(), path: c.path().unwrap_or("").to_string(), expires: c .expires_datetime() .map(|e| e.to_string()) .unwrap_or("".to_string()), max_age: c.max_age().map(|d| d.to_string()).unwrap_or("".to_string()), raw: c.to_string(), http_only: c.http_only().unwrap_or(false), secure: c.secure().unwrap_or(false), }) .for_each(|c| { result.insert(c.name.clone(), c); }); } Err(_) => {} }, Err(_) => {} } result } pub fn get_domain_cookies(&self, domain: String) -> Option<BTreeMap<String, Cookie>> { let mut result = BTreeMap::new(); match self.cookie_store.lock() { Ok(store) => { store .iter_any() .filter(|c| { c.domain == CookieDomain::HostOnly(domain.clone()) || c.domain == CookieDomain::Suffix(domain.clone()) }) .map(|c| Cookie { name: c.name().to_string(), value: c.value().to_string(), domain: domain.clone(), path: c.path().unwrap_or("").to_string(), expires: c .expires_datetime() .map(|e| e.to_string()) .unwrap_or("".to_string()), max_age: c.max_age().map(|d| d.to_string()).unwrap_or("".to_string()), raw: c.to_string(), http_only: c.http_only().unwrap_or(false), secure: c.secure().unwrap_or(false), }) .for_each(|c| { result.insert(c.name.clone(), c); }); } Err(_) => {} } Some(result) } pub fn add_domain_cookies(&self, cookie: Cookie) -> Result<(), String> { let result = match &RawCookie::parse(cookie.raw.as_str()) { Ok(c) => match self.cookie_store.lock() { Ok(mut store) => match store.insert_raw_no_url_check(c) { Ok(_) => Ok(()), Err(e) => Err(e.to_string()), }, Err(e) => Err(e.to_string()), }, Err(e) => Err(e.to_string()), }; if result.is_ok() { self.save(); } result } pub fn update_domain_cookies( &self, cookie: Cookie, domain: String, name: String, ) -> Result<(), String> { let result = match &RawCookie::parse(cookie.raw.as_str()) { Ok(c) => { if c.name() != name || (c.domain().is_some() && c.domain() != Some(domain.as_str())) { return Err("Domain or Name is changed.".to_string()); } match self.cookie_store.lock() { Ok(mut store) => match store.insert_raw_no_url_check(c) { Ok(_) => Ok(()), Err(e) => Err(e.to_string()), }, Err(e) => Err(e.to_string()), } } Err(e) => Err(e.to_string()), }; if result.is_ok() { self.save(); } result } pub fn remove_domain(&self, mut domain: String) { match self.cookie_store.lock() { Ok(mut store) => { store.remove_domain(domain.as_str()); self.save() } Err(_) => {} } } pub fn remove_domain_path_name(&self, mut domain: String, path: String, name: String) { match self.cookie_store.lock() { Ok(mut store) => { store.remove(domain.as_str(), path.as_str(), name.as_str()); self.save() } Err(_) => {} } } pub fn get_cookie_domains(&self) -> Vec<String> { let mut hash_set: BTreeSet<String> = BTreeSet::new(); match self.cookie_store.lock() { Ok(store) => { for cookie in store.iter_any() { match &cookie.domain { CookieDomain::HostOnly(domain) => { hash_set.insert(domain.clone()); } CookieDomain::Suffix(domain) => { hash_set.insert(domain.clone()); } CookieDomain::NotPresent => {} CookieDomain::Empty => {} } } } Err(_) => {} } let mut keys = vec![]; for domain_name in hash_set { keys.push(domain_name) } keys } } #[derive(Default, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)] #[serde(default)] pub struct Cookie { pub name: String, pub value: String, pub domain: String, pub path: String, pub expires: String, pub max_age: String, pub raw: String, pub http_only: bool, pub secure: bool, } impl Cookie { pub fn from_raw(raw: String) -> Self { let mut cookie = Cookie { name: "".to_string(), value: "".to_string(), domain: "".to_string(), path: "".to_string(), expires: "".to_string(), max_age: "".to_string(), raw, http_only: false, secure: false, }; let raw = cookie.raw.clone(); let s = raw.split(";"); for (index, x) in s.into_iter().enumerate() { let one: Vec<&str> = x.splitn(2, "=").collect(); if one.len() < 2 { continue; } match one[0].trim() { "expires" => cookie.expires = one[1].to_string(), "path" => cookie.path = one[1].to_string(), "domain" => cookie.domain = one[1].to_string(), "max-age" => cookie.max_age = one[1].to_string(), "secure" => cookie.secure = true, "httponly" => cookie.http_only = true, _ => { if index == 0 { cookie.value = one[1].to_string(); cookie.name = one[0].to_string() } } } } cookie } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/reqwest_cookie_store/src/lib.rs
crates/reqwest_cookie_store/src/lib.rs
#![allow(unused_imports)] #![deny(warnings, missing_debug_implementations, rust_2018_idioms)] #![cfg_attr(docsrs, feature(doc_cfg))] //! # Example //! The following example demonstrates loading a [`cookie_store::CookieStore`] (re-exported in this crate) from disk, and using it within a //! [`CookieStoreMutex`]. It then makes a series of requests, examining and modifying the contents //! of the underlying [`cookie_store::CookieStore`] in between. //! ```no_run //! # tokio_test::block_on(async { //! // Load an existing set of cookies, serialized as json //! let cookie_store = { //! if let Ok(file) = std::fs::File::open("cookies.json") //! .map(std::io::BufReader::new) //! { //! // use re-exported version of `CookieStore` for crate compatibility //! reqwest_cookie_store::CookieStore::load_json(file).unwrap() //! } //! else //! { //! reqwest_cookie_store::CookieStore::new(None) //! } //! }; //! let cookie_store = reqwest_cookie_store::CookieStoreMutex::new(cookie_store); //! let cookie_store = std::sync::Arc::new(cookie_store); //! { //! // Examine initial contents //! println!("initial load"); //! let store = cookie_store.lock().unwrap(); //! for c in store.iter_any() { //! println!("{:?}", c); //! } //! } //! //! // Build a `reqwest` Client, providing the deserialized store //! let client = reqwest::Client::builder() //! .cookie_provider(std::sync::Arc::clone(&cookie_store)) //! .build() //! .unwrap(); //! //! // Make a sample request //! client.get("https://google.com").send().await.unwrap(); //! { //! // Examine the contents of the store. //! println!("after google.com GET"); //! let store = cookie_store.lock().unwrap(); //! for c in store.iter_any() { //! println!("{:?}", c); //! } //! } //! //! // Make another request from another domain //! println!("GET from msn"); //! client.get("https://msn.com").send().await.unwrap(); //! { //! // Examine the contents of the store. //! println!("after msn.com GET"); //! let mut store = cookie_store.lock().unwrap(); //! for c in store.iter_any() { //! println!("{:?}", c); //! } //! // Clear the store, and examine again //! store.clear(); //! println!("after clear"); //! for c in store.iter_any() { //! println!("{:?}", c); //! } //! } //! //! // Get some new cookies //! client.get("https://google.com").send().await.unwrap(); //! { //! // Write store back to disk //! let mut writer = std::fs::File::create("cookies2.json") //! .map(std::io::BufWriter::new) //! .unwrap(); //! let store = cookie_store.lock().unwrap(); //! store.save_json(&mut writer).unwrap(); //! } //! # }); //!``` use std::sync::{ LockResult, Mutex, MutexGuard, PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard, }; use bytes::Bytes; use reqwest::header::HeaderValue; use url; pub use cookie_store::{CookieStore, RawCookie, RawCookieParseError}; fn set_cookies( cookie_store: &mut CookieStore, cookie_headers: &mut dyn Iterator<Item = &HeaderValue>, url: &url::Url, ) { let cookies = cookie_headers.filter_map(|val| { std::str::from_utf8(val.as_bytes()) .map_err(RawCookieParseError::from) .and_then(RawCookie::parse) .map(|c| c.into_owned()) .ok() }); cookie_store.store_response_cookies(cookies, url); } fn cookies(cookie_store: &CookieStore, url: &url::Url) -> Option<HeaderValue> { let s = cookie_store .get_request_values(url) .map(|(name, value)| format!("{}={}", name, value)) .collect::<Vec<_>>() .join("; "); if s.is_empty() { return None; } HeaderValue::from_maybe_shared(Bytes::from(s)).ok() } /// A [`cookie_store::CookieStore`] wrapped internally by a [`std::sync::Mutex`], suitable for use in /// async/concurrent contexts. #[derive(Debug)] pub struct CookieStoreMutex(Mutex<CookieStore>); impl Default for CookieStoreMutex { /// Create a new, empty [`CookieStoreMutex`] fn default() -> Self { CookieStoreMutex::new(CookieStore::default()) } } impl CookieStoreMutex { /// Create a new [`CookieStoreMutex`] from an existing [`cookie_store::CookieStore`]. pub fn new(cookie_store: CookieStore) -> CookieStoreMutex { CookieStoreMutex(Mutex::new(cookie_store)) } /// Lock and get a handle to the contained [`cookie_store::CookieStore`]. pub fn lock( &self, ) -> Result<MutexGuard<'_, CookieStore>, PoisonError<MutexGuard<'_, CookieStore>>> { self.0.lock() } /// Consumes this [`CookieStoreMutex`], returning the underlying [`cookie_store::CookieStore`] pub fn into_inner(self) -> LockResult<CookieStore> { self.0.into_inner() } } impl reqwest::cookie::CookieStore for CookieStoreMutex { fn set_cookies(&self, cookie_headers: &mut dyn Iterator<Item = &HeaderValue>, url: &url::Url) { let mut store = self.0.lock().unwrap(); set_cookies(&mut store, cookie_headers, url); } fn cookies(&self, url: &url::Url) -> Option<HeaderValue> { let store = self.0.lock().unwrap(); cookies(&store, url) } } /// A [`cookie_store::CookieStore`] wrapped internally by a [`std::sync::RwLock`], suitable for use in /// async/concurrent contexts. #[derive(Debug)] pub struct CookieStoreRwLock(RwLock<CookieStore>); impl Default for CookieStoreRwLock { /// Create a new, empty [`CookieStoreRwLock`]. fn default() -> Self { CookieStoreRwLock::new(CookieStore::default()) } } impl CookieStoreRwLock { /// Create a new [`CookieStoreRwLock`] from an existing [`cookie_store::CookieStore`]. pub fn new(cookie_store: CookieStore) -> CookieStoreRwLock { CookieStoreRwLock(RwLock::new(cookie_store)) } /// Lock and get a read (non-exclusive) handle to the contained [`cookie_store::CookieStore`]. pub fn read( &self, ) -> Result<RwLockReadGuard<'_, CookieStore>, PoisonError<RwLockReadGuard<'_, CookieStore>>> { self.0.read() } /// Lock and get a write (exclusive) handle to the contained [`cookie_store::CookieStore`]. pub fn write( &self, ) -> Result<RwLockWriteGuard<'_, CookieStore>, PoisonError<RwLockWriteGuard<'_, CookieStore>>> { self.0.write() } /// Consume this [`CookieStoreRwLock`], returning the underlying [`cookie_store::CookieStore`] pub fn into_inner(self) -> LockResult<CookieStore> { self.0.into_inner() } } impl reqwest::cookie::CookieStore for CookieStoreRwLock { fn set_cookies(&self, cookie_headers: &mut dyn Iterator<Item = &HeaderValue>, url: &url::Url) { let mut write = self.0.write().unwrap(); set_cookies(&mut write, cookie_headers, url); } fn cookies(&self, url: &url::Url) -> Option<HeaderValue> { let read = self.0.read().unwrap(); cookies(&read, url) } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/egui_code_editor/src/highlighting.rs
crates/egui_code_editor/src/highlighting.rs
use super::syntax::{Syntax, TokenType, QUOTES, SEPARATORS}; use std::mem; #[derive(Default, Debug, PartialEq, PartialOrd, Eq, Ord)] /// Lexer and Token pub struct Token { ty: TokenType, buffer: String, } impl Token { pub fn new<S: Into<String>>(ty: TokenType, buffer: S) -> Self { Token { ty, buffer: buffer.into(), } } pub fn ty(&self) -> TokenType { self.ty } pub fn buffer(&self) -> &str { &self.buffer } fn first(&mut self, c: char, syntax: &Syntax) -> Option<Self> { self.buffer.push(c); let mut token = None; self.ty = match c { c if c.is_whitespace() => { self.ty = TokenType::Whitespace(c); token = self.drain(self.ty); TokenType::Whitespace(c) } c if syntax.is_keyword(c.to_string().as_str()) => TokenType::Keyword, c if syntax.is_type(c.to_string().as_str()) => TokenType::Type, c if syntax.is_special(c.to_string().as_str()) => TokenType::Special, c if syntax.comment == c.to_string().as_str() => TokenType::Comment(false), c if syntax.comment_multiline[0] == c.to_string().as_str() => TokenType::Comment(true), _ => TokenType::from(c), }; token } fn drain(&mut self, ty: TokenType) -> Option<Self> { let mut token = None; if !self.buffer().is_empty() { token = Some(Token { buffer: mem::take(&mut self.buffer), ty: self.ty, }); } self.ty = ty; token } fn push_drain(&mut self, c: char, ty: TokenType) -> Option<Self> { self.buffer.push(c); self.drain(ty) } fn drain_push(&mut self, c: char, ty: TokenType) -> Option<Self> { let token = self.drain(self.ty); self.buffer.push(c); self.ty = ty; token } #[cfg(feature = "egui")] /// Syntax highlighting pub fn highlight(&mut self, editor: &CodeEditor, text: &str) -> LayoutJob { *self = Token::default(); let mut job = LayoutJob::default(); for c in text.chars() { for token in self.automata(c, &editor.syntax) { editor.append(&mut job, &token); } } editor.append(&mut job, self); job } /// Lexer pub fn tokens(&mut self, syntax: &Syntax, text: &str) -> Vec<Self> { let mut tokens: Vec<Self> = text .chars() .flat_map(|c| self.automata(c, syntax)) .collect(); if !self.buffer.is_empty() { tokens.push(mem::take(self)); } tokens } fn automata(&mut self, c: char, syntax: &Syntax) -> Vec<Self> { use TokenType as Ty; let mut tokens = vec![]; match (self.ty, Ty::from(c)) { (Ty::Comment(false), Ty::Whitespace('\n')) => { self.buffer.push(c); let n = self.buffer.pop(); tokens.extend(self.drain(Ty::Whitespace(c))); if let Some(n) = n { tokens.extend(self.push_drain(n, self.ty)); } } (Ty::Comment(false), _) => { self.buffer.push(c); } (Ty::Comment(true), _) => { self.buffer.push(c); if self.buffer.ends_with(syntax.comment_multiline[1]) { tokens.extend(self.drain(Ty::Unknown)); } } (Ty::Literal | Ty::Punctuation(_), Ty::Whitespace(_)) => { tokens.extend(self.drain(Ty::Whitespace(c))); tokens.extend(self.first(c, syntax)); } (Ty::Hyperlink, Ty::Whitespace(_)) => { tokens.extend(self.drain(Ty::Whitespace(c))); tokens.extend(self.first(c, syntax)); } (Ty::Hyperlink, _) => { self.buffer.push(c); } (Ty::Literal, _) => match c { c if c == '(' => { self.ty = Ty::Function; tokens.extend(self.drain(Ty::Punctuation(c))); tokens.extend(self.push_drain(c, Ty::Unknown)); } c if !c.is_alphanumeric() && !SEPARATORS.contains(&c) => { tokens.extend(self.drain(self.ty)); self.buffer.push(c); self.ty = if QUOTES.contains(&c) { Ty::Str(c) } else { Ty::Punctuation(c) }; } _ => { self.buffer.push(c); self.ty = { if self.buffer.starts_with(syntax.comment) { Ty::Comment(false) } else if self.buffer.starts_with(syntax.comment_multiline[0]) { Ty::Comment(true) } else if syntax.is_hyperlink(&self.buffer) { Ty::Hyperlink } else if syntax.is_keyword(&self.buffer) { Ty::Keyword } else if syntax.is_type(&self.buffer) { Ty::Type } else if syntax.is_special(&self.buffer) { Ty::Special } else { Ty::Literal } }; } }, (Ty::Numeric(false), Ty::Punctuation('.')) => { self.buffer.push(c); self.ty = Ty::Numeric(true); } (Ty::Numeric(_), Ty::Numeric(_)) => { self.buffer.push(c); } (Ty::Numeric(_), Ty::Literal) => { tokens.extend(self.drain(self.ty)); self.buffer.push(c); } (Ty::Numeric(_), _) | (Ty::Punctuation(_), Ty::Literal | Ty::Numeric(_)) => { tokens.extend(self.drain(self.ty)); tokens.extend(self.first(c, syntax)); } (Ty::Punctuation(_), Ty::Str(_)) => { tokens.extend(self.drain_push(c, Ty::Str(c))); } (Ty::Punctuation(_), _) => { if !(syntax.comment.starts_with(&self.buffer) || syntax.comment_multiline[0].starts_with(&self.buffer)) { tokens.extend(self.drain(self.ty)); tokens.extend(self.first(c, syntax)); } else { self.buffer.push(c); if self.buffer.starts_with(syntax.comment) { self.ty = Ty::Comment(false); } else if self.buffer.starts_with(syntax.comment_multiline[0]) { self.ty = Ty::Comment(true); } else if let Some(c) = self.buffer.pop() { tokens.extend(self.drain(Ty::Punctuation(c))); tokens.extend(self.first(c, syntax)); } } } (Ty::Str(q), _) => { let control = self.buffer.ends_with('\\'); self.buffer.push(c); if c == q && !control { tokens.extend(self.drain(Ty::Unknown)); } } (Ty::Whitespace(_) | Ty::Unknown, _) => { tokens.extend(self.first(c, syntax)); } // Keyword, Type, Special (_reserved, Ty::Literal | Ty::Numeric(_)) => { self.buffer.push(c); self.ty = if syntax.is_keyword(&self.buffer) { Ty::Keyword } else if syntax.is_type(&self.buffer) { Ty::Type } else if syntax.is_special(&self.buffer) { Ty::Special } else { Ty::Literal }; } (reserved, _) => { self.ty = reserved; tokens.extend(self.drain(self.ty)); tokens.extend(self.first(c, syntax)); } } tokens } } #[cfg(feature = "egui")] use super::CodeEditor; #[cfg(feature = "egui")] use egui::text::LayoutJob; #[cfg(feature = "egui")] impl egui::util::cache::ComputerMut<(&CodeEditor, &str), LayoutJob> for Token { fn compute(&mut self, (cache, text): (&CodeEditor, &str)) -> LayoutJob { self.highlight(cache, text) } } #[cfg(feature = "egui")] pub type HighlightCache = egui::util::cache::FrameCache<LayoutJob, Token>; #[cfg(feature = "egui")] pub fn highlight(ctx: &egui::Context, cache: &CodeEditor, text: &str) -> LayoutJob { ctx.memory_mut(|mem| mem.caches.cache::<HighlightCache>().get((cache, text))) } #[cfg(feature = "egui")] impl CodeEditor { fn append(&self, job: &mut LayoutJob, token: &Token) { job.append(token.buffer(), 0.0, self.format(token.ty())); } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/egui_code_editor/src/lib.rs
crates/egui_code_editor/src/lib.rs
use std::collections::BTreeMap; use std::hash::{Hash, Hasher}; use egui::{Align, Area, Context, Event, EventFilter, Frame, Id, Key, Layout, Order, Pos2, pos2, Response, RichText, TextBuffer, Ui}; use egui::text::{CCursor, CCursorRange, CursorRange}; use egui::text_edit::TextEditState; #[cfg(feature = "egui")] use egui::widgets::text_edit::TextEditOutput; use serde::{Deserialize, Serialize}; #[cfg(feature = "egui")] use highlighting::highlight; pub use highlighting::Token; pub use syntax::{Syntax, TokenType}; pub use themes::ColorTheme; pub use themes::DEFAULT_THEMES; pub mod highlighting; mod syntax; #[cfg(test)] mod tests; mod themes; #[derive(Clone, Debug, PartialEq)] /// CodeEditor struct which stores settings for highlighting. pub struct CodeEditor { id: String, theme: ColorTheme, syntax: Syntax, numlines: bool, fontsize: f32, rows: usize, vscroll: bool, stick_to_bottom: bool, shrink: bool, _prompt: Prompt, _popup_id:Id, } #[derive(Clone, Debug, PartialEq, Default,Serialize,Deserialize)] pub struct Prompt { pub map: BTreeMap<String,PromptInfo> } #[derive(Clone, Debug, PartialEq, Default,Serialize,Deserialize)] pub struct PromptInfo{ pub desc:String, pub fill:String } impl Prompt{ pub fn from_str(text:&str) ->Self{ serde_yaml::from_str(text).unwrap_or_default() } } impl Hash for CodeEditor { fn hash<H: Hasher>(&self, state: &mut H) { self.theme.hash(state); #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] (self.fontsize as u32).hash(state); self.syntax.hash(state); } } impl Default for CodeEditor { fn default() -> CodeEditor { CodeEditor { id: String::from("Code Editor"), theme: ColorTheme::GRUVBOX, syntax: Syntax::rust(), numlines: true, fontsize: 10.0, rows: 10, vscroll: true, stick_to_bottom: false, shrink: false, _prompt: Prompt::default(), _popup_id: Id::new("code_editor_prompt"), } } } impl CodeEditor { pub fn id_source(self, id_source: impl Into<String>) -> Self { let id = id_source.into(); CodeEditor { id: id.clone(), _popup_id: Id::new(format!("{}_{}",id.clone(),"popup")), ..self } } /// Minimum number of rows to show. /// /// **Default: 10** pub fn with_rows(self, rows: usize) -> Self { CodeEditor { rows, ..self } } /// Use custom Color Theme /// /// **Default: Gruvbox** pub fn with_theme(self, theme: ColorTheme) -> Self { CodeEditor { theme, ..self } } /// Use custom font size /// /// **Default: 10.0** pub fn with_fontsize(self, fontsize: f32) -> Self { CodeEditor { fontsize, ..self } } #[cfg(feature = "egui")] /// Use UI font size pub fn with_ui_fontsize(self, ui: &mut egui::Ui) -> Self { CodeEditor { fontsize: egui::TextStyle::Monospace.resolve(ui.style()).size, ..self } } /// Show or hide lines numbering /// /// **Default: true** pub fn with_numlines(self, numlines: bool) -> Self { CodeEditor { numlines, ..self } } /// Use custom syntax for highlighting /// /// **Default: Rust** pub fn with_syntax(self, syntax: Syntax) -> Self { CodeEditor { syntax, ..self } } pub fn with_prompt(self, prompt: Prompt) -> Self { CodeEditor { _prompt: prompt, ..self } } /// Turn on/off scrolling on the vertical axis. /// /// **Default: true** pub fn vscroll(self, vscroll: bool) -> Self { CodeEditor { vscroll, ..self } } /// Should the containing area shrink if the content is small? /// /// **Default: false** pub fn auto_shrink(self, shrink: bool) -> Self { CodeEditor { shrink, ..self } } /// Stick to bottom /// The scroll handle will stick to the bottom position even while the content size /// changes dynamically. This can be useful to simulate terminal UIs or log/info scrollers. /// The scroll handle remains stuck until user manually changes position. Once "unstuck" /// it will remain focused on whatever content viewport the user left it on. If the scroll /// handle is dragged to the bottom it will again become stuck and remain there until manually /// pulled from the end position. /// /// **Default: false** pub fn stick_to_bottom(self, stick_to_bottom: bool) -> Self { CodeEditor { stick_to_bottom, ..self } } #[cfg(feature = "egui")] pub fn format(&self, ty: TokenType) -> egui::text::TextFormat { let font_id = egui::FontId::monospace(self.fontsize); let color = self.theme.type_color(ty); egui::text::TextFormat::simple(font_id, color) } #[cfg(feature = "egui")] fn numlines_show(&self, ui: &mut egui::Ui, text: &str) { let total = if text.ends_with('\n') || text.is_empty() { text.lines().count() + 1 } else { text.lines().count() } .max(self.rows); let max_indent = total.to_string().len(); let mut counter = (1..=total) .map(|i| { let label = i.to_string(); format!( "{}{label}", " ".repeat(max_indent.saturating_sub(label.len())) ) }) .collect::<Vec<String>>() .join("\n"); #[allow(clippy::cast_precision_loss)] let width = max_indent as f32 * self.fontsize * 0.5; let mut layouter = |ui: &egui::Ui, string: &str, _wrap_width: f32| { let layout_job = egui::text::LayoutJob::single_section( string.to_string(), egui::TextFormat::simple( egui::FontId::monospace(self.fontsize), self.theme.type_color(TokenType::Comment(true)), ), ); ui.fonts(|f| f.layout_job(layout_job)) }; ui.add( egui::TextEdit::multiline(&mut counter) .id_source(format!("{}_numlines", self.id)) .font(egui::TextStyle::Monospace) .interactive(false) .frame(false) .desired_rows(self.rows) .desired_width(width) .layouter(&mut layouter), ); } #[cfg(feature = "egui")] /// Show Code Editor pub fn show(&mut self, ui: &mut egui::Ui, text: &mut String) -> TextEditOutput { let mut need_insert_text = false; let mut need_up = false; let mut need_down = false; let mut is_pop = false; ui.ctx().memory(|mem|{ if mem.is_popup_open(self._popup_id) { is_pop = true; } }); if is_pop{ ui.input(|input_state|{ if input_state.key_released(Key::Tab)||input_state.key_pressed(Key::Enter) { need_insert_text = true; } if input_state.key_released(Key::ArrowUp){ need_up = true; } if input_state.key_released(Key::ArrowDown){ need_down = true; } }); if need_up{ let mut prompt_state = CodeEditorPromptState::load(ui.ctx(),self._popup_id); let mut index = 0; if prompt_state.index<=0{ index = prompt_state.prompts.len()-1; }else{ index = prompt_state.index-1; } prompt_state.index = index; prompt_state.select = prompt_state.prompts.get(index).cloned().unwrap_or_default(); prompt_state.store(ui.ctx(),self._popup_id); } if need_down{ let mut prompt_state = CodeEditorPromptState::load(ui.ctx(),self._popup_id); let mut index = prompt_state.index+1; if index>=prompt_state.prompts.len(){ index = 0; } prompt_state.index = index; prompt_state.select = prompt_state.prompts.get(index).cloned().unwrap_or_default(); prompt_state.store(ui.ctx(),self._popup_id); } ui.input_mut(|i|{ i.events.retain(|e|{ match e { Event::Key { key, .. } => { let k = key.clone(); if k==Key::ArrowUp||k==Key::ArrowDown||k==Key::Tab||k==Key::Enter{ return false } return true } _=>{ return true } } }) }); } let mut text_edit_output: Option<TextEditOutput> = None; let mut code_editor = |ui: &mut egui::Ui| { ui.horizontal_top(|h| { self.theme.modify_style(h, self.fontsize); if self.numlines { self.numlines_show(h, text); } egui::ScrollArea::horizontal() .id_source(format!("{}_inner_scroll", self.id)) .show(h, |ui| { let mut layouter = |ui: &egui::Ui, string: &str, _wrap_width: f32| { let layout_job = highlight(ui.ctx(), self, string); ui.fonts(|f| f.layout_job(layout_job)) }; let output = egui::TextEdit::multiline(text) .id_source(&self.id) .lock_focus(true) .desired_rows(self.rows) .frame(true) .desired_width(if self.shrink { 0.0 } else { f32::MAX }) .layouter(&mut layouter) .show(ui); self.popup(ui, text,&output); if need_insert_text { let prompt_state = CodeEditorPromptState::load(ui.ctx(),self._popup_id); let fill_text = self._prompt.map.get(prompt_state.select.as_str()).unwrap().fill.clone(); prompt_state.cursor_range.map(|c|{ text.insert_text( &fill_text[prompt_state.prompt.len()..].to_string(), c.primary.ccursor.index, ); ui.memory_mut(|mem| mem.toggle_popup(self._popup_id)); let mut tes = TextEditState::load(ui.ctx(), output.response.id).unwrap(); tes.cursor.set_char_range(Some(CCursorRange { primary: CCursor { index: c.primary.ccursor.index+fill_text.len()-prompt_state.prompt.len(), prefer_next_row: false, }, secondary: CCursor { index: c.primary.ccursor.index+fill_text.len()-prompt_state.prompt.len(), prefer_next_row: false, }, })); tes.store(ui.ctx(), output.response.id); ui.ctx().request_repaint(); }); } text_edit_output = Some(output); }); }); }; if self.vscroll { egui::ScrollArea::vertical() .id_source(format!("{}_outer_scroll", self.id)) .stick_to_bottom(self.stick_to_bottom) .show(ui, code_editor); } else { code_editor(ui); } text_edit_output.expect("TextEditOutput should exist at this point") } fn popup(&self, ui: &mut Ui, text: &mut String, output:&TextEditOutput) { output.cursor_range.map(|c| { let len = text.as_str().len(); if len <= 1 || c.primary.ccursor.index > len { return; } let before_cursor_text: String = text .as_str() .chars() .take(c.primary.ccursor.index) .collect(); let mut after_cursor_text: String = text.as_str().chars().skip(c.primary.ccursor.index).collect(); after_cursor_text = after_cursor_text.replace("\n"," ") .replace(","," ") .replace("\t"," ").replace(";"," "); if !after_cursor_text.starts_with(" ")&&!after_cursor_text.is_empty(){ ui.memory_mut(|mem| { if mem.is_popup_open(self._popup_id) { mem.close_popup() } }); return; } let (prompt,prompts) = self.find_prompt(before_cursor_text); if prompts.len()>0 { ui.memory_mut(|mem| { mem.open_popup(self._popup_id) }); self.popup_prompt_widget( ui, pos2( output.galley_pos.x + (c.primary.rcursor.column as f32) * (12.0 / 2.0 + 1.0), output.galley_pos.y + (c.primary.rcursor.row as f32) * (12.0 / 2.0 + 1.0) + 16.0, ), |ui| { self.render_popup_prompt(c, prompt, prompts, ui) }, ); }else{ ui.memory_mut(|mem| { if mem.is_popup_open(self._popup_id) { mem.close_popup() } }); } }); } fn render_popup_prompt( &self, c: CursorRange, prompt: String, prompts: Vec<String>, ui: &mut Ui, ) { let mut prompt_state = CodeEditorPromptState::load(ui.ctx(),self._popup_id); ui.horizontal(|ui| { let scroll = egui::ScrollArea::vertical() .max_width(150.0) .min_scrolled_height(150.0) .max_height(400.0); scroll.show(ui, |ui| { ui.vertical(|ui| { let mut not_found = false; if prompts.iter().find(|key|{ key.as_str()==prompt_state.select }).is_none(){ not_found = true; } for (index, key) in prompts.iter().enumerate() { let show_text = key.split(".").last().unwrap_or_default(); let label = ui.selectable_value(&mut prompt_state.select ,key.to_string(),RichText::new(show_text).strong()); if index == 0 { if not_found{ prompt_state.select = key.to_string(); prompt_state.index = 0; } } if index==prompt_state.index{ label.scroll_to_me(Some(Align::Center)); } } let new_prompt_state = CodeEditorPromptState{ prompts:prompts.clone(), select:prompt_state.select.clone(), index:prompts.iter().position(|x|x.as_str()==prompt_state.select.as_str()).unwrap(), prompt:prompt.clone(), cursor_range: Some(c.clone()), }; new_prompt_state.store(ui.ctx(),self._popup_id); }); }); ui.separator(); ui.vertical(|ui| { let prompt_state = CodeEditorPromptState::load(ui.ctx(),self._popup_id); ui.heading(prompt_state.select.as_str()); ui.horizontal_wrapped(|ui|{ ui.strong(self._prompt.map.get(prompt_state.select.as_str()).cloned().unwrap_or_default().desc) }); }); }); } fn popup_prompt_widget<R>( &self, ui: &Ui, suggested_position: Pos2, add_contents: impl FnOnce(&mut Ui) -> R, ) -> Option<R> { if ui.memory(|mem| mem.is_popup_open(self._popup_id)) { let inner = Area::new(self._popup_id) .order(Order::Foreground) .constrain(true) .fixed_pos(suggested_position) .show(ui.ctx(), |ui| { let frame = Frame::popup(ui.style()); frame .show(ui, |ui| { ui.with_layout(Layout::left_to_right(Align::LEFT), |ui| add_contents(ui)) .inner }) .inner }) .inner; Some(inner) } else { None } } fn count_dots(sentence: &str) -> usize { let dot: char = '.'; sentence.chars().filter(|&c| c == dot).count() } fn find_prompt(&self,text:String)->(String,Vec<String>){ let mut replace = text .replace("{"," ") .replace("}"," ") .replace(";"," ") .replace(","," ") .replace("\t"," ") .replace("\n"," "); if text.ends_with("("){ replace = replace.replace("("," "); } let sentence = replace.split(" ").last().unwrap_or_default(); if sentence.is_empty(){ return ("".to_string(),vec![]) } let dot_count = Self::count_dots(sentence); (sentence.to_string(), self._prompt.map.keys().filter(|(k)|{ k.starts_with(sentence)&&k.as_str()!= sentence }).filter(|(k)|{ Self::count_dots(k)==dot_count }).cloned().collect()) } } #[derive(Clone, Default, Serialize, Deserialize, Debug)] struct CodeEditorPromptState { pub select: String, pub prompt: String, pub prompts:Vec<String>, pub index: usize, pub cursor_range:Option<CursorRange> } impl CodeEditorPromptState { pub fn load(ctx: &Context, id: Id) -> Self { ctx.data_mut(|d| d.get_persisted(id)).unwrap_or_default() } pub fn store(self, ctx: &Context, id: Id) { ctx.data_mut(|d| d.insert_persisted(id, self)); } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/egui_code_editor/src/tests.rs
crates/egui_code_editor/src/tests.rs
use super::*; #[test] fn numeric_float() { assert_eq!( Token::default().tokens(&Syntax::default(), "3.14"), [Token::new(TokenType::Numeric(true), "3.14")] ); } #[test] fn numeric_float_desription() { assert_eq!( Token::default().tokens(&Syntax::default(), "3.14_f32"), [ Token::new(TokenType::Numeric(true), "3.14"), Token::new(TokenType::Numeric(true), "_"), Token::new(TokenType::Numeric(true), "f32") ] ); } #[test] fn numeric_float_second_dot() { assert_eq!( Token::default().tokens(&Syntax::default(), "3.14.032"), [ Token::new(TokenType::Numeric(true), "3.14"), Token::new(TokenType::Punctuation('.'), "."), Token::new(TokenType::Numeric(false), "032") ] ); } #[test] fn simple_rust() { let syntax = Syntax::rust(); let input = vec![ Token::new(TokenType::Keyword, "fn"), Token::new(TokenType::Whitespace(' '), " "), Token::new(TokenType::Function, "function"), Token::new(TokenType::Punctuation('('), "("), Token::new(TokenType::Str('\"'), "\"String\""), Token::new(TokenType::Punctuation(')'), ")"), Token::new(TokenType::Punctuation('{'), "{"), Token::new(TokenType::Whitespace('\n'), "\n"), Token::new(TokenType::Whitespace('\t'), "\t"), Token::new(TokenType::Keyword, "let"), Token::new(TokenType::Whitespace(' '), " "), Token::new(TokenType::Literal, "x_0"), Token::new(TokenType::Punctuation(':'), ":"), Token::new(TokenType::Whitespace(' '), " "), Token::new(TokenType::Type, "f32"), Token::new(TokenType::Whitespace(' '), " "), Token::new(TokenType::Punctuation('='), "="), Token::new(TokenType::Numeric(true), "13.34"), Token::new(TokenType::Punctuation(';'), ";"), Token::new(TokenType::Whitespace('\n'), "\n"), Token::new(TokenType::Punctuation('}'), "}"), ]; let str = input.iter().map(|h| h.buffer()).collect::<String>(); let output = Token::default().tokens(&syntax, &str); println!("{str}"); assert_eq!(input, output); }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/egui_code_editor/src/themes/sonokai.rs
crates/egui_code_editor/src/themes/sonokai.rs
use super::ColorTheme; impl ColorTheme { /// Original Author: sainnhe <https://github.com/sainnhe/sonokai> /// Modified by p4ymak <https://github.com/p4ymak> pub const SONOKAI: ColorTheme = ColorTheme { name: "Sonokai", dark: true, bg: "#2c2e34", // bg0 cursor: "#76cce0", // blue selection: "#444852", // bg5 comments: "#7f8490", // gray functions: "#9ed072", // green keywords: "#fc5d7c", // red literals: "#e2e2e3", // foreground numerics: "#b39df3", // purple punctuation: "#7f8490", // gray strs: "#e7c664", // yellow types: "#399ee6", // blue special: "#f39660", // orange }; }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/egui_code_editor/src/themes/gruvbox.rs
crates/egui_code_editor/src/themes/gruvbox.rs
use super::ColorTheme; impl ColorTheme { /// Author : Jakub Bartodziej <kubabartodziej@gmail.com> /// Theme uses the gruvbox dark palette with standard contrast <https://github.com/morhetz/gruvbox> pub const GRUVBOX: ColorTheme = ColorTheme { name: "Gruvbox", dark: true, bg: "#282828", cursor: "#a89984", // fg4 selection: "#504945", // bg2 comments: "#928374", // gray1 functions: "#b8bb26", // green1 keywords: "#fb4934", // red1 literals: "#ebdbb2", // fg1 numerics: "#d3869b", // purple1 punctuation: "#fe8019", // orange1 strs: "#8ec07c", // aqua1 types: "#fabd2f", // yellow1 special: "#83a598", // blue1 }; pub const GRUVBOX_DARK: ColorTheme = ColorTheme::GRUVBOX; pub const GRUVBOX_LIGHT: ColorTheme = ColorTheme { name: "Gruvbox Light", dark: false, bg: "#fbf1c7", cursor: "#7c6f64", // fg4 selection: "#b57614", // yellow1 comments: "#7c6f64", // gray1 functions: "#79740e", // green1 keywords: "#9d0006", // red1 literals: "#282828", // fg1 numerics: "#8f3f71", // purple1 punctuation: "#af3a03", // orange1 strs: "#427b58", // aqua1 types: "#b57614", // yellow1 special: "#af3a03", // orange1 }; }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/egui_code_editor/src/themes/mod.rs
crates/egui_code_editor/src/themes/mod.rs
#![allow(dead_code)] pub mod ayu; pub mod github; pub mod gruvbox; pub mod sonokai; use super::syntax::TokenType; #[cfg(feature = "egui")] use egui::Color32; #[cfg(feature = "egui")] pub const ERROR_COLOR: Color32 = Color32::from_rgb(255, 0, 255); /// Array of default themes. pub const DEFAULT_THEMES: [ColorTheme; 8] = [ ColorTheme::AYU, ColorTheme::AYU_MIRAGE, ColorTheme::AYU_DARK, ColorTheme::GITHUB_DARK, ColorTheme::GITHUB_LIGHT, ColorTheme::GRUVBOX, ColorTheme::GRUVBOX_LIGHT, ColorTheme::SONOKAI, ]; #[cfg(feature = "egui")] fn color_from_hex(hex: &str) -> Option<Color32> { if hex == "none" { return Some(Color32::from_rgba_premultiplied(255, 0, 255, 0)); } let rgb = (1..hex.len()) .step_by(2) .filter_map(|i| u8::from_str_radix(&hex[i..i + 2], 16).ok()) .collect::<Vec<u8>>(); let color = Color32::from_rgb(*rgb.first()?, *rgb.get(1)?, *rgb.get(2)?); Some(color) } #[derive(Hash, Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] /// Colors in hexadecimal notation as used in HTML and CSS. pub struct ColorTheme { pub name: &'static str, pub dark: bool, pub bg: &'static str, pub cursor: &'static str, pub selection: &'static str, pub comments: &'static str, pub functions: &'static str, pub keywords: &'static str, pub literals: &'static str, pub numerics: &'static str, pub punctuation: &'static str, pub strs: &'static str, pub types: &'static str, pub special: &'static str, } impl Default for ColorTheme { fn default() -> Self { ColorTheme::GRUVBOX } } impl ColorTheme { pub fn name(&self) -> &str { self.name } pub fn is_dark(&self) -> bool { self.dark } #[cfg(feature = "egui")] pub fn bg(&self) -> Color32 { color_from_hex(self.bg).unwrap_or(ERROR_COLOR) } #[cfg(feature = "egui")] pub fn cursor(&self) -> Color32 { color_from_hex(self.cursor).unwrap_or(ERROR_COLOR) } #[cfg(feature = "egui")] pub fn selection(&self) -> Color32 { color_from_hex(self.selection).unwrap_or(ERROR_COLOR) } #[cfg(feature = "egui")] pub fn modify_style(&self, ui: &mut egui::Ui, fontsize: f32) { let style = ui.style_mut(); style.visuals.widgets.noninteractive.bg_fill = self.bg(); style.visuals.window_fill = self.bg(); style.visuals.selection.stroke.color = self.cursor(); style.visuals.selection.bg_fill = self.selection(); style.visuals.extreme_bg_color = self.bg(); style.override_font_id = Some(egui::FontId::monospace(fontsize)); style.visuals.text_cursor.width = fontsize * 0.1; } pub const fn type_color_str(&self, ty: TokenType) -> &'static str { match ty { TokenType::Comment(_) => self.comments, TokenType::Function => self.functions, TokenType::Keyword => self.keywords, TokenType::Literal => self.literals, TokenType::Hyperlink => self.special, TokenType::Numeric(_) => self.numerics, TokenType::Punctuation(_) => self.punctuation, TokenType::Special => self.special, TokenType::Str(_) => self.strs, TokenType::Type => self.types, TokenType::Whitespace(_) | TokenType::Unknown => self.comments, } } #[cfg(feature = "egui")] pub fn type_color(&self, ty: TokenType) -> Color32 { match ty { TokenType::Comment(_) => color_from_hex(self.comments), TokenType::Function => color_from_hex(self.functions), TokenType::Keyword => color_from_hex(self.keywords), TokenType::Literal => color_from_hex(self.literals), TokenType::Hyperlink => color_from_hex(self.special), TokenType::Numeric(_) => color_from_hex(self.numerics), TokenType::Punctuation(_) => color_from_hex(self.punctuation), TokenType::Special => color_from_hex(self.special), TokenType::Str(_) => color_from_hex(self.strs), TokenType::Type => color_from_hex(self.types), TokenType::Whitespace(_) | TokenType::Unknown => color_from_hex(self.comments), } .unwrap_or(ERROR_COLOR) } pub fn monocolor( dark: bool, bg: &'static str, fg: &'static str, cursor: &'static str, selection: &'static str, ) -> Self { ColorTheme { name: "monocolor", dark, bg, cursor, selection, literals: fg, numerics: fg, keywords: fg, functions: fg, punctuation: fg, types: fg, strs: fg, comments: fg, special: fg, } } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/egui_code_editor/src/themes/ayu.rs
crates/egui_code_editor/src/themes/ayu.rs
use super::ColorTheme; impl ColorTheme { /// Author: André Sá <enkodr@outlook.com> /// /// Based on the AYU theme colors from <https://github.com/dempfi/ayu> pub const AYU: ColorTheme = ColorTheme { name: "Ayu", dark: false, bg: "#fafafa", cursor: "#5c6166", // foreground selection: "#fa8d3e", // orange comments: "#828c9a", // gray functions: "#ffaa33", // yellow keywords: "#fa8d3e", // orange literals: "#5c6166", // foreground numerics: "#a37acc", // magenta punctuation: "#5c6166", // foreground strs: "#86b300", // green types: "#399ee6", // blue special: "#f07171", // red }; pub const AYU_MIRAGE: ColorTheme = ColorTheme { name: "Ayu Mirage", dark: true, bg: "#1f2430", cursor: "#cccac2", // foreground selection: "#ffad66", // orange comments: "#565b66", // gray functions: "#ffcc77", // yellow keywords: "#ffad66", // orange literals: "#cccac2", // foreground numerics: "#dfbfff", // magenta punctuation: "#cccac2", // foreground strs: "#d5ff80", // green types: "#73d0ff", // blue special: "#f28779", // red }; pub const AYU_DARK: ColorTheme = ColorTheme { name: "Ayu Dark", dark: true, bg: "#0f1419", cursor: "#bfbdb6", // foreground selection: "#ffad66", // orange comments: "#5c6773", // gray functions: "#e6b450", // yellow keywords: "#ffad66", // orange literals: "#bfbdb6", // foreground numerics: "#dfbfff", // magenta punctuation: "#bfbdb6", // foreground strs: "#aad94c", // green types: "#59c2ff", // blue special: "#f28779", // red }; }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/egui_code_editor/src/themes/github.rs
crates/egui_code_editor/src/themes/github.rs
use super::ColorTheme; impl ColorTheme { /// Author : OwOSwordsman <owoswordsman@gmail.com> /// An unofficial GitHub theme, generated using colors from: <https://primer.style/primitives/colors> pub const GITHUB_DARK: ColorTheme = ColorTheme { name: "Github Dark", dark: true, bg: "#0d1117", // default cursor: "#d29922", // attention.fg selection: "#0c2d6b", // scale.blue.8 comments: "#8b949e", // fg.muted functions: "#d2a8ff", // scale.purple.2 keywords: "#ff7b72", // scale.red.3 literals: "#c9d1d9", // fg.default numerics: "#79c0ff", // scale.blue.2 punctuation: "#c9d1d9", // fg.default strs: "#a5d6ff", // scale.blue.1 types: "#ffa657", // scale.orange.2 special: "#a5d6ff", // scale.blue.1 }; pub const GITHUB_LIGHT: ColorTheme = ColorTheme { name: "Github Light", dark: false, bg: "#ffffff", // default cursor: "#000000", // invert selection: "#0550ae", // scale.blue.6 comments: "#57606a", // fg.muted functions: "#8250df", // done.fg keywords: "#cf222e", // scale.red.5 literals: "#24292f", // fg.default numerics: "#0550ae", // scale.blue.6 punctuation: "#24292f", // fg.default strs: "#0a3069", // scale.blue.8 types: "#953800", // scale.orange.6 special: "#a475f9", // scale.purple.4 }; }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/egui_code_editor/src/syntax/rust.rs
crates/egui_code_editor/src/syntax/rust.rs
use super::Syntax; use std::collections::BTreeSet; impl Syntax { pub fn rust() -> Self { Syntax { language: "Rust", case_sensitive: true, comment: "//", comment_multiline: ["/*", "*/"], hyperlinks: BTreeSet::from(["http"]), keywords: BTreeSet::from([ "as", "break", "const", "continue", "crate", "else", "enum", "extern", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref", "return", "self", "struct", "super", "trait", "type", "use", "where", "while", "async", "await", "abstract", "become", "box", "do", "final", "macro", "override", "priv", "typeof", "unsized", "virtual", "yield", "try", "unsafe", "dyn", ]), types: BTreeSet::from([ "Option", "Result", "Error", "Box", "Cow", // Primitives "bool", "i8", "u8", "i16", "u16", "i32", "u32", "i64", "u64", "i128", "u128", "isize", "usize", "f32", "f64", "char", "str", "String", // STD Collections "Vec", "BTreeMap", "BTreeSet", "BTreeMap", "BTreeSet", "VecDeque", "BinaryHeap", "LinkedList", // RC "Rc", "Weak", "LazyCell", "SyncUnsafeCell", "BorrowErrorl", "BorrowMutErrorl", "Celll", "OnceCelll", "Refl", "RefCelll", "RefMutl", "UnsafeCell", "Exclusive", "LazyLock", // ARC "Arc", "Barrier", "BarrierWaitResult", "Condvar", "Mutex", "MutexGuard", "Once", "OnceLock", "OnceState", "PoisonError", "RwLock", "RwLockReadGuard", "RwLockWriteGuard", "WaitTimeoutResult", "Weak", ]), special: BTreeSet::from(["Self", "static", "true", "false"]), } } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/egui_code_editor/src/syntax/asm.rs
crates/egui_code_editor/src/syntax/asm.rs
use super::Syntax; use std::collections::BTreeSet; impl Syntax { pub fn asm() -> Self { Syntax { language: "Assembly", case_sensitive: false, comment: ";", comment_multiline: ["/*", "*/"], hyperlinks: BTreeSet::from(["http"]), keywords: BTreeSet::from([ "vaddpd", "divsd", "vrcp14ps", "haddps", "outsd", "scasw", "vaesenclast", "pcmpgtq", "popcnt", "lodsw", "int", "vbroadcasti64x4", "rdpmc", "prefetcht0", "setnp", "cvtpi2pd", "cvtsd2si", "vbroadcastf64x2", "vscalefps", "vfnmadd132sd", "vpminuq", "vfixupimmps", "vcvtss2sd", "vpminud", "vfnmsub213sd", "kshiftrb", "vfpclassss", "vaddsubpd", "sar", "vfnmadd231ss", "monitor", "vgatherqps", "vmovdqu32", "vpmovm2d", "vprolvd", "vpgatherdq", "setae", "aas", "iret", "vpsllw", "vfmsub213pd", "rcl", "pavgw", "vpsrlvw", "vpandd", "lldt", "vcvtps2pd", "vpabsw", "vpmovzxbw", "pmaxub", "vpmovq2m", "vpconflictd", "jz", "vcvtph2ps", "vfmsub132ps", "vpunpcklbw", "vrsqrt28ss", "movmskpd", "fucompp", "vpmulhuw", "minpd", "vpermi2ps", "fninit1", "pmaxsw", "movntdq", "vfnmsub231pd", "vexpandpd", "vsqrtss", "setpe", "vpgatherqq", "vp4dpwssds", "mul", "fprem1", "vcvtph2psx", "cbw", "minps", "imm8", "vpermt2w", "addsubpd", "kandnb", "vpbroadcastd", "vsubss", "vpaddw", "setnb", "sha256rnds2", "vmulss", "vmovddup", "movups", "movupd", "vfnmadd231sd", "jnae", "pblendvb", "fdivr", "psignw", "packusdw", "test", "ib", "scas", "kaddd", "vmovhps", "movnti", "paddsw", "ib1", "fld", "pand", "fldln2", "hlt", "rol", "getsec", "vpcmpeqq", "pmullw", "emms", "vhsubpd", "movsx", "movapd", "vpmaxuw", "vpdpbusds", "pcmpeqb", "nop", "vmovlpd", "fdiv", "divpd", "vmovntdqa", "mulss", "jne", "finit", "packsswb", "vrcpps", "sha1nexte", "vmulpd", "pminud", "subss", "cmovnge", "vpsubw", "cvtpd2dq", "or", "rsqrtss", "vpsubq", "vpshldvd", "cvtdq2ps", "vpcmpgtw", "vpacksswb", "setp", "xor", "cvtpd2pi", "movdiri", "vpmullw", "vpmovsdw", "vxorps", "vpmulhrsw", "rdpkru", "rcpps", "vpminsb", "vrcp28pd", "jpe", "fcomp", "vpmaxsb", "cvtps2pd", "vandnpd", "vmulps", "vphaddsw", "blendvps", "kshiftrd", "vfnmadd213ss", "vhaddpd", "aam", "cmovnbe", "wbinvd", "paddusw", "vcvtpd2udq", "setnbe", "kortestb", "vmovdqu64", "minss", "vplzcntd", "vpmovusdw", "pmovzxdq", "punpckhdq", "vpunpckhwd", "stos", "cmove", "ltr", "fsubr", "vpblendmq", "setnz", "setle", "pminsb", "kortestq", "vpbroadcastw", "vpminub", "punpckhwd", "fcmovbe", "cqo", "vpermilpd", "sete", "vpunpcklqdq", "fimul", "sets", "movdqa", "vorpd", "rcpss", "cmovns", "vunpcklpd", "idiv", "pxor", "fcmove", "pmovzxbw", "kxnorb", "pmovmskb", "xorps", "fist", "hsubpd", "cmpxchg", "vmaskmovps", "movntps", "pmaxuw", "jl", "vfmadd231ps", "vpmovsxbq", "pcmpgtd", "in", "vpcmpgtq", "vpmaddwd", "je", "kortestw", "vpexpandq", "jnz", "pcmpgtw", "kmovb", "prefetchnta", "lsl", "vmaxpd", "lodsb", "kunpckdq", "vpmuludq", "vrsqrtps", "vpmaxuq", "comiss", "vpxor", "unpckhpd", "jo", "vpsravw", "pmuldq", "shlx", "vfmaddsub213pd", "fclex", "v4fmaddps", "vpsubd", "vbroadcastf128", "vcvtsd2usi", "vcompressps", "cmovc", "vp2intersectq", "vpblendmd", "fucomp", "vrcp28sd", "vfmsubadd132ps", "popf", "cvtss2si", "cvttsd2si", "pmaxsd", "vrsqrt14ps", "cvttps2dq", "vpsignb", "vmovhpd", "vpexpandd", "fisttp", "vunpcklps", "pext", "lzcnt", "cvtdq2pd", "psubw", "cvtsi2sd", "pmovzxbq", "pcmpeqd", "vfmsub132pd", "movmskps", "fnclex1", "vpmovm2q", "cdq", "bndcl", "psadbw", "cld", "vpcompressq", "fucomip", "vcvttpd2dq", "/is4", "vpgatherqd", "vaesenc", "vmovmskps", "vpmovsxbd", "vpermi2q", "vpmaxsq", "addss", "ib", "vbroadcastf32x4", "imul", "vdivss", "fisub", "aesdeclast", "cmovle", "paddb", "pmaxsb", "vfnmsub213ps", "vpermt2q", "vandpd", "vandps", "vpmadd52huq", "jc", "kshiftrq", "clc", "pminub", "vcvtps2udq", "vpcompressb", "vpcompressw", "vfmsubadd231pd", "setnl", "vfmsub231ss", "vfnmsub132pd", "subpd", "vpmovsqb", "kord", "invd", "pushad", "cmovge", "vaesdec", "les", "vexp2ps", "prefetcht1", "pmulld", "vpmovm2w", "vpmovusqb", "vrangess", "rcr", "fsubp", "sha256msg1", "vfnmadd132ss", "jrcxz", "vsqrtsd", "vpmovdb", "kaddq", "vscalefss", "paddq", "bndmov", "pmovsxbd", "psrlq", "fldl2t", "vcvtqq2ps", "vfmsub213sd", "blendvpd", "pmulhrsw", "subps", "vpermilps", "pop", "vpabsb", "vdivpd", "loop", "adc", "vmovaps", "outsb", "sha1msg2", "vrsqrtss", "vpmovusdb", "vpavgw", "jp", "fcmovb", "addps", "addpd", "kshiftld", "pabsd", "vpavgb", "por", "punpckldq", "vfmadd132ps", "vbroadcasti32x8", "div", "popfd", "setns", "jno", "vmovss", "tzcnt", "cmovpe", "vpackuswb", "js", "vptestnmb", "punpcklqdq", "vpsubsb", "vmulsd", "vfmsubadd213pd", "vpmovd2m", "kxorb", "vpmovuswb", "vpsignd", "vfnmsub213pd", "pdep", "vpdpwssds", "kxorq", "vcvtdq2ps", "vrsqrt28sd", "btr", "movs", "kxnord", "korb", "pmovsxwq", "movlps", "sha256msg2", "vptestmw", "vmovd", "vcvttss2usi", "movddup", "sysenter", "vbroadcastf32x8", "lds", "vrcp14pd", "vucomiss", "vpaddusb", "vfmaddsub132pd", "comisd", "cvttpd2dq", "fprem", "vpmadd52luq", "vexp2pd", "kxord", "kunpckwd", "scasd", "psllw", "ja", "jnc", "vmovshdup", "stosw", "vcvttsd2usi", "v4fnmaddps", "vtestps", "paddw", "movlhps", "phsubw", "vphminposuw", "vpmovzxwq", "vrsqrt28ps", "vrsqrt14ss", "vcvtdq2pd", "vpsignw", "vpsadbw", "vhaddps", "vplzcntq", "bextr", "lgdt", "psubusw", "vpminsd", "vpermq", "lidt", "swapgs", "invpcid", "psignb", "vptest", "vpshldvq", "fidiv", "vpmaxsw", "fldpi", "aad", "vfmadd132ss", "kandnq", "vbroadcastsd", "vfnmsub213ss", "sbb", "cmovo", "aesdec", "cmps", "outs", "vcvttpd2qq", "lgs", "fcomip", "cmovna", "jnge", "cvtsi2ss", "lods", "cmpsq", "pmovsxbw", "pmuludq", "vpxord", "gf2p8mulb", "not", "vmovsd", "vpord", "vpunpckldq", "vcvttps2uqq", "vfmsubadd231ps", "fnsave1", "vgetexpps", "cmovno", "vmovdqu8", "ktestb", "vaddsubps", "vporq", "vmaxsd", "vpsubusb", "pabsb", "pmovsxbq", "cvtps2pi", "vpsraw", "setnge", "vorps", "vcvttps2qq", "vpcmpeqd", "vfnmadd132ps", "pmaddubsw", "vbroadcastss", "vpsrlvq", "vpsraq", "ud2", "vmovdqu16", "sub", "wrmsr", "vpsllvq", "cvttss2si", "wait", "psubsw", "cvtpd2ps", "daa", "movzx", "fidivr", "fisubr", "fucomi", "packuswb", "vaddps", "maskmovdqu", "pmaddwd", "pminuw", "vpunpckhdq", "fyl2xp1", "kxnorq", "movntdqa", "vexpandps", "vfnmsub132sd", "vcvtps2phx", "jnle", "bound", "movntpd", "vpdpwssd", "pmovsxdq", "vptestnmd", "mulps", "ktestw", "faddp", "vlddqu", "paddsb", "vdivsd", "paddd", "vpmovwb", "cmovl", "movshdup", "ror", "vfnmadd231pd", "vp2intersectd", "cmovae", "vsubps", "vpaddd", "vpandn", "vrsqrt14sd", "psubb", "fcmovnb", "iretq", "vblendmps", "cwd", "cpuid", "vpsravq", "vptestmb", "bzhi", "vfmsub213ss", "fstp", "vbroadcasti128", "kmovq", "vpabsd", "psignd", "vcvtudq2pd", "vpermt2d", "vscalefsd", "arpl", "vpcmpgtd", "cmpsb", "vbroadcastf64x4", "kshiftlw", "lodsd", "vpmovswb", "vminss", "vphaddw", "vmovdqa64", "fsave", "vrcp28ps", "vfmadd231ss", "vxorpd", "vscalefpd", "kortestd", "phaddsw", "vpshufbitqmb", "andnps", "vcvtsi2ss", "fnstenv1", "lmsw", "lodsq", "vmovlps", "vpcmpeqw", "dec", "kshiftrw", "vpermt2pd", "vpsrlvd", "fldl2e", "setb", "vmovmskpd", "vpsllvd", "vmovdqa", "bswap", "vpermw", "setbe", "movlpd", "vcvtusi2ss", "jecxz", "shr", "vfmsub213ps", "bts", "fwait", "vphsubw", "bsr", "vpermi2w", "vpermps", "scasq", "vfnmadd132pd", "cmpsd", "orpd", "aaa", "andps", "knotd", "vpmulhw", "vunpckhps", "pslld", "ktestq", "pushf", "sti", "32", "jcxz", "unpcklpd", "vpaddq", "vbroadcastf32x2", "vpmaskmovq", "bndcn", "vpsravd", "xorpd", "vpbroadcastq", "aesimc", "knotb", "mulpd", "vpmovsxwd", "sldt", "xsetbv", "movsw", "fsub", "cvtpi2ps", "vmovntpd", "sqrtpd", "vaesimc", "bndmk", "kshiftlq", "maxpd", "vpminsw", "psrad", "ficom", "vtestpd", "xlatb", "vcvtsi2sd", "vpackssdw", "kandb", "shrx", "vpabsq", "vrcpss", "knotq", "movsd", "pmovsxwd", "maxsd", "mwait", "enter", "vpconflictq", "vcvtps2uqq", "vprorvq", "cmovnc", "phaddd", "sysexit", "vgetexpsd", "movsq", "vptestmq", "pcmpeqw", "vrcp28ss", "vmovupd", "fbld", "vbroadcasti64x2", "insw", "vpshrdvq", "vpbroadcastb", "pcmpgtb", "kandd", "ins", "vpsllvw", "vfmadd213ss", "vpcmpgtb", "vfmsub231ps", "pusha", "fsubrp", "setz", "fsincos", "vcvtpd2uqq", "vpexpandw", "vpandnd", "cmpsw", "rdtsc", "mov", "vpblendmb", "vpcompressd", "vpmovusqd", "outsw", "jng", "fild", "vcvtss2si", "vpermi2d", "sahf", "cli", "cvtps2dq", "fdivrp", "lar", "setnle", "vcvtsd2si", "vminps", "psubd", "sqrtsd", "vsubpd", "fcom", "vcomisd", "inc", "vpdpbusd", "vcvtuqq2ps", "cvttps2pi", "vblendmpd", "movsxd", "vunpckhpd", "pmovzxbd", "vpmovqw", "seta", "psraw", "kmovd", "vfmadd213pd", "vpaddsb", "vgatherqpd", "bndcu", "vpsubusw", "smsw", "vpbroadcastmw2d", "fptan", "fmul", "phsubd", "vpmovzxbd", "vandnps", "vpandq", "vcvttpd2udq", "movdq2q", "setge", "vhsubps", "vfmsubadd213ps", "vpmovsxdq", "vfmadd213sd", "into", "vfmsubadd132pd", "pmulhuw", "fiadd", "setpo", "vpopcntw", "cmovb", "psrlw", "vpermd", "vcvttsd2si", "vpmovsxwq", "fstenv", "sha1msg1", "vmovups", "vfnmadd213ps", "vpslld", "vpaddusw", "crc32", "vfmadd213ps", "vpermpd", "pavgb", "mulx", "ret", "vpopcntb", "jbe", "vfmadd132pd", "int1", "vfmadd231pd", "movsldup", "vcvtss2usi", "psubq", "setg", "vpunpcklwd", "repe", "std", "vpmullq", "scasb", "setne", "maxps", "pminsw", "cmovnp", "bndstx", "vpmovsqw", "fyl2x", "adox", "jnb", "pmaxud", "punpckhqdq", "cwde", "ibvpermilps", "jnbe", "cvtsd2ss", "vfnmsub231ps", "adcx", "btc", "vphaddd", "sfence", "movntq", "jb", "vpsllq", "popfq", "vptestnmq", "vpmovb2m", "vrsqrt14pd", "vfmaddsub213ps", "vdivps", "andnpd", "vcvtpd2ps", "vfmaddsub132ps", "vcvtne2ps2bf16", "movdir64b", "vpandnq", "sqrtps", "pcmpeqq", "vpshrdvd", "cmovpo", "vpmovzxdq", "v4fmaddss", "cmovs", "vpmovusqw", "vmaxss", "vcompresspd", "vgetexpss", "rsm", "sal", "knotw", "kandnw", "vminsd", "syscall", "vpsrld", "vmovhlps", "vptestmd", "cmovnle", "pause", "xgetbv", "movhpd", "sqrtss", "cmovng", "vaddsd", "cmovnl", "vphsubsw", "vptestnmw", "jnl", "vmovntps", "andn", "vfnmadd231ps", "vcomiss", "cmovp", "xchg", "iretd", "stosd", "pmovzxwd", "vpmuldq", "vpexpandb", "vfmaddsub231ps", "aesenc", "clts", "vpunpckhqdq", "ucomiss", "vpshldvw", "minsd", "vfnmadd213sd", "vfmadd231sd", "fstcw", "kshiftlb", "vsubsd", "kaddb", "vmovdqa32", "phaddw", "movhps", "vcvttps2dq", "pabsw", "fst", "maxss", "orps", "xlat", "addsd", "punpcklbw", "vphsubd", "setng", "vmaxps", "vrsqrt28pd", "vpsrlq", "vpbroadcastmb2q", "addsubps", "phsubsw", "cmova", "out", "stosq", "unpckhps", "vpmovsdb", "andpd", "vpopcntd", "vp4dpwssd", "cmovg", "vcvtqq2pd", "vgatherdps", "jnp", "kmovw", "ptest", "ud01", "cmovnb", "loopne", "fldlg2", "jna", "cmovnz", "divps", "hsubps", "jmp", "ucomisd", "vcvtneps2bf16", "vcvtudq2ps", "vcvtusi2sd", "vcvttps2udq", "vpmaxub", "vpermt2ps", "vfmsub132sd", "fxch", "divss", "vpgatherdd", "vcvttss2si", "mulsd", "vpopcntq", "vpmovzxwd", "subsd", "sarx", "setnc", "vgf2p8mulb", "lddqu", "jae", "cmc", "vpaddsw", "vpcmpeqb", "movaps", "vmovntdq", "vpxorq", "setnae", "vfnmsub231sd", "fucom", "vpblendmw", "vpmultishiftqb", "repne", "vbroadcasti32x4", "vpermi2pd", "bsf", "stc", "vfmsub132ss", "psllq", "cmp", "vpunpckhbw", "vcvttpd2uqq", "vpmovw2m", "vfmadd132sd", "vfnmsub132ss", "jle", "vpmovmskb", "vmovdqu", "vpsrlw", "push", "vmovapd", "ficomp", "kandw", "vpmovdw", "vpmulld", "kaddw", "fld1", "verr", "haddpd", "pshufb", "kxorw", "verw", "jg", "korw", "insd", "vfmsub231sd", "vgetexppd", "str", "kxnorw", "vpminsq", "vpmovsxbw", "psrld", "cdqe", "setl", "vpor", "psubsb", "vcvtuqq2pd", "bndldx", "vdpbf16ps", "vfmsub231pd", "vcvtpd2dq", "fcmovnbe", "movd", "v4fnmaddss", "unpcklps", "shld", "cmovnae", "shrd", "fistp", "kunpckbw", "setc", "vmaskmovpd", "vsqrtpd", "vpsubb", "vpermt2b", "phminposuw", "fldz", "kandnd", "cmovbe", "fcomi", "punpcklwd", "jge", "punpckhbw", "vfnmsub132ps", "vpmaddubsw", "vpshrdvw", "jpo", "vmaskmovdqu", "vaddss", "movss", "vsqrtps", "movq", "lfs", "vpmaxsd", "rep", "fcmovnu", "vrangesd", "ud1", "fmulp", "fdivp", "movdqu", "vpmovm2b", "vpmovqb", "vpmovqd", "vfnmadd213pd", "xadd", "vpmaskmovd", "popa", "movhlps", "vmovq", "movq2dq", "vfnmsub231ss", "shl", "vpmovzxbq", "insb", "prefetcht2", "ktestd", "movbe", "vpermi2b", "aesenclast", "vcvtsd2ss", "vcvtpd2qq", "lss", "vcvtps2qq", "setna", "vmovlhps", "vpsrad", "leave", "rdtscp", "vcvtps2dq", "seto", "psubusb", "loope", "fcompp", "movsb", "pmovzxwq", "vpmaxud", "vucomisd", "vmovsldup", "vfmaddsub231pd", "pandn", "pmulhw", "call", "lock", "korq", "paddusb", "rsqrtps", "vaesdeclast", "vpminuw", "neg", "vpackusdw", "vgatherdpd", "cmovne", "fadd", "vprolvq", "fstsw", "packssdw", "sysret", "popad", "vpsubsw", "lea", "cvtss2sd", "pushfd", "vminpd", "vbroadcasti32x2", "kandq", "das", "stosb", "add", "vpand", "vpshufb", "vrcp14ss", "jns", "fcmovu", "cmovz", "and", "bt", "vpaddb", "vpmovsqd", "vrcp14sd", "pushfq", "int3", "cvttpd2pi", "fnstsw1", "maskmovq", "pminsd", "fnstcw1", "vprorvd", "fcmovne", "setno", "vpermb", ]), types: BTreeSet::from(["ptr", "byte", "word", "dword", "qword"]), special: BTreeSet::from([ "RAX", "RBX", "RCX", "RDX", "RSI", "RDI", "RBP", "RSP", "R8", "R9", "R10", "R11", "R12", "R13", "R14", "R15", // 64-bit registers "EAX", "EBX", "ECX", "EDX", "ESI", "EDI", "EBP", "ESP", "R8D", "R9D", "R10D", "R11D", "R12D", "R13D", "R14D", "R15D", // 32-bit registers "AX", "BX", "CX", "DX", "SI", "DI", "BP", "SP", "R8W", "R9W", "R10W", "R11W", "R12W", "R13W", "R14W", "R15W", // 16-bit registers "AH", "BH", "CH", "DH", "AL", "BL", "CL", "DL", "SIL", "DIL", "BPL", "SPL", "R8B", "R9B", "R10B", "R11B", "R12B", "R13B", "R14B", "R15B", // 8-bit registers "XMM0", "XMM1", "XMM2", "XMM3", "XMM4", "XMM5", "XMM6", "XMM7", "XMM8", "XMM9", "XMM10", "XMM11", "XMM12", "XMM13", "XMM14", "XMM15", // XMM "YMM0", "YMM1", "YMM2", "YMM3", "YMM4", "YMM5", "YMM6", "YMM7", "YMM8", "YMM9", "YMM10", "YMM11", "YMM12", "YMM13", "YMM14", "YMM15", // YMM "ZMM0", "ZMM1", "ZMM2", "ZMM3", "ZMM4", "ZMM5", "ZMM6", "ZMM7", "ZMM8", "ZMM9", "ZMM10", "ZMM11", "ZMM12", "ZMM13", "ZMM14", "ZMM15", // ZMM ]), } } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/egui_code_editor/src/syntax/shell.rs
crates/egui_code_editor/src/syntax/shell.rs
use super::Syntax; use std::collections::BTreeSet; impl Syntax { pub fn shell() -> Self { Syntax { language: "Shell", case_sensitive: true, comment: "#", hyperlinks: BTreeSet::from(["http"]), keywords: BTreeSet::from([ "echo", "read", "set", "unset", "readonly", "shift", "export", "if", "fi", "else", "while", "do", "done", "for", "until", "case", "esac", "break", "continue", "exit", "return", "trap", "wait", "eval", "exec", "ulimit", "umask", ]), comment_multiline: [": '", "'"], types: BTreeSet::from([ "ENV", "HOME", "IFS", "LANG", "LC_ALL", "LC_COLLATE", "LC_CTYPE", "LC_MESSAGES", "LINENO", "NLSPATH", "PATH", "PPID", "PS1", "PS2", "PS4", "PWD", ]), special: BTreeSet::from([ "alias", "bg", "cd", "command", "false", "fc", "fg", "getopts", "jobs", "kill", "newgrp", "pwd", "read", "true", "umask", "unalias", "wait", ]), } } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/egui_code_editor/src/syntax/python.rs
crates/egui_code_editor/src/syntax/python.rs
use super::Syntax; use std::collections::BTreeSet; impl Syntax { pub fn python() -> Syntax { Syntax { language: "Python", case_sensitive: true, comment: "#", comment_multiline: [r#"'''"#, r#"'''"#], hyperlinks: BTreeSet::from(["http"]), keywords: BTreeSet::from([ "and", "as", "assert", "break", "class", "continue", "def", "del", "elif", "else", "except", "finally", "for", "from", "global", "if", "import", "in", "is", "lambda", "nonlocal", "not", "or", "pass", "raise", "return", "try", "while", "with", "yield", ]), types: BTreeSet::from([ "bool", "int", "float", "complex", "str", "list", "tuple", "range", "bytes", "bytearray", "memoryview", "dict", "set", "frozenset", ]), special: BTreeSet::from(["False", "None", "True"]), } } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/egui_code_editor/src/syntax/sql.rs
crates/egui_code_editor/src/syntax/sql.rs
use super::Syntax; use std::collections::BTreeSet; impl Syntax { pub fn sql() -> Self { Syntax { language: "SQL", case_sensitive: false, comment: "--", comment_multiline: ["/*", "*/"], hyperlinks: BTreeSet::from(["http"]), keywords: BTreeSet::from([ "ADD", "ALL", "ALTER", "AND", "ANY", "AS", "ASC", "BACKUP", "BETWEEN", "CASE", "CHECK", "COLUMN", "CONSTRAINT", "CREATE", "INDEX", "OR", "REPLACE", "VIEW", "PROCEDURE", "UNIQUE", "DEFAULT", "DELETE", "DESC", "DISTINCT", "DROP", "PRIMARY", "FOREIGN", "EXEC", "EXISTS", "FROM", "FULL", "OUTER", "JOIN", "GROUP", "BY", "HAVING", "IN", "INNER", "INSERT", "INTO", "SELECT", "IS", "KEY", "NOT", "NULL", "LEFT", "LIKE", "LIMIT", "ORDER", "A", "RIGHT", "ROWNUM", "TOP", "TOPDOWN", //FIXME "TRUNCATE", "UNION", "UPDATE", "VALUES", "WHERE", "WITH", ]), types: BTreeSet::from([ "BOOL", "INTEGER", "SMALLINT", "BIGINT", "REAL", "DOUBLEPRECISION", "VARCHAR", "NUMBER", "CHAR", "TEXT", "DATE", "TIMESTAMP", "UUID", "BYTEA", "LOB", "BLOB", "CLOB", "BIGINT", "NUMERIC", "BIT", "SMALLINT", "DECIMAL", "SMALLMONEY", "INT", "INT4", "INT8", "INT16", "INT32", "INT64", "INT128", "TINYINT", "MONEY", "FLOAT", "REAL", "DATE", "DATETIMEOFFSET", "DATETIME2", "SMALLDATETIME", "DATETIME", "TIME", "CHAR", "VARCHAR", "VARCHAR2", "TEXT", "NCHAR", "NVARCHAR", "NTEXT", "BINARY", "VARBINARY", "IMAGE", "ROWVERSION", "HIERARCHYID", "UNIQUEIDENTIFIER", "SQL_VARIANT", "XML", "XMLTYPE", "TABLE", "SET", "DATABASE", ]), special: BTreeSet::from(["PUBLIC"]), } } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/egui_code_editor/src/syntax/mod.rs
crates/egui_code_editor/src/syntax/mod.rs
#![allow(dead_code)] pub mod asm; pub mod lua; pub mod python; pub mod rust; pub mod shell; pub mod sql; use std::collections::BTreeSet; use std::hash::{Hash, Hasher}; pub const SEPARATORS: [char; 1] = ['_']; pub const QUOTES: [char; 3] = ['\'', '"', '`']; type MultiLine = bool; type Float = bool; #[derive(Default, Clone, Copy, PartialEq, PartialOrd, Eq, Ord)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum TokenType { Comment(MultiLine), Function, Keyword, Literal, Hyperlink, Numeric(Float), Punctuation(char), Special, Str(char), Type, Whitespace(char), #[default] Unknown, } impl std::fmt::Debug for TokenType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut name = String::new(); match &self { TokenType::Comment(multiline) => { name.push_str("Comment"); { if *multiline { name.push_str(" MultiLine"); } else { name.push_str(" SingleLine"); } } } TokenType::Function => name.push_str("Function"), TokenType::Keyword => name.push_str("Keyword"), TokenType::Literal => name.push_str("Literal"), TokenType::Hyperlink => name.push_str("Hyperlink"), TokenType::Numeric(float) => { name.push_str("Numeric"); if *float { name.push_str(" Float"); } else { name.push_str(" Integer"); } } TokenType::Punctuation(_) => name.push_str("Punctuation"), TokenType::Special => name.push_str("Special"), TokenType::Str(quote) => { name.push_str("Str "); name.push(*quote); } TokenType::Type => name.push_str("Type"), TokenType::Whitespace(c) => { name.push_str("Whitespace"); match c { ' ' => name.push_str(" Space"), '\t' => name.push_str(" Tab"), '\n' => name.push_str(" New Line"), _ => (), }; } TokenType::Unknown => name.push_str("Unknown"), }; write!(f, "{name}") } } impl From<char> for TokenType { fn from(c: char) -> Self { match c { c if c.is_whitespace() => TokenType::Whitespace(c), c if QUOTES.contains(&c) => TokenType::Str(c), c if c.is_numeric() => TokenType::Numeric(false), c if c.is_alphabetic() || SEPARATORS.contains(&c) => TokenType::Literal, c if c.is_ascii_punctuation() => TokenType::Punctuation(c), _ => TokenType::Unknown, } } } #[derive(Clone, Debug, PartialEq)] /// Rules for highlighting. pub struct Syntax { pub language: &'static str, pub case_sensitive: bool, pub comment: &'static str, pub comment_multiline: [&'static str; 2], pub hyperlinks: BTreeSet<&'static str>, pub keywords: BTreeSet<&'static str>, pub types: BTreeSet<&'static str>, pub special: BTreeSet<&'static str>, } impl Default for Syntax { fn default() -> Self { Syntax::rust() } } impl Hash for Syntax { fn hash<H: Hasher>(&self, state: &mut H) { self.language.hash(state); } } impl Syntax { pub fn new(language: &'static str) -> Self { Syntax { language, ..Default::default() } } pub fn with_case_sensitive(self, case_sensitive: bool) -> Self { Syntax { case_sensitive, ..self } } pub fn with_comment(self, comment: &'static str) -> Self { Syntax { comment, ..self } } pub fn with_comment_multiline(self, comment_multiline: [&'static str; 2]) -> Self { Syntax { comment_multiline, ..self } } pub fn with_hyperlinks<T: Into<BTreeSet<&'static str>>>(self, hyperlinks: T) -> Self { Syntax { hyperlinks: hyperlinks.into(), ..self } } pub fn with_keywords<T: Into<BTreeSet<&'static str>>>(self, keywords: T) -> Self { Syntax { keywords: keywords.into(), ..self } } pub fn with_types<T: Into<BTreeSet<&'static str>>>(self, types: T) -> Self { Syntax { types: types.into(), ..self } } pub fn with_special<T: Into<BTreeSet<&'static str>>>(self, special: T) -> Self { Syntax { special: special.into(), ..self } } pub fn language(&self) -> &str { self.language } pub fn comment(&self) -> &str { self.comment } pub fn is_hyperlink(&self, word: &str) -> bool { self.hyperlinks.contains(word.to_ascii_lowercase().as_str()) } pub fn is_keyword(&self, word: &str) -> bool { if self.case_sensitive { self.keywords.contains(&word) } else { self.keywords.contains(word.to_ascii_uppercase().as_str()) } } pub fn is_type(&self, word: &str) -> bool { if self.case_sensitive { self.types.contains(&word) } else { self.types.contains(word.to_ascii_uppercase().as_str()) } } pub fn is_special(&self, word: &str) -> bool { if self.case_sensitive { self.special.contains(&word) } else { self.special.contains(word.to_ascii_uppercase().as_str()) } } } impl Syntax { pub fn simple(comment: &'static str) -> Self { Syntax { language: "", case_sensitive: false, comment, comment_multiline: [comment; 2], hyperlinks: BTreeSet::new(), keywords: BTreeSet::new(), types: BTreeSet::new(), special: BTreeSet::new(), } } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/egui_code_editor/src/syntax/lua.rs
crates/egui_code_editor/src/syntax/lua.rs
use super::Syntax; use std::collections::BTreeSet; impl Syntax { pub fn lua() -> Syntax { Syntax { language: "Lua", case_sensitive: true, comment: "--", comment_multiline: ["--[[", "]]"], hyperlinks: BTreeSet::from(["http"]), keywords: BTreeSet::from([ "and", "break", "do", "else", "elseif", "end", "for", "function", "if", "in", "local", "not", "or", "repeat", "return", "then", "until", "while", ]), types: BTreeSet::from([ "boolean", "number", "string", "function", "userdata", "thread", "table", ]), special: BTreeSet::from(["false", "nil", "true"]), } } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/cookie_store/src/cookie_domain.rs
crates/cookie_store/src/cookie_domain.rs
use std; use std::convert::TryFrom; use cookie::Cookie as RawCookie; use idna; #[cfg(feature = "public_suffix")] use publicsuffix::{List, Psl, Suffix}; use serde_derive::{Deserialize, Serialize}; use url::{Host, Url}; use crate::utils::is_host_name; use crate::CookieError; pub fn is_match(domain: &str, request_url: &Url) -> bool { CookieDomain::try_from(domain) .map(|domain| domain.matches(request_url)) .unwrap_or(false) } /// The domain of a `Cookie` #[derive(PartialEq, Eq, Clone, Debug, Hash, PartialOrd, Ord, Serialize, Deserialize)] pub enum CookieDomain { /// No Domain attribute in Set-Cookie header HostOnly(String), /// Domain attribute from Set-Cookie header Suffix(String), /// Domain attribute was not present in the Set-Cookie header NotPresent, /// Domain attribute-value was empty; technically undefined behavior, but suggested that this /// be treated as invalid Empty, } // 5.1.3. Domain Matching // A string domain-matches a given domain string if at least one of the // following conditions hold: // // o The domain string and the string are identical. (Note that both // the domain string and the string will have been canonicalized to // lower case at this point.) // // o All of the following conditions hold: // // * The domain string is a suffix of the string. // // * The last character of the string that is not included in the // domain string is a %x2E (".") character. // // * The string is a host name (i.e., not an IP address). /// The concept of a domain match per [IETF RFC6265 Section /// 5.1.3](https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.3) impl CookieDomain { /// Get the CookieDomain::HostOnly variant based on `request_url`. This is the effective behavior of /// setting the domain-attribute to empty pub fn host_only(request_url: &Url) -> Result<CookieDomain, CookieError> { request_url .host() .ok_or(CookieError::NonRelativeScheme) .map(|h| match h { Host::Domain(d) => CookieDomain::HostOnly(d.into()), Host::Ipv4(addr) => CookieDomain::HostOnly(format!("{}", addr)), Host::Ipv6(addr) => CookieDomain::HostOnly(format!("[{}]", addr)), }) } /// Tests if the given `url::Url` meets the domain-match criteria pub fn matches(&self, request_url: &Url) -> bool { if let Some(url_host) = request_url.host_str() { match *self { CookieDomain::HostOnly(ref host) => host == url_host, CookieDomain::Suffix(ref suffix) => { suffix == url_host || (is_host_name(url_host) && url_host.ends_with(suffix) && url_host[(url_host.len() - suffix.len() - 1)..].starts_with('.')) } CookieDomain::NotPresent | CookieDomain::Empty => false, // nothing can match the Empty case } } else { false // not a matchable scheme } } /// Tests if the given `url::Url` has a request-host identical to the domain attribute pub fn host_is_identical(&self, request_url: &Url) -> bool { if let Some(url_host) = request_url.host_str() { match *self { CookieDomain::HostOnly(ref host) => host == url_host, CookieDomain::Suffix(ref suffix) => suffix == url_host, CookieDomain::NotPresent | CookieDomain::Empty => false, // nothing can match the Empty case } } else { false // not a matchable scheme } } /// Tests if the domain-attribute is a public suffix as indicated by the provided /// `publicsuffix::List`. #[cfg(feature = "public_suffix")] pub fn is_public_suffix(&self, psl: &List) -> bool { if let Some(domain) = self.as_cow().as_ref().map(|d| d.as_bytes()) { psl.suffix(domain) // Only consider suffixes explicitly listed in the public suffix list // to avoid issues like https://github.com/curl/curl/issues/658 .filter(Suffix::is_known) .filter(|suffix| suffix == &domain) .is_some() } else { false } } /// Get a borrowed string representation of the domain. For `Empty` and `NotPresent` variants, /// `None` shall be returned; pub fn as_cow(&self) -> Option<std::borrow::Cow<'_, str>> { match *self { CookieDomain::HostOnly(ref s) | CookieDomain::Suffix(ref s) => { Some(std::borrow::Cow::Borrowed(s)) } CookieDomain::Empty | CookieDomain::NotPresent => None, } } } /// Construct a `CookieDomain::Suffix` from a string, stripping a single leading '.' if present. /// If the source string is empty, returns the `CookieDomain::Empty` variant. impl<'a> TryFrom<&'a str> for CookieDomain { type Error = crate::Error; fn try_from(value: &str) -> Result<CookieDomain, Self::Error> { idna::domain_to_ascii(value.trim()) .map_err(super::IdnaErrors::from) .map_err(Into::into) .map(|domain| { if domain.is_empty() || "." == domain { CookieDomain::Empty } else if domain.starts_with('.') { CookieDomain::Suffix(String::from(&domain[1..])) } else { CookieDomain::Suffix(domain) } }) } } /// Construct a `CookieDomain::Suffix` from a `cookie::Cookie`, which handles stripping a leading /// '.' for us. If the cookie.domain is None or an empty string, the `CookieDomain::Empty` variant /// is returned. /// __NOTE__: `cookie::Cookie` domain values already have the leading '.' stripped. To avoid /// performing this step twice, the `From<&cookie::Cookie>` impl should be used, /// instead of passing `cookie.domain` to the `From<&str>` impl. impl<'a, 'c> TryFrom<&'a RawCookie<'c>> for CookieDomain { type Error = crate::Error; fn try_from(cookie: &'a RawCookie<'c>) -> Result<CookieDomain, Self::Error> { if let Some(domain) = cookie.domain() { idna::domain_to_ascii(domain.trim()) .map_err(super::IdnaErrors::from) .map_err(Into::into) .map(|domain| { if domain.is_empty() { CookieDomain::Empty } else { CookieDomain::Suffix(domain) } }) } else { Ok(CookieDomain::NotPresent) } } } impl<'a> From<&'a CookieDomain> for String { fn from(c: &'a CookieDomain) -> String { match *c { CookieDomain::HostOnly(ref h) => h.to_owned(), CookieDomain::Suffix(ref s) => s.to_owned(), CookieDomain::Empty | CookieDomain::NotPresent => "".to_owned(), } } } #[cfg(test)] mod tests { use std::convert::TryFrom; use cookie::Cookie as RawCookie; use url::Url; use crate::utils::test::*; use super::CookieDomain; #[inline] fn matches(expected: bool, cookie_domain: &CookieDomain, url: &str) { let url = Url::parse(url).unwrap(); assert!( expected == cookie_domain.matches(&url), "cookie_domain: {:?} url: {:?}, url.host_str(): {:?}", cookie_domain, url, url.host_str() ); } #[inline] fn variants(expected: bool, cookie_domain: &CookieDomain, url: &str) { matches(expected, cookie_domain, url); matches(expected, cookie_domain, &format!("{}/", url)); matches(expected, cookie_domain, &format!("{}:8080", url)); matches(expected, cookie_domain, &format!("{}/foo/bar", url)); matches(expected, cookie_domain, &format!("{}:8080/foo/bar", url)); } #[test] fn matches_hostonly() { { let url = url("http://example.com"); // HostOnly must be an identical string match, and may be an IP address // or a hostname let host_name = CookieDomain::host_only(&url).expect("unable to parse domain"); matches(false, &host_name, "data:nonrelative"); variants(true, &host_name, "http://example.com"); variants(false, &host_name, "http://example.org"); // per RFC6265: // WARNING: Some existing user agents treat an absent Domain // attribute as if the Domain attribute were present and contained // the current host name. For example, if example.com returns a Set- // Cookie header without a Domain attribute, these user agents will // erroneously send the cookie to www.example.com as well. variants(false, &host_name, "http://foo.example.com"); variants(false, &host_name, "http://127.0.0.1"); variants(false, &host_name, "http://[::1]"); } { let url = url("http://127.0.0.1"); let ip4 = CookieDomain::host_only(&url).expect("unable to parse Ipv4"); matches(false, &ip4, "data:nonrelative"); variants(true, &ip4, "http://127.0.0.1"); variants(false, &ip4, "http://[::1]"); } { let url = url("http://[::1]"); let ip6 = CookieDomain::host_only(&url).expect("unable to parse Ipv6"); matches(false, &ip6, "data:nonrelative"); variants(false, &ip6, "http://127.0.0.1"); variants(true, &ip6, "http://[::1]"); } } #[test] fn from_strs() { assert_eq!( CookieDomain::Empty, CookieDomain::try_from("").expect("unable to parse domain") ); assert_eq!( CookieDomain::Empty, CookieDomain::try_from(".").expect("unable to parse domain") ); // per [IETF RFC6265 Section 5.2.3](https://datatracker.ietf.org/doc/html/rfc6265#section-5.2.3) //If the first character of the attribute-value string is %x2E ("."): // //Let cookie-domain be the attribute-value without the leading %x2E //(".") character. assert_eq!( CookieDomain::Suffix(String::from(".")), CookieDomain::try_from("..").expect("unable to parse domain") ); assert_eq!( CookieDomain::Suffix(String::from("example.com")), CookieDomain::try_from("example.com").expect("unable to parse domain") ); assert_eq!( CookieDomain::Suffix(String::from("example.com")), CookieDomain::try_from(".example.com").expect("unable to parse domain") ); assert_eq!( CookieDomain::Suffix(String::from(".example.com")), CookieDomain::try_from("..example.com").expect("unable to parse domain") ); } #[test] fn from_raw_cookie() { fn raw_cookie(s: &str) -> RawCookie<'_> { RawCookie::parse(s).unwrap() } assert_eq!( CookieDomain::NotPresent, CookieDomain::try_from(&raw_cookie("cookie=value")).expect("unable to parse domain") ); // cookie::Cookie handles this (cookie.domain == None) assert_eq!( CookieDomain::NotPresent, CookieDomain::try_from(&raw_cookie("cookie=value; Domain=")) .expect("unable to parse domain") ); // cookie::Cookie does not handle this (empty after stripping leading dot) assert_eq!( CookieDomain::Empty, CookieDomain::try_from(&raw_cookie("cookie=value; Domain=.")) .expect("unable to parse domain") ); assert_eq!( CookieDomain::Suffix(String::from("example.com")), CookieDomain::try_from(&raw_cookie("cookie=value; Domain=.example.com")) .expect("unable to parse domain") ); assert_eq!( CookieDomain::Suffix(String::from("example.com")), CookieDomain::try_from(&raw_cookie("cookie=value; Domain=example.com")) .expect("unable to parse domain") ); } #[test] fn matches_suffix() { { let suffix = CookieDomain::try_from("example.com").expect("unable to parse domain"); variants(true, &suffix, "http://example.com"); // exact match variants(true, &suffix, "http://foo.example.com"); // suffix match variants(false, &suffix, "http://example.org"); // no match variants(false, &suffix, "http://xample.com"); // request is the suffix, no match variants(false, &suffix, "http://fooexample.com"); // suffix, but no "." b/w foo and example, no match } { // strip leading dot let suffix = CookieDomain::try_from(".example.com").expect("unable to parse domain"); variants(true, &suffix, "http://example.com"); variants(true, &suffix, "http://foo.example.com"); variants(false, &suffix, "http://example.org"); variants(false, &suffix, "http://xample.com"); variants(false, &suffix, "http://fooexample.com"); } { // only first leading dot is stripped let suffix = CookieDomain::try_from("..example.com").expect("unable to parse domain"); variants(true, &suffix, "http://.example.com"); variants(true, &suffix, "http://foo..example.com"); variants(false, &suffix, "http://example.com"); variants(false, &suffix, "http://foo.example.com"); variants(false, &suffix, "http://example.org"); variants(false, &suffix, "http://xample.com"); variants(false, &suffix, "http://fooexample.com"); } { // an exact string match, although an IP is specified let suffix = CookieDomain::try_from("127.0.0.1").expect("unable to parse Ipv4"); variants(true, &suffix, "http://127.0.0.1"); } { // an exact string match, although an IP is specified let suffix = CookieDomain::try_from("[::1]").expect("unable to parse Ipv6"); variants(true, &suffix, "http://[::1]"); } { // non-identical suffix match only works for host names (i.e. not IPs) let suffix = CookieDomain::try_from("0.0.1").expect("unable to parse Ipv4"); variants(false, &suffix, "http://127.0.0.1"); } } } #[cfg(test)] mod serde_tests { use std::convert::TryFrom; use serde_json; use crate::cookie_domain::CookieDomain; use crate::utils::test::*; fn encode_decode(cd: &CookieDomain, exp_json: &str) { let encoded = serde_json::to_string(cd).unwrap(); assert!( exp_json == encoded, "expected: '{}'\n encoded: '{}'", exp_json, encoded ); let decoded: CookieDomain = serde_json::from_str(&encoded).unwrap(); assert!( *cd == decoded, "expected: '{:?}'\n decoded: '{:?}'", cd, decoded ); } #[test] fn serde() { let url = url("http://example.com"); encode_decode( &CookieDomain::host_only(&url).expect("cannot parse domain"), "{\"HostOnly\":\"example.com\"}", ); encode_decode( &CookieDomain::try_from(".example.com").expect("cannot parse domain"), "{\"Suffix\":\"example.com\"}", ); encode_decode(&CookieDomain::NotPresent, "\"NotPresent\""); encode_decode(&CookieDomain::Empty, "\"Empty\""); } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/cookie_store/src/lib.rs
crates/cookie_store/src/lib.rs
#![cfg_attr(docsrs, feature(doc_cfg))] //! # cookie_store //! Provides an implementation for storing and retrieving [`Cookie`]s per the path and domain matching //! rules specified in [RFC6265](https://datatracker.ietf.org/doc/html/rfc6265). //! //! ## Feature `preserve_order` //! If enabled, [`CookieStore`] will use [`indexmap::IndexMap`] internally, and [`Cookie`] //! insertion order will be preserved. Adds dependency `indexmap`. //! //! ## Example //! Please refer to the [reqwest_cookie_store](https://crates.io/crates/reqwest_cookie_store) for //! an example of using this library along with [reqwest](https://crates.io/crates/reqwest). pub use ::cookie::{Cookie as RawCookie, ParseError as RawCookieParseError}; use idna; pub use crate::cookie::Error as CookieError; pub use crate::cookie::{Cookie, CookieResult}; pub use crate::cookie_domain::CookieDomain; pub use crate::cookie_expiration::CookieExpiration; pub use crate::cookie_path::CookiePath; pub use crate::cookie_store::CookieStore; mod cookie; mod cookie_domain; mod cookie_expiration; mod cookie_path; mod cookie_store; mod utils; #[derive(Debug)] pub struct IdnaErrors(idna::Errors); impl std::fmt::Display for IdnaErrors { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "IDNA errors: {:#?}", self.0) } } impl std::error::Error for IdnaErrors {} impl From<idna::Errors> for IdnaErrors { fn from(e: idna::Errors) -> Self { IdnaErrors(e) } } pub type Error = Box<dyn std::error::Error + Send + Sync>; pub type Result<T> = std::result::Result<T, Error>; pub(crate) mod rfc3339_fmt { pub(crate) const RFC3339_FORMAT: &[time::format_description::FormatItem] = time::macros::format_description!("[year]-[month]-[day]T[hour]:[minute]:[second]Z"); pub(super) fn serialize<S>(t: &time::OffsetDateTime, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { use serde::ser::Error; // An explicit format string is used here, instead of time::format_description::well_known::Rfc3339, to explicitly // utilize the 'Z' terminator instead of +00:00 format for Zulu time. let s = t.format(&RFC3339_FORMAT).map_err(|e| { println!("{}", e); S::Error::custom(format!( "Could not parse datetime '{}' as RFC3339 UTC format: {}", t, e )) })?; serializer.serialize_str(&s) } pub(super) fn deserialize<'de, D>(t: D) -> Result<time::OffsetDateTime, D::Error> where D: serde::Deserializer<'de>, { use serde::{de::Error, Deserialize}; let s = String::deserialize(t)?; time::OffsetDateTime::parse(&s, &time::format_description::well_known::Rfc3339).map_err( |e| { D::Error::custom(format!( "Could not parse string '{}' as RFC3339 UTC format: {}", s, e )) }, ) } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/cookie_store/src/cookie_store.rs
crates/cookie_store/src/cookie_store.rs
#[cfg(not(feature = "preserve_order"))] use std::collections::HashMap; use std::fmt::{self, Formatter}; use std::io::{BufRead, Write}; use std::iter; use std::ops::Deref; use cookie::Cookie as RawCookie; #[cfg(feature = "preserve_order")] use indexmap::IndexMap; use log::debug; use serde::de::{SeqAccess, Visitor}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use url::Url; use crate::cookie::Cookie; use crate::cookie_domain::is_match as domain_match; use crate::cookie_path::is_match as path_match; use crate::utils::{is_http_scheme, is_secure}; use crate::CookieError; #[cfg(feature = "preserve_order")] type Map<K, V> = IndexMap<K, V>; #[cfg(not(feature = "preserve_order"))] type Map<K, V> = HashMap<K, V>; type NameMap = Map<String, Cookie<'static>>; type PathMap = Map<String, NameMap>; type DomainMap = Map<String, PathMap>; #[derive(PartialEq, Clone, Debug, Eq)] pub enum StoreAction { /// The `Cookie` was successfully added to the store Inserted, /// The `Cookie` successfully expired a `Cookie` already in the store ExpiredExisting, /// The `Cookie` was added to the store, replacing an existing entry UpdatedExisting, } pub type StoreResult<T> = Result<T, crate::Error>; pub type InsertResult = Result<StoreAction, CookieError>; #[derive(Debug, Default, Clone)] /// An implementation for storing and retrieving [`Cookie`]s per the path and domain matching /// rules specified in [RFC6265](https://datatracker.ietf.org/doc/html/rfc6265). pub struct CookieStore { /// Cookies stored by domain, path, then name cookies: DomainMap, #[cfg(feature = "public_suffix")] /// If set, enables [public suffix](https://datatracker.ietf.org/doc/html/rfc6265#section-5.3) rejection based on the provided `publicsuffix::List` public_suffix_list: Option<publicsuffix::List>, } impl CookieStore { #[deprecated( since = "0.14.1", note = "Please use the `get_request_values` function instead" )] /// Return an `Iterator` of the cookies for `url` in the store, suitable for submitting in an /// HTTP request. As the items are intended for use in creating a `Cookie` header in a GET request, /// they may contain only the `name` and `value` of a received cookie, eliding other parameters /// such as `path` or `expires`. For iteration over `Cookie` instances containing all data, please /// refer to [`CookieStore::matches`]. pub fn get_request_cookies(&self, url: &Url) -> impl Iterator<Item = &RawCookie<'static>> { self.matches(url).into_iter().map(|c| c.deref()) } /// Return an `Iterator` of the cookie (`name`, `value`) pairs for `url` in the store, suitable /// for use in the `Cookie` header of an HTTP request. For iteration over `Cookie` instances, /// please refer to [`CookieStore::matches`]. pub fn get_request_values(&self, url: &Url) -> impl Iterator<Item = (&str, &str)> { self.matches(url).into_iter().map(|c| c.name_value()) } /// Store the `cookies` received from `url` pub fn store_response_cookies<I: Iterator<Item = RawCookie<'static>>>( &mut self, cookies: I, url: &Url, ) { for cookie in cookies { if cookie.secure() != Some(true) || cfg!(feature = "log_secure_cookie_values") { debug!("inserting Set-Cookie '{:?}'", cookie); } else { debug!("inserting secure cookie '{}'", cookie.name()); } if let Err(e) = self.insert_raw(&cookie, url) { debug!("unable to store Set-Cookie: {:?}", e); } } } /// Specify a `publicsuffix::List` for the `CookieStore` to allow [public suffix /// matching](https://datatracker.ietf.org/doc/html/rfc6265#section-5.3) #[cfg(feature = "public_suffix")] pub fn with_suffix_list(self, psl: publicsuffix::List) -> CookieStore { CookieStore { cookies: self.cookies, public_suffix_list: Some(psl), } } /// Returns true if the `CookieStore` contains an __unexpired__ `Cookie` corresponding to the /// specified `domain`, `path`, and `name`. pub fn contains(&self, domain: &str, path: &str, name: &str) -> bool { self.get(domain, path, name).is_some() } /// Returns true if the `CookieStore` contains any (even an __expired__) `Cookie` corresponding /// to the specified `domain`, `path`, and `name`. pub fn contains_any(&self, domain: &str, path: &str, name: &str) -> bool { self.get_any(domain, path, name).is_some() } /// Returns a reference to the __unexpired__ `Cookie` corresponding to the specified `domain`, /// `path`, and `name`. pub fn get(&self, domain: &str, path: &str, name: &str) -> Option<&Cookie<'_>> { self.get_any(domain, path, name).and_then(|cookie| { if cookie.is_expired() { None } else { Some(cookie) } }) } /// Returns a mutable reference to the __unexpired__ `Cookie` corresponding to the specified /// `domain`, `path`, and `name`. fn get_mut(&mut self, domain: &str, path: &str, name: &str) -> Option<&mut Cookie<'static>> { self.get_mut_any(domain, path, name).and_then(|cookie| { if cookie.is_expired() { None } else { Some(cookie) } }) } /// Returns a reference to the (possibly __expired__) `Cookie` corresponding to the specified /// `domain`, `path`, and `name`. pub fn get_any(&self, domain: &str, path: &str, name: &str) -> Option<&Cookie<'static>> { self.cookies.get(domain).and_then(|domain_cookies| { domain_cookies .get(path) .and_then(|path_cookies| path_cookies.get(name)) }) } /// Returns a mutable reference to the (possibly __expired__) `Cookie` corresponding to the /// specified `domain`, `path`, and `name`. fn get_mut_any( &mut self, domain: &str, path: &str, name: &str, ) -> Option<&mut Cookie<'static>> { self.cookies.get_mut(domain).and_then(|domain_cookies| { domain_cookies .get_mut(path) .and_then(|path_cookies| path_cookies.get_mut(name)) }) } pub fn remove_domain(&mut self, domain: &str) { self.cookies.remove(domain); } /// Removes a `Cookie` from the store, returning the `Cookie` if it was in the store pub fn remove(&mut self, domain: &str, path: &str, name: &str) -> Option<Cookie<'static>> { #[cfg(not(feature = "preserve_order"))] fn map_remove<K, V, Q>(map: &mut Map<K, V>, key: &Q) -> Option<V> where K: std::borrow::Borrow<Q> + std::cmp::Eq + std::hash::Hash, Q: std::cmp::Eq + std::hash::Hash + ?Sized, { map.remove(key) } #[cfg(feature = "preserve_order")] fn map_remove<K, V, Q>(map: &mut Map<K, V>, key: &Q) -> Option<V> where K: std::borrow::Borrow<Q> + std::cmp::Eq + std::hash::Hash, Q: std::cmp::Eq + std::hash::Hash + ?Sized, { map.shift_remove(key) } let (removed, remove_domain) = match self.cookies.get_mut(domain) { None => (None, false), Some(domain_cookies) => { let (removed, remove_path) = match domain_cookies.get_mut(path) { None => (None, false), Some(path_cookies) => { let removed = map_remove(path_cookies, name); (removed, path_cookies.is_empty()) } }; if remove_path { map_remove(domain_cookies, path); (removed, domain_cookies.is_empty()) } else { (removed, false) } } }; if remove_domain { map_remove(&mut self.cookies, domain); } removed } /// Returns a collection of references to __unexpired__ cookies that path- and domain-match /// `request_url`, as well as having HttpOnly and Secure attributes compatible with the /// `request_url`. pub fn matches(&self, request_url: &Url) -> Vec<&Cookie<'static>> { // although we domain_match and path_match as we descend through the tree, we // still need to // do a full Cookie::matches() check in the last filter. Otherwise, we cannot // properly deal // with HostOnly Cookies. let cookies = self .cookies .iter() .filter(|&(d, _)| domain_match(d, request_url)) .flat_map(|(_, dcs)| { dcs.iter() .filter(|&(p, _)| path_match(p, request_url)) .flat_map(|(_, pcs)| { pcs.values() .filter(|c| !c.is_expired() && c.matches(request_url)) }) }); match (!is_http_scheme(request_url), !is_secure(request_url)) { (true, true) => cookies .filter(|c| !c.http_only().unwrap_or(false) && !c.secure().unwrap_or(false)) .collect(), (true, false) => cookies .filter(|c| !c.http_only().unwrap_or(false)) .collect(), (false, true) => cookies.filter(|c| !c.secure().unwrap_or(false)).collect(), (false, false) => cookies.collect(), } } /// Parses a new `Cookie` from `cookie_str` and inserts it into the store. pub fn parse(&mut self, cookie_str: &str, request_url: &Url) -> InsertResult { Cookie::parse(cookie_str, request_url) .and_then(|cookie| self.insert(cookie.into_owned(), request_url)) } /// Converts a `cookie::Cookie` (from the `cookie` crate) into a `cookie_store::Cookie` and /// inserts it into the store. pub fn insert_raw(&mut self, cookie: &RawCookie<'_>, request_url: &Url) -> InsertResult { Cookie::try_from_raw_cookie(cookie, request_url) .and_then(|cookie| self.insert(cookie.into_owned(), request_url)) } pub fn insert_raw_no_url_check(&mut self, cookie: &RawCookie<'_>) -> InsertResult { Cookie::try_from_raw_cookie_no_url_check(cookie) .and_then(|cookie| self.insert_no_url_check(cookie.into_owned())) } /// Inserts `cookie`, received from `request_url`, into the store, following the rules of the /// [IETF RFC6265 Storage Model](https://datatracker.ietf.org/doc/html/rfc6265#section-5.3). If the /// `Cookie` is __unexpired__ and is successfully inserted, returns /// `Ok(StoreAction::Inserted)`. If the `Cookie` is __expired__ *and* matches an existing /// `Cookie` in the store, the existing `Cookie` wil be `expired()` and /// `Ok(StoreAction::ExpiredExisting)` will be returned. pub fn insert(&mut self, cookie: Cookie<'static>, request_url: &Url) -> InsertResult { if cookie.http_only().unwrap_or(false) && !is_http_scheme(request_url) { // If the cookie was received from a "non-HTTP" API and the // cookie's http-only-flag is set, abort these steps and ignore the // cookie entirely. return Err(CookieError::NonHttpScheme); } #[cfg(feature = "public_suffix")] let mut cookie = cookie; #[cfg(feature = "public_suffix")] if let Some(ref psl) = self.public_suffix_list { // If the user agent is configured to reject "public suffixes" if cookie.domain.is_public_suffix(psl) { // and the domain-attribute is a public suffix: if cookie.domain.host_is_identical(request_url) { // If the domain-attribute is identical to the canonicalized // request-host: // Let the domain-attribute be the empty string. // (NB: at this point, an empty domain-attribute should be represented // as the HostOnly variant of CookieDomain) cookie.domain = crate::cookie_domain::CookieDomain::host_only(request_url)?; } else { // Otherwise: // Ignore the cookie entirely and abort these steps. return Err(CookieError::PublicSuffix); } } } if !cookie.domain.matches(request_url) { // If the canonicalized request-host does not domain-match the // domain-attribute: // Ignore the cookie entirely and abort these steps. return Err(CookieError::DomainMismatch); } // NB: we do not bail out above on is_expired(), as servers can remove a cookie // by sending // an expired one, so we need to do the old_cookie check below before checking // is_expired() on an incoming cookie { // At this point in parsing, any non-present Domain attribute should have been // converted into a HostOnly variant let cookie_domain = cookie .domain .as_cow() .ok_or_else(|| CookieError::UnspecifiedDomain)?; if let Some(old_cookie) = self.get_mut(&cookie_domain, &cookie.path, cookie.name()) { if old_cookie.http_only().unwrap_or(false) && !is_http_scheme(request_url) { // 2. If the newly created cookie was received from a "non-HTTP" // API and the old-cookie's http-only-flag is set, abort these // steps and ignore the newly created cookie entirely. return Err(CookieError::NonHttpScheme); } else if cookie.is_expired() { old_cookie.expire(); return Ok(StoreAction::ExpiredExisting); } } } if !cookie.is_expired() { Ok( if self .cookies .entry(String::from(&cookie.domain)) .or_insert_with(Map::new) .entry(String::from(&cookie.path)) .or_insert_with(Map::new) .insert(cookie.name().to_owned(), cookie) .is_none() { StoreAction::Inserted } else { StoreAction::UpdatedExisting }, ) } else { Err(CookieError::Expired) } } pub fn insert_no_url_check(&mut self, cookie: Cookie<'static>) -> InsertResult { if !cookie.is_expired() { Ok( if self .cookies .entry(String::from(&cookie.domain)) .or_insert_with(Map::new) .entry(String::from(&cookie.path)) .or_insert_with(Map::new) .insert(cookie.name().to_owned(), cookie) .is_none() { StoreAction::Inserted } else { StoreAction::UpdatedExisting }, ) } else { Err(CookieError::Expired) } } /// Clear the contents of the store pub fn clear(&mut self) { self.cookies.clear() } /// An iterator visiting all the __unexpired__ cookies in the store pub fn iter_unexpired<'a>(&'a self) -> impl Iterator<Item = &'a Cookie<'static>> + 'a { self.cookies .values() .flat_map(|dcs| dcs.values()) .flat_map(|pcs| pcs.values()) .filter(|c| !c.is_expired()) } /// An iterator visiting all (including __expired__) cookies in the store pub fn iter_any<'a>(&'a self) -> impl Iterator<Item = &'a Cookie<'static>> + 'a { self.cookies .values() .flat_map(|dcs| dcs.values()) .flat_map(|pcs| pcs.values()) } /// Serialize any __unexpired__ and __persistent__ cookies in the store with `cookie_to_string` /// and write them to `writer` pub fn save<W, E, F>(&self, writer: &mut W, cookie_to_string: F) -> StoreResult<()> where W: Write, F: Fn(&Cookie<'static>) -> Result<String, E>, crate::Error: From<E>, { for cookie in self.iter_unexpired().filter_map(|c| { if c.is_persistent() { Some(cookie_to_string(c)) } else { None } }) { writeln!(writer, "{}", cookie?)?; } Ok(()) } /// Serialize any __unexpired__ and __persistent__ cookies in the store to JSON format and /// write them to `writer` pub fn save_json<W: Write>(&self, writer: &mut W) -> StoreResult<()> { self.save(writer, ::serde_json::to_string) } /// Serialize all (including __expired__ and __non-persistent__) cookies in the store with `cookie_to_string` and write them to `writer` pub fn save_incl_expired_and_nonpersistent<W, E, F>( &self, writer: &mut W, cookie_to_string: F, ) -> StoreResult<()> where W: Write, F: Fn(&Cookie<'static>) -> Result<String, E>, crate::Error: From<E>, { for cookie in self.iter_any() { writeln!(writer, "{}", cookie_to_string(cookie)?)?; } Ok(()) } /// Serialize all (including __expired__ and __non-persistent__) cookies in the store to JSON format and write them to `writer` pub fn save_incl_expired_and_nonpersistent_json<W: Write>( &self, writer: &mut W, ) -> StoreResult<()> { self.save_incl_expired_and_nonpersistent(writer, ::serde_json::to_string) } /// Load cookies from `reader`, deserializing with `cookie_from_str`, skipping any __expired__ /// cookies pub fn load<R, E, F>(reader: R, cookie_from_str: F) -> StoreResult<CookieStore> where R: BufRead, F: Fn(&str) -> Result<Cookie<'static>, E>, crate::Error: From<E>, { CookieStore::load_from(reader, cookie_from_str, false) } /// Load cookies from `reader`, deserializing with `cookie_from_str`, loading both __unexpired__ /// and __expired__ cookies pub fn load_all<R, E, F>(reader: R, cookie_from_str: F) -> StoreResult<CookieStore> where R: BufRead, F: Fn(&str) -> Result<Cookie<'static>, E>, crate::Error: From<E>, { CookieStore::load_from(reader, cookie_from_str, true) } fn load_from<R, E, F>( reader: R, cookie_from_str: F, include_expired: bool, ) -> StoreResult<CookieStore> where R: BufRead, F: Fn(&str) -> Result<Cookie<'static>, E>, crate::Error: From<E>, { let cookies = reader.lines().map(|line_result| { line_result .map_err(Into::into) .and_then(|line| cookie_from_str(&line).map_err(crate::Error::from)) }); Self::from_cookies(cookies, include_expired) } /// Load JSON-formatted cookies from `reader`, skipping any __expired__ cookies pub fn load_json<R: BufRead>(reader: R) -> StoreResult<CookieStore> { CookieStore::load(reader, |cookie| ::serde_json::from_str(cookie)) } /// Load JSON-formatted cookies from `reader`, loading both __expired__ and __unexpired__ cookies pub fn load_json_all<R: BufRead>(reader: R) -> StoreResult<CookieStore> { CookieStore::load_all(reader, |cookie| ::serde_json::from_str(cookie)) } /// Create a `CookieStore` from an iterator of `Cookie` values. When /// `include_expired` is `true`, both __expired__ and __unexpired__ cookies in the incoming /// iterator will be included in the produced `CookieStore`; otherwise, only /// __unexpired__ cookies will be included, and __expired__ cookies filtered /// out. pub fn from_cookies<I, E>(iter: I, include_expired: bool) -> Result<Self, E> where I: IntoIterator<Item = Result<Cookie<'static>, E>>, { let mut cookies = Map::new(); for cookie in iter { let cookie = cookie?; if include_expired || !cookie.is_expired() { cookies .entry(String::from(&cookie.domain)) .or_insert_with(Map::new) .entry(String::from(&cookie.path)) .or_insert_with(Map::new) .insert(cookie.name().to_owned(), cookie); } } Ok(Self { cookies, #[cfg(feature = "public_suffix")] public_suffix_list: None, }) } pub fn new( #[cfg(feature = "public_suffix")] public_suffix_list: Option<publicsuffix::List>, ) -> Self { Self { cookies: DomainMap::new(), #[cfg(feature = "public_suffix")] public_suffix_list, } } } impl Serialize for CookieStore { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.collect_seq(self.iter_unexpired().filter(|c| c.is_persistent())) } } struct CookieStoreVisitor; impl<'de> Visitor<'de> for CookieStoreVisitor { type Value = CookieStore; fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result { write!(formatter, "a sequence of cookies") } fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error> where A: SeqAccess<'de>, { CookieStore::from_cookies(iter::from_fn(|| seq.next_element().transpose()), false) } } impl<'de> Deserialize<'de> for CookieStore { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_seq(CookieStoreVisitor) } } #[cfg(test)] mod tests { use std::str::from_utf8; use ::cookie::Cookie as RawCookie; use time::OffsetDateTime; use crate::cookie::Cookie; use crate::utils::test as test_utils; use crate::CookieError; use super::CookieStore; use super::{InsertResult, StoreAction}; macro_rules! has_str { ($e: expr, $i: ident) => {{ let val = from_utf8(&$i[..]).unwrap(); assert!(val.contains($e), "exp: {}\nval: {}", $e, val); }}; } macro_rules! not_has_str { ($e: expr, $i: ident) => {{ let val = from_utf8(&$i[..]).unwrap(); assert!(!val.contains($e), "exp: {}\nval: {}", $e, val); }}; } macro_rules! inserted { ($e: expr) => { assert_eq!(Ok(StoreAction::Inserted), $e) }; } macro_rules! updated { ($e: expr) => { assert_eq!(Ok(StoreAction::UpdatedExisting), $e) }; } macro_rules! expired_existing { ($e: expr) => { assert_eq!(Ok(StoreAction::ExpiredExisting), $e) }; } macro_rules! domain_mismatch { ($e: expr) => { assert_eq!(Err(CookieError::DomainMismatch), $e) }; } macro_rules! non_http_scheme { ($e: expr) => { assert_eq!(Err(CookieError::NonHttpScheme), $e) }; } macro_rules! non_rel_scheme { ($e: expr) => { assert_eq!(Err(CookieError::NonRelativeScheme), $e) }; } macro_rules! expired_err { ($e: expr) => { assert_eq!(Err(CookieError::Expired), $e) }; } macro_rules! values_are { ($store: expr, $url: expr, $values: expr) => {{ let mut matched_values = $store .matches(&test_utils::url($url)) .iter() .map(|c| &c.value()[..]) .collect::<Vec<_>>(); matched_values.sort(); let mut values: Vec<&str> = $values; values.sort(); assert!( matched_values == values, "\n{:?}\n!=\n{:?}\n", matched_values, values ); }}; } fn add_cookie( store: &mut CookieStore, cookie: &str, url: &str, expires: Option<OffsetDateTime>, max_age: Option<u64>, ) -> InsertResult { store.insert( test_utils::make_cookie(cookie, url, expires, max_age), &test_utils::url(url), ) } fn make_match_store() -> CookieStore { let mut store = CookieStore::default(); inserted!(add_cookie( &mut store, "cookie1=1", "http://example.com/foo/bar", None, Some(60 * 5), )); inserted!(add_cookie( &mut store, "cookie2=2; Secure", "https://example.com/sec/", None, Some(60 * 5), )); inserted!(add_cookie( &mut store, "cookie3=3; HttpOnly", "https://example.com/sec/", None, Some(60 * 5), )); inserted!(add_cookie( &mut store, "cookie4=4; Secure; HttpOnly", "https://example.com/sec/", None, Some(60 * 5), )); inserted!(add_cookie( &mut store, "cookie5=5", "http://example.com/foo/", None, Some(60 * 5), )); inserted!(add_cookie( &mut store, "cookie6=6", "http://example.com/", None, Some(60 * 5), )); inserted!(add_cookie( &mut store, "cookie7=7", "http://bar.example.com/foo/", None, Some(60 * 5), )); inserted!(add_cookie( &mut store, "cookie8=8", "http://example.org/foo/bar", None, Some(60 * 5), )); inserted!(add_cookie( &mut store, "cookie9=9", "http://bar.example.org/foo/bar", None, Some(60 * 5), )); store } macro_rules! check_matches { ($store: expr) => {{ values_are!($store, "http://unknowndomain.org/foo/bar", vec![]); values_are!($store, "http://example.org/foo/bar", vec!["8"]); values_are!($store, "http://example.org/bus/bar", vec![]); values_are!($store, "http://bar.example.org/foo/bar", vec!["9"]); values_are!($store, "http://bar.example.org/bus/bar", vec![]); values_are!( $store, "https://example.com/sec/foo", vec!["6", "4", "3", "2"] ); values_are!($store, "http://example.com/sec/foo", vec!["6", "3"]); values_are!($store, "ftp://example.com/sec/foo", vec!["6"]); values_are!($store, "http://bar.example.com/foo/bar/bus", vec!["7"]); values_are!( $store, "http://example.com/foo/bar/bus", vec!["1", "5", "6"] ); }}; } #[test] fn insert_raw() { let mut store = CookieStore::default(); inserted!(store.insert_raw( &RawCookie::parse("cookie1=value1").unwrap(), &test_utils::url("http://example.com/foo/bar"), )); non_rel_scheme!(store.insert_raw( &RawCookie::parse("cookie1=value1").unwrap(), &test_utils::url("data:nonrelativescheme"), )); non_http_scheme!(store.insert_raw( &RawCookie::parse("cookie1=value1; HttpOnly").unwrap(), &test_utils::url("ftp://example.com/"), )); expired_existing!(store.insert_raw( &RawCookie::parse("cookie1=value1; Max-Age=0").unwrap(), &test_utils::url("http://example.com/foo/bar"), )); expired_err!(store.insert_raw( &RawCookie::parse("cookie1=value1; Max-Age=-1").unwrap(), &test_utils::url("http://example.com/foo/bar"), )); updated!(store.insert_raw( &RawCookie::parse("cookie1=value1").unwrap(), &test_utils::url("http://example.com/foo/bar"), )); expired_existing!(store.insert_raw( &RawCookie::parse("cookie1=value1; Max-Age=-1").unwrap(), &test_utils::url("http://example.com/foo/bar"), )); domain_mismatch!(store.insert_raw( &RawCookie::parse("cookie1=value1; Domain=bar.example.com").unwrap(), &test_utils::url("http://example.com/foo/bar"), )); } #[test] fn parse() { let mut store = CookieStore::default(); inserted!(store.parse( "cookie1=value1", &test_utils::url("http://example.com/foo/bar"), )); non_rel_scheme!(store.parse("cookie1=value1", &test_utils::url("data:nonrelativescheme"),)); non_http_scheme!(store.parse( "cookie1=value1; HttpOnly", &test_utils::url("ftp://example.com/"), )); expired_existing!(store.parse( "cookie1=value1; Max-Age=0", &test_utils::url("http://example.com/foo/bar"), )); expired_err!(store.parse( "cookie1=value1; Max-Age=-1", &test_utils::url("http://example.com/foo/bar"), )); updated!(store.parse( "cookie1=value1", &test_utils::url("http://example.com/foo/bar"), )); expired_existing!(store.parse( "cookie1=value1; Max-Age=-1", &test_utils::url("http://example.com/foo/bar"), )); domain_mismatch!(store.parse( "cookie1=value1; Domain=bar.example.com", &test_utils::url("http://example.com/foo/bar"), )); } #[test] fn save() { let mut output = vec![]; let mut store = CookieStore::default(); store.save_json(&mut output).unwrap(); assert_eq!("", from_utf8(&output[..]).unwrap()); // non-persistent cookie, should not be saved inserted!(add_cookie( &mut store, "cookie0=value0", "http://example.com/foo/bar", None, None, )); store.save_json(&mut output).unwrap(); assert_eq!("", from_utf8(&output[..]).unwrap()); // persistent cookie, Max-Age inserted!(add_cookie( &mut store, "cookie1=value1", "http://example.com/foo/bar", None, Some(10), )); store.save_json(&mut output).unwrap(); not_has_str!("cookie0=value0", output); has_str!("cookie1=value1", output); output.clear(); // persistent cookie, Expires inserted!(add_cookie( &mut store, "cookie2=value2", "http://example.com/foo/bar", Some(test_utils::in_days(1)), None, )); store.save_json(&mut output).unwrap(); not_has_str!("cookie0=value0", output); has_str!("cookie1=value1", output); has_str!("cookie2=value2", output); output.clear(); inserted!(add_cookie( &mut store, "cookie3=value3; Domain=example.com", "http://foo.example.com/foo/bar", Some(test_utils::in_days(1)), None, )); inserted!(add_cookie( &mut store, "cookie4=value4; Path=/foo/", "http://foo.example.com/foo/bar", Some(test_utils::in_days(1)), None, )); inserted!(add_cookie( &mut store, "cookie5=value5", "http://127.0.0.1/foo/bar", Some(test_utils::in_days(1)), None, )); inserted!(add_cookie( &mut store, "cookie6=value6", "http://[::1]/foo/bar", Some(test_utils::in_days(1)), None, )); inserted!(add_cookie( &mut store, "cookie7=value7; Secure", "https://[::1]/foo/bar", Some(test_utils::in_days(1)), None, )); inserted!(add_cookie( &mut store, "cookie8=value8; HttpOnly", "http://[::1]/foo/bar", Some(test_utils::in_days(1)), None, )); store.save_json(&mut output).unwrap();
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
true
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/cookie_store/src/utils.rs
crates/cookie_store/src/utils.rs
use std::net::{Ipv4Addr, Ipv6Addr}; use url::Url; use url::{Host, ParseError as UrlError}; pub trait IntoUrl { fn into_url(self) -> Result<Url, UrlError>; } impl IntoUrl for Url { fn into_url(self) -> Result<Url, UrlError> { Ok(self) } } impl<'a> IntoUrl for &'a str { fn into_url(self) -> Result<Url, UrlError> { Url::parse(self) } } impl<'a> IntoUrl for &'a String { fn into_url(self) -> Result<Url, UrlError> { Url::parse(self) } } pub fn is_http_scheme(url: &Url) -> bool { url.scheme().starts_with("http") } pub fn is_host_name(host: &str) -> bool { host.parse::<Ipv4Addr>().is_err() && host.parse::<Ipv6Addr>().is_err() } pub fn is_secure(url: &Url) -> bool { if url.scheme() == "https" { return true; } if let Some(u) = url.host() { match u { Host::Domain(d) => d == "localhost", Host::Ipv4(ip) => ip.is_loopback(), Host::Ipv6(ip) => ip.is_loopback(), } } else { false } } #[cfg(test)] pub mod test { use time::{Duration, OffsetDateTime}; use url::Url; use crate::cookie::Cookie; #[inline] pub fn url(url: &str) -> Url { Url::parse(url).unwrap() } #[inline] pub fn make_cookie<'a>( cookie: &str, url_str: &str, expires: Option<OffsetDateTime>, max_age: Option<u64>, ) -> Cookie<'a> { Cookie::parse( format!( "{}{}{}", cookie, expires.map_or(String::from(""), |e| format!( "; Expires={}", e.format(time::macros::format_description!("[weekday repr:short], [day] [month repr:short] [year] [hour]:[minute]:[second] GMT")).unwrap() )), max_age.map_or(String::from(""), |m| format!("; Max-Age={}", m)) ), &url(url_str), ) .unwrap() } #[inline] pub fn in_days(days: i64) -> OffsetDateTime { OffsetDateTime::now_utc() + Duration::days(days) } #[inline] pub fn in_minutes(mins: i64) -> OffsetDateTime { OffsetDateTime::now_utc() + Duration::minutes(mins) } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/cookie_store/src/cookie.rs
crates/cookie_store/src/cookie.rs
use std::borrow::Cow; use std::convert::TryFrom; use std::fmt; use std::ops::Deref; use cookie::{Cookie as RawCookie, CookieBuilder as RawCookieBuilder, ParseError}; use serde_derive::{Deserialize, Serialize}; use time; use url::Url; use crate::cookie_domain::CookieDomain; use crate::cookie_expiration::CookieExpiration; use crate::cookie_path::CookiePath; use crate::utils::{is_http_scheme, is_secure}; #[derive(Debug, Clone, PartialEq, Eq)] pub enum Error { /// Cookie had attribute HttpOnly but was received from a request-uri which was not an http /// scheme NonHttpScheme, /// Cookie did not specify domain but was received from non-relative-scheme request-uri from /// which host could not be determined NonRelativeScheme, /// Cookie received from a request-uri that does not domain-match DomainMismatch, /// Cookie is Expired Expired, /// `cookie::Cookie` Parse error Parse, #[cfg(feature = "public_suffix")] /// Cookie specified a public suffix domain-attribute that does not match the canonicalized /// request-uri host PublicSuffix, /// Tried to use a CookieDomain variant of `Empty` or `NotPresent` in a context requiring a Domain value UnspecifiedDomain, } impl std::error::Error for Error {} impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{}", match *self { Error::NonHttpScheme => "request-uri is not an http scheme but HttpOnly attribute set", Error::NonRelativeScheme => { "request-uri is not a relative scheme; cannot determine host" } Error::DomainMismatch => "request-uri does not domain-match the cookie", Error::Expired => "attempted to utilize an Expired Cookie", Error::Parse => "unable to parse string as cookie::Cookie", #[cfg(feature = "public_suffix")] Error::PublicSuffix => "domain-attribute value is a public suffix", Error::UnspecifiedDomain => "domain-attribute is not specified", } ) } } // cookie::Cookie::parse returns Result<Cookie, ()> impl From<ParseError> for Error { fn from(_: ParseError) -> Error { Error::Parse } } pub type CookieResult<'a> = Result<Cookie<'a>, Error>; /// A cookie conforming more closely to [IETF RFC6265](https://datatracker.ietf.org/doc/html/rfc6265) #[derive(PartialEq, Clone, Debug, Serialize, Deserialize)] pub struct Cookie<'a> { /// The parsed Set-Cookie data #[serde(serialize_with = "serde_raw_cookie::serialize")] #[serde(deserialize_with = "serde_raw_cookie::deserialize")] raw_cookie: RawCookie<'a>, /// The Path attribute from a Set-Cookie header or the default-path as /// determined from /// the request-uri pub path: CookiePath, /// The Domain attribute from a Set-Cookie header, or a HostOnly variant if no /// non-empty Domain attribute /// found pub domain: CookieDomain, /// For a persistent Cookie (see [IETF RFC6265 Section /// 5.3](https://datatracker.ietf.org/doc/html/rfc6265#section-5.3)), /// the expiration time as defined by the Max-Age or Expires attribute, /// otherwise SessionEnd, /// indicating a non-persistent `Cookie` that should expire at the end of the /// session pub expires: CookieExpiration, } mod serde_raw_cookie { use std::str::FromStr; use cookie::Cookie as RawCookie; use serde::de::Error; use serde::de::Unexpected; use serde::{Deserialize, Deserializer, Serialize, Serializer}; pub fn serialize<S>(cookie: &RawCookie<'_>, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { cookie.to_string().serialize(serializer) } pub fn deserialize<'a, D>(deserializer: D) -> Result<RawCookie<'static>, D::Error> where D: Deserializer<'a>, { let cookie = String::deserialize(deserializer)?; match RawCookie::from_str(&cookie) { Ok(cookie) => Ok(cookie), Err(_) => Err(D::Error::invalid_value( Unexpected::Str(&cookie), &"a cookie string", )), } } } impl<'a> Cookie<'a> { /// Whether this `Cookie` should be included for `request_url` pub fn matches(&self, request_url: &Url) -> bool { self.path.matches(request_url) && self.domain.matches(request_url) && (!self.raw_cookie.secure().unwrap_or(false) || is_secure(request_url)) && (!self.raw_cookie.http_only().unwrap_or(false) || is_http_scheme(request_url)) } /// Should this `Cookie` be persisted across sessions? pub fn is_persistent(&self) -> bool { match self.expires { CookieExpiration::AtUtc(_) => true, CookieExpiration::SessionEnd => false, } } /// Expire this cookie pub fn expire(&mut self) { self.expires = CookieExpiration::from(0u64); } /// Return whether the `Cookie` is expired *now* pub fn is_expired(&self) -> bool { self.expires.is_expired() } /// Indicates if the `Cookie` expires as of `utc_tm`. pub fn expires_by(&self, utc_tm: &time::OffsetDateTime) -> bool { self.expires.expires_by(utc_tm) } /// Parses a new `cookie_store::Cookie` from `cookie_str`. pub fn parse<S>(cookie_str: S, request_url: &Url) -> CookieResult<'a> where S: Into<Cow<'a, str>>, { Cookie::try_from_raw_cookie(&RawCookie::parse(cookie_str)?, request_url) } /// Create a new `cookie_store::Cookie` from a `cookie::Cookie` (from the `cookie` crate) /// received from `request_url`. pub fn try_from_raw_cookie(raw_cookie: &RawCookie<'a>, request_url: &Url) -> CookieResult<'a> { if raw_cookie.http_only().unwrap_or(false) && !is_http_scheme(request_url) { // If the cookie was received from a "non-HTTP" API and the // cookie's http-only-flag is set, abort these steps and ignore the // cookie entirely. return Err(Error::NonHttpScheme); } let domain = match CookieDomain::try_from(raw_cookie) { // 6. If the domain-attribute is non-empty: Ok(d @ CookieDomain::Suffix(_)) => { if !d.matches(request_url) { // If the canonicalized request-host does not domain-match the // domain-attribute: // Ignore the cookie entirely and abort these steps. Err(Error::DomainMismatch) } else { // Otherwise: // Set the cookie's host-only-flag to false. // Set the cookie's domain to the domain-attribute. Ok(d) } } Err(_) => Err(Error::Parse), // Otherwise: // Set the cookie's host-only-flag to true. // Set the cookie's domain to the canonicalized request-host. _ => CookieDomain::host_only(request_url), }?; let path = raw_cookie .path() .as_ref() .and_then(|p| CookiePath::parse(p)) .unwrap_or_else(|| CookiePath::default_path(request_url)); // per RFC6265, Max-Age takes precedence, then Expires, otherwise is Session // only let expires = if let Some(max_age) = raw_cookie.max_age() { CookieExpiration::from(max_age) } else if let Some(expiration) = raw_cookie.expires() { CookieExpiration::from(expiration) } else { CookieExpiration::SessionEnd }; Ok(Cookie { raw_cookie: raw_cookie.clone(), path, expires, domain, }) } pub fn try_from_raw_cookie_no_url_check(raw_cookie: &RawCookie<'a>) -> CookieResult<'a> { let domain = match CookieDomain::try_from(raw_cookie) { Ok(d @ CookieDomain::Suffix(_)) => Ok(d), Ok(d @ CookieDomain::HostOnly(_)) => Ok(d), Err(_) => Err(Error::Parse), _ => Err(Error::Parse), }?; let path = raw_cookie .path() .as_ref() .and_then(|p| CookiePath::parse(p)) .ok_or(Error::Parse)?; // only let expires = if let Some(max_age) = raw_cookie.max_age() { CookieExpiration::from(max_age) } else if let Some(expiration) = raw_cookie.expires() { CookieExpiration::from(expiration) } else { CookieExpiration::SessionEnd }; Ok(Cookie { raw_cookie: raw_cookie.clone(), path, expires, domain, }) } pub fn into_owned(self) -> Cookie<'static> { Cookie { raw_cookie: self.raw_cookie.into_owned(), path: self.path, domain: self.domain, expires: self.expires, } } } impl<'a> Deref for Cookie<'a> { type Target = RawCookie<'a>; fn deref(&self) -> &Self::Target { &self.raw_cookie } } impl<'a> From<Cookie<'a>> for RawCookie<'a> { fn from(cookie: Cookie<'a>) -> RawCookie<'static> { let mut builder = RawCookieBuilder::new(cookie.name().to_owned(), cookie.value().to_owned()); // Max-Age is relative, will not have same meaning now, so only set `Expires`. match cookie.expires { CookieExpiration::AtUtc(utc_tm) => { builder = builder.expires(utc_tm); } CookieExpiration::SessionEnd => {} } if cookie.path.is_from_path_attr() { builder = builder.path(String::from(cookie.path)); } if let CookieDomain::Suffix(s) = cookie.domain { builder = builder.domain(s); } builder.finish() } } #[cfg(test)] mod tests { use cookie::Cookie as RawCookie; use time::{Duration, OffsetDateTime}; use url::Url; use crate::cookie_domain::CookieDomain; use crate::cookie_expiration::CookieExpiration; use crate::utils::test as test_utils; use super::Cookie; fn cmp_domain(cookie: &str, url: &str, exp: CookieDomain) { let ua = test_utils::make_cookie(cookie, url, None, None); assert!(ua.domain == exp, "\n{:?}", ua); } #[test] fn no_domain() { let url = test_utils::url("http://example.com/foo/bar"); cmp_domain( "cookie1=value1", "http://example.com/foo/bar", CookieDomain::host_only(&url).expect("unable to parse domain"), ); } // per RFC6265: // If the attribute-value is empty, the behavior is undefined. However, // the user agent SHOULD ignore the cookie-av entirely. #[test] fn empty_domain() { let url = test_utils::url("http://example.com/foo/bar"); cmp_domain( "cookie1=value1; Domain=", "http://example.com/foo/bar", CookieDomain::host_only(&url).expect("unable to parse domain"), ); } #[test] fn mismatched_domain() { let ua = Cookie::parse( "cookie1=value1; Domain=notmydomain.com", &test_utils::url("http://example.com/foo/bar"), ); assert!(ua.is_err(), "{:?}", ua); } #[test] fn domains() { fn domain_from(domain: &str, request_url: &str, is_some: bool) { let cookie_str = format!("cookie1=value1; Domain={}", domain); let raw_cookie = RawCookie::parse(cookie_str).unwrap(); let cookie = Cookie::try_from_raw_cookie(&raw_cookie, &test_utils::url(request_url)); assert_eq!(is_some, cookie.is_ok()) } // The user agent will reject cookies unless the Domain attribute // specifies a scope for the cookie that would include the origin // server. For example, the user agent will accept a cookie with a // Domain attribute of "example.com" or of "foo.example.com" from // foo.example.com, but the user agent will not accept a cookie with a // Domain attribute of "bar.example.com" or of "baz.foo.example.com". domain_from("example.com", "http://foo.example.com", true); domain_from(".example.com", "http://foo.example.com", true); domain_from("foo.example.com", "http://foo.example.com", true); domain_from(".foo.example.com", "http://foo.example.com", true); domain_from("oo.example.com", "http://foo.example.com", false); domain_from("myexample.com", "http://foo.example.com", false); domain_from("bar.example.com", "http://foo.example.com", false); domain_from("baz.foo.example.com", "http://foo.example.com", false); } #[test] fn httponly() { let c = RawCookie::parse("cookie1=value1; HttpOnly").unwrap(); let url = Url::parse("ftp://example.com/foo/bar").unwrap(); let ua = Cookie::try_from_raw_cookie(&c, &url); assert!(ua.is_err(), "{:?}", ua); } #[test] fn identical_domain() { cmp_domain( "cookie1=value1; Domain=example.com", "http://example.com/foo/bar", CookieDomain::Suffix(String::from("example.com")), ); } #[test] fn identical_domain_leading_dot() { cmp_domain( "cookie1=value1; Domain=.example.com", "http://example.com/foo/bar", CookieDomain::Suffix(String::from("example.com")), ); } #[test] fn identical_domain_two_leading_dots() { cmp_domain( "cookie1=value1; Domain=..example.com", "http://..example.com/foo/bar", CookieDomain::Suffix(String::from(".example.com")), ); } #[test] fn upper_case_domain() { cmp_domain( "cookie1=value1; Domain=EXAMPLE.com", "http://example.com/foo/bar", CookieDomain::Suffix(String::from("example.com")), ); } fn cmp_path(cookie: &str, url: &str, exp: &str) { let ua = test_utils::make_cookie(cookie, url, None, None); assert!(String::from(ua.path.clone()) == exp, "\n{:?}", ua); } #[test] fn no_path() { // no Path specified cmp_path("cookie1=value1", "http://example.com/foo/bar/", "/foo/bar"); cmp_path("cookie1=value1", "http://example.com/foo/bar", "/foo"); cmp_path("cookie1=value1", "http://example.com/foo", "/"); cmp_path("cookie1=value1", "http://example.com/", "/"); cmp_path("cookie1=value1", "http://example.com", "/"); } #[test] fn empty_path() { // Path specified with empty value cmp_path( "cookie1=value1; Path=", "http://example.com/foo/bar/", "/foo/bar", ); cmp_path( "cookie1=value1; Path=", "http://example.com/foo/bar", "/foo", ); cmp_path("cookie1=value1; Path=", "http://example.com/foo", "/"); cmp_path("cookie1=value1; Path=", "http://example.com/", "/"); cmp_path("cookie1=value1; Path=", "http://example.com", "/"); } #[test] fn invalid_path() { // Invalid Path specified (first character not /) cmp_path( "cookie1=value1; Path=baz", "http://example.com/foo/bar/", "/foo/bar", ); cmp_path( "cookie1=value1; Path=baz", "http://example.com/foo/bar", "/foo", ); cmp_path("cookie1=value1; Path=baz", "http://example.com/foo", "/"); cmp_path("cookie1=value1; Path=baz", "http://example.com/", "/"); cmp_path("cookie1=value1; Path=baz", "http://example.com", "/"); } #[test] fn path() { // Path specified, single / cmp_path( "cookie1=value1; Path=/baz", "http://example.com/foo/bar/", "/baz", ); // Path specified, multiple / (for valid attribute-value on path, take full // string) cmp_path( "cookie1=value1; Path=/baz/", "http://example.com/foo/bar/", "/baz/", ); } // expiry-related tests #[inline] fn in_days(days: i64) -> OffsetDateTime { OffsetDateTime::now_utc() + Duration::days(days) } #[inline] fn in_minutes(mins: i64) -> OffsetDateTime { OffsetDateTime::now_utc() + Duration::minutes(mins) } #[test] fn max_age_bounds() { let ua = test_utils::make_cookie( "cookie1=value1", "http://example.com/foo/bar", None, Some(9223372036854776), ); assert!(match ua.expires { CookieExpiration::AtUtc(_) => true, _ => false, }); } #[test] fn max_age() { let ua = test_utils::make_cookie( "cookie1=value1", "http://example.com/foo/bar", None, Some(60), ); assert!(!ua.is_expired()); assert!(ua.expires_by(&in_minutes(2))); } #[test] fn expired() { let ua = test_utils::make_cookie( "cookie1=value1", "http://example.com/foo/bar", None, Some(0u64), ); assert!(ua.is_expired()); assert!(ua.expires_by(&in_days(-1))); let ua = test_utils::make_cookie( "cookie1=value1; Max-Age=0", "http://example.com/foo/bar", None, None, ); assert!(ua.is_expired()); assert!(ua.expires_by(&in_days(-1))); let ua = test_utils::make_cookie( "cookie1=value1; Max-Age=-1", "http://example.com/foo/bar", None, None, ); assert!(ua.is_expired()); assert!(ua.expires_by(&in_days(-1))); } #[test] fn session_end() { let ua = test_utils::make_cookie("cookie1=value1", "http://example.com/foo/bar", None, None); assert!(match ua.expires { CookieExpiration::SessionEnd => true, _ => false, }); assert!(!ua.is_expired()); assert!(!ua.expires_by(&in_days(1))); assert!(!ua.expires_by(&in_days(-1))); } #[test] fn expires_tmrw_at_utc() { let ua = test_utils::make_cookie( "cookie1=value1", "http://example.com/foo/bar", Some(in_days(1)), None, ); assert!(!ua.is_expired()); assert!(ua.expires_by(&in_days(2))); } #[test] fn expired_yest_at_utc() { let ua = test_utils::make_cookie( "cookie1=value1", "http://example.com/foo/bar", Some(in_days(-1)), None, ); assert!(ua.is_expired()); assert!(!ua.expires_by(&in_days(-2))); } #[test] fn is_persistent() { let ua = test_utils::make_cookie("cookie1=value1", "http://example.com/foo/bar", None, None); assert!(!ua.is_persistent()); // SessionEnd let ua = test_utils::make_cookie( "cookie1=value1", "http://example.com/foo/bar", Some(in_days(1)), None, ); assert!(ua.is_persistent()); // AtUtc from Expires let ua = test_utils::make_cookie( "cookie1=value1", "http://example.com/foo/bar", Some(in_days(1)), Some(60), ); assert!(ua.is_persistent()); // AtUtc from Max-Age } #[test] fn max_age_overrides_expires() { // Expires indicates expiration yesterday, but Max-Age indicates expiry in 1 // minute let ua = test_utils::make_cookie( "cookie1=value1", "http://example.com/foo/bar", Some(in_days(-1)), Some(60), ); assert!(!ua.is_expired()); assert!(ua.expires_by(&in_minutes(2))); } // A request-path path-matches a given cookie-path if at least one of // the following conditions holds: // o The cookie-path and the request-path are identical. // o The cookie-path is a prefix of the request-path, and the last // character of the cookie-path is %x2F ("/"). // o The cookie-path is a prefix of the request-path, and the first // character of the request-path that is not included in the cookie- // path is a %x2F ("/") character. #[test] fn matches() { fn do_match(exp: bool, cookie: &str, src_url: &str, request_url: Option<&str>) { let ua = test_utils::make_cookie(cookie, src_url, None, None); let request_url = request_url.unwrap_or(src_url); assert!( exp == ua.matches(&Url::parse(request_url).unwrap()), "\n>> {:?}\nshould{}match\n>> {:?}\n", ua, if exp { " " } else { " NOT " }, request_url ); } fn is_match(cookie: &str, url: &str, request_url: Option<&str>) { do_match(true, cookie, url, request_url); } fn is_mismatch(cookie: &str, url: &str, request_url: Option<&str>) { do_match(false, cookie, url, request_url); } // match: request-path & cookie-path (defaulted from request-uri) identical is_match("cookie1=value1", "http://example.com/foo/bar", None); // mismatch: request-path & cookie-path do not match is_mismatch( "cookie1=value1", "http://example.com/bus/baz/", Some("http://example.com/foo/bar"), ); is_mismatch( "cookie1=value1; Path=/bus/baz", "http://example.com/foo/bar", None, ); // match: cookie-path a prefix of request-path and last character of // cookie-path is / is_match( "cookie1=value1", "http://example.com/foo/bar", Some("http://example.com/foo/bar"), ); is_match( "cookie1=value1; Path=/foo/", "http://example.com/foo/bar", None, ); // mismatch: cookie-path a prefix of request-path but last character of // cookie-path is not / // and first character of request-path not included in cookie-path is not / is_mismatch( "cookie1=value1", "http://example.com/fo/", Some("http://example.com/foo/bar"), ); is_mismatch( "cookie1=value1; Path=/fo", "http://example.com/foo/bar", None, ); // match: cookie-path a prefix of request-path and first character of // request-path // not included in the cookie-path is / is_match( "cookie1=value1", "http://example.com/foo/", Some("http://example.com/foo/bar"), ); is_match( "cookie1=value1; Path=/foo", "http://example.com/foo/bar", None, ); // match: Path overridden to /, which matches all paths from the domain is_match( "cookie1=value1; Path=/", "http://example.com/foo/bar", Some("http://example.com/bus/baz"), ); // mismatch: different domain is_mismatch( "cookie1=value1", "http://example.com/foo/", Some("http://notmydomain.com/foo/bar"), ); is_mismatch( "cookie1=value1; Domain=example.com", "http://foo.example.com/foo/", Some("http://notmydomain.com/foo/bar"), ); // match: secure protocol is_match( "cookie1=value1; Secure", "http://example.com/foo/bar", Some("https://example.com/foo/bar"), ); // mismatch: non-secure protocol is_mismatch( "cookie1=value1; Secure", "http://example.com/foo/bar", Some("http://example.com/foo/bar"), ); // match: no http restriction is_match( "cookie1=value1", "http://example.com/foo/bar", Some("ftp://example.com/foo/bar"), ); // match: http protocol is_match( "cookie1=value1; HttpOnly", "http://example.com/foo/bar", Some("http://example.com/foo/bar"), ); is_match( "cookie1=value1; HttpOnly", "http://example.com/foo/bar", Some("HTTP://example.com/foo/bar"), ); is_match( "cookie1=value1; HttpOnly", "http://example.com/foo/bar", Some("https://example.com/foo/bar"), ); // mismatch: http requried is_mismatch( "cookie1=value1; HttpOnly", "http://example.com/foo/bar", Some("ftp://example.com/foo/bar"), ); is_mismatch( "cookie1=value1; HttpOnly", "http://example.com/foo/bar", Some("data:nonrelativescheme"), ); } } #[cfg(test)] mod serde_tests { use serde_json::json; use time; use crate::cookie::Cookie; use crate::cookie_expiration::CookieExpiration; use crate::utils::test as test_utils; use crate::utils::test::*; fn encode_decode(c: &Cookie<'_>, expected: serde_json::Value) { let encoded = serde_json::to_value(c).unwrap(); assert_eq!( expected, encoded, "\nexpected: '{}'\n encoded: '{}'", expected.to_string(), encoded.to_string() ); let decoded: Cookie<'_> = serde_json::from_value(encoded).unwrap(); assert_eq!( *c, decoded, "\nexpected: '{}'\n decoded: '{}'", c.to_string(), decoded.to_string() ); } #[test] fn serde() { encode_decode( &test_utils::make_cookie("cookie1=value1", "http://example.com/foo/bar", None, None), json!({ "raw_cookie": "cookie1=value1", "path": ["/foo", false], "domain": { "HostOnly": "example.com" }, "expires": "SessionEnd" }), ); encode_decode( &test_utils::make_cookie( "cookie2=value2; Domain=example.com", "http://foo.example.com/foo/bar", None, None, ), json!({ "raw_cookie": "cookie2=value2; Domain=example.com", "path": ["/foo", false], "domain": { "Suffix": "example.com" }, "expires": "SessionEnd" }), ); encode_decode( &test_utils::make_cookie( "cookie3=value3; Path=/foo/bar", "http://foo.example.com/foo", None, None, ), json!({ "raw_cookie": "cookie3=value3; Path=/foo/bar", "path": ["/foo/bar", true], "domain": { "HostOnly": "foo.example.com" }, "expires": "SessionEnd", }), ); let at_utc = time::macros::date!(2015 - 08 - 11) .with_time(time::macros::time!(16:41:42)) .assume_utc(); encode_decode( &test_utils::make_cookie( "cookie4=value4", "http://example.com/foo/bar", Some(at_utc), None, ), json!({ "raw_cookie": "cookie4=value4; Expires=Tue, 11 Aug 2015 16:41:42 GMT", "path": ["/foo", false], "domain": { "HostOnly": "example.com" }, "expires": { "AtUtc": at_utc.format(crate::rfc3339_fmt::RFC3339_FORMAT).unwrap().to_string() }, }), ); let expires = test_utils::make_cookie( "cookie5=value5", "http://example.com/foo/bar", Some(in_minutes(10)), None, ); let utc_tm = match expires.expires { CookieExpiration::AtUtc(ref utc_tm) => utc_tm, CookieExpiration::SessionEnd => unreachable!(), }; let utc_formatted = utc_tm .format(&time::format_description::well_known::Rfc2822) .unwrap() .to_string() .replace("+0000", "GMT"); let raw_cookie_value = format!("cookie5=value5; Expires={utc_formatted}"); encode_decode( &expires, json!({ "raw_cookie": raw_cookie_value, "path":["/foo", false], "domain": { "HostOnly": "example.com" }, "expires": { "AtUtc": utc_tm.format(crate::rfc3339_fmt::RFC3339_FORMAT).unwrap().to_string() }, }), ); dbg!(&at_utc); let max_age = test_utils::make_cookie( "cookie6=value6", "http://example.com/foo/bar", Some(at_utc), Some(10), ); dbg!(&max_age); let utc_tm = match max_age.expires { CookieExpiration::AtUtc(ref utc_tm) => time::OffsetDateTime::parse( &utc_tm.format(crate::rfc3339_fmt::RFC3339_FORMAT).unwrap(), &time::format_description::well_known::Rfc3339, ) .expect("could not re-parse time"), CookieExpiration::SessionEnd => unreachable!(), }; dbg!(&utc_tm); encode_decode( &max_age, json!({ "raw_cookie": "cookie6=value6; Max-Age=10; Expires=Tue, 11 Aug 2015 16:41:42 GMT", "path":["/foo", false], "domain": { "HostOnly": "example.com" }, "expires": { "AtUtc": utc_tm.format(crate::rfc3339_fmt::RFC3339_FORMAT).unwrap().to_string() }, }), ); let max_age = test_utils::make_cookie( "cookie7=value7", "http://example.com/foo/bar", None, Some(10), ); let utc_tm = match max_age.expires { CookieExpiration::AtUtc(ref utc_tm) => utc_tm, CookieExpiration::SessionEnd => unreachable!(), }; encode_decode( &max_age, json!({ "raw_cookie": "cookie7=value7; Max-Age=10", "path":["/foo", false], "domain": { "HostOnly": "example.com" }, "expires": { "AtUtc": utc_tm.format(crate::rfc3339_fmt::RFC3339_FORMAT).unwrap().to_string() }, }), ); } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false
tmtbe/netpurr
https://github.com/tmtbe/netpurr/blob/922e0e29e2a4685249fafe7eba87bb4fffe7d72e/crates/cookie_store/src/cookie_expiration.rs
crates/cookie_store/src/cookie_expiration.rs
use std; use serde_derive::{Deserialize, Serialize}; use time::{self, OffsetDateTime}; /// When a given `Cookie` expires #[derive(Eq, Clone, Debug, Serialize, Deserialize)] pub enum CookieExpiration { /// `Cookie` expires at the given UTC time, as set from either the Max-Age /// or Expires attribute of a Set-Cookie header #[serde(with = "crate::rfc3339_fmt")] AtUtc(OffsetDateTime), /// `Cookie` expires at the end of the current `Session`; this means the cookie /// is not persistent SessionEnd, } // We directly impl `PartialEq` as the cookie Expires attribute does not include nanosecond precision impl std::cmp::PartialEq for CookieExpiration { fn eq(&self, other: &Self) -> bool { match (self, other) { (CookieExpiration::SessionEnd, CookieExpiration::SessionEnd) => true, (CookieExpiration::AtUtc(this_offset), CookieExpiration::AtUtc(other_offset)) => { // All instances should already be UTC offset this_offset.date() == other_offset.date() && this_offset.time().hour() == other_offset.time().hour() && this_offset.time().minute() == other_offset.time().minute() && this_offset.time().second() == other_offset.time().second() } _ => false, } } } impl CookieExpiration { /// Indicates if the `Cookie` is expired as of *now*. pub fn is_expired(&self) -> bool { self.expires_by(&time::OffsetDateTime::now_utc()) } /// Indicates if the `Cookie` expires as of `utc_tm`. pub fn expires_by(&self, utc_tm: &time::OffsetDateTime) -> bool { match *self { CookieExpiration::AtUtc(ref expire_tm) => *expire_tm <= *utc_tm, CookieExpiration::SessionEnd => false, } } } const MAX_RFC3339: time::OffsetDateTime = time::macros::date!(9999 - 12 - 31) .with_time(time::macros::time!(23:59:59)) .assume_utc(); impl From<u64> for CookieExpiration { fn from(max_age: u64) -> CookieExpiration { // make sure we don't trigger a panic! in Duration by restricting the seconds // to the max CookieExpiration::from(time::Duration::seconds(std::cmp::min( time::Duration::MAX.whole_seconds() as u64, max_age, ) as i64)) } } impl From<time::OffsetDateTime> for CookieExpiration { fn from(utc_tm: OffsetDateTime) -> CookieExpiration { CookieExpiration::AtUtc(utc_tm.min(MAX_RFC3339)) } } impl From<cookie::Expiration> for CookieExpiration { fn from(expiration: cookie::Expiration) -> CookieExpiration { match expiration { cookie::Expiration::DateTime(offset) => CookieExpiration::AtUtc(offset), cookie::Expiration::Session => CookieExpiration::SessionEnd, } } } impl From<time::Duration> for CookieExpiration { fn from(duration: time::Duration) -> Self { // If delta-seconds is less than or equal to zero (0), let expiry-time // be the earliest representable date and time. Otherwise, let the // expiry-time be the current date and time plus delta-seconds seconds. let utc_tm = if duration.is_zero() { time::OffsetDateTime::UNIX_EPOCH } else { let now_utc = time::OffsetDateTime::now_utc(); let d = (MAX_RFC3339 - now_utc).min(duration); now_utc + d }; CookieExpiration::from(utc_tm) } } #[cfg(test)] mod tests { use time; use crate::utils::test::*; use super::CookieExpiration; #[test] fn max_age_bounds() { match CookieExpiration::from(time::Duration::MAX.whole_seconds() as u64 + 1) { CookieExpiration::AtUtc(_) => assert!(true), _ => assert!(false), } } #[test] fn expired() { let ma = CookieExpiration::from(0u64); // Max-Age<=0 indicates the cookie is expired assert!(ma.is_expired()); assert!(ma.expires_by(&in_days(-1))); } #[test] fn max_age() { let ma = CookieExpiration::from(60u64); assert!(!ma.is_expired()); assert!(ma.expires_by(&in_minutes(2))); } #[test] fn session_end() { // SessionEnd never "expires"; lives until end of session let se = CookieExpiration::SessionEnd; assert!(!se.is_expired()); assert!(!se.expires_by(&in_days(1))); assert!(!se.expires_by(&in_days(-1))); } #[test] fn at_utc() { { let expire_tmrw = CookieExpiration::from(in_days(1)); assert!(!expire_tmrw.is_expired()); assert!(expire_tmrw.expires_by(&in_days(2))); } { let expired_yest = CookieExpiration::from(in_days(-1)); assert!(expired_yest.is_expired()); assert!(!expired_yest.expires_by(&in_days(-2))); } } }
rust
Apache-2.0
922e0e29e2a4685249fafe7eba87bb4fffe7d72e
2026-01-04T20:20:05.778379Z
false