audb 0.1.11

AuDB - Compile-time database application framework with gold files
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
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
//! Dependency management for AuDB projects
//!
//! This module handles project dependencies that will be added to the generated
//! Cargo.toml file. It supports:
//!
//! - Latest compatible version (default when no version specified)
//! - Explicit version pinning
//! - Version requirement formats (^, ~, >=, =)
//! - Feature flags
//!
//! ## Usage
//!
//! ```ignore
//! use audb::model::DependencySpec;
//!
//! // Latest compatible version
//! let dep = DependencySpec::new("serde");
//!
//! // With specific version
//! let dep = DependencySpec::new("tokio").version("1.0");
//!
//! // With features
//! let dep = DependencySpec::new("tokio")
//!     .version("1.0")
//!     .features(vec!["full"]);
//! ```

use std::collections::HashMap;

/// Dependency specification for a Rust crate
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DependencySpec {
    /// Crate name
    pub name: String,

    /// Version requirement (None = latest compatible)
    pub version: Option<VersionRequirement>,

    /// Feature flags to enable
    pub features: Vec<String>,

    /// Whether this is an optional dependency
    pub optional: bool,

    /// Whether to use default features
    pub default_features: bool,

    /// Git repository URL (alternative to crates.io)
    pub git: Option<String>,

    /// Git branch/tag/rev
    pub git_ref: Option<GitRef>,

    /// Local path (for path dependencies)
    pub path: Option<String>,
}

impl DependencySpec {
    /// Create a new dependency with the given name
    ///
    /// By default, uses latest compatible version from crates.io.
    pub fn new<S: Into<String>>(name: S) -> Self {
        Self {
            name: name.into(),
            version: None,
            features: Vec::new(),
            optional: false,
            default_features: true,
            git: None,
            git_ref: None,
            path: None,
        }
    }

    /// Set the version requirement
    pub fn version<S: Into<String>>(mut self, version: S) -> Self {
        self.version = Some(VersionRequirement::parse(version.into()));
        self
    }

    /// Set feature flags
    pub fn features<I, S>(mut self, features: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.features = features.into_iter().map(|s| s.into()).collect();
        self
    }

    /// Add a single feature
    pub fn feature<S: Into<String>>(mut self, feature: S) -> Self {
        self.features.push(feature.into());
        self
    }

    /// Mark as optional dependency
    pub fn optional(mut self, optional: bool) -> Self {
        self.optional = optional;
        self
    }

    /// Set whether to use default features
    pub fn default_features(mut self, enable: bool) -> Self {
        self.default_features = enable;
        self
    }

    /// Set Git repository URL
    pub fn git<S: Into<String>>(mut self, url: S) -> Self {
        self.git = Some(url.into());
        self
    }

    /// Set Git branch
    pub fn branch<S: Into<String>>(mut self, branch: S) -> Self {
        self.git_ref = Some(GitRef::Branch(branch.into()));
        self
    }

    /// Set Git tag
    pub fn tag<S: Into<String>>(mut self, tag: S) -> Self {
        self.git_ref = Some(GitRef::Tag(tag.into()));
        self
    }

    /// Set Git revision
    pub fn rev<S: Into<String>>(mut self, rev: S) -> Self {
        self.git_ref = Some(GitRef::Rev(rev.into()));
        self
    }

    /// Set local path
    pub fn path<S: Into<String>>(mut self, path: S) -> Self {
        self.path = Some(path.into());
        self
    }

    /// Generate Cargo.toml entry for this dependency
    pub fn to_toml_string(&self) -> String {
        // Simple case: just the crate name
        if self.features.is_empty()
            && self.default_features
            && self.version.is_none()
            && self.git.is_none()
            && self.path.is_none()
            && !self.optional
        {
            return format!("{} = \"*\"", self.name);
        }

        let mut parts = Vec::new();

        // Version
        if let Some(ref version) = self.version {
            parts.push(format!("version = \"{}\"", version));
        }

        // Git
        if let Some(ref git) = self.git {
            parts.push(format!("git = \"{}\"", git));
            if let Some(ref git_ref) = self.git_ref {
                match git_ref {
                    GitRef::Branch(b) => parts.push(format!("branch = \"{}\"", b)),
                    GitRef::Tag(t) => parts.push(format!("tag = \"{}\"", t)),
                    GitRef::Rev(r) => parts.push(format!("rev = \"{}\"", r)),
                }
            }
        }

        // Path
        if let Some(ref path) = self.path {
            parts.push(format!("path = \"{}\"", path));
        }

        // Features
        if !self.features.is_empty() {
            let features_str = self
                .features
                .iter()
                .map(|f| format!("\"{}\"", f))
                .collect::<Vec<_>>()
                .join(", ");
            parts.push(format!("features = [{}]", features_str));
        }

        // Optional
        if self.optional {
            parts.push("optional = true".to_string());
        }

        // Default features
        if !self.default_features {
            parts.push("default-features = false".to_string());
        }

        if parts.is_empty() {
            format!("{} = \"*\"", self.name)
        } else {
            format!("{} = {{ {} }}", self.name, parts.join(", "))
        }
    }
}

