|
| 1 | +import * as path from 'path'; |
| 2 | +import * as vscode from 'vscode'; |
| 3 | +import * as editor from '../utils/editor-helper'; |
| 4 | +import { ApplicationError } from '../utils/errors'; |
| 5 | +import * as fileManager from '../utils/file-manager'; |
| 6 | + |
| 7 | +const INDEX_FILE_NAME = 'index.ts'; |
| 8 | + |
| 9 | +const getFilePath = (): string => { |
| 10 | + if (!editor.fileIsOpened()) { |
| 11 | + throw new ApplicationError('No file is opened.'); |
| 12 | + } |
| 13 | + |
| 14 | + if (!editor.fileIsSaved()) { |
| 15 | + throw new ApplicationError('The file is not saved yet.'); |
| 16 | + } |
| 17 | + |
| 18 | + return editor.getCurrentFilePath(); |
| 19 | +}; |
| 20 | + |
| 21 | +const getIndexPath = (filePath: string): string => { |
| 22 | + const dirPath = path.dirname(filePath); |
| 23 | + return path.join(dirPath, INDEX_FILE_NAME); |
| 24 | +}; |
| 25 | + |
| 26 | +const getExportationLine = (filePath: string): string => { |
| 27 | + const fileName = path.basename(filePath); |
| 28 | + const fileNameWithoutExtension = fileName.split('.')[0]; |
| 29 | + return `export * from './${fileNameWithoutExtension}';`; |
| 30 | +}; |
| 31 | + |
| 32 | +const writeLineAndSort = (filePath: string, line: string): void => { |
| 33 | + const lines = fileManager.getLines(filePath).filter(l => l !== ''); |
| 34 | + |
| 35 | + if (!lines.includes(line)) { |
| 36 | + lines.push(line); |
| 37 | + } |
| 38 | + |
| 39 | + lines.sort(); |
| 40 | + const written = `${lines.join('\n')}\n`; |
| 41 | + |
| 42 | + fileManager.writeFile(filePath, written); |
| 43 | +}; |
| 44 | + |
| 45 | +export const addCurrentFileExportationToIndex = () => { |
| 46 | + try { |
| 47 | + const filePath = getFilePath(); |
| 48 | + const indexFilePath = getIndexPath(filePath); |
| 49 | + |
| 50 | + if (filePath === indexFilePath) { |
| 51 | + throw new ApplicationError('The file is index.ts itself.'); |
| 52 | + } |
| 53 | + |
| 54 | + if (!filePath.match(/\.ts$/)) { |
| 55 | + throw new ApplicationError('The file is not TypeScript.'); |
| 56 | + } |
| 57 | + |
| 58 | + fileManager.createFileIfNotExists(indexFilePath); |
| 59 | + |
| 60 | + const exportationLine = getExportationLine(filePath); |
| 61 | + writeLineAndSort(indexFilePath, exportationLine); |
| 62 | + } catch (err) { |
| 63 | + if (err instanceof ApplicationError) { |
| 64 | + vscode.window.showErrorMessage(err.message); |
| 65 | + return; |
| 66 | + } |
| 67 | + |
| 68 | + throw err; |
| 69 | + } |
| 70 | + |
| 71 | +}; |
0 commit comments