FindParent is a command-line tool to navigate a dynamically built file system and find the closest parent directory that contains two given file paths. The file system is constructed based on the input paths provided by the user.
- Clone the repository:
git clone https://github.com/yourusername/findparent-cli.git
cd findparent-cli- Install the dependencies:
npm install- Build the project:
npm run buildTo find the common parent of two file paths, use the following command:
npm start "<path1>" "<path2>"npm start "a/b/c" "a/b/d"This command will output:
Common parent: bGiven the file system structure:
root
├── a
│ ├── c
│ └── d
└── bnpm start "a/c" "a/d" will output Common parent: a
npm start "a/c" "b" will output Common parent: root
To add new tests, update the test/fileSystem.spec.ts file. You can run the tests using:
npm testThe file system is dynamically built from the paths provided. The buildFileSystem function handles the creation of the file nodes and their hierarchical structure.
The findParent function leverages Depth-First Search (DFS) to find the common parent directory of two given files. Here's how it works:
- Start from the Root: The function begins at the root node and pushes it onto the path.
- Check if Root is the Target: If the current node (
root) is the target node, the function returnstrue. - Recursively Search Children: If the current node is not the target, the function recursively searches each child.
- If any recursive call returns
true, indicating the target was found in that subtree, the current call also returnstrue. - If no children lead to the target, the current node is removed from the path (backtracking) and the function returns
false.
- If any recursive call returns
- Path Construction: By the end of the function, if the target is found,
pathcontains the sequence of nodes from the root to the target.
- Find Paths: The function uses
findPathto get the paths from the root to both target files (file1andfile2). - Compare Paths: The function then compares these paths to find the deepest common ancestor.
- It iterates through both paths until the nodes differ.
- The last common node before the paths diverge is the closest common parent.