Skip to main content

Context

Struct Context 

Source
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

Source

pub fn new() -> Self

Create a new context with default settings.

For more control over the context’s configuration, use ContextBuilder.

Source

pub fn parent(&self) -> Option<&Arc<Context>>

Get the parent context, if any.

Source

pub fn info_name(&self) -> Option<&str>

Get the info name for this context.

Source

pub fn params(&self) -> &HashMap<String, BoxedValue>

Get the parsed parameter values.

Source

pub fn params_mut(&mut self) -> &mut HashMap<String, BoxedValue>

Get a mutable reference to the parsed parameter values.

Source

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));
Source

pub fn args(&self) -> &[String]

Get the leftover arguments.

Source

pub fn args_mut(&mut self) -> &mut Vec<String>

Get a mutable reference to the leftover arguments.

Source

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());
Source

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.

Source

pub fn set_obj<T: Any + Send + Sync + 'static>(&mut self, obj: T)

Set the user object.

Source

pub fn meta(&self) -> &HashMap<String, BoxedValue>

Get the shared metadata map.

Source

pub fn meta_mut(&mut self) -> &mut HashMap<String, BoxedValue>

Get a mutable reference to the shared metadata map.

Source

pub fn get_meta<T: 'static>(&self, key: &str) -> Option<&T>

Get a metadata value by key, downcast to the expected type.

Source

pub fn invoked_subcommand(&self) -> Option<&str>

Get the invoked subcommand name, if any.

Source

pub fn set_invoked_subcommand(&mut self, name: Option<String>)

Set the invoked subcommand name.

Source

pub fn terminal_width(&self) -> Option<usize>

Get the terminal width.

Source

pub fn max_content_width(&self) -> Option<usize>

Get the maximum content width.

Source

pub fn allow_extra_args(&self) -> bool

Check if extra arguments are allowed.

Source

pub fn allow_interspersed_args(&self) -> bool

Check if interspersed arguments are allowed.

Source

pub fn ignore_unknown_options(&self) -> bool

Check if unknown options should be ignored.

Source

pub fn help_option_names(&self) -> &[String]

Get the help option names.

Source

pub fn resilient_parsing(&self) -> bool

Check if resilient parsing is enabled.

Source

pub fn auto_envvar_prefix(&self) -> Option<&str>

Get the auto envvar prefix.

Source

pub fn color(&self) -> Option<bool>

Get the color setting.

Source

pub fn show_default(&self) -> Option<bool>

Get the show_default setting.

Source

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());
Source

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");
Source

pub fn find_root(&self) -> &Context

Find the root context.

Walks up the parent chain to find the outermost context.

Source

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);
Source

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.

Source

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 { .. }));
Source

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));
Source

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 }));
Source

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));
Source

pub fn close(&self)

Invoke all close callbacks.

This runs all functions registered with call_on_close in reverse order (last registered, first called).

Source

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));
Source

pub fn lookup_default_value(&self, name: &str) -> Option<BoxedValue>

Look up a default value from the default_map and return the stored Arc.

Source

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 invoke
  • args - 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));
Source

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());
Source

pub fn with_resource<T, F, C, R>(&self, resource: T, f: F, cleanup: C) -> R
where T: Send + 'static, F: FnOnce(&T) -> R, C: FnOnce() + Send + 'static,

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 be Send + 'static)
  • F - The function to execute with the resource
  • C - The cleanup function
  • R - The return type of the function
§Arguments
  • resource - The resource to manage
  • f - The function to execute with the resource
  • cleanup - 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

Trait Implementations§

Source§

impl Debug for Context

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Context

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.