From 728399938a6af3658f060638121e229920b200b7 Mon Sep 17 00:00:00 2001 From: wancat Date: Tue, 29 Aug 2023 13:01:13 +0800 Subject: [PATCH] feat: update contains and add test cases --- packages/file-graph/file.js | 7 +++-- packages/file-graph/file.test.js | 49 ++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 2 deletions(-) create mode 100644 packages/file-graph/file.test.js diff --git a/packages/file-graph/file.js b/packages/file-graph/file.js index 986e280..983cbeb 100644 --- a/packages/file-graph/file.js +++ b/packages/file-graph/file.js @@ -2,7 +2,7 @@ import { basename } from './utils.js' export default class File { constructor({ path, type, discovered }) { - this.path = path + this.path = path.trimEnd('/') this.name = basename(path) this.type = type this.discovered = discovered @@ -13,6 +13,9 @@ export default class File { } contains(file) { - return this.isDirectory() && file.path.startsWith(this.path) + if (!this.isDirectory()) return false + if (this.path === file.path) return true + const parentPath = this.path.endsWith('/') ? this.path : `${this.path}/` + return file.path.startsWith(parentPath) } } diff --git a/packages/file-graph/file.test.js b/packages/file-graph/file.test.js new file mode 100644 index 0000000..175ac73 --- /dev/null +++ b/packages/file-graph/file.test.js @@ -0,0 +1,49 @@ +import File from './file.js' + +describe('File', () => { + let file + beforeEach(() => { + file = new File({ path: '/home/user', type: 'folder', discovered: true }) + }) + + const filesToCompare = [ + { + name: 'direct children', + path: '/home/user/file1.txt', + answer: true, + }, + { + name: 'nested children', + path: '/home/user/folder1/file1.txt', + answer: true, + }, + { + name: 'outer file', + path: '/etc/file1.txt', + answer: false, + }, + { + name: 'fake children', + path: '/home/user2/file2.txt', + answer: false, + }, + { + name: 'same', + path: '/home/user', + answer: true, + }, + { + name: 'same with trailing', + path: '/home/user/', + answer: true, + }, + ] + + filesToCompare.forEach(({ name, path, answer }) => { + test(`${name}: ${path}`, () => { + const fileToCompare = new File({ path, type: 'file', discovered: true }) + console.log(fileToCompare) + expect(file.contains(fileToCompare)).toBe(answer) + }) + }) +})