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
//! Changes report data structures for aggregating package changes.
//!
//! **What**: Provides types for representing a complete analysis report of changes across
//! packages, including analysis metadata, affected packages, and summary statistics.
//!
//! **How**: Aggregates `PackageChanges` from multiple packages with analysis context
//! (mode, timestamp, git references) and provides filtering and querying capabilities.
//!
//! **Why**: To provide a comprehensive, queryable view of all changes in a workspace,
//! supporting version bumping, changelog generation, and release decision-making.
//!
//! # Examples
//!
//! ## Creating a changes report
//!
//! ```rust,ignore
//! use sublime_pkg_tools::changes::{ChangesReport, AnalysisMode, PackageChanges};
//! use chrono::Utc;
//!
//! let report = ChangesReport {
//!     analyzed_at: Utc::now(),
//!     analysis_mode: AnalysisMode::WorkingDirectory,
//!     base_ref: None,
//!     head_ref: None,
//!     packages: vec![],
//!     summary: ChangesSummary::new(),
//!     is_monorepo: false,
//! };
//!
//! assert_eq!(report.analysis_mode, AnalysisMode::WorkingDirectory);
//! ```
//!
//! ## Filtering packages
//!
//! ```rust,ignore
//! # use sublime_pkg_tools::changes::ChangesReport;
//! let packages_with_changes = report.packages_with_changes();
//! let packages_without_changes = report.packages_without_changes();
//! ```

use crate::changes::{ChangesSummary, FileChangeType, PackageChanges};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

/// Analysis mode indicating how changes were detected.
///
/// Different analysis modes provide different levels of information about changes.
/// For example, working directory analysis doesn't include commit information,
/// while commit range analysis includes full commit history.
///
/// # Examples
///
/// ```rust
/// use sublime_pkg_tools::changes::AnalysisMode;
///
/// let mode = AnalysisMode::WorkingDirectory;
/// assert!(mode.is_working_directory());
/// assert!(!mode.is_commit_range());
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AnalysisMode {
    /// Uncommitted changes (working tree + staging area).
    ///
    /// Analyzes files with changes that haven't been committed yet.
    /// This mode doesn't include commit information.
    WorkingDirectory,

    /// Changes between two commits or branches.
    ///
    /// Analyzes changes by comparing two git references (commits, tags, branches).
    /// Includes full commit history for the range.
    CommitRange,

    /// Changes in a single commit.
    ///
    /// Analyzes changes introduced by a specific commit.
    SingleCommit,

    /// Changes from a list of commits.
    ///
    /// Analyzes changes from a specific set of commits, typically from a changeset.
    CommitList,
}

impl AnalysisMode {
    /// Returns whether this mode analyzes the working directory.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sublime_pkg_tools::changes::AnalysisMode;
    ///
    /// assert!(AnalysisMode::WorkingDirectory.is_working_directory());
    /// assert!(!AnalysisMode::CommitRange.is_working_directory());
    /// ```
    #[must_use]
    pub fn is_working_directory(&self) -> bool {
        matches!(self, Self::WorkingDirectory)
    }

    /// Returns whether this mode analyzes a commit range.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sublime_pkg_tools::changes::AnalysisMode;
    ///
    /// assert!(AnalysisMode::CommitRange.is_commit_range());
    /// assert!(!AnalysisMode::WorkingDirectory.is_commit_range());
    /// ```
    #[must_use]
    pub fn is_commit_range(&self) -> bool {
        matches!(self, Self::CommitRange)
    }

    /// Returns whether this mode analyzes a single commit.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sublime_pkg_tools::changes::AnalysisMode;
    ///
    /// assert!(AnalysisMode::SingleCommit.is_single_commit());
    /// assert!(!AnalysisMode::CommitRange.is_single_commit());
    /// ```
    #[must_use]
    pub fn is_single_commit(&self) -> bool {
        matches!(self, Self::SingleCommit)
    }

    /// Returns whether this mode analyzes a commit list.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sublime_pkg_tools::changes::AnalysisMode;
    ///
    /// assert!(AnalysisMode::CommitList.is_commit_list());
    /// assert!(!AnalysisMode::WorkingDirectory.is_commit_list());
    /// ```
    #[must_use]
    pub fn is_commit_list(&self) -> bool {
        matches!(self, Self::CommitList)
    }

