Crate thag_rs

Crate thag_rs 

Source
Expand description

Introducing thag_rs (command thag) - a set of creative solutions to enhance your Rust development experience.

thag combines a script runner, expression evaluator, and REPL into a single command, with an array of smart features.

thag’s mission is to remove obstacles to productivity by giving you a selection of tools and examples to make it as quick and easy as possible to explore coding solutions without tedious setup.

🚀 Core Features:

  • Run Rust code straight from the command line

  • Evaluate expressions on the fly

  • Interactive REPL mode for rapid prototyping

  • Uses AST analysis to understand your code

  • Optionally embed custom Cargo manifest settings in “toml block” comments

  • Shebang support for true scripting (but thag’s command building is much better still!)

  • Loop-filter mode for data processing

🎯 Smart Features:

  • Toml-free by default: dependency inference from imports and Rust paths (x::y::z)

  • You’re in control: dependency inference (max/min/config/none) and/or toml block

  • Beyond shebangs: build instant commands from your snippets and programs

  • Execute scripts directly from URLs (GitHub, GitLab, BitBucket, Rust Playground)

  • Paste-and-run with built-in TUI editor

  • An evolution path for your code from REPL to edit-submit loop to saved scripts

  • Edit-submit standard input

  • Integrate your favourite editor (VS Code, Helix, Zed, vim, nano etc.)

  • Run any Cargo command (clippy, tree, test) against your scripts. (Yes, you can even include unit tests in your scripts)

  • View macro expansions side-by-side with your base script

  • Proc macro development support, including proc macro starter kit and a maybe_expand... option to show an expanded view of your proc macro

  • Automated, configurable inclusion of derive or other features of specific dependencies

💡 Getting Started:

Jump into thag’s collection of 250+ sample scripts in demo/README.md to see what’s possible. Contributions will be considered under MIT/Apache 2 license.

Whether you’re prototyping, learning, or building tools, thag_rs adapts to your style - from quick one-liners to full-featured programs.

§Feature flags

thag_rs is a full-featured binary, but it is also a library so that you can call thag_rs functionality from your code. When you do so, the script build time can be greatly reduced by only specifying the features you need. See the demo script library for examples.



The following features are supported:

  • default — Default features: full and simplelog
  • ast (enabled by default) — AST and Parsing
  • build (enabled by default) — Build and Analysis
  • clipboard — Clipboard support
  • color_detect (enabled by default) — Terminal color support
  • config (enabled by default) — Configuration
  • core (enabled by default) — Core and Logging Features
  • debug_logging — Optional/Debug Features
  • document-features — Documentation features
  • error_handling (enabled by default) — Error handling
  • full (enabled by default) — All features
  • repl (enabled by default) — REPL capability
  • simplelog (enabled by default)simplelog crate
  • tools — Tools feature - includes all dependencies needed by tools
  • tui (enabled by default) — TUI editing

Re-exports§

pub use errors::ThagError;
pub use errors::ThagResult;
pub use ast::find_crates;
pub use ast::find_metadata;
pub use ast::Ast;
pub use ast::CratesFinder;
pub use ast::MetadataFinder;
pub use code_utils::to_ast;
pub use builder::display_timings;
pub use builder::execute;
pub use builder::gen_build_run;
pub use builder::process_expr;
pub use builder::BuildState;
pub use builder::ScriptState;
pub use cmd_args::get_args;
pub use cmd_args::get_proc_flags;
pub use cmd_args::set_verbosity;
pub use cmd_args::validate_args;
pub use cmd_args::Cli;
pub use cmd_args::ProcFlags;
pub use code_utils::modified_since_compiled;
pub use logging::configure_log;
pub use manifest::extract;
pub use keys::KeyCombination;
pub use tui_editor::CrosstermEventReader;
pub use tui_editor::EventReader;
pub use tui_editor::KeyDisplayLine;
pub use tui_editor::MockEventReader;
pub use log;
pub use ratatui::crossterm;
pub use termbg;

Modules§

ast
AST analysis and dependency inference capability for thag_rs.
builder
The main driver for the thag_rs binary command thag, which controls execution based on input from the command line or caller and possibly from a script file or standard input.
cmd_args
Command-line argument and processing flags handling
code_utils
Operations on code
config
Configuration loader Configuration management module
errors
Core: Error handling
file_dialog
TUI file dialog
help_system
Lightweight help system for thag tools
inquire_theming
Helper functions for inquire UI theming integration
keys
TUI key handling and combinations
logging
Core: Basic logging
manifest
Manifest processing and Cargo.toml generation for the script
repl
REPL implementation
stdin
Paste-and-run and standard input handling
terminal
This module handles detection of terminal capabilities while preserving terminal state. In particular, it manages raw mode status which can be affected by some detection operations.
tool_errors
Error types for command-line tools Error types for thag command-line tools.
tui_editor
TUI editor for paste-and-run, stdin processing and REPL expression promotion.

Macros§

