influxdb3-plugin-cli 0.5.0

InfluxDB 3 author-side CLI for templating, validating, and packaging InfluxDB 3 plugins.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
//! `new` command — scaffold a plugin or index from a built-in template.
//!
//! Each built-in template is a self-contained module under [`templates`];
//! the CLI dispatches through [`NewCommand`]. Adding a template is a
//! two-step: add a submodule under `templates/` and a variant here.

pub(crate) mod list;
pub(crate) mod templates;

use clap::{Args as ClapArgs, Subcommand};
use influxdb3_plugin_schemas::{ArtifactsUrl, PluginName, SchemaError, TriggerType};
use influxdb3_plugin_sdk::scaffold;
use std::path::{Path, PathBuf};
use std::str::FromStr;

use crate::cli_error::CliError;
use crate::color::Stream;
use crate::output::error_mapping::{ErrorContext, json_error_from_sdk};
use crate::output::json::{JsonError, NewOutput, write_envelope_ok};
use crate::output::{Env, OutputMode, RealEnv, resolve_output_mode};
use crate::path_display::{absolutize_for_json, display_relative_to_cwd};
use crate::style::Palette;
use templates::TemplateMetadata;

/// Global flags shared by every `new` subcommand. Flattened into each
/// subcommand's `Args` so clap parses them at the leaf level.
#[derive(Debug, ClapArgs)]
pub(crate) struct GlobalFlags {
    /// Output format. Auto-detected from stdout's TTY status and `CI`
    /// when omitted.
    #[arg(long, value_enum)]
    pub output: Option<OutputMode>,

    /// Overwrite files the template would write if they already exist.
    /// Files in the target directory that the template does not write
    /// are left alone regardless.
    #[arg(long)]
    pub force: bool,
}

#[derive(Debug, Subcommand)]
#[command(
    rename_all = "snake_case",
    override_usage = "\
influxdb3-plugin new <TEMPLATE> [PATH] [OPTIONS]
       influxdb3-plugin new list [OPTIONS]",
    after_help = "\
Run `influxdb3-plugin new list` to see available templates, \
or `influxdb3-plugin new <template> --help` for per-template options. \
Pass `--output` after the template name (e.g. `new index --output json`)."
)]
pub(crate) enum NewCommand {
    /// List available templates.
    List(list::Args),

    /// Plugin triggered by rows written to a database.
    #[command(hide = true)]
    ProcessWrites(templates::process_writes::Args),

    /// Plugin triggered on a schedule.
    #[command(hide = true)]
    ProcessScheduledCall(templates::process_scheduled_call::Args),

    /// Plugin triggered by an HTTP request.
    #[command(hide = true)]
    ProcessRequest(templates::process_request::Args),

    /// Empty registry index file.
    #[command(hide = true)]
    Index(templates::index::Args),
}

impl NewCommand {
    pub(crate) fn run(self) -> anyhow::Result<()> {
        match self {
            Self::List(a) => list::run(a),
            Self::ProcessWrites(a) => templates::process_writes::run(a),
            Self::ProcessScheduledCall(a) => templates::process_scheduled_call::run(a),
            Self::ProcessRequest(a) => templates::process_request::run(a),
            Self::Index(a) => templates::index::run(a),
        }
    }
}

pub(crate) fn plugin_scaffold(
    metadata: &'static TemplateMetadata,
    trigger: TriggerType,
    global: GlobalFlags,
    path: PathBuf,
    name_arg: Option<String>,
    database_version: Option<String>,
) -> anyhow::Result<()> {
    run_plugin_with_env(
        metadata,
        trigger,
        global,
        path,
        name_arg,
        database_version,
        &RealEnv,
    )
}

pub(crate) fn index_scaffold(
    metadata: &'static TemplateMetadata,
    global: GlobalFlags,
    path: PathBuf,
    artifacts_url: Option<String>,
) -> anyhow::Result<()> {
    run_index_with_env(metadata, global, path, artifacts_url, &RealEnv)
}

fn run_plugin_with_env(
    metadata: &'static TemplateMetadata,
    trigger: TriggerType,
    global: GlobalFlags,
    path: PathBuf,
    name_arg: Option<String>,
    database_version: Option<String>,
    env: &dyn Env,
) -> anyhow::Result<()> {
    let mode = resolve_output_mode(global.output, env);
    let stdout_palette = Palette::for_stream(Stream::Stdout, mode, env, env.stdout_is_terminal());

    let name = resolve_plugin_name(&path, name_arg)?;

    if let Some(raw) = database_version.as_deref()
        && let Err(e) = semver::VersionReq::parse(raw)
    {
        return Err(CliError::usage(JsonError {
            code: "usage::invalid_database_version".into(),
            message: format!("invalid --database-version {raw:?}: {e}"),
            field: None,
            details: Some(serde_json::json!({
                "value": raw,
                "reason": e.to_string(),
            })),
            diagnostics: vec![],
            cause: vec![],
        }));
    }

    // path.parent() is "" for a bare relative name (e.g. `my-plugin`);
    // read_dir("") is implementation-defined — fall back to "." explicitly.
    let parent = path.parent().unwrap_or_else(|| Path::new("."));
    check_sibling_canonical_collision(parent, &name)?;

    let target_dir = absolutize_for_json(&path)?;

    scaffold::plugin(
        &target_dir,
        &name,
        trigger,
        database_version.as_deref(),
        global.force,
    )
    .map_err(|e| CliError::runtime(json_error_from_sdk(&e, ErrorContext::NewPlugin)))?;

    let summary = Summary {
        kind: SummaryKind::Plugin,
        template: metadata,
        target_dir,
        name: Some(name),
        files_written: vec![
            PathBuf::from("manifest.toml"),
            PathBuf::from("__init__.py"),
            PathBuf::from("README.md"),
        ],
    };
    render(&summary, mode, stdout_palette)
}

