-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
1191 lines (1083 loc) · 55.2 KB
/
main.js
File metadata and controls
1191 lines (1083 loc) · 55.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// CodebaseCompress/main.js (V4 - Based on Official Docs)
// import plugin from './plugin.json'; // This works if using the official template's build process.
// If not, you'll get plugin.id manually.
class CodebaseCompressPluginV4 {
constructor(pluginIdFromAcodesetPluginInit) {
// pluginId can be passed if needed for settings etc.
// Core Acode services will be initialized in the async init() method
this.pluginId = pluginIdFromAcodesetPluginInit;
this.baseUrl = null;
this.$page = null; // For UI, if needed by your plugin (not for this dumper)
this.cache = null; // For cache, if needed
// --- Modules to be loaded via acode.require() ---
this.fsModule = null; // This will be the function returned by acode.require('fs')
this.dialogs = {
// We'll populate this with specific dialog functions
alert: null,
confirm: null
// ... other dialogs if needed
};
this.toast = null;
this.Url = null; // For acode.require('Url')
this.settings = null; // For acode.require('settings') if used for app settings
// --- From global editorManager ---
this.editorCommands = null; // From editorManager.editor.commands
this.editorManagerInstance = null; // The global editorManager
// --- Global Acode WORKSPACES / Added Folders ---
this.addedFolders = null; // global window.addedFolder
this.MB_BYTES = 1024 * 1024;
this.isProcessing = false;
this.cancelProcessing = false;
this.commandHandle = null;
this.config = {}; // Plugin-specific settings from plugin.json
// Settings from plugin.json are typically handled by Acode and passed/accessible differently
// than acode.require('settings') which is for app-wide settings.
}
/**
* Asynchronous initialization called from acode.setPluginInit's callback.
* This is where we load Acode modules.
* The 'settingsInPluginJson' is the 3rd arg to acode.setPluginInit if you define it.
*/
async _initializeServices(
baseUrl,
$page,
cache,
acodeSettingsForThisPlugin
) {
if (!baseUrl.endsWith("/")) baseUrl += "/";
this.baseUrl = baseUrl;
this.$page = $page;
this.cache = cache;
// Load core modules using global acode.require()
if (!window.acode || typeof window.acode.require !== "function") {
throw new Error(
"CodebaseCompress: global 'acode.require' is not available."
);
}
this.fsModule = acode.require("fs"); // Or 'fsOperation' - test both if one fails
this.dialogs.alert = acode.require("alert");
this.dialogs.confirm = acode.require("confirm");
this.toast = acode.require("toast"); // Or window.toast
this.Url = acode.require("Url");
this.settings = acode.require("settings"); // For Acode app settings, not plugin settings
// Access global editorManager
if (
typeof editorManager === "undefined" ||
!editorManager ||
!editorManager.editor
) {
throw new Error(
"CodebaseCompress: global 'editorManager' or 'editorManager.editor' is not available."
);
}
this.editorManagerInstance = editorManager;
this.editorCommands = editorManager.editor.commands;
// Access global addedFolder
if (typeof addedFolder === "undefined") {
// Or window.addedFolder
console.warn(
"CodebaseCompress: global 'addedFolder' (for workspaces) is not available."
);
this.addedFolders = []; // Default to empty if not found
} else {
this.addedFolders = addedFolder;
}
// Critical check for loaded modules
let missing = [];
if (!this.fsModule) missing.push("fs module function");
if (!this.dialogs.alert) missing.push("alert dialog");
if (!this.dialogs.confirm) missing.push("confirm dialog");
if (!this.toast) missing.push("toast");
if (!this.Url) missing.push("Url utils");
if (!this.editorCommands) missing.push("editorCommands");
if (missing.length > 0) {
throw new Error(
`CodebaseCompress: Critical Acode services missing after require: [${missing.join(
", "
)}].`
);
}
// Load plugin-specific settings (defined in plugin.json's "settings" property)
// These are usually managed by Acode and values made available via the settings object
// passed as the 3rd argument to setPluginInit, which we might get via pluginHotContext
// or if our main class's `init` (called by setPluginInit) gets it.
// For now, let's assume `acodeSettingsForThisPlugin` holds the values.
this._loadPluginSettings(acodeSettingsForThisPlugin || {});
this.registerCommand();
this.toast("Project Dumper (V4) Ready!", 2000); // Use this.toast
}
_loadPluginSettings(pluginSettingsValues) {
this.config=this.config || {}
// Default values if settings are not found or not defined in plugin.json
const defaults = {
allowedExtensions:
".js,.jsx,.ts,.tsx,.py,.java,.kt,.html,.htm,.css,.scss,.json,.xml,.md,.go,.rs,.c,.cpp,.h,.hpp,.sh,.yaml,.yml,.toml,.rb",
ignoredDirectories:
".git,node_modules,venv,dist,build,__pycache__,target,out,.DS_Store,.vscode,.idea,bin,obj,vendor,tmp,temp,logs,coverage,.next",
ignoredFiles: "package-lock.json,yarn.lock,pnpm-lock.yaml,.env",
maxIndividualFileSizeMB: 5,
outputFileNamePrefix: "llm_project_dump_",
parallelIoLimit: 5
};
const parseCommaSeparatedTextToSet = textValue => {
return new Set(
(textValue || "")
.split(",")
.map(s => s.trim().toLowerCase())
.filter(s => s !== "")
);
};
this.config.allowedExtensions = parseCommaSeparatedTextToSet(
pluginSettingsValues.allowedExtensions ?? defaults.allowedExtensions
);
this.config.ignoredDirs = parseCommaSeparatedTextToSet(
pluginSettingsValues.ignoredDirectories ??
defaults.ignoredDirectories
);
this.config.ignoredFiles = parseCommaSeparatedTextToSet(
pluginSettingsValues.ignoredFiles ?? defaults.ignoredFiles
);
this.config.maxIndividualFileSizeMB =
parseFloat(
pluginSettingsValues.maxIndividualFileSizeMB ??
defaults.maxIndividualFileSizeMB
) || 5;
this.config.outputFileNamePrefix = String(
pluginSettingsValues.outputFileNamePrefix ??
defaults.outputFileNamePrefix
).trim();
this.config.parallelIoLimit =
parseInt(
pluginSettingsValues.parallelIoLimit ??
defaults.parallelIoLimit,
10
) || 5;
console.log("CodebaseCompressV4: Plugin settings loaded:", this.config);
}
async testCreateFileStrict() {
this.toast("Starting strict create file test...", 2000);
if (!this.fsModule) {
// Use this.dialogs.alert - ensure this.dialogs is initialized and has .alert
if (this.dialogs && this.dialogs.alert)
this.dialogs.alert("Error", "fsModule not initialized!");
else
console.error(
"fsModule not initialized and dialogs.alert not available"
);
return;
}
if (!this.Url) {
this.dialogs.alert("Error", "Url module not initialized!");
return;
}
let targetDirUri;
if (this.addedFolders && this.addedFolders.length > 0) {
targetDirUri = this.addedFolders[0].url; // Use the first open folder
const useThis = await this.dialogs.confirm(
"Test Target",
`Test createFile in: ${targetDirUri}?`
);
if (!useThis) {
this.toast("Test cancelled.", 2000);
return;
}
} else {
try {
const fileBrowser = acode.require("fileBrowser");
const folder = await fileBrowser(
"folder",
"Select a TEST directory for createFile"
);
if (!folder || !folder.url) {
this.toast("Test directory selection cancelled.", 2000);
return;
}
targetDirUri = folder.url;
} catch (e) {
this.toast("Test directory selection failed/cancelled.", 2000);
return;
}
}
if (!targetDirUri) {
this.dialogs.alert(
"Error",
"No target directory selected for test."
);
return;
}
// Ensure canonical directory format with trailing slash
const canonicalDirUri = this.Url.trimSlash(targetDirUri) + "/";
const testFileName = "plugin_strict_test_create.txt";
const testFileContent =
"Strict test write: " + new Date().toISOString();
console.log(
`[Strict Test] Target Directory URI (Canonical): ${canonicalDirUri}`
);
console.log(`[Strict Test] Test Filename: ${testFileName}`);
try {
// OPTION 1: Use canonicalDirUri directly
console.log(
`[Strict Test] Getting FileSystem object for: ${canonicalDirUri}`
);
const dirFsObject = await this.fsModule(canonicalDirUri);
console.log(
`[Strict Test] FileSystem object obtained. Type: ${typeof dirFsObject}`,
dirFsObject
);
if (!dirFsObject || typeof dirFsObject.createFile !== "function") {
throw new Error(
"Failed to get valid FileSystem object or createFile method is missing."
);
}
console.log(
`[Strict Test] Calling dirFsObject.createFile("${testFileName}", ...)`
);
const createdFileUri = await dirFsObject.createFile(
testFileName,
testFileContent
);
this.toast(`STRICT TEST SUCCESS: Created ${createdFileUri}`, 5000);
console.log(
`[Strict Test] File created successfully at: ${createdFileUri}`
);
// Optional: Verify by reading
// const readFileFsObject = await this.fsModule(createdFileUri);
// const contentRead = await readFileFsObject.readFile('utf-8');
// console.log("[Strict Test] Read back:", contentRead);
} catch (error) {
console.error("[Strict Test] createFile FAILED:", error);
this.dialogs.alert(
"Strict Test FAILED",
`createFile error: ${error.message}\nDir: ${canonicalDirUri}\nFile: ${testFileName}\nStack: ${error.stack}`
);
}
// OPTION 2: Try with acode.toInternalUrl (if Option 1 fails)
// Comment out Option 1 and uncomment this section to test it.
/*
try {
console.log(`[Strict Test - InternalUrl] Converting to internal URL: ${canonicalDirUri}`);
if (typeof acode.toInternalUrl !== 'function') {
throw new Error("acode.toInternalUrl is not a function.");
}
const internalDirUri = await acode.toInternalUrl(canonicalDirUri);
console.log(`[Strict Test - InternalUrl] Internal Directory URI: ${internalDirUri}`);
console.log(`[Strict Test - InternalUrl] Getting FileSystem object for: ${internalDirUri}`);
const dirFsObjectInternal = await this.fsModule(internalDirUri);
console.log(`[Strict Test - InternalUrl] FileSystem object obtained. Type: ${typeof dirFsObjectInternal}`, dirFsObjectInternal);
if (!dirFsObjectInternal || typeof dirFsObjectInternal.createFile !== 'function') {
throw new Error("Failed to get valid FileSystem object (internal URL) or createFile method is missing.");
}
console.log(`[Strict Test - InternalUrl] Calling dirFsObjectInternal.createFile("${testFileName}", ...)`);
const createdFileUriInternal = await dirFsObjectInternal.createFile(testFileName, testFileContent);
this.toast(`STRICT TEST (InternalUrl) SUCCESS: Created ${createdFileUriInternal}`, 5000);
console.log(`[Strict Test - InternalUrl] File created successfully at: ${createdFileUriInternal}`);
} catch (error) {
console.error("[Strict Test - InternalUrl] createFile FAILED:", error);
this.dialogs.alert("Strict Test (InternalUrl) FAILED", `createFile error: ${error.message}\nDir: ${canonicalDirUri} (Internal: ${internalDirUri || 'N/A'})\nFile: ${testFileName}\nStack: ${error.stack}`);
}
*/
}
// --- runDump method (Fleshed out) ---
async runDump() {
if (this.isProcessing) {
this.toast("A dump operation is already in progress.", 2000);
return;
}
this.isProcessing = true;
this.cancelProcessing = false;
let userCancelled = false;
let outputPathUri = null;
let rootsToProcess = []; // This will hold the URIs of folders to scan
try {
let projectRootUri;
// --- 1. Determine the overall Project Root ---
// (Your existing logic for getting projectRootUri via addedFolders or fileBrowser)
// ... (ensure projectRootUri is set and canonicalized, e.g., ends with '/')
if (this.addedFolders && this.addedFolders.length > 0) {
if (this.addedFolders.length === 1) {
projectRootUri = this.addedFolders[0].url;
const confirmUse = await this.dialogs.confirm(
"Use Current Project?",
`Process content from "${
this.addedFolders[0].title ||
this.Url.basename(projectRootUri)
}" as root?`
);
if (!confirmUse) projectRootUri = null;
} else {
const SelectModule = acode.require("select");
const folderChoices = this.addedFolders.map(f => ({
value: f.url,
text: f.title || this.Url.basename(f.url)
}));
const selected = await SelectModule(
"Select Project Root",
folderChoices
);
if (selected && typeof selected === "string") {
projectRootUri = selected;
} else {
this.toast("Root selection cancelled.", 2000);
this.isProcessing = false;
return;
}
}
}
if (!projectRootUri) {
const fileBrowser = acode.require("fileBrowser");
try {
const folder = await fileBrowser(
"folder",
"Select Overall Project Root Folder"
);
if (!folder || !folder.url) {
this.toast("Root selection cancelled.", 2000);
this.isProcessing = false;
return;
}
projectRootUri = folder.url;
} catch (fbError) {
this.toast("Root selection cancelled/failed.", 2000);
this.isProcessing = false;
return;
}
}
projectRootUri = this.Url.trimSlash(projectRootUri) + "/";
// --- 2. List Top-Level Directories in projectRootUri ---
this.toast("Fetching top-level folders...", 2000);
let topLevelDirs = [];
try {
const rootFs = await this.fsModule(projectRootUri);
const entries = await rootFs.lsDir();
for (const entry of entries) {
if (
entry.isDirectory &&
!this.config.ignoredDirs.has(entry.name.toLowerCase())
) {
topLevelDirs.push({
name: entry.name,
uri: this.Url.join(projectRootUri, entry.name) // Use Url.join
});
}
}
} catch (e) {
this.dialogs.alert(
"Error Listing Folders",
`Could not list top-level folders in ${projectRootUri}: ${e.message}`
);
this.isProcessing = false;
return;
}
let initiallySelectedRoots = [];
if (topLevelDirs.length === 0) {
const processRootOnly = await this.dialogs.confirm(
"No Subfolders",
`No non-ignored subfolders found in "${this.Url.basename(
projectRootUri.slice(0, -1)
)}". Process files directly in this root folder only?`
);
if (processRootOnly) {
rootsToProcess.push(projectRootUri);
} else {
this.toast("No folders to process.", 2000);
this.isProcessing = false;
return;
}
} else {
const SelectModule = acode.require("select");
let availableDirsToSelect = [...topLevelDirs]; // Copy to modify
this.toast("Select folders one by one, or 'Done'.", 3000); // Initial instruction
while (true) {
if (this.cancelProcessing) { userCancelled = true; break; }
if (availableDirsToSelect.length === 0) {
this.toast("No more folders to select from this list.", 2000);
break;
}
// Create a map from display name to URI for easy lookup later
const nameToUriMap = new Map();
availableDirsToSelect.forEach(dir => nameToUriMap.set(dir.name, dir.uri));
// Create items for select: an array of folder NAMES (strings)
const selectDisplayItems = availableDirsToSelect.map(dir => dir.name);
// Add a "Done Selecting" option (as a simple string)
const DONE_OPTION_TEXT = "=== Done Selecting Folders ===";
selectDisplayItems.push(DONE_OPTION_TEXT);
let currentSelectionTitle = `Select Folders to Include`;
if (initiallySelectedRoots.length > 0) {
const selectedNames = initiallySelectedRoots.map(uri => this.Url.basename(uri.replace(/\/$/, '')));
currentSelectionTitle += ` (Selected: ${selectedNames.join(', ')})`;
}
let selectedDisplayText; // This will be the string selected by the user
try {
selectedDisplayText = await SelectModule(currentSelectionTitle, selectDisplayItems);
} catch (e) {
console.warn("Select dialog cancelled or errored (iterative selection):", e);
selectedDisplayText = null;
}
if (this.cancelProcessing) { userCancelled = true; break; }
if (!selectedDisplayText) {
const continueSelection = await this.dialogs.confirm("Selection Cancelled", "You cancelled the folder selection. Continue selecting folders, or finish with current selections?");
if (continueSelection) continue;
else { userCancelled = true; break; }
}
if (selectedDisplayText === DONE_OPTION_TEXT) {
break; // User explicitly chose "Done Selecting"
}
// User selected a folder name. Get the corresponding URI from our map.
const actualSelectedUri = nameToUriMap.get(selectedDisplayText);
if (actualSelectedUri) {
if (!initiallySelectedRoots.includes(actualSelectedUri)) {
initiallySelectedRoots.push(actualSelectedUri);
}
availableDirsToSelect = availableDirsToSelect.filter(dir => dir.uri !== actualSelectedUri);
// Now use selectedDisplayText for the toast, as it's guaranteed to be a string
this.toast(`Selected: ${selectedDisplayText}. Select another or 'Done'.`, 3000);
} else {
// Should not happen if DONE_OPTION_TEXT is handled correctly
console.warn("Selected display text not found in map:", selectedDisplayText);
}
if (availableDirsToSelect.length === 0 && selectedDisplayText !== DONE_OPTION_TEXT) {
this.toast(`Selected: ${selectedDisplayText}. No more folders in the list.`, 3000);
}
} // End of while loop
// After the loop, finalize rootsToProcess
if (userCancelled && initiallySelectedRoots.length === 0) { // User cancelled before selecting anything meaningful
this.toast('Folder selection completely cancelled.', 2000);
this.isProcessing = false; return;
}
if (initiallySelectedRoots.length === 0) {
// ... (your logic if no subfolders were selected after iteration - process root or cancel)
const processRootInstead = await this.dialogs.confirm(
"No Folders Selected",
"You didn't select any subfolders. Process files in the main project root only?" +
"\n\n[OK] = Process Root Only\n[Cancel] = Cancel Dump"
);
if (processRootInstead) {
rootsToProcess.push(projectRootUri);
this.toast("Processing root folder only.", 2000);
} else {
this.toast('No folders to process. Dump cancelled.', 2000);
this.isProcessing = false; return;
}
} else {
rootsToProcess = initiallySelectedRoots.map(uri => this.Url.trimSlash(uri) + '/');
const includeRootFiles = await this.dialogs.confirm(
"Include Root Files?",
"Also include files directly within the main project root (not in the selected subfolders)?"
);
if (includeRootFiles && !rootsToProcess.some(r => r === projectRootUri)) {
// ... (your logic to add projectRootUri if not already covered)
let rootIsAlreadyEffectivelySelected = false;
for(const selectedR of rootsToProcess){
if(selectedR === projectRootUri){
rootIsAlreadyEffectivelySelected = true;
break;
}
}
if(!rootIsAlreadyEffectivelySelected) rootsToProcess.push(projectRootUri);
}
}
}
// --- (Optional) Second-Level Selection ---
// For simplicity, we'll skip this for now. If needed, you'd loop through `rootsToProcess`,
// list subdirs for each, and prompt again, then replace the top-level URI with selected second-level URIs.
if (rootsToProcess.length === 0) {
this.toast("Nothing to process. Dump cancelled.", 2000);
this.isProcessing = false;
return;
}
// --- 4. Setup for Output File ---
const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
const baseNameForFile =
rootsToProcess.length === 1
? this.Url.basename(rootsToProcess[0].slice(0, -1))
: this.Url.basename(projectRootUri.slice(0, -1)) + "_multi";
const outputFileName = `${this.config.outputFileNamePrefix}${baseNameForFile}_${timestamp}.txt`;
// IMPORTANT: Where to save? The output file should ideally go into the *overall projectRootUri*
// or a user-selected output location if you implement SAF save later.
// For now, let's target the original projectRootUri.
outputPathUri = this.Url.join(projectRootUri, outputFileName);
const getCleanNameForHeader = (uri, baseUriForRelatives) => {
if (!uri) return 'unknown_uri';
let displayPath = uri;
// --- Handle Termux content URIs specifically for display ---
if (uri.startsWith("content://com.termux.documents/tree/")) {
const parts = uri.split('::');
if (parts.length > 1 && parts[1]) {
// The part after '::' is the actual file system path within Termux's exposed root
displayPath = parts[1];
// It might still have URL encoding for slashes, decode it for readability
try {
displayPath = decodeURIComponent(displayPath);
} catch (e) {
console.warn(`Failed to decode Termux path segment: ${parts[1]}`, e);
// Use as is if decoding fails
}
} else {
// Fallback if '::' is not found as expected, just use the original uri for basename
console.warn(`Termux URI format unexpected (no '::'): ${uri}`);
}
} else {
// For other URI schemes (like file:///), just decode the whole thing
try {
displayPath = decodeURIComponent(uri);
} catch (e) {
console.warn(`Failed to decode URI: ${uri}`, e);
}
}
// --- End of Termux/general URI preprocessing for displayPath ---
// Now, work with the potentially simplified 'displayPath' for relativity and basename
const canonicalBase = this.Url.trimSlash(baseUriForRelatives) + '/'; // Base URI should already be "clean" or similarly processed if it's also a Termux URI
// Process baseUriForRelatives the same way if it's also a Termux URI for comparison
let displayBaseUri = baseUriForRelatives;
if (baseUriForRelatives.startsWith("content://com.termux.documents/tree/")) {
const baseParts = baseUriForRelatives.split('::');
if (baseParts.length > 1 && baseParts[1]) {
try {
displayBaseUri = decodeURIComponent(baseParts[1]);
} catch (e) { /* use as is */ }
}
} else {
try {
displayBaseUri = decodeURIComponent(baseUriForRelatives);
} catch (e) { /* use as is */ }
}
const canonicalDisplayBase = this.Url.trimSlash(displayBaseUri) + '/';
const canonicalDisplayPath = this.Url.trimSlash(displayPath) + '/';
console.log(`[getCleanName] Original URI: ${uri}, Processed displayPath: ${displayPath}, Canonical displayPath: ${canonicalDisplayPath}`);
console.log(`[getCleanName] Original Base: ${baseUriForRelatives}, Processed displayBaseUri: ${displayBaseUri}, Canonical displayBase: ${canonicalDisplayBase}`);
if (canonicalDisplayPath.startsWith(canonicalDisplayBase) && canonicalDisplayPath !== canonicalDisplayBase) {
let relative = canonicalDisplayPath.substring(canonicalDisplayBase.length).replace(/\/$/, '');
console.log(`[getCleanName] Relative to base: ${relative}`);
return relative || this.Url.basename(displayPath.replace(/\/$/, ''));
}
let basename = this.Url.basename(displayPath.replace(/\/$/, ''));
console.log(`[getCleanName] Basename: ${basename}`);
return basename || 'unknown_folder';
};
const cleanSelectedRootsForHeader = rootsToProcess.map(uri =>
getCleanNameForHeader(uri, projectRootUri)
).join(', ');
let cleanProjectRootForHeader = projectRootUri; // Start with original
if (projectRootUri.startsWith("content://com.termux.documents/tree/")) {
const parts = projectRootUri.split('::');
if (parts.length > 1 && parts[1]) {
try { cleanProjectRootForHeader = decodeURIComponent(parts[1]); } catch(e) {}
}
} else {
try { cleanProjectRootForHeader = decodeURIComponent(projectRootUri); } catch(e) {}
}
cleanProjectRootForHeader = this.Url.basename(cleanProjectRootForHeader.replace(/\/$/, '')) || "ProjectRoot";
const folderNamesToProcess = rootsToProcess.map(uri => this.Url.basename(uri.slice(0, -1)) || "root").join(', ');
const confirmOp = await this.dialogs.confirm(
'Confirm Dump',
`Dump from selected folders: ${folderNamesToProcess}\nInto: ${outputFileName} (in ${this.Url.basename(projectRootUri.slice(0, -1))})?`
);
if (!confirmOp) { this.toast('Dump cancelled.', 2000); this.isProcessing = false; return; }
this.toast(`Starting scan of: ${folderNamesToProcess}...`, 3000);
await new Promise(resolve => setTimeout(resolve, 50));
// --- 5. Initialize Processing Loop ---
// VVVVVV MODIFIED HEADER VVVVVV
const header = `/*\n Selected Folders: ${cleanSelectedRootsForHeader}\n Overall Project Root Folder: ${cleanProjectRootForHeader}\n Timestamp: ${new Date().toISOString()}\n File: ${outputFileName}\n Config: ${JSON.stringify(this.config, (k,v) => v instanceof Set ? Array.from(v) : v, 2)}\n*/\n\n`;
let fileContentsArray = [header];
let filesProcessedCount = 0;
let totalSizeProcessedBytes = 0;
let filesSkippedCount = 0;
let errorsEncountered = 0;
let filesScannedCount = 0;
// HERE, the 'queue' for the main processing loop starts with 'rootsToProcess'
const queue = [...rootsToProcess]; // Start queue with selected directories
const visitedDirs = new Set(); // Visited Dirs should still be global to the whole operation
let activeIoTasks = 0;
const fileProcessingPromises = [];
const processEntry = async (entryUri, entryName, isDirectory) => {
if (this.cancelProcessing) return;
const entryNameLower = entryName.toLowerCase();
const relativePath = this._getRelativePath(
entryUri,
projectRootUri
);
if (isDirectory) {
if (
!this.config.ignoredDirs.has(entryNameLower) &&
entryName !== "." &&
entryName !== ".."
) {
const canonicalDirUri =
this.Url.trimSlash(entryUri) + "/";
if (!visitedDirs.has(canonicalDirUri)) {
// Avoid adding if already processed or in queue implicitly
queue.push(canonicalDirUri);
}
}
} else {
// It's a file
filesScannedCount++;
const extension = this.Url.extname(entryNameLower); // Url.extname includes the dot
if (
this.config.allowedExtensions.has(extension) &&
!this.config.ignoredFiles.has(entryNameLower)
) {
let fileSystemObjectForEntry;
let stats;
try {
if (this.cancelProcessing) return;
fileSystemObjectForEntry =
await this.fsModule(entryUri);
if (this.cancelProcessing) return;
stats = await fileSystemObjectForEntry.stat();
if (this.cancelProcessing) return;
} catch (statError) {
console.warn(
`Could not get stats for ${relativePath}:`,
statError
);
fileContentsArray.push(
`// --- ERROR STATS: ${relativePath} ---\n// ${String(
statError.message || statError
).substring(0, 150)}\n\n`
);
errorsEncountered++;
return;
}
const fileSize = stats.size;
if (
this.config.maxIndividualFileSizeMB > 0 &&
fileSize / this.MB_BYTES >
this.config.maxIndividualFileSizeMB
) {
fileContentsArray.push(
`// --- SKIPPED LARGE FILE: ${relativePath} (Size: ${(
fileSize / this.MB_BYTES
).toFixed(2)} MB) ---\n\n`
);
filesSkippedCount++;
} else if (
fileSize === 0 &&
!this.config.allowedExtensions.has(".txt") &&
!this.config.allowedExtensions.has(".md")
) {
// Optionally log skipped empty files
} else {
try {
const content =
await fileSystemObjectForEntry.readFile(
"utf-8"
);
if (this.cancelProcessing) return;
fileContentsArray.push(
`// --- START FILE: ${relativePath} (Size: ${fileSize} bytes) ---\n`
);
fileContentsArray.push(content); // Add content separately for potential future chunking if needed
fileContentsArray.push(
`\n// --- END FILE: ${relativePath} ---\n\n`
);
filesProcessedCount++;
totalSizeProcessedBytes += content.length; // Or use Buffer.byteLength(content, 'utf8') for more accuracy
} catch (readError) {
console.warn(
`Could not read file ${relativePath}:`,
readError
);
fileContentsArray.push(
`// --- ERROR READING FILE: ${relativePath} ---\n// ${String(
readError.message || readError
).substring(0, 150)}\n\n`
);
errorsEncountered++;
}
}
}
}
};
// --- End of processEntry function ---
// --- Main processing loop (Fleshed out) ---
let lastToastUpdateTime = 0;
const TOAST_UPDATE_INTERVAL = 3000; // ms
while (
queue.length > 0 ||
activeIoTasks > 0 ||
fileProcessingPromises.length > 0
) {
if (this.cancelProcessing) {
userCancelled = true;
break;
}
// 1. Process items from the directory queue (lsDir operations)
while (
queue.length > 0 &&
activeIoTasks < this.config.parallelIoLimit
) {
const currentDirUri = queue.shift();
if (visitedDirs.has(currentDirUri)) {
continue;
}
visitedDirs.add(currentDirUri);
activeIoTasks++;
// CORRECTED FS USAGE:
// First, await this.fsModule(currentDirUri) to get the dirFsObj
// Then, call lsDir on it.
// This whole block will be an async operation pushed to the general promise handling.
const listDirAndProcessEntriesPromise = async () => {
try {
if (this.cancelProcessing) return;
const dirFsObj = await this.fsModule(currentDirUri); // Step 1: Get FileSystem object
if (this.cancelProcessing) return;
const entries = await dirFsObj.lsDir(); // Step 2: Call lsDir on the object
if (this.cancelProcessing || !entries) return;
for (const entry of entries) {
if (this.cancelProcessing) break;
const entryUri = this.Url.join(
currentDirUri,
entry.name
); // Make sure currentDirUri is canonical
// processEntry is already async and handles its own errors internally by pushing to fileContentsArray
fileProcessingPromises.push(
processEntry(
entryUri,
entry.name,
entry.isDirectory
).catch(e => {
console.error(
`Error from processEntry for ${entryUri}:`,
e
);
// errorsEncountered is incremented inside processEntry
})
);
}
} catch (listDirError) {
console.error(
`Error listing directory ${currentDirUri}:`,
listDirError
);
fileContentsArray.push(
`// --- ERROR LISTING DIRECTORY: ${this._getRelativePath(
currentDirUri,
projectRootUri
)} ---\n// ${String(
listDirError.message || listDirError
).substring(0, 150)}\n\n`
);
errorsEncountered++;
} finally {
activeIoTasks--; // Decrement here as this specific task (listing one dir) is done
}
};
listDirAndProcessEntriesPromise(); // Fire off the async operation
// It will manage activeIoTasks internally upon completion/error.
}
// 2. Process accumulated file operations (stat, readFile) from fileProcessingPromises
let promisesToRunCount = 0;
while (
fileProcessingPromises.length > 0 &&
activeIoTasks < this.config.parallelIoLimit
) {
if (this.cancelProcessing) {
userCancelled = true;
break;
}
const filePromise = fileProcessingPromises.shift();
activeIoTasks++;
promisesToRunCount++;
filePromise.finally(() => {
// This finally is on the promise returned by processEntry
activeIoTasks--;
});
}
if (userCancelled) break;
// Update toast periodically
if (Date.now() - lastToastUpdateTime > TOAST_UPDATE_INTERVAL) {
this.toast(
`Scanned: ${filesScannedCount}, Dirs: ${visitedDirs.size}, Processed: ${filesProcessedCount} files... Active: ${activeIoTasks}`,
2000
);
lastToastUpdateTime = Date.now();
}
if (
queue.length === 0 &&
activeIoTasks === 0 &&
fileProcessingPromises.length === 0
) {
break; // All queues and active tasks are done
}
if (this.cancelProcessing) {
userCancelled = true;
break;
}
await new Promise(resolve => setTimeout(resolve, 100));
}
if (userCancelled) {
this.toast("Dump operation cancelled by user.", 3000);
this.isProcessing = false;
return;
}
if (
fileContentsArray.length <= 1 &&
filesProcessedCount === 0 &&
errorsEncountered === 0
) {
// Only header means nothing was added
this.dialogs.alert(
"No Files Processed",
"No relevant files were found or processed based on your settings."
);
this.isProcessing = false;
return;
}
const finalCode = fileContentsArray.join("");
// --- WRITING LOGIC (mirroring the successful testCreateFileStrict pattern) ---
this.toast(`Attempting to write ${outputFileName}...`, 2000);
console.log(
`[runDump] Target Directory for createFile: ${projectRootUri}`
); // projectRootUri should be canonical (e.g. ends with /)
console.log(`[runDump] Filename for createFile: ${outputFileName}`);
try {
// Get a FileSystem object for the PARENT DIRECTORY (projectRootUri)
const parentDirFsObject = await this.fsModule(projectRootUri);
if (
!parentDirFsObject ||
typeof parentDirFsObject.createFile !== "function"
) {
throw new Error(
"Failed to get valid FileSystem object for parent directory or createFile method is missing."
);
}
console.log(
"[runDump] Parent directory FileSystem object obtained."
);
// Use createFile on the directory object. outputFileName is just the name.
const createdFileUri = await parentDirFsObject.createFile(
outputFileName,
finalCode
);
console.log(
`[runDump] File successfully created/written at: ${createdFileUri}`
);
this.toast(
`Dump successful: ${filesProcessedCount} files saved to ${outputFileName}.`,
3000
);
let summaryMessages = [];
summaryMessages.push(
`Successfully wrote to: ${outputFileName}`
);
summaryMessages.push(` (Full URI: ${createdFileUri})`); // Add for clarity
summaryMessages.push(
`- Files processed: ${filesProcessedCount}`
);
if (filesSkippedCount > 0)
summaryMessages.push(
`- Files skipped: ${filesSkippedCount}`
);
if (errorsEncountered > 0)
summaryMessages.push(
`- Errors encountered: ${errorsEncountered}`
);
summaryMessages.push(
`- Total content size: ${(
totalSizeProcessedBytes / this.MB_BYTES
).toFixed(2)} MB`
);
if (totalSizeProcessedBytes > 1 * this.MB_BYTES) {
summaryMessages.push(
`\nWARNING: Output is large. May exceed LLM context limits or editor performance.`
);
}
const openFile = await this.dialogs.confirm(
"Dump Complete",
summaryMessages.join("\n") + "\n\nOpen the generated file?"
);
if (openFile) {
if (
this.editorManagerInstance &&
typeof this.editorManagerInstance.openFile ===
"function"
) {
this.editorManagerInstance.openFile(createdFileUri); // Use the URI returned by createFile
} else {
this.toast(
`Cannot auto-open file. Path: ${createdFileUri}`,
5000
);
}
}
} catch (writeError) {