-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmini-a-utils.js
More file actions
3756 lines (3416 loc) · 147 KB
/
mini-a-utils.js
File metadata and controls
3756 lines (3416 loc) · 147 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
// Author: Nuno Aguiar
// License: Apache 2.0
// Description: Mini-A utils tool for basic file operations within a specified root directory
loadLib("mini-a-common.js")
/**
* <odoc>
* <key>MiniUtilsTool(options) : MiniUtilsTool</key>
* Creates a MiniUtilsTool instance to perform file operations within a specified root directory.
* </odoc>
*/
var MiniUtilsTool = function(options) {
this._initialized = false
this._root = null
this._rootWithSep = null
this._readWrite = false
this._separator = String(java.io.File.separator)
this._listNestedKeys = ["files", "dirs", "children", "items", "list", "entries", "content"]
this._skillTemplateCandidates = ["SKILL.yaml", "SKILL.yml", "SKILL.json", "SKILL.md", "skill.md"]
this._skillsRoots = []
this._wikiManager = __
//if (isDef(options)) {
this.init(options)
//}
}
/**
* <odoc>
* <key>MiniUtilsTool.init(options) : Object</key>
* Initializes the MiniUtilsTool instance with the specified options.
*
* The `options` parameter can be:
* - A string representing the root directory path.
* - An object with the following properties:
* - `root` (string): The root directory path. Defaults to the current directory (`"."`).
* - `readwrite` (boolean): If set to `true`, enables write operations. Defaults to `false` (read-only mode).
*
* Returns the MiniUtilsTool instance on success, or an error message string on failure.
* </odoc>
*/
MiniUtilsTool.prototype.init = function(options) {
try {
if (isUnDef(options)) options = {}
if (isString(options) || options instanceof java.lang.String) options = { root: options }
var rootPath = options.root || "."
var rootFile = io.fileInfo(rootPath)
var canonicalRoot = rootFile.canonicalPath
if (!io.fileExists(canonicalRoot)) {
return "[ERROR] Root path not found: " + rootPath
}
if (!rootFile.isDirectory) {
return "[ERROR] Root path is not a directory: " + canonicalRoot
}
var info = io.fileInfo(canonicalRoot)
if (isUnDef(info) || info.isDirectory !== true) {
return "[ERROR] Unable to load directory information for: " + canonicalRoot
}
this._root = canonicalRoot
this._readWrite = options.readwrite === true
this._skillsRoots = this._resolveSkillsRoots(options)
var sep = String(java.io.File.separator)
this._separator = sep
if (canonicalRoot.indexOf(sep, canonicalRoot.length - sep.length) === -1) {
this._rootWithSep = canonicalRoot + sep
} else {
this._rootWithSep = canonicalRoot
}
this._initialized = true
return this
} catch (e) {
this._initialized = false
return "[ERROR] " + __miniAErrMsg(e)
}
}
MiniUtilsTool.prototype._ensureInitialized = function() {
if (this._initialized !== true) {
throw new Error("File context not initialized")
}
}
MiniUtilsTool.prototype._withinRoot = function(candidate) {
if (!isString(candidate)) return false
if (candidate === this._root) return true
return isString(this._rootWithSep) && candidate.indexOf(this._rootWithSep) === 0
}
MiniUtilsTool.prototype._toRelative = function(targetPath) {
if (!isString(targetPath)) return targetPath
if (!this._withinRoot(targetPath)) return targetPath
var relative = targetPath.substring(this._root.length)
if (relative.indexOf(this._separator) === 0) {
relative = relative.substring(this._separator.length)
}
if (relative.length === 0) {
relative = "."
}
return relative
}
MiniUtilsTool.prototype._resolve = function(target) {
var candidate = new java.io.File(target)
if (!candidate.isAbsolute()) {
candidate = new java.io.File(this._root, target)
}
var resolved = String(candidate.getCanonicalPath())
if (!this._withinRoot(resolved)) {
throw new Error("Path outside of allowed root: " + target)
}
return resolved
}
MiniUtilsTool.prototype._ensureWritable = function(operation) {
if (this._readWrite !== true) {
throw new Error("Read-only mode. Set readwrite=true to allow " + operation)
}
}
MiniUtilsTool.prototype._createGlobMatcher = function(pattern) {
try {
var fileSystem = java.nio.file.FileSystems.getDefault()
return fileSystem.getPathMatcher("glob:" + pattern)
} catch (e) {
return null
}
}
MiniUtilsTool.prototype._resolveSkillsRoots = function(options) {
options = isMap(options) ? options : {}
var roots = []
var seen = {}
var self = this
var addRoot = function(pathValue) {
if (!(isString(pathValue) || pathValue instanceof java.lang.String)) return
var trimmed = String(pathValue).trim()
if (trimmed.length === 0) return
var expanded = self._expandHomePath(trimmed)
var canonical
try {
canonical = String(new java.io.File(expanded).getCanonicalPath())
} catch (e) {
return
}
if (seen[canonical]) return
if (!io.fileExists(canonical)) return
var info = io.fileInfo(canonical)
if (isUnDef(info) || info.isDirectory !== true) return
seen[canonical] = true
roots.push(canonical)
}
if (isString(options.skillsroot) || options.skillsroot instanceof java.lang.String) addRoot(options.skillsroot)
if (isArray(options.skillsroots)) {
options.skillsroots.forEach(function(entry) {
addRoot(entry)
})
}
if (roots.length === 0) {
var userHome = java.lang.System.getProperty("user.home")
if (isString(userHome) || userHome instanceof java.lang.String) {
userHome = String(userHome)
if (userHome.length > 0) {
addRoot(userHome + java.io.File.separator + ".openaf-mini-a" + java.io.File.separator + "skills")
}
}
if (typeof __gHDir === "function") {
try {
var gHome = __gHDir()
if (isString(gHome) || gHome instanceof java.lang.String) {
gHome = String(gHome)
if (gHome.length > 0) {
addRoot(gHome + java.io.File.separator + ".openaf-mini-a" + java.io.File.separator + "skills")
}
}
} catch (ignoreGHDirError) {
}
}
}
return roots
}
MiniUtilsTool.prototype._expandHomePath = function(pathValue) {
if (!(isString(pathValue) || pathValue instanceof java.lang.String)) return pathValue
pathValue = String(pathValue)
if (pathValue === "~") return java.lang.System.getProperty("user.home")
if (pathValue.indexOf("~/") === 0 || pathValue.indexOf("~\\") === 0) {
var home = java.lang.System.getProperty("user.home")
if (isString(home) && home.length > 0) {
return home + pathValue.substring(1)
}
}
return pathValue
}
MiniUtilsTool.prototype._getSkillRelativeToRoot = function(rootPath, targetPath) {
if (!(isString(rootPath) || rootPath instanceof java.lang.String)) return targetPath
if (!(isString(targetPath) || targetPath instanceof java.lang.String)) return targetPath
rootPath = String(rootPath)
targetPath = String(targetPath)
if (targetPath === rootPath) return "."
var sep = String(java.io.File.separator)
var rootWithSep = rootPath
if (rootPath.indexOf(sep, rootPath.length - sep.length) === -1) {
rootWithSep = rootPath + sep
}
if (targetPath.indexOf(rootWithSep) === 0) {
return targetPath.substring(rootWithSep.length)
}
return targetPath
}
MiniUtilsTool.prototype._resolveSkillTemplateFromFolder = function(folderPath) {
if (!(isString(folderPath) || folderPath instanceof java.lang.String)) return __
return __miniAResolveSkillTemplateFromFolder(String(folderPath), this._skillTemplateCandidates)
}
MiniUtilsTool.prototype._readSkillDescriptionFromTemplate = function(templatePath) {
if (!(isString(templatePath) || templatePath instanceof java.lang.String)) return __
return __miniAReadSkillDescriptionFromTemplate(String(templatePath))
}
MiniUtilsTool.prototype._listSkills = function(params) {
var payload = isMap(params) ? params : {}
var includeHidden = payload.includeHidden === true
var query = isString(payload.query) ? payload.query.toLowerCase().trim() : ""
var seenByName = {}
var results = []
var self = this
var validName = /^[a-z0-9][a-z0-9_-]*$/
this._skillsRoots.forEach(function(rootPath) {
var listing
try {
listing = io.listFiles(rootPath)
} catch (e) {
listing = __
}
if (!isMap(listing) || !isArray(listing.files)) return
listing.files.forEach(function(entry) {
var entryName = __
var isDirectory = false
if (isMap(entry) && (isString(entry.filename) || entry.filename instanceof java.lang.String)) {
entryName = String(entry.filename)
isDirectory = entry.isDirectory === true
} else if (isString(entry) || entry instanceof java.lang.String) {
entryName = String(entry)
try {
var fromString = new java.io.File(rootPath, entryName)
isDirectory = fromString.isDirectory()
} catch (entryErr) {
isDirectory = false
}
} else {
return
}
if (!isString(entryName) || entryName.length === 0) return
if (__miniAShouldIgnoreSkillEntryName(entryName, includeHidden)) return
var name = __
var sourceType = "file"
var templatePath = __
if (isDirectory === true) {
name = entryName.toLowerCase()
try {
var folderPath = String(new java.io.File(rootPath, entryName).getCanonicalPath())
templatePath = self._resolveSkillTemplateFromFolder(folderPath)
} catch (folderErr) {
templatePath = __
}
if (isUnDef(templatePath)) return
sourceType = "folder"
} else {
if (!/\.(md|ya?ml|json)$/i.test(entryName)) return
name = entryName.replace(/\.(md|ya?ml|json)$/i, "").toLowerCase()
try {
templatePath = String(new java.io.File(rootPath, entryName).getCanonicalPath())
} catch (fileErr) {
templatePath = __
}
}
if (!isString(name) || !validName.test(name)) return
if (!isString(templatePath) || !io.fileExists(templatePath)) return
if (seenByName[name]) return
var description = sourceType === "folder"
? self._readSkillDescriptionFromTemplate(templatePath)
: (function() {
var doc = __miniALoadSkillTemplateDocument(templatePath)
return isObject(doc) && isString(doc.description) ? doc.description : __
})()
var skillFormat = __miniASkillTemplateFormatFromPath(templatePath)
var relativePath = self._getSkillRelativeToRoot(rootPath, templatePath)
var queryText = [
name,
isString(relativePath) ? relativePath : "",
isString(description) ? description : ""
].join(" ").toLowerCase()
if (query.length > 0 && queryText.indexOf(query) < 0) return
seenByName[name] = true
results.push({
name : name,
sourceType : sourceType,
skillFormat : skillFormat,
description : description,
templatePath: templatePath,
relativePath: relativePath,
rootPath : rootPath
})
})
})
results.sort(function(a, b) {
return String(a.name).localeCompare(String(b.name))
})
return results
}
MiniUtilsTool.prototype._parseSkillArgs = function(rawValue) {
var raw = isString(rawValue) ? rawValue.trim() : ""
if (raw.length === 0) return { ok: true, raw: "", argv: [], argc: 0 }
var argv = []
var current = ""
var quote = ""
var escaping = false
for (var i = 0; i < raw.length; i++) {
var ch = raw.charAt(i)
if (escaping) {
current += ch
escaping = false
continue
}
if (ch === "\\") {
escaping = true
continue
}
if (quote.length > 0) {
if (ch === quote) quote = ""
else current += ch
continue
}
if (ch === "'" || ch === "\"") {
quote = ch
continue
}
if (/\s/.test(ch)) {
if (current.length > 0) {
argv.push(current)
current = ""
}
continue
}
current += ch
}
if (escaping || quote.length > 0) {
return { ok: false, error: "Unbalanced quotes or trailing escape in arguments." }
}
if (current.length > 0) argv.push(current)
return {
ok : true,
raw : raw,
argv: argv,
argc: argv.length
}
}
MiniUtilsTool.prototype._renderSkillTemplate = function(template, parsedArgs) {
return __miniARenderSkillTemplate(template, parsedArgs)
}
MiniUtilsTool.prototype._normalizeSkillReferencePath = function(rawPath) {
if (!isString(rawPath)) return __
var normalized = rawPath.trim()
if (normalized.length === 0) return __
if (normalized.charAt(0) === "<" && normalized.charAt(normalized.length - 1) === ">") {
normalized = normalized.substring(1, normalized.length - 1).trim()
}
return normalized.length > 0 ? normalized : __
}
MiniUtilsTool.prototype._isAbsoluteOrExternalSkillPath = function(pathValue) {
if (!isString(pathValue) || pathValue.length === 0) return false
if (pathValue.charAt(0) === "/" || pathValue.charAt(0) === "~") return true
if (/^[A-Za-z]:[\\/]/.test(pathValue)) return true
if (/^[a-z][a-z0-9+.-]*:/i.test(pathValue)) return true
if (pathValue.indexOf("//") === 0) return true
return false
}
MiniUtilsTool.prototype._normalizeSkillVirtualPath = function(rawPath) {
if (!isString(rawPath)) return __
var normalized = rawPath.trim().replace(/\\/g, "/")
if (normalized.length === 0) return __
if (normalized.charAt(0) === "<" && normalized.charAt(normalized.length - 1) === ">") normalized = normalized.substring(1, normalized.length - 1).trim()
if (normalized.indexOf("./") === 0) normalized = normalized.substring(2)
while (normalized.indexOf("//") >= 0) normalized = normalized.replace(/\/\//g, "/")
return normalized.length > 0 ? normalized : __
}
MiniUtilsTool.prototype._recordSkillReference = function(references, seen, ref) {
if (!isArray(references) || !isMap(ref)) return
var key = (isString(ref.type) ? ref.type : "file") + ":" + (isString(ref.path) ? ref.path : "")
if (key === "file:") return
if (seen[key]) return
seen[key] = true
references.push(ref)
}
MiniUtilsTool.prototype._preprocessSkillTemplateReferences = function(templateText, selected, loadedDoc) {
var result = {
text: isString(templateText) ? String(templateText) : "",
references: []
}
if (!isString(result.text) || result.text.length === 0) return result
if (!isMap(selected) || !isString(selected.templatePath) || selected.templatePath.trim().length === 0) return result
var templatePath = String(selected.templatePath)
var templateDir = templatePath.replace(/[\\\/][^\\\/]+$/, "")
if (!isString(templateDir) || templateDir.length === 0) return result
var virtualFiles = (isObject(loadedDoc) && isObject(loadedDoc.virtualFiles)) ? loadedDoc.virtualFiles : {}
var references = []
var seen = {}
var self = this
function splitAttachmentToken(rawToken) {
var token = isString(rawToken) ? rawToken : ""
var suffix = ""
while (token.length > 0) {
var lastChar = token.charAt(token.length - 1)
if (/[,.;:!?)\]}'"]/.test(lastChar)) {
suffix = lastChar + suffix
token = token.substring(0, token.length - 1)
continue
}
break
}
return { filePath: token, suffix: suffix }
}
function countImmediateBackslashes(text, position) {
if (!isString(text) || !isNumber(position) || position <= 0) return 0
var count = 0
for (var idx = position - 1; idx >= 0 && text.charAt(idx) === "\\"; idx--) count++
return count
}
function canStartInlineShortcut(text, markerPos) {
if (!isString(text) || !isNumber(markerPos) || markerPos < 0 || markerPos >= text.length) return false
if (markerPos === 0) return true
var prevChar = text.charAt(markerPos - 1)
if (/\s/.test(prevChar)) return true
if (/[\(\[\{<"'`,;:!?]/.test(prevChar)) return true
return false
}
var text = result.text
var chunks = []
var cursor = 0
var wsPattern = /\s/
while (cursor < text.length) {
var atPos = text.indexOf("@", cursor)
if (atPos < 0) {
chunks.push(text.substring(cursor))
break
}
if (countImmediateBackslashes(text, atPos) > 0 || !canStartInlineShortcut(text, atPos)) {
chunks.push(text.substring(cursor, atPos + 1))
cursor = atPos + 1
continue
}
var endPos = atPos + 1
while (endPos < text.length && !wsPattern.test(text.charAt(endPos))) endPos++
var rawToken = text.substring(atPos + 1, endPos)
var tokenParts = splitAttachmentToken(rawToken)
var filePath = self._normalizeSkillReferencePath(tokenParts.filePath)
var replacement = "@" + tokenParts.filePath
var normalizedVirtualPath = self._normalizeSkillVirtualPath(filePath)
if (isString(normalizedVirtualPath) && Object.prototype.hasOwnProperty.call(virtualFiles, normalizedVirtualPath)) {
var virtualBody = virtualFiles[normalizedVirtualPath]
if (!isString(virtualBody)) virtualBody = String(virtualBody || "")
self._recordSkillReference(references, seen, { type: "embedded", path: normalizedVirtualPath })
replacement = "\n\n--- Skill reference from " + normalizedVirtualPath + " ---\n" + virtualBody + "\n--- End of " + normalizedVirtualPath + " ---\n"
} else if (isString(filePath) && filePath.length > 0 && !self._isAbsoluteOrExternalSkillPath(filePath)) {
var resolved = String(new java.io.File(templateDir, filePath).getCanonicalPath())
try {
if (io.fileExists(resolved) && io.fileInfo(resolved).isFile === true) {
self._recordSkillReference(references, seen, { type: "file", path: resolved, relativePath: filePath })
replacement = "@" + resolved
}
} catch(ignoreResolvedSkillRefError) { }
}
chunks.push(text.substring(cursor, atPos))
chunks.push(replacement)
if (tokenParts.suffix.length > 0) chunks.push(tokenParts.suffix)
cursor = endPos
}
text = chunks.join("")
var includedPaths = {}
var includeBlocks = []
text.replace(/\[[^\]]*\]\(([^)\n]+)\)/g, function(_, targetSpec) {
var spec = isString(targetSpec) ? targetSpec.trim() : ""
if (spec.length === 0) return _
var firstToken = spec.split(/\s+/)[0]
var normalizedTarget = self._normalizeSkillReferencePath(firstToken)
if (!isString(normalizedTarget) || normalizedTarget.length === 0) return _
if (normalizedTarget.charAt(0) === "#") return _
if (self._isAbsoluteOrExternalSkillPath(normalizedTarget)) return _
var cleanTarget = normalizedTarget.split("#")[0].split("?")[0]
if (!/\.md$/i.test(cleanTarget)) return _
var normalizedVirtualTarget = self._normalizeSkillVirtualPath(cleanTarget)
if (isString(normalizedVirtualTarget) && Object.prototype.hasOwnProperty.call(virtualFiles, normalizedVirtualTarget)) {
if (Object.prototype.hasOwnProperty.call(includedPaths, "virtual:" + normalizedVirtualTarget)) return _
includedPaths["virtual:" + normalizedVirtualTarget] = true
var virtualRefContent = virtualFiles[normalizedVirtualTarget]
if (!isString(virtualRefContent)) virtualRefContent = String(virtualRefContent || "")
self._recordSkillReference(references, seen, { type: "embedded", path: normalizedVirtualTarget })
includeBlocks.push("\n\n--- Skill reference from " + normalizedVirtualTarget + " ---\n" + virtualRefContent + "\n--- End of " + normalizedVirtualTarget + " ---\n")
return _
}
var resolvedPath = String(new java.io.File(templateDir, cleanTarget).getCanonicalPath())
if (Object.prototype.hasOwnProperty.call(includedPaths, resolvedPath)) return _
includedPaths[resolvedPath] = true
try {
if (!io.fileExists(resolvedPath) || io.fileInfo(resolvedPath).isFile !== true) return _
var refContent = io.readFileString(resolvedPath)
self._recordSkillReference(references, seen, { type: "file", path: resolvedPath, relativePath: cleanTarget })
includeBlocks.push("\n\n--- Skill reference from " + cleanTarget + " ---\n" + refContent + "\n--- End of " + cleanTarget + " ---\n")
} catch(ignoreSkillRefError) { }
return _
})
if (includeBlocks.length > 0) text += includeBlocks.join("")
result.text = text
result.references = references
return result
}
MiniUtilsTool.prototype._serializeSkillArgv = function(argv) {
if (!isArray(argv) || argv.length === 0) return ""
return argv.map(function(value) {
var token = String(value)
if (token.length === 0) return "\"\""
if (/[\\\s"]/.test(token)) {
return "\"" + token.replace(/\\/g, "\\\\").replace(/"/g, "\\\"") + "\""
}
return token
}).join(" ")
}
MiniUtilsTool.prototype._listEntries = function(baseDir, options) {
var self = this
options = options || {}
var includeHidden = options.includeHidden === true
var recursive = options.recursive === true
var results = []
var seen = {}
var pushEntry = function(fullPath) {
if (!isString(fullPath)) return
if (!self._withinRoot(fullPath)) return
if (fullPath === baseDir) return
if (seen[fullPath]) return
var fileObj = new java.io.File(fullPath)
var fileName = String(fileObj.getName())
if (!includeHidden && (fileObj.isHidden() || fileName.charAt(0) === ".")) return
var info = io.fileInfo(fullPath)
if (isUnDef(info)) return
info.filename = isString(info.filename) ? info.filename : fileName
info.lastModified = isDef(info.lastModified) ? new Date(info.lastModified) : __
info.createTime = isDef(info.createTime) ? new Date(info.createTime) : __
info.lastAccess = isDef(info.lastAccess) ? new Date(info.lastAccess) : __
info.relativePath = self._toRelative(info.canonicalPath || fullPath)
info.isDirectory = info.isDirectory === true
info.isFile = info.isFile === true
info.hidden = fileObj.isHidden()
delete info.canonicalPath
delete info.filepath
delete info.path
results.push(info)
seen[fullPath] = true
}
var _traverse = function(value, ctxDir) {
if (isUnDef(value)) return
if (isArray(value)) {
value.forEach(function(entry) {
_traverse(entry, ctxDir)
})
return
}
if (isString(value)) {
try {
var fromString = new java.io.File(isString(ctxDir) ? ctxDir : baseDir, value)
var resolved = String(fromString.getCanonicalPath())
pushEntry(resolved)
} catch (innerErr) {
}
return
}
if (isMap(value)) {
var resolved
var candidate = value.canonicalPath || value.filepath || value.path
if (isString(candidate)) {
try {
var fileCandidate = new java.io.File(candidate)
if (!fileCandidate.isAbsolute()) {
fileCandidate = new java.io.File(isString(ctxDir) ? ctxDir : baseDir, candidate)
}
resolved = String(fileCandidate.getCanonicalPath())
pushEntry(resolved)
} catch (innerErr2) {
resolved = null
}
} else if (isString(value.filename)) {
try {
var parentDir = value.directory
var baseForName
if (isString(parentDir)) {
baseForName = new java.io.File(parentDir)
if (!baseForName.isAbsolute()) {
baseForName = new java.io.File(isString(ctxDir) ? ctxDir : baseDir, parentDir)
}
} else {
baseForName = new java.io.File(isString(ctxDir) ? ctxDir : baseDir)
}
resolved = String(new java.io.File(baseForName, value.filename).getCanonicalPath())
pushEntry(resolved)
} catch (innerErr3) {
resolved = null
}
}
var childContext = resolved
if (!isString(childContext) || value.isDirectory !== true) {
childContext = ctxDir
}
self._listNestedKeys.forEach(function(key) {
if (isDef(value[key])) {
_traverse(value[key], childContext)
}
})
}
}
var fallbackEnumerate = function(currentDir) {
try {
var listed = io.listFiles(currentDir).files || []
if (isArray(listed)) {
listed.forEach(function(entry) {
try {
var childFile = new java.io.File(currentDir, entry)
var childPath = String(childFile.getCanonicalPath())
pushEntry(childPath)
if (recursive) {
var childInfo = io.fileInfo(childPath)
if (isDef(childInfo) && childInfo.isDirectory === true) {
fallbackEnumerate(childPath)
}
}
} catch (innerErr) {
}
})
} else {
_traverse(listed, currentDir)
}
} catch (innerErr2) {
}
}
var raw
try {
raw = recursive ? listFilesRecursive(baseDir) : io.listFiles(baseDir).files
} catch (e) {
raw = null
}
if (isUnDef(raw)) {
fallbackEnumerate(baseDir)
} else {
_traverse(raw, baseDir)
if (results.length === 0) {
fallbackEnumerate(baseDir)
}
}
results.sort(function(a, b) {
var left = isDef(a.relativePath) ? String(a.relativePath) : String(a.path || a.filename || "")
var right = isDef(b.relativePath) ? String(b.relativePath) : String(b.path || b.filename || "")
return left.localeCompare(right)
})
return results
}
/**
* <odoc>
* <key>MiniUtilsTool.readFile(params) : Object</key>
* Reads the content of a file specified by the `path` parameter.
* The `params` object can have the following properties:
* - `path` (string, required): The relative or absolute path to the file to be read.
* - `encoding` (string, optional): The character encoding to use when reading the file. Defaults to `"utf-8"`.
* - `byteStart` (number, optional): Zero-based byte offset to start reading from.
* - `byteEnd` (number, optional): Zero-based byte offset to stop reading (inclusive).
* - `byteLength` (number, optional): Number of bytes to read from `byteStart`.
* - `lineStart` (number, optional): One-based line number to start reading from.
* - `lineEnd` (number, optional): One-based line number to stop reading (inclusive).
* - `maxLines` (number, optional): Maximum number of lines to read (useful with `lineStart`).
* - `lineSeparator` (string, optional): Line separator to use when joining output. Defaults to "\n".
* - `countLines` (boolean, optional): If true, returns the total line count without loading full contents.
*
* Returns an object containing file details and content on success, or an error message string on failure.
* The returned object includes:
* - `path`: The canonical path of the file.
* - `relativePath`: The path of the file relative to the root directory.
* - `encoding`: The encoding used to read the file.
* - `content`: The content of the file as a string.
* - Other file metadata such as size, last modified date, etc.
* </odoc>
*/
MiniUtilsTool.prototype.readFile = function(params) {
params = params || {}
if (isUnDef(params.path)) return "[ERROR] path is required"
try {
this._ensureInitialized()
var filePath = this._resolve(params.path)
if (!io.fileExists(filePath)) {
return "[ERROR] File not found: " + params.path
}
var details = io.fileInfo(filePath)
if (isUnDef(details) || details.isFile !== true) {
return "[ERROR] Path is not a file: " + params.path
}
var encoding = params.encoding || "utf-8"
var hasByteRange = isDef(params.byteStart) || isDef(params.byteEnd) || isDef(params.byteLength)
var hasLineRange = isDef(params.lineStart) || isDef(params.lineEnd) || isDef(params.maxLines)
var shouldCountLines = params.countLines === true
if (hasByteRange && hasLineRange) {
return "[ERROR] byte range and line range options are mutually exclusive"
}
if (hasByteRange && shouldCountLines) {
return "[ERROR] countLines cannot be combined with byte range options"
}
var content = ""
var byteDetails = null
var lineDetails = null
var totalLines = null
if (hasByteRange) {
var byteStart = isDef(params.byteStart) ? Number(params.byteStart) : 0
var byteEnd = isDef(params.byteEnd) ? Number(params.byteEnd) : __
var byteLength = isDef(params.byteLength) ? Number(params.byteLength) : __
if (isNaN(byteStart) || byteStart < 0) return "[ERROR] byteStart must be >= 0"
if (isDef(byteEnd) && (isNaN(byteEnd) || byteEnd < 0)) return "[ERROR] byteEnd must be >= 0"
if (isDef(byteLength) && (isNaN(byteLength) || byteLength < 0)) return "[ERROR] byteLength must be >= 0"
if (isDef(byteEnd) && byteEnd < byteStart) return "[ERROR] byteEnd must be >= byteStart"
var raf = io.randomAccessFile(filePath, "r")
var fileSize = Number(raf.length())
if (byteStart > fileSize) byteStart = fileSize
var computedEnd = null
if (isDef(byteLength)) {
computedEnd = byteStart + byteLength - 1
} else if (isDef(byteEnd)) {
computedEnd = byteEnd
} else {
computedEnd = fileSize > 0 ? fileSize - 1 : 0
}
if (computedEnd >= fileSize) computedEnd = fileSize > 0 ? fileSize - 1 : 0
var readLength = (fileSize === 0 || computedEnd < byteStart) ? 0 : (computedEnd - byteStart + 1)
var bytesRead = 0
if (readLength > 0) {
raf.seek(byteStart)
var buffer = java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, readLength)
while (bytesRead < readLength) {
var read = raf.read(buffer, bytesRead, readLength - bytesRead)
if (read === -1) break
bytesRead += read
}
content = String(new java.lang.String(buffer, 0, bytesRead, encoding))
}
raf.close()
byteDetails = {
byteStart: byteStart,
byteEnd: bytesRead === 0 ? byteStart : (byteStart + bytesRead - 1),
bytesRead: bytesRead
}
} else if (hasLineRange) {
var lineStart = isDef(params.lineStart) ? Number(params.lineStart) : 1
var lineEnd = isDef(params.lineEnd) ? Number(params.lineEnd) : __
var maxLines = isDef(params.maxLines) ? Number(params.maxLines) : null
var lineSeparator = isDef(params.lineSeparator) ? String(params.lineSeparator) : "\n"
if (isNaN(lineStart) || lineStart < 1) return "[ERROR] lineStart must be >= 1"
if (isDef(lineEnd) && (isNaN(lineEnd) || lineEnd < 1)) return "[ERROR] lineEnd must be >= 1"
if (isDef(maxLines) && (isNaN(maxLines) || maxLines < 0)) return "[ERROR] maxLines must be >= 0"
if (isDef(lineEnd) && lineEnd < lineStart) return "[ERROR] lineEnd must be >= lineStart"
var lineNo = 0
var lines = []
var countAll = 0
var reader = new java.io.BufferedReader(
new java.io.InputStreamReader(new java.io.FileInputStream(filePath), encoding)
)
try {
while (true) {
var line = reader.readLine()
if (line === null) break
lineNo++
countAll++
var inRange = lineNo >= lineStart && (!isDef(lineEnd) || lineNo <= lineEnd)
if (inRange) {
if (!isDef(maxLines) || lines.length < maxLines) {
lines.push(String(line))
}
}
if (!shouldCountLines) {
if (isDef(lineEnd) && lineNo >= lineEnd) break
if (isDef(maxLines) && lines.length >= maxLines && lineNo >= lineStart) break
}
}
} finally {
try { reader.close() } catch (e) {}
}
content = lines.join(lineSeparator)
lineDetails = {
lineStart: lineStart,
lineEnd: lines.length === 0 ? lineStart - 1 : (lineStart + lines.length - 1),
linesRead: lines.length,
lineSeparator: lineSeparator
}
if (shouldCountLines) {
totalLines = countAll
}
} else {
if (shouldCountLines) {
var reader2 = new java.io.BufferedReader(
new java.io.InputStreamReader(new java.io.FileInputStream(filePath), encoding)
)
var count2 = 0
try {
while (reader2.readLine() !== null) {
count2++
}
} finally {
try { reader2.close() } catch (e) {}
}
totalLines = count2
} else {
content = io.readFileString(filePath, encoding)
}
}
if (params.compact === true) {
var compactResult = {
relativePath: this._toRelative(details.canonicalPath || filePath),
size: details.size,
encoding: encoding,
content: content
}
if (totalLines !== null) {
compactResult.linesTotal = totalLines
}
if (byteDetails) {
compactResult.byteStart = byteDetails.byteStart
compactResult.byteEnd = byteDetails.byteEnd
compactResult.bytesRead = byteDetails.bytesRead
}
if (lineDetails) {
compactResult.lineStart = lineDetails.lineStart
compactResult.lineEnd = lineDetails.lineEnd
compactResult.linesRead = lineDetails.linesRead
compactResult.lineSeparator = lineDetails.lineSeparator
}
return compactResult
}
details.path = isString(details.canonicalPath) ? details.canonicalPath : filePath
details.relativePath = this._toRelative(details.path)
details.encoding = encoding
details.content = content
if (totalLines !== null) {
details.linesTotal = totalLines
}
if (byteDetails) {
details.byteStart = byteDetails.byteStart
details.byteEnd = byteDetails.byteEnd
details.bytesRead = byteDetails.bytesRead
}
if (lineDetails) {
details.lineStart = lineDetails.lineStart
details.lineEnd = lineDetails.lineEnd
details.linesRead = lineDetails.linesRead
details.lineSeparator = lineDetails.lineSeparator
}
return details
} catch (e) {
return "[ERROR] " + __miniAErrMsg(e)
}
}
/**
* <odoc>
* <key>MiniUtilsTool.listDirectory(params) : Array</key>
* Lists the contents of a directory specified by the `path` parameter.
* The `params` object can have the following properties:
* - `path` (string, optional): The relative or absolute path to the directory to be listed. Defaults to the root directory (`"."`).
* - `includeHidden` (boolean, optional): If set to `true`, includes hidden files and directories in the listing. Defaults to `false`.
* - `recursive` (boolean, optional): If set to `true`, lists contents recursively. Defaults to `false`.
*
* Returns an array of objects representing the files and directories within the specified directory on success, or an error message string on failure.
* Each object in the returned array includes:
* - `relativePath`: The path of the file or directory relative to the root directory.
* - Other file metadata such as size, last modified date, type (file or directory), etc.
* </odoc>
*/
MiniUtilsTool.prototype.listDirectory = function(params) {
params = params || {}
try {
this._ensureInitialized()
var dirPath = this._resolve(isDef(params.path) ? params.path : ".")
var info = io.fileInfo(dirPath)
if (isUnDef(info) || info.isDirectory !== true) {
return "[ERROR] Path is not a directory: " + (isDef(params.path) ? params.path : ".")
}
var includeHidden = params.includeHidden === true
var recursive = params.recursive === true
var entries = this._listEntries(dirPath, {
recursive: recursive,
includeHidden: includeHidden
})
if (params.compact === true) {
var fileCount = 0
var dirCount = 0
var compactEntries = entries.map(function(entry) {
if (entry.isDirectory) dirCount++
if (entry.isFile) fileCount++
return {
name: entry.filename,
relativePath: entry.relativePath,
isDirectory: entry.isDirectory,
isFile: entry.isFile,
size: entry.size
}
})
return {
count: entries.length,
files: fileCount,
directories: dirCount,
items: compactEntries
}
}
return entries
} catch (e) {
return "[ERROR] " + __miniAErrMsg(e)
}
}
MiniUtilsTool.prototype.globFiles = function(params) {
params = params || {}
if (isUnDef(params.pattern)) return "[ERROR] pattern is required"
try {
this._ensureInitialized()
var basePath = this._resolve(isDef(params.path) ? params.path : ".")
var info = io.fileInfo(basePath)