rez-next-package 0.3.6

Advanced package management with complete package.py parsing and 100% Rez compatibility
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
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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
//! Package method implementations.

use rez_next_common::RezCoreError;
use rez_next_version::Version;
use std::collections::HashMap;

use super::types::Package;

impl Package {
    pub fn new(name: String) -> Self {
        Self {
            name,
            version: None,
            description: None,
            authors: Vec::new(),
            requires: Vec::new(),
            build_requires: Vec::new(),
            private_build_requires: Vec::new(),
            variants: Vec::new(),
            tools: Vec::new(),
            commands: None,
            commands_function: None,
            build_command: None,
            build_system: None,
            pre_commands: None,
            post_commands: None,
            pre_test_commands: None,
            pre_build_commands: None,
            tests: HashMap::new(),
            requires_rez_version: None,
            uuid: None,
            config: HashMap::new(),
            help: None,
            relocatable: None,
            cachable: None,
            timestamp: None,
            revision: None,
            changelog: None,
            release_message: None,
            previous_version: None,
            previous_revision: None,
            vcs: None,
            format_version: None,
            base: None,
            has_plugins: None,
            plugin_for: Vec::new(),
            hashed_variants: None,
            preprocess: None,
            is_dev_package: None,
            filepath: None,
            includes: None,
        }
    }

    /// Get the qualified name of the package (name-version)
    pub fn qualified_name(&self) -> String {
        match &self.version {
            Some(version) => format!("{}-{}", self.name, version.as_str()),
            None => self.name.clone(),
        }
    }

    /// Get the package as an exact requirement string
    pub fn as_exact_requirement(&self) -> String {
        match &self.version {
            Some(version) => format!("{}=={}", self.name, version.as_str()),
            None => self.name.clone(),
        }
    }

    /// Check if this is a package (always true for Package)
    pub fn is_package(&self) -> bool {
        true
    }

    /// Check if this is a variant (always false for Package)
    pub fn is_variant(&self) -> bool {
        false
    }

    /// Get the number of variants
    pub fn num_variants(&self) -> usize {
        self.variants.len()
    }

    /// Set the package version
    pub fn set_version(&mut self, version: Version) {
        self.version = Some(version);
    }

    /// Set the package description
    pub fn set_description(&mut self, description: String) {
        self.description = Some(description);
    }

    /// Add an author
    pub fn add_author(&mut self, author: String) {
        self.authors.push(author);
    }

    /// Add a requirement
    pub fn add_requirement(&mut self, requirement: String) {
        self.requires.push(requirement);
    }

    /// Add a build requirement
    pub fn add_build_requirement(&mut self, requirement: String) {
        self.build_requires.push(requirement);
    }

    /// Add a private build requirement
    pub fn add_private_build_requirement(&mut self, requirement: String) {
        self.private_build_requires.push(requirement);
    }

    /// Add a variant
    pub fn add_variant(&mut self, variant: Vec<String>) {
        self.variants.push(variant);
    }

    /// Add a tool
    pub fn add_tool(&mut self, tool: String) {
        self.tools.push(tool);
    }

    /// Set commands
    pub fn set_commands(&mut self, commands: String) {
        self.commands = Some(commands);
    }

    /// Check if the package definition is valid
    pub fn is_valid(&self) -> bool {
        self.validate().is_ok()
    }

    /// Validate the package definition
    pub fn validate(&self) -> Result<(), RezCoreError> {
        if self.name.is_empty() {
            return Err(RezCoreError::PackageParse(
                "Package name cannot be empty".to_string(),
            ));
        }

        if !self
            .name
            .chars()
            .all(|c| c.is_alphanumeric() || c == '_' || c == '-')
        {
            return Err(RezCoreError::PackageParse(format!(
                "Invalid package name '{}': only alphanumeric, underscore, and hyphen allowed",
                self.name
            )));
        }

        if let Some(ref version) = self.version
            && version.as_str().is_empty()
        {
            return Err(RezCoreError::PackageParse(
                "Package version cannot be empty".to_string(),
            ));
        }

        for req in &self.requires {
            if req.is_empty() {
                return Err(RezCoreError::PackageParse(
                    "Requirement cannot be empty".to_string(),
                ));
            }
        }

        for req in &self.build_requires {
            if req.is_empty() {
                return Err(RezCoreError::PackageParse(
                    "Build requirement cannot be empty".to_string(),
                ));
            }
        }

        for req in &self.private_build_requires {
            if req.is_empty() {
                return Err(RezCoreError::PackageParse(
                    "Private build requirement cannot be empty".to_string(),
                ));
            }
        }

        for variant in &self.variants {
            for req in variant {
                if req.is_empty() {
                    return Err(RezCoreError::PackageParse(
                        "Variant requirement cannot be empty".to_string(),
                    ));
                }
            }
        }

        Ok(())
    }

