elf-magic 0.5.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
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
use std::{
    collections::HashMap,
    path::{Path, PathBuf},
};

use cargo_metadata::{CrateType, Metadata, MetadataCommand};

use crate::{
    config::{resolve_constants_paths, resolve_targets_paths, Config},
    error::Error,
    programs::{DiscoveredPrograms, SolanaProgram},
};

/// Load workspaces from config
pub fn load_workspaces(config_file_dir: &Path, config: &Config) -> Result<Vec<Workspace>, Error> {
    // Get resolved overrides from config
    let resolved_constants = resolve_constants_paths(&config.constants(), config_file_dir);
    let resolved_targets = resolve_targets_paths(&config.targets(), config_file_dir);

    match config {
        Config::LaserEyes { workspaces, .. } => {
            let mut results = Vec::new();
            for workspace in workspaces {
                let metadata = MetadataCommand::new()
                    .manifest_path(&workspace.manifest_path)
                    .no_deps()
                    .other_options(vec!["--locked".to_string()])
                    .exec()?;

                let manifest_path = workspace.manifest_path.clone();

                results.push(Workspace {
                    metadata,
                    manifest_path,
                    filter_mode: FilterMode::Only(workspace.only.clone()),
                    constants_overrides: resolved_constants.clone(),
                    targets_overrides: resolved_targets.clone(),
                });
            }
            Ok(results)
        }
        Config::Magic => {
            let metadata = MetadataCommand::new()
                .no_deps()
                .other_options(vec!["--locked".to_string()])
                .exec()?;

            let manifest_path = metadata
                .workspace_root
                .as_std_path()
                .join("Cargo.toml")
                .display()
                .to_string();

            Ok(vec![Workspace {
                metadata,
                manifest_path,
                filter_mode: FilterMode::Magic,
                constants_overrides: resolved_constants,
                targets_overrides: resolved_targets,
            }])
        }
        Config::Permissive {
            workspaces,
            global_deny,
            ..
        } => {
            let mut results = Vec::new();
            for workspace in workspaces {
                let metadata = MetadataCommand::new()
                    .manifest_path(&workspace.manifest_path)
                    .no_deps()
                    .other_options(vec!["--locked".to_string()])
                    .exec()?;

                let manifest_path = workspace.manifest_path.clone();

                // Merge global excludes with workspace-specific excludes
                let mut merged_denies = global_deny.clone();
                merged_denies.extend(workspace.deny.clone());

                results.push(Workspace {
                    metadata,
                    manifest_path,
                    filter_mode: FilterMode::Deny(merged_denies),
                    constants_overrides: resolved_constants.clone(),
                    targets_overrides: resolved_targets.clone(),
                });
            }
            Ok(results)
        }
    }
}

/// Filtering mode for programs
#[derive(Debug, Clone)]
pub enum FilterMode {
    /// Magic mode: include all programs (no filtering)
    Magic,
    /// Permissive mode: include all except those matching deny patterns
    Deny(Vec<String>),
    /// Laser-eyes mode: include programs matching only patterns
    Only(Vec<String>),
}

/// Information about an individual cargo workspace
pub struct Workspace {
    pub metadata: Metadata,
    pub manifest_path: String,
    pub filter_mode: FilterMode,
    pub constants_overrides: HashMap<PathBuf, String>,
    pub targets_overrides: HashMap<PathBuf, String>,
}

impl Workspace {
    /// Discover Solana programs in the workspace
    pub fn discover_programs(&self) -> Result<DiscoveredPrograms, Error> {
        let mut included = Vec::new();
        let mut excluded = Vec::new();

        for package in &self.metadata.packages {
            for target in &package.targets {
                let is_cdylib = target.crate_types.contains(&CrateType::CDyLib);
                if !is_cdylib {
                    continue;
                }

                let manifest_path = package.manifest_path.as_std_path().to_path_buf();
                let base_target_name = target.name.to_string();

                // Create fully resolved program upfront
                let program = SolanaProgram {
                    package_name: package.name.to_string(),
                    target_name: resolve_target_name(
                        &base_target_name,
                        &manifest_path,
                        &self.targets_overrides,
                    ),
                    manifest_path: manifest_path.clone(),
                    constant_name: resolve_constant_name(
                        &base_target_name,
                        &manifest_path,
                        &self.constants_overrides,
                    ),
                };

                // Now filter the fully resolved program
                match &self.filter_mode {
                    FilterMode::Magic => {
                        // Magic mode: include all programs
                        included.push(program);
                    }
                    FilterMode::Deny(deny_patterns) => {
                        // Permissive mode: include all except those matching deny patterns
                        if should_include_program_permissive(&program, deny_patterns) {
                            included.push(program);
                        } else {
                            excluded.push(program);
                        }
                    }
                    FilterMode::Only(only_patterns) => {
                        // Laser-eyes mode: include programs matching only patterns
                        if should_only_include_program(&program, only_patterns) {
                            included.push(program);
                        } else {
                            excluded.push(program);
                        }
                    }
                }
            }
        }

        included.sort_by(|a, b| a.target_name.cmp(&b.target_name));
        excluded.sort_by(|a, b| a.target_name.cmp(&b.target_name));

        Ok(DiscoveredPrograms {
            workspace_path: self.manifest_path.clone(),
            included,
            excluded,
        })
    }
}

