Skip to content

Commit

Permalink
feat(turborepo): Calculate package inference (#5406)
Browse files Browse the repository at this point in the history
Co-authored-by: Greg Soltis <Greg Soltis>
Co-authored-by: Nicholas Yang <nicholas.yang@vercel.com>
Co-authored-by: Alexander Lyon <arlyon@me.com>
  • Loading branch information
3 people authored Jul 10, 2023
1 parent a2b1fd4 commit 4314d1d
Show file tree
Hide file tree
Showing 6 changed files with 91 additions and 12 deletions.
24 changes: 20 additions & 4 deletions crates/turborepo-lib/src/opts.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#![allow(dead_code)]
use anyhow::{anyhow, Result};
use serde::{Deserialize, Serialize};
use turbopath::AnchoredSystemPathBuf;

use crate::{
cli::{Command, DryRunMode, EnvMode, LogPrefix, RunArgs},
Expand Down Expand Up @@ -51,11 +52,11 @@ impl<'a> TryFrom<&'a Args> for Opts<'a> {
};
let run_opts = RunOpts::try_from(run_args.as_ref())?;
let cache_opts = CacheOpts::from(run_args.as_ref());

let scope_opts = ScopeOpts::try_from(run_args.as_ref())?;
Ok(Self {
run_opts,
cache_opts,
scope_opts: ScopeOpts::default(),
scope_opts,
runcache_opts: RunCacheOpts::default(),
})
}
Expand Down Expand Up @@ -154,5 +155,20 @@ fn parse_concurrency(concurrency_raw: &str) -> Result<u32> {
}
}

#[derive(Debug, Default)]
pub struct ScopeOpts {}
#[derive(Debug)]
pub struct ScopeOpts {
pub pkg_inference_root: Option<AnchoredSystemPathBuf>,
}

impl<'a> TryFrom<&'a RunArgs> for ScopeOpts {
type Error = anyhow::Error;

fn try_from(args: &'a RunArgs) -> std::result::Result<Self, Self::Error> {
let pkg_inference_root = args
.pkg_inference_root
.as_ref()
.map(AnchoredSystemPathBuf::from_raw)
.transpose()?;
Ok(Self { pkg_inference_root })
}
}
2 changes: 1 addition & 1 deletion crates/turborepo-lib/src/package_graph/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ impl PackageGraph {
impl fmt::Display for WorkspaceName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
WorkspaceName::Root => f.write_str("Root workspace"),
WorkspaceName::Root => f.write_str("//"),
WorkspaceName::Other(other) => f.write_str(other),
}
}
Expand Down
10 changes: 7 additions & 3 deletions crates/turborepo-lib/src/run/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,6 @@ impl Run {

#[cfg(test)]
mod test {
use std::fs;

use anyhow::Result;
use tempfile::tempdir;
Expand All @@ -144,22 +143,27 @@ mod test {
};

#[tokio::test]
#[ignore]
async fn test_run() -> Result<()> {
let dir = tempdir()?;
let repo_root = AbsoluteSystemPathBuf::try_from(dir.path())?;
let mut args = Args::default();
// Daemon does not work with run stub yet
let run_args = RunArgs {
no_daemon: true,
pkg_inference_root: Some(["apps", "my-app"].join(std::path::MAIN_SEPARATOR_STR)),
..Default::default()
};
args.command = Some(Command::Run(Box::new(run_args)));

let ui = UI::infer();

// Add package.json
fs::write(repo_root.join_component("package.json"), "{}")?;
repo_root
.join_component("package.json")
.create_with_contents("{\"workspaces\": [\"apps/*\"]}")?;
repo_root
.join_component("package-lock.json")
.create_with_contents("")?;

let base = CommandBase::new(args, repo_root, get_version(), ui)?;
let mut run = Run::new(base);
Expand Down
53 changes: 53 additions & 0 deletions crates/turborepo-lib/src/run/scope/filter.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
use tracing::debug;
use turbopath::{AbsoluteSystemPath, AnchoredSystemPathBuf};

use crate::package_graph;

pub struct PackageInference {
package_name: Option<String>,
directory_root: AnchoredSystemPathBuf,
}

impl PackageInference {
// calculate, based on the directory that global turbo was invoked in,
// the pieces of a filter spec that we will infer. If turbo was invoked
// somewhere between the root and packages, scope turbo invocations to the
// packages below where turbo was invoked. If turbo was invoked at or within
// a particular package, scope the turbo invocation to just that package.
pub fn calculate(
turbo_root: &AbsoluteSystemPath,
pkg_inference_path: &AnchoredSystemPathBuf,
pkg_graph: &package_graph::PackageGraph,
) -> Self {
debug!(
"Using {} as a basis for selecting pacakges",
pkg_inference_path
);
let full_inference_path = turbo_root.resolve(pkg_inference_path);
for (workspace_name, workspace_entry) in pkg_graph.workspaces() {
let pkg_path = turbo_root.resolve(&workspace_entry.package_json_path());
let inferred_path_is_below = pkg_path.contains(&full_inference_path);
// We skip over the root package as the inferred path will always be below it
if inferred_path_is_below && (&pkg_path as &AbsoluteSystemPath) != turbo_root {
// set both. The user might have set a parent directory filter,
// in which case we *should* fail to find any packages, but we should
// do so in a consistent manner
return Self {
package_name: Some(workspace_name.to_string()),
directory_root: workspace_entry.package_json_path().clone(),
};
}
let inferred_path_is_between_root_and_pkg = full_inference_path.contains(&pkg_path);
if inferred_path_is_between_root_and_pkg {
// we've found *some* package below our inference directory. We can stop now and
// conclude that we're looking for all packages in a
// subdirectory
break;
}
}
Self {
package_name: None,
directory_root: pkg_inference_path.to_owned(),
}
}
}
Original file line number Diff line number Diff line change
@@ -1,17 +1,23 @@
mod filter;

use std::collections::HashSet;

use anyhow::Result;
use filter::PackageInference;
use tracing::warn;
use turborepo_scm::SCM;

use crate::{commands::CommandBase, opts::ScopeOpts, package_graph};

pub fn resolve_packages(
_opts: &ScopeOpts,
_base: &CommandBase,
_ctx: &package_graph::PackageGraph,
opts: &ScopeOpts,
base: &CommandBase,
pkg_graph: &package_graph::PackageGraph,
_scm: &SCM,
) -> Result<HashSet<String>> {
let _pkg_inference = opts.pkg_inference_root.as_ref().map(|pkg_inference_path| {
PackageInference::calculate(&base.repo_root, &pkg_inference_path, pkg_graph)
});
warn!("resolve packages not implemented yet");
Ok(HashSet::new())
}
2 changes: 1 addition & 1 deletion crates/turborepo-paths/src/absolute_system_path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use crate::{
AbsoluteSystemPathBuf, AnchoredSystemPath, AnchoredSystemPathBuf, PathError, RelativeUnixPath,
};

#[derive(Debug)]
#[derive(Debug, PartialEq, Eq)]
pub struct AbsoluteSystemPath(Utf8Path);

impl ToOwned for AbsoluteSystemPath {
Expand Down

0 comments on commit 4314d1d

Please sign in to comment.