From 04a0fd02e3e00e78f80f61370446e2d249c948c3 Mon Sep 17 00:00:00 2001 From: Alexander Zech Date: Tue, 30 May 2023 23:08:41 +0300 Subject: [PATCH] chore: add object path utility fn --- src/utils/file.js | 18 ++++++++++++++++++ src/utils/index.js | 2 ++ tests/utils/file.tests.js | 11 +++++++++++ 3 files changed, 31 insertions(+) create mode 100644 tests/utils/file.tests.js diff --git a/src/utils/file.js b/src/utils/file.js index 7b3af268..b738774e 100644 --- a/src/utils/file.js +++ b/src/utils/file.js @@ -58,3 +58,21 @@ export function getDirectories(currentPath) { .filter((dirent) => dirent.isDirectory()) .map((dirent) => dirent.name); } + +/** + * Construct object path compatible with lodash.get/lodash.set from file path. + * Note: if no root path is provided the file's dirname is taken instead. + * @param {string} filePath - Path to file. + * @param {string} root - Path to a parent directory to construct relative path. + * @return {string} - Object path reflecting file path. + * @example + * createObjectPathFromFilePath("/a/b/c/d/e.yml", "/a/b"); + * // "['c']['d']['e']" + */ +export function createObjectPathFromFilePath(filePath, root) { + const dirname = path.dirname(filePath); + const extension = path.extname(filePath); + const basename = path.basename(filePath, extension); + const parentDirs = root ? path.relative(root, dirname).split(path.sep) : []; + return [...parentDirs, basename].map((item) => `['${item}']`).join(""); +} diff --git a/src/utils/index.js b/src/utils/index.js index c65981fd..b4e6f288 100644 --- a/src/utils/index.js +++ b/src/utils/index.js @@ -4,6 +4,7 @@ import { cloneClass, extendClass, extendClassStaticProps, extendThis } from "./c import { deepClone } from "./clone"; import { refreshCodeMirror } from "./codemirror"; import { + createObjectPathFromFilePath, formatFileSize, getDirectories, getFilesInDirectory, @@ -90,4 +91,5 @@ export { filterEntityList, getFilesInDirectory, getDirectories, + createObjectPathFromFilePath, }; diff --git a/tests/utils/file.tests.js b/tests/utils/file.tests.js new file mode 100644 index 00000000..e75180fb --- /dev/null +++ b/tests/utils/file.tests.js @@ -0,0 +1,11 @@ +import { expect } from "chai"; + +import { createObjectPathFromFilePath } from "../../src/utils/file"; + +describe("file utilities", () => { + it("should create an object path from a file path", () => { + const thisFile = "/code.js/tests/utils/file.tests.js"; + const objectPath = createObjectPathFromFilePath(thisFile, "/code.js"); + expect(objectPath).to.be.equal("['tests']['utils']['file.tests']"); + }); +});