Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions rust/otap-dataflow/.chloggen/ctl-configurable-branding.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Use this changelog template to create an entry for release notes.

# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix'
change_type: enhancement

# The name of the component, or a single word describing the area of concern, (e.g. engine, otap).
# Must be one of the components listed in rust/otap-dataflow/.chloggen/config.yaml.
component: engine

# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`).
note: >-
`otap-df-ctl` now lets library embedders override the CLI identity used in
output. A new `Branding` type (binary name + output-envelope `schemaVersion`)
and a `run_with_terminal_and_diagnostics_branded` entrypoint allow a
downstream binary that embeds the library to emit help, shell completions, and
machine-readable JSON envelopes under its own identity instead of `dfctl`. The
standalone `dfctl` binary and the existing public entrypoints are unchanged;
they use the default `dfctl` / `dfctl/v1` branding.

# Mandatory: One or more tracking issues related to the change. You can use the PR number here if no issue exists.
issues: [3370]

# (Optional) One or more lines of additional information to render under the primary note.
# These lines will be padded with 2 spaces and then inserted directly into the document.
# Use pipe (|) for multiline entries.
subtext: >-
Initial scope covers the binary name and envelope `schemaVersion`. Schema
catalog identifiers, schema `$id` URLs, `DFCTL_*` environment-variable
prefixes, and the interactive TUI command hints remain `dfctl`-branded and may
be addressed in follow-ups.
61 changes: 61 additions & 0 deletions rust/otap-dataflow/crates/ctl/src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,32 @@ impl Cli {
Self::from_arg_matches_with_effective_defaults(&matches)
}

/// Return a cloned `clap::Command` with the given [`Branding`] applied.
///
/// The standalone `dfctl` binary uses [`Cli::command()`] (compile-time
/// [`crate::BIN_NAME`]); embedders can use this to produce a command whose
/// `--help`, `--version`, and error messages carry their own binary name.
#[must_use]
pub fn command_branded(branding: &crate::Branding) -> clap::Command {
let mut cmd = Self::command();
cmd = cmd.name(branding.bin_name);
cmd
}

/// Parse arguments through a command built with [`Cli::command_branded`].
pub fn try_parse_from_branded<I, T>(
itr: I,
branding: &crate::Branding,
) -> Result<Self, clap::Error>
where
I: IntoIterator<Item = T>,
T: Into<OsString> + Clone,
{
Self::command_branded(branding)
.try_get_matches_from(itr)
.and_then(|m| Self::from_arg_matches_with_effective_defaults(&m))
}

fn from_arg_matches_with_effective_defaults(matches: &ArgMatches) -> Result<Self, clap::Error> {
let error_format_is_default =
matches.value_source("error_format") == Some(ValueSource::DefaultValue);
Expand Down Expand Up @@ -1528,4 +1554,39 @@ mod tests {
other => panic!("unexpected command: {other:?}"),
}
}

/// Scenario: a branded command carries the embedder's binary name.
/// Guarantees: `command_branded` produces a clap `Command` whose `--help`
/// and `--version` output is named for the embedder rather than `dfctl`.
#[test]
fn command_branded_uses_embedder_name() {
use crate::Branding;
let branding = Branding {
bin_name: "embedder",
schema_version: "embedder/v1",
};
let cmd = Cli::command_branded(&branding);
assert_eq!(cmd.get_name(), "embedder");
}

/// Scenario: parse errors under a branded command carry the embedder's
/// binary name in the error message.
/// Guarantees: the embedder name appears in the clap error output so
/// operators see their own tool name in diagnostics.
#[test]
fn try_parse_from_branded_error_uses_bin_name() {
use crate::Branding;
let branding = Branding {
bin_name: "embedder",
schema_version: "embedder/v1",
};
// Use a bogus unrecognized subcommand to provoke a clap parse error.
let err = Cli::try_parse_from_branded(["embedder", "__nonexistent__"], &branding)
.expect_err("nonexistent subcommand should fail parsing");
let rendered = err.to_string();
assert!(
rendered.contains("embedder"),
"parse error should name the embedder binary, got: {rendered}"
);
}
}
77 changes: 77 additions & 0 deletions rust/otap-dataflow/crates/ctl/src/branding.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

//! Configurable CLI identity for library embedders.
//!
//! The standalone `dfctl` binary always uses the default identity. A downstream
//! binary that embeds this crate's library entrypoints can override the identity
//! so that help text, shell completions, and machine-readable output envelopes
//! reflect the embedding binary instead of `dfctl`.
//!
//! Branding is process-global and set-once, mirroring the crypto-provider
//! bootstrap in [`crate::crypto`]: a process runs as exactly one binary identity.
//! The branded entrypoints install the branding before executing a command; all
//! other entrypoints leave it unset and observe [`Branding::default`].

use std::sync::OnceLock;

/// The single `dfctl` default binary-name literal shared by the standalone
/// `BIN_NAME` constant and [`Branding::default`].
pub(crate) const DEFAULT_BIN_NAME: &str = "dfctl";

/// Identity strings used in the CLI's user-visible and machine-readable output.
///
/// Defaults reproduce the standalone `dfctl` identity. The fields are
/// `&'static str` because a binary's identity is fixed for the life of the
/// process.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Branding {
/// Installed command name used in help, completions, shell completions,
/// generated command metadata, and diagnostics (e.g. `dfctl`). Use
/// [`crate::Cli::command_branded`] to produce a clap `Command` with your
/// own name before parsing, and [`crate::run_with_terminal_and_diagnostics_branded`]
/// to install the branding for runtime output.
pub bin_name: &'static str,
/// Schema-version identifier stamped into machine-readable output envelopes
/// (e.g. `dfctl/v1`).
pub schema_version: &'static str,
}

