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

feat: add strict mode #121

Merged
merged 10 commits into from
Feb 6, 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
6 changes: 3 additions & 3 deletions packages/assetpack/src/core/Asset.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import fs from 'fs-extra';
import { Logger } from './logger/Logger.js';
import { BuildReporter } from './logger/BuildReporter.js';
import { extractTagsFromFileName } from './utils/extractTagsFromFileName.js';
import { getHash } from './utils/getHash.js';
import { path } from './utils/path.js';
Expand Down Expand Up @@ -126,7 +126,7 @@ export class Asset
{
if (this.isFolder)
{
Logger.warn('[AssetPack] folders should not have buffers!. Contact the developer of AssetPack');
BuildReporter.error('[AssetPack] folders should not have buffers!. Contact the developer of AssetPack');
}

if (!this._buffer)
Expand All @@ -148,7 +148,7 @@ export class Asset
{
if (this.isFolder)
{
Logger.warn('[AssetPack] folders should not have hashes. Contact the developer of the AssetPack');
BuildReporter.error('[AssetPack] folders should not have hashes. Contact the developer of the AssetPack');
}

try
Expand Down
22 changes: 12 additions & 10 deletions packages/assetpack/src/core/AssetPack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import fs from 'fs-extra';
import merge from 'merge';
import { AssetCache } from './AssetCache.js';
import { AssetWatcher } from './AssetWatcher.js';
import { Logger } from './logger/Logger.js';
import { BuildReporter } from './logger/BuildReporter.js';
import { finalCopyPipe } from './pipes/finalCopyPipe.js';
import { PipeSystem } from './pipes/PipeSystem.js';
import { generateCacheName } from './utils/generateCacheName.js';
Expand All @@ -24,6 +24,7 @@ export class AssetPack
cacheLocation: '.assetpack',
logLevel: 'info',
pipes: [],
strict: false,
};

readonly config: AssetPackConfig;
Expand Down Expand Up @@ -51,8 +52,9 @@ export class AssetPack
this._entryPath = normalizePath(this.config.entry as string);
this._outputPath = normalizePath(this.config.output as string);

Logger.init({
BuildReporter.init({
level: this.config.logLevel || 'info',
strict: this.config.strict || false,
});

const { pipes, cache, cacheLocation } = this.config;
Expand All @@ -79,11 +81,11 @@ export class AssetPack
// by the AssetWatcher
if (assetCache.exists())
{
Logger.info('[AssetPack] cache found.');
BuildReporter.info('[AssetPack] cache found.');
}
else
{
Logger.warn('[AssetPack] cache not found, clearing output folder');
BuildReporter.warn('[AssetPack] cache not found, clearing output folder');

// to be safe - lets nuke the folder as the cache is empty
fs.removeSync(this._outputPath);
Expand Down Expand Up @@ -117,15 +119,15 @@ export class AssetPack
assetSettingsData: this.config.assetSettings as AssetSettings[] || [],
onUpdate: async (root: Asset) =>
{
Logger.report({
BuildReporter.report({
type: 'buildProgress',
phase: 'transform',
message: '0'
});

await this._transform(root).catch((e) =>
{
Logger.error(`[AssetPack] Transform failed: ${e.message}`);
BuildReporter.error(`[AssetPack] Transform failed: ${e.message}`);
});
},
onComplete: async (root: Asset) =>
Expand All @@ -137,10 +139,10 @@ export class AssetPack

root.releaseChildrenBuffers();

Logger.info('cache updated.');
BuildReporter.info('cache updated.');
}

Logger.report({
BuildReporter.report({
type: 'buildSuccess',
});

Expand Down Expand Up @@ -230,7 +232,7 @@ export class AssetPack
stats.error = e.message;

// eslint-disable-next-line max-len
Logger.error(`[AssetPack] Transform failed:\ntransform: ${e.name}\nasset:${asset.path}\nerror:${e.message}`);
BuildReporter.error(`[AssetPack] Transform failed:\ntransform: ${e.name}\nasset:${asset.path}\nerror:${e.message}`);
});

stats.duration = performance.now() - now;
Expand All @@ -239,7 +241,7 @@ export class AssetPack

const percent = Math.round((index / assetsToTransform.length) * 100);

Logger.report({
BuildReporter.report({
type: 'buildProgress',
phase: 'transform',
message: percent.toString()
Expand Down
4 changes: 2 additions & 2 deletions packages/assetpack/src/core/AssetWatcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import upath from 'upath';
import { Asset } from './Asset.js';
import { AssetIgnore } from './AssetIgnore.js';
import { deleteAssetFiles } from './AssetPack.js';
import { Logger } from './logger/Logger.js';
import { BuildReporter } from './logger/BuildReporter.js';
import { applySettingToAsset } from './utils/applySettingToAsset.js';
import { path } from './utils/path.js';
import { syncAssetsWithCache } from './utils/syncAssetsWithCache.js';
Expand Down Expand Up @@ -70,7 +70,7 @@ export class AssetWatcher

private _init()
{
Logger.report({
BuildReporter.report({
type: 'buildStart',
message: this._entryPath,
});
Expand Down
12 changes: 12 additions & 0 deletions packages/assetpack/src/core/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,20 @@ export interface AssetPackConfig
* If true cached tree will be used
*/
cache?: boolean;
/**
* The location of the cache to be loaded/saved
*/
cacheLocation?: string;
/**
* The log level of the logger
*/
logLevel?: LogLevelKeys;

/**
* If true, the asset pack will be strict and will throw an error if a file is not processed correctly
*/
strict?: boolean;

pipes?: (AssetPipe | AssetPipe[])[];
assetSettings?: AssetSettings[];
}
Expand Down
2 changes: 1 addition & 1 deletion packages/assetpack/src/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ export * from './Asset.js';
export * from './AssetPack.js';
export * from './config.js';
export * from './config.js';
export * from './logger/Logger.js';
export * from './logger/BuildReporter.js';
export * from './pipes/AssetPipe.js';
export * from './pipes/multiPipe.js';
export * from './pipes/PipeSystem.js';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,23 @@ import { Reporter } from './Reporter.js';
import type { LogLevelKeys } from './logLevel.js';
import type { ReporterEvent } from './Reporter.js';

export interface LoggerOptions
export interface BuildReporterOptions
{
level: LogLevelKeys;
strict: boolean;
}
/** @deprecated Use BuildReporterOptions instead */
export interface LoggerOptions extends BuildReporterOptions {}

class LoggerClass
class BuildReporterClass
{
private _reporter: Reporter = new Reporter();
private strict = false;

public init(options: LoggerOptions)
public init(options: BuildReporterOptions)
{
this._reporter.level = options.level || 'info';
this.strict = options.strict;
}

public verbose(message: string)
Expand Down Expand Up @@ -47,6 +52,12 @@ class LoggerClass
level: 'error',
message,
});

if (this.strict)
{
this.report({ type: 'buildFailure' });
process.exit(1);
}
}

public warn(message: string)
Expand All @@ -64,4 +75,8 @@ class LoggerClass
}
}

export const Logger = new LoggerClass();
export const BuildReporter = new BuildReporterClass();
/**
* @deprecated Use BuildReporter instead
*/
export const Logger = BuildReporter;
2 changes: 1 addition & 1 deletion packages/assetpack/src/core/logger/Reporter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ export class Reporter

stopProgress();
resetWindow();
persistMessage(chalk.green.bold(`✖ AssetPack Build Failed`));
persistMessage(chalk.red.bold(`✖ AssetPack Build Failed`));

break;
case 'log': {
Expand Down
4 changes: 2 additions & 2 deletions packages/assetpack/src/json/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import json5 from 'json5';
import { checkExt, createNewAssetAt, Logger } from '../core/index.js';
import { BuildReporter, checkExt, createNewAssetAt } from '../core/index.js';

import type { Asset, AssetPipe } from '../core/index.js';

Expand Down Expand Up @@ -33,7 +33,7 @@ export function json(): AssetPipe<any, 'nc'>
}
catch (e)
{
Logger.warn(`[AssetPack][json] Failed to compress json file: ${asset.path}`);
BuildReporter.error(`[AssetPack][json] Failed to compress json file: ${asset.path}`);

return [asset];
}
Expand Down
4 changes: 2 additions & 2 deletions packages/assetpack/src/manifest/pixiManifest.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import fs from 'fs-extra';
import { Logger, path, stripTags } from '../core/index.js';
import { BuildReporter, path, stripTags } from '../core/index.js';

import type {
Asset,
Expand Down Expand Up @@ -142,7 +142,7 @@ function filterUniqueNames(manifest: PixiManifest, options: PixiManifestOptions)
if (bundleNames.has(bundle.name))
{
duplicateBundleNames.add(bundle.name);
Logger.warn(`[AssetPack][manifest] Duplicate bundle name '${bundle.name}'. All bundles with that name will be renamed to their relative name instead.`);
BuildReporter.warn(`[AssetPack][manifest] Duplicate bundle name '${bundle.name}'. All bundles with that name will be renamed to their relative name instead.`);
}
else
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { MaxRectsPacker } from 'maxrects-packer';
import sharp from 'sharp';
import { Logger } from '../../core/index.js';
import { BuildReporter } from '../../core/index.js';

import type { PackTexturesOptions, PixiRectData, TextureData } from './packTextures.js';

Expand Down Expand Up @@ -57,7 +57,7 @@ export async function createTextureData(options: Required<PackTexturesOptions>)
let result = await sharpImage.toBuffer({ resolveWithObject: true }).catch((error) =>
{
// eslint-disable-next-line max-len
Logger.warn(`[AssetPack][packTextures] Failed to process texture: ${texture.path} - ${error}, using empty pixel texture instead.`);
BuildReporter.error(`[AssetPack][packTextures] Failed to process texture: ${texture.path} - ${error}, using empty pixel texture instead.`);

return { data: null, info: null };
});
Expand Down
4 changes: 2 additions & 2 deletions packages/assetpack/src/texture-packer/texturePacker.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import fs from 'fs-extra';
import { glob } from 'glob';
import { createNewAssetAt, Logger, path, stripTags } from '../core/index.js';
import { BuildReporter, createNewAssetAt, path, stripTags } from '../core/index.js';
import { packTextures } from './packer/packTextures.js';

import type { Asset, AssetPipe, PluginOptions } from '../core/index.js';
Expand Down Expand Up @@ -45,7 +45,7 @@ function checkForTexturePackerShortcutClashes(
if (clashes.length > 0)
{
// eslint-disable-next-line max-len
Logger.warn(`[AssetPack][texturePacker] Texture Packer Shortcut clash detected for between ${clashes.join(', ')}. This means that 'nameStyle' is set to 'short' and different sprite sheets have frames that share the same name. Please either rename the files or set 'nameStyle' in the texture packer options to 'relative'`);
BuildReporter.warn(`[AssetPack][texturePacker] Texture Packer Shortcut clash detected for ${clashes.join(', ')}. This means that 'nameStyle' is set to 'short' and different sprite sheets have frames that share the same name. Please either rename the files or set 'nameStyle' in the texture packer options to 'relative'`);
}
}

Expand Down
2 changes: 2 additions & 0 deletions packages/assetpack/test/core/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ describe('AssetPack Config', () =>
cacheLocation: '.assetpack',
logLevel: 'info',
pipes: [],
strict: false,
});
});

Expand Down Expand Up @@ -45,6 +46,7 @@ describe('AssetPack Config', () =>
pipes: [
plugin
],
strict: false,
});
});
});
6 changes: 3 additions & 3 deletions packages/assetpack/test/texture-packer/texturePacker.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import fs from 'fs-extra';
import { existsSync } from 'node:fs';
import sharp from 'sharp';
import { describe, expect, it, vi } from 'vitest';
import { AssetPack, Logger } from '../../src/core/index.js';
import { AssetPack, BuildReporter } from '../../src/core/index.js';
import { texturePacker } from '../../src/texture-packer/texturePacker.js';
import { createTPSFolder } from '../utils/createTPSFolder.js';
import { assetPath, createFolder, getCacheDir, getInputDir, getOutputDir } from '../utils/index.js';
Expand Down Expand Up @@ -660,14 +660,14 @@ describe('Texture Packer', () =>
});

