changepacks-core 0.2.20

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
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
use std::{collections::HashSet, path::Path};

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

/// Interface for monorepo workspace roots.
///
/// Extends Package behavior with workspace-specific operations like updating workspace
/// dependencies. Implemented by language-specific workspace types.
#[async_trait]
pub trait Workspace: std::fmt::Debug + Send + Sync {
    fn name(&self) -> Option<&str>;
    fn path(&self) -> &Path;
    fn relative_path(&self) -> &Path;
    fn version(&self) -> Option<&str>;
    /// # Errors
    /// Returns error if the version update operation fails.
    async fn update_version(&mut self, update_type: UpdateType) -> Result<()>;
    fn language(&self) -> Language;

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

    /// # Errors
    /// Returns error if the parent path cannot be determined.
    // Default implementation for check_changed
    ///
    /// Excluded from coverage: see `Package::check_changed` for the same
    /// tarpaulin attribution caveat on the multi-line `&&` condition.
    #[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 set_changed(&mut self, changed: bool);

    /// Set the workspace 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 workspace type
    fn default_publish_command(&self) -> String;

    /// Get the default dry-run publish command for this workspace type.
    ///
    /// Returns `None` for ecosystems whose default publish tool does not
    /// support a built-in dry-run mode. Users may still provide an override
    /// via `config.publish_dry_run`.
    fn default_dry_run_publish_command(&self) -> Option<String>;

    /// Publish the workspace using the configured command or default
    ///
    /// # Errors
    /// Returns error if the publish command fails to spawn or the workspace 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("Workspace 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 workspace
    /// 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("Workspace directory not found")?;
        Ok(Some(
            crate::publish::run_publish_command(&command, dir).await?,
        ))
    }

    /// Get the publish command for this workspace, 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 workspace, checking config
    /// first, then falling back to the workspace'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(not(tarpaulin_include))]
    async fn update_workspace_dependencies(&self, _packages: &[&dyn Package]) -> Result<()> {
        Ok(())
    }
}

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

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

    impl MockWorkspace {
        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 Workspace for MockWorkspace {
        fn name(&self) -> Option<&str> {
            self.name.as_deref()
        }
        fn path(&self) -> &Path {
            &self.path
        }
        fn relative_path(&self) -> &Path {
            &self.relative_path
        }
        fn version(&self) -> Option<&str> {
            self.version.as_deref()
        }
        async fn update_version(&mut self, _update_type: UpdateType) -> Result<()> {
            Ok(())
        }
        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 is_changed(&self) -> bool {
            self.changed
        }
        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 workspace =
            MockWorkspace::new(Some("test"), "/project/package.json", "package.json");
        workspace.changed = true;

        // Should return early if already changed
        workspace
            .check_changed(Path::new("/project/src/index.js"))
            .unwrap();
        assert!(workspace.is_changed());
    }

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

        // File in project directory should mark as changed
        workspace
            .check_changed(Path::new("/project/src/index.js"))
            .unwrap();
        assert!(workspace.is_changed());
    }

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

        // Files in .changepacks should be ignored
        workspace
            .check_changed(Path::new("/project/.changepacks/change.json"))
            .unwrap();
        assert!(!workspace.is_changed());
    }

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

        // Files in other directories should not mark as changed
        workspace
            .check_changed(Path::new("/other-project/src/index.js"))
            .unwrap();
        assert!(!workspace.is_changed());
    }

    #[test]
    fn test_get_publish_command_by_path() {
        let workspace = MockWorkspace::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!(workspace.get_publish_command(&config), "custom publish");
    }

    #[test]
    fn test_get_publish_command_by_language() {
        let workspace = MockWorkspace::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!(
            workspace.get_publish_command(&config),
            "npm publish --access public"
        );
    }

    #[test]
    fn test_get_publish_command_python() {
        let workspace =
            MockWorkspace::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!(workspace.get_publish_command(&config), "poetry publish");
    }

    #[test]
    fn test_get_publish_command_rust() {
        let workspace = MockWorkspace::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!(workspace.get_publish_command(&config), "cargo publish");
    }

    #[test]
    fn test_get_publish_command_dart() {
        let workspace = MockWorkspace::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!(workspace.get_publish_command(&config), "dart pub publish");
    }

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

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

    #[test]
    fn test_get_dry_run_publish_command_falls_back_to_workspace_default() {
        let workspace = MockWorkspace::new(Some("test"), "/project/package.json", "package.json")
            .with_language(Language::Node);
        let config = Config::default();

        // With no override, the trait method returns the workspace's own
        // `default_dry_run_publish_command()` (here, the MockWorkspace stub).
        assert_eq!(
            workspace.get_dry_run_publish_command(&config).as_deref(),
            Some("echo publish --dry-run")
        );
    }

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

        // Per-project override wins over the workspace's own default.
        assert_eq!(
            workspace.get_dry_run_publish_command(&config).as_deref(),
            Some("custom dry")
        );
    }

    #[test]
    fn test_get_dry_run_publish_command_override_by_language() {
        let workspace = MockWorkspace::new(Some("test"), "/project/package.json", "package.json")
            .with_language(Language::Node);
        let mut publish_dry_run = HashMap::new();
        publish_dry_run.insert(
            "node".to_string(),
            "npm publish --dry-run --tag next".to_string(),
        );
        let config = Config {
            publish_dry_run,
            ..Default::default()
        };

        // Per-language override wins over the workspace's own default.
        assert_eq!(
            workspace.get_dry_run_publish_command(&config).as_deref(),
            Some("npm publish --dry-run --tag next")
        );
    }

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

        // This will run "echo publish" which should succeed
        let output = workspace.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 workspace = MockWorkspace::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 = workspace.publish(&config).await.unwrap();
        assert!(!output.success);
    }

    #[tokio::test]
    async fn test_update_workspace_dependencies_default() {
        let workspace = MockWorkspace::new(Some("test"), "/project/package.json", "package.json");
        let packages: Vec<&dyn Package> = vec![];

        let result = workspace.update_workspace_dependencies(&packages).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_publish_no_parent_directory() {
        let workspace = MockWorkspace {
            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 = workspace.publish(&config).await;
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Workspace directory not found")
        );
    }

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