forked from Nimblesite/CommandTree
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCommandTreeProvider.ts
More file actions
234 lines (206 loc) · 7.76 KB
/
Copy pathCommandTreeProvider.ts
File metadata and controls
234 lines (206 loc) · 7.76 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
import * as vscode from "vscode";
import { isPhonyTask, isPrivateTask } from "./models/TaskItem";
import type { CommandItem, CategoryDef } from "./models/TaskItem";
import type { CommandTreeItem } from "./models/TaskItem";
import type { DiscoveryResult } from "./discovery";
import { discoverAllTasks, flattenTasks, getExcludePatterns, CATEGORY_DEFS } from "./discovery";
import { TagConfig } from "./config/TagConfig";
import { logger } from "./utils/logger";
import { buildNestedFolderItems } from "./tree/folderTree";
import { createCategoryNode, createTaskNodes } from "./tree/nodeFactory";
import { getAllRows } from "./db/db";
import type { CommandRow } from "./db/db";
import { getDbOrThrow } from "./db/lifecycle";
type SortOrder = "folder" | "name" | "type";
/**
* Tree data provider for CommandTree view.
*/
export class CommandTreeProvider implements vscode.TreeDataProvider<CommandTreeItem> {
private readonly _onDidChangeTreeData = new vscode.EventEmitter<CommandTreeItem | undefined>();
public readonly onDidChangeTreeData = this._onDidChangeTreeData.event;
private commands: CommandItem[] = [];
private discoveryResult: DiscoveryResult | null = null;
private tagFilter: string | null = null;
private summaries: ReadonlyMap<string, CommandRow> = new Map();
private readonly tagConfig: TagConfig;
private readonly workspaceRoot: string;
public constructor(workspaceRoot: string) {
this.workspaceRoot = workspaceRoot;
this.tagConfig = new TagConfig();
}
public async refresh(): Promise<void> {
logger.info("CommandTreeProvider.refresh() starting");
this.tagConfig.load();
logger.info("Tag config loaded, getting exclude patterns");
const excludePatterns = getExcludePatterns();
logger.info("Exclude patterns", { excludePatterns });
this.discoveryResult = await discoverAllTasks(this.workspaceRoot, excludePatterns);
logger.info("Discovery result received, flattening tasks");
this.commands = this.tagConfig.applyTags(flattenTasks(this.discoveryResult));
logger.info("Tasks flattened and tagged", { count: this.commands.length });
this.loadSummaries();
this.commands = this.attachSummaries(this.commands);
logger.info("Summaries attached, firing tree change event");
this._onDidChangeTreeData.fire(undefined);
}
private loadSummaries(): void {
const handle = getDbOrThrow();
const rows = getAllRows(handle);
const map = new Map<string, CommandRow>();
for (const row of rows) {
map.set(row.commandId, row);
}
this.summaries = map;
}
private attachSummaries(tasks: CommandItem[]): CommandItem[] {
if (this.summaries.size === 0) {
return tasks;
}
return tasks.map((task) => {
const record = this.summaries.get(task.id);
if (record === undefined) {
return task;
}
const warning = record.securityWarning;
return {
...task,
summary: record.summary,
...(warning !== null ? { securityWarning: warning } : {}),
};
});
}
public setTagFilter(tag: string | null): void {
logger.filter("setTagFilter", { tagFilter: tag });
this.tagFilter = tag;
this._onDidChangeTreeData.fire(undefined);
}
public clearFilters(): void {
this.tagFilter = null;
this._onDidChangeTreeData.fire(undefined);
}
public hasFilter(): boolean {
return this.tagFilter !== null;
}
public getAllTags(): string[] {
const tags = new Set<string>();
for (const task of this.commands) {
for (const tag of task.tags) {
tags.add(tag);
}
}
for (const tag of this.tagConfig.getTagNames()) {
tags.add(tag);
}
return Array.from(tags).sort();
}
public async addTaskToTag(task: CommandItem, tagName: string): Promise<void> {
this.tagConfig.addTaskToTag(task, tagName);
await this.refresh();
}
public async removeTaskFromTag(task: CommandItem, tagName: string): Promise<void> {
this.tagConfig.removeTaskFromTag(task, tagName);
await this.refresh();
}
public getAllTasks(): CommandItem[] {
return this.commands;
}
public getTreeItem(element: CommandTreeItem): vscode.TreeItem {
return element;
}
public async getChildren(element?: CommandTreeItem): Promise<CommandTreeItem[]> {
if (!this.discoveryResult) {
logger.info("getChildren: no discovery result yet, triggering refresh");
await this.refresh();
}
if (!element) {
const roots = this.buildRootCategories();
logger.info("getChildren: root categories built", { categoryCount: roots.length });
return roots;
}
return element.children;
}
private buildRootCategories(): CommandTreeItem[] {
const filtered = this.applyTagFilter(this.commands);
return CATEGORY_DEFS.map((def) => this.buildCategoryIfNonEmpty(filtered, def)).filter(
(c): c is CommandTreeItem => c !== null
);
}
private buildCategoryIfNonEmpty(tasks: readonly CommandItem[], def: CategoryDef): CommandTreeItem | null {
const matched = tasks.filter((t) => t.type === def.type);
if (matched.length === 0) {
return null;
}
return def.flat === true ? this.buildFlatCategory(def, matched) : this.buildCategoryWithFolders(def, matched);
}
private buildCategoryWithFolders(def: CategoryDef, tasks: CommandItem[]): CommandTreeItem {
const children = buildNestedFolderItems({
tasks,
workspaceRoot: this.workspaceRoot,
categoryId: def.label,
sortTasks: (t) => this.sortTasks(t),
});
return createCategoryNode({
label: `${def.label} (${tasks.length})`,
children,
type: def.type,
});
}
private buildFlatCategory(def: CategoryDef, tasks: CommandItem[]): CommandTreeItem {
const sorted = this.sortTasks(tasks);
const children = createTaskNodes(sorted);
return createCategoryNode({
label: `${def.label} (${tasks.length})`,
children,
type: def.type,
});
}
private getSortOrder(): SortOrder {
return vscode.workspace.getConfiguration("commandtree").get<SortOrder>("sortOrder", "folder");
}
private sortTasks(tasks: CommandItem[]): CommandItem[] {
const comparator = this.getComparator();
return [...tasks].sort(comparator);
}
private comparePrivateTasks(a: CommandItem, b: CommandItem): number {
return Number(isPrivateTask(a)) - Number(isPrivateTask(b));
}
private compareHelpTasks(a: CommandItem, b: CommandItem): number {
const isHelpA = a.type === "make" && a.label === "help";
const isHelpB = b.type === "make" && b.label === "help";
return Number(isHelpB) - Number(isHelpA);
}
private comparePhonyTasks(a: CommandItem, b: CommandItem): number {
return Number(isPhonyTask(b)) - Number(isPhonyTask(a));
}
private compareMakeTaskPriority(a: CommandItem, b: CommandItem): number {
if (a.type !== "make" || b.type !== "make") {
return 0;
}
return this.compareHelpTasks(a, b) || this.comparePhonyTasks(a, b);
}
private getComparator(): (a: CommandItem, b: CommandItem) => number {
const order = this.getSortOrder();
if (order === "folder") {
return (a, b) =>
a.category.localeCompare(b.category) ||
this.comparePrivateTasks(a, b) ||
this.compareMakeTaskPriority(a, b) ||
a.label.localeCompare(b.label);
}
if (order === "type") {
return (a, b) =>
a.type.localeCompare(b.type) ||
this.comparePrivateTasks(a, b) ||
this.compareMakeTaskPriority(a, b) ||
a.label.localeCompare(b.label);
}
return (a, b) => this.comparePrivateTasks(a, b) || this.compareMakeTaskPriority(a, b) || a.label.localeCompare(b.label);
}
private applyTagFilter(tasks: CommandItem[]): CommandItem[] {
if (this.tagFilter === null || this.tagFilter === "") {
return tasks;
}
const tag = this.tagFilter;
return tasks.filter((t) => t.tags.includes(tag));
}
}