1use crate::sort::{SortField, SortOptions, SortOrder};
2use clap::{ArgGroup, Parser};
4use std::ffi::OsString;
5
6#[derive(Parser, Debug)]
7#[command(
8 author,
9 version,
10 about,
11 long_about = None,
12 group(
13 ArgGroup::new("display_mode")
14 .args(["long", "one_per_line"])
15 .multiple(false)
16 ),
17 after_help = "Examples:\n lx -la\n lx -lr\n lx -alr path/to/dir"
18)]
19pub struct Args {
20 #[arg(default_value = ".")]
21 pub target: String,
22
23 #[arg(short, long, help = "Use a long listing format")]
24 pub long: bool,
25
26 #[arg(
27 short = 'a',
28 long = "all",
29 help = "Show all files, including hidden ones"
30 )]
31 pub show_hidden: bool,
32
33 #[arg(
34 short = 'f',
35 long = "files",
36 help = "Show only files",
37 conflicts_with = "recursive"
38 )]
39 pub files: bool,
40
41 #[arg(
42 short = 'd',
43 long = "directories",
44 help = "Show only directories",
45 conflicts_with = "recursive"
46 )]
47 pub directories: bool,
48
49 #[arg(
50 short = 'x',
51 long,
52 value_name = "PATTERN",
53 value_delimiter = ',',
54 help = "Exclude comma-separated glob patterns (repeatable)"
55 )]
56 pub exclude: Vec<String>,
57
58 #[arg(
59 short = 's',
60 long,
61 value_enum,
62 value_name = "FIELD",
63 help = "Sort by name, size, modified time, type, or long-format field"
64 )]
65 pub sort: Option<SortField>,
66
67 #[arg(
68 long,
69 value_enum,
70 value_name = "ORDER",
71 requires = "sort",
72 help = "Sort ascending or descending (ascending by default)"
73 )]
74 pub sort_order: Option<SortOrder>,
75
76 #[arg(
77 short = '1',
78 help = "Force single column output",
79 conflicts_with = "recursive"
80 )]
81 pub one_per_line: bool,
82
83 #[arg(
84 short = 'c',
85 long,
86 help = "Use compact columns with a limited number of rows",
87 conflicts_with_all = ["long", "one_per_line", "recursive"]
88 )]
89 pub compact: bool,
90
91 #[arg(
92 short = 'r',
93 long = "recursive",
94 help = "Show directory tree recursively"
95 )]
96 pub recursive: bool,
97}
98
99impl Args {
100 pub fn parse_args() -> Self {
101 Self::try_parse_args_from(std::env::args_os()).unwrap_or_else(|error| error.exit())
102 }
103
104 pub fn try_parse_args_from<I, T>(arguments: I) -> Result<Self, clap::Error>
105 where
106 I: IntoIterator<Item = T>,
107 T: Into<OsString>,
108 {
109 <Self as Parser>::try_parse_from(normalize_sort_order(arguments))
110 }
111
112 pub fn sort_options(&self, configured_default: SortOptions) -> SortOptions {
113 self.sort
114 .map(|field| SortOptions::new(Some(field), self.sort_order.unwrap_or_default()))
115 .unwrap_or(configured_default)
116 }
117}
118
119fn normalize_sort_order<I, T>(arguments: I) -> Vec<OsString>
120where
121 I: IntoIterator<Item = T>,
122 T: Into<OsString>,
123{
124 let arguments: Vec<OsString> = arguments.into_iter().map(Into::into).collect();
125 let mut normalized = Vec::with_capacity(arguments.len() + 2);
126 let mut index = 0;
127
128 while let Some(argument) = arguments.get(index) {
129 match sort_argument_form(argument) {
130 Some(SortArgumentForm::SeparateValue) => {
131 normalized.push(argument.clone());
132 if let Some(field) = arguments.get(index + 1) {
133 normalized.push(field.clone());
134 if let Some(order) = arguments
135 .get(index + 2)
136 .filter(|argument| is_sort_order(argument))
137 {
138 normalized.push("--sort-order".into());
139 normalized.push(order.clone());
140 index += 3;
141 continue;
142 }
143 index += 2;
144 continue;
145 }
146 index += 1;
147 continue;
148 }
149 Some(SortArgumentForm::AttachedValue) => {
150 normalized.push(argument.clone());
151 if let Some(order) = arguments
152 .get(index + 1)
153 .filter(|argument| is_sort_order(argument))
154 {
155 normalized.push("--sort-order".into());
156 normalized.push(order.clone());
157 index += 2;
158 continue;
159 }
160 index += 1;
161 continue;
162 }
163 None => {}
164 }
165
166 normalized.push(argument.clone());
167 index += 1;
168 }
169
170 normalized
171}
172
173enum SortArgumentForm {
174 SeparateValue,
175 AttachedValue,
176}
177
178fn sort_argument_form(argument: &OsString) -> Option<SortArgumentForm> {
179 let argument = argument.to_str()?;
180
181 if argument == "--sort" || argument == "-s" || is_short_flag_group_ending_in_sort(argument) {
182 return Some(SortArgumentForm::SeparateValue);
183 }
184
185 if argument.starts_with("--sort=") || (argument.starts_with("-s") && argument.len() > 2) {
186 return Some(SortArgumentForm::AttachedValue);
187 }
188
189 None
190}
191
192fn is_short_flag_group_ending_in_sort(argument: &str) -> bool {
193 let Some(flags) = argument.strip_prefix('-') else {
194 return false;
195 };
196
197 flags.len() > 1
198 && flags.ends_with('s')
199 && flags[..flags.len() - 1]
200 .chars()
201 .all(|flag| matches!(flag, 'a' | 'l' | 'f' | 'd' | '1' | 'c' | 'r'))
202}
203
204fn is_sort_order(argument: &OsString) -> bool {
205 matches!(argument.to_str(), Some("asc" | "desc"))
206}
207
208#[cfg(test)]
209mod tests {
210 use super::Args;
211 use crate::sort::{SortField, SortOrder};
212 use clap::Parser;
213
214 #[test]
215 fn handles_short_flag_groups_and_conflicts() {
216 let args = Args::try_parse_from(["lx", "-alr"]).expect("parse -alr");
217
218 assert!(args.show_hidden);
219 assert!(args.long);
220 assert!(args.recursive);
221 assert_eq!(args.target, ".");
222 assert!(
223 Args::try_parse_from(["lx", "-c"])
224 .expect("parse -c")
225 .compact
226 );
227 assert!(Args::try_parse_from(["lx", "-l1"]).is_err());
228 assert!(Args::try_parse_from(["lx", "-1r"]).is_err());
229 assert!(Args::try_parse_from(["lx", "-cl"]).is_err());
230 let filters = Args::try_parse_from(["lx", "-fd"]).expect("parse -fd");
231 assert!(filters.files && filters.directories);
232 assert!(Args::try_parse_from(["lx", "-rf"]).is_err());
233 let excluded = Args::try_parse_from(["lx", "-x", ".git,target,*.toml"])
234 .expect("parse multiple exclusion patterns");
235 assert_eq!(excluded.exclude, [".git", "target", "*.toml"]);
236 let sort = Args::try_parse_from(["lx", "-s", "size", "--sort-order", "desc"])
237 .expect("parse sort options");
238 assert_eq!(sort.sort, Some(SortField::Size));
239 assert_eq!(sort.sort_order, Some(SortOrder::Desc));
240 assert!(Args::try_parse_from(["lx", "--sort-order", "desc"]).is_err());
241 }
242}