elf-magic 0.3.0

Automatic compile-time ELF exports for Solana programs. One-liner integration, zero config, just works. ✨
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
use std::{fs, path::Path};

use minijinja::{context, Environment};

use crate::{error::Error, programs::BuildResult};

/// Template for the generated lib.rs file
const LIB_RS_TEMPLATE: &str = r#"
// This file is auto-generated by elf-magic
// DO NOT EDIT MANUALLY - Changes will be overwritten
//
// Build Status:
{% for build_status in build_statuses -%}
// {{ build_status.icon }} {{ build_status.program_name }} - {{ build_status.message }}
{% endfor -%}
// ------------------------------------------------------------
// Constants
{% for constant in constants -%}
/// ELF binary for the {{ constant.program_name }} Solana program
pub const {{ constant.constant_name }}: &[u8] = include_bytes!(env!("{{ constant.env_var }}"));

{% endfor -%}

/// Get all available Solana program ELF binaries
/// Returns a vector of (program_name, elf_bytes) tuples
pub fn elves() -> Vec<(&'static str, &'static [u8])> {
    vec![
{%- for constant in constants %}
        ("{{ constant.program_name }}", {{ constant.constant_name }}),
{%- endfor %}
    ]
}
"#;

/// Generate code for Solana programs from build results
pub fn generate(build_result: &BuildResult) -> Result<String, Error> {
    // Collect all programs with render data in one pass
    let mut program_specs: Vec<(String, Option<serde_json::Value>, serde_json::Value)> = Vec::new();

    // Process successful programs
    for (program, _path) in &build_result.successful {
        let constant = Some(serde_json::json!({
            "constant_name": program.constant_name(),
            "env_var": program.env_var_name(),
            "program_name": program.target_name.clone()
        }));

        let build_status = serde_json::json!({
            "icon": "",
            "program_name": program.target_name,
            "message": "SUCCESS"
        });

        program_specs.push((program.target_name.clone(), constant, build_status));
    }

    // Process failed programs
    for (program, error) in &build_result.failed {
        let build_status = serde_json::json!({
            "icon": "",
            "program_name": program.target_name,
            "message": format!("FAILED: {}", error)
        });

        program_specs.push((program.target_name.clone(), None, build_status));
    }

    // Sort once by target_name
    program_specs.sort_by(|a, b| a.0.cmp(&b.0));

    // Create minijinja environment and render template
    let mut env = Environment::new();

    env.add_template("lib.rs", LIB_RS_TEMPLATE).map_err(|e| {
        let msg = format!("Failed to add template: {}", e);
        Error::CodeGeneration(msg)
    })?;

    let template = env.get_template("lib.rs").map_err(|e| {
        let msg = format!("Failed to get template: {}", e);
        Error::CodeGeneration(msg)
    })?;

    let constants: Vec<_> = program_specs
        .iter()
        .filter_map(|(_, constant, _)| constant.clone())
        .collect();

    let build_statuses: Vec<_> = program_specs
        .iter()
        .map(|(_, _, build_status)| build_status)
        .collect();

    let rendered_content = template
        .render(context! {
            constants => constants,
            build_statuses => build_statuses,
        })
        .map_err(|e| {
            let msg = format!("Failed to render template: {}", e);
            Error::CodeGeneration(msg)
        })?;

    Ok(rendered_content)
}

