curie-build 0.6.0

The Curie build tool
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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
//! `curie fmt` — format Java and Kotlin source files.
//!
//! # How it works
//!
//! Two formatters are used, each resolved from Maven Central on first run and
//! cached in `~/.m2` for all subsequent invocations:
//!
//!   * **Java** — [`palantir-java-format`] (`com.palantir.javaformat:palantir-java-format`)
//!     invoked via `java -cp <jars> com.palantir.javaformat.java.Main --aosp`.
//!   * **Kotlin** — [`ktfmt`] (`com.facebook:ktfmt`)
//!     invoked via `java -cp <jars> com.facebook.ktfmt.cli.Main --kotlinlang-style`.
//!
//! The Kotlin step is skipped entirely (including resolution) when the project
//! has no `.kt` sources.
//!
//! # JVM flags
//!
//! PJF's JAR manifest declares `Add-Exports` entries it needs on JDK 17+.
//! When the JAR is invoked via `-cp` (not `-jar`) the JVM does not process
//! manifest attributes, so we supply the flags explicitly.  ktfmt uses the
//! Kotlin compiler's PSI library which accesses `sun.misc.Unsafe`; we pass
//! `--enable-native-access=ALL-UNNAMED` to silence the warning (the same flag
//! used when invoking kotlinc for compilation).
//!
//! # File discovery
//!
//! **Java** — all `*.java` files under `src/main/java/`, `src/test/java/`,
//! and flat-package source roots.
//!
//! **Kotlin** — all `*.kt` files under `src/main/kotlin/`, `src/test/kotlin/`,
//! and flat-package source/test roots.  Test files (`*Test.kt` etc.) are
//! included — formatting tests is desirable.

use crate::compile::{flat_package_src_dirs, flat_package_test_dirs};
use anyhow::{bail, Context, Result};
use crate::build::central_repos;
use curie_deps::resolver::{resolve, DepEntry, ResolveOptions};
use std::path::{Path, PathBuf};
use std::process::Command;
use walkdir::WalkDir;

/// PJF coordinate pinned to the latest version on Maven Central.
const PJF_COORD: &str = "com.palantir.javaformat:palantir-java-format";
const PJF_VERSION: &str = "2.90.0";
/// Fully-qualified name of PJF's CLI entry point.
const PJF_MAIN: &str = "com.palantir.javaformat.java.Main";

/// ktfmt coordinate pinned to the latest stable version on Maven Central.
const KTFMT_COORD: &str = "com.facebook:ktfmt";
const KTFMT_VERSION: &str = "0.51";
/// Fully-qualified name of ktfmt's CLI entry point (stable since 0.42).
const KTFMT_MAIN: &str = "com.facebook.ktfmt.cli.Main";

// ---------------------------------------------------------------------------
// Public entry points
// ---------------------------------------------------------------------------

/// Resolve palantir-java-format and its transitive dependencies once.
///
/// Callers that format more than one project in a single invocation
/// (e.g. `fmt_all` over a workspace) MUST call this once and reuse the
/// resulting classpath via [`run_fmt_with_jars`] — concurrent identical
/// `resolve()` calls would otherwise race on the same `~/.m2/.part` files.
pub fn resolve_pjf(offline: bool) -> Result<Vec<PathBuf>> {
    resolve(
        &[DepEntry { key: PJF_COORD, version: PJF_VERSION, repo_id: None }],
        &ResolveOptions {
            default_repos: central_repos(),
            named_repos: vec![],
            progress: false,
            bom_imports: vec![],
            offline,
        },
    )
    .context("failed to resolve palantir-java-format from Maven Central")
}

/// Resolve ktfmt and its transitive dependencies once.
///
/// Same sharing contract as [`resolve_pjf`]: call once at the workspace level
/// and pass the result to [`run_fmt_with_jars`] to avoid concurrent races.
pub fn resolve_ktfmt(offline: bool) -> Result<Vec<PathBuf>> {
    resolve(
        &[DepEntry { key: KTFMT_COORD, version: KTFMT_VERSION, repo_id: None }],
        &ResolveOptions {
            default_repos: central_repos(),
            named_repos: vec![],
            progress: false,
            bom_imports: vec![],
            offline,
        },
    )
    .context("failed to resolve ktfmt from Maven Central")
}

/// Return `true` if `project_root` contains at least one `.kt` source file.
///
/// Used by `fmt_all` to decide whether to bother resolving ktfmt for the
/// whole workspace.  Short-circuits on the first match.
pub fn has_kotlin_sources(project_root: &Path) -> bool {
    kotlin_source_roots(project_root).into_iter().any(|root| {
        WalkDir::new(root)
            .into_iter()
            .filter_map(|e| e.ok())
            .any(|e| {
                e.file_type().is_file()
                    && e.path().extension().map_or(false, |x| x == "kt")
            })
    })
}

