bito 2.0.0

Quality gate tooling for building-in-the-open artifacts
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
//! Configuration integration tests.
//!
//! These tests verify config discovery, format parsing, and precedence
//! from an end-to-end perspective using the compiled binary. Tests use
//! `info --json` to assert actual config values, not just process success.

use assert_cmd::Command;
use predicates::prelude::*;
use serde_json::Value;
use std::fs;
use tempfile::TempDir;

/// Returns a Command configured to run our binary.
#[allow(deprecated)]
fn cmd() -> Command {
    let mut cmd = Command::cargo_bin(env!("CARGO_PKG_NAME")).unwrap();
    // Route log output to a temp directory so tests don't write to production paths
    let prefix = env!("CARGO_PKG_NAME").to_uppercase().replace('-', "_");
    let test_log_dir = std::env::temp_dir().join(format!("{}-test-logs", env!("CARGO_PKG_NAME")));
    cmd.env(format!("{prefix}_LOG_DIR"), test_log_dir);
    // See the note on cli.rs's helper: an unsuppressed release check costs up
    // to 30 seconds per subprocess on an offline runner.
    cmd.env("BITO_NO_UPDATE_CHECK", "1");
    cmd
}

/// Run `info --json` from a directory and parse the JSON output.
fn info_json(dir: &std::path::Path) -> Value {
    let output = cmd()
        .args(["-C", dir.to_str().unwrap(), "info", "--json"])
        .output()
        .expect("failed to run command");
    assert!(
        output.status.success(),
        "command failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    serde_json::from_slice(&output.stdout).expect("invalid JSON output")
}

// =============================================================================
// Config File Discovery
// =============================================================================

#[test]
fn runs_without_config_file() {
    let tmp = TempDir::new().unwrap();
    let json = info_json(tmp.path());

    assert_eq!(
        json["config"]["log_level"], "info",
        "should use default log level"
    );
    assert!(
        json["config"]["config_file"].is_null(),
        "no config file should be reported"
    );
}

#[test]
fn discovers_dotfile_config_in_current_dir() {
    let tmp = TempDir::new().unwrap();
    let config_path = tmp.path().join(".bito.toml");
    fs::write(&config_path, r#"log_level = "debug""#).unwrap();

    let json = info_json(tmp.path());

    assert_eq!(json["config"]["log_level"], "debug");
    let reported = json["config"]["config_file"].as_str().unwrap();
    assert!(
        reported.ends_with(".bito.toml"),
        "should report dotfile: {reported}"
    );
}

#[test]
fn discovers_regular_config_in_current_dir() {
    let tmp = TempDir::new().unwrap();
    let config_path = tmp.path().join("bito.toml");
    fs::write(&config_path, r#"log_level = "warn""#).unwrap();

    let json = info_json(tmp.path());

    assert_eq!(json["config"]["log_level"], "warn");
    let reported = json["config"]["config_file"].as_str().unwrap();
    assert!(
        reported.ends_with("bito.toml"),
        "should report regular config: {reported}"
    );
}

#[test]
fn discovers_config_in_parent_directory() {
    let tmp = TempDir::new().unwrap();
    let sub_dir = tmp.path().join("nested").join("deep");
    fs::create_dir_all(&sub_dir).unwrap();

    // Config in root, run from nested/deep
    fs::write(tmp.path().join(".bito.toml"), r#"log_level = "debug""#).unwrap();

    let json = info_json(&sub_dir);

    assert_eq!(json["config"]["log_level"], "debug");
    assert!(
        json["config"]["config_file"].as_str().is_some(),
        "should find parent config"
    );
}

#[test]
fn discovers_dotconfig_directory_config() {
    let tmp = TempDir::new().unwrap();
    let dotconfig = tmp.path().join(".config");
    fs::create_dir_all(&dotconfig).unwrap();
    fs::write(dotconfig.join("bito.toml"), r#"log_level = "debug""#).unwrap();

    let json = info_json(tmp.path());

    assert_eq!(json["config"]["log_level"], "debug");
    let reported = json["config"]["config_file"].as_str().unwrap();
    assert!(
        reported.contains(".config/"),
        "should report .config/ path: {reported}"
    );
}

#[test]
fn dotconfig_takes_precedence_over_dotfile() {
    let tmp = TempDir::new().unwrap();
    let dotconfig = tmp.path().join(".config");
    fs::create_dir_all(&dotconfig).unwrap();

    // .config/ gets debug, dotfile gets error — .config/ should win
    fs::write(dotconfig.join("bito.toml"), r#"log_level = "debug""#).unwrap();
    fs::write(tmp.path().join(".bito.toml"), r#"log_level = "error""#).unwrap();

    let json = info_json(tmp.path());

    assert_eq!(
        json["config"]["log_level"], "debug",
        ".config/ should win over dotfile"
    );
}

#[test]
fn dotfile_takes_precedence_over_regular_name() {
    let tmp = TempDir::new().unwrap();

    // Both configs exist — dotfile is checked first and wins
    fs::write(tmp.path().join(".bito.toml"), r#"log_level = "debug""#).unwrap();
    fs::write(tmp.path().join("bito.toml"), r#"log_level = "error""#).unwrap();

    let json = info_json(tmp.path());

    assert_eq!(
        json["config"]["log_level"], "debug",
        "dotfile should win over regular name"
    );
}

// =============================================================================
// Config Format Parsing
// =============================================================================

#[test]
fn parses_toml_config() {
    let tmp = TempDir::new().unwrap();
    fs::write(tmp.path().join(".bito.toml"), r#"log_level = "warn""#).unwrap();

    let json = info_json(tmp.path());
    assert_eq!(json["config"]["log_level"], "warn");
}

#[test]
fn parses_yaml_config() {
    let tmp = TempDir::new().unwrap();
    fs::write(tmp.path().join(".bito.yaml"), "log_level: warn\n").unwrap();

    let json = info_json(tmp.path());
    assert_eq!(json["config"]["log_level"], "warn");
}

#[test]
fn parses_yml_config() {
    let tmp = TempDir::new().unwrap();
    fs::write(tmp.path().join(".bito.yml"), "log_level: debug\n").unwrap();

    let json = info_json(tmp.path());
    assert_eq!(json["config"]["log_level"], "debug");
}

#[test]
fn parses_json_config() {
    let tmp = TempDir::new().unwrap();
    fs::write(tmp.path().join(".bito.json"), r#"{"log_level": "error"}"#).unwrap();

    let json = info_json(tmp.path());
    assert_eq!(json["config"]["log_level"], "error");
}

// =============================================================================
// Config Precedence
// =============================================================================

#[test]
fn closer_config_takes_precedence() {
    let tmp = TempDir::new().unwrap();
    let sub_dir = tmp.path().join("project");
    fs::create_dir_all(&sub_dir).unwrap();

    // Parent config (error) vs child config (debug) — child should win
    fs::write(tmp.path().join(".bito.toml"), r#"log_level = "error""#).unwrap();
    fs::write(sub_dir.join(".bito.toml"), r#"log_level = "debug""#).unwrap();

    let json = info_json(&sub_dir);

    assert_eq!(
        json["config"]["log_level"], "debug",
        "closer config should win"
    );
}

#[test]
fn first_extension_wins_in_same_directory() {
    let tmp = TempDir::new().unwrap();

    // Both dotfiles exist — TOML is checked first and wins
    fs::write(tmp.path().join(".bito.toml"), r#"log_level = "debug""#).unwrap();
    fs::write(tmp.path().join(".bito.yaml"), "log_level: error\n").unwrap();

    let json = info_json(tmp.path());
    assert_eq!(
        json["config"]["log_level"], "debug",
        "first extension (TOML) should win"
    );
}

#[test]
fn explicit_config_overrides_discovered() {
    let tmp = TempDir::new().unwrap();

    // Project config sets debug
    fs::write(tmp.path().join(".bito.toml"), r#"log_level = "debug""#).unwrap();

    // Explicit config sets error
    let explicit = tmp.path().join("override.toml");
    fs::write(&explicit, r#"log_level = "error""#).unwrap();

    let output = cmd()
        .args([
            "-C",
            tmp.path().to_str().unwrap(),
            "--config",
            explicit.to_str().unwrap(),
            "info",
            "--json",
        ])
        .output()
        .expect("failed to run command");
    assert!(output.status.success());

    let json: Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(
        json["config"]["log_level"], "error",
        "--config should override discovered config"
    );
    let reported = json["config"]["config_file"].as_str().unwrap();
    assert!(
        reported.ends_with("override.toml"),
        "--config path should be reported: {reported}"
    );
}

// =============================================================================
// Error Cases
// =============================================================================

#[test]
fn invalid_toml_config_shows_error() {
    let tmp = TempDir::new().unwrap();
    fs::write(tmp.path().join(".bito.toml"), "this is not valid toml [[[").unwrap();

    cmd()
        .args(["-C", tmp.path().to_str().unwrap(), "info"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("configuration").or(predicate::str::contains("config")));
}

#[test]
fn invalid_yaml_config_shows_error() {
    let tmp = TempDir::new().unwrap();
    fs::write(
        tmp.path().join(".bito.yaml"),
        "invalid:\n  yaml\n content:\n[broken",
    )
    .unwrap();

    cmd()
        .args(["-C", tmp.path().to_str().unwrap(), "info"])
        .assert()
        .failure();
}

#[test]
fn invalid_json_config_shows_error() {
    let tmp = TempDir::new().unwrap();
    fs::write(tmp.path().join(".bito.json"), "{not valid json}").unwrap();

    cmd()
        .args(["-C", tmp.path().to_str().unwrap(), "info"])
        .assert()
        .failure();
}

#[test]
fn unknown_config_field_is_ignored() {
    // Figment ignores unknown fields by default with serde
    let tmp = TempDir::new().unwrap();
    fs::write(
        tmp.path().join(".bito.toml"),
        "log_level = \"info\"\nunknown_field = \"should be ignored\"\nanother_unknown = 42\n",
    )
    .unwrap();

    let json = info_json(tmp.path());
    assert_eq!(json["config"]["log_level"], "info");
}

// =============================================================================
// Boundary Marker Tests
// =============================================================================

#[test]
fn git_boundary_stops_config_search() {
    let tmp = TempDir::new().unwrap();

    // Structure: /tmp/parent/.project.toml + /tmp/parent/repo/.git/ + /tmp/parent/repo/src/
    let parent = tmp.path().join("parent");
    let repo = parent.join("repo");
    let src = repo.join("src");
    fs::create_dir_all(&src).unwrap();

    // Config in parent (outside repo)
    fs::write(parent.join(".bito.toml"), r#"log_level = "error""#).unwrap();

    // .git directory marks repo boundary
    fs::create_dir(repo.join(".git")).unwrap();

    // Running from src/ should NOT find parent config (stopped at .git)
    let json = info_json(&src);

    assert_eq!(
        json["config"]["log_level"], "info",
        "should use default — boundary stops search"
    );
    assert!(
        json["config"]["config_file"].is_null(),
        "should not find config beyond boundary"
    );
}

#[test]
fn config_in_same_dir_as_git_is_found() {
    let tmp = TempDir::new().unwrap();
    let repo = tmp.path().join("repo");
    let src = repo.join("src");
    fs::create_dir_all(&src).unwrap();

    // .git and config in same directory
    fs::create_dir(repo.join(".git")).unwrap();
    fs::write(repo.join(".bito.toml"), r#"log_level = "debug""#).unwrap();

    // Running from src/ should find the repo config
    let json = info_json(&src);

    assert_eq!(
        json["config"]["log_level"], "debug",
        "config next to .git should be found"
    );
    assert!(
        json["config"]["config_file"].as_str().is_some(),
        "should report config file"
    );
}

// =============================================================================
// Environment Variable Typing
// =============================================================================
//
// These run with `-C <tempdir>` deliberately. Config discovery walks up from
// the working directory, and bito's own `.config/bito.yaml` sets `max_grade`
// and `passive_max_percent` — which is exactly what supplies the type these
// tests exist to check. Run from the repo, they pass against a librebar that
// cannot type an unset optional at all.

/// Every numeric config field has to be settable from the environment.
///
/// librebar types environment values against the serialized defaults, and
/// every numeric field on `Config` is an `Option<T>` defaulting to `None` —
/// which serializes to `null` and carries no type. Before librebar 0.6 these
/// arrived as strings and bito refused to start: exit 2, "invalid type:
/// string". The failure was total, yet no test caught it, because all six
/// existing environment tests set `BITO_DIALECT` — a string, and strings were
/// the one shape that already worked.
#[test]
fn numeric_environment_variables_are_typed() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path().to_str().unwrap();

    for (variable, value) in [
        ("BITO_MAX_GRADE", "12.0"),
        ("BITO_TOKEN_BUDGET", "4000"),
        ("BITO_PASSIVE_MAX_PERCENT", "15.0"),
        ("BITO_STYLE_MIN_SCORE", "70"),
        ("BITO_MAX_INPUT_BYTES", "1048576"),
        ("BITO_LOG_RETENTION_DAYS", "3"),
    ] {
        let output = cmd()
            .env(variable, value)
            .args(["-C", dir, "--format", "text", "info"])
            .output()
            .expect("failed to run command");

        assert!(
            output.status.success(),
            "{variable}={value} should load: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }
}

/// Parsing a value is not the same as applying it.
///
/// A field can deserialize and still never reach the check that reads it, so
/// pin the effect: one document, two ceilings, opposite exit codes, with the
/// environment as the only difference.
#[test]
fn env_max_grade_gates_the_readability_check() {
    let tmp = TempDir::new().unwrap();
    let doc = tmp.path().join("doc.md");
    fs::write(&doc, "# Title\n\nShort text. It reads easily.\n").unwrap();
    let dir = tmp.path().to_str().unwrap();
    let doc = doc.to_str().unwrap();

    cmd()
        .env("BITO_MAX_GRADE", "20.0")
        .args(["-C", dir, "--format", "text", "readability", doc])
        .assert()
        .code(0);

    cmd()
        .env("BITO_MAX_GRADE", "-5.0")
        .args(["-C", dir, "--format", "text", "readability", doc])
        .assert()
        .code(1);
}

/// A value that is not a number names the variable and the type expected.
#[test]
fn an_unparseable_numeric_environment_variable_is_reported() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path().to_str().unwrap();

    cmd()
        .env("BITO_MAX_GRADE", "abc")
        .args(["-C", dir, "--format", "text", "info"])
        .assert()
        .code(2)
        .stderr(predicate::str::contains("BITO_MAX_GRADE"))
        .stderr(predicate::str::contains("number"));
}