quanttide-devops 0.1.3

QuantTide DevOps toolkit — 契约驱动的 DevOps 治理工具库
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
use super::{platform::*, scope::*, source::*, stage::*};
use serde::{Deserialize, Serialize};
use std::path::Path;

// ── Contract ──────────────────────────────────────────────────────────

/// 完整契约,对应 `.quanttide/devops/contract.yaml`。
///
/// 按四维架构组织:Stage(时序)、Platform(载体)、Source(事实源)、Scope(边界)。
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct Contract {
    #[serde(default)]
    pub stages: Stage,
    #[serde(default)]
    pub platform: Platform,
    #[serde(default)]
    pub sources: Source,
    #[serde(default, deserialize_with = "deserialize_scopes")]
    pub scopes: Vec<Scope>,
}

// ── 便捷访问器 ────────────────────────────────────────────────────────

impl Contract {
    /// 获取 scope 的发布配置(scope 级覆盖 → 全局默认)。
    pub fn scope_release<'a>(&'a self, scope: &'a Scope) -> &'a StageRelease {
        let has_custom =
            !scope.release.pre_publish.is_empty() || scope.release.changelog != "CHANGELOG.md";
        if has_custom {
            &scope.release
        } else {
            &self.stages.release
        }
    }

    /// 获取 scope 的测试阈值。
    pub fn scope_test_threshold(&self, scope: &Scope) -> f64 {
        scope.test_threshold.unwrap_or(self.stages.test.threshold)
    }

    /// 根据路径查找匹配的 scope(最长前缀匹配)。
    ///
    /// 例如当前在 `src/cli/sub` 时,`cli` scope(dir: `src/cli`)
    /// 比 root scope(dir: `.`)优先级高。
    pub fn find_scope_by_path(&self, current_dir: &Path) -> Option<&Scope> {
        let current_str = current_dir.to_string_lossy();
        self.scopes
            .iter()
            .filter(|s| current_str.starts_with(&s.dir) || s.dir == ".")
            .max_by_key(|s| s.dir.len())
    }

    /// 语言探测:scope 声明了具体语言则返回,否则按目录文件推测。
    pub fn resolve_language(&self, scope: &Scope, scope_dir: &Path) -> Language {
        match &scope.language {
            Language::Unknown(_) => detect_language_by_files(scope_dir),
            lang => lang.clone(),
        }
    }

    /// 验算契约:检查 scope 配置是否合法。
    ///
    /// 返回所有问题的描述列表,空表示合法。
    ///
    /// ```
    /// use std::path::Path;
    /// use quanttide_devops::contract::Contract;
    ///
    /// let c = Contract::default();
    /// let errors = c.validate(Path::new("/tmp/nonexistent"));
    /// assert!(errors.is_empty()); // 空契约→无 scope 可检查
    /// ```
    pub fn validate(&self, repo_path: &Path) -> Vec<String> {
        let mut errors = Vec::new();
        for scope in &self.scopes {
            let dir = repo_path.join(&scope.dir);
            if !dir.exists() {
                errors.push(format!("scope '{}' 目录不存在: {}", scope.name, scope.dir));
            }
        }
        errors
    }
}

/// 根据目录下的标志文件推测编程语言。
pub fn detect_language_by_files(dir: &Path) -> Language {
    if dir.join("Cargo.toml").exists() {
        Language::Rust
    } else if dir.join("pyproject.toml").exists() || dir.join("requirements.txt").exists() {
        Language::Python
    } else if dir.join("go.mod").exists() {
        Language::Go
    } else if dir.join("pubspec.yaml").exists() {
        Language::Dart
    } else if dir.join("package.json").exists() {
        Language::TypeScript
    } else {
        Language::Unknown("无法识别".into())
    }
}

