alef 0.25.53

Opinionated polyglot binding generator for Rust libraries
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
//! C# e2e project and shared test setup rendering.

use crate::core::config::manifest_extras::ManifestExtras;
use crate::core::hash::{self, CommentStyle};
use crate::core::template_versions as tv;
use std::collections::HashMap;
use std::fmt::Write as FmtWrite;

pub(super) fn render_csproj(
    pkg_name: &str,
    pkg_path: &str,
    pkg_version: &str,
    dep_mode: crate::e2e::config::DependencyMode,
    extras: Option<&ManifestExtras>,
) -> String {
    let pkg_ref = match dep_mode {
        crate::e2e::config::DependencyMode::Registry => {
            format!("    <PackageReference Include=\"{pkg_name}\" Version=\"{pkg_version}\" />")
        }
        crate::e2e::config::DependencyMode::Local => {
            format!("    <ProjectReference Include=\"{pkg_path}\" />")
        }
    };

    // Build extras block: combine dependencies and dev_dependencies as PackageReference elements.
    // C# .csproj has no dev/runtime split — all are PackageReference. Both buckets render as
    // the same element type, though in practice harness_extras would only use dev_dependencies
    // (vitest, mock-server libs, etc.).
    let extras_block = match extras {
        Some(e) if !e.is_empty() => {
            let mut lines = Vec::new();
            // Combine both buckets (dependencies, dev_dependencies) into one sorted set.
            let mut all_deps = e.dependencies.clone();
            for (name, spec) in &e.dev_dependencies {
                all_deps.insert(name.clone(), spec.clone());
            }

            if !all_deps.is_empty() {
                for (name, spec) in &all_deps {
                    if let Some(version) = spec.version() {
                        lines.push(format!(
                            "    <PackageReference Include=\"{name}\" Version=\"{version}\" />"
                        ));
                    }
                }
            }
            lines.join("\n")
        }
        _ => String::new(),
    };

    crate::e2e::template_env::render(
        "csharp/csproj.jinja",
        minijinja::context! {
            pkg_ref => pkg_ref,
            extras_block => extras_block,
            namespace => pkg_name,
            microsoft_net_test_sdk_version => tv::nuget::MICROSOFT_NET_TEST_SDK,
            xunit_version => tv::nuget::XUNIT,
            xunit_runner_version => tv::nuget::XUNIT_RUNNER_VISUALSTUDIO,
        },
    )
}

