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
//! Keep a Changelog formatter implementation.
//!
//! **What**: Implements the Keep a Changelog format specification for changelog generation.
//! This formatter converts internal changelog data structures into the standard format
//! defined at <https://keepachangelog.com>.
//!
//! **How**: Maps internal section types to Keep a Changelog sections (Added, Changed,
//! Deprecated, Removed, Fixed, Security) and formats entries according to the specification.
//! The formatter respects configuration settings for links, authors, and templates.
//!
//! **Why**: Keep a Changelog is a widely adopted standard that provides a consistent,
//! human-readable format for documenting changes. Following this standard makes it easier
//! for users to understand what has changed between versions.
//!
//! # Keep a Changelog Specification
//!
//! The format follows these principles:
//! - Changelogs are for humans, not machines
//! - There should be an entry for every single version
//! - The same types of changes should be grouped
//! - Versions and sections should be linkable
//! - The latest version comes first
//! - The release date of each version is displayed
//!
//! Standard sections (in order):
//! - **Added** for new features
//! - **Changed** for changes in existing functionality
//! - **Deprecated** for soon-to-be removed features
//! - **Removed** for now removed features
//! - **Fixed** for any bug fixes
//! - **Security** for security vulnerability fixes
//!
//! # Section Mapping
//!
//! Internal `SectionType` values are mapped to Keep a Changelog sections as follows:
//! - `Features` → Added
//! - `Fixes` → Fixed
//! - `Deprecations` → Deprecated
//! - `Performance` → Changed
//! - `Refactoring` → Changed
//! - `Documentation` → Changed
//! - `Build` → Changed
//! - `CI` → Changed
//! - `Tests` → Changed
//! - `Breaking` → Changed (with special notation)
//! - `Other` → Changed
//!
//! # Example Output
//!
//! ```markdown
//! ## [1.0.0] - 2024-01-15
//!
//! ### Added
//! - New feature X ([abc123](repo/commit/abc123))
//! - New feature Y ([def456](repo/commit/def456))
//!
//! ### Changed
//! - **BREAKING**: Updated API behavior ([ghi789](repo/commit/ghi789))
//! - Improved performance of Z ([jkl012](repo/commit/jkl012))
//!
//! ### Fixed
//! - Fixed bug in parser ([mno345](repo/commit/mno345)) ([#123](repo/issues/123))
//! ```

use crate::changelog::{Changelog, ChangelogEntry, ChangelogSection, SectionType};
use crate::config::ChangelogConfig;
use std::collections::HashMap;

/// Formatter for Keep a Changelog format.
///
/// This formatter converts `Changelog` structures into markdown following
/// the Keep a Changelog specification.
///
/// # Examples
///
/// ```rust,ignore
/// use sublime_pkg_tools::changelog::formatter::KeepAChangelogFormatter;
/// use sublime_pkg_tools::changelog::Changelog;
/// use sublime_pkg_tools::config::ChangelogConfig;
/// use chrono::Utc;
///
/// let config = ChangelogConfig::default();
/// let formatter = KeepAChangelogFormatter::new(&config);
///
/// let changelog = Changelog::new(Some("my-package"), "1.0.0", None, Utc::now());
/// let formatted = formatter.format(&changelog);
/// ```
#[derive(Debug)]
pub struct KeepAChangelogFormatter<'a> {
    /// Configuration for formatting options.
    config: &'a ChangelogConfig,
}

/// Keep a Changelog section type.
///
/// Represents the standard sections defined in the Keep a Changelog specification.
///
/// # Note on Unused Variants
///
/// The `Removed` and `Security` sections are part of the Keep a Changelog specification
/// but are not currently mapped from internal `SectionType` values. They are included
/// for completeness and future extensibility. When custom section support is added in
/// future stories, these sections will be available for use.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[allow(dead_code)]
pub(crate) enum KeepAChangelogSection {
    /// New features.
    Added,
    /// Changes in existing functionality.
    Changed,
    /// Soon-to-be removed features.
    Deprecated,
    /// Now removed features.
    Removed,
    /// Bug fixes.
    Fixed,
    /// Security vulnerability fixes.
    Security,
}

impl KeepAChangelogSection {
    /// Returns the section title.
    ///
    /// # Returns
    ///
    /// The standard Keep a Changelog section title.
    pub(crate) fn title(&self) -> &str {
        match self {
            KeepAChangelogSection::Added => "Added",
            KeepAChangelogSection::Changed => "Changed",
            KeepAChangelogSection::Deprecated => "Deprecated",
            KeepAChangelogSection::Removed => "Removed",
            KeepAChangelogSection::Fixed => "Fixed",
            KeepAChangelogSection::Security => "Security",
        }
    }

    /// Returns the section priority for ordering.
    ///
    /// Lower numbers appear first. This follows the Keep a Changelog
    /// standard section ordering.
    ///
    /// # Returns
    ///
    /// Priority value (0-5).
    pub(crate) fn priority(&self) -> u8 {
        match self {
            KeepAChangelogSection::Added => 0,
            KeepAChangelogSection::Changed => 1,
            KeepAChangelogSection::Deprecated => 2,
            KeepAChangelogSection::Removed => 3,
            KeepAChangelogSection::Fixed => 4,
            KeepAChangelogSection::Security => 5,
        }
    }
}

