Skip to content

Commit fefdf69

Browse files
julescubtreeSchniz
andauthored
fix: list-remote --filter --latest panics when filter has no results (#1184)
* check for non-empty vector before draining to latest version * when filtering to latest, use swap+truncate instead of drain * add changeset * add a test --------- Co-authored-by: Gal Schlezinger <gal@spitfire.co.il>
1 parent 1000914 commit fefdf69

2 files changed

Lines changed: 35 additions & 1 deletion

File tree

‎.changeset/plenty-flies-refuse.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"fnm": patch
3+
---
4+
5+
fix panic when list-remote --filter --latest has no results

‎src/commands/ls_remote.rs‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,15 @@ pub enum SortingMethod {
3535
Ascending,
3636
}
3737

38+
/// Drain all elements but the last one
39+
fn truncate_except_latest<T>(list: &mut Vec<T>) {
40+
let len = list.len();
41+
if len > 1 {
42+
list.swap(0, len - 1);
43+
list.truncate(1);
44+
}
45+
}
46+
3847
impl super::command::Command for LsRemote {
3948
type Error = Error;
4049

@@ -57,7 +66,7 @@ impl super::command::Command for LsRemote {
5766
}
5867

5968
if self.latest {
60-
all_versions.drain(0..all_versions.len() - 1);
69+
truncate_except_latest(&mut all_versions);
6170
}
6271

6372
if let SortingMethod::Descending = self.sort {
@@ -89,3 +98,23 @@ pub enum Error {
8998
source: crate::http::Error,
9099
},
91100
}
101+
102+
#[cfg(test)]
103+
mod test {
104+
use super::*;
105+
106+
#[test]
107+
fn test_truncate_except_latest() {
108+
let mut list = vec![1, 2, 3, 4, 5];
109+
truncate_except_latest(&mut list);
110+
assert_eq!(list, vec![5]);
111+
112+
let mut list: Vec<()> = vec![];
113+
truncate_except_latest(&mut list);
114+
assert_eq!(list, vec![]);
115+
116+
let mut list = vec![1];
117+
truncate_except_latest(&mut list);
118+
assert_eq!(list, vec![1]);
119+
}
120+
}

0 commit comments

Comments
 (0)