apicurio-cli 0.1.2

A powerful CLI tool for managing schema artifacts from Apicurio Registry with lockfile-based dependency management
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
//! Configuration management for Apicurio CLI
//!
//! This module handles loading, parsing, and merging of configuration files including:
//! - Repository configuration (`apicurioconfig.yaml`)
//! - Global registries configuration
//! - Environment variable expansion
//! - Configuration validation
//!
//! ## Configuration Files
//!
//! ### Repository Configuration
//! The main project configuration file that defines dependencies, registries, and publishing settings.
//!
//! ### Global Registries
//! Shared registry definitions stored in `~/.config/apicurio/registries.yaml` or
//! the path specified by `APICURIO_REGISTRIES_PATH`.
//!
//! ## Environment Variable Expansion
//!
//! Configuration files support environment variable expansion with the following syntax:
//! - `${VAR}` - Simple substitution
//! - `${VAR:-default}` - Use default if VAR is unset or empty
//! - `${VAR-default}` - Use default if VAR is unset
//! - `${VAR:+alt}` - Use alt if VAR is set and non-empty
//! - `${VAR+alt}` - Use alt if VAR is set

use anyhow::Context;
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::path::Path;
use std::{env, fs, path::PathBuf};

/// Repository-specific configuration loaded from `apicurioconfig.yaml`
///
/// This is the main configuration file for a project, containing:
/// - Registry definitions (can be merged with global registries)
/// - Dependencies to fetch from registries
/// - Publishing configuration for uploading artifacts
///
/// # Example
///
/// ```yaml
/// externalRegistriesFile: ${APICURIO_REGISTRIES_PATH:-}
/// registries:
///   - name: production
///     url: https://registry.example.com
///     auth:
///       type: bearer
///       tokenEnv: APICURIO_TOKEN
/// dependencies:
///   - name: user-service
///     groupId: com.example
///     artifactId: user-service
///     version: ^1.0.0
///     registry: production
///     outputPath: protos/user-service.proto
/// ```
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct RepoConfig {
    /// Optional path to external registries file for additional registry definitions
    pub external_registries_file: Option<String>,
    /// Registry definitions specific to this repository
    #[serde(default)]
    pub registries: Vec<RegistryConfig>,
    /// Dependencies to fetch from registries
    #[serde(default)]
    pub dependencies: Vec<DependencyConfig>,
    /// Artifacts to publish to registries
    #[serde(default)]
    pub publishes: Vec<PublishConfig>,
}

/// Registry configuration defining connection details and authentication
///
/// Registries can be defined globally or per-repository. Repository-specific
/// registries override global registries with the same name.
#[derive(Deserialize, Serialize, Debug, Clone, Default)]
#[serde(rename_all = "camelCase")]
pub struct RegistryConfig {
    /// Unique name for this registry (used as reference in dependencies)
    pub name: String,
    /// Base URL of the Apicurio Registry API
    pub url: String,
    /// Authentication configuration
    #[serde(default)]
    pub auth: AuthConfig,
}

/// Authentication configuration for registry access
///
/// Supports multiple authentication methods commonly used with Apicurio Registry.
/// Credentials are always sourced from environment variables for security.
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
#[serde(tag = "type")]
#[derive(Default)]
pub enum AuthConfig {
    /// No authentication (anonymous access)
    #[default]
    None,
    /// HTTP Basic authentication
    Basic {
        /// Username for basic auth
        username: String,
        /// Environment variable containing the password
        password_env: String,
    },
    /// Token-based authentication (custom header)
    Token {
        /// Environment variable containing the token
        token_env: String,
    },
    /// Bearer token authentication (Authorization header)
    Bearer {
        /// Environment variable containing the bearer token
        token_env: String,
    },
}

/// Dependency configuration for artifacts to fetch from registries
///
/// Dependencies support semantic version ranges and are resolved to exact
/// versions in the lock file for reproducible builds.
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct DependencyConfig {
    /// Local name/alias for this dependency
    pub name: String,
    /// Group ID of the artifact in the registry
    pub group_id: String,
    /// Artifact ID in the registry
    pub artifact_id: String,
    /// Version specification (supports semver ranges like ^1.0.0, ~2.1.0)
    pub version: String,
    /// Name of the registry to fetch from (must match a registry name)
    pub registry: String,
    /// Local path where the artifact should be saved
    pub output_path: String,
}

