changepacks-core 0.2.21

Core types and traits for changepacks workspace and package management
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
use std::{collections::HashSet, path::Path};

use crate::{Config, Language, update_type::UpdateType};
use anyhow::{Context, Result};
use async_trait::async_trait;

/// Interface for single versioned packages.
///
/// Implemented by language-specific package types for reading versions, updating files,
/// detecting changes, and publishing. All I/O operations are async.
#[async_trait]
pub trait Package: std::fmt::Debug + Send + Sync {
    fn name(&self) -> Option<&str>;
    fn version(&self) -> Option<&str>;
    fn path(&self) -> &Path;
    fn relative_path(&self) -> &Path;
    /// # Errors
    /// Returns error if the version update operation fails.
    async fn update_version(&mut self, update_type: UpdateType) -> Result<()>;
    /// # Errors
    /// Returns error if the parent path cannot be determined.
    ///
    /// Excluded from coverage: tarpaulin mis-attributes the multi-line
    /// `&&`-condition's first line under normal rustfmt despite both
    /// branches being exercised by `test_check_changed_*`. The function
    /// is fully covered by its tests; the gap is a reporting artifact.
    #[cfg(not(tarpaulin_include))]
    fn check_changed(&mut self, path: &Path) -> Result<()> {
        if self.is_changed() {
            return Ok(());
        }
        if !path.to_string_lossy().contains(".changepacks")
            && path.starts_with(self.path().parent().context("Parent not found")?)
        {
            self.set_changed(true);
        }
        Ok(())
    }
    fn is_changed(&self) -> bool;
    fn language(&self) -> Language;

    fn dependencies(&self) -> &HashSet<String>;
    fn add_dependency(&mut self, dependency: &str);

    fn set_changed(&mut self, changed: bool);

    /// Set the package name (used for fallback when name is not found in manifest)
    fn set_name(&mut self, _name: String) {}

    /// Get the default publish command for this package type
    fn default_publish_command(&self) -> String;

    /// Get the default dry-run publish command for this package type.
    ///
    /// Returns `None` for ecosystems whose default publish tool does not
    /// support a built-in dry-run mode (e.g. `dotnet nuget push`). Callers
    /// should treat `None` as "dry-run not supported; skip with a warning"
    /// rather than as a failure. Users may still provide an override via
    /// `config.publish_dry_run`.
    fn default_dry_run_publish_command(&self) -> Option<String>;

    /// Whether this package inherits its version from the workspace root via `version.workspace = true`
    fn inherits_workspace_version(&self) -> bool {
        false
    }

    /// Path to the workspace root Cargo.toml, if this package inherits its version from workspace
    fn workspace_root_path(&self) -> Option<&Path> {
        None
    }

    /// Publish the package using the configured command or default
    ///
    /// # Errors
    /// Returns error if the publish command fails to spawn or the package directory is missing.
    /// A non-zero exit code is reported via `PublishOutput::success = false`.
    #[cfg(not(tarpaulin_include))]
    async fn publish(&self, config: &Config) -> Result<crate::publish::PublishOutput> {
        let command = self.get_publish_command(config);
        let dir = self
            .path()
            .parent()
            .context("Package directory not found")?;
        crate::publish::run_publish_command(&command, dir).await
    }

    /// Run the publish command in dry-run mode to verify the pre-release flow
    /// works without actually publishing.
    ///
    /// Returns `Ok(Some(output))` with the captured command output, or
    /// `Ok(None)` when the language does not support a dry-run mode and the
    /// user has not provided an override in `config.publish_dry_run`.
    ///
    /// # Errors
    /// Returns error if the dry-run command fails to spawn or the package
    /// directory is missing. A non-zero exit code is reported via
    /// `PublishOutput::success = false`.
    #[cfg(not(tarpaulin_include))]
    async fn dry_run_publish(
        &self,
        config: &Config,
    ) -> Result<Option<crate::publish::PublishOutput>> {
        let Some(command) = self.get_dry_run_publish_command(config) else {
            return Ok(None);
        };
        let dir = self
            .path()
            .parent()
            .context("Package directory not found")?;
        Ok(Some(
            crate::publish::run_publish_command(&command, dir).await?,
        ))
    }