pub(super) fn render_test_setup(
    needs_mock_server: bool,
    test_documents_dir: &str,
    namespace: &str,
    env: &HashMap<String, String>,
) -> String {
    let mut out = String::new();
    out.push_str(&hash::header(CommentStyle::DoubleSlash));
    out.push_str("using System;\n");
    out.push_str("using System.IO;\n");
    if needs_mock_server {
        out.push_str("using System.Diagnostics;\n");
    }
    out.push_str("using System.Runtime.CompilerServices;\n\n");
    let _ = writeln!(out, "namespace {namespace};\n");
    out.push_str("internal static class TestSetup\n");
    out.push_str("{\n");
    if needs_mock_server {
        out.push_str("    private static Process? _mockServer;\n\n");
    }
    out.push_str("    [ModuleInitializer]\n");
    out.push_str("    internal static void Init()\n");
    out.push_str("    {\n");

    // Emit env vars if present
    if !env.is_empty() {
        let mut sorted_keys: Vec<_> = env.keys().collect();
        sorted_keys.sort();
        for key in sorted_keys {
            let value = &env[key];
            let _ = writeln!(
                out,
                "        if (Environment.GetEnvironmentVariable(\"{key}\") == null) {{"
            );
            let _ = writeln!(
                out,
                "            Environment.SetEnvironmentVariable(\"{key}\", \"{value}\");"
            );
            out.push_str("        }\n");
        }
        out.push('\n');
    }

    let _ = writeln!(
        out,
        "        // Walk up from the assembly directory until we find the repo root."
    );
    let _ = writeln!(
        out,
        "        // Prefer a sibling {test_documents_dir}/ directory (chdir into it so that"
    );
    out.push_str("        // fixture paths like \"docx/fake.docx\" resolve relative to it). If that\n");
    out.push_str("        // is absent (projects with no document fixtures), fall\n");
    out.push_str("        // back to a sibling alef.toml or fixtures/ marker as the repo root.\n");
    out.push_str("        var dir = new DirectoryInfo(AppContext.BaseDirectory);\n");
    out.push_str("        DirectoryInfo? repoRoot = null;\n");
    out.push_str("        while (dir != null)\n");
    out.push_str("        {\n");
    let _ = writeln!(
        out,
        "            var documentsCandidate = Path.Combine(dir.FullName, \"{test_documents_dir}\");"
    );
    out.push_str("            if (Directory.Exists(documentsCandidate))\n");
    out.push_str("            {\n");
    out.push_str("                repoRoot = dir;\n");
    out.push_str("                Directory.SetCurrentDirectory(documentsCandidate);\n");
    out.push_str("                break;\n");
    out.push_str("            }\n");
    out.push_str("            if (File.Exists(Path.Combine(dir.FullName, \"alef.toml\"))\n");
    out.push_str("                || Directory.Exists(Path.Combine(dir.FullName, \"fixtures\")))\n");
    out.push_str("            {\n");
    out.push_str("                repoRoot = dir;\n");
    out.push_str("                break;\n");
    out.push_str("            }\n");
    out.push_str("            dir = dir.Parent;\n");
    out.push_str("        }\n");
    if needs_mock_server {
        out.push('\n');
        let mock_server_code =
            crate::e2e::template_env::render("csharp/test_setup_mock_server.cs.jinja", minijinja::context! {});
        out.push_str(&mock_server_code);
    }
    out.push_str("    }\n");
    out.push_str("}\n");
    out
}

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

    #[test]
    fn test_render_test_setup_with_env_vars() {
        let mut env = HashMap::new();
        env.insert("ZEBRA_VAR".to_string(), "z_value".to_string());
        env.insert("ALPHA_VAR".to_string(), "a_value".to_string());
        env.insert("BETA_VAR".to_string(), "b_value".to_string());

        let output = render_test_setup(false, "fixtures", "FixtureE2E", &env);

        assert!(output.contains("ALPHA_VAR"));
        assert!(output.contains("a_value"));
        assert!(output.contains("BETA_VAR"));
        assert!(output.contains("b_value"));
        assert!(output.contains("ZEBRA_VAR"));
        assert!(output.contains("z_value"));

        // Verify alphabetical order
        let alpha_pos = output.find("ALPHA_VAR").unwrap();
        let beta_pos = output.find("BETA_VAR").unwrap();
        let zebra_pos = output.find("ZEBRA_VAR").unwrap();
        assert!(alpha_pos < beta_pos && beta_pos < zebra_pos);

        // Verify SetEnvironmentVariable pattern
        assert!(output.contains("Environment.SetEnvironmentVariable("));
    }

    #[test]
    fn test_render_test_setup_empty_env() {
        let env = HashMap::new();
        let output = render_test_setup(false, "fixtures", "FixtureE2E", &env);

        // Should not contain SetEnvironmentVariable calls for empty env
        assert!(!output.contains("Environment.SetEnvironmentVariable("));
    }

    #[test]
    fn test_render_test_setup_env_null_check() {
        let mut env = HashMap::new();
        env.insert("TEST_VAR".to_string(), "test_value".to_string());

        let output = render_test_setup(false, "fixtures", "FixtureE2E", &env);

        // Verify null-check pattern: if null, set
        assert!(output.contains("if (Environment.GetEnvironmentVariable(\"TEST_VAR\") == null)"));
        assert!(output.contains("Environment.SetEnvironmentVariable(\"TEST_VAR\", \"test_value\");"));
    }

    #[test]
    fn test_render_csproj_with_extras() {
        use crate::core::config::manifest_extras::{ExtraDepSpec, ManifestExtras};

        let mut extras = ManifestExtras::default();
        extras.dependencies.insert(
            "TreeSitter.DotNet".to_string(),
            ExtraDepSpec::Simple("1.3.0".to_string()),
        );

        let output = render_csproj(
            "MyLib",
            "../../packages/csharp/MyLib/MyLib.csproj",
            "0.1.0",
            crate::e2e::config::DependencyMode::Local,
            Some(&extras),
        );

        // Verify the extras PackageReference is present
        assert!(
            output.contains("<PackageReference Include=\"TreeSitter.DotNet\" Version=\"1.3.0\" />"),
            "extras should inject PackageReference, got: {}",
            output
        );
        // Verify the main package reference is still there
        assert!(
            output.contains("<ProjectReference Include=\"../../packages/csharp/MyLib/MyLib.csproj\" />"),
            "Local mode should use ProjectReference"
        );
    }

    #[test]
    fn test_render_csproj_with_dev_dependencies() {
        use crate::core::config::manifest_extras::{ExtraDepSpec, ManifestExtras};

        let mut extras = ManifestExtras::default();
        extras.dev_dependencies.insert(
            "Bogus".to_string(),
            ExtraDepSpec::Simple("^35.0.0".to_string()),
        );

        let output = render_csproj(
            "MyLib",
            "../../packages/csharp/MyLib/MyLib.csproj",
            "0.1.0",
            crate::e2e::config::DependencyMode::Local,
            Some(&extras),
        );

        // Dev dependencies should also render as PackageReference
        assert!(
            output.contains("<PackageReference Include=\"Bogus\" Version=\"^35.0.0\" />"),
            "dev_dependencies should inject as PackageReference, got: {}",
            output
        );
    }

    #[test]
    fn test_render_csproj_with_both_dependency_buckets() {
        use crate::core::config::manifest_extras::{ExtraDepSpec, ManifestExtras};

        let mut extras = ManifestExtras::default();
        extras.dependencies.insert(
            "TreeSitter.DotNet".to_string(),
            ExtraDepSpec::Simple("1.3.0".to_string()),
        );
        extras.dev_dependencies.insert(
            "Bogus".to_string(),
            ExtraDepSpec::Simple("^35.0.0".to_string()),
        );

        let output = render_csproj(
            "MyLib",
            "../../packages/csharp/MyLib/MyLib.csproj",
            "0.1.0",
            crate::e2e::config::DependencyMode::Local,
            Some(&extras),
        );

        // Both buckets should be present
        assert!(output.contains("<PackageReference Include=\"TreeSitter.DotNet\""));
        assert!(output.contains("<PackageReference Include=\"Bogus\""));
    }

    #[test]
    fn test_render_csproj_without_extras() {
        let output = render_csproj(
            "MyLib",
            "../../packages/csharp/MyLib/MyLib.csproj",
            "0.1.0",
            crate::e2e::config::DependencyMode::Local,
            None,
        );

        // Should not have extras block, only baseline dependencies
        assert!(output.contains("Microsoft.NET.Test.Sdk"));
        assert!(output.contains("xunit"));
        assert!(output.contains("<ProjectReference Include=\"../../packages/csharp/MyLib/MyLib.csproj\" />"));
    }

    #[test]
    fn test_render_csproj_with_empty_extras() {
        use crate::core::config::manifest_extras::ManifestExtras;

        let extras = ManifestExtras::default(); // Empty: no dependencies or dev_dependencies

        let output = render_csproj(
            "MyLib",
            "../../packages/csharp/MyLib/MyLib.csproj",
            "0.1.0",
            crate::e2e::config::DependencyMode::Local,
            Some(&extras),
        );

        // Empty extras should not affect output (idempotent)
        assert!(output.contains("Microsoft.NET.Test.Sdk"));
        assert!(output.contains("<ProjectReference Include=\"../../packages/csharp/MyLib/MyLib.csproj\" />"));
    }

    #[test]
    fn test_render_csproj_registry_mode_ignores_extras() {
        use crate::core::config::manifest_extras::{ExtraDepSpec, ManifestExtras};

        let mut extras = ManifestExtras::default();
        extras.dependencies.insert(
            "TreeSitter.DotNet".to_string(),
            ExtraDepSpec::Simple("1.3.0".to_string()),
        );

        let output = render_csproj(
            "MyLib",
            "../../packages/csharp/MyLib/MyLib.csproj",
            "0.1.0",
            crate::e2e::config::DependencyMode::Registry,
            Some(&extras),
        );

        // Registry mode should NOT include extras; template may still process empty extras_block
        // but the real filtering happens at the call site. Verify the baseline works.
        assert!(output.contains("<PackageReference Include=\"MyLib\" Version=\"0.1.0\" />"));
        assert!(output.contains("Microsoft.NET.Test.Sdk"));
    }

    #[test]
    fn test_render_csproj_extras_within_item_group() {
        use crate::core::config::manifest_extras::{ExtraDepSpec, ManifestExtras};

        let mut extras = ManifestExtras::default();
        extras.dependencies.insert(
            "TreeSitter.DotNet".to_string(),
            ExtraDepSpec::Simple("1.3.0".to_string()),
        );
        extras.dev_dependencies.insert(
            "Moq".to_string(),
            ExtraDepSpec::Simple("4.16.0".to_string()),
        );

        let output = render_csproj(
            "MyLib",
            "../../packages/csharp/MyLib/MyLib.csproj",
            "0.1.0",
            crate::e2e::config::DependencyMode::Local,
            Some(&extras),
        );

        // Verify structure: extras should be within the first ItemGroup with test dependencies
        let first_item_group_start = output.find("<ItemGroup>").expect("should have ItemGroup");
        let first_item_group_end = output.find("</ItemGroup>").expect("should have /ItemGroup");
        let first_item_group = &output[first_item_group_start..=first_item_group_end];

        // Both extras and xunit should be in the same ItemGroup
        assert!(
            first_item_group.contains("xunit"),
            "xunit should be in first ItemGroup"
        );
        assert!(
            first_item_group.contains("TreeSitter.DotNet"),
            "extras should be in first ItemGroup"
        );
        assert!(
            first_item_group.contains("Moq"),
            "dev_dependencies should also be in first ItemGroup"
        );

        // Verify the second ItemGroup has the pkg_ref
        let second_item_group_start = output[first_item_group_end..]
            .find("<ItemGroup>")
            .map(|i| i + first_item_group_end)
            .expect("should have second ItemGroup");
        let second_item_group_end = output[second_item_group_start..]
            .find("</ItemGroup>")
            .map(|i| i + second_item_group_start + 1)
            .unwrap_or(output.len());
        let second_item_group = &output[second_item_group_start..second_item_group_end];

        assert!(
            second_item_group.contains("ProjectReference"),
            "second ItemGroup should have ProjectReference"
        );
    }

    #[test]
    fn test_render_csproj_idempotent_with_same_extras() {
        use crate::core::config::manifest_extras::{ExtraDepSpec, ManifestExtras};

        let mut extras = ManifestExtras::default();
        extras.dependencies.insert(
            "TreeSitter.DotNet".to_string(),
            ExtraDepSpec::Simple("1.3.0".to_string()),
        );

        let output1 = render_csproj(
            "MyLib",
            "../../packages/csharp/MyLib/MyLib.csproj",
            "0.1.0",
            crate::e2e::config::DependencyMode::Local,
            Some(&extras),
        );

        let output2 = render_csproj(
            "MyLib",
            "../../packages/csharp/MyLib/MyLib.csproj",
            "0.1.0",
            crate::e2e::config::DependencyMode::Local,
            Some(&extras),
        );

        assert_eq!(
            output1, output2,
            "rendering with identical extras should be idempotent"
        );
    }
}