From 2ccf308e1bb0e98946dd336ea77bc7144da1b289 Mon Sep 17 00:00:00 2001 From: "Stanislav N. aka pztrn" Date: Sat, 8 Feb 2020 12:51:42 +0500 Subject: [PATCH] Get copyrights from license file. --- outputters/csv/csv.go | 3 ++- projecter/project.go | 32 +++++++++++++++++++++++++++++++- structs/license.go | 2 +- 3 files changed, 34 insertions(+), 3 deletions(-) diff --git a/outputters/csv/csv.go b/outputters/csv/csv.go index e974a62..5d1e020 100644 --- a/outputters/csv/csv.go +++ b/outputters/csv/csv.go @@ -6,6 +6,7 @@ import ( "log" "os" "strconv" + "strings" // local "go.dev.pztrn.name/glp/structs" @@ -40,7 +41,7 @@ func (o *outputter) Write(deps []*structs.Dependency, outFile string) { // Write dependencies information. for _, dep := range deps { - _ = writer.Write([]string{dep.Name, dep.Version, dep.License.Name, dep.VCS.VCSPath, dep.License.URL, dep.Parent, dep.License.Copyrights}) + _ = writer.Write([]string{dep.Name, dep.Version, dep.License.Name, dep.VCS.VCSPath, dep.License.URL, dep.Parent, strings.Join(dep.License.Copyrights, ",")}) } writer.Flush() diff --git a/projecter/project.go b/projecter/project.go index 8b15322..7e22c38 100644 --- a/projecter/project.go +++ b/projecter/project.go @@ -2,6 +2,7 @@ package projecter import ( // stdlib + "bufio" "log" "os" "path/filepath" @@ -63,6 +64,31 @@ func (p *Project) initialize(packagePath string) { } } +// Parses license file for copyrights. +func (p *Project) parseLicenseForCopyrights(licencePath string) []string { + f, err := os.Open(licencePath) + if err != nil { + log.Println("Failed to open license file for reading:", err.Error()) + return nil + } + + var copyrights []string + + // Read file data line by line. + gosum := bufio.NewScanner(f) + gosum.Split(bufio.ScanLines) + + for gosum.Scan() { + line := gosum.Text() + + if strings.HasPrefix(strings.ToLower(line), "copyright ") && !strings.Contains(strings.ToLower(line), "notice") { + copyrights = append(copyrights, line) + } + } + + return copyrights +} + // Starts project parsing. func (p *Project) process() { // We should determine project type. @@ -137,8 +163,12 @@ func (p *Project) process() { dep.License.Name = licenseName - // Generate license path. + // Generate license URL. urlFormatter := strings.NewReplacer("{dir}", "", "{/dir}", "", "{file}", licenseFile, "{/file}", licenseFile, "#L{line}", "") dep.License.URL = urlFormatter.Replace(dep.VCS.SourceURLFileTemplate) + + // As we should have dependency locally available we should try + // to parse license file to get copyrights. + dep.License.Copyrights = p.parseLicenseForCopyrights(filepath.Join(dep.LocalPath, licenseFile)) } } diff --git a/structs/license.go b/structs/license.go index 1f772d0..4b9c27d 100644 --- a/structs/license.go +++ b/structs/license.go @@ -1,7 +1,7 @@ package structs type License struct { - Copyrights string + Copyrights []string Name string URL string }