/// Publishing configuration for uploading artifacts to registries
///
/// Defines how local artifacts should be published to registries, including
/// metadata, references, and conflict resolution behavior.
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct PublishConfig {
    /// Name/identifier for this publish configuration
    pub name: String,
    /// Local path to the file to publish
    pub input_path: String,
    /// Exact version to publish (no semver ranges allowed)
    pub version: String,
    /// Target registry name
    pub registry: String,

    // Optional fields with smart defaults
    /// Group ID (defaults from name if contains /)
    #[serde(default)]
    pub group_id: Option<String>,
    /// Artifact ID (defaults from name)
    #[serde(default)]
    pub artifact_id: Option<String>,
    /// Artifact type (auto-detected from file extension if not specified)
    #[serde(default)]
    pub r#type: Option<ArtifactType>,
    /// Behavior when artifact already exists
    #[serde(default)]
    pub if_exists: IfExistsAction,
    /// Human-readable description
    #[serde(default)]
    pub description: Option<String>,
    /// Key-value labels for metadata
    #[serde(default)]
    pub labels: std::collections::HashMap<String, String>,
    /// References to other artifacts
    #[serde(default)]
    pub references: Vec<ArtifactReference>,
}

/// Supported artifact types for publishing
///
/// The CLI can auto-detect most types from file extensions, but explicit
/// specification is supported for edge cases.
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "kebab-case")]
pub enum ArtifactType {
    /// Protocol Buffers (.proto files)
    Protobuf,
    /// Apache Avro schemas
    Avro,
    /// JSON Schema definitions
    JsonSchema,
    /// OpenAPI specifications
    Openapi,
    /// AsyncAPI specifications
    AsyncApi,
    /// GraphQL schemas
    GraphQL,
    /// XML schemas
    Xml,
    /// WSDL definitions
    Wsdl,
}

/// Behavior when publishing an artifact that already exists
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[derive(Default)]
pub enum IfExistsAction {
    /// Fail if artifact already exists
    #[default]
    Fail,
    /// Create a new version if artifact exists
    CreateVersion,
    /// Find existing version or create new one
    FindOrCreateVersion,
}

/// Reference to another artifact (used in publishing)
///
/// Artifacts can reference other artifacts to establish dependencies.
/// References must use exact versions (no semver ranges) to ensure
/// deterministic builds.
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ArtifactReference {
    // Either use name (group/artifact format) or explicit groupId/artifactId
    /// Name in group/artifact format (alternative to explicit groupId/artifactId)
    #[serde(default)]
    pub name: Option<String>,
    /// Explicit group ID (alternative to name)
    #[serde(default)]
    pub group_id: Option<String>,
    /// Explicit artifact ID (alternative to name)
    #[serde(default)]
    pub artifact_id: Option<String>,

    /// EXACT version only (e.g., "1.2.3"), no ranges
    pub version: String,

    /// Optional alias for imports (e.g., "text_message.proto")
    #[serde(default)]
    pub name_alias: Option<String>,
}

/// Global configuration for shared registry definitions
///
/// This configuration is loaded from `~/.config/apicurio/registries.yaml`
/// or the path specified by `APICURIO_REGISTRIES_PATH` environment variable.
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct GlobalConfig {
    /// Shared registry definitions
    #[serde(default)]
    pub registries: Vec<RegistryConfig>,
}

