Skip to content

Commit 4b0c0eb

Browse files
DaniPopesorhun
andauthored
refactor(lib): clean up some code (#709)
* refactor: clean up some code * Update git-cliff/src/lib.rs Co-authored-by: Orhun Parmaksız <orhunparmaksiz@gmail.com> * review * fmt * fix: read before opening the file to prepend * style: update formatting --------- Co-authored-by: Orhun Parmaksız <orhunparmaksiz@gmail.com>
1 parent 35b886e commit 4b0c0eb

3 files changed

Lines changed: 107 additions & 128 deletions

File tree

‎git-cliff-core/src/changelog.rs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -499,7 +499,7 @@ impl<'a> Changelog<'a> {
499499
}
500500

501501
/// Generates the changelog and writes it to the given output.
502-
pub fn generate<W: Write>(&self, out: &mut W) -> Result<()> {
502+
pub fn generate<W: Write + ?Sized>(&self, out: &mut W) -> Result<()> {
503503
debug!("Generating changelog...");
504504
let postprocessors = self
505505
.config
@@ -567,7 +567,7 @@ impl<'a> Changelog<'a> {
567567
}
568568

569569
/// Generates a changelog and prepends it to the given changelog.
570-
pub fn prepend<W: Write>(
570+
pub fn prepend<W: Write + ?Sized>(
571571
&self,
572572
mut changelog: String,
573573
out: &mut W,
@@ -582,7 +582,7 @@ impl<'a> Changelog<'a> {
582582
}
583583

584584
/// Prints the changelog context to the given output.
585-
pub fn write_context<W: Write>(&self, out: &mut W) -> Result<()> {
585+
pub fn write_context<W: Write + ?Sized>(&self, out: &mut W) -> Result<()> {
586586
let output = Releases {
587587
releases: &self.releases,
588588
}

‎git-cliff-core/src/repo.rs‎

Lines changed: 29 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -59,14 +59,14 @@ impl Repository {
5959
/// Sorts the commits by their time.
6060
pub fn commits(
6161
&self,
62-
range: Option<String>,
63-
include_path: Option<Vec<Pattern>>,
64-
exclude_path: Option<Vec<Pattern>>,
62+
range: Option<&str>,
63+
include_path: Option<&[Pattern]>,
64+
exclude_path: Option<&[Pattern]>,
6565
) -> Result<Vec<Commit>> {
6666
let mut revwalk = self.inner.revwalk()?;
6767
revwalk.set_sorting(Sort::TOPOLOGICAL)?;
6868
if let Some(range) = range {
69-
revwalk.push_range(&range)?;
69+
revwalk.push_range(range)?;
7070
} else {
7171
revwalk.push_head()?;
7272
}
@@ -76,31 +76,31 @@ impl Repository {
7676
.collect();
7777
if include_path.is_some() || exclude_path.is_some() {
7878
commits.retain(|commit| {
79-
if let Ok(prev_commit) = commit.parent(0) {
80-
if let Ok(diff) = self.inner.diff_tree_to_tree(
81-
commit.tree().ok().as_ref(),
82-
prev_commit.tree().ok().as_ref(),
83-
None,
84-
) {
85-
return diff
86-
.deltas()
87-
.filter_map(|delta| delta.new_file().path())
88-
.any(|new_file_path| {
89-
if let Some(include_path) = &include_path {
90-
include_path
91-
.iter()
92-
.any(|glob| glob.matches_path(new_file_path))
93-
} else if let Some(exclude_path) = &exclude_path {
94-
!exclude_path
95-
.iter()
96-
.any(|glob| glob.matches_path(new_file_path))
97-
} else {
98-
false
99-
}
100-
});
101-
}
102-
}
103-
false
79+
let Ok(prev_commit) = commit.parent(0) else {
80+
return false;
81+
};
82+
let Ok(diff) = self.inner.diff_tree_to_tree(
83+
commit.tree().ok().as_ref(),
84+
prev_commit.tree().ok().as_ref(),
85+
None,
86+
) else {
87+
return false;
88+
};
89+
diff.deltas()
90+
.filter_map(|delta| delta.new_file().path())
91+
.any(|new_file_path| {
92+
if let Some(include_path) = include_path {
93+
return include_path
94+
.iter()
95+
.any(|glob| glob.matches_path(new_file_path));
96+
}
97+
if let Some(exclude_path) = exclude_path {
98+
return !exclude_path
99+
.iter()
100+
.any(|glob| glob.matches_path(new_file_path));
101+
}
102+
unreachable!()
103+
})
104104
});
105105
}
106106
Ok(commits)

‎git-cliff/src/lib.rs‎

Lines changed: 75 additions & 96 deletions
Original file line numberDiff line numberDiff line change
@@ -45,11 +45,8 @@ use std::fs::{
4545
self,
4646
File,
4747
};
48-
use std::io::{
49-
self,
50-
Write,
51-
};
52-
use std::path::PathBuf;
48+
use std::io;
49+
use std::path::Path;
5350
use std::time::{
5451
SystemTime,
5552
UNIX_EPOCH,
@@ -89,31 +86,28 @@ fn process_repository<'a>(
8986
let mut tags = repository.tags(&config.git.tag_pattern, args.topo_order)?;
9087
let skip_regex = config.git.skip_tags.as_ref();
9188
let ignore_regex = config.git.ignore_tags.as_ref();
92-
tags = tags
93-
.into_iter()
94-
.filter(|(_, tag)| {
95-
let name = &tag.name;
96-
97-
// Keep skip tags to drop commits in the later stage.
98-
let skip = skip_regex.map(|r| r.is_match(name)).unwrap_or_default();
99-
100-
let ignore = ignore_regex
101-
.map(|r| {
102-
if r.as_str().trim().is_empty() {
103-
return false;
104-
}
89+
tags.retain(|_, tag| {
90+
let name = &tag.name;
10591

106-
let ignore_tag = r.is_match(name);
107-
if ignore_tag {
108-
trace!("Ignoring release: {}", name)
109-
}
110-
ignore_tag
111-
})
112-
.unwrap_or_default();
92+
// Keep skip tags to drop commits in the later stage.
93+
let skip = skip_regex.is_some_and(|r| r.is_match(name));
94+
if skip {
95+
return true;
96+
}
11397

114-
skip || !ignore
115-
})
116-
.collect();
98+
let ignore = ignore_regex.is_some_and(|r| {
99+
if r.as_str().trim().is_empty() {
100+
return false;
101+
}
102+
103+
let ignore_tag = r.is_match(name);
104+
if ignore_tag {
105+
trace!("Ignoring release: {}", name)
106+
}
107+
ignore_tag
108+
});
109+
!ignore
110+
});
117111

118112
if !config.remote.github.is_set() {
119113
match repository.upstream_remote() {
@@ -214,14 +208,12 @@ fn process_repository<'a>(
214208
}
215209
}
216210
let mut commits = repository.commits(
217-
commit_range,
218-
args.include_path.clone(),
219-
args.exclude_path.clone(),
211+
commit_range.as_deref(),
212+
args.include_path.as_deref(),
213+
args.exclude_path.as_deref(),
220214
)?;
221215
if let Some(commit_limit_value) = config.git.limit_commits {
222-
commits = commits
223-
.drain(..commits.len().min(commit_limit_value))
224-
.collect();
216+
commits.truncate(commit_limit_value);
225217
}
226218

227219
// Update tags.
@@ -240,27 +232,19 @@ fn process_repository<'a>(
240232

241233
// Process releases.
242234
let mut releases = vec![Release::default()];
243-
let mut release_index = 0;
244235
let mut previous_release = Release::default();
245236
let mut first_processed_tag = None;
246237
for git_commit in commits.iter().rev() {
238+
let release = releases.last_mut().unwrap();
247239
let commit = Commit::from(git_commit);
248240
let commit_id = commit.id.to_string();
249-
releases[release_index].repository =
250-
Some(repository.path.to_string_lossy().to_string());
251-
if args.sort == Sort::Newest {
252-
releases[release_index].commits.insert(0, commit);
253-
} else {
254-
releases[release_index].commits.push(commit);
255-
}
241+
release.commits.push(commit);
242+
release.repository = Some(repository.path.to_string_lossy().into_owned());
256243
if let Some(tag) = tags.get(&commit_id) {
257-
let tag_name = &tag.name;
258-
259-
releases[release_index].version = Some(tag_name.clone());
260-
releases[release_index].message = tag.message.clone();
261-
releases[release_index].commit_id = Some(commit_id);
262-
releases[release_index].timestamp = if args.tag == Some(tag_name.clone())
263-
{
244+
release.version = Some(tag.name.to_string());
245+
release.message = tag.message.clone();
246+
release.commit_id = Some(commit_id);
247+
release.timestamp = if args.tag.as_deref() == Some(tag.name.as_str()) {
264248
SystemTime::now()
265249
.duration_since(UNIX_EPOCH)?
266250
.as_secs()
@@ -272,27 +256,32 @@ fn process_repository<'a>(
272256
first_processed_tag = Some(tag);
273257
}
274258
previous_release.previous = None;
275-
releases[release_index].previous = Some(Box::new(previous_release));
276-
previous_release = releases[release_index].clone();
259+
release.previous = Some(Box::new(previous_release));
260+
previous_release = release.clone();
277261
releases.push(Release::default());
278-
release_index += 1;
279262
}
280263
}
281264

282-
if release_index > 0 {
265+
debug_assert!(!releases.is_empty());
266+
267+
if releases.len() > 1 {
283268
previous_release.previous = None;
284-
releases[release_index].previous = Some(Box::new(previous_release));
269+
releases.last_mut().unwrap().previous = Some(Box::new(previous_release));
270+
}
271+
272+
if args.sort == Sort::Newest {
273+
for release in &mut releases {
274+
release.commits.reverse();
275+
}
285276
}
286277

287278
// Add custom commit messages to the latest release.
288279
if let Some(custom_commits) = &args.with_commit {
289-
if let Some(latest_release) = releases.iter_mut().last() {
290-
custom_commits.iter().for_each(|message| {
291-
latest_release
292-
.commits
293-
.push(Commit::from(message.to_string()))
294-
});
295-
}
280+
releases
281+
.last_mut()
282+
.unwrap()
283+
.commits
284+
.extend(custom_commits.iter().cloned().map(Commit::from));
296285
}
297286

298287
// Set custom message for the latest release.
@@ -303,12 +292,11 @@ fn process_repository<'a>(
303292
}
304293

305294
// Set the previous release if the first release does not have one set.
306-
if !releases.is_empty() &&
307-
releases
308-
.first()
309-
.and_then(|r| r.previous.as_ref())
310-
.and_then(|p| p.version.as_ref())
311-
.is_none()
295+
if releases[0]
296+
.previous
297+
.as_ref()
298+
.and_then(|p| p.version.as_ref())
299+
.is_none()
312300
{
313301
// Get the previous tag of the first processed tag in the release loop.
314302
let first_tag = first_processed_tag
@@ -553,6 +541,15 @@ pub fn run(mut args: Opt) -> Result<()> {
553541
let mut changelog = Changelog::new(releases, &config)?;
554542

555543
// Print the result.
544+
let mut out: Box<dyn io::Write> = if let Some(path) = &args.output {
545+
if path == Path::new("-") {
546+
Box::new(io::stdout())
547+
} else {
548+
Box::new(io::BufWriter::new(File::create(path)?))
549+
}
550+
} else {
551+
Box::new(io::stdout())
552+
};
556553
if args.bump.is_some() || args.bumped_version {
557554
let next_version = if let Some(next_version) = changelog.bump_version()? {
558555
next_version
@@ -565,40 +562,22 @@ pub fn run(mut args: Opt) -> Result<()> {
565562
return Ok(());
566563
};
567564
if args.bumped_version {
568-
if let Some(path) = args.output {
569-
let mut output = File::create(path)?;
570-
output.write_all(next_version.as_bytes())?;
571-
} else {
572-
println!("{next_version}");
573-
}
565+
writeln!(out, "{next_version}")?;
574566
return Ok(());
575567
}
576568
}
577569
if args.context {
578-
return if let Some(path) = args.output {
579-
let mut output = File::create(path)?;
580-
changelog.write_context(&mut output)
581-
} else {
582-
changelog.write_context(&mut io::stdout())
583-
};
570+
changelog.write_context(&mut out)?;
571+
return Ok(());
584572
}
585-
if let Some(ref path) = args.prepend {
586-
changelog.prepend(fs::read_to_string(path)?, &mut File::create(path)?)?;
573+
if let Some(path) = &args.prepend {
574+
let changelog_before = fs::read_to_string(path)?;
575+
let mut out = io::BufWriter::new(File::create(path)?);
576+
changelog.prepend(changelog_before, &mut out)?;
587577
}
588-
if let Some(path) = args.output {
589-
let mut output: Box<dyn Write> = if path == PathBuf::from("-") {
590-
Box::new(io::stdout())
591-
} else {
592-
Box::new(File::create(path)?)
593-
};
594-
if args.context {
595-
changelog.write_context(&mut output)
596-
} else {
597-
changelog.generate(&mut output)
598-
}
599-
} else if args.prepend.is_none() {
600-
changelog.generate(&mut io::stdout())
601-
} else {
602-
Ok(())
578+
if args.output.is_some() || args.prepend.is_none() {
579+
changelog.generate(&mut out)?;
603580
}
581+
582+
Ok(())
604583
}

0 commit comments

Comments
 (0)