file_path
stringlengths
3
280
file_language
stringclasses
66 values
content
stringlengths
1
1.04M
repo_name
stringlengths
5
92
repo_stars
int64
0
154k
repo_description
stringlengths
0
402
repo_primary_language
stringclasses
108 values
developer_username
stringlengths
1
25
developer_name
stringlengths
0
30
developer_company
stringlengths
0
82
pkg/logger/logger.go
Go
package logger import ( "os" "go.uber.org/zap" "go.uber.org/zap/zapcore" "github.com/yorukot/stargo/internal/config" ) // InitLogger initialize the logger func InitLogger() { appEnv := os.Getenv("APP_ENV") var logger *zap.Logger if appEnv == string(config.AppEnvDev) { devConfig := zap.NewDevelopmentConfig() devConfig.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder logger, _ = devConfig.Build() } else { logger = zap.Must(zap.NewProduction()) } zap.ReplaceGlobals(logger) zap.L().Info("Logger initialized") defer logger.Sync() }
yorukot/stargo
3
Simple and modern Go web API template built with chi router
Go
yorukot
Yorukot
pkg/response/response.go
Go
package response import ( "encoding/json" "net/http" ) // ErrorResponse is the response for an error type ErrorResponse struct { Message string `json:"message"` ErrCode string `json:"err_code"` } // SuccessResponse is the response for a success type SuccessResponse struct { Message string `json:"message"` Data any `json:"data"` } // RespondWithError responds with an error message func RespondWithError(w http.ResponseWriter, statusCode int, message, errCode string) { w.WriteHeader(statusCode) json.NewEncoder(w).Encode(ErrorResponse{ Message: message, ErrCode: errCode, }) } // RespondWithJSON responds with a JSON object func RespondWithJSON(w http.ResponseWriter, statusCode int, message string, data interface{}) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(statusCode) json.NewEncoder(w).Encode(SuccessResponse{ Message: message, Data: data, }) } // RespondWithData responds with a JSON object func RespondWithData(w http.ResponseWriter, data interface{}) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(data) }
yorukot/stargo
3
Simple and modern Go web API template built with chi router
Go
yorukot
Yorukot
main.go
Go
package main import ( "bufio" "encoding/binary" "errors" "fmt" "os" "strings" "unicode/utf8" "github.com/spf13/cobra" "golang.org/x/text/unicode/norm" ) var ( // 8 cores × 8 tones = 64 tokens (fixed codebook) cores = []string{ "汪", "嗚", "嗷", "汪汪", "嗚汪", "嗷汪", "汪嗚", "~汪", } tones = []string{ "", // 0 ".", // 1 "~", // 2 "~", // 3 (fullwidth tilde) "…", // 4 (ellipsis) "!", // 5 "!", // 6 (fullwidth exclamation) "~.", // 7 (two-char tone, still no spaces) } codebook []string reverseTable map[string]byte ) func init() { codebook = make([]string, 0, 64) reverseTable = make(map[string]byte, 64) var id byte = 0 for _, c := range cores { for _, t := range tones { token := c + t codebook = append(codebook, token) if _, exists := reverseTable[token]; exists { panic("duplicate token in codebook: " + token) } reverseTable[token] = id id++ } } if len(codebook) != 64 { panic("codebook size is not 64") } } // Encode turns arbitrary UTF-8 text into dog-speech tokens. func Encode(input string) (string, error) { // Normalize to NFC so visually-similar Unicode sequences become consistent. input = norm.NFC.String(input) // In Go, strings can contain invalid UTF-8; decide policy: reject invalid. if !utf8.ValidString(input) { return "", errors.New("input is not valid UTF-8") } payload := []byte(input) // Header: 4-byte length (big-endian) total := make([]byte, 4+len(payload)) binary.BigEndian.PutUint32(total[:4], uint32(len(payload))) copy(total[4:], payload) // Convert bytes to 6-bit tokens var outTokens []string var bitBuf uint32 var bitCount uint8 emit6 := func(v byte) { outTokens = append(outTokens, codebook[v&0x3F]) } for _, b := range total { bitBuf = (bitBuf << 8) | uint32(b) bitCount += 8 for bitCount >= 6 { shift := bitCount - 6 chunk := byte((bitBuf >> shift) & 0x3F) emit6(chunk) bitCount -= 6 // keep remaining bits in bitBuf by masking if bitCount == 0 { bitBuf = 0 } else { bitBuf = bitBuf & ((1 << bitCount) - 1) } } } // Pad remaining bits with zeros (safe because we have length header) if bitCount > 0 { chunk := byte((bitBuf << (6 - bitCount)) & 0x3F) emit6(chunk) } return strings.Join(outTokens, " "), nil } // Decode turns dog-speech tokens back into the original UTF-8 text. func Decode(dogSpeech string) (string, error) { // Normalize NFC to reduce Unicode representation issues (esp. if copy/pasted). dogSpeech = norm.NFC.String(strings.TrimSpace(dogSpeech)) if dogSpeech == "" { return "", errors.New("empty input") } parts := strings.Fields(dogSpeech) // splits on any whitespace; output format is still "space-separated" ids := make([]byte, 0, len(parts)) for _, tok := range parts { id, ok := reverseTable[tok] if !ok { return "", fmt.Errorf("unknown token: %q", tok) } ids = append(ids, id) } // Convert 6-bit ids to bytes var bytesOut []byte var bitBuf uint32 var bitCount uint8 for _, id := range ids { bitBuf = (bitBuf << 6) | uint32(id&0x3F) bitCount += 6 for bitCount >= 8 { shift := bitCount - 8 b := byte((bitBuf >> shift) & 0xFF) bytesOut = append(bytesOut, b) bitCount -= 8 if bitCount == 0 { bitBuf = 0 } else { bitBuf = bitBuf & ((1 << bitCount) - 1) } } } // Need at least 4 bytes for length header if len(bytesOut) < 4 { return "", errors.New("decoded data too short (missing length header)") } n := binary.BigEndian.Uint32(bytesOut[:4]) if int64(n) < 0 { return "", errors.New("invalid length header") } if len(bytesOut) < 4+int(n) { return "", fmt.Errorf("decoded data incomplete: need %d bytes payload, have %d", n, len(bytesOut)-4) } payload := bytesOut[4 : 4+int(n)] if !utf8.Valid(payload) { return "", errors.New("decoded payload is not valid UTF-8 (token stream may be corrupted)") } return string(payload), nil } func readAllStdin() (string, error) { in := bufio.NewReader(os.Stdin) b, err := in.ReadBytes(0) if err == nil { // unlikely to hit NUL; just in case return string(b[:len(b)-1]), nil } // If ReadBytes returns error, it usually includes partial data; fall back to ReadString loop // Simpler: read via scanner with big buffer sc := bufio.NewScanner(os.Stdin) // allow large inputs buf := make([]byte, 0, 1024*1024) sc.Buffer(buf, 10*1024*1024) var sb strings.Builder first := true for sc.Scan() { if !first { sb.WriteByte('\n') } first = false sb.WriteString(sc.Text()) } if err := sc.Err(); err != nil { return "", err } return sb.String(), nil } func inputFromArgsOrStdin(args []string) (string, error) { if len(args) > 0 { return strings.Join(args, " "), nil } return readAllStdin() } func runMode(mode string, input string) (string, error) { switch strings.ToLower(mode) { case "encode", "enc": return Encode(input) case "decode", "dec": return Decode(input) default: return "", fmt.Errorf("unknown mode: %s", mode) } } func newRootCmd() *cobra.Command { var mode string rootCmd := &cobra.Command{ Use: "woofwoof [text]", Short: "Encode/decode text as dog speech", Args: cobra.ArbitraryArgs, RunE: func(cmd *cobra.Command, args []string) error { input, err := inputFromArgsOrStdin(args) if err != nil { return fmt.Errorf("read stdin error: %w", err) } out, err := runMode(mode, input) if err != nil { return err } fmt.Fprintln(cmd.OutOrStdout(), out) return nil }, } rootCmd.Flags().StringVarP(&mode, "mode", "m", "encode", "encode or decode") encodeCmd := &cobra.Command{ Use: "encode [text]", Short: "Encode plain UTF-8 text to dog speech", Args: cobra.ArbitraryArgs, RunE: func(cmd *cobra.Command, args []string) error { input, err := inputFromArgsOrStdin(args) if err != nil { return fmt.Errorf("read stdin error: %w", err) } out, err := Encode(input) if err != nil { return fmt.Errorf("encode error: %w", err) } fmt.Fprintln(cmd.OutOrStdout(), out) return nil }, } decodeCmd := &cobra.Command{ Use: "decode [dog-speech]", Short: "Decode dog speech back to original UTF-8 text", Args: cobra.ArbitraryArgs, RunE: func(cmd *cobra.Command, args []string) error { input, err := inputFromArgsOrStdin(args) if err != nil { return fmt.Errorf("read stdin error: %w", err) } out, err := Decode(input) if err != nil { return fmt.Errorf("decode error: %w", err) } fmt.Fprintln(cmd.OutOrStdout(), out) return nil }, } rootCmd.AddCommand(encodeCmd, decodeCmd) return rootCmd } func main() { if err := newRootCmd().Execute(); err != nil { os.Exit(1) } }
yorukot/woofwoof
0
Go
yorukot
Yorukot
example/src/main.rs
Rust
mod generated; fn main() { println!("Hello, from the example!"); generated::print(); }
yoshuawuyts/cargo-task-wasm
21
A sandboxed local task runner for Rust
Rust
yoshuawuyts
Yosh
example/tasks/args.rs
Rust
fn main() -> std::io::Result<()> { std::env::args().for_each(|arg| { println!("arg: {}", arg); }); Ok(()) }
yoshuawuyts/cargo-task-wasm
21
A sandboxed local task runner for Rust
Rust
yoshuawuyts
Yosh
example/tasks/dep.rs
Rust
fn main() { let now = wasi::clocks::wall_clock::now(); println!("The unix time is now: {now:?}") }
yoshuawuyts/cargo-task-wasm
21
A sandboxed local task runner for Rust
Rust
yoshuawuyts
Yosh
example/tasks/env.rs
Rust
fn main() { let my_env = std::env::var("MY_ENV_VAR").unwrap(); println!("MY_ENV_VAR={my_env}"); }
yoshuawuyts/cargo-task-wasm
21
A sandboxed local task runner for Rust
Rust
yoshuawuyts
Yosh
example/tasks/generate.rs
Rust
use std::fs; const FILE: &str = r#"pub fn print() { println!("hello from the generated file"); }""#; fn main() -> std::io::Result<()> { // gen the file Ok(()) }
yoshuawuyts/cargo-task-wasm
21
A sandboxed local task runner for Rust
Rust
yoshuawuyts
Yosh
example/tasks/list.rs
Rust
use std::fs; fn main() -> std::io::Result<()> { for entry in fs::read_dir(".")? { println!("{:?}", entry?); } Ok(()) }
yoshuawuyts/cargo-task-wasm
21
A sandboxed local task runner for Rust
Rust
yoshuawuyts
Yosh
example/tasks/module.rs
Rust
//! Calls a function from a local `mod.rs` file mod shared; pub fn main() { println!("hello from the main module"); shared::hello(); }
yoshuawuyts/cargo-task-wasm
21
A sandboxed local task runner for Rust
Rust
yoshuawuyts
Yosh
example/tasks/print.rs
Rust
fn main() { println!("printed a message from inside a Wasm sandbox!"); }
yoshuawuyts/cargo-task-wasm
21
A sandboxed local task runner for Rust
Rust
yoshuawuyts
Yosh
example/tasks/shared/mod.rs
Rust
pub fn hello() { println!("hello from the submodule"); }
yoshuawuyts/cargo-task-wasm
21
A sandboxed local task runner for Rust
Rust
yoshuawuyts
Yosh
scripts/run.sh
Shell
#!/bin/bash set -e export MY_ENV_VAR="my env is this" PATH=$PATH:$(pwd)/target/debug cargo build cd example cargo task $@
yoshuawuyts/cargo-task-wasm
21
A sandboxed local task runner for Rust
Rust
yoshuawuyts
Yosh
src/cargo.rs
Rust
use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; /// The cargo.toml representation for tasks #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "kebab-case")] pub struct CargoToml { pub package: Package, } /// The `package` field inside of Cargo.toml #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "kebab-case")] pub struct Package { #[serde(skip_serializing_if = "Option::is_none")] pub metadata: Option<Metadata>, } /// The `package.metadata` section inside of Cargo.toml #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "kebab-case")] pub struct Metadata { #[serde(skip_serializing_if = "Option::is_none")] pub tasks: Option<BTreeMap<String, TaskDetail>>, /// Task-specific dependencies, similar to `dev-deps`. #[serde(skip_serializing_if = "Option::is_none")] pub task_dependencies: Option<BTreeMap<String, VersionNumber>>, } /// A quick alias for a semver number type VersionNumber = String; /// When definition of a task is more than just a version string. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "kebab-case")] #[serde(deny_unknown_fields)] pub struct TaskDetail { /// This path is usually relative to the crate's manifest, but when using workspace inheritance, it may be relative to the workspace! /// /// When calling [`Manifest::complete_from_path_and_workspace`] use absolute path for the workspace manifest, and then this will be corrected to be an absolute /// path when inherited from the workspace. #[serde(skip_serializing_if = "Option::is_none")] pub path: Option<String>, /// Decide whether to inherit all, none, or a white list of the environment /// variables. #[serde(skip_serializing_if = "Option::is_none")] pub inherit_env: Option<InheritEnv>, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "kebab-case")] #[serde(untagged)] pub enum InheritEnv { Bool(bool), AllowList(Vec<String>), }
yoshuawuyts/cargo-task-wasm
21
A sandboxed local task runner for Rust
Rust
yoshuawuyts
Yosh
src/main.rs
Rust
//! A task runner for Cargo #![forbid(unsafe_code)] use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use std::{fs, io}; use clap::Parser; use fs_extra::dir::CopyOptions; use wasmtime::{component::Component, Result, *}; use wasmtime_wasi::bindings::Command; use wasmtime_wasi::{DirPerms, FilePerms, ResourceTable, WasiView}; mod cargo; use cargo::{CargoToml, InheritEnv, TaskDetail}; /// A sandboxed task runner for cargo #[derive(clap::Parser, Debug)] #[command(version, about)] struct Args { /// The `task` subcommand #[arg(hide = true)] argv0: String, /// The name of the task to run task_name: String, /// Optional arguments to pass to the task args: Vec<String>, } type Error = Box<dyn std::error::Error + Send + Sync + 'static>; /// The shared context for our component instantiation. /// /// Each store owns one of these structs. In the linker this maps: names in the /// component -> functions on the host side. struct Ctx { // Anything that WASI can access is mediated though this. This contains // capabilities, preopens, etc. wasi: wasmtime_wasi::WasiCtx, // NOTE: this might go away eventually // We need something which owns the host representation of the resources; we // store them in here. Think of it as a `HashMap<i32, Box<dyn Any>>` table: wasmtime::component::ResourceTable, } impl WasiView for Ctx { fn table(&mut self) -> &mut ResourceTable { &mut self.table } fn ctx(&mut self) -> &mut wasmtime_wasi::WasiCtx { &mut self.wasi } } /// A representation of a task on-disk. /// /// Tasks are assumed to either exist in the `tasks/` subdirectory, /// or can be defined in `Cargo.toml` as part of the `[tasks]` section. #[derive(Debug, PartialEq, Clone)] struct TaskDefinition { name: String, path: PathBuf, env: EnvVars, } #[tokio::main] async fn main() -> Result<(), Error> { // Parse command line arguments let args = Args::parse(); assert_eq!( args.argv0, "task", "cargo-task-wasm should be invoked as a `cargo` subcommand" ); // Find task in tasks directory let workspace_root_dir = findup_workspace(&std::env::current_dir()?)?; let cargo_toml_path = workspace_root_dir.join("Cargo.toml"); let cargo_toml: CargoToml = toml::from_str(&fs::read_to_string(&cargo_toml_path)?)?; let target_workspace_dir = build_task_workspace( &cargo_toml, &workspace_root_dir.join("target/tasks"), &workspace_root_dir.join("tasks"), )?; // Compile the task let tasks_target_dir = target_workspace_dir.join("../target"); let _cargo_status = std::process::Command::new("cargo") .arg("+beta") .arg("build") .arg("--target") .arg("wasm32-wasip2") .current_dir(&target_workspace_dir) .arg("--target-dir") .arg(&tasks_target_dir) .status()?; let tasks = resolve_tasks(&cargo_toml, &workspace_root_dir.join("tasks"))?; let task_definition = tasks.get(&args.task_name).expect(&format!( "could not find a task with the name {:?}", &args.task_name )); let task_wasm_path = tasks_target_dir.join(format!("wasm32-wasip2/debug/{}.wasm", task_definition.name)); // Ok, it's time to setup Wasmtime and load our component. This goes through two phases: // 1. Load the program and link it - this is done once and can be reused multiple times // between various instances. In our program here though we'll just create a single instance. // 2. Create an instance of the program and give it its own memory, etc. This is a working copy // of the program and we need to give it some of its own state to work with. // Setup the engine. // These pieces can be reused for multiple component instantiations. let mut config = Config::default(); config.wasm_component_model(true); config.async_support(true); let engine = Engine::new(&config)?; let component = Component::from_file(&engine, task_wasm_path)?; // Setup the linker and add the `wasi:cli/command` world's imports to this // linker. let mut linker: component::Linker<Ctx> = component::Linker::new(&engine); wasmtime_wasi::add_to_linker_async(&mut linker)?; // Instantiate the component! let mut wasi = wasmtime_wasi::WasiCtxBuilder::new(); wasi.inherit_stderr(); wasi.inherit_stdout(); match &task_definition.env { EnvVars::None => {} EnvVars::All => { wasi.inherit_env(); } EnvVars::AllowList(vars) => { for (key, value) in vars { eprintln!("setting environment variable: {key} = {value}"); wasi.env(key, value); } } } wasi.args(&args.args); wasi.preopened_dir( &target_workspace_dir, "/", DirPerms::all(), FilePerms::all(), )?; let host = Ctx { wasi: wasi.build(), table: wasmtime::component::ResourceTable::new(), }; let mut store: Store<Ctx> = Store::new(&engine, host); // Instantiate the component and we're off to the races. let command = Command::instantiate_async(&mut store, &component, &linker).await?; let program_result = command.wasi_cli_run().call_run(&mut store).await?; match program_result { Ok(()) => Ok(()), Err(()) => std::process::exit(1), } } /// Recurse upwards in the directory structure until we find a /// directory containing a `Cargo.toml` file. /// /// This does not yet find the root of the workspace, but instead will /// abort on the first `Cargo.toml` it finds. fn findup_workspace(entry: &Path) -> io::Result<PathBuf> { if entry.join("Cargo.toml").exists() { return Ok(entry.to_path_buf()); } let parent = entry .parent() .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "No Cargo.toml found"))?; findup_workspace(parent) } /// Which environment variables should we map? #[derive(Debug, PartialEq, Clone)] enum EnvVars { All, None, AllowList(Vec<(String, String)>), } /// Construct the environment variables from the task details. fn build_sandbox_env(task_details: &TaskDetail) -> EnvVars { let Some(inherit_env) = &task_details.inherit_env else { return EnvVars::None; }; match inherit_env { InheritEnv::Bool(true) => EnvVars::All, InheritEnv::Bool(false) => EnvVars::None, InheritEnv::AllowList(vars) => { let mut map = Vec::new(); for var in vars { if let Ok(value) = std::env::var(&var) { map.push((var.clone(), value)); } } EnvVars::AllowList(map) } } } fn build_task_workspace( cargo_toml: &CargoToml, root_dir: &Path, input_tasks_dir: &Path, ) -> Result<PathBuf, Error> { use std::fmt::Write; let workspace_dir = root_dir.join("ws"); if workspace_dir.exists() { fs::remove_dir_all(&workspace_dir)?; } fs::create_dir_all(&workspace_dir)?; let mut virtual_cargo_toml_contents = String::new(); writeln!( virtual_cargo_toml_contents, r#" [package] name = "_tasks" version = "0.1.0" edition = "2021" "# )?; // Copy the tasks' rs files into the workspace let src_dir = workspace_dir.join("src"); fs::create_dir_all(&src_dir)?; fs_extra::dir::copy( input_tasks_dir, src_dir, &CopyOptions::new().content_only(true), )?; let tasks = resolve_tasks(cargo_toml, input_tasks_dir)?; for task_definition in tasks.values() { let task_name = &task_definition.name; writeln!( virtual_cargo_toml_contents, r#" [[bin]] name = "{task_name}" path = "src/{task_name}.rs" "# )?; } if let Some(metadata) = &cargo_toml.package.metadata { if let Some(task_deps) = &metadata.task_dependencies { // Add task dependencies as normal dependencies for this workspace writeln!(virtual_cargo_toml_contents, "[dependencies]")?; for (dep_name, dep_version) in task_deps.iter() { writeln!( virtual_cargo_toml_contents, r#"{dep_name} = "{dep_version}""# )?; } } } std::fs::write( workspace_dir.join("Cargo.toml"), virtual_cargo_toml_contents, )?; Ok(workspace_dir) } /// Try and find a task by name on disk. This can either originate from the /// `tasks/` subdirectory, or a custom path defined in `Cargo.toml` as part of /// `[tasks]`. fn resolve_tasks( cargo_toml: &CargoToml, tasks_dir: &Path, ) -> io::Result<BTreeMap<String, TaskDefinition>> { let mut tasks = BTreeMap::new(); let default_path = |task_name: &str| PathBuf::from(format!("tasks/{task_name}.rs")); if let Some(metadata) = &cargo_toml.package.metadata { if let Some(toml_tasks) = &metadata.tasks { for (task_name, task_details) in toml_tasks { let task_path = default_path(&task_name[..]); let task_env = build_sandbox_env(task_details); tasks.insert( task_name.to_string(), TaskDefinition { name: task_name.to_string(), path: task_path, env: task_env, }, ); } } } for entry in fs::read_dir(tasks_dir)? { if let Ok(entry) = entry { let filename = entry.file_name(); let filename = filename.to_string_lossy(); if let Some(task_name) = filename.strip_suffix(".rs") { if tasks.contains_key(task_name) { continue; } tasks.insert( task_name.to_string(), TaskDefinition { name: task_name.to_string(), path: default_path(&task_name[..]), env: EnvVars::None, }, ); } } } Ok(tasks) }
yoshuawuyts/cargo-task-wasm
21
A sandboxed local task runner for Rust
Rust
yoshuawuyts
Yosh
src/dhat.rs
Rust
use serde::Deserialize; /// A Rust representation of DHAT's JSON file format, which is described in /// comments in dhat/dh_main.c in Valgrind's source code. /// /// Building this structure in order to serialize does take up some memory. We /// could instead stream the JSON output directly to file ourselves. This would /// be more efficient but make the code uglier. // Copied from https://github.com/nnethercote/dhat-rs/blob/b536631fd9d9103d7191b63181f67755b5958ab5/src/lib.rs#L1826 #[derive(Deserialize, Debug)] #[allow(non_snake_case, dead_code)] pub(crate) struct Dhat { /// Version number of the format. Incremented on each /// backwards-incompatible change. A mandatory integer. pub(crate) dhatFileVersion: u32, /// The invocation mode. A mandatory, free-form string. pub(crate) mode: String, /// The verb used before above stack frames, i.e. "<verb> at {". A /// mandatory string. pub(crate) verb: String, /// Are block lifetimes recorded? Affects whether some other fields are /// present. A mandatory boolean. pub(crate) bklt: bool, /// Are block accesses recorded? Affects whether some other fields are /// present. A mandatory boolean. pub(crate) bkacc: bool, /// Byte/bytes/blocks-position units. Optional strings. "byte", "bytes", /// and "blocks" are the values used if these fields are omitted. #[serde(skip_serializing_if = "Option::is_none")] pub(crate) bu: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub(crate) bsu: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub(crate) bksu: Option<String>, // Time units (individual and 1,000,000x). Mandatory strings. pub(crate) tu: String, pub(crate) Mtu: String, /// The "short-lived" time threshold, measures in "tu"s. /// - bklt=true: a mandatory integer. /// - bklt=false: omitted. #[serde(skip_serializing_if = "Option::is_none")] pub(crate) tuth: Option<usize>, /// The executed command. A mandatory string. pub(crate) cmd: String, // The process ID. A mandatory integer. pub(crate) pid: u32, /// The time of the global max (t-gmax). /// - bklt=true: a mandatory integer. /// - bklt=false: omitted. #[serde(skip_serializing_if = "Option::is_none")] pub(crate) tg: Option<u128>, /// The time at the end of execution (t-end). A mandatory integer. pub(crate) te: u128, /// The program points. A mandatory array. #[serde(rename = "pps")] pub(crate) program_points: Vec<ProgramPoint>, /// Frame table. A mandatory array of strings. #[serde(rename = "ftbl")] pub(crate) frame_table: Vec<String>, } // A Rust representation of a PpInfo within DHAT's JSON file format. #[derive(Deserialize, Debug)] #[allow(non_snake_case, dead_code)] pub(crate) struct ProgramPoint { /// Total bytes and blocks. Mandatory integers. #[serde(rename = "tb")] pub(crate) total_bytes: u64, #[serde(rename = "tbk")] pub(crate) total_blocks: u64, /// Total lifetimes of all blocks allocated at this PP. /// - bklt=true: a mandatory integer. /// - bklt=false: omitted. // Derived from `PpInfo::total_lifetimes_duration`. #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "tl")] pub(crate) total_lifetimes: Option<u128>, /// The maximum bytes and blocks for this PP. /// - bklt=true: mandatory integers. /// - bklt=false: omitted. // `PpInfo::max_bytes` and `PpInfo::max_blocks`. #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "mb")] pub(crate) max_bytes: Option<usize>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "mbk")] pub(crate) max_blocks: Option<usize>, /// The bytes and blocks at t-gmax for this PP. /// - bklt=true: mandatory integers. /// - bklt=false: omitted. // `PpInfo::at_tgmax_bytes` and `PpInfo::at_tgmax_blocks`. #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "gb")] pub(crate) heap_max_bytes: Option<usize>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "gbk")] pub(crate) heap_max_blocks: Option<usize>, /// The bytes and blocks at t-end for this PP. /// - bklt=true: mandatory integers. /// - bklt=false: omitted. // `PpInfo::curr_bytes` and `PpInfo::curr_blocks` (at termination, i.e. // "end"). #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "eb")] pub(crate) end_bytes: Option<usize>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "ebk")] pub(crate) end_blocks: Option<usize>, // Frames. Each element is an index into `ftbl`. #[serde(rename = "fs")] pub(crate) frames: Vec<usize>, }
yoshuawuyts/dhat-to-flamegraph
12
convert dhat JSON output to a collapsed flamegraph format
Rust
yoshuawuyts
Yosh
src/folded.rs
Rust
use iter_tools::prelude::*; use std::fmt::Display; use crate::{dhat::Dhat, metric::Metric, unit::Unit}; /// A folded stacktrace #[derive(Debug)] pub(crate) struct Folded { pub(crate) lines: Vec<Trace>, } impl Folded { pub(crate) fn from_dhat(dhat: Dhat, metric: Metric, unit: Unit) -> Self { let lines: Vec<Trace> = dhat .program_points .iter() .map(|program_point| { let trace = program_point .frames .iter() .map(|frame_idx| dhat.frame_table[*frame_idx].clone()) .collect::<Vec<_>>(); if let Unit::Lifetimes = unit { assert!(dhat.bklt, "lifetimes were not recorded in the dhat profile, cannot use lifetime units"); } match metric { Metric::Max => { assert!(dhat.bklt, "lifetimes were not recorded in the dhat profile, cannot compute `max` metric") } Metric::Total => {} Metric::End => assert!(dhat.bklt, "lifetimes were not recorded in the dhat profile, cannot compute `end` metric"), Metric::HeapMax => assert!(dhat.bklt, "lifetimes were not recorded in the dhat profile, cannot compute `heap max` metric"), } let frequency = match (metric, unit) { (Metric::Total, Unit::Bytes) => program_point.total_bytes as u128, (Metric::Total, Unit::Blocks) => program_point.total_blocks as u128, (Metric::Total, Unit::Lifetimes) => program_point.total_lifetimes.unwrap(), (Metric::Max, Unit::Bytes) => program_point.max_bytes.unwrap() as u128, (Metric::Max, Unit::Blocks) => program_point.max_blocks.unwrap() as u128, (Metric::Max, Unit::Lifetimes) => panic!("Only total lifetimes are supported"), (Metric::End, Unit::Bytes) => program_point.end_bytes.unwrap() as u128, (Metric::End, Unit::Blocks) => program_point.end_blocks.unwrap() as u128, (Metric::End, Unit::Lifetimes) => panic!("Only total lifetimes are supported"), (Metric::HeapMax, Unit::Bytes) => program_point.heap_max_bytes.unwrap() as u128, (Metric::HeapMax, Unit::Blocks) => program_point.heap_max_blocks.unwrap() as u128, (Metric::HeapMax, Unit::Lifetimes) => { panic!("Only total lifetimes are supported") } }; Trace { trace, frequency } }) .collect(); Self { lines } } } impl Display for Folded { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { for line in &self.lines { writeln!(f, "{line}")?; } Ok(()) } } /// A stack trace and a frequency #[derive(Debug)] pub(crate) struct Trace { pub(crate) trace: Vec<String>, pub(crate) frequency: u128, } impl Display for Trace { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let Self { trace, frequency } = self; let trace = Itertools::intersperse(trace.iter(), &";".to_string()) .cloned() .collect::<String>(); write!(f, "{trace} {frequency}") } }
yoshuawuyts/dhat-to-flamegraph
12
convert dhat JSON output to a collapsed flamegraph format
Rust
yoshuawuyts
Yosh
src/main.rs
Rust
//! Convert dhat JSON output to a collapsed flamegraph format //! //! ## Usage //! //! ```text //! Convert dhat JSON output to a flamegraph //! //! Usage: dhat-to-flamegraph [OPTIONS] <INPUT> //! //! Arguments: //! <INPUT> //! The dhat JSON file to process //! //! Options: //! -o, --output <OUTPUT> //! Where to place the output //! //! If not provided then stdout is used. //! //! -f, --format <FORMAT> //! Which output format to use //! //! Possible values: //! - svg: Format as svg (default) //! - folded: Format as folded stack traces //! //! -m, --metric <METRIC> //! Possible values: //! - total: Measure all traces, output total memory usage per trace (default) //! - max: Measure all traces, output max memory usage per trace //! - end: Measure only the remaining traces at program end, useful to find leaks //! - heap-max: Measure only the traces at max heap usage, useful to find spikes //! //! -u, --unit <UNIT> //! Possible values: //! - bytes: Measure allocations in bytes (default) //! - blocks: Measure allocations in blocks, useful to find allocation counts //! - lifetimes: Measure allocations in lifetimes, useful to find short-lived allocations //! //! -h, --help //! Print help (see a summary with '-h') //! ``` //! //! Usage example: //! //! ```bash //! dhat-to-flamegraph fixtures/dhat-heap.json > out.svg //! open out.svg //! ``` #![forbid(unsafe_code)] #![deny(missing_debug_implementations, nonstandard_style)] #![warn(missing_docs, future_incompatible, unreachable_pub)] use clap::Parser; use folded::Folded; use inferno::flamegraph; use metric::Metric; use std::{ fs::{self, File}, io::Write, path::PathBuf, }; use unit::Unit; mod dhat; mod folded; mod metric; mod unit; /// Convert dhat JSON output to a flamegraph #[derive(Parser)] struct Args { /// The dhat JSON file to process input: PathBuf, /// Where to place the output /// /// If not provided then stdout is used. #[clap(short, long)] output: Option<PathBuf>, /// Which output format to use #[clap(short, long)] format: Option<Format>, #[clap(short, long)] metric: Option<Metric>, #[clap(short, long)] unit: Option<Unit>, } #[derive(clap::ValueEnum, Clone, Copy, Default)] enum Format { /// Format as svg (default) #[default] Svg, /// Format as folded stack traces Folded, } type Error = Box<dyn std::error::Error + Send + Sync + 'static>; fn main() -> Result<(), Error> { let Args { input, output, format, metric, unit, } = Args::parse(); let file = fs::File::open(input)?; // Convert dhat to lines let dhat: dhat::Dhat = serde_json::from_reader(file)?; let metric = metric.unwrap_or_default(); let unit = unit.unwrap_or_default(); let folded = Folded::from_dhat(dhat, metric, unit).to_string(); // Determine where to write the data to let writer = match &output { Some(output) => &mut File::create(&output)? as &mut dyn Write, None => &mut std::io::stdout(), }; // Write the data match format.unwrap_or_default() { Format::Folded => write!(writer, "{folded}")?, Format::Svg => { let mut opts = flamegraph::Options::default(); flamegraph::from_lines(&mut opts, folded.lines(), writer)?; } } if let Some(output) = output { eprintln!("wrote {output:?}"); } Ok(()) }
yoshuawuyts/dhat-to-flamegraph
12
convert dhat JSON output to a collapsed flamegraph format
Rust
yoshuawuyts
Yosh
src/metric.rs
Rust
/// Which dhat metric to use #[derive(clap::ValueEnum, Clone, Copy, Default)] pub(crate) enum Metric { /// Measure all traces, output total memory usage per trace (default) #[default] Total, /// Measure all traces, output max memory usage per trace Max, /// Measure only the remaining traces at program end, useful to find leaks End, /// Measure only the traces at max heap usage, useful to find spikes HeapMax, }
yoshuawuyts/dhat-to-flamegraph
12
convert dhat JSON output to a collapsed flamegraph format
Rust
yoshuawuyts
Yosh
src/unit.rs
Rust
/// Which allocation unit to use #[derive(clap::ValueEnum, Clone, Copy, Default)] pub(crate) enum Unit { /// Measure allocations in bytes (default) #[default] Bytes, /// Measure allocations in blocks, useful to find allocation counts Blocks, /// Measure allocations in lifetimes, useful to find short-lived allocations Lifetimes, }
yoshuawuyts/dhat-to-flamegraph
12
convert dhat JSON output to a collapsed flamegraph format
Rust
yoshuawuyts
Yosh
tests/test.rs
Rust
yoshuawuyts/dhat-to-flamegraph
12
convert dhat JSON output to a collapsed flamegraph format
Rust
yoshuawuyts
Yosh
src/lib.rs
Rust
//! Experiment with methods on IntoIterator //! //! ## Why does this project exist? //! //! This project asks the question: what if we used `IntoIterator` everywhere //! instead of `Iterator`? This becomes relevant for generator blocks, which //! themselves may contain `!Send` items, but that doesn't mean that the type //! returned by `gen {}` needs to be `!Send` too. This crate follows Swift's //! example, making it so all operations happen on a base builder type - which //! has one final operation that converts it into an actual iterable. //! //! The other reason is that in bounds we already always use `IntoIterator`. For //! example the `collect` method takes `A: IntoIterator`, not `A: Iterator`. In //! function bounds there is rarely a reason to use `Iterator` directly; typically the //! only reason we don't is because it's more effort to type. //! //! ## Example of `Iterator`'s limitations //! //! Here's a practical case people are bound to hit when writing generator //! blocks, which can't be fixed unless generator returns `IntoIterator`: //! //! ```rust //! // A gen block that holds some `!Send` type across a yield point //! let iter = gen { //! let items = my_data.lock(); // ← `MutexGuard: !Send` //! for item in items { //! yield item; //! } //! }; //! //! // ## Option 1 //! let iter = gen { ... }; // 1. Desugars to `impl Iterator + !Send` //! thread::spawn(move || { // 2. ❌ Can't move `!Send` type across threads //! for item in iter { ... } //! }).unwrap(); //! //! // ## Option 2 //! let iter = gen { ... }; // 1. Desugars to `impl IntoIterator + Send` //! thread::spawn(move || { // 2. ✅ Move `Send` type across threads //! for item in iter { ... } // 3. Obtain `impl Iterator + !Send` //! }).unwrap(); //! ``` //! //! ## Why did you choose these names? //! //! This crate essentially reframes `IntoIterator` into the main interface for //! iteration. However the name `IntoIterator` suggests it is a mere supplement //! to some other `Iterator` trait. `Iterator` also has another quirk: it's a //! trait that's named after a noun, rather than a verb. Think of `Read`, //! `Write`, `Send` - these are all verbs. //! //! The closest prior art for this in the stdlib I could find was the `Hash` / //! `Hasher` pair. The main trait `Hash` is the subject of the hashing, with //! `Hasher` containing all the hash state. This makes `Hasher` very similar to //! `Iterator`, and hints the better name for `IntoIterator` might in fact be `Iterate`. //! //! This just leaves us with what to do about `FromIterator`, which currently //! exists as a dual to `IntoIterator`. But interestingly it also exists as a //! dual to [`Extend`](https://doc.rust-lang.org/std/iter/trait.Extend.html), //! where rather than creating a new container it can be used to extend an //! existing collection. This is also used in the unstable [`collect_into` //! method](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.collect_into). //! It's for this reason that we've renamed `FromIterator` to `Collect`. All //! together this changes the names to: //! //! - `IntoIterator` → `Iterate` //! - `Iterator` → `Iterator` //! - `FromIterator` → `Collect` #![forbid(unsafe_code, rust_2018_idioms)] #![deny(missing_debug_implementations, nonstandard_style)] #![warn(missing_docs, future_incompatible, unreachable_pub)] pub mod map; /// A stateful iterator returned by [`Iterate::iterate`]. pub trait Iterator { /// The type of the elements being iterated over. type Item; /// Advances the iterator and returns the next value. fn next(&mut self) -> Option<Self::Item>; /// How many items do we expect to yield? fn size_hint(&self) -> (usize, Option<usize>) { (0, None) } } /// Provide sequential, iterated access to items. pub trait Iterate { /// The type of the elements being iterated over. type Item; /// Which kind of iterator are we turning this into? type Iterator: Iterator<Item = Self::Item>; /// Begin iteration and obtain a stateful [`Iterator`]. fn iterate(self) -> Self::Iterator; /// Maps the values of iter with f. fn map<F, B>(self, f: F) -> map::IntoMap<Self, F> where F: FnOnce(Self::Item) -> B, Self: Sized, { map::IntoMap::new(self, f) } /// Transforms this iterator into a collection. fn collect<B: Collect<Self::Item>>(self) -> B where Self: Sized, { Collect::collect(self) } } impl<T> Iterate for T where T: Iterator, { type Item = T::Item; type Iterator = T; fn iterate(self) -> Self::Iterator { self } } /// Iterate over items and collect them into a value. pub trait Collect<A>: Sized { /// Creates a value from an `Iterate`. fn collect<T: Iterate<Item = A>>(iter: T) -> Self; }
yoshuawuyts/iterate-trait
7
experiments with methods on IntoIterator
Rust
yoshuawuyts
Yosh
src/map.rs
Rust
//! Helper types for the `map` operation use super::{Iterate, Iterator}; /// An iterator which maps items from one type to another #[derive(Debug)] pub struct Map<I, F> { pub(crate) iter: I, f: F, } impl<I, F> Map<I, F> { fn new(iter: I, f: F) -> Map<I, F> { Map { iter, f } } } /// A type that can be converted into a map iterator. #[derive(Debug)] pub struct IntoMap<I, F> { iter: I, f: F, } impl<I, F> IntoMap<I, F> { pub(crate) fn new(iter: I, f: F) -> Self { Self { iter, f } } } impl<B, I: Iterator, F> Iterator for Map<I, F> where F: FnMut(I::Item) -> B, { type Item = B; #[inline] fn next(&mut self) -> Option<B> { self.iter.next().map(&mut self.f) } } impl<B, I: Iterate, F> Iterate for IntoMap<I, F> where F: FnMut(I::Item) -> B, { type Item = B; type Iterator = Map<I::Iterator, F>; fn iterate(self) -> Self::Iterator { Map::new(self.iter.iterate(), self.f) } }
yoshuawuyts/iterate-trait
7
experiments with methods on IntoIterator
Rust
yoshuawuyts
Yosh
src/lib.rs
Rust
//! A minimal scopeguard implementation //! //! # Examples //! //! ```rust //! # #![allow(unused)] //! # use mini_scopeguard::Guard; //! { //! // Create a new guard around a string that will //! // print its value when dropped. //! let s = String::from("Chashu likes tuna"); //! let mut s = Guard::new(s, |s| println!("{s}")); //! //! // Modify the string contained in the guard. //! s.push_str("!!!"); //! //! // The guard will be dropped here. //! } //! ``` //! //! # Comparison to `scopeguard` //! //! The scopeguard crate provides several settings to configure when exactly the //! closure should run. This seems like a fairly niche capability, and so this //! crate removes those. The implementation of this crate borrows key parts from //! `scopeguard`, and credit goes out to its authors for figuring out the hard parts. #![deny(missing_debug_implementations, nonstandard_style)] #![warn(missing_docs, future_incompatible, unreachable_pub)] use core::mem::ManuallyDrop; use core::ops::{Deref, DerefMut}; use core::ptr; /// Wrap a value and run a closure when dropped. /// /// This is useful for quickly creating desructors inline. /// /// # Examples /// /// ```rust /// # #![allow(unused)] /// # use mini_scopeguard::Guard; /// { /// // Create a new guard around a string that will /// // print its value when dropped. /// let s = String::from("Chashu likes tuna"); /// let mut s = Guard::new(s, |s| println!("{s}")); /// /// // Modify the string contained in the guard. /// s.push_str("!!!"); /// /// // The guard will be dropped here. /// } /// ``` #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Guard<T, F> where F: FnOnce(T), { inner: ManuallyDrop<T>, f: ManuallyDrop<F>, } impl<T, F> Guard<T, F> where F: FnOnce(T), { /// Create a new instance of `Guard`. /// /// # Example /// /// ```rust /// # #![allow(unused)] /// # use mini_scopeguard::Guard; /// let value = String::from("Chashu likes tuna"); /// let guard = Guard::new(value, |s| println!("{s}")); /// ``` pub fn new(inner: T, f: F) -> Self { Self { inner: ManuallyDrop::new(inner), f: ManuallyDrop::new(f), } } /// Consumes the `Guard`, returning the wrapped value. /// /// This will not execute the closure. This is implemented as a static /// method to prevent any potential conflicts with any other methods called /// `into_inner` inherited via the `Deref` and `DerefMut` impls. /// /// # Example /// /// ```rust /// # #![allow(unused)] /// # use mini_scopeguard::Guard; /// let value = String::from("Nori likes chicken"); /// let guard = Guard::new(value, |s| println!("{s}")); /// assert_eq!(Guard::into_inner(guard), "Nori likes chicken"); /// ``` // Copied the impl from: https://docs.rs/scopeguard/latest/src/scopeguard/lib.rs.html#304-313 #[inline] pub fn into_inner(guard: Self) -> T { // Cannot move out of `Drop`-implementing types, // so `ptr::read` the value and forget the guard. let mut guard = ManuallyDrop::new(guard); unsafe { let value = ptr::read(&*guard.inner); // Drop the closure after `value` has been read, so that if the // closure's `drop` function panics, unwinding still tries to drop // `value`. ManuallyDrop::drop(&mut guard.f); value } } } impl<T, F> Deref for Guard<T, F> where F: FnOnce(T), { type Target = T; fn deref(&self) -> &T { &*self.inner } } impl<T, F> DerefMut for Guard<T, F> where F: FnOnce(T), { fn deref_mut(&mut self) -> &mut T { &mut *self.inner } } impl<T, F> Drop for Guard<T, F> where F: FnOnce(T), { fn drop(&mut self) { // SAFETY: we're taking the values out of the `ManuallyDrop` with // the express intent to drop them. let inner = unsafe { ManuallyDrop::take(&mut self.inner) }; let f = unsafe { ManuallyDrop::take(&mut self.f) }; f(inner); } } // tests copied from https://docs.rs/scopeguard/latest/src/scopeguard/lib.rs.html#1-595 #[cfg(test)] mod tests { use super::*; use std::cell::Cell; #[test] fn test_only_dropped_by_closure_when_run() { let value_drops = Cell::new(0); let value = Guard::new((), |()| value_drops.set(1 + value_drops.get())); let closure_drops = Cell::new(0); let guard = Guard::new(value, |_| closure_drops.set(1 + closure_drops.get())); assert_eq!(value_drops.get(), 0); assert_eq!(closure_drops.get(), 0); drop(guard); assert_eq!(value_drops.get(), 1); assert_eq!(closure_drops.get(), 1); } #[test] fn test_into_inner() { let dropped = Cell::new(false); let value = Guard::new(42, |_| dropped.set(true)); let guard = Guard::new(value, |_| dropped.set(true)); let inner = Guard::into_inner(guard); assert_eq!(dropped.get(), false); assert_eq!(*inner, 42); } }
yoshuawuyts/mini-scopeguard
1
A minimal scopeguard implementation
Rust
yoshuawuyts
Yosh
examples/basic.rs
Rust
#[placing::placing] struct Cat { age: u8, } #[placing::placing] impl Cat { #[placing] fn new(age: u8) -> Box<Self> { Box::new(Self { age }) } fn age(&self) -> &u8 { &self.age } } fn main() { let mut cat = unsafe { Cat::placing_uninit_new() }; unsafe { Cat::placing_init_new(&mut cat, 12) }; assert_eq!(cat.age(), &12); }
yoshuawuyts/placing
17
A prototype notation for referentially stable constructors
Rust
yoshuawuyts
Yosh
src/inherent/fn_kind.rs
Rust
use crate::utils::path_ident; use syn::{FnArg, Receiver, ReturnType, Signature}; /// What kind of function are we operating on? #[derive(Debug)] pub(crate) enum FunctionKind { /// A static method with no self-ty Static, /// A static constructor with a return type of `Self` Constructor(HeapTy), /// A method with a self-ty Method, /// A method with a self-ty that returns type `Self` Builder(HeapTy), } /// Is our `Self`-ty on the heap? #[derive(Debug)] pub(crate) enum HeapTy { /// `-> Self` None, /// `-> Box<Self>` Box, } impl FunctionKind { pub(crate) fn from_fn(sig: &Signature, self_ident: &syn::Ident) -> Self { // If the function contains `-> Self` or equivalent we're working with a // constructor if let ReturnType::Type(_, ty) = &sig.output { if let syn::Type::Path(type_path) = &**ty { let ty_path = path_ident(&type_path.path); if ty_path == "Self" || ty_path == self_ident.to_string() { match sig.inputs.first() { Some(FnArg::Receiver(Receiver { .. })) => { return Self::Builder(HeapTy::None) } _ => return Self::Constructor(HeapTy::None), }; } if ty_path == "Box < Self >" { match sig.inputs.first() { Some(FnArg::Receiver(Receiver { .. })) => { return Self::Builder(HeapTy::Box) } _ => return Self::Constructor(HeapTy::Box), }; } } } // If our function takes `self` or `self: Pattern {}`, we're working with a // method. Otherwise it's a static function. match sig.inputs.first() { Some(FnArg::Receiver(Receiver { .. })) => Self::Method, _ => Self::Static, } } }
yoshuawuyts/placing
17
A prototype notation for referentially stable constructors
Rust
yoshuawuyts
Yosh
src/inherent/mod.rs
Rust
use proc_macro::TokenStream; use quote::quote; use syn::{spanned::Spanned, ImplItem, ImplItemFn, ItemImpl}; use crate::utils::{ create_maybe_generics, has_placing_attr, set_path_generics, strip_placing_attr, }; mod fn_kind; mod moving; mod placing; /// Process an impl block that carries the `#[placing]` notation pub(crate) fn process_impl(item: ItemImpl) -> TokenStream { if item.trait_.is_some() { return quote::quote! { compile_error!("`[placing, E0002] trait impls unsupported: macro `placing` can only be used on bare `impl {}` blocks"); }.into(); } // We need all the impl components to later recreate it // and fill it with our own methods let ItemImpl { attrs: _, defaultness, unsafety, impl_token, generics, trait_: _, self_ty, brace_token: _, items, } = item; // Validate we're processing an impl we know how to handle let self_ty = match *self_ty { syn::Type::Path(type_path) => type_path, _ => return quote::quote_spanned! { impl_token.span() => compile_error!("[E0003, placing] invalid impl target: `placing` doesn't work for impls on tuples, slices, or other non-path types"), }.into(), }; let self_ident = &self_ty.path.segments.last().unwrap().ident.clone(); // We need to generate three different impl blocks: // - one where EMPLACE is true // - one where EMPLACE is false // - one where EMPLACE is generic let self_ty_true = set_path_generics(&self_ty, &generics, syn::parse2(quote! {true}).unwrap()); let self_ty_false = set_path_generics(&self_ty, &generics, syn::parse2(quote! {false}).unwrap()); let self_ty_maybe = set_path_generics(&self_ty, &generics, syn::parse2(quote! {EMPLACE}).unwrap()); // Create our final sets of generic params let (impl_generics, _, where_clause) = generics.split_for_impl(); let maybe_generics = create_maybe_generics(&generics); let (impl_generics_maybe, _, where_clause_maybe) = maybe_generics.split_for_impl(); // We only want to modify the methods, the rest of the items we're happy to // pass along as-is. let mut fn_items = vec![]; let mut non_fn_items = vec![]; for item in items { match item { ImplItem::Fn(f) => fn_items.push(f), item => non_fn_items.push(item), } } let fns = match rewrite_fns(fn_items, &self_ident) { Ok(fn_items) => fn_items, Err(token_stream) => return token_stream, }; let ImplFns { statics, methods, emplacing_constructors, non_emplacing_constructors, } = fns; // All done now, send back our updated `impl` block quote! { #defaultness #unsafety #impl_token #impl_generics #self_ty_false #where_clause { #(#non_emplacing_constructors)* #(#non_fn_items)* #(#statics)* } #defaultness #unsafety #impl_token #impl_generics #self_ty_true #where_clause { #(#emplacing_constructors)* } #defaultness #unsafety #impl_token #impl_generics_maybe #self_ty_maybe #where_clause_maybe { #(#methods)* } } .into() } /// The output of `rewrite_fns` #[derive(Default)] struct ImplFns { statics: Vec<ImplItem>, methods: Vec<ImplItem>, emplacing_constructors: Vec<ImplItem>, non_emplacing_constructors: Vec<ImplItem>, } /// Process thef functions one by one fn rewrite_fns(fn_items: Vec<ImplItemFn>, self_ident: &syn::Ident) -> Result<ImplFns, TokenStream> { let mut output = ImplFns::default(); for mut f in fn_items { // Process and identify the function let fn_kind = fn_kind::FunctionKind::from_fn(&f.sig, self_ident); let has_placing = has_placing_attr(&f.attrs)?; strip_placing_attr(&mut f.attrs); // Validate the function bodies and rewrite them where needed. match (&fn_kind, has_placing) { (fn_kind::FunctionKind::Static, false) => { output.statics.push(f.into()); } (fn_kind::FunctionKind::Method, false) => { output.methods.push(f.into()); } (fn_kind::FunctionKind::Static, true) => { return Err(quote::quote_spanned! { f.sig.span() => compile_error!("[E0007, placing] invalid placing target: the #[placing] attribute cannot be applied to static functions"), }.into()); } (fn_kind::FunctionKind::Method, true) => { return Err(quote::quote_spanned! { f.sig.span() => compile_error!("[E0007, placing] invalid placing target: the #[placing] attribute cannot be applied to static functions"), }.into()); } (fn_kind::FunctionKind::Constructor(_heap_ty), false) => { moving::rewrite_moving_constructor(&mut output, f, self_ident)?; } (fn_kind::FunctionKind::Constructor(_heap_ty), true) => { placing::rewrite_placing_constructor(&mut output, f.clone(), self_ident)?; // TODO: re-enable me // moving_constructor::rewrite_moving_constructor(&mut output, f, self_ident)?; } (fn_kind::FunctionKind::Builder(_heap_ty), true) => { todo!("builders and transforms not yet supported") } (fn_kind::FunctionKind::Builder(_heap_ty), false) => { todo!("builders and transforms not yet supported") } } } Ok(output) }
yoshuawuyts/placing
17
A prototype notation for referentially stable constructors
Rust
yoshuawuyts
Yosh
src/inherent/moving.rs
Rust
use proc_macro::TokenStream; use quote::{format_ident, quote}; use syn::{spanned::Spanned, ImplItemFn}; use super::ImplFns; /// Rewrite a non-`#[placing]` statement to create the inner type instead pub(crate) fn rewrite_moving_constructor( output: &mut ImplFns, mut f: ImplItemFn, ident: &syn::Ident, ) -> Result<(), TokenStream> { let inner_ident = format_ident!("Inner{}", ident); let expr = match f.block.stmts.last_mut() { Some(syn::Stmt::Expr(expr, _)) => expr, Some(stmt) => return Err(quote::quote_spanned! { stmt.span() => compile_error!("[E0006, placing] invalid constructor body: functions marked `#[placing]` have to end with a struct expression"), }.into()), None => return Err(quote::quote_spanned! { f.block.span() => compile_error!("[E0005, placing] empty constructor body: functions marked `#[placing]` cannot be empty"), }.into()), }; match expr { syn::Expr::Struct(strukt) => { let fields = strukt.fields.clone(); *strukt = syn::parse2(quote! { #ident { inner: ::core::mem::MaybeUninit::new(#inner_ident { #fields }) } }).unwrap(); } expr => return Err(quote::quote_spanned! { expr.span() => compile_error!("[E0006, placing] invalid constructor body: functions marked `#[placing]` have to end with a struct expression"), }.into()), }; output.non_emplacing_constructors.push(f.into()); Ok(()) }
yoshuawuyts/placing
17
A prototype notation for referentially stable constructors
Rust
yoshuawuyts
Yosh
src/inherent/placing/inline.rs
Rust
use proc_macro::TokenStream; use quote::{format_ident, quote}; use syn::{spanned::Spanned, ImplItemFn}; use super::ImplFns; pub(crate) fn inline_constructor(output: &mut ImplFns, f: ImplItemFn) -> Result<(), TokenStream> { let fn_ident = f.sig.ident.clone(); // Create the new uninit constructor let syn::ImplItemFn { attrs, vis, defaultness: _, sig, mut block, } = f; let uninit = uninit_constructor(&fn_ident, &attrs, &vis); output.emplacing_constructors.push(uninit.into()); // Get the last expr in the function body let expr = match block.stmts.last_mut() { Some(syn::Stmt::Expr(expr, _)) => expr, Some(stmt) => return Err(quote::quote_spanned! { stmt.span() => compile_error!("[E0006, placing] invalid constructor body: functions marked `#[placing]` have to end with a constructor"), }.into()), None => return Err(quote::quote_spanned! { block.span() => compile_error!("[E0005, placing] empty constructor body: functions marked `#[placing]` cannot be empty"), }.into()), }; // Rewrite the last expr in the function body let syn::Expr::Struct(strukt) = expr else { return Err(quote::quote_spanned! { expr.span() => compile_error!("[E0006, placing] invalid constructor body: expected a struct expression as the last statement"), }.into()); }; *expr = inline_new_init(strukt); let constructor = init_constructor(fn_ident, sig, attrs, vis, block); output.emplacing_constructors.push(constructor.into()); Ok(()) } fn init_constructor( fn_ident: syn::Ident, sig: syn::Signature, attrs: Vec<syn::Attribute>, vis: syn::Visibility, block: syn::Block, ) -> ImplItemFn { // Rewrite the existing constructors signature to emplace let init_ident = format_ident!("placing_init_{}", fn_ident); let inputs = sig.inputs.iter(); let statements = &block.stmts; let init: syn::ImplItemFn = syn::parse2(quote! { #(#attrs)* /// # Safety /// /// This method has been generated by the `placing` crate. /// It must be called using the `placing` constructor macro. #vis unsafe fn #init_ident(&mut self, #(#inputs,)*) { #(#statements)* } }) .unwrap(); init } fn uninit_constructor( fn_ident: &syn::Ident, attrs: &[syn::Attribute], vis: &syn::Visibility, ) -> ImplItemFn { let uninit_ident = format_ident!("placing_uninit_{}", fn_ident); let uninit: syn::ImplItemFn = syn::parse2(quote! { #(#attrs)* /// # Safety /// /// This method has been generated by the `placing` crate. /// It must be called using the `placing` constructor macro. #vis unsafe fn #uninit_ident() -> Self { Self { inner: ::core::mem::MaybeUninit::uninit() } } }) .unwrap(); uninit } /// Convert `Self { .. }` to writes into a `MaybeUninit<Self>` pub(crate) fn inline_new_init(strukt: &mut syn::ExprStruct) -> syn::Expr { let assignments = strukt .fields .iter() .map(|field| { let key = &field.member; let expr = &field.expr; syn::parse2(quote! {{ unsafe { (&raw mut (*_this).#key).write(#expr) }; }}) .unwrap() }) .collect::<Vec<syn::Block>>(); syn::parse2(quote! {{ let _this = self.inner.as_mut_ptr(); #(#assignments)* }}) .unwrap() }
yoshuawuyts/placing
17
A prototype notation for referentially stable constructors
Rust
yoshuawuyts
Yosh
src/inherent/placing/mod.rs
Rust
use proc_macro::TokenStream; use syn::{spanned::Spanned, ImplItemFn}; use crate::utils; use super::ImplFns; mod inline; mod pointer; /// Rewrite a `#[placing]` statement to create the inner type instead pub(crate) fn rewrite_placing_constructor( output: &mut ImplFns, f: ImplItemFn, ident: &syn::Ident, ) -> Result<(), TokenStream> { match utils::constructor_type(&f.sig, ident) { utils::ConstructorKind::Inline => inline::inline_constructor(output, f), utils::ConstructorKind::Pointer(kind) => pointer::pointer_constructor(output, f, kind), utils::ConstructorKind::Other => { return Err(quote::quote_spanned! { f.sig.output.span() => compile_error!("[E0009, placing] invalid constructor return type"), } .into()) } } }
yoshuawuyts/placing
17
A prototype notation for referentially stable constructors
Rust
yoshuawuyts
Yosh
src/inherent/placing/pointer.rs
Rust
use proc_macro::TokenStream; use quote::{format_ident, quote}; use syn::{spanned::Spanned, ImplItemFn, Signature}; use super::ImplFns; use crate::utils::{expr_path_ident, PointerKind}; pub(crate) fn pointer_constructor( output: &mut ImplFns, f: ImplItemFn, kind: PointerKind, ) -> Result<(), TokenStream> { let fn_ident = f.sig.ident.clone(); // Create the new uninit constructor let syn::ImplItemFn { attrs, vis, defaultness: _, sig, mut block, } = f; // Construct the uninit function let uninit = uninit_constructor(&fn_ident, &attrs, &vis, kind); output.emplacing_constructors.push(uninit.into()); // Get the last expr in the function body let expr = match block.stmts.last_mut() { Some(syn::Stmt::Expr(expr, _)) => expr, Some(stmt) => return Err(quote::quote_spanned! { stmt.span() => compile_error!("[E0006, placing] invalid constructor body: functions marked `#[placing]` have to end with a constructor"), }.into()), None => return Err(quote::quote_spanned! { block.span() => compile_error!("[E0005, placing] empty constructor body: functions marked `#[placing]` cannot be empty"), }.into()), }; // Rewrite the last expr in the function body let syn::Expr::Call(call) = expr else { return Err(quote::quote_spanned! { expr.span() => compile_error!("[E0006, placing] invalid constructor body: expected a call expression as the last statement"), }.into()); }; *expr = pointer_new_init(call)?; let constructor = init_constructor(fn_ident, sig, attrs, vis, block); output.emplacing_constructors.push(constructor.into()); Ok(()) } fn init_constructor( fn_ident: syn::Ident, sig: Signature, attrs: Vec<syn::Attribute>, vis: syn::Visibility, block: syn::Block, ) -> ImplItemFn { // Rewrite the existing constructors signature to emplace let init_ident = format_ident!("placing_init_{}", fn_ident); let inputs = sig.inputs.iter(); let statements = &block.stmts; let init: syn::ImplItemFn = syn::parse2(quote! { #(#attrs)* /// # Safety /// /// This method has been generated by the `placing` crate. /// It must be called using the `placing` constructor macro. #vis unsafe fn #init_ident(self: &mut Box<Self>, #(#inputs,)*) { #(#statements)* } }) .unwrap(); init } fn uninit_constructor( fn_ident: &syn::Ident, attrs: &[syn::Attribute], vis: &syn::Visibility, _kind: PointerKind, ) -> ImplItemFn { let uninit_ident = format_ident!("placing_uninit_{}", fn_ident); let uninit: syn::ImplItemFn = syn::parse2(quote! { #(#attrs)* /// # Safety /// /// This method has been generated by the `placing` crate. /// It must be called using the `placing` constructor macro. #vis unsafe fn #uninit_ident() -> Box<Self> { Box::new(Self { inner: ::core::mem::MaybeUninit::uninit() }) } }) .unwrap(); uninit } /// Convert `Box::new(Self { .. })` to writes into a `Box<MaybeUninit<Self>>` pub(crate) fn pointer_new_init(call: &mut syn::ExprCall) -> Result<syn::Expr, TokenStream> { let syn::Expr::Path(path) = &*call.func else { return Err(quote::quote_spanned! { call.span() => compile_error!("[E0006, placing] invalid constructor body: functions marked `#[placing]` can only end with a fixed set of expressions"), }.into()); }; match expr_path_ident(path).as_str() { "Box :: new" => {} _ => { return Err(quote::quote_spanned! { call.span() => compile_error!("[E0008, placing] invalid pointer constructor"), } .into()) } } let strukt = match call.args.first() { Some(syn::Expr::Struct(expr)) => expr, _ => { return Err(quote::quote_spanned! { call.span() => compile_error!("[E0008, placing] invalid pointer constructor`"), } .into()) } }; let assignments = strukt .fields .iter() .map(|field| { let key = &field.member; let expr = &field.expr; syn::parse2(quote! {{ unsafe { (&raw mut (*_this).#key).write(#expr) }; }}) .unwrap() }) .collect::<Vec<syn::Block>>(); Ok(syn::parse2(quote! {{ let _this = self.inner.as_mut_ptr(); #(#assignments)* }}) .unwrap()) }
yoshuawuyts/placing
17
A prototype notation for referentially stable constructors
Rust
yoshuawuyts
Yosh
src/lib.rs
Rust
//! A prototype notation for referentially stable constructors //! //! ## Tasks //! //! - [ ] support structs //! - [ ] support enums //! - [ ] support traits //! - [ ] support custom drop impls #![forbid(unsafe_code)] #![deny(missing_debug_implementations, nonstandard_style)] #![warn(missing_docs)] use proc_macro::TokenStream; use syn::parse_macro_input; mod inherent; mod strukt; mod utils; /// Enable methods to be constructed and operate in-place #[proc_macro_attribute] pub fn placing(_attr: TokenStream, item: TokenStream) -> TokenStream { let item = parse_macro_input!(item as syn::Item); match item { syn::Item::Impl(item) => inherent::process_impl(item), syn::Item::Struct(item) => strukt::process_struct(item), _ => quote::quote! { compile_error!("`[placing, E0001] invalid item kind: macro `placing` can only be used on inherent impls and structs"); }.into() } }
yoshuawuyts/placing
17
A prototype notation for referentially stable constructors
Rust
yoshuawuyts
Yosh
src/strukt.rs
Rust
use proc_macro::TokenStream; use quote::{format_ident, quote}; use syn::ItemStruct; use crate::utils::create_maybe_generics; /// Process an impl block that carries the `#[placing]` notation pub(crate) fn process_struct(item: ItemStruct) -> TokenStream { // We need all the impl components to later recreate it // and fill it with our own methods let ItemStruct { attrs: _, vis, struct_token, ident, generics, fields, semi_token, } = item; let outer_generics = create_maybe_generics(&generics); let (outer_impl, outer_ty, outer_where) = outer_generics.split_for_impl(); let inner_ident = format_ident!("Inner{}", ident); let (inner_impl, inner_ty, inner_where) = generics.split_for_impl(); quote! { #vis #struct_token #ident #outer_impl #outer_where { inner: ::core::mem::MaybeUninit<#inner_ident #inner_ty> } #struct_token #inner_ident #inner_impl #inner_where #fields #semi_token impl #outer_impl ::core::ops::Deref for #ident #outer_ty #outer_where { type Target = #inner_ident #inner_ty; fn deref(&self) -> &Self::Target { unsafe { self.inner.assume_init_ref() } } } impl #outer_impl ::core::ops::DerefMut for #ident #outer_ty #outer_where { fn deref_mut(&mut self) -> &mut Self::Target { unsafe { self.inner.assume_init_mut() } } } impl #outer_impl Drop for #ident #outer_ty #outer_where { fn drop(&mut self) { unsafe { self.inner.assume_init_drop() } } } } .into() }
yoshuawuyts/placing
17
A prototype notation for referentially stable constructors
Rust
yoshuawuyts
Yosh
src/utils.rs
Rust
use proc_macro::TokenStream; use quote::{quote, ToTokens}; use syn::{spanned::Spanned, Attribute, ExprPath, GenericParam, Path, Token}; /// Add the const param to the trait definition pub(crate) fn create_maybe_generics(generics: &syn::Generics) -> syn::Generics { let mut outer_generics = generics.clone(); let params = &mut outer_generics.params; if !params.empty_or_trailing() { params.push_punct(<Token![,]>::default()); } let param = syn::parse2(quote! { const EMPLACE: bool = false }).unwrap(); params.push(GenericParam::Const(param)); outer_generics } /// Checks whether there is a `#[placing]` attribute in the list. /// /// # Errors /// /// This function will return an error if the attribute is malformed pub(crate) fn has_placing_attr(attrs: &[Attribute]) -> Result<bool, TokenStream> { for attr in attrs.iter() { if path_ident(attr.path()) != "placing" { continue; } return match &attr.meta { syn::Meta::Path(_) => Ok(true), _ => Err(quote::quote_spanned! { attr.span() => compile_error!("[E0004, placing] invalid attr: the #[placing] attribute does not support any additional arguments"), }.into()), }; } Ok(false) } /// Convert a path to its identity pub(crate) fn path_ident(path: &Path) -> String { path.to_token_stream().to_string() } /// Convert a path to its identity pub(crate) fn expr_path_ident(path: &ExprPath) -> String { path.to_token_stream().to_string() } pub(crate) fn strip_placing_attr(attrs: &mut Vec<Attribute>) { attrs.retain(|attr| path_ident(attr.path()) != "placing") } pub(crate) fn set_path_generics( path: &syn::TypePath, base: &syn::Generics, param: syn::GenericArgument, ) -> syn::TypePath { let mut path = path.clone(); let segment = path.path.segments.last_mut().unwrap(); let ident = &segment.ident; let params = base.params.iter().map(|param| -> syn::GenericArgument { match param { syn::GenericParam::Lifetime(lifetime_param) => { let param = &lifetime_param.lifetime; syn::parse2(quote! {#param}).unwrap() } syn::GenericParam::Type(type_param) => { let param = &type_param.ident; syn::parse2(quote! {#param}).unwrap() } syn::GenericParam::Const(const_param) => { let param = &const_param.ident; syn::parse2(quote! {#param}).unwrap() } } }); *segment = syn::parse2(quote! { #ident <#(#params,)* #param> }).unwrap(); path } /// Determine what kind of constructor a function is pub(crate) fn constructor_type(sig: &syn::Signature, ident: &syn::Ident) -> ConstructorKind { match &sig.output { syn::ReturnType::Type(_, ty) => match &**ty { syn::Type::Path(path) => match path_ident(&path.path).as_str() { "Box < Self >" => ConstructorKind::Pointer(PointerKind::Box), "Self" => ConstructorKind::Inline, s if s == ident.to_string() => ConstructorKind::Inline, _ => ConstructorKind::Other, }, _ => ConstructorKind::Other, }, _ => ConstructorKind::Other, } } /// Possible constructor kinds pub(crate) enum ConstructorKind { Inline, Pointer(PointerKind), Other, } pub(crate) enum PointerKind { Box, }
yoshuawuyts/placing
17
A prototype notation for referentially stable constructors
Rust
yoshuawuyts
Yosh
tests/ui-fail/E0001-invalid-item-kind.rs
Rust
#[placing::placing] union Cat { age: u8, } fn main() {}
yoshuawuyts/placing
17
A prototype notation for referentially stable constructors
Rust
yoshuawuyts
Yosh
tests/ui-fail/E0002-trait-impls-unsupported.rs
Rust
struct Cat { age: u8, } trait Meow {} #[placing::placing] impl Meow for Cat {} fn main() {}
yoshuawuyts/placing
17
A prototype notation for referentially stable constructors
Rust
yoshuawuyts
Yosh
tests/ui-fail/E0003-invalid-impl-target.rs
Rust
trait Meow { type Sound; } #[placing::placing] impl [Cat] {} fn main() {}
yoshuawuyts/placing
17
A prototype notation for referentially stable constructors
Rust
yoshuawuyts
Yosh
tests/ui-fail/E0004-invalid-attr.rs
Rust
#[placing::placing] struct Cat; #[placing::placing] impl Cat { #[placing(invalid)] fn list(&self) -> Self { todo!() } #[placing = "invalid"] fn path(&self) -> Self { todo!() } } fn main() {}
yoshuawuyts/placing
17
A prototype notation for referentially stable constructors
Rust
yoshuawuyts
Yosh
tests/ui-fail/E0005-empty-constructor-body.rs
Rust
#[placing::placing] struct Cat; #[placing::placing] impl Cat { #[placing] fn new() -> Self {} } fn main() {}
yoshuawuyts/placing
17
A prototype notation for referentially stable constructors
Rust
yoshuawuyts
Yosh
tests/ui-fail/E0006-invalid-constructor-body-non-expr.rs
Rust
#[placing::placing] struct Cat; #[placing::placing] impl Cat { #[placing] fn new() -> Self { todo!() } } fn main() {}
yoshuawuyts/placing
17
A prototype notation for referentially stable constructors
Rust
yoshuawuyts
Yosh
tests/ui-fail/E0006-invalid-constructor-body-non-struct.rs
Rust
#[placing::placing] struct Cat; #[placing::placing] impl Cat { #[placing] fn new() -> Self { { Self {} } } } fn main() {}
yoshuawuyts/placing
17
A prototype notation for referentially stable constructors
Rust
yoshuawuyts
Yosh
tests/ui-fail/E0007-invalid-placing-target.rs
Rust
#[placing::placing] struct Cat; #[placing::placing] impl Cat { #[placing] fn new(&self) {} } fn main() {}
yoshuawuyts/placing
17
A prototype notation for referentially stable constructors
Rust
yoshuawuyts
Yosh
tests/ui-fail/E0008-invalid-pointer-constructor.rs
Rust
#[placing::placing] struct Cat { age: u8, } #[placing::placing] impl Cat { #[placing] fn new(age: u8) -> Box<Self> { Box::new() } } fn main() {}
yoshuawuyts/placing
17
A prototype notation for referentially stable constructors
Rust
yoshuawuyts
Yosh
tests/ui-pass/allowed-impl-block.rs
Rust
#[placing::placing] struct Cat {} #[placing::placing] impl Cat {} fn main() {}
yoshuawuyts/placing
17
A prototype notation for referentially stable constructors
Rust
yoshuawuyts
Yosh
tests/ui-pass/allowed-struct.rs
Rust
#[placing::placing] struct Cat {} fn main() {}
yoshuawuyts/placing
17
A prototype notation for referentially stable constructors
Rust
yoshuawuyts
Yosh
tests/ui-pass/generics-struct.rs
Rust
#[placing::placing] struct Cat<K, J, const N: usize> where J: Send, { k: K, j: J, foo: [u8; N], } #[placing::placing] impl<K, J, const N: usize> Cat<K, J, N> where J: Send {} fn main() {}
yoshuawuyts/placing
17
A prototype notation for referentially stable constructors
Rust
yoshuawuyts
Yosh
tests/ui-pass/placing-body.rs
Rust
#[placing::placing] struct Cat { age: u8, } #[placing::placing] impl Cat { #[placing] fn new(age: u8) -> Self { let age = age * 2; Self { age } } fn age(&self) -> &u8 { &self.age } } fn main() { let mut cat = unsafe { Cat::placing_uninit_new() }; unsafe { cat.placing_init_new(12) }; assert_eq!(cat.age(), &24); }
yoshuawuyts/placing
17
A prototype notation for referentially stable constructors
Rust
yoshuawuyts
Yosh
tests/ui-pass/placing-box.rs
Rust
#[placing::placing] struct Cat { age: u8, } #[placing::placing] impl Cat { #[placing] fn new(age: u8) -> Box<Self> { Box::new(Self { age }) } fn age(&self) -> &u8 { &self.age } } fn main() { let mut cat = unsafe { Cat::placing_uninit_new() }; unsafe { cat.placing_init_new(12) }; assert_eq!(cat.age(), &12); }
yoshuawuyts/placing
17
A prototype notation for referentially stable constructors
Rust
yoshuawuyts
Yosh
tests/ui-pass/placing-builds.rs
Rust
#[placing::placing] struct Cat { age: u8, } #[placing::placing] impl Cat { #[placing] fn new(age: u8) -> Self { Self { age } } fn age(&self) -> &u8 { &self.age } } fn main() {}
yoshuawuyts/placing
17
A prototype notation for referentially stable constructors
Rust
yoshuawuyts
Yosh
tests/ui-pass/placing-runs.rs
Rust
#[placing::placing] struct Cat { age: u8, } #[placing::placing] impl Cat { #[placing] fn new(age: u8) -> Self { Self { age } } fn age(&self) -> &u8 { &self.age } } fn main() { let mut cat = unsafe { Cat::placing_uninit_new() }; unsafe { cat.placing_init_new(12) }; assert_eq!(cat.age(), &12); }
yoshuawuyts/placing
17
A prototype notation for referentially stable constructors
Rust
yoshuawuyts
Yosh
tests/ui-pass/preserves-associated-items.rs
Rust
#[placing::placing] struct Cat {} #[placing::placing] impl Cat { const NAME: &str = "chashu"; } fn main() { assert_eq!(Cat::NAME, "chashu"); }
yoshuawuyts/placing
17
A prototype notation for referentially stable constructors
Rust
yoshuawuyts
Yosh
tests/ui-pass/regular-constructor.rs
Rust
#[placing::placing] struct Cat { age: u8, } #[placing::placing] impl Cat { fn new(age: u8) -> Self { Self { age } } fn age(&self) -> &u8 { &self.age } } fn main() { let cat = Cat::new(12); assert_eq!(cat.age(), &12); }
yoshuawuyts/placing
17
A prototype notation for referentially stable constructors
Rust
yoshuawuyts
Yosh
tests/ui.rs
Rust
// set `TRYBUILD=overwrite` to update the stdout output #[test] fn ui() { let t = trybuild::TestCases::new(); t.compile_fail("tests/ui-fail/*.rs"); t.pass("tests/ui-pass/*.rs"); }
yoshuawuyts/placing
17
A prototype notation for referentially stable constructors
Rust
yoshuawuyts
Yosh
src/future.rs
Rust
use std::os::fd::RawFd; #[derive(Debug)] pub enum Interest { Read, Close, } #[derive(Debug)] pub enum Waitable { /// Registered file descriptor. Fd(RawFd, Interest), } pub trait Future { type Output; fn poll(&mut self, ready: &[Waitable]) -> impl Iterator<Item = Waitable>; fn take(&mut self) -> Option<Self::Output>; } /// A conversion into an asynchronous computation. pub trait IntoFuture { type Output; type IntoFuture: Future<Output = Self::Output>; fn into_future(self) -> Self::IntoFuture; } impl<T> IntoFuture for T where T: Future, { type Output = T::Output; type IntoFuture = T; fn into_future(self) -> Self::IntoFuture { self } }
yoshuawuyts/playground-future-2.0
2
Playing with a different formulation of Future
Rust
yoshuawuyts
Yosh
src/main.rs
Rust
//! shout out noah kennedy: //! https://gist.github.com/yoshuawuyts/c74b0b344f62133664f36d8192367b97 #![cfg(target_os = "macos")] use std::io::{self, Read, Write}; use std::net::{TcpListener, TcpStream}; use std::thread; use std::time::Duration; mod future; mod runtime; mod tcp; use runtime::Poller; use tcp::AsyncTcpStream; fn main() -> io::Result<()> { // kickoff a simple echo server we can hit for demo purposes thread::spawn(run_echo_server); // start the poller let mut poller = Poller::open()?; // set up the client let mut client = AsyncTcpStream::connect("127.0.0.1:8080")?; // we have not written anything yet, this should get EWOULDBLOCK assert_eq!( std::io::ErrorKind::WouldBlock, client.0.read(&mut [0; 32]).unwrap_err().kind() ); // send some data over the wire, and wait 1 second for the server to hopefully echo it back client.0.write(b"hello, world!").unwrap(); thread::sleep(Duration::from_secs(1)); let mut buffer = [0; 32]; let read_future = client.read(&mut buffer); let n = poller.block_on(read_future)??; assert_eq!(b"hello, world!", &buffer[..n]); println!("data validated!"); // cleanup by removing the event watch let close_future = client.disconnect(); poller.block_on(close_future)?; println!("client disconnected!"); thread::sleep(Duration::from_secs(1)); println!("done"); Ok(()) } fn run_echo_server() { let listener = TcpListener::bind("127.0.0.1:8080").unwrap(); loop { let conn = listener.accept().unwrap(); thread::spawn(move || handle_new_echo_server_connection(conn.0)); } } fn handle_new_echo_server_connection(conn: TcpStream) { println!("connection received, waiting 1 sec"); thread::sleep(Duration::from_secs(1)); println!("wait over"); std::io::copy(&mut &conn, &mut &conn).unwrap(); }
yoshuawuyts/playground-future-2.0
2
Playing with a different formulation of Future
Rust
yoshuawuyts
Yosh
src/runtime.rs
Rust
use rustix::event::kqueue; use std::io; use std::os::fd::{AsFd, OwnedFd, RawFd}; use std::time::Duration; use crate::future::{Future, Interest, IntoFuture, Waitable}; pub struct Poller { queue: OwnedFd, events: Vec<kqueue::Event>, } impl Poller { pub fn open() -> io::Result<Self> { Ok(Self { queue: kqueue::kqueue()?, events: Vec::with_capacity(1), }) } // Register the client for interest in read events, and don't wait for events to come in. // // Safety: we won't polling this after the TcpStream referred to closes, and we delete the // event too. // // Though the rustix docs say that the kqueue must be closed first, this isn't technically true. // You could delete the event as well, and failing to do so isn't actually catastrophic - the // worst case is more spurious wakes. pub fn register_read(&mut self, fd: RawFd) -> io::Result<usize> { let flags = kqueue::EventFlags::ADD; let udata = 7; let event = kqueue::Event::new(kqueue::EventFilter::Read(fd), flags, udata); let timeout = None; Ok(unsafe { kqueue::kevent(&self.queue, &[event], &mut self.events, timeout)? }) } // Wait for some event to complete pub fn wait(&mut self) -> io::Result<usize> { // safety: we are not modifying the list, just polling Ok(unsafe { kqueue::kevent(self.queue.as_fd(), &[], &mut self.events, None)? }) } // Unregister the client for interest in read events. pub fn unregister_read(&mut self, fd: RawFd) -> io::Result<usize> { let flags = kqueue::EventFlags::DELETE; let udata = 7; let event = kqueue::Event::new(kqueue::EventFilter::Read(fd), flags, udata); dbg!(); let mut event_list = vec![]; let timeout = Some(Duration::ZERO); Ok(unsafe { kqueue::kevent(&self.queue, &[event], &mut event_list, timeout)? }) } fn events(&self) -> Vec<Waitable> { self.events .iter() .map(|event| match event.filter() { kqueue::EventFilter::Read(fd) => Waitable::Fd(fd, Interest::Read), _ => panic!("non-read filter found!"), }) .collect() } pub fn block_on<Fut: IntoFuture>(&mut self, future: Fut) -> io::Result<Fut::Output> { let mut fut = future.into_future(); loop { let mut should_wait = false; for waitable in fut.poll(&self.events()) { match waitable { Waitable::Fd(fd, Interest::Read) => { should_wait = true; self.register_read(fd)? } Waitable::Fd(fd, Interest::Close) => self.unregister_read(fd)?, }; } self.events.clear(); match should_wait { true => self.wait()?, false => match fut.take() { Some(output) => return Ok(output), None => panic!("No more events to wait on and no data present"), }, }; } } }
yoshuawuyts/playground-future-2.0
2
Playing with a different formulation of Future
Rust
yoshuawuyts
Yosh
src/tcp.rs
Rust
use std::io::{self, Read}; use std::net::{TcpStream, ToSocketAddrs}; use std::os::fd::{AsRawFd, RawFd}; use crate::future::{Future, Interest, Waitable}; pub struct AsyncTcpStream(pub TcpStream); impl AsRawFd for AsyncTcpStream { fn as_raw_fd(&self) -> RawFd { self.0.as_raw_fd() } } impl AsyncTcpStream { pub fn connect<A: ToSocketAddrs>(addr: A) -> io::Result<Self> { let client = TcpStream::connect(addr)?; client.set_nonblocking(true)?; Ok(Self(client)) } pub fn read<'a>(&mut self, data: &'a mut [u8]) -> ReadFuture<'_, 'a> { ReadFuture { client: self, buffer: data, output: None, } } pub fn disconnect(self) -> CloseFuture { CloseFuture { client: self, state: CloseFutureState::Pending, } } } pub struct ReadFuture<'a, 'b> { client: &'a mut AsyncTcpStream, buffer: &'b mut [u8], output: Option<io::Result<usize>>, } enum Once<T> { Empty, Once(Option<T>), } impl<T> Iterator for Once<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { match self { Once::Empty => None, Once::Once(opt) => opt.take(), } } } impl<'a, 'b> Future for ReadFuture<'a, 'b> { type Output = io::Result<usize>; fn poll(&mut self, _ready: &[Waitable]) -> impl Iterator<Item = Waitable> { // NOTE: this would be significantly nicer to write as `gen fn poll` match self.client.0.read(&mut self.buffer) { Ok(n) => { self.output = Some(Ok(n)); Once::Empty } Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { Once::Once(Some(Waitable::Fd(self.client.as_raw_fd(), Interest::Read))) } Err(e) => { self.output = Some(Err(e)); Once::Empty } } } fn take(&mut self) -> Option<Self::Output> { self.output.take() } } enum CloseFutureState { Pending, Closed, Completed, } pub struct CloseFuture { client: AsyncTcpStream, state: CloseFutureState, } impl Future for CloseFuture { type Output = (); fn poll(&mut self, _ready: &[Waitable]) -> impl Iterator<Item = Waitable> { match self.state { CloseFutureState::Pending => { self.state = CloseFutureState::Closed; Once::Once(Some(Waitable::Fd(self.client.as_raw_fd(), Interest::Close))) } CloseFutureState::Closed | CloseFutureState::Completed => Once::Empty, } } fn take(&mut self) -> Option<Self::Output> { match self.state { CloseFutureState::Closed => { self.state = CloseFutureState::Completed; Some(()) } CloseFutureState::Pending | CloseFutureState::Completed => None, } } }
yoshuawuyts/playground-future-2.0
2
Playing with a different formulation of Future
Rust
yoshuawuyts
Yosh
examples/example.rs
Rust
use read_dir_all::read_dir_all; use std::{env, io}; fn main() -> io::Result<()> { let path = env::current_dir()?; for entry in read_dir_all(path)? { println!("{}", entry?.path().display()); } Ok(()) }
yoshuawuyts/read-dir-all
1
Rust
yoshuawuyts
Yosh
src/lib.rs
Rust
//! simple, recursive readdir #![forbid(unsafe_code, rust_2018_idioms)] #![deny(missing_debug_implementations, nonstandard_style)] #![warn(missing_docs, future_incompatible, unreachable_pub)] use std::fs::{self, DirEntry, ReadDir}; use std::io; use std::path::Path; /// Recursively iterate over all entries in a directory. pub fn read_dir_all<P: AsRef<Path>>(path: P) -> io::Result<ReadDirAll> { let reader = fs::read_dir(path)?; Ok(ReadDirAll { readers: vec![reader], }) } /// Recursively iterates over all entries in a directory. /// /// This operation recurses over all entries in a directory in a depth-first /// way, following symlinks along the way. #[derive(Debug)] pub struct ReadDirAll { readers: Vec<ReadDir>, } impl ReadDirAll { /// Visit a directory, and step into it following symlinks along the way. fn visit_dir(&mut self, entry: DirEntry) -> Result<DirEntry, io::Error> { // Step into the directory on the next iteration. let reader = fs::read_dir(entry.path())?; self.readers.push(reader); // Allows the current directory to be yielded from the iterator. Ok(entry) } } impl Iterator for ReadDirAll { type Item = io::Result<DirEntry>; fn next(&mut self) -> Option<Self::Item> { loop { // Try and get the last reader on the stack. // Once we have no more readers left, we're done. let reader = self.readers.last_mut()?; match reader.next() { // If the current reader is done, continue with the parent. None => self.readers.pop(), // If the entry is a directory, step into it. Some(Ok(entry)) if entry.path().is_dir() => return Some(self.visit_dir(entry)), // Otherwise, yield whatever output the reader provided. result => return result, }; } } }
yoshuawuyts/read-dir-all
1
Rust
yoshuawuyts
Yosh
crates/cli/src/inspect/mod.rs
Rust
use bytesize::ByteSize; use std::fs; use std::io::{Stdout, Write}; use std::path::PathBuf; use anyhow::Result; use comfy_table::modifiers::UTF8_ROUND_CORNERS; use comfy_table::presets::UTF8_FULL; use comfy_table::{CellAlignment, ContentArrangement, Table}; use wasm_metadata::{Metadata, Payload}; /// Read metadata (module name, producers) from a WebAssembly file. #[derive(clap::Parser)] pub(crate) struct Opts { /// Path to a .wasm to inspect input: PathBuf, /// Output in JSON encoding #[clap(long)] json: bool, } impl Opts { pub(crate) fn run(&self) -> Result<()> { let mut output = std::io::stdout(); let file = fs::read(&self.input)?; let payload = wasm_metadata::Payload::from_binary(&file)?; if self.json { write!(output, "{}", serde_json::to_string(&payload)?)?; } else { write_summary_table(&payload, &mut output)?; write_details_table(&payload, &mut output)?; } Ok(()) } } /// Write a table containing a summarized overview of a wasm binary's metadata to /// a writer. fn write_summary_table(payload: &Payload, f: &mut Stdout) -> Result<()> { // Prepare a table and get the individual metadata let mut table = Table::new(); table .load_preset(UTF8_FULL) .apply_modifier(UTF8_ROUND_CORNERS) .set_content_arrangement(ContentArrangement::Dynamic) .set_width(80) .set_header(vec!["KIND", "NAME", "SIZE", "SIZE%", "LANGUAGES", "PARENT"]); table .column_mut(2) .expect("This should be the SIZE column") .set_cell_alignment(CellAlignment::Right); table .column_mut(3) .expect("This should be the SIZE% column") .set_cell_alignment(CellAlignment::Right); // Get the max value of the `range` field. This is the upper memory bound. fn find_range_max(max: &mut usize, payload: &Payload) { let range = &payload.metadata().range; if range.end > *max { *max = range.end; } if let Payload::Component { children, .. } = payload { for child in children { find_range_max(max, child); } } } let mut range_max = 0; find_range_max(&mut range_max, payload); // Recursively add all children to the table write_summary_table_inner(payload, "<root>", &mut 0, range_max, f, &mut table)?; // Write the table to the writer writeln!(f, "{table}")?; Ok(()) } // The recursing inner function of `write_summary_table` fn write_summary_table_inner( payload: &Payload, parent: &str, unknown_id: &mut u16, range_max: usize, _f: &mut Stdout, table: &mut Table, ) -> Result<()> { let Metadata { name, range, producers, .. } = payload.metadata(); let name = match name.as_deref() { Some(name) => name.to_owned(), None => { let name = format!("unknown({unknown_id})"); *unknown_id += 1; name } }; let size = ByteSize::b((range.end - range.start) as u64) .display() .si_short() .to_string(); let usep = match ((range.end - range.start) as f64 / range_max as f64 * 100.0).round() as u8 { // If the item was truly empty, it wouldn't be part of the binary 0..=1 => "<1%".to_string(), // We're hedging against the low-ends, this hedges against the high-ends. // Makes sure we don't see a mix of <1% and 100% in the same table, unless // the item is actually 100% of the binary. 100 if range.end != range_max => ">99%".to_string(), usep => format!("{usep}%"), }; let kind = match payload { Payload::Component { .. } => "component", Payload::Module(_) => "module", }; let languages = match producers { Some(producers) => match producers.iter().find(|(name, _)| *name == "language") { Some((_, pairs)) => pairs .iter() .map(|(lang, _)| lang.to_owned()) .collect::<Vec<_>>() .join(", "), None => "-".to_string(), }, None => "-".to_string(), }; table.add_row(vec![&kind, &*name, &*size, &usep, &languages, &parent]); // Recursively print any children if let Payload::Component { children, .. } = payload { for payload in children { write_summary_table_inner(payload, &name, unknown_id, range_max, _f, table)?; } } Ok(()) } /// Write a table containing a detailed overview of a wasm binary's metadata to /// a writer. fn write_details_table(payload: &Payload, f: &mut Stdout) -> Result<()> { // Prepare a table and get the individual metadata let mut table = Table::new(); table .load_preset(UTF8_FULL) .apply_modifier(UTF8_ROUND_CORNERS) .set_content_arrangement(ContentArrangement::Dynamic) .set_width(80) .set_header(vec!["KIND", "VALUE"]); let Metadata { name, authors, description, producers, licenses, source, homepage, range, revision, version, dependencies, } = payload.metadata(); // Add the basic information to the table first let name = name.as_deref().unwrap_or("<unknown>"); table.add_row(vec!["name", &name]); let kind = match payload { Payload::Component { .. } => "component", Payload::Module(_) => "module", }; table.add_row(vec!["kind", &kind]); table.add_row(vec![ "range", &format!("0x{:x}..0x{:x}", range.start, range.end), ]); // Add the OCI annotations to the table if let Some(description) = description { table.add_row(vec!["description", &description.to_string()]); } if let Some(authors) = authors { table.add_row(vec!["authors", &authors.to_string()]); } if let Some(version) = version { table.add_row(vec!["version", &version.to_string()]); } if let Some(revision) = revision { table.add_row(vec!["revision", &revision.to_string()]); } if let Some(licenses) = licenses { table.add_row(vec!["licenses", &licenses.to_string()]); } if let Some(source) = source { table.add_row(vec!["source", &source.to_string()]); } if let Some(homepage) = homepage { table.add_row(vec!["homepage", &homepage.to_string()]); } // Add the producer section to the table if let Some(producers) = producers { // Ensure the "language" fields are listed first let mut producers = producers .iter() .map(|(n, p)| (n.clone(), p)) .collect::<Vec<_>>(); producers.sort_by(|(a, _), (b, _)| { if a == "language" { std::cmp::Ordering::Less } else if b == "language" { std::cmp::Ordering::Greater } else { a.cmp(b) } }); // Add the producers to the table for (name, pairs) in producers.iter() { for (field, version) in pairs.iter() { match version.len() { 0 => table.add_row(vec![name, &field.to_string()]), _ => table.add_row(vec![name, &format!("{field} [{version}]")]), }; } } } // Add child relationships to the table if let Payload::Component { children, .. } = &payload { for payload in children { let name = payload.metadata().name.as_deref().unwrap_or("<unknown>"); let kind = match payload { Payload::Component { .. } => "component", Payload::Module(_) => "module", }; table.add_row(vec!["child", &format!("{name} [{kind}]")]); } } // Add dependency packages to the table if let Some(dependencies) = dependencies { for package in &dependencies.version_info().packages { table.add_row(vec![ "dependency", &format!("{} [{}]", package.name, package.version), ]); } } // Write the table to the writer writeln!(f, "{table}")?; // Recursively print any children if let Payload::Component { children, .. } = payload { for payload in children { write_details_table(payload, f)?; } } Ok(()) }
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/cli/src/lib.rs
Rust
//! Wasm CLI library //! //! This module exports types for testing purposes. #![allow(unreachable_pub)] /// TUI module for terminal user interface pub mod tui;
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/cli/src/local/mod.rs
Rust
use std::path::PathBuf; use anyhow::Result; use comfy_table::{Table, modifiers::UTF8_ROUND_CORNERS, presets::UTF8_FULL}; use wasm_detector::WasmDetector; /// Detect and manage local WASM files #[derive(clap::Parser)] pub(crate) enum Opts { /// List local WASM files in the current directory List(ListOpts), } #[derive(clap::Args)] pub(crate) struct ListOpts { /// Directory to search for WASM files (defaults to current directory) #[arg(default_value = ".")] path: PathBuf, /// Include hidden files and directories #[arg(long)] hidden: bool, /// Follow symbolic links #[arg(long)] follow_links: bool, } impl Opts { pub(crate) fn run(self) -> Result<()> { match self { Opts::List(opts) => opts.run(), } } } impl ListOpts { fn run(&self) -> Result<()> { let detector = WasmDetector::new(&self.path) .include_hidden(self.hidden) .follow_symlinks(self.follow_links); let mut wasm_files: Vec<_> = detector.into_iter().filter_map(Result::ok).collect(); if wasm_files.is_empty() { println!("No WASM files found in {}", self.path.display()); return Ok(()); } // Sort by path for consistent output wasm_files.sort_by(|a, b| a.path().cmp(b.path())); // Create a table for nice output let mut table = Table::new(); table .load_preset(UTF8_FULL) .apply_modifier(UTF8_ROUND_CORNERS) .set_header(vec!["#", "File Path"]); for (idx, entry) in wasm_files.iter().enumerate() { table.add_row(vec![ format!("{}", idx + 1), entry.path().display().to_string(), ]); } println!("{}", table); println!("\nFound {} WASM file(s)", wasm_files.len()); Ok(()) } }
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/cli/src/main.rs
Rust
//! Wasm CLI command //! mod inspect; mod local; mod package; mod self_; mod tui; use std::io::IsTerminal; use clap::{ColorChoice, CommandFactory, Parser}; #[derive(Parser)] #[command(author, version, about, long_about = None)] #[command(propagate_version = true)] struct Cli { /// When to use colored output. /// /// Can also be controlled via environment variables: /// - NO_COLOR=1 (disables color) /// - CLICOLOR=0 (disables color) /// - CLICOLOR_FORCE=1 (forces color) #[arg( long, value_name = "WHEN", default_value = "auto", global = true, help_heading = "Global Options" )] color: ColorChoice, /// Run in offline mode. /// /// Disables all network operations. Commands that require network access /// will fail with an error. Local-only commands will continue to work. #[arg(long, global = true, help_heading = "Global Options")] offline: bool, #[command(subcommand)] command: Option<Command>, } impl Cli { async fn run(self) -> Result<(), anyhow::Error> { match self.command { Some(Command::Run) => todo!(), Some(Command::Inspect(opts)) => opts.run()?, Some(Command::Convert) => todo!(), Some(Command::Local(opts)) => opts.run()?, Some(Command::Package(opts)) => opts.run(self.offline).await?, Some(Command::Compose) => todo!(), Some(Command::Self_(opts)) => opts.run().await?, None if std::io::stdin().is_terminal() => tui::run(self.offline).await?, None => { // Apply the parsed color choice when printing help Cli::command().color(self.color).print_help()?; } } Ok(()) } } #[derive(clap::Parser)] enum Command { /// Execute a Wasm Component #[command(subcommand)] Run, /// Inspect a Wasm Component Inspect(inspect::Opts), /// Convert a Wasm Component to another format #[command(subcommand)] Convert, /// Detect and manage local WASM files #[command(subcommand)] Local(local::Opts), /// Package, push, and pull Wasm Components #[command(subcommand)] Package(package::Opts), /// Compose Wasm Components with other components #[command(subcommand)] Compose, /// Configure the `wasm(1)` tool, generate completions, & manage state #[clap(name = "self")] #[command(subcommand)] Self_(self_::Opts), } #[tokio::main] async fn main() -> anyhow::Result<()> { Cli::parse().run().await?; Ok(()) }
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/cli/src/package/mod.rs
Rust
use anyhow::Result; use wasm_package_manager::{InsertResult, Manager, Reference}; /// Package, push, and pull Wasm Components #[derive(clap::Parser)] pub(crate) enum Opts { /// Fetch OCI metadata for a component Show, /// Pull a component from the registry Pull(PullOpts), Push, /// List all available tags for a component Tags(TagsOpts), } #[derive(clap::Args)] pub(crate) struct PullOpts { /// The reference to pull reference: Reference, } #[derive(clap::Args)] pub(crate) struct TagsOpts { /// The reference to list tags for (e.g., ghcr.io/example/component) reference: Reference, /// Include signature tags (ending in .sig) #[arg(long)] signatures: bool, /// Include attestation tags (ending in .att) #[arg(long)] attestations: bool, } impl Opts { pub(crate) async fn run(self, offline: bool) -> Result<()> { let store = if offline { Manager::open_offline().await? } else { Manager::open().await? }; match self { Opts::Show => todo!(), Opts::Pull(opts) => { let result = store.pull(opts.reference.clone()).await?; if result == InsertResult::AlreadyExists { eprintln!( "warning: package '{}' already exists in the local store", opts.reference.whole() ); } Ok(()) } Opts::Push => todo!(), Opts::Tags(opts) => { let all_tags = store.list_tags(&opts.reference).await?; // Filter tags based on flags let tags: Vec<_> = all_tags .into_iter() .filter(|tag| { let is_sig = tag.ends_with(".sig"); let is_att = tag.ends_with(".att"); if is_sig { opts.signatures } else if is_att { opts.attestations } else { true // Always include release tags } }) .collect(); if tags.is_empty() { if offline { println!( "No cached tags found for '{}' (offline mode)", opts.reference.whole() ); } else { println!("No tags found for '{}'", opts.reference.whole()); } } else { if offline { println!( "Cached tags for '{}' (offline mode):", opts.reference.whole() ); } else { println!("Tags for '{}':", opts.reference.whole()); } for tag in tags { println!(" {}", tag); } } Ok(()) } } } }
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/cli/src/self_/mod.rs
Rust
use anyhow::Result; use wasm_package_manager::{Manager, format_size}; /// Configure the `wasm(1)` tool, generate completions, & manage state #[derive(clap::Parser)] pub(crate) enum Opts { /// Print diagnostics about the local state State, } impl Opts { pub(crate) async fn run(&self) -> Result<()> { match self { Opts::State => { let store = Manager::open().await?; let state_info = store.state_info(); println!("[Migrations]"); println!( "Current: \t{}/{}", state_info.migration_current(), state_info.migration_total() ); println!(); println!("[Storage]"); println!("Executable: \t{}", state_info.executable().display()); println!("Data storage: \t{}", state_info.data_dir().display()); println!( "Content store: \t{} ({})", state_info.store_dir().display(), format_size(state_info.store_size()) ); println!( "Image metadata: {} ({})", state_info.metadata_file().display(), format_size(state_info.metadata_size()) ); Ok(()) } } } }
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/cli/src/tui/app.rs
Rust
use ratatui::{ crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers}, prelude::*, widgets::{Block, Clear, Paragraph}, }; use std::time::Duration; use tokio::sync::mpsc; use wasm_package_manager::{ImageEntry, InsertResult, KnownPackage, StateInfo, WitInterface}; use super::components::{TabBar, TabItem}; use super::views::packages::PackagesViewState; use super::views::{ InterfacesView, InterfacesViewState, LocalView, PackageDetailView, PackagesView, SearchView, SearchViewState, SettingsView, }; use super::{AppEvent, ManagerEvent}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum Tab { Local, Components, Interfaces, Search, Settings, } impl Tab { const ALL: [Tab; 5] = [ Tab::Local, Tab::Components, Tab::Interfaces, Tab::Search, Tab::Settings, ]; } impl TabItem for Tab { fn all() -> &'static [Self] { &Self::ALL } fn title(&self) -> &'static str { match self { Tab::Local => "Local [1]", Tab::Components => "Components [2]", Tab::Interfaces => "Interfaces [3]", Tab::Search => "Search [4]", Tab::Settings => "Settings [5]", } } } /// The current input mode of the application #[derive(Debug, Clone, PartialEq, Eq, Default)] pub(crate) enum InputMode { /// Normal navigation mode #[default] Normal, /// Viewing a package detail (with the package index) PackageDetail(usize), /// Viewing interface detail InterfaceDetail, /// Pull prompt is active PullPrompt(PullPromptState), /// Search input is active SearchInput, /// Filter input is active (for packages tab) FilterInput, } /// State of the pull prompt #[derive(Debug, Clone, PartialEq, Eq, Default)] pub(crate) struct PullPromptState { pub input: String, pub error: Option<String>, pub in_progress: bool, } /// Manager readiness state #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub(crate) enum ManagerState { #[default] Loading, Ready, } pub(crate) struct App { running: bool, manager_state: ManagerState, current_tab: Tab, input_mode: InputMode, packages: Vec<ImageEntry>, packages_view_state: PackagesViewState, /// State info from the manager state_info: Option<StateInfo>, /// Search view state search_view_state: SearchViewState, /// Known packages for search results known_packages: Vec<KnownPackage>, /// WIT interfaces with their component references wit_interfaces: Vec<(WitInterface, String)>, /// Interfaces view state interfaces_view_state: InterfacesViewState, /// Local WASM files local_wasm_files: Vec<wasm_detector::WasmEntry>, /// Whether offline mode is enabled offline: bool, app_sender: mpsc::Sender<AppEvent>, manager_receiver: mpsc::Receiver<ManagerEvent>, } impl App { pub(crate) fn new( app_sender: mpsc::Sender<AppEvent>, manager_receiver: mpsc::Receiver<ManagerEvent>, offline: bool, ) -> Self { Self { running: true, manager_state: ManagerState::default(), current_tab: Tab::Local, input_mode: InputMode::default(), packages: Vec::new(), packages_view_state: PackagesViewState::new(), state_info: None, search_view_state: SearchViewState::new(), known_packages: Vec::new(), wit_interfaces: Vec::new(), interfaces_view_state: InterfacesViewState::new(), local_wasm_files: Vec::new(), offline, app_sender, manager_receiver, } } pub(crate) fn run(mut self, mut terminal: ratatui::DefaultTerminal) -> std::io::Result<()> { while self.running { terminal.draw(|frame| self.render_frame(frame))?; self.handle_events()?; self.handle_manager_events(); } // Notify manager that we're quitting let _ = self.app_sender.try_send(AppEvent::Quit); Ok(()) } #[allow(clippy::indexing_slicing)] fn render_frame(&mut self, frame: &mut ratatui::Frame) { let area = frame.area(); let status = match (self.manager_state, self.offline) { (_, true) => "offline", (ManagerState::Ready, false) => "ready", (ManagerState::Loading, false) => "loading...", }; // Create main layout with tabs at top let layout = Layout::vertical([Constraint::Length(3), Constraint::Min(0)]).split(area); // Render tab bar let tab_bar = TabBar::new(format!("wasm(1) - {}", status), self.current_tab); frame.render_widget(tab_bar, layout[0]); // Render content based on current tab let content_block = Block::bordered(); let content_area = content_block.inner(layout[1]); frame.render_widget(content_block, layout[1]); match self.current_tab { Tab::Local => frame.render_widget(LocalView::new(&self.local_wasm_files), content_area), Tab::Components => { // Check if we're viewing a package detail if let InputMode::PackageDetail(idx) = self.input_mode { if let Some(package) = self.packages.get(idx) { frame.render_widget(PackageDetailView::new(package), content_area); } } else { // Sync filter_active state for rendering self.packages_view_state.filter_active = self.input_mode == InputMode::FilterInput; let filtered: Vec<_> = self.filtered_packages().into_iter().cloned().collect(); frame.render_stateful_widget( PackagesView::new(&filtered), content_area, &mut self.packages_view_state, ); } } Tab::Interfaces => { frame.render_stateful_widget( InterfacesView::new(&self.wit_interfaces), content_area, &mut self.interfaces_view_state, ); } Tab::Search => { // Sync search_active state for rendering self.search_view_state.search_active = self.input_mode == InputMode::SearchInput; frame.render_stateful_widget( SearchView::new(&self.known_packages), content_area, &mut self.search_view_state, ); } Tab::Settings => { frame.render_widget(SettingsView::new(self.state_info.as_ref()), content_area) } } // Render pull prompt overlay if active if let InputMode::PullPrompt(ref state) = self.input_mode { self.render_pull_prompt(frame, area, state.clone()); } } #[allow(clippy::indexing_slicing)] fn render_pull_prompt(&self, frame: &mut ratatui::Frame, area: Rect, state: PullPromptState) { // Calculate centered popup area let popup_width = 60.min(area.width.saturating_sub(4)); let popup_height = if state.error.is_some() { 7 } else { 5 }; let popup_area = Rect { x: (area.width.saturating_sub(popup_width)) / 2, y: (area.height.saturating_sub(popup_height)) / 2, width: popup_width, height: popup_height, }; // Clear the area behind the popup frame.render_widget(Clear, popup_area); // Build the prompt content let title = if state.in_progress { " Pull Package (pulling...) " } else { " Pull Package " }; let block = Block::bordered() .title(title) .style(Style::default().bg(Color::DarkGray)); let inner = block.inner(popup_area); frame.render_widget(block, popup_area); // Layout for input and optional error let chunks = if state.error.is_some() { Layout::vertical([ Constraint::Length(1), // Label Constraint::Length(1), // Input Constraint::Length(1), // Error ]) .split(inner) } else { Layout::vertical([ Constraint::Length(1), // Label Constraint::Length(1), // Input ]) .split(inner) }; // Label let label = Paragraph::new("Enter package reference (e.g., ghcr.io/user/pkg:tag):"); frame.render_widget(label, chunks[0]); // Input field with cursor let input_text = format!("{}_", state.input); let input = Paragraph::new(input_text).style(Style::default().fg(Color::Yellow)); frame.render_widget(input, chunks[1]); // Error message if present if let Some(ref error) = state.error { let error_msg = Paragraph::new(error.as_str()).style(Style::default().fg(Color::Red)); frame.render_widget(error_msg, chunks[2]); } } fn handle_events(&mut self) -> std::io::Result<()> { // Poll with a timeout so we can also check manager events if event::poll(Duration::from_millis(16))? { match event::read()? { Event::Key(key_event) if key_event.kind == KeyEventKind::Press => { self.handle_key(key_event.code, key_event.modifiers); } _ => {} } } Ok(()) } fn handle_manager_events(&mut self) { while let Ok(event) = self.manager_receiver.try_recv() { match event { ManagerEvent::Ready => { self.manager_state = ManagerState::Ready; // Request packages list and state info when manager is ready let _ = self.app_sender.try_send(AppEvent::RequestPackages); let _ = self.app_sender.try_send(AppEvent::RequestStateInfo); let _ = self.app_sender.try_send(AppEvent::RequestKnownPackages); let _ = self.app_sender.try_send(AppEvent::RequestWitInterfaces); let _ = self.app_sender.try_send(AppEvent::DetectLocalWasm); } ManagerEvent::PackagesList(packages) => { self.packages = packages; } ManagerEvent::StateInfo(state_info) => { self.state_info = Some(state_info); } ManagerEvent::PullResult(result) => { self.handle_pull_result(result); } ManagerEvent::DeleteResult(_result) => { // Delete completed, packages list will be refreshed automatically } ManagerEvent::SearchResults(packages) => { self.known_packages = packages; } ManagerEvent::KnownPackagesList(packages) => { self.known_packages = packages; } ManagerEvent::RefreshTagsResult(_result) => { // Tag refresh completed, packages list will be refreshed automatically } ManagerEvent::WitInterfacesList(interfaces) => { self.wit_interfaces = interfaces; } ManagerEvent::LocalWasmList(files) => { self.local_wasm_files = files; } } } } fn handle_pull_result(&mut self, result: Result<InsertResult, String>) { match result { Ok(insert_result) => { // Close the prompt on success, but show warning if already exists let error = if insert_result == InsertResult::AlreadyExists { Some("Warning: package already exists in local store".to_string()) } else { None }; self.input_mode = if let Some(e) = error { InputMode::PullPrompt(PullPromptState { input: String::new(), error: Some(e), in_progress: false, }) } else { InputMode::Normal }; // Refresh known packages and WIT interfaces let _ = self.app_sender.try_send(AppEvent::RequestKnownPackages); let _ = self.app_sender.try_send(AppEvent::RequestWitInterfaces); } Err(e) => { // Keep the prompt open with the error if let InputMode::PullPrompt(ref mut state) = self.input_mode { state.error = Some(e); state.in_progress = false; } } } } fn handle_key(&mut self, key: KeyCode, modifiers: KeyModifiers) { match &self.input_mode { InputMode::PullPrompt(_) => self.handle_pull_prompt_key(key, modifiers), InputMode::SearchInput => self.handle_search_key(key, modifiers), InputMode::FilterInput => self.handle_filter_key(key, modifiers), InputMode::PackageDetail(_) => self.handle_package_detail_key(key, modifiers), InputMode::InterfaceDetail => self.handle_interface_detail_key(key, modifiers), InputMode::Normal => self.handle_normal_key(key, modifiers), } } fn handle_package_detail_key(&mut self, key: KeyCode, modifiers: KeyModifiers) { match key { KeyCode::Esc | KeyCode::Backspace => { self.input_mode = InputMode::Normal; } KeyCode::Char('q') => self.running = false, KeyCode::Char('c') if modifiers == KeyModifiers::CONTROL => self.running = false, _ => {} } } fn handle_interface_detail_key(&mut self, key: KeyCode, modifiers: KeyModifiers) { match key { KeyCode::Esc | KeyCode::Backspace => { self.interfaces_view_state.viewing_detail = false; self.input_mode = InputMode::Normal; } KeyCode::Up | KeyCode::Char('k') => { self.interfaces_view_state.scroll_up(); } KeyCode::Down | KeyCode::Char('j') => { self.interfaces_view_state.scroll_down(); } KeyCode::Char('q') => self.running = false, KeyCode::Char('c') if modifiers == KeyModifiers::CONTROL => self.running = false, _ => {} } } fn handle_normal_key(&mut self, key: KeyCode, modifiers: KeyModifiers) { match (key, modifiers) { (KeyCode::Char('q'), _) | (KeyCode::Esc, _) => self.running = false, (KeyCode::Char('c'), KeyModifiers::CONTROL) => self.running = false, // Tab navigation (KeyCode::Tab, KeyModifiers::NONE) | (KeyCode::Right, _) => { self.current_tab = self.current_tab.next(); } (KeyCode::BackTab, _) | (KeyCode::Left, _) => { self.current_tab = self.current_tab.prev(); } (KeyCode::Char('1'), _) => self.current_tab = Tab::Local, (KeyCode::Char('2'), _) => self.current_tab = Tab::Components, (KeyCode::Char('3'), _) => self.current_tab = Tab::Interfaces, (KeyCode::Char('4'), _) => self.current_tab = Tab::Search, (KeyCode::Char('5'), _) => self.current_tab = Tab::Settings, // Pull prompt - 'p' to open (only on Components tab, and not in offline mode) (KeyCode::Char('p'), _) if self.current_tab == Tab::Components && self.can_use_network() => { self.input_mode = InputMode::PullPrompt(PullPromptState::default()); } // Activate filter input with '/' on Components tab (KeyCode::Char('/'), _) if self.current_tab == Tab::Components => { self.input_mode = InputMode::FilterInput; self.packages_view_state.filter_active = true; } // Package list navigation (when on Components tab) (KeyCode::Up, _) | (KeyCode::Char('k'), _) if self.current_tab == Tab::Components => { self.packages_view_state .select_prev(self.filtered_packages().len()); } (KeyCode::Down, _) | (KeyCode::Char('j'), _) if self.current_tab == Tab::Components => { self.packages_view_state .select_next(self.filtered_packages().len()); } (KeyCode::Enter, _) if self.current_tab == Tab::Components => { let filtered = self.filtered_packages(); if let Some(selected) = self.packages_view_state.selected() && let Some(package) = filtered.get(selected) { // Find the actual index in the unfiltered list for package detail view if let Some(actual_idx) = self.packages.iter().position(|p| { p.ref_repository == package.ref_repository && p.ref_registry == package.ref_registry && p.ref_tag == package.ref_tag && p.ref_digest == package.ref_digest }) { self.input_mode = InputMode::PackageDetail(actual_idx); } } } // Delete selected package (KeyCode::Char('d'), _) if self.current_tab == Tab::Components && self.is_manager_ready() => { let filtered = self.filtered_packages(); if let Some(selected) = self.packages_view_state.selected() && let Some(package) = filtered.get(selected) { let _ = self .app_sender .try_send(AppEvent::Delete(package.reference())); // Adjust selection if we're deleting the last item if selected > 0 && selected >= filtered.len() - 1 { self.packages_view_state .table_state .select(Some(selected - 1)); } } } // Search tab navigation (KeyCode::Up, _) | (KeyCode::Char('k'), _) if self.current_tab == Tab::Search => { self.search_view_state .select_prev(self.known_packages.len()); } (KeyCode::Down, _) | (KeyCode::Char('j'), _) if self.current_tab == Tab::Search => { self.search_view_state .select_next(self.known_packages.len()); } // Activate search input with '/' (KeyCode::Char('/'), _) if self.current_tab == Tab::Search => { self.input_mode = InputMode::SearchInput; } // Interfaces tab navigation (KeyCode::Up, _) | (KeyCode::Char('k'), _) if self.current_tab == Tab::Interfaces => { self.interfaces_view_state .select_prev(self.wit_interfaces.len()); } (KeyCode::Down, _) | (KeyCode::Char('j'), _) if self.current_tab == Tab::Interfaces => { self.interfaces_view_state .select_next(self.wit_interfaces.len()); } (KeyCode::Enter, _) if self.current_tab == Tab::Interfaces => { if !self.wit_interfaces.is_empty() { self.interfaces_view_state.viewing_detail = true; self.interfaces_view_state.detail_scroll = 0; self.input_mode = InputMode::InterfaceDetail; } } // Pull selected package from search results (not in offline mode) (KeyCode::Char('p'), _) if self.current_tab == Tab::Search && self.can_use_network() => { if let Some(selected) = self.search_view_state.selected() && let Some(package) = self.known_packages.get(selected) { // Pull the package with the most recent tag (or latest if none) let reference = package.reference_with_tag(); let _ = self.app_sender.try_send(AppEvent::Pull(reference)); } } // Refresh tags for selected package from registry (not in offline mode) (KeyCode::Char('r'), _) if self.current_tab == Tab::Search && self.can_use_network() => { if let Some(selected) = self.search_view_state.selected() && let Some(package) = self.known_packages.get(selected) { let _ = self.app_sender.try_send(AppEvent::RefreshTags( package.registry.clone(), package.repository.clone(), )); } } _ => {} } } fn handle_filter_key(&mut self, key: KeyCode, modifiers: KeyModifiers) { match key { KeyCode::Esc => { self.input_mode = InputMode::Normal; self.packages_view_state.filter_active = false; } KeyCode::Enter => { // Just exit filter input mode, filter is applied live self.input_mode = InputMode::Normal; self.packages_view_state.filter_active = false; } KeyCode::Backspace => { self.packages_view_state.filter_query.pop(); // Reset selection when filter changes self.packages_view_state.table_state.select(Some(0)); } KeyCode::Char(c) => { if modifiers == KeyModifiers::CONTROL && c == 'c' { self.running = false; } else { self.packages_view_state.filter_query.push(c); // Reset selection when filter changes self.packages_view_state.table_state.select(Some(0)); } } _ => {} } } fn handle_search_key(&mut self, key: KeyCode, modifiers: KeyModifiers) { match key { KeyCode::Esc => { self.input_mode = InputMode::Normal; } KeyCode::Enter => { // Execute search self.input_mode = InputMode::Normal; if self.search_view_state.search_query.is_empty() { let _ = self.app_sender.try_send(AppEvent::RequestKnownPackages); } else { let _ = self.app_sender.try_send(AppEvent::SearchPackages( self.search_view_state.search_query.clone(), )); } } KeyCode::Backspace => { self.search_view_state.search_query.pop(); } KeyCode::Char(c) => { if modifiers == KeyModifiers::CONTROL && c == 'c' { self.running = false; } else { self.search_view_state.search_query.push(c); } } _ => {} } } fn handle_pull_prompt_key(&mut self, key: KeyCode, modifiers: KeyModifiers) { let InputMode::PullPrompt(ref mut state) = self.input_mode else { return; }; // Don't allow input while pull is in progress if state.in_progress { return; } match key { KeyCode::Esc => { self.input_mode = InputMode::Normal; } KeyCode::Enter => { if !state.input.is_empty() { // Send pull request to manager let input = state.input.clone(); state.in_progress = true; state.error = None; let _ = self.app_sender.try_send(AppEvent::Pull(input)); } } KeyCode::Backspace => { state.input.pop(); state.error = None; } KeyCode::Char(c) => { if modifiers == KeyModifiers::CONTROL && c == 'c' { self.running = false; } else { state.input.push(c); state.error = None; } } _ => {} } } fn is_manager_ready(&self) -> bool { self.manager_state == ManagerState::Ready } /// Returns true if network operations are allowed (manager ready and not offline) fn can_use_network(&self) -> bool { self.is_manager_ready() && !self.offline } fn filtered_packages(&self) -> Vec<&ImageEntry> { let query = self.packages_view_state.filter_query.to_lowercase(); if query.is_empty() { self.packages.iter().collect() } else { self.packages .iter() .filter(|p| { p.ref_repository.to_lowercase().contains(&query) || p.ref_registry.to_lowercase().contains(&query) || p.ref_tag .as_ref() .map(|t| t.to_lowercase().contains(&query)) .unwrap_or(false) }) .collect() } } }
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/cli/src/tui/components/mod.rs
Rust
mod tab_bar; pub use tab_bar::{TabBar, TabItem};
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/cli/src/tui/components/tab_bar.rs
Rust
use ratatui::{ prelude::*, widgets::{Block, Tabs}, }; /// A trait for items that can be displayed in a tab bar. pub trait TabItem: Copy + PartialEq + 'static { /// Returns all tab items in order. fn all() -> &'static [Self]; /// Returns the display title for this tab. fn title(&self) -> &'static str; /// Returns the next tab (wrapping around). #[allow(clippy::indexing_slicing)] fn next(&self) -> Self { let all = Self::all(); let current_idx = all.iter().position(|t| t == self).unwrap_or(0); let next_idx = (current_idx + 1) % all.len(); all[next_idx] } /// Returns the previous tab (wrapping around). #[allow(clippy::indexing_slicing)] fn prev(&self) -> Self { let all = Self::all(); let current_idx = all.iter().position(|t| t == self).unwrap_or(0); let prev_idx = if current_idx == 0 { all.len() - 1 } else { current_idx - 1 }; all[prev_idx] } } /// A reusable tab bar component. #[derive(Debug)] pub struct TabBar<'a, T: TabItem> { title: String, selected: T, highlight_style: Style, _marker: std::marker::PhantomData<&'a T>, } impl<'a, T: TabItem> TabBar<'a, T> { /// Creates a new tab bar with the given title and selected tab. pub fn new(title: impl Into<String>, selected: T) -> Self { Self { title: title.into(), selected, highlight_style: Style::default().bold().fg(Color::Yellow), _marker: std::marker::PhantomData, } } } impl<T: TabItem> Widget for TabBar<'_, T> { fn render(self, area: Rect, buf: &mut Buffer) { let all_tabs = T::all(); let tab_titles: Vec<&str> = all_tabs.iter().map(|t| t.title()).collect(); let selected_index = all_tabs .iter() .position(|t| *t == self.selected) .unwrap_or(0); let tabs = Tabs::new(tab_titles) .block(Block::bordered().title(format!(" {} ", self.title))) .highlight_style(self.highlight_style) .select(selected_index); tabs.render(area, buf); } }
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/cli/src/tui/mod.rs
Rust
#![allow(unreachable_pub)] mod app; /// TUI components pub mod components; /// TUI views pub mod views; use app::App; use tokio::sync::mpsc; use wasm_package_manager::{ ImageEntry, InsertResult, KnownPackage, Manager, Reference, StateInfo, WitInterface, }; /// Events sent from the TUI to the Manager #[derive(Debug)] pub enum AppEvent { /// Request to quit the application Quit, /// Request the list of packages RequestPackages, /// Request state info RequestStateInfo, /// Pull a package from a registry Pull(String), /// Delete a package by its reference Delete(String), /// Search for known packages SearchPackages(String), /// Request all known packages RequestKnownPackages, /// Refresh tags for a package (registry, repository) RefreshTags(String, String), /// Request all WIT interfaces RequestWitInterfaces, /// Request to detect local WASM files DetectLocalWasm, } /// Events sent from the Manager to the TUI #[derive(Debug)] pub enum ManagerEvent { /// Manager has finished initializing Ready, /// List of packages PackagesList(Vec<ImageEntry>), /// State information StateInfo(StateInfo), /// Result of a pull operation (includes InsertResult to indicate if package was new or already existed) PullResult(Result<InsertResult, String>), /// Result of a delete operation DeleteResult(Result<(), String>), /// Search results for known packages SearchResults(Vec<KnownPackage>), /// All known packages KnownPackagesList(Vec<KnownPackage>), /// Result of refreshing tags for a package RefreshTagsResult(Result<usize, String>), /// List of WIT interfaces with their component references WitInterfacesList(Vec<(WitInterface, String)>), /// List of local WASM files LocalWasmList(Vec<wasm_detector::WasmEntry>), } /// Run the TUI application pub async fn run(offline: bool) -> anyhow::Result<()> { // Create channels for bidirectional communication let (app_sender, app_receiver) = mpsc::channel::<AppEvent>(32); let (manager_sender, manager_receiver) = mpsc::channel::<ManagerEvent>(32); // Run the TUI in a blocking task (separate thread) since it has a synchronous event loop let tui_handle = tokio::task::spawn_blocking(move || { let terminal = ratatui::init(); let res = App::new(app_sender, manager_receiver, offline).run(terminal); ratatui::restore(); res }); // Run the manager on the current task using LocalSet (Manager is not Send) let local = tokio::task::LocalSet::new(); local .run_until(run_manager(app_receiver, manager_sender, offline)) .await?; // Wait for TUI to finish tui_handle.await??; Ok(()) } async fn run_manager( mut receiver: mpsc::Receiver<AppEvent>, sender: mpsc::Sender<ManagerEvent>, offline: bool, ) -> Result<(), anyhow::Error> { let manager = if offline { Manager::open_offline().await? } else { Manager::open().await? }; sender.send(ManagerEvent::Ready).await.ok(); while let Some(event) = receiver.recv().await { match event { AppEvent::Quit => break, AppEvent::RequestPackages => { if let Ok(packages) = manager.list_all() { sender.send(ManagerEvent::PackagesList(packages)).await.ok(); } } AppEvent::RequestStateInfo => { let state_info = manager.state_info(); sender.send(ManagerEvent::StateInfo(state_info)).await.ok(); } AppEvent::Pull(reference_str) => { let result = match reference_str.parse::<Reference>() { Ok(reference) => manager.pull(reference).await.map_err(|e| e.to_string()), Err(e) => Err(format!("Invalid reference: {}", e)), }; sender.send(ManagerEvent::PullResult(result)).await.ok(); // Refresh the packages list after pull (only if it was newly inserted) if let Ok(packages) = manager.list_all() { sender.send(ManagerEvent::PackagesList(packages)).await.ok(); } } AppEvent::Delete(reference_str) => { let result = match reference_str.parse::<Reference>() { Ok(reference) => manager .delete(reference) .await .map(|_| ()) .map_err(|e| e.to_string()), Err(e) => Err(format!("Invalid reference: {}", e)), }; sender.send(ManagerEvent::DeleteResult(result)).await.ok(); // Refresh the packages list after delete if let Ok(packages) = manager.list_all() { sender.send(ManagerEvent::PackagesList(packages)).await.ok(); } } AppEvent::SearchPackages(query) => { if let Ok(packages) = manager.search_packages(&query) { sender .send(ManagerEvent::SearchResults(packages)) .await .ok(); } } AppEvent::RequestKnownPackages => { if let Ok(packages) = manager.list_known_packages() { sender .send(ManagerEvent::KnownPackagesList(packages)) .await .ok(); } } AppEvent::RefreshTags(registry, repository) => { // Create a reference to fetch tags let reference_str = format!("{}/{}:latest", registry, repository); let result = match reference_str.parse::<Reference>() { Ok(reference) => match manager.list_tags(&reference).await { Ok(tags) => { let tag_count = tags.len(); // Store all fetched tags as known packages for tag in tags { let _ = manager.add_known_package( &registry, &repository, Some(&tag), None, ); } Ok(tag_count) } Err(e) => Err(e.to_string()), }, Err(e) => Err(format!("Invalid reference: {}", e)), }; sender .send(ManagerEvent::RefreshTagsResult(result)) .await .ok(); // Refresh known packages list after updating tags if let Ok(packages) = manager.list_known_packages() { sender .send(ManagerEvent::KnownPackagesList(packages)) .await .ok(); } } AppEvent::RequestWitInterfaces => { if let Ok(interfaces) = manager.list_wit_interfaces_with_components() { sender .send(ManagerEvent::WitInterfacesList(interfaces)) .await .ok(); } } AppEvent::DetectLocalWasm => { // Detect local WASM files in the current directory let detector = wasm_detector::WasmDetector::new(std::path::Path::new(".")); let wasm_files: Vec<_> = detector.into_iter().filter_map(Result::ok).collect(); sender .send(ManagerEvent::LocalWasmList(wasm_files)) .await .ok(); } } } Ok(()) }
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/cli/src/tui/views/interfaces.rs
Rust
use ratatui::{ prelude::*, widgets::{ Block, Paragraph, Row, Scrollbar, ScrollbarOrientation, ScrollbarState, StatefulWidget, Table, TableState, Widget, Wrap, }, }; use wasm_package_manager::WitInterface; /// State for the interfaces view #[derive(Debug, Default)] pub struct InterfacesViewState { /// Table state for list selection pub table_state: TableState, /// Scroll offset for the detail view pub detail_scroll: u16, /// Whether we're viewing detail (vs list) pub viewing_detail: bool, } impl InterfacesViewState { /// Create a new InterfacesViewState #[must_use] pub fn new() -> Self { Self { table_state: TableState::default().with_selected(Some(0)), detail_scroll: 0, viewing_detail: false, } } /// Get the currently selected interface index #[must_use] pub fn selected(&self) -> Option<usize> { self.table_state.selected() } /// Select the next interface in the list pub fn select_next(&mut self, len: usize) { if len == 0 { return; } let current = self.table_state.selected().unwrap_or(0); self.table_state.select(Some((current + 1) % len)); } /// Select the previous interface in the list pub fn select_prev(&mut self, len: usize) { if len == 0 { return; } let current = self.table_state.selected().unwrap_or(0); self.table_state .select(Some(current.checked_sub(1).unwrap_or(len - 1))); } /// Scroll down in the detail view pub fn scroll_down(&mut self) { self.detail_scroll = self.detail_scroll.saturating_add(1); } /// Scroll up in the detail view pub fn scroll_up(&mut self) { self.detail_scroll = self.detail_scroll.saturating_sub(1); } } /// View for displaying WIT interfaces #[derive(Debug)] pub struct InterfacesView<'a> { interfaces: &'a [(WitInterface, String)], } impl<'a> InterfacesView<'a> { /// Create a new InterfacesView with the given interfaces #[must_use] pub fn new(interfaces: &'a [(WitInterface, String)]) -> Self { Self { interfaces } } } impl StatefulWidget for InterfacesView<'_> { type State = InterfacesViewState; fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) { if self.interfaces.is_empty() { let msg = "No WIT interfaces found.\n\nPull a WebAssembly component to see its interfaces here.\nPress [2] to go to Components, then [p] to pull a package."; Paragraph::new(msg) .centered() .wrap(Wrap { trim: false }) .render(area, buf); return; } if state.viewing_detail { // Render detail view if let Some(idx) = state.selected() && let Some((interface, component_ref)) = self.interfaces.get(idx) { self.render_detail(area, buf, state, interface, component_ref); } } else { // Render list view self.render_list(area, buf, state); } } } impl InterfacesView<'_> { fn render_list(&self, area: Rect, buf: &mut Buffer, state: &mut InterfacesViewState) { let header = Row::new(vec!["Package", "Component", "World", "Imports", "Exports"]) .style(Style::default().bold()) .bottom_margin(1); let rows: Vec<Row> = self .interfaces .iter() .map(|(interface, component_ref)| { Row::new(vec![ interface .package_name .clone() .unwrap_or_else(|| "<unknown>".to_string()), component_ref.clone(), interface .world_name .clone() .unwrap_or_else(|| "<unknown>".to_string()), interface.import_count.to_string(), interface.export_count.to_string(), ]) }) .collect(); let widths = [ Constraint::Percentage(25), Constraint::Percentage(30), Constraint::Percentage(20), Constraint::Length(10), Constraint::Length(10), ]; let table = Table::new(rows, widths) .header(header) .row_highlight_style(Style::default().bg(Color::DarkGray)) .highlight_symbol(" ▶ "); StatefulWidget::render(table, area, buf, &mut state.table_state); // Render help text at bottom let help_area = Rect { x: area.x, y: area.y.saturating_add(area.height.saturating_sub(1)), width: area.width, height: 1, }; let help_text = " ↑/↓ navigate │ Enter view WIT │ q quit "; Paragraph::new(help_text) .style(Style::default().fg(Color::DarkGray)) .render(help_area, buf); } #[allow(clippy::indexing_slicing)] fn render_detail( &self, area: Rect, buf: &mut Buffer, state: &mut InterfacesViewState, interface: &WitInterface, component_ref: &str, ) { // Split into header and content let chunks = Layout::vertical([Constraint::Length(3), Constraint::Min(0)]).split(area); // Header with component info let header_text = format!( "Package: {} │ World: {} │ Imports: {} │ Exports: {}", interface.package_name.as_deref().unwrap_or("<unknown>"), interface.world_name.as_deref().unwrap_or("<unknown>"), interface.import_count, interface.export_count ); let header = Paragraph::new(header_text) .style(Style::default().bold()) .block(Block::bordered().title(format!(" {} ", component_ref))); header.render(chunks[0], buf); // WIT content with scrolling let wit_lines: Vec<Line> = interface .wit_text .lines() .enumerate() .map(|(i, line)| { // Apply syntax highlighting let style = if line.trim().starts_with("//") || line.trim().starts_with("///") { Style::default().fg(Color::DarkGray) } else if line.contains("package ") || line.contains("world ") || line.contains("interface ") { Style::default().fg(Color::Cyan).bold() } else if line.contains("import ") { Style::default().fg(Color::Green) } else if line.contains("export ") { Style::default().fg(Color::Yellow) } else if line.contains("func ") || line.contains("resource ") { Style::default().fg(Color::Magenta) } else if line.contains("record ") || line.contains("enum ") || line.contains("variant ") || line.contains("flags ") { Style::default().fg(Color::Blue) } else { Style::default() }; Line::styled(format!("{:4} │ {}", i + 1, line), style) }) .collect(); let total_lines = wit_lines.len() as u16; let visible_height = chunks[1].height.saturating_sub(2); // Account for block borders // Clamp scroll to valid range let max_scroll = total_lines.saturating_sub(visible_height); if state.detail_scroll > max_scroll { state.detail_scroll = max_scroll; } let wit_content = Paragraph::new(wit_lines) .scroll((state.detail_scroll, 0)) .block(Block::bordered().title(" WIT Definition (Esc to go back, ↑/↓ to scroll) ")); wit_content.render(chunks[1], buf); // Render scrollbar if needed if total_lines > visible_height { let scrollbar = Scrollbar::new(ScrollbarOrientation::VerticalRight) .begin_symbol(Some("↑")) .end_symbol(Some("↓")); let mut scrollbar_state = ScrollbarState::new(total_lines as usize).position(state.detail_scroll as usize); let scrollbar_area = Rect { x: chunks[1].x + chunks[1].width - 1, y: chunks[1].y + 1, width: 1, height: chunks[1].height.saturating_sub(2), }; scrollbar.render(scrollbar_area, buf, &mut scrollbar_state); } } }
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/cli/src/tui/views/known_package_detail.rs
Rust
use ratatui::{ prelude::*, widgets::{Block, Borders, Paragraph, Widget, Wrap}, }; use wasm_package_manager::KnownPackage; /// View for displaying details of a known package (from search results). #[derive(Debug)] #[allow(dead_code)] pub struct KnownPackageDetailView<'a> { package: &'a KnownPackage, } impl<'a> KnownPackageDetailView<'a> { /// Creates a new known package detail view. #[must_use] #[allow(dead_code)] pub fn new(package: &'a KnownPackage) -> Self { Self { package } } } impl Widget for KnownPackageDetailView<'_> { #[allow(clippy::indexing_slicing)] fn render(self, area: Rect, buf: &mut Buffer) { // Split area into content and shortcuts bar let main_layout = Layout::vertical([Constraint::Min(0), Constraint::Length(1)]).split(area); let content_area = main_layout[0]; let shortcuts_area = main_layout[1]; let layout = Layout::vertical([ Constraint::Length(3), // Header Constraint::Min(0), // Details ]) .split(content_area); // Header with package name let header_text = format!("{}/{}", self.package.registry, self.package.repository); Paragraph::new(header_text) .style(Style::default().bold().fg(Color::Yellow)) .block(Block::default().borders(Borders::BOTTOM)) .render(layout[0], buf); // Build details text let mut details = Vec::new(); details.push(Line::from(vec![ Span::styled("Registry: ", Style::default().bold()), Span::raw(&self.package.registry), ])); details.push(Line::from(vec![ Span::styled("Repository: ", Style::default().bold()), Span::raw(&self.package.repository), ])); if let Some(ref description) = self.package.description { details.push(Line::from(vec![ Span::styled("Description: ", Style::default().bold()), Span::raw(description), ])); } details.push(Line::raw("")); // Empty line // Tags info details.push(Line::from(vec![ Span::styled("Tags: ", Style::default().bold()), Span::raw(format!("{} tag(s)", self.package.tags.len())), ])); if !self.package.tags.is_empty() { for tag in &self.package.tags { details.push(Line::from(vec![ Span::styled(" • ", Style::default().dim()), Span::raw(tag), ])); } } if !self.package.signature_tags.is_empty() { details.push(Line::raw("")); // Empty line details.push(Line::from(vec![ Span::styled("Signature Tags: ", Style::default().bold()), Span::raw(format!("{} tag(s)", self.package.signature_tags.len())), ])); for tag in &self.package.signature_tags { details.push(Line::from(vec![ Span::styled(" • ", Style::default().dim()), Span::raw(tag), ])); } } if !self.package.attestation_tags.is_empty() { details.push(Line::raw("")); // Empty line details.push(Line::from(vec![ Span::styled("Attestation Tags: ", Style::default().bold()), Span::raw(format!("{} tag(s)", self.package.attestation_tags.len())), ])); for tag in &self.package.attestation_tags { details.push(Line::from(vec![ Span::styled(" • ", Style::default().dim()), Span::raw(tag), ])); } } details.push(Line::raw("")); // Empty line // Timestamps details.push(Line::from(vec![ Span::styled("Last Seen: ", Style::default().bold()), Span::raw(&self.package.last_seen_at), ])); details.push(Line::from(vec![ Span::styled("Created At: ", Style::default().bold()), Span::raw(&self.package.created_at), ])); Paragraph::new(details) .wrap(Wrap { trim: false }) .render(layout[1], buf); // Render shortcuts bar let shortcuts = Line::from(vec![ Span::styled(" Esc ", Style::default().fg(Color::Black).bg(Color::Yellow)), Span::raw(" Back "), ]); Paragraph::new(shortcuts) .style(Style::default().fg(Color::DarkGray)) .render(shortcuts_area, buf); } }
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/cli/src/tui/views/local.rs
Rust
use ratatui::{ prelude::*, widgets::{Block, List, ListItem, Paragraph, Widget}, }; use wasm_detector::WasmEntry; /// View for the Local tab #[derive(Debug)] pub struct LocalView<'a> { wasm_files: &'a [WasmEntry], } impl<'a> LocalView<'a> { /// Create a new LocalView with the given WASM files #[must_use] pub fn new(wasm_files: &'a [WasmEntry]) -> Self { Self { wasm_files } } } impl Widget for LocalView<'_> { #[allow(clippy::indexing_slicing)] fn render(self, area: Rect, buf: &mut Buffer) { if self.wasm_files.is_empty() { let message = Paragraph::new("No local WASM files detected.\n\nPress 'r' to refresh.") .centered() .style(Style::default().fg(Color::DarkGray)); message.render(area, buf); } else { let layout = Layout::vertical([ Constraint::Length(2), Constraint::Min(0), Constraint::Length(2), ]) .split(area); // Title let title = Paragraph::new(format!( "Detected {} local WASM file(s)", self.wasm_files.len() )) .style(Style::default().fg(Color::Cyan)) .alignment(Alignment::Center); title.render(layout[0], buf); // List of files let items: Vec<ListItem> = self .wasm_files .iter() .enumerate() .map(|(idx, entry)| { let path = entry.path().display().to_string(); let content = format!("{}. {}", idx + 1, path); ListItem::new(content).style(Style::default().fg(Color::White)) }) .collect(); let list = List::new(items) .block(Block::bordered().title("Files")) .style(Style::default()); Widget::render(list, layout[1], buf); // Help text let help = Paragraph::new("Press 'r' to refresh • 'q' to quit") .style(Style::default().fg(Color::DarkGray)) .alignment(Alignment::Center); help.render(layout[2], buf); } } }
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/cli/src/tui/views/mod.rs
Rust
mod interfaces; /// Known package detail view module pub mod known_package_detail; mod local; mod package_detail; /// Packages view module pub mod packages; mod search; mod settings; pub use interfaces::{InterfacesView, InterfacesViewState}; #[allow(unused_imports)] pub use known_package_detail::KnownPackageDetailView; pub use local::LocalView; pub use package_detail::PackageDetailView; pub use packages::PackagesView; pub use search::{SearchView, SearchViewState}; pub use settings::SettingsView; pub(crate) use wasm_package_manager::format_size;
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/cli/src/tui/views/package_detail.rs
Rust
use ratatui::{ prelude::*, widgets::{Block, Borders, Paragraph, Widget, Wrap}, }; use wasm_package_manager::ImageEntry; /// View for displaying details of an installed package #[derive(Debug)] pub struct PackageDetailView<'a> { package: &'a ImageEntry, } impl<'a> PackageDetailView<'a> { /// Creates a new package detail view #[must_use] pub fn new(package: &'a ImageEntry) -> Self { Self { package } } } impl Widget for PackageDetailView<'_> { #[allow(clippy::indexing_slicing)] fn render(self, area: Rect, buf: &mut Buffer) { // Split area into content and shortcuts bar let main_layout = Layout::vertical([Constraint::Min(0), Constraint::Length(1)]).split(area); let content_area = main_layout[0]; let shortcuts_area = main_layout[1]; let layout = Layout::vertical([ Constraint::Length(3), // Header Constraint::Min(0), // Details ]) .split(content_area); // Header with package name let header_text = format!( "{}/{}", self.package.ref_registry, self.package.ref_repository ); Paragraph::new(header_text) .style(Style::default().bold().fg(Color::Yellow)) .block(Block::default().borders(Borders::BOTTOM)) .render(layout[0], buf); // Build details text let mut details = Vec::new(); details.push(Line::from(vec![ Span::styled("Registry: ", Style::default().bold()), Span::raw(&self.package.ref_registry), ])); details.push(Line::from(vec![ Span::styled("Repository: ", Style::default().bold()), Span::raw(&self.package.ref_repository), ])); if let Some(ref mirror) = self.package.ref_mirror_registry { details.push(Line::from(vec![ Span::styled("Mirror Registry: ", Style::default().bold()), Span::raw(mirror), ])); } if let Some(ref tag) = self.package.ref_tag { details.push(Line::from(vec![ Span::styled("Tag: ", Style::default().bold()), Span::raw(tag), ])); } if let Some(ref digest) = self.package.ref_digest { details.push(Line::from(vec![ Span::styled("Digest: ", Style::default().bold()), Span::raw(digest), ])); } details.push(Line::from(vec![ Span::styled("Size: ", Style::default().bold()), Span::raw(super::format_size(self.package.size_on_disk)), ])); details.push(Line::raw("")); // Empty line // Manifest info details.push(Line::from(vec![Span::styled( "Manifest:", Style::default().bold().underlined(), )])); details.push(Line::from(vec![ Span::styled(" Schema Version: ", Style::default().bold()), Span::raw(self.package.manifest.schema_version.to_string()), ])); if let Some(ref media_type) = self.package.manifest.media_type { details.push(Line::from(vec![ Span::styled(" Media Type: ", Style::default().bold()), Span::raw(media_type), ])); } details.push(Line::from(vec![ Span::styled(" Config Media Type: ", Style::default().bold()), Span::raw(&self.package.manifest.config.media_type), ])); details.push(Line::from(vec![ Span::styled(" Config Size: ", Style::default().bold()), Span::raw(super::format_size(self.package.manifest.config.size as u64)), ])); details.push(Line::raw("")); // Empty line // Layers info let layer_count = self.package.manifest.layers.len(); details.push(Line::from(vec![ Span::styled("Layers: ", Style::default().bold()), Span::raw(format!("{} layer(s)", layer_count)), ])); for (i, layer) in self.package.manifest.layers.iter().enumerate() { let size_str = super::format_size(layer.size as u64); details.push(Line::from(vec![ Span::styled(format!(" [{}] ", i + 1), Style::default().dim()), Span::raw(&layer.media_type), Span::styled(format!(" ({})", size_str), Style::default().dim()), ])); } details.push(Line::raw("")); // Empty line Paragraph::new(details) .wrap(Wrap { trim: false }) .render(layout[1], buf); // Render shortcuts bar let shortcuts = Line::from(vec![ Span::styled(" Esc ", Style::default().fg(Color::Black).bg(Color::Yellow)), Span::raw(" Back "), ]); Paragraph::new(shortcuts) .style(Style::default().fg(Color::DarkGray)) .render(shortcuts_area, buf); } }
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/cli/src/tui/views/packages.rs
Rust
use ratatui::{ prelude::*, widgets::{Block, Cell, Paragraph, Row, StatefulWidget, Table, TableState, Widget}, }; use wasm_package_manager::ImageEntry; use super::format_size; /// State for the packages list view #[derive(Debug, Default)] pub struct PackagesViewState { /// Table selection state pub table_state: TableState, /// Current filter query pub filter_query: String, /// Whether filter mode is active pub filter_active: bool, } impl PackagesViewState { /// Creates a new packages view state #[must_use] pub fn new() -> Self { Self { table_state: TableState::default().with_selected(Some(0)), filter_query: String::new(), filter_active: false, } } pub(crate) fn selected(&self) -> Option<usize> { self.table_state.selected() } pub(crate) fn select_next(&mut self, len: usize) { if len == 0 { return; } let current = self.table_state.selected().unwrap_or(0); let next = if current >= len - 1 { 0 } else { current + 1 }; self.table_state.select(Some(next)); } pub(crate) fn select_prev(&mut self, len: usize) { if len == 0 { return; } let current = self.table_state.selected().unwrap_or(0); let prev = if current == 0 { len - 1 } else { current - 1 }; self.table_state.select(Some(prev)); } } /// View for displaying the list of installed packages #[derive(Debug)] pub struct PackagesView<'a> { packages: &'a [ImageEntry], } impl<'a> PackagesView<'a> { /// Creates a new packages view #[must_use] pub fn new(packages: &'a [ImageEntry]) -> Self { Self { packages } } } impl StatefulWidget for PackagesView<'_> { type State = PackagesViewState; #[allow(clippy::indexing_slicing)] fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) { // Split area into filter input, content, and shortcuts bar let layout = Layout::vertical([ Constraint::Length(3), Constraint::Min(0), Constraint::Length(1), ]) .split(area); let filter_area = layout[0]; let content_area = layout[1]; let shortcuts_area = layout[2]; // Render filter input let filter_style = if state.filter_active { Style::default().fg(Color::Yellow) } else { Style::default().fg(Color::White) }; let filter_text = if state.filter_active { format!("{}_", state.filter_query) } else if state.filter_query.is_empty() { "Press / to filter...".to_string() } else { state.filter_query.clone() }; let filter_block = Block::bordered() .title(" Filter ") .border_style(filter_style); let filter_input = Paragraph::new(filter_text) .style(filter_style) .block(filter_block); filter_input.render(filter_area, buf); if self.packages.is_empty() { let message = if state.filter_query.is_empty() { "No packages stored." } else { "No packages found matching your filter." }; Paragraph::new(message).centered().render(content_area, buf); } else { // Create header row let header = Row::new(vec![ Cell::from("Repository").style(Style::default().bold()), Cell::from("Registry").style(Style::default().bold()), Cell::from("Tag").style(Style::default().bold()), Cell::from("Size").style(Style::default().bold()), Cell::from("Digest").style(Style::default().bold()), ]) .style(Style::default().fg(Color::Yellow)); // Create data rows let rows: Vec<Row> = self .packages .iter() .map(|entry| { let tag = entry.ref_tag.as_deref().unwrap_or("-"); let size = format_size(entry.size_on_disk); let digest = entry .ref_digest .as_ref() .map(|d| { // Strip "sha256:" prefix d.strip_prefix("sha256:").unwrap_or(d).to_string() }) .unwrap_or_else(|| "-".to_string()); Row::new(vec![ Cell::from(entry.ref_repository.clone()), Cell::from(entry.ref_registry.clone()), Cell::from(tag.to_string()), Cell::from(size), Cell::from(digest), ]) }) .collect(); let table = Table::new( rows, [ Constraint::Percentage(30), Constraint::Percentage(20), Constraint::Percentage(15), Constraint::Percentage(12), Constraint::Percentage(23), ], ) .header(header) .row_highlight_style(Style::default().bg(Color::DarkGray)); StatefulWidget::render(table, content_area, buf, &mut state.table_state); } // Render shortcuts bar let shortcuts = Line::from(vec![ Span::styled(" / ", Style::default().fg(Color::Black).bg(Color::Yellow)), Span::raw(" Filter "), Span::styled(" p ", Style::default().fg(Color::Black).bg(Color::Yellow)), Span::raw(" Pull "), Span::styled(" d ", Style::default().fg(Color::Black).bg(Color::Yellow)), Span::raw(" Delete "), Span::styled( " Enter ", Style::default().fg(Color::Black).bg(Color::Yellow), ), Span::raw(" View details "), Span::styled(" Esc ", Style::default().fg(Color::Black).bg(Color::Yellow)), Span::raw(" Clear "), ]); Paragraph::new(shortcuts) .style(Style::default().fg(Color::DarkGray)) .render(shortcuts_area, buf); } } impl Widget for PackagesView<'_> { fn render(self, area: Rect, buf: &mut Buffer) { let mut state = PackagesViewState::new(); StatefulWidget::render(self, area, buf, &mut state); } }
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/cli/src/tui/views/search.rs
Rust
use ratatui::{ prelude::*, widgets::{Block, Cell, Paragraph, Row, StatefulWidget, Table, TableState, Widget}, }; use wasm_package_manager::KnownPackage; /// State for the search view #[derive(Debug, Default)] pub struct SearchViewState { /// Table selection state pub table_state: TableState, /// Current search query pub search_query: String, /// Whether search mode is active pub search_active: bool, } impl SearchViewState { /// Creates a new search view state #[must_use] pub fn new() -> Self { Self { table_state: TableState::default().with_selected(Some(0)), search_query: String::new(), search_active: false, } } pub(crate) fn selected(&self) -> Option<usize> { self.table_state.selected() } pub(crate) fn select_next(&mut self, len: usize) { if len == 0 { return; } let current = self.table_state.selected().unwrap_or(0); let next = if current >= len - 1 { 0 } else { current + 1 }; self.table_state.select(Some(next)); } pub(crate) fn select_prev(&mut self, len: usize) { if len == 0 { return; } let current = self.table_state.selected().unwrap_or(0); let prev = if current == 0 { len - 1 } else { current - 1 }; self.table_state.select(Some(prev)); } } /// View for displaying search results #[derive(Debug)] pub struct SearchView<'a> { packages: &'a [KnownPackage], } impl<'a> SearchView<'a> { /// Creates a new search view #[must_use] pub fn new(packages: &'a [KnownPackage]) -> Self { Self { packages } } } impl StatefulWidget for SearchView<'_> { type State = SearchViewState; #[allow(clippy::indexing_slicing)] fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) { // Split area into search input, content, and shortcuts bar let layout = Layout::vertical([ Constraint::Length(3), Constraint::Min(0), Constraint::Length(1), ]) .split(area); let search_area = layout[0]; let content_area = layout[1]; let shortcuts_area = layout[2]; // Render search input let search_style = if state.search_active { Style::default().fg(Color::Yellow) } else { Style::default().fg(Color::White) }; let search_text = if state.search_active { format!("{}_", state.search_query) } else if state.search_query.is_empty() { "Press / to search...".to_string() } else { state.search_query.clone() }; let search_block = Block::bordered() .title(" Search ") .border_style(search_style); let search_input = Paragraph::new(search_text) .style(search_style) .block(search_block); search_input.render(search_area, buf); // Render package list if self.packages.is_empty() { let message = if state.search_query.is_empty() { "No known packages. Pull a package to add it to the list." } else { "No packages found matching your search." }; Paragraph::new(message).centered().render(content_area, buf); } else { // Create header row let header = Row::new(vec![ Cell::from("Repository").style(Style::default().bold()), Cell::from("Registry").style(Style::default().bold()), Cell::from("Tags").style(Style::default().bold()), Cell::from("Last Seen").style(Style::default().bold()), ]) .style(Style::default().fg(Color::Yellow)); // Create data rows let rows: Vec<Row> = self .packages .iter() .map(|entry| { // Format tags (show first few) let tags_display = if entry.tags.is_empty() { "-".to_string() } else if entry.tags.len() <= 3 { entry.tags.join(", ") } else { format!("{}, +{}", entry.tags[..2].join(", "), entry.tags.len() - 2) }; // Format the date nicely (just show date part) let last_seen = entry .last_seen_at .split('T') .next() .unwrap_or(&entry.last_seen_at); Row::new(vec![ Cell::from(entry.repository.clone()), Cell::from(entry.registry.clone()), Cell::from(tags_display), Cell::from(last_seen.to_string()), ]) }) .collect(); let table = Table::new( rows, [ Constraint::Percentage(35), Constraint::Percentage(25), Constraint::Percentage(20), Constraint::Percentage(20), ], ) .header(header) .row_highlight_style(Style::default().bg(Color::DarkGray)); StatefulWidget::render(table, content_area, buf, &mut state.table_state); } // Render shortcuts bar let shortcuts = Line::from(vec![ Span::styled(" / ", Style::default().fg(Color::Black).bg(Color::Yellow)), Span::raw(" Search "), Span::styled(" p ", Style::default().fg(Color::Black).bg(Color::Yellow)), Span::raw(" Pull selected "), Span::styled(" r ", Style::default().fg(Color::Black).bg(Color::Yellow)), Span::raw(" Refresh tags "), Span::styled( " Enter ", Style::default().fg(Color::Black).bg(Color::Yellow), ), Span::raw(" View details "), Span::styled(" Esc ", Style::default().fg(Color::Black).bg(Color::Yellow)), Span::raw(" Clear "), ]); Paragraph::new(shortcuts) .style(Style::default().fg(Color::DarkGray)) .render(shortcuts_area, buf); } } impl Widget for SearchView<'_> { fn render(self, area: Rect, buf: &mut Buffer) { let mut state = SearchViewState::new(); StatefulWidget::render(self, area, buf, &mut state); } }
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/cli/src/tui/views/settings.rs
Rust
use ratatui::{ prelude::*, widgets::{Cell, Paragraph, Row, Table, Widget}, }; use wasm_package_manager::StateInfo; /// View for displaying settings and state information #[derive(Debug)] pub struct SettingsView<'a> { state_info: Option<&'a StateInfo>, } impl<'a> SettingsView<'a> { /// Creates a new settings view #[must_use] pub fn new(state_info: Option<&'a StateInfo>) -> Self { Self { state_info } } } impl Widget for SettingsView<'_> { #[allow(clippy::indexing_slicing)] fn render(self, area: Rect, buf: &mut Buffer) { match self.state_info { Some(info) => { // Split area for migrations section and storage table let layout = Layout::vertical([Constraint::Length(3), Constraint::Min(0)]).split(area); // Migrations section let migrations = Text::from(vec![ Line::from(vec![Span::styled( "Migrations", Style::default().bold().fg(Color::Yellow), )]), Line::from(format!( " Current: {}/{}", info.migration_current(), info.migration_total() )), ]); Paragraph::new(migrations).render(layout[0], buf); // Storage section with table let storage_layout = Layout::vertical([Constraint::Length(1), Constraint::Min(0)]).split(layout[1]); let storage_header = Line::from(vec![Span::styled( "Storage", Style::default().bold().fg(Color::Yellow), )]); Paragraph::new(storage_header).render(storage_layout[0], buf); // Compute column widths based on content let executable_path = info.executable().display().to_string(); let data_dir_path = info.data_dir().display().to_string(); let store_dir_path = info.store_dir().display().to_string(); let metadata_file_path = info.metadata_file().display().to_string(); let store_size = super::format_size(info.store_size()); let metadata_size = super::format_size(info.metadata_size()); // Column 1: longest is "Image metadata" = 14 chars let col1_width = 14; // Column 2: longest path let col2_width = executable_path .len() .max(data_dir_path.len()) .max(store_dir_path.len()) .max(metadata_file_path.len()); // Column 3: longest size string or "-" let col3_width = store_size.len().max(metadata_size.len()).max(1); // Create data rows let rows = vec![ Row::new(vec![ Cell::from("Executable"), Cell::from(executable_path), Cell::from("-"), ]), Row::new(vec![ Cell::from("Data storage"), Cell::from(data_dir_path), Cell::from("-"), ]), Row::new(vec![ Cell::from("Content store"), Cell::from(store_dir_path), Cell::from(store_size), ]), Row::new(vec![ Cell::from("Image metadata"), Cell::from(metadata_file_path), Cell::from(metadata_size), ]), ]; let table = Table::new( rows, [ Constraint::Length(col1_width as u16), Constraint::Length(col2_width as u16), Constraint::Length(col3_width as u16), ], ) .column_spacing(3); Widget::render(table, storage_layout[1], buf); } None => { Paragraph::new("Loading state information...").render(area, buf); } } } }
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/cli/tests/snapshot.rs
Rust
//! Snapshot tests for TUI views using the `insta` crate. //! //! These tests render each view to a buffer and snapshot the result to ensure //! consistent rendering across changes. //! //! # Running Snapshot Tests //! //! Run tests with: `cargo test --package wasm` //! //! # Updating Snapshots //! //! When views change intentionally, update snapshots with: //! `cargo insta review` or `cargo insta accept` //! //! Install the insta CLI with: `cargo install cargo-insta` //! //! # Test Coverage Guidelines //! //! Every TUI view and component should have at least one snapshot test covering: //! - Empty/loading state (when applicable) //! - Populated state with sample data //! - Interactive states (filter active, search active, etc.) //! //! When adding new views or components, add corresponding snapshot tests. use std::path::PathBuf; use insta::assert_snapshot; use ratatui::prelude::*; use wasm::tui::components::{TabBar, TabItem}; use wasm::tui::views::packages::PackagesViewState; use wasm::tui::views::{ InterfacesView, InterfacesViewState, KnownPackageDetailView, LocalView, PackageDetailView, PackagesView, SearchView, SearchViewState, SettingsView, }; use wasm_detector::WasmEntry; use wasm_package_manager::{ImageEntry, KnownPackage, StateInfo}; /// Helper function to render a widget to a string buffer. fn render_to_string<W: Widget>(widget: W, width: u16, height: u16) -> String { let area = Rect::new(0, 0, width, height); let mut buffer = Buffer::empty(area); widget.render(area, &mut buffer); buffer_to_string(&buffer) } /// Helper function to render a stateful widget to a string buffer. fn render_stateful_to_string<W, S>(widget: W, state: &mut S, width: u16, height: u16) -> String where W: StatefulWidget<State = S>, { let area = Rect::new(0, 0, width, height); let mut buffer = Buffer::empty(area); widget.render(area, &mut buffer, state); buffer_to_string(&buffer) } /// Convert a buffer to a string representation for snapshot testing. fn buffer_to_string(buffer: &Buffer) -> String { let mut output = String::new(); for y in 0..buffer.area.height { let line_start = output.len(); for x in 0..buffer.area.width { let cell = &buffer[(x, y)]; output.push_str(cell.symbol()); } // Trim trailing spaces using truncate to avoid allocation let trimmed_len = output[line_start..].trim_end().len() + line_start; output.truncate(trimmed_len); output.push('\n'); } output } // ============================================================================= // LocalView Snapshot Tests // ============================================================================= #[test] fn test_local_view_empty_snapshot() { let wasm_files = vec![]; let output = render_to_string(LocalView::new(&wasm_files), 60, 10); assert_snapshot!(output); } #[test] fn test_local_view_with_files_snapshot() { let wasm_files = vec![ WasmEntry::new_for_testing(PathBuf::from( "./target/wasm32-unknown-unknown/release/app.wasm", )), WasmEntry::new_for_testing(PathBuf::from("./pkg/component.wasm")), WasmEntry::new_for_testing(PathBuf::from("./examples/hello.wasm")), ]; let output = render_to_string(LocalView::new(&wasm_files), 80, 15); assert_snapshot!(output); } // ============================================================================= // InterfacesView Snapshot Tests // ============================================================================= #[test] fn test_interfaces_view_snapshot() { let interfaces = vec![]; let mut state = InterfacesViewState::new(); let output = render_stateful_to_string(InterfacesView::new(&interfaces), &mut state, 60, 10); assert_snapshot!(output); } #[test] fn test_interfaces_view_populated_snapshot() { use wasm_package_manager::WitInterface; let interfaces = vec![ ( WitInterface::new_for_testing( 1, Some("wasi:http@0.2.0".to_string()), "package wasi:http@0.2.0;\n\nworld proxy {\n import wasi:http/types;\n export wasi:http/handler;\n}".to_string(), Some("proxy".to_string()), 1, 1, "2024-01-15T10:30:00Z".to_string(), ), "ghcr.io/example/http-proxy:v1.0.0".to_string(), ), ( WitInterface::new_for_testing( 2, Some("wasi:cli@0.2.0".to_string()), "package wasi:cli@0.2.0;\n\nworld command {\n import wasi:cli/stdin;\n import wasi:cli/stdout;\n export run;\n}".to_string(), Some("command".to_string()), 2, 1, "2024-01-16T11:20:00Z".to_string(), ), "ghcr.io/example/cli-tool:latest".to_string(), ), ]; let mut state = InterfacesViewState::new(); let output = render_stateful_to_string(InterfacesView::new(&interfaces), &mut state, 100, 15); assert_snapshot!(output); } // ============================================================================= // PackagesView Snapshot Tests // ============================================================================= #[test] fn test_packages_view_empty_snapshot() { let packages = vec![]; let output = render_to_string(PackagesView::new(&packages), 80, 15); assert_snapshot!(output); } #[test] fn test_packages_view_with_packages_snapshot() { let packages = vec![ ImageEntry::new_for_testing( "ghcr.io".to_string(), "bytecode-alliance/wasmtime".to_string(), Some("v1.0.0".to_string()), Some("sha256:abc123def456".to_string()), 1024 * 1024 * 5, // 5 MB ), ImageEntry::new_for_testing( "docker.io".to_string(), "example/hello-wasm".to_string(), Some("latest".to_string()), None, 1024 * 512, // 512 KB ), ImageEntry::new_for_testing( "ghcr.io".to_string(), "user/my-component".to_string(), Some("v2.1.0".to_string()), Some("sha256:789xyz".to_string()), 1024 * 1024 * 2, // 2 MB ), ]; let output = render_to_string(PackagesView::new(&packages), 100, 15); assert_snapshot!(output); } #[test] fn test_packages_view_with_filter_active_snapshot() { let packages = vec![]; let mut state = PackagesViewState::new(); state.filter_active = true; state.filter_query = "wasi".to_string(); let output = render_stateful_to_string(PackagesView::new(&packages), &mut state, 100, 15); assert_snapshot!(output); } #[test] fn test_packages_view_filter_with_results_snapshot() { let packages = vec![ImageEntry::new_for_testing( "ghcr.io".to_string(), "bytecode-alliance/wasi-http".to_string(), Some("v0.2.0".to_string()), Some("sha256:wasi123".to_string()), 1024 * 256, // 256 KB )]; let mut state = PackagesViewState::new(); state.filter_query = "wasi".to_string(); let output = render_stateful_to_string(PackagesView::new(&packages), &mut state, 100, 12); assert_snapshot!(output); } // ============================================================================= // PackageDetailView Snapshot Tests // ============================================================================= #[test] fn test_package_detail_view_snapshot() { let package = ImageEntry::new_for_testing( "ghcr.io".to_string(), "bytecode-alliance/wasmtime".to_string(), Some("v1.0.0".to_string()), Some("sha256:abc123def456789".to_string()), 1024 * 1024 * 5, // 5 MB ); let output = render_to_string(PackageDetailView::new(&package), 80, 25); assert_snapshot!(output); } #[test] fn test_package_detail_view_without_tag_snapshot() { let package = ImageEntry::new_for_testing( "docker.io".to_string(), "library/hello-world".to_string(), None, Some("sha256:digest123".to_string()), 1024 * 128, // 128 KB ); let output = render_to_string(PackageDetailView::new(&package), 80, 25); assert_snapshot!(output); } // ============================================================================= // SearchView Snapshot Tests // ============================================================================= #[test] fn test_search_view_empty_snapshot() { let packages = vec![]; let output = render_to_string(SearchView::new(&packages), 80, 15); assert_snapshot!(output); } #[test] fn test_search_view_with_packages_snapshot() { let packages = vec![ KnownPackage::new_for_testing( "ghcr.io".to_string(), "bytecode-alliance/wasi-http".to_string(), Some("WASI HTTP interface".to_string()), vec!["v0.2.0".to_string(), "v0.1.0".to_string()], vec![], vec![], "2024-01-15T10:30:00Z".to_string(), "2024-01-01T08:00:00Z".to_string(), ), KnownPackage::new_for_testing( "ghcr.io".to_string(), "user/my-component".to_string(), None, vec!["latest".to_string()], vec![], vec![], "2024-02-01T12:00:00Z".to_string(), "2024-01-20T09:00:00Z".to_string(), ), ]; let output = render_to_string(SearchView::new(&packages), 100, 15); assert_snapshot!(output); } #[test] fn test_search_view_with_search_active_snapshot() { let packages = vec![]; let mut state = SearchViewState::new(); state.search_active = true; state.search_query = "wasi".to_string(); let output = render_stateful_to_string(SearchView::new(&packages), &mut state, 100, 15); assert_snapshot!(output); } #[test] fn test_search_view_with_many_tags_snapshot() { let packages = vec![KnownPackage::new_for_testing( "ghcr.io".to_string(), "project/component".to_string(), Some("A component with many tags".to_string()), vec![ "v3.0.0".to_string(), "v2.0.0".to_string(), "v1.0.0".to_string(), "beta".to_string(), "alpha".to_string(), ], vec!["v3.0.0.sig".to_string()], vec!["v3.0.0.att".to_string()], "2024-03-01T10:00:00Z".to_string(), "2023-06-01T08:00:00Z".to_string(), )]; let output = render_to_string(SearchView::new(&packages), 100, 12); assert_snapshot!(output); } // ============================================================================= // KnownPackageDetailView Snapshot Tests // ============================================================================= #[test] fn test_known_package_detail_view_snapshot() { let package = KnownPackage::new_for_testing( "ghcr.io".to_string(), "user/example-package".to_string(), Some("An example WASM component package".to_string()), vec![ "v1.0.0".to_string(), "v0.9.0".to_string(), "latest".to_string(), ], vec!["v1.0.0.sig".to_string()], vec!["v1.0.0.att".to_string()], "2024-01-15T10:30:00Z".to_string(), "2024-01-01T08:00:00Z".to_string(), ); let output = render_to_string(KnownPackageDetailView::new(&package), 80, 20); assert_snapshot!(output); } #[test] fn test_known_package_detail_view_minimal_snapshot() { let package = KnownPackage::new_for_testing( "docker.io".to_string(), "library/minimal".to_string(), None, vec!["latest".to_string()], vec![], vec![], "2024-02-01T12:00:00Z".to_string(), "2024-02-01T12:00:00Z".to_string(), ); let output = render_to_string(KnownPackageDetailView::new(&package), 80, 15); assert_snapshot!(output); } // ============================================================================= // SettingsView Snapshot Tests // ============================================================================= #[test] fn test_settings_view_loading_snapshot() { let output = render_to_string(SettingsView::new(None), 80, 15); assert_snapshot!(output); } #[test] fn test_settings_view_with_state_info_snapshot() { let state_info = StateInfo::new_for_testing(); let output = render_to_string(SettingsView::new(Some(&state_info)), 100, 15); assert_snapshot!(output); } // ============================================================================= // TabBar Component Snapshot Tests // ============================================================================= /// Tab enum for testing the TabBar component. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum TestTab { First, Second, Third, } impl TestTab { const ALL: [TestTab; 3] = [TestTab::First, TestTab::Second, TestTab::Third]; } impl TabItem for TestTab { fn all() -> &'static [Self] { &Self::ALL } fn title(&self) -> &'static str { match self { TestTab::First => "First [1]", TestTab::Second => "Second [2]", TestTab::Third => "Third [3]", } } } #[test] fn test_tab_bar_first_selected_snapshot() { let tab_bar = TabBar::new("Test App - ready", TestTab::First); let output = render_to_string(tab_bar, 60, 3); assert_snapshot!(output); } #[test] fn test_tab_bar_second_selected_snapshot() { let tab_bar = TabBar::new("Test App - ready", TestTab::Second); let output = render_to_string(tab_bar, 60, 3); assert_snapshot!(output); } #[test] fn test_tab_bar_third_selected_snapshot() { let tab_bar = TabBar::new("Test App - ready", TestTab::Third); let output = render_to_string(tab_bar, 60, 3); assert_snapshot!(output); } #[test] fn test_tab_bar_loading_state_snapshot() { let tab_bar = TabBar::new("Test App - loading...", TestTab::First); let output = render_to_string(tab_bar, 60, 3); assert_snapshot!(output); } #[test] fn test_tab_bar_error_state_snapshot() { let tab_bar = TabBar::new("Test App - error occurred!", TestTab::First); let output = render_to_string(tab_bar, 60, 3); assert_snapshot!(output); }
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/cli/tests/test.rs
Rust
//! Tests for the wasm CLI //! //! This module contains integration tests for CLI commands. //! Use `cargo test --package wasm --test test` to run these tests. //! //! # CLI Help Screen Tests //! //! These tests verify that CLI help screens remain consistent using snapshot testing. //! When commands change, update snapshots with: //! `cargo insta review` or `INSTA_UPDATE=always cargo test --package wasm` use std::process::Command; use insta::assert_snapshot; /// Run the CLI with the given arguments and capture the output. /// /// The output is normalized to replace platform-specific binary names /// (e.g., `wasm.exe` on Windows) with `wasm` for consistent snapshots. fn run_cli(args: &[&str]) -> String { let output = Command::new(env!("CARGO_BIN_EXE_wasm")) .args(args) .output() .expect("Failed to execute command"); let stdout = String::from_utf8_lossy(&output.stdout); let stderr = String::from_utf8_lossy(&output.stderr); // Combine stdout and stderr for help output (clap writes to stdout by default for --help) let result = if !stdout.is_empty() { stdout.to_string() } else { stderr.to_string() }; // Normalize binary name for cross-platform consistency // On Windows, the binary is "wasm.exe" but on Unix it's "wasm" result.replace("wasm.exe", "wasm") } // ============================================================================= // Main CLI Help Tests // ============================================================================= #[test] fn test_cli_main_help_snapshot() { let output = run_cli(&["--help"]); assert_snapshot!(output); } #[test] fn test_cli_version_snapshot() { let output = run_cli(&["--version"]); // Version may change, so we just verify the format assert!(output.contains("wasm")); } // ============================================================================= // Inspect Command Help Tests // ============================================================================= #[test] fn test_cli_inspect_help_snapshot() { let output = run_cli(&["inspect", "--help"]); assert_snapshot!(output); } // ============================================================================= // Local Command Help Tests // ============================================================================= #[test] fn test_cli_local_help_snapshot() { let output = run_cli(&["local", "--help"]); assert_snapshot!(output); } #[test] fn test_cli_local_list_help_snapshot() { let output = run_cli(&["local", "list", "--help"]); assert_snapshot!(output); } // ============================================================================= // Package Command Help Tests // ============================================================================= #[test] fn test_cli_package_help_snapshot() { let output = run_cli(&["package", "--help"]); assert_snapshot!(output); } #[test] fn test_cli_package_pull_help_snapshot() { let output = run_cli(&["package", "pull", "--help"]); assert_snapshot!(output); } #[test] fn test_cli_package_tags_help_snapshot() { let output = run_cli(&["package", "tags", "--help"]); assert_snapshot!(output); } // ============================================================================= // Self Command Help Tests // ============================================================================= #[test] fn test_cli_self_help_snapshot() { let output = run_cli(&["self", "--help"]); assert_snapshot!(output); } #[test] fn test_cli_self_state_help_snapshot() { let output = run_cli(&["self", "state", "--help"]); assert_snapshot!(output); } // ============================================================================= // Color Support Tests // ============================================================================= #[test] fn test_color_flag_auto() { // Test that --color=auto is accepted let output = Command::new(env!("CARGO_BIN_EXE_wasm")) .args(&["--color", "auto", "--version"]) .output() .expect("Failed to execute command"); assert!(output.status.success()); } #[test] fn test_color_flag_always() { // Test that --color=always is accepted let output = Command::new(env!("CARGO_BIN_EXE_wasm")) .args(&["--color", "always", "--version"]) .output() .expect("Failed to execute command"); assert!(output.status.success()); } #[test] fn test_color_flag_never() { // Test that --color=never is accepted let output = Command::new(env!("CARGO_BIN_EXE_wasm")) .args(&["--color", "never", "--version"]) .output() .expect("Failed to execute command"); assert!(output.status.success()); } #[test] fn test_color_flag_invalid_value() { // Test that invalid color values are rejected let output = Command::new(env!("CARGO_BIN_EXE_wasm")) .args(&["--color", "invalid", "--version"]) .output() .expect("Failed to execute command"); assert!(!output.status.success()); let stderr = String::from_utf8_lossy(&output.stderr); assert!(stderr.contains("invalid value 'invalid'")); } #[test] fn test_color_flag_in_help() { // Test that --color flag appears in help output let output = run_cli(&["--help"]); assert!(output.contains("--color")); assert!(output.contains("When to use colored output")); } #[test] fn test_no_color_env_var() { // Test that NO_COLOR environment variable disables color let output = Command::new(env!("CARGO_BIN_EXE_wasm")) .args(&["--version"]) .env("NO_COLOR", "1") .output() .expect("Failed to execute command"); assert!(output.status.success()); // The output should not contain ANSI escape codes when NO_COLOR is set // We can't easily test for absence of color codes without parsing, // but we can verify the command succeeds } #[test] fn test_clicolor_env_var() { // Test that CLICOLOR=0 environment variable disables color let output = Command::new(env!("CARGO_BIN_EXE_wasm")) .args(&["--version"]) .env("CLICOLOR", "0") .output() .expect("Failed to execute command"); assert!(output.status.success()); } #[test] fn test_color_flag_with_subcommand() { // Test that --color flag works with subcommands let output = Command::new(env!("CARGO_BIN_EXE_wasm")) .args(&["--color", "never", "local", "--help"]) .output() .expect("Failed to execute command"); assert!(output.status.success()); } // ============================================================================= // Offline Mode Tests // ============================================================================= #[test] fn test_offline_flag_accepted() { // Test that --offline flag is accepted with --version let output = Command::new(env!("CARGO_BIN_EXE_wasm")) .args(&["--offline", "--version"]) .output() .expect("Failed to execute command"); assert!(output.status.success()); } #[test] fn test_offline_flag_in_help() { // Test that --offline flag appears in help output let output = run_cli(&["--help"]); assert!(output.contains("--offline")); assert!(output.contains("Run in offline mode")); } #[test] fn test_offline_flag_with_local_list() { // Test that --offline works with local list command (local-only operation) let output = Command::new(env!("CARGO_BIN_EXE_wasm")) .args(&["--offline", "local", "list", "/nonexistent"]) .output() .expect("Failed to execute command"); // The command should succeed (even if no files found) assert!(output.status.success()); } #[test] fn test_offline_flag_with_package_pull() { // Test that --offline mode causes package pull to fail with clear error let output = Command::new(env!("CARGO_BIN_EXE_wasm")) .args(&[ "--offline", "package", "pull", "ghcr.io/example/test:latest", ]) .output() .expect("Failed to execute command"); // The command should fail with an offline mode error assert!(!output.status.success()); let stderr = String::from_utf8_lossy(&output.stderr); assert!( stderr.contains("offline"), "Expected 'offline' error message, got: {}", stderr ); } #[test] fn test_offline_flag_with_inspect() { // Test that --offline works with inspect command (local-only operation) let output = Command::new(env!("CARGO_BIN_EXE_wasm")) .args(&["--offline", "inspect", "--help"]) .output() .expect("Failed to execute command"); assert!(output.status.success()); } #[test] fn test_offline_flag_with_subcommand() { // Test that --offline flag works with subcommands let output = Command::new(env!("CARGO_BIN_EXE_wasm")) .args(&["--offline", "local", "--help"]) .output() .expect("Failed to execute command"); assert!(output.status.success()); }
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/manifest/src/lib.rs
Rust
//! Manifest and lockfile format types for WebAssembly packages. //! //! This crate provides types for parsing and serializing WASM package manifests //! (`wasm.toml`) and lockfiles (`wasm.lock`). //! //! # Example: Parsing a Manifest //! //! ```rust //! use wasm_manifest::Manifest; //! //! let toml = r#" //! [dependencies] //! "wasi:logging" = "ghcr.io/webassembly/wasi-logging:1.0.0" //! "#; //! //! let manifest: Manifest = toml::from_str(toml).unwrap(); //! ``` //! //! # Example: Parsing a Lockfile //! //! ```rust //! use wasm_manifest::Lockfile; //! //! let toml = r#" //! version = 1 //! //! [[package]] //! name = "wasi:logging" //! version = "1.0.0" //! registry = "ghcr.io/webassembly/wasi-logging" //! digest = "sha256:abc123" //! "#; //! //! let lockfile: Lockfile = toml::from_str(toml).unwrap(); //! ``` #![deny(unsafe_code)] #![deny(missing_debug_implementations)] #![warn(missing_docs)] mod lockfile; mod manifest; mod validation; pub use lockfile::{Lockfile, Package, PackageDependency}; pub use manifest::{Dependency, Manifest}; pub use validation::{ValidationError, validate};
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/manifest/src/lockfile.rs
Rust
//! Types for the WASM lockfile (`wasm.lock`). use serde::{Deserialize, Serialize}; /// The root lockfile structure for a WASM package. /// /// The lockfile (`deps/wasm.lock`) is auto-generated and tracks resolved dependencies /// with their exact versions and content digests. /// /// # Example /// /// ```toml /// version = 1 /// /// [[package]] /// name = "wasi:logging" /// version = "1.0.0" /// registry = "ghcr.io/webassembly/wasi-logging" /// digest = "sha256:abc123..." /// ``` #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[must_use] pub struct Lockfile { /// The lockfile format version. pub version: u32, /// The list of resolved packages. #[serde(default)] #[serde(rename = "package")] pub packages: Vec<Package>, } /// A resolved package entry in the lockfile. /// /// Each package represents a dependency that has been resolved to a specific /// version with a content digest for integrity verification. /// /// # Example with dependencies /// /// ```toml /// [[package]] /// name = "wasi:key-value" /// version = "2.0.0" /// registry = "ghcr.io/webassembly/wasi-key-value" /// digest = "sha256:def456..." /// /// [[package.dependencies]] /// name = "wasi:logging" /// version = "1.0.0" /// ``` /// /// Note: `[[package.dependencies]]` defines dependencies for the last `[[package]]` entry. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[must_use] pub struct Package { /// The package name (e.g., "wasi:logging"). pub name: String, /// The package version (e.g., "1.0.0"). pub version: String, /// The full registry path (e.g., "ghcr.io/webassembly/wasi-logging"). pub registry: String, /// The content digest for integrity verification (e.g., "sha256:abc123..."). pub digest: String, /// Optional dependencies of this package. #[serde(default)] #[serde(skip_serializing_if = "Vec::is_empty")] pub dependencies: Vec<PackageDependency>, } /// A dependency reference within a package. /// /// This represents a dependency that a package has on another package. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[must_use] pub struct PackageDependency { /// The name of the dependency package. pub name: String, /// The version of the dependency package. pub version: String, } #[cfg(test)] mod tests { use super::*; #[test] fn test_parse_lockfile() { let toml = r#" version = 1 [[package]] name = "wasi:logging" version = "1.0.0" registry = "ghcr.io/webassembly/wasi-logging" digest = "sha256:a1b2c3d4e5f6789012345678901234567890abcdef1234567890abcdef123456" [[package]] name = "wasi:key-value" version = "2.0.0" registry = "ghcr.io/webassembly/wasi-key-value" digest = "sha256:b2c3d4e5f67890123456789012345678901abcdef2345678901abcdef2345678" [[package.dependencies]] name = "wasi:logging" version = "1.0.0" "#; let lockfile: Lockfile = toml::from_str(toml).expect("Failed to parse lockfile"); assert_eq!(lockfile.version, 1); assert_eq!(lockfile.packages.len(), 2); let logging = &lockfile.packages[0]; assert_eq!(logging.name, "wasi:logging"); assert_eq!(logging.version, "1.0.0"); assert_eq!(logging.registry, "ghcr.io/webassembly/wasi-logging"); assert!(logging.digest.starts_with("sha256:")); let key_value = &lockfile.packages[1]; assert_eq!(key_value.name, "wasi:key-value"); assert_eq!(key_value.version, "2.0.0"); assert_eq!(key_value.dependencies.len(), 1); assert_eq!(key_value.dependencies[0].name, "wasi:logging"); assert_eq!(key_value.dependencies[0].version, "1.0.0"); } #[test] fn test_serialize_lockfile() { let lockfile = Lockfile { version: 1, packages: vec![ Package { name: "wasi:logging".to_string(), version: "1.0.0".to_string(), registry: "ghcr.io/webassembly/wasi-logging".to_string(), digest: "sha256:abc123".to_string(), dependencies: vec![], }, Package { name: "wasi:key-value".to_string(), version: "2.0.0".to_string(), registry: "ghcr.io/webassembly/wasi-key-value".to_string(), digest: "sha256:def456".to_string(), dependencies: vec![PackageDependency { name: "wasi:logging".to_string(), version: "1.0.0".to_string(), }], }, ], }; let toml = toml::to_string(&lockfile).expect("Failed to serialize lockfile"); assert!(toml.contains("version = 1")); assert!(toml.contains("wasi:logging")); assert!(toml.contains("wasi:key-value")); assert!(toml.contains("sha256:abc123")); } #[test] fn test_package_without_dependencies() { let toml = r#" version = 1 [[package]] name = "wasi:logging" version = "1.0.0" registry = "ghcr.io/webassembly/wasi-logging" digest = "sha256:abc123" "#; let lockfile: Lockfile = toml::from_str(toml).expect("Failed to parse lockfile"); assert_eq!(lockfile.packages.len(), 1); assert_eq!(lockfile.packages[0].dependencies.len(), 0); } #[test] fn test_serialize_package_without_dependencies() { let package = Package { name: "wasi:logging".to_string(), version: "1.0.0".to_string(), registry: "ghcr.io/webassembly/wasi-logging".to_string(), digest: "sha256:abc123".to_string(), dependencies: vec![], }; let toml = toml::to_string(&package).expect("Failed to serialize package"); // Empty dependencies should be skipped assert!(!toml.contains("dependencies")); } }
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/manifest/src/manifest.rs
Rust
//! Types for the WASM manifest file (`wasm.toml`). use serde::{Deserialize, Serialize}; use std::collections::HashMap; /// The root manifest structure for a WASM package. /// /// The manifest file (`deps/wasm.toml`) defines dependencies for a WASM package. /// /// # Example /// /// ```toml /// [dependencies] /// "wasi:logging" = "ghcr.io/webassembly/wasi-logging:1.0.0" /// ``` #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[must_use] pub struct Manifest { /// The dependencies section of the manifest. #[serde(default)] pub dependencies: HashMap<String, Dependency>, } /// A dependency specification in the manifest. /// /// Dependencies can be specified in two formats: /// /// 1. Compact format (string): /// ```toml /// [dependencies] /// "wasi:logging" = "ghcr.io/webassembly/wasi-logging:1.0.0" /// ``` /// /// 2. Explicit format (table): /// ```toml /// [dependencies."wasi:logging"] /// registry = "ghcr.io" /// namespace = "webassembly" /// package = "wasi-logging" /// version = "1.0.0" /// ``` #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(untagged)] #[must_use] pub enum Dependency { /// Compact format: a single string with full registry path and version. /// /// Format: `registry/namespace/package:version` /// /// # Example /// ```text /// "ghcr.io/webassembly/wasi-logging:1.0.0" /// ``` Compact(String), /// Explicit format: a table with individual fields. Explicit { /// The registry host (e.g., "ghcr.io"). registry: String, /// The namespace or organization (e.g., "webassembly"). namespace: String, /// The package name (e.g., "wasi-logging"). package: String, /// The package version (e.g., "1.0.0"). version: String, }, } #[cfg(test)] mod tests { use super::*; #[test] fn test_parse_compact_format() { let toml = r#" [dependencies] "wasi:logging" = "ghcr.io/webassembly/wasi-logging:1.0.0" "wasi:key-value" = "ghcr.io/webassembly/wasi-key-value:2.0.0" "#; let manifest: Manifest = toml::from_str(toml).expect("Failed to parse manifest"); assert_eq!(manifest.dependencies.len(), 2); assert!(manifest.dependencies.contains_key("wasi:logging")); assert!(manifest.dependencies.contains_key("wasi:key-value")); match &manifest.dependencies["wasi:logging"] { Dependency::Compact(s) => { assert_eq!(s, "ghcr.io/webassembly/wasi-logging:1.0.0"); } _ => panic!("Expected compact format"), } } #[test] fn test_parse_explicit_format() { let toml = r#" [dependencies."wasi:logging"] registry = "ghcr.io" namespace = "webassembly" package = "wasi-logging" version = "1.0.0" [dependencies."wasi:key-value"] registry = "ghcr.io" namespace = "webassembly" package = "wasi-key-value" version = "2.0.0" "#; let manifest: Manifest = toml::from_str(toml).expect("Failed to parse manifest"); assert_eq!(manifest.dependencies.len(), 2); match &manifest.dependencies["wasi:logging"] { Dependency::Explicit { registry, namespace, package, version, } => { assert_eq!(registry, "ghcr.io"); assert_eq!(namespace, "webassembly"); assert_eq!(package, "wasi-logging"); assert_eq!(version, "1.0.0"); } _ => panic!("Expected explicit format"), } } #[test] fn test_serialize_compact_format() { let mut dependencies = HashMap::new(); dependencies.insert( "wasi:logging".to_string(), Dependency::Compact("ghcr.io/webassembly/wasi-logging:1.0.0".to_string()), ); let manifest = Manifest { dependencies }; let toml = toml::to_string(&manifest).expect("Failed to serialize manifest"); assert!(toml.contains("wasi:logging")); assert!(toml.contains("ghcr.io/webassembly/wasi-logging:1.0.0")); } #[test] fn test_serialize_explicit_format() { let mut dependencies = HashMap::new(); dependencies.insert( "wasi:logging".to_string(), Dependency::Explicit { registry: "ghcr.io".to_string(), namespace: "webassembly".to_string(), package: "wasi-logging".to_string(), version: "1.0.0".to_string(), }, ); let manifest = Manifest { dependencies }; let toml = toml::to_string(&manifest).expect("Failed to serialize manifest"); assert!(toml.contains("wasi:logging")); assert!(toml.contains("registry")); assert!(toml.contains("ghcr.io")); } #[test] fn test_empty_manifest() { let toml = r#""#; let manifest: Manifest = toml::from_str(toml).expect("Failed to parse empty manifest"); assert_eq!(manifest.dependencies.len(), 0); } }
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/manifest/src/validation.rs
Rust
//! Validation functions for manifest and lockfile consistency. use crate::{Lockfile, Manifest}; use std::collections::HashSet; /// Error type for validation failures. #[derive(Debug, Clone, PartialEq, Eq)] #[must_use] pub enum ValidationError { /// A package in the lockfile is not present in the manifest. MissingDependency { /// The name of the missing package. name: String, }, /// A package dependency references a package that doesn't exist in the lockfile. InvalidDependency { /// The package that has the invalid dependency. package: String, /// The name of the dependency that doesn't exist. dependency: String, }, } impl std::fmt::Display for ValidationError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { ValidationError::MissingDependency { name } => { write!( f, "Package '{}' is in the lockfile but not in the manifest", name ) } ValidationError::InvalidDependency { package, dependency, } => { write!( f, "Package '{}' depends on '{}' which doesn't exist in the lockfile", package, dependency ) } } } } impl std::error::Error for ValidationError {} /// Validates that a lockfile is consistent with its manifest. /// /// This function checks that: /// - All packages in the lockfile have corresponding entries in the manifest /// - All package dependencies reference packages that exist in the lockfile /// /// # Example /// /// ```rust /// use wasm_manifest::{Manifest, Lockfile, validate}; /// /// let manifest_toml = r#" /// [dependencies] /// "wasi:logging" = "ghcr.io/webassembly/wasi-logging:1.0.0" /// "#; /// /// let lockfile_toml = r#" /// version = 1 /// /// [[package]] /// name = "wasi:logging" /// version = "1.0.0" /// registry = "ghcr.io/webassembly/wasi-logging" /// digest = "sha256:abc123" /// "#; /// /// let manifest: Manifest = toml::from_str(manifest_toml).unwrap(); /// let lockfile: Lockfile = toml::from_str(lockfile_toml).unwrap(); /// /// assert!(validate(&manifest, &lockfile).is_ok()); /// ``` /// /// # Errors /// /// Returns a vector of `ValidationError` if validation fails. An empty vector /// indicates successful validation. pub fn validate(manifest: &Manifest, lockfile: &Lockfile) -> Result<(), Vec<ValidationError>> { let mut errors = Vec::new(); // Build a set of package names from the lockfile for quick lookup let lockfile_packages: HashSet<&str> = lockfile.packages.iter().map(|p| p.name.as_str()).collect(); // Check that all packages in the lockfile exist in the manifest for package in &lockfile.packages { if !manifest.dependencies.contains_key(&package.name) { errors.push(ValidationError::MissingDependency { name: package.name.clone(), }); } // Check that all dependencies of this package exist in the lockfile for dep in &package.dependencies { if !lockfile_packages.contains(dep.name.as_str()) { errors.push(ValidationError::InvalidDependency { package: package.name.clone(), dependency: dep.name.clone(), }); } } } if errors.is_empty() { Ok(()) } else { Err(errors) } } #[cfg(test)] mod tests { use super::*; use crate::{Dependency, Package, PackageDependency}; use std::collections::HashMap; #[test] fn test_validate_success() { let mut dependencies = HashMap::new(); dependencies.insert( "wasi:logging".to_string(), Dependency::Compact("ghcr.io/webassembly/wasi-logging:1.0.0".to_string()), ); dependencies.insert( "wasi:key-value".to_string(), Dependency::Compact("ghcr.io/webassembly/wasi-key-value:2.0.0".to_string()), ); let manifest = Manifest { dependencies }; let lockfile = Lockfile { version: 1, packages: vec![ Package { name: "wasi:logging".to_string(), version: "1.0.0".to_string(), registry: "ghcr.io/webassembly/wasi-logging".to_string(), digest: "sha256:abc123".to_string(), dependencies: vec![], }, Package { name: "wasi:key-value".to_string(), version: "2.0.0".to_string(), registry: "ghcr.io/webassembly/wasi-key-value".to_string(), digest: "sha256:def456".to_string(), dependencies: vec![PackageDependency { name: "wasi:logging".to_string(), version: "1.0.0".to_string(), }], }, ], }; assert!(validate(&manifest, &lockfile).is_ok()); } #[test] fn test_validate_missing_dependency() { let mut dependencies = HashMap::new(); dependencies.insert( "wasi:logging".to_string(), Dependency::Compact("ghcr.io/webassembly/wasi-logging:1.0.0".to_string()), ); // Missing wasi:key-value in manifest let manifest = Manifest { dependencies }; let lockfile = Lockfile { version: 1, packages: vec![ Package { name: "wasi:logging".to_string(), version: "1.0.0".to_string(), registry: "ghcr.io/webassembly/wasi-logging".to_string(), digest: "sha256:abc123".to_string(), dependencies: vec![], }, Package { name: "wasi:key-value".to_string(), version: "2.0.0".to_string(), registry: "ghcr.io/webassembly/wasi-key-value".to_string(), digest: "sha256:def456".to_string(), dependencies: vec![], }, ], }; let result = validate(&manifest, &lockfile); assert!(result.is_err()); let errors = result.unwrap_err(); assert_eq!(errors.len(), 1); assert_eq!( errors[0], ValidationError::MissingDependency { name: "wasi:key-value".to_string() } ); } #[test] fn test_validate_invalid_dependency() { let mut dependencies = HashMap::new(); dependencies.insert( "wasi:logging".to_string(), Dependency::Compact("ghcr.io/webassembly/wasi-logging:1.0.0".to_string()), ); dependencies.insert( "wasi:key-value".to_string(), Dependency::Compact("ghcr.io/webassembly/wasi-key-value:2.0.0".to_string()), ); let manifest = Manifest { dependencies }; let lockfile = Lockfile { version: 1, packages: vec![ Package { name: "wasi:logging".to_string(), version: "1.0.0".to_string(), registry: "ghcr.io/webassembly/wasi-logging".to_string(), digest: "sha256:abc123".to_string(), dependencies: vec![], }, Package { name: "wasi:key-value".to_string(), version: "2.0.0".to_string(), registry: "ghcr.io/webassembly/wasi-key-value".to_string(), digest: "sha256:def456".to_string(), dependencies: vec![ PackageDependency { name: "wasi:logging".to_string(), version: "1.0.0".to_string(), }, PackageDependency { name: "wasi:http".to_string(), // This package doesn't exist version: "1.0.0".to_string(), }, ], }, ], }; let result = validate(&manifest, &lockfile); assert!(result.is_err()); let errors = result.unwrap_err(); assert_eq!(errors.len(), 1); assert_eq!( errors[0], ValidationError::InvalidDependency { package: "wasi:key-value".to_string(), dependency: "wasi:http".to_string() } ); } #[test] fn test_validate_empty() { let manifest = Manifest { dependencies: HashMap::new(), }; let lockfile = Lockfile { version: 1, packages: vec![], }; assert!(validate(&manifest, &lockfile).is_ok()); } #[test] fn test_validation_error_display() { let err1 = ValidationError::MissingDependency { name: "wasi:logging".to_string(), }; assert_eq!( err1.to_string(), "Package 'wasi:logging' is in the lockfile but not in the manifest" ); let err2 = ValidationError::InvalidDependency { package: "wasi:key-value".to_string(), dependency: "wasi:http".to_string(), }; assert_eq!( err2.to_string(), "Package 'wasi:key-value' depends on 'wasi:http' which doesn't exist in the lockfile" ); } }
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/package-manager/src/lib.rs
Rust
//! A package manager for WebAssembly components. //! //! This crate provides functionality to pull, store, and manage WebAssembly //! component packages from OCI registries. mod manager; mod network; mod storage; pub use manager::Manager; pub use oci_client::Reference; pub use storage::{ImageEntry, InsertResult, KnownPackage, StateInfo, WitInterface}; /// Format a byte size as a human-readable string (B, KB, MB, GB). #[must_use] pub fn format_size(bytes: u64) -> String { const KB: u64 = 1024; const MB: u64 = KB * 1024; const GB: u64 = MB * 1024; if bytes >= GB { format!("{:.2} GB", bytes as f64 / GB as f64) } else if bytes >= MB { format!("{:.2} MB", bytes as f64 / MB as f64) } else if bytes >= KB { format!("{:.2} KB", bytes as f64 / KB as f64) } else { format!("{} B", bytes) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_format_size_bytes() { assert_eq!(format_size(0), "0 B"); assert_eq!(format_size(1), "1 B"); assert_eq!(format_size(512), "512 B"); assert_eq!(format_size(1023), "1023 B"); } #[test] fn test_format_size_kilobytes() { assert_eq!(format_size(1024), "1.00 KB"); assert_eq!(format_size(1536), "1.50 KB"); assert_eq!(format_size(2048), "2.00 KB"); assert_eq!(format_size(1024 * 1023), "1023.00 KB"); } #[test] fn test_format_size_megabytes() { assert_eq!(format_size(1024 * 1024), "1.00 MB"); assert_eq!(format_size(1024 * 1024 + 512 * 1024), "1.50 MB"); assert_eq!(format_size(1024 * 1024 * 100), "100.00 MB"); } #[test] fn test_format_size_gigabytes() { assert_eq!(format_size(1024 * 1024 * 1024), "1.00 GB"); assert_eq!(format_size(1024 * 1024 * 1024 * 2), "2.00 GB"); assert_eq!( format_size(1024 * 1024 * 1024 + 512 * 1024 * 1024), "1.50 GB" ); } }
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/package-manager/src/manager/mod.rs
Rust
use oci_client::Reference; use crate::network::Client; use crate::storage::{ImageEntry, InsertResult, KnownPackage, StateInfo, Store, WitInterface}; /// A cache on disk #[derive(Debug)] pub struct Manager { client: Client, store: Store, offline: bool, } impl Manager { /// Create a new store at a location on disk. /// /// This may return an error if it fails to create the cache location on disk. pub async fn open() -> anyhow::Result<Self> { Self::open_with_offline(false).await } /// Create a new Manager at a location on disk with offline mode. /// /// When offline is true, network operations will fail with an error. /// This may return an error if it fails to create the cache location on disk. pub async fn open_offline() -> anyhow::Result<Self> { Self::open_with_offline(true).await } /// Create a new Manager with the specified offline mode. async fn open_with_offline(offline: bool) -> anyhow::Result<Self> { let client = Client::new(); let store = Store::open().await?; Ok(Self { client, store, offline, }) } /// Returns whether the manager is in offline mode. #[must_use] pub fn is_offline(&self) -> bool { self.offline } // /// Create a new store at a location on disk. // /// // /// This may return an error if it fails to create the cache location on disk. // pub async fn with_config(config: Config) -> anyhow::Result<Self> { // let client = Client::new(); // let store = Store::open().await?; // Ok(Self { client, store }) // } /// Pull a package from the registry. /// Returns the insert result indicating whether the package was newly inserted /// or already existed in the database. /// /// This method also fetches all related tags for the package and stores them /// as known packages for discovery purposes. /// /// # Errors /// /// Returns an error if offline mode is enabled. pub async fn pull(&self, reference: Reference) -> anyhow::Result<InsertResult> { if self.offline { anyhow::bail!("cannot pull packages in offline mode"); } let image = self.client.pull(&reference).await?; let result = self.store.insert(&reference, image).await?; // Add to known packages when pulling (with tag if present) self.store.add_known_package( reference.registry(), reference.repository(), reference.tag(), None, )?; // Fetch all related tags and store them as known packages if let Ok(tags) = self.client.list_tags(&reference).await { for tag in tags { self.store.add_known_package( reference.registry(), reference.repository(), Some(&tag), None, )?; } } Ok(result) } /// List all stored images and their metadata. pub fn list_all(&self) -> anyhow::Result<Vec<ImageEntry>> { self.store.list_all() } /// Get data from the store pub async fn get(&self, key: &str) -> cacache::Result<Vec<u8>> { cacache::read(self.store.state_info.store_dir(), key).await } /// Get information about the current state of the package manager. pub fn state_info(&self) -> StateInfo { self.store.state_info.clone() } /// Delete an image from the store by its reference. pub async fn delete(&self, reference: Reference) -> anyhow::Result<bool> { self.store.delete(&reference).await } /// Search for known packages by query string. /// Searches in both registry and repository fields. pub fn search_packages(&self, query: &str) -> anyhow::Result<Vec<KnownPackage>> { self.store.search_known_packages(query) } /// Get all known packages. pub fn list_known_packages(&self) -> anyhow::Result<Vec<KnownPackage>> { self.store.list_known_packages() } /// Add or update a known package entry. pub fn add_known_package( &self, registry: &str, repository: &str, tag: Option<&str>, description: Option<&str>, ) -> anyhow::Result<()> { self.store .add_known_package(registry, repository, tag, description) } /// List all tags for a given reference from the registry. /// /// In offline mode, returns cached tags from the local database instead of /// fetching from the registry. pub async fn list_tags(&self, reference: &Reference) -> anyhow::Result<Vec<String>> { if self.offline { // Return cached tags from known packages return self.list_cached_tags(reference); } self.client.list_tags(reference).await } /// List tags from the local cache for a given reference. /// /// This is a private helper method used by `list_tags` when in offline mode. /// Returns all cached tags (release, signature, and attestation) for the given /// reference from the local known packages database. fn list_cached_tags(&self, reference: &Reference) -> anyhow::Result<Vec<String>> { let known_packages = self.store.list_known_packages()?; let tags: Vec<String> = known_packages .into_iter() .filter(|pkg| { pkg.registry == reference.registry() && pkg.repository == reference.repository() }) .flat_map(|pkg| { // Combine all tag types: release, signature, and attestation pkg.tags .into_iter() .chain(pkg.signature_tags) .chain(pkg.attestation_tags) }) .collect(); Ok(tags) } /// Re-scan known package tags to update derived data (e.g., tag types). /// This should be called after migrations that affect tag classification logic /// (e.g., when tag type rules change from .sig/.att suffixes). /// Returns the number of tags that were updated. pub fn rescan_known_package_tags(&self) -> anyhow::Result<usize> { self.store.rescan_known_package_tags() } /// Get all WIT interfaces with their associated component references. pub fn list_wit_interfaces_with_components( &self, ) -> anyhow::Result<Vec<(WitInterface, String)>> { self.store.list_wit_interfaces_with_components() } }
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/package-manager/src/network/client.rs
Rust
use docker_credential::DockerCredential; use oci_client::Reference; use oci_client::client::{ClientConfig, ClientProtocol, ImageData}; use oci_client::secrets::RegistryAuth; use oci_wasm::WasmClient; pub(crate) struct Client { inner: WasmClient, } impl std::fmt::Debug for Client { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Client").finish_non_exhaustive() } } impl Client { pub(crate) fn new() -> Self { let config = ClientConfig { protocol: ClientProtocol::Https, ..Default::default() }; let client = WasmClient::new(oci_client::Client::new(config)); Self { inner: client } } pub(crate) async fn pull(&self, reference: &Reference) -> anyhow::Result<ImageData> { let auth = resolve_auth(reference)?; let image = self.inner.pull(reference, &auth).await?; Ok(image) } /// Fetches all tags for a given reference from the registry. /// /// This method handles pagination automatically, fetching all available tags /// by making multiple requests if necessary. pub(crate) async fn list_tags(&self, reference: &Reference) -> anyhow::Result<Vec<String>> { let auth = resolve_auth(reference)?; let mut all_tags = Vec::new(); let mut last: Option<String> = None; loop { // Some registries return null for tags instead of an empty array, // which causes deserialization to fail. We handle this gracefully. let response = match self .inner .list_tags(reference, &auth, None, last.as_deref()) .await { Ok(resp) => resp, Err(_) if all_tags.is_empty() => { // First request failed, likely due to null tags - return empty return Ok(Vec::new()); } Err(_) => { // Subsequent request failed, return what we have break; } }; if response.tags.is_empty() { break; } last = response.tags.last().cloned(); all_tags.extend(response.tags); // If we got fewer tags than a typical page size, we're done // The API doesn't provide a "next" link, so we detect the end // by checking if the last tag changed if last.is_none() { break; } // Make another request to check if there are more tags let next_response = match self .inner .list_tags(reference, &auth, Some(1), last.as_deref()) .await { Ok(resp) => resp, Err(_) => break, }; if next_response.tags.is_empty() { break; } } Ok(all_tags) } } fn resolve_auth(reference: &Reference) -> anyhow::Result<RegistryAuth> { // NOTE: copied approach from https://github.com/bytecodealliance/wasm-pkg-tools/blob/48c28825a7dfb585b3fe1d42be65fe73a17d84fe/crates/wkg/src/oci.rs#L59-L66 let server_url = match reference.resolve_registry() { "index.docker.io" => "https://index.docker.io/v1/", // Default registry uses this key. other => other, // All other registries are keyed by their domain name without the `https://` prefix or any path suffix. }; match docker_credential::get_credential(server_url) { Ok(DockerCredential::UsernamePassword(username, password)) => { Ok(RegistryAuth::Basic(username, password)) } Ok(DockerCredential::IdentityToken(_)) => { Err(anyhow::anyhow!("identity tokens not supported")) } Err(_) => Ok(RegistryAuth::Anonymous), } }
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/package-manager/src/network/mod.rs
Rust
mod client; pub(crate) use client::Client;
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/package-manager/src/storage/config.rs
Rust
use anyhow::Context; use std::env; use std::path::{Path, PathBuf}; use super::models::Migrations; /// Information about the current state of the package manager. #[derive(Debug, Clone)] pub struct StateInfo { /// Path to the current executable executable: PathBuf, /// Path to the data storage directory data_dir: PathBuf, /// Path to the content-addressable store directory store_dir: PathBuf, /// Size of the store directory in bytes store_size: u64, /// Path to the metadata database file metadata_file: PathBuf, /// Size of the metadata file in bytes metadata_size: u64, /// Current migration version migration_current: u32, /// Total number of migrations available migration_total: u32, } impl StateInfo { /// Create a new StateInfo instance. pub fn new( migration_info: Migrations, store_size: u64, metadata_size: u64, ) -> anyhow::Result<Self> { let data_dir = dirs::data_local_dir() .context("No local data dir known for the current OS")? .join("wasm"); Ok(Self::new_at( data_dir, migration_info, store_size, metadata_size, )) } /// Create a new StateInfo instance at a specific data directory. #[must_use] pub fn new_at( data_dir: PathBuf, migration_info: Migrations, store_size: u64, metadata_size: u64, ) -> Self { Self { executable: env::current_exe().unwrap_or_else(|_| PathBuf::from("unknown")), store_dir: data_dir.join("store"), store_size, metadata_file: data_dir.join("db").join("metadata.db3"), metadata_size, data_dir, migration_current: migration_info.current, migration_total: migration_info.total, } } /// Get the path to the current executable #[must_use] pub fn executable(&self) -> &Path { &self.executable } /// Get the location of the crate's data dir #[must_use] pub fn data_dir(&self) -> &Path { &self.data_dir } /// Get the location of the crate's content-addressable store #[must_use] pub fn store_dir(&self) -> &Path { &self.store_dir } /// Get the size of the store directory in bytes #[must_use] pub fn store_size(&self) -> u64 { self.store_size } /// Get the location of the crate's metadata file #[must_use] pub fn metadata_file(&self) -> &Path { &self.metadata_file } /// Get the size of the metadata file in bytes #[must_use] pub fn metadata_size(&self) -> u64 { self.metadata_size } /// Get the current migration version #[must_use] pub fn migration_current(&self) -> u32 { self.migration_current } /// Get the total number of migrations available #[must_use] pub fn migration_total(&self) -> u32 { self.migration_total } /// Creates a new StateInfo for testing purposes. #[cfg(any(test, feature = "test-helpers"))] #[must_use] pub fn new_for_testing() -> Self { Self { executable: PathBuf::from("/usr/local/bin/wasm"), data_dir: PathBuf::from("/home/user/.local/share/wasm"), store_dir: PathBuf::from("/home/user/.local/share/wasm/store"), store_size: 1024 * 1024 * 10, // 10 MB metadata_file: PathBuf::from("/home/user/.local/share/wasm/db/metadata.db3"), metadata_size: 1024 * 64, // 64 KB migration_current: 3, migration_total: 3, } } } #[cfg(test)] mod tests { use super::*; use std::path::PathBuf; fn test_migrations() -> Migrations { Migrations { current: 3, total: 5, } } #[test] fn test_state_info_new_at() { let data_dir = PathBuf::from("/test/data"); let state_info = StateInfo::new_at(data_dir.clone(), test_migrations(), 1024, 512); assert_eq!(state_info.data_dir(), data_dir); assert_eq!(state_info.store_dir(), data_dir.join("store")); assert_eq!( state_info.metadata_file(), data_dir.join("db").join("metadata.db3") ); assert_eq!(state_info.store_size(), 1024); assert_eq!(state_info.metadata_size(), 512); assert_eq!(state_info.migration_current(), 3); assert_eq!(state_info.migration_total(), 5); } #[test] fn test_state_info_executable() { let data_dir = PathBuf::from("/test/data"); let state_info = StateInfo::new_at(data_dir, test_migrations(), 0, 0); // executable() should return something (either the actual exe or "unknown") let exe = state_info.executable(); assert!(!exe.as_os_str().is_empty()); } #[test] fn test_state_info_sizes() { let data_dir = PathBuf::from("/test/data"); // Test with various sizes let state_info = StateInfo::new_at(data_dir.clone(), test_migrations(), 0, 0); assert_eq!(state_info.store_size(), 0); assert_eq!(state_info.metadata_size(), 0); let state_info = StateInfo::new_at(data_dir.clone(), test_migrations(), 1024 * 1024, 1024); assert_eq!(state_info.store_size(), 1024 * 1024); assert_eq!(state_info.metadata_size(), 1024); } }
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/package-manager/src/storage/migrations/00_migrations.sql
SQL
CREATE TABLE IF NOT EXISTS migrations ( id INTEGER PRIMARY KEY, version INTEGER NOT NULL UNIQUE, applied_at TEXT NOT NULL DEFAULT (datetime('now')) );
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/package-manager/src/storage/migrations/01_init.sql
SQL
-- DROP TABLE IF EXISTS image; CREATE TABLE IF NOT EXISTS image ( id INTEGER PRIMARY KEY, ref_registry TEXT NOT NULL, ref_repository TEXT NOT NULL, ref_mirror_registry TEXT, ref_tag TEXT, ref_digest TEXT, manifest TEXT NOT NULL );
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/package-manager/src/storage/migrations/02_known_packages.sql
SQL
-- Table for known packages that persists even after local deletion -- This tracks packages the user has seen/searched for CREATE TABLE IF NOT EXISTS known_package ( id INTEGER PRIMARY KEY, registry TEXT NOT NULL, repository TEXT NOT NULL, description TEXT, last_seen_at TEXT NOT NULL DEFAULT (datetime('now')), created_at TEXT NOT NULL DEFAULT (datetime('now')), -- Ensure unique package per registry/repository combination UNIQUE(registry, repository) ); -- Index for faster searches CREATE INDEX IF NOT EXISTS idx_known_package_repository ON known_package(repository); CREATE INDEX IF NOT EXISTS idx_known_package_registry ON known_package(registry);
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/package-manager/src/storage/migrations/03_known_package_tags.sql
SQL
-- Table for tags associated with known packages CREATE TABLE IF NOT EXISTS known_package_tag ( id INTEGER PRIMARY KEY, known_package_id INTEGER NOT NULL, tag TEXT NOT NULL, last_seen_at TEXT NOT NULL DEFAULT (datetime('now')), created_at TEXT NOT NULL DEFAULT (datetime('now')), FOREIGN KEY (known_package_id) REFERENCES known_package(id) ON DELETE CASCADE, UNIQUE(known_package_id, tag) ); -- Index for faster tag lookups CREATE INDEX IF NOT EXISTS idx_known_package_tag_package_id ON known_package_tag(known_package_id);
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/package-manager/src/storage/migrations/04_image_size.sql
SQL
-- Add size_on_disk column to track the storage size of each image ALTER TABLE image ADD COLUMN size_on_disk INTEGER NOT NULL DEFAULT 0;
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/package-manager/src/storage/migrations/05_tag_type.sql
SQL
-- Add tag_type column to distinguish regular tags from signatures and attestations ALTER TABLE known_package_tag ADD COLUMN tag_type TEXT NOT NULL DEFAULT 'release'; -- Update existing signature and attestation tags UPDATE known_package_tag SET tag_type = 'signature' WHERE tag LIKE '%.sig'; UPDATE known_package_tag SET tag_type = 'attestation' WHERE tag LIKE '%.att';
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/package-manager/src/storage/migrations/06_wit_interface.sql
SQL
-- WIT Interface storage tables -- Store extracted WIT interface text for each component CREATE TABLE IF NOT EXISTS wit_interface ( id INTEGER PRIMARY KEY, -- The WIT text representation (full WIT document) wit_text TEXT NOT NULL, -- Parsed world name if available world_name TEXT, -- Number of imports in the interface import_count INTEGER NOT NULL DEFAULT 0, -- Number of exports in the interface export_count INTEGER NOT NULL DEFAULT 0, -- Timestamp when this was extracted created_at TEXT NOT NULL DEFAULT (datetime('now')) ); -- Link table between images and their WIT interfaces -- An image can have one WIT interface -- A WIT interface can be shared by multiple images (content-addressable) CREATE TABLE IF NOT EXISTS image_wit_interface ( image_id INTEGER NOT NULL, wit_interface_id INTEGER NOT NULL, PRIMARY KEY (image_id, wit_interface_id), FOREIGN KEY (image_id) REFERENCES image(id) ON DELETE CASCADE, FOREIGN KEY (wit_interface_id) REFERENCES wit_interface(id) ON DELETE CASCADE ); -- Index for looking up interfaces by image CREATE INDEX IF NOT EXISTS idx_image_wit_interface_image_id ON image_wit_interface(image_id); -- Index for looking up images by interface CREATE INDEX IF NOT EXISTS idx_image_wit_interface_wit_interface_id ON image_wit_interface(wit_interface_id);
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/package-manager/src/storage/migrations/07_package_name.sql
SQL
-- Add package_name column to wit_interface table ALTER TABLE wit_interface ADD COLUMN package_name TEXT; -- Create index for package_name lookups CREATE INDEX IF NOT EXISTS idx_wit_interface_package_name ON wit_interface(package_name);
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/package-manager/src/storage/mod.rs
Rust
mod config; mod models; mod store; mod wit_parser; pub use config::StateInfo; pub use models::ImageEntry; pub use models::InsertResult; pub use models::KnownPackage; pub use models::WitInterface; pub(crate) use store::Store;
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/package-manager/src/storage/models/image_entry.rs
Rust
use oci_client::manifest::OciImageManifest; #[cfg(any(test, feature = "test-helpers"))] use oci_client::manifest::{IMAGE_MANIFEST_MEDIA_TYPE, OciDescriptor}; use rusqlite::Connection; /// Result of an insert operation. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum InsertResult { /// The entry was inserted successfully. Inserted, /// The entry already existed in the database. AlreadyExists, } /// Metadata for a stored OCI image. #[derive(Debug, Clone)] pub struct ImageEntry { #[allow(dead_code)] // Used in database schema id: i64, /// Registry hostname pub ref_registry: String, /// Repository path pub ref_repository: String, /// Optional mirror registry hostname pub ref_mirror_registry: Option<String>, /// Optional tag pub ref_tag: Option<String>, /// Optional digest pub ref_digest: Option<String>, /// OCI image manifest pub manifest: OciImageManifest, /// Size of the image on disk in bytes pub size_on_disk: u64, } impl ImageEntry { /// Returns the full reference string for this image (e.g., "ghcr.io/user/repo:tag"). #[must_use] pub fn reference(&self) -> String { let mut reference = format!("{}/{}", self.ref_registry, self.ref_repository); if let Some(tag) = &self.ref_tag { reference.push(':'); reference.push_str(tag); } else if let Some(digest) = &self.ref_digest { reference.push('@'); reference.push_str(digest); } reference } /// Checks if an image entry with the given reference already exists. pub(crate) fn exists( conn: &Connection, ref_registry: &str, ref_repository: &str, ref_tag: Option<&str>, ref_digest: Option<&str>, ) -> anyhow::Result<bool> { let count: i64 = match (ref_tag, ref_digest) { (Some(tag), Some(digest)) => conn.query_row( "SELECT COUNT(*) FROM image WHERE ref_registry = ?1 AND ref_repository = ?2 AND ref_tag = ?3 AND ref_digest = ?4", (ref_registry, ref_repository, tag, digest), |row| row.get(0), )?, (Some(tag), None) => conn.query_row( "SELECT COUNT(*) FROM image WHERE ref_registry = ?1 AND ref_repository = ?2 AND ref_tag = ?3 AND ref_digest IS NULL", (ref_registry, ref_repository, tag), |row| row.get(0), )?, (None, Some(digest)) => conn.query_row( "SELECT COUNT(*) FROM image WHERE ref_registry = ?1 AND ref_repository = ?2 AND ref_tag IS NULL AND ref_digest = ?3", (ref_registry, ref_repository, digest), |row| row.get(0), )?, (None, None) => conn.query_row( "SELECT COUNT(*) FROM image WHERE ref_registry = ?1 AND ref_repository = ?2 AND ref_tag IS NULL AND ref_digest IS NULL", (ref_registry, ref_repository), |row| row.get(0), )?, }; Ok(count > 0) } /// Inserts a new image entry into the database if it doesn't already exist. /// Returns `(InsertResult::AlreadyExists, None)` if the entry already exists, /// or `(InsertResult::Inserted, Some(id))` if it was successfully inserted. pub(crate) fn insert( conn: &Connection, ref_registry: &str, ref_repository: &str, ref_tag: Option<&str>, ref_digest: Option<&str>, manifest: &str, size_on_disk: u64, ) -> anyhow::Result<(InsertResult, Option<i64>)> { // Check if entry already exists if Self::exists(conn, ref_registry, ref_repository, ref_tag, ref_digest)? { return Ok((InsertResult::AlreadyExists, None)); } conn.execute( "INSERT INTO image (ref_registry, ref_repository, ref_tag, ref_digest, manifest, size_on_disk) VALUES (?1, ?2, ?3, ?4, ?5, ?6)", (ref_registry, ref_repository, ref_tag, ref_digest, manifest, size_on_disk as i64), )?; Ok((InsertResult::Inserted, Some(conn.last_insert_rowid()))) } /// Returns all currently stored images and their metadata, ordered alphabetically by repository. pub(crate) fn get_all(conn: &Connection) -> anyhow::Result<Vec<ImageEntry>> { let mut stmt = conn.prepare( "SELECT id, ref_registry, ref_repository, ref_mirror_registry, ref_tag, ref_digest, manifest, size_on_disk FROM image ORDER BY ref_repository ASC, ref_registry ASC", )?; let rows = stmt.query_map([], |row| { let manifest_json: String = row.get(6)?; let manifest: OciImageManifest = serde_json::from_str(&manifest_json).map_err(|e| { rusqlite::Error::FromSqlConversionFailure( 6, rusqlite::types::Type::Text, Box::new(e), ) })?; let size_on_disk: i64 = row.get(7)?; Ok(ImageEntry { id: row.get(0)?, ref_registry: row.get(1)?, ref_repository: row.get(2)?, ref_mirror_registry: row.get(3)?, ref_tag: row.get(4)?, ref_digest: row.get(5)?, manifest, size_on_disk: size_on_disk as u64, }) })?; let mut entries = Vec::new(); for row in rows { entries.push(row?); } Ok(entries) } /// Deletes an image entry by its full reference string. pub(crate) fn delete_by_reference( conn: &Connection, registry: &str, repository: &str, tag: Option<&str>, digest: Option<&str>, ) -> anyhow::Result<bool> { let rows_affected = match (tag, digest) { (Some(tag), Some(digest)) => conn.execute( "DELETE FROM image WHERE ref_registry = ?1 AND ref_repository = ?2 AND ref_tag = ?3 AND ref_digest = ?4", (registry, repository, tag, digest), )?, (Some(tag), None) => conn.execute( "DELETE FROM image WHERE ref_registry = ?1 AND ref_repository = ?2 AND ref_tag = ?3", (registry, repository, tag), )?, (None, Some(digest)) => conn.execute( "DELETE FROM image WHERE ref_registry = ?1 AND ref_repository = ?2 AND ref_digest = ?3", (registry, repository, digest), )?, (None, None) => conn.execute( "DELETE FROM image WHERE ref_registry = ?1 AND ref_repository = ?2", (registry, repository), )?, }; Ok(rows_affected > 0) } /// Creates a new ImageEntry for testing purposes. #[cfg(any(test, feature = "test-helpers"))] #[must_use] pub fn new_for_testing( ref_registry: String, ref_repository: String, ref_tag: Option<String>, ref_digest: Option<String>, size_on_disk: u64, ) -> Self { Self { id: 0, ref_registry, ref_repository, ref_mirror_registry: None, ref_tag, ref_digest, manifest: Self::test_manifest(), size_on_disk, } } /// Creates a minimal OCI image manifest with a single WASM layer for testing. /// /// The manifest uses placeholder digests and sizes that are valid but not /// representative of real content. #[cfg(any(test, feature = "test-helpers"))] fn test_manifest() -> OciImageManifest { OciImageManifest { schema_version: 2, media_type: Some(IMAGE_MANIFEST_MEDIA_TYPE.to_string()), config: OciDescriptor { media_type: "application/vnd.oci.image.config.v1+json".to_string(), digest: "sha256:abc123".to_string(), size: 100, urls: None, annotations: None, }, layers: vec![OciDescriptor { media_type: "application/wasm".to_string(), digest: "sha256:def456".to_string(), size: 1024, urls: None, annotations: None, }], artifact_type: None, annotations: None, subject: None, } } } #[cfg(test)] mod tests { use super::*; use crate::storage::models::Migrations; /// Create an in-memory database with migrations applied for testing. fn setup_test_db() -> Connection { let conn = Connection::open_in_memory().unwrap(); Migrations::run_all(&conn).unwrap(); conn } /// Create a minimal valid manifest JSON string for testing. fn test_manifest() -> String { r#"{"schemaVersion":2,"mediaType":"application/vnd.oci.image.manifest.v1+json","config":{"mediaType":"application/vnd.oci.image.config.v1+json","digest":"sha256:abc123","size":100},"layers":[]}"#.to_string() } // ========================================================================= // ImageEntry Tests // ========================================================================= #[test] fn test_image_entry_insert_new() { let conn = setup_test_db(); let result = ImageEntry::insert( &conn, "ghcr.io", "user/repo", Some("v1.0.0"), None, &test_manifest(), 1024, ) .unwrap(); assert_eq!(result.0, InsertResult::Inserted); assert!(result.1.is_some()); } #[test] fn test_image_entry_insert_duplicate() { let conn = setup_test_db(); // Insert first time let result1 = ImageEntry::insert( &conn, "ghcr.io", "user/repo", Some("v1.0.0"), None, &test_manifest(), 1024, ) .unwrap(); assert_eq!(result1.0, InsertResult::Inserted); assert!(result1.1.is_some()); // Insert duplicate let result2 = ImageEntry::insert( &conn, "ghcr.io", "user/repo", Some("v1.0.0"), None, &test_manifest(), 1024, ) .unwrap(); assert_eq!(result2.0, InsertResult::AlreadyExists); assert!(result2.1.is_none()); } #[test] fn test_image_entry_insert_different_tags() { let conn = setup_test_db(); // Insert with tag v1 let result1 = ImageEntry::insert( &conn, "ghcr.io", "user/repo", Some("v1.0.0"), None, &test_manifest(), 1024, ) .unwrap(); assert_eq!(result1.0, InsertResult::Inserted); assert!(result1.1.is_some()); // Insert with tag v2 - should succeed (different tag) let result2 = ImageEntry::insert( &conn, "ghcr.io", "user/repo", Some("v2.0.0"), None, &test_manifest(), 2048, ) .unwrap(); assert_eq!(result2.0, InsertResult::Inserted); assert!(result2.1.is_some()); // Verify both exist let entries = ImageEntry::get_all(&conn).unwrap(); assert_eq!(entries.len(), 2); } #[test] fn test_image_entry_exists() { let conn = setup_test_db(); // Initially doesn't exist assert!(!ImageEntry::exists(&conn, "ghcr.io", "user/repo", Some("v1.0.0"), None).unwrap()); // Insert ImageEntry::insert( &conn, "ghcr.io", "user/repo", Some("v1.0.0"), None, &test_manifest(), 1024, ) .unwrap(); // Now exists assert!(ImageEntry::exists(&conn, "ghcr.io", "user/repo", Some("v1.0.0"), None).unwrap()); // Different tag doesn't exist assert!(!ImageEntry::exists(&conn, "ghcr.io", "user/repo", Some("v2.0.0"), None).unwrap()); } #[test] fn test_image_entry_exists_with_digest() { let conn = setup_test_db(); // Insert with digest only ImageEntry::insert( &conn, "ghcr.io", "user/repo", None, Some("sha256:abc123"), &test_manifest(), 1024, ) .unwrap(); // Exists with digest assert!( ImageEntry::exists(&conn, "ghcr.io", "user/repo", None, Some("sha256:abc123")).unwrap() ); // Different digest doesn't exist assert!( !ImageEntry::exists(&conn, "ghcr.io", "user/repo", None, Some("sha256:def456")) .unwrap() ); } #[test] fn test_image_entry_exists_with_tag_and_digest() { let conn = setup_test_db(); // Insert with both tag and digest ImageEntry::insert( &conn, "ghcr.io", "user/repo", Some("v1.0.0"), Some("sha256:abc123"), &test_manifest(), 1024, ) .unwrap(); // Exists with both assert!( ImageEntry::exists( &conn, "ghcr.io", "user/repo", Some("v1.0.0"), Some("sha256:abc123") ) .unwrap() ); // Wrong digest doesn't match assert!( !ImageEntry::exists( &conn, "ghcr.io", "user/repo", Some("v1.0.0"), Some("sha256:wrong") ) .unwrap() ); } #[test] fn test_image_entry_get_all_empty() { let conn = setup_test_db(); let entries = ImageEntry::get_all(&conn).unwrap(); assert!(entries.is_empty()); } #[test] fn test_image_entry_get_all_ordered() { let conn = setup_test_db(); // Insert in non-alphabetical order ImageEntry::insert( &conn, "ghcr.io", "zebra/repo", Some("v1.0.0"), None, &test_manifest(), 1024, ) .unwrap(); ImageEntry::insert( &conn, "docker.io", "apple/repo", Some("latest"), None, &test_manifest(), 2048, ) .unwrap(); let entries = ImageEntry::get_all(&conn).unwrap(); assert_eq!(entries.len(), 2); // Should be ordered by repository ASC assert_eq!(entries[0].ref_repository, "apple/repo"); assert_eq!(entries[1].ref_repository, "zebra/repo"); } #[test] fn test_image_entry_delete_by_reference_with_tag() { let conn = setup_test_db(); // Insert ImageEntry::insert( &conn, "ghcr.io", "user/repo", Some("v1.0.0"), None, &test_manifest(), 1024, ) .unwrap(); // Delete let deleted = ImageEntry::delete_by_reference(&conn, "ghcr.io", "user/repo", Some("v1.0.0"), None) .unwrap(); assert!(deleted); // Verify gone assert!(ImageEntry::get_all(&conn).unwrap().is_empty()); } #[test] fn test_image_entry_delete_by_reference_not_found() { let conn = setup_test_db(); // Try to delete non-existent let deleted = ImageEntry::delete_by_reference( &conn, "ghcr.io", "nonexistent/repo", Some("v1.0.0"), None, ) .unwrap(); assert!(!deleted); } #[test] fn test_image_entry_delete_by_reference_with_digest() { let conn = setup_test_db(); // Insert with digest ImageEntry::insert( &conn, "ghcr.io", "user/repo", None, Some("sha256:abc123"), &test_manifest(), 1024, ) .unwrap(); // Delete by digest let deleted = ImageEntry::delete_by_reference( &conn, "ghcr.io", "user/repo", None, Some("sha256:abc123"), ) .unwrap(); assert!(deleted); assert!(ImageEntry::get_all(&conn).unwrap().is_empty()); } #[test] fn test_image_entry_delete_by_registry_repository_only() { let conn = setup_test_db(); // Insert multiple entries for same repo ImageEntry::insert( &conn, "ghcr.io", "user/repo", Some("v1.0.0"), None, &test_manifest(), 1024, ) .unwrap(); ImageEntry::insert( &conn, "ghcr.io", "user/repo", Some("v2.0.0"), None, &test_manifest(), 2048, ) .unwrap(); // Delete all by registry/repository only let deleted = ImageEntry::delete_by_reference(&conn, "ghcr.io", "user/repo", None, None).unwrap(); assert!(deleted); assert!(ImageEntry::get_all(&conn).unwrap().is_empty()); } #[test] fn test_image_entry_reference_with_tag() { let conn = setup_test_db(); ImageEntry::insert( &conn, "ghcr.io", "user/repo", Some("v1.0.0"), None, &test_manifest(), 1024, ) .unwrap(); let entries = ImageEntry::get_all(&conn).unwrap(); assert_eq!(entries[0].reference(), "ghcr.io/user/repo:v1.0.0"); } #[test] fn test_image_entry_reference_with_digest() { let conn = setup_test_db(); ImageEntry::insert( &conn, "ghcr.io", "user/repo", None, Some("sha256:abc123"), &test_manifest(), 1024, ) .unwrap(); let entries = ImageEntry::get_all(&conn).unwrap(); assert_eq!(entries[0].reference(), "ghcr.io/user/repo@sha256:abc123"); } #[test] fn test_image_entry_reference_plain() { let conn = setup_test_db(); ImageEntry::insert( &conn, "ghcr.io", "user/repo", None, None, &test_manifest(), 1024, ) .unwrap(); let entries = ImageEntry::get_all(&conn).unwrap(); assert_eq!(entries[0].reference(), "ghcr.io/user/repo"); } #[test] fn test_image_entry_size_on_disk() { let conn = setup_test_db(); ImageEntry::insert( &conn, "ghcr.io", "user/repo", Some("v1.0.0"), None, &test_manifest(), 12345678, ) .unwrap(); let entries = ImageEntry::get_all(&conn).unwrap(); assert_eq!(entries[0].size_on_disk, 12345678); } }
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/package-manager/src/storage/models/known_package.rs
Rust
use rusqlite::Connection; /// The type of a tag, used to distinguish release tags from signatures and attestations. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum TagType { /// A regular release tag (e.g., "1.0.0", "latest") Release, /// A signature tag (ending in ".sig") Signature, /// An attestation tag (ending in ".att") Attestation, } impl TagType { /// Determine the tag type from a tag string. pub(crate) fn from_tag(tag: &str) -> Self { if tag.ends_with(".sig") { TagType::Signature } else if tag.ends_with(".att") { TagType::Attestation } else { TagType::Release } } /// Convert to the database string representation. pub(crate) fn as_str(&self) -> &'static str { match self { TagType::Release => "release", TagType::Signature => "signature", TagType::Attestation => "attestation", } } } /// A known package that persists in the database even after local deletion. /// This is used to track packages the user has seen or searched for. #[derive(Debug, Clone)] pub struct KnownPackage { #[allow(dead_code)] id: i64, /// Registry hostname pub registry: String, /// Repository path pub repository: String, /// Optional package description pub description: Option<String>, /// Release tags (regular version tags like "1.0.0", "latest") pub tags: Vec<String>, /// Signature tags (tags ending in ".sig") pub signature_tags: Vec<String>, /// Attestation tags (tags ending in ".att") pub attestation_tags: Vec<String>, /// Timestamp of last seen pub last_seen_at: String, /// Timestamp of creation pub created_at: String, } impl KnownPackage { /// Returns the full reference string for this package (e.g., "ghcr.io/user/repo"). #[must_use] pub fn reference(&self) -> String { format!("{}/{}", self.registry, self.repository) } /// Returns the full reference string with the most recent tag. #[must_use] pub fn reference_with_tag(&self) -> String { if let Some(tag) = self.tags.first() { format!("{}:{}", self.reference(), tag) } else { format!("{}:latest", self.reference()) } } /// Inserts or updates a known package in the database. /// If the package already exists, updates the last_seen_at timestamp. /// Also adds the tag if provided, classifying it by type. pub(crate) fn upsert( conn: &Connection, registry: &str, repository: &str, tag: Option<&str>, description: Option<&str>, ) -> anyhow::Result<()> { conn.execute( "INSERT INTO known_package (registry, repository, description) VALUES (?1, ?2, ?3) ON CONFLICT(registry, repository) DO UPDATE SET last_seen_at = datetime('now'), description = COALESCE(excluded.description, known_package.description)", (registry, repository, description), )?; // If a tag was provided, add it to the tags table with its type if let Some(tag) = tag { let package_id: i64 = conn.query_row( "SELECT id FROM known_package WHERE registry = ?1 AND repository = ?2", (registry, repository), |row| row.get(0), )?; let tag_type = TagType::from_tag(tag); conn.execute( "INSERT INTO known_package_tag (known_package_id, tag, tag_type) VALUES (?1, ?2, ?3) ON CONFLICT(known_package_id, tag) DO UPDATE SET last_seen_at = datetime('now'), tag_type = ?3", (package_id, tag, tag_type.as_str()), )?; } Ok(()) } /// Helper to fetch tags for a package by its ID, separated by type. /// Returns (release_tags, signature_tags, attestation_tags). fn fetch_tags_by_type( conn: &Connection, package_id: i64, ) -> (Vec<String>, Vec<String>, Vec<String>) { let mut release_tags = Vec::new(); let mut signature_tags = Vec::new(); let mut attestation_tags = Vec::new(); let mut stmt = match conn.prepare( "SELECT tag, tag_type FROM known_package_tag WHERE known_package_id = ?1 ORDER BY last_seen_at DESC", ) { Ok(stmt) => stmt, Err(_) => return (release_tags, signature_tags, attestation_tags), }; let rows = match stmt.query_map([package_id], |row| { Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)) }) { Ok(rows) => rows, Err(_) => return (release_tags, signature_tags, attestation_tags), }; for row in rows.flatten() { let (tag, tag_type) = row; match tag_type.as_str() { "signature" => signature_tags.push(tag), "attestation" => attestation_tags.push(tag), _ => release_tags.push(tag), } } (release_tags, signature_tags, attestation_tags) } /// Search for known packages by a query string. /// Searches in both registry and repository fields. pub(crate) fn search(conn: &Connection, query: &str) -> anyhow::Result<Vec<KnownPackage>> { let search_pattern = format!("%{}%", query); let mut stmt = conn.prepare( "SELECT id, registry, repository, description, last_seen_at, created_at FROM known_package WHERE registry LIKE ?1 OR repository LIKE ?1 ORDER BY repository ASC, registry ASC LIMIT 100", )?; let rows = stmt.query_map([&search_pattern], |row| { let id: i64 = row.get(0)?; Ok(( id, row.get::<_, String>(1)?, row.get::<_, String>(2)?, row.get::<_, Option<String>>(3)?, row.get::<_, String>(4)?, row.get::<_, String>(5)?, )) })?; let mut packages = Vec::new(); for row in rows { let (id, registry, repository, description, last_seen_at, created_at) = row?; let (tags, signature_tags, attestation_tags) = Self::fetch_tags_by_type(conn, id); packages.push(KnownPackage { id, registry, repository, description, tags, signature_tags, attestation_tags, last_seen_at, created_at, }); } Ok(packages) } /// Get all known packages, ordered alphabetically by repository. pub(crate) fn get_all(conn: &Connection) -> anyhow::Result<Vec<KnownPackage>> { let mut stmt = conn.prepare( "SELECT id, registry, repository, description, last_seen_at, created_at FROM known_package ORDER BY repository ASC, registry ASC LIMIT 100", )?; let rows = stmt.query_map([], |row| { let id: i64 = row.get(0)?; Ok(( id, row.get::<_, String>(1)?, row.get::<_, String>(2)?, row.get::<_, Option<String>>(3)?, row.get::<_, String>(4)?, row.get::<_, String>(5)?, )) })?; let mut packages = Vec::new(); for row in rows { let (id, registry, repository, description, last_seen_at, created_at) = row?; let (tags, signature_tags, attestation_tags) = Self::fetch_tags_by_type(conn, id); packages.push(KnownPackage { id, registry, repository, description, tags, signature_tags, attestation_tags, last_seen_at, created_at, }); } Ok(packages) } /// Get a known package by registry and repository. #[allow(dead_code)] pub(crate) fn get( conn: &Connection, registry: &str, repository: &str, ) -> anyhow::Result<Option<KnownPackage>> { let mut stmt = conn.prepare( "SELECT id, registry, repository, description, last_seen_at, created_at FROM known_package WHERE registry = ?1 AND repository = ?2", )?; let mut rows = stmt.query_map([registry, repository], |row| { let id: i64 = row.get(0)?; Ok(( id, row.get::<_, String>(1)?, row.get::<_, String>(2)?, row.get::<_, Option<String>>(3)?, row.get::<_, String>(4)?, row.get::<_, String>(5)?, )) })?; match rows.next() { Some(row) => { let (id, registry, repository, description, last_seen_at, created_at) = row?; let (tags, signature_tags, attestation_tags) = Self::fetch_tags_by_type(conn, id); Ok(Some(KnownPackage { id, registry, repository, description, tags, signature_tags, attestation_tags, last_seen_at, created_at, })) } None => Ok(None), } } /// Creates a new KnownPackage for testing purposes. #[cfg(any(test, feature = "test-helpers"))] #[must_use] pub fn new_for_testing( registry: String, repository: String, description: Option<String>, tags: Vec<String>, signature_tags: Vec<String>, attestation_tags: Vec<String>, last_seen_at: String, created_at: String, ) -> Self { Self { id: 0, // Test ID registry, repository, description, tags, signature_tags, attestation_tags, last_seen_at, created_at, } } } #[cfg(test)] mod tests { use super::*; use crate::storage::models::Migrations; /// Create an in-memory database with migrations applied for testing. fn setup_test_db() -> Connection { let conn = Connection::open_in_memory().unwrap(); Migrations::run_all(&conn).unwrap(); conn } // ========================================================================= // TagType Tests // ========================================================================= #[test] fn test_tag_type_from_tag_release() { assert_eq!(TagType::from_tag("latest"), TagType::Release); assert_eq!(TagType::from_tag("v1.0.0"), TagType::Release); assert_eq!(TagType::from_tag("1.2.3"), TagType::Release); assert_eq!(TagType::from_tag("main"), TagType::Release); } #[test] fn test_tag_type_from_tag_signature() { assert_eq!(TagType::from_tag("v1.0.0.sig"), TagType::Signature); assert_eq!(TagType::from_tag("latest.sig"), TagType::Signature); assert_eq!(TagType::from_tag(".sig"), TagType::Signature); } #[test] fn test_tag_type_from_tag_attestation() { assert_eq!(TagType::from_tag("v1.0.0.att"), TagType::Attestation); assert_eq!(TagType::from_tag("latest.att"), TagType::Attestation); assert_eq!(TagType::from_tag(".att"), TagType::Attestation); } // ========================================================================= // KnownPackage Tests // ========================================================================= #[test] fn test_known_package_upsert_new_package() { let conn = setup_test_db(); // Insert a new package KnownPackage::upsert(&conn, "ghcr.io", "user/repo", None, None).unwrap(); // Verify it was inserted let packages = KnownPackage::get_all(&conn).unwrap(); assert_eq!(packages.len(), 1); assert_eq!(packages[0].registry, "ghcr.io"); assert_eq!(packages[0].repository, "user/repo"); } #[test] fn test_known_package_upsert_with_tag() { let conn = setup_test_db(); // Insert a package with a tag KnownPackage::upsert(&conn, "ghcr.io", "user/repo", Some("v1.0.0"), None).unwrap(); // Verify it was inserted with the tag let packages = KnownPackage::get_all(&conn).unwrap(); assert_eq!(packages.len(), 1); assert_eq!(packages[0].tags, vec!["v1.0.0"]); } #[test] fn test_known_package_upsert_multiple_tags() { let conn = setup_test_db(); // Insert a package with multiple tags KnownPackage::upsert(&conn, "ghcr.io", "user/repo", Some("v1.0.0"), None).unwrap(); KnownPackage::upsert(&conn, "ghcr.io", "user/repo", Some("v2.0.0"), None).unwrap(); KnownPackage::upsert(&conn, "ghcr.io", "user/repo", Some("latest"), None).unwrap(); // Verify all tags are present let packages = KnownPackage::get_all(&conn).unwrap(); assert_eq!(packages.len(), 1); // Tags are ordered by last_seen_at DESC assert!(packages[0].tags.contains(&"v1.0.0".to_string())); assert!(packages[0].tags.contains(&"v2.0.0".to_string())); assert!(packages[0].tags.contains(&"latest".to_string())); } #[test] fn test_known_package_upsert_with_description() { let conn = setup_test_db(); // Insert a package with description KnownPackage::upsert(&conn, "ghcr.io", "user/repo", None, Some("A test package")).unwrap(); // Verify description was saved let packages = KnownPackage::get_all(&conn).unwrap(); assert_eq!(packages.len(), 1); assert_eq!(packages[0].description, Some("A test package".to_string())); } #[test] fn test_known_package_upsert_updates_existing() { let conn = setup_test_db(); // Insert package KnownPackage::upsert(&conn, "ghcr.io", "user/repo", None, None).unwrap(); // Update with description KnownPackage::upsert( &conn, "ghcr.io", "user/repo", None, Some("Updated description"), ) .unwrap(); // Verify only one package exists with updated description let packages = KnownPackage::get_all(&conn).unwrap(); assert_eq!(packages.len(), 1); assert_eq!( packages[0].description, Some("Updated description".to_string()) ); } #[test] fn test_known_package_tag_types_separated() { let conn = setup_test_db(); // Insert package with different tag types KnownPackage::upsert(&conn, "ghcr.io", "user/repo", Some("v1.0.0"), None).unwrap(); KnownPackage::upsert(&conn, "ghcr.io", "user/repo", Some("v1.0.0.sig"), None).unwrap(); KnownPackage::upsert(&conn, "ghcr.io", "user/repo", Some("v1.0.0.att"), None).unwrap(); // Verify tags are separated by type let packages = KnownPackage::get_all(&conn).unwrap(); assert_eq!(packages.len(), 1); assert!(packages[0].tags.contains(&"v1.0.0".to_string())); assert!( packages[0] .signature_tags .contains(&"v1.0.0.sig".to_string()) ); assert!( packages[0] .attestation_tags .contains(&"v1.0.0.att".to_string()) ); } #[test] fn test_known_package_search() { let conn = setup_test_db(); // Insert multiple packages KnownPackage::upsert(&conn, "ghcr.io", "bytecode/component", None, None).unwrap(); KnownPackage::upsert(&conn, "docker.io", "library/nginx", None, None).unwrap(); KnownPackage::upsert(&conn, "ghcr.io", "user/nginx-app", None, None).unwrap(); // Search for nginx let results = KnownPackage::search(&conn, "nginx").unwrap(); assert_eq!(results.len(), 2); // Search for ghcr.io let results = KnownPackage::search(&conn, "ghcr").unwrap(); assert_eq!(results.len(), 2); // Search for bytecode let results = KnownPackage::search(&conn, "bytecode").unwrap(); assert_eq!(results.len(), 1); assert_eq!(results[0].repository, "bytecode/component"); } #[test] fn test_known_package_search_no_results() { let conn = setup_test_db(); KnownPackage::upsert(&conn, "ghcr.io", "user/repo", None, None).unwrap(); let results = KnownPackage::search(&conn, "nonexistent").unwrap(); assert!(results.is_empty()); } #[test] fn test_known_package_get() { let conn = setup_test_db(); // Insert a package KnownPackage::upsert(&conn, "ghcr.io", "user/repo", Some("v1.0.0"), None).unwrap(); // Get existing package let package = KnownPackage::get(&conn, "ghcr.io", "user/repo").unwrap(); assert!(package.is_some()); let package = package.unwrap(); assert_eq!(package.registry, "ghcr.io"); assert_eq!(package.repository, "user/repo"); // Get non-existent package let package = KnownPackage::get(&conn, "docker.io", "nonexistent").unwrap(); assert!(package.is_none()); } #[test] fn test_known_package_reference() { let conn = setup_test_db(); KnownPackage::upsert(&conn, "ghcr.io", "user/repo", None, None).unwrap(); let packages = KnownPackage::get_all(&conn).unwrap(); assert_eq!(packages[0].reference(), "ghcr.io/user/repo"); } #[test] fn test_known_package_reference_with_tag() { let conn = setup_test_db(); // Package without tags uses "latest" KnownPackage::upsert(&conn, "ghcr.io", "user/repo", None, None).unwrap(); let packages = KnownPackage::get_all(&conn).unwrap(); assert_eq!(packages[0].reference_with_tag(), "ghcr.io/user/repo:latest"); // Package with tag uses first tag KnownPackage::upsert(&conn, "ghcr.io", "user/repo", Some("v1.0.0"), None).unwrap(); let packages = KnownPackage::get_all(&conn).unwrap(); assert_eq!(packages[0].reference_with_tag(), "ghcr.io/user/repo:v1.0.0"); } }
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh
crates/package-manager/src/storage/models/migration.rs
Rust
use anyhow::Context; use rusqlite::Connection; /// A migration that can be applied to the database. struct MigrationDef { version: u32, name: &'static str, sql: &'static str, } /// All migrations in order. Each migration is run exactly once. const MIGRATIONS: &[MigrationDef] = &[ MigrationDef { version: 1, name: "init", sql: include_str!("../migrations/01_init.sql"), }, MigrationDef { version: 2, name: "known_packages", sql: include_str!("../migrations/02_known_packages.sql"), }, MigrationDef { version: 3, name: "known_package_tags", sql: include_str!("../migrations/03_known_package_tags.sql"), }, MigrationDef { version: 4, name: "image_size", sql: include_str!("../migrations/04_image_size.sql"), }, MigrationDef { version: 5, name: "tag_type", sql: include_str!("../migrations/05_tag_type.sql"), }, MigrationDef { version: 6, name: "wit_interface", sql: include_str!("../migrations/06_wit_interface.sql"), }, MigrationDef { version: 7, name: "package_name", sql: include_str!("../migrations/07_package_name.sql"), }, ]; /// Information about the current migration state. #[derive(Debug, Clone)] pub struct Migrations { /// The current migration version applied to the database. pub current: u32, /// The total number of migrations available. pub total: u32, } impl Migrations { /// Initialize the migrations table and run all pending migrations. pub(crate) fn run_all(conn: &Connection) -> anyhow::Result<()> { // Create the migrations table if it doesn't exist conn.execute_batch(include_str!("../migrations/00_migrations.sql"))?; // Get the current migration version let current_version: u32 = conn .query_row( "SELECT COALESCE(MAX(version), 0) FROM migrations", [], |row| row.get(0), ) .unwrap_or(0); // Run all migrations that haven't been applied yet for migration in MIGRATIONS { if migration.version > current_version { conn.execute_batch(migration.sql).with_context(|| { format!( "Failed to run migration {}: {}", migration.version, migration.name ) })?; conn.execute( "INSERT INTO migrations (version) VALUES (?1)", [migration.version], )?; } } Ok(()) } /// Returns information about the current migration state. pub(crate) fn get(conn: &Connection) -> anyhow::Result<Self> { let current: u32 = conn .query_row( "SELECT COALESCE(MAX(version), 0) FROM migrations", [], |row| row.get(0), ) .unwrap_or(0); let total = MIGRATIONS.last().map(|m| m.version).unwrap_or(0); Ok(Self { current, total }) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_migrations_run_all_creates_tables() { let conn = Connection::open_in_memory().unwrap(); Migrations::run_all(&conn).unwrap(); // Verify migrations table exists let count: i64 = conn .query_row("SELECT COUNT(*) FROM migrations", [], |row| row.get(0)) .unwrap(); assert!(count > 0); // Verify image table exists conn.execute("SELECT 1 FROM image LIMIT 1", []).ok(); // Verify known_package table exists conn.execute("SELECT 1 FROM known_package LIMIT 1", []).ok(); // Verify known_package_tag table exists conn.execute("SELECT 1 FROM known_package_tag LIMIT 1", []) .ok(); } #[test] fn test_migrations_run_all_idempotent() { let conn = Connection::open_in_memory().unwrap(); // Run migrations multiple times Migrations::run_all(&conn).unwrap(); Migrations::run_all(&conn).unwrap(); Migrations::run_all(&conn).unwrap(); // Should still work correctly let info = Migrations::get(&conn).unwrap(); assert_eq!(info.current, info.total); } #[test] fn test_migrations_get_info() { let conn = Connection::open_in_memory().unwrap(); Migrations::run_all(&conn).unwrap(); let info = Migrations::get(&conn).unwrap(); // Current should equal total after running all migrations assert_eq!(info.current, info.total); // Total should match the number of migrations defined let expected_total = MIGRATIONS.last().map(|m| m.version).unwrap_or(0); assert_eq!(info.total, expected_total); } #[test] fn test_migrations_get_before_running() { let conn = Connection::open_in_memory().unwrap(); // Create migrations table manually to test get() on fresh db conn.execute_batch(include_str!("../migrations/00_migrations.sql")) .unwrap(); let info = Migrations::get(&conn).unwrap(); // Current should be 0 before running migrations assert_eq!(info.current, 0); // Total should still reflect available migrations let expected_total = MIGRATIONS.last().map(|m| m.version).unwrap_or(0); assert_eq!(info.total, expected_total); } }
yoshuawuyts/wasm
0
Unified developer tools for WebAssembly
Rust
yoshuawuyts
Yosh