impl<'a> KeepAChangelogFormatter<'a> {
    /// Creates a new Keep a Changelog formatter.
    ///
    /// # Arguments
    ///
    /// * `config` - Configuration for formatting options
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use sublime_pkg_tools::changelog::formatter::KeepAChangelogFormatter;
    /// use sublime_pkg_tools::config::ChangelogConfig;
    ///
    /// let config = ChangelogConfig::default();
    /// let formatter = KeepAChangelogFormatter::new(&config);
    /// ```
    #[must_use]
    pub fn new(config: &'a ChangelogConfig) -> Self {
        Self { config }
    }

    /// Formats a changelog into Keep a Changelog format.
    ///
    /// # Arguments
    ///
    /// * `changelog` - The changelog to format
    ///
    /// # Returns
    ///
    /// A markdown string in Keep a Changelog format.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use sublime_pkg_tools::changelog::formatter::KeepAChangelogFormatter;
    /// use sublime_pkg_tools::changelog::Changelog;
    /// use sublime_pkg_tools::config::ChangelogConfig;
    /// use chrono::Utc;
    ///
    /// let config = ChangelogConfig::default();
    /// let formatter = KeepAChangelogFormatter::new(&config);
    /// let changelog = Changelog::new(Some("my-package"), "1.0.0", None, Utc::now());
    ///
    /// let formatted = formatter.format(&changelog);
    /// println!("{}", formatted);
    /// ```
    #[must_use]
    pub fn format(&self, changelog: &Changelog) -> String {
        let mut output = String::new();

        // Version header
        output.push_str(&self.format_version_header(changelog));
        output.push_str("\n\n");

        // Group sections by Keep a Changelog categories
        let grouped_sections = self.group_sections(&changelog.sections);

        // Format each Keep a Changelog section in priority order
        let mut sections: Vec<_> = grouped_sections.into_iter().collect();
        sections.sort_by_key(|(section, _)| section.priority());

        for (keep_section, entries) in sections {
            if !entries.is_empty() {
                output.push_str(&self.format_section(&keep_section, &entries));
                output.push('\n');
            }
        }

        output
    }

    /// Formats the version header according to Keep a Changelog format.
    ///
    /// # Arguments
    ///
    /// * `changelog` - The changelog to format the header for
    ///
    /// # Returns
    ///
    /// The formatted version header string.
    pub(crate) fn format_version_header(&self, changelog: &Changelog) -> String {
        let date_str = changelog.date.format("%Y-%m-%d").to_string();

        // Use template if provided, otherwise use Keep a Changelog standard format
        if self.config.template.version_header.contains("{version}")
            && self.config.template.version_header.contains("{date}")
        {
            self.config
                .template
                .version_header
                .replace("{version}", &changelog.version)
                .replace("{date}", &date_str)
        } else {
            // Standard Keep a Changelog format
            format!("## [{}] - {}", changelog.version, date_str)
        }
    }

