Skip to content

Commit 2c7ee7b

Browse files
authored
Merge pull request #47 from Exabyte-io/chore/SOF-6464
chore/SOF-6464
2 parents 31accf1 + 04a0fd0 commit 2c7ee7b

File tree

3 files changed

+31
-0
lines changed

3 files changed

+31
-0
lines changed

src/utils/file.js

+18
Original file line numberDiff line numberDiff line change
@@ -58,3 +58,21 @@ export function getDirectories(currentPath) {
5858
.filter((dirent) => dirent.isDirectory())
5959
.map((dirent) => dirent.name);
6060
}
61+
62+
/**
63+
* Construct object path compatible with lodash.get/lodash.set from file path.
64+
* Note: if no root path is provided the file's dirname is taken instead.
65+
* @param {string} filePath - Path to file.
66+
* @param {string} root - Path to a parent directory to construct relative path.
67+
* @return {string} - Object path reflecting file path.
68+
* @example
69+
* createObjectPathFromFilePath("/a/b/c/d/e.yml", "/a/b");
70+
* // "['c']['d']['e']"
71+
*/
72+
export function createObjectPathFromFilePath(filePath, root) {
73+
const dirname = path.dirname(filePath);
74+
const extension = path.extname(filePath);
75+
const basename = path.basename(filePath, extension);
76+
const parentDirs = root ? path.relative(root, dirname).split(path.sep) : [];
77+
return [...parentDirs, basename].map((item) => `['${item}']`).join("");
78+
}

src/utils/index.js

+2
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { cloneClass, extendClass, extendClassStaticProps, extendThis } from "./c
44
import { deepClone } from "./clone";
55
import { refreshCodeMirror } from "./codemirror";
66
import {
7+
createObjectPathFromFilePath,
78
formatFileSize,
89
getDirectories,
910
getFilesInDirectory,
@@ -87,4 +88,5 @@ export {
8788
filterEntityList,
8889
getFilesInDirectory,
8990
getDirectories,
91+
createObjectPathFromFilePath,
9092
};

tests/utils/file.tests.js

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { expect } from "chai";
2+
3+
import { createObjectPathFromFilePath } from "../../src/utils/file";
4+
5+
describe("file utilities", () => {
6+
it("should create an object path from a file path", () => {
7+
const thisFile = "/code.js/tests/utils/file.tests.js";
8+
const objectPath = createObjectPathFromFilePath(thisFile, "/code.js");
9+
expect(objectPath).to.be.equal("['tests']['utils']['file.tests']");
10+
});
11+
});

0 commit comments

Comments
 (0)