Skip to content

Commit

Permalink
feat(api): add generateManyIndex
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Apr 17, 2020
1 parent 7374e39 commit 30f0320
Show file tree
Hide file tree
Showing 8 changed files with 176 additions and 50 deletions.
18 changes: 11 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -186,15 +186,19 @@ pnpx vscode-generate-index-standalone src/ scripts/
#### API

```js
import { generateIndex } from 'vscode-generate-index-standalone'
import { generateIndex, generateManyIndex } from 'vscode-generate-index-standalone'
import { join } from 'path'

const indexedFileContent = await generateIndex(
// The file path
join(__dirname, '../src/index.ts'),
// Whether to replace the file
true,
)
const generateResult = await generateIndex({
filePath: join(__dirname, '../src/index.ts'),
replaceFile: true,
}

const generateManyResult = await generateManyIndex({
patterns: ['../src/**/index.ts', '!**/ignore/index.ts'],
cwd: __dirname,
replaceFile: true,
})
```
## License
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@
},
"dependencies": {
"change-case": "^3.1.0",
"fs-extra": "^9.0.0",
"globby": "^10.0.0",
"vtils": "^2.7.1",
"yargs": "^15.3.1"
Expand All @@ -91,7 +92,6 @@
"@types/rimraf": "^3.0.0",
"cross-spawn": "^7.0.2",
"eslint": "^6",
"fs-extra": "^9.0.0",
"haoma": "^1.7.0",
"husky": "^4",
"jest": "^25.3.0",
Expand Down
3 changes: 2 additions & 1 deletion src/IndexGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export interface IndexGeneratorOptions {
export class IndexGenerator {
constructor(private options: IndexGeneratorOptions) {}

public async generate() {
public async generate(): Promise<false | void> {
const { filePath, fileContent, onWarning, onGenerate } = this.options
const fileDir = dirname(filePath)
const markers = IndexGenerator.findMarkers(fileContent, onWarning)
Expand Down Expand Up @@ -83,6 +83,7 @@ export class IndexGenerator {
}
} else {
onWarning('No @index maker found.')
return false
}
}

Expand Down
26 changes: 24 additions & 2 deletions src/__snapshots__/generateIndex.test.ts.snap
Original file line number Diff line number Diff line change
@@ -1,5 +1,29 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`many: res[0].generatedFileContent 1`] = `
"// @index('./*', f => \`export * from '\${f.path}'\`)
export * from './_8'
export * from './1'
export * from './x'
export * from './国家'
// @endindex"
`;

exports[`many: successMsgs 1`] = `
Array [
"index.ts",
]
`;

exports[`many: warningMsgs 1`] = `
Array [
"1.ts: No @index maker found.",
"_8.ts: No @index maker found.",
"国家.ts: No @index maker found.",
"x.ts: No @index maker found.",
]
`;

exports[`normal: file content 1`] = `
"// @index('./*', f => \`export * from '\${f.path}'\`)
// @endindex"
Expand All @@ -14,8 +38,6 @@ export * from './国家'
// @endindex"
`;

exports[`not found 1`] = `[Error: File not found.]`;

exports[`replace: file content 1`] = `
"// @index('./*', f => \`export * from '\${f.path}'\`)
export * from './_8'
Expand Down
39 changes: 22 additions & 17 deletions src/cli.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
#!/usr/bin/env node
import globby from 'globby'
import yargs from 'yargs'
import { generateIndex } from './generateIndex'
import { generateManyIndex } from './generateIndex'
import { IndexGenerator } from './IndexGenerator'

const argv = yargs
Expand All @@ -13,23 +12,29 @@ const argv = yargs
describe: 'Current working directory',
default: process.cwd(),
})
.option('debug', {
type: 'boolean',
describe: 'Debug mode',
default: false,
})
// Show help if no args
// ref: https://github.com/yargs/yargs/issues/895
.demandCommand(1, '').argv

const filePaths = !argv._.length
? []
: globby.sync(argv._, {
absolute: true,
cwd: argv.cwd,
dot: true,
onlyFiles: true,
unique: true,
gitignore: false,
})

for (const filePath of filePaths) {
generateIndex(filePath, true).then(() => {
generateManyIndex({
patterns: argv._,
replaceFile: true,
cwd: argv.cwd,
onSuccess: filePath => {
console.log(`✔️ ${IndexGenerator.getRelativePath(argv.cwd, filePath)}`)
})
}
},
onWarning: (filePath, msg) => {
if (argv.debug) {
console.warn(
`⚠️ ${msg} <${IndexGenerator.getRelativePath(argv.cwd, filePath)}>`,
)
}
},
}).catch(err => {
throw err
})
46 changes: 38 additions & 8 deletions src/generateIndex.test.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import tmp from 'tempy'
import { basename, join } from 'path'
import { dedent } from 'vtils'
import { generateIndex } from './generateIndex'
import { join } from 'path'
import { generateIndex, generateManyIndex } from './generateIndex'
import { readFileSync, writeFileSync } from 'fs'
import { sync as rmrf } from 'rimraf'

let dir: string

beforeAll(() => {
beforeEach(() => {
dir = tmp.directory()
writeFileSync(
join(dir, 'index.ts'),
Expand All @@ -22,20 +22,25 @@ beforeAll(() => {
writeFileSync(join(dir, '_8.ts'), '')
})

afterAll(() => {
afterEach(() => {
rmrf(dir)
})

test('normal', async () => {
const generatedContent = await generateIndex(join(dir, 'index.ts'))
const generatedContent = await generateIndex({
filePath: join(dir, 'index.ts'),
})
expect(generatedContent).toMatchSnapshot('generated content')
expect(readFileSync(join(dir, 'index.ts')).toString()).toMatchSnapshot(
'file content',
)
})

test('replace', async () => {
const generatedContent = await generateIndex(join(dir, 'index.ts'), true)
const generatedContent = await generateIndex({
filePath: join(dir, 'index.ts'),
replaceFile: true,
})
expect(generatedContent).toMatchSnapshot('generated content')
expect(readFileSync(join(dir, 'index.ts')).toString()).toMatchSnapshot(
'file content',
Expand All @@ -45,9 +50,34 @@ test('replace', async () => {
test('not found', async () => {
let err: any
try {
await generateIndex(join(dir, 'no-file'))
await generateIndex({
filePath: join(dir, 'no-file'),
})
} catch (e) {
err = e
}
expect(err).toMatchSnapshot()
expect(err).toBeInstanceOf(Error)
expect(String(err)).toMatch(/File not found.*no-file/)
})

test('many', async () => {
const successMsgs: string[] = []
const warningMsgs: string[] = []
const res = await generateManyIndex({
patterns: [dir],
replaceFile: true,
onSuccess: filePath => {
successMsgs.push(basename(filePath))
},
onWarning: (filePath, msg) => {
warningMsgs.push(`${basename(filePath)}: ${msg}`)
},
})
expect(res.length).toEqual(1)
expect(res[0].filePath).toMatch(/index\.ts/)
expect(res[0].generatedFileContent).toMatchSnapshot(
'res[0].generatedFileContent',
)
expect(successMsgs).toMatchSnapshot('successMsgs')
expect(warningMsgs).toMatchSnapshot('warningMsgs')
})
88 changes: 76 additions & 12 deletions src/generateIndex.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,25 @@
import { existsSync, readFileSync, writeFileSync } from 'fs'
import globby from 'globby'
import { IndexGenerator } from './IndexGenerator'
import { Merge } from 'vtils'
import { pathExists, readFile, writeFile } from 'fs-extra'

export interface GenerateIndexPayload {
filePath: string
replaceFile?: boolean
onWarning?: (msg: string) => any
}

export async function generateIndex(
filePath: string,
replaceFile = false,
onWarning?: (msg: string) => any,
): Promise<string> {
if (!existsSync(filePath)) {
throw new Error('File not found.')
{
filePath,
replaceFile = false,
onWarning,
}: GenerateIndexPayload = {} as any,
): Promise<string | false> {
if (!(await pathExists(filePath))) {
throw new Error(`File not found. <${filePath}>`)
}
let fileContent = readFileSync(filePath).toString()
let fileContent = (await readFile(filePath)).toString()
const generator = new IndexGenerator({
filePath: filePath,
fileContent: fileContent,
Expand All @@ -23,9 +33,63 @@ export async function generateIndex(
fileContent.substr(marker.end, fileContent.length)
},
})
await generator.generate()
if (replaceFile) {
writeFileSync(filePath, fileContent)
const generateResult = await generator.generate()
if (generateResult !== false && replaceFile) {
await writeFile(filePath, fileContent)
}
return fileContent
return generateResult === false ? false : fileContent
}

export interface GenerateManyIndexPayload {
patterns: string | string[]
cwd?: string
replaceFile: boolean
onWarning?: (filePath: string, msg: string) => any
onSuccess?: (filePath: string) => any
}

export interface GenerateManyIndexResult {
filePath: string
generatedFileContent: string
}

export async function generateManyIndex(
{
patterns,
cwd = process.cwd(),
replaceFile = false,
onWarning,
onSuccess,
}: GenerateManyIndexPayload = {} as any,
): Promise<GenerateManyIndexResult[]> {
if (!patterns.length) return []
const filePaths = await globby(patterns, {
absolute: true,
cwd: cwd,
dot: true,
onlyFiles: true,
unique: true,
gitignore: false,
})
const result = await Promise.all(
filePaths.map<
Promise<
Merge<GenerateManyIndexResult, { generatedFileContent: string | false }>
>
>(async filePath => {
const generatedFileContent = await generateIndex({
filePath: filePath,
replaceFile: replaceFile,
onWarning: msg => onWarning?.(filePath, msg),
})
if (generatedFileContent !== false) {
onSuccess?.(filePath)
}
return {
filePath: filePath,
generatedFileContent: generatedFileContent,
}
}),
)
return result.filter(item => item.generatedFileContent !== false) as any
}
4 changes: 2 additions & 2 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
{
"compilerOptions": {
"module": "CommonJS",
"target": "ES6",
"target": "ES2018",
"outDir": "out",
"lib": ["ES6"],
"lib": ["ES2018"],
"sourceMap": true,
"declaration": true,
"esModuleInterop": true,
Expand Down

0 comments on commit 30f0320

Please sign in to comment.