/// Run both formatters on all sources in `project_root`.
///
/// * `check_only` — dry-run + exit-non-zero-if-changed (CI mode).
/// * `offline` — resolve from `~/.m2` cache only.
pub fn run_fmt(project_root: &Path, check_only: bool, offline: bool) -> Result<()> {
    let pjf_jars = resolve_pjf(offline)?;
    let ktfmt_jars = if has_kotlin_sources(project_root) {
        resolve_ktfmt(offline)?
    } else {
        Vec::new()
    };
    run_fmt_with_jars(project_root, check_only, &pjf_jars, &ktfmt_jars)
}

/// Format against already-resolved formatter classpaths.
///
/// Splitting resolution out of the runner lets `fmt_all` resolve both
/// formatters exactly once and reuse them across every workspace member.
///
/// `ktfmt_jars` may be empty — pass `&[]` for projects / workspaces with
/// no Kotlin sources.  Both formatters run independently; if one fails the
/// other still runs so `--check` in CI reports all unformatted files in a
/// single pass.
pub fn run_fmt_with_jars(
    project_root: &Path,
    check_only: bool,
    pjf_jars: &[PathBuf],
    ktfmt_jars: &[PathBuf],
) -> Result<()> {
    let java_files = collect_java_files(project_root);
    let kotlin_files = if ktfmt_jars.is_empty() {
        vec![]
    } else {
        collect_kotlin_files(project_root)
    };

    if java_files.is_empty() && kotlin_files.is_empty() {
        return Ok(());
    }

    let file_summary = match (java_files.len(), kotlin_files.len()) {
        (j, 0) => format!("{j} Java file(s)"),
        (0, k) => format!("{k} Kotlin file(s)"),
        (j, k) => format!("{j} Java, {k} Kotlin file(s)"),
    };
    let action = if check_only { "Check" } else { "Format" };
    crate::parallel::emit(&crate::style::fmt_step(action, &file_summary));

    // Run both formatters independently so that both errors surface in one
    // --check pass rather than short-circuiting on the first failure.
    let java_err = if !java_files.is_empty() {
        fmt_java(&java_files, pjf_jars, check_only).err()
    } else {
        None
    };
    let kotlin_err = if !kotlin_files.is_empty() {
        fmt_kotlin(&kotlin_files, ktfmt_jars, check_only).err()
    } else {
        None
    };

    match (java_err, kotlin_err) {
        (None, None) => Ok(()),
        (Some(e), None) | (None, Some(e)) => Err(e),
        (Some(je), Some(ke)) => bail!("{:#}\n{:#}", je, ke),
    }
}

// ---------------------------------------------------------------------------
// Private formatter invocations
// ---------------------------------------------------------------------------

/// Everything that distinguishes one formatter (PJF vs ktfmt) from another.
struct FormatterSpec {
    /// Fully-qualified main class to invoke via `java -cp`.
    main_class: &'static str,
    /// Extra JVM arguments placed before `-cp` (e.g. `--add-exports` flags).
    jvm_flags: Vec<String>,
    /// Arguments passed to the formatter when reformatting in-place.
    reformat_args: &'static [&'static str],
    /// Arguments passed to the formatter when doing a dry-run check.
    check_args: &'static [&'static str],
    /// Human-readable name used in error messages.
    name: &'static str,
    /// Language name used in the "not correctly formatted" error message.
    language: &'static str,
}

/// Invoke a formatter on a set of source files.
fn run_formatter(
    files: &[PathBuf],
    jars: &[PathBuf],
    check_only: bool,
    spec: &FormatterSpec,
) -> Result<()> {
    let cp = classpath(jars);
    let mut cmd = Command::new("java");
    for flag in &spec.jvm_flags {
        cmd.arg(flag);
    }
    cmd.arg("-cp").arg(&cp).arg(spec.main_class);
    if check_only {
        for arg in spec.check_args {
            cmd.arg(arg);
        }
    } else {
        for arg in spec.reformat_args {
            cmd.arg(arg);
        }
    }
    for f in files {
        cmd.arg(f);
    }
    let status = crate::proc::spawn_cmd(&mut cmd)
        .context("failed to launch `java` — is a JDK installed and on PATH?")?;
    if !status.success() {
        if check_only {
            bail!(
                "fmt: one or more {} files are not correctly formatted. \
                 Run `curie fmt` (without --check) to fix them.",
                spec.language
            );
        } else {
            bail!("{} exited non-zero", spec.name);
        }
    }
    Ok(())
}

