Files
knock/src-tauri/src/commands.rs
T
JoshiCodes a73490e5d4 Import Bruno's YAML collections; fix defaults of on-by-default switches
- Bruno OpenCollection format (opencollection.yml, folder.yml, .yml
  requests, environments): folders and order, requests, bodies, auth
  including OAuth 2.0, settings, docs; scripts and other rules kept in
  Docs; a note when Bruno's hosted callback URI was used
- bruno.json is optional for .bru collections; picking a folder that
  holds several collections names them
- Collection variables that look like credentials (cookie, session,
  token, secret, password, api key) move to the secrets file and keep
  working under their name
- KeyValue, CollectionSettings, MultipartPart, ExtractRule and
  AssertRule default to enabled like the file format; new collections
  no longer start with the cookie jar turned off
2026-11-27 21:44:33 +01:00

797 lines
29 KiB
Rust

use crate::db;
use crate::state::AppState;
use crate::watch;
use indexmap::IndexMap;
use knock_core::collection::{Collection, EnvEntry, FolderNode, Problem};
use knock_core::model::*;
use knock_core::prepare::{ContextInput, RequestContext};
use knock_core::run::{execute, RunOutput};
use knock_core::secrets::{self, SecretStore};
use knock_core::vars::{VarInfo, DYNAMIC_VARS};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use std::sync::Arc;
use tauri::{AppHandle, Manager, State};
type Res<T> = Result<T, String>;
fn err(e: impl std::fmt::Display) -> String {
e.to_string()
}
fn errx(e: anyhow::Error) -> String {
format!("{e:#}")
}
// ---------------------------------------------------------------- collections
#[derive(Serialize)]
pub struct CollectionView {
pub id: String,
pub root: String,
pub name: String,
pub tree: FolderNode,
pub environments: Vec<EnvEntry>,
pub problems: Vec<Problem>,
}
fn view(c: &Collection) -> CollectionView {
CollectionView {
id: c.manifest.id.clone(),
root: c.root.display().to_string(),
name: c.manifest.name.clone(),
tree: c.tree.clone(),
environments: c.environments.clone(),
problems: c.problems.clone(),
}
}
fn remember_recent(state: &AppState, root: &str) {
let db = state.db.lock().unwrap();
let mut recent: Vec<String> = db::kv_get(&db, "recent")
.ok()
.flatten()
.and_then(|s| serde_json::from_str(&s).ok())
.unwrap_or_default();
recent.retain(|r| r != root);
recent.insert(0, root.to_string());
recent.truncate(12);
let _ = db::kv_set(&db, "recent", &serde_json::to_string(&recent).unwrap());
}
fn register(app: &AppHandle, state: &AppState, c: Collection) -> Res<CollectionView> {
let v = view(&c);
if let Ok(Some(json)) = db::jar_load(&state.db.lock().unwrap(), &v.id) {
state.engine.load_jar(&v.id, &json);
}
let root = c.root.clone();
state.collections.write().unwrap().insert(v.id.clone(), c);
remember_recent(state, &v.root);
watch::start(app, state, &v.id, &root);
Ok(v)
}
#[tauri::command]
pub fn collection_open(app: AppHandle, state: State<'_, AppState>, path: String) -> Res<CollectionView> {
let c = Collection::open(&path).map_err(errx)?;
register(&app, &state, c)
}
#[tauri::command]
pub fn collection_create(
app: AppHandle,
state: State<'_, AppState>,
path: String,
name: String,
) -> Res<CollectionView> {
let c = Collection::create(&path, &name).map_err(errx)?;
register(&app, &state, c)
}
#[tauri::command]
pub fn collection_get(state: State<'_, AppState>, id: String) -> Res<CollectionView> {
state.with_collection(&id, |c| Ok(view(c))).map_err(errx)
}
#[tauri::command]
pub fn collection_close(state: State<'_, AppState>, id: String) -> Res<()> {
state.collections.write().unwrap().remove(&id);
state.watchers.lock().unwrap().remove(&id);
Ok(())
}
#[tauri::command]
pub fn recent_collections(state: State<'_, AppState>) -> Res<Vec<String>> {
let db = state.db.lock().unwrap();
Ok(db::kv_get(&db, "recent")
.map_err(errx)?
.and_then(|s| serde_json::from_str::<Vec<String>>(&s).ok())
.unwrap_or_default()
.into_iter()
.filter(|p| PathBuf::from(p).join("knock.yaml").exists())
.collect())
}
#[tauri::command]
pub fn recent_forget(state: State<'_, AppState>, path: String) -> Res<()> {
let db = state.db.lock().unwrap();
let mut recent: Vec<String> = db::kv_get(&db, "recent")
.map_err(errx)?
.and_then(|s| serde_json::from_str(&s).ok())
.unwrap_or_default();
recent.retain(|r| r != &path);
db::kv_set(&db, "recent", &serde_json::to_string(&recent).unwrap()).map_err(errx)
}
// ---------------------------------------------------------------- tree edits
fn after_edit(state: &AppState, col: &str) -> Res<CollectionView> {
state.reload(col).map_err(errx)?;
state.with_collection(col, |c| Ok(view(c))).map_err(errx)
}
#[derive(Serialize)]
pub struct EditResult {
pub id: String,
pub collection: CollectionView,
}
#[tauri::command]
pub fn request_get(state: State<'_, AppState>, col: String, id: String) -> Res<Request> {
state.with_collection(&col, |c| c.request(&id)).map_err(errx)
}
#[tauri::command]
pub fn request_save(state: State<'_, AppState>, col: String, id: String, request: Request) -> Res<CollectionView> {
state.with_collection(&col, |c| c.save_request(&id, &request)).map_err(errx)?;
after_edit(&state, &col)
}
#[tauri::command]
pub fn request_create(
state: State<'_, AppState>,
col: String,
folder: String,
request: Request,
) -> Res<EditResult> {
let id = state.with_collection(&col, |c| c.create_request(&folder, &request)).map_err(errx)?;
Ok(EditResult { id, collection: after_edit(&state, &col)? })
}
#[tauri::command]
pub fn folder_create(state: State<'_, AppState>, col: String, parent: String, name: String) -> Res<EditResult> {
let id = state.with_collection(&col, |c| c.create_folder(&parent, &name)).map_err(errx)?;
Ok(EditResult { id, collection: after_edit(&state, &col)? })
}
#[tauri::command]
pub fn node_rename(state: State<'_, AppState>, col: String, id: String, name: String) -> Res<EditResult> {
let id = state.with_collection(&col, |c| c.rename(&id, &name)).map_err(errx)?;
Ok(EditResult { id, collection: after_edit(&state, &col)? })
}
#[tauri::command]
pub fn node_duplicate(state: State<'_, AppState>, col: String, id: String) -> Res<EditResult> {
let id = state.with_collection(&col, |c| c.duplicate(&id)).map_err(errx)?;
Ok(EditResult { id, collection: after_edit(&state, &col)? })
}
#[tauri::command]
pub fn node_delete(state: State<'_, AppState>, col: String, id: String) -> Res<CollectionView> {
state.with_collection(&col, |c| c.delete(&id)).map_err(errx)?;
after_edit(&state, &col)
}
#[tauri::command]
pub fn node_move(
state: State<'_, AppState>,
col: String,
id: String,
folder: String,
index: Option<usize>,
) -> Res<EditResult> {
let id = state.with_collection(&col, |c| c.move_node(&id, &folder, index)).map_err(errx)?;
Ok(EditResult { id, collection: after_edit(&state, &col)? })
}
#[tauri::command]
pub fn folder_get(state: State<'_, AppState>, col: String, id: String) -> Res<FolderMeta> {
state.with_collection(&col, |c| c.folder_meta(&id)).map_err(errx)
}
#[tauri::command]
pub fn folder_save(state: State<'_, AppState>, col: String, id: String, meta: FolderMeta) -> Res<CollectionView> {
state.with_collection(&col, |c| c.save_folder_meta(&id, &meta)).map_err(errx)?;
after_edit(&state, &col)
}
#[tauri::command]
pub fn manifest_get(state: State<'_, AppState>, col: String) -> Res<Manifest> {
state.with_collection(&col, |c| Ok(c.manifest.clone())).map_err(errx)
}
#[tauri::command]
pub fn manifest_save(state: State<'_, AppState>, col: String, manifest: Manifest) -> Res<CollectionView> {
state.with_collection(&col, |c| c.save_manifest(&manifest)).map_err(errx)?;
after_edit(&state, &col)
}
// ---------------------------------------------------------------- environments
#[tauri::command]
pub fn env_get(state: State<'_, AppState>, col: String, id: String) -> Res<Environment> {
state.with_collection(&col, |c| c.environment(&id)).map_err(errx)
}
#[tauri::command]
pub fn env_save(state: State<'_, AppState>, col: String, id: String, env: Environment) -> Res<CollectionView> {
state.with_collection(&col, |c| c.save_environment(&id, &env)).map_err(errx)?;
after_edit(&state, &col)
}
#[tauri::command]
pub fn env_delete(state: State<'_, AppState>, col: String, id: String) -> Res<CollectionView> {
state.with_collection(&col, |c| c.delete_environment(&id)).map_err(errx)?;
after_edit(&state, &col)
}
#[derive(Serialize)]
pub struct SecretStatus {
pub name: String,
pub source: Option<secrets::SecretSource>,
pub value: Option<String>,
}
/// Where each secret of an environment currently comes from. Values are
/// returned so the UI can reveal them on demand; it masks by default.
#[tauri::command]
pub async fn env_secrets(state: State<'_, AppState>, col: String, env: String) -> Res<Vec<SecretStatus>> {
let (e, file) = state
.with_collection(&col, |c| Ok((c.environment(&env)?, c.secrets_file(&env)?)))
.map_err(errx)?;
let store = SecretStore::new(&col, Some(&env), file.vars, true);
Ok(e.vars
.iter()
.filter(|(_, v)| v.secret)
.map(|(k, _)| {
let found = store.find(k);
SecretStatus {
name: k.clone(),
source: found.as_ref().map(|f| f.1),
value: found.map(|f| f.0),
}
})
.collect())
}
#[tauri::command]
pub async fn secret_set(
state: State<'_, AppState>,
col: String,
env: Option<String>,
name: String,
value: Option<String>,
target: String,
) -> Res<()> {
match target.as_str() {
"file" => {
let env = env.ok_or("secrets files belong to an environment")?;
state
.with_collection(&col, |c| {
let mut f = c.secrets_file(&env)?;
match &value {
Some(v) => {
f.vars.insert(name.clone(), v.clone());
}
None => {
f.vars.shift_remove(&name);
}
}
c.save_secrets_file(&env, &f)
})
.map_err(errx)
}
_ => match value {
Some(v) => secrets::keyring_set(&col, env.as_deref(), &name, &v).map_err(|e| {
format!("could not write to the system keyring ({e:#}). Is a Secret Service (KWallet, GNOME Keyring) running? You can store it in the secrets file instead.")
}),
None => secrets::keyring_delete(&col, env.as_deref(), &name).map_err(errx),
},
}
}
// ---------------------------------------------------------------- variables
#[derive(Deserialize)]
pub struct ScopeArgs {
pub col: Option<String>,
pub request_id: Option<String>,
pub request: Request,
pub env: Option<String>,
}
pub fn build_context(app: &AppHandle, state: &AppState, a: &ScopeArgs) -> anyhow::Result<RequestContext> {
let globals = db::globals_load(&state.db.lock().unwrap()).unwrap_or_default();
match &a.col {
Some(col) => {
let c = state.collection(col)?;
let file = a.env.as_deref().map(|e| c.secrets_file(e).unwrap_or_default()).unwrap_or_default();
let store = SecretStore::new(&c.manifest.id, a.env.as_deref(), file.vars, true);
let rid = a.request_id.clone().unwrap_or_else(|| "__unsaved__.yaml".into());
RequestContext::build(ContextInput {
collection: &c,
request_id: &rid,
request: &a.request,
env: a.env.as_deref(),
runtime: state.runtime_vars(col),
globals,
secrets: Arc::new(store),
oauth: Some(Arc::new(crate::oauth::TokenLookup::new(app, &c, a.env.as_deref()))),
})
}
None => {
let mut ctx = RequestContext::standalone(&a.request, std::env::temp_dir());
ctx.resolver.layers.push(knock_core::vars::Layer::new(
knock_core::vars::Scope::Global,
"global",
globals,
));
ctx.resolver.push_front(knock_core::vars::Layer::new(
knock_core::vars::Scope::Runtime,
"runtime",
state.runtime_vars(""),
));
Ok(ctx)
}
}
}
#[derive(Serialize)]
pub struct VarsView {
pub vars: Vec<VarInfo>,
pub dynamic: Vec<(String, String)>,
}
#[tauri::command]
pub fn vars_list(app: AppHandle, state: State<'_, AppState>, args: ScopeArgs) -> Res<VarsView> {
let ctx = build_context(&app, &state, &args).map_err(errx)?;
Ok(VarsView {
vars: ctx.resolver.names(),
dynamic: DYNAMIC_VARS.iter().map(|(a, b)| (a.to_string(), b.to_string())).collect(),
})
}
#[tauri::command]
pub fn runtime_list(state: State<'_, AppState>, col: Option<String>) -> Res<IndexMap<String, String>> {
Ok(state.runtime_vars(col.as_deref().unwrap_or("")))
}
#[tauri::command]
pub fn runtime_set(
state: State<'_, AppState>,
col: Option<String>,
name: String,
value: Option<String>,
persist: bool,
) -> Res<()> {
state.set_runtime(col.as_deref().unwrap_or(""), &name, value, persist);
Ok(())
}
#[tauri::command]
pub fn globals_get(state: State<'_, AppState>) -> Res<IndexMap<String, String>> {
db::globals_load(&state.db.lock().unwrap()).map_err(errx)
}
#[tauri::command]
pub fn globals_save(state: State<'_, AppState>, vars: IndexMap<String, String>) -> Res<()> {
db::globals_save(&state.db.lock().unwrap(), &vars).map_err(errx)
}
// ---------------------------------------------------------------- sending
#[derive(Deserialize)]
pub struct SendArgs {
#[serde(flatten)]
pub scope: ScopeArgs,
pub tab: String,
/// Store up to this many bytes of the body in history (0 = none).
#[serde(default)]
pub history_body_limit: usize,
}
#[derive(Serialize)]
pub struct SendResult {
pub output: RunOutput,
pub body_id: Option<String>,
pub history_id: Option<i64>,
pub body_file: Option<String>,
}
#[tauri::command]
pub async fn request_send(app: AppHandle, args: SendArgs) -> Res<SendResult> {
let state = app.state::<AppState>();
let ctx = build_context(&app, &state, &args.scope).map_err(errx)?;
let engine = state.engine.clone();
let req = args.scope.request.clone();
let host = crate::oauth::Host::new(app.clone(), args.scope.col.clone(), args.scope.env.clone());
let task = tokio::spawn(async move {
let out = execute(&engine, &req, &ctx, Some(&host)).await;
(out, ctx)
});
state.inflight.lock().unwrap().insert(args.tab.clone(), task.abort_handle());
let joined = task.await;
state.inflight.lock().unwrap().remove(&args.tab);
let (mut out, ctx) = match joined {
Ok(v) => v,
Err(e) if e.is_cancelled() => return Err("cancelled".into()),
Err(e) => return Err(err(e)),
};
let col_key = args.scope.col.clone().unwrap_or_default();
for x in &out.extracted {
if let Some(v) = &x.value {
state.set_runtime(&col_key, &x.var, Some(v.clone()), x.persist);
}
}
if let Some(col) = &args.scope.col {
let json = state.engine.save_jar(col);
let _ = db::jar_save(&state.db.lock().unwrap(), col, &json);
}
let mut body_id = None;
let mut body_file = None;
let mut stored_body: Option<Vec<u8>> = None;
if let Some(resp) = out.response.as_mut() {
let body = std::mem::take(&mut resp.body);
if args.history_body_limit > 0 && body.len() <= args.history_body_limit && resp.body_file.is_none() {
stored_body = Some(body.clone());
}
body_file = resp.body_file.as_ref().map(|p| p.display().to_string());
body_id = Some(state.store_body(body, resp.body_file.clone()));
}
// History never contains secrets in clear text.
let mask = |s: &str| ctx.resolver.mask(s);
let mut hist_req = args.scope.request.clone();
if let Some(sent) = &out.request {
hist_req.url = mask(&sent.url);
}
let req_json = mask(&serde_json::to_string(&hist_req).unwrap_or_default());
let meta = out.response.as_ref().map(|r| mask(&serde_json::to_string(r).unwrap_or_default()));
let history_id = {
let db = state.db.lock().unwrap();
db::history_add(
&db,
db::NewHistory {
collection: &col_key,
request_id: args.scope.request_id.as_deref(),
name: &args.scope.request.name,
method: out.request.as_ref().map(|r| r.method.as_str()).unwrap_or(args.scope.request.method()),
url: &out.request.as_ref().map(|r| mask(&r.url)).unwrap_or_else(|| args.scope.request.url.clone()),
status: out.response.as_ref().map(|r| r.status),
duration_ms: out.response.as_ref().map(|r| r.timings.total_ms),
size: out.response.as_ref().map(|r| r.size),
error: out.error.as_deref(),
request_json: &req_json,
response_meta: meta.as_deref(),
response_body: stored_body.as_deref(),
},
500 * 1024 * 1024,
)
.ok()
};
Ok(SendResult { output: out, body_id, history_id, body_file })
}
#[tauri::command]
pub fn request_cancel(state: State<'_, AppState>, tab: String) -> Res<()> {
if let Some(h) = state.inflight.lock().unwrap().remove(&tab) {
h.abort();
}
Ok(())
}
/// Raw body bytes; the frontend decodes them itself.
#[tauri::command]
pub fn response_body(state: State<'_, AppState>, id: String) -> Res<tauri::ipc::Response> {
let guard = state.responses.lock().unwrap();
let b = guard.0.get(&id).ok_or("response is no longer available")?;
Ok(tauri::ipc::Response::new(b.body.clone()))
}
#[tauri::command]
pub fn response_save(state: State<'_, AppState>, id: String, path: String) -> Res<()> {
let guard = state.responses.lock().unwrap();
let b = guard.0.get(&id).ok_or("response is no longer available")?;
match &b.file {
Some(f) => std::fs::copy(f, &path).map(|_| ()).map_err(err),
None => std::fs::write(&path, &b.body).map_err(err),
}
}
#[derive(Serialize)]
pub struct Preview {
pub request: Option<knock_core::run::SentRequest>,
pub auth: knock_core::auth::AuthDebug,
pub missing: Vec<String>,
pub error: Option<String>,
}
/// What would be sent, without sending: resolved URL, headers, body and auth.
/// OAuth tokens are not fetched here.
#[tauri::command]
pub async fn request_preview(app: AppHandle, args: ScopeArgs) -> Res<Preview> {
let state = app.state::<AppState>();
let ctx = build_context(&app, &state, &args).map_err(errx)?;
let mut p = match knock_core::prepare::prepare(&args.request, &ctx) {
Ok(p) => p,
Err(e) => {
return Ok(Preview { request: None, auth: Default::default(), missing: vec![], error: Some(errx(e)) })
}
};
let host = crate::oauth::Host::preview(app.clone(), args.col.clone(), args.env.clone());
let auth = knock_core::auth::apply(&ctx.auth, &mut p, &ctx.resolver, Some(&host), false, &ctx.root).await;
Ok(Preview {
request: Some(knock_core::run::SentRequest {
method: p.method.clone(),
url: p.url.clone(),
headers: p.headers.clone(),
body: match &p.body {
knock_core::prepare::PreparedBody::Bytes { preview, .. } => preview.clone(),
_ => String::new(),
},
}),
missing: p.missing.clone(),
auth,
error: None,
})
}
// ---------------------------------------------------------------- cookies
#[tauri::command]
pub fn cookies_list(state: State<'_, AppState>, col: String) -> Res<Vec<knock_core::http::CookieInfo>> {
Ok(state.engine.cookies(&col))
}
#[tauri::command]
pub fn cookie_delete(
state: State<'_, AppState>,
col: String,
domain: Option<String>,
path: Option<String>,
name: Option<String>,
) -> Res<()> {
match (domain, path, name) {
(Some(d), Some(p), Some(n)) => state.engine.delete_cookie(&col, &d, &p, &n),
_ => state.engine.clear_cookies(&col),
}
let json = state.engine.save_jar(&col);
db::jar_save(&state.db.lock().unwrap(), &col, &json).map_err(errx)
}
// ---------------------------------------------------------------- history
#[tauri::command]
pub fn history_list(state: State<'_, AppState>, query: String, limit: Option<u32>) -> Res<Vec<db::HistoryEntry>> {
db::history_list(&state.db.lock().unwrap(), &query, limit.unwrap_or(300)).map_err(errx)
}
#[derive(Serialize)]
pub struct HistoryView {
pub request: Request,
pub response: Option<serde_json::Value>,
pub body_id: Option<String>,
}
#[tauri::command]
pub fn history_get(state: State<'_, AppState>, id: i64) -> Res<HistoryView> {
let d = db::history_get(&state.db.lock().unwrap(), id)
.map_err(errx)?
.ok_or("history entry not found")?;
let request: Request = serde_json::from_str(&d.request_json).map_err(err)?;
let response = d.response_meta.and_then(|m| serde_json::from_str(&m).ok());
let body_id = d.response_body.map(|b| state.store_body(b, None));
Ok(HistoryView { request, response, body_id })
}
#[tauri::command]
pub fn history_delete(state: State<'_, AppState>, id: Option<i64>) -> Res<()> {
db::history_delete(&state.db.lock().unwrap(), id).map_err(errx)
}
// ---------------------------------------------------------------- misc
#[tauri::command]
pub fn setting_get(state: State<'_, AppState>, key: String) -> Res<Option<String>> {
db::kv_get(&state.db.lock().unwrap(), &format!("setting.{key}")).map_err(errx)
}
#[tauri::command]
pub fn setting_set(state: State<'_, AppState>, key: String, value: String) -> Res<()> {
db::kv_set(&state.db.lock().unwrap(), &format!("setting.{key}"), &value).map_err(errx)
}
#[tauri::command]
pub fn path_params(url: String) -> Vec<String> {
knock_core::prepare::path_param_names(&url)
}
#[tauri::command]
pub fn app_version() -> String {
env!("CARGO_PKG_VERSION").to_string()
}
#[tauri::command]
pub fn write_text_file(path: String, text: String) -> Res<()> {
std::fs::write(&path, text).map_err(err)
}
#[derive(Serialize)]
pub struct RunResult {
pub report: knock_core::runner::RunReport,
pub json: String,
pub junit: String,
}
#[tauri::command]
pub async fn runner_run(
app: AppHandle,
col: String,
folder: String,
env: Option<String>,
bail: bool,
delay_ms: u64,
) -> Res<RunResult> {
use tauri::Emitter;
let state = app.state::<AppState>();
let c = state.collection(&col).map_err(errx)?;
let file = env.as_deref().map(|e| c.secrets_file(e).unwrap_or_default()).unwrap_or_default();
let secrets = Arc::new(SecretStore::new(&c.manifest.id, env.as_deref(), file.vars, true));
let oauth = Arc::new(crate::oauth::TokenLookup::new(&app, &c, env.as_deref()));
let host = crate::oauth::Host::new(app.clone(), Some(col.clone()), env.clone());
let engine = state.engine.clone();
let opts = knock_core::runner::RunOptions {
env: env.clone(),
bail,
delay_ms,
globals: db::globals_load(&state.db.lock().unwrap()).unwrap_or_default(),
runtime: state.runtime_vars(&col),
};
let deps = knock_core::runner::RunDeps { engine: &engine, secrets, oauth: Some(oauth), host: Some(&host) };
let report = knock_core::runner::run(&c, &folder, &opts, &deps, |done, total, item| {
let _ = app.emit("run-progress", (done, total, item));
})
.await;
for (k, v) in &report.runtime {
state.set_runtime(&col, k, Some(v.clone()), false);
}
let json = state.engine.save_jar(&col);
let _ = db::jar_save(&state.db.lock().unwrap(), &col, &json);
Ok(RunResult { json: knock_core::runner::to_json(&report), junit: knock_core::runner::to_junit(&report), report })
}
// ---------------------------------------------------------------- import / export
use knock_core::import::{self as importer, ImportReport, Kind as ImportKind};
#[tauri::command]
pub fn import_curl(text: String) -> Res<Request> {
importer::parse_curl(&text).map_err(errx)
}
#[tauri::command]
pub fn import_detect(text: String) -> Option<ImportKind> {
importer::detect(&text)
}
/// Imports a file or folder (Bruno) into a new collection at `dest` and opens it.
#[tauri::command]
pub fn import_source(app: AppHandle, state: State<'_, AppState>, source: String, dest: String) -> Res<(ImportReport, CollectionView)> {
let src = PathBuf::from(&source);
let dest_path = PathBuf::from(&dest);
let report = if src.is_dir() {
importer::import_folder(&src, &dest_path).map_err(errx)?
} else {
let text = std::fs::read_to_string(&src).map_err(|e| format!("{source}: {e}"))?;
import_text_into(&text, &dest_path)?
};
let c = Collection::open(&report.collection_root).map_err(errx)?;
let view = register(&app, &state, c)?;
Ok((report, view))
}
#[tauri::command]
pub fn import_text(app: AppHandle, state: State<'_, AppState>, text: String, dest: String) -> Res<(ImportReport, CollectionView)> {
let report = import_text_into(&text, &PathBuf::from(&dest))?;
let c = Collection::open(&report.collection_root).map_err(errx)?;
let view = register(&app, &state, c)?;
Ok((report, view))
}
fn import_text_into(text: &str, dest: &std::path::Path) -> Res<ImportReport> {
match importer::detect(text) {
Some(ImportKind::PostmanCollection) => importer::import_postman(text, dest).map_err(errx),
Some(ImportKind::Insomnia) => importer::import_insomnia(text, dest).map_err(errx),
Some(ImportKind::Openapi) => importer::import_openapi(text, dest).map_err(errx),
Some(ImportKind::Curl) => {
let mut req = importer::parse_curl(text).map_err(errx)?;
let name = dest.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "Imported".into());
let c = Collection::create(dest, &name).map_err(errx)?;
// Credentials from the command go to the gitignored secrets file, not the request.
let mut store = IndexMap::new();
importer::externalize_secrets(&mut req.auth, "curl", &mut store);
if !store.is_empty() {
let mut f = c.secrets_file("local").unwrap_or_default();
f.vars.extend(store);
c.save_secrets_file("local", &f).map_err(errx)?;
}
c.create_request("", &req).map_err(errx)?;
Ok(ImportReport { collection_root: c.root.clone(), requests: 1, ..Default::default() })
}
Some(ImportKind::PostmanEnvironment) => Err("this is a Postman environment. Open the collection first, then import the environment from its Environments tab".into()),
None => Err("could not recognise the format. knock imports Postman, Bruno, Insomnia, OpenAPI/Swagger and cURL".into()),
}
}
#[tauri::command]
pub fn import_environment(state: State<'_, AppState>, col: String, source: String) -> Res<CollectionView> {
let text = std::fs::read_to_string(&source).map_err(|e| format!("{source}: {e}"))?;
let root = state.with_collection(&col, |c| Ok(c.root.clone())).map_err(errx)?;
importer::import_postman_environment(&text, &root).map_err(errx)?;
after_edit(&state, &col)
}
#[tauri::command]
pub fn export_postman(state: State<'_, AppState>, col: String, path: String) -> Res<()> {
let json = state.with_collection(&col, knock_core::export::export_postman).map_err(errx)?;
std::fs::write(&path, json).map_err(err)
}
/// Code for the request. `resolve` fills in variables (secrets stay masked);
/// otherwise `{{placeholders}}` are kept as written.
#[tauri::command]
pub async fn code_snippet(app: AppHandle, args: ScopeArgs, lang: knock_core::export::Lang, resolve: bool) -> Res<String> {
use knock_core::prepare::{Prepared, PreparedBody};
let state = app.state::<AppState>();
let p = if resolve {
let ctx = build_context(&app, &state, &args).map_err(errx)?;
let mut p = knock_core::prepare::prepare(&args.request, &ctx).map_err(errx)?;
// Stored tokens only; generating code never starts a login.
let host = crate::oauth::Host::preview(app.clone(), args.col.clone(), args.env.clone());
knock_core::auth::apply(&ctx.auth, &mut p, &ctx.resolver, Some(&host), false, &ctx.root).await;
let mask = |s: &str| ctx.resolver.mask(s);
p.url = mask(&p.url);
p.headers = p.headers.into_iter().map(|(k, v)| (k, mask(&v))).collect();
if let PreparedBody::Bytes { data, preview } = &p.body {
let text = mask(&String::from_utf8_lossy(data));
p.body = PreparedBody::Bytes { data: text.clone().into_bytes(), preview: preview.clone() };
}
p
} else {
let r = &args.request;
let body = match r.body.kind {
BodyType::None => PreparedBody::None,
BodyType::FormUrlencoded => {
let s = r.body.form.iter().filter(|f| f.enabled).map(|f| format!("{}={}", f.name, f.value)).collect::<Vec<_>>().join("&");
PreparedBody::Bytes { preview: s.clone(), data: s.into_bytes() }
}
_ => PreparedBody::Bytes { preview: r.body.content.clone(), data: r.body.content.clone().into_bytes() },
};
let mut headers: Vec<(String, String)> = r.headers.iter().filter(|h| h.enabled).map(|h| (h.name.clone(), h.value.clone())).collect();
if r.body.kind == BodyType::Json && !headers.iter().any(|(k, _)| k.eq_ignore_ascii_case("content-type")) {
headers.push(("Content-Type".into(), "application/json".into()));
}
Prepared {
method: r.method().to_string(),
url: r.url.clone(),
headers,
body,
settings: r.settings.clone(),
missing: vec![],
cycles: vec![],
}
};
Ok(knock_core::export::snippet(&p, lang))
}