-
Notifications
You must be signed in to change notification settings - Fork 0
/
jar.go
90 lines (64 loc) · 2.11 KB
/
jar.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
package jar
// ////////////////////////////////////////////////////////////////////////////////// //
// //
// Copyright (c) 2022 ESSENTIAL KAOS //
// Apache License, Version 2.0 <https://www.apache.org/licenses/LICENSE-2.0> //
// //
// ////////////////////////////////////////////////////////////////////////////////// //
import (
"archive/zip"
"bufio"
"errors"
"io"
"strings"
)
// ////////////////////////////////////////////////////////////////////////////////// //
type Manifest map[string]string
// ////////////////////////////////////////////////////////////////////////////////// //
var ErrNotJAR = errors.New("Given file is not a JAR file")
var ErrWrongManifestFormat = errors.New("Can't parse manifest file (wrong format)")
// ////////////////////////////////////////////////////////////////////////////////// //
// ReadFile reads JAR file and parses manifest file
func ReadFile(jarFile string) (Manifest, error) {
r, err := zip.OpenReader(jarFile)
if err != nil {
return nil, err
}
defer r.Close()
for _, f := range r.File {
if f.Name != "META-INF/MANIFEST.MF" {
continue
}
rc, err := f.Open()
if err != nil {
return nil, err
}
return readManifestData(rc)
}
return nil, ErrNotJAR
}
// ////////////////////////////////////////////////////////////////////////////////// //
// readManifestData reads manifest data
func readManifestData(r io.Reader) (Manifest, error) {
m := make(Manifest)
s := bufio.NewScanner(r)
var propName, propVal string
for s.Scan() {
text := s.Text()
if len(text) == 0 {
continue
}
if strings.HasPrefix(text, " ") {
m[propName] += strings.TrimLeft(text, " ")
continue
}
propSepIndex := strings.Index(text, ": ")
if propSepIndex == -1 || len(text) < propSepIndex+2 {
return nil, ErrWrongManifestFormat
}
propName = text[:propSepIndex]
propVal = text[propSepIndex+2:]
m[propName] = propVal
}
return m, nil
}