/
lockfile.go
57 lines (49 loc) · 1.43 KB
/
lockfile.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
package lockfile
import (
"bytes"
"fmt"
"io"
"os"
"path/filepath"
"deps.dev/util/resolve"
"github.com/google/osv-scanner/pkg/lockfile"
)
type DependencyPatch struct {
Pkg resolve.PackageKey
OrigVersion string
NewVersion string
}
type LockfileIO interface {
// Read parses a lockfile into a resolved graph
Read(file lockfile.DepFile) (*resolve.Graph, error)
// Write applies the DependencyPatches to the lockfile, with minimal changes to the file.
// `original` is the original lockfile to read from. The updated lockfile is written to `output`.
Write(original lockfile.DepFile, output io.Writer, patches []DependencyPatch) error
}
func Overwrite(rw LockfileIO, filename string, patches []DependencyPatch) error {
r, err := lockfile.OpenLocalDepFile(filename)
if err != nil {
return err
}
var buf bytes.Buffer
err = rw.Write(r, &buf, patches)
r.Close() // Make sure the file is closed before we start writing to it.
if err != nil {
return err
}
//nolint:gosec // Complaining about the 0644 permissions.
// The file already exists anyway so the permissions don't matter.
if err := os.WriteFile(filename, buf.Bytes(), 0644); err != nil {
return err
}
return nil
}
func GetLockfileIO(pathToLockfile string) (LockfileIO, error) {
base := filepath.Base(pathToLockfile)
switch {
case base == "package-lock.json":
return NpmLockfileIO{}, nil
default:
return nil, fmt.Errorf("unsupported lockfile type: %s", base)
}
}