This repository was archived by the owner on Aug 29, 2023. It is now read-only.
generated from IBM/repo-template
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathlicense.go
760 lines (667 loc) · 22.5 KB
/
license.go
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
// SPDX-License-Identifier: Apache-2.0
package licenses
import (
"encoding/json"
"errors"
"fmt"
"io/fs"
"io/ioutil"
"os"
"path"
"path/filepath"
"regexp"
"sort"
"strings"
"sync"
"github.com/IBM/license-scanner/configurer"
"github.com/spf13/viper"
"github.com/mrutkows/sbom-utility/log"
"github.com/IBM/license-scanner/normalizer"
)
const (
Resources = "resources"
SPDX = "spdx"
customDir = "custom"
template = "template"
precheck = "precheck"
jsonDir = "json"
LicenseInfoJSON = "license_info.json"
PreChecksPattern = "prechecks_"
PrimaryPattern = "license_"
AssociatedPattern = "associated_"
OptionalPattern = "optional_"
LicensePatterns = "license_patterns"
AcceptablePatterns = "acceptable_patterns"
)
var (
Logger = log.NewLogger(log.INFO)
pointyBracketSegmentRE = regexp.MustCompile(` *<<(.*?)>> *`)
RegexUnsafePattern = regexp.MustCompile(`([\\.*+?^${}()|[\]])`)
spaceTagReplacer = strings.NewReplacer(
" <<", "<<",
">> ", ">>",
)
tagReplacer = strings.NewReplacer(
"<<omitable>>", "BEGIN_OMITABLE",
"<</omitable>>", "END_OMITABLE",
"<<copyright>>", "COPYRIGHT",
)
tokenReplacer = strings.NewReplacer(
"BEGIN_OMITABLE", " *(?:",
"END_OMITABLE", " *)?",
"COPYRIGHT", ".*",
)
)
type LicenseLibrary struct {
SPDXVersion string
LicenseMap LicenseMap
PrimaryPatternPreCheckMap PrimaryPatternPreCheckMap
AcceptablePatternsMap PatternsMap
Config *viper.Viper
}
type LicensePreChecks struct {
StaticBlocks []string
}
type LicensePatternKey struct {
FilePath string // Each ID may have multiple license_*.txt primary patterns
}
type PrimaryPatternPreCheckMap map[LicensePatternKey]*LicensePreChecks
type Detail struct {
ID string
Name string
Family string
NumTemplates int
IsOSIApproved bool
IsFSFLibre bool
}
type Exception struct {
ID string
Name string
Family string
NumTemplates int
}
func NewLicenseLibrary(config *viper.Viper) (*LicenseLibrary, error) {
if config == nil {
cfg, err := configurer.InitConfig(nil)
if err != nil {
return nil, err
}
config = cfg
}
ll := LicenseLibrary{
LicenseMap: make(LicenseMap),
PrimaryPatternPreCheckMap: make(PrimaryPatternPreCheckMap),
AcceptablePatternsMap: make(PatternsMap),
Config: config,
}
return &ll, nil
}
type LicenseMap map[string]License
// License holds the specification of each license
type License struct {
// SPDX License ID if applicable, for example, "Apache-2.0"
SPDXLicenseID string
LicenseInfo LicenseInfo
PrimaryPatterns []*PrimaryPatterns
PrimaryPatternsSources []PrimaryPatternsSources
AssociatedPatterns []*PrimaryPatterns
AssociatedPatternsSources []PrimaryPatternsSources
// Aliases (and names and IDs) can be used like primary patterns (unless disabled), but are simple strings not regex. They also require word boundaries.
Aliases []string
// URLs can be used like primary patterns (unless disabled), but are simple strings not regex with URL matching.
URLs []string
// license text or an expression
Text LicenseText
}
type PatternsMap map[string]*regexp.Regexp
type PrimaryPatterns struct {
Text string
doOnce sync.Once
re *regexp.Regexp
CaptureGroups []*normalizer.CaptureGroup
FileName string
}
type PrimaryPatternsSources struct {
SourceText string
Filename string
}
// LicenseText contains the content type along with the content
type LicenseText struct {
// content type of the license, for example, "text/plain"
ContentType string
// any encoding if the license text is encoded in any particular format, for example, "base64"
Encoding string
// license text encoded in the format specified
Content string
}
type SPDXLicenceInfo struct {
Name string `json:"name"`
LicenseID string `json:"licenseId"`
IsOSIApproved bool `json:"isOsiApproved"`
IsFSFLibre bool `json:"isFsfLibre"`
IsDeprecatedLicenseID bool `json:"isDeprecatedLicenseId"`
}
type SPDXExceptionInfo struct {
Name string `json:"name"`
LicenseExceptionID string `json:"licenseExceptionId"`
IsDeprecatedLicenseID bool `json:"isDeprecatedLicenseId"`
}
type SPDXLicenceList struct {
LicenseListVersion string `json:"licenseListVersion"`
Licenses []SPDXLicenceInfo `json:"licenses"`
Exceptions []SPDXExceptionInfo `json:"exceptions"`
}
type LicenseInfo struct {
Name string `json:"name"`
Family string `json:"family"`
SPDXStandard bool `json:"spdx_standard"`
SPDXException bool `json:"spdx_exception"`
OSIApproved bool `json:"osi_approved"`
IgnoreIDMatch bool `json:"ignore_id_match"`
IgnoreNameMatch bool `json:"ignore_name_match"`
Aliases SliceOfStrings `json:"aliases"`
URLs SliceOfStrings `json:"urls"`
EligibleLicenses SliceOfStrings `json:"eligible_licenses"`
IsMutator bool `json:"is_mutator"`
IsDeprecated bool `json:"is_deprecated"`
IsFSFLibre bool `json:"is_fsf_libre"`
}
// SliceOfStrings gives us []string with special UnmarshalJSON
type SliceOfStrings []string
// UnmarshalJSON reads string or array of strings into []string when json.Unmarshal encounters a SliceOfStrings
func (stringArray *SliceOfStrings) UnmarshalJSON(b []byte) error {
var stringOrStrings interface{}
err := json.Unmarshal(b, &stringOrStrings)
if err != nil {
return err
}
*stringArray = toSliceOfStrings(stringOrStrings)
return nil
}
// toSliceOfStrings takes an interface which can be a string, a slice of strings, or some interface{} version of that, and convert it into a []string
func toSliceOfStrings(got interface{}) []string {
if got == nil {
return nil
}
switch got.(type) {
case []interface{}, []string:
got := got.([]interface{})
ret := make([]string, 0, len(got))
for _, s := range got {
ret = append(ret, s.(string))
}
return ret
case interface{}, string:
return []string{got.(string)}
default:
panic(fmt.Sprintf("NOT A STRING OR STRINGS %v", got))
}
}
// readLicenseInfoJSON unmarshalls the json bytes into LicenseInfo
func readLicenseInfoJSON(fileContents []byte) (*LicenseInfo, error) {
var licenseInfo LicenseInfo
if err := json.Unmarshal(fileContents, &licenseInfo); err != nil {
return nil, err
}
return &licenseInfo, nil
}
// ReadSPDXLicenseListJSON unmarshalls the json bytes into SPDXLicenseList
func ReadSPDXLicenseListJSON(fileContents []byte) (*SPDXLicenceList, error) {
var ret SPDXLicenceList
err := json.Unmarshal(fileContents, &ret)
return &ret, err
}
type addFunc func(string, string) error
func (l License) GetID() string {
if l.SPDXLicenseID != "" {
return l.SPDXLicenseID
} else {
return l.LicenseInfo.Name
}
}
func (ll *LicenseLibrary) AddAll() error {
if err := ll.AddAllSPDX(); err != nil && !errors.Is(err, fs.ErrNotExist) {
// not exist is okay for now. Assuming legacy resources
return err
}
return ll.AddAllLegacy()
}
func (ll *LicenseLibrary) AddAllSPDX() error {
resourcesPath := ll.Config.GetString(Resources)
SPDXDir := ll.Config.GetString(SPDX)
// templateMap := make(map[string]string)
templatePath := path.Join(resourcesPath, "spdx", SPDXDir, template)
jsonPath := path.Join(resourcesPath, "spdx", SPDXDir, jsonDir)
licensesJSON := path.Join(jsonPath, "licenses.json")
SPDXLicenseListBytes, err := os.ReadFile(licensesJSON)
if err != nil {
return fmt.Errorf("read SPDXLicenseListJSON from %v error: %w", licensesJSON, err)
}
licenseList, err := ReadSPDXLicenseListJSON(SPDXLicenseListBytes)
if err != nil {
return fmt.Errorf("unmarshal SPDXLicenseListJSON from %v error: %w", licensesJSON, err)
}
ll.SPDXVersion = licenseList.LicenseListVersion
exceptionsJSON := path.Join(jsonPath, "exceptions.json")
SPDXExceptionsListBytes, err := os.ReadFile(exceptionsJSON)
if err != nil {
return fmt.Errorf("read exceptions JSON from %v error: %w", exceptionsJSON, err)
}
exceptionsList, err := ReadSPDXLicenseListJSON(SPDXExceptionsListBytes)
if err != nil {
return fmt.Errorf("unmarshal SPDXLicenseListJSON from %v error: %w", exceptionsJSON, err)
}
for _, sl := range licenseList.Licenses {
id := sl.LicenseID
f := getTemplateFilePath(id, sl.IsDeprecatedLicenseID, templatePath)
tBytes, err := os.ReadFile(f)
if err != nil {
if os.IsNotExist(err) {
Logger.Debugf("Skipping missing template file '%v'", f)
continue
}
return err
}
l := ll.LicenseMap[id]
if err := AddPrimaryPatternAndSource(string(tBytes), f, &l); err != nil {
return err
}
l.SPDXLicenseID = id
l.LicenseInfo.Name = sl.Name
l.LicenseInfo.SPDXStandard = true
l.LicenseInfo.SPDXException = false
l.LicenseInfo.IsDeprecated = sl.IsDeprecatedLicenseID
l.LicenseInfo.OSIApproved = sl.IsOSIApproved
l.LicenseInfo.IsFSFLibre = sl.IsFSFLibre
ll.LicenseMap[id] = l
}
for _, se := range exceptionsList.Exceptions {
id := se.LicenseExceptionID
f := getTemplateFilePath(id, se.IsDeprecatedLicenseID, templatePath)
tBytes, err := os.ReadFile(f)
if err != nil {
if os.IsNotExist(err) {
Logger.Debugf("Skipping missing template file '%v'", f)
continue
}
return err
}
l := ll.LicenseMap[id]
if err := AddPrimaryPatternAndSource(string(tBytes), f, &l); err != nil {
return err
}
l.SPDXLicenseID = id
l.LicenseInfo.Name = se.Name
l.LicenseInfo.SPDXStandard = true
l.LicenseInfo.SPDXException = true
l.LicenseInfo.IsDeprecated = se.IsDeprecatedLicenseID
ll.LicenseMap[id] = l
}
preCheckMap := make(map[string]string)
preCheckPath := path.Join(resourcesPath, "spdx", SPDXDir, precheck)
if err := filepath.WalkDir(preCheckPath, func(path string, de fs.DirEntry, err error) error {
if err != nil {
return err
}
if de.IsDir() {
if de.Name() == precheck {
return nil // walk the template dir
}
return filepath.SkipDir // ignore any other dirs
}
if strings.HasSuffix(de.Name(), ".json") {
preCheckMap[strings.TrimSuffix(de.Name(), ".json")] = path
}
return err
}); err != nil {
return err
}
for id, f := range preCheckMap {
fileContents, err := os.ReadFile(f)
if err != nil {
return err
}
isDeprecated := ll.LicenseMap[id].LicenseInfo.IsDeprecated
templateFilePath := getTemplateFilePath(id, isDeprecated, templatePath)
if err := addPreChecks(fileContents, templateFilePath, ll); err != nil {
return err
}
}
return nil
}
func getTemplateFilePath(id string, isDeprecated bool, templatePath string) string {
f := id + ".template.txt"
if isDeprecated {
f = "deprecated_" + f
}
f = path.Join(templatePath, f)
return f
}
func (ll *LicenseLibrary) AddAllLegacy() error {
if err := ll.addAcceptablePatternsFromBundledLibrary(); err != nil {
return err
}
Logger.Debugf("Loaded %v acceptable patterns", len(ll.AcceptablePatternsMap))
if err := ll.AddLicenses(); err != nil {
return err
}
Logger.Debugf("Loaded %v licenses", len(ll.LicenseMap))
return nil
}
func (ll *LicenseLibrary) addAcceptablePattern(patternId string, source string) error {
if _, ok := ll.AcceptablePatternsMap[patternId]; ok {
return fmt.Errorf("An acceptable pattern already exists with the ID %v", patternId)
}
source = strings.TrimSpace(source)
re, err := regexp.Compile("(?i)" + source)
if err != nil {
return err
}
ll.AcceptablePatternsMap[patternId] = re
return nil
}
func (ll *LicenseLibrary) addAcceptablePatternsFromBundledLibrary() error {
_, acceptablePatternsPath := getResourcePaths(ll.Config)
if err := ll.addRegexFromSourceToLibrary(acceptablePatternsPath, ll.addAcceptablePattern); err != nil && !os.IsNotExist(err) {
// Ignoring IsNotExist to make acceptable patterns optional, but other errs are not ok
return err
}
return nil
}
func (ll *LicenseLibrary) addRegexFromSourceToLibrary(sourceDir string, addFunction addFunc) error {
files, err := ioutil.ReadDir(sourceDir)
if err != nil {
if !os.IsNotExist(err) {
return err
} else {
return nil
}
}
for _, file := range files {
if file.IsDir() {
continue
}
fileName := file.Name()
patternId := fileName[:len(fileName)-len(filepath.Ext(fileName))]
source, err := ioutil.ReadFile(path.Join(sourceDir, fileName))
if err != nil {
return err
}
if err := addFunction(patternId, string(source)); err != nil {
_ = Logger.Errorf("invalid regex from %v/%v with error: %v", sourceDir, fileName, err)
return err
}
}
return nil
}
func getResourcePaths(cfg *viper.Viper) (licensePatternsPath, acceptablePatternsPath string) {
rd := cfg.GetString(Resources)
customVersionedDir := cfg.GetString(configurer.CustomFlag)
licensePatternsPath = path.Join(rd, customDir, customVersionedDir, LicensePatterns)
acceptablePatternsPath = path.Join(rd, customDir, customVersionedDir, AcceptablePatterns)
return
}
// AddLicenses initializes the license data set to scan the input license file against
// all the possible licenses available in the resources are read
func (ll *LicenseLibrary) AddLicenses() error {
licensePatternsPath, _ := getResourcePaths(ll.Config)
licenseIds, err := ioutil.ReadDir(licensePatternsPath)
if err != nil {
return err
}
// retrieve each license ID based on the directory name, i.e. resources/license_patterns/licenseID
// for example, resources/license_patterns/MIT
for _, id := range licenseIds {
err := AddLicense(id.Name(), ll)
if err != nil {
_ = Logger.Errorf("AddLicense error on %v: %v", id.Name(), err)
return err
}
}
return nil
}
func AddLicense(id string, ll *LicenseLibrary) error {
l, existed := ll.LicenseMap[id]
licensePatternsPath, _ := getResourcePaths(ll.Config)
// license directory is at the LicensePatternsPath/id
licenseDirectory := path.Join(licensePatternsPath, id)
directoryContents, err := ioutil.ReadDir(licenseDirectory)
if err != nil {
return err
}
// load license data from the license directory
for _, file := range directoryContents {
// reading from a directory at this point is not expected
// the license patterns contains a list of files with primary and associated patterns (license_MIT.txt, associated_full_title.txt, etc)
if file.IsDir() {
continue
}
// read the file contents, determine the file path by joining licenseDirectory (LicensePatternsPath/id) and file name
fileContents, err := ioutil.ReadFile(path.Join(licenseDirectory, file.Name()))
if err != nil {
return err
}
fileName := file.Name()
filePath := path.Join(licenseDirectory, fileName)
lowerFileName := strings.ToLower(fileName)
switch {
// the JSON payload is always stored in license_info.txt
case lowerFileName == LicenseInfoJSON:
payload, err := readLicenseInfoJSON(fileContents)
if err != nil {
return Logger.Errorf("Unmarshal LicenseInfo from %v using LicenseReader error: %v", file.Name(), err)
}
if l.SPDXLicenseID == "" {
if payload.SPDXStandard {
l.SPDXLicenseID = id
}
} else if !payload.SPDXStandard {
return Logger.Errorf("Cannot add non-SPDX custom policies from %v to existing SPDX license %v", id, l.SPDXLicenseID)
}
// Instead of trying to do the optional "the " and optional " license", any string wanted should be configured to be used as-is.
// Word boundaries before and after the strings will be enforced.
// ToLower the aliases to prepare them to match it against normalized data.
var aliases []string
for _, a := range payload.Aliases {
aliases = append(aliases, strings.ToLower(a))
}
if !payload.IgnoreIDMatch {
aliases = append(aliases, strings.ToLower(id))
}
if !payload.IgnoreNameMatch && payload.Name != "" {
aliases = append(aliases, strings.ToLower(payload.Name))
}
l.Aliases = aliases
// When the legacy one is disabled, use the stringy version of matching.
// Instead of trying to do the optional http(s), optional www, etc... any string wanted should be configured to be used as-is.
// ToLower the URLs to prepare them to match it against normalized data.
var urls []string
for _, u := range payload.URLs {
_, after, found := strings.Cut(u, "://")
if found {
urls = append(urls, strings.ToLower(after))
} else {
urls = append(urls, strings.ToLower(u))
}
}
l.URLs = urls
if existed { // merge the additional LicenseInfo with the existing SPDX attributes
if l.LicenseInfo.Name != "" {
payload.Name = l.LicenseInfo.Name // Use first name we got (from SPDX), if not empty
}
// Merge SPDX bools flags. Use true if either existing or payload says true
payload.SPDXStandard = payload.SPDXStandard || l.LicenseInfo.SPDXStandard
payload.SPDXException = payload.SPDXException || l.LicenseInfo.SPDXException
payload.IsDeprecated = payload.IsDeprecated || l.LicenseInfo.IsDeprecated
payload.OSIApproved = payload.OSIApproved || l.LicenseInfo.OSIApproved
payload.IsFSFLibre = payload.IsFSFLibre || l.LicenseInfo.IsFSFLibre
}
l.LicenseInfo = *payload
// all other files starting with "license_" are primary license patterns
case strings.HasPrefix(lowerFileName, PrimaryPattern):
if err := AddPrimaryPatternAndSource(string(fileContents), filePath, &l); err != nil {
return err
}
// all other files starting with "prechecks_" are prechecks for license patterns
case strings.HasPrefix(lowerFileName, PreChecksPattern):
sourceFile := strings.TrimPrefix(fileName, PreChecksPattern)
ext := path.Ext(sourceFile)
sourceFile = sourceFile[0:len(sourceFile)-len(ext)] + ".txt" // Replace .json with .txt
filePath := path.Join(licenseDirectory, sourceFile)
if err := addPreChecks(fileContents, filePath, ll); err != nil {
return err
}
// All files starting with "associated_" or "optional_" are associated patterns
case strings.HasPrefix(lowerFileName, AssociatedPattern), strings.HasPrefix(lowerFileName, OptionalPattern):
p := PrimaryPatternsSources{
SourceText: string(fileContents),
Filename: filePath,
}
l.AssociatedPatternsSources = append(l.AssociatedPatternsSources, p)
associatedPattern := PrimaryPatterns{
Text: p.SourceText,
FileName: p.Filename,
}
l.AssociatedPatterns = append(l.AssociatedPatterns, &associatedPattern)
default:
Logger.Info(fmt.Sprintf("found an invalid file name %s", filePath))
}
}
ll.LicenseMap[id] = l
return nil
}
func addPreChecks(fileContents []byte, templatePath string, ll *LicenseLibrary) error {
readPreChecks := &LicensePreChecks{}
err := json.Unmarshal(fileContents, readPreChecks)
if err != nil {
return fmt.Errorf("error on unmarshal %v: %w", templatePath, err)
} else {
licensePatternKey := LicensePatternKey{
FilePath: templatePath,
}
ll.PrimaryPatternPreCheckMap[licensePatternKey] = readPreChecks
}
return nil
}
func AddPrimaryPatternAndSource(fileContents string, filePath string, l *License) error {
p := PrimaryPatternsSources{
SourceText: fileContents,
Filename: filePath,
}
l.PrimaryPatternsSources = append(l.PrimaryPatternsSources, p)
primaryPattern := PrimaryPatterns{
Text: p.SourceText,
FileName: p.Filename,
}
l.PrimaryPatterns = append(l.PrimaryPatterns, &primaryPattern)
return nil
}
// GenerateMatchingPatternFromSourceText normalizes and compiles a pattern once with sync
func GenerateMatchingPatternFromSourceText(pp *PrimaryPatterns) (*regexp.Regexp, error) {
var err error
pp.doOnce.Do(func() {
// Normalize the input text.
normalizedData := normalizer.NewNormalizationData(pp.Text, true)
err = normalizedData.NormalizeText()
if err == nil {
var re *regexp.Regexp
re, err = GenerateRegexFromNormalizedText(normalizedData.NormalizedText)
if err == nil {
pp.re = re
pp.CaptureGroups = normalizedData.CaptureGroups
} else {
err = fmt.Errorf("cannot generate re: %v", err)
}
}
})
return pp.re, err
}
func GenerateRegexFromNormalizedText(normalizedText string) (*regexp.Regexp, error) {
// Eat optional single space before "<<" and after ">>" (just refactoring what was in regex)
text := spaceTagReplacer.Replace(normalizedText)
// Replace simple tags with tokens, so we can attack the not-simple tags which might be nested in these
text = tagReplacer.Replace(text)
// Replace matched <<segment>> with ` ?(?:(`+segment+`) ?)`
// Escape regex-unsafe characters outside of tags.
// Then put the segments back together
matches := pointyBracketSegmentRE.FindAllStringSubmatchIndex(text, -1)
var segments []string
prev := 0
for _, ii := range matches {
start := ii[0]
end := ii[1]
if start > prev {
// Handle pre-match characters
// Escape unsafe characters in the text elements.
segment := text[prev:start]
segment = RegexUnsafePattern.ReplaceAllString(segment, `\${1}`)
segments = append(segments, segment)
}
// Handle the sub-matched chars (inside the <<>>)
submatchStart := ii[2]
submatchEnd := ii[3]
segment := text[submatchStart:submatchEnd]
prev = end
segments = append(segments, ` *(?:(`+segment+`) *)`)
}
if prev < len(text) {
segment := text[prev:]
segment = RegexUnsafePattern.ReplaceAllString(segment, `\${1}`)
segments = append(segments, segment)
}
// Rejoin segments, replace tokens, compile, and return (*re, err)
text = strings.Join(segments, "")
text = tokenReplacer.Replace(text)
return regexp.Compile(text)
}
func List(config *viper.Viper) (lics []Detail, deprecatedLics []Detail, exceptions []Exception, deprecatedExceptions []Exception, spdxVersion string, err error) {
var ll *LicenseLibrary
ll, err = NewLicenseLibrary(config)
if err != nil {
return
}
err = ll.AddAll()
if err != nil {
return
}
spdxVersion = ll.SPDXVersion
lm := ll.LicenseMap
// Sort by key
keys := make([]string, 0, len(lm))
for key := range lm {
keys = append(keys, key)
}
sort.Strings(keys)
for _, k := range keys {
isException := lm[k].LicenseInfo.SPDXException
isDeprecated := lm[k].LicenseInfo.IsDeprecated
if isException { //nolint:nestif
e := Exception{
ID: lm[k].SPDXLicenseID,
Name: lm[k].LicenseInfo.Name,
Family: lm[k].LicenseInfo.Family,
NumTemplates: len(lm[k].PrimaryPatterns),
}
if isDeprecated {
deprecatedExceptions = append(deprecatedExceptions, e)
} else {
exceptions = append(exceptions, e)
}
} else {
l := Detail{
ID: lm[k].SPDXLicenseID,
Name: lm[k].LicenseInfo.Name,
Family: lm[k].LicenseInfo.Family,
IsOSIApproved: lm[k].LicenseInfo.OSIApproved,
IsFSFLibre: lm[k].LicenseInfo.IsFSFLibre,
NumTemplates: len(lm[k].PrimaryPatterns),
}
if isDeprecated {
deprecatedLics = append(deprecatedLics, l)
} else {
lics = append(lics, l)
}
}
}
return
}