printprojecttree 2.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.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +86 -0
  3. package/index.js +305 -0
  4. package/package.json +30 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Abdo9616
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,86 @@
1
+ # Project Tree
2
+
3
+ Small CLI to print directory structures in tree format.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install
9
+ npm link
10
+ ```
11
+
12
+ After linking, these commands are available:
13
+
14
+ ```bash
15
+ project-tree
16
+ ptree
17
+ ```
18
+
19
+ ## Quick Usage
20
+
21
+ ```bash
22
+ # Interactive mode
23
+ project-tree
24
+
25
+ # Print any directory (relative or absolute)
26
+ project-tree ../another-folder
27
+ ptree "C:/Users/you/Documents/project"
28
+
29
+ # Multiple targets
30
+ project-tree ./src ./tests
31
+
32
+ # Comma-separated targets (compatibility)
33
+ project-tree --paths "./src,./tests"
34
+
35
+ # One-time excludes
36
+ project-tree . --exclude "dist,coverage"
37
+
38
+ # Include node_modules/.git too
39
+ project-tree . --no-default-ignores
40
+ ```
41
+
42
+ ## Saved Excludes (JSON Config)
43
+
44
+ Saved excludes are stored in your user config directory by default:
45
+
46
+ - Windows: `%APPDATA%\\project-tree\\config.json`
47
+ - Linux/macOS (XDG): `$XDG_CONFIG_HOME/project-tree/config.json`
48
+ - Linux/macOS (fallback): `~/.config/project-tree/config.json`
49
+
50
+ Example config:
51
+
52
+ ```json
53
+ {
54
+ "savedExcludes": ["dist", "coverage"]
55
+ }
56
+ ```
57
+
58
+ Manage saved excludes:
59
+
60
+ ```bash
61
+ project-tree --add-saved-excludes "dist,coverage"
62
+ project-tree --remove-saved-excludes "coverage"
63
+ project-tree --set-saved-excludes "dist,build"
64
+ project-tree --clear-saved-excludes
65
+ project-tree --list-saved-excludes
66
+ ```
67
+
68
+ Use a custom config location:
69
+
70
+ ```bash
71
+ project-tree --config "./config/tree.json" --list-saved-excludes
72
+ ```
73
+
74
+ If you prefer project-local config:
75
+
76
+ ```bash
77
+ project-tree --config ".project-tree.json" --add-saved-excludes "dist,coverage"
78
+ ```
79
+
80
+ ## Behavior Summary
81
+
82
+ - Default ignores are enabled: `node_modules`, `.git`.
83
+ - Final excludes are merged from:
84
+ - Default ignores (unless `--no-default-ignores`)
85
+ - Saved excludes from config
86
+ - One-time excludes from `--exclude`
package/index.js ADDED
@@ -0,0 +1,305 @@
1
+ #!/usr/bin/env node
2
+
3
+ const fs = require("fs");
4
+ const os = require("os");
5
+ const path = require("path");
6
+ const readline = require("readline");
7
+ const { program } = require("commander");
8
+ const pkg = require("./package.json");
9
+
10
+ const DEFAULT_EXCLUDES = ["node_modules", ".git"];
11
+
12
+ function getDefaultConfigPath() {
13
+ if (process.platform === "win32" && process.env.APPDATA) {
14
+ return path.join(process.env.APPDATA, "project-tree", "config.json");
15
+ }
16
+
17
+ if (process.env.XDG_CONFIG_HOME) {
18
+ return path.join(process.env.XDG_CONFIG_HOME, "project-tree", "config.json");
19
+ }
20
+
21
+ return path.join(os.homedir(), ".config", "project-tree", "config.json");
22
+ }
23
+
24
+ const DEFAULT_CONFIG_PATH = getDefaultConfigPath();
25
+
26
+ function parseList(str) {
27
+ if (!str) {
28
+ return [];
29
+ }
30
+
31
+ return str
32
+ .split(",")
33
+ .map(item => item.trim())
34
+ .filter(Boolean);
35
+ }
36
+
37
+ function uniqueStrings(items) {
38
+ return [...new Set(items)];
39
+ }
40
+
41
+ function normalizeSavedExcludes(value) {
42
+ if (!Array.isArray(value)) {
43
+ return [];
44
+ }
45
+
46
+ return uniqueStrings(
47
+ value
48
+ .filter(item => typeof item === "string")
49
+ .map(item => item.trim())
50
+ .filter(Boolean)
51
+ );
52
+ }
53
+
54
+ function parseTargets(values) {
55
+ if (!Array.isArray(values) || values.length === 0) {
56
+ return [];
57
+ }
58
+
59
+ const splitValues = values.flatMap(value => parseList(value));
60
+ return uniqueStrings(splitValues.map(item => path.resolve(item)));
61
+ }
62
+
63
+ function readConfig(configPath) {
64
+ if (!fs.existsSync(configPath)) {
65
+ return { savedExcludes: [] };
66
+ }
67
+
68
+ let raw;
69
+ try {
70
+ raw = fs.readFileSync(configPath, "utf8");
71
+ } catch (error) {
72
+ throw new Error(`Failed to read config file at ${configPath}: ${error.message}`);
73
+ }
74
+
75
+ if (!raw.trim()) {
76
+ return { savedExcludes: [] };
77
+ }
78
+
79
+ let parsed;
80
+ try {
81
+ parsed = JSON.parse(raw);
82
+ } catch (error) {
83
+ throw new Error(`Invalid JSON in config file ${configPath}: ${error.message}`);
84
+ }
85
+
86
+ return {
87
+ savedExcludes: normalizeSavedExcludes(parsed.savedExcludes || parsed.excludes)
88
+ };
89
+ }
90
+
91
+ function writeConfig(configPath, config) {
92
+ const normalized = {
93
+ savedExcludes: normalizeSavedExcludes(config.savedExcludes)
94
+ };
95
+
96
+ fs.mkdirSync(path.dirname(configPath), { recursive: true });
97
+ fs.writeFileSync(configPath, `${JSON.stringify(normalized, null, 2)}\n`, "utf8");
98
+ }
99
+
100
+ function printSavedExcludes(configPath, excludes) {
101
+ console.log(`\nSaved excludes (${configPath}):`);
102
+ if (excludes.length === 0) {
103
+ console.log("(none)");
104
+ return;
105
+ }
106
+
107
+ for (const item of excludes) {
108
+ console.log(`- ${item}`);
109
+ }
110
+ }
111
+
112
+ function walkTree(dir, prefix, excludeSet) {
113
+ let entries;
114
+ try {
115
+ entries = fs.readdirSync(dir, { withFileTypes: true });
116
+ } catch (error) {
117
+ console.error(`${prefix}[unreadable] ${path.basename(dir)} (${error.message})`);
118
+ return;
119
+ }
120
+
121
+ entries = entries
122
+ .filter(entry => !excludeSet.has(entry.name))
123
+ .sort((a, b) => {
124
+ if (a.isDirectory() !== b.isDirectory()) {
125
+ return a.isDirectory() ? -1 : 1;
126
+ }
127
+ return a.name.localeCompare(b.name);
128
+ });
129
+
130
+ entries.forEach((entry, index) => {
131
+ const fullPath = path.join(dir, entry.name);
132
+ const isLast = index === entries.length - 1;
133
+ const pointer = isLast ? "└── " : "├── ";
134
+
135
+ console.log(prefix + pointer + entry.name);
136
+
137
+ if (entry.isDirectory()) {
138
+ const newPrefix = prefix + (isLast ? " " : "│ ");
139
+ walkTree(fullPath, newPrefix, excludeSet);
140
+ }
141
+ });
142
+ }
143
+
144
+ function printTarget(targetPath, excludeSet) {
145
+ const resolved = path.resolve(targetPath);
146
+
147
+ if (!fs.existsSync(resolved)) {
148
+ console.error(`\n[skip] Path not found: ${resolved}`);
149
+ return false;
150
+ }
151
+
152
+ let stat;
153
+ try {
154
+ stat = fs.lstatSync(resolved);
155
+ } catch (error) {
156
+ console.error(`\n[skip] Cannot read path: ${resolved} (${error.message})`);
157
+ return false;
158
+ }
159
+
160
+ console.log(`\n${resolved}`);
161
+
162
+ if (stat.isFile()) {
163
+ return true;
164
+ }
165
+
166
+ walkTree(resolved, "", excludeSet);
167
+ return true;
168
+ }
169
+
170
+ function ask(question) {
171
+ const rl = readline.createInterface({
172
+ input: process.stdin,
173
+ output: process.stdout
174
+ });
175
+
176
+ return new Promise(resolve => {
177
+ rl.question(question, answer => {
178
+ rl.close();
179
+ resolve(answer.trim());
180
+ });
181
+ });
182
+ }
183
+
184
+ (async () => {
185
+ program
186
+ .name(pkg.name || "project-tree")
187
+ .description(pkg.description || "Print the structure of a project")
188
+ .version(pkg.version || "0.0.0")
189
+ .argument("[targets...]", "Space-separated target paths")
190
+ .option("-p, --paths <paths>", "Comma-separated paths to print")
191
+ .option("-e, --exclude <items>", "Comma-separated folders/files to exclude")
192
+ .option("--config <path>", `Config file path (default: ${DEFAULT_CONFIG_PATH})`)
193
+ .option("--set-saved-excludes <items>", "Replace saved excludes in config with comma-separated values")
194
+ .option("--add-saved-excludes <items>", "Add comma-separated excludes to config")
195
+ .option("--remove-saved-excludes <items>", "Remove comma-separated excludes from config")
196
+ .option("--clear-saved-excludes", "Clear all saved excludes in config")
197
+ .option("--list-saved-excludes", "Print saved excludes from config and exit when no target is provided")
198
+ .option("--no-default-ignores", "Disable default ignores (node_modules, .git) for this run")
199
+ .option("-y, --yes", "Run non-interactive with defaults")
200
+ .option("-n, --non-interactive", "Run without prompts (uses provided options or defaults)")
201
+ .showHelpAfterError()
202
+ .parse(process.argv);
203
+
204
+ const opts = program.opts();
205
+ const positionalTargets = parseTargets(program.args || []);
206
+ const pathTargets = opts.paths ? parseTargets([opts.paths]) : [];
207
+ const explicitTargets = uniqueStrings([...positionalTargets, ...pathTargets]);
208
+ const configPath = opts.config ? path.resolve(opts.config) : DEFAULT_CONFIG_PATH;
209
+
210
+ let config;
211
+ try {
212
+ config = readConfig(configPath);
213
+ } catch (error) {
214
+ console.error(error.message);
215
+ process.exit(1);
216
+ }
217
+
218
+ const setProvided = typeof opts.setSavedExcludes === "string";
219
+ const addProvided = typeof opts.addSavedExcludes === "string";
220
+ const removeProvided = typeof opts.removeSavedExcludes === "string";
221
+ const clearProvided = Boolean(opts.clearSavedExcludes);
222
+ const hasConfigMutation = setProvided || addProvided || removeProvided || clearProvided;
223
+
224
+ if (setProvided) {
225
+ config.savedExcludes = parseList(opts.setSavedExcludes);
226
+ }
227
+
228
+ if (addProvided) {
229
+ config.savedExcludes = uniqueStrings([...config.savedExcludes, ...parseList(opts.addSavedExcludes)]);
230
+ }
231
+
232
+ if (removeProvided) {
233
+ const toRemove = new Set(parseList(opts.removeSavedExcludes));
234
+ config.savedExcludes = config.savedExcludes.filter(item => !toRemove.has(item));
235
+ }
236
+
237
+ if (clearProvided) {
238
+ config.savedExcludes = [];
239
+ }
240
+
241
+ if (hasConfigMutation) {
242
+ writeConfig(configPath, config);
243
+ console.log(`\n[config] Saved excludes updated at ${configPath}`);
244
+ }
245
+
246
+ if (opts.listSavedExcludes || hasConfigMutation) {
247
+ printSavedExcludes(configPath, config.savedExcludes);
248
+ }
249
+
250
+ if (explicitTargets.length === 0 && (opts.listSavedExcludes || hasConfigMutation)) {
251
+ process.exit(0);
252
+ }
253
+
254
+ const shouldPrompt = !opts.nonInteractive && !opts.yes && explicitTargets.length === 0;
255
+
256
+ let targets = explicitTargets;
257
+ let useDefaultIgnores = opts.defaultIgnores;
258
+ let runtimeExcludes = opts.exclude ? parseList(opts.exclude) : [];
259
+
260
+ if (shouldPrompt) {
261
+ console.log("Project Tree Generator\n");
262
+ const pathInput = await ask("Enter paths (comma separated) or press ENTER for current directory:\n> ");
263
+ targets = pathInput ? parseTargets([pathInput]) : [process.cwd()];
264
+
265
+ if (config.savedExcludes.length > 0) {
266
+ console.log(`\nSaved excludes from config: ${config.savedExcludes.join(", ")}`);
267
+ } else {
268
+ console.log("\nSaved excludes from config: (none)");
269
+ }
270
+
271
+ if (useDefaultIgnores) {
272
+ console.log(`Default excludes: ${DEFAULT_EXCLUDES.join(", ")}`);
273
+ }
274
+
275
+ const disableDefaultsInput = await ask("Disable default excludes for this run? (y/N):\n> ");
276
+ if (/^(y|yes)$/i.test(disableDefaultsInput)) {
277
+ useDefaultIgnores = false;
278
+ }
279
+
280
+ const excludeInput = await ask("Add one-time excludes (comma separated) or press ENTER to skip:\n> ");
281
+ runtimeExcludes = excludeInput ? parseList(excludeInput) : [];
282
+ }
283
+
284
+ if (targets.length === 0) {
285
+ targets = [process.cwd()];
286
+ }
287
+
288
+ const combinedExcludes = uniqueStrings([
289
+ ...(useDefaultIgnores ? DEFAULT_EXCLUDES : []),
290
+ ...config.savedExcludes,
291
+ ...runtimeExcludes
292
+ ]);
293
+ const excludeSet = new Set(combinedExcludes);
294
+
295
+ let printedCount = 0;
296
+ for (const target of targets) {
297
+ if (printTarget(target, excludeSet)) {
298
+ printedCount += 1;
299
+ }
300
+ }
301
+
302
+ if (printedCount === 0) {
303
+ process.exit(1);
304
+ }
305
+ })();
package/package.json ADDED
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "printprojecttree",
3
+ "version": "2.0.0",
4
+ "bin": {
5
+ "project-tree": "index.js",
6
+ "ptree": "index.js"
7
+ },
8
+ "description": "A tool to print the structure of a project in a tree format.",
9
+ "main": "index.js",
10
+ "scripts": {
11
+ "test": "echo \"Error: no test specified\" && exit 1",
12
+ "start": "node index.js"
13
+ },
14
+ "preferGlobal": true,
15
+ "dependencies": {
16
+ "commander": "^11.0.0"
17
+ },
18
+ "keywords": [],
19
+ "author": "Abdo9616",
20
+ "license": "MIT",
21
+ "type": "commonjs",
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/Abdo9616/project-tree.git"
25
+ },
26
+ "bugs": {
27
+ "url": "https://github.com/Abdo9616/project-tree/issues"
28
+ },
29
+ "homepage": "https://github.com/Abdo9616/project-tree#readme"
30
+ }