Skip to content

add dependency feature #304

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

Merged
merged 31 commits into from
Nov 7, 2020
Merged
Show file tree
Hide file tree
Changes from 26 commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
5a9ec69
begin dependency feature
Luke-zhang-04 Nov 1, 2020
1c65108
fix get_deps() implementation --WIP
o2sh Nov 1, 2020
cd63dae
match on Option after parsing number of deps
o2sh Nov 1, 2020
596f2cf
rename dependencies --> deps
o2sh Nov 1, 2020
6581979
fix typo
o2sh Nov 1, 2020
230088d
editorconfig did stuff
Luke-zhang-04 Nov 4, 2020
1c62703
feat: add dependency insights field
Luke-zhang-04 Nov 4, 2020
582b246
feat: add support for go modules
Luke-zhang-04 Nov 4, 2020
d79f447
feat: add support for pip
Luke-zhang-04 Nov 4, 2020
bd98e3a
rust fmt
Luke-zhang-04 Nov 4, 2020
774d2e5
Merge branch 'master' of https://github.com/o2sh/onefetch
Luke-zhang-04 Nov 4, 2020
23042b4
rust fmt
Luke-zhang-04 Nov 4, 2020
deefcb5
feat: add support for yarn
Luke-zhang-04 Nov 4, 2020
f5ea1f7
feat: add support for Cargo
Luke-zhang-04 Nov 4, 2020
b966cc5
cargo fmt
Luke-zhang-04 Nov 4, 2020
369506c
split deps into multiple files and replace Option with Result for bet…
o2sh Nov 5, 2020
5bb1e05
docs: adding a new package manager
Luke-zhang-04 Nov 5, 2020
afc7ef0
change i32 in `package_parsers` to uint
Luke-zhang-04 Nov 5, 2020
9311d49
fix: detect `yarn.lock` with absolute directory
Luke-zhang-04 Nov 5, 2020
a19ced8
refactor: simplify regex in package parsers
Luke-zhang-04 Nov 5, 2020
d60ecfe
catch dependencies instead of `.unwrap()`
Luke-zhang-04 Nov 5, 2020
6fdb61d
refactor: move `is_package_file` to Detector impl`
Luke-zhang-04 Nov 5, 2020
0b8caa0
refactor: use `map.contains_key()` instead of iterating
Luke-zhang-04 Nov 5, 2020
3d94170
add a comment
Luke-zhang-04 Nov 5, 2020
8824206
make contributing clearer
Luke-zhang-04 Nov 5, 2020
978c9c8
Update CONTRIBUTING.md
o2sh Nov 5, 2020
1d6d95b
fix: handle Cargo.toml without dependency field
Luke-zhang-04 Nov 6, 2020
483faa6
Merge branch 'master' of https://github.com/Luke-zhang-04/onefetch
Luke-zhang-04 Nov 6, 2020
aa62542
Merge branch 'master' of https://github.com/o2sh/onefetch
Luke-zhang-04 Nov 6, 2020
2677401
update CONTRIBUTING.md
Luke-zhang-04 Nov 6, 2020
ba97550
fix: check for `=>` in go.mod
Luke-zhang-04 Nov 6, 2020
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
55 changes: 50 additions & 5 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
Thank you for your interest in contributing to onefetch! Whether it's a bug report, new feature, correction, or additional
Thank you for your interest in contributing to onefetch! Whether it's a bug report, new feature, correction, or additional
documentation, we greatly value feedback and contributions from our community.

Please read through this document before submitting any issues or pull requests to ensure we have all the necessary
Please read through this document before submitting any issues or pull requests to ensure we have all the necessary
information to effectively respond to your bug report or contribution.

# Contributing Guidelines
Expand All @@ -11,13 +11,14 @@ information to effectively respond to your bug report or contribution.
* [Finding contributions to work on](#finding-contributions-to-work-on)
* [Adding support for a new language](#adding-support-for-a-new-language)
* [Ascii logo](#ascii-logo)
* [Adding support for a new package manager](#adding-support-for-a-new-package-manager)
* [Project-specific notes](#project-specific-notes)

## Reporting Bugs / Feature Requests

We welcome you to use the GitHub issue tracker to report bugs or suggest features.

When filing an issue, please check [existing open](https://github.com/o2sh/onefetch/issues), or [recently closed](https://github.com/o2sh/onefetch/issues?utf8=%E2%9C%93&q=is%3Aissue%20is%3Aclosed%20), issues to make sure somebody else hasn't already
When filing an issue, please check [existing open](https://github.com/o2sh/onefetch/issues), or [recently closed](https://github.com/o2sh/onefetch/issues?utf8=%E2%9C%93&q=is%3Aissue%20is%3Aclosed%20), issues to make sure somebody else hasn't already
reported the issue. Please try to include as much information as you can. Details like these are incredibly useful:

* A reproducible test case or series of steps
Expand All @@ -42,7 +43,7 @@ To send us a pull request, please:
5. Send us a pull request, answering any default questions in the pull request interface.
6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation.

GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and
GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and
[creating a pull request](https://help.github.com/articles/creating-a-pull-request/).

### Finding contributions to work on
Expand All @@ -64,7 +65,7 @@ The first item `CSharp` corresponds to the name of the language as defined in to
#### Ascii logo

```
{4} _{1} _ _
{4} _{1} _ _
{4} _|_{1}(_|/ \
{0} o{4}| {1} _|\_/

Expand Down Expand Up @@ -101,6 +102,50 @@ Remarks:
{ CSharp, "csharp.ascii", "C#", define_colors!( Colors { basic_colors: vec![Color::Blue, Color::Magenta] , true_colors: Some(vec![Color::TrueColor{ r:0, g:255, b:255 }, Color::TrueColor{ r:255, g:0, b:255 } ] ) } ), "c#" },
```

### Adding support for a new package manager

Any package manager is supported, as long as there is a file you can get the dependencies from.

To add a new package manager, make sure you follow these steps:
1. in `src/onefetch/deps/package_manager.rs`, add the name of your package manager to the `PackageManager` enum
```rust
pub enum PackageManager {
// ...
Cargo,
// ...
}
```

2. in `src/onefetch/deps/package_manager.rs`, add a `writeln` macro call to the `fmt` function
```rust
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match *self {
// ...
PackageManager::Cargo => write!(f, "Cargo"),
// ...
}
}
```

3. in `src/onefetch/deps/package_parser.rs`, add a function whose name corresponds to your manager. This function should take in a `string` as the contents of the package manager file, and return `usize` as the number of dependencies
```rust
pub fn cargo(contents: &str) -> Result<usize> {
let parsed = contents.parse::<Value>()?;

Ok(parsed["dependencies"].as_table().unwrap().len())
}
```

4. in `src/onefetch/deps/mod.rs`, in the `new` method of the `DependencyDetector` impl, insert your new package managers information
```rust
package_managers.insert(
String::from("Cargo.toml"), // File name

// Parser function, then the corresponding element from the PackageManager enum
(package_parser::cargo, package_manager::PackageManager::Cargo),
);
```

### Project-specific notes

- Please ensure your changes are formatted according to `cargo fmt`.
Expand Down
20 changes: 14 additions & 6 deletions Cargo.lock

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

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ priority = "optional"
color_quant = "1.1" # Use version required by image
colored= "2.0.0"
git2 = { version = "0.13.12", default-features = false }
json = "0.12.4"
tokei = "12.0.0"
askalono = "0.4.3"
bytecount = "0.6.0"
Expand All @@ -30,6 +31,7 @@ strum = { version = "0.19.5", features = ["derive"] }
image = "0.23.11"
regex = "1"
error-chain = "0.12"
toml = "0.5.7"

[target.'cfg(windows)'.dependencies]
ansi_term = "0.12"
Expand Down
2 changes: 1 addition & 1 deletion src/onefetch/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ impl Cli {
Arg::with_name("off")
.long("off")
.help("Only shows the info lines.")
.conflicts_with_all(&["image", "ascii-language", "ascii-input"]),
.conflicts_with_all(&["image", "ascii-language", "ascii-input"]),
).get_matches();

let no_bold = matches.is_present("no-bold");
Expand Down
82 changes: 82 additions & 0 deletions src/onefetch/deps/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
use {
crate::onefetch::error::*,
std::collections::HashMap,
std::{ffi::OsStr, fs},
};

mod package_manager;
mod package_parser;

type DependencyParser = fn(&str) -> Result<usize>;

pub struct DependencyDetector {
package_managers: HashMap<String, (DependencyParser, package_manager::PackageManager)>,
}

impl DependencyDetector {
pub fn new() -> Self {
let mut package_managers: HashMap<
String,
(DependencyParser, package_manager::PackageManager),
> = HashMap::new();

package_managers.insert(
String::from("Cargo.toml"),
(package_parser::cargo, package_manager::PackageManager::Cargo),
);
package_managers.insert(
String::from("go.mod"),
(package_parser::go_modules, package_manager::PackageManager::GoModules),
);
package_managers.insert(
String::from("package.json"),
(package_parser::npm, package_manager::PackageManager::Npm),
);
package_managers.insert(
String::from("requirements.txt"),
(package_parser::pip, package_manager::PackageManager::Pip),
);

DependencyDetector { package_managers }
}

pub fn get_deps_info(&self, dir: &str) -> Result<String> {
let deps = fs::read_dir(dir)
.chain_err(|| "Could not read directory")?
.filter_map(std::result::Result::ok)
.map(|entry| entry.path())
.filter(|entry| {
entry.is_file()
&& entry
.file_name()
.map(OsStr::to_string_lossy)
.map(|s| self.package_managers.contains_key(s.as_ref()))
.unwrap_or_default()
})
.map(|entry| {
let (parser, found_package_manager) =
&self.package_managers[entry.file_name().unwrap().to_str().unwrap()];
let contents = fs::read_to_string(entry)?;
let number_of_deps = parser(&contents)?;
let used_package_manager;

// If a yarn.lock file is found and the current package manager
// is NPM, change the package manager to Yarn instead
if found_package_manager == &package_manager::PackageManager::Npm
&& std::path::Path::new(&format!("{}yarn.lock", dir)).exists()
{
used_package_manager = &package_manager::PackageManager::Yarn;
} else {
used_package_manager = found_package_manager;
}

Ok(format!("{} ({})", number_of_deps, used_package_manager))
})
.filter_map(Result::ok)
.collect::<Vec<_>>();

let output = deps.join(", ");

Ok(output)
}
}
20 changes: 20 additions & 0 deletions src/onefetch/deps/package_manager.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#[derive(PartialEq)]
pub enum PackageManager {
Cargo,
GoModules,
Npm,
Pip,
Yarn,
}

impl std::fmt::Display for PackageManager {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match *self {
PackageManager::Cargo => write!(f, "Cargo"),
PackageManager::GoModules => write!(f, "Go Modules"),
PackageManager::Npm => write!(f, "Npm"),
PackageManager::Pip => write!(f, "Pip"),
PackageManager::Yarn => write!(f, "Yarn"),
}
}
}
26 changes: 26 additions & 0 deletions src/onefetch/deps/package_parser.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
use crate::onefetch::error::*;
use {regex::Regex, toml::Value};

pub fn cargo(contents: &str) -> Result<usize> {
let parsed = contents.parse::<Value>()?;

Ok(parsed["dependencies"].as_table().unwrap().len())
}

pub fn go_modules(contents: &str) -> Result<usize> {
let count = Regex::new(r"v[0-9]+")?.find_iter(contents).count();

Ok(count)
}

pub fn npm(contents: &str) -> Result<usize> {
let parsed = json::parse(contents)?;

Ok(parsed["dependencies"].len())
}

pub fn pip(contents: &str) -> Result<usize> {
let count = Regex::new(r"(^|\n)[A-z]+")?.find_iter(contents).count();

Ok(count)
}
3 changes: 3 additions & 0 deletions src/onefetch/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ error_chain! {
ParseIntError(::std::num::ParseIntError);
Image(image::error::ImageError);
Utf8(std::string::FromUtf8Error);
Json(json::Error);
Regex(regex::Error);
Toml(toml::de::Error);
}
}

Expand Down
14 changes: 13 additions & 1 deletion src/onefetch/info.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use {
crate::onefetch::{
cli::Cli, commit_info::CommitInfo, error::*, language::Language, license::Detector,
cli::Cli, commit_info::CommitInfo, deps, error::*, language::Language, license::Detector,
text_color::TextColor,
},
colored::{Color, ColoredString, Colorize},
Expand All @@ -18,6 +18,7 @@ pub struct Info {
creation_date: String,
pub dominant_language: Language,
languages: Vec<(Language, f64)>,
dependencies: String,
authors: Vec<(String, usize, usize)>,
last_change: String,
repo_url: String,
Expand Down Expand Up @@ -114,6 +115,15 @@ impl std::fmt::Display for Info {
)?;
}

if !self.config.disabled_fields.dependencies && !self.dependencies.is_empty() {
writeln!(
f,
"{}{}",
&self.get_formatted_subtitle_label("Dependencies"),
&self.dependencies.color(self.color_set.info),
)?;
}

if !self.config.disabled_fields.authors && !self.authors.is_empty() {
let title = if self.authors.len() > 1 { "Authors" } else { "Author" };

Expand Down Expand Up @@ -222,6 +232,7 @@ impl Info {
let last_change = Info::get_date_of_last_commit(&git_history);
let project_license = Detector::new()?.get_project_license(workdir_str);
let dominant_language = Language::get_dominant_language(&languages_stats);
let dependencies = deps::DependencyDetector::new().get_deps_info(workdir_str)?;
let colors = Info::get_colors(
&config.ascii_language,
&dominant_language,
Expand All @@ -239,6 +250,7 @@ impl Info {
creation_date: creation_date?,
dominant_language,
languages: languages_stats,
dependencies,
authors,
last_change: last_change?,
repo_url: repository_url,
Expand Down
3 changes: 3 additions & 0 deletions src/onefetch/info_fields.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ pub struct InfoFieldOn {
pub head: bool,
pub version: bool,
pub created: bool,
pub dependencies: bool,
pub languages: bool,
pub authors: bool,
pub last_change: bool,
Expand All @@ -30,6 +31,7 @@ pub enum InfoFields {
HEAD,
Version,
Created,
Dependencies,
Languages,
Authors,
LastChange,
Expand All @@ -55,6 +57,7 @@ pub fn get_disabled_fields(fields_to_hide: Vec<String>) -> Result<InfoFieldOn> {
InfoFields::HEAD => disabled_fields.head = true,
InfoFields::Version => disabled_fields.version = true,
InfoFields::Created => disabled_fields.created = true,
InfoFields::Dependencies => disabled_fields.dependencies = true,
InfoFields::Languages => disabled_fields.languages = true,
InfoFields::Authors => disabled_fields.authors = true,
InfoFields::LastChange => disabled_fields.last_change = true,
Expand Down
Loading