Skip to content

Commit 59a2251

Browse files
committed
house cleaning: smaller optimizations
1 parent 669b612 commit 59a2251

4 files changed

Lines changed: 65 additions & 93 deletions

File tree

pkg/checksums/filewalker.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,10 @@ import (
88
)
99

1010
// Will recursively walk and send filepaths from root, who are smaller than sizeLimit to filepaths
11-
func DirectoryWalker(root string, sizeLimit int, filepaths chan<- string) (err error) {
12-
logger.Info("Checking %s", root)
11+
func DirectoryWalker(root string, sizeLimit int, filepaths chan<- string) error {
12+
logger.Debug("Checking %s", root)
1313

14-
err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
14+
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
1515
if err != nil {
1616
// Ignore a file if we get "Access is denied" error
1717
if os.IsPermission(err) {

pkg/checksums/runner.go

Lines changed: 18 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -17,55 +17,35 @@ type Result struct {
1717
func Runner(wg *sync.WaitGroup, filepaths <-chan string, results chan<- *Result, silenceErrors bool) {
1818
defer wg.Done()
1919

20+
hashFuncs := []struct {
21+
name string
22+
fn func(string) (string, error)
23+
}{
24+
{"SHA1", calcSHA1},
25+
{"SHA256", calcSHA256},
26+
{"MD5", calcMD5},
27+
}
28+
2029
for filepath := range filepaths {
2130
// The order of the hash checks was choosen based on the amount of hashes upon writing this bit
2231
// SHA1 > SHA2 > MD5
2332

24-
sha1, err := calcSHA1(filepath)
25-
if err != nil && !silenceErrors {
26-
logger.Error(err)
27-
continue
28-
} else {
29-
matched, driver := loldrivers.MatchHash(sha1)
30-
if matched {
31-
results <- &Result{
32-
Filepath: filepath,
33-
Checksum: sha1,
34-
Driver: driver,
33+
for _, hash := range hashFuncs {
34+
checksum, err := hash.fn(filepath)
35+
if err != nil {
36+
if !silenceErrors {
37+
logger.Errorf("Error calculating %s for %s: %v", hash.name, filepath, err)
3538
}
36-
37-
continue // No need to check others as there was a match
39+
continue
3840
}
39-
}
40-
41-
sha256, err := calcSHA256(filepath)
42-
if err != nil && !silenceErrors {
43-
logger.Error(err)
44-
continue
45-
} else {
46-
matched, driver := loldrivers.MatchHash(sha256)
47-
if matched {
48-
results <- &Result{
49-
Filepath: filepath,
50-
Checksum: sha256,
51-
Driver: driver,
52-
}
53-
54-
continue // No need to check others as there was a match
55-
}
56-
}
5741

58-
md5, err := calcMD5(filepath)
59-
if err != nil && !silenceErrors {
60-
logger.Error(err)
61-
} else {
62-
matched, driver := loldrivers.MatchHash(md5)
63-
if matched {
42+
if matched, driver := loldrivers.MatchHash(checksum); matched {
6443
results <- &Result{
6544
Filepath: filepath,
66-
Checksum: md5,
45+
Checksum: checksum,
6746
Driver: driver,
6847
}
48+
break // Found a match, skip remaining hashes
6949
}
7050
}
7151
}

pkg/loldrivers/loldrivers.go

Lines changed: 18 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package loldrivers
22

33
import (
4+
"fmt"
45
"io"
56
"net/http"
67
"os"
@@ -9,41 +10,26 @@ import (
910
)
1011

1112
// Will load the drivers based on the selected mode (online, local (requires filePath), internal)
12-
func LoadDrivers(mode string, filePath string) (err error) {
13-
var jsonData []byte
13+
func LoadDrivers(mode string, filePath string) error {
14+
var (
15+
jsonData []byte
16+
err error
17+
)
1418

1519
switch mode {
1620
case "online":
1721
jsonData, err = downloadNewestData()
18-
if err != nil {
19-
logger.Error(err)
20-
jsonData = internalDrivers // Fallback
21-
}
22-
2322
case "local":
24-
jsonData, err = func() (b []byte, err error) {
25-
// Read the local .json file
26-
fp, err := os.Open(filePath) // #nosec G304
27-
if err != nil {
28-
return nil, err
29-
}
30-
defer fp.Close()
31-
32-
b, err = io.ReadAll(fp)
33-
if err != nil {
34-
return nil, err
35-
}
36-
37-
return b, nil
38-
}()
39-
40-
if err != nil {
41-
logger.Error(err)
42-
jsonData = internalDrivers // Fallback
43-
}
44-
23+
jsonData, err = os.ReadFile(filePath) // #nosec G304
4524
case "internal":
46-
// Use the built in ones
25+
jsonData = internalDrivers
26+
default:
27+
return fmt.Errorf("invalid mode: %s", mode)
28+
}
29+
30+
if err != nil {
31+
logger.Error(err)
32+
logger.Debug("Falling back to internal drivers")
4733
jsonData = internalDrivers
4834
}
4935

@@ -55,7 +41,7 @@ func LoadDrivers(mode string, filePath string) (err error) {
5541
}
5642

5743
// Will return true and a pointer to the matching driver, else return false and nil
58-
func MatchHash(hash string) (matched bool, match *Driver) {
44+
func MatchHash(hash string) (bool, *Driver) {
5945
switch len(hash) {
6046
case 32:
6147
if driver := md5Sums[hash]; driver != nil {
@@ -74,9 +60,9 @@ func MatchHash(hash string) (matched bool, match *Driver) {
7460
return false, nil
7561
}
7662

77-
// Downloads the newset driver set from the loldrivers API
63+
// Downloads the newset driver set from the loldrivers.io API
7864
func downloadNewestData() ([]byte, error) {
79-
logger.Info("Downloading the newest data set")
65+
logger.Debug("Downloading the newest data set")
8066

8167
client := &http.Client{}
8268
request, err := http.NewRequest("GET", "https://www.loldrivers.io/api/drivers.json", nil)

pkg/options/options.go

Lines changed: 26 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,9 @@ import (
44
"errors"
55
"time"
66

7-
"github.com/rtfmkiesel/loldrivers-client/pkg/logger"
87
flag "github.com/spf13/pflag"
8+
9+
"github.com/rtfmkiesel/loldrivers-client/pkg/logger"
910
)
1011

1112
var (
@@ -25,28 +26,28 @@ type Options struct {
2526
}
2627

2728
// Parse the command line options into an Options struct
28-
func Parse() (opt *Options, err error) {
29-
opt = &Options{}
30-
opt.StartTime = time.Now()
29+
func Parse() (*Options, error) {
30+
opt := &Options{
31+
StartTime: time.Now(),
32+
}
33+
34+
var (
35+
flagDir string
36+
flagGrepable bool
37+
flagJson bool
38+
)
3139

3240
flag.StringVarP(&opt.Mode, "mode", "m", "online", "Operating Mode {online, local, internal}")
3341
flag.StringVarP(&opt.ModeLocalFilePath, "driver-file", "f", "", "File path to 'drivers.json', when mode == local")
34-
35-
var flagDir string
3642
flag.StringVarP(&flagDir, "scan-dir", "d", "", "Directory to scan for drivers (default: Windows driver folders)")
3743
flag.IntVarP(&opt.ScanSizeLimit, "scan-size", "l", 10, "Size limit for files to scan in MB")
3844
flag.IntVarP(&opt.ScanWorkers, "workers", "w", 20, "Number of checksum \"threads\" to spawn")
3945
flag.BoolVarP(&opt.ScanShowErrors, "surpress-errors", "s", false, "Do not show file read errors when calculating checksums")
40-
41-
var flagGrepable bool
42-
var flagJson bool
4346
flag.BoolVarP(&flagGrepable, "grepable", "g", false, "Will only output found files for easy parsing")
4447
flag.BoolVarP(&flagJson, "json", "j", false, "Format output as JSON")
4548

4649
flag.Parse()
4750

48-
logger.Verbose = true
49-
5051
switch opt.Mode {
5152
case "online", "internal":
5253
// we good
@@ -61,20 +62,25 @@ func Parse() (opt *Options, err error) {
6162
// Only one output style
6263
if flagGrepable && flagJson {
6364
return nil, errors.New("only use '-g/--grepable' or '-j/--json', not both")
64-
} else if flagGrepable {
65+
}
66+
67+
switch {
68+
case flagGrepable:
6569
opt.OutputMode = "grep"
66-
logger.Verbose = false
67-
} else if flagJson {
70+
logger.ShowDebugOutput = false
71+
case flagJson:
6872
opt.OutputMode = "json"
69-
logger.Verbose = false
73+
logger.ShowDebugOutput = false
74+
default:
75+
logger.ShowDebugOutput = true
7076
}
7177

72-
if flagDir == "" {
78+
if flagDir != "" {
79+
// User specified a custom folder to scan
80+
opt.ScanDirectories = []string{flagDir}
81+
} else {
7382
// User did not specify a path with '-d', use the default Windows directories
7483
opt.ScanDirectories = windowsDriverDirs
75-
} else {
76-
// User specified a custom folder to scan
77-
opt.ScanDirectories = append(opt.ScanDirectories, flagDir)
7884
}
7985

8086
printBanner()
@@ -83,7 +89,7 @@ func Parse() (opt *Options, err error) {
8389
}
8490

8591
func printBanner() {
86-
logger.PlainStderr(`
92+
logger.Stderr(`
8793
╔─────────────────────────────────────╗
8894
│ LOLDrivers-client │
8995
│ https://www.loldrivers.io │

0 commit comments

Comments
 (0)