-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathquickActions.ts
More file actions
1227 lines (1091 loc) · 41.7 KB
/
Copy pathquickActions.ts
File metadata and controls
1227 lines (1091 loc) · 41.7 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
import { execFile } from "node:child_process";
import * as fs from "node:fs/promises";
import * as os from "node:os";
import * as path from "node:path";
import { promisify } from "node:util";
import type * as VSCode from "vscode";
import { patchloomNeedsUpgrade, resolvePatchloomStatus } from "../binary/patchloom.js";
import { getPatchloomLog } from "../logging/outputChannel.js";
import { formatCliOutput, formatError } from "../util.js";
import { activeWorkspaceFolder, describeWorkspaceEnvironment } from "../workspace/readiness.js";
const execFileAsync = promisify(execFile);
const STRUCTURED_FILE_EXTENSIONS = new Set([".json", ".yaml", ".yml", ".toml"]);
const MARKDOWN_FILE_EXTENSIONS = new Set([".md", ".markdown", ".mdx"]);
export type TidyFix = "ensure-final-newline" | "trim-trailing-whitespace" | "normalize-eol-lf";
export interface PlannedQuickAction {
readonly title: string;
readonly targetPath: string;
readonly targetArgIndices: readonly number[];
readonly args: readonly string[];
}
interface WorkspaceFileTarget {
readonly workspaceFolder: VSCode.WorkspaceFolder;
readonly absolutePath: string;
readonly relativePath: string;
readonly uri: VSCode.Uri;
}
interface PatchloomCommandResult {
readonly exitCode: number;
readonly stdout: string;
readonly stderr: string;
}
export async function runQuickAction(): Promise<void> {
const vscode = await import("vscode");
const status = await resolvePatchloomStatus();
if (!status.ready || !status.binaryPath) {
const choice = await vscode.window.showWarningMessage(status.message, "Open Settings");
if (choice === "Open Settings") {
await vscode.commands.executeCommand("patchloom.openPatchloomSettings");
}
return;
}
if (patchloomNeedsUpgrade(status)) {
const choice = await vscode.window.showWarningMessage(
`${status.compatibilityMessage}\n\nUpgrade Patchloom before running quick actions.`,
"Open Releases"
);
if (choice === "Open Releases") {
await vscode.commands.executeCommand("patchloom.openPatchloomReleases");
}
return;
}
const binaryPath = status.binaryPath;
const actions: Array<VSCode.QuickPickItem & { run: () => Promise<void> }> = [
{
label: "Replace text in file",
description: "Literal text replacement with diff preview",
detail: "Builds `patchloom replace <from> --to <to> <file>`",
run: async () => {
const target = await pickWorkspaceFileTarget("Select a file for Patchloom replace");
if (!target) {
return;
}
const from = await vscode.window.showInputBox({
prompt: "Text to find",
placeHolder: "old_name",
validateInput: (value) => value.length > 0 ? undefined : "Search text is required."
});
if (from === undefined) {
return;
}
const to = await vscode.window.showInputBox({
prompt: "Replacement text",
placeHolder: "new_name"
});
if (to === undefined) {
return;
}
await previewAndMaybeApply(binaryPath, target, buildReplaceQuickAction(target.absolutePath, from, to));
}
},
{
label: "Tidy file",
description: "Whitespace and newline cleanup with diff preview",
detail: "Builds `patchloom tidy fix <file> ...`",
run: async () => {
const target = await pickWorkspaceFileTarget("Select a file for Patchloom tidy");
if (!target) {
return;
}
const fixes = await vscode.window.showQuickPick<VSCode.QuickPickItem & { fix: TidyFix }>([
{
label: "Ensure final newline",
description: "Recommended",
picked: true,
fix: "ensure-final-newline"
},
{
label: "Trim trailing whitespace",
description: "Recommended",
picked: true,
fix: "trim-trailing-whitespace"
},
{
label: "Normalize line endings to LF",
description: "Optional",
fix: "normalize-eol-lf"
}
], {
canPickMany: true,
placeHolder: "Select tidy fixes to preview"
});
if (!fixes || fixes.length === 0) {
return;
}
await previewAndMaybeApply(
binaryPath,
target,
buildTidyQuickAction(target.absolutePath, fixes.map((fix) => fix.fix))
);
}
},
{
label: "Set structured value",
description: "Update JSON, YAML, or TOML with diff preview",
detail: "Builds `patchloom doc set <file> <selector> <value>`",
run: async () => {
const target = await pickWorkspaceFileTarget("Select a JSON, YAML, or TOML file for Patchloom doc set");
if (!target) {
return;
}
if (!isStructuredDocumentPath(target.absolutePath)) {
await vscode.window.showWarningMessage(
`${target.relativePath} is not a supported JSON, YAML, or TOML file for Patchloom doc set.`
);
return;
}
const selector = await vscode.window.showInputBox({
prompt: "Selector path",
placeHolder: "scripts.test",
validateInput: (value) => value.length > 0 ? undefined : "Selector is required."
});
if (selector === undefined) {
return;
}
const value = await vscode.window.showInputBox({
prompt: "Value",
placeHolder: "true, 42, hello, or {\"key\":\"value\"}",
value: "",
validateInput: (input) => input.length > 0 ? undefined : "Value is required."
});
if (value === undefined) {
return;
}
await previewAndMaybeApply(binaryPath, target, buildDocSetQuickAction(target.absolutePath, selector, value));
}
},
{
label: "Search text across files",
description: "Find pattern matches in workspace files",
detail: "Builds `patchloom search <pattern> [--glob <glob>] <workspace>`",
run: async () => {
const folder = await activeWorkspaceFolder({
promptIfMany: true,
placeHolder: "Select workspace folder for Patchloom search"
});
if (!folder) {
await vscode.window.showWarningMessage("Open a workspace folder before running Patchloom search.");
return;
}
const pattern = await vscode.window.showInputBox({
prompt: "Search pattern",
placeHolder: "TODO|FIXME",
validateInput: (value) => value.length > 0 ? undefined : "Pattern is required."
});
if (pattern === undefined) {
return;
}
const glob = await vscode.window.showInputBox({
prompt: "File glob (optional, leave empty for all files)",
placeHolder: "*.ts"
});
if (glob === undefined) {
return;
}
const action = buildSearchQuickAction(folder.uri.fsPath, pattern, glob || undefined);
const result = await executePatchloom(binaryPath, action.args, folder.uri.fsPath);
const log = getPatchloomLog();
if (result.exitCode === 3) {
await vscode.window.showInformationMessage(`No matches found for "${pattern}".`);
} else if (result.exitCode !== 0) {
await vscode.window.showErrorMessage(`Patchloom search failed: ${formatCliOutput(result)}`);
} else {
log?.show();
await vscode.window.showInformationMessage("Search results displayed in the Patchloom output channel.");
}
}
},
{
label: "Create a new file",
description: "Scaffold a new file in the workspace",
detail: "Builds `patchloom create <path>`",
run: async () => {
const folder = await activeWorkspaceFolder({
promptIfMany: true,
placeHolder: "Select workspace folder for Patchloom create"
});
if (!folder) {
await vscode.window.showWarningMessage("Open a workspace folder before running Patchloom create.");
return;
}
const relativePath = await vscode.window.showInputBox({
prompt: "File path relative to workspace",
placeHolder: "src/newfile.ts",
validateInput: (value) => value.trim().length > 0 ? undefined : "Path is required."
});
if (relativePath === undefined) {
return;
}
const absolutePath = path.resolve(folder.uri.fsPath, relativePath.trim());
const relative = path.relative(folder.uri.fsPath, absolutePath);
if (!relative || relative.startsWith("..") || path.isAbsolute(relative)) {
await vscode.window.showWarningMessage("File path must stay inside the workspace folder.");
return;
}
const action = buildCreateQuickAction(absolutePath);
const result = await executePatchloom(binaryPath, action.args, folder.uri.fsPath);
if (result.exitCode !== 0) {
await vscode.window.showErrorMessage(`Patchloom create failed: ${formatCliOutput(result)}`);
return;
}
const uri = vscode.Uri.file(absolutePath);
const doc = await vscode.workspace.openTextDocument(uri);
await vscode.window.showTextDocument(doc, { preview: false });
await vscode.window.showInformationMessage(`Created ${relativePath.trim()}.`);
}
},
{
label: "Read structured value",
description: "Read a value from JSON, YAML, or TOML",
detail: "Builds `patchloom doc get <file> <selector>`",
run: async () => {
const target = await pickWorkspaceFileTarget("Select a JSON, YAML, or TOML file for Patchloom doc get");
if (!target) {
return;
}
if (!isStructuredDocumentPath(target.absolutePath)) {
await vscode.window.showWarningMessage(
`${target.relativePath} is not a supported JSON, YAML, or TOML file for Patchloom doc get.`
);
return;
}
const selector = await vscode.window.showInputBox({
prompt: "Selector path",
placeHolder: "scripts.test",
validateInput: (value) => value.length > 0 ? undefined : "Selector is required."
});
if (selector === undefined) {
return;
}
const action = buildDocGetQuickAction(target.absolutePath, selector);
const result = await executePatchloom(binaryPath, action.args, target.workspaceFolder.uri.fsPath);
if (result.exitCode !== 0) {
await vscode.window.showErrorMessage(`Patchloom doc get failed: ${formatCliOutput(result)}`);
return;
}
const value = result.stdout.trim();
await vscode.env.clipboard.writeText(value);
await vscode.window.showInformationMessage(`${selector} = ${value} (copied to clipboard)`);
}
},
{
label: "Delete structured value",
description: "Remove a key from JSON, YAML, or TOML with diff preview",
detail: "Builds `patchloom doc delete <file> <selector>`",
run: async () => {
const target = await pickWorkspaceFileTarget("Select a JSON, YAML, or TOML file for Patchloom doc delete");
if (!target) {
return;
}
if (!isStructuredDocumentPath(target.absolutePath)) {
await vscode.window.showWarningMessage(
`${target.relativePath} is not a supported JSON, YAML, or TOML file for Patchloom doc delete.`
);
return;
}
const selector = await vscode.window.showInputBox({
prompt: "Selector path to delete",
placeHolder: "scripts.deprecated",
validateInput: (value) => value.length > 0 ? undefined : "Selector is required."
});
if (selector === undefined) {
return;
}
await previewAndMaybeApply(binaryPath, target, buildDocDeleteQuickAction(target.absolutePath, selector));
}
},
{
label: "Merge into structured file",
description: "Merge a partial JSON object into a config file",
detail: "Builds `patchloom doc merge <file> --value <json>`",
run: async () => {
const target = await pickWorkspaceFileTarget("Select a JSON, YAML, or TOML file for Patchloom doc merge");
if (!target) {
return;
}
if (!isStructuredDocumentPath(target.absolutePath)) {
await vscode.window.showWarningMessage(
`${target.relativePath} is not a supported JSON, YAML, or TOML file for Patchloom doc merge.`
);
return;
}
const value = await vscode.window.showInputBox({
prompt: "Partial JSON object to merge",
placeHolder: '{"debug": true, "logLevel": "verbose"}',
validateInput: (input) => input.length > 0 ? undefined : "Value is required."
});
if (value === undefined) {
return;
}
await previewAndMaybeApply(binaryPath, target, buildDocMergeQuickAction(target.absolutePath, value));
}
},
{
label: "Append to array",
description: "Append a value to a JSON, YAML, or TOML array",
detail: "Builds `patchloom doc append <file> <selector> <value>`",
run: async () => {
const target = await pickWorkspaceFileTarget("Select a JSON, YAML, or TOML file for Patchloom doc append");
if (!target) {
return;
}
if (!isStructuredDocumentPath(target.absolutePath)) {
await vscode.window.showWarningMessage(
`${target.relativePath} is not a supported JSON, YAML, or TOML file for Patchloom doc append.`
);
return;
}
const selector = await vscode.window.showInputBox({
prompt: "Selector path to the array",
placeHolder: "dependencies",
validateInput: (value) => value.length > 0 ? undefined : "Selector is required."
});
if (selector === undefined) {
return;
}
const value = await vscode.window.showInputBox({
prompt: "Value to append",
placeHolder: '"new-item"',
validateInput: (input) => input.length > 0 ? undefined : "Value is required."
});
if (value === undefined) {
return;
}
await previewAndMaybeApply(binaryPath, target, buildDocAppendQuickAction(target.absolutePath, selector, value));
}
},
{
label: "Prepend to array",
description: "Prepend a value to a JSON, YAML, or TOML array",
detail: "Builds `patchloom doc prepend <file> <selector> <value>`",
run: async () => {
const target = await pickWorkspaceFileTarget("Select a JSON, YAML, or TOML file for Patchloom doc prepend");
if (!target) {
return;
}
if (!isStructuredDocumentPath(target.absolutePath)) {
await vscode.window.showWarningMessage(
`${target.relativePath} is not a supported JSON, YAML, or TOML file for Patchloom doc prepend.`
);
return;
}
const selector = await vscode.window.showInputBox({
prompt: "Selector path to the array",
placeHolder: "dependencies",
validateInput: (value) => value.length > 0 ? undefined : "Selector is required."
});
if (selector === undefined) {
return;
}
const value = await vscode.window.showInputBox({
prompt: "Value to prepend",
placeHolder: '"new-item"',
validateInput: (input) => input.length > 0 ? undefined : "Value is required."
});
if (value === undefined) {
return;
}
await previewAndMaybeApply(binaryPath, target, buildDocPrependQuickAction(target.absolutePath, selector, value));
}
},
{
label: "Ensure structured value",
description: "Idempotent set: only write if the key is missing",
detail: "Builds `patchloom doc ensure <file> <selector> <value>`",
run: async () => {
const target = await pickWorkspaceFileTarget("Select a JSON, YAML, or TOML file for Patchloom doc ensure");
if (!target) {
return;
}
if (!isStructuredDocumentPath(target.absolutePath)) {
await vscode.window.showWarningMessage(
`${target.relativePath} is not a supported JSON, YAML, or TOML file for Patchloom doc ensure.`
);
return;
}
const selector = await vscode.window.showInputBox({
prompt: "Selector path",
placeHolder: "server.port",
validateInput: (value) => value.length > 0 ? undefined : "Selector is required."
});
if (selector === undefined) {
return;
}
const value = await vscode.window.showInputBox({
prompt: "Default value (set only if missing)",
placeHolder: "8080",
validateInput: (input) => input.length > 0 ? undefined : "Value is required."
});
if (value === undefined) {
return;
}
await previewAndMaybeApply(binaryPath, target, buildDocEnsureQuickAction(target.absolutePath, selector, value));
}
},
{
label: "Move/rename key",
description: "Move or rename a selector path in JSON, YAML, or TOML",
detail: "Builds `patchloom doc move <file> <from> <to>`",
run: async () => {
const target = await pickWorkspaceFileTarget("Select a JSON, YAML, or TOML file for Patchloom doc move");
if (!target) {
return;
}
if (!isStructuredDocumentPath(target.absolutePath)) {
await vscode.window.showWarningMessage(
`${target.relativePath} is not a supported JSON, YAML, or TOML file for Patchloom doc move.`
);
return;
}
const from = await vscode.window.showInputBox({
prompt: "Source selector path",
placeHolder: "old.key",
validateInput: (value) => value.length > 0 ? undefined : "Source selector is required."
});
if (from === undefined) {
return;
}
const to = await vscode.window.showInputBox({
prompt: "Destination selector path",
placeHolder: "new.key",
validateInput: (value) => value.length > 0 ? undefined : "Destination selector is required."
});
if (to === undefined) {
return;
}
await previewAndMaybeApply(binaryPath, target, buildDocMoveQuickAction(target.absolutePath, from, to));
}
},
{
label: "Insert after heading",
description: "Insert content after a markdown heading",
detail: "Builds `patchloom md insert-after-heading <file> --heading <h> --content <text>`",
run: async () => {
const target = await pickWorkspaceFileTarget("Select a markdown file for Patchloom insert-after-heading");
if (!target) {
return;
}
if (!isMarkdownPath(target.absolutePath)) {
await vscode.window.showWarningMessage(
`${target.relativePath} is not a markdown file.`
);
return;
}
const heading = await vscode.window.showInputBox({
prompt: "Heading to insert content after",
placeHolder: "## Installation",
validateInput: (value) => value.length > 0 ? undefined : "Heading is required."
});
if (heading === undefined) {
return;
}
const content = await vscode.window.showInputBox({
prompt: "Content to insert",
placeHolder: "New paragraph text",
validateInput: (value) => value.length > 0 ? undefined : "Content is required."
});
if (content === undefined) {
return;
}
await previewAndMaybeApply(binaryPath, target, buildMdInsertAfterHeadingQuickAction(target.absolutePath, heading, content));
}
},
{
label: "Insert before heading",
description: "Insert content before a markdown heading",
detail: "Builds `patchloom md insert-before-heading <file> --heading <h> --content <text>`",
run: async () => {
const target = await pickWorkspaceFileTarget("Select a markdown file for Patchloom insert-before-heading");
if (!target) {
return;
}
if (!isMarkdownPath(target.absolutePath)) {
await vscode.window.showWarningMessage(
`${target.relativePath} is not a markdown file.`
);
return;
}
const heading = await vscode.window.showInputBox({
prompt: "Heading to insert content before",
placeHolder: "## Changelog",
validateInput: (value) => value.length > 0 ? undefined : "Heading is required."
});
if (heading === undefined) {
return;
}
const content = await vscode.window.showInputBox({
prompt: "Content to insert",
placeHolder: "New section text",
validateInput: (value) => value.length > 0 ? undefined : "Content is required."
});
if (content === undefined) {
return;
}
await previewAndMaybeApply(binaryPath, target, buildMdInsertBeforeHeadingQuickAction(target.absolutePath, heading, content));
}
},
{
label: "Append table row",
description: "Append a row to a markdown table under a heading",
detail: "Builds `patchloom md table-append <file> --heading <h> --row <row>`",
run: async () => {
const target = await pickWorkspaceFileTarget("Select a markdown file for Patchloom table-append");
if (!target) {
return;
}
if (!isMarkdownPath(target.absolutePath)) {
await vscode.window.showWarningMessage(
`${target.relativePath} is not a markdown file.`
);
return;
}
const heading = await vscode.window.showInputBox({
prompt: "Heading containing the table",
placeHolder: "## API",
validateInput: (value) => value.length > 0 ? undefined : "Heading is required."
});
if (heading === undefined) {
return;
}
const row = await vscode.window.showInputBox({
prompt: "Table row to append (pipe-delimited)",
placeHolder: "| /users | List users | GET |",
validateInput: (value) => value.length > 0 ? undefined : "Row is required."
});
if (row === undefined) {
return;
}
await previewAndMaybeApply(binaryPath, target, buildMdTableAppendQuickAction(target.absolutePath, heading, row));
}
},
{
label: "Upsert bullet",
description: "Add a bullet under a markdown heading (idempotent)",
detail: "Builds `patchloom md upsert-bullet <file> --heading <h> --bullet <text>`",
run: async () => {
const target = await pickWorkspaceFileTarget("Select a markdown file for Patchloom upsert-bullet");
if (!target) {
return;
}
if (!isMarkdownPath(target.absolutePath)) {
await vscode.window.showWarningMessage(
`${target.relativePath} is not a markdown file.`
);
return;
}
const heading = await vscode.window.showInputBox({
prompt: "Heading to add the bullet under",
placeHolder: "## Rules",
validateInput: (value) => value.length > 0 ? undefined : "Heading is required."
});
if (heading === undefined) {
return;
}
const bullet = await vscode.window.showInputBox({
prompt: "Bullet text (without leading dash)",
placeHolder: "Run make check before committing",
validateInput: (value) => value.length > 0 ? undefined : "Bullet text is required."
});
if (bullet === undefined) {
return;
}
await previewAndMaybeApply(binaryPath, target, buildMdUpsertBulletQuickAction(target.absolutePath, heading, bullet));
}
},
{
label: "Replace markdown section",
description: "Replace content under a markdown heading",
detail: "Builds `patchloom md replace-section <file> --heading <h> --content <text>`",
run: async () => {
const target = await pickWorkspaceFileTarget("Select a markdown file for Patchloom replace-section");
if (!target) {
return;
}
if (!isMarkdownPath(target.absolutePath)) {
await vscode.window.showWarningMessage(
`${target.relativePath} is not a markdown file.`
);
return;
}
const heading = await vscode.window.showInputBox({
prompt: "Heading of the section to replace",
placeHolder: "## Unreleased",
validateInput: (value) => value.length > 0 ? undefined : "Heading is required."
});
if (heading === undefined) {
return;
}
const content = await vscode.window.showInputBox({
prompt: "New section content",
placeHolder: "- New feature added",
validateInput: (value) => value.length > 0 ? undefined : "Content is required."
});
if (content === undefined) {
return;
}
await previewAndMaybeApply(binaryPath, target, buildMdReplaceSectionQuickAction(target.absolutePath, heading, content));
}
},
{
label: "Undo last change",
description: "Restore files from the last patchloom backup",
detail: "Runs `patchloom undo`",
run: async () => {
const folder = await activeWorkspaceFolder({
promptIfMany: true,
placeHolder: "Select workspace folder for Patchloom undo"
});
if (!folder) {
await vscode.window.showWarningMessage("Open a workspace folder before running Patchloom undo.");
return;
}
const confirm = await vscode.window.showWarningMessage(
"Undo the last patchloom edit? This restores files from backup.",
{ modal: true },
"Undo"
);
if (confirm !== "Undo") {
return;
}
const action = buildUndoQuickAction(folder.uri.fsPath);
const result = await executePatchloom(binaryPath, action.args, folder.uri.fsPath);
if (result.exitCode !== 0) {
const message = result.stderr.includes("no backup")
? "No patchloom backup to undo."
: `Patchloom undo failed: ${formatCliOutput(result)}`;
await vscode.window.showWarningMessage(message);
return;
}
const log = getPatchloomLog();
log?.show();
await vscode.window.showInformationMessage("Patchloom undo complete. Restored files shown in the output channel.");
}
}
];
const selection = await vscode.window.showQuickPick(actions, {
placeHolder: "Select a Patchloom quick action"
});
if (!selection) {
return;
}
await selection.run();
}
export function buildReplaceQuickAction(targetPath: string, from: string, to: string): PlannedQuickAction {
return {
title: `Replace text in ${path.basename(targetPath)}`,
targetPath,
targetArgIndices: [4],
args: ["replace", from, "--to", to, targetPath]
};
}
export function buildTidyQuickAction(targetPath: string, fixes: readonly TidyFix[]): PlannedQuickAction {
const args = ["tidy", "fix", targetPath];
if (fixes.includes("ensure-final-newline")) {
args.push("--ensure-final-newline");
}
if (fixes.includes("trim-trailing-whitespace")) {
args.push("--trim-trailing-whitespace");
}
if (fixes.includes("normalize-eol-lf")) {
args.push("--normalize-eol", "lf");
}
return {
title: `Tidy ${path.basename(targetPath)}`,
targetPath,
targetArgIndices: [2],
args
};
}
export function buildDocSetQuickAction(targetPath: string, selector: string, value: string): PlannedQuickAction {
return {
title: `Set ${selector} in ${path.basename(targetPath)}`,
targetPath,
targetArgIndices: [2],
args: ["doc", "set", targetPath, selector, value]
};
}
export function buildSearchQuickAction(workspacePath: string, pattern: string, glob?: string): PlannedQuickAction {
const args: string[] = ["search", pattern];
if (glob) {
args.push("--glob", glob);
}
args.push(workspacePath);
const targetIndex = args.length - 1;
return {
title: `Search for "${pattern}"`,
targetPath: workspacePath,
targetArgIndices: [targetIndex],
args
};
}
export function buildCreateQuickAction(filePath: string): PlannedQuickAction {
return {
title: `Create ${path.basename(filePath)}`,
targetPath: filePath,
targetArgIndices: [1],
args: ["create", filePath]
};
}
export function buildDocGetQuickAction(targetPath: string, selector: string): PlannedQuickAction {
return {
title: `Get ${selector} from ${path.basename(targetPath)}`,
targetPath,
targetArgIndices: [2],
args: ["doc", "get", targetPath, selector]
};
}
export function buildDocDeleteQuickAction(targetPath: string, selector: string): PlannedQuickAction {
return {
title: `Delete ${selector} from ${path.basename(targetPath)}`,
targetPath,
targetArgIndices: [2],
args: ["doc", "delete", targetPath, selector]
};
}
export function buildDocMergeQuickAction(targetPath: string, value: string): PlannedQuickAction {
return {
title: `Merge into ${path.basename(targetPath)}`,
targetPath,
targetArgIndices: [2],
args: ["doc", "merge", targetPath, "--value", value]
};
}
export function buildDocAppendQuickAction(targetPath: string, selector: string, value: string): PlannedQuickAction {
return {
title: `Append to ${selector} in ${path.basename(targetPath)}`,
targetPath,
targetArgIndices: [2],
args: ["doc", "append", targetPath, selector, value]
};
}
export function buildMdTableAppendQuickAction(targetPath: string, heading: string, row: string): PlannedQuickAction {
return {
title: `Append table row under "${heading}" in ${path.basename(targetPath)}`,
targetPath,
targetArgIndices: [2],
args: ["md", "table-append", targetPath, "--heading", heading, "--row", row]
};
}
export function buildMdUpsertBulletQuickAction(targetPath: string, heading: string, bullet: string): PlannedQuickAction {
return {
title: `Upsert bullet under "${heading}" in ${path.basename(targetPath)}`,
targetPath,
targetArgIndices: [2],
args: ["md", "upsert-bullet", targetPath, "--heading", heading, "--bullet", bullet]
};
}
export function buildMdReplaceSectionQuickAction(targetPath: string, heading: string, content: string): PlannedQuickAction {
return {
title: `Replace "${heading}" in ${path.basename(targetPath)}`,
targetPath,
targetArgIndices: [2],
args: ["md", "replace-section", targetPath, "--heading", heading, "--content", content]
};
}
export function buildDocPrependQuickAction(targetPath: string, selector: string, value: string): PlannedQuickAction {
return {
title: `Prepend to ${selector} in ${path.basename(targetPath)}`,
targetPath,
targetArgIndices: [2],
args: ["doc", "prepend", targetPath, selector, value]
};
}
export function buildDocEnsureQuickAction(targetPath: string, selector: string, value: string): PlannedQuickAction {
return {
title: `Ensure ${selector} in ${path.basename(targetPath)}`,
targetPath,
targetArgIndices: [2],
args: ["doc", "ensure", targetPath, selector, value]
};
}
export function buildDocMoveQuickAction(targetPath: string, from: string, to: string): PlannedQuickAction {
return {
title: `Move ${from} to ${to} in ${path.basename(targetPath)}`,
targetPath,
targetArgIndices: [2],
args: ["doc", "move", targetPath, from, to]
};
}
export function buildMdInsertAfterHeadingQuickAction(targetPath: string, heading: string, content: string): PlannedQuickAction {
return {
title: `Insert after "${heading}" in ${path.basename(targetPath)}`,
targetPath,
targetArgIndices: [2],
args: ["md", "insert-after-heading", targetPath, "--heading", heading, "--content", content]
};
}
export function buildMdInsertBeforeHeadingQuickAction(targetPath: string, heading: string, content: string): PlannedQuickAction {
return {
title: `Insert before "${heading}" in ${path.basename(targetPath)}`,
targetPath,
targetArgIndices: [2],
args: ["md", "insert-before-heading", targetPath, "--heading", heading, "--content", content]
};
}
export function buildUndoQuickAction(workspacePath: string): PlannedQuickAction {
return {
title: "Undo last patchloom change",
targetPath: workspacePath,
targetArgIndices: [],
args: ["undo", "--apply"]
};
}
export function isMarkdownPath(filePath: string): boolean {
return MARKDOWN_FILE_EXTENSIONS.has(path.extname(filePath).toLowerCase());
}
export function isStructuredDocumentPath(filePath: string): boolean {
return STRUCTURED_FILE_EXTENSIONS.has(path.extname(filePath).toLowerCase());
}
export function retargetQuickAction(action: PlannedQuickAction, nextTargetPath: string): PlannedQuickAction {
return {
...action,
targetPath: nextTargetPath,
args: action.args.map((arg, index) => action.targetArgIndices.includes(index) ? nextTargetPath : arg)
};
}
export function withApplyFlag(args: readonly string[]): string[] {
return args.includes("--apply") ? [...args] : [...args, "--apply"];
}
async function previewAndMaybeApply(
binaryPath: string,
target: WorkspaceFileTarget,
action: PlannedQuickAction
): Promise<void> {
const vscode = await import("vscode");
const originalDocument = await vscode.workspace.openTextDocument(target.uri);
const originalContent = await fs.readFile(target.absolutePath, "utf8");
const preview = await buildPreviewDocument(binaryPath, action, originalContent, originalDocument.languageId);
if (!preview) {
await vscode.window.showInformationMessage(`No changes to preview for ${target.relativePath}.`);
return;
}
await vscode.commands.executeCommand(
"vscode.diff",
target.uri,
preview.uri,
`${action.title} (Patchloom preview)`
);
const choice = await vscode.window.showInformationMessage(
`Preview ready for ${target.relativePath}. Apply these changes?`,
"Apply Changes"
);
if (choice !== "Apply Changes") {
return;
}
const result = await executePatchloom(binaryPath, withApplyFlag(action.args), target.workspaceFolder.uri.fsPath);
if (result.exitCode !== 0) {
await vscode.window.showErrorMessage(
`Patchloom failed while applying changes to ${target.relativePath}: ${formatCliOutput(result)}`
);
return;
}
const document = await vscode.workspace.openTextDocument(target.uri);
await vscode.window.showTextDocument(document, { preview: false });
const { refreshStatusBar } = await import("../status/statusBar.js");
await refreshStatusBar();
await vscode.window.showInformationMessage(`Applied Patchloom quick action to ${target.relativePath}.`);
}
async function buildPreviewDocument(
binaryPath: string,
action: PlannedQuickAction,
originalContent: string,