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

fix(query): validate package name #9370

Merged
merged 7 commits into from
Nov 5, 2024
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
9 changes: 4 additions & 5 deletions crates/turborepo-lib/src/commands/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,10 @@ struct QueryError {
impl QueryError {
fn get_index_from_row_column(query: &str, row: usize, column: usize) -> usize {
let mut index = 0;
for line in query.lines().take(row + 1) {
for line in query.lines().take(row.saturating_sub(1)) {
index += line.len() + 1;
}
index + column
index + column - 1
}
fn new(server_error: ServerError, query: String) -> Self {
let span: Option<SourceSpan> = server_error.locations.first().map(|location| {
Expand Down Expand Up @@ -106,9 +106,8 @@ pub async fn run(
let request = Request::new(&query).variables(variables);

let result = schema.execute(request).await;
if result.errors.is_empty() {
println!("{}", serde_json::to_string_pretty(&result)?);
} else {
println!("{}", serde_json::to_string_pretty(&result)?);
if !result.errors.is_empty() {
for error in result.errors {
let error = QueryError::new(error, query.clone());
eprintln!("{:?}", Report::new(error));
Expand Down
83 changes: 50 additions & 33 deletions crates/turborepo-lib/src/query/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@ mod package;
mod server;
mod task;

use std::{io, sync::Arc};
use std::{
io,
ops::{Deref, DerefMut},
sync::Arc,
};

use async_graphql::{http::GraphiQLSource, *};
use axum::{response, response::IntoResponse};
use itertools::Itertools;
use miette::Diagnostic;
use package::Package;
pub use server::run_server;
Expand Down Expand Up @@ -74,6 +77,19 @@ pub struct Array<T: OutputType> {
length: usize,
}

impl<T: OutputType> Deref for Array<T> {
type Target = [T];
fn deref(&self) -> &Self::Target {
&self.items
}
}

impl<T: OutputType> DerefMut for Array<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.items
}
}
NicholasLYang marked this conversation as resolved.
Show resolved Hide resolved

impl<T: OutputType> FromIterator<T> for Array<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
let items: Vec<_> = iter.into_iter().collect();
Expand Down Expand Up @@ -120,7 +136,7 @@ struct PackagePredicate {
impl PackagePredicate {
fn check_equals(pkg: &Package, field: &PackageFields, value: &Any) -> bool {
match (field, &value.0) {
(PackageFields::Name, Value::String(name)) => pkg.name.as_ref() == name,
(PackageFields::Name, Value::String(name)) => pkg.get_name().as_ref() == name,
(PackageFields::DirectDependencyCount, Value::Number(n)) => {
let Some(n) = n.as_u64() else {
return false;
Expand Down Expand Up @@ -247,7 +263,7 @@ impl PackagePredicate {

fn check_has(pkg: &Package, field: &PackageFields, value: &Any) -> bool {
match (field, &value.0) {
(PackageFields::Name, Value::String(name)) => pkg.name.as_ref() == name,
(PackageFields::Name, Value::String(name)) => pkg.get_name().as_str() == name,
(PackageFields::TaskName, Value::String(name)) => pkg.get_tasks().contains_key(name),
_ => false,
}
Expand Down Expand Up @@ -491,32 +507,36 @@ impl RepositoryQuery {
let mut opts = self.run.opts().clone();
opts.scope_opts.affected_range = Some((base, head));

Ok(RunBuilder::calculate_filtered_packages(
let mut packages = RunBuilder::calculate_filtered_packages(
self.run.repo_root(),
&opts,
self.run.pkg_dep_graph(),
self.run.scm(),
self.run.root_turbo_json(),
)?
.into_iter()
.map(|(package, reason)| ChangedPackage {
package: Package {
run: self.run.clone(),
name: package,
},
reason: reason.into(),
.map(|(package, reason)| {
Ok(ChangedPackage {
package: Package::new(self.run.clone(), package)?,
reason: reason.into(),
})
})
.filter(|package| filter.as_ref().map_or(true, |f| f.check(&package.package)))
.sorted_by(|a, b| a.package.name.cmp(&b.package.name))
.collect())
.filter(|package: &Result<ChangedPackage, Error>| {
let Ok(package) = package.as_ref() else {
return true;
};
filter.as_ref().map_or(true, |f| f.check(&package.package))
})
.collect::<Result<Array<_>, _>>()?;

packages.sort_by(|a, b| a.package.get_name().cmp(b.package.get_name()));
Ok(packages)
}

/// Gets a single package by name
async fn package(&self, name: String) -> Result<Package, Error> {
let name = PackageName::from(name);
Ok(Package {
run: self.run.clone(),
name,
})
Package::new(self.run.clone(), name)
}

async fn version(&self) -> &'static str {
Expand All @@ -536,29 +556,26 @@ impl RepositoryQuery {
/// Gets a list of packages that match the given filter
async fn packages(&self, filter: Option<PackagePredicate>) -> Result<Array<Package>, Error> {
let Some(filter) = filter else {
return Ok(self
let mut packages = self
.run
.pkg_dep_graph()
.packages()
.map(|(name, _)| Package {
run: self.run.clone(),
name: name.clone(),
})
.sorted_by(|a, b| a.name.cmp(&b.name))
.collect());
.map(|(name, _)| Package::new(self.run.clone(), name.clone()))
.collect::<Result<Array<_>, _>>()?;
packages.sort_by(|a, b| a.get_name().cmp(b.get_name()));
return Ok(packages);
};

Ok(self
let mut packages = self
.run
.pkg_dep_graph()
.packages()
.map(|(name, _)| Package {
run: self.run.clone(),
name: name.clone(),
})
.filter(|pkg| filter.check(pkg))
.sorted_by(|a, b| a.name.cmp(&b.name))
.collect())
.map(|(name, _)| Package::new(self.run.clone(), name.clone()))
.filter(|pkg| pkg.as_ref().map_or(false, |pkg| filter.check(pkg)))
.collect::<Result<Array<_>, _>>()?;
packages.sort_by(|a, b| a.get_name().cmp(b.get_name()));

Ok(packages)
}
}

Expand Down
22 changes: 20 additions & 2 deletions crates/turborepo-lib/src/query/package.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,29 @@ use crate::{

#[derive(Clone)]
pub struct Package {
pub run: Arc<Run>,
pub name: PackageName,
run: Arc<Run>,
name: PackageName,
}

impl Package {
pub fn new(run: Arc<Run>, name: PackageName) -> Result<Self, Error> {
run.pkg_dep_graph()
.package_info(&name)
.ok_or_else(|| Error::PackageNotFound(name.clone()))?;

Ok(Self { run, name })
}

pub fn run(&self) -> &Arc<Run> {
&self.run
}

/// This uses a different naming convention because we already have a
/// `name` resolver defined for GraphQL
pub fn get_name(&self) -> &PackageName {
&self.name
}
NicholasLYang marked this conversation as resolved.
Show resolved Hide resolved

pub fn get_tasks(&self) -> HashMap<String, Spanned<String>> {
self.run
.pkg_dep_graph()
Expand Down
Loading
Loading