sublime_pkg_tools 0.0.27

Package and version management toolkit for Node.js projects with changeset support
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
//! Tests for automatic changeset creation and integration with upgrade application.

#![allow(clippy::expect_used)]
#![allow(clippy::panic)]

use super::applier::{apply_with_changeset, extract_affected_packages};
use super::creator::create_changeset_for_upgrades;
use crate::changeset::{ChangesetManager, FileBasedChangesetStorage};
use crate::config::UpgradeConfig;
use crate::error::UpgradeError;
use crate::types::{DependencyType, VersionBump};
use crate::upgrade::UpgradeSelection;
use crate::upgrade::application::result::UpgradeResult as UpgradeResultType;
use crate::upgrade::application::result::{AppliedUpgrade, ApplySummary};
use crate::upgrade::detection::{DependencyUpgrade, PackageUpgrades, VersionInfo};
use crate::upgrade::registry::UpgradeType;
use chrono::Utc;
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use sublime_git_tools::Repo;
use sublime_standard_tools::filesystem::FileSystemManager;
use tempfile::TempDir;

// ============================================================================
// Test Helpers
// ============================================================================

async fn setup_test_repo() -> (TempDir, PathBuf, Repo) {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let repo_path = temp_dir.path().to_path_buf();
    let repo_path_str = repo_path.to_str().expect("Invalid path");

    // Initialize git repo
    let repo = Repo::create(repo_path_str).expect("Failed to create git repo");

    // Configure git
    repo.config("user.name", "Test User").expect("Failed to set git config");
    repo.config("user.email", "test@example.com").expect("Failed to set git config");

    // Create initial commit
    std::fs::write(repo_path.join("README.md"), "# Test\n").expect("Failed to write file");
    repo.add("README.md").expect("Failed to add file");
    repo.commit("Initial commit").expect("Failed to commit");

    (temp_dir, repo_path, repo)
}

async fn setup_test_workspace() -> (TempDir, PathBuf, Repo) {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let workspace_root = temp_dir.path().to_path_buf();
    let workspace_str = workspace_root.to_str().expect("Invalid path");

    // Initialize git repo
    let repo = Repo::create(workspace_str).expect("Failed to create git repo");
    repo.config("user.name", "Test User").expect("Failed to set git config");
    repo.config("user.email", "test@example.com").expect("Failed to set git config");

    // Create initial commit
    std::fs::write(workspace_root.join("README.md"), "# Test\n").expect("Failed to write file");
    repo.add("README.md").expect("Failed to add file");
    repo.commit("Initial commit").expect("Failed to commit");

    // Create a package
    let package_dir = workspace_root.join("packages").join("core");
    std::fs::create_dir_all(&package_dir).expect("Failed to create package dir");

    let package_json = serde_json::json!({
        "name": "@myorg/core",
        "version": "1.0.0",
        "dependencies": {
            "lodash": "^4.17.20"
        }
    });
    std::fs::write(
        package_dir.join("package.json"),
        serde_json::to_string_pretty(&package_json).expect("Failed to serialize"),
    )
    .expect("Failed to write package.json");

    (temp_dir, workspace_root, repo)
}

async fn setup_changeset_manager(
    workspace_root: &PathBuf,
) -> ChangesetManager<FileBasedChangesetStorage<FileSystemManager>> {
    let fs = FileSystemManager::new();
    let config = crate::config::PackageToolsConfig::default();
    let repo_path_str = workspace_root.to_str().expect("Invalid path");
    let repo = Repo::open(repo_path_str).ok();

    let storage = FileBasedChangesetStorage::new(
        workspace_root.clone(),
        config.changeset.path.clone(),
        config.changeset.history_path.clone(),
        fs,
    );
    ChangesetManager::with_storage(storage, workspace_root, repo, config)
}

fn create_test_upgrades(workspace_root: &Path) -> Vec<PackageUpgrades> {
    vec![PackageUpgrades {
        package_name: "@myorg/core".to_string(),
        package_path: workspace_root.join("packages").join("core"),
        current_version: Some("1.0.0".to_string()),
        upgrades: vec![DependencyUpgrade {
            name: "lodash".to_string(),
            dependency_type: DependencyType::Regular,
            current_version: "4.17.20".to_string(),
            latest_version: "4.17.21".to_string(),
            upgrade_type: UpgradeType::Patch,
            registry_url: "https://registry.npmjs.org".to_string(),
            version_info: VersionInfo {
                available_versions: vec!["4.17.20".to_string(), "4.17.21".to_string()],
                latest_stable: "4.17.21".to_string(),
                latest_prerelease: None,
                deprecated: None,
                published_at: Some(Utc::now()),
            },
        }],
    }]
}

// ============================================================================
// Creator Tests
// ============================================================================

