-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathwindowsSpecific.go
More file actions
1637 lines (1394 loc) · 41.1 KB
/
windowsSpecific.go
File metadata and controls
1637 lines (1394 loc) · 41.1 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
//go:build windows
package shuffle
import (
"strings"
"runtime"
"encoding/json"
"log"
"os"
"bytes"
"time"
"context"
"io"
"errors"
"fmt"
"regexp"
"path/filepath"
"bufio"
"io/fs"
"unsafe" // for pointer control. Not ideal, but ok
"syscall"
"os/exec"
"golang.org/x/sys/windows"
"golang.org/x/sys/windows/registry"
)
func scanRegistryUninstall() []Software {
roots := []struct {
key registry.Key
path string
flag uint32
source string
}{
{registry.LOCAL_MACHINE, `Software\Microsoft\Windows\CurrentVersion\Uninstall`, registry.WOW64_64KEY, "registry-lm-64"},
{registry.LOCAL_MACHINE, `Software\Microsoft\Windows\CurrentVersion\Uninstall`, registry.WOW64_32KEY, "registry-lm-32"},
{registry.CURRENT_USER, `Software\Microsoft\Windows\CurrentVersion\Uninstall`, 0, "registry-cu"},
}
var out []Software
for _, r := range roots {
k, err := registry.OpenKey(r.key, r.path, registry.READ|r.flag)
if err != nil {
continue
}
defer k.Close()
names, _ := k.ReadSubKeyNames(-1)
for _, n := range names {
sk, err := registry.OpenKey(k, n, registry.READ|r.flag)
if err != nil {
continue
}
name, _, _ := sk.GetStringValue("DisplayName")
version, _, _ := sk.GetStringValue("DisplayVersion")
path, _, _ := sk.GetStringValue("InstallLocation")
sk.Close()
if name == "" {
continue
}
out = append(out, Software{
Name: name,
Version: version,
Path: path,
Source: r.source,
})
}
}
return out
}
// Infrastructure package prefixes to drop.
// These are runtime components, not user-installed apps.
var appxSkipPrefixes = []string{
"Microsoft.NET.",
"Microsoft.VCLibs.",
"Microsoft.VCRedist.",
"Microsoft.UI.",
"Microsoft.Windows.",
"Microsoft.Xbox",
"Microsoft.Advertising.",
"Microsoft.Services.",
"Windows.",
"MicrosoftCorporationII.",
}
func scanAppx() []Software {
cmd := `Get-AppxPackage | Select Name, Version | ConvertTo-Json -Compress`
out, err := exec.Command("powershell", "-NoProfile", "-Command", cmd).Output()
if err != nil || len(out) == 0 {
return nil
}
type pkg struct {
Name string
Version string
}
// ConvertTo-Json emits a bare object (not array) when there's exactly
// one result. Try array first, fall back to single object.
var packages []pkg
if err := json.Unmarshal(out, &packages); err != nil {
var single pkg
if err2 := json.Unmarshal(out, &single); err2 != nil {
return nil
}
packages = []pkg{single}
}
var res []Software
for _, p := range packages {
if isInfraAppx(p.Name) {
continue
}
res = append(res, Software{
Name: p.Name,
Version: p.Version,
Source: "appx",
})
}
return res
}
func isInfraAppx(name string) bool {
for _, prefix := range appxSkipPrefixes {
if strings.HasPrefix(name, prefix) {
return true
}
}
return false
}
var roots = []string{
`C:\Program Files`,
`C:\Program Files (x86)`,
}
func scanProgramFiles() []Software {
var out []Software
for _, root := range roots {
filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return nil
}
// limit depth (cheap heuristic)
if strings.Count(path, string(os.PathSeparator)) > 4 {
return filepath.SkipDir
}
if d.IsDir() {
return nil
}
if !strings.HasSuffix(strings.ToLower(d.Name()), ".exe") {
return nil
}
name, version := getFileVersion(path)
if name == "" {
return nil
}
out = append(out, Software{
Name: name,
Version: version,
Path: path,
Source: "filesystem",
})
return nil
})
}
return out
}
var (
modVersion = windows.NewLazySystemDLL("version.dll")
procGetFileVersionInfo = modVersion.NewProc("GetFileVersionInfoW")
procGetFileVersionSize = modVersion.NewProc("GetFileVersionInfoSizeW")
procVerQueryValue = modVersion.NewProc("VerQueryValueW")
)
func getFileVersion(path string) (name, version string) {
pathPtr, err := windows.UTF16PtrFromString(path)
if err != nil {
return "", ""
}
// First call: get required buffer size
size, _, _ := procGetFileVersionSize.Call(
uintptr(unsafe.Pointer(pathPtr)),
0,
)
if size == 0 {
return "", ""
}
buf := make([]byte, size)
// Second call: fill the buffer
ret, _, _ := procGetFileVersionInfo.Call(
uintptr(unsafe.Pointer(pathPtr)),
0,
size,
uintptr(unsafe.Pointer(&buf[0])),
)
if ret == 0 {
return "", ""
}
// Query the translation table to find the right language/codepage pair
type langCodepage struct{ lang, codepage uint16 }
var translations *langCodepage
var transLen uint32
ret, _, _ = procVerQueryValue.Call(
uintptr(unsafe.Pointer(&buf[0])),
uintptr(unsafe.Pointer(windows.StringToUTF16Ptr(`\VarFileInfo\Translation`))),
uintptr(unsafe.Pointer(&translations)),
uintptr(unsafe.Pointer(&transLen)),
)
if ret == 0 || transLen == 0 {
return "", ""
}
// Use the first available translation
lang := fmt.Sprintf(`\StringFileInfo\%04x%04x\`, translations.lang, translations.codepage)
name = queryStringValue(buf, lang+"ProductName")
version = queryStringValue(buf, lang+"ProductVersion")
return name, version
}
func queryStringValue(buf []byte, key string) string {
keyPtr, err := windows.UTF16PtrFromString(key)
if err != nil {
return ""
}
var valPtr uintptr
var valLen uint32
ret, _, _ := procVerQueryValue.Call(
uintptr(unsafe.Pointer(&buf[0])),
uintptr(unsafe.Pointer(keyPtr)),
uintptr(unsafe.Pointer(&valPtr)),
uintptr(unsafe.Pointer(&valLen)),
)
if ret == 0 || valLen == 0 {
return ""
}
// valPtr points into buf, valLen is in characters (UTF-16)
utf16Slice := unsafe.Slice((*uint16)(unsafe.Pointer(valPtr)), valLen)
return windows.UTF16ToString(utf16Slice)
}
func scanWinget() []Software {
out, err := exec.Command(
"winget", "list",
"--disable-interactivity",
"--accept-source-agreements",
).Output()
if err != nil || len(out) == 0 {
return nil
}
lines := strings.Split(string(out), "\n")
// Find the header line — it contains "Name" and "Id"
headerIdx := -1
for i, l := range lines {
if strings.Contains(l, "Name") && strings.Contains(l, "Id") {
headerIdx = i
break
}
}
if headerIdx < 0 || headerIdx+2 >= len(lines) {
return nil
}
header := lines[headerIdx]
// Column start positions by header label
nameCol := strings.Index(header, "Name")
idCol := strings.Index(header, "Id")
versionCol := strings.Index(header, "Version")
sourceCol := strings.Index(header, "Source") // may be -1
if nameCol < 0 || idCol < 0 || versionCol < 0 {
return nil
}
// Skip header + separator line (headerIdx+1 is "----")
var res []Software
for _, line := range lines[headerIdx+2:] {
// Trim Windows line endings; skip short/empty lines
line = strings.TrimRight(line, "\r")
if len(line) < versionCol+1 {
continue
}
name := columnSlice(line, nameCol, idCol)
version := columnSlice(line, versionCol, sourceCol)
if name == "" {
continue
}
res = append(res, Software{
Name: name,
Version: version,
Source: "winget",
})
}
return res
}
// columnSlice extracts text between start and end column positions,
// trimming whitespace. If end is -1 (column not present), reads to EOL.
func columnSlice(line string, start, end int) string {
if start >= len(line) {
return ""
}
if end < 0 || end >= len(line) {
return strings.TrimSpace(line[start:])
}
return strings.TrimSpace(line[start:end])
}
func dedupe(in []Software) []Software {
seen := map[string]bool{}
var out []Software
for _, s := range in {
key := strings.ToLower(s.Name + "|" + s.Version)
if seen[key] {
continue
}
seen[key] = true
out = append(out, s)
}
return out
}
func ListInstalledSoftware() []Software {
var all []Software
all = append(all, scanRegistryUninstall()...)
all = append(all, scanAppx()...)
all = append(all, scanProgramFiles()...)
all = append(all, scanWinget()...)
return dedupe(all)
}
func IsElevated() bool {
var token windows.Token
err := windows.OpenProcessToken(windows.CurrentProcess(), windows.TOKEN_QUERY, &token)
if err != nil {
return false
}
defer token.Close()
return token.IsElevated()
}
func extractRegValue(output string) string {
// Windows reg output format:
// " ValueName REG_TYPE ActualValue"
// We need to extract "ActualValue"
lines := strings.Split(output, "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
// Skip empty lines and the key path line
if line == "" || strings.HasPrefix(line, "HKEY_") {
continue
}
// Split by whitespace and get the last non-empty field
fields := strings.Fields(line)
if len(fields) >= 3 {
// Last field is the value
return fields[len(fields)-1]
}
}
return ""
}
func isEncryptedWindows() bool {
out, err := exec.Command("manage-bde", "-status", "C:").Output()
if err != nil {
return false
}
s := strings.ToLower(string(out))
// key signals
return strings.Contains(s, "protection on")
}
func IsDiskEncrypted() bool {
switch runtime.GOOS {
case "windows":
return isEncryptedWindows()
default:
return false
}
}
func GetProfiler() string {
cmds := []string{
"(Get-CimInstance Win32_BIOS).SerialNumber",
"(Get-CimInstance Win32_ComputerSystemProduct).IdentifyingNumber",
}
for _, c := range cmds {
out, err := exec.Command("powershell", "-Command", c).Output()
if err == nil {
s := strings.TrimSpace(string(out))
if isValidSerial(s) {
return s
}
}
}
return "failed to get profiler"
}
var (
kernel32 = syscall.NewLazyDLL("kernel32.dll")
procCreateJobObjectW = kernel32.NewProc("CreateJobObjectW")
procAssignProcessToJobObject = kernel32.NewProc("AssignProcessToJobObject")
procTerminateJobObject = kernel32.NewProc("TerminateJobObject")
)
func createJobObject() (syscall.Handle, error) {
r1, _, err := procCreateJobObjectW.Call(0, 0)
if r1 == 0 {
return 0, err
}
return syscall.Handle(r1), nil
}
func assignProcessToJob(job syscall.Handle, p *os.Process) error {
r1, _, err := procAssignProcessToJobObject.Call(
uintptr(job),
uintptr(p.Pid),
)
if r1 == 0 {
return err
}
return nil
}
func RunCommandString(command string, timeout time.Duration, onStream StreamFn) (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
cmd := exec.CommandContext(ctx, "cmd", "/C", command)
stdout, err := cmd.StdoutPipe()
if err != nil {
return "", err
}
stderr, err := cmd.StderrPipe()
if err != nil {
return "", err
}
if err := cmd.Start(); err != nil {
return "", err
}
var out bytes.Buffer
read := func(r io.ReadCloser) {
buf := make([]byte, 32*1024)
for {
n, err := r.Read(buf)
if n > 0 {
chunk := buf[:n]
out.Write(chunk)
if onStream != nil {
onStream(string(chunk))
}
}
if err != nil {
return
}
}
}
go read(stdout)
go read(stderr)
waitCh := make(chan error, 1)
go func() {
waitCh <- cmd.Wait()
}()
select {
case err := <-waitCh:
return out.String(), err
case <-ctx.Done():
// timeout path: kill only the parent process
_ = cmd.Process.Kill()
<-waitCh // ensure cleanup
return out.String(), fmt.Errorf("timeout after %s", timeout)
}
}
func (c *AuditLogCollector) Stop() {
return
}
func (c *AuditLogCollector) LogCollectorStart(ctx context.Context) error {
return errors.New("Not implemented on windows")
}
func NewAuditLogCollector(config TelemetryConfig) (*AuditLogCollector, error) {
auditLogCollector := AuditLogCollector{}
return &auditLogCollector, errors.New("Not implemented on windows")
}
func queryRegValue(name string) (string, error) {
cmd := exec.Command(
"reg", "query",
`HKEY_CURRENT_USER\Control Panel\Desktop`,
"/v", name,
)
out, err := cmd.CombinedOutput()
if err != nil {
return "", err
}
lines := strings.Split(string(out), "\n")
for _, line := range lines {
if strings.Contains(line, name) {
fields := strings.Fields(line)
if len(fields) >= 3 {
return fields[len(fields)-1], nil
}
}
}
return "", fmt.Errorf("value not found")
}
func IsAutomaticScreenlockEnabled() bool {
activeStr, err := queryRegValue("ScreenSaveActive")
if err != nil {
log.Printf("[ERROR] ScreenSaveActive: %v", err)
return false
}
secureStr, err := queryRegValue("ScreenSaverIsSecure")
if err != nil {
log.Printf("[ERROR] ScreenSaverIsSecure: %v", err)
return false
}
timeoutStr, err := queryRegValue("ScreenSaveTimeOut")
if err != nil {
log.Printf("[ERROR] ScreenSaveTimeOut: %v", err)
return false
}
active := parseInt(activeStr)
secure := parseInt(secureStr)
timeout := parseInt(timeoutStr)
return active == 1 && secure == 1 && timeout <= 900
}
type osVersionInfoEx struct {
dwOSVersionInfoSize uint32
dwMajorVersion uint32
dwMinorVersion uint32
dwBuildNumber uint32
dwPlatformId uint32
szCSDVersion [128]uint16
wServicePackMajor uint16
wServicePackMinor uint16
wSuiteMask uint16
wProductType byte
wReserved byte
}
const (
backupFile = "C:\\Windows\\Temp\\firewall_backup_edr.wfw"
)
func isAdmin() bool {
_, err := os.Open("\\\\.\\PHYSICALDRIVE0")
return err == nil
}
func isolateHostWindows(allowIPs []string) error {
// Must run as admin
if !isAdmin() {
return fmt.Errorf("requires administrator privileges")
}
// 1. Backup firewall state
exec.Command("netsh", "advfirewall", "export", backupFile).Run()
// 2. Set default block policies
cmds := [][]string{
{"netsh", "advfirewall", "set", "allprofiles", "firewallpolicy", "blockinbound,blockoutbound"},
}
for _, c := range cmds {
if err := exec.Command(c[0], c[1:]...).Run(); err != nil {
return fmt.Errorf("failed to set firewall policy: %w", err)
}
}
// 3. Allow loopback explicitly
exec.Command("netsh", "advfirewall", "firewall", "add", "rule",
"name=EDR-Allow-Loopback",
"dir=in",
"action=allow",
"interface=any",
"enable=yes").Run()
exec.Command("netsh", "advfirewall", "firewall", "add", "rule",
"name=EDR-Allow-Loopback-Out",
"dir=out",
"action=allow",
"interface=any",
"enable=yes").Run()
// 4. Allow EDR endpoints
for _, ip := range allowIPs {
exec.Command("netsh", "advfirewall", "firewall", "add", "rule",
fmt.Sprintf("name=EDR-Allow-%s", ip),
"dir=out",
"action=allow",
fmt.Sprintf("remoteip=%s", ip),
"enable=yes").Run()
exec.Command("netsh", "advfirewall", "firewall", "add", "rule",
fmt.Sprintf("name=EDR-Allow-In-%s", ip),
"dir=in",
"action=allow",
fmt.Sprintf("remoteip=%s", ip),
"enable=yes").Run()
}
return nil
}
func unisolateHostWindows() error {
if !isAdmin() {
return fmt.Errorf("requires administrator privileges")
}
// Restore firewall config
return exec.Command("netsh", "advfirewall", "import", backupFile).Run()
}
func isolateHost(allowIPs []string) error {
return isolateHostWindows(allowIPs)
}
func unisolateHost() error {
return unisolateHostWindows()
}
// ── Constructor ──────────────────────────────────────────────────────────────
func NewScanner() *Scanner {
return &Scanner{
results: make(chan ProjectInfo),
visited: make(map[string]bool),
}
}
// ── Public entry point ───────────────────────────────────────────────────────
func (s *Scanner) Scan(rootDir string) ([]ProjectInfo, error) {
absRoot, err := filepath.Abs(rootDir)
if err != nil {
return nil, fmt.Errorf("invalid root directory: %w", err)
}
s.wg.Add(1)
go s.scanDir(absRoot)
var results []ProjectInfo
done := make(chan struct{})
go func() {
for p := range s.results {
results = append(results, p)
}
close(done)
}()
s.wg.Wait()
close(s.results)
<-done
return results, nil
}
// ── Directory walker ─────────────────────────────────────────────────────────
func (s *Scanner) scanDir(dir string) {
defer s.wg.Done()
// Resolve symlinks so we never visit the same inode twice.
real, err := filepath.EvalSymlinks(dir)
if err != nil {
return
}
s.mu.Lock()
if s.visited[real] {
s.mu.Unlock()
return
}
s.visited[real] = true
s.mu.Unlock()
entries, err := os.ReadDir(dir)
if err != nil {
return
}
for _, entry := range entries {
if shouldSkip(entry.Name()) {
continue
}
fullPath := filepath.Join(dir, entry.Name())
if !entry.IsDir() {
continue
}
if projectType := detectProjectType(fullPath); projectType != "" {
packages := extractPackages(fullPath, projectType)
s.results <- ProjectInfo{
Path: fullPath,
Type: projectType,
Packages: packages,
}
// Do not recurse into found projects — avoids duplicates.
continue
}
s.wg.Add(1)
go s.scanDir(fullPath)
}
}
// ── Skip list ────────────────────────────────────────────────────────────────
// skipDirs is the unified skip list for all platforms.
// Windows-specific entries are appended at init time.
var skipDirs = map[string]bool{
// VCS
".git": true,
".hg": true,
".svn": true,
// Dependency caches
"node_modules": true,
"vendor": true,
".venv": true,
"venv": true,
".env": true,
// IDE / tooling
".vscode": true,
".idea": true,
// Build output
"dist": true,
"build": true,
"target": true,
"out": true,
"bin": true,
"obj": true, // .NET
// Caches
".cache": true,
"__pycache__": true,
}
func init() {
if runtime.GOOS == "windows" {
// Windows system and user-profile noise — these directories sit under
// %USERPROFILE% but contain no user code.
for _, d := range []string{
"AppData",
"Application Data",
"Local Settings",
"MicrosoftEdgeBackups",
"OneDrive", // mirror of cloud files, not local projects
"Windows",
"Program Files",
"Program Files (x86)",
"ProgramData",
"$Recycle.Bin",
"System Volume Information",
"Recovery",
} {
skipDirs[d] = true
}
}
}
func shouldSkip(name string) bool {
if skipDirs[name] {
return true
}
// Hidden directories (dot-prefixed) on Unix; also catches .git etc. on Windows.
if strings.HasPrefix(name, ".") && name != "." {
return true
}
return false
}
// ── Project detection ────────────────────────────────────────────────────────
func detectProjectType(dir string) string {
if fileExists(filepath.Join(dir, "go.mod")) {
return "golang"
}
if fileExists(filepath.Join(dir, "pyproject.toml")) ||
fileExists(filepath.Join(dir, "requirements.txt")) ||
fileExists(filepath.Join(dir, "Pipfile")) {
return "python"
}
if fileExists(filepath.Join(dir, "package.json")) {
return "javascript"
}
if fileExists(filepath.Join(dir, "pom.xml")) ||
fileExists(filepath.Join(dir, "build.gradle")) ||
fileExists(filepath.Join(dir, "build.gradle.kts")) {
return "java"
}
if fileExists(filepath.Join(dir, "Gemfile")) ||
fileExists(filepath.Join(dir, "Rakefile")) {
return "ruby"
}
// .NET: must ReadDir — glob patterns are not valid os.Stat paths.
if entries, err := os.ReadDir(dir); err == nil {
for _, e := range entries {
n := e.Name()
if strings.HasSuffix(n, ".csproj") ||
strings.HasSuffix(n, ".vbproj") ||
strings.HasSuffix(n, ".fsproj") {
return "dotnet"
}
}
}
return ""
}
// ── Dispatcher ───────────────────────────────────────────────────────────────
func extractPackages(dir, projectType string) []Software {
switch projectType {
case "golang":
return extractGoPackages(dir)
case "python":
return extractPythonPackages(dir)
case "javascript":
return extractJavaScriptPackages(dir)
case "java":
return extractJavaPackages(dir)
case "ruby":
return extractRubyPackages(dir)
case "dotnet":
return extractDotnetPackages(dir)
}
return nil
}
// ── Go ───────────────────────────────────────────────────────────────────────
func extractGoPackages(dir string) []Software {
f, err := os.Open(filepath.Join(dir, "go.mod"))
if err != nil {
return nil
}
defer f.Close()
var pkgs []Software
sc := bufio.NewScanner(f)
inBlock := false
for sc.Scan() {
line := strings.TrimSpace(sc.Text())
switch {
case line == "require (":
inBlock = true
case line == ")" && inBlock:
inBlock = false
case strings.HasPrefix(line, "require ") && !inBlock:
// Single-line form: require github.com/foo/bar v1.2.3
parts := strings.Fields(line)
if len(parts) == 3 {
pkgs = append(pkgs, Software{Name: parts[1], Version: parts[2]})
}
case inBlock && line != "" && !strings.HasPrefix(line, "//"):
parts := strings.Fields(line)
if len(parts) >= 2 {
pkgs = append(pkgs, Software{Name: parts[0], Version: parts[1]})
} else if len(parts) == 1 {
pkgs = append(pkgs, Software{Name: parts[0]})
}
}
}
return pkgs
}
// ── Python ───────────────────────────────────────────────────────────────────
func extractPythonPackages(dir string) []Software {
if data, err := os.ReadFile(filepath.Join(dir, "pyproject.toml")); err == nil {
if pkgs := parsePyprojectToml(string(data)); len(pkgs) > 0 {
return pkgs
}
}
if data, err := os.ReadFile(filepath.Join(dir, "requirements.txt")); err == nil {
if pkgs := parseRequirementsTxt(string(data)); len(pkgs) > 0 {
return pkgs
}
}
if data, err := os.ReadFile(filepath.Join(dir, "Pipfile")); err == nil {
return parsePipfile(string(data))
}
return nil
}
// versionOps are Python version specifier operators, longest-match first.
var versionOps = []string{">=", "<=", "==", "~=", "!=", ">", "<", ";"}
func splitPyDep(dep string) (name, version string) {
minIdx := len(dep)
for _, op := range versionOps {
if idx := strings.Index(dep, op); idx >= 0 && idx < minIdx {
minIdx = idx
}
}
if minIdx < len(dep) {
return strings.TrimSpace(dep[:minIdx]), strings.TrimSpace(dep[minIdx:])
}
return strings.TrimSpace(dep), ""
}
func parseRequirementsTxt(content string) []Software {
var pkgs []Software
sc := bufio.NewScanner(strings.NewReader(content))
for sc.Scan() {
line := strings.TrimSpace(sc.Text())
if line == "" || strings.HasPrefix(line, "#") || strings.HasPrefix(line, "-") {
continue
}
// Strip inline comments.
if i := strings.Index(line, " #"); i >= 0 {
line = strings.TrimSpace(line[:i])
}
name, version := splitPyDep(line)
if name != "" {
pkgs = append(pkgs, Software{Name: name, Version: version})
}
}
return pkgs
}
func parsePyprojectToml(content string) []Software {
var pkgs []Software
inDeps := false
sc := bufio.NewScanner(strings.NewReader(content))
for sc.Scan() {