    /// Returns whether this mode includes commit information.
    ///
    /// Working directory analysis doesn't include commits, while all other modes do.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sublime_pkg_tools::changes::AnalysisMode;
    ///
    /// assert!(!AnalysisMode::WorkingDirectory.has_commits());
    /// assert!(AnalysisMode::CommitRange.has_commits());
    /// assert!(AnalysisMode::SingleCommit.has_commits());
    /// ```
    #[must_use]
    pub fn has_commits(&self) -> bool {
        !matches!(self, Self::WorkingDirectory)
    }
}

/// Complete report of changes across packages.
///
/// Contains comprehensive information about all changes in a workspace, including
/// which packages were affected, what files changed, commit history, and statistics.
///
/// # Examples
///
/// ```rust,ignore
/// use sublime_pkg_tools::changes::{ChangesReport, AnalysisMode};
/// use chrono::Utc;
///
/// let report = ChangesReport::new(AnalysisMode::WorkingDirectory, false);
/// assert_eq!(report.analysis_mode, AnalysisMode::WorkingDirectory);
/// assert!(!report.is_monorepo);
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChangesReport {
    /// Timestamp when the analysis was performed.
    pub analyzed_at: DateTime<Utc>,

    /// Mode of analysis (working directory, commit range, etc.).
    pub analysis_mode: AnalysisMode,

    /// Base git reference for commit range analysis.
    ///
    /// This is `None` for working directory analysis.
    /// For commit range analysis, this is typically "main" or a commit hash.
    pub base_ref: Option<String>,

    /// Head git reference for commit range analysis.
    ///
    /// This is `None` for working directory analysis.
    /// For commit range analysis, this is typically "HEAD" or a branch name.
    pub head_ref: Option<String>,

    /// All packages analyzed, including those with and without changes.
    pub packages: Vec<PackageChanges>,

    /// Summary statistics across all packages.
    pub summary: ChangesSummary,

    /// Whether this workspace is a monorepo.
    pub is_monorepo: bool,
}

impl ChangesReport {
    /// Creates a new `ChangesReport` with default values.
    ///
    /// # Arguments
    ///
    /// * `analysis_mode` - The mode of analysis
    /// * `is_monorepo` - Whether this is a monorepo workspace
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sublime_pkg_tools::changes::{ChangesReport, AnalysisMode};
    ///
    /// let report = ChangesReport::new(AnalysisMode::WorkingDirectory, true);
    /// assert_eq!(report.analysis_mode, AnalysisMode::WorkingDirectory);
    /// assert!(report.is_monorepo);
    /// assert!(report.packages.is_empty());
    /// ```
    #[must_use]
    pub fn new(analysis_mode: AnalysisMode, is_monorepo: bool) -> Self {
        Self {
            analyzed_at: Utc::now(),
            analysis_mode,
            base_ref: None,
            head_ref: None,
            packages: Vec::new(),
            summary: ChangesSummary::new(),
            is_monorepo,
        }
    }

    /// Creates a new `ChangesReport` for commit range analysis.
    ///
    /// # Arguments
    ///
    /// * `base_ref` - Base git reference
    /// * `head_ref` - Head git reference
    /// * `is_monorepo` - Whether this is a monorepo workspace
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sublime_pkg_tools::changes::ChangesReport;
    ///
    /// let report = ChangesReport::new_for_range("main", "HEAD", false);
    /// assert_eq!(report.base_ref, Some("main".to_string()));
    /// assert_eq!(report.head_ref, Some("HEAD".to_string()));
    /// ```
    #[must_use]
    pub fn new_for_range(base_ref: &str, head_ref: &str, is_monorepo: bool) -> Self {
        Self {
            analyzed_at: Utc::now(),
            analysis_mode: AnalysisMode::CommitRange,
            base_ref: Some(base_ref.to_string()),
            head_ref: Some(head_ref.to_string()),
            packages: Vec::new(),
            summary: ChangesSummary::new(),
            is_monorepo,
        }
    }

    /// Returns a reference to a specific package by name.
    ///
    /// # Arguments
    ///
    /// * `name` - Package name to search for
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// # use sublime_pkg_tools::changes::ChangesReport;
    /// let package = report.get_package("@myorg/core");
    /// ```
    #[must_use]
    pub fn get_package(&self, name: &str) -> Option<&PackageChanges> {
        self.packages.iter().find(|p| p.package_name() == name)
    }

