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
|
package semantic
import (
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"sync"
"time"
)
// ProjectManager manages project context and boundaries
type ProjectManager struct {
rootPath string
config *ProjectConfig
languageFiles map[string][]string // language -> file_paths
excludeRules []string
mu sync.RWMutex
}
// FileInfo represents information about a file
type FileInfo struct {
Path string
Size int64
ModTime time.Time
IsDir bool
}
// NewProjectManager creates a new project manager
func NewProjectManager() *ProjectManager {
return &ProjectManager{
languageFiles: make(map[string][]string),
excludeRules: []string{
"**/node_modules/**",
"**/vendor/**",
"**/.git/**",
"**/target/**",
"**/dist/**",
"**/build/**",
"**/*.min.js",
"**/*.min.css",
},
}
}
// DiscoverProject initializes project discovery from a root path
func (pm *ProjectManager) DiscoverProject(rootPath string) error {
pm.mu.Lock()
defer pm.mu.Unlock()
absPath, err := filepath.Abs(rootPath)
if err != nil {
return fmt.Errorf("failed to get absolute path: %w", err)
}
pm.rootPath = absPath
// Initialize project config
pm.config = &ProjectConfig{
Name: filepath.Base(absPath),
RootPath: absPath,
Languages: []string{},
ExcludePatterns: pm.excludeRules,
IncludePatterns: []string{"**/*"},
CustomSettings: make(map[string]string),
}
// Scan for files and detect languages
if err := pm.scanProject(); err != nil {
return fmt.Errorf("failed to scan project: %w", err)
}
return nil
}
// scanProject scans the project and categorizes files by language
func (pm *ProjectManager) scanProject() error {
pm.languageFiles = make(map[string][]string)
err := filepath.WalkDir(pm.rootPath, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return nil // Continue on errors
}
// Skip excluded paths
if pm.shouldExclude(path) {
if d.IsDir() {
return filepath.SkipDir
}
return nil
}
// Only process files
if d.IsDir() {
return nil
}
// Detect language and add to appropriate list
language := pm.detectLanguage(path)
if language != "" {
pm.languageFiles[language] = append(pm.languageFiles[language], path)
// Add to supported languages if not already present
found := false
for _, lang := range pm.config.Languages {
if lang == language {
found = true
break
}
}
if !found {
pm.config.Languages = append(pm.config.Languages, language)
}
}
return nil
})
return err
}
// shouldExclude checks if a path should be excluded based on patterns
func (pm *ProjectManager) shouldExclude(path string) bool {
relPath, err := filepath.Rel(pm.rootPath, path)
if err != nil {
return true
}
for _, pattern := range pm.excludeRules {
if matched, _ := filepath.Match(pattern, relPath); matched {
return true
}
// Handle ** patterns manually
if strings.Contains(pattern, "**") {
pattern = strings.ReplaceAll(pattern, "**", "*")
if matched, _ := filepath.Match(pattern, relPath); matched {
return true
}
}
// Check if any parent directory matches
parts := strings.Split(relPath, string(filepath.Separator))
for i := range parts {
partialPath := strings.Join(parts[:i+1], string(filepath.Separator))
if matched, _ := filepath.Match(pattern, partialPath); matched {
return true
}
}
}
return false
}
// detectLanguage detects the programming language from file extension
func (pm *ProjectManager) detectLanguage(filePath string) string {
ext := strings.ToLower(filepath.Ext(filePath))
for language, config := range DefaultLanguageServers {
for _, supportedExt := range config.FileExts {
if ext == supportedExt {
return language
}
}
}
return ""
}
// GetSupportedLanguages returns list of detected languages in the project
func (pm *ProjectManager) GetSupportedLanguages() []string {
pm.mu.RLock()
defer pm.mu.RUnlock()
if pm.config == nil {
return []string{}
}
return pm.config.Languages
}
// GetFilesByLanguage returns all files for a specific language
func (pm *ProjectManager) GetFilesByLanguage(language string) []string {
pm.mu.RLock()
defer pm.mu.RUnlock()
files, exists := pm.languageFiles[language]
if !exists {
return []string{}
}
// Return a copy to avoid race conditions
result := make([]string, len(files))
copy(result, files)
return result
}
// GetFilesInDirectory returns all supported files in a directory
func (pm *ProjectManager) GetFilesInDirectory(dirPath string) []string {
pm.mu.RLock()
defer pm.mu.RUnlock()
var files []string
// Convert to absolute path if relative
if !filepath.IsAbs(dirPath) {
dirPath = filepath.Join(pm.rootPath, dirPath)
}
// Walk the directory
filepath.WalkDir(dirPath, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return nil
}
if d.IsDir() {
return nil
}
// Check if file is supported
if pm.detectLanguage(path) != "" && !pm.shouldExclude(path) {
files = append(files, path)
}
return nil
})
return files
}
// IsFileInProject checks if a file is within project boundaries
func (pm *ProjectManager) IsFileInProject(filePath string) bool {
pm.mu.RLock()
defer pm.mu.RUnlock()
if pm.rootPath == "" {
return false
}
absPath, err := filepath.Abs(filePath)
if err != nil {
return false
}
// Check if file is under project root
relPath, err := filepath.Rel(pm.rootPath, absPath)
if err != nil || strings.HasPrefix(relPath, "..") {
return false
}
// Check if file should be excluded
return !pm.shouldExclude(absPath)
}
// ReadFile reads the contents of a file
func (pm *ProjectManager) ReadFile(filePath string) ([]byte, error) {
if !pm.IsFileInProject(filePath) {
return nil, fmt.Errorf("file is outside project boundaries: %s", filePath)
}
return os.ReadFile(filePath)
}
// GetFileInfo gets information about a file
func (pm *ProjectManager) GetFileInfo(filePath string) (*FileInfo, error) {
if !pm.IsFileInProject(filePath) {
return nil, fmt.Errorf("file is outside project boundaries: %s", filePath)
}
stat, err := os.Stat(filePath)
if err != nil {
return nil, fmt.Errorf("failed to stat file: %w", err)
}
return &FileInfo{
Path: filePath,
Size: stat.Size(),
ModTime: stat.ModTime(),
IsDir: stat.IsDir(),
}, nil
}
// GetProjectStats returns statistics about the project
func (pm *ProjectManager) GetProjectStats() map[string]interface{} {
pm.mu.RLock()
defer pm.mu.RUnlock()
stats := make(map[string]interface{})
if pm.config != nil {
stats["name"] = pm.config.Name
stats["root_path"] = pm.config.RootPath
stats["languages"] = pm.config.Languages
}
stats["files_by_language"] = make(map[string]int)
totalFiles := 0
for language, files := range pm.languageFiles {
count := len(files)
stats["files_by_language"].(map[string]int)[language] = count
totalFiles += count
}
stats["total_files"] = totalFiles
return stats
}
// GetRootPath returns the project root path
func (pm *ProjectManager) GetRootPath() string {
pm.mu.RLock()
defer pm.mu.RUnlock()
return pm.rootPath
}
// GetConfig returns the project configuration
func (pm *ProjectManager) GetConfig() *ProjectConfig {
pm.mu.RLock()
defer pm.mu.RUnlock()
if pm.config == nil {
return nil
}
// Return a copy
config := *pm.config
config.Languages = make([]string, len(pm.config.Languages))
copy(config.Languages, pm.config.Languages)
config.ExcludePatterns = make([]string, len(pm.config.ExcludePatterns))
copy(config.ExcludePatterns, pm.config.ExcludePatterns)
config.IncludePatterns = make([]string, len(pm.config.IncludePatterns))
copy(config.IncludePatterns, pm.config.IncludePatterns)
config.CustomSettings = make(map[string]string)
for k, v := range pm.config.CustomSettings {
config.CustomSettings[k] = v
}
return &config
}
// SetExcludePatterns sets custom exclude patterns
func (pm *ProjectManager) SetExcludePatterns(patterns []string) {
pm.mu.Lock()
defer pm.mu.Unlock()
pm.excludeRules = patterns
if pm.config != nil {
pm.config.ExcludePatterns = patterns
}
// Re-scan project with new patterns
if pm.rootPath != "" {
pm.scanProject()
}
}
// AddExcludePattern adds a new exclude pattern
func (pm *ProjectManager) AddExcludePattern(pattern string) {
pm.mu.Lock()
defer pm.mu.Unlock()
pm.excludeRules = append(pm.excludeRules, pattern)
if pm.config != nil {
pm.config.ExcludePatterns = append(pm.config.ExcludePatterns, pattern)
}
}
// Shutdown gracefully shuts down the project manager
func (pm *ProjectManager) Shutdown() error {
pm.mu.Lock()
defer pm.mu.Unlock()
// Clear all data
pm.languageFiles = make(map[string][]string)
pm.config = nil
pm.rootPath = ""
return nil
}
|