Skip to content

Commit 6a36c8d

Browse files
authored
fix: start code index from one as done in dashboard and in edit subcommand (#458)
Fixes #457
2 parents d35a94b + c182195 commit 6a36c8d

File tree

1 file changed

+42
-7
lines changed

1 file changed

+42
-7
lines changed

src/arguments/list.rs

Lines changed: 42 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,8 @@ impl<'a> TryFrom<&'a OTPElement> for JsonOtpList<'a> {
5656
}
5757
}
5858

59+
const NO_ISSUER_TEXT: &str = "<No issuer>";
60+
5961
impl SubcommandExecutor for ListArgs {
6062
fn run_command(self, otp_database: OTPDatabase) -> color_eyre::Result<OTPDatabase> {
6163
if self.format.unwrap_or_default().json {
@@ -69,24 +71,44 @@ impl SubcommandExecutor for ListArgs {
6971
.map_err(|e| eyre!("Error during JSON serialization: {:?}", e))?;
7072
print!("{stringified}");
7173
} else {
74+
let issuer_width = calculate_width(&otp_database, |element| {
75+
let issuer_length = element.issuer.chars().count();
76+
if issuer_length > 0 {
77+
issuer_length
78+
} else {
79+
NO_ISSUER_TEXT.chars().count()
80+
}
81+
});
82+
83+
let label_width =
84+
calculate_width(&otp_database, |element| element.label.chars().count());
85+
7286
println!(
73-
"{0: <6} {1: <30} {2: <70} {3: <10}",
74-
"Index", "Issuer", "Label", "OTP"
87+
"{0: <6} {1} {2} {3: <10}",
88+
"Index",
89+
"Issuer".to_owned() + " ".repeat(issuer_width - 6).as_ref(),
90+
"Label".to_owned() + " ".repeat(label_width - 5).as_ref(),
91+
"OTP",
7592
);
7693
otp_database
7794
.elements
7895
.iter()
7996
.enumerate()
8097
.for_each(|(index, e)| {
8198
println!(
82-
"{0: <6} {1: <30} {2: <70} {3: <10}",
83-
index,
99+
"{0: <6} {1} {2} {3: <10}",
100+
index + 1,
84101
if e.issuer.is_empty() {
85-
"<No issuer>"
102+
NO_ISSUER_TEXT.to_owned()
103+
+ " "
104+
.repeat(issuer_width - NO_ISSUER_TEXT.chars().count())
105+
.as_str()
86106
} else {
87-
e.issuer.as_str()
107+
e.issuer.to_owned()
108+
+ " ".repeat(issuer_width - e.issuer.chars().count()).as_str()
88109
},
89-
&e.label,
110+
e.label.to_owned()
111+
+ " ".repeat(label_width - e.label.chars().count()).as_str(),
90112
e.get_otp_code().unwrap_or("ERROR".to_string())
91113
)
92114
});
@@ -95,3 +117,16 @@ impl SubcommandExecutor for ListArgs {
95117
Ok(otp_database)
96118
}
97119
}
120+
121+
fn calculate_width<F>(otp_database: &OTPDatabase, get_number_of_chars: F) -> usize
122+
where
123+
F: Fn(&OTPElement) -> usize,
124+
{
125+
otp_database
126+
.elements
127+
.iter()
128+
.map(get_number_of_chars)
129+
.max()
130+
.unwrap_or_default()
131+
+ 3
132+
}

0 commit comments

Comments
 (0)