From 1da41aa1aa81eecb93720405291a7dadd0cefe0c Mon Sep 17 00:00:00 2001 From: Lloyd Francis Date: Sun, 23 Aug 2020 20:13:05 +0530 Subject: [PATCH] Child directory support (#16) * Adding base-url and add-path feature support from child directories * Adding child directory support for cleanup * Fixing a bug for cleanup * Updating README --- README.md | 4 +- package-lock.json | 192 ++++++++++++++++++++++--- package.json | 3 +- src/lib/cleanup.ts | 8 +- src/lib/configure.ts | 33 ++--- src/util/__tests__/file.util.test.ts | 4 +- src/util/__tests__/string.util.test.ts | 3 +- src/util/file.util.ts | 33 +++-- src/util/string.util.ts | 7 + 9 files changed, 227 insertions(+), 60 deletions(-) diff --git a/README.md b/README.md index e16dbe1..7758a54 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ ![npm bundle size](https://img.shields.io/bundlephobia/min/unrelate) ![npm](https://img.shields.io/npm/v/unrelate) -This library is used to transform relative paths into absolute paths for [TypeScript](https://www.typescriptlang.org) projects. **You should have a [tsconfig.json](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html) file present in the directory where you run this tool.** +This library is used to transform relative paths into absolute paths for [TypeScript](https://www.typescriptlang.org) projects. ## Usage @@ -48,7 +48,7 @@ npx unrelate ## Base URL -Before you start using `unrelate`, you have to configure the [baseUrl](https://www.typescriptlang.org/docs/handbook/module-resolution.html#base-url) property in your `tsconfig.json` file. It informs the compiler where to find modules. All absolute import paths you configure using `unrelate`, are always relative to the `baseUrl`. So set the property to the folder that contains, or contains subfolders that contains all the `.ts` files that would use the absolute imports. It's common to set `baseUrl` to the project root folder or the `src` or `lib` folders, depending on where most of your code lies. +Before you start using `unrelate`, you have to configure the [baseUrl](https://www.typescriptlang.org/docs/handbook/module-resolution.html#base-url) property in your [tsconfig.json](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html) file. It informs the compiler where to find modules. All absolute import paths you configure using `unrelate`, are always relative to the `baseUrl`. So set the property to the folder that contains, or contains subfolders that contains all the `.ts` files that would use the absolute imports. It's common to set `baseUrl` to the project root folder or the `src` or `lib` folders, depending on where most of your code lies. ### Configuration diff --git a/package-lock.json b/package-lock.json index 5b15e4f..d18c591 100644 --- a/package-lock.json +++ b/package-lock.json @@ -391,6 +391,43 @@ "resolve-from": "^5.0.0" }, "dependencies": { + "find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, + "requires": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + } + }, + "locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, + "requires": { + "p-locate": "^4.1.0" + } + }, + "p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, + "requires": { + "p-try": "^2.0.0" + } + }, + "p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, + "requires": { + "p-limit": "^2.2.0" + } + }, "resolve-from": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", @@ -2508,12 +2545,11 @@ } }, "find-up": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", - "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", - "dev": true, + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", "requires": { - "locate-path": "^5.0.0", + "locate-path": "^6.0.0", "path-exists": "^4.0.0" } }, @@ -4623,12 +4659,11 @@ "dev": true }, "locate-path": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", - "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", - "dev": true, + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", "requires": { - "p-locate": "^4.1.0" + "p-locate": "^5.0.0" } }, "lodash": { @@ -4991,28 +5026,25 @@ "dev": true }, "p-limit": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", - "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", - "dev": true, + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.0.2.tgz", + "integrity": "sha512-iwqZSOoWIW+Ew4kAGUlN16J4M7OB3ysMLSZtnhmqx7njIHFPlxWBX8xo3lVTyFVq6mI/lL9qt2IsN1sHwaxJkg==", "requires": { "p-try": "^2.0.0" } }, "p-locate": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", - "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", - "dev": true, + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", "requires": { - "p-limit": "^2.2.0" + "p-limit": "^3.0.2" } }, "p-try": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", - "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", - "dev": true + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==" }, "parent-module": { "version": "1.0.1", @@ -5050,8 +5082,7 @@ "path-exists": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", - "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", - "dev": true + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==" }, "path-is-absolute": { "version": "1.0.1", @@ -5099,6 +5130,45 @@ "dev": true, "requires": { "find-up": "^4.0.0" + }, + "dependencies": { + "find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, + "requires": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + } + }, + "locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, + "requires": { + "p-locate": "^4.1.0" + } + }, + "p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, + "requires": { + "p-try": "^2.0.0" + } + }, + "p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, + "requires": { + "p-limit": "^2.2.0" + } + } } }, "posix-character-classes": { @@ -5246,6 +5316,45 @@ "find-up": "^4.1.0", "read-pkg": "^5.2.0", "type-fest": "^0.8.1" + }, + "dependencies": { + "find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, + "requires": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + } + }, + "locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, + "requires": { + "p-locate": "^4.1.0" + } + }, + "p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, + "requires": { + "p-try": "^2.0.0" + } + }, + "p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, + "requires": { + "p-limit": "^2.2.0" + } + } } }, "regex-not": { @@ -6643,12 +6752,49 @@ "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", "dev": true }, + "find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, + "requires": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + } + }, "is-fullwidth-code-point": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", "dev": true }, + "locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, + "requires": { + "p-locate": "^4.1.0" + } + }, + "p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, + "requires": { + "p-try": "^2.0.0" + } + }, + "p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, + "requires": { + "p-limit": "^2.2.0" + } + }, "string-width": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.0.tgz", diff --git a/package.json b/package.json index 5a707ee..ae94362 100644 --- a/package.json +++ b/package.json @@ -25,7 +25,8 @@ "author": "lloydaf", "license": "MIT", "dependencies": { - "comment-json": "^3.0.3" + "comment-json": "^3.0.3", + "find-up": "^5.0.0" }, "devDependencies": { "@types/comment-json": "^1.1.1", diff --git a/src/lib/cleanup.ts b/src/lib/cleanup.ts index a569b11..ee43f2e 100644 --- a/src/lib/cleanup.ts +++ b/src/lib/cleanup.ts @@ -5,6 +5,7 @@ import { doesItExist, fileOrFolder, getDirectoryItems, + getAbsolutePathRelativeToBaseUrl, } from '../util/file.util'; import { CommentJSONValue } from 'comment-json'; import { dirname } from 'path'; @@ -37,17 +38,19 @@ export async function cleanup(paramPath: string): Promise { const configManager = configFileDataManager(); const configFile: CommentJSONValue = (await configManager.next()).value; const configuredPathsObj: Record = configFile?.compilerOptions?.paths; - const baseUrl: string = configFile?.compilerOptions?.baseUrl; + let baseUrl: string = configFile?.compilerOptions?.baseUrl; if (!configuredPathsObj || !baseUrl) { throw new Error('You need to configure base-url and paths first'); } + !baseUrl.endsWith('/') && (baseUrl = `${baseUrl}/`); + // the configured paths const configuredPaths: Record = Object.entries(configuredPathsObj).reduce( (acc: Record, [key, val]: [string, string[]]) => ({ ...acc, - [getFilePath(baseUrl + val[0])]: removeTrailingCharacter(key, '*'), + [getAbsolutePathRelativeToBaseUrl(baseUrl + val[0])]: removeTrailingCharacter(key, '*'), }), {}, ); @@ -58,6 +61,7 @@ export async function cleanup(paramPath: string): Promise { const relativePathsInFile: string[] = file.match(RegExp(`(?<=['"]{1})(\\./)*(\\.\\./)+.*`, 'g')) || []; const absolutePathsInFile = relativePathsInFile.map((path: string) => getFilePath(`${dirname(paramPath)}/${path}`)) || []; + Object.entries(configuredPaths).forEach(([key, value]) => { absolutePathsInFile.forEach((path, index) => { if (path.includes(key)) { diff --git a/src/lib/configure.ts b/src/lib/configure.ts index b51fee5..3b07ad9 100644 --- a/src/lib/configure.ts +++ b/src/lib/configure.ts @@ -1,6 +1,6 @@ -import { configFileDataManager, doesItExist, fileOrFolder } from '../util/file.util'; +import { configFileDataManager, doesItExist, fileOrFolder, getPathFromProjectRoot } from '../util/file.util'; import { CommentJSONValue } from 'comment-json'; -import { removeTrailingCharacter } from '../util/string.util'; +import { removeTrailingCharacter, removeLeadingCharacter } from '../util/string.util'; import { Commands, PathTypes } from '../model/enums'; export async function configure(action: string, value: string): Promise { @@ -27,35 +27,31 @@ export async function addPath(path: string): Promise { if (!doesItExist(path)) { throw new Error(`Not a valid ${fileOrFolder(path)} path`); } - if (!path.startsWith('./')) { - path = `./${path}`; - } + let relativePath = await getPathFromProjectRoot(path); const manager = configFileDataManager(); const data = (await manager.next()).value; const baseUrl = data?.compilerOptions?.baseUrl; if (!baseUrl) { throw new Error(`${Commands.BASE_URL} must be configured before adding paths`); } - if (baseUrl === path) { + if (baseUrl === relativePath) { throw new Error(`${Commands.BASE_URL} and path cannot be the same`); } - if (path.includes(baseUrl)) { - path = path.replace(baseUrl, ''); - } - path = removeTrailingCharacter(path, '/'); + relativePath = removeLeadingCharacter(relativePath.replace(baseUrl, ''), '/'); + relativePath = removeTrailingCharacter(relativePath, '/'); const paths = data.compilerOptions.paths || {}; - const keyStart = path.lastIndexOf('/') || 0; - const key = path.slice(keyStart + 1); + const keyStart = relativePath.lastIndexOf('/') || 0; + const key = relativePath.slice(keyStart + 1); // This allows adding a path for a file as well switch (fileOrFolder(path)) { case PathTypes.FILE: { - paths[`@${key.slice(0, key.lastIndexOf('.'))}`] = [`${path.slice(0, path.lastIndexOf('.'))}`]; + paths[`@${key.slice(0, key.lastIndexOf('.'))}`] = [`${relativePath.slice(0, path.lastIndexOf('.'))}`]; break; } case PathTypes.FOLDER: { - paths[`@${key}*`] = [`${path}*`]; - doesItExist(`${path}/index.ts`) && (paths[`@${key}`] = [`${path}/index`]); + paths[`@${key}*`] = [`${relativePath}*`]; + doesItExist(`${path}/index.ts`) && (paths[`@${key}`] = [`${relativePath}/index`]); break; } } @@ -73,12 +69,7 @@ export async function configureBaseUrl(baseUrl: string): Promise { } const manager = configFileDataManager(); const data: CommentJSONValue = (await manager.next()).value; - if (baseUrl === '.') { - baseUrl = './'; - } - if (!baseUrl.startsWith('./')) { - baseUrl = `./${baseUrl}`; - } + baseUrl = await getPathFromProjectRoot(baseUrl); data.compilerOptions.baseUrl = baseUrl; await manager.next(data); } diff --git a/src/util/__tests__/file.util.test.ts b/src/util/__tests__/file.util.test.ts index 0b19118..7ed68b3 100644 --- a/src/util/__tests__/file.util.test.ts +++ b/src/util/__tests__/file.util.test.ts @@ -1,12 +1,14 @@ import * as exported from '../file.util'; describe('tests for config-file.util', () => { - it('should export configFileDataManager, fileDataManager, getFilePath, doesItExist, fileOrFolder, getDirectoryItems', () => { + it('should export configFileDataManager, fileDataManager, getFilePath, doesItExist, fileOrFolder, getDirectoryItems, getPathFromProjectRoot, getAbsolutePathRelativeToBaseUrl', () => { expect(exported['configFileDataManager']).toBeTruthy(); expect(exported['fileDataManager']).toBeTruthy(); expect(exported['getFilePath']).toBeTruthy(); expect(exported['doesItExist']).toBeTruthy(); expect(exported['fileOrFolder']).toBeTruthy(); expect(exported['getDirectoryItems']).toBeTruthy(); + expect(exported['getPathFromProjectRoot']).toBeTruthy(); + expect(exported['getAbsolutePathRelativeToBaseUrl']).toBeTruthy(); }); }); diff --git a/src/util/__tests__/string.util.test.ts b/src/util/__tests__/string.util.test.ts index c137a35..6b1d069 100644 --- a/src/util/__tests__/string.util.test.ts +++ b/src/util/__tests__/string.util.test.ts @@ -1,7 +1,8 @@ import * as exported from '../string.util'; describe('tests for string.util', () => { - it('should export removeTrailingCharacter', () => { + it('should export removeTrailingCharacter, removeLeadingCharacter', () => { expect(exported['removeTrailingCharacter']).toBeTruthy(); + expect(exported['removeLeadingCharacter']).toBeTruthy(); }); }); diff --git a/src/util/file.util.ts b/src/util/file.util.ts index d500d94..8d6030d 100644 --- a/src/util/file.util.ts +++ b/src/util/file.util.ts @@ -1,17 +1,18 @@ import files, { promises as fs } from 'fs'; import { parse, stringify, CommentJSONValue } from 'comment-json'; import { Config, PathTypes } from '../model/enums'; -import { resolve } from 'path'; -import { removeTrailingCharacter } from './string.util'; +import { resolve, dirname } from 'path'; +import { removeTrailingCharacter, removeLeadingCharacter } from './string.util'; +import findUp from 'find-up'; async function saveFile(data: string, path: string): Promise { - const configFile = getFilePath(path); - await fs.writeFile(configFile, data, 'utf-8'); + const file = getFilePath(path); + await fs.writeFile(file, data, 'utf-8'); } async function getFile(path: string): Promise { - const configFile = getFilePath(path); - const data: string = await fs.readFile(configFile, 'utf-8'); + const file = getFilePath(path); + const data: string = await fs.readFile(file, 'utf-8'); return data; } @@ -22,6 +23,13 @@ export function getFilePath(relativeFilePath: string): string { return absoluteFilePath; } +export function getAbsolutePathRelativeToBaseUrl(relativeFilePath: string): string { + const projectRootDirectory = resolve(dirname(findUp.sync(Config.TSCONFIG) || Config.TSCONFIG)); + relativeFilePath = removeTrailingCharacter(relativeFilePath, '*'); + const absoluteFilePath = resolve(`${projectRootDirectory}/${relativeFilePath}`); + return absoluteFilePath; +} + export async function* fileDataManager(filePath: string): AsyncGenerator { const dataStr = await getFile(filePath); const data: string = yield dataStr; @@ -29,14 +37,21 @@ export async function* fileDataManager(filePath: string): AsyncGenerator { + const projectRootDirectory = resolve(dirname((await findUp(Config.TSCONFIG)) || Config.TSCONFIG)); + let currentPath = resolve(`${process.cwd()}/${path}`); + currentPath = removeLeadingCharacter(currentPath.replace(`${projectRootDirectory}`, ''), '/'); + return `./${currentPath}`; +} + /** * This is a generator function that is used to get/set data from tsconfig */ export async function* configFileDataManager(): AsyncGenerator { - const fileName = Config.TSCONFIG; - const dataStr = await getFile(fileName); + const configFilePath = (await findUp(Config.TSCONFIG)) || Config.TSCONFIG; + const dataStr = await fs.readFile(configFilePath, 'utf-8'); const data: CommentJSONValue = yield parse(dataStr); - await saveFile(stringify(data, null, 2), fileName); + await fs.writeFile(configFilePath, stringify(data, null, 2), 'utf-8'); return; } diff --git a/src/util/string.util.ts b/src/util/string.util.ts index 89a1ed3..1e82059 100644 --- a/src/util/string.util.ts +++ b/src/util/string.util.ts @@ -4,3 +4,10 @@ export function removeTrailingCharacter(str: string, character: string): string } return str; } + +export function removeLeadingCharacter(str: string, character: string): string { + if (str.slice(0, 1) === character) { + str = str.slice(1, str.length); + } + return str; +}