/// Resolve target name using overrides
fn resolve_target_name(
    base_target_name: &str,
    manifest_path: &Path,
    targets_overrides: &HashMap<PathBuf, String>,
) -> String {
    targets_overrides
        .get(manifest_path)
        .cloned()
        .unwrap_or_else(|| base_target_name.to_string())
}

/// Resolve constant name using overrides
fn resolve_constant_name(
    base_target_name: &str,
    manifest_path: &Path,
    constants_overrides: &HashMap<PathBuf, String>,
) -> String {
    constants_overrides
        .get(manifest_path)
        .cloned()
        .unwrap_or_else(|| format!("{}_ELF", base_target_name.to_uppercase()))
}

/// Check if a program should be included in laser-eyes mode (matches only patterns)
fn should_only_include_program(program: &SolanaProgram, only_patterns: &[String]) -> bool {
    only_patterns
        .iter()
        .any(|pattern| matches_program_pattern(program, pattern))
}

/// Check if a program should be included (not denied by glob patterns)
fn should_include_program_permissive(program: &SolanaProgram, deny_patterns: &[String]) -> bool {
    !deny_patterns
        .iter()
        .any(|pattern| matches_program_pattern(program, pattern))
}

fn matches_program_pattern(program: &SolanaProgram, pattern: &str) -> bool {
    if let Some(target_pattern) = pattern.strip_prefix("target:") {
        matches_glob(&program.target_name, target_pattern)
    } else if let Some(package_pattern) = pattern.strip_prefix("package:") {
        matches_glob(&program.package_name, package_pattern)
    } else if let Some(path_pattern) = pattern.strip_prefix("path:") {
        matches_glob(&program.manifest_path.to_string_lossy(), path_pattern)
    } else {
        // No fallback - invalid pattern
        eprintln!(
            "Warning: Invalid deny pattern '{}'. Use 'target:', 'package:', or 'path:' prefix.",
            pattern
        );
        false
    }
}

