2022-12-02 02:08:48 +03:00
|
|
|
// Copyright 2021 OpenSSF Scorecard Authors
|
2021-06-09 02:55:43 +03:00
|
|
|
//
|
|
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
// you may not use this file except in compliance with the License.
|
|
|
|
// You may obtain a copy of the License at
|
|
|
|
//
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
//
|
|
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
// See the License for the specific language governing permissions and
|
|
|
|
// limitations under the License.
|
|
|
|
|
|
|
|
package data
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/csv"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"sort"
|
|
|
|
|
|
|
|
"github.com/jszwec/csvutil"
|
|
|
|
)
|
|
|
|
|
2021-11-18 20:04:07 +03:00
|
|
|
// WriteTo writes `repos` to `out`.
|
|
|
|
func WriteTo(out io.Writer, repos []RepoFormat) error {
|
|
|
|
csvWriter := csv.NewWriter(out)
|
|
|
|
enc := csvutil.NewEncoder(csvWriter)
|
|
|
|
if err := enc.Encode(repos); err != nil {
|
|
|
|
return fmt.Errorf("error during Encode: %w", err)
|
|
|
|
}
|
|
|
|
csvWriter.Flush()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-08-01 01:31:34 +03:00
|
|
|
// SortAndAppendTo appends `oldRepos` and `newRepos` before sorting and writing out the result to `out`.
|
2021-10-29 19:07:46 +03:00
|
|
|
func SortAndAppendTo(out io.Writer, oldRepos, newRepos []RepoFormat) error {
|
|
|
|
oldRepos = append(oldRepos, newRepos...)
|
2021-06-10 23:24:33 +03:00
|
|
|
|
2021-10-29 19:07:46 +03:00
|
|
|
sort.SliceStable(oldRepos, func(i, j int) bool {
|
|
|
|
return oldRepos[i].Repo < oldRepos[j].Repo
|
2021-06-10 23:24:33 +03:00
|
|
|
})
|
2021-11-18 20:04:07 +03:00
|
|
|
return WriteTo(out, oldRepos)
|
2021-06-10 23:24:33 +03:00
|
|
|
}
|
|
|
|
|
2021-08-01 01:31:34 +03:00
|
|
|
// SortAndAppendFrom reads from `in`, appends to newRepos and writes the sorted output to `out`.
|
2021-10-29 19:07:46 +03:00
|
|
|
func SortAndAppendFrom(in io.Reader, out io.Writer, newRepos []RepoFormat) error {
|
2021-07-19 03:33:45 +03:00
|
|
|
iter, err := MakeIteratorFrom(in)
|
2021-06-09 02:55:43 +03:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("error during MakeIterator: %w", err)
|
|
|
|
}
|
|
|
|
|
2021-10-29 19:07:46 +03:00
|
|
|
oldRepos := make([]RepoFormat, 0)
|
2021-06-09 02:55:43 +03:00
|
|
|
for iter.HasNext() {
|
|
|
|
repo, err := iter.Next()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("error during iter.Next: %w", err)
|
|
|
|
}
|
2021-06-10 23:24:33 +03:00
|
|
|
oldRepos = append(oldRepos, repo)
|
2021-06-09 02:55:43 +03:00
|
|
|
}
|
2021-06-10 23:24:33 +03:00
|
|
|
return SortAndAppendTo(out, oldRepos, newRepos)
|
2021-06-09 02:55:43 +03:00
|
|
|
}
|