Skip to content

Commit

Permalink
feat(core): remove default logic that parse components for lib root p…
Browse files Browse the repository at this point in the history
…ath, only according to include, and root dir exclude include in config

BREAKING CHANGES:
should add '' or './' to include when lib root folder is src folder
  • Loading branch information
why520crazy committed Apr 21, 2023
1 parent 964b12a commit 76d1e78
Show file tree
Hide file tree
Showing 12 changed files with 161 additions and 36 deletions.
2 changes: 1 addition & 1 deletion .docgenirc.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ module.exports = {
{
name: 'alib',
rootDir: './packages/a-lib',
include: ['common'],
include: ['./', 'common'],
exclude: '',
apiMode: 'compatible',
categories: [
Expand Down
4 changes: 4 additions & 0 deletions packages/a-lib/common/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/**
* @public
*/
export class MyService {}
4 changes: 4 additions & 0 deletions packages/a-lib/layout/layout.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Component, OnInit, HostBinding, Input, Output, EventEmitter } from '@an

/**
* Layout container component. it is required that all child components should be placed inside.
* @name alibLayout
*/
@Component({
selector: 'alib-layout, [alibLayout]',
Expand Down Expand Up @@ -30,6 +31,9 @@ export class AlibLayoutComponent implements OnInit {
ngOnInit(): void {}
}

/**
* @name alibSidebar
*/
@Component({
selector: 'alib-sidebar, [alibSidebar]',
template: `
Expand Down
44 changes: 43 additions & 1 deletion packages/cli/src/schematics/ng-add/index.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Tree } from '@angular-devkit/schematics';
import { Tree, move } from '@angular-devkit/schematics';
import { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing';
// import { DEPENDENCIES } from '../dependencies';
import { createTestWorkspaceFactory, getJsonFileContent, TestWorkspaceFactory } from '../testing';
Expand Down Expand Up @@ -88,6 +88,41 @@ describe('ng-add Schematic', () => {
expect(toolkit.strings.compatibleNormalize(config)).toEqual(toolkit.strings.compatibleNormalize(expectContent));
});

it('should include src without lib dir', async () => {
const libraryName = 'lib-test';
await factory.addLibrary({ name: libraryName });
tree = factory.getTree();
deleteDirFilesInTree(tree, `projects/${libraryName}/src/lib`);
workspaceTree = await schematicRunner.runSchematic('ng-add', undefined, tree);
const config = workspaceTree.read('.docgenirc.js').toString();
expect(config).toContain(`rootDir: 'projects/${libraryName}'`);
expect(config).toContain(`lib: '${libraryName}'`);
expect(config).toContain(`apiMode: 'automatic'`);
const expectContent = await toolkit.fs.readFileContent(
path.resolve(__dirname, '../../../test/fixtures/docgenirc/output/.docgenirc-without-lib.js')
);
expect(toolkit.strings.compatibleNormalize(config)).toEqual(toolkit.strings.compatibleNormalize(expectContent));
});

it('should include src when sourceRoot is equal root', async () => {
const libraryName = 'lib-test';
await factory.addLibrary({ name: libraryName });
tree = factory.getTree();
const angularJSONText = tree.readText('angular.json');
tree.overwrite('angular.json', angularJSONText.replace(`projects/lib-test/src`, `projects/lib-test`));
deleteDirFilesInTree(tree, `projects/${libraryName}/src/lib`);
deleteDirFilesInTree(tree, `projects/${libraryName}/src`);
workspaceTree = await schematicRunner.runSchematic('ng-add', undefined, tree);
const config = workspaceTree.read('.docgenirc.js').toString();
expect(config).toContain(`rootDir: 'projects/${libraryName}'`);
expect(config).toContain(`lib: '${libraryName}'`);
expect(config).toContain(`apiMode: 'automatic'`);
const expectContent = await toolkit.fs.readFileContent(
path.resolve(__dirname, '../../../test/fixtures/docgenirc/output/.docgenirc-root-equal-source-root.js')
);
expect(toolkit.strings.compatibleNormalize(config)).toEqual(toolkit.strings.compatibleNormalize(expectContent));
});

it('should generate without angular.json', async () => {
const libraryName = 'lib-test';
await factory.addLibrary({ name: libraryName });
Expand Down Expand Up @@ -116,3 +151,10 @@ describe('ng-add Schematic', () => {
expect(gitignoreContent.split('\n').some(item => item === '.docgeni/site')).toBeTruthy();
});
});

function deleteDirFilesInTree(tree: Tree, dir: string) {
const dirEntry = tree.getDir(dir);
dirEntry.subfiles.forEach(subFile => {
tree.delete(`${dir}/${subFile}`);
});
}
23 changes: 22 additions & 1 deletion packages/cli/src/schematics/ng-add/init-docgenirc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ import stringifyObject from 'stringify-object';

export class InitDocgenirc {
private docgenirc: Partial<DocgeniConfig> = {};

constructor(private options: NgAddSchema) {}

private addProperty<T extends keyof DocgeniConfig>(key: T, value: DocgeniConfig[T]) {
if (!value) {
return this;
Expand All @@ -34,10 +36,29 @@ export class InitDocgenirc {
lib: projectName,
locales: {}
});
const include: string[] = [];
const exclude: string[] = [];
const libDirEntry = host.getDir(`${config.sourceRoot}/lib`);
const libDirExists = libDirEntry.subdirs.length > 0 || libDirEntry.subfiles.length > 0;
if (config.sourceRoot && config.sourceRoot !== config.root) {
const sourceDir = config.sourceRoot.replace(config.root + '/', '');
// 如果当前 sourceDir 路径和 root 路径不同,说明有 src 文件夹
if (sourceDir) {
if (libDirExists) {
include.push(`${sourceDir}/lib`);
} else {
// src 文件夹添加到 include,读取 src 文件夹的组件
include.push(sourceDir);
}
}
} else {
include.push('');
}
libs.push({
name: projectName,
rootDir: config.root,
include: ['src', 'src/lib'],
include: include,
exclude: exclude,
apiMode: 'automatic',
categories: []
});
Expand Down
32 changes: 16 additions & 16 deletions packages/cli/src/schematics/testing/test-workspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ import { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/te

export class TestWorkspaceFactory {
private hostTree = new HostTree();

private tree: UnitTestTree;

constructor(public runner: SchematicTestRunner) {}

async create(options?: {
Expand All @@ -14,29 +16,27 @@ export class TestWorkspaceFactory {
strict?: boolean;
packageManager?: 'npm' | 'yarn' | 'pnpm' | 'cnpm';
}) {
this.tree = await this.runner
.runExternalSchematicAsync(
'@schematics/angular',
'workspace',
{
name: 'test-workspace',
version: '14.2.10',
newProjectRoot: 'projects',
...options
},
this.hostTree
)
.toPromise();
this.tree = await this.runner.runExternalSchematic(
'@schematics/angular',
'workspace',
{
name: 'test-workspace',
version: '14.2.10',
newProjectRoot: 'projects',
...options
},
this.hostTree
);
return this.tree;
}

async addApplication(options: { name: string; [name: string]: any }) {
this.tree = await this.runner.runExternalSchematicAsync('@schematics/angular', 'application', options, this.tree).toPromise();
this.tree = await this.runner.runExternalSchematic('@schematics/angular', 'application', options, this.tree);
return this.tree;
}

async addLibrary(options: { name: string; [name: string]: any }) {
this.tree = await this.runner.runExternalSchematicAsync('@schematics/angular', 'library', options, this.tree).toPromise();
async addLibrary(options: { name: string; [key: string]: any }) {
this.tree = await this.runner.runExternalSchematic('@schematics/angular', 'library', options, this.tree);
return this.tree;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/**
* @type {import('@docgeni/core').DocgeniConfig}
*/
module.exports = {
mode: 'lite',
title: 'test-workspace',
description: '',
docsDir: 'docs',
navs: [
null,
{
title: 'Components',
path: 'components',
lib: 'lib-test',
locales: {}
}
],
libs: [
{
name: 'lib-test',
rootDir: 'projects/lib-test',
include: [
''
],
exclude: [],
apiMode: 'automatic',
categories: []
}
]
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/**
* @type {import('@docgeni/core').DocgeniConfig}
*/
module.exports = {
mode: 'lite',
title: 'test-workspace',
description: '',
docsDir: 'docs',
navs: [
null,
{
title: 'Components',
path: 'components',
lib: 'lib-test',
locales: {}
}
],
libs: [
{
name: 'lib-test',
rootDir: 'projects/lib-test',
include: [
'src'
],
exclude: [],
apiMode: 'automatic',
categories: []
}
]
};
2 changes: 1 addition & 1 deletion packages/cli/test/fixtures/docgenirc/output/.docgenirc.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ module.exports = {
name: 'lib-test',
rootDir: 'projects/lib-test',
include: [
'src',
'src/lib'
],
exclude: [],
apiMode: 'automatic',
categories: []
}
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/builders/libraries-builder.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ describe('libraries-builder', () => {
const library = {
name: 'alib',
rootDir: libDirPath,
include: ['common'],
include: ['', 'common'],
exclude: '',
categories: [
{
Expand Down
6 changes: 3 additions & 3 deletions packages/core/src/builders/library-builder.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ describe('#library-builder', () => {
const library = normalizeLibConfig({
name: 'alib',
rootDir: 'a-lib',
include: ['common'],
include: ['', 'common'],
exclude: '',
categories: [
{
Expand Down Expand Up @@ -168,7 +168,7 @@ describe('#library-builder', () => {

expect(libraryBuilder.components.size).toEqual(0);
await libraryBuilder.initialize();
expect(libraryBuilder.components.size).toEqual(4);
expect(libraryBuilder.components.size).toEqual(3);

const barComponent = libraryBuilder.components.get(`${libDirPath}/common/bar`);
expect(barComponent).toBeTruthy();
Expand Down Expand Up @@ -335,7 +335,7 @@ describe('#library-builder', () => {
const ngParserSpectator = new NgParserSpectator();

const tsconfig = resolve(libDirPath, 'tsconfig.lib.json');
context.host.writeFile(tsconfig, '{includes: []}');
context.host.writeFile(tsconfig, `{include: []}`);
const libraryBuilder = new LibraryBuilderImpl(context, library);
expect(libraryBuilder.getNgDocParser()).toBeFalsy();
ngParserSpectator.notHaveBeenCalled();
Expand Down
18 changes: 6 additions & 12 deletions packages/core/src/builders/library-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,17 @@ export class LibraryBuilderImpl extends FileEmitter implements LibraryBuilder {
public async initialize(): Promise<void> {
this.buildLocaleCategoriesMap(this.lib.categories);

const components: LibraryComponentImpl[] = [];
const includes = this.lib.include ? toolkit.utils.coerceArray(this.lib.include) : [];
const excludes = [...this.lib.exclude];
for (const include of includes) {
// 比如示例中的 common/zoo, 那么 common 文件夹不是一个组件,所以需要把 includes 都排除
if (include === '' || include === './') {
excludes.push(...includes);
}
const includeAbsPath = resolve(this.absLibPath, include);
const dirExists = await this.docgeni.host.pathExists(includeAbsPath);
if (dirExists) {
const subDirs = await this.docgeni.host.getDirs(includeAbsPath, { exclude: this.lib.exclude });
const subDirs = await this.docgeni.host.getDirs(includeAbsPath, { exclude: excludes });
subDirs.forEach(dir => {
const absComponentPath = resolve(includeAbsPath, dir);
const component = new LibraryComponentImpl(this.docgeni, this.lib, dir, absComponentPath);
Expand All @@ -47,16 +51,6 @@ export class LibraryBuilderImpl extends FileEmitter implements LibraryBuilder {
}
}

// 比如示例中的 common/zoo, 那么 common 文件夹不是一个组件
const excludes = this.lib.exclude ? toolkit.utils.coerceArray(this.lib.exclude) : [];
const dirs = await this.docgeni.host.getDirs(this.absLibPath, { exclude: [...excludes] });
dirs.forEach(dir => {
const absComponentPath = resolve(this.absLibPath, dir);
const component = new LibraryComponentImpl(this.docgeni, this.lib, dir, absComponentPath);
components.push(component);
this.componentsMap.set(absComponentPath, component);
});

this.watch();
await this.initializeNgDocParser();
}
Expand Down

0 comments on commit 76d1e78

Please sign in to comment.