Skip to content

Commit

Permalink
feat: run stc from integrations (#2342)
Browse files Browse the repository at this point in the history
  • Loading branch information
tzachbon committed Apr 5, 2022
1 parent 46b9372 commit de007a9
Show file tree
Hide file tree
Showing 54 changed files with 1,079 additions and 261 deletions.
6 changes: 5 additions & 1 deletion package-lock.json

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

10 changes: 8 additions & 2 deletions packages/build-tools/src/load-stylable-config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import findConfig from 'find-config';

export function loadStylableConfig<T>(context: string, extract: (config: any) => T): T | undefined {
export function loadStylableConfig<T>(
context: string,
extract: (config: any) => T
): { path: string; config: T } | undefined {
const path = findConfig('stylable.config.js', { cwd: context });
let config;
if (path) {
Expand All @@ -16,7 +19,10 @@ export function loadStylableConfig<T>(context: string, extract: (config: any) =>
`Stylable configuration loaded from ${path} but no exported configuration found`
);
}
return extract(config);
return {
path,
config: extract(config),
};
}
return undefined;
}
1 change: 1 addition & 0 deletions packages/cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ After installing `@stylable/cli`, the `stc` command will be available, running `
| `--dts` | | output definition files for the stylable source files (`.st.css.d.ts`) | `false` |
| `--dtsSourceMap` | | output source-maps for the definitions of stylable source files (`.st.css.d.ts.map`) | `true` if `--dts` is true, otherwise `false` |
| `--watch` | `w` | enable watch mode | `false` |
| `--config` | `c` | The path to a config file specifying how to build and output Stylable stylesheets | The directory containing the config file is assumed to be the "rootDir" for the project named "stylable.config.js" |
| `--useNamespaceReference` | `unsr` | mark output stylable source files with relative path for namespacing purposes (\*) | `false` |
| `--customGenerator` | | path of a custom index file generator | - |
| `--ext` | | extension of stylable css files | `.st.css` |
Expand Down
15 changes: 8 additions & 7 deletions packages/cli/src/build-single-file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -282,13 +282,14 @@ export function getAllDiagnostics(res: StylableResults): Diagnostic[] {
? res.meta.diagnostics.reports.concat(res.meta.transformDiagnostics.reports)
: res.meta.diagnostics.reports;

return diagnostics.map((diagnostic) => {
const err = diagnostic.node.error(diagnostic.message, diagnostic.options);

return {
type: diagnostic.type,
message: `${diagnostic.message}\n${err.showSourceCode(true)}`,
offset: diagnostic.node.source?.start?.offset,
return diagnostics.map(({ message, node, options, type }) => {
const err = node.error(message, options);
const diagnostic: Diagnostic = {
type,
message: `${message}\n${err.showSourceCode(true)}`,
...(node.source?.start && {}),
};

return diagnostic;
});
}
31 changes: 22 additions & 9 deletions packages/cli/src/build-stylable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ export interface BuildStylableContext
outputFiles?: Map<string, Set<string>>;
defaultOptions?: BuildOptions;
overrideBuildOptions?: Partial<BuildOptions>;
configFilePath?: string;
watchOptions?: {
lazy?: boolean;
};
}

export async function buildStylable(
Expand All @@ -35,18 +39,27 @@ export async function buildStylable(
fileProcessorCache = {},
diagnosticsManager = new DiagnosticsManager({
log,
onFatalDiagnostics() {
if (!watch) {
process.exitCode = 1;
}
hooks: {
postReport(_diagnostics, hasFatalDiagnostic) {
if (hasFatalDiagnostic && !watch) {
process.exitCode = 1;
}
},
},
}),
outputFiles = new Map(),
requireModule = require,
resolveNamespace = requireModule(NAMESPACE_RESOLVER_MODULE_REQUEST).resolveNamespace,
configFilePath,
watchOptions = {},
}: BuildStylableContext = {}
) {
const projects = await projectsConfig(rootDir, overrideBuildOptions, defaultOptions);
const projects = await projectsConfig(
rootDir,
overrideBuildOptions,
defaultOptions,
configFilePath
);
const watchHandler = new WatchHandler(fileSystem, {
log,
resolverCache,
Expand Down Expand Up @@ -77,7 +90,7 @@ export async function buildStylable(
fileProcessorCache,
});

const { service } = await build(buildOptions, {
const { service, generatedFiles } = await build(buildOptions, {
watch,
stylable,
log,
Expand All @@ -89,15 +102,15 @@ export async function buildStylable(
diagnosticsManager,
});

watchHandler.register({ service, identifier, stylable });
watchHandler.register({ service, identifier, stylable, generatedFiles });
}
}

diagnosticsManager.report();

if (watch) {
if (watch && !watchOptions.lazy) {
watchHandler.start();
}

return { watchHandler };
return { watchHandler, outputFiles, projects, diagnosticsManager };
}
6 changes: 3 additions & 3 deletions packages/cli/src/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ export async function build(
log(mode, buildMessages.BUILD_SKIPPED(isMultiPackagesProject ? identifier : undefined));
}

return { service };
return { service, generatedFiles: buildGeneratedFiles };

function buildFiles(filesToBuild: Set<string>, generated: Set<string>) {
for (const filePath of filesToBuild) {
Expand Down Expand Up @@ -273,14 +273,14 @@ export async function build(
}

function setFileErrorDiagnostic(filePath: string, error: any) {
const diangostic: Diagnostic = {
const diagnostic: Diagnostic = {
type: 'error',
message: error instanceof Error ? error.message : String(error),
};

diagnosticsManager.set(identifier, filePath, {
diagnosticsMode,
diagnostics: [diangostic],
diagnostics: [diagnostic],
});
}

Expand Down
2 changes: 2 additions & 0 deletions packages/cli/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ async function main() {
log: shouldLog,
namespaceResolver,
preserveWatchOutput,
config,
} = argv;
const { resolveNamespace } = require(namespaceResolver);
const rootDir = resolve(argv.rootDir);
Expand Down Expand Up @@ -44,6 +45,7 @@ async function main() {
resolveNamespace,
watch,
log,
configFilePath: config,
});

process.on('SIGTERM', () => {
Expand Down
56 changes: 35 additions & 21 deletions packages/cli/src/config/projects-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import type {
RawProjectEntity,
ResolveProjectsContext,
ResolveRequests,
STCConfig,
STCProjects,
} from '../types';
import { processProjects } from './process-projects';
import { createDefaultOptions, mergeBuildOptions, validateOptions } from './resolve-options';
Expand All @@ -17,28 +17,30 @@ import { resolveNpmRequests } from './resolve-requests';
export async function projectsConfig(
rootDir: string,
overrideBuildOptions: Partial<BuildOptions>,
defaultOptions: BuildOptions = createDefaultOptions()
): Promise<STCConfig> {
const configFile = resolveConfigFile(rootDir);
defaultOptions: BuildOptions = createDefaultOptions(),
configFilePath?: string
): Promise<STCProjects> {
const { config } = resolveConfig(rootDir, configFilePath) || {};

const topLevelOptions = mergeBuildOptions(
defaultOptions,
configFile?.options,
config?.options,
overrideBuildOptions
);

validateOptions(topLevelOptions);

let projects: STCConfig;
let projects: STCProjects;

if (isMultipleConfigProject(configFile)) {
const { entities } = processProjects(configFile, {
if (isMultipleConfigProject(config)) {
const { entities } = processProjects(config, {
defaultOptions: topLevelOptions,
});

projects = await resolveProjectsRequests({
rootDir,
entities,
resolveRequests: configFile.projectsOptions?.resolveRequests ?? resolveNpmRequests,
resolveRequests: config.projectsOptions?.resolveRequests ?? resolveNpmRequests,
});
} else {
projects = [
Expand All @@ -52,17 +54,29 @@ export async function projectsConfig(
return projects;
}

export function resolveConfigFile(context: string) {
return loadStylableConfig(context, (config) =>
tryRun(
() =>
isSTCConfig(config)
? typeof config.stcConfig === 'function'
? config.stcConfig()
: config.stcConfig
: undefined,
'Failed to evaluate "stcConfig"'
)
export function resolveConfig(context: string, request?: string) {
return request ? requireConfigFile(request, context) : resolveConfigFile(context);
}

function requireConfigFile(request: string, context: string) {
const path = require.resolve(request, { paths: [context] });
const config = resolveConfigValue(require(path));
return config ? { config, path } : undefined;
}

function resolveConfigFile(context: string) {
return loadStylableConfig(context, (config) => resolveConfigValue(config));
}

function resolveConfigValue(config: any) {
return tryRun(
() =>
isSTCConfig(config)
? typeof config.stcConfig === 'function'
? config.stcConfig()
: config.stcConfig
: undefined,
'Failed to evaluate "stcConfig"'
);
}

Expand All @@ -86,7 +100,7 @@ async function resolveProjectsRequests({
rootDir: string;
entities: Array<RawProjectEntity>;
resolveRequests: ResolveRequests;
}): Promise<STCConfig> {
}): Promise<STCProjects> {
const context: ResolveProjectsContext = { rootDir };

return resolveRequests(entities, context);
Expand Down
8 changes: 8 additions & 0 deletions packages/cli/src/config/resolve-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,14 @@ export function getCliArguments(): Arguments<CliArguments> {
defaultDescription: defaults.diagnosticsMode,
choices: ['strict', 'loose'],
})
.option('config', {
alias: 'c',
type: 'string',
description:
'The path to a config file specifying how to build and output Stylable stylesheets',
defaultDescription:
'The directory containing the config file is assumed to be the "rootDir" for the project named "stylable.config.js"',
})
.option('watch', {
alias: 'w',
type: 'boolean',
Expand Down
13 changes: 8 additions & 5 deletions packages/cli/src/diagnostics-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@ type DiagnosticsStore = Map<string, Map<string, ProcessDiagnostics>>;

interface DiagnosticsManagerOptions {
log?: Log;
onFatalDiagnostics?: () => void;
hooks?: {
preReport?(diagnosticsMessages: DiagnosticMessages): void;
postReport?(diagnosticsMessages: DiagnosticMessages, hasFatalDiagnostic: boolean): void;
};
}

export class DiagnosticsManager {
Expand Down Expand Up @@ -94,16 +97,16 @@ export class DiagnosticsManager {
}
}

this.options.hooks?.preReport?.(diagnosticMessages);

if (diagnosticMessages.size) {
const hasFatalDiangostics = reportDiagnostics(
const hasFatalDiagnostics = reportDiagnostics(
this.log,
diagnosticMessages,
diagnosticMode
);

if (hasFatalDiangostics) {
this.options.onFatalDiagnostics?.();
}
this.options.hooks?.postReport?.(diagnosticMessages, hasFatalDiagnostics);
}

return Boolean(diagnosticMessages.size);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,14 +51,15 @@ export class DirectoryProcessService {
this.registerInvalidateOnChange(item.path);
}
}
if (affectedFiles.size === 0) {
return;
}
try {
await this.options.processFiles?.(this, affectedFiles, new Set());
} catch (error) {
this.options.onError?.(error as Error);
if (affectedFiles.size) {
try {
await this.options.processFiles?.(this, affectedFiles, new Set());
} catch (error) {
this.options.onError?.(error as Error);
}
}

return affectedFiles;
}
private addFileToWatchedDirectory(filePath: string) {
const dirName = this.fs.dirname(filePath);
Expand Down Expand Up @@ -110,7 +111,9 @@ export class DirectoryProcessService {
for (const event of files.values()) {
if (event.stats?.isDirectory()) {
if (this.options.directoryFilter?.(event.path) ?? true) {
await this.init(event.path);
for (const filePath of await this.init(event.path)) {
affectedFiles.add(filePath);
}
}
continue;
}
Expand Down

0 comments on commit de007a9

Please sign in to comment.