#[tokio::test]
async fn test_create_new_changeset() {
    let (_temp, repo_path, repo) = setup_test_repo().await;

    // Create a feature branch
    repo.create_branch("feature/upgrade-deps").expect("Failed to create branch");
    repo.checkout("feature/upgrade-deps").expect("Failed to checkout branch");

    let manager = setup_changeset_manager(&repo_path).await;

    let mut packages = HashSet::new();
    packages.insert("@myorg/core".to_string());
    packages.insert("@myorg/utils".to_string());

    // Create changeset
    let result = create_changeset_for_upgrades(&manager, packages, &repo_path, "patch").await;

    assert!(result.is_ok());
    let changeset_id = result.expect("Failed to create changeset");
    assert!(changeset_id.is_some());
    assert_eq!(changeset_id.expect("No changeset ID"), "feature/upgrade-deps");

    // Verify changeset was created
    let changeset = manager.load("feature/upgrade-deps").await.expect("Failed to load");
    assert_eq!(changeset.branch, "feature/upgrade-deps");
    assert_eq!(changeset.bump, VersionBump::Patch);
    assert_eq!(changeset.packages.len(), 2);
    assert!(changeset.packages.contains(&"@myorg/core".to_string()));
    assert!(changeset.packages.contains(&"@myorg/utils".to_string()));
}

#[tokio::test]
async fn test_update_existing_changeset() {
    let (_temp, repo_path, repo) = setup_test_repo().await;

    // Create a feature branch
    repo.create_branch("feature/upgrade-deps").expect("Failed to create branch");
    repo.checkout("feature/upgrade-deps").expect("Failed to checkout branch");

    let manager = setup_changeset_manager(&repo_path).await;

    // Create initial changeset
    let mut packages1 = HashSet::new();
    packages1.insert("@myorg/core".to_string());

    create_changeset_for_upgrades(&manager, packages1, &repo_path, "patch")
        .await
        .expect("Failed to create changeset");

    // Update with more packages
    let mut packages2 = HashSet::new();
    packages2.insert("@myorg/utils".to_string());
    packages2.insert("@myorg/cli".to_string());

    let result = create_changeset_for_upgrades(&manager, packages2, &repo_path, "patch").await;

    assert!(result.is_ok());

    // Verify changeset was updated
    let changeset = manager.load("feature/upgrade-deps").await.expect("Failed to load");
    assert_eq!(changeset.packages.len(), 3);
    assert!(changeset.packages.contains(&"@myorg/core".to_string()));
    assert!(changeset.packages.contains(&"@myorg/utils".to_string()));
    assert!(changeset.packages.contains(&"@myorg/cli".to_string()));
}

#[tokio::test]
async fn test_no_duplicate_packages() {
    let (_temp, repo_path, repo) = setup_test_repo().await;

    // Create a feature branch
    repo.create_branch("feature/upgrade-deps").expect("Failed to create branch");
    repo.checkout("feature/upgrade-deps").expect("Failed to checkout branch");

    let manager = setup_changeset_manager(&repo_path).await;

    // Create initial changeset
    let mut packages1 = HashSet::new();
    packages1.insert("@myorg/core".to_string());

    create_changeset_for_upgrades(&manager, packages1, &repo_path, "patch")
        .await
        .expect("Failed to create changeset");

    // Update with overlapping packages
    let mut packages2 = HashSet::new();
    packages2.insert("@myorg/core".to_string()); // Duplicate
    packages2.insert("@myorg/utils".to_string());

    create_changeset_for_upgrades(&manager, packages2, &repo_path, "patch")
        .await
        .expect("Failed to update changeset");

    // Verify no duplicates
    let changeset = manager.load("feature/upgrade-deps").await.expect("Failed to load");
    assert_eq!(changeset.packages.len(), 2);
    assert!(changeset.packages.contains(&"@myorg/core".to_string()));
    assert!(changeset.packages.contains(&"@myorg/utils".to_string()));
}

#[tokio::test]
async fn test_empty_packages() {
    let (_temp, repo_path, _repo) = setup_test_repo().await;
    let manager = setup_changeset_manager(&repo_path).await;

    let packages = HashSet::new();

    // Should return None for empty packages
    let result = create_changeset_for_upgrades(&manager, packages, &repo_path, "patch").await;

    assert!(result.is_ok());
    assert!(result.expect("Failed").is_none());
}

