Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions src/utils/file.js
Original file line number Diff line number Diff line change
Expand Up @@ -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("");
}
2 changes: 2 additions & 0 deletions src/utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { cloneClass, extendClass, extendClassStaticProps, extendThis } from "./c
import { deepClone } from "./clone";
import { refreshCodeMirror } from "./codemirror";
import {
createObjectPathFromFilePath,
formatFileSize,
getDirectories,
getFilesInDirectory,
Expand Down Expand Up @@ -90,4 +91,5 @@ export {
filterEntityList,
getFilesInDirectory,
getDirectories,
createObjectPathFromFilePath,
};
11 changes: 11 additions & 0 deletions tests/utils/file.tests.js
Original file line number Diff line number Diff line change
@@ -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']");
});
});