/// Write generated code to lib.rs
pub fn save(manifest_dir: &Path, code: &str) -> Result<(), Error> {
    let output_path = manifest_dir.join("src").join("lib.rs");
    fs::write(&output_path, code).map_err(|e| {
        let message = format!("Failed to write lib.rs: {}", e);
        Error::CodeGeneration(message)
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::programs::SolanaProgram;
    use std::path::PathBuf;

    fn sample_programs() -> Vec<SolanaProgram> {
        vec![
            SolanaProgram {
                package_name: "package1".to_string(),
                target_name: "target1".to_string(),
                manifest_path: PathBuf::from("/path/to/Cargo.toml"),
            },
            SolanaProgram {
                package_name: "package2".to_string(),
                target_name: "target2".to_string(),
                manifest_path: PathBuf::from("/path/to/other/Cargo.toml"),
            },
        ]
    }

    #[test]
    fn test_generate_empty_programs() {
        let result = generate(&BuildResult {
            successful: Vec::new(),
            failed: Vec::new(),
        })
        .unwrap();

        // Should generate valid Rust code with empty elves function
        assert!(result.contains("pub fn elves() -> Vec<(&'static str, &'static [u8])> {"));
        assert!(result.contains("vec![\n    ]"));
        assert!(result.contains("// This file is auto-generated by elf-magic"));
    }

    #[test]
    fn test_generate_single_program() {
        let programs = [SolanaProgram {
            package_name: "my_package".to_string(),
            target_name: "my_target".to_string(),
            manifest_path: PathBuf::from("/path/to/Cargo.toml"),
        }];

        let result = generate(&BuildResult {
            successful: programs
                .iter()
                .map(|p| (p.clone(), PathBuf::from("/path/to/Cargo.toml")))
                .collect(),
            failed: Vec::new(),
        })
        .unwrap();

        // Check constant definition
        assert!(result.contains(
            "pub const MY_TARGET_ELF: &[u8] = include_bytes!(env!(\"MY_TARGET_ELF_PATH\"));"
        ));

        // Check elves function includes the program
        assert!(result.contains("(\"my_target\", MY_TARGET_ELF),"));

        // Check doc comment
        assert!(result.contains("/// ELF binary for the my_target Solana program"));
    }

    #[test]
    fn test_generate_multiple_programs() {
        let programs = sample_programs();
        let result = generate(&BuildResult {
            successful: programs
                .iter()
                .map(|p| (p.clone(), PathBuf::from("/path/to/Cargo.toml")))
                .collect(),
            failed: Vec::new(),
        })
        .unwrap();

        // Should have both constants
        assert!(result.contains("pub const TARGET1_ELF"));
        assert!(result.contains("pub const TARGET2_ELF"));

        // Should have both environment variables
        assert!(result.contains("env!(\"TARGET1_ELF_PATH\")"));
        assert!(result.contains("env!(\"TARGET2_ELF_PATH\")"));

        // Should include both in elves function
        assert!(result.contains("(\"target1\", TARGET1_ELF),"));
        assert!(result.contains("(\"target2\", TARGET2_ELF),"));

        // Should have proper doc comments
        assert!(result.contains("/// ELF binary for the target1 Solana program"));
        assert!(result.contains("/// ELF binary for the target2 Solana program"));
    }

    #[test]
    fn test_generate_with_special_characters() {
        let programs = [SolanaProgram {
            package_name: "my-special-package".to_string(),
            target_name: "my_target_name".to_string(),
            manifest_path: PathBuf::from("/path/to/Cargo.toml"),
        }];

        let result = generate(&BuildResult {
            successful: programs
                .iter()
                .map(|p| (p.clone(), PathBuf::from("/path/to/Cargo.toml")))
                .collect(),
            failed: Vec::new(),
        })
        .unwrap();

        // Target name should be preserved as-is in program name
        assert!(result.contains("(\"my_target_name\", MY_TARGET_NAME_ELF),"));

        // But constant and env var should follow their respective conventions
        assert!(result.contains("pub const MY_TARGET_NAME_ELF"));
        assert!(result.contains("env!(\"MY_TARGET_NAME_ELF_PATH\")"));
    }

    #[test]
    fn test_generated_code_is_valid_rust() {
        let programs = sample_programs();
        let result = generate(&BuildResult {
            successful: programs
                .iter()
                .map(|p| (p.clone(), PathBuf::from("/path/to/Cargo.toml")))
                .collect(),
            failed: Vec::new(),
        })
        .unwrap();

        // Basic syntax checks
        assert!(result.contains("pub const"));
        assert!(result.contains("pub fn elves()"));
        assert!(result.contains("vec!["));
        assert!(!result.contains("{{")); // No unresolved template variables
        assert!(!result.contains("}}"));

        // Should be properly formatted
        let lines: Vec<&str> = result.lines().collect();
        assert!(lines.len() > 5); // Should have multiple lines

        // Comments should be present
        assert!(result.contains("// This file is auto-generated by elf-magic"));
        assert!(result.contains("// DO NOT EDIT MANUALLY"));
    }

    #[test]
    fn test_template_render_error_handling() {
        // This is harder to test without breaking the template
        // But we can at least verify the function signature works
        let _programs: Vec<SolanaProgram> = vec![];
        let result = generate(&BuildResult {
            successful: Vec::new(),
            failed: Vec::new(),
        });
        assert!(result.is_ok());
    }

    #[test]
    fn test_generate_with_build_status() {
        let successful_program = SolanaProgram {
            package_name: "good_package".to_string(),
            target_name: "good_program".to_string(),
            manifest_path: PathBuf::from("/path/to/good/Cargo.toml"),
        };

        let failed_program = SolanaProgram {
            package_name: "bad_package".to_string(),
            target_name: "bad_program".to_string(),
            manifest_path: PathBuf::from("/path/to/bad/Cargo.toml"),
        };

        let build_result = BuildResult {
            successful: vec![(successful_program, PathBuf::from("/tmp/good_program.so"))],
            failed: vec![(
                failed_program,
                Error::ProgramBuild {
                    program: "bad_program".to_string(),
                    error: "wasi crate contains multiple cdylib targets".to_string(),
                },
            )],
        };

        let result = generate(&build_result).unwrap();

        // Should contain build status comments
        assert!(result.contains("// Build Status:"));
        assert!(result.contains("// ✓ good_program - SUCCESS"));
        assert!(result.contains("// ✗ bad_program - FAILED: Failed to build program bad_program: wasi crate contains multiple cdylib targets"));

        // Should only include successful program in constants
        assert!(result.contains("pub const GOOD_PROGRAM_ELF"));
        assert!(!result.contains("pub const BAD_PROGRAM_ELF"));

        // Should only include successful program in elves function
        assert!(result.contains("(\"good_program\", GOOD_PROGRAM_ELF),"));
        assert!(!result.contains("(\"bad_program\""));
    }

    #[test]
    fn test_alphabetical_sorting_mixed_success_and_failure() {
        // Create programs with names that should be sorted alphabetically
        let zebra_program = SolanaProgram {
            package_name: "zebra".to_string(),
            target_name: "zebra".to_string(),
            manifest_path: PathBuf::from("/path/to/zebra/Cargo.toml"),
        };

        let alpha_program = SolanaProgram {
            package_name: "alpha".to_string(),
            target_name: "alpha".to_string(),
            manifest_path: PathBuf::from("/path/to/alpha/Cargo.toml"),
        };

        let beta_program = SolanaProgram {
            package_name: "beta".to_string(),
            target_name: "beta".to_string(),
            manifest_path: PathBuf::from("/path/to/beta/Cargo.toml"),
        };

        // Mix success and failure to test unified sorting
        let build_result = BuildResult {
            successful: vec![
                (zebra_program, PathBuf::from("/tmp/zebra.so")),
                (beta_program, PathBuf::from("/tmp/beta.so")),
            ],
            failed: vec![(
                alpha_program,
                Error::ProgramBuild {
                    program: "alpha".to_string(),
                    error: "dependency not found".to_string(),
                },
            )],
        };

        let result = generate(&build_result).unwrap();

        // Find the build status section
        let build_status_start = result.find("// Build Status:").unwrap();
        let build_status_section = &result[build_status_start..];

        // Build status should be alphabetical: alpha (failed), beta (success), zebra (success)
        let alpha_pos = build_status_section.find("// ✗ alpha").unwrap();
        let beta_pos = build_status_section.find("// ✓ beta").unwrap();
        let zebra_pos = build_status_section.find("// ✓ zebra").unwrap();

        assert!(
            alpha_pos < beta_pos,
            "alpha should come before beta in build status"
        );
        assert!(
            beta_pos < zebra_pos,
            "beta should come before zebra in build status"
        );

        // Constants should be alphabetical too: beta, zebra (alpha failed so no constant)
        let beta_const_pos = result.find("pub const BETA_ELF").unwrap();
        let zebra_const_pos = result.find("pub const ZEBRA_ELF").unwrap();

        assert!(
            beta_const_pos < zebra_const_pos,
            "BETA_ELF should come before ZEBRA_ELF"
        );

        // elves() function should be alphabetical: beta, zebra
        let elves_section = result.find("pub fn elves()").unwrap();
        let elves_content = &result[elves_section..];

        let beta_elves_pos = elves_content.find("(\"beta\", BETA_ELF)").unwrap();
        let zebra_elves_pos = elves_content.find("(\"zebra\", ZEBRA_ELF)").unwrap();

        assert!(
            beta_elves_pos < zebra_elves_pos,
            "beta should come before zebra in elves()"
        );
    }

    #[test]
    fn test_alphabetical_sorting_case_sensitive() {
        let lower_program = SolanaProgram {
            package_name: "lower".to_string(),
            target_name: "aaa_program".to_string(),
            manifest_path: PathBuf::from("/path/to/lower/Cargo.toml"),
        };

        let upper_program = SolanaProgram {
            package_name: "upper".to_string(),
            target_name: "ZZZ_program".to_string(),
            manifest_path: PathBuf::from("/path/to/upper/Cargo.toml"),
        };

        let build_result = BuildResult {
            successful: vec![
                (upper_program, PathBuf::from("/tmp/ZZZ_program.so")),
                (lower_program, PathBuf::from("/tmp/aaa_program.so")),
            ],
            failed: Vec::new(),
        };

        let result = generate(&build_result).unwrap();

        // Build status should be sorted by target_name: ZZZ_program, aaa_program (uppercase comes first in ASCII)
        let build_status_start = result.find("// Build Status:").unwrap();
        let build_status_section = &result[build_status_start..];

        let zzz_pos = build_status_section.find("// ✓ ZZZ_program").unwrap();
        let aaa_pos = build_status_section.find("// ✓ aaa_program").unwrap();

        assert!(zzz_pos < aaa_pos, "ZZZ_program should come before aaa_program (uppercase letters come first in ASCII sort)");

        // Constants should follow same order
        let zzz_const_pos = result.find("pub const ZZZ_PROGRAM_ELF").unwrap();
        let aaa_const_pos = result.find("pub const AAA_PROGRAM_ELF").unwrap();

        assert!(
            zzz_const_pos < aaa_const_pos,
            "ZZZ_PROGRAM_ELF should come before AAA_PROGRAM_ELF"
        );
    }
}