impl Default for Branding {
fn default() -> Self {
Self {
bin_name: DEFAULT_BIN_NAME,
schema_version: "dfctl/v1",
}
}
}

/// Process-global active branding. Unset means [`Branding::default`].
static ACTIVE: OnceLock<Branding> = OnceLock::new();

/// Install the process-wide branding.
///
/// Idempotent and set-once (like the crypto provider): the first call wins and
/// subsequent calls are ignored. Standalone `dfctl` never calls this and so
/// observes [`Branding::default`].
pub(crate) fn set_branding(branding: Branding) {
// First-writer-wins; a binary has a single identity for its lifetime.
let _ = ACTIVE.set(branding);
}

/// Return the active branding, or the default if none was installed.
pub(crate) fn active() -> Branding {
ACTIVE.get().copied().unwrap_or_default()
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn default_is_dfctl() {
let b = Branding::default();
assert_eq!(b.bin_name, "dfctl");
assert_eq!(b.schema_version, "dfctl/v1");
}
}
28 changes: 19 additions & 9 deletions rust/otap-dataflow/crates/ctl/src/commands/catalog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,9 @@
//! long-running commands are classified correctly, and high-impact mutations
//! expose safety, dry-run, wait/watch, stdin, and schema metadata.

use crate::Cli;
use crate::args::CommandsArgs;
use crate::branding;
use crate::commands::output::write_read_command_output;
use crate::commands::schemas::{
AGENT_ENVELOPE_SCHEMA, COMMAND_CATALOG_SCHEMA, DIAGNOSE_REPORT_SCHEMA, ERROR_SCHEMA,
Expand All @@ -45,7 +47,6 @@ use crate::commands::schemas::{
};
use crate::error::CliError;
use crate::style::HumanStyle;
use crate::{BIN_NAME, Cli};
use clap::builder::ValueRange;
use clap::{Arg, ArgAction, Command as ClapCommand, CommandFactory};
use serde::Serialize;
Expand Down Expand Up @@ -87,10 +88,11 @@ fn build_catalog() -> CommandCatalog {
collect_command(command, &mut path, &mut commands);
}

let bin_name = branding::active().bin_name;
CommandCatalog {
schema_version: SCHEMA_VERSION,
generated_at: humantime::format_rfc3339_seconds(SystemTime::now()).to_string(),
binary: BIN_NAME,
binary: bin_name,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Now that the catalog can use a custom binary name, the schema still says binary must always be dfctl. Should we update the schema too, or keep the catalog binary field fixed as dfctl?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! Relaxed the schema: "binary" is now { "type": "string", "description": "Active binary name at catalog generation time." }

version: env!("CARGO_PKG_VERSION"),
global_arguments: global_arguments.clone(),
commands,
Expand Down Expand Up @@ -344,12 +346,16 @@ fn supports_dry_run(arguments: &[ArgumentEntry]) -> bool {

/// Builds a stable, dot-separated command identifier.
fn command_id(path: &[String]) -> String {
format!("{BIN_NAME}.{}", path.join(".").replace('-', "_"))
format!(
"{}.{}",
branding::active().bin_name,
path.join(".").replace('-', "_")
)
}

/// Builds the shortest command-line prefix for a command path.
fn command_line(path: &[String]) -> String {
format!("{BIN_NAME} {}", path.join(" "))
format!("{} {}", branding::active().bin_name, path.join(" "))
}

/// Builds a compact usage string from catalog argument metadata.
Expand Down Expand Up @@ -553,9 +559,9 @@ fn curated_examples(path: &[String]) -> Vec<String> {
}
}

/// Builds a curated command example from the shared binary name.
/// Builds a curated command example from the active binary name.
fn command_example(args: &str) -> String {
format!("{BIN_NAME} {args}")
format!("{} {args}", branding::active().bin_name)
}

/// Returns the best display placeholder for an argument value.
Expand Down Expand Up @@ -746,8 +752,9 @@ fn render_human(style: &HumanStyle, catalog: &CommandCatalog) -> String {
})
.collect::<Vec<_>>();

let bin_name = branding::active().bin_name;
let lines = [
style.header(format!("{BIN_NAME} command catalog")),
style.header(format!("{bin_name} command catalog")),
format!("{}: {}", style.label("schema"), catalog.schema_version),
format!("{}: {}", style.label("commands"), catalog.commands.len()),
String::new(),
Expand All @@ -760,7 +767,7 @@ fn render_human(style: &HumanStyle, catalog: &CommandCatalog) -> String {
rows,
),
String::new(),
format!("Use `{BIN_NAME} commands --output json` for the machine-readable catalog."),
format!("Use `{bin_name} commands --output json` for the machine-readable catalog."),
];
lines.join("\n")
}
Expand Down Expand Up @@ -1111,7 +1118,10 @@ mod tests {
pipeline_get.output_modes,
vec!["human", "json", "yaml", "agent-json"]
);
assert_eq!(pipeline_get.id, format!("{BIN_NAME}.pipelines.get"));
assert_eq!(
pipeline_get.id,
format!("{}.pipelines.get", branding::active().bin_name)
);
assert_eq!(pipeline_get.default_output.as_deref(), Some("human"));
assert_eq!(
pipeline_get.agent_default_output.as_deref(),
Expand Down
Loading
Loading