fn fmt_java(java_files: &[PathBuf], pjf_jars: &[PathBuf], check_only: bool) -> Result<()> {
    run_formatter(java_files, pjf_jars, check_only, &FormatterSpec {
        main_class: PJF_MAIN,
        jvm_flags: jvm_add_exports(),
        reformat_args: &["--aosp", "--replace"],
        check_args: &["--aosp", "--dry-run", "--set-exit-if-changed"],
        name: "palantir-java-format",
        language: "Java",
    })
}

fn fmt_kotlin(kotlin_files: &[PathBuf], ktfmt_jars: &[PathBuf], check_only: bool) -> Result<()> {
    // ktfmt rewrites in-place by default — no --replace flag needed.
    run_formatter(kotlin_files, ktfmt_jars, check_only, &FormatterSpec {
        main_class: KTFMT_MAIN,
        jvm_flags: vec!["--enable-native-access=ALL-UNNAMED".to_string()],
        reformat_args: &["--kotlinlang-style"],
        check_args: &["--kotlinlang-style", "--dry-run", "--set-exit-if-changed"],
        name: "ktfmt",
        language: "Kotlin",
    })
}

fn classpath(jars: &[PathBuf]) -> String {
    jars.iter()
        .map(|p| p.to_string_lossy())
        .collect::<Vec<_>>()
        .join(":")
}

// ---------------------------------------------------------------------------
// Helpers (pub(crate) for unit-testability)
// ---------------------------------------------------------------------------

/// Return all `*.java` files under the project's source roots (sorted).
///
/// Source roots:
///   * `src/main/java/`  — Maven-style production sources
///   * `src/test/java/`  — Maven-style test sources
///   * flat-package dirs (`src/com.example.foo/` etc.)
pub(crate) fn collect_java_files(project_root: &Path) -> Vec<PathBuf> {
    let mut roots: Vec<PathBuf> = Vec::new();

    let main_java = project_root.join("src").join("main").join("java");
    if main_java.exists() {
        roots.push(main_java);
    }

    let test_java = project_root.join("src").join("test").join("java");
    if test_java.exists() {
        roots.push(test_java);
    }

    roots.extend(flat_package_src_dirs(project_root));

    let mut files: Vec<PathBuf> = roots
        .iter()
        .flat_map(|root| {
            WalkDir::new(root)
                .into_iter()
                .filter_map(|e| e.ok())
                .filter(|e| {
                    e.file_type().is_file()
                        && e.path().extension().map_or(false, |x| x == "java")
                })
                .map(|e| e.into_path())
        })
        .collect();

    files.sort();
    files
}

/// Return all `*.kt` files under the project's Kotlin source roots (sorted).
///
/// Source roots:
///   * `src/main/kotlin/` — Maven-style Kotlin production sources
///   * `src/test/kotlin/` — Maven-style Kotlin test sources
///   * flat-package `src/<dot-name>/` dirs — both `.java` and `.kt` files live here
///   * flat-package `tests/<dot-name>/` dirs — integration test sources
///
/// Unlike the compile-time Kotlin source discovery, test files (`*Test.kt`,
/// `*Tests.kt`, `*Spec.kt`) are NOT excluded — formatting test files is
/// desirable and mirrors the Java formatter behaviour.
pub(crate) fn collect_kotlin_files(project_root: &Path) -> Vec<PathBuf> {
    let mut files: Vec<PathBuf> = kotlin_source_roots(project_root)
        .iter()
        .flat_map(|root| {
            WalkDir::new(root)
                .into_iter()
                .filter_map(|e| e.ok())
                .filter(|e| {
                    e.file_type().is_file()
                        && e.path().extension().map_or(false, |x| x == "kt")
                })
                .map(|e| e.into_path())
        })
        .collect();

    files.sort();
    files.dedup();
    files
}

/// All source roots that may contain `.kt` files for this project.
fn kotlin_source_roots(project_root: &Path) -> Vec<PathBuf> {
    let mut roots: Vec<PathBuf> = Vec::new();

    let main_kotlin = project_root.join("src").join("main").join("kotlin");
    if main_kotlin.exists() {
        roots.push(main_kotlin);
    }
    let test_kotlin = project_root.join("src").join("test").join("kotlin");
    if test_kotlin.exists() {
        roots.push(test_kotlin);
    }
    roots.extend(flat_package_src_dirs(project_root));
    roots.extend(flat_package_test_dirs(project_root));
    roots
}