fn matches_glob(text: &str, pattern: &str) -> bool {
    glob::Pattern::new(pattern)
        .map(|p| p.matches(text))
        .unwrap_or(false)
}

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

    fn sample_program(target_name: &str, package_name: &str) -> SolanaProgram {
        SolanaProgram {
            target_name: target_name.to_string(),
            package_name: package_name.to_string(),
            manifest_path: PathBuf::from("/workspace/Cargo.toml"),
            constant_name: format!("{}_ELF", target_name.to_uppercase()),
        }
    }

    #[test]
    fn test_should_include_program_no_exclusions() {
        let program = sample_program("my_target", "my_package");
        let deny_patterns = vec![];

        assert!(should_include_program_permissive(&program, &deny_patterns));
    }

    #[test]
    fn test_should_include_program_target_exclusion_match() {
        let program = sample_program("test_program", "my_package");
        let deny_patterns = vec!["target:test*".to_string()];

        assert!(!should_include_program_permissive(&program, &deny_patterns));
    }

    #[test]
    fn test_should_include_program_target_exclusion_no_match() {
        let program = sample_program("main_program", "my_package");
        let deny_patterns = vec!["target:test*".to_string()];

        assert!(should_include_program_permissive(&program, &deny_patterns));
    }

    #[test]
    fn test_should_include_program_package_exclusion_match() {
        let program = sample_program("my_target", "dev_package");
        let deny_patterns = vec!["package:dev*".to_string()];

        assert!(!should_include_program_permissive(&program, &deny_patterns));
    }

    #[test]
    fn test_should_include_program_package_exclusion_no_match() {
        let program = sample_program("my_target", "main_package");
        let deny_patterns = vec!["package:dev*".to_string()];

        assert!(should_include_program_permissive(&program, &deny_patterns));
    }

    #[test]
    fn test_should_include_program_path_exclusion_match() {
        let program = SolanaProgram {
            target_name: "my_target".to_string(),
            package_name: "my_package".to_string(),
            manifest_path: PathBuf::from("/workspace/examples/test/Cargo.toml"),
            constant_name: "MY_TARGET_ELF".to_string(),
        };
        let deny_patterns = vec!["path:*/examples/*".to_string()];

        assert!(!should_include_program_permissive(&program, &deny_patterns));
    }

    #[test]
    fn test_should_include_program_path_exclusion_no_match() {
        let program = SolanaProgram {
            target_name: "my_target".to_string(),
            package_name: "my_package".to_string(),
            manifest_path: PathBuf::from("/workspace/src/Cargo.toml"),
            constant_name: "MY_TARGET_ELF".to_string(),
        };
        let deny_patterns = vec!["path:*/examples/*".to_string()];

        assert!(should_include_program_permissive(&program, &deny_patterns));
    }

    #[test]
    fn test_should_include_program_multiple_exclusions() {
        let program = sample_program("test_target", "dev_package");
        let deny_patterns = vec!["target:test*".to_string(), "package:dev*".to_string()];

        // Should be denied because it matches the target pattern
        assert!(!should_include_program_permissive(&program, &deny_patterns));
    }

    #[test]
    fn test_should_include_program_multiple_exclusions_no_match() {
        let program = sample_program("main_target", "main_package");
        let deny_patterns = vec!["target:test*".to_string(), "package:dev*".to_string()];

        assert!(should_include_program_permissive(&program, &deny_patterns));
    }

    #[test]
    fn test_matches_program_pattern_target() {
        let program = sample_program("test_program", "my_package");

        assert!(matches_program_pattern(&program, "target:test*"));
        assert!(matches_program_pattern(&program, "target:test_program"));
        assert!(!matches_program_pattern(&program, "target:main*"));
    }

    #[test]
    fn test_matches_program_pattern_package() {
        let program = sample_program("my_target", "dev_package");

        assert!(matches_program_pattern(&program, "package:dev*"));
        assert!(matches_program_pattern(&program, "package:dev_package"));
        assert!(!matches_program_pattern(&program, "package:main*"));
    }

    #[test]
    fn test_matches_program_pattern_path() {
        let program = SolanaProgram {
            target_name: "my_target".to_string(),
            package_name: "my_package".to_string(),
            manifest_path: PathBuf::from("/workspace/examples/basic/Cargo.toml"),
            constant_name: "MY_TARGET_ELF".to_string(),
        };

        assert!(matches_program_pattern(&program, "path:*/examples/*"));
        assert!(matches_program_pattern(&program, "path:*/basic/*"));
        assert!(!matches_program_pattern(&program, "path:*/src/*"));
    }

    #[test]
    fn test_matches_program_pattern_invalid_prefix() {
        let program = sample_program("test_program", "my_package");

        // Invalid patterns should return false and print warning
        assert!(!matches_program_pattern(&program, "invalid:test*"));
        assert!(!matches_program_pattern(&program, "test*")); // No prefix
        assert!(!matches_program_pattern(&program, "random_pattern"));
    }

    #[test]
    fn test_matches_glob_basic() {
        assert!(matches_glob("test_program", "test*"));
        assert!(matches_glob("test_program", "*program"));
        assert!(matches_glob("test_program", "test_program"));
        assert!(!matches_glob("test_program", "main*"));
    }

    #[test]
    fn test_matches_glob_question_mark() {
        assert!(matches_glob("test", "tes?"));
        assert!(matches_glob("test", "t?st"));
        assert!(!matches_glob("test", "tes??"));
    }

    #[test]
    fn test_matches_glob_complex_patterns() {
        assert!(matches_glob("my-test-program", "*test*"));
        assert!(matches_glob("program_v1", "program_*"));
        assert!(matches_glob("examples/basic/program", "examples/*/program"));
        assert!(!matches_glob(
            "examples/basic/program",
            "examples/advanced/*"
        ));
    }

    #[test]
    fn test_matches_glob_invalid_pattern() {
        // Invalid glob pattern should not match anything
        assert!(!matches_glob("test", "[invalid"));
    }

    #[test]
    fn test_global_exclude_merging() {
        let program1 = sample_program("my_target", "apl-token");
        let program2 = sample_program("test_target", "my_package");
        let program3 = sample_program("my_target", "dev-package");

        // Test merging: global excludes + workspace excludes
        let global_denies = vec!["package:apl-*".to_string()];
        let workspace_denies = vec!["target:test*".to_string()];
        let mut merged_denies = global_denies.clone();
        merged_denies.extend(workspace_denies);

        // program1 should be excluded by global exclude (package:apl-*)
        assert!(!should_include_program_permissive(
            &program1,
            &merged_denies
        ));

        // program2 should be excluded by workspace exclude (target:test*)
        assert!(!should_include_program_permissive(
            &program2,
            &merged_denies
        ));

        // program3 should be included (matches neither pattern)
        assert!(should_include_program_permissive(&program3, &merged_denies));
    }

    #[test]
    fn test_should_only_include_program_target_match() {
        let program = sample_program("token_manager", "my_package");
        let only_patterns = vec!["target:token*".to_string()];

        assert!(should_only_include_program(&program, &only_patterns));
    }

    #[test]
    fn test_should_only_include_program_target_no_match() {
        let program = sample_program("governance", "my_package");
        let only_patterns = vec!["target:token*".to_string()];

        assert!(!should_only_include_program(&program, &only_patterns));
    }

    #[test]
    fn test_should_only_include_program_package_match() {
        let program = sample_program("my_target", "token_program");
        let only_patterns = vec!["package:token*".to_string()];

        assert!(should_only_include_program(&program, &only_patterns));
    }

    #[test]
    fn test_should_only_include_program_package_no_match() {
        let program = sample_program("my_target", "governance_program");
        let only_patterns = vec!["package:token*".to_string()];

        assert!(!should_only_include_program(&program, &only_patterns));
    }

    #[test]
    fn test_should_only_include_program_multiple_patterns() {
        let program1 = sample_program("token_manager", "my_package");
        let program2 = sample_program("governance", "my_package");
        let program3 = sample_program("other_program", "my_package");

        let only_patterns = vec!["target:token*".to_string(), "target:governance".to_string()];

        // Should match both token* and governance patterns
        assert!(should_only_include_program(&program1, &only_patterns));
        assert!(should_only_include_program(&program2, &only_patterns));

        // Should not match
        assert!(!should_only_include_program(&program3, &only_patterns));
    }

    #[test]
    fn test_should_only_include_program_empty_patterns() {
        let program = sample_program("any_program", "any_package");
        let only_patterns = vec![];

        // Empty patterns should include nothing
        assert!(!should_only_include_program(&program, &only_patterns));
    }

    #[test]
    fn test_should_only_include_program_path_match() {
        let program = SolanaProgram {
            target_name: "my_target".to_string(),
            package_name: "my_package".to_string(),
            manifest_path: PathBuf::from("/workspace/programs/core/Cargo.toml"),
            constant_name: "MY_TARGET_ELF".to_string(),
        };
        let only_patterns = vec!["path:*/programs/core/*".to_string()];

        assert!(should_only_include_program(&program, &only_patterns));
    }

    #[test]
    fn test_filter_mode_magic() {
        let filter_mode = FilterMode::Magic;

        match filter_mode {
            FilterMode::Magic => {
                // Magic mode should include all programs - test passes by not panicking
            }
            _ => panic!("Expected Magic filter mode"),
        }
    }

    #[test]
    fn test_filter_mode_exclude() {
        let filter_mode = FilterMode::Deny(vec!["target:test*".to_string()]);

        match filter_mode {
            FilterMode::Deny(patterns) => {
                assert_eq!(patterns, vec!["target:test*"]);
            }
            _ => panic!("Expected Exclude filter mode"),
        }
    }

    #[test]
    fn test_filter_mode_include() {
        let filter_mode = FilterMode::Only(vec!["target:token*".to_string()]);

        match filter_mode {
            FilterMode::Only(patterns) => {
                assert_eq!(patterns, vec!["target:token*"]);
            }
            _ => panic!("Expected Include filter mode"),
        }
    }
}