#[tokio::test]
async fn test_invalid_bump_type() {
    let (_temp, repo_path, repo) = setup_test_repo().await;

    // Create a feature branch
    repo.create_branch("feature/upgrade-deps").expect("Failed to create branch");
    repo.checkout("feature/upgrade-deps").expect("Failed to checkout branch");

    let manager = setup_changeset_manager(&repo_path).await;

    let mut packages = HashSet::new();
    packages.insert("@myorg/core".to_string());

    // Should fail with invalid bump type
    let result = create_changeset_for_upgrades(&manager, packages, &repo_path, "invalid").await;

    assert!(result.is_err());
    match result {
        Err(UpgradeError::ChangesetCreationFailed { reason }) => {
            assert!(reason.contains("Invalid bump type"));
        }
        _ => panic!("Expected ChangesetCreation error"),
    }
}

#[tokio::test]
async fn test_different_bump_types() {
    let (_temp, repo_path, repo) = setup_test_repo().await;
    let manager = setup_changeset_manager(&repo_path).await;

    // Test patch
    repo.create_branch("feature/patch").expect("Failed to create branch");
    repo.checkout("feature/patch").expect("Failed to checkout branch");

    let mut packages = HashSet::new();
    packages.insert("@myorg/core".to_string());

    create_changeset_for_upgrades(&manager, packages.clone(), &repo_path, "patch")
        .await
        .expect("Failed to create changeset");

    let changeset = manager.load("feature/patch").await.expect("Failed to load");
    assert_eq!(changeset.bump, VersionBump::Patch);

    // Test minor
    repo.checkout("main").expect("Failed to checkout main");
    repo.create_branch("feature/minor").expect("Failed to create branch");
    repo.checkout("feature/minor").expect("Failed to checkout branch");

    create_changeset_for_upgrades(&manager, packages.clone(), &repo_path, "minor")
        .await
        .expect("Failed to create changeset");

    let changeset = manager.load("feature/minor").await.expect("Failed to load");
    assert_eq!(changeset.bump, VersionBump::Minor);

    // Test major
    repo.checkout("main").expect("Failed to checkout main");
    repo.create_branch("feature/major").expect("Failed to create branch");
    repo.checkout("feature/major").expect("Failed to checkout branch");

    create_changeset_for_upgrades(&manager, packages, &repo_path, "major")
        .await
        .expect("Failed to create changeset");

    let changeset = manager.load("feature/major").await.expect("Failed to load");
    assert_eq!(changeset.bump, VersionBump::Major);
}

#[tokio::test]
async fn test_packages_sorted() {
    let (_temp, repo_path, repo) = setup_test_repo().await;

    // Create a feature branch
    repo.create_branch("feature/upgrade-deps").expect("Failed to create branch");
    repo.checkout("feature/upgrade-deps").expect("Failed to checkout branch");

    let manager = setup_changeset_manager(&repo_path).await;

    // Create with packages in random order
    let mut packages = HashSet::new();
    packages.insert("zebra".to_string());
    packages.insert("apple".to_string());
    packages.insert("mango".to_string());

    create_changeset_for_upgrades(&manager, packages, &repo_path, "patch")
        .await
        .expect("Failed to create changeset");

    // Verify packages are sorted
    let changeset = manager.load("feature/upgrade-deps").await.expect("Failed to load");
    let sorted: Vec<String> = changeset.packages.clone();
    let mut expected = sorted.clone();
    expected.sort();
    assert_eq!(sorted, expected);
}

// ============================================================================
// Applier Tests
// ============================================================================

#[tokio::test]
async fn test_apply_with_changeset_enabled() {
    let (_temp, workspace_root, repo) = setup_test_workspace().await;

    // Create feature branch
    repo.create_branch("feature/upgrade-deps").expect("Failed to create branch");
    repo.checkout("feature/upgrade-deps").expect("Failed to checkout");

    let manager = setup_changeset_manager(&workspace_root).await;
    let fs = FileSystemManager::new();
    let config = UpgradeConfig::default();
    assert!(config.auto_changeset); // Should be enabled by default

    let upgrades = create_test_upgrades(&workspace_root);
    let selection = UpgradeSelection::all();

    let result = apply_with_changeset(
        upgrades,
        selection,
        false,
        &workspace_root,
        &config,
        Some(&manager),
        &fs,
    )
    .await
    .expect("Failed to apply with changeset");

    // Verify upgrades were applied
    assert_eq!(result.applied.len(), 1);
    assert!(!result.dry_run);

    // Verify changeset was created
    assert!(result.changeset_id.is_some());
    assert_eq!(result.changeset_id.expect("No changeset ID"), "feature/upgrade-deps");

    // Verify changeset contents
    let changeset = manager.load("feature/upgrade-deps").await.expect("Failed to load changeset");
    assert_eq!(changeset.branch, "feature/upgrade-deps");
    assert_eq!(changeset.bump, VersionBump::Patch);
    assert!(changeset.packages.contains(&"@myorg/core".to_string()));
}

