pub struct Context { /* private fields */ }Expand description
The central execution context for click-rs.
The context holds state relevant for script execution at every single level. It’s normally invisible to commands unless they opt-in to getting access to it.
A context manages:
- Parsed parameter values
- Parent context chain (for nested commands)
- Parameter source tracking (CLI, env, default, prompt)
- Resource cleanup via close callbacks
- Shared metadata between nested contexts
§Construction
Use ContextBuilder to create a new context with custom settings.
§Example
use click::context::{Context, ContextBuilder};
use std::sync::Arc;
let parent = Arc::new(ContextBuilder::new()
.info_name("cli")
.auto_envvar_prefix("MYAPP")
.build());
let child = ContextBuilder::new()
.info_name("subcommand")
.parent(parent)
.build();
assert_eq!(child.command_path(), "cli subcommand");Implementations§
Source§impl Context
impl Context
Sourcepub fn new() -> Self
pub fn new() -> Self
Create a new context with default settings.
For more control over the context’s configuration, use ContextBuilder.
Sourcepub fn params(&self) -> &HashMap<String, BoxedValue>
pub fn params(&self) -> &HashMap<String, BoxedValue>
Get the parsed parameter values.
Sourcepub fn params_mut(&mut self) -> &mut HashMap<String, BoxedValue>
pub fn params_mut(&mut self) -> &mut HashMap<String, BoxedValue>
Get a mutable reference to the parsed parameter values.
Sourcepub fn get_param<T: 'static>(&self, name: &str) -> Option<&T>
pub fn get_param<T: 'static>(&self, name: &str) -> Option<&T>
Get a parameter value by name, downcast to the expected type.
Returns None if the parameter doesn’t exist or has the wrong type.
§Example
use click::context::ContextBuilder;
use std::sync::Arc;
let mut ctx = ContextBuilder::new().build();
ctx.params_mut().insert("count".to_string(), Arc::new(42i32));
let count: Option<&i32> = ctx.get_param("count");
assert_eq!(count, Some(&42));Sourcepub fn args_mut(&mut self) -> &mut Vec<String>
pub fn args_mut(&mut self) -> &mut Vec<String>
Get a mutable reference to the leftover arguments.
Sourcepub fn obj<T: 'static>(&self) -> Option<&T>
pub fn obj<T: 'static>(&self) -> Option<&T>
Get the user object, downcast to the expected type.
§Example
use click::context::ContextBuilder;
#[derive(Debug)]
struct AppState { db_url: String }
let ctx = ContextBuilder::new()
.obj(AppState { db_url: "postgres://...".to_string() })
.build();
let state: Option<&AppState> = ctx.obj();
assert!(state.is_some());Sourcepub fn find_obj<T: 'static>(&self) -> Option<&T>
pub fn find_obj<T: 'static>(&self) -> Option<&T>
Find a user object of type T by walking up the parent chain.
This is a convenience for decorator-style helpers that want to accept objects stored in a parent context.
Sourcepub fn meta(&self) -> &HashMap<String, BoxedValue>
pub fn meta(&self) -> &HashMap<String, BoxedValue>
Get the shared metadata map.
Sourcepub fn meta_mut(&mut self) -> &mut HashMap<String, BoxedValue>
pub fn meta_mut(&mut self) -> &mut HashMap<String, BoxedValue>
Get a mutable reference to the shared metadata map.
Sourcepub fn get_meta<T: 'static>(&self, key: &str) -> Option<&T>
pub fn get_meta<T: 'static>(&self, key: &str) -> Option<&T>
Get a metadata value by key, downcast to the expected type.
Sourcepub fn invoked_subcommand(&self) -> Option<&str>
pub fn invoked_subcommand(&self) -> Option<&str>
Get the invoked subcommand name, if any.
Sourcepub fn set_invoked_subcommand(&mut self, name: Option<String>)
pub fn set_invoked_subcommand(&mut self, name: Option<String>)
Set the invoked subcommand name.
Sourcepub fn terminal_width(&self) -> Option<usize>
pub fn terminal_width(&self) -> Option<usize>
Get the terminal width.
Sourcepub fn max_content_width(&self) -> Option<usize>
pub fn max_content_width(&self) -> Option<usize>
Get the maximum content width.
Sourcepub fn allow_extra_args(&self) -> bool
pub fn allow_extra_args(&self) -> bool
Check if extra arguments are allowed.
Sourcepub fn allow_interspersed_args(&self) -> bool
pub fn allow_interspersed_args(&self) -> bool
Check if interspersed arguments are allowed.
Sourcepub fn ignore_unknown_options(&self) -> bool
pub fn ignore_unknown_options(&self) -> bool
Check if unknown options should be ignored.
Sourcepub fn help_option_names(&self) -> &[String]
pub fn help_option_names(&self) -> &[String]
Get the help option names.
Sourcepub fn resilient_parsing(&self) -> bool
pub fn resilient_parsing(&self) -> bool
Check if resilient parsing is enabled.
Sourcepub fn auto_envvar_prefix(&self) -> Option<&str>
pub fn auto_envvar_prefix(&self) -> Option<&str>
Get the auto envvar prefix.
Sourcepub fn show_default(&self) -> Option<bool>
pub fn show_default(&self) -> Option<bool>
Get the show_default setting.
Sourcepub fn help_renderer(&self) -> Option<&HelpRenderer>
pub fn help_renderer(&self) -> Option<&HelpRenderer>
Get the pluggable help renderer, walking up the parent chain.
Returns a reference to the first renderer found while walking from
self toward the root context. Returns None if none was installed.
§Example
use click::context::{Context, ContextBuilder, HelpRenderer};
use click::group::CommandLike;
use std::sync::Arc;
let renderer: HelpRenderer = Arc::new(|cmd, ctx| {
format!("custom help for {}", ctx.info_name().unwrap_or(""))
});
let ctx = ContextBuilder::new()
.info_name("root")
.help_renderer(renderer)
.build();
assert!(ctx.help_renderer().is_some());Sourcepub fn command_path(&self) -> String
pub fn command_path(&self) -> String
Get the computed command path.
This is used for the usage information on the help page.
It’s automatically created by combining the info names of the
chain of contexts to the root.
§Example
use click::context::ContextBuilder;
use std::sync::Arc;
let root = Arc::new(ContextBuilder::new().info_name("cli").build());
let sub = ContextBuilder::new()
.info_name("subcommand")
.parent(root)
.build();
assert_eq!(sub.command_path(), "cli subcommand");Sourcepub fn find_root(&self) -> &Context
pub fn find_root(&self) -> &Context
Find the root context.
Walks up the parent chain to find the outermost context.
Sourcepub fn get_parameter_source(&self, name: &str) -> Option<ParameterSource>
pub fn get_parameter_source(&self, name: &str) -> Option<ParameterSource>
Get the source of a parameter’s value.
Returns None if the parameter was not provided from any source.
§Example
use click::context::ContextBuilder;
use click::ParameterSource;
let mut ctx = ContextBuilder::new().build();
ctx.set_parameter_source("name", ParameterSource::CommandLine);
assert_eq!(ctx.get_parameter_source("name"), Some(ParameterSource::CommandLine));
assert_eq!(ctx.get_parameter_source("other"), None);Sourcepub fn set_parameter_source(&mut self, name: &str, source: ParameterSource)
pub fn set_parameter_source(&mut self, name: &str, source: ParameterSource)
Set the source of a parameter’s value.
This indicates the location from which the value of the parameter was obtained.
Sourcepub fn fail(&self, message: &str) -> ClickError
pub fn fail(&self, message: &str) -> ClickError
Create a usage error for this context.
Returns a ClickError::UsageError with the given message.
§Example
use click::context::ContextBuilder;
use click::error::ClickError;
let ctx = ContextBuilder::new().info_name("myapp").build();
let err = ctx.fail("invalid input");
assert!(matches!(err, ClickError::UsageError { .. }));Sourcepub fn abort(&self) -> ClickError
pub fn abort(&self) -> ClickError
Create an abort error.
Returns a ClickError::Abort.
§Example
use click::context::ContextBuilder;
use click::error::ClickError;
let ctx = ContextBuilder::new().build();
let err = ctx.abort();
assert!(matches!(err, ClickError::Abort));Sourcepub fn exit(&self, code: i32) -> ClickError
pub fn exit(&self, code: i32) -> ClickError
Create an exit error with the given code.
Returns a ClickError::Exit with the specified exit code.
§Example
use click::context::ContextBuilder;
use click::error::ClickError;
let ctx = ContextBuilder::new().build();
let err = ctx.exit(1);
assert!(matches!(err, ClickError::Exit { code: 1 }));Sourcepub fn call_on_close(&self, f: impl FnOnce() + Send + 'static)
pub fn call_on_close(&self, f: impl FnOnce() + Send + 'static)
Register a callback to be called when the context is closed.
This can be used to close resources opened during script execution.
§Example
use click::context::ContextBuilder;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
let closed = Arc::new(AtomicBool::new(false));
let closed_clone = Arc::clone(&closed);
let mut ctx = ContextBuilder::new().build();
ctx.call_on_close(move || {
closed_clone.store(true, Ordering::SeqCst);
});
assert!(!closed.load(Ordering::SeqCst));
ctx.close();
assert!(closed.load(Ordering::SeqCst));Sourcepub fn close(&self)
pub fn close(&self)
Invoke all close callbacks.
This runs all functions registered with call_on_close
in reverse order (last registered, first called).
Sourcepub fn lookup_default(&self, name: &str) -> Option<&dyn Any>
pub fn lookup_default(&self, name: &str) -> Option<&dyn Any>
Look up a default value for a parameter from the default_map.
Returns None if no default_map is set or the parameter is not in the map.
§Example
use click::context::ContextBuilder;
use std::collections::HashMap;
use std::sync::Arc;
let mut defaults: HashMap<String, Arc<dyn std::any::Any + Send + Sync>> = HashMap::new();
defaults.insert("count".to_string(), Arc::new(10i32));
let ctx = ContextBuilder::new()
.default_map(defaults)
.build();
let default = ctx.lookup_default("count");
assert!(default.is_some());
assert_eq!(default.and_then(|v| v.downcast_ref::<i32>()), Some(&10));Sourcepub fn lookup_default_value(&self, name: &str) -> Option<BoxedValue>
pub fn lookup_default_value(&self, name: &str) -> Option<BoxedValue>
Look up a default value from the default_map and return the stored Arc.
Sourcepub fn invoke(
self: &Arc<Self>,
cmd: &dyn CommandLike,
args: &[String],
) -> Result<(), ClickError>
pub fn invoke( self: &Arc<Self>, cmd: &dyn CommandLike, args: &[String], ) -> Result<(), ClickError>
Programmatically invoke another command with the given arguments.
This creates a child context for the invoked command and runs it. The invoked command will have this context as its parent.
This is useful for calling other commands from within a command callback,
similar to Python Click’s ctx.invoke().
§Arguments
cmd- The command to invokeargs- The arguments to pass to the command
§Example
use click::command::Command;
use click::context::ContextBuilder;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
let invoked = Arc::new(AtomicBool::new(false));
let invoked_clone = Arc::clone(&invoked);
let other_cmd = Command::new("other")
.callback(move |_ctx| {
invoked_clone.store(true, Ordering::SeqCst);
Ok(())
})
.build();
let ctx = Arc::new(ContextBuilder::new().info_name("main").build());
let result = ctx.invoke(&other_cmd, &[]);
assert!(result.is_ok());
assert!(invoked.load(Ordering::SeqCst));Sourcepub fn forward(
self: &Arc<Self>,
cmd: &dyn CommandLike,
) -> Result<(), ClickError>
pub fn forward( self: &Arc<Self>, cmd: &dyn CommandLike, ) -> Result<(), ClickError>
Forward the current context’s parameters to another command.
This is similar to invoke, but reuses the current context’s
parameter values instead of parsing new arguments. The invoked command will
see the same parameter values as this context.
This is useful for delegating to another command while preserving the
current context’s state, similar to Python Click’s ctx.forward().
§Arguments
cmd- The command to forward to
§Example
use click::command::Command;
use click::context::ContextBuilder;
use click::group::CommandLike;
use std::sync::Arc;
let other_cmd = Command::new("other")
.callback(|ctx| {
// This command will see the forwarded params
if let Some(name) = ctx.get_param::<String>("name") {
println!("Forwarded name: {}", name);
}
Ok(())
})
.build();
let mut ctx = ContextBuilder::new().info_name("main").build();
ctx.params_mut().insert("name".to_string(), Arc::new("Alice".to_string()));
let ctx = Arc::new(ctx);
let result = ctx.forward(&other_cmd);
assert!(result.is_ok());Sourcepub fn with_resource<T, F, C, R>(&self, resource: T, f: F, cleanup: C) -> R
pub fn with_resource<T, F, C, R>(&self, resource: T, f: F, cleanup: C) -> R
Execute a function with a resource, ensuring cleanup on close.
This is a convenience method that combines resource registration with
immediate use. The resource is passed to the provided function, and
a cleanup callback is registered via call_on_close.
This pattern is useful for managing resources like file handles, database connections, or other cleanup-requiring objects within command execution.
§Type Parameters
T- The resource type (must beSend + 'static)F- The function to execute with the resourceC- The cleanup functionR- The return type of the function
§Arguments
resource- The resource to managef- The function to execute with the resourcecleanup- The cleanup function to run when the context closes
§Example
use click::context::ContextBuilder;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
struct Resource {
value: i32,
}
let cleaned_up = Arc::new(AtomicBool::new(false));
let cleaned_up_clone = Arc::clone(&cleaned_up);
let ctx = ContextBuilder::new().build();
let result = ctx.with_resource(
Resource { value: 42 },
|res| res.value * 2,
move || {
cleaned_up_clone.store(true, Ordering::SeqCst);
},
);
assert_eq!(result, 84);
assert!(!cleaned_up.load(Ordering::SeqCst)); // Not yet cleaned up
ctx.close();
assert!(cleaned_up.load(Ordering::SeqCst)); // Now cleaned up