folder-tidy 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 kirtan-kalathiya
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,105 @@
1
+ # folder-tidy
2
+
3
+ `folder-tidy` is a proper Node.js CLI project for cleaning messy folders safely.
4
+
5
+ It now has:
6
+
7
+ - a cleaner project structure
8
+ - modular source files
9
+ - multiple organize modes
10
+ - manifest history
11
+ - undo support
12
+
13
+ ## Project Structure
14
+
15
+ ```text
16
+ folder-tidy/
17
+ ├─ index.js
18
+ ├─ package.json
19
+ └─ src/
20
+ ├─ cli.js
21
+ ├─ commands/
22
+ ├─ core/
23
+ └─ utils/
24
+ ```
25
+
26
+ ## Features
27
+
28
+ - `tidy` command for organizing files
29
+ - `undo` command for restoring the last run or a specific manifest
30
+ - organize by `type`, `name`, or `date`
31
+ - dry-run preview mode
32
+ - recursive scanning
33
+ - exclusion patterns
34
+ - hidden file support
35
+ - JSON report export
36
+ - automatic collision-safe renaming
37
+ - manifest storage in `.folder-tidy/`
38
+
39
+ ## Installation
40
+
41
+ ```bash
42
+ npm install -g folder-tidy
43
+ ```
44
+
45
+ ## Commands
46
+
47
+ ### Organize files
48
+
49
+ ```bash
50
+ folder-tidy tidy
51
+ folder-tidy tidy --target ./Downloads
52
+ folder-tidy tidy --mode name --dry-run
53
+ folder-tidy tidy --mode date --recursive
54
+ folder-tidy tidy --report reports/latest.json
55
+ ```
56
+
57
+ You can still use the short default style too:
58
+
59
+ ```bash
60
+ folder-tidy --dry-run
61
+ ```
62
+
63
+ ### Undo the last run
64
+
65
+ ```bash
66
+ folder-tidy undo
67
+ folder-tidy undo --target ./Downloads
68
+ folder-tidy undo --manifest .folder-tidy/manifest-123.json
69
+ folder-tidy undo --dry-run
70
+ ```
71
+
72
+ ## CLI Options For `tidy`
73
+
74
+ ```text
75
+ --target <path> Organize a specific directory
76
+ --mode <type|name|date> Choose how files are grouped
77
+ --dry-run Preview changes without moving files
78
+ --recursive Scan subfolders recursively
79
+ --exclude <patterns> Exclude files or folders, comma-separated globs
80
+ --include-hidden Include hidden files
81
+ --report <file> Save a JSON report
82
+ --no-manifest Skip saving an undo manifest
83
+ --verbose Show detailed logs
84
+ ```
85
+
86
+ ## CLI Options For `undo`
87
+
88
+ ```text
89
+ --target <path> Target directory that contains .folder-tidy manifests
90
+ --manifest <file> Restore a specific manifest file
91
+ --dry-run Preview restore actions without moving files
92
+ --verbose Show detailed logs
93
+ ```
94
+
95
+ ## Testing Locally
96
+
97
+ ```bash
98
+ node index.js --help
99
+ node index.js tidy --dry-run
100
+ node index.js undo --help
101
+ ```
102
+
103
+ ## Version
104
+
105
+ Current release: `1.0.0`
package/index.js ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+
3
+ require('./src/cli').run(process.argv.slice(2));
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "folder-tidy",
3
+ "version": "1.0.0",
4
+ "description": "A smarter CLI to organize messy folders by type, name, or date with undo support",
5
+ "main": "index.js",
6
+ "files": [
7
+ "index.js",
8
+ "src",
9
+ "README.md",
10
+ "LICENSE"
11
+ ],
12
+ "bin": {
13
+ "folder-tidy": "./index.js"
14
+ },
15
+ "scripts": {
16
+ "start": "node index.js",
17
+ "help": "node index.js --help",
18
+ "test:smoke": "node index.js --help && node index.js tidy --dry-run && node index.js undo --help",
19
+ "prepublishOnly": "npm run test:smoke"
20
+ },
21
+ "keywords": [
22
+ "folder-tidy",
23
+ "cli",
24
+ "file-organizer",
25
+ "downloads-cleaner",
26
+ "automation",
27
+ "filesystem",
28
+ "productivity",
29
+ "nodejs",
30
+ "undo",
31
+ "file-management"
32
+ ],
33
+ "author": "kirtan kalathiya",
34
+ "license": "MIT",
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/kirtan-kalathiya/folder-tidy.git"
38
+ },
39
+ "homepage": "https://github.com/kirtan-kalathiya/folder-tidy#readme",
40
+ "bugs": {
41
+ "url": "https://github.com/kirtan-kalathiya/folder-tidy/issues"
42
+ },
43
+ "publishConfig": {
44
+ "access": "public"
45
+ },
46
+ "engines": {
47
+ "node": ">=16"
48
+ }
49
+ }
package/src/cli.js ADDED
@@ -0,0 +1,68 @@
1
+ const { VERSION } = require('./constants');
2
+ const { printTidyHelp, runTidy } = require('./commands/tidy');
3
+ const { printUndoHelp, runUndo } = require('./commands/undo');
4
+
5
+ function printGlobalHelp() {
6
+ console.log(`
7
+ folder-tidy ${VERSION}
8
+
9
+ Commands:
10
+ tidy Organize files in a folder
11
+ undo Restore the latest tidy run or a specific manifest
12
+
13
+ Usage:
14
+ folder-tidy tidy --target <path>
15
+ folder-tidy undo --target <path>
16
+
17
+ Quick use:
18
+ folder-tidy --dry-run
19
+ folder-tidy --mode name
20
+
21
+ Global options:
22
+ --help, -h Show help
23
+ --version Show version
24
+ `);
25
+ }
26
+
27
+ function run(argv) {
28
+ if (argv.includes('--version')) {
29
+ console.log(VERSION);
30
+ return;
31
+ }
32
+
33
+ if (argv.length === 0) {
34
+ runTidy([], VERSION);
35
+ return;
36
+ }
37
+
38
+ const [command, ...rest] = argv;
39
+
40
+ if (command === '--help' || command === '-h' || command === 'help') {
41
+ printGlobalHelp();
42
+ return;
43
+ }
44
+
45
+ if (command === 'tidy') {
46
+ runTidy(rest, VERSION);
47
+ return;
48
+ }
49
+
50
+ if (command === 'undo') {
51
+ runUndo(rest);
52
+ return;
53
+ }
54
+
55
+ // Backward-compatible shorthand: treat options as tidy args.
56
+ if (command.startsWith('-')) {
57
+ runTidy(argv, VERSION);
58
+ return;
59
+ }
60
+
61
+ console.error(`Unknown command "${command}".`);
62
+ printGlobalHelp();
63
+ process.exit(1);
64
+ }
65
+
66
+ module.exports = {
67
+ run,
68
+ };
@@ -0,0 +1,129 @@
1
+ const fs = require('fs');
2
+ const { normalizePath } = require('../utils/paths');
3
+ const { tidyDirectory } = require('../core/organizer');
4
+
5
+ function printTidyHelp(version) {
6
+ console.log(`
7
+ folder-tidy ${version}
8
+
9
+ Usage:
10
+ folder-tidy tidy
11
+ folder-tidy tidy --target <path>
12
+ folder-tidy tidy --mode <type|name|date>
13
+
14
+ Options:
15
+ --target <path> Organize a specific directory
16
+ --mode <mode> Organize by file type, file name, or modified date
17
+ --dry-run Preview changes without moving anything
18
+ --recursive Scan subfolders recursively
19
+ --exclude <patterns> Exclude files or folders, comma-separated globs
20
+ --include-hidden Include hidden files
21
+ --report <file> Save a JSON report of the run
22
+ --no-manifest Skip saving an undo manifest
23
+ --verbose Show detailed skip and scan logs
24
+ --help, -h Show tidy help
25
+ `);
26
+ }
27
+
28
+ function parseTidyOptions(argv, version) {
29
+ const options = {
30
+ targetDir: process.cwd(),
31
+ dryRun: false,
32
+ verbose: false,
33
+ recursive: false,
34
+ includeHidden: false,
35
+ noManifest: false,
36
+ mode: 'type',
37
+ excludePatterns: [],
38
+ reportPath: null,
39
+ };
40
+
41
+ for (let i = 0; i < argv.length; i += 1) {
42
+ const arg = argv[i];
43
+
44
+ if (arg === '--help' || arg === '-h') {
45
+ printTidyHelp(version);
46
+ process.exit(0);
47
+ }
48
+
49
+ if (arg === '--target' && argv[i + 1]) {
50
+ options.targetDir = argv[i + 1];
51
+ i += 1;
52
+ continue;
53
+ }
54
+
55
+ if (arg === '--mode' && argv[i + 1]) {
56
+ options.mode = argv[i + 1].toLowerCase();
57
+ i += 1;
58
+ continue;
59
+ }
60
+
61
+ if (arg === '--exclude' && argv[i + 1]) {
62
+ options.excludePatterns = argv[i + 1]
63
+ .split(',')
64
+ .map((pattern) => pattern.trim())
65
+ .filter(Boolean);
66
+ i += 1;
67
+ continue;
68
+ }
69
+
70
+ if (arg === '--report' && argv[i + 1]) {
71
+ options.reportPath = argv[i + 1];
72
+ i += 1;
73
+ continue;
74
+ }
75
+
76
+ if (arg === '--dry-run') options.dryRun = true;
77
+ if (arg === '--verbose' || arg === '-v') options.verbose = true;
78
+ if (arg === '--recursive') options.recursive = true;
79
+ if (arg === '--include-hidden') options.includeHidden = true;
80
+ if (arg === '--no-manifest') options.noManifest = true;
81
+ }
82
+
83
+ if (!['type', 'name', 'date'].includes(options.mode)) {
84
+ console.error(`Invalid mode "${options.mode}". Use type, name, or date.`);
85
+ process.exit(1);
86
+ }
87
+
88
+ return options;
89
+ }
90
+
91
+ function runTidy(argv, version) {
92
+ const options = parseTidyOptions(argv, version);
93
+ const targetDir = normalizePath(options.targetDir);
94
+
95
+ if (!fs.existsSync(targetDir) || !fs.statSync(targetDir).isDirectory()) {
96
+ console.error(`Target directory not found: ${targetDir}`);
97
+ process.exit(1);
98
+ }
99
+
100
+ const result = tidyDirectory(targetDir, options);
101
+
102
+ console.log('');
103
+ console.log('Summary');
104
+ console.log(`scanned: ${result.stats.scanned}`);
105
+ console.log(`moved: ${result.stats.moved}`);
106
+ console.log(`skipped: ${result.stats.skipped}`);
107
+ console.log(`errors: ${result.stats.errors}`);
108
+
109
+ if (Object.keys(result.stats.categories).length > 0) {
110
+ console.log('');
111
+ for (const folder of Object.keys(result.stats.categories).sort()) {
112
+ console.log(`${folder}: ${result.stats.categories[folder]}`);
113
+ }
114
+ }
115
+
116
+ if (result.manifestPath) {
117
+ console.log('');
118
+ console.log(`manifest: ${result.manifestPath}`);
119
+ }
120
+
121
+ if (result.reportPath) {
122
+ console.log(`report: ${result.reportPath}`);
123
+ }
124
+ }
125
+
126
+ module.exports = {
127
+ printTidyHelp,
128
+ runTidy,
129
+ };
@@ -0,0 +1,123 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const { VERSION } = require('../constants');
4
+ const { ensureDirectory, getSafeDestination } = require('../core/filesystem');
5
+ const { getLatestManifest, readManifest } = require('../core/manifest');
6
+ const { normalizePath } = require('../utils/paths');
7
+
8
+ function printUndoHelp() {
9
+ console.log(`
10
+ folder-tidy ${VERSION}
11
+
12
+ Usage:
13
+ folder-tidy undo
14
+ folder-tidy undo --target <path>
15
+ folder-tidy undo --manifest <file>
16
+
17
+ Options:
18
+ --target <path> Target directory that contains .folder-tidy manifests
19
+ --manifest <file> Restore a specific manifest file
20
+ --dry-run Preview restore actions without moving anything
21
+ --verbose Show detailed logs
22
+ --help, -h Show undo help
23
+ `);
24
+ }
25
+
26
+ function parseUndoOptions(argv) {
27
+ const options = {
28
+ targetDir: process.cwd(),
29
+ manifestPath: null,
30
+ dryRun: false,
31
+ verbose: false,
32
+ };
33
+
34
+ for (let i = 0; i < argv.length; i += 1) {
35
+ const arg = argv[i];
36
+
37
+ if (arg === '--help' || arg === '-h') {
38
+ printUndoHelp();
39
+ process.exit(0);
40
+ }
41
+
42
+ if (arg === '--target' && argv[i + 1]) {
43
+ options.targetDir = argv[i + 1];
44
+ i += 1;
45
+ continue;
46
+ }
47
+
48
+ if (arg === '--manifest' && argv[i + 1]) {
49
+ options.manifestPath = argv[i + 1];
50
+ i += 1;
51
+ continue;
52
+ }
53
+
54
+ if (arg === '--dry-run') options.dryRun = true;
55
+ if (arg === '--verbose' || arg === '-v') options.verbose = true;
56
+ }
57
+
58
+ return options;
59
+ }
60
+
61
+ function runUndo(argv) {
62
+ const options = parseUndoOptions(argv);
63
+ const targetDir = normalizePath(options.targetDir);
64
+ const manifestPath = options.manifestPath
65
+ ? normalizePath(options.manifestPath)
66
+ : getLatestManifest(targetDir);
67
+
68
+ if (!manifestPath || !fs.existsSync(manifestPath)) {
69
+ console.error('No manifest found to undo.');
70
+ process.exit(1);
71
+ }
72
+
73
+ const manifest = readManifest(manifestPath);
74
+ const moves = Array.isArray(manifest.moves) ? [...manifest.moves].reverse() : [];
75
+
76
+ console.log(`folder-tidy ${VERSION}`);
77
+ console.log(`command: undo`);
78
+ console.log(`manifest: ${manifestPath}`);
79
+ console.log(`target: ${targetDir}${options.dryRun ? ' (dry run)' : ''}`);
80
+ console.log('');
81
+
82
+ let restored = 0;
83
+ let skipped = 0;
84
+ let errors = 0;
85
+
86
+ for (const move of moves) {
87
+ const currentPath = path.join(targetDir, move.to);
88
+ const restoreDir = path.dirname(path.join(targetDir, move.from));
89
+ const restorePath = getSafeDestination(restoreDir, path.basename(move.from));
90
+
91
+ if (!fs.existsSync(currentPath)) {
92
+ if (options.verbose) console.log(`skip missing: ${move.to}`);
93
+ skipped += 1;
94
+ continue;
95
+ }
96
+
97
+ try {
98
+ ensureDirectory(restoreDir, options.dryRun);
99
+
100
+ if (!options.dryRun) {
101
+ fs.renameSync(currentPath, restorePath);
102
+ }
103
+
104
+ console.log(`${options.dryRun ? 'plan' : 'restore'}: ${move.to} -> ${path.relative(targetDir, restorePath)}`);
105
+ restored += 1;
106
+ } catch (error) {
107
+ console.error(`failed: ${move.to}`);
108
+ if (options.verbose) console.error(error.message);
109
+ errors += 1;
110
+ }
111
+ }
112
+
113
+ console.log('');
114
+ console.log('Summary');
115
+ console.log(`restored: ${restored}`);
116
+ console.log(`skipped: ${skipped}`);
117
+ console.log(`errors: ${errors}`);
118
+ }
119
+
120
+ module.exports = {
121
+ printUndoHelp,
122
+ runUndo,
123
+ };
@@ -0,0 +1,35 @@
1
+ const VERSION = '3.0.0';
2
+ const APP_FOLDER = '.folder-tidy';
3
+ const MANIFEST_PREFIX = 'manifest-';
4
+ const INTERNAL_FILES = new Set(['index.js', 'package.json', 'README.md', 'LICENSE']);
5
+
6
+ const CATEGORY_RULES = {
7
+ Images: ['.jpg', '.jpeg', '.png', '.gif', '.svg', '.webp', '.ico', '.tif', '.tiff', '.heic', '.bmp', '.avif'],
8
+ Videos: ['.mp4', '.mkv', '.avi', '.mov', '.wmv', '.webm', '.flv', '.m4v'],
9
+ Audio: ['.mp3', '.wav', '.flac', '.aac', '.ogg', '.m4a'],
10
+ Documents: ['.pdf', '.doc', '.docx', '.txt', '.rtf', '.odt', '.xls', '.xlsx', '.csv', '.ppt', '.pptx', '.md'],
11
+ Code: ['.js', '.cjs', '.mjs', '.ts', '.tsx', '.jsx', '.json', '.yaml', '.yml', '.xml', '.html', '.css', '.scss', '.less', '.py', '.java', '.c', '.cpp', '.cs', '.go', '.rs', '.php', '.rb', '.sh', '.ps1', '.sql'],
12
+ Archives: ['.zip', '.rar', '.7z', '.tar', '.gz', '.bz2', '.xz'],
13
+ Installers: ['.exe', '.msi', '.apk', '.dmg', '.pkg', '.deb', '.rpm'],
14
+ Fonts: ['.ttf', '.otf', '.woff', '.woff2'],
15
+ Design: ['.fig', '.sketch', '.xd', '.psd', '.ai'],
16
+ Data: ['.db', '.sqlite', '.sqlite3', '.parquet', '.log'],
17
+ };
18
+
19
+ const NAME_RULES = [
20
+ { folder: 'Screenshots', patterns: [/^screenshot/i, /^screen[-_ ]?shot/i] },
21
+ { folder: 'Installers', patterns: [/\bsetup\b/i, /\binstall/i, /\bupdate\b/i] },
22
+ { folder: 'Backups', patterns: [/\bbackup\b/i, /\.bak$/i, /copy/i] },
23
+ { folder: 'Notes', patterns: [/\bnote/i, /\bnotes\b/i, /\bmeeting\b/i, /\btodo\b/i] },
24
+ { folder: 'Invoices', patterns: [/\binvoice\b/i, /\breceipt\b/i, /\bbill\b/i] },
25
+ { folder: 'Presentations', patterns: [/\bpresentation\b/i, /\bslides?\b/i, /\bpitch\b/i] },
26
+ ];
27
+
28
+ module.exports = {
29
+ APP_FOLDER,
30
+ CATEGORY_RULES,
31
+ INTERNAL_FILES,
32
+ MANIFEST_PREFIX,
33
+ NAME_RULES,
34
+ VERSION,
35
+ };
@@ -0,0 +1,25 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+
4
+ function ensureDirectory(dirPath, dryRun) {
5
+ if (dryRun || fs.existsSync(dirPath)) return;
6
+ fs.mkdirSync(dirPath, { recursive: true });
7
+ }
8
+
9
+ function getSafeDestination(destinationDir, fileName) {
10
+ const parsed = path.parse(fileName);
11
+ let candidate = fileName;
12
+ let counter = 1;
13
+
14
+ while (fs.existsSync(path.join(destinationDir, candidate))) {
15
+ candidate = `${parsed.name}(${counter})${parsed.ext}`;
16
+ counter += 1;
17
+ }
18
+
19
+ return path.join(destinationDir, candidate);
20
+ }
21
+
22
+ module.exports = {
23
+ ensureDirectory,
24
+ getSafeDestination,
25
+ };
@@ -0,0 +1,46 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const { APP_FOLDER, MANIFEST_PREFIX } = require('../constants');
4
+
5
+ function getAppDir(targetDir) {
6
+ return path.join(targetDir, APP_FOLDER);
7
+ }
8
+
9
+ function getTimestampId() {
10
+ return new Date().toISOString().replace(/[:.]/g, '-');
11
+ }
12
+
13
+ function saveManifest(targetDir, payload) {
14
+ const appDir = getAppDir(targetDir);
15
+ if (!fs.existsSync(appDir)) {
16
+ fs.mkdirSync(appDir, { recursive: true });
17
+ }
18
+
19
+ const manifestPath = path.join(appDir, `${MANIFEST_PREFIX}${getTimestampId()}.json`);
20
+ fs.writeFileSync(manifestPath, JSON.stringify(payload, null, 2));
21
+ return manifestPath;
22
+ }
23
+
24
+ function readManifest(manifestPath) {
25
+ return JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
26
+ }
27
+
28
+ function getLatestManifest(targetDir) {
29
+ const appDir = getAppDir(targetDir);
30
+ if (!fs.existsSync(appDir)) return null;
31
+
32
+ const candidates = fs
33
+ .readdirSync(appDir)
34
+ .filter((file) => file.startsWith(MANIFEST_PREFIX) && file.endsWith('.json'))
35
+ .sort();
36
+
37
+ if (candidates.length === 0) return null;
38
+ return path.join(appDir, candidates[candidates.length - 1]);
39
+ }
40
+
41
+ module.exports = {
42
+ getAppDir,
43
+ getLatestManifest,
44
+ readManifest,
45
+ saveManifest,
46
+ };
@@ -0,0 +1,174 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const { APP_FOLDER, INTERNAL_FILES, VERSION } = require('../constants');
4
+ const { ensureDirectory, getSafeDestination } = require('./filesystem');
5
+ const { saveManifest } = require('./manifest');
6
+ const { writeReport } = require('./report');
7
+ const { buildDestinationFolder, getManagedFolders } = require('./rules');
8
+ const { ensureRelative } = require('../utils/paths');
9
+ const { isHidden, matchesPattern } = require('../utils/patterns');
10
+
11
+ function createStats() {
12
+ return {
13
+ scanned: 0,
14
+ moved: 0,
15
+ skipped: 0,
16
+ errors: 0,
17
+ categories: {},
18
+ moves: [],
19
+ };
20
+ }
21
+
22
+ function collectFiles(rootDir, options, stats) {
23
+ const files = [];
24
+ const destinationFolders = getManagedFolders();
25
+ destinationFolders.add(APP_FOLDER);
26
+
27
+ function walk(currentDir) {
28
+ const entries = fs.readdirSync(currentDir, { withFileTypes: true });
29
+
30
+ for (const entry of entries) {
31
+ const absolutePath = path.join(currentDir, entry.name);
32
+ const relativePath = path.relative(rootDir, absolutePath) || entry.name;
33
+
34
+ if (!options.includeHidden && isHidden(entry.name)) {
35
+ if (options.verbose) console.log(`skip hidden: ${relativePath}`);
36
+ stats.skipped += 1;
37
+ continue;
38
+ }
39
+
40
+ if (matchesPattern(entry.name, options.excludePatterns) || matchesPattern(relativePath, options.excludePatterns)) {
41
+ if (options.verbose) console.log(`skip excluded: ${relativePath}`);
42
+ stats.skipped += 1;
43
+ continue;
44
+ }
45
+
46
+ if (entry.isDirectory()) {
47
+ if (destinationFolders.has(entry.name)) {
48
+ if (options.verbose) console.log(`skip managed folder: ${relativePath}`);
49
+ stats.skipped += 1;
50
+ continue;
51
+ }
52
+
53
+ if (options.recursive) {
54
+ walk(absolutePath);
55
+ } else if (options.verbose) {
56
+ console.log(`skip subfolder: ${relativePath}`);
57
+ }
58
+ continue;
59
+ }
60
+
61
+ files.push({ absolutePath, relativePath, name: entry.name });
62
+ }
63
+ }
64
+
65
+ walk(rootDir);
66
+ return files;
67
+ }
68
+
69
+ function tidyDirectory(targetDir, options) {
70
+ const stats = createStats();
71
+ const files = collectFiles(targetDir, options, stats);
72
+
73
+ console.log(`folder-tidy ${VERSION}`);
74
+ console.log(`command: tidy`);
75
+ console.log(`target: ${targetDir}`);
76
+ console.log(`mode: ${options.mode}${options.dryRun ? ' (dry run)' : ''}`);
77
+ console.log(`recursive: ${options.recursive ? 'yes' : 'no'}`);
78
+ console.log('');
79
+
80
+ for (const file of files) {
81
+ stats.scanned += 1;
82
+
83
+ if (targetDir === process.cwd() && INTERNAL_FILES.has(file.name)) {
84
+ if (options.verbose) console.log(`skip project file: ${file.name}`);
85
+ stats.skipped += 1;
86
+ continue;
87
+ }
88
+
89
+ let fileStats;
90
+ try {
91
+ fileStats = fs.statSync(file.absolutePath);
92
+ } catch (error) {
93
+ console.error(`failed to read file stats: ${file.relativePath}`);
94
+ stats.errors += 1;
95
+ continue;
96
+ }
97
+
98
+ const folderName = buildDestinationFolder(file.name, fileStats, options.mode);
99
+ const destinationDir = path.join(targetDir, folderName);
100
+
101
+ if (path.dirname(file.absolutePath) === destinationDir) {
102
+ if (options.verbose) console.log(`skip already organized: ${file.relativePath}`);
103
+ stats.skipped += 1;
104
+ continue;
105
+ }
106
+
107
+ const destinationPath = getSafeDestination(destinationDir, file.name);
108
+ const relativeDestination = ensureRelative(targetDir, destinationPath);
109
+
110
+ try {
111
+ ensureDirectory(destinationDir, options.dryRun);
112
+
113
+ if (!options.dryRun) {
114
+ fs.renameSync(file.absolutePath, destinationPath);
115
+ }
116
+
117
+ console.log(`${options.dryRun ? 'plan' : 'move'}: ${file.relativePath} -> ${relativeDestination}`);
118
+ stats.moved += 1;
119
+ stats.categories[folderName] = (stats.categories[folderName] || 0) + 1;
120
+ stats.moves.push({
121
+ from: file.relativePath,
122
+ to: relativeDestination,
123
+ });
124
+ } catch (error) {
125
+ console.error(`failed: ${file.relativePath} -> ${relativeDestination}`);
126
+ if (options.verbose) console.error(error.message);
127
+ stats.errors += 1;
128
+ }
129
+ }
130
+
131
+ let manifestPath = null;
132
+ if (!options.dryRun && !options.noManifest && stats.moves.length > 0) {
133
+ manifestPath = saveManifest(targetDir, {
134
+ version: VERSION,
135
+ command: 'tidy',
136
+ target: targetDir,
137
+ mode: options.mode,
138
+ recursive: options.recursive,
139
+ includeHidden: options.includeHidden,
140
+ excludePatterns: options.excludePatterns,
141
+ createdAt: new Date().toISOString(),
142
+ moves: stats.moves,
143
+ });
144
+ }
145
+
146
+ let reportPath = null;
147
+ if (options.reportPath) {
148
+ reportPath = writeReport(options.reportPath, {
149
+ version: VERSION,
150
+ command: 'tidy',
151
+ target: targetDir,
152
+ options: {
153
+ mode: options.mode,
154
+ dryRun: options.dryRun,
155
+ recursive: options.recursive,
156
+ includeHidden: options.includeHidden,
157
+ excludePatterns: options.excludePatterns,
158
+ },
159
+ stats,
160
+ manifestPath,
161
+ createdAt: new Date().toISOString(),
162
+ });
163
+ }
164
+
165
+ return {
166
+ stats,
167
+ manifestPath,
168
+ reportPath,
169
+ };
170
+ }
171
+
172
+ module.exports = {
173
+ tidyDirectory,
174
+ };
@@ -0,0 +1,19 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const { normalizePath } = require('../utils/paths');
4
+
5
+ function writeReport(reportPath, payload) {
6
+ const resolved = normalizePath(reportPath);
7
+ const parentDir = path.dirname(resolved);
8
+
9
+ if (!fs.existsSync(parentDir)) {
10
+ fs.mkdirSync(parentDir, { recursive: true });
11
+ }
12
+
13
+ fs.writeFileSync(resolved, JSON.stringify(payload, null, 2));
14
+ return resolved;
15
+ }
16
+
17
+ module.exports = {
18
+ writeReport,
19
+ };
@@ -0,0 +1,48 @@
1
+ const path = require('path');
2
+ const { CATEGORY_RULES, NAME_RULES } = require('../constants');
3
+
4
+ function getDateFolder(fileStats) {
5
+ const date = fileStats.mtime;
6
+ const year = date.getFullYear();
7
+ const month = String(date.getMonth() + 1).padStart(2, '0');
8
+ return `${year}-${month}`;
9
+ }
10
+
11
+ function getTypeFolder(fileName) {
12
+ const extension = path.extname(fileName).toLowerCase();
13
+ for (const [folder, extensions] of Object.entries(CATEGORY_RULES)) {
14
+ if (extensions.includes(extension)) {
15
+ return folder;
16
+ }
17
+ }
18
+ return extension ? 'Others' : 'No Extension';
19
+ }
20
+
21
+ function getNameFolder(fileName) {
22
+ for (const rule of NAME_RULES) {
23
+ if (rule.patterns.some((pattern) => pattern.test(fileName))) {
24
+ return rule.folder;
25
+ }
26
+ }
27
+ return getTypeFolder(fileName);
28
+ }
29
+
30
+ function buildDestinationFolder(fileName, fileStats, mode) {
31
+ if (mode === 'date') return getDateFolder(fileStats);
32
+ if (mode === 'name') return getNameFolder(fileName);
33
+ return getTypeFolder(fileName);
34
+ }
35
+
36
+ function getManagedFolders() {
37
+ return new Set([
38
+ ...Object.keys(CATEGORY_RULES),
39
+ ...NAME_RULES.map((rule) => rule.folder),
40
+ 'Others',
41
+ 'No Extension',
42
+ ]);
43
+ }
44
+
45
+ module.exports = {
46
+ buildDestinationFolder,
47
+ getManagedFolders,
48
+ };
@@ -0,0 +1,14 @@
1
+ const path = require('path');
2
+
3
+ function normalizePath(inputPath) {
4
+ return path.resolve(inputPath);
5
+ }
6
+
7
+ function ensureRelative(baseDir, targetPath) {
8
+ return path.relative(baseDir, targetPath).split(path.sep).join('/');
9
+ }
10
+
11
+ module.exports = {
12
+ ensureRelative,
13
+ normalizePath,
14
+ };
@@ -0,0 +1,17 @@
1
+ function globToRegex(pattern) {
2
+ const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, '\\$&');
3
+ return new RegExp(`^${escaped.replace(/\*/g, '.*')}$`, 'i');
4
+ }
5
+
6
+ function matchesPattern(value, patterns) {
7
+ return patterns.some((pattern) => globToRegex(pattern).test(value));
8
+ }
9
+
10
+ function isHidden(name) {
11
+ return name.startsWith('.');
12
+ }
13
+
14
+ module.exports = {
15
+ matchesPattern,
16
+ isHidden,
17
+ };