auto_help
Macro to automatically extract help from current source file
debug_log
Debugging logger.
file_navigator
Generates a FileNavigator to allow the user to navigate the file system and select files and directories from a command-line interface.
help_system
Macro to create a help system - manually specify the source
key
A macro that calls the private key proc macro to create a KeyCombination from an idiomatic shorthand. Directly borrowed from the crokey crate.
key_mappings
Key mappings for display purposes via (Ctrl-l) in TUI editor and file dialog.
lazy_static_var
Lazy-static variable generator.
re
Lazy-static regular expression generator.
repeat_dash
Generates a constant DASH_LINE consisting of a dash (hyphen) repeated the number of times specified by the integer literal argument n.
set_verbosity
Convenient macro for setting global verbosity with short syntax.
sprtln
Styled print line macro (replacement for cprtln!) Format: sprtln!(style: Style, "Lorem ipsum dolor {} amet", content: &str); Also accepts Role: sprtln!(Role::Code, "Hello {}", "world");
static_lazy
Creates a lazily-initialized static variable.
svprtln
Styled verbosity-gated print line macro (replacement for cvprtln!) Conditionally logs a message with verbosity control and styling.
vprtln
Verbosity-gated print line macro for user messages

Structs§

Color
Provides static methods for creating basic ANSI color styles
ColorInfo
Contains color information including the color value, ANSI escape sequence, and palette index
Config
Configuration categories
Dependencies
Dependency handling
FeatureOverride
Crate-specific feature overrides
Logging
Logging settings
Misc
Miscellaneous configuration parameters
PaletteConfig
Configuration structure for theme palette colors and styles
ProcMacros
Demo proc macro settings
Style
A foreground style for message styling.
Styled
A styled text container that applies ANSI terminal effects to text.
StyledString
A styled string that preserves styling context like colored’s ColoredString
Styling
Terminal color settings
Theme
Represents a complete theme configuration with color palette and styling information

Enums§

ColorInitStrategy
Strategies for initializing terminal color attributes and theme selection
ColorSupport
An enum to categorise the current terminal’s level of colour support as detected, configured or defaulted.
ColorValue
Represents different color value formats for terminal styling
HowInitialized
Indicates how terminal attributes were initialized
Role
Defines the role (purpose and relative prominence) of a piece of text
TermBgLuma
Terminal background luminance detection and specification
Verbosity
Controls the detail level of user messaging

Constants§

BUILT_IN_CRATES
Built-in crates that are always available in Rust
DYNAMIC_SUBDIR
Subdirectory name for dynamic/temporary Rust files
EXECUTABLE_CACHE_SUBDIR
Subdirectory name for executable cache (stores built script executables)
FLOWER_BOX_LEN
Length of decorative flower box borders for output formatting
PACKAGE_NAME
Package name from Cargo.toml
REPL_SCRIPT_NAME
Default filename for REPL scripts
REPL_SUBDIR
Subdirectory name for REPL files
RS_SUFFIX
Rust source file extension
SHARED_TARGET_SUBDIR
Subdirectory name for shared build target (all scripts share dependencies)
TEMP_DIR_NAME
Temporary directory name
TEMP_SCRIPT_NAME
Default filename for temporary scripts
TOML_NAME
Cargo manifest filename
VERSION
Package version from Cargo.toml

Statics§

OUTPUT_MANAGER
Global output manager instance protected by a reentrant mutex for thread-safe access
TMPDIR
System temporary directory path

Traits§

AnsiStyleExt
Extension trait for applying ANSI terminal styling to any displayable type.
Context
Trait for providing configuration context, allowing for different implementations in production versus testing environments.
Styleable
Trait that allows strings to be styled directly with automatic context preservation
StyledPrint
Extension trait to add convenience methods for StyledString
Styler
Trait that allows both Style and Role to be used interchangeably with styling macros

Functions§

debug_timings
Developer method to log method timings.
display_theme_details
Displays detailed theme information including theme attributes and terminal attributes.
display_theme_roles
Displays all available roles and their corresponding styles in the given theme.
escape_path_for_windows
No-op function for non-Windows platforms.
find_closest_color
Finds the closest color in the 256-color palette to the given RGB value.
get_home_dir
Get the user’s home directory as a PathBuf.
get_home_dir_string
Get the user’s home directory as a String.
get_verbosity
Initializes and returns the global verbosity setting.
init_verbosity
Initialize verbosity with a convenient function that handles common patterns.
load
Load the existing configuration file, if one exists at the specified location. The absence of a configuration file is not an error.
maybe_config
Initializes and returns the configuration.
paint_for_role
Applies styling to text based on the specified role
set_global_verbosity
Set the output verbosity for the current execution.
set_verbosity_from_env
Set global verbosity from the THAG_VERBOSITY environment variable.
themed_inquire_config
Create an inquire RenderConfig for inquire prompts that respects the current theme
thousands
Formats a given positive integer with thousands separators (commas).

Type Aliases§

V
Type alias for Verbosity to provide a shorter name for convenience