-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_output.txt
More file actions
362 lines (307 loc) · 16.2 KB
/
example_output.txt
File metadata and controls
362 lines (307 loc) · 16.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
--- PROJECT TREE ---
.
+-- .resources
| +-- run.png
| L-- UI.png
+-- ExportCodebase.ps1
+-- file-sets.txt
L-- readme.md
---------
ExportCodebase.ps1
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
# Configuration
$targetDirectory = $PSScriptRoot
$fileSetsPath = Join-Path -Path $targetDirectory -ChildPath "file-sets.txt"
# Base Excluded Folders (will be combined with .gitignore)
$baseExclude = @(
'__pycache__', 'venv', 'tts_cache', 'XTTS-v2', 'node_modules',
'.git', 'audio_previews', '.vscode', '.idea', '.gradle', '.kotlin'
)
# A script-level flag to prevent recursive events when programmatically checking boxes
$script:isUpdatingChecks = $false
#region Helper Functions
function Get-SafeFileContent {
[CmdletBinding()]
param ([Parameter(Mandatory = $true)][string]$FilePath)
try { return Get-Content -Path $FilePath -Raw -ErrorAction Stop }
catch {
Write-Warning "Error reading file '$FilePath': $($_.Exception.Message)"
return "ERROR READING FILE: $($_.Exception.Message)"
}
}
function Get-FileSet {
[CmdletBinding()]
param ([Parameter(Mandatory = $true)][string]$FilePath)
$fileSets = [ordered]@{}
if (Test-Path -Path $FilePath) {
$lines = Get-Content -Path $FilePath
$currentSetName = $null
foreach ($line in $lines) {
if ($line.StartsWith("[")) {
$currentSetName = $line.Trim("[]")
$fileSets[$currentSetName] = @()
}
elseif ($currentSetName -and $line.Trim() -ne "") {
$fileSets[$currentSetName] += $line.Trim()
}
}
}
return $fileSets
}
function Set-FileSet {
[CmdletBinding()]
param ([Parameter(Mandatory = $true)][string]$FilePath, [Parameter(Mandatory = $true)][hashtable]$FileSets)
$content = ""
foreach ($setName in $FileSets.Keys) {
$content += "[$setName]`r`n"
$FileSets[$setName] | ForEach-Object { $content += "$_`r`n" }
$content += "`r`n"
}
$content | Out-File -FilePath $FilePath -Encoding utf8
}
# Function to get a combined exclusion list from base list and .gitignore
function Get-ExclusionList {
param (
[string]$RootPath,
[string[]]$BaseExclusions
)
$combinedExclusions = [System.Collections.Generic.List[string]]::new()
$combinedExclusions.AddRange($BaseExclusions)
$gitignorePath = Join-Path -Path $RootPath -ChildPath ".gitignore"
if (Test-Path -Path $gitignorePath) {
try {
$gitignorePatterns = [string[]](Get-Content -Path $gitignorePath -ErrorAction Stop | ForEach-Object {
$line = $_.Trim()
if ($line -and !$line.StartsWith("#")) {
$line.TrimStart("/").TrimEnd("/")
}
} | Where-Object { $_ })
if ($gitignorePatterns) {
$combinedExclusions.AddRange($gitignorePatterns)
}
} catch {
Write-Warning "Could not read .gitignore file at '$gitignorePath': $($_.Exception.Message)"
}
}
return $combinedExclusions | Select-Object -Unique
}
#endregion
#region TreeView Functions
function Add-TreeViewNodes {
param($nodes, $path, $rootPath, [string[]]$exclusionList)
# Use the passed exclusion list
Get-ChildItem -Path $path -Directory | Where-Object { $exclusionList -notcontains $_.Name } | ForEach-Object {
$dirNode = New-Object System.Windows.Forms.TreeNode($_.Name); $dirNode.Tag = $_.FullName; $nodes.Add($dirNode)
Add-TreeViewNodes -nodes $dirNode.Nodes -path $_.FullName -rootPath $rootPath -exclusionList $exclusionList
}
Get-ChildItem -Path $path -File | Where-Object { $exclusionList -notcontains $_.Name } | ForEach-Object {
$fileNode = New-Object System.Windows.Forms.TreeNode($_.Name)
$fileNode.Tag = $_.FullName -ireplace [regex]::Escape($rootPath), ""
$nodes.Add($fileNode)
}
}
function Get-CheckedNodes {
param([Parameter(Mandatory=$true)]$nodes)
$checkedFiles = [System.Collections.Generic.List[string]]::new()
foreach ($node in $nodes) {
if ($node.Checked -and $node.Nodes.Count -eq 0) { $checkedFiles.Add($node.Tag) }
if ($node.Nodes.Count -gt 0) {
$childResults = [string[]](Get-CheckedNodes -nodes $node.Nodes)
if ($null -ne $childResults -and $childResults.Count -gt 0) { $checkedFiles.AddRange($childResults) }
}
}
return $checkedFiles
}
function Update-TreeViewChecks {
param ($nodes, [string[]]$filesToCheck)
foreach ($node in $nodes) {
if ($node.Nodes.Count -eq 0) { $node.Checked = $filesToCheck -contains $node.Tag }
if ($node.Nodes.Count -gt 0) { Update-TreeViewChecks -nodes $node.Nodes -filesToCheck $filesToCheck }
}
}
function Set-ChildNodeChecks {
param ($node, [bool]$isChecked)
foreach ($childNode in $node.Nodes) {
$childNode.Checked = $isChecked
if ($childNode.Nodes.Count -gt 0) { Set-ChildNodeChecks -node $childNode -isChecked $isChecked }
}
}
function Find-NodeByTag {
param(
[Parameter(Mandatory=$true)] $nodes,
[Parameter(Mandatory=$true)] [string]$tagToFind
)
foreach ($node in $nodes) {
if ($node.Tag -eq $tagToFind) { return $node }
if ($node.Nodes.Count -gt 0) {
$found = Find-NodeByTag -nodes $node.Nodes -tagToFind $tagToFind
if ($null -ne $found) { return $found }
}
}
return $null
}
# Function to generate a text-based tree from TreeView nodes
function Get-TextTree {
param (
[Parameter(Mandatory=$true)]
[System.Windows.Forms.TreeNodeCollection]$nodes,
[string]$indent = ""
)
$nodeCount = $nodes.Count
for ($i = 0; $i -lt $nodeCount; $i++) {
$node = $nodes[$i]
$isLast = ($i -eq ($nodeCount - 1))
$marker = ""
$childIndent = ""
if ($isLast) {
$marker = "L-- "
$childIndent = $indent + " "
} else {
$marker = "+-- "
$childIndent = $indent + "| "
}
"$indent$marker$($node.Text)"
if ($node.Nodes.Count -gt 0) {
Get-TextTree -nodes $node.Nodes -indent $childIndent
}
}
}
#endregion
# Main Script
$finalExcludeList = Get-ExclusionList -RootPath $targetDirectory -BaseExclusions $baseExclude
$fileSets = Get-FileSet -FilePath $fileSetsPath
$normalizedTargetDirectory = ($targetDirectory -replace '[\\/]$') + [System.IO.Path]::DirectorySeparatorChar
# --- UI Creation ---
$form = New-Object System.Windows.Forms.Form; $form.Text = "File and Folder Selection"; $form.Size = New-Object System.Drawing.Size(600, 700); $form.StartPosition = "CenterScreen"; $form.MinimumSize = New-Object System.Drawing.Size(450, 400)
$treeView = New-Object System.Windows.Forms.TreeView; $treeView.Location = New-Object System.Drawing.Point(20, 80); $treeView.Size = New-Object System.Drawing.Size(540, 450); $treeView.CheckBoxes = $true; $treeView.Anchor = 'Top, Bottom, Left, Right'; $form.Controls.Add($treeView)
$fileSetComboBox = New-Object System.Windows.Forms.ComboBox; $fileSetComboBox.Location = New-Object System.Drawing.Point(20, 20); $fileSetComboBox.Size = New-Object System.Drawing.Size(200, 20); $fileSetComboBox.DropDownStyle = "DropDownList"; $fileSetComboBox.Items.AddRange($fileSets.Keys); $form.Controls.Add($fileSetComboBox)
$loadFileSetButton = New-Object System.Windows.Forms.Button;$loadFileSetButton.Location = New-Object System.Drawing.Point(230, 20);$loadFileSetButton.Size = New-Object System.Drawing.Size(100, 23);$loadFileSetButton.Text = "Load Set";$form.Controls.Add($loadFileSetButton)
$fileSetNameTextBox = New-Object System.Windows.Forms.TextBox;$fileSetNameTextBox.Location = New-Object System.Drawing.Point(20, 50);$fileSetNameTextBox.Size = New-Object System.Drawing.Size(200, 20);$form.Controls.Add($fileSetNameTextBox)
$saveFileSetButton = New-Object System.Windows.Forms.Button;$saveFileSetButton.Location = New-Object System.Drawing.Point(230, 50);$saveFileSetButton.Size = New-Object System.Drawing.Size(100, 23);$saveFileSetButton.Text = "Save Set";$form.Controls.Add($saveFileSetButton)
$submitButton = New-Object System.Windows.Forms.Button;$submitButton.Location = New-Object System.Drawing.Point(20, 550);$submitButton.Size = New-Object System.Drawing.Size(100, 30);$submitButton.Text = "Export";$submitButton.Anchor = 'Bottom, Left';$form.Controls.Add($submitButton)
$statusLabel = New-Object System.Windows.Forms.Label;$statusLabel.Location = New-Object System.Drawing.Point(20, 585);$statusLabel.Size = New-Object System.Drawing.Size(540, 20);$statusLabel.Anchor = 'Bottom, Left';$form.Controls.Add($statusLabel)
# Checkbox for adding the project tree
$addTreeViewCheckbox = New-Object System.Windows.Forms.CheckBox; $addTreeViewCheckbox.Location = New-Object System.Drawing.Point(130, 555); $addTreeViewCheckbox.Size = New-Object System.Drawing.Size(200, 23); $addTreeViewCheckbox.Text = "Add project tree to output"; $addTreeViewCheckbox.Checked = $true; $addTreeViewCheckbox.Anchor = 'Bottom, Left'; $form.Controls.Add($addTreeViewCheckbox)
$statusLabel.Text = "Loading file tree (respecting .gitignore)..."; $form.Update()
# Pass the final exclusion list to the population function
Add-TreeViewNodes -nodes $treeView.Nodes -path $targetDirectory -rootPath $normalizedTargetDirectory -exclusionList $finalExcludeList
$statusLabel.Text = "Ready. Select files or load a set."
# Event Handlers
$treeView.Add_AfterCheck({param($s, $e)
if ($script:isUpdatingChecks) { return }
$script:isUpdatingChecks = $true
if ($e.Node.Nodes.Count -gt 0) { Set-ChildNodeChecks -node $e.Node -isChecked $e.Node.Checked }
$script:isUpdatingChecks = $false
})
$loadFileSetButton.Add_Click({
$selectedSetName = $fileSetComboBox.SelectedItem
if ($selectedSetName) {
$filesToLoad = @($fileSets[$selectedSetName])
$script:isUpdatingChecks = $true
Update-TreeViewChecks -nodes $treeView.Nodes -filesToCheck $filesToLoad
$script:isUpdatingChecks = $false
$treeView.BeginUpdate()
try {
$firstNodeFound = $null
foreach ($file in $filesToLoad) {
$fileNode = Find-NodeByTag -nodes $treeView.Nodes -tagToFind $file
if ($null -ne $fileNode) {
if ($null -eq $firstNodeFound) { $firstNodeFound = $fileNode }
$parentNode = $fileNode.Parent
while ($null -ne $parentNode) {
$parentNode.Expand()
$parentNode = $parentNode.Parent
}
}
}
if ($null -ne $firstNodeFound) { $firstNodeFound.EnsureVisible() }
} finally { $treeView.EndUpdate() }
$statusLabel.Text = "Loaded set '$selectedSetName'."
}
})
$saveFileSetButton.Add_Click({
$setName = $fileSetNameTextBox.Text.Trim()
if ($setName) {
$selectedFiles = Get-CheckedNodes -nodes $treeView.Nodes
$fileSets[$setName] = $selectedFiles
Set-FileSet -FilePath $fileSetsPath -FileSets $fileSets
$fileSetComboBox.Items.Clear(); $fileSetComboBox.Items.AddRange($fileSets.Keys); $fileSetComboBox.SelectedItem = $setName
$statusLabel.Text = "File Set '$setName' Saved."
} else { $statusLabel.Text = "Enter a File Set Name." }
})
$submitButton.Add_Click({
$selectedRelativePaths = Get-CheckedNodes -nodes $treeView.Nodes
if ($selectedRelativePaths.Count -eq 0) { $statusLabel.Text = "No files were selected."; return }
$saveFileDialog = New-Object System.Windows.Forms.SaveFileDialog; $saveFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*"; $saveFileDialog.Title = "Save Combined File Contents"; $saveFileDialog.FileName = "combined_output.txt"
if ($saveFileDialog.ShowDialog() -eq "OK") {
$outputFilePath = $saveFileDialog.FileName
$statusLabel.Text = "Processing..."; $form.Update()
$outputLines = [System.Collections.Generic.List[string]]::new()
if ($addTreeViewCheckbox.Checked) {
$outputLines.Add("--- PROJECT TREE ---")
$outputLines.Add(".")
$treeBodyLines = [string[]](Get-TextTree -nodes $treeView.Nodes)
if ($treeBodyLines) {
$outputLines.AddRange($treeBodyLines)
}
$outputLines.Add("")
}
foreach ($relativePath in $selectedRelativePaths) {
$fullPath = Join-Path -Path $targetDirectory -ChildPath $relativePath
$outputLines.Add("---------"); $outputLines.Add($relativePath); $outputLines.Add((Get-SafeFileContent -FilePath $fullPath))
}
[System.IO.File]::WriteAllLines($outputFilePath, $outputLines)
$statusLabel.Text = "Output saved to: $outputFilePath"
} else { $statusLabel.Text = "Operation cancelled." }
})
[void]$form.ShowDialog()
---------
file-sets.txt
[Text Files]
ExportCodebase.ps1
file-sets.txt
[All Files]
.resources\run.png
.resources\UI.png
ExportCodebase.ps1
file-sets.txt
---------
readme.md
# PowerShell Codebase Exporter
A PowerShell script with a graphical user interface (GUI) designed to select files and folders from a project and combine them into a single text file. Its primary purpose is to create a well-formatted codebase export for use with AI assistants.
## Features
- Graphical file and folder selection via a tree view.
- Save and load common file selections as "File Sets".
- Automatic exclusion of files and folders listed in the project's `.gitignore` file.
- A configurable list for manual exclusions directly within the script.
- Optionally prepends a project structure tree to the output file.
- Combines selected files into a single, clearly delimited text file.
## Setup
Place the `ExportCodebase.ps1` script into the root directory of the project you wish to export files from. I usually name it `zExportCodebase.ps1` so that I can always find it at the bottom of my file list in VS Code.
## How to Use
1. Run the `ExportCodebase.ps1` script.
2. The GUI will appear, displaying your project's file tree.
3. Check the boxes next to the files and folders you want to include in the export.
4. Optionally, save your current selection as a "File Set" for future use.
5. Choose whether to include the project tree in the output.
6. Click the "Export" button and choose a location to save the combined `.txt` file.
## UI Overview

