perf(package): only try to read files that exist (#3904)

* perf(package): only try to read files that exist

Have refactored the package module to improve performance. Before this
change the module would try to open every single file that could contain
some package information until it found a valid version. This resulted
in a lot of unneeded disk IO. Have added a new fn, `read_file_from_pwd`
that uses the current context to check if that file already exists and
fast failing if it doesn't. From my local testing this speeds up the
package module from taking ~1ms to ~50µs in an empty directory.

* refactor: move read_file_from_pwd to context

* refactor(haskell): use read_files_from_pwd

* refactor(nodejs): use read_files_from_pwd
This commit is contained in:
Thomas O'Donnell
2022-04-25 16:18:01 +02:00
committed by GitHub
parent 4471e3654c
commit 2a650bfd14
4 changed files with 35 additions and 27 deletions
+13 -1
View File
@@ -1,7 +1,7 @@
use crate::config::{ModuleConfig, StarshipConfig};
use crate::configs::StarshipRootConfig;
use crate::module::Module;
use crate::utils::{create_command, exec_timeout, CommandOutput};
use crate::utils::{create_command, exec_timeout, read_file, CommandOutput};
use crate::modules;
use crate::utils::{self, home_dir};
@@ -342,6 +342,18 @@ impl<'a> Context<'a> {
.iter()
.find_map(|attempt| self.exec_cmd(attempt[0], &attempt[1..]))
}
/// Returns the string contents of a file from the current working directory
pub fn read_file_from_pwd(&self, file_name: &str) -> Option<String> {
if !self.try_begin_scan()?.set_files(&[file_name]).is_match() {
log::debug!(
"Not attempting to read {file_name} because, it was not found during scan."
);
return None;
}
read_file(self.current_dir.join(file_name)).ok()
}
}
#[derive(Debug)]