on master help sign in
Reduce nesting in if blocks by short circuiting
commit372e42f3509c3ec87504a054271ad1289ce3b4ac authorMarcin Puc <marcin.e.puc@gmail.com> dateFri 10 Sep 2021, 21:52 (5 years ago) parent9124271
5 files changed+84−88
src/assets.rs+46−47 src/bin/bat/main.rs+7−10 src/input.rs+9−9 src/less.rs+6−6 src/printer.rs+16−16
src/assets.rs+46−47
@@ -255,57 +255,56 @@ impl HighlightingAssets {
255255 ) -> Result<SyntaxReferenceInSet> {
256256 if let Some(language) = language {
257257 let syntax_set = self.get_syntax_set_by_name(language)?;
258− syntax_set
258+ return syntax_set
259259 .find_syntax_by_token(language)
260260 .map(|syntax| SyntaxReferenceInSet { syntax, syntax_set })
261− .ok_or_else(|| Error::UnknownSyntax(language.to_owned()))
262− } else {
263− let line_syntax = self.get_first_line_syntax(&mut input.reader)?;
264−
265− // Get the path of the file:
266− // If this was set by the metadata, that will take priority.
267− // If it wasn't, it will use the real file path (if available).
268− let path_str =
269− input
270− .metadata
271− .user_provided_name
272− .as_ref()
273− .or_else(|| match input.kind {
274− OpenedInputKind::OrdinaryFile(ref path) => Some(path),
275− _ => None,
276− });
277−
278− if let Some(path_str) = path_str {
279− // If a path was provided, we try and detect the syntax based on extension mappings.
280− let path = Path::new(path_str);
281− let absolute_path = PathAbs::new(path)
282− .ok()
283− .map(|p| p.as_path().to_path_buf())
284− .unwrap_or_else(|| path.to_owned());
285−
286− match mapping.get_syntax_for(absolute_path) {
287− Some(MappingTarget::MapToUnknown) => line_syntax
288− .ok_or_else(|| Error::UndetectedSyntax(path.to_string_lossy().into())),
289−
290− Some(MappingTarget::MapTo(syntax_name)) => {
291− let syntax_set = self.get_syntax_set()?;
292− syntax_set
293− .find_syntax_by_name(syntax_name)
294− .map(|syntax| SyntaxReferenceInSet { syntax, syntax_set })
295− .ok_or_else(|| Error::UnknownSyntax(syntax_name.to_owned()))
296− }
297−
298− None => {
299− let file_name = path.file_name().unwrap_or_default();
300− self.get_extension_syntax(file_name)?
301− .or(line_syntax)
302− .ok_or_else(|| Error::UndetectedSyntax(path.to_string_lossy().into()))
303− }
261+ .ok_or_else(|| Error::UnknownSyntax(language.to_owned()));
262+ }
263+
264+ let line_syntax = self.get_first_line_syntax(&mut input.reader)?;
265+
266+ // Get the path of the file:
267+ // If this was set by the metadata, that will take priority.
268+ // If it wasn't, it will use the real file path (if available).
269+ let path_str = input
270+ .metadata
271+ .user_provided_name
272+ .as_ref()
273+ .or_else(|| match input.kind {
274+ OpenedInputKind::OrdinaryFile(ref path) => Some(path),
275+ _ => None,
276+ });
277+
278+ if let Some(path_str) = path_str {
279+ // If a path was provided, we try and detect the syntax based on extension mappings.
280+ let path = Path::new(path_str);
281+ let absolute_path = PathAbs::new(path)
282+ .ok()
283+ .map(|p| p.as_path().to_path_buf())
284+ .unwrap_or_else(|| path.to_owned());
285+
286+ match mapping.get_syntax_for(absolute_path) {
287+ Some(MappingTarget::MapToUnknown) => line_syntax
288+ .ok_or_else(|| Error::UndetectedSyntax(path.to_string_lossy().into())),
289+
290+ Some(MappingTarget::MapTo(syntax_name)) => {
291+ let syntax_set = self.get_syntax_set()?;
292+ syntax_set
293+ .find_syntax_by_name(syntax_name)
294+ .map(|syntax| SyntaxReferenceInSet { syntax, syntax_set })
295+ .ok_or_else(|| Error::UnknownSyntax(syntax_name.to_owned()))
296+ }
297+
298+ None => {
299+ let file_name = path.file_name().unwrap_or_default();
300+ self.get_extension_syntax(file_name)?
301+ .or(line_syntax)
302+ .ok_or_else(|| Error::UndetectedSyntax(path.to_string_lossy().into()))
304303 }
305− } else {
306− // If a path wasn't provided, we fall back to the detect first-line syntax.
307− line_syntax.ok_or_else(|| Error::UndetectedSyntax("[unknown]".into()))
308304 }
305+ } else {
306+ // If a path wasn't provided, we fall back to the detect first-line syntax.
307+ line_syntax.ok_or_else(|| Error::UndetectedSyntax("[unknown]".into()))
309308 }
310309 }
311310
src/bin/bat/main.rs+7−10
@@ -100,17 +100,14 @@ pub fn get_languages(config: &Config) -> Result<String> {
100100 // Also skip if the 'extension' contains another real extension, likely
101101 // that is a full match file name like 'CMakeLists.txt' and 'Cargo.lock'
102102 if extension.starts_with('.') || Path::new(extension).extension().is_some() {
103− true
104− } else {
105− let test_file = Path::new("test").with_extension(extension);
106− let syntax_in_set = assets
107− .get_syntax_for_file_name(test_file, &config.syntax_mapping)
108− .unwrap(); // safe since .get_syntaxes() above worked
109− match syntax_in_set {
110− Some(syntax_in_set) => syntax_in_set.syntax.name == lang_name,
111− None => false,
112− }
103+ return true;
113104 }
105+
106+ let test_file = Path::new("test").with_extension(extension);
107+ let syntax_in_set = assets
108+ .get_syntax_for_file_name(test_file, &config.syntax_mapping)
109+ .unwrap(); // safe since .get_syntaxes() above worked
110+ matches!(syntax_in_set, Some(syntax_in_set) if syntax_in_set.syntax.name == lang_name)
114111 });
115112 }
116113
src/input.rs+9−9
@@ -256,18 +256,18 @@ impl<'a> InputReader<'a> {
256256 }
257257
258258 pub(crate) fn read_line(&mut self, buf: &mut Vec<u8>) -> io::Result<bool> {
259− if self.first_line.is_empty() {
260− let res = self.inner.read_until(b'\n', buf).map(|size| size > 0)?;
259+ if !self.first_line.is_empty() {
260+ buf.append(&mut self.first_line);
261+ return Ok(true);
262+ }
261263
262− if self.content_type == Some(ContentType::UTF_16LE) {
263− self.inner.read_until(0x00, buf).ok();
264− }
264+ let res = self.inner.read_until(b'\n', buf).map(|size| size > 0)?;
265265
266− Ok(res)
267− } else {
268− buf.append(&mut self.first_line);
269− Ok(true)
266+ if self.content_type == Some(ContentType::UTF_16LE) {
267+ let _ = self.inner.read_until(0x00, buf);
270268 }
269+
270+ Ok(res)
271271 }
272272}
273273
src/less.rs+6−6
@@ -11,13 +11,13 @@ pub fn retrieve_less_version(less_path: &dyn AsRef<OsStr>) -> Option<usize> {
1111}
1212
1313fn parse_less_version(output: &[u8]) -> Option<usize> {
14− if output.starts_with(b"less ") {
15− let version = std::str::from_utf8(&output[5..]).ok()?;
16− let end = version.find(|c: char| !c.is_ascii_digit())?;
17− version[..end].parse::<usize>().ok()
18− } else {
19− None
14+ if !output.starts_with(b"less ") {
15+ return None;
2016 }
17+
18+ let version = std::str::from_utf8(&output[5..]).ok()?;
19+ let end = version.find(|c: char| !c.is_ascii_digit())?;
20+ version[..end].parse::<usize>().ok()
2121}
2222
2323#[test]
src/printer.rs+16−16
@@ -226,29 +226,29 @@ impl<'a> InteractivePrinter<'a> {
226226
227227 fn create_fake_panel(&self, text: &str) -> String {
228228 if self.panel_width == 0 {
229− "".to_string()
229+ return "".to_string();
230+ }
231+
232+ let text_truncated: String = text.chars().take(self.panel_width - 1).collect();
233+ let text_filled: String = format!(
234+ "{}{}",
235+ text_truncated,
236+ " ".repeat(self.panel_width - 1 - text_truncated.len())
237+ );
238+ if self.config.style_components.grid() {
239+ format!("{} │ ", text_filled)
230240 } else {
231− let text_truncated: String = text.chars().take(self.panel_width - 1).collect();
232− let text_filled: String = format!(
233− "{}{}",
234− text_truncated,
235− " ".repeat(self.panel_width - 1 - text_truncated.len())
236− );
237− if self.config.style_components.grid() {
238− format!("{} │ ", text_filled)
239− } else {
240− text_filled
241− }
241+ text_filled
242242 }
243243 }
244244
245245 fn preprocess(&self, text: &str, cursor: &mut usize) -> String {
246246 if self.config.tab_width > 0 {
247− expand_tabs(text, self.config.tab_width, cursor)
248− } else {
249− *cursor += text.len();
250− text.to_string()
247+ return expand_tabs(text, self.config.tab_width, cursor);
251248 }
249+
250+ *cursor += text.len();
251+ text.to_string()
252252 }
253253}
254254