// ═══════════════════════════════════════════════════════════════════════
// 测试
// ═══════════════════════════════════════════════════════════════════════

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

    fn parse_yaml(s: &str) -> Contract {
        serde_yaml::from_str(s).expect("YAML 应能解析")
    }

    // ── 完整契约 ──────────────────────────────────────────────────

    #[test]
    fn test_full_contract() {
        let yaml = r#"
stages:
  build:
    command: cargo build
  test:
    command: cargo test
    threshold: 80.0
  release:
    changelog: CHANGELOG.md
    pre_publish:
      - cargo publish

platform:
  source_control: github
  pipeline: github_actions
  artifact_registry: crates

sources:
  version:
    type: cargo

scopes:
  cli:
    dir: src/cli
    language: rust
    build_tool: cargo
    registry: crates
    test_threshold: 90.0
  web:
    dir: src/web
    language: typescript
    build_tool: npm
"#;
        let c: Contract = parse_yaml(yaml);
        assert_eq!(c.stages.build.command.as_deref(), Some("cargo build"));
        assert_eq!(c.stages.test.threshold, 80.0);
        assert_eq!(c.stages.test.command.as_deref(), Some("cargo test"));
        assert_eq!(c.stages.release.changelog, "CHANGELOG.md");
        assert_eq!(
            c.stages.release.pre_publish,
            vec!["cargo publish".to_string()]
        );

        assert_eq!(c.platform.source_control, SourceControl::Github);
        assert_eq!(c.platform.pipeline, Pipeline::GithubActions);
        assert_eq!(c.platform.artifact_registry, Registry::Crates);

        assert_eq!(c.sources.version.source_type, SourceType::Cargo);

        assert_eq!(c.scopes.len(), 2);

        let cli = &c.scopes[0];
        assert_eq!(cli.name, "cli");
        assert_eq!(cli.dir, "src/cli");
        assert_eq!(cli.language, Language::Rust);
        assert_eq!(cli.build_tool, BuildTool::Cargo);
        assert_eq!(cli.registry, Registry::Crates);
        assert_eq!(cli.test_threshold, Some(90.0));

        let web = &c.scopes[1];
        assert_eq!(web.name, "web");
        assert_eq!(web.language, Language::TypeScript);
        assert_eq!(web.build_tool, BuildTool::Npm);
    }

    // ── 最小契约(全默认值) ──────────────────────────────────────

    #[test]
    fn test_empty_contract() {
        let yaml = r#"
stages:
scopes:
"#;
        let c: Contract = parse_yaml(yaml);
        assert_eq!(c.stages.build.command, None);
        assert_eq!(c.stages.test.threshold, 70.0);
        assert_eq!(c.stages.release.changelog, "CHANGELOG.md");
        assert_eq!(c.platform.source_control, SourceControl::Github);
        assert_eq!(c.sources.version.source_type, SourceType::Auto);
        assert!(c.scopes.is_empty());
    }

    #[test]
    fn test_fully_empty_yaml() {
        let c: Contract = serde_yaml::from_str("").unwrap_or_default();
        assert_eq!(c.stages.test.threshold, 70.0);
        assert!(c.scopes.is_empty());
    }

    // ── Language 解析 ─────────────────────────────────────────────

    #[test]
    fn test_language_parse() {
        let c: Contract = parse_yaml(
            r#"
scopes:
  a:
    dir: .
    language: rust
  b:
    dir: .
    language: typescript
  c:
    dir: .
    language: ts
  d:
    dir: .
    language: node
  e:
    dir: .
    language: unknown_lang
"#,
        );
        assert_eq!(c.scopes[0].language, Language::Rust);
        assert_eq!(c.scopes[1].language, Language::TypeScript);
        assert_eq!(c.scopes[2].language, Language::TypeScript);
        assert_eq!(c.scopes[3].language, Language::TypeScript);
        assert_eq!(
            c.scopes[4].language,
            Language::Unknown("unknown_lang".into())
        );
    }

    // ── Registry 解析 ─────────────────────────────────────────────

    #[test]
    fn test_registry_parse() {
        let c: Contract = parse_yaml(
            r#"
platform:
  artifact_registry: pypi
scopes:
  s:
    dir: .
    registry: github_releases
"#,
        );
        assert_eq!(c.platform.artifact_registry, Registry::PyPI);
        assert_eq!(c.scopes[0].registry, Registry::GitHubReleases);
    }

    // ── SourceType 解析 ───────────────────────────────────────────

    #[test]
    fn test_source_type() {
        let c: Contract = parse_yaml(
            r#"
sources:
  version:
    type: package.json
"#,
        );
        assert_eq!(c.sources.version.source_type, SourceType::PackageJson);
    }

    // ── 便捷访问器 ────────────────────────────────────────────────

    #[test]
    fn test_scope_release_fallback() {
        let c: Contract = parse_yaml(
            r#"
stages:
  release:
    changelog: CHANGELOG.md
    pre_publish:
      - cargo publish
scopes:
  cli:
    dir: src/cli
    language: rust
"#,
        );
        let cli = &c.scopes[0];
        let rel = c.scope_release(cli);
        assert_eq!(rel.pre_publish, vec!["cargo publish".to_string()]);
    }

    #[test]
    fn test_scope_release_override() {
        let c: Contract = parse_yaml(
            r#"
stages:
  release:
    changelog: CHANGELOG.md
scopes:
  cli:
    dir: src/cli
    language: rust
    release:
      changelog: docs/CHANGELOG.md
"#,
        );
        let cli = &c.scopes[0];
        let rel = c.scope_release(cli);
        assert_eq!(rel.changelog, "docs/CHANGELOG.md");
    }

    #[test]
    fn test_scope_test_threshold() {
        let c: Contract = parse_yaml(
            r#"
stages:
  test:
    threshold: 70.0
scopes:
  a:
    dir: .
  b:
    dir: .
    test_threshold: 90.0
"#,
        );
        assert_eq!(c.scope_test_threshold(&c.scopes[0]), 70.0);
        assert_eq!(c.scope_test_threshold(&c.scopes[1]), 90.0);
    }

    // ── find_scope_by_path ────────────────────────────────────────

    #[test]
    fn test_find_scope_by_path() {
        let c: Contract = parse_yaml(
            r#"
scopes:
  root:
    dir: .
  cli:
    dir: src/cli
  web:
    dir: src/web
"#,
        );
        assert_eq!(
            c.find_scope_by_path(std::path::Path::new("src/cli/sub"))
                .map(|s| s.name.as_str()),
            Some("cli")
        );
        assert_eq!(
            c.find_scope_by_path(std::path::Path::new("src/web"))
                .map(|s| s.name.as_str()),
            Some("web")
        );
        assert_eq!(
            c.find_scope_by_path(std::path::Path::new("unknown"))
                .map(|s| s.name.as_str()),
            Some("root")
        );
    }

    // ── resolve_language ──────────────────────────────────────────

    #[test]
    fn test_resolve_language_declared() {
        let c: Contract = parse_yaml(
            r#"
scopes:
  cli:
    dir: .
    language: rust
"#,
        );
        let lang = c.resolve_language(&c.scopes[0], std::path::Path::new("/tmp"));
        assert_eq!(lang, Language::Rust);
    }

    #[test]
    fn test_resolve_language_auto() {
        let d = tempfile::tempdir().unwrap();
        std::fs::write(d.path().join("Cargo.toml"), "").unwrap();
        let c: Contract = parse_yaml(
            r#"
scopes:
  cli:
    dir: .
"#,
        );
        let lang = c.resolve_language(&c.scopes[0], d.path());
        assert_eq!(lang, Language::Rust);
    }

    // ── detect_language_by_files ──────────────────────────────────

    #[test]
    fn test_detect_by_files() {
        let d = tempfile::tempdir().unwrap();
        assert_eq!(
            detect_language_by_files(d.path()),
            Language::Unknown("无法识别".into())
        );
        std::fs::write(d.path().join("Cargo.toml"), "").unwrap();
        assert_eq!(detect_language_by_files(d.path()), Language::Rust);
        std::fs::write(d.path().join("go.mod"), "").unwrap();
        // Cargo.toml 优先(顺序检测)
        assert_eq!(detect_language_by_files(d.path()), Language::Rust);
    }
}