    /// Groups internal sections into Keep a Changelog sections.
    ///
    /// # Arguments
    ///
    /// * `sections` - The internal changelog sections to group
    ///
    /// # Returns
    ///
    /// A map of Keep a Changelog sections to entries.
    pub(crate) fn group_sections<'b>(
        &self,
        sections: &'b [ChangelogSection],
    ) -> HashMap<KeepAChangelogSection, Vec<&'b ChangelogEntry>> {
        let mut grouped: HashMap<KeepAChangelogSection, Vec<&ChangelogEntry>> = HashMap::new();

        for section in sections {
            let keep_section = self.map_section_type(&section.section_type);

            for entry in &section.entries {
                grouped.entry(keep_section).or_default().push(entry);
            }
        }

        grouped
    }

    /// Maps internal `SectionType` to Keep a Changelog section.
    ///
    /// # Arguments
    ///
    /// * `section_type` - The internal section type
    ///
    /// # Returns
    ///
    /// The corresponding Keep a Changelog section.
    pub(crate) fn map_section_type(&self, section_type: &SectionType) -> KeepAChangelogSection {
        match section_type {
            SectionType::Features => KeepAChangelogSection::Added,
            SectionType::Fixes => KeepAChangelogSection::Fixed,
            SectionType::Deprecations => KeepAChangelogSection::Deprecated,
            SectionType::Breaking => KeepAChangelogSection::Changed,
            SectionType::Performance => KeepAChangelogSection::Changed,
            SectionType::Refactoring => KeepAChangelogSection::Changed,
            SectionType::Documentation => KeepAChangelogSection::Changed,
            SectionType::Build => KeepAChangelogSection::Changed,
            SectionType::CI => KeepAChangelogSection::Changed,
            SectionType::Tests => KeepAChangelogSection::Changed,
            SectionType::Other => KeepAChangelogSection::Changed,
        }
    }

    /// Formats a Keep a Changelog section with its entries.
    ///
    /// # Arguments
    ///
    /// * `section` - The Keep a Changelog section type
    /// * `entries` - The entries for this section
    ///
    /// # Returns
    ///
    /// The formatted section string.
    pub(crate) fn format_section(
        &self,
        section: &KeepAChangelogSection,
        entries: &[&ChangelogEntry],
    ) -> String {
        let mut output = String::new();

        // Section header
        output.push_str(&format!("### {}\n\n", section.title()));

        // Format each entry
        for entry in entries {
            output.push_str(&self.format_entry(entry));
            output.push('\n');
        }

        output
    }

    /// Formats a single changelog entry.
    ///
    /// # Arguments
    ///
    /// * `entry` - The entry to format
    ///
    /// # Returns
    ///
    /// The formatted entry string.
    pub(crate) fn format_entry(&self, entry: &ChangelogEntry) -> String {
        let mut output = String::from("- ");

        // Add breaking change marker if applicable
        if entry.breaking {
            output.push_str("**BREAKING**: ");
        }

        // Add description
        output.push_str(&entry.description);

        // Add commit link
        if self.config.include_commit_links {
            output.push(' ');
            if let Some(ref repo_url) = self.config.repository_url {
                let commit_link = self.format_commit_link(entry, repo_url);
                output.push_str(&commit_link);
            } else {
                output.push_str(&format!("({})", entry.short_hash));
            }
        }

        // Add issue links
        if self.config.include_issue_links && !entry.references.is_empty() {
            output.push(' ');
            if let Some(ref repo_url) = self.config.repository_url {
                let issue_links = self.format_issue_links(entry, repo_url);
                output.push_str(&format!("({})", issue_links.join(", ")));
            } else {
                let refs = entry.references.join(", ");
                output.push_str(&format!("({})", refs));
            }
        }

        // Add author
        if self.config.include_authors && !entry.author.is_empty() {
            output.push_str(&format!(" by {}", entry.author));
        }

        output
    }

    /// Formats a commit link for the repository.
    ///
    /// # Arguments
    ///
    /// * `entry` - The changelog entry
    /// * `base_url` - Base repository URL
    ///
    /// # Returns
    ///
    /// A markdown link to the commit.
    pub(crate) fn format_commit_link(&self, entry: &ChangelogEntry, base_url: &str) -> String {
        let url = base_url.trim_end_matches('/');
        format!("[{}]({}/commit/{})", entry.short_hash, url, entry.commit_hash)
    }

    /// Formats issue links for the repository.
    ///
    /// # Arguments
    ///
    /// * `entry` - The changelog entry
    /// * `base_url` - Base repository URL
    ///
    /// # Returns
    ///
    /// A vector of markdown links to issues/PRs.
    pub(crate) fn format_issue_links(&self, entry: &ChangelogEntry, base_url: &str) -> Vec<String> {
        let url = base_url.trim_end_matches('/');
        entry
            .references
            .iter()
            .map(|ref_| {
                let issue_num = ref_.trim_start_matches('#');
                format!("[{}]({}/issues/{})", ref_, url, issue_num)
            })
            .collect()
    }

    /// Formats the complete changelog header with description.
    ///
    /// This includes the standard Keep a Changelog header and description
    /// that explains the format and semantic versioning adherence.
    ///
    /// # Returns
    ///
    /// The formatted header string.
    #[must_use]
    pub fn format_header(&self) -> String {
        if self.config.template.header.contains("Keep a Changelog")
            || self.config.template.header.contains("keepachangelog")
        {
            // Use custom header if it references Keep a Changelog
            self.config.template.header.clone()
        } else {
            // Use standard Keep a Changelog header
            String::from(
                "# Changelog\n\n\
                 All notable changes to this project will be documented in this file.\n\n\
                 The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),\n\
                 and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n\n",
            )
        }
    }

    /// Formats multiple changelog versions into a complete changelog file.
    ///
    /// # Arguments
    ///
    /// * `changelogs` - Vector of changelogs to format (should be in reverse chronological order)
    ///
    /// # Returns
    ///
    /// A complete changelog file content.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use sublime_pkg_tools::changelog::formatter::KeepAChangelogFormatter;
    /// use sublime_pkg_tools::changelog::Changelog;
    /// use sublime_pkg_tools::config::ChangelogConfig;
    /// use chrono::Utc;
    ///
    /// let config = ChangelogConfig::default();
    /// let formatter = KeepAChangelogFormatter::new(&config);
    ///
    /// let changelogs = vec![
    ///     Changelog::new(Some("pkg"), "1.1.0", Some("1.0.0"), Utc::now()),
    ///     Changelog::new(Some("pkg"), "1.0.0", None, Utc::now()),
    /// ];
    ///
    /// let complete = formatter.format_complete(&changelogs);
    /// ```
    #[must_use]
    pub fn format_complete(&self, changelogs: &[Changelog]) -> String {
        let mut output = self.format_header();

        // Add unreleased section if configured
        output.push_str("## [Unreleased]\n\n");

        // Format each version
        for changelog in changelogs {
            output.push_str(&self.format(changelog));
        }

        output
    }
}