/// Version requirement for a dependency
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VersionRequirement {
    /// Any version (*)
    Any,

    /// Exact version (=1.0.0)
    Exact(String),

    /// Caret requirement (^1.0)
    Caret(String),

    /// Tilde requirement (~1.0)
    Tilde(String),

    /// Greater than or equal (>=1.0)
    GreaterOrEqual(String),

    /// Less than (<2.0)
    LessThan(String),

    /// Complex requirement (>=1.0, <2.0)
    Complex(String),
}

impl VersionRequirement {
    /// Parse a version requirement string
    pub fn parse(s: String) -> Self {
        if s.is_empty() || s == "*" {
            return VersionRequirement::Any;
        }

        if s.starts_with('=') {
            return VersionRequirement::Exact(s[1..].trim().to_string());
        }

        if s.starts_with('^') {
            return VersionRequirement::Caret(s[1..].trim().to_string());
        }

        if s.starts_with('~') {
            return VersionRequirement::Tilde(s[1..].trim().to_string());
        }

        if s.starts_with(">=") {
            return VersionRequirement::GreaterOrEqual(s[2..].trim().to_string());
        }

        if s.starts_with('<') {
            return VersionRequirement::LessThan(s[1..].trim().to_string());
        }

        if s.contains(',') {
            return VersionRequirement::Complex(s);
        }

        // Default to caret requirement for bare version numbers
        VersionRequirement::Caret(s)
    }
}

impl std::fmt::Display for VersionRequirement {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            VersionRequirement::Any => write!(f, "*"),
            VersionRequirement::Exact(v) => write!(f, "={}", v),
            VersionRequirement::Caret(v) => write!(f, "^{}", v),
            VersionRequirement::Tilde(v) => write!(f, "~{}", v),
            VersionRequirement::GreaterOrEqual(v) => write!(f, ">={}", v),
            VersionRequirement::LessThan(v) => write!(f, "<{}", v),
            VersionRequirement::Complex(v) => write!(f, "{}", v),
        }
    }
}

/// Git reference type
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GitRef {
    /// Branch name
    Branch(String),

    /// Tag name
    Tag(String),

    /// Commit revision
    Rev(String),
}

/// Dependency manager for a project
#[derive(Debug, Clone, Default)]
pub struct DependencyManager {
    /// All dependencies
    dependencies: HashMap<String, DependencySpec>,
}

impl DependencyManager {
    /// Create a new empty dependency manager
    pub fn new() -> Self {
        Self {
            dependencies: HashMap::new(),
        }
    }

    /// Add a dependency
    pub fn add(&mut self, dep: DependencySpec) -> &mut Self {
        self.dependencies.insert(dep.name.clone(), dep);
        self
    }

    /// Remove a dependency by name
    pub fn remove(&mut self, name: &str) -> Option<DependencySpec> {
        self.dependencies.remove(name)
    }

    /// Get a dependency by name
    pub fn get(&self, name: &str) -> Option<&DependencySpec> {
        self.dependencies.get(name)
    }

    /// Check if a dependency exists
    pub fn contains(&self, name: &str) -> bool {
        self.dependencies.contains_key(name)
    }

    /// List all dependency names
    pub fn list(&self) -> Vec<&str> {
        self.dependencies.keys().map(|s| s.as_str()).collect()
    }

    /// Get all dependencies
    pub fn all(&self) -> &HashMap<String, DependencySpec> {
        &self.dependencies
    }

    /// Generate Cargo.toml [dependencies] section
    pub fn to_toml_section(&self) -> String {
        if self.dependencies.is_empty() {
            return String::new();
        }

        let mut lines = vec!["[dependencies]".to_string()];
        let mut deps: Vec<_> = self.dependencies.values().collect();
        deps.sort_by(|a, b| a.name.cmp(&b.name));

        for dep in deps {
            lines.push(dep.to_toml_string());
        }

        lines.join("\n")
    }