fn run_index_with_env(
    metadata: &'static TemplateMetadata,
    global: GlobalFlags,
    path: PathBuf,
    artifacts_url: Option<String>,
    env: &dyn Env,
) -> anyhow::Result<()> {
    let mode = resolve_output_mode(global.output, env);
    let stdout_palette = Palette::for_stream(Stream::Stdout, mode, env, env.stdout_is_terminal());

    if let Some(raw) = artifacts_url.as_deref()
        && let Err(e) = ArtifactsUrl::try_new(raw)
    {
        return Err(CliError::usage(JsonError {
            code: "usage::invalid_artifacts_url".into(),
            message: format!("invalid --artifacts-url {raw:?}: {e}"),
            field: None,
            details: Some(serde_json::json!({
                "value": raw,
                "reason": e.to_string(),
            })),
            diagnostics: vec![],
            cause: vec![],
        }));
    }

    let target_dir = absolutize_for_json(&path)?;

    scaffold::index(&target_dir, artifacts_url.as_deref(), global.force)
        .map_err(|e| CliError::runtime(json_error_from_sdk(&e, ErrorContext::NewIndex)))?;

    let summary = Summary {
        kind: SummaryKind::Index,
        template: metadata,
        target_dir,
        name: None,
        files_written: vec![PathBuf::from("index.json")],
    };
    render(&summary, mode, stdout_palette)
}

/// Derives a plugin name from `--name`, else the basename of `dir`.
/// Returns an actionable error when neither yields a valid plugin name.
fn resolve_plugin_name(dir: &Path, name_arg: Option<String>) -> anyhow::Result<String> {
    let (candidate, source_was_explicit) = match name_arg {
        Some(n) => (n, true),
        None => {
            // Canonicalize-without-existence so `.`, `./foo`, `../bar`, and
            // absolute paths all resolve to the same basename rule. Without
            // absolute(), `.`'s file_name is None and a bare
            // `new <template>` invocation fails.
            let absolute = std::path::absolute(dir).map_err(|_source| {
                CliError::runtime(JsonError {
                    code: "new::path_resolution_failed".into(),
                    message: format!("could not resolve path {dir:?}: {_source}"),
                    field: None,
                    details: None,
                    diagnostics: vec![],
                    cause: vec![],
                })
            })?;
            let basename = absolute
                .file_name()
                .and_then(|s| s.to_str())
                .ok_or_else(|| {
                    CliError::runtime(JsonError {
                        code: "new::derived_name_unavailable".into(),
                        message: format!(
                            "could not derive a plugin name from path {dir:?}; \
                             pass --name <name> explicitly"
                        ),
                        field: None,
                        details: None,
                        diagnostics: vec![],
                        cause: vec![],
                    })
                })?
                .to_owned();
            (basename, false)
        }
    };

    match PluginName::from_str(&candidate) {
        Ok(_) => Ok(candidate),
        Err(SchemaError::ReservedPluginName { .. }) if source_was_explicit => {
            Err(CliError::usage(JsonError {
                code: "usage::invalid_name".into(),
                message: format!(
                    "--name {candidate:?} is a Windows reserved device name \
                     (case-insensitive); pick a different name"
                ),
                field: None,
                details: Some(serde_json::json!({
                    "value": candidate,
                    "reason": "reserved_name",
                })),
                diagnostics: vec![],
                cause: vec![],
            }))
        }
        Err(_) if source_was_explicit => Err(CliError::usage(JsonError {
            code: "usage::invalid_name".into(),
            message: format!("--name {candidate:?} is not a valid plugin name; {PLUGIN_NAME_RULE}"),
            field: None,
            details: Some(serde_json::json!({
                "value": candidate,
                "reason": "invalid_format",
            })),
            diagnostics: vec![],
            cause: vec![],
        })),
        Err(SchemaError::ReservedPluginName { .. }) => {
            let dir_display = absolutize_for_json(dir)?.display().to_string();
            Err(CliError::runtime(JsonError {
                code: "new::derived_name_invalid".into(),
                message: format!(
                    "derived plugin name {candidate:?} (from path basename) is a \
                     Windows reserved device name; pass --name <name> explicitly"
                ),
                field: Some(dir_display),
                details: None,
                diagnostics: vec![],
                cause: vec![],
            }))
        }
        Err(_) => {
            let dir_display = absolutize_for_json(dir)?.display().to_string();
            Err(CliError::runtime(JsonError {
                code: "new::derived_name_invalid".into(),
                message: format!(
                    "derived plugin name {candidate:?} (from path basename) is not a valid \
                     plugin name; pass --name <name> explicitly. {PLUGIN_NAME_RULE}"
                ),
                field: Some(dir_display),
                details: None,
                diagnostics: vec![],
                cause: vec![],
            }))
        }
    }
}