    /// Returns all packages that have changes.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// # use sublime_pkg_tools::changes::ChangesReport;
    /// let packages = report.packages_with_changes();
    /// for package in packages {
    ///     println!("Package {} has changes", package.package_name());
    /// }
    /// ```
    #[must_use]
    pub fn packages_with_changes(&self) -> Vec<&PackageChanges> {
        self.packages.iter().filter(|p| p.has_changes).collect()
    }

    /// Returns all packages without changes.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// # use sublime_pkg_tools::changes::ChangesReport;
    /// let unchanged = report.packages_without_changes();
    /// ```
    #[must_use]
    pub fn packages_without_changes(&self) -> Vec<&PackageChanges> {
        self.packages.iter().filter(|p| !p.has_changes).collect()
    }

    /// Filters packages by file change type.
    ///
    /// Returns packages that have at least one file with the specified change type.
    ///
    /// # Arguments
    ///
    /// * `change_type` - The type of change to filter by
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// # use sublime_pkg_tools::changes::{ChangesReport, FileChangeType};
    /// let packages = report.filter_by_change_type(FileChangeType::Added);
    /// ```
    #[must_use]
    pub fn filter_by_change_type(&self, change_type: FileChangeType) -> Vec<&PackageChanges> {
        self.packages
            .iter()
            .filter(|p| p.files.iter().any(|f| f.change_type == change_type))
            .collect()
    }

    /// Returns packages where package.json was modified.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// # use sublime_pkg_tools::changes::ChangesReport;
    /// let packages = report.packages_with_package_json_changes();
    /// ```
    #[must_use]
    pub fn packages_with_package_json_changes(&self) -> Vec<&PackageChanges> {
        self.packages.iter().filter(|p| p.package_json_modified()).collect()
    }

    /// Returns whether any changes were detected.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sublime_pkg_tools::changes::{ChangesReport, AnalysisMode};
    ///
    /// let report = ChangesReport::new(AnalysisMode::WorkingDirectory, false);
    /// assert!(!report.has_changes());
    /// ```
    #[must_use]
    pub fn has_changes(&self) -> bool {
        self.summary.has_changes()
    }

    /// Returns the total number of files changed across all packages.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// # use sublime_pkg_tools::changes::ChangesReport;
    /// let count = report.total_files_changed();
    /// println!("Total files changed: {}", count);
    /// ```
    #[must_use]
    pub fn total_files_changed(&self) -> usize {
        self.summary.total_files_changed
    }

    /// Returns the total number of commits analyzed.
    ///
    /// This will be 0 for working directory analysis.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// # use sublime_pkg_tools::changes::ChangesReport;
    /// let count = report.total_commits();
    /// ```
    #[must_use]
    pub fn total_commits(&self) -> usize {
        self.summary.total_commits
    }

    /// Adds a package to the report.
    ///
    /// Updates the summary statistics automatically.
    ///
    /// # Arguments
    ///
    /// * `package` - The package changes to add
    pub fn add_package(&mut self, package: PackageChanges) {
        // Update summary
        self.summary.total_packages += 1;
        if package.has_changes {
            self.summary.packages_with_changes += 1;
        } else {
            self.summary.packages_without_changes += 1;
        }

        self.summary.total_files_changed += package.stats.files_changed;
        self.summary.total_lines_added += package.stats.lines_added;
        self.summary.total_lines_deleted += package.stats.lines_deleted;

        // Commits are counted uniquely across packages
        // For now, just add the package's commit count
        // (proper unique counting will be done in commit range analysis)
        self.summary.total_commits += package.stats.commits;

        self.packages.push(package);
    }

    /// Recalculates the summary statistics from current packages.
    ///
    /// This should be called after manually modifying packages.
    pub fn recalculate_summary(&mut self) {
        let mut summary = ChangesSummary::new();

        summary.total_packages = self.packages.len();

        for package in &self.packages {
            if package.has_changes {
                summary.packages_with_changes += 1;
            } else {
                summary.packages_without_changes += 1;
            }

            summary.total_files_changed += package.stats.files_changed;
            summary.total_lines_added += package.stats.lines_added;
            summary.total_lines_deleted += package.stats.lines_deleted;
            summary.total_commits += package.stats.commits;
        }

        self.summary = summary;
    }
}