    /// Load a developer package from a path.
    ///
    /// This aligns with Rez's `DeveloperPackage.from_path()` interface.
    /// Supports both file path (package.py/package.yaml) and directory path.
    ///
    /// # Arguments
    /// * `path` - Directory containing package definition, or path to the file itself
    ///
    /// # Returns
    /// * `Result<Package, RezCoreError>` - The loaded package
    ///
    /// # Example
    /// ```
    /// # use rez_next_package::package::types::Package;
    /// # use std::path::PathBuf;
    /// # use tempfile::TempDir;
    /// # let dir = TempDir::new().unwrap();
    /// # let pkg_path = dir.path().join("package.py");
    /// # std::fs::write(&pkg_path, r#"name = "mypackage""#).unwrap();
    /// let pkg = Package::from_path(pkg_path).unwrap();
    /// assert_eq!(pkg.name, "mypackage");
    /// ```
    pub fn from_path<P: AsRef<std::path::Path>>(path: P) -> Result<Self, RezCoreError> {
        let path = path.as_ref();

        // Determine if path is a directory or file
        let file_path = if path.is_dir() {
            // Look for package.py or package.yaml in directory
            let package_py = path.join("package.py");
            let package_yaml = path.join("package.yaml");
            let package_yml = path.join("package.yml");

            if package_py.exists() {
                package_py
            } else if package_yaml.exists() {
                package_yaml
            } else if package_yml.exists() {
                package_yml
            } else {
                return Err(RezCoreError::PackageParse(format!(
                    "No package definition file found in {}",
                    path.display()
                )));
            }
        } else {
            path.to_path_buf()
        };

        // Load package from file
        let mut pkg = crate::serialization::PackageSerializer::load_from_file(&file_path)
            .map_err(|e| RezCoreError::PackageParse(format!("Failed to load package: {}", e)))?;

        // Set filepath
        pkg.filepath = Some(file_path.to_string_lossy().to_string());

        // Set is_dev_package flag
        pkg.is_dev_package = Some(true);

        // TODO: Collect includes from SourceCode objects
        // This requires parsing the package data to find all @include decorators
        // For now, we leave includes as None

        Ok(pkg)
    }

    /// Get the root directory of the package (parent of filepath).
    ///
    /// Aligns with Rez's `DeveloperPackage.root` property.
    pub fn root(&self) -> Option<String> {
        self.filepath.as_ref().and_then(|fp| {
            std::path::Path::new(fp)
                .parent()
                .map(|p| p.to_string_lossy().to_string())
        })
    }

