mirror of
https://github.com/JoshiCodes/knock.git
synced 2026-12-04 14:59:41 +01:00
- knock-core: YAML collection format with unknown-field round trip, variable resolution across scopes with secrets and dynamic values, HTTP engine with manual redirects, cookie jar and large-body spill, basic/bearer/API key auth with debug output, assertions and extracts - Tauri app: collection commands, file watcher, SQLite history, keyring-backed secrets - Svelte UI: sidebar tree, tabs, request editor, response viewer, JSON form/code editor with schema hints, environments, settings
767 lines
25 KiB
Rust
767 lines
25 KiB
Rust
//! A collection is a directory of YAML files. Ids are paths relative to the
|
|
//! collection root, always with forward slashes.
|
|
|
|
use crate::model::*;
|
|
use anyhow::{anyhow, bail, Context, Result};
|
|
use serde::{Deserialize, Serialize};
|
|
use std::fs;
|
|
use std::path::{Component, Path, PathBuf};
|
|
|
|
pub const MANIFEST: &str = "knock.yaml";
|
|
pub const FOLDER_META: &str = "folder.yaml";
|
|
pub const ENV_DIR: &str = "environments";
|
|
|
|
#[derive(Debug, Clone, Serialize)]
|
|
pub struct Collection {
|
|
pub root: PathBuf,
|
|
pub manifest: Manifest,
|
|
pub tree: FolderNode,
|
|
pub environments: Vec<EnvEntry>,
|
|
/// Files that failed to parse, with the error. They stay on disk untouched.
|
|
pub problems: Vec<Problem>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Serialize)]
|
|
pub struct Problem {
|
|
pub path: String,
|
|
pub message: String,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Serialize)]
|
|
pub struct EnvEntry {
|
|
pub id: String,
|
|
pub name: String,
|
|
pub color: Option<String>,
|
|
pub protected: bool,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Serialize)]
|
|
#[serde(tag = "node", rename_all = "lowercase")]
|
|
pub enum Node {
|
|
Folder(FolderNode),
|
|
Request(RequestHead),
|
|
}
|
|
|
|
impl Node {
|
|
pub fn id(&self) -> &str {
|
|
match self {
|
|
Node::Folder(f) => &f.id,
|
|
Node::Request(r) => &r.id,
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone, Serialize)]
|
|
pub struct FolderNode {
|
|
/// "" for the collection root.
|
|
pub id: String,
|
|
pub name: String,
|
|
pub children: Vec<Node>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
pub struct RequestHead {
|
|
#[serde(default)]
|
|
pub id: String,
|
|
#[serde(default)]
|
|
pub name: String,
|
|
#[serde(rename = "type", default)]
|
|
pub kind: RequestKind,
|
|
#[serde(default)]
|
|
pub method: Option<String>,
|
|
}
|
|
|
|
impl Collection {
|
|
pub fn open(root: impl AsRef<Path>) -> Result<Self> {
|
|
let root = root.as_ref().canonicalize().with_context(|| {
|
|
format!("collection folder {} not found", root.as_ref().display())
|
|
})?;
|
|
let manifest_path = root.join(MANIFEST);
|
|
let mut manifest: Manifest = read_yaml(&manifest_path)
|
|
.with_context(|| format!("{} is not a knock collection", root.display()))?;
|
|
if manifest.version > FORMAT_VERSION {
|
|
bail!(
|
|
"collection format v{} is newer than this knock (v{FORMAT_VERSION}); update knock",
|
|
manifest.version
|
|
);
|
|
}
|
|
if manifest.id.is_empty() {
|
|
manifest.id = uuid::Uuid::new_v4().to_string();
|
|
write_yaml(&manifest_path, &manifest)?;
|
|
}
|
|
let mut problems = Vec::new();
|
|
let tree = load_folder(&root, "", &manifest.name, &manifest.order, &mut problems)?;
|
|
let environments = load_env_list(&root)?;
|
|
Ok(Self {
|
|
root,
|
|
manifest,
|
|
tree,
|
|
environments,
|
|
problems,
|
|
})
|
|
}
|
|
|
|
/// Creates a new collection in an empty (or not yet existing) folder.
|
|
pub fn create(root: impl AsRef<Path>, name: &str) -> Result<Self> {
|
|
let root = root.as_ref();
|
|
fs::create_dir_all(root.join(ENV_DIR))?;
|
|
if root.join(MANIFEST).exists() {
|
|
bail!("{} already contains a collection", root.display());
|
|
}
|
|
let manifest = Manifest {
|
|
version: FORMAT_VERSION,
|
|
name: name.to_string(),
|
|
id: uuid::Uuid::new_v4().to_string(),
|
|
..Default::default()
|
|
};
|
|
write_yaml(&root.join(MANIFEST), &manifest)?;
|
|
let env = Environment {
|
|
vars: [(
|
|
"baseUrl".to_string(),
|
|
EnvVar {
|
|
value: "http://localhost:8080".into(),
|
|
secret: false,
|
|
description: None,
|
|
},
|
|
)]
|
|
.into_iter()
|
|
.collect(),
|
|
..Default::default()
|
|
};
|
|
write_yaml(&root.join(ENV_DIR).join("local.yaml"), &env)?;
|
|
ensure_gitignore(root)?;
|
|
Self::open(root)
|
|
}
|
|
|
|
pub fn reload(&mut self) -> Result<()> {
|
|
*self = Self::open(&self.root)?;
|
|
Ok(())
|
|
}
|
|
|
|
pub fn abs(&self, id: &str) -> Result<PathBuf> {
|
|
resolve_inside(&self.root, id)
|
|
}
|
|
|
|
// ------------------------------------------------------------ reading
|
|
|
|
pub fn request(&self, id: &str) -> Result<Request> {
|
|
read_yaml(&self.abs(id)?)
|
|
}
|
|
|
|
pub fn folder_meta(&self, id: &str) -> Result<FolderMeta> {
|
|
let p = self.abs(id)?.join(FOLDER_META);
|
|
if p.exists() {
|
|
read_yaml(&p)
|
|
} else {
|
|
Ok(FolderMeta::default())
|
|
}
|
|
}
|
|
|
|
pub fn environment(&self, id: &str) -> Result<Environment> {
|
|
read_yaml(&self.root.join(ENV_DIR).join(format!("{id}.yaml")))
|
|
}
|
|
|
|
pub fn secrets_file(&self, env: &str) -> Result<SecretsFile> {
|
|
let p = self.root.join(ENV_DIR).join(format!("{env}.secrets.yaml"));
|
|
if p.exists() {
|
|
read_yaml(&p)
|
|
} else {
|
|
Ok(SecretsFile::default())
|
|
}
|
|
}
|
|
|
|
/// Folder chain from the root down to the folder that contains `id`,
|
|
/// root first. Used for auth, header and variable inheritance.
|
|
pub fn ancestors(&self, id: &str) -> Result<Vec<(String, FolderMeta)>> {
|
|
let mut out = Vec::new();
|
|
let parts: Vec<&str> = id.split('/').collect();
|
|
let mut cur = String::new();
|
|
for part in &parts[..parts.len().saturating_sub(1)] {
|
|
if !cur.is_empty() {
|
|
cur.push('/');
|
|
}
|
|
cur.push_str(part);
|
|
out.push((cur.clone(), self.folder_meta(&cur)?));
|
|
}
|
|
Ok(out)
|
|
}
|
|
|
|
pub fn find(&self, id: &str) -> Option<&Node> {
|
|
fn walk<'a>(f: &'a FolderNode, id: &str) -> Option<&'a Node> {
|
|
for c in &f.children {
|
|
if c.id() == id {
|
|
return Some(c);
|
|
}
|
|
if let Node::Folder(sub) = c {
|
|
if id.starts_with(&format!("{}/", sub.id)) {
|
|
return walk(sub, id);
|
|
}
|
|
}
|
|
}
|
|
None
|
|
}
|
|
walk(&self.tree, id)
|
|
}
|
|
|
|
/// All request ids below `folder` ("" = whole collection) in sidebar order.
|
|
pub fn requests_in(&self, folder: &str) -> Vec<String> {
|
|
fn walk(f: &FolderNode, out: &mut Vec<String>) {
|
|
for c in &f.children {
|
|
match c {
|
|
Node::Request(r) => out.push(r.id.clone()),
|
|
Node::Folder(sub) => walk(sub, out),
|
|
}
|
|
}
|
|
}
|
|
let mut out = Vec::new();
|
|
if folder.is_empty() {
|
|
walk(&self.tree, &mut out);
|
|
} else if let Some(Node::Folder(f)) = self.find(folder) {
|
|
walk(f, &mut out);
|
|
} else if let Some(Node::Request(r)) = self.find(folder) {
|
|
out.push(r.id.clone());
|
|
}
|
|
out
|
|
}
|
|
|
|
// ------------------------------------------------------------ writing
|
|
|
|
pub fn save_request(&self, id: &str, req: &Request) -> Result<()> {
|
|
write_yaml(&self.abs(id)?, req)
|
|
}
|
|
|
|
pub fn save_folder_meta(&self, id: &str, meta: &FolderMeta) -> Result<()> {
|
|
if id.is_empty() {
|
|
bail!("the collection root has no folder.yaml; edit the manifest instead");
|
|
}
|
|
write_yaml(&self.abs(id)?.join(FOLDER_META), meta)
|
|
}
|
|
|
|
pub fn save_manifest(&self, m: &Manifest) -> Result<()> {
|
|
write_yaml(&self.root.join(MANIFEST), m)
|
|
}
|
|
|
|
pub fn save_environment(&self, id: &str, env: &Environment) -> Result<()> {
|
|
check_slug(id)?;
|
|
write_yaml(&self.root.join(ENV_DIR).join(format!("{id}.yaml")), env)
|
|
}
|
|
|
|
pub fn save_secrets_file(&self, env: &str, s: &SecretsFile) -> Result<()> {
|
|
check_slug(env)?;
|
|
ensure_gitignore(&self.root)?;
|
|
write_yaml(&self.root.join(ENV_DIR).join(format!("{env}.secrets.yaml")), s)
|
|
}
|
|
|
|
pub fn delete_environment(&self, id: &str) -> Result<()> {
|
|
check_slug(id)?;
|
|
let dir = self.root.join(ENV_DIR);
|
|
fs::remove_file(dir.join(format!("{id}.yaml")))?;
|
|
let _ = fs::remove_file(dir.join(format!("{id}.secrets.yaml")));
|
|
Ok(())
|
|
}
|
|
|
|
/// Creates a request file in `folder` and returns its id.
|
|
pub fn create_request(&self, folder: &str, req: &Request) -> Result<String> {
|
|
let dir = self.abs(folder)?;
|
|
let suffix = match req.kind {
|
|
RequestKind::Ws => ".ws.yaml",
|
|
RequestKind::Graphql => ".gql.yaml",
|
|
RequestKind::Http => ".yaml",
|
|
};
|
|
let file = unique_name(&dir, &slugify(&req.name), suffix);
|
|
let id = join_id(folder, &file);
|
|
self.save_request(&id, req)?;
|
|
self.append_order(folder, &file)?;
|
|
Ok(id)
|
|
}
|
|
|
|
pub fn create_folder(&self, parent: &str, name: &str) -> Result<String> {
|
|
let dir = self.abs(parent)?;
|
|
let slug = unique_name(&dir, &slugify(name), "");
|
|
fs::create_dir_all(dir.join(&slug))?;
|
|
let id = join_id(parent, &slug);
|
|
let meta = FolderMeta {
|
|
name: Some(name.to_string()),
|
|
..Default::default()
|
|
};
|
|
self.save_folder_meta(&id, &meta)?;
|
|
self.append_order(parent, &slug)?;
|
|
Ok(id)
|
|
}
|
|
|
|
/// Renames the display name and the file or folder on disk. Returns the new id.
|
|
pub fn rename(&self, id: &str, new_name: &str) -> Result<String> {
|
|
let path = self.abs(id)?;
|
|
let (parent, old_file) = split_id(id);
|
|
let new_file;
|
|
if path.is_dir() {
|
|
let mut meta = self.folder_meta(id)?;
|
|
meta.name = Some(new_name.to_string());
|
|
self.save_folder_meta(id, &meta)?;
|
|
new_file = unique_name(&self.abs(parent)?, &slugify(new_name), "");
|
|
} else {
|
|
let mut req = self.request(id)?;
|
|
req.name = new_name.to_string();
|
|
self.save_request(id, &req)?;
|
|
let suffix = request_suffix(old_file);
|
|
let base = slugify(new_name);
|
|
if format!("{base}{suffix}") == old_file {
|
|
return Ok(id.to_string());
|
|
}
|
|
new_file = unique_name(&self.abs(parent)?, &base, suffix);
|
|
}
|
|
if new_file == old_file {
|
|
return Ok(id.to_string());
|
|
}
|
|
fs::rename(&path, self.abs(parent)?.join(&new_file))?;
|
|
self.replace_in_order(parent, old_file, &new_file)?;
|
|
Ok(join_id(parent, &new_file))
|
|
}
|
|
|
|
pub fn duplicate(&self, id: &str) -> Result<String> {
|
|
let mut req = self.request(id)?;
|
|
req.name = format!("{} copy", req.name);
|
|
let (parent, _) = split_id(id);
|
|
let dir = self.abs(parent)?;
|
|
let suffix = request_suffix(split_id(id).1);
|
|
let file = unique_name(&dir, &slugify(&req.name), suffix);
|
|
let new_id = join_id(parent, &file);
|
|
self.save_request(&new_id, &req)?;
|
|
self.insert_order_after(parent, split_id(id).1, &file)?;
|
|
Ok(new_id)
|
|
}
|
|
|
|
pub fn delete(&self, id: &str) -> Result<()> {
|
|
if id.is_empty() {
|
|
bail!("refusing to delete the collection root");
|
|
}
|
|
let path = self.abs(id)?;
|
|
if path.is_dir() {
|
|
fs::remove_dir_all(&path)?;
|
|
} else {
|
|
fs::remove_file(&path)?;
|
|
}
|
|
let (parent, file) = split_id(id);
|
|
self.remove_from_order(parent, file)
|
|
}
|
|
|
|
/// Moves a node into `target_folder` at `index` (None = end). Also used to
|
|
/// reorder within the same folder.
|
|
pub fn move_node(&self, id: &str, target_folder: &str, index: Option<usize>) -> Result<String> {
|
|
let (parent, file) = split_id(id);
|
|
if target_folder == id || target_folder.starts_with(&format!("{id}/")) {
|
|
bail!("cannot move a folder into itself");
|
|
}
|
|
let new_file = if parent == target_folder {
|
|
file.to_string()
|
|
} else {
|
|
let dir = self.abs(target_folder)?;
|
|
let new_file = if dir.join(file).exists() {
|
|
let suffix = request_suffix(file);
|
|
let base = file.strip_suffix(suffix).unwrap_or(file);
|
|
unique_name(&dir, base, suffix)
|
|
} else {
|
|
file.to_string()
|
|
};
|
|
fs::rename(self.abs(id)?, dir.join(&new_file))?;
|
|
self.remove_from_order(parent, file)?;
|
|
new_file
|
|
};
|
|
let mut order = self.effective_order(target_folder)?;
|
|
order.retain(|f| f != &new_file);
|
|
let at = index.unwrap_or(order.len()).min(order.len());
|
|
order.insert(at, new_file.clone());
|
|
self.set_order(target_folder, order)?;
|
|
Ok(join_id(target_folder, &new_file))
|
|
}
|
|
|
|
// ------------------------------------------------------------ ordering
|
|
|
|
/// Order as it is on disk right now, so earlier writes in the same
|
|
/// operation are taken into account.
|
|
fn effective_order(&self, folder: &str) -> Result<Vec<String>> {
|
|
let dir = self.abs(folder)?;
|
|
let stored = if folder.is_empty() {
|
|
read_yaml::<Manifest>(&self.root.join(MANIFEST))?.order
|
|
} else {
|
|
self.folder_meta(folder)?.order
|
|
};
|
|
let entries = list_entries(&dir)?;
|
|
Ok(apply_order(&stored, entries))
|
|
}
|
|
|
|
fn set_order(&self, folder: &str, order: Vec<String>) -> Result<()> {
|
|
if folder.is_empty() {
|
|
let mut m: Manifest = read_yaml(&self.root.join(MANIFEST))?;
|
|
m.order = order;
|
|
self.save_manifest(&m)
|
|
} else {
|
|
let mut meta = self.folder_meta(folder)?;
|
|
meta.order = order;
|
|
self.save_folder_meta(folder, &meta)
|
|
}
|
|
}
|
|
|
|
fn append_order(&self, folder: &str, file: &str) -> Result<()> {
|
|
let mut order = self.effective_order(folder)?;
|
|
if !order.iter().any(|f| f == file) {
|
|
order.push(file.to_string());
|
|
}
|
|
self.set_order(folder, order)
|
|
}
|
|
|
|
fn insert_order_after(&self, folder: &str, after: &str, file: &str) -> Result<()> {
|
|
let mut order = self.effective_order(folder)?;
|
|
order.retain(|f| f != file);
|
|
let at = order.iter().position(|f| f == after).map(|i| i + 1).unwrap_or(order.len());
|
|
order.insert(at, file.to_string());
|
|
self.set_order(folder, order)
|
|
}
|
|
|
|
fn replace_in_order(&self, folder: &str, old: &str, new: &str) -> Result<()> {
|
|
let stored = if folder.is_empty() {
|
|
read_yaml::<Manifest>(&self.root.join(MANIFEST))?.order
|
|
} else {
|
|
self.folder_meta(folder)?.order
|
|
};
|
|
if stored.is_empty() {
|
|
return Ok(());
|
|
}
|
|
let order = stored
|
|
.into_iter()
|
|
.map(|f| if f == old { new.to_string() } else { f })
|
|
.collect();
|
|
self.set_order(folder, order)
|
|
}
|
|
|
|
fn remove_from_order(&self, folder: &str, file: &str) -> Result<()> {
|
|
let stored = if folder.is_empty() {
|
|
read_yaml::<Manifest>(&self.root.join(MANIFEST))?.order
|
|
} else {
|
|
let p = self.abs(folder)?.join(FOLDER_META);
|
|
if !p.exists() {
|
|
return Ok(());
|
|
}
|
|
self.folder_meta(folder)?.order
|
|
};
|
|
if !stored.iter().any(|f| f == file) {
|
|
return Ok(());
|
|
}
|
|
self.set_order(folder, stored.into_iter().filter(|f| f != file).collect())
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------- loading
|
|
|
|
fn load_folder(
|
|
root: &Path,
|
|
id: &str,
|
|
name: &str,
|
|
order: &[String],
|
|
problems: &mut Vec<Problem>,
|
|
) -> Result<FolderNode> {
|
|
let dir = if id.is_empty() { root.to_path_buf() } else { root.join(id) };
|
|
let entries = list_entries(&dir)?;
|
|
let ordered = apply_order(order, entries);
|
|
let mut children = Vec::with_capacity(ordered.len());
|
|
for file in ordered {
|
|
let child_id = join_id(id, &file);
|
|
let path = dir.join(&file);
|
|
if path.is_dir() {
|
|
let meta: FolderMeta = match path.join(FOLDER_META) {
|
|
p if p.exists() => match read_yaml(&p) {
|
|
Ok(m) => m,
|
|
Err(e) => {
|
|
problems.push(Problem {
|
|
path: format!("{child_id}/{FOLDER_META}"),
|
|
message: format!("{e:#}"),
|
|
});
|
|
FolderMeta::default()
|
|
}
|
|
},
|
|
_ => FolderMeta::default(),
|
|
};
|
|
let fname = meta.name.clone().unwrap_or_else(|| file.clone());
|
|
children.push(Node::Folder(load_folder(
|
|
root, &child_id, &fname, &meta.order, problems,
|
|
)?));
|
|
} else {
|
|
match read_yaml::<RequestHead>(&path) {
|
|
Ok(mut head) => {
|
|
head.id = child_id;
|
|
if head.name.is_empty() {
|
|
head.name = file.trim_end_matches(".yaml").to_string();
|
|
}
|
|
children.push(Node::Request(head));
|
|
}
|
|
Err(e) => problems.push(Problem {
|
|
path: child_id,
|
|
message: format!("{e:#}"),
|
|
}),
|
|
}
|
|
}
|
|
}
|
|
Ok(FolderNode {
|
|
id: id.to_string(),
|
|
name: name.to_string(),
|
|
children,
|
|
})
|
|
}
|
|
|
|
/// Request files and sub folders of a directory, unordered.
|
|
fn list_entries(dir: &Path) -> Result<Vec<String>> {
|
|
let mut out = Vec::new();
|
|
for e in fs::read_dir(dir).with_context(|| format!("reading {}", dir.display()))? {
|
|
let e = e?;
|
|
let name = e.file_name().to_string_lossy().to_string();
|
|
if name.starts_with('.') {
|
|
continue;
|
|
}
|
|
let ft = e.file_type()?;
|
|
if ft.is_dir() {
|
|
if name == ENV_DIR || name == "node_modules" || name == "target" {
|
|
continue;
|
|
}
|
|
out.push(name);
|
|
} else if (name.ends_with(".yaml") || name.ends_with(".yml"))
|
|
&& name != MANIFEST
|
|
&& name != FOLDER_META
|
|
{
|
|
out.push(name);
|
|
}
|
|
}
|
|
Ok(out)
|
|
}
|
|
|
|
/// Stored order first (skipping entries that no longer exist), then the rest
|
|
/// sorted by name.
|
|
fn apply_order(stored: &[String], mut entries: Vec<String>) -> Vec<String> {
|
|
let mut out = Vec::with_capacity(entries.len());
|
|
for s in stored {
|
|
if let Some(i) = entries.iter().position(|e| e == s) {
|
|
out.push(entries.swap_remove(i));
|
|
}
|
|
}
|
|
entries.sort_by_key(|a| a.to_lowercase());
|
|
out.extend(entries);
|
|
out
|
|
}
|
|
|
|
fn load_env_list(root: &Path) -> Result<Vec<EnvEntry>> {
|
|
let dir = root.join(ENV_DIR);
|
|
let mut out = Vec::new();
|
|
if !dir.exists() {
|
|
return Ok(out);
|
|
}
|
|
for e in fs::read_dir(&dir)? {
|
|
let e = e?;
|
|
let name = e.file_name().to_string_lossy().to_string();
|
|
let Some(id) = name.strip_suffix(".yaml") else { continue };
|
|
if id.ends_with(".secrets") {
|
|
continue;
|
|
}
|
|
let env: Environment = read_yaml(&e.path()).unwrap_or_default();
|
|
out.push(EnvEntry {
|
|
id: id.to_string(),
|
|
name: env.name.unwrap_or_else(|| id.to_string()),
|
|
color: env.color,
|
|
protected: env.protected,
|
|
});
|
|
}
|
|
out.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));
|
|
Ok(out)
|
|
}
|
|
|
|
// ---------------------------------------------------------------- helpers
|
|
|
|
pub fn read_yaml<T: for<'de> Deserialize<'de>>(path: &Path) -> Result<T> {
|
|
let text = fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
|
|
serde_yaml_ng::from_str(&text).with_context(|| format!("parsing {}", path.display()))
|
|
}
|
|
|
|
/// Writes atomically (temp file + rename) so a crash never leaves half a file
|
|
/// and file watchers see one change.
|
|
pub fn write_yaml<T: Serialize>(path: &Path, value: &T) -> Result<()> {
|
|
let text = serde_yaml_ng::to_string(value)?;
|
|
if let Some(parent) = path.parent() {
|
|
fs::create_dir_all(parent)?;
|
|
}
|
|
if fs::read_to_string(path).ok().as_deref() == Some(text.as_str()) {
|
|
return Ok(());
|
|
}
|
|
let tmp = path.with_extension("yaml.tmp");
|
|
fs::write(&tmp, text)?;
|
|
fs::rename(&tmp, path)?;
|
|
Ok(())
|
|
}
|
|
|
|
fn ensure_gitignore(root: &Path) -> Result<()> {
|
|
let p = root.join(".gitignore");
|
|
let line = "*.secrets.yaml";
|
|
let cur = fs::read_to_string(&p).unwrap_or_default();
|
|
if !cur.lines().any(|l| l.trim() == line) {
|
|
let mut next = cur;
|
|
if !next.is_empty() && !next.ends_with('\n') {
|
|
next.push('\n');
|
|
}
|
|
next.push_str(line);
|
|
next.push('\n');
|
|
fs::write(&p, next)?;
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Joins `id` onto `root` and refuses anything that would leave it.
|
|
pub fn resolve_inside(root: &Path, id: &str) -> Result<PathBuf> {
|
|
let rel = Path::new(id);
|
|
for c in rel.components() {
|
|
match c {
|
|
Component::Normal(_) | Component::CurDir => {}
|
|
_ => return Err(anyhow!("invalid path '{id}'")),
|
|
}
|
|
}
|
|
Ok(root.join(rel))
|
|
}
|
|
|
|
fn check_slug(s: &str) -> Result<()> {
|
|
if s.is_empty() || s.contains(['/', '\\']) || s.starts_with('.') {
|
|
bail!("invalid name '{s}'");
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub fn join_id(parent: &str, file: &str) -> String {
|
|
if parent.is_empty() {
|
|
file.to_string()
|
|
} else {
|
|
format!("{parent}/{file}")
|
|
}
|
|
}
|
|
|
|
pub fn split_id(id: &str) -> (&str, &str) {
|
|
match id.rfind('/') {
|
|
Some(i) => (&id[..i], &id[i + 1..]),
|
|
None => ("", id),
|
|
}
|
|
}
|
|
|
|
fn request_suffix(file: &str) -> &'static str {
|
|
if file.ends_with(".ws.yaml") {
|
|
".ws.yaml"
|
|
} else if file.ends_with(".gql.yaml") {
|
|
".gql.yaml"
|
|
} else if file.ends_with(".yml") {
|
|
".yml"
|
|
} else {
|
|
".yaml"
|
|
}
|
|
}
|
|
|
|
pub fn slugify(name: &str) -> String {
|
|
let mut out = String::new();
|
|
let mut dash = false;
|
|
for ch in name.trim().chars() {
|
|
let c = match ch {
|
|
'ä' | 'Ä' => Some("ae"),
|
|
'ö' | 'Ö' => Some("oe"),
|
|
'ü' | 'Ü' => Some("ue"),
|
|
'ß' => Some("ss"),
|
|
_ => None,
|
|
};
|
|
if let Some(rep) = c {
|
|
out.push_str(rep);
|
|
dash = false;
|
|
} else if ch.is_ascii_alphanumeric() {
|
|
out.push(ch.to_ascii_lowercase());
|
|
dash = false;
|
|
} else if !dash && !out.is_empty() {
|
|
out.push('-');
|
|
dash = true;
|
|
}
|
|
}
|
|
let out = out.trim_end_matches('-').to_string();
|
|
if out.is_empty() {
|
|
"untitled".into()
|
|
} else {
|
|
out
|
|
}
|
|
}
|
|
|
|
fn unique_name(dir: &Path, base: &str, suffix: &str) -> String {
|
|
let first = format!("{base}{suffix}");
|
|
if !dir.join(&first).exists() {
|
|
return first;
|
|
}
|
|
(2..)
|
|
.map(|n| format!("{base}-{n}{suffix}"))
|
|
.find(|n| !dir.join(n).exists())
|
|
.unwrap()
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn tmp() -> PathBuf {
|
|
let p = std::env::temp_dir().join(format!("knock-test-{}", uuid::Uuid::new_v4()));
|
|
fs::create_dir_all(&p).unwrap();
|
|
p
|
|
}
|
|
|
|
#[test]
|
|
fn create_load_and_order() {
|
|
let dir = tmp();
|
|
let c = Collection::create(&dir, "My API").unwrap();
|
|
assert!(fs::read_to_string(dir.join(".gitignore")).unwrap().contains("*.secrets.yaml"));
|
|
let users = c.create_folder("", "Users").unwrap();
|
|
let mut r = Request::default();
|
|
r.name = "List users".into();
|
|
let a = c.create_request(&users, &r).unwrap();
|
|
r.name = "Create user".into();
|
|
let b = c.create_request(&users, &r).unwrap();
|
|
assert_eq!(a, "users/list-users.yaml");
|
|
|
|
let c = Collection::open(&dir).unwrap();
|
|
assert_eq!(c.requests_in("users"), vec![a.clone(), b.clone()]);
|
|
assert_eq!(c.environments[0].id, "local");
|
|
|
|
// move b before a
|
|
c.move_node(&b, "users", Some(0)).unwrap();
|
|
let c = Collection::open(&dir).unwrap();
|
|
assert_eq!(c.requests_in(""), vec![b.clone(), a.clone()]);
|
|
|
|
let renamed = c.rename(&a, "All users").unwrap();
|
|
assert_eq!(renamed, "users/all-users.yaml");
|
|
let c = Collection::open(&dir).unwrap();
|
|
assert_eq!(c.requests_in(""), vec![b.clone(), renamed.clone()]);
|
|
|
|
let dup = c.duplicate(&b).unwrap();
|
|
let c = Collection::open(&dir).unwrap();
|
|
assert_eq!(c.requests_in(""), vec![b.clone(), dup.clone(), renamed.clone()]);
|
|
|
|
let moved = c.move_node(&dup, "", None).unwrap();
|
|
let c = Collection::open(&dir).unwrap();
|
|
assert_eq!(c.requests_in(""), vec![b.clone(), renamed.clone(), moved.clone()]);
|
|
c.delete(&moved).unwrap();
|
|
let c = Collection::open(&dir).unwrap();
|
|
assert_eq!(c.requests_in("").len(), 2);
|
|
assert!(c.move_node("users", "users", None).is_err());
|
|
fs::remove_dir_all(dir).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn rejects_escaping_paths() {
|
|
let root = Path::new("/tmp/x");
|
|
assert!(resolve_inside(root, "../etc/passwd").is_err());
|
|
assert!(resolve_inside(root, "/etc/passwd").is_err());
|
|
assert!(resolve_inside(root, "a/b.yaml").is_ok());
|
|
}
|
|
|
|
#[test]
|
|
fn slugs() {
|
|
assert_eq!(slugify("Create user"), "create-user");
|
|
assert_eq!(slugify(" Größe / Übersicht!! "), "groesse-uebersicht");
|
|
assert_eq!(slugify("///"), "untitled");
|
|
}
|
|
}
|