1. **Load File Set**: Select a previously saved set from this dropdown menu and click the "Load Set" button. The tree view will automatically check all the files associated with that set.
2. **Save File Set**: After checking the desired files in the tree, enter a name in the text field and click the "Save Set" button. This selection will be saved into `file-sets.txt` for later use.
3. **Add project tree to output**: If checked, a text-based representation of your project's complete file and folder structure (respecting all exclusions) will be added to the top of the exported file. This tree of the project really seems helpful to the AI.
4. **Export**: After selecting your files, click this button to open a save dialog. The script will then generate a single `.txt` file containing the contents of all selected files. Each file's content is preceded by a divider and its relative path. For AI Studio I open the exported file, select all, copy and paste into chat. For OpenWebUI and OpenRouter I drop in the text file.
## File Descriptions
- **`ExportCodebase.ps1`**: The main executable PowerShell script.
- **`file-sets.txt`**: A plain text file that stores the saved file sets. This file will be created if you save a file set.
## Running the Script
The script can be run from any PowerShell terminal. Navigate to your project's root directory and execute the script:
```powershell
.\ExportCodebase.ps1
```
Alternatively, I use the [Run in Powershell](https://marketplace.visualstudio.com/items?itemName=tobysmith568.run-in-powershell) extension in VS Code.

### Customization
You can manually add folder or file names to a base exclusion list. This is useful for project-specific tooling or build directories that aren't in `.gitignore`.
To do this, open `ExportCodebase.ps1` and add the desired folder/file names to the `$baseExclude` array near the top of the file.