2023-03-15 16:00:52 +00:00
|
|
|
/**
|
|
|
|
* Copyright (c) HashiCorp, Inc.
|
|
|
|
* SPDX-License-Identifier: MPL-2.0
|
|
|
|
*/
|
|
|
|
|
2018-08-16 17:48:24 +00:00
|
|
|
import flat from 'flat';
|
|
|
|
import deepmerge from 'deepmerge';
|
|
|
|
|
|
|
|
const { unflatten } = flat;
|
|
|
|
const DOT_REPLACEMENT = '☃';
|
|
|
|
|
|
|
|
//function that takes a list of path and returns a deeply nested object
|
|
|
|
//representing a tree of all of those paths
|
|
|
|
//
|
|
|
|
//
|
|
|
|
// given ["foo", "bar", "foo1", "foo/bar", "foo/baz", "foo/bar/baz"]
|
|
|
|
//
|
|
|
|
// returns {
|
|
|
|
// bar: null,
|
|
|
|
// foo: {
|
|
|
|
// bar: {
|
|
|
|
// baz: null
|
|
|
|
// },
|
|
|
|
// baz: null,
|
|
|
|
// },
|
|
|
|
// foo1: null,
|
|
|
|
// }
|
2021-12-17 03:44:29 +00:00
|
|
|
export default function (paths) {
|
2018-08-16 17:48:24 +00:00
|
|
|
// first sort the list by length, then alphanumeric
|
2022-11-09 23:15:31 +00:00
|
|
|
const list = paths.slice(0).sort((a, b) => b.length - a.length || b.localeCompare(a));
|
2018-08-16 17:48:24 +00:00
|
|
|
// then reduce to an array
|
|
|
|
// and we remove all of the items that have a string
|
|
|
|
// that starts with the same prefix from the list
|
|
|
|
// so if we have "foo/bar/baz", both "foo" and "foo/bar"
|
|
|
|
// won't be included in the list
|
|
|
|
let tree = list.reduce((accumulator, ns) => {
|
2022-11-09 23:15:31 +00:00
|
|
|
const nsWithPrefix = accumulator.find((path) => path.startsWith(ns));
|
2018-08-16 17:48:24 +00:00
|
|
|
// we need to make sure it's a match for the full path part
|
2022-11-09 23:15:31 +00:00
|
|
|
const isFullMatch = nsWithPrefix && nsWithPrefix.charAt(ns.length) === '/';
|
2018-08-16 17:48:24 +00:00
|
|
|
if (!isFullMatch) {
|
|
|
|
accumulator.push(ns);
|
|
|
|
}
|
|
|
|
return accumulator;
|
|
|
|
}, []);
|
|
|
|
|
2019-08-22 19:00:53 +00:00
|
|
|
tree = tree.sort((a, b) => a.localeCompare(b));
|
2018-08-16 17:48:24 +00:00
|
|
|
// after the reduction we're left with an array that contains
|
|
|
|
// strings that represent the longest branches
|
|
|
|
// we'll replace the dots in the paths, then expand the path
|
|
|
|
// to a nested object that we can then query with Ember.get
|
|
|
|
return deepmerge.all(
|
2021-12-17 03:44:29 +00:00
|
|
|
tree.map((p) => {
|
2018-08-16 17:48:24 +00:00
|
|
|
p = p.replace(/\.+/g, DOT_REPLACEMENT);
|
2019-08-22 19:00:53 +00:00
|
|
|
return unflatten({ [p]: null }, { delimiter: '/', object: true });
|
2018-08-16 17:48:24 +00:00
|
|
|
})
|
|
|
|
);
|
|
|
|
}
|