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 deps tree functionality #4172

Merged
merged 6 commits into from
Jan 20, 2025
Merged
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
38 changes: 38 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,44 @@
when "Cmd/Ctrl + K", "s" or "/" is pressed.
([Sambit Sahoo](https://github.com/soulsam480))

- `gleam deps` now supports `tree` operation that lists the dependency tree.

```markdown
Usage: gleam deps tree [OPTIONS]

Options:
-p, --package <PACKAGE> Package to be used as the root of the tree
-i, --invert <PACKAGE> Invert the tree direction and focus on the given package
-h, --help Print help
```
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would be nice to show the format of the output here!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've added a sample output, not sure if this is what we're looking for. Please let me know.


For example, if the root project (`project_a`) depends on `package_b` and `package_c`, and `package_c` also depends on `package_b`, the output will be:


```markdown
$ gleam deps tree

project_a v1.0.0
├── package_b v0.52.0
└── package_c v1.2.0
└── package_b v0.52.0

$ gleam deps tree --package package_c

package_c v1.2.0
└── package_b v0.52.0

$ gleam deps tree --invert package_b

package_b v0.52.0
├── package_c v1.2.0
│ └── project_a v1.0.0
└── project_a v1.0.0

```

([Ramkarthik Krishnamurthy](https://github.com/ramkarthik))

### Language server

- The language server can now generate the definition of functions that do not
Expand Down
141 changes: 138 additions & 3 deletions compiler-cli/src/dependencies.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::{
};

use camino::{Utf8Path, Utf8PathBuf};
use ecow::EcoString;
use ecow::{eco_format, EcoString};
use flate2::read::GzDecoder;
use futures::future;
use gleam_core::{
Expand Down Expand Up @@ -32,12 +32,54 @@ use crate::{
cli,
fs::{self, ProjectIO},
http::HttpClient,
TreeOptions,
};

struct Symbols {
down: &'static str,
tee: &'static str,
ell: &'static str,
right: &'static str,
}

static UTF8_SYMBOLS: Symbols = Symbols {
down: "│",
tee: "├",
ell: "└",
right: "─",
};

pub fn list() -> Result<()> {
let (_, _, manifest) = get_manifest_details()?;
list_manifest_packages(std::io::stdout(), manifest)
}

pub fn tree(options: TreeOptions) -> Result<()> {
let (project, config, manifest) = get_manifest_details()?;

// Initialize the root package since it is not part of the manifest
let root_package = ManifestPackage {
build_tools: vec![],
name: config.name.clone(),
requirements: config.all_direct_dependencies()?.keys().cloned().collect(),
version: config.version.clone(),
source: ManifestPackageSource::Local {
path: project.clone(),
},
otp_app: None,
};

// Get the manifest packages and add the root package to the vec
let mut packages = manifest.packages.iter().cloned().collect_vec();
packages.append(&mut vec![root_package.clone()]);

list_package_and_dependencies_tree(std::io::stdout(), options, packages.clone(), config.name)
}

fn get_manifest_details() -> Result<(Utf8PathBuf, PackageConfig, Manifest)> {
let runtime = tokio::runtime::Runtime::new().expect("Unable to start Tokio async runtime");
let project = fs::get_project_root(fs::get_current_directory()?)?;
let paths = ProjectPaths::new(project);
let paths = ProjectPaths::new(project.clone());
let config = crate::config::root_config()?;
let (_, manifest) = get_manifest(
&paths,
Expand All @@ -48,7 +90,7 @@ pub fn list() -> Result<()> {
UseManifest::Yes,
Vec::new(),
)?;
list_manifest_packages(std::io::stdout(), manifest)
Ok((project, config, manifest))
}

fn list_manifest_packages<W: std::io::Write>(mut buffer: W, manifest: Manifest) -> Result<()> {
Expand All @@ -62,6 +104,99 @@ fn list_manifest_packages<W: std::io::Write>(mut buffer: W, manifest: Manifest)
})
}

fn list_package_and_dependencies_tree<W: std::io::Write>(
mut buffer: W,
options: TreeOptions,
packages: Vec<ManifestPackage>,
root_package_name: EcoString,
) -> Result<()> {
let mut invert = false;

let package: Option<&ManifestPackage> = if let Some(input_package_name) = options.package {
packages.iter().find(|p| p.name == input_package_name)
} else if let Some(input_package_name) = options.invert {
invert = true;
packages.iter().find(|p| p.name == input_package_name)
} else {
packages.iter().find(|p| p.name == root_package_name)
};

if let Some(package) = package {
let tree = Vec::from([eco_format!("{0} v{1}", package.name, package.version)]);
let tree = list_dependencies_tree(
tree.clone(),
package.clone(),
packages,
EcoString::new(),
invert,
);

tree.iter()
.try_for_each(|line| writeln!(buffer, "{}", line))
.map_err(|e| Error::StandardIo {
action: StandardIoAction::Write,
err: Some(e.kind()),
})
} else {
writeln!(buffer, "Package not found. Please check the package name.").map_err(|e| {
Error::StandardIo {
action: StandardIoAction::Write,
err: Some(e.kind()),
}
})
}
}

fn list_dependencies_tree(
mut tree: Vec<EcoString>,
package: ManifestPackage,
packages: Vec<ManifestPackage>,
accum: EcoString,
invert: bool,
) -> Vec<EcoString> {
let dependencies = packages
.iter()
.filter(|p| {
(invert && p.requirements.contains(&package.name))
|| (!invert && package.requirements.contains(&p.name))
})
.cloned()
.collect_vec();

let dependencies = dependencies.iter().sorted().enumerate();

let deps_length = dependencies.len();
for (index, dependency) in dependencies {
let is_last = index == deps_length - 1;
let prefix = if is_last {
UTF8_SYMBOLS.ell
} else {
UTF8_SYMBOLS.tee
};

tree.push(eco_format!(
"{0}{1}{2}{2} {3} v{4}",
accum.clone(),
prefix,
UTF8_SYMBOLS.right,
dependency.name,
dependency.version
));

let accum = accum.clone() + (if !is_last { UTF8_SYMBOLS.down } else { " " }) + " ";

tree = list_dependencies_tree(
tree.clone(),
dependency.clone(),
packages.clone(),
accum.clone(),
invert,
);
}

tree
}

#[derive(Debug, Clone, Copy)]
pub enum UseManifest {
Yes,
Expand Down
Loading
Loading