/// Return the `--add-exports` JVM flags required by PJF on JDK 17+.
///
/// These mirror the `Add-Exports` attribute in PJF's JAR manifest.  When
/// the JAR is invoked via `-cp` instead of `-jar` the JVM does not process
/// manifest attributes, so we must supply the flags explicitly.
pub(crate) fn jvm_add_exports() -> Vec<String> {
    let packages = [
        "com.sun.tools.javac.api",
        "com.sun.tools.javac.code",
        "com.sun.tools.javac.file",
        "com.sun.tools.javac.main",
        "com.sun.tools.javac.parser",
        "com.sun.tools.javac.tree",
        "com.sun.tools.javac.util",
    ];
    packages
        .iter()
        .map(|p| format!("--add-exports=jdk.compiler/{}=ALL-UNNAMED", p))
        .collect()
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    // --- jvm_add_exports ----------------------------------------------------

    #[test]
    fn jvm_add_exports_covers_required_packages() {
        let flags = jvm_add_exports();
        let required = [
            "com.sun.tools.javac.api",
            "com.sun.tools.javac.code",
            "com.sun.tools.javac.file",
            "com.sun.tools.javac.main",
            "com.sun.tools.javac.parser",
            "com.sun.tools.javac.tree",
            "com.sun.tools.javac.util",
        ];
        for pkg in required {
            let needle = format!("jdk.compiler/{}=ALL-UNNAMED", pkg);
            assert!(
                flags.iter().any(|f| f.contains(&needle)),
                "missing --add-exports for {pkg}"
            );
        }
    }

    #[test]
    fn jvm_add_exports_all_start_with_flag() {
        for flag in jvm_add_exports() {
            assert!(
                flag.starts_with("--add-exports="),
                "unexpected flag format: {flag}"
            );
        }
    }

    // --- collect_java_files -------------------------------------------------

    #[test]
    fn collect_java_files_empty_project() {
        let tmp = TempDir::new().unwrap();
        let files = collect_java_files(tmp.path());
        assert!(files.is_empty(), "expected no files in empty project");
    }

    #[test]
    fn collect_java_files_maven_layout() {
        let tmp = TempDir::new().unwrap();
        let main_java = tmp.path().join("src").join("main").join("java");
        let test_java = tmp.path().join("src").join("test").join("java");
        fs::create_dir_all(&main_java).unwrap();
        fs::create_dir_all(&test_java).unwrap();

        fs::write(main_java.join("Foo.java"), "class Foo {}").unwrap();
        fs::write(main_java.join("Bar.java"), "class Bar {}").unwrap();
        fs::write(test_java.join("FooTest.java"), "class FooTest {}").unwrap();
        fs::write(main_java.join("README.txt"), "docs").unwrap();

        let files = collect_java_files(tmp.path());
        assert_eq!(files.len(), 3, "expected 3 .java files, got {:?}", files);
        for f in &files {
            assert_eq!(f.extension().unwrap(), "java");
        }
    }

    #[test]
    fn collect_java_files_returns_sorted() {
        let tmp = TempDir::new().unwrap();
        let src = tmp.path().join("src").join("main").join("java");
        fs::create_dir_all(&src).unwrap();
        fs::write(src.join("Zoo.java"), "class Zoo {}").unwrap();
        fs::write(src.join("Alpha.java"), "class Alpha {}").unwrap();
        fs::write(src.join("Mango.java"), "class Mango {}").unwrap();

        let files = collect_java_files(tmp.path());
        let names: Vec<_> = files
            .iter()
            .map(|p| p.file_name().unwrap().to_str().unwrap())
            .collect();
        let mut sorted = names.clone();
        sorted.sort();
        assert_eq!(names, sorted, "files should be returned sorted");
    }

    #[test]
    fn collect_java_files_recursive() {
        let tmp = TempDir::new().unwrap();
        let pkg = tmp
            .path()
            .join("src")
            .join("main")
            .join("java")
            .join("com")
            .join("example");
        fs::create_dir_all(&pkg).unwrap();
        fs::write(pkg.join("Deep.java"), "class Deep {}").unwrap();

        let files = collect_java_files(tmp.path());
        assert_eq!(files.len(), 1);
        assert!(files[0].ends_with("Deep.java"));
    }

    // --- collect_kotlin_files -----------------------------------------------

    #[test]
    fn collect_kotlin_files_empty_project() {
        let tmp = TempDir::new().unwrap();
        assert!(collect_kotlin_files(tmp.path()).is_empty());
    }

    #[test]
    fn collect_kotlin_files_maven_layout() {
        let tmp = TempDir::new().unwrap();
        let main_kt = tmp.path().join("src").join("main").join("kotlin");
        let test_kt = tmp.path().join("src").join("test").join("kotlin");
        fs::create_dir_all(&main_kt).unwrap();
        fs::create_dir_all(&test_kt).unwrap();

        fs::write(main_kt.join("Greeting.kt"), "class Greeting").unwrap();
        fs::write(test_kt.join("GreetingTest.kt"), "class GreetingTest").unwrap();
        // Non-.kt file — must be excluded.
        fs::write(main_kt.join("notes.txt"), "docs").unwrap();

        let files = collect_kotlin_files(tmp.path());
        assert_eq!(files.len(), 2, "expected 2 .kt files, got {:?}", files);
        for f in &files {
            assert_eq!(f.extension().unwrap(), "kt");
        }
    }

    #[test]
    fn collect_kotlin_files_flat_package() {
        let tmp = TempDir::new().unwrap();
        let pkg = tmp.path().join("src").join("com.example.mixed");
        fs::create_dir_all(&pkg).unwrap();
        fs::write(pkg.join("Greeting.kt"), "class Greeting").unwrap();
        fs::write(pkg.join("Main.java"), "class Main {}").unwrap(); // should be ignored

        let files = collect_kotlin_files(tmp.path());
        assert_eq!(files.len(), 1);
        assert!(files[0].ends_with("Greeting.kt"));
    }

    #[test]
    fn collect_kotlin_files_includes_test_files() {
        // Regression: compile excludes *Test.kt; fmt must include them.
        let tmp = TempDir::new().unwrap();
        let pkg = tmp.path().join("src").join("com.example");
        fs::create_dir_all(&pkg).unwrap();
        fs::write(pkg.join("Foo.kt"), "class Foo").unwrap();
        fs::write(pkg.join("FooTest.kt"), "class FooTest").unwrap();
        fs::write(pkg.join("FooSpec.kt"), "class FooSpec").unwrap();

        let files = collect_kotlin_files(tmp.path());
        assert_eq!(files.len(), 3, "test/spec files must be included in fmt: {:?}", files);
    }

    #[test]
    fn collect_kotlin_files_includes_tests_dir() {
        // Integration tests in flat-package tests/ should also be formatted.
        let tmp = TempDir::new().unwrap();
        let tests_pkg = tmp.path().join("tests").join("com.example");
        fs::create_dir_all(&tests_pkg).unwrap();
        fs::write(tests_pkg.join("IntTest.kt"), "class IntTest").unwrap();

        let files = collect_kotlin_files(tmp.path());
        assert_eq!(files.len(), 1);
        assert!(files[0].ends_with("IntTest.kt"));
    }

    #[test]
    fn collect_kotlin_files_returns_sorted() {
        let tmp = TempDir::new().unwrap();
        let src = tmp.path().join("src").join("main").join("kotlin");
        fs::create_dir_all(&src).unwrap();
        fs::write(src.join("Zoo.kt"), "class Zoo").unwrap();
        fs::write(src.join("Alpha.kt"), "class Alpha").unwrap();

        let files = collect_kotlin_files(tmp.path());
        let names: Vec<_> = files
            .iter()
            .map(|p| p.file_name().unwrap().to_str().unwrap())
            .collect();
        let mut sorted = names.clone();
        sorted.sort();
        assert_eq!(names, sorted);
    }

    // --- has_kotlin_sources -------------------------------------------------

    #[test]
    fn has_kotlin_sources_false_for_empty_project() {
        let tmp = TempDir::new().unwrap();
        assert!(!has_kotlin_sources(tmp.path()));
    }

    #[test]
    fn has_kotlin_sources_false_for_java_only() {
        let tmp = TempDir::new().unwrap();
        let src = tmp.path().join("src").join("main").join("java");
        fs::create_dir_all(&src).unwrap();
        fs::write(src.join("Foo.java"), "class Foo {}").unwrap();
        assert!(!has_kotlin_sources(tmp.path()));
    }

    #[test]
    fn has_kotlin_sources_true_when_kt_present() {
        let tmp = TempDir::new().unwrap();
        let src = tmp.path().join("src").join("main").join("kotlin");
        fs::create_dir_all(&src).unwrap();
        fs::write(src.join("Greeting.kt"), "class Greeting").unwrap();
        assert!(has_kotlin_sources(tmp.path()));
    }

    #[test]
    fn has_kotlin_sources_true_for_flat_package_kt() {
        let tmp = TempDir::new().unwrap();
        let pkg = tmp.path().join("src").join("com.example");
        fs::create_dir_all(&pkg).unwrap();
        fs::write(pkg.join("App.kt"), "fun main() {}").unwrap();
        assert!(has_kotlin_sources(tmp.path()));
    }
}