Skip to content

Commit

Permalink
fix: add missing files in workspace
Browse files Browse the repository at this point in the history
  • Loading branch information
kpanot committed Jan 10, 2025
1 parent 897af75 commit 09c15eb
Show file tree
Hide file tree
Showing 13 changed files with 296 additions and 56 deletions.
43 changes: 0 additions & 43 deletions .commitlintrc.json

This file was deleted.

50 changes: 50 additions & 0 deletions commitlint.config.cts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import type {
UserConfig,
} from '@commitlint/types';

export default {
extends: [
'@commitlint/config-conventional',
'@commitlint/config-angular'
],
rules: {
'body-leading-blank': [1, 'always'],
'footer-leading-blank': [1, 'always'],
'header-max-length': [2, 'always', 100],
'scope-case': [2, 'always', 'lower-case'],
'subject-case': [2, 'never',
[
'sentence-case',
'start-case',
'pascal-case',
'upper-case'
]
],
'subject-empty': [2, 'never'],
'subject-full-stop': [2, 'never', '.'],
'type-case': [2, 'always', 'lower-case'],
'type-empty': [2, 'never'],
'type-enum': [2, 'always',
[
'build',
'chore',
'ci',
'docs',
'deprecate',
'feat',
'feature',
'features',
'fix',
'bugfix',
'fixes',
'bugfixes',
'improvement',
'perf',
'refactor',
'revert',
'style',
'test'
]
]
}
} as const satisfies UserConfig;
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,9 @@
"@babel/core": "~7.26.0",
"@babel/preset-typescript": "~7.26.0",
"@commitlint/cli": "^19.0.0",
"@commitlint/config-angular": "^19.0.0",
"@commitlint/config-conventional": "^19.0.0",
"@commitlint/types": "^19.0.0",
"@compodoc/compodoc": "^1.1.19",
"@design-factory/design-factory": "~18.1.0",
"@eslint-community/eslint-plugin-eslint-comments": "^4.4.0",
Expand Down
12 changes: 9 additions & 3 deletions packages/@o3r/schematics/src/tasks/package-manager/npm-exec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,28 @@ import {
} from '@angular-devkit/schematics/tasks/package-manager/options';
import {
getPackageManager,
type SupportedPackageManagers,
} from '../../utility/package-manager-runner';