    /// Merge dependencies from another manager
    pub fn merge(&mut self, other: &DependencyManager) {
        for (name, dep) in &other.dependencies {
            self.dependencies.insert(name.clone(), dep.clone());
        }
    }
}

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

    #[test]
    fn test_simple_dependency() {
        let dep = DependencySpec::new("serde");
        assert_eq!(dep.name, "serde");
        assert_eq!(dep.version, None);
        assert!(dep.features.is_empty());
    }

    #[test]
    fn test_dependency_with_version() {
        let dep = DependencySpec::new("serde").version("1.0");
        assert_eq!(dep.name, "serde");
        assert_eq!(
            dep.version,
            Some(VersionRequirement::Caret("1.0".to_string()))
        );
    }

    #[test]
    fn test_dependency_with_features() {
        let dep = DependencySpec::new("tokio").features(vec!["full", "rt"]);
        assert_eq!(dep.features, vec!["full", "rt"]);
    }

    #[test]
    fn test_version_requirement_parsing() {
        assert_eq!(
            VersionRequirement::parse("*".to_string()),
            VersionRequirement::Any
        );
        assert_eq!(
            VersionRequirement::parse("=1.0.0".to_string()),
            VersionRequirement::Exact("1.0.0".to_string())
        );
        assert_eq!(
            VersionRequirement::parse("^1.0".to_string()),
            VersionRequirement::Caret("1.0".to_string())
        );
        assert_eq!(
            VersionRequirement::parse("~1.0".to_string()),
            VersionRequirement::Tilde("1.0".to_string())
        );
        assert_eq!(
            VersionRequirement::parse(">=1.0".to_string()),
            VersionRequirement::GreaterOrEqual("1.0".to_string())
        );
        assert_eq!(
            VersionRequirement::parse("1.0".to_string()),
            VersionRequirement::Caret("1.0".to_string())
        );
    }

    #[test]
    fn test_toml_string_simple() {
        let dep = DependencySpec::new("serde");
        assert_eq!(dep.to_toml_string(), "serde = \"*\"");
    }

    #[test]
    fn test_toml_string_with_version() {
        let dep = DependencySpec::new("serde").version("1.0");
        assert_eq!(dep.to_toml_string(), "serde = { version = \"^1.0\" }");
    }

    #[test]
    fn test_toml_string_with_features() {
        let dep = DependencySpec::new("tokio")
            .version("1.0")
            .features(vec!["full"]);
        assert!(dep.to_toml_string().contains("features = [\"full\"]"));
    }

    #[test]
    fn test_dependency_manager() {
        let mut manager = DependencyManager::new();

        manager.add(DependencySpec::new("serde").version("1.0"));
        manager.add(
            DependencySpec::new("tokio")
                .version("1.0")
                .features(vec!["full"]),
        );

        assert!(manager.contains("serde"));
        assert!(manager.contains("tokio"));
        assert_eq!(manager.list().len(), 2);
    }

    #[test]
    fn test_dependency_manager_remove() {
        let mut manager = DependencyManager::new();
        manager.add(DependencySpec::new("serde"));

        assert!(manager.contains("serde"));
        manager.remove("serde");
        assert!(!manager.contains("serde"));
    }

    #[test]
    fn test_toml_section_generation() {
        let mut manager = DependencyManager::new();
        manager.add(DependencySpec::new("serde").version("1.0"));
        manager.add(DependencySpec::new("tokio").version("1.0"));

        let toml = manager.to_toml_section();
        assert!(toml.contains("[dependencies]"));
        assert!(toml.contains("serde"));
        assert!(toml.contains("tokio"));
    }

    #[test]
    fn test_git_dependency() {
        let dep = DependencySpec::new("my-crate")
            .git("https://github.com/user/repo")
            .branch("main");

        let toml = dep.to_toml_string();
        assert!(toml.contains("git = \"https://github.com/user/repo\""));
        assert!(toml.contains("branch = \"main\""));
    }

    #[test]
    fn test_path_dependency() {
        let dep = DependencySpec::new("local-crate").path("../local-crate");

        let toml = dep.to_toml_string();
        assert!(toml.contains("path = \"../local-crate\""));
    }

    #[test]
    fn test_optional_dependency() {
        let dep = DependencySpec::new("feature-dep")
            .version("1.0")
            .optional(true);

        let toml = dep.to_toml_string();
        assert!(toml.contains("optional = true"));
    }

    #[test]
    fn test_no_default_features() {
        let dep = DependencySpec::new("minimal")
            .version("1.0")
            .default_features(false);

        let toml = dep.to_toml_string();
        assert!(toml.contains("default-features = false"));
    }
}