Skip to content

Commit

Permalink
chore(core): fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
FrozenPandaz committed Sep 5, 2024
1 parent f601907 commit c453042
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 54 deletions.
12 changes: 7 additions & 5 deletions packages/nx/src/native/cache/expand_outputs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,18 +72,20 @@ where
Ok(found_paths)
}

fn partition_globs_into_map(globs: Vec<String>) -> HashMap<String, Vec<String>> {
fn partition_globs_into_map(globs: Vec<String>) -> anyhow::Result<HashMap<String, Vec<String>>> {
globs
.iter()
.map(|glob| partition_glob(glob))
// Right now we have an iterator where each item is (root: String, patterns: String[]).
// We want a singular root, with the patterns mapped to it.
.fold(
HashMap::<String, Vec<String>>::new(),
|mut map, (root, patterns)| {
Ok(HashMap::<String, Vec<String>>::new()),
|map_result, parsed_glob| {
let mut map = map_result?;
let (root, patterns) = parsed_glob?;
let entry = map.entry(root).or_insert(vec![]);
entry.extend(patterns);
map
Ok(map)
},
)
}
Expand Down Expand Up @@ -117,7 +119,7 @@ pub fn get_files_for_outputs(
}

if !globs.is_empty() {
let partitioned_globs = partition_globs_into_map(globs);
let partitioned_globs = partition_globs_into_map(globs)?;
for (root, patterns) in partitioned_globs {
let root_path = directory.join(&root);
let glob_set = build_glob_set(&patterns)?;
Expand Down
21 changes: 10 additions & 11 deletions packages/nx/src/native/cache/validate_outputs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,27 +13,26 @@ fn is_missing_prefix(output: &str) -> bool {

#[napi]
pub fn validate_outputs(outputs: Vec<String>) -> anyhow::Result<()> {
let (missing_prefix, workspace_globs) = outputs.iter().fold(
(vec![], vec![]),
|(mut missing_prefix, mut workspace_globs), output| {
if is_missing_prefix(output) {
missing_prefix.push(output);
}
let outputs_len = outputs.len();
let mut missing_prefix = Vec::with_capacity(outputs_len);
let mut workspace_globs = Vec::with_capacity(outputs_len);

for output in outputs.iter() {
if is_missing_prefix(output) {
missing_prefix.push(output);
} else {
for prefix in ALLOWED_WORKSPACE_ROOT_OUTPUT_PREFIXES.iter() {
if let Some(trimmed) = output.strip_prefix(prefix) {
if contains_glob_pattern(&trimmed) {
let (root, _) = partition_glob(&trimmed);
let (root, _) = partition_glob(&trimmed)?;
if root.is_empty() {
workspace_globs.push(output);
}
}
}
}

(missing_prefix, workspace_globs)
},
);
}
}

if workspace_globs.is_empty() && missing_prefix.is_empty() {
return Ok(());
Expand Down
45 changes: 25 additions & 20 deletions packages/nx/src/native/glob/glob_transform.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::native::glob::glob_group::GlobGroup;
use crate::native::glob::glob_parser::parse_glob;
use itertools::Itertools;
use std::collections::HashSet;

use itertools::Either::{Left, Right};
use super::contains_glob_pattern;

#[derive(Debug)]
Expand Down Expand Up @@ -113,31 +113,29 @@ fn build_segment(
}
}

pub fn partition_glob(glob: &str) -> (String, Vec<String>) {
let (negated, groups) = parse_glob(glob).unwrap();
pub fn partition_glob(glob: &str) -> anyhow::Result<(String, Vec<String>)> {
let (negated, groups) = parse_glob(glob)?;
// Partition glob into leading directories and patterns that should be matched
let mut leading_dir_segments: Vec<String> = vec![];
let mut pattern_segments = vec![];
groups
let mut has_patterns = false;
let (leading_dir_segments, pattern_segments): (Vec<String>, _) = groups
.into_iter()
.filter(|group| !group.is_empty())
.for_each(|group| match &group[0] {
GlobGroup::NonSpecial(value) => {
if !contains_glob_pattern(&value) && pattern_segments.is_empty() {
leading_dir_segments.push(value.to_string());
} else {
pattern_segments.push(group);
.partition_map(|group| {
match &group[0] {
GlobGroup::NonSpecial(value) if !contains_glob_pattern(&value) && !has_patterns => {
Left(value.to_string())
}
_ => {
has_patterns = true;
Right(group)
}
}
_ => {
pattern_segments.push(group);
}
});

(
Ok((
leading_dir_segments.join("/"),
convert_glob_segments(negated, pattern_segments),
)
))
}

#[cfg(test)]
Expand Down Expand Up @@ -269,21 +267,28 @@ mod test {

#[test]
fn should_partition_glob_with_leading_dirs() {
let (leading_dirs, globs) = super::partition_glob("dist/app/**/!(README|LICENSE).(js|ts)");
let (leading_dirs, globs) = super::partition_glob("dist/app/**/!(README|LICENSE).(js|ts)").unwrap();
assert_eq!(leading_dirs, "dist/app");
assert_eq!(globs, ["!**/{README,LICENSE}.{js,ts}", "**/*.{js,ts}",]);
}

#[test]
fn should_partition_glob_with_leading_dirs_and_simple_patterns() {
let (leading_dirs, globs) = super::partition_glob("dist/app/**/*.css");
let (leading_dirs, globs) = super::partition_glob("dist/app/**/*.css").unwrap();
assert_eq!(leading_dirs, "dist/app");
assert_eq!(globs, ["**/*.css"]);
}

#[test]
fn should_partition_glob_with_leading_dirs_dirs_and_patterns() {
let (leading_dirs, globs) = super::partition_glob("dist/app/**/js/*.js").unwrap();
assert_eq!(leading_dirs, "dist/app");
assert_eq!(globs, ["**/js/*.js"]);
}

#[test]
fn should_partition_glob_with_leading_dirs_and_no_patterns() {
let (leading_dirs, globs) = super::partition_glob("dist/app/");
let (leading_dirs, globs) = super::partition_glob("dist/app/").unwrap();
assert_eq!(leading_dirs, "dist/app");
assert_eq!(globs, [] as [String; 0]);
}
Expand Down
6 changes: 3 additions & 3 deletions packages/storybook/src/plugins/plugin.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ describe('@nx/storybook/plugin', () => {
},
cache: true,
outputs: [
'{workspaceRoot}/{projectRoot}/storybook-static',
'{projectRoot}/storybook-static',
'{options.output-dir}',
'{options.outputDir}',
'{options.o}',
Expand Down Expand Up @@ -127,7 +127,7 @@ describe('@nx/storybook/plugin', () => {
},
cache: true,
outputs: [
'{workspaceRoot}/{projectRoot}/storybook-static',
'{projectRoot}/storybook-static',
'{options.output-dir}',
'{options.outputDir}',
'{options.o}',
Expand Down Expand Up @@ -192,7 +192,7 @@ describe('@nx/storybook/plugin', () => {
},
cache: true,
outputs: [
'{workspaceRoot}/{projectRoot}/storybook-static',
'{projectRoot}/storybook-static',
'{options.output-dir}',
'{options.outputDir}',
'{options.o}',
Expand Down
20 changes: 5 additions & 15 deletions packages/storybook/src/plugins/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@ import {
CreateDependencies,
CreateNodes,
CreateNodesContext,
TargetConfiguration,
detectPackageManager,
joinPathFragments,
parseJson,
readJsonFile,
TargetConfiguration,
writeJsonFile,
} from '@nx/devkit';
import { dirname, join } from 'path';
import { getNamedInputs } from '@nx/devkit/src/utils/get-named-inputs';
import { existsSync, readFileSync, readdirSync } from 'fs';
import { existsSync, readdirSync, readFileSync } from 'fs';
import { calculateHashForCreateNodes } from '@nx/devkit/src/utils/calculate-hash-for-create-nodes';
import { workspaceDataDirectory } from 'nx/src/utils/cache-directory';
import { getLockFileName } from '@nx/js';
Expand Down Expand Up @@ -109,7 +109,7 @@ async function buildStorybookTargets(
context: CreateNodesContext,
projectName: string
) {
const buildOutputs = getOutputs(projectRoot);
const buildOutputs = getOutputs();

const namedInputs = getNamedInputs(projectRoot, context);

Expand Down Expand Up @@ -274,11 +274,9 @@ async function getStorybookFramework(
return typeof framework === 'string' ? framework : framework.name;
}

function getOutputs(projectRoot: string): string[] {
const normalizedOutputPath = normalizeOutputPath(projectRoot);

function getOutputs(): string[] {
const outputs = [
normalizedOutputPath,
`{projectRoot}/storybook-static`,
`{options.output-dir}`,
`{options.outputDir}`,
`{options.o}`,
Expand All @@ -287,14 +285,6 @@ function getOutputs(projectRoot: string): string[] {
return outputs;
}

function normalizeOutputPath(projectRoot: string): string | undefined {
if (projectRoot === '.') {
return `{projectRoot}/storybook-static`;
} else {
return `{projectRoot}/storybook-static`;
}
}

function normalizeOptions(
options: StorybookPluginOptions
): StorybookPluginOptions {
Expand Down

0 comments on commit c453042

Please sign in to comment.