/**
* Configuration used to run an Npm binary during schematics execution
* Note that this only works if the necessary files are created on the disk (doesn't work on tree)
*/
export class NpmExecTask implements TaskConfigurationGenerator<NodePackageTaskOptions> {
constructor(private readonly script: string, private readonly args: string[] = [], private readonly workingDirectory?: string) {}
constructor(
private readonly script: string,

Check warning on line 20 in packages/@o3r/schematics/src/tasks/package-manager/npm-exec.ts

View check run for this annotation

Codecov / codecov/patch

packages/@o3r/schematics/src/tasks/package-manager/npm-exec.ts#L19-L20

Added lines #L19 - L20 were not covered by tests
private readonly args: string[] = [],
private readonly workingDirectory?: string,
private readonly packageManager?: SupportedPackageManagers

Check warning on line 23 in packages/@o3r/schematics/src/tasks/package-manager/npm-exec.ts

View check run for this annotation

Codecov / codecov/patch

packages/@o3r/schematics/src/tasks/package-manager/npm-exec.ts#L22-L23

Added lines #L22 - L23 were not covered by tests
) {}

public toConfiguration(): TaskConfiguration<NodePackageTaskOptions> {
const packageManager = getPackageManager();
const packageManager = this.packageManager || getPackageManager();
return {
name: NodePackageName,
options: {
command: 'exec',
packageName: `exec ${this.script} ${packageManager === 'npm' ? '-- ' : ''}${this.args.map((arg) => `"${arg}"`).join(' ')}`,
packageName: `exec ${this.script} ${packageManager === 'npm' && this.args.length > 0 ? '-- ' : ''}${this.args.map((arg) => `"${arg}"`).join(' ')}`,
workingDirectory: this.workingDirectory,
packageManager
}
Expand Down
9 changes: 8 additions & 1 deletion packages/@o3r/workspace/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -125,10 +125,17 @@
},
"generatorDependencies": {
"@angular/material": "~18.2.0",
"@commitlint/cli": "^19.0.0",
"@commitlint/config-angular": "^19.0.0",
"@commitlint/config-conventional": "^19.0.0",
"@commitlint/types": "^19.0.0",
"@ngrx/router-store": "~18.0.0",
"@ngrx/effects": "~18.0.0",
"@ngrx/store-devtools": "~18.0.0",
"lerna": "^8.1.7"
"editorconfig-checker": "^5.1.8",
"husky": "~9.1.0",
"lerna": "^8.1.7",
"lint-staged": "^15.0.0"
},
"engines": {
"node": "^18.19.1 || ^20.11.1 || >=22.0.0"
Expand Down
9 changes: 7 additions & 2 deletions packages/@o3r/workspace/schematics/index.it.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ describe('new otter workspace', () => {
expect(() => packageManagerRunOnProject('@my-sdk/sdk', isInWorkspace, { script: 'spec:upgrade' }, execAppOptions)).not.toThrow();
});

test('should add a library to an existing workspace', () => {
test('should add a library to an existing workspace', async () => {
const { workspacePath } = o3rEnvironment.testEnvironment;
const execAppOptions = { ...getDefaultExecSyncOptions(), cwd: workspacePath };
const libName = 'test-library';
Expand All @@ -110,11 +110,16 @@ describe('new otter workspace', () => {
'jest.config.js',
'tsconfig.builders.json',
'tsconfig.json',
'testing/setup-jest.ts'];
'commitlint.config.cts',
'testing/setup-jest.ts',
'.husky/commit-msg',
'.husky/pre-commit'
];
expect(() => packageManagerExec({ script: 'ng', args: ['g', 'library', libName] }, execAppOptions)).not.toThrow();
expect(existsSync(path.join(workspacePath, 'project'))).toBe(false);
generatedLibFiles.forEach((file) => expect(existsSync(path.join(inLibraryPath, file))).toBe(true));
expect(() => packageManagerRunOnProject(libName, true, { script: 'build' }, execAppOptions)).not.toThrow();
await expect(fs.readFile(path.join(workspacePath, '.husky/pre-commit'), { encoding: 'utf8' })).resolves.toMatch(/lint-stage/);
});

test('should generate a monorepo setup', async () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import * as path from 'node:path';
import {
Tree,
} from '@angular-devkit/schematics';
import {
SchematicTestRunner,
UnitTestTree,
} from '@angular-devkit/schematics/testing';
import {
firstValueFrom,
} from 'rxjs';
import {
editPackageJson,
generateCommitLintConfig,
getCommitHookInitTask,
} from './index';

const collectionPath = path.join(__dirname, '..', '..', '..', '..', 'collection.json');

describe('getCommitHookInitTask', () => {
let context: any;

beforeEach(() => {
// jest.clearAllMocks();
process.env.ENFORCED_PACKAGE_MANAGER = undefined;
context = {
addTask: jest.fn().mockReturnValue({ id: 123 })
};
});

test('should correctly register the tasks', () => {
process.env.ENFORCED_PACKAGE_MANAGER = 'yarn';
const runAfter = [{ id: 111 }];
getCommitHookInitTask(context)(runAfter);

expect(context.addTask).toHaveBeenNthCalledWith(1, expect.objectContaining({ script: 'husky init' }), runAfter);
expect(context.addTask).toHaveBeenNthCalledWith(2, expect.objectContaining({ script: `-c 'echo "yarn exec lint-stage" > .husky/pre-commit'` }), [{ id: 123 }]);
});
});

describe('generateCommitLintConfig', () => {
const initialTree = new UnitTestTree(Tree.empty());
const apply = jest.fn();
jest.mock('@angular-devkit/schematics', () => ({
apply,
getTemplateFolder: jest.fn(),
template: jest.fn(),
renameTemplateFiles: jest.fn(),
url: jest.fn(),
mergeWith: jest.fn().mockReturnValue(initialTree)
}));

test('should generate template', () => {
expect(() => generateCommitLintConfig()(initialTree, {} as any)).not.toThrow();
expect(apply).not.toHaveBeenCalled();
});
});

describe('editPackageJson', () => {
let initialTree: UnitTestTree;

beforeEach(() => {
initialTree = new UnitTestTree(Tree.empty());
initialTree.create('/package.json', '{}');
});

test('should add stage-lint if not present', async () => {
const runner = new SchematicTestRunner(
'@o3r/workspace',
collectionPath
);
const tree = await firstValueFrom(runner.callRule(editPackageJson, initialTree));
expect((tree.readJson('/package.json') as any)['lint-staged']).toBeDefined();
});

test('should not touche stage-lint if present', async () => {
initialTree.overwrite('/package.json', '{"lint-staged": "test"}');
const runner = new SchematicTestRunner(
'@o3r/workspace',
collectionPath
);
const tree = await firstValueFrom(runner.callRule(editPackageJson, initialTree));
expect((tree.readJson('/package.json') as any)['lint-staged']).toBe('test');
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import {
apply,
chain,
MergeStrategy,
mergeWith,
renameTemplateFiles,
type Rule,
type SchematicContext,
type TaskId,
template,
url,
} from '@angular-devkit/schematics';
import {
getPackageManager,
NpmExecTask,
} from '@o3r/schematics';
import type {
PackageJson,
} from 'type-fest';

/** Dev Dependencies to install to setup Commit hooks */
export const commitHookDevDependencies = [
'lint-staged',
'editorconfig-checker',
'@commitlint/cli',
'@commitlint/config-angular',
'@commitlint/config-conventional',
'@commitlint/types'
];

/**
* Retrieve the task callback function to initialization the commit hooks
* @param context
*/
export function getCommitHookInitTask(context: SchematicContext) {
return (taskIds?: TaskId[]) => {
const packageManager = getPackageManager();
const huskyTask = new NpmExecTask('husky init');
const taskId = context.addTask(huskyTask, taskIds);
const setupLintStage = new NpmExecTask(`-c 'echo "${packageManager} exec lint-stage" > .husky/pre-commit'`, undefined, undefined, 'npm');
context.addTask(setupLintStage, [taskId]);
};
}

export const editPackageJson: Rule = (tree, context) => {
const packageJson = tree.readJson('/package.json') as PackageJson;
if (packageJson['lint-staged']) {
context.logger.debug('A Lint-stage configuration is already defined, the default value will not be applied');
return tree;
}
packageJson['lint-staged'] = {
'*': [
'editorconfig-checker --verbose'
]
};
tree.overwrite('/package.json', JSON.stringify(packageJson));
};

/**
* Add Commit Lint and husky configurations to Otter project
* @param rootPath @see RuleFactory.rootPath
*/
export function generateCommitLintConfig(): Rule {
return () => {
const packageManager = getPackageManager();
const templateSource = apply(url('./helpers/commit-hooks/templates'), [
template({
empty: '',
packageManager
}),
renameTemplateFiles()
]);
const rule = mergeWith(templateSource, MergeStrategy.Overwrite);
return chain([
editPackageJson,
rule
]);
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<%= packageManager %> exec commitlint <%= packageManager === 'npm' ? '-- ' : '' %>--edit $1
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import type {
UserConfig,
} from '@commitlint/types';

export default {
extends: [
'@commitlint/config-conventional',
'@commitlint/config-angular'
]
} as const satisfies UserConfig;
Loading

0 comments on commit 09c15eb

Please sign in to comment.