// Mock console.warn
const mockWarn = vi.spyOn(Logger, 'warn').mockImplementation(() => { /**/ });
const mockWarn = vi.spyOn(BuildReporter, 'warn').mockImplementation(() => { /**/ });

await assetpack.run();

// Check if console.warn was called
expect(mockWarn).toHaveBeenCalled();
// eslint-disable-next-line max-len
expect(mockWarn).toHaveBeenCalledWith(`[AssetPack][texturePacker] Texture Packer Shortcut clash detected for between sprite9.png, sprite8.png, sprite7.png, sprite6.png, sprite5.png, sprite4.png, sprite3.png, sprite2.png, sprite1.png, sprite0.png. This means that 'nameStyle' is set to 'short' and different sprite sheets have frames that share the same name. Please either rename the files or set 'nameStyle' in the texture packer options to 'relative'`); // Adjust this line based on expected message
expect(mockWarn).toHaveBeenCalledWith(`[AssetPack][texturePacker] Texture Packer Shortcut clash detected for sprite9.png, sprite8.png, sprite7.png, sprite6.png, sprite5.png, sprite4.png, sprite3.png, sprite2.png, sprite1.png, sprite0.png. This means that 'nameStyle' is set to 'short' and different sprite sheets have frames that share the same name. Please either rename the files or set 'nameStyle' in the texture packer options to 'relative'`); // Adjust this line based on expected message

// Restore console.warn
mockWarn.mockRestore();
Expand Down
12 changes: 10 additions & 2 deletions packages/docs/docs/guide/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,14 @@ An optional boolean to enable or disable caching.

An optional string to set the location of the cache.

### strict

| Type | Default | Required |
| --------- | ------- | -------- |
| `boolean` | `false` | No |

If set to `true`, AssetPack will throw an error if any of the assets fail to be processed. This is can be useful for CI/CD pipelines.

### logLevel

| Type | Default | Required |
Expand All @@ -56,8 +64,8 @@ An optional string to set the log level.

### pipes

| Type | Default | Required |
| -------- | ------- | -------- |
| Type | Default | Required |
| ---------- | ------- | -------- |
| `Plugin[]` | | No |

An array of pipes to use. For examples of pipes, see [Plugins](/docs/guide/pipes/overview#plugins).
Expand Down