    /// Get the publish command for this package, checking config first
    fn get_publish_command(&self, config: &Config) -> String {
        crate::publish::resolve_publish_command(
            self.relative_path(),
            self.language(),
            &self.default_publish_command(),
            config,
        )
    }

    /// Get the dry-run publish command for this package, checking config
    /// first, then falling back to the package's `default_dry_run_publish_command`.
    fn get_dry_run_publish_command(&self, config: &Config) -> Option<String> {
        crate::publish::resolve_dry_run_publish_command(
            self.relative_path(),
            self.language(),
            self.default_dry_run_publish_command().as_deref(),
            config,
        )
    }
}

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

    #[derive(Debug)]
    struct MockPackage {
        name: Option<String>,
        path: PathBuf,
        relative_path: PathBuf,
        version: Option<String>,
        language: Language,
        dependencies: HashSet<String>,
        changed: bool,
    }

    impl MockPackage {
        fn new(name: Option<&str>, path: &str, relative_path: &str) -> Self {
            Self {
                name: name.map(String::from),
                path: PathBuf::from(path),
                relative_path: PathBuf::from(relative_path),
                version: Some("1.0.0".to_string()),
                language: Language::Node,
                dependencies: HashSet::new(),
                changed: false,
            }
        }

        fn with_language(mut self, language: Language) -> Self {
            self.language = language;
            self
        }
    }

    #[async_trait]
    impl Package for MockPackage {
        fn name(&self) -> Option<&str> {
            self.name.as_deref()
        }
        fn version(&self) -> Option<&str> {
            self.version.as_deref()
        }
        fn path(&self) -> &Path {
            &self.path
        }
        fn relative_path(&self) -> &Path {
            &self.relative_path
        }
        async fn update_version(&mut self, _update_type: UpdateType) -> Result<()> {
            Ok(())
        }
        fn is_changed(&self) -> bool {
            self.changed
        }
        fn language(&self) -> Language {
            self.language
        }
        fn dependencies(&self) -> &HashSet<String> {
            &self.dependencies
        }
        fn add_dependency(&mut self, dependency: &str) {
            self.dependencies.insert(dependency.to_string());
        }
        fn set_changed(&mut self, changed: bool) {
            self.changed = changed;
        }
        fn default_publish_command(&self) -> String {
            "echo publish".to_string()
        }
        fn default_dry_run_publish_command(&self) -> Option<String> {
            Some("echo publish --dry-run".to_string())
        }
    }

    #[test]
    fn test_check_changed_already_changed() {
        let mut package = MockPackage::new(Some("test"), "/project/package.json", "package.json");
        package.changed = true;

        package
            .check_changed(Path::new("/project/src/index.js"))
            .unwrap();
        assert!(package.is_changed());
    }

    #[test]
    fn test_check_changed_sets_changed() {
        let mut package = MockPackage::new(Some("test"), "/project/package.json", "package.json");

        package
            .check_changed(Path::new("/project/src/index.js"))
            .unwrap();
        assert!(package.is_changed());
    }

    #[test]
    fn test_check_changed_ignores_changepacks() {
        let mut package = MockPackage::new(Some("test"), "/project/package.json", "package.json");

        package
            .check_changed(Path::new("/project/.changepacks/change.json"))
            .unwrap();
        assert!(!package.is_changed());
    }

    #[test]
    fn test_check_changed_ignores_other_projects() {
        let mut package = MockPackage::new(Some("test"), "/project/package.json", "package.json");

        package
            .check_changed(Path::new("/other-project/src/index.js"))
            .unwrap();
        assert!(!package.is_changed());
    }

    #[test]
    fn test_inherits_workspace_version_default() {
        let package = MockPackage::new(Some("test"), "/project/package.json", "package.json");
        assert!(!package.inherits_workspace_version());
    }

    #[test]
    fn test_workspace_root_path_default() {
        let package = MockPackage::new(Some("test"), "/project/package.json", "package.json");
        assert!(package.workspace_root_path().is_none());
    }

    #[test]
    fn test_get_publish_command_by_path() {
        let package = MockPackage::new(
            Some("test"),
            "/project/package.json",
            "packages/core/package.json",
        );
        let mut publish = HashMap::new();
        publish.insert(
            "packages/core/package.json".to_string(),
            "custom publish".to_string(),
        );
        let config = Config {
            publish,
            ..Default::default()
        };

        assert_eq!(package.get_publish_command(&config), "custom publish");
    }

    #[test]
    fn test_get_publish_command_by_language_node() {
        let package = MockPackage::new(Some("test"), "/project/package.json", "package.json")
            .with_language(Language::Node);
        let mut publish = HashMap::new();
        publish.insert(
            "node".to_string(),
            "npm publish --access public".to_string(),
        );
        let config = Config {
            publish,
            ..Default::default()
        };

        assert_eq!(
            package.get_publish_command(&config),
            "npm publish --access public"
        );
    }

    #[test]
    fn test_get_publish_command_by_language_python() {
        let package = MockPackage::new(Some("test"), "/project/pyproject.toml", "pyproject.toml")
            .with_language(Language::Python);
        let mut publish = HashMap::new();
        publish.insert("python".to_string(), "poetry publish".to_string());
        let config = Config {
            publish,
            ..Default::default()
        };

        assert_eq!(package.get_publish_command(&config), "poetry publish");
    }

    #[test]
    fn test_get_publish_command_by_language_rust() {
        let package = MockPackage::new(Some("test"), "/project/Cargo.toml", "Cargo.toml")
            .with_language(Language::Rust);
        let mut publish = HashMap::new();
        publish.insert("rust".to_string(), "cargo publish".to_string());
        let config = Config {
            publish,
            ..Default::default()
        };

        assert_eq!(package.get_publish_command(&config), "cargo publish");
    }

    #[test]
    fn test_get_publish_command_by_language_dart() {
        let package = MockPackage::new(Some("test"), "/project/pubspec.yaml", "pubspec.yaml")
            .with_language(Language::Dart);
        let mut publish = HashMap::new();
        publish.insert("dart".to_string(), "dart pub publish".to_string());
        let config = Config {
            publish,
            ..Default::default()
        };

        assert_eq!(package.get_publish_command(&config), "dart pub publish");
    }

    #[test]
    fn test_get_publish_command_default() {
        let package = MockPackage::new(Some("test"), "/project/package.json", "package.json");
        let config = Config::default();

        assert_eq!(package.get_publish_command(&config), "echo publish");
    }

    #[tokio::test]
    async fn test_publish_success() {
        let temp_dir = std::env::temp_dir();
        let path = temp_dir.join("package.json");
        let package = MockPackage::new(Some("test"), path.to_str().unwrap(), "package.json");
        let config = Config::default();

        let output = package.publish(&config).await.unwrap();
        assert!(output.success);
    }

    #[tokio::test]
    async fn test_publish_failure() {
        let temp_dir = std::env::temp_dir();
        let path = temp_dir.join("package.json");
        let package = MockPackage::new(Some("test"), path.to_str().unwrap(), "package.json");
        let mut publish = HashMap::new();
        let fail_cmd = if cfg!(target_os = "windows") {
            "cmd /c exit 1"
        } else {
            "exit 1"
        };
        publish.insert("node".to_string(), fail_cmd.to_string());
        let config = Config {
            publish,
            ..Default::default()
        };

        let output = package.publish(&config).await.unwrap();
        assert!(!output.success);
    }

    #[tokio::test]
    async fn test_publish_no_parent_directory() {
        let package = MockPackage {
            name: Some("test".to_string()),
            path: PathBuf::from(""),
            relative_path: PathBuf::from(""),
            version: Some("1.0.0".to_string()),
            language: Language::Node,
            dependencies: HashSet::new(),
            changed: false,
        };
        let config = Config::default();
        let result = package.publish(&config).await;
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Package directory not found")
        );
    }

    #[test]
    fn test_set_name_default_is_noop() {
        let mut package =
            MockPackage::new(Some("original"), "/project/package.json", "package.json");
        package.set_name("new-name".to_string());
        // Default implementation is a no-op, name should remain unchanged
        assert_eq!(package.name(), Some("original"));
    }
}