/// Human-readable rendering of the character-level `PluginName` rule.
/// The Windows-reserved check produces its own dedicated message, so this
/// const is only the alphabet/length portion — kept as a single `const`
/// so the explicit-`--name` and basename-derived error paths stay in
/// lockstep if the rule ever changes.
const PLUGIN_NAME_RULE: &str = "plugin names must match `[a-zA-Z][a-zA-Z0-9_-]*` (1-64 chars, ASCII \
     alphanumerics / `-` / `_`, starting with a letter)";

/// Scans `parent` for sibling directories whose basenames canonicalize to
/// the same form as `resolved_name`. Returns an error if any sibling's
/// basename is a valid `PluginName` that canonical-collides with
/// `resolved_name` *and* spells the name differently.
///
/// Siblings whose basenames are not valid `PluginName`s (`.hidden`, files,
/// invalid characters, non-UTF8 bytes) are ignored — they can never be
/// published and thus cannot collide at the registry layer.
///
/// Identical spellings are *not* errors here: they're handled by
/// `scaffold::plugin`'s existing `check_no_existing` path (different error,
/// different fix — `--force` or pick another path).
///
/// A non-existent or unreadable `parent` is treated as "no siblings" — the
/// check is a no-op rather than a hard error.
fn check_sibling_canonical_collision(
    parent: &Path,
    resolved_name: &str,
) -> Result<(), anyhow::Error> {
    let Ok(target_canonical) = PluginName::from_str(resolved_name).map(|p| p.canonical()) else {
        return Ok(());
    };

    let read_dir = match std::fs::read_dir(parent) {
        Ok(rd) => rd,
        Err(_) => return Ok(()),
    };

    for entry in read_dir.flatten() {
        let path = entry.path();
        if !path.is_dir() {
            continue;
        }
        let Some(basename) = path.file_name().and_then(|s| s.to_str()) else {
            continue;
        };
        let Ok(sibling_name) = PluginName::from_str(basename) else {
            continue;
        };
        if sibling_name.canonical() == target_canonical && sibling_name.as_str() != resolved_name {
            return Err(CliError::usage(JsonError {
                code: "usage::sibling_canonical_collision".into(),
                message: format!(
                    "plugin name {resolved_name:?} canonically collides with existing \
                     sibling directory {basename:?} (both normalize to {target_canonical:?}). \
                     Rename the new plugin or use the existing spelling."
                ),
                field: None,
                details: Some(serde_json::json!({
                    "name": resolved_name,
                    "sibling": basename,
                    "canonical": target_canonical,
                })),
                diagnostics: vec![],
                cause: vec![],
            }));
        }
    }

    Ok(())
}

#[derive(Debug)]
struct Summary {
    kind: SummaryKind,
    template: &'static TemplateMetadata,
    target_dir: PathBuf,
    name: Option<String>,
    files_written: Vec<PathBuf>,
}

#[derive(Debug, Clone, Copy)]
enum SummaryKind {
    Plugin,
    Index,
}

impl SummaryKind {
    fn as_str(self) -> &'static str {
        match self {
            Self::Plugin => "plugin",
            Self::Index => "index",
        }
    }
}

fn render(summary: &Summary, mode: OutputMode, stdout_palette: Palette) -> anyhow::Result<()> {
    match mode {
        OutputMode::Human => render_human(summary, stdout_palette, &mut std::io::stdout())?,
        OutputMode::Json => render_json(summary, &mut std::io::stdout())?,
    }
    Ok(())
}

fn render_human(
    summary: &Summary,
    palette: Palette,
    writer: &mut impl std::io::Write,
) -> std::io::Result<()> {
    let kind = summary.kind.as_str();
    let template = summary.template.short_name;
    let ok = palette.success.render();
    let ok_reset = palette.success.render_reset();
    writeln!(
        writer,
        "{ok}Scaffolded {kind} ({template} template) at {}{ok_reset}",
        display_relative_to_cwd(&summary.target_dir)
    )?;
    if let Some(name) = &summary.name {
        writeln!(writer, "  name: {name}")?;
    }
    writeln!(writer, "  files written:")?;
    for file in &summary.files_written {
        writeln!(writer, "    {}", display_relative_to_cwd(file))?;
    }
    Ok(())
}

fn render_json(summary: &Summary, writer: &mut impl std::io::Write) -> anyhow::Result<()> {
    let payload = NewOutput {
        kind: summary.kind.as_str(),
        template: summary.template.short_name,
        target_dir: summary.target_dir.clone(),
        name: summary.name.clone(),
        files_written: summary.files_written.clone(),
    };
    write_envelope_ok(writer, payload)?;
    Ok(())
}