Skip to content

Commit 10c9211

Browse files
Enhance documentation and improve code structure across multiple files
- Added detailed JSDoc comments to `ccpWebviewProvider.ts`, `extension.ts`, `fileSelector.ts`, `statsManager.ts`, and `statsViewProvider.ts` for better clarity on functionality and parameters. - Improved the organization of code by grouping related functionalities and enhancing readability. - Updated the `CommentPattern` and `CommentHandler` classes in `ccp.py` with comprehensive docstrings to clarify their purpose and usage. - Enhanced the `StatisticsManager` class to include methods for resetting statistics and improved logging for better debugging. - Refined the HTML generation in `StatisticsViewProvider` to ensure accurate display of statistics and improved formatting functions. - Overall, these changes aim to improve maintainability and usability of the codebase.
1 parent 22c0bed commit 10c9211

8 files changed

Lines changed: 582 additions & 107 deletions

File tree

src/ccpRunner.ts

Lines changed: 26 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,16 @@ import * as cp from 'child_process';
22
import * as path from 'path';
33
import * as vscode from 'vscode';
44

5+
/**
6+
* Executes the CCP Python script with the provided parameters
7+
* @param filePath - Path to the file being processed
8+
* @param noBackup - Whether to skip backup creation
9+
* @param force - Whether to force processing for unsupported file types
10+
* @param preserveTodo - Whether to keep TODO and FIXME comments
11+
* @param preservePatterns - Array of regex patterns for comments to preserve
12+
* @param keepDocComments - Whether to keep documentation comments
13+
* @returns Promise resolving with the Python script's output
14+
*/
515
export function runCcpScript(
616
filePath: string,
717
noBackup: boolean,
@@ -11,17 +21,14 @@ export function runCcpScript(
1121
keepDocComments: boolean = false
1222
): Promise<string> {
1323
return new Promise((resolve, reject) => {
14-
// Get path to the Python script, relative to extension directory
1524
const pythonScriptPath = path.join(__dirname, 'python', 'ccp.py');
1625

17-
// Check if Python script exists
1826
const fs = require('fs');
1927
if (!fs.existsSync(pythonScriptPath)) {
2028
reject(`Python script not found: ${pythonScriptPath}`);
2129
return;
2230
}
2331

24-
// Build command with proper arguments - use an array for better argument handling
2532
const pythonArgs = [
2633
pythonScriptPath,
2734
filePath,
@@ -47,11 +54,9 @@ export function runCcpScript(
4754
pythonArgs.push('--preserve-patterns', JSON.stringify(preservePatterns));
4855
}
4956

50-
// Log the full command for debugging
5157
console.log(`Executing: python ${pythonArgs.join(' ')}`);
5258
vscode.window.showInformationMessage(`Running: python with ${pythonScriptPath}`);
5359

54-
// Use spawn instead of exec for better output handling
5560
const pythonProcess = cp.spawn('python', pythonArgs);
5661

5762
let stdout = '';
@@ -76,7 +81,6 @@ export function runCcpScript(
7681
if (!stdout.trim() && !stderr.trim()) {
7782
console.log("Warning: Python script produced no output");
7883
}
79-
// Pass both stdout and stderr to resolve
8084
resolve(stdout + '\n' + stderr);
8185
}
8286
});
@@ -87,6 +91,16 @@ export function runCcpScript(
8791
});
8892
}
8993

94+
/**
95+
* High-level function to execute the comment cleaning process and parse results
96+
* @param filePath - Path to the file being processed
97+
* @param noBackup - Whether to skip backup creation
98+
* @param force - Whether to force processing for unsupported file types
99+
* @param preserveTodo - Whether to keep TODO and FIXME comments
100+
* @param preservePatterns - Array of regex patterns for comments to preserve
101+
* @param keepDocComments - Whether to keep documentation comments
102+
* @returns Promise resolving with parsed results object
103+
*/
90104
export async function executeCcp(
91105
filePath: string,
92106
noBackup: boolean,
@@ -96,7 +110,6 @@ export async function executeCcp(
96110
keepDocComments: boolean = false
97111
): Promise<any> {
98112
try {
99-
// Update the runCcpScript call to include the new parameters
100113
const output = await runCcpScript(
101114
filePath,
102115
noBackup,
@@ -107,7 +120,6 @@ export async function executeCcp(
107120
);
108121
console.log("Python script output:", output);
109122

110-
// Always use parseCleanResults now, no dry run option
111123
const results = parseCleanResults(output, filePath);
112124
return results;
113125
} catch (error) {
@@ -116,7 +128,12 @@ export async function executeCcp(
116128
}
117129
}
118130

119-
// Make sure this function exists and works correctly
131+
/**
132+
* Parses the output from the Python script to extract cleaning statistics
133+
* @param output - Raw output string from Python script
134+
* @param filePath - Path to the processed file
135+
* @returns Object containing parsed cleaning statistics
136+
*/
120137
function parseCleanResults(output: string, filePath: string): any {
121138
const results: any = {
122139
fileName: path.basename(filePath),
@@ -127,10 +144,8 @@ function parseCleanResults(output: string, filePath: string): any {
127144
sizePercentage: 0
128145
};
129146

130-
// Log the output for debugging
131147
console.log("Raw Python output to parse:", output);
132148

133-
// Updated regex patterns with more flexible whitespace matching
134149
const commentMatch = output.match(/Removed\s+approximately\s+(\d+)\s+comments?\s*\((\d+)\s+lines?\)/i) ||
135150
output.match(/Removed.*?(\d+).*?comment.*?\((\d+).*?line/i);
136151

src/ccpViewProvider.ts

Lines changed: 72 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2,25 +2,46 @@ import * as vscode from 'vscode';
22
import * as path from 'path';
33
import { executeCcp } from './ccpRunner';
44

5+
/**
6+
* Tree view provider for file operations in the sidebar
7+
* Provides actions for cleaning individual and multiple files
8+
*/
59
export class FilesViewProvider implements vscode.TreeDataProvider<FileItem> {
610
private _onDidChangeTreeData: vscode.EventEmitter<FileItem | undefined | null | void> = new vscode.EventEmitter<FileItem | undefined | null | void>();
711
readonly onDidChangeTreeData: vscode.Event<FileItem | undefined | null | void> = this._onDidChangeTreeData.event;
812

913
private _languageFilter: string | undefined;
1014

15+
/**
16+
* Refreshes the tree view
17+
*/
1118
refresh(): void {
1219
this._onDidChangeTreeData.fire();
1320
}
1421

22+
/**
23+
* Sets a language filter for the tree view
24+
* @param language - Language identifier to filter by, or undefined to clear filter
25+
*/
1526
setLanguageFilter(language: string | undefined) {
1627
this._languageFilter = language;
1728
this._onDidChangeTreeData.fire();
1829
}
1930

31+
/**
32+
* Returns the tree item for a given element
33+
* @param element - The item to display
34+
* @returns The tree item for display
35+
*/
2036
getTreeItem(element: FileItem): vscode.TreeItem {
2137
return element;
2238
}
2339

40+
/**
41+
* Gets child items for a tree element
42+
* @param element - Parent element, or undefined for root
43+
* @returns Promise resolving with child items
44+
*/
2445
getChildren(element?: FileItem): Thenable<FileItem[]> {
2546
if (element) {
2647
return Promise.resolve([]);
@@ -38,7 +59,7 @@ export class FilesViewProvider implements vscode.TreeDataProvider<FileItem> {
3859
title: 'Clean Current File'
3960
},
4061
undefined,
41-
true // Mark as button
62+
true
4263
);
4364
cleanCurrentItem.iconPath = new vscode.ThemeIcon('trash');
4465

@@ -50,7 +71,7 @@ export class FilesViewProvider implements vscode.TreeDataProvider<FileItem> {
5071
title: 'Clean Multiple Files'
5172
},
5273
undefined,
53-
true // Mark as button
74+
true
5475
);
5576
cleanMultipleItem.iconPath = new vscode.ThemeIcon('files');
5677

@@ -59,29 +80,42 @@ export class FilesViewProvider implements vscode.TreeDataProvider<FileItem> {
5980
}
6081
}
6182

83+
/**
84+
* Tree view provider for processed file history
85+
* Maintains a list of previously cleaned files and provides filtering capabilities
86+
*/
6287
export class HistoryViewProvider implements vscode.TreeDataProvider<FileItem> {
6388
private _onDidChangeTreeData: vscode.EventEmitter<FileItem | undefined | null | void> = new vscode.EventEmitter<FileItem | undefined | null | void>();
6489
readonly onDidChangeTreeData: vscode.Event<FileItem | undefined | null | void> = this._onDidChangeTreeData.event;
6590
private history: string[] = [];
66-
67-
// Add this property
6891
private _languageFilter: string | undefined;
6992

7093
constructor() {
7194
this.history = [];
7295
}
7396

97+
/**
98+
* Refreshes the history view
99+
*/
74100
refresh(): void {
75101
this._onDidChangeTreeData.fire();
76102
}
77103

104+
/**
105+
* Adds a file to the history
106+
* @param filePath - Path of file to add to history
107+
*/
78108
addToHistory(filePath: string): void {
79109
if (!this.history.includes(filePath)) {
80110
this.history.unshift(filePath);
81111
}
82112
this.refresh();
83113
}
84114

115+
/**
116+
* Removes a file from the history
117+
* @param filePath - Path of file to remove from history
118+
*/
85119
removeFromHistory(filePath: string): void {
86120
const index = this.history.indexOf(filePath);
87121
if (index !== -1) {
@@ -90,21 +124,37 @@ export class HistoryViewProvider implements vscode.TreeDataProvider<FileItem> {
90124
}
91125
}
92126

93-
// Add this method
127+
/**
128+
* Sets a language filter for the history view
129+
* @param language - Language identifier to filter by, or undefined to clear filter
130+
*/
94131
setLanguageFilter(language: string | undefined) {
95132
this._languageFilter = language;
96133
this.refresh();
97134
}
98135

136+
/**
137+
* Clears the entire history
138+
*/
99139
clearHistory(): void {
100140
this.history = [];
101141
this.refresh();
102142
}
103143

144+
/**
145+
* Returns the tree item for a given element
146+
* @param element - The item to display
147+
* @returns The tree item for display
148+
*/
104149
getTreeItem(element: FileItem): vscode.TreeItem {
105150
return element;
106151
}
107152

153+
/**
154+
* Gets child items for a tree element
155+
* @param element - Parent element, or undefined for root
156+
* @returns Promise resolving with child items
157+
*/
108158
getChildren(element?: FileItem): Thenable<FileItem[]> {
109159
if (element) {
110160
return Promise.resolve([]);
@@ -115,10 +165,8 @@ export class HistoryViewProvider implements vscode.TreeDataProvider<FileItem> {
115165
]);
116166
}
117167

118-
// Add the filter option as the first item
119168
const items: FileItem[] = [];
120169

121-
// Add filter option at top
122170
const filterItem = new FileItem(
123171
'Filter by Language',
124172
vscode.TreeItemCollapsibleState.None,
@@ -127,27 +175,21 @@ export class HistoryViewProvider implements vscode.TreeDataProvider<FileItem> {
127175
title: 'Filter by Language'
128176
},
129177
undefined,
130-
true // Mark as button
178+
true
131179
);
132-
// Add these lines to make the filter item correctly appear as a button
133180
filterItem.iconPath = new vscode.ThemeIcon('filter');
134181
filterItem.contextValue = 'buttonItem';
135-
// Add this line to apply CSS classes
136182
filterItem.tooltip = 'Filter history by programming language';
137-
// This is important to make VS Code apply custom styling
138183
filterItem.description = '';
139184
items.push(filterItem);
140185

141-
// Filter history items by language if filter is active
142186
const filteredHistory = this._languageFilter
143187
? this.history.filter(file => {
144188
const ext = path.extname(file).toLowerCase();
145-
// Map extension to language and check if it matches filter
146189
return identifyLanguage(ext) === this._languageFilter;
147190
})
148191
: this.history;
149192

150-
// Add filtered history items
151193
filteredHistory.forEach(file => {
152194
const filename = path.basename(file);
153195
const item = new FileItem(
@@ -160,7 +202,6 @@ export class HistoryViewProvider implements vscode.TreeDataProvider<FileItem> {
160202
},
161203
file
162204
);
163-
// Add this line:
164205
item.contextValue = 'historyItem';
165206
items.push(item);
166207
});
@@ -170,7 +211,18 @@ export class HistoryViewProvider implements vscode.TreeDataProvider<FileItem> {
170211
}
171212
}
172213

214+
/**
215+
* Tree item representing a file or action in the sidepanel views
216+
*/
173217
class FileItem extends vscode.TreeItem {
218+
/**
219+
* Creates a new file item
220+
* @param label - Display name of the item
221+
* @param collapsibleState - Whether item can be expanded
222+
* @param command - Command to execute when item is clicked
223+
* @param filePath - Path to the file (for history items)
224+
* @param isButton - Whether this item represents an action button
225+
*/
174226
constructor(
175227
public readonly label: string,
176228
public readonly collapsibleState: vscode.TreeItemCollapsibleState,
@@ -182,14 +234,12 @@ class FileItem extends vscode.TreeItem {
182234
this.tooltip = filePath || label;
183235

184236
if (isButton) {
185-
// Make items look like buttons
186237
this.description = "";
187238
this.tooltip = command?.title || label;
188239
} else {
189240
this.description = filePath ? path.dirname(filePath) : '';
190241
}
191242

192-
// Set appropriate icon based on action type
193243
if (label === 'Clean Current File') {
194244
this.iconPath = new vscode.ThemeIcon('trash');
195245
this.contextValue = 'buttonItem';
@@ -209,7 +259,6 @@ class FileItem extends vscode.TreeItem {
209259
this.iconPath = new vscode.ThemeIcon('trash');
210260
this.contextValue = 'buttonItem';
211261
} else {
212-
// For file entries in history
213262
if (filePath) {
214263
this.iconPath = vscode.ThemeIcon.File;
215264
this.contextValue = 'historyItem';
@@ -218,7 +267,11 @@ class FileItem extends vscode.TreeItem {
218267
}
219268
}
220269

221-
// Helper function to map extensions to languages
270+
/**
271+
* Maps file extensions to programming language identifiers
272+
* @param extension - File extension including dot (e.g. ".js")
273+
* @returns Language identifier string
274+
*/
222275
function identifyLanguage(extension: string): string {
223276
const extensionMap: {[key: string]: string} = {
224277
'.py': 'python',

0 commit comments

Comments
 (0)