mirror of
https://github.com/JoshiCodes/knock.git
synced 2026-12-04 14:59:41 +01:00
- GraphQL editor with schema introspection, cached schema, autocomplete and explorer - WebSocket: auth and subprotocols in the handshake, text/JSON/hex/file messages, saved messages, live log with filter, search and export, reconnect with backoff - Import from Postman (collections and environments), Bruno, Insomnia, OpenAPI/Swagger and cURL; imported scripts are kept as docs, never run; credentials move to the gitignored secrets file - Code snippets for cURL, fetch, Python, HTTPie, Go, PowerShell; Postman export - Runner for folders and collections with JSON and JUnit reports - knock CLI: send, run, import, auth login/debug/logout - Large JSON responses parsed off the main thread - PKGBUILDs, desktop entry with knock:// handler, CI workflow, README
793 lines
30 KiB
Rust
793 lines
30 KiB
Rust
//! Bruno collections: a folder with `bruno.json`, `.bru` request files,
|
|
//! `folder.bru`, `collection.bru` and `environments/*.bru`.
|
|
|
|
use super::{append_docs, looks_like_json, parse_query, pretty_json, scripts_doc, set_url, ImportReport, Writer};
|
|
use crate::model::*;
|
|
use anyhow::{anyhow, bail, Context, Result};
|
|
use indexmap::IndexMap;
|
|
use std::fs;
|
|
use std::path::Path;
|
|
|
|
// ---------------------------------------------------------------- .bru parser
|
|
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub struct Entry {
|
|
pub key: String,
|
|
pub value: String,
|
|
pub enabled: bool,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub enum BlockBody {
|
|
/// `key: value` lines.
|
|
Dict(Vec<Entry>),
|
|
/// Free text with the block indentation removed.
|
|
Text(String),
|
|
/// `name [ a, b ]`.
|
|
List(Vec<Entry>),
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub struct Block {
|
|
pub name: String,
|
|
pub body: BlockBody,
|
|
}
|
|
|
|
#[derive(Debug, Default)]
|
|
pub struct BruFile {
|
|
pub blocks: Vec<Block>,
|
|
}
|
|
|
|
impl BruFile {
|
|
pub fn block(&self, name: &str) -> Option<&BlockBody> {
|
|
self.blocks.iter().find(|b| b.name == name).map(|b| &b.body)
|
|
}
|
|
|
|
pub fn dict(&self, name: &str) -> &[Entry] {
|
|
match self.block(name) {
|
|
Some(BlockBody::Dict(d)) | Some(BlockBody::List(d)) => d,
|
|
_ => &[],
|
|
}
|
|
}
|
|
|
|
pub fn get(&self, block: &str, key: &str) -> Option<&str> {
|
|
self.dict(block).iter().find(|e| e.key == key && e.enabled).map(|e| e.value.as_str())
|
|
}
|
|
|
|
pub fn text(&self, name: &str) -> Option<&str> {
|
|
match self.block(name) {
|
|
Some(BlockBody::Text(t)) if !t.trim().is_empty() => Some(t),
|
|
_ => None,
|
|
}
|
|
}
|
|
}
|
|
|
|
fn is_text_block(name: &str) -> bool {
|
|
name.starts_with("body:") && !matches!(name, "body:form-urlencoded" | "body:multipart-form" | "body:file")
|
|
|| name.starts_with("script:")
|
|
|| name == "tests"
|
|
|| name == "docs"
|
|
}
|
|
|
|
/// Parses the `.bru` block format.
|
|
pub fn parse_bru(src: &str) -> Result<BruFile> {
|
|
let lines: Vec<&str> = src.lines().collect();
|
|
let mut out = BruFile::default();
|
|
let mut i = 0;
|
|
while i < lines.len() {
|
|
let line = lines[i].trim_end();
|
|
i += 1;
|
|
if line.trim().is_empty() {
|
|
continue;
|
|
}
|
|
if let Some(name) = line.strip_suffix('{').map(str::trim).filter(|n| !n.is_empty() && !n.contains(' ')) {
|
|
let start = i;
|
|
while i < lines.len() && lines[i].trim_end() != "}" {
|
|
i += 1;
|
|
}
|
|
if i >= lines.len() {
|
|
bail!("block `{name}` starting on line {start} is not closed with `}}`");
|
|
}
|
|
let content = &lines[start..i];
|
|
i += 1;
|
|
let body = if is_text_block(name) {
|
|
BlockBody::Text(dedent(content))
|
|
} else {
|
|
BlockBody::Dict(parse_dict(content))
|
|
};
|
|
out.blocks.push(Block { name: name.to_string(), body });
|
|
} else if let Some(name) = line.strip_suffix('[').map(str::trim).filter(|n| !n.is_empty()) {
|
|
let start = i;
|
|
let mut items = Vec::new();
|
|
while i < lines.len() && lines[i].trim() != "]" {
|
|
for raw in lines[i].split(',') {
|
|
let t = raw.trim();
|
|
if !t.is_empty() {
|
|
let (enabled, key) = match t.strip_prefix('~') {
|
|
Some(k) => (false, k),
|
|
None => (true, t),
|
|
};
|
|
items.push(Entry { key: key.to_string(), value: String::new(), enabled });
|
|
}
|
|
}
|
|
i += 1;
|
|
}
|
|
if i >= lines.len() {
|
|
bail!("list `{name}` starting on line {start} is not closed with `]`");
|
|
}
|
|
i += 1;
|
|
out.blocks.push(Block { name: name.to_string(), body: BlockBody::List(items) });
|
|
} else {
|
|
bail!("unexpected line {i}: `{}`", line.trim());
|
|
}
|
|
}
|
|
Ok(out)
|
|
}
|
|
|
|
fn dedent(lines: &[&str]) -> String {
|
|
let text: Vec<&str> = lines.iter().map(|l| l.strip_prefix(" ").unwrap_or(l)).collect();
|
|
text.join("\n").trim_matches('\n').to_string()
|
|
}
|
|
|
|
fn parse_dict(lines: &[&str]) -> Vec<Entry> {
|
|
let mut out = Vec::new();
|
|
let mut i = 0;
|
|
while i < lines.len() {
|
|
let t = lines[i].trim();
|
|
i += 1;
|
|
if t.is_empty() {
|
|
continue;
|
|
}
|
|
let (enabled, t) = match t.strip_prefix('~') {
|
|
Some(rest) => (false, rest),
|
|
None => (true, t),
|
|
};
|
|
let (key, value) = match t.split_once(':') {
|
|
Some((k, v)) => (k.trim(), v.trim()),
|
|
None => (t, ""),
|
|
};
|
|
let mut value = value.to_string();
|
|
// Multi-line values are wrapped in ''' … '''.
|
|
if value == "'''" {
|
|
let mut buf = Vec::new();
|
|
while i < lines.len() && lines[i].trim() != "'''" {
|
|
buf.push(lines[i].strip_prefix(" ").unwrap_or(lines[i]));
|
|
i += 1;
|
|
}
|
|
i += 1;
|
|
value = buf.join("\n");
|
|
}
|
|
out.push(Entry { key: unquote_key(key), value, enabled });
|
|
}
|
|
out
|
|
}
|
|
|
|
fn unquote_key(k: &str) -> String {
|
|
k.strip_prefix('"').and_then(|s| s.strip_suffix('"')).unwrap_or(k).to_string()
|
|
}
|
|
|
|
// ---------------------------------------------------------------- import
|
|
|
|
const METHODS: &[&str] = &["get", "post", "put", "patch", "delete", "options", "head", "connect", "trace"];
|
|
|
|
pub fn import_bruno(src_dir: &Path, dest: &Path) -> Result<ImportReport> {
|
|
let manifest_path = src_dir.join("bruno.json");
|
|
let manifest: serde_json::Value = serde_json::from_str(
|
|
&fs::read_to_string(&manifest_path)
|
|
.with_context(|| format!("{} is not a Bruno collection (bruno.json missing)", src_dir.display()))?,
|
|
)
|
|
.context("bruno.json is not valid JSON")?;
|
|
let name = super::text(manifest.get("name"));
|
|
let ignore: Vec<String> = manifest
|
|
.get("ignore")
|
|
.and_then(|v| v.as_array())
|
|
.map(|a| a.iter().filter_map(|s| s.as_str().map(str::to_string)).collect())
|
|
.unwrap_or_else(|| vec!["node_modules".into(), ".git".into()]);
|
|
|
|
let mut w = Writer::start(dest, &name)?;
|
|
|
|
let coll_file = src_dir.join("collection.bru");
|
|
if coll_file.exists() {
|
|
let bru = read_bru(&coll_file)?;
|
|
let mut warnings = Vec::new();
|
|
let auth = map_auth(&bru, &mut warnings);
|
|
let headers = kv(bru.dict("headers"));
|
|
let vars = vars_map(bru.dict("vars:pre-request"));
|
|
let (docs, scripts) = misc_docs(&bru);
|
|
w.report.scripts_skipped += scripts;
|
|
w.manifest(|m| {
|
|
m.headers = headers;
|
|
m.vars = vars;
|
|
if !docs.is_empty() {
|
|
m.extra.insert("docs".into(), docs.into());
|
|
}
|
|
})?;
|
|
w.collection_auth(auth)?;
|
|
for msg in warnings {
|
|
w.warn(format!("collection.bru: {msg}"));
|
|
}
|
|
}
|
|
|
|
let env_dir = src_dir.join("environments");
|
|
if env_dir.is_dir() {
|
|
let mut has_local = false;
|
|
let mut files: Vec<_> = fs::read_dir(&env_dir)?.filter_map(|e| e.ok()).map(|e| e.path()).collect();
|
|
files.sort();
|
|
for p in files.iter().filter(|p| p.extension().is_some_and(|e| e == "bru")) {
|
|
let stem = p.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default();
|
|
let bru = read_bru(p)?;
|
|
let mut env = Environment::default();
|
|
for e in bru.dict("vars").iter().filter(|e| e.enabled) {
|
|
env.vars.insert(e.key.clone(), EnvVar { value: e.value.clone(), secret: false, description: None });
|
|
}
|
|
for e in bru.dict("vars:secret").iter().filter(|e| e.enabled) {
|
|
env.vars.insert(e.key.clone(), EnvVar { value: String::new(), secret: true, description: None });
|
|
}
|
|
let id = w.environment(&stem, env, IndexMap::new())?;
|
|
has_local |= id == "local";
|
|
}
|
|
if !files.is_empty() && !has_local {
|
|
w.remove_local_env()?;
|
|
}
|
|
if bru_secret_count(&files) > 0 {
|
|
w.warn("Bruno stores secret values outside the collection; set them again in knock's environment editor");
|
|
}
|
|
}
|
|
|
|
import_dir(&mut w, src_dir, src_dir, "", &ignore)?;
|
|
w.finish()
|
|
}
|
|
|
|
fn bru_secret_count(files: &[std::path::PathBuf]) -> usize {
|
|
files
|
|
.iter()
|
|
.filter_map(|p| read_bru(p).ok())
|
|
.map(|b| b.dict("vars:secret").len())
|
|
.sum()
|
|
}
|
|
|
|
fn read_bru(p: &Path) -> Result<BruFile> {
|
|
let text = fs::read_to_string(p).with_context(|| format!("reading {}", p.display()))?;
|
|
parse_bru(&text).with_context(|| format!("parsing {}", p.display()))
|
|
}
|
|
|
|
enum Child {
|
|
Folder { path: std::path::PathBuf, name: String, seq: f64, meta: Option<BruFile> },
|
|
Request { file: BruFile, name: String, seq: f64 },
|
|
}
|
|
|
|
fn import_dir(w: &mut Writer, root: &Path, dir: &Path, folder: &str, ignore: &[String]) -> Result<()> {
|
|
let mut children = Vec::new();
|
|
for e in fs::read_dir(dir).with_context(|| format!("reading {}", dir.display()))? {
|
|
let e = e?;
|
|
let path = e.path();
|
|
let fname = e.file_name().to_string_lossy().to_string();
|
|
let rel = path.strip_prefix(root).unwrap_or(&path).to_string_lossy().replace('\\', "/");
|
|
if fname.starts_with('.') || ignore.iter().any(|i| *i == fname || *i == rel) {
|
|
continue;
|
|
}
|
|
if path.is_dir() {
|
|
if dir == root && fname == "environments" {
|
|
continue;
|
|
}
|
|
let meta_path = path.join("folder.bru");
|
|
let meta = if meta_path.exists() { Some(read_bru(&meta_path)?) } else { None };
|
|
let name = meta.as_ref().and_then(|m| m.get("meta", "name")).map(str::to_string).unwrap_or_else(|| fname.clone());
|
|
let seq = meta.as_ref().and_then(|m| m.get("meta", "seq")).and_then(|s| s.parse().ok()).unwrap_or(f64::MAX);
|
|
children.push(Child::Folder { path, name, seq, meta });
|
|
} else if fname.ends_with(".bru") && fname != "folder.bru" && fname != "collection.bru" {
|
|
let file = match read_bru(&path) {
|
|
Ok(f) => f,
|
|
Err(err) => {
|
|
w.warn(format!("{rel} skipped: {err:#}"));
|
|
continue;
|
|
}
|
|
};
|
|
let name = file.get("meta", "name").map(str::to_string).unwrap_or_else(|| fname.trim_end_matches(".bru").to_string());
|
|
let seq = file.get("meta", "seq").and_then(|s| s.parse().ok()).unwrap_or(f64::MAX);
|
|
children.push(Child::Request { file, name, seq });
|
|
}
|
|
}
|
|
children.sort_by(|a, b| {
|
|
let key = |c: &Child| match c {
|
|
Child::Folder { seq, name, .. } | Child::Request { seq, name, .. } => (*seq, name.to_lowercase()),
|
|
};
|
|
let (sa, na) = key(a);
|
|
let (sb, nb) = key(b);
|
|
sa.total_cmp(&sb).then(na.cmp(&nb))
|
|
});
|
|
for child in children {
|
|
match child {
|
|
Child::Folder { path, name, meta, .. } => {
|
|
let id = w.folder(folder, &name)?;
|
|
if let Some(bru) = meta {
|
|
let mut warnings = Vec::new();
|
|
let auth = map_auth(&bru, &mut warnings);
|
|
let headers = kv(bru.dict("headers"));
|
|
let vars = vars_map(bru.dict("vars:pre-request"));
|
|
let (docs, scripts) = misc_docs(&bru);
|
|
w.report.scripts_skipped += scripts;
|
|
w.folder_meta(&id, |m| {
|
|
m.auth = auth;
|
|
m.headers = headers;
|
|
m.vars = vars;
|
|
if !docs.is_empty() {
|
|
m.extra.insert("docs".into(), docs.into());
|
|
}
|
|
})?;
|
|
for msg in warnings {
|
|
w.warn(format!("{name}: {msg}"));
|
|
}
|
|
}
|
|
import_dir(w, root, &path, &id, ignore)?;
|
|
}
|
|
Child::Request { file, name, .. } => {
|
|
let mut warnings = Vec::new();
|
|
let mut scripts = 0;
|
|
match map_request(&file, &name, &mut warnings, &mut scripts) {
|
|
Ok(req) => {
|
|
w.report.scripts_skipped += scripts;
|
|
w.request(folder, req)?;
|
|
}
|
|
Err(e) => w.warn(format!("{name} skipped: {e:#}")),
|
|
}
|
|
for msg in warnings {
|
|
w.warn(format!("{name}: {msg}"));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn kv(entries: &[Entry]) -> Vec<KeyValue> {
|
|
entries
|
|
.iter()
|
|
.map(|e| KeyValue {
|
|
name: e.key.clone(),
|
|
value: e.value.clone(),
|
|
enabled: e.enabled,
|
|
..Default::default()
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
fn vars_map(entries: &[Entry]) -> IndexMap<String, String> {
|
|
entries.iter().filter(|e| e.enabled).map(|e| (e.key.clone(), e.value.clone())).collect()
|
|
}
|
|
|
|
/// Docs plus scripts and tests rendered as markdown, and the number of scripts.
|
|
fn misc_docs(bru: &BruFile) -> (String, usize) {
|
|
let mut docs = bru.text("docs").unwrap_or_default().to_string();
|
|
let scripts: Vec<(&str, &str, String)> = [
|
|
("script:pre-request", "Pre-request script"),
|
|
("script:post-response", "Post-response script"),
|
|
("tests", "Tests"),
|
|
]
|
|
.into_iter()
|
|
.filter_map(|(block, label)| bru.text(block).map(|t| (label, "js", t.to_string())))
|
|
.collect();
|
|
if !scripts.is_empty() {
|
|
if !docs.is_empty() {
|
|
docs.push_str("\n\n");
|
|
}
|
|
docs.push_str(&scripts_doc("Bruno", &scripts));
|
|
}
|
|
(docs, scripts.len())
|
|
}
|
|
|
|
fn map_auth(bru: &BruFile, warnings: &mut Vec<String>) -> Auth {
|
|
let mode = bru
|
|
.get("auth", "mode")
|
|
.or_else(|| METHODS.iter().find_map(|m| bru.get(m, "auth")))
|
|
.unwrap_or("inherit");
|
|
let g = |block: &str, key: &str| bru.get(block, key).unwrap_or("").to_string();
|
|
match mode {
|
|
"none" => Auth::None,
|
|
"inherit" => Auth::Inherit,
|
|
"basic" => super::auth("basic", [("username", g("auth:basic", "username")), ("password", g("auth:basic", "password"))]),
|
|
"digest" => super::auth("digest", [("username", g("auth:digest", "username")), ("password", g("auth:digest", "password"))]),
|
|
"bearer" => super::auth("bearer", [("token", g("auth:bearer", "token"))]),
|
|
"apikey" => {
|
|
let place = if g("auth:apikey", "placement") == "queryparams" { "query" } else { "header" };
|
|
super::auth("apikey", [("key", g("auth:apikey", "key")), ("value", g("auth:apikey", "value")), ("in", place.into())])
|
|
}
|
|
"awsv4" => super::auth(
|
|
"awsv4",
|
|
[
|
|
("access_key", g("auth:awsv4", "accessKeyId")),
|
|
("secret_key", g("auth:awsv4", "secretAccessKey")),
|
|
("session_token", g("auth:awsv4", "sessionToken")),
|
|
("region", g("auth:awsv4", "region")),
|
|
("service", g("auth:awsv4", "service")),
|
|
],
|
|
),
|
|
"oauth2" => {
|
|
let o = |k: &str| g("auth:oauth2", k);
|
|
let grant = match o("grant_type").as_str() {
|
|
"client_credentials" => "client_credentials",
|
|
"password" => "password",
|
|
_ => "authorization_code",
|
|
};
|
|
let client_auth = if o("credentials_placement") == "body" { "post" } else { "basic" };
|
|
let mut auth = super::auth(
|
|
"oauth2",
|
|
[
|
|
("grant", grant.to_string()),
|
|
("authorize_url", o("authorization_url")),
|
|
("token_url", o("access_token_url")),
|
|
("client_id", o("client_id")),
|
|
("client_secret", o("client_secret")),
|
|
("client_auth", client_auth.to_string()),
|
|
("scopes", o("scope")),
|
|
("username", o("username")),
|
|
("password", o("password")),
|
|
("token_prefix", o("token_header_prefix")),
|
|
],
|
|
);
|
|
if let Auth::Config(c) = &mut auth {
|
|
if o("pkce") == "true" {
|
|
c.fields.insert("pkce".into(), serde_json::Value::Bool(true));
|
|
}
|
|
}
|
|
auth
|
|
}
|
|
other => {
|
|
warnings.push(format!("auth mode `{other}` is not supported and was left as inherit"));
|
|
Auth::Inherit
|
|
}
|
|
}
|
|
}
|
|
|
|
fn map_request(bru: &BruFile, name: &str, warnings: &mut Vec<String>, scripts: &mut usize) -> Result<Request> {
|
|
let method = METHODS
|
|
.iter()
|
|
.find(|m| bru.block(m).is_some())
|
|
.ok_or_else(|| anyhow!("no method block (get, post, …) found"))?;
|
|
let url = bru.get(method, "url").unwrap_or("").to_string();
|
|
let body_mode = bru.get(method, "body").unwrap_or("none");
|
|
let graphql = bru.get("meta", "type") == Some("graphql");
|
|
|
|
let mut req = Request {
|
|
name: name.to_string(),
|
|
method: Some(method.to_uppercase()),
|
|
headers: kv(bru.dict("headers")),
|
|
vars: vars_map(bru.dict("vars:pre-request")),
|
|
..Default::default()
|
|
};
|
|
req.auth = map_auth(bru, warnings);
|
|
|
|
let rows = match bru.block("params:query") {
|
|
Some(BlockBody::Dict(d)) => kv(d),
|
|
_ => parse_query(&url),
|
|
};
|
|
set_url(&mut req, &url, rows);
|
|
for e in bru.dict("params:path") {
|
|
req.params.path.insert(e.key.clone(), e.value.clone());
|
|
}
|
|
|
|
if graphql || body_mode == "graphql" {
|
|
req.kind = RequestKind::Graphql;
|
|
req.graphql = Some(GraphqlSpec {
|
|
query: bru.text("body:graphql").unwrap_or("").to_string(),
|
|
variables: bru.text("body:graphql:vars").unwrap_or("").to_string(),
|
|
operation_name: None,
|
|
});
|
|
} else {
|
|
req.body = map_body(bru, body_mode, warnings);
|
|
}
|
|
|
|
let mut leftovers = Vec::new();
|
|
for e in bru.dict("vars:post-response") {
|
|
match extract_rule(&e.key, &e.value) {
|
|
Some(mut r) => {
|
|
r.enabled = e.enabled;
|
|
req.extract.push(r);
|
|
}
|
|
None => leftovers.push(format!("- vars:post-response `{}: {}`", e.key, e.value)),
|
|
}
|
|
}
|
|
for e in bru.dict("assert") {
|
|
match assert_rule(&e.key, &e.value) {
|
|
Some(mut r) => {
|
|
r.enabled = e.enabled;
|
|
req.assert.push(r);
|
|
}
|
|
None => leftovers.push(format!("- assert `{}: {}`", e.key, e.value)),
|
|
}
|
|
}
|
|
|
|
let (docs, n) = misc_docs(bru);
|
|
*scripts += n;
|
|
append_docs(&mut req, &docs);
|
|
if !leftovers.is_empty() {
|
|
append_docs(
|
|
&mut req,
|
|
&format!("## Bruno rules not converted\n\n{}", leftovers.join("\n")),
|
|
);
|
|
}
|
|
Ok(req)
|
|
}
|
|
|
|
fn map_body(bru: &BruFile, mode: &str, warnings: &mut Vec<String>) -> Body {
|
|
let raw = |block: &str, ct: Option<&str>| Body {
|
|
kind: BodyType::Raw,
|
|
content: bru.text(block).unwrap_or("").to_string(),
|
|
content_type: ct.map(str::to_string),
|
|
..Default::default()
|
|
};
|
|
match mode {
|
|
"json" => {
|
|
let content = bru.text("body:json").unwrap_or("").to_string();
|
|
let jsonc = !content.trim().is_empty()
|
|
&& !looks_like_json(&content)
|
|
&& serde_json::from_str::<serde_json::Value>(&crate::prepare::strip_json_comments(&content)).is_ok();
|
|
Body {
|
|
kind: BodyType::Json,
|
|
content: if looks_like_json(&content) { pretty_json(&content) } else { content },
|
|
jsonc,
|
|
..Default::default()
|
|
}
|
|
}
|
|
"text" => raw("body:text", Some("text/plain")),
|
|
"xml" => raw("body:xml", Some("application/xml")),
|
|
"sparql" => raw("body:sparql", Some("application/sparql-query")),
|
|
"formUrlEncoded" => Body {
|
|
kind: BodyType::FormUrlencoded,
|
|
form: kv(bru.dict("body:form-urlencoded")),
|
|
..Default::default()
|
|
},
|
|
"multipartForm" => Body {
|
|
kind: BodyType::Multipart,
|
|
multipart: bru
|
|
.dict("body:multipart-form")
|
|
.iter()
|
|
.map(|e| {
|
|
let (value, ct) = split_content_type(&e.value);
|
|
let file = file_ref(&value, warnings, &e.key);
|
|
MultipartPart {
|
|
name: e.key.clone(),
|
|
value: if file.is_some() { String::new() } else { value },
|
|
file,
|
|
content_type: ct,
|
|
enabled: e.enabled,
|
|
}
|
|
})
|
|
.collect(),
|
|
..Default::default()
|
|
},
|
|
"file" => {
|
|
let first = bru.dict("body:file").iter().find(|e| e.enabled);
|
|
let (file, ct) = first
|
|
.map(|e| {
|
|
let (v, ct) = split_content_type(&e.value);
|
|
(file_ref(&v, warnings, &e.key), ct)
|
|
})
|
|
.unwrap_or((None, None));
|
|
Body {
|
|
kind: BodyType::Binary,
|
|
file,
|
|
content_type: ct,
|
|
..Default::default()
|
|
}
|
|
}
|
|
"none" | "" => Body::default(),
|
|
other => {
|
|
warnings.push(format!("body mode `{other}` is not supported"));
|
|
Body::default()
|
|
}
|
|
}
|
|
}
|
|
|
|
/// `value @contentType(x)` → (value, x).
|
|
fn split_content_type(v: &str) -> (String, Option<String>) {
|
|
match v.rfind("@contentType(") {
|
|
Some(i) if v.ends_with(')') => (
|
|
v[..i].trim().to_string(),
|
|
Some(v[i + "@contentType(".len()..v.len() - 1].to_string()),
|
|
),
|
|
_ => (v.to_string(), None),
|
|
}
|
|
}
|
|
|
|
/// `@file(a|b)` → first path.
|
|
fn file_ref(v: &str, warnings: &mut Vec<String>, key: &str) -> Option<String> {
|
|
let inner = v.strip_prefix("@file(")?.strip_suffix(')')?;
|
|
let mut files = inner.split('|');
|
|
let first = files.next().unwrap_or("").to_string();
|
|
if files.next().is_some() {
|
|
warnings.push(format!("form field `{key}` had several files; only the first was kept"));
|
|
}
|
|
Some(first)
|
|
}
|
|
|
|
/// `res.body.a.b` → JSONPath `$.a.b`.
|
|
fn body_path(expr: &str) -> Option<String> {
|
|
let rest = expr.strip_prefix("res.body")?;
|
|
if rest.is_empty() {
|
|
return Some("$".into());
|
|
}
|
|
if rest.starts_with('.') || rest.starts_with('[') {
|
|
let ok = rest.chars().all(|c| c.is_alphanumeric() || "._[]-\"'*".contains(c));
|
|
return ok.then(|| format!("${rest}"));
|
|
}
|
|
None
|
|
}
|
|
|
|
fn header_name(expr: &str) -> Option<String> {
|
|
let rest = expr.strip_prefix("res.headers.").or_else(|| expr.strip_prefix("res.headers["))?;
|
|
let name = rest.trim_end_matches(']').trim_matches(['"', '\'']);
|
|
(!name.is_empty()).then(|| name.to_string())
|
|
}
|
|
|
|
fn extract_rule(var: &str, expr: &str) -> Option<ExtractRule> {
|
|
let expr = expr.trim();
|
|
let (from, path) = if let Some(p) = body_path(expr) {
|
|
(ExtractSource::Json, p)
|
|
} else if let Some(h) = header_name(expr) {
|
|
(ExtractSource::Header, h)
|
|
} else if expr == "res.status" {
|
|
(ExtractSource::Status, String::new())
|
|
} else {
|
|
return None;
|
|
};
|
|
Some(ExtractRule {
|
|
var: var.to_string(),
|
|
from,
|
|
path,
|
|
enabled: true,
|
|
persist: false,
|
|
})
|
|
}
|
|
|
|
fn literal(v: &str) -> serde_json::Value {
|
|
let v = v.trim();
|
|
serde_json::from_str(v).unwrap_or_else(|_| {
|
|
serde_json::Value::String(v.trim_matches(|c| c == '\'' || c == '"').to_string())
|
|
})
|
|
}
|
|
|
|
fn assert_rule(target: &str, expr: &str) -> Option<AssertRule> {
|
|
let target = target.trim();
|
|
let mut rule = AssertRule { enabled: true, ..Default::default() };
|
|
if target == "res.status" {
|
|
rule.on = AssertTarget::Status;
|
|
} else if target == "res.responseTime" {
|
|
rule.on = AssertTarget::Time;
|
|
} else if let Some(h) = header_name(target) {
|
|
rule.on = AssertTarget::Header;
|
|
rule.path = Some(h);
|
|
} else {
|
|
rule.on = AssertTarget::Json;
|
|
rule.path = Some(body_path(target)?);
|
|
}
|
|
let expr = expr.trim();
|
|
let (op, arg) = match expr.split_once(' ') {
|
|
Some((o, a)) => (o, a.trim()),
|
|
None => (expr, ""),
|
|
};
|
|
let num = || arg.trim().parse::<f64>().ok();
|
|
match op {
|
|
"eq" => rule.equals = Some(literal(arg)),
|
|
"neq" => rule.not_equals = Some(literal(arg)),
|
|
"gt" => rule.gt = Some(num()?),
|
|
"lt" => rule.lt = Some(num()?),
|
|
"contains" => rule.contains = Some(literal(arg)),
|
|
"matches" => rule.matches = Some(arg.trim_matches(['"', '\'']).to_string()),
|
|
"startsWith" => rule.matches = Some(format!("^{}", regex::escape(arg.trim_matches(['"', '\''])))),
|
|
"endsWith" => rule.matches = Some(format!("{}$", regex::escape(arg.trim_matches(['"', '\''])))),
|
|
"isDefined" => rule.exists = Some(true),
|
|
"isUndefined" => rule.exists = Some(false),
|
|
"isNull" => rule.equals = Some(serde_json::Value::Null),
|
|
"isString" => rule.type_is = Some("string".into()),
|
|
"isNumber" => rule.type_is = Some("number".into()),
|
|
"isBoolean" => rule.type_is = Some("boolean".into()),
|
|
"isArray" => rule.type_is = Some("array".into()),
|
|
_ => return None,
|
|
}
|
|
// Header and status checks only support a subset.
|
|
if rule.on == AssertTarget::Status && (rule.exists.is_some() || rule.type_is.is_some()) {
|
|
return None;
|
|
}
|
|
Some(rule)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use crate::collection::Collection;
|
|
|
|
fn fixture() -> std::path::PathBuf {
|
|
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/bruno")
|
|
}
|
|
|
|
#[test]
|
|
fn parses_blocks() {
|
|
let src = "meta {\n name: Get\n seq: 2\n}\n\nget {\n url: {{baseUrl}}/a?x=1\n}\n\nheaders {\n Accept: application/json\n ~X-Off: 1\n}\n\nbody:json {\n {\n \"a\": \"}\"\n }\n}\n\nvars:secret [\n token,\n ~old\n]\n";
|
|
let f = parse_bru(src).unwrap();
|
|
assert_eq!(f.get("meta", "seq"), Some("2"));
|
|
assert_eq!(f.get("get", "url"), Some("{{baseUrl}}/a?x=1"));
|
|
assert!(!f.dict("headers")[1].enabled);
|
|
assert_eq!(f.text("body:json"), Some("{\n \"a\": \"}\"\n}"));
|
|
assert_eq!(f.dict("vars:secret").len(), 2);
|
|
assert!(parse_bru("get {\n url: x\n").is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn converts_asserts_and_extracts() {
|
|
let a = assert_rule("res.status", "eq 200").unwrap();
|
|
assert_eq!((a.on, a.equals), (AssertTarget::Status, Some(serde_json::json!(200))));
|
|
let a = assert_rule("res.body.id", "isDefined").unwrap();
|
|
assert_eq!((a.path.as_deref(), a.exists), (Some("$.id"), Some(true)));
|
|
let a = assert_rule("res.headers.content-type", "contains json").unwrap();
|
|
assert_eq!((a.on, a.path.as_deref()), (AssertTarget::Header, Some("content-type")));
|
|
assert_eq!(a.contains, Some(serde_json::json!("json")));
|
|
assert!(assert_rule("res.body.items", "length 3").is_none());
|
|
let e = extract_rule("token", "res.body.token").unwrap();
|
|
assert_eq!((e.from, e.path.as_str()), (ExtractSource::Json, "$.token"));
|
|
let e = extract_rule("first", "res.body.items[0].id").unwrap();
|
|
assert_eq!(e.path, "$.items[0].id");
|
|
assert!(extract_rule("x", "res.body.items.map(i => i.id)").is_none());
|
|
}
|
|
|
|
#[test]
|
|
fn imports_fixture_collection() {
|
|
let dir = super::super::tmp_dir();
|
|
let rep = import_bruno(&fixture(), &dir).unwrap();
|
|
assert_eq!(rep.requests, 6, "{rep:?}");
|
|
assert_eq!(rep.folders, 2);
|
|
assert_eq!(rep.scripts_skipped, 3);
|
|
assert_eq!(rep.environments, vec!["local".to_string(), "production".to_string()]);
|
|
|
|
let c = Collection::open(&dir).unwrap();
|
|
assert_eq!(c.manifest.name, "Shop API");
|
|
assert_eq!(c.manifest.headers[0].name, "X-Client");
|
|
assert!(matches!(&c.manifest.auth, Auth::Config(a) if a.kind == "bearer"));
|
|
assert_eq!(
|
|
c.requests_in(""),
|
|
vec![
|
|
"auth/login.yaml",
|
|
"users/list-users.yaml",
|
|
"users/create-user.yaml",
|
|
"users/upload-avatar.yaml",
|
|
"search.gql.yaml",
|
|
"health.yaml"
|
|
]
|
|
);
|
|
|
|
let login = c.request("auth/login.yaml").unwrap();
|
|
assert_eq!(login.auth, Auth::None);
|
|
assert_eq!(login.extract[0].var, "token");
|
|
assert_eq!(login.extract[0].path, "$.token");
|
|
assert_eq!(login.assert.len(), 3);
|
|
let docs = login.docs.unwrap();
|
|
assert!(docs.contains("Imported Bruno scripts (not run)"));
|
|
assert!(docs.contains("res.body.roles: length 2"));
|
|
|
|
let list = c.request("users/list-users.yaml").unwrap();
|
|
assert_eq!(list.url, "{{baseUrl}}/users?page=1");
|
|
assert_eq!(list.params.query.len(), 2);
|
|
assert!(!list.params.query[1].enabled);
|
|
|
|
let create = c.request("users/create-user.yaml").unwrap();
|
|
assert_eq!(create.body.kind, BodyType::Json);
|
|
assert_eq!(create.params.path["org"], "acme");
|
|
let Auth::Config(basic) = &create.auth else { panic!() };
|
|
assert!(basic.str("password").unwrap().starts_with("{{secret."));
|
|
|
|
let up = c.request("users/upload-avatar.yaml").unwrap();
|
|
assert_eq!(up.body.multipart[0].file.as_deref(), Some("avatars/me.png"));
|
|
assert_eq!(up.body.multipart[1].value, "profile");
|
|
|
|
let gql = c.request("search.gql.yaml").unwrap();
|
|
assert!(gql.graphql.unwrap().query.contains("products"));
|
|
|
|
let prod = c.environment("production").unwrap();
|
|
assert!(prod.vars["apiToken"].secret);
|
|
assert_eq!(prod.vars["baseUrl"].value, "https://api.shop.example.com");
|
|
let folder = c.folder_meta("users").unwrap();
|
|
assert_eq!(folder.vars["pageSize"], "20");
|
|
std::fs::remove_dir_all(dir).unwrap();
|
|
}
|
|
}
|