Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add format flag with json support #126

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 78 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ num_cpus = "1.8.0"
ignore = "0.4.2"
edit-distance = "2.0.1"
smallvec = "0.6.5"
serde = "1.0.101"
serde_json = "1.0.41"
serde_derive = "1.0.101"

[profile.release]
incremental = false
Expand Down
7 changes: 5 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
extern crate memchr;
extern crate smallvec;
#[macro_use]
extern crate serde_derive;

use std::path::Path;
use std::fs::File;
Expand All @@ -11,7 +13,7 @@ use memchr::memchr;
use smallvec::*;

// Why is it called partialEq?
#[derive(Debug, PartialEq, Default, Clone)]
#[derive(Debug, PartialEq, Default, Copy, Clone, Serialize)]
pub struct Count {
pub code: u32,
pub comment: u32,
Expand All @@ -28,6 +30,7 @@ impl Count {
}
}

#[derive(Serialize, Copy, Clone)]
pub struct LangTotal {
pub files: u32,
pub count: Count,
Expand All @@ -37,7 +40,7 @@ pub struct LangTotal {
// We can probably do something with the encoding crate where we decode
// as ascii, and then use unsafe_from_utf8. If decoding fails,
// we catch it and just use the safe from_utf8 as we're doing now.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Clone)]
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Clone, Serialize)]
pub enum Lang {
ActionScript,
Ada,
Expand Down
51 changes: 49 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ extern crate num_cpus;
extern crate regex;
extern crate ignore;
extern crate edit_distance;
extern crate serde_json;

use clap::{Arg, App, AppSettings};
use ignore::WalkBuilder;
Expand Down Expand Up @@ -99,6 +100,23 @@ impl FromStr for Sort {
}
}

#[derive(PartialEq)]
enum Format {
Table,
JSON
}

impl FromStr for Format {
type Err = Option<String>;
fn from_str(s: &str) -> Result<Format, Self::Err> {
match s {
"table" | "Table" => Ok(Format::Table),
"json" | "Json" | "JSON" => Ok(Format::JSON),
_ => Err(None)
}
}
}

// TODO(cgag): tune smallvec array sizes
// TODO(cgag): try smallstring
// TODO(cgag): more tests for nested comments
Expand Down Expand Up @@ -133,6 +151,12 @@ fn main() {
.value_name("COLUMN")
.takes_value(true)
.help("Column to sort by"))
.arg(Arg::with_name("format")
.required(false)
.long("format")
.short("f")
.takes_value(true)
.help("The output format, defaults to 'table' and accepts 'json'."))
.arg(Arg::with_name("unrestricted")
.required(false)
.multiple(true)
Expand Down Expand Up @@ -169,6 +193,18 @@ fn main() {
None => Sort::Code,
};

let format = match matches.value_of("format") {
Some(string) => match Format::from_str(string) {
Ok(format) => format,
Err(_) => {
println!("Error: invalid value for --format: '{}'", string);
println!(" Hint: legal values are Table and Json");
return
}
},
None => Format::Table,
};

let by_file: bool = matches.is_present("files");

if by_file && (sort == Sort::Language || sort == Sort::Files) {
Expand Down Expand Up @@ -339,7 +375,10 @@ fn main() {
Sort::Lines => totals_by_lang.sort_by(|&(_, c1), &(_, c2)| c2.count.lines.cmp(&c1.count.lines)),
}

print_totals_by_lang(&linesep, &totals_by_lang);
match format {
Format::Table => print_totals_by_lang_table(&linesep, &totals_by_lang),
Format::JSON => print_totals_by_lang_json(&totals_by_lang),
}
}

}
Expand All @@ -357,7 +396,15 @@ fn str_repeat(s: &str, n: usize) -> String {
std::iter::repeat(s).take(n).collect::<Vec<_>>().join("")
}

fn print_totals_by_lang(linesep: &str, totals_by_lang: &[(&&Lang, &LangTotal)]) {
fn print_totals_by_lang_json(totals_by_lang: &[(&&Lang, &LangTotal)]) {
let mut langs = std::collections::HashMap::new();
for (l, t) in totals_by_lang {
langs.insert((***l).to_string(), **t);
}
println!("{}", serde_json::to_string(&langs).unwrap());
}

fn print_totals_by_lang_table(linesep: &str, totals_by_lang: &[(&&Lang, &LangTotal)]) {
println!("{}", linesep);
println!(" {0: <17} {1: >8} {2: >12} {3: >12} {4: >12} {5: >12}",
"Language",
Expand Down