    /// Serialize the package to package.py format string.
    /// Compatible with rez package.py format.
    pub fn to_package_py(&self) -> String {
        let mut lines = Vec::new();

        // name (required)
        lines.push(format!("name = \"{}\"", self.name));

        // version (optional)
        if let Some(ref version) = self.version {
            lines.push(format!("version = \"{}\"", version.as_str()));
        }

        // description (optional)
        if let Some(ref desc) = self.description {
            // Escape quotes in description
            let desc_escaped = desc.replace("\"", "\\\"");
            lines.push(format!("description = \"{}\"", desc_escaped));
        }

        // authors (optional)
        if !self.authors.is_empty() {
            let authors_str = self
                .authors
                .iter()
                .map(|a| format!("\"{}\"", a.replace("\"", "\\\"")))
                .collect::<Vec<_>>()
                .join(", ");
            lines.push(format!("authors = [{}]", authors_str));
        }

        // requires (optional)
        if !self.requires.is_empty() {
            let req_str = self
                .requires
                .iter()
                .map(|r| format!("    \"{}\"", r))
                .collect::<Vec<_>>()
                .join(",\n");
            lines.push(format!("requires = [\n{}\n]", req_str));
        }

        // build_requires (optional)
        if !self.build_requires.is_empty() {
            let req_str = self
                .build_requires
                .iter()
                .map(|r| format!("    \"{}\"", r))
                .collect::<Vec<_>>()
                .join(",\n");
            lines.push(format!("build_requires = [\n{}\n]", req_str));
        }

        // private_build_requires (optional)
        if !self.private_build_requires.is_empty() {
            let req_str = self
                .private_build_requires
                .iter()
                .map(|r| format!("    \"{}\"", r))
                .collect::<Vec<_>>()
                .join(",\n");
            lines.push(format!("private_build_requires = [\n{}\n]", req_str));
        }

        // variants (optional)
        if !self.variants.is_empty() {
            let mut variant_lines = Vec::new();
            for variant in &self.variants {
                let var_str = variant
                    .iter()
                    .map(|r| format!("\"{}\"", r))
                    .collect::<Vec<_>>()
                    .join(", ");
                variant_lines.push(format!("    [{}]", var_str));
            }
            lines.push(format!("variants = [\n{}\n]", variant_lines.join(",\n")));
        }

        // tools (optional)
        if !self.tools.is_empty() {
            let tools_str = self
                .tools
                .iter()
                .map(|t| format!("\"{}\"", t))
                .collect::<Vec<_>>()
                .join(", ");
            lines.push(format!("tools = [{}]", tools_str));
        }

        // uuid (optional)
        if let Some(ref uuid) = self.uuid {
            lines.push(format!("uuid = \"{}\"", uuid));
        }

        // relocatable (optional)
        if let Some(ref relocatable) = self.relocatable {
            lines.push(format!("relocatable = {}", relocatable));
        }

        // cachable (optional)
        if let Some(ref cachable) = self.cachable {
            lines.push(format!("cachable = {}", cachable));
        }

        // commands function (optional)
        if let Some(ref commands) = self.commands {
            lines.push("\ndef commands():".to_string());
            // Add commands function body with proper indentation
            for line in commands.lines() {
                if line.trim().is_empty() {
                    lines.push("".to_string());
                } else {
                    lines.push(format!("    {}", line));
                }
            }
        }

        // pre_commands (optional)
        if let Some(ref pre_commands) = self.pre_commands {
            lines.push("\ndef pre_commands():".to_string());
            for line in pre_commands.lines() {
                if line.trim().is_empty() {
                    lines.push("".to_string());
                } else {
                    lines.push(format!("    {}", line));
                }
            }
        }

        // post_commands (optional)
        if let Some(ref post_commands) = self.post_commands {
            lines.push("\ndef post_commands():".to_string());
            for line in post_commands.lines() {
                if line.trim().is_empty() {
                    lines.push("".to_string());
                } else {
                    lines.push(format!("    {}", line));
                }
            }
        }

        // tests (optional) - simplified serialization
        if !self.tests.is_empty() {
            lines.push("\ntests = {".to_string());
            for test_name in self.tests.keys() {
                // Simplified: just add a comment, full serialization is complex
                lines.push(format!("    \"{}\": {{", test_name));
                lines.push("        # test definition".to_string());
                lines.push("    },".to_string());
            }
            lines.push("}".to_string());
        }

        lines.join("\n")
    }
}

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

    #[test]
    fn test_to_package_py_basic() {
        let pkg = Package::new("test_pkg".to_string());
        let result = pkg.to_package_py();
        assert!(result.contains("name = \"test_pkg\""));
        assert!(!result.contains("version = "));
    }

    #[test]
    fn test_to_package_py_with_version() {
        let mut pkg = Package::new("test_pkg".to_string());
        pkg.version = Some(Version::parse("1.0.0").unwrap());
        let result = pkg.to_package_py();
        assert!(result.contains("name = \"test_pkg\""));
        assert!(result.contains("version = \"1.0.0\""));
    }

    #[test]
    fn test_to_package_py_with_description() {
        let mut pkg = Package::new("test_pkg".to_string());
        pkg.description = Some("A test package".to_string());
        let result = pkg.to_package_py();
        assert!(result.contains("description = \"A test package\""));
    }

    #[test]
    fn test_to_package_py_with_authors() {
        let mut pkg = Package::new("test_pkg".to_string());
        pkg.authors = vec!["Author One".to_string(), "Author Two".to_string()];
        let result = pkg.to_package_py();
        assert!(result.contains("authors = ["));
        assert!(result.contains("\"Author One\""));
        assert!(result.contains("\"Author Two\""));
    }

    #[test]
    fn test_to_package_py_with_requires() {
        let mut pkg = Package::new("test_pkg".to_string());
        pkg.requires = vec!["python-3.9".to_string(), "maya-2024".to_string()];
        let result = pkg.to_package_py();
        assert!(result.contains("requires = ["));
        assert!(result.contains("\"python-3.9\""));
        assert!(result.contains("\"maya-2024\""));
    }

    #[test]
    fn test_to_package_py_with_variants() {
        let mut pkg = Package::new("test_pkg".to_string());
        pkg.variants = vec![
            vec!["python-3.9".to_string()],
            vec!["python-3.10".to_string()],
        ];
        let result = pkg.to_package_py();
        assert!(result.contains("variants = ["));
        assert!(result.contains("[\"python-3.9\"]"));
        assert!(result.contains("[\"python-3.10\"]"));
    }

    #[test]
    fn test_to_package_py_with_tools() {
        let mut pkg = Package::new("test_pkg".to_string());
        pkg.tools = vec!["mytool".to_string(), "another_tool".to_string()];
        let result = pkg.to_package_py();
        assert!(result.contains("tools = ["));
        assert!(result.contains("\"mytool\""));
        assert!(result.contains("\"another_tool\""));
    }

    #[test]
    fn test_to_package_py_with_commands() {
        let mut pkg = Package::new("test_pkg".to_string());
        pkg.commands = Some("    env.PATH.prepend(\"{root}/bin\")\n".to_string());
        let result = pkg.to_package_py();
        assert!(result.contains("def commands():"));
        assert!(result.contains("env.PATH.prepend"));
    }

    #[test]
    fn test_to_package_py_with_uuid() {
        let mut pkg = Package::new("test_pkg".to_string());
        pkg.uuid = Some("12345678-1234-1234-1234-123456789012".to_string());
        let result = pkg.to_package_py();
        assert!(result.contains("uuid = \"12345678-1234-1234-1234-123456789012\""));
    }

    #[test]
    fn test_to_package_py_with_relocatable() {
        let mut pkg = Package::new("test_pkg".to_string());
        pkg.relocatable = Some(true);
        let result = pkg.to_package_py();
        assert!(result.contains("relocatable = true"));
    }

    #[test]
    fn test_to_package_py_with_cachable() {
        let mut pkg = Package::new("test_pkg".to_string());
        pkg.cachable = Some(false);
        let result = pkg.to_package_py();
        assert!(result.contains("cachable = false"));
    }

    #[test]
    fn test_to_package_py_complete() {
        let mut pkg = Package::new("complete_pkg".to_string());
        pkg.version = Some(Version::parse("2.1.0").unwrap());
        pkg.description = Some("A complete test package".to_string());
        pkg.authors = vec!["Test Author".to_string()];
        pkg.requires = vec!["python-3.9".to_string()];
        pkg.build_requires = vec!["cmake-3.20".to_string()];
        pkg.variants = vec![
            vec!["python-3.9".to_string()],
            vec!["python-3.10".to_string()],
        ];
        pkg.tools = vec!["mytool".to_string()];
        pkg.commands = Some("    env.PATH.prepend(\"{root}/bin\")\n".to_string());
        pkg.uuid = Some("12345678-1234-1234-1234-123456789012".to_string());
        pkg.relocatable = Some(true);
        pkg.cachable = Some(true);

        let result = pkg.to_package_py();

        // Verify all fields are present
        assert!(result.contains("name = \"complete_pkg\""));
        assert!(result.contains("version = \"2.1.0\""));
        assert!(result.contains("description = \"A complete test package\""));
        assert!(result.contains("authors = ["));
        assert!(result.contains("requires = ["));
        assert!(result.contains("build_requires = ["));
        assert!(result.contains("variants = ["));
        assert!(result.contains("tools = ["));
        assert!(result.contains("def commands():"));
        assert!(result.contains("uuid = "));
        assert!(result.contains("relocatable = true"));
        assert!(result.contains("cachable = true"));
    }

    #[test]
    fn test_to_package_py_output_format_valid() {
        let mut pkg = Package::new("format_test".to_string());
        pkg.version = Some(Version::parse("1.0.0").unwrap());
        pkg.requires = vec!["python-3.9".to_string()];
        pkg.commands = Some("    env.PATH.prepend(\"{root}/bin\")\n".to_string());

        let result = pkg.to_package_py();

        // Verify output can be parsed as valid Python (basic check)
        assert!(result.starts_with("name = "));
        assert!(result.contains("def commands():"));
        assert!(result.contains("    env.PATH.prepend"));
    }

    #[test]
    fn test_to_package_py_escapes_description() {
        let mut pkg = Package::new("escape_test".to_string());
        pkg.description = Some("Description with \"quotes\"".to_string());
        let result = pkg.to_package_py();
        assert!(result.contains("Description with \\\"quotes\\\""));
    }

    // ── Phase N: from_path() and root() tests ─────────────────────────────

    #[test]
    fn test_from_path_with_package_py() {
        use std::fs::File;
        use std::io::Write;
        use tempfile::TempDir;

        let tmp = TempDir::new().unwrap();
        let pkg_path = tmp.path().join("package.py");
        let mut file = File::create(&pkg_path).unwrap();
        writeln!(file, "name = 'mypackage'").unwrap();
        writeln!(file, "version = '1.0.0'").unwrap();
        file.flush().unwrap();

        let pkg = Package::from_path(pkg_path.to_str().unwrap()).unwrap();
        assert_eq!(pkg.name, "mypackage");
        assert_eq!(pkg.version.as_ref().unwrap().as_str(), "1.0.0");
        assert_eq!(pkg.filepath, Some(pkg_path.to_string_lossy().to_string()));
        assert_eq!(pkg.is_dev_package, Some(true));
    }

    #[test]
    fn test_from_path_with_directory() {
        use std::fs::File;
        use std::io::Write;
        use tempfile::TempDir;

        let tmp = TempDir::new().unwrap();
        let pkg_path = tmp.path().join("package.py");
        let mut file = File::create(&pkg_path).unwrap();
        writeln!(file, "name = 'dirpkg'").unwrap();
        writeln!(file, "version = '2.0.0'").unwrap();
        file.flush().unwrap();

        // Pass directory path
        let pkg = Package::from_path(tmp.path().to_str().unwrap()).unwrap();
        assert_eq!(pkg.name, "dirpkg");
        assert_eq!(pkg.filepath, Some(pkg_path.to_string_lossy().to_string()));
    }

    #[test]
    fn test_root() {
        use std::fs::File;
        use std::io::Write;
        use tempfile::TempDir;

        let tmp = TempDir::new().unwrap();
        let pkg_path = tmp.path().join("package.py");
        let mut file = File::create(&pkg_path).unwrap();
        writeln!(file, "name = 'rootpkg'").unwrap();
        file.flush().unwrap();

        let pkg = Package::from_path(pkg_path.to_str().unwrap()).unwrap();
        let root = pkg.root();
        assert_eq!(root, Some(tmp.path().to_string_lossy().to_string()));
    }

    #[test]
    fn test_from_path_no_package_file() {
        use tempfile::TempDir;
        let tmp = TempDir::new().unwrap();
        let result = Package::from_path(tmp.path().to_str().unwrap());
        assert!(result.is_err());
    }
}