#[tokio::test]
async fn test_apply_with_changeset_disabled() {
    let (_temp, workspace_root, repo) = setup_test_workspace().await;

    // Create feature branch
    repo.create_branch("feature/upgrade-deps").expect("Failed to create branch");
    repo.checkout("feature/upgrade-deps").expect("Failed to checkout");

    let manager = setup_changeset_manager(&workspace_root).await;
    let fs = FileSystemManager::new();
    let config = UpgradeConfig { auto_changeset: false, ..UpgradeConfig::default() };

    let upgrades = create_test_upgrades(&workspace_root);
    let selection = UpgradeSelection::all();

    let result = apply_with_changeset(
        upgrades,
        selection,
        false,
        &workspace_root,
        &config,
        Some(&manager),
        &fs,
    )
    .await
    .expect("Failed to apply with changeset");

    // Verify upgrades were applied
    assert_eq!(result.applied.len(), 1);

    // Verify changeset was NOT created
    assert!(result.changeset_id.is_none());
}

#[tokio::test]
async fn test_apply_with_changeset_dry_run() {
    let (_temp, workspace_root, repo) = setup_test_workspace().await;

    // Create feature branch
    repo.create_branch("feature/upgrade-deps").expect("Failed to create branch");
    repo.checkout("feature/upgrade-deps").expect("Failed to checkout");

    let manager = setup_changeset_manager(&workspace_root).await;
    let fs = FileSystemManager::new();
    let config = UpgradeConfig::default();

    let upgrades = create_test_upgrades(&workspace_root);
    let selection = UpgradeSelection::all();

    let result = apply_with_changeset(
        upgrades,
        selection,
        true, // Dry run
        &workspace_root,
        &config,
        Some(&manager),
        &fs,
    )
    .await
    .expect("Failed to apply with changeset");

    // Verify this was a dry run
    assert!(result.dry_run);

    // Verify changeset was NOT created (dry run)
    assert!(result.changeset_id.is_none());
}

#[tokio::test]
async fn test_apply_with_changeset_no_manager() {
    let (_temp, workspace_root, _repo) = setup_test_workspace().await;

    let fs = FileSystemManager::new();
    let config = UpgradeConfig::default();

    let upgrades = create_test_upgrades(&workspace_root);
    let selection = UpgradeSelection::all();

    // No manager provided
    let result = apply_with_changeset::<_, FileBasedChangesetStorage<FileSystemManager>>(
        upgrades,
        selection,
        false,
        &workspace_root,
        &config,
        None, // No manager
        &fs,
    )
    .await
    .expect("Failed to apply with changeset");

    // Verify upgrades were applied
    assert_eq!(result.applied.len(), 1);

    // Verify changeset was NOT created (no manager)
    assert!(result.changeset_id.is_none());
}

#[tokio::test]
async fn test_extract_affected_packages() {
    let workspace_root = PathBuf::from("/workspace");
    let result = UpgradeResultType::applied(
        vec![
            AppliedUpgrade {
                package_path: workspace_root.join("packages").join("core"),
                dependency_name: "lodash".to_string(),
                dependency_type: DependencyType::Regular,
                old_version: "4.17.20".to_string(),
                new_version: "4.17.21".to_string(),
                upgrade_type: UpgradeType::Patch,
            },
            AppliedUpgrade {
                package_path: workspace_root.join("packages").join("core"),
                dependency_name: "react".to_string(),
                dependency_type: DependencyType::Regular,
                old_version: "17.0.0".to_string(),
                new_version: "18.0.0".to_string(),
                upgrade_type: UpgradeType::Major,
            },
        ],
        vec![],
        None,
        None,
        ApplySummary::new(),
    );

    let packages = extract_affected_packages(&result);

    // Should have 1 unique package
    assert_eq!(packages.len(), 1);
    assert!(packages.contains("core"));
}

#[tokio::test]
async fn test_different_changeset_bump_types() {
    let (_temp, workspace_root, repo) = setup_test_workspace().await;

    // Create feature branch
    repo.create_branch("feature/minor-upgrade").expect("Failed to create branch");
    repo.checkout("feature/minor-upgrade").expect("Failed to checkout");

    let manager = setup_changeset_manager(&workspace_root).await;
    let fs = FileSystemManager::new();
    let config = UpgradeConfig { changeset_bump: "minor".to_string(), ..UpgradeConfig::default() };

    let upgrades = create_test_upgrades(&workspace_root);
    let selection = UpgradeSelection::all();

    let _result = apply_with_changeset(
        upgrades,
        selection,
        false,
        &workspace_root,
        &config,
        Some(&manager),
        &fs,
    )
    .await
    .expect("Failed to apply with changeset");

    // Verify changeset was created with minor bump
    let changeset = manager.load("feature/minor-upgrade").await.expect("Failed to load changeset");
    assert_eq!(changeset.bump, VersionBump::Minor);
}