impl RepoConfig {
    /// Merge global, external, and repo-local registries
    ///
    /// Registry definitions are merged in the following order (later wins):
    /// 1. Global registries from `~/.config/apicurio/registries.yaml`
    /// 2. External registries from file specified in `externalRegistriesFile`
    /// 3. Repository-local registries from `apicurioconfig.yaml`
    ///
    /// # Arguments
    /// * `global` - Global configuration containing shared registries
    ///
    /// # Returns
    /// Vector of merged registry configurations with duplicates resolved
    ///
    /// # Errors
    /// Returns error if external registries file cannot be read or parsed
    pub fn merge_registries(&self, global: GlobalConfig) -> anyhow::Result<Vec<RegistryConfig>> {
        let mut map = std::collections::HashMap::new();
        // 1) global
        for reg in global.registries {
            map.insert(reg.name.clone(), reg);
        }
        // 2) external file
        if let Some(path) = &self.external_registries_file {
            let contents = fs::read_to_string(path)
                .with_context(|| format!("reading external registries from {path}"))?;
            let ext: GlobalConfig = serde_yaml::from_str(&contents)?;
            for reg in ext.registries {
                map.insert(reg.name.clone(), reg);
            }
        }
        // 3) repo-local
        for reg in &self.registries {
            map.insert(reg.name.clone(), reg.clone());
        }
        Ok(map.into_values().collect())
    }
}

impl PublishConfig {
    /// Get the resolved group ID for this publish configuration
    ///
    /// If `group_id` is explicitly set, uses that value. Otherwise:
    /// - If `name` contains '/', uses the part before '/' as group ID
    /// - Otherwise defaults to "default"
    ///
    /// # Examples
    /// - name: "com.example/my-service" → group_id: "com.example"
    /// - name: "my-service" → group_id: "default"
    pub fn resolved_group_id(&self) -> String {
        self.group_id.clone().unwrap_or_else(|| {
            if let Some((group, _)) = self.name.split_once('/') {
                group.to_string()
            } else {
                "default".to_string()
            }
        })
    }

    pub fn resolved_artifact_id(&self) -> String {
        self.artifact_id.clone().unwrap_or_else(|| {
            if let Some((_, artifact)) = self.name.split_once('/') {
                artifact.to_string()
            } else {
                self.name.clone()
            }
        })
    }

    pub fn resolved_content_type(&self) -> String {
        if let Some(ref artifact_type) = self.r#type {
            match artifact_type {
                ArtifactType::Protobuf => "application/x-protobuf".to_string(),
                ArtifactType::Avro => "application/json".to_string(),
                ArtifactType::JsonSchema => "application/json".to_string(),
                ArtifactType::Openapi => "application/json".to_string(),
                ArtifactType::AsyncApi => "application/json".to_string(),
                ArtifactType::GraphQL => "application/graphql".to_string(),
                ArtifactType::Xml => "application/xml".to_string(),
                ArtifactType::Wsdl => "application/xml".to_string(),
            }
        } else {
            // Auto-detect from file extension
            let path = std::path::Path::new(&self.input_path);
            match path.extension().and_then(|e| e.to_str()) {
                Some("proto") => "application/x-protobuf".to_string(),
                Some("avsc") => "application/json".to_string(),
                Some("json") => "application/json".to_string(),
                Some("yaml") | Some("yml") => "application/yaml".to_string(),
                Some("xml") => "application/xml".to_string(),
                Some("graphql") | Some("gql") => "application/graphql".to_string(),
                _ => "application/octet-stream".to_string(),
            }
        }
    }

    pub fn resolved_artifact_type(&self) -> String {
        if let Some(ref artifact_type) = self.r#type {
            match artifact_type {
                ArtifactType::Protobuf => "PROTOBUF".to_string(),
                ArtifactType::Avro => "AVRO".to_string(),
                ArtifactType::JsonSchema => "JSON".to_string(),
                ArtifactType::Openapi => "OPENAPI".to_string(),
                ArtifactType::AsyncApi => "ASYNCAPI".to_string(),
                ArtifactType::GraphQL => "GRAPHQL".to_string(),
                ArtifactType::Xml => "XML".to_string(),
                ArtifactType::Wsdl => "WSDL".to_string(),
            }
        } else {
            // Auto-detect from file extension
            let path = std::path::Path::new(&self.input_path);
            match path.extension().and_then(|e| e.to_str()) {
                Some("proto") => "PROTOBUF".to_string(),
                Some("avsc") => "AVRO".to_string(),
                Some("json") => "JSON".to_string(),
                Some("yaml") | Some("yml") => "JSON".to_string(),
                Some("xml") => "XML".to_string(),
                Some("graphql") | Some("gql") => "GRAPHQL".to_string(),
                _ => "JSON".to_string(),
            }
        }
    }
}

