Files
reqlite/crates/app/src/action.rs
T
Torbjörn Molin 1e7f8678eb
windows / build (push) Successful in 5m0s
Added custom auth support
2026-11-09 12:56:54 +01:00

1746 lines
62 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! `Action`s (what happened) and the pure `update` function that applies them
//! to [`AppState`] and returns [`Effect`]s (what to do outside: I/O, dialogs).
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::time::{Instant, SystemTime, UNIX_EPOCH};
use reqlite_core::collection::{self, Collection};
use reqlite_core::env::{self, Environments};
use reqlite_core::export::curl::to_curl;
use reqlite_core::folder::{
self, auth_mode, same_auth, with_inherited_auth, AuthHeader, AuthMode, FolderAuth, FolderSettings,
};
use reqlite_core::http::{HttpError, Response};
use reqlite_core::httpfile::{render_request, HttpFile};
use reqlite_core::import::curl::{from_curl, looks_like_curl};
use reqlite_core::params::{parse_params, with_params, Param};
use reqlite_core::resolve::resolve_request;
use reqlite_core::{Body, CancelToken, Header, Method, Request};
use crate::effects::{Effect, FileOp};
use crate::history::HistoryEntry;
use crate::settings::Settings;
use crate::state::*;
use crate::strings as txt;
#[derive(Debug)]
pub enum Action {
// Tabs.
NewTab,
CloseTab(TabId),
/// Close even with unsaved changes.
DiscardAndCloseTab(TabId),
/// Close several tabs; asks once about the ones with unsaved changes.
CloseTabs(Vec<TabId>),
DiscardAndCloseTabs(Vec<TabId>),
/// Rename the tab's request: in its file right away if the tab has no
/// other unsaved edits, else as an edit that Save writes.
RenameTab {
tab: TabId,
title: String,
},
SelectTab(TabId),
OpenRequest {
file: PathBuf,
index: usize,
},
NewTabFromHttp(String),
// Editing a tab.
SetMethod(TabId, Method),
UrlEdited(TabId, String),
ParamsEdited(TabId, Vec<Param>),
HeadersEdited(TabId, Vec<Header>),
BodyEdited(TabId, Body),
/// Sets the request's own Authorization header, `# @no-auth`, or
/// neither (it inherits its folder's auth).
AuthEdited(TabId, AuthMode),
SourceEdited(TabId, String),
SetRequestTab(TabId, RequestTab),
SetResponseTab(TabId, ResponseTab),
SetBodyView(TabId, BodyView),
SetNoRedirect(TabId, bool),
PickBodyFile(TabId),
BodyFilePicked(TabId, PathBuf),
// Sending.
Send(TabId),
Cancel(TabId),
ResponseReceived {
tab: TabId,
seq: u64,
result: Result<Response, HttpError>,
},
BodyPrepared {
tab: TabId,
seq: u64,
body: PreparedBody,
},
SaveResponseBody(TabId),
// Response search.
SearchOpen(TabId, bool),
SearchQuery(TabId, String),
SearchStep(TabId, i32),
ScrolledTo(TabId),
// Collections.
PickCollection,
OpenCollection(PathBuf),
CloseCollection(PathBuf),
/// Makes a collection the current one (environment picker, untitled tabs).
SetActiveCollection(PathBuf),
CollectionLoaded(Result<Collection, String>),
/// The environments, and whether the private file exists without being git-ignored.
EnvironmentsLoaded {
root: PathBuf,
result: Result<(Environments, bool), String>,
},
FileChangedOnDisk {
path: PathBuf,
text: Option<String>,
},
Rescan(PathBuf),
Save(TabId),
/// `existing` is the current content of `path`, if it exists.
SaveAs {
tab: TabId,
path: PathBuf,
existing: Option<String>,
},
ResolveConflict {
tab: TabId,
keep_mine: bool,
},
NewFile {
dir: PathBuf,
name: String,
},
NewRequestIn {
file: PathBuf,
},
RenameRequest {
file: PathBuf,
index: usize,
title: String,
},
DuplicateRequest {
file: PathBuf,
index: usize,
},
DeleteRequest {
file: PathBuf,
index: usize,
},
MoveRequest {
from: PathBuf,
index: usize,
to: PathBuf,
},
RenameFile {
path: PathBuf,
new_name: String,
},
DeleteFile(PathBuf),
DuplicateFile(PathBuf),
// Folder auth.
/// Opens the folder auth editor for a folder (or the collection root).
EditFolderAuth(PathBuf),
SetFolderAuth {
dir: PathBuf,
auth: FolderAuth,
},
/// Opens (or re-plans) the "Consolidate auth" dialog for a folder;
/// `target` picks the auth to inherit when the folder has none.
ConsolidateAuth {
dir: PathBuf,
target: Option<AuthHeader>,
},
ApplyConsolidateAuth(ConsolidateAuth),
// Environments.
SelectEnv(Option<String>),
OpenEnvEditor,
EnvEditorChanged(EnvEditor),
EnvEditorSave,
EnvEditorClose,
AddPrivateFileToGitignore(PathBuf),
DismissGitignoreOffer(PathBuf),
// Import / export.
CopyAsCurl(TabId),
CopyAsHttp(TabId),
ImportPostman,
PostmanImported {
root: PathBuf,
files: usize,
warnings: Vec<String>,
},
// History, cookies, settings.
HistoryLoaded(Vec<HistoryEntry>),
RestoreHistory(usize),
ClearHistory,
ClearCookies,
DeleteCookie(usize),
SettingsLoaded(Settings),
SettingsChanged(Settings),
PickCaFile,
CaFilePicked(PathBuf),
// Shell.
ShowDialog(Option<Dialog>),
SetWindows(Windows),
QuickOpen(Option<QuickOpen>),
FocusUrl,
UrlFocused,
CloseRequested,
ConfirmQuit,
Error(String),
Info(String),
DismissStatus,
}
/// Applies an action. The only place that changes [`AppState`].
pub fn update(state: &mut AppState, action: Action) -> Vec<Effect> {
let mut fx = Vec::new();
match action {
// ---------------------------------------------------------- tabs
Action::NewTab => {
new_tab(state, Request::default(), None, String::new());
state.focus_url = true;
}
Action::CloseTab(id) => {
if state.tab(id).is_some_and(Tab::is_dirty) {
state.dialog = Some(Dialog::ConfirmCloseTab(id));
} else {
close_tab(state, id);
}
}
Action::DiscardAndCloseTab(id) => {
state.dialog = None;
close_tab(state, id);
}
Action::CloseTabs(ids) => {
let mut dirty = Vec::new();
for id in ids {
if state.tab(id).is_some_and(Tab::is_dirty) {
dirty.push(id);
} else {
close_tab(state, id);
}
}
if !dirty.is_empty() {
state.dialog = Some(Dialog::ConfirmCloseTabs(dirty));
}
}
Action::DiscardAndCloseTabs(ids) => {
state.dialog = None;
for id in ids {
close_tab(state, id);
}
}
Action::RenameTab { tab, title } => {
state.dialog = None;
let Some(t) = state.tab(tab) else { return fx };
let in_file = t
.origin
.as_ref()
.filter(|_| !t.is_dirty())
.and_then(|o| Some((o.file.clone(), file_of(state, &o.file)?.find(&o.key)?)));
if let Some((file, index)) = in_file {
return update(state, Action::RenameRequest { file, index, title });
}
let title = title.trim().to_string();
edit(state, tab, |r| {
r.title = (!title.is_empty()).then_some(title);
if r.name.is_some() {
r.name = r.title.as_deref().map(slug_name);
}
});
}
Action::SelectTab(id) => {
if let Some(t) = state.tab(id) {
let root = t
.origin
.as_ref()
.and_then(|o| state.collection_of(&o.file))
.map(|c| c.root.clone());
state.active = Some(id);
if root.is_some() {
state.active_collection = root;
}
}
}
Action::OpenRequest { file, index } => open_request(state, &file, index),
Action::NewTabFromHttp(text) => {
let f = HttpFile::parse(text.clone());
match f.request(0) {
Some(r) => {
let mut r = r.clone();
r.source = Default::default();
let src = f.request_source(0).unwrap_or("").to_string();
new_tab(state, r, None, src);
}
None => state.set_error(txt::msg::NO_REQUEST_IN_TEXT),
}
}
// ---------------------------------------------------- editing
Action::SetMethod(id, m) => edit(state, id, |r| r.method = m),
Action::UrlEdited(id, url) => {
if looks_like_curl(&url) {
match from_curl(&url) {
Ok(mut req) => {
if let Some(t) = state.tab(id) {
req.title = t.request.title.clone();
req.name = t.request.name.clone();
}
edit(state, id, |r| *r = req);
state.set_info(txt::msg::CURL_IMPORTED);
}
Err(e) => {
state.set_error(txt::msg::curl_import_failed(e));
edit(state, id, |r| r.url = url);
}
}
} else {
edit(state, id, |r| r.url = url);
}
}
Action::ParamsEdited(id, params) => {
if let Some(t) = state.tab_mut(id) {
let url = with_params(&t.request.url, &params);
t.request.url = url;
// Keep the rows as the user has them (including a half-typed
// empty row) rather than re-deriving from the URL.
t.params = params;
after_form_edit(t);
}
}
Action::HeadersEdited(id, headers) => edit(state, id, |r| r.headers = headers),
Action::BodyEdited(id, body) => edit(state, id, |r| r.body = body),
Action::AuthEdited(id, mode) => edit(state, id, |r| folder::set_auth_mode(r, &mode)),
Action::SetNoRedirect(id, on) => edit(state, id, |r| r.directives.no_redirect = on),
Action::PickBodyFile(id) => fx.push(Effect::PickBodyFile(id)),
Action::BodyFilePicked(id, path) => {
let Some(t) = state.tab(id) else { return fx };
// Store it relative to the .http file when possible, like `< ./x`.
let base = state.base_dir_for(t);
let path = match path.strip_prefix(&base) {
Ok(rel) => Path::new(".").join(rel),
Err(_) => path,
};
let substitute = matches!(t.request.body, Body::FileRef { substitute: true, .. });
edit(state, id, |r| r.body = Body::FileRef { path, substitute });
}
Action::SourceEdited(id, text) => {
if let Some(t) = state.tab_mut(id) {
let f = HttpFile::parse(text.clone());
t.source = text;
t.source_authoritative = true;
match f.request_count() {
1 => {
let mut r = f.request(0).unwrap().clone();
r.source = t.request.source;
t.params = parse_params(&r.url);
t.request = r;
t.source_error = None;
}
0 => t.source_error = Some(txt::msg::NO_REQUEST_LINE.into()),
n => t.source_error = Some(txt::msg::not_one_request(n)),
}
}
}
Action::SetRequestTab(id, rt) => {
if let Some(t) = state.tab_mut(id) {
t.request_tab = rt;
}
}
Action::SetResponseTab(id, rt) => {
if let Some(t) = state.tab_mut(id) {
t.response_tab = rt;
}
}
Action::SetBodyView(id, v) => {
if let Some(t) = state.tab_mut(id) {
t.body_view = v;
recompute_search(t);
}
}
// ---------------------------------------------------- sending
Action::Send(id) => send(state, id, &mut fx),
Action::Cancel(id) => {
if let Some(t) = state.tab_mut(id) {
if let Some(f) = t.in_flight.take() {
f.cancel.cancel();
t.error = Some(txt::msg::CANCELLED.into());
}
}
}
Action::ResponseReceived { tab, seq, result } => receive(state, tab, seq, result, &mut fx),
Action::BodyPrepared { tab, seq, body } => {
if let Some(t) = state.tab_mut(tab) {
if t.seq == seq {
if let Some(r) = &mut t.response {
r.prepared = Some(body);
}
recompute_search(t);
}
}
}
Action::SaveResponseBody(id) => {
if let Some(r) = state.tab(id).and_then(|t| t.response.as_ref()) {
fx.push(Effect::SaveResponseBody {
body: r.response.body.clone(),
suggested_name: suggested_file_name(&r.response),
});
}
}
// ---------------------------------------------------- search
Action::SearchOpen(id, open) => {
if let Some(t) = state.tab_mut(id) {
t.search.open = open;
if open {
t.response_tab = ResponseTab::Body;
}
}
}
Action::SearchQuery(id, q) => {
if let Some(t) = state.tab_mut(id) {
t.search.query = q;
t.search.current = 0;
recompute_search(t);
t.search.scroll_to = t.search.matches.first().map(|m| m.0);
}
}
Action::SearchStep(id, delta) => {
if let Some(t) = state.tab_mut(id) {
let n = t.search.matches.len();
if n > 0 {
t.search.current = (t.search.current as i64 + delta as i64).rem_euclid(n as i64) as usize;
t.search.scroll_to = Some(t.search.matches[t.search.current].0);
}
}
}
Action::ScrolledTo(id) => {
if let Some(t) = state.tab_mut(id) {
t.search.scroll_to = None;
}
}
// ---------------------------------------------------- collections
Action::PickCollection => fx.push(Effect::PickCollectionFolder),
Action::OpenCollection(root) => {
if state.collection(&root).is_some() {
state.active_collection = Some(root);
return fx;
}
if let Some(other) = state
.collections
.iter()
.find(|c| root.starts_with(&c.root) || c.root.starts_with(&root))
{
state.set_error(txt::msg::overlaps(root.display(), other.root.display()));
return fx;
}
state.settings.add_recent(root.clone());
if !state.settings.open_collections.contains(&root) {
state.settings.open_collections.push(root.clone());
}
fx.push(Effect::SaveSettings(state.settings.clone()));
fx.push(Effect::LoadCollection(root));
}
Action::CloseCollection(root) => {
let Some(pos) = state.collections.iter().position(|c| c.root == root) else {
return fx;
};
state.collections.remove(pos);
fx.push(Effect::Unwatch(root.clone()));
state.settings.open_collections.retain(|r| r != &root);
fx.push(Effect::SaveSettings(state.settings.clone()));
state.cookie_jars.remove(&Some(root.clone()));
if state.env_editor.as_ref().is_some_and(|e| e.root == root) {
state.env_editor = None;
}
if state.active_collection.as_ref() == Some(&root) {
state.active_collection = state.collections.first().map(|c| c.root.clone());
}
// Clean tabs from it close; tabs with edits stay, detached from their file.
let ids: Vec<(TabId, bool)> = state
.tabs
.iter()
.filter(|t| t.origin.as_ref().is_some_and(|o| o.file.starts_with(&root)))
.map(|t| (t.id, t.is_dirty()))
.collect();
for (id, dirty) in ids {
if dirty {
if let Some(t) = state.tab_mut(id) {
t.origin = None;
t.orphaned = true;
}
} else {
close_tab(state, id);
}
}
}
Action::SetActiveCollection(root) => {
if state.collection(&root).is_some() {
state.active_collection = Some(root);
}
}
Action::CollectionLoaded(Err(e)) => state.set_error(txt::msg::collection_failed(e)),
Action::CollectionLoaded(Ok(c)) => collection_loaded(state, c, &mut fx),
Action::EnvironmentsLoaded { root, result } => {
if let Some(c) = state.collection_mut(&root) {
match result {
Ok((envs, private_not_ignored)) => {
c.envs = envs;
c.env_error = None;
c.private_not_ignored = private_not_ignored;
if c.selected_env.as_ref().is_some_and(|sel| !c.envs.names().contains(sel)) {
c.selected_env = None;
}
}
Err(e) => c.env_error = Some(e),
}
}
}
Action::FileChangedOnDisk { path, text } => file_changed(state, path, text, &mut fx),
Action::Rescan(root) => {
if state.collection(&root).is_some() {
fx.push(Effect::LoadCollection(root));
}
}
Action::Save(id) => save(state, id, &mut fx),
Action::SaveAs { tab, path, existing } => save_as(state, tab, path, existing, &mut fx),
Action::ResolveConflict { tab, keep_mine } => {
state.dialog = None;
if !keep_mine {
if let Some(t) = state.tab(tab) {
if let Some(o) = t.origin.clone() {
reload_tab_from_file(state, tab, &o.file);
}
}
}
}
Action::NewFile { dir, name } => {
state.dialog = None;
let name = name.trim();
if name.is_empty() {
return fx;
}
let name = if collection::is_http_file(Path::new(name)) {
name.to_string()
} else {
format!("{name}.http")
};
let path = dir.join(name);
if state.collection_of(&path).is_some_and(|c| c.files.contains_key(&path)) {
state.set_error(txt::msg::already_exists(path.display()));
return fx;
}
let req = Request {
title: Some(txt::common::NEW_REQUEST.into()),
..Request::default()
};
let text = render_request(&req, "\n");
fx.push(file_ops(state, vec![FileOp::Write(path.clone(), text.clone())], true));
insert_file(state, &path, text);
open_request(state, &path, 0);
}
Action::NewRequestIn { file } => {
let Some(f) = file_of(state, &file) else { return fx };
let n = f.request_count();
let req = Request {
title: Some(unique_title(f, txt::common::NEW_REQUEST)),
..Request::default()
};
let text = f.insert_request(None, &req);
fx.push(file_ops(state, vec![FileOp::Write(file.clone(), text.clone())], false));
insert_file(state, &file, text);
open_request(state, &file, n);
state.focus_url = true;
}
Action::RenameRequest { file, index, title } => {
state.dialog = None;
let Some(f) = file_of(state, &file) else { return fx };
let Some(old) = f.request(index).cloned() else {
return fx;
};
let mut req = old.clone();
let title = title.trim().to_string();
req.title = (!title.is_empty()).then_some(title);
// A rename should rename: drop an @name that would shadow the title.
if req.name.is_some() {
req.name = req.title.as_deref().map(slug_name);
}
let Some(text) = f.replace_request(index, &req) else {
return fx;
};
fx.push(file_ops(state, vec![FileOp::Write(file.clone(), text.clone())], false));
insert_file(state, &file, text);
// Keep open tabs pointing at the renamed request.
let new_key = file_of(state, &file).and_then(|f| f.key_of(index));
for t in state.tabs.iter_mut() {
if let Some(o) = &mut t.origin {
if o.file == file && o.key.index == index {
if let Some(k) = &new_key {
o.key = k.clone();
}
t.request.title = req.title.clone();
t.request.name = req.name.clone();
t.saved.title = req.title.clone();
t.saved.name = req.name.clone();
refresh_source(t);
}
}
}
}
Action::DuplicateRequest { file, index } => {
let Some(f) = file_of(state, &file) else { return fx };
let Some(src) = f.request_source(index) else { return fx };
let orig = f.request(index).cloned().unwrap_or_default();
// Re-title the copy so its key is unique.
let base = orig.display_name().unwrap_or(txt::names::REQUEST).to_string();
let mut copy = HttpFile::parse(src.to_string());
let mut r = copy.request(0).cloned().unwrap_or_default();
r.title = Some(unique_title(f, &txt::names::copy_of(&base)));
r.name = r.name.as_ref().map(|_| slug_name(r.title.as_deref().unwrap()));
if let Some(t) = copy.replace_request(0, &r) {
copy = HttpFile::parse(t);
}
let block = if copy.text().starts_with("###") {
copy.text().to_string()
} else {
format!("###\n{}", copy.text())
};
let text = f.insert_request_text(Some(index), &block);
fx.push(file_ops(state, vec![FileOp::Write(file.clone(), text.clone())], false));
shift_origins(state, &file, index + 1, 1);
insert_file(state, &file, text);
open_request(state, &file, index + 1);
}
Action::DeleteRequest { file, index } => {
state.dialog = None;
let Some(f) = file_of(state, &file) else { return fx };
let Some(text) = f.remove_request(index) else { return fx };
fx.push(file_ops(state, vec![FileOp::Write(file.clone(), text.clone())], false));
orphan_tabs(state, &file, Some(index));
shift_origins(state, &file, index + 1, -1);
insert_file(state, &file, text);
}
Action::MoveRequest { from, index, to } => {
if from == to {
return fx;
}
let (Some(src_file), Some(dst_file)) = (file_of(state, &from), file_of(state, &to)) else {
return fx;
};
let Some(block) = src_file.request_source(index) else {
return fx;
};
let mut block = block.to_string();
if !block.starts_with("###") {
block = format!("###\n{block}");
}
let new_index = dst_file.request_count();
let Some(src_text) = src_file.remove_request(index) else {
return fx;
};
let dst_text = dst_file.insert_request_text(None, &block);
fx.push(file_ops(
state,
vec![
FileOp::Write(to.clone(), dst_text.clone()),
FileOp::Write(from.clone(), src_text.clone()),
],
false,
));
// Tabs follow the request to its new file.
for t in state.tabs.iter_mut() {
if let Some(o) = &mut t.origin {
if o.file == from && o.key.index == index {
o.file = to.clone();
o.key.index = new_index;
}
}
}
shift_origins(state, &from, index + 1, -1);
insert_file(state, &to, dst_text);
insert_file(state, &from, src_text);
}
Action::RenameFile { path, new_name } => {
state.dialog = None;
let new_name = new_name.trim();
if new_name.is_empty() {
return fx;
}
let new_name = if collection::is_http_file(Path::new(new_name)) {
new_name.to_string()
} else {
format!("{new_name}.http")
};
let Some(dir) = path.parent() else { return fx };
let to = dir.join(new_name);
if to == path {
return fx;
}
fx.push(file_ops(state, vec![FileOp::Rename(path.clone(), to.clone())], true));
for t in state.tabs.iter_mut() {
if let Some(o) = &mut t.origin {
if o.file == path {
o.file = to.clone();
}
}
}
if let Some(c) = state.collection_of_mut(&path) {
if let Some(f) = c.files.remove(&path) {
c.files.insert(to, f);
}
}
}
Action::DuplicateFile(path) => {
let Some(f) = file_of(state, &path) else { return fx };
let text = f.text().to_string();
let stem = path
.file_stem()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_default();
let ext = path
.extension()
.map(|e| e.to_string_lossy().into_owned())
.unwrap_or("http".into());
let dir = path.parent().map(Path::to_path_buf).unwrap_or_default();
let taken = |p: &PathBuf| state.collection_of(p).is_some_and(|c| c.files.contains_key(p));
let copy = std::iter::once(dir.join(txt::names::file_copy(&stem, &ext)))
.chain((2..).map(|n| dir.join(txt::names::file_copy_n(&stem, n, &ext))))
.find(|p| !taken(p))
.unwrap();
fx.push(file_ops(state, vec![FileOp::Write(copy.clone(), text.clone())], true));
insert_file(state, &copy, text);
}
Action::DeleteFile(path) => {
state.dialog = None;
fx.push(file_ops(state, vec![FileOp::Delete(path.clone())], true));
orphan_tabs(state, &path, None);
if let Some(c) = state.collection_of_mut(&path) {
c.files.remove(&path);
}
}
// ---------------------------------------------------- folder auth
Action::EditFolderAuth(dir) => {
if let Some(c) = state.collection_of(&dir) {
state.dialog = Some(Dialog::FolderAuth(FolderAuthEdit {
auth: c.folder_auth(&dir),
dir,
}));
}
}
Action::SetFolderAuth { dir, auth } => {
state.dialog = None;
let Some(c) = state.collection_of_mut(&dir) else {
return fx;
};
let mut settings = c.folders.get(&dir).cloned().unwrap_or_default();
settings.auth = auth;
let path = folder::settings_path(&dir);
let op = if settings.is_empty() {
c.folders.remove(&dir).map(|_| FileOp::Delete(path))
} else {
let json = settings.to_json();
c.folders.insert(dir, settings);
Some(FileOp::Write(path, json))
};
if let Some(op) = op {
fx.push(Effect::FileOps {
ops: vec![op],
rescan: None,
});
}
}
Action::ConsolidateAuth { dir, target } => {
state.dialog = plan_consolidation(state, &dir, target).map(Dialog::ConsolidateAuth);
}
Action::ApplyConsolidateAuth(plan) => apply_consolidation(state, plan, &mut fx),
// ---------------------------------------------------- environments
Action::SelectEnv(e) => {
let Some(root) = state.current_collection().map(|c| c.root.clone()) else {
return fx;
};
if let Some(c) = state.collection_mut(&root) {
c.selected_env = e;
}
state.active_collection = Some(root);
}
Action::OpenEnvEditor => {
if let Some(c) = state.current_collection() {
let selected = c
.selected_env
.clone()
.or_else(|| c.envs.names().first().cloned())
.unwrap_or_else(|| "dev".into());
state.env_editor = Some(EnvEditor {
root: c.root.clone(),
envs: c.envs.clone(),
selected,
revealed: Vec::new(),
dirty: false,
});
} else {
state.set_error(txt::msg::NEED_COLLECTION_FOR_ENVS);
}
}
Action::EnvEditorChanged(e) => state.env_editor = Some(e),
Action::EnvEditorClose => state.env_editor = None,
Action::EnvEditorSave => {
let Some(ed) = &mut state.env_editor else { return fx };
let Some(c) = state.collections.iter_mut().find(|c| c.root == ed.root) else {
return fx;
};
let mut ops = Vec::new();
if ed.envs.public != c.envs.public {
ops.push(FileOp::Write(c.root.join(env::PUBLIC_FILE), ed.envs.public.to_json()));
}
if ed.envs.private != c.envs.private {
ops.push(FileOp::Write(c.root.join(env::PRIVATE_FILE), ed.envs.private.to_json()));
}
c.envs = ed.envs.clone();
ed.dirty = false;
if !ops.is_empty() {
fx.push(Effect::FileOps { ops, rescan: None });
// Re-check whether the private file is git-ignored.
fx.push(Effect::LoadEnvironments(c.root.clone()));
}
}
Action::AddPrivateFileToGitignore(root) => {
if let Some(c) = state.collection_mut(&root) {
fx.push(Effect::AppendGitignore(root));
c.private_not_ignored = false;
}
}
Action::DismissGitignoreOffer(root) => {
if let Some(c) = state.collection_mut(&root) {
c.gitignore_offer_dismissed = true;
}
}
// ---------------------------------------------------- import/export
Action::CopyAsCurl(id) => {
let Some(t) = state.tab(id) else { return fx };
let resolver = state.resolver_for(t);
match resolve_request(
&with_inherited_auth(&t.request, state.inherited_auth_for(t).as_ref()),
&resolver,
&state.base_dir_for(t),
&state.settings.request_options(),
) {
Ok(r) => {
fx.push(Effect::CopyToClipboard(to_curl(&r)));
state.set_info(txt::msg::COPIED_CURL);
}
Err(e) => state.set_error(txt::msg::curl_failed(e)),
}
}
Action::CopyAsHttp(id) => {
let Some(t) = state.tab(id) else { return fx };
let text = if t.source.trim().is_empty() {
render_request(&t.request, "\n")
} else {
t.source.clone()
};
fx.push(Effect::CopyToClipboard(text));
state.set_info(txt::msg::COPIED_HTTP);
}
Action::ImportPostman => fx.push(Effect::PickPostmanImport),
Action::PostmanImported { root, files, warnings } => {
state.dialog = Some(Dialog::ImportSummary {
root: root.clone(),
files,
warnings,
});
return update(state, Action::OpenCollection(root));
}
// ---------------------------------------------------- history etc.
Action::HistoryLoaded(h) => state.history = h,
Action::RestoreHistory(i) => {
if let Some(e) = state.history.get(i) {
let text = e.http.clone();
let env = e.env.clone();
let root = state.current_collection().map(|c| c.root.clone());
if let (Some(env), Some(root)) = (env, root) {
if let Some(c) = state.collection_mut(&root) {
if c.envs.names().contains(&env) {
c.selected_env = Some(env);
}
}
}
return update(state, Action::NewTabFromHttp(text));
}
}
Action::ClearHistory => {
state.history.clear();
fx.push(Effect::RewriteHistory(Vec::new()));
}
Action::ClearCookies => {
let key = state.current_collection().map(|c| c.root.clone());
state.cookie_jars.entry(key).or_default().clear();
}
Action::DeleteCookie(i) => {
let key = state.current_collection().map(|c| c.root.clone());
state.cookie_jars.entry(key).or_default().remove(i);
}
Action::SettingsLoaded(s) => {
fx.push(Effect::SetConcurrency(s.max_concurrent_requests));
state.settings = s;
}
Action::SettingsChanged(s) => {
if s.max_concurrent_requests != state.settings.max_concurrent_requests {
fx.push(Effect::SetConcurrency(s.max_concurrent_requests));
}
state.settings = s;
fx.push(Effect::SaveSettings(state.settings.clone()));
}
Action::PickCaFile => fx.push(Effect::PickCaFile),
Action::CaFilePicked(p) => {
state.settings.ca_file = Some(p);
fx.push(Effect::SaveSettings(state.settings.clone()));
}
// ---------------------------------------------------- shell
Action::ShowDialog(d) => state.dialog = d,
Action::SetWindows(w) => state.windows = w,
Action::QuickOpen(q) => state.quick_open = q,
Action::FocusUrl => state.focus_url = true,
Action::UrlFocused => state.focus_url = false,
Action::CloseRequested => {
if state.any_dirty() && !state.quit_confirmed {
state.dialog = Some(Dialog::ConfirmQuit);
} else {
state.quit_confirmed = true;
fx.push(Effect::Quit);
}
}
Action::ConfirmQuit => {
state.dialog = None;
state.quit_confirmed = true;
fx.push(Effect::Quit);
}
Action::Error(e) => state.set_error(e),
Action::Info(i) => state.set_info(i),
Action::DismissStatus => state.status = None,
}
fx
}
// ------------------------------------------------------------------ helpers
fn new_tab(state: &mut AppState, req: Request, origin: Option<Origin>, source: String) -> TabId {
let id = state.alloc_tab_id();
let source = if source.is_empty() && !req.url.is_empty() {
render_request(&req, "\n")
} else {
source
};
state.tabs.push(Tab::new(id, req, origin, source));
state.active = Some(id);
id
}
fn close_tab(state: &mut AppState, id: TabId) {
let Some(pos) = state.tabs.iter().position(|t| t.id == id) else {
return;
};
let tab = state.tabs.remove(pos);
if let Some(f) = tab.in_flight {
f.cancel.cancel();
}
if state.active == Some(id) {
state.active = state
.tabs
.get(pos)
.or_else(|| state.tabs.get(pos.wrapping_sub(1)))
.map(|t| t.id);
}
}
fn file_of<'a>(state: &'a AppState, path: &Path) -> Option<&'a HttpFile> {
state.collection_of(path)?.files.get(path)
}
fn insert_file(state: &mut AppState, path: &Path, text: String) {
if let Some(c) = state.collection_of_mut(path) {
c.files.insert(path.to_path_buf(), HttpFile::parse(text));
}
}
/// File operations, followed by a rescan of the collection of the first
/// operation's file when `rescan` is set.
fn file_ops(state: &AppState, ops: Vec<FileOp>, rescan: bool) -> Effect {
let first = ops.first().map(|op| match op {
FileOp::Write(p, _) | FileOp::Delete(p) | FileOp::Rename(p, _) => p.clone(),
});
Effect::FileOps {
rescan: first
.filter(|_| rescan)
.and_then(|p| state.collection_of(&p))
.map(|c| c.root.clone()),
ops,
}
}
fn open_request(state: &mut AppState, file: &Path, index: usize) {
// Focus an existing tab for the same request.
if let Some(t) = state.tabs.iter().find(|t| {
t.origin
.as_ref()
.is_some_and(|o| o.file == file && o.key.index == index)
}) {
state.active = Some(t.id);
return;
}
let Some(f) = file_of(state, file) else { return };
let (Some(req), Some(key), Some(src)) = (f.request(index), f.key_of(index), f.request_source(index)) else {
return;
};
let (req, src) = (req.clone(), src.to_string());
state.active_collection = state.collection_of(file).map(|c| c.root.clone());
new_tab(
state,
req,
Some(Origin {
file: file.to_path_buf(),
key,
}),
src,
);
}
/// Applies a form edit to a tab's request.
fn edit(state: &mut AppState, id: TabId, f: impl FnOnce(&mut Request)) {
if let Some(t) = state.tab_mut(id) {
f(&mut t.request);
t.params = parse_params(&t.request.url);
after_form_edit(t);
}
}
fn after_form_edit(t: &mut Tab) {
t.source_authoritative = false;
t.source_error = None;
refresh_source(t);
}
/// Regenerates the Source text from the form, keeping comments and other
/// unmodelled parts of the saved text.
fn refresh_source(t: &mut Tab) {
let base = HttpFile::parse(t.saved_source.clone());
t.source = if base.request_count() == 1 {
base.replace_request(0, &t.request)
.unwrap_or_else(|| render_request(&t.request, "\n"))
} else {
render_request(&t.request, "\n")
};
}
fn send(state: &mut AppState, id: TabId, fx: &mut Vec<Effect>) {
let Some(t) = state.tab(id) else { return };
if t.in_flight.is_some() {
return;
}
if let Some(e) = &t.source_error {
let e = e.clone();
if let Some(t) = state.tab_mut(id) {
t.error = Some(txt::msg::fix_source(e));
}
return;
}
let resolver = state.resolver_for(t);
let base_dir = state.base_dir_for(t);
let inherited = state.inherited_auth_for(t);
let req = with_inherited_auth(&t.request, inherited.as_ref());
let resolved = resolve_request(&req, &resolver, &base_dir, &state.settings.request_options());
let mut resolved = match resolved {
Ok(r) => r,
Err(e) => {
if let Some(t) = state.tab_mut(id) {
t.error = Some(e.to_string());
t.response = None;
}
return;
}
};
let collection = state.collection_for_tab(t);
let jar_key = (!t.request.directives.no_cookie_jar).then(|| collection.map(|c| c.root.clone()));
let env = collection.and_then(|c| c.selected_env.clone());
if let Some(key) = &jar_key {
let has_cookie = resolved.headers.iter().any(|(n, _)| n.eq_ignore_ascii_case("cookie"));
if let Some(c) = state
.cookie_jars
.get(key)
.and_then(|j| j.header_for(&resolved.url, SystemTime::now()))
{
if !has_cookie {
resolved.headers.push(("Cookie".into(), c));
}
}
}
let history = HistoryEntry {
at: SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0),
method: resolved.method.clone(),
url: resolved.url.clone(),
status: None,
duration_ms: 0,
env,
http: if t.source.trim().is_empty() {
render_request(&t.request, "\n")
} else {
t.source.clone()
},
error: None,
};
let no_log = t.request.directives.no_log;
let cancel = CancelToken::new();
let t = state.tab_mut(id).unwrap();
t.seq += 1;
t.error = None;
t.search.matches.clear();
t.in_flight = Some(InFlight {
cancel: cancel.clone(),
started: Instant::now(),
seq: t.seq,
history: HistoryEntry {
// `@no-log` keeps the request out of history.
http: if no_log { String::new() } else { history.http },
..history
},
cookie_jar: jar_key,
url: resolved.url.clone(),
});
fx.push(Effect::SendRequest {
tab: id,
seq: t.seq,
request: resolved,
cancel,
});
}
fn receive(state: &mut AppState, id: TabId, seq: u64, result: Result<Response, HttpError>, fx: &mut Vec<Effect>) {
let Some(t) = state.tab_mut(id) else { return };
if t.seq != seq {
return; // a newer request replaced this one
}
let Some(flight) = t.in_flight.take() else {
return; // cancelled
};
let mut entry = flight.history;
entry.duration_ms = flight.started.elapsed().as_millis() as u64;
match result {
Ok(resp) => {
entry.status = Some(resp.status);
entry.duration_ms = resp.timings.total.as_millis() as u64;
fx.push(Effect::PrepareBody {
tab: id,
seq,
body: resp.body.clone(),
content_type: resp.content_type().to_string(),
});
let set_cookies: Vec<String> = resp.headers_named("set-cookie").map(str::to_string).collect();
t.response = Some(ResponseView {
response: resp,
received_at: SystemTime::now(),
prepared: None,
});
t.error = None;
if let Some(key) = flight.cookie_jar {
state.cookie_jars.entry(key).or_default().store(
&flight.url,
set_cookies.iter().map(String::as_str),
SystemTime::now(),
);
}
}
Err(HttpError::Cancelled) => return,
Err(e) => {
entry.error = Some(e.to_string());
t.error = Some(e.to_string());
t.response = None;
}
}
if !entry.http.is_empty() {
state.history.push(entry.clone());
let limit = state.settings.history_limit.max(1);
if state.history.len() > limit {
let excess = state.history.len() - limit;
state.history.drain(..excess);
}
fx.push(Effect::AppendHistory(entry));
}
}
fn suggested_file_name(r: &Response) -> String {
let last = r
.effective_url
.split(['?', '#'])
.next()
.unwrap_or("")
.rsplit('/')
.next()
.unwrap_or("")
.to_string();
let ext = match r.content_type().split(';').next().unwrap_or("").trim() {
"application/json" => "json",
"text/html" => "html",
"text/plain" => "txt",
"application/xml" | "text/xml" => "xml",
"image/png" => "png",
"image/jpeg" => "jpg",
"application/pdf" => "pdf",
_ => "bin",
};
if !last.is_empty() && last.contains('.') {
last
} else if !last.is_empty() {
format!("{last}.{ext}")
} else {
format!("response.{ext}")
}
}
/// Recomputes search matches over the visible body text.
fn recompute_search(t: &mut Tab) {
t.search.matches.clear();
let q = t.search.query.to_lowercase();
if q.is_empty() {
return;
}
let Some(prepared) = t.response.as_ref().and_then(|r| r.prepared.as_ref()) else {
return;
};
let lines = prepared.text(t.body_view);
const MAX: usize = 10_000;
for i in 0..lines.line_count() {
let line = lines.line(i);
let lower = line.to_lowercase();
// Byte offsets only line up when lowercasing kept the length.
if lower.len() != line.len() {
continue;
}
let mut from = 0;
while let Some(pos) = lower[from..].find(&q) {
let start = from + pos;
t.search.matches.push((i, start..start + q.len()));
from = start + q.len().max(1);
if t.search.matches.len() >= MAX {
return;
}
}
}
if t.search.current >= t.search.matches.len() {
t.search.current = 0;
}
}
fn collection_loaded(state: &mut AppState, c: Collection, fx: &mut Vec<Effect>) {
let root = c.root.clone();
match state.collection_mut(&root) {
Some(existing) => {
// A rescan: keep environments and choices, take the new tree.
existing.tree = c.tree;
existing.files = c.files;
existing.folders = c.folders;
existing.folder_errors = c.folder_errors;
let ids: Vec<(TabId, PathBuf)> = state
.tabs
.iter()
.filter_map(|t| t.origin.as_ref().map(|o| (t.id, o.file.clone())))
.filter(|(_, f)| f.starts_with(&root))
.collect();
for (id, file) in ids {
if file_of(state, &file).is_none() {
if let Some(t) = state.tab_mut(id) {
t.orphaned = true;
}
}
}
}
None => {
state.collections.push(CollectionState {
root: c.root,
tree: c.tree,
files: c.files,
folders: c.folders,
folder_errors: c.folder_errors,
envs: Environments::default(),
selected_env: None,
env_error: None,
private_not_ignored: false,
gitignore_offer_dismissed: false,
});
state.active_collection = Some(root.clone());
fx.push(Effect::Watch(root.clone()));
}
}
fx.push(Effect::LoadEnvironments(root));
}
fn file_changed(state: &mut AppState, path: PathBuf, text: Option<String>, fx: &mut Vec<Effect>) {
let Some(c) = state.collection_of_mut(&path) else {
return;
};
let root = c.root.clone();
if let Some(dir) = folder::settings_dir(&path) {
let dir = dir.to_path_buf();
c.folder_errors.clear();
match text.map(|t| FolderSettings::parse(&t, &path)) {
None => {
c.folders.remove(&dir);
}
Some(Ok(s)) => {
c.folders.insert(dir, s);
}
Some(Err(e)) => c.folder_errors.push(e.to_string()),
}
return;
}
let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
if name == env::PUBLIC_FILE || name == env::PRIVATE_FILE {
// Only the env files at the collection root count.
if path.parent() == Some(root.as_path()) {
fx.push(Effect::LoadEnvironments(root));
}
return;
}
if !collection::is_http_file(&path) {
return;
}
match text {
None => {
if c.files.remove(&path).is_some() {
orphan_tabs(state, &path, None);
fx.push(Effect::LoadCollection(root));
}
}
Some(text) => {
if c.files.get(&path).is_some_and(|f| f.text() == text) {
return; // our own write, or no real change
}
let is_new = !c.files.contains_key(&path);
c.files.insert(path.clone(), HttpFile::parse(text));
if is_new {
fx.push(Effect::LoadCollection(root));
}
let ids: Vec<TabId> = state
.tabs
.iter()
.filter(|t| t.origin.as_ref().is_some_and(|o| o.file == path))
.map(|t| t.id)
.collect();
for id in ids {
let dirty = state.tab(id).is_some_and(Tab::is_dirty);
if dirty {
state.dialog = Some(Dialog::Conflict {
tab: id,
path: path.clone(),
});
} else {
reload_tab_from_file(state, id, &path);
}
}
}
}
}
/// Replaces a tab's request with the version in its file.
fn reload_tab_from_file(state: &mut AppState, id: TabId, path: &Path) {
let Some(key) = state.tab(id).and_then(|t| t.origin.as_ref()).map(|o| o.key.clone()) else {
return;
};
let found = file_of(state, path).and_then(|f| {
let i = f.find(&key)?;
Some((f.request(i)?.clone(), f.request_source(i)?.to_string(), f.key_of(i)?))
});
let Some(t) = state.tab_mut(id) else { return };
match found {
Some((req, src, key)) => {
t.params = parse_params(&req.url);
t.request = req.clone();
t.saved = req;
t.source = src.clone();
t.saved_source = src;
t.source_authoritative = false;
t.source_error = None;
t.orphaned = false;
if let Some(o) = &mut t.origin {
o.key = key;
}
}
None => t.orphaned = true,
}
}
/// Marks tabs whose request no longer exists in its file.
fn orphan_tabs(state: &mut AppState, file: &Path, index: Option<usize>) {
for t in state.tabs.iter_mut() {
if let Some(o) = &t.origin {
if o.file == file && index.is_none_or(|i| o.key.index == i) {
t.origin = None;
t.orphaned = true;
}
}
}
}
/// Shifts the index of tabs pointing at requests `from..` in `file`.
fn shift_origins(state: &mut AppState, file: &Path, from: usize, delta: i64) {
for t in state.tabs.iter_mut() {
if let Some(o) = &mut t.origin {
if o.file == file && o.key.index >= from {
o.key.index = (o.key.index as i64 + delta).max(0) as usize;
}
}
}
}
fn unique_title(f: &HttpFile, base: &str) -> String {
let taken = |t: &str| f.requests().any(|r| r.display_name() == Some(t));
if !taken(base) {
return base.to_string();
}
(2..)
.map(|n| txt::names::numbered(base, n))
.find(|t| !taken(t))
.unwrap()
}
fn slug_name(title: &str) -> String {
reqlite_core::import::postman::slug(title)
}
/// Works out what "Consolidate auth" on `dir` would do: which requests can
/// drop their own auth header and inherit `dir`'s auth instead.
/// When `dir` has no auth of its own, `pick` (or what it already inherits,
/// or the most used header) becomes its auth.
pub fn plan_consolidation(state: &AppState, dir: &Path, pick: Option<AuthHeader>) -> Option<ConsolidateAuth> {
let c = state.collection_of(dir)?;
let requests: Vec<_> = c.all_requests().filter(|(p, _, _)| p.starts_with(dir)).collect();
let mut choices: Vec<(AuthHeader, usize)> = Vec::new();
for (_, _, r) in &requests {
if let AuthMode::Own(v) = auth_mode(r) {
match choices.iter_mut().find(|(c, _)| same_auth(c, &v)) {
Some(c) => c.1 += 1,
None => choices.push((v, 1)),
}
}
}
choices.sort_by_key(|c| std::cmp::Reverse(c.1));
let current = c.inherited_auth(dir).and_then(|i| i.value);
let (target, set_folder) = match c.folder_auth(dir) {
FolderAuth::Header(h) => {
choices.clear();
(Some(h), false)
}
_ => {
let target = pick
.or_else(|| current.clone())
.or_else(|| choices.first().map(|c| c.0.clone()));
let same_as_now = matches!((&current, &target), (Some(a), Some(b)) if same_auth(a, b));
(target.clone(), target.is_some() && !same_as_now)
}
};
// Folder settings as they will be after applying.
let mut new_settings = c.folders.get(dir).cloned().unwrap_or_default();
if let Some(t) = &target {
new_settings.auth = FolderAuth::Header(t.clone());
}
let after = |d: &Path| {
folder::inherited_auth(&c.root, d, |x| {
if set_folder && x == dir {
Some(&new_settings)
} else {
c.folders.get(x)
}
})
.and_then(|i| i.value)
};
let dirty = |file: &Path, index: usize| {
state.tabs.iter().any(|t| {
t.is_dirty()
&& t.origin
.as_ref()
.is_some_and(|o| o.file == file && o.key.index == index)
})
};
let mut plan = ConsolidateAuth {
dir: dir.to_path_buf(),
target,
set_folder,
choices,
own: Vec::new(),
affected: Vec::new(),
keep_affected: true,
skipped_dirty: Vec::new(),
};
for (file, index, r) in requests {
let fdir = file.parent().unwrap_or(dir);
let request = RequestRef {
file: file.clone(),
index,
label: format!(
"{} › {}",
c.relative(file).display(),
r.display_name().unwrap_or(r.url.as_str())
),
};
let item = match auth_mode(r) {
AuthMode::Own(value) => {
let mut own = OwnAuth {
request,
value,
inherits: after(fdir),
selected: false,
};
own.selected = own.same();
Some(Ok(own))
}
AuthMode::Inherit => {
let before = c.inherited_auth(fdir).and_then(|i| i.value);
let changes = match (&before, &after(fdir)) {
(Some(a), Some(b)) => !same_auth(a, b),
(a, b) => a.is_some() != b.is_some(),
};
changes.then_some(Err((request, before)))
}
AuthMode::NoAuth => None,
};
match item {
Some(Ok(own)) if dirty(file, index) => plan.skipped_dirty.push(own.request),
Some(Err((request, _))) if dirty(file, index) => plan.skipped_dirty.push(request),
Some(Ok(own)) => plan.own.push(own),
Some(Err(affected)) => plan.affected.push(affected),
None => {}
}
}
Some(plan)
}
/// What consolidating does to one request.
enum AuthFix {
/// Drop its own header so it inherits.
Inherit,
/// Pin the auth it sends today (a header, or `# @no-auth` for `None`).
Keep(Option<AuthHeader>),
}
fn apply_consolidation(state: &mut AppState, plan: ConsolidateAuth, fx: &mut Vec<Effect>) {
state.dialog = None;
let mut edits: BTreeMap<PathBuf, Vec<(usize, AuthFix)>> = BTreeMap::new();
for o in plan.own.iter().filter(|o| o.selected) {
edits
.entry(o.request.file.clone())
.or_default()
.push((o.request.index, AuthFix::Inherit));
}
if plan.keep_affected && plan.set_folder {
for (r, before) in &plan.affected {
edits
.entry(r.file.clone())
.or_default()
.push((r.index, AuthFix::Keep(before.clone())));
}
}
let mut ops = Vec::new();
let (mut dropped, mut pinned) = (0, 0);
for (path, list) in edits {
let Some(mut f) = file_of(state, &path).cloned() else {
continue;
};
for (index, edit) in list {
let Some(mut r) = f.request(index).cloned() else {
continue;
};
// The file may have changed since the plan was made.
match (&edit, auth_mode(&r)) {
(AuthFix::Inherit, AuthMode::Own(_)) => {
folder::set_auth_mode(&mut r, &AuthMode::Inherit);
dropped += 1;
}
(AuthFix::Keep(before), AuthMode::Inherit) => {
let mode = match before {
Some(h) => AuthMode::Own(h.clone()),
None => AuthMode::NoAuth,
};
folder::set_auth_mode(&mut r, &mode);
pinned += 1;
}
_ => continue,
}
if let Some(text) = f.replace_request(index, &r) {
f = HttpFile::parse(text);
}
}
if file_of(state, &path).is_some_and(|old| old.text() != f.text()) {
ops.push(FileOp::Write(path.clone(), f.text().to_string()));
insert_file(state, &path, f.text().to_string());
let clean: Vec<TabId> = state
.tabs
.iter()
.filter(|t| !t.is_dirty() && t.origin.as_ref().is_some_and(|o| o.file == path))
.map(|t| t.id)
.collect();
for id in clean {
reload_tab_from_file(state, id, &path);
}
}
}
let mut msg = Vec::new();
if plan.set_folder {
if let (Some(target), Some(c)) = (&plan.target, state.collection_of_mut(&plan.dir)) {
let mut settings = c.folders.get(&plan.dir).cloned().unwrap_or_default();
settings.auth = FolderAuth::Header(target.clone());
ops.push(FileOp::Write(folder::settings_path(&plan.dir), settings.to_json()));
c.folders.insert(plan.dir.clone(), settings);
msg.push(txt::consolidate::set_folder(&target.to_string()));
}
}
if dropped > 0 {
msg.push(txt::consolidate::dropped(dropped));
}
if pinned > 0 {
msg.push(txt::consolidate::pinned(pinned));
}
if !plan.skipped_dirty.is_empty() {
msg.push(txt::consolidate::skipped(plan.skipped_dirty.len()));
}
if !ops.is_empty() {
fx.push(Effect::FileOps { ops, rescan: None });
}
if msg.is_empty() {
state.set_info(txt::consolidate::NOTHING_TO_CHANGE);
} else {
let mut text = msg.join(", ");
text[..1].make_ascii_uppercase();
state.set_info(text);
}
}
fn save(state: &mut AppState, id: TabId, fx: &mut Vec<Effect>) {
let Some(t) = state.tab(id) else { return };
if let Some(e) = &t.source_error {
let e = e.clone();
state.set_error(txt::msg::cannot_save(e));
return;
}
let Some(origin) = t.origin.clone() else {
fx.push(Effect::PickSaveTarget(id));
return;
};
let Some(f) = file_of(state, &origin.file) else {
state.set_error(txt::msg::not_loaded(origin.file.display()));
return;
};
let Some(index) = f.find(&origin.key) else {
state.set_error(txt::msg::NO_LONGER_IN_FILE);
return;
};
let new_text = if t.source_authoritative {
f.replace_request_text(index, &t.source)
} else {
f.replace_request(index, &t.request)
};
let Some(new_text) = new_text else { return };
let changed = new_text != f.text();
if changed {
fx.push(Effect::FileOps {
ops: vec![FileOp::Write(origin.file.clone(), new_text.clone())],
rescan: None,
});
insert_file(state, &origin.file, new_text);
}
// The file may now say slightly different things (e.g. a new title).
let fresh = file_of(state, &origin.file).and_then(|f| {
Some((
f.request(index)?.clone(),
f.request_source(index)?.to_string(),
f.key_of(index)?,
))
});
let t = state.tab_mut(id).unwrap();
if let Some((req, src, key)) = fresh {
t.saved = req.clone();
t.request = req;
t.saved_source = src.clone();
t.source = src;
t.source_authoritative = false;
t.params = parse_params(&t.request.url);
if let Some(o) = &mut t.origin {
o.key = key;
}
}
t.orphaned = false;
}
fn save_as(state: &mut AppState, id: TabId, path: PathBuf, existing: Option<String>, fx: &mut Vec<Effect>) {
let Some(t) = state.tab(id) else { return };
let block = if t.source_authoritative && !t.source.trim().is_empty() {
t.source.clone()
} else {
render_request(&t.request, "\n")
};
let existing = file_of(state, &path).map(|f| f.text().to_string()).or(existing);
let file = HttpFile::parse(existing.unwrap_or_default());
let index = file.request_count();
let block = if index > 0 && !block.starts_with("###") {
format!("###\n{block}")
} else {
block
};
let text = file.insert_request_text(None, &block);
fx.push(Effect::FileOps {
ops: vec![FileOp::Write(path.clone(), text.clone())],
rescan: state.collection_of(&path).map(|c| c.root.clone()),
});
let parsed = HttpFile::parse(text);
let fresh = (|| {
Some((
parsed.request(index)?.clone(),
parsed.request_source(index)?.to_string(),
parsed.key_of(index)?,
))
})();
if let Some(c) = state.collection_of_mut(&path) {
c.files.insert(path.clone(), parsed);
}
let t = state.tab_mut(id).unwrap();
if let Some((req, src, key)) = fresh {
t.request = req.clone();
t.saved = req;
t.source = src.clone();
t.saved_source = src;
t.source_authoritative = false;
t.origin = Some(Origin { file: path, key });
t.orphaned = false;
}
}
#[cfg(test)]
mod tests;