Skip to content

Commit

Permalink
Merge pull request #14 from g4s8/13-preload
Browse files Browse the repository at this point in the history
Preload method with benchmarks
  • Loading branch information
bzz authored Jul 6, 2021
2 parents 21a939e + 6403a23 commit 4f2ca6a
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 0 deletions.
5 changes: 5 additions & 0 deletions licensedb/internal/investigation.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,3 +161,8 @@ func InvestigateReadmeText(text []byte, fs filer.Filer) map[string]float32 {
func IsLicenseDirectory(fileName string) bool {
return licenseDirectoryRe.MatchString(strings.ToLower(fileName))
}

// Preload license database
func Preload() {
_ = globalLicenseDatabase()
}
10 changes: 10 additions & 0 deletions licensedb/licensedb.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,13 @@ func Detect(fs filer.Filer) (map[string]api.Match, error) {
}
return licenses, nil
}

// Preload database with licenses - load internal database from assets into memory.
// This method is an optimization for cases when the `Detect` method should return fast,
// e.g. in HTTP web servers where connection timeout can occur during detect
// `Preload` method could be called before server startup.
// This method os optional and it's not required to be called, other APIs loads license database
// lazily on first invocation.
func Preload() {
internal.Preload()
}
45 changes: 45 additions & 0 deletions licensedb/licensedb_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package licensedb

import (
"os"
"path/filepath"
"testing"

"github.com/go-enry/go-license-detector/v4/licensedb/filer"
)

func BenchmarkDetect(b *testing.B) {
f := pwdFiler()
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, err := Detect(f)
if err != nil {
panic(err)
}
}
}

func BenchmarkDetectWithPreload(b *testing.B) {
f := pwdFiler()
Preload()
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, err := Detect(f)
if err != nil {
panic(err)
}
}
}

func pwdFiler() filer.Filer {
pwd, err := os.Getwd()
if err != nil {
panic(err)
}
root := filepath.Dir(pwd)
f, err := filer.FromDirectory(root)
if err != nil {
panic(err)
}
return f
}

0 comments on commit 4f2ca6a

Please sign in to comment.