impl ArtifactReference {
    /// Validate that the version is exact (no semver ranges)
    pub fn validate_exact_version(&self) -> anyhow::Result<()> {
        if self.version.contains('^')
            || self.version.contains('~')
            || self.version.contains('*')
            || self.version.contains('>')
            || self.version.contains('<')
        {
            anyhow::bail!(
                "Reference version must be exact, got '{}'. Use exact version like '1.2.3'",
                self.version
            );
        }
        Ok(())
    }

    pub fn resolved_group_id(&self) -> String {
        self.group_id.clone().unwrap_or_else(|| {
            if let Some(name) = &self.name {
                if let Some((group, _)) = name.split_once('/') {
                    group.to_string()
                } else {
                    "default".to_string()
                }
            } else {
                "default".to_string()
            }
        })
    }

    pub fn resolved_artifact_id(&self) -> String {
        self.artifact_id.clone().unwrap_or_else(|| {
            if let Some(name) = &self.name {
                if let Some((_, artifact)) = name.split_once('/') {
                    artifact.to_string()
                } else {
                    name.clone()
                }
            } else {
                panic!("Either name or artifactId must be specified for reference")
            }
        })
    }
}

pub fn load_repo_config(path: &Path) -> anyhow::Result<RepoConfig> {
    let preprocessed_data = preprocess_config(path)?; // Preprocess the YAML file to expand environment variables
    let cfg: RepoConfig = serde_yaml::from_str(&preprocessed_data)?;
    Ok(cfg)
}

pub fn load_global_config() -> anyhow::Result<GlobalConfig> {
    let path = env::var("APICURIO_REGISTRIES_PATH")
        .map(PathBuf::from)
        .unwrap_or_else(|_| {
            let mut p = dirs::config_dir().unwrap_or_else(|| PathBuf::from("."));
            p.push("apicurio/registries.yaml");
            p
        });
    if !path.exists() {
        return Ok(GlobalConfig { registries: vec![] });
    }
    let data = fs::read_to_string(&path)
        .with_context(|| format!("reading global registries {}", path.display()))?;
    let cfg: GlobalConfig = serde_yaml::from_str(&data)?;
    Ok(cfg)
}

pub fn save_global_config(cfg: &GlobalConfig) -> anyhow::Result<()> {
    // same path logic as load_global_config
    let path = env::var("APICURIO_REGISTRIES_PATH")
        .map(PathBuf::from)
        .unwrap_or_else(|_| {
            let mut p = dirs::config_dir().unwrap_or_else(|| PathBuf::from("."));
            p.push("apicurio/registries.yaml");
            p
        });
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }
    let data = serde_yaml::to_string(cfg)?;
    fs::write(&path, data)?;
    println!("Saved global registries to {}", path.display());
    Ok(())
}

pub fn expand_env_placeholders(input: &str) -> String {
    let re = Regex::new(r"\$\{([A-Za-z_][A-Za-z0-9_]*)(?:(:?[-+])([^}]*))?\}").unwrap();
    re.replace_all(input, |caps: &regex::Captures| {
        let var_name = &caps[1];
        let op = caps.get(2).map_or("", |m| m.as_str());
        let val = caps.get(3).map_or("", |m| m.as_str());
        let var = env::var(var_name).ok();

        match (var.as_deref(), op) {
            (Some(v), _) if op.is_empty() => v.to_string(), // ${VAR}
            (Some(v), ":-") if !v.is_empty() => v.to_string(), // ${VAR:-default}
            (None, ":-") => val.to_string(),
            (Some(v), "-") => {
                if v.is_empty() {
                    val.to_string()
                } else {
                    v.to_string()
                }
            } // ${VAR-default}
            (None, "-") => val.to_string(),
            (Some(v), ":+") if !v.is_empty() => val.to_string(), // ${VAR:+alt}
            (Some(_), "+") => val.to_string(),                   // ${VAR+alt}
            _ => "".to_string(),
        }
    })
    .to_string()
}

pub fn preprocess_config(path: &Path) -> anyhow::Result<String> {
    let raw_data = fs::read_to_string(path)?;
    Ok(expand_env_placeholders(&raw_data))
}