Browse Source

add rustfmt.toml

pull/308/head
o2sh 5 years ago
parent
commit
71230ce111
  1. 3
      .rustfmt.toml
  2. 6
      src/main.rs
  3. 71
      src/onefetch/ascii_art.rs
  4. 5
      src/onefetch/cli.rs
  5. 6
      src/onefetch/cli_utils.rs
  6. 4
      src/onefetch/image_backends/iterm2.rs
  7. 39
      src/onefetch/image_backends/kitty.rs
  8. 6
      src/onefetch/image_backends/sixel.rs
  9. 67
      src/onefetch/info.rs
  10. 4
      src/onefetch/info_fields.rs
  11. 11
      src/onefetch/language.rs
  12. 10
      src/onefetch/license.rs

3
.rustfmt.toml

@ -0,0 +1,3 @@ @@ -0,0 +1,3 @@
newline_style = "Unix"
# The "Default" setting has a heuristic which splits lines too aggresively.
use_small_heuristics = "Max"

6
src/main.rs

@ -50,9 +50,5 @@ fn main() { @@ -50,9 +50,5 @@ fn main() {
}
fn is_git_installed() -> bool {
Command::new("git")
.arg("--version")
.stdout(Stdio::null())
.status()
.is_ok()
Command::new("git").arg("--version").stdout(Stdio::null()).status().is_ok()
}

71
src/onefetch/ascii_art.rs

@ -29,13 +29,7 @@ impl<'a> AsciiArt<'a> { @@ -29,13 +29,7 @@ impl<'a> AsciiArt<'a> {
(acc_s.min(line_s), acc_e.max(line_e))
});
AsciiArt {
content: Box::new(lines.into_iter()),
colors,
bold,
start,
end,
}
AsciiArt { content: Box::new(lines.into_iter()), colors, bold, start, end }
}
pub fn width(&self) -> usize {
assert!(self.end >= self.start);
@ -96,9 +90,8 @@ struct Tokens<'a>(&'a str); @@ -96,9 +90,8 @@ struct Tokens<'a>(&'a str);
impl<'a> Iterator for Tokens<'a> {
type Item = Token;
fn next(&mut self) -> Option<Token> {
let (s, tok) = color_token(self.0)
.or_else(|| space_token(self.0))
.or_else(|| char_token(self.0))?;
let (s, tok) =
color_token(self.0).or_else(|| space_token(self.0)).or_else(|| char_token(self.0))?;
self.0 = s;
Some(tok)
@ -129,9 +122,7 @@ impl<'a> Tokens<'a> { @@ -129,9 +122,7 @@ impl<'a> Tokens<'a> {
last_non_space
}
fn leading_spaces(&mut self) -> usize {
self.take_while(|token| !token.is_solid())
.filter(|token| token.is_space())
.count()
self.take_while(|token| !token.is_solid()).filter(|token| token.is_space()).count()
}
fn truncate(self, mut start: usize, end: usize) -> impl 'a + Iterator<Item = Token> {
assert!(start <= end);
@ -269,40 +260,19 @@ mod test { @@ -269,40 +260,19 @@ mod test {
let colors_shim = Vec::new();
assert_eq!(
Tokens("").render(&colors_shim, 0, 0, true),
"\u{1b}[1;37m\u{1b}[0m"
);
assert_eq!(Tokens("").render(&colors_shim, 0, 0, true), "\u{1b}[1;37m\u{1b}[0m");
assert_eq!(
Tokens(" ").render(&colors_shim, 0, 0, true),
"\u{1b}[1;37m\u{1b}[0m"
);
assert_eq!(Tokens(" ").render(&colors_shim, 0, 0, true), "\u{1b}[1;37m\u{1b}[0m");
assert_eq!(
Tokens(" ").render(&colors_shim, 0, 5, true),
"\u{1b}[1;37m \u{1b}[0m"
);
assert_eq!(Tokens(" ").render(&colors_shim, 0, 5, true), "\u{1b}[1;37m \u{1b}[0m");
assert_eq!(
Tokens(" ").render(&colors_shim, 1, 5, true),
"\u{1b}[1;37m \u{1b}[0m"
);
assert_eq!(Tokens(" ").render(&colors_shim, 1, 5, true), "\u{1b}[1;37m \u{1b}[0m");
assert_eq!(
Tokens(" ").render(&colors_shim, 3, 5, true),
"\u{1b}[1;37m \u{1b}[0m"
);
assert_eq!(Tokens(" ").render(&colors_shim, 3, 5, true), "\u{1b}[1;37m \u{1b}[0m");
assert_eq!(
Tokens(" ").render(&colors_shim, 0, 4, true),
"\u{1b}[1;37m \u{1b}[0m"
);
assert_eq!(Tokens(" ").render(&colors_shim, 0, 4, true), "\u{1b}[1;37m \u{1b}[0m");
assert_eq!(
Tokens(" ").render(&colors_shim, 0, 3, true),
"\u{1b}[1;37m \u{1b}[0m"
);
assert_eq!(Tokens(" ").render(&colors_shim, 0, 3, true), "\u{1b}[1;37m \u{1b}[0m");
assert_eq!(
Tokens(" {1} {5} {9} a").render(&colors_shim, 4, 10, true),
@ -310,22 +280,13 @@ mod test { @@ -310,22 +280,13 @@ mod test {
);
// Tests for bold disabled
assert_eq!(
Tokens(" ").render(&colors_shim, 0, 0, false),
"\u{1b}[37m\u{1b}[0m"
);
assert_eq!(
Tokens(" ").render(&colors_shim, 0, 5, false),
"\u{1b}[37m \u{1b}[0m"
);
assert_eq!(Tokens(" ").render(&colors_shim, 0, 0, false), "\u{1b}[37m\u{1b}[0m");
assert_eq!(Tokens(" ").render(&colors_shim, 0, 5, false), "\u{1b}[37m \u{1b}[0m");
}
#[test]
fn truncate() {
assert_eq!(
Tokens("").truncate(0, 0).collect::<Vec<_>>(),
Tokens("").collect::<Vec<_>>()
);
assert_eq!(Tokens("").truncate(0, 0).collect::<Vec<_>>(), Tokens("").collect::<Vec<_>>());
assert_eq!(
Tokens(" ").truncate(0, 0).collect::<Vec<_>>(),
@ -353,9 +314,7 @@ mod test { @@ -353,9 +314,7 @@ mod test {
);
assert_eq!(
Tokens(" {1} {5} {9} a")
.truncate(4, 10)
.collect::<Vec<_>>(),
Tokens(" {1} {5} {9} a").truncate(4, 10).collect::<Vec<_>>(),
Tokens("{1}{5} {9} a").collect::<Vec<_>>()
);
}

5
src/onefetch/cli.rs

@ -39,9 +39,8 @@ impl Cli { @@ -39,9 +39,8 @@ impl Cli {
let possible_backends = ["kitty", "iterm2", "sixel"];
#[cfg(windows)]
let possible_backends = [];
let color_values = &[
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15",
];
let color_values =
&["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"];
let matches = App::new(crate_name!())
.version(crate_version!())
.about(crate_description!())

6
src/onefetch/cli_utils.rs

@ -33,11 +33,7 @@ impl<W: Write> Printer<W> { @@ -33,11 +33,7 @@ impl<W: Write> Printer<W> {
let mut logo_lines = if let Some(custom_ascii) = &self.info.config.ascii_input {
AsciiArt::new(custom_ascii, &colors, !self.info.config.no_bold)
} else {
AsciiArt::new(
self.get_ascii(),
&self.info.colors,
!self.info.config.no_bold,
)
AsciiArt::new(self.get_ascii(), &self.info.colors, !self.info.config.no_bold)
};
loop {

4
src/onefetch/image_backends/iterm2.rs

@ -37,9 +37,7 @@ impl super::ImageBackend for ITerm2Backend { @@ -37,9 +37,7 @@ impl super::ImageBackend for ITerm2Backend {
let image_rows = height_ratio * f64::from(image.height());
let mut bytes: Vec<u8> = Vec::new();
image
.write_to(&mut bytes, image::ImageOutputFormat::Png)
.unwrap();
image.write_to(&mut bytes, image::ImageOutputFormat::Png).unwrap();
let encoded_image = base64::encode(bytes);
let mut image_data = Vec::<u8>::new();

39
src/onefetch/image_backends/kitty.rs

@ -16,10 +16,7 @@ impl KittyBackend { @@ -16,10 +16,7 @@ impl KittyBackend {
}
pub fn supported() -> bool {
if !env::var("KITTY_WINDOW_ID")
.unwrap_or("".to_string())
.is_empty()
{
if !env::var("KITTY_WINDOW_ID").unwrap_or("".to_string()).is_empty() {
return true;
}
@ -37,24 +34,13 @@ impl KittyBackend { @@ -37,24 +34,13 @@ impl KittyBackend {
// generate red rgba test image
let mut test_image = Vec::<u8>::with_capacity(32 * 32 * 4);
test_image.extend(
std::iter::repeat([255, 0, 0, 255].iter())
.take(32 * 32)
.flatten(),
);
test_image.extend(std::iter::repeat([255, 0, 0, 255].iter()).take(32 * 32).flatten());
// print the test image with the action set to query
println!(
"\x1B_Gi=1,f=32,s=32,v=32,a=q;{}\x1B\\",
base64::encode(&test_image)
);
println!("\x1B_Gi=1,f=32,s=32,v=32,a=q;{}\x1B\\", base64::encode(&test_image));
let start_time = Instant::now();
let mut stdin_pollfd = pollfd {
fd: STDIN_FILENO,
events: POLLIN,
revents: 0,
};
let mut stdin_pollfd = pollfd { fd: STDIN_FILENO, events: POLLIN, revents: 0 };
let allowed_bytes = [0x1B, b'_', b'G', b'\\'];
let mut buf = Vec::<u8>::new();
loop {
@ -106,25 +92,16 @@ impl super::ImageBackend for KittyBackend { @@ -106,25 +92,16 @@ impl super::ImageBackend for KittyBackend {
// convert the image to rgba samples
let rgba_image = image.to_rgba();
let flat_samples = rgba_image.as_flat_samples();
let raw_image = flat_samples
.image_slice()
.expect("Conversion from image to rgba samples failed");
assert_eq!(
image.width() as usize * image.height() as usize * 4,
raw_image.len()
);
let raw_image =
flat_samples.image_slice().expect("Conversion from image to rgba samples failed");
assert_eq!(image.width() as usize * image.height() as usize * 4, raw_image.len());
let encoded_image = base64::encode(&raw_image); // image data is base64 encoded
let mut image_data = Vec::<u8>::new();
for chunk in encoded_image.as_bytes().chunks(4096) {
// send a 4096 byte chunk of base64 encoded rgba image data
image_data.extend(
format!(
"\x1B_Gf=32,s={},v={},m=1,a=T;",
image.width(),
image.height()
)
.as_bytes(),
format!("\x1B_Gf=32,s={},v={},m=1,a=T;", image.width(), image.height()).as_bytes(),
);
image_data.extend(chunk);
image_data.extend(b"\x1B\\");

6
src/onefetch/image_backends/sixel.rs

@ -35,11 +35,7 @@ impl SixelBackend { @@ -35,11 +35,7 @@ impl SixelBackend {
println!("\x1B[c");
let start_time = Instant::now();
let mut stdin_pollfd = pollfd {
fd: STDIN_FILENO,
events: POLLIN,
revents: 0,
};
let mut stdin_pollfd = pollfd { fd: STDIN_FILENO, events: POLLIN, revents: 0 };
let mut buf = Vec::<u8>::new();
loop {
// check for timeout while polling to avoid blocking the main thread

67
src/onefetch/info.rs

@ -102,11 +102,7 @@ impl std::fmt::Display for Info { @@ -102,11 +102,7 @@ impl std::fmt::Display for Info {
}
if !self.config.disabled_fields.languages && !self.languages.is_empty() {
let title = if self.languages.len() > 1 {
"Languages"
} else {
"Language"
};
let title = if self.languages.len() > 1 { "Languages" } else { "Language" };
let languages_str = self.get_language_field(title);
@ -119,11 +115,7 @@ impl std::fmt::Display for Info { @@ -119,11 +115,7 @@ impl std::fmt::Display for Info {
}
if !self.config.disabled_fields.authors && !self.authors.is_empty() {
let title = if self.authors.len() > 1 {
"Authors"
} else {
"Author"
};
let title = if self.authors.len() > 1 { "Authors" } else { "Author" };
let author_str = self.get_author_field(title);
@ -213,9 +205,7 @@ impl Info { @@ -213,9 +205,7 @@ impl Info {
pub async fn new(config: Cli) -> Result<Info> {
let repo = Repository::discover(&config.path)
.chain_err(|| "Could not find a valid git repo on the current path")?;
let workdir = repo
.workdir()
.chain_err(|| "Unable to run onefetch on bare git repo")?;
let workdir = repo.workdir().chain_err(|| "Unable to run onefetch on bare git repo")?;
let workdir_str = workdir.to_str().unwrap();
let (languages_stats, number_of_lines) =
Language::get_language_statistics(workdir_str, &config.excluded)?;
@ -285,11 +275,7 @@ impl Info { @@ -285,11 +275,7 @@ impl Info {
args.push("--pretty=%cr\t%ae\t%an");
let output = Command::new("git")
.args(args)
.output()
.await
.expect("Failed to execute git.");
let output = Command::new("git").args(args).output().await.expect("Failed to execute git.");
let output = String::from_utf8_lossy(&output.stdout);
output.lines().map(|x| x.to_string()).collect::<Vec<_>>()
@ -328,9 +314,7 @@ impl Info { @@ -328,9 +314,7 @@ impl Info {
}
fn get_repo_name_and_url(repo: &Repository) -> (String, String) {
let config = repo
.config()
.chain_err(|| "Could not retrieve git configuration data");
let config = repo.config().chain_err(|| "Could not retrieve git configuration data");
let mut remote_url = String::new();
let mut repository_name = String::new();
@ -363,15 +347,10 @@ impl Info { @@ -363,15 +347,10 @@ impl Info {
}
fn get_current_commit_info(repo: &Repository) -> Result<CommitInfo> {
let head = repo
.head()
.chain_err(|| "Error while retrieving reference information")?;
let head_oid = head
.target()
.ok_or("Error while retrieving reference information")?;
let refs = repo
.references()
.chain_err(|| "Error while retrieving reference information")?;
let head = repo.head().chain_err(|| "Error while retrieving reference information")?;
let head_oid = head.target().ok_or("Error while retrieving reference information")?;
let refs =
repo.references().chain_err(|| "Error while retrieving reference information")?;
let refs_info = refs
.filter_map(|reference| match reference {
Ok(reference) => match (reference.target(), reference.shorthand()) {
@ -398,9 +377,7 @@ impl Info { @@ -398,9 +377,7 @@ impl Info {
let author_email = line.split('\t').collect::<Vec<_>>()[1].to_string();
let author_name = line.split('\t').collect::<Vec<_>>()[2].to_string();
let commit_count = authors.entry(author_email.to_string()).or_insert(0);
author_name_by_email
.entry(author_email.to_string())
.or_insert(author_name);
author_name_by_email.entry(author_email.to_string()).or_insert(author_name);
*commit_count += 1;
total_commits += 1;
}
@ -414,11 +391,7 @@ impl Info { @@ -414,11 +391,7 @@ impl Info {
.into_iter()
.map(|(author, count)| {
(
author_name_by_email
.get(&author)
.unwrap()
.trim_matches('\'')
.to_string(),
author_name_by_email.get(&author).unwrap().trim_matches('\'').to_string(),
count,
count * 100 / total_commits,
)
@ -429,11 +402,8 @@ impl Info { @@ -429,11 +402,8 @@ impl Info {
}
async fn get_git_version_and_username(dir: &str) -> (String, String) {
let version = Command::new("git")
.arg("--version")
.output()
.await
.expect("Failed to execute git.");
let version =
Command::new("git").arg("--version").output().await.expect("Failed to execute git.");
let version = String::from_utf8_lossy(&version.stdout).replace('\n', "");
let username = Command::new("git")
@ -535,9 +505,7 @@ impl Info { @@ -535,9 +505,7 @@ impl Info {
let output = String::from_utf8_lossy(&output.stdout);
let lines = output.to_string();
let size_line = lines
.split('\n')
.find(|line| line.starts_with("size-pack:"));
let size_line = lines.split('\n').find(|line| line.starts_with("size-pack:"));
let repo_size = match size_line {
None => "??",
@ -647,11 +615,8 @@ impl Info { @@ -647,11 +615,8 @@ impl Info {
}
fn get_formatted_subtitle_label(&self, label: &str) -> ColoredString {
let formatted_label = format!(
"{}{} ",
label.color(self.color_set.subtitle),
":".color(self.color_set.colon)
);
let formatted_label =
format!("{}{} ", label.color(self.color_set.subtitle), ":".color(self.color_set.colon));
self.bold(&formatted_label)
}

4
src/onefetch/info_fields.rs

@ -43,9 +43,7 @@ pub enum InfoFields { @@ -43,9 +43,7 @@ pub enum InfoFields {
}
pub fn get_disabled_fields(fields_to_hide: Vec<String>) -> Result<InfoFieldOn> {
let mut disabled_fields = InfoFieldOn {
..Default::default()
};
let mut disabled_fields = InfoFieldOn { ..Default::default() };
for field in fields_to_hide.iter() {
let item = InfoFields::from_str(field.to_lowercase().as_str())

11
src/onefetch/language.rs

@ -339,21 +339,14 @@ impl Language { @@ -339,21 +339,14 @@ impl Language {
let mut languages = tokei::Languages::new();
let required_languages = get_all_language_types();
let tokei_config = Config {
types: Some(required_languages),
..Config::default()
};
let tokei_config = Config { types: Some(required_languages), ..Config::default() };
if !ignored_directories.is_empty() {
let re = Regex::new(r"((.*)+/)+(.*)").unwrap();
let mut v = Vec::with_capacity(ignored_directories.len());
for ignored in ignored_directories {
if re.is_match(&ignored) {
let p = if ignored.starts_with('/') {
"**"
} else {
"**/"
};
let p = if ignored.starts_with('/') { "**" } else { "**/" };
v.push(format!("{}{}", p, ignored));
} else {
v.push(String::from(ignored));

10
src/onefetch/license.rs

@ -6,10 +6,8 @@ use { @@ -6,10 +6,8 @@ use {
const LICENSE_FILES: [&str; 3] = ["LICENSE", "LICENCE", "COPYING"];
static CACHE_DATA: &[u8] = include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/resources/licenses/cache.bin.zstd"
));
static CACHE_DATA: &[u8] =
include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/resources/licenses/cache.bin.zstd"));
const MIN_THRESHOLD: f32 = 0.8;
pub struct Detector {
@ -25,9 +23,7 @@ impl Detector { @@ -25,9 +23,7 @@ impl Detector {
pub fn get_project_license(&self, dir: &str) -> Result<String> {
fn is_license_file<S: AsRef<str>>(file_name: S) -> bool {
LICENSE_FILES
.iter()
.any(|&name| file_name.as_ref().starts_with(name))
LICENSE_FILES.iter().any(|&name| file_name.as_ref().starts_with(name))
}
let mut output = fs::read_dir(dir)

Loading…
Cancel
Save