/
maven_command.go
269 lines (222 loc) · 6.67 KB
/
maven_command.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
/*
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You 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 maven
import (
"bufio"
"context"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path"
"regexp"
"strings"
"github.com/pkg/errors"
"github.com/apache/camel-k/pkg/util"
"github.com/apache/camel-k/pkg/util/log"
)
var Log = log.WithName("maven")
type Command struct {
context Context
project Project
}
func (c *Command) Do(ctx context.Context) error {
if err := generateProjectStructure(c.context, c.project); err != nil {
return err
}
mvnCmd := "mvn"
if c, ok := os.LookupEnv("MAVEN_CMD"); ok {
mvnCmd = c
}
args := make([]string, 0)
args = append(args, "--batch-mode")
if c.context.LocalRepository == "" {
args = append(args, "-Dcamel.noop=true")
} else if _, err := os.Stat(c.context.LocalRepository); err == nil {
args = append(args, "-Dmaven.repo.local="+c.context.LocalRepository)
}
settingsPath := path.Join(c.context.Path, "settings.xml")
settingsExists, err := util.FileExists(settingsPath)
if err != nil {
return err
}
if settingsExists {
args = append(args, "--settings", settingsPath)
}
args = append(args, c.context.AdditionalArguments...)
cmd := exec.CommandContext(ctx, mvnCmd, args...)
cmd.Dir = c.context.Path
var mavenOptions string
if len(c.context.ExtraMavenOpts) > 0 {
// Inherit the parent process environment
env := os.Environ()
mavenOpts, ok := os.LookupEnv("MAVEN_OPTS")
if !ok {
mavenOptions = strings.Join(c.context.ExtraMavenOpts, " ")
env = append(env, "MAVEN_OPTS="+mavenOptions)
} else {
var extraOptions []string
options := strings.Fields(mavenOpts)
for _, extraOption := range c.context.ExtraMavenOpts {
// Basic duplicated key detection, that should be improved
// to support a wider range of JVM options
key := strings.SplitN(extraOption, "=", 2)[0]
exists := false
for _, opt := range options {
if strings.HasPrefix(opt, key) {
exists = true
break
}
}
if !exists {
extraOptions = append(extraOptions, extraOption)
}
}
options = append(options, extraOptions...)
mavenOptions = strings.Join(options, " ")
for i, e := range env {
if strings.HasPrefix(e, "MAVEN_OPTS=") {
env[i] = "MAVEN_OPTS=" + mavenOptions
break
}
}
}
cmd.Env = env
}
Log.WithValues("MAVEN_OPTS", mavenOptions).Infof("executing: %s", strings.Join(cmd.Args, " "))
stdOut, err := cmd.StdoutPipe()
if err != nil {
return nil
}
err = cmd.Start()
if err != nil {
return err
}
scanner := bufio.NewScanner(stdOut)
Log.Debug("About to start parsing the Maven output")
for scanner.Scan() {
line := scanner.Text()
mavenLog, parseError := parseLog(line)
if parseError == nil {
normalizeLog(mavenLog)
} else {
// Why we are ignoring the parsing errors here: there are a few scenarios where this would likely occur.
// For example, if something outside of Maven outputs something (i.e.: the JDK, a misbehaved plugin,
// etc). The build may still have succeeded, though.
nonNormalizedLog(line)
}
}
Log.Debug("Finished parsing Maven output")
return cmd.Wait()
}
func NewContext(buildDir string) Context {
return Context{
Path: buildDir,
AdditionalArguments: make([]string, 0),
AdditionalEntries: make(map[string]interface{}),
}
}
type Context struct {
Path string
// Project Project
ExtraMavenOpts []string
SettingsContent []byte
AdditionalArguments []string
AdditionalEntries map[string]interface{}
// Timeout time.Duration
LocalRepository string
// Stdout io.Writer
}
func (c *Context) AddEntry(id string, entry interface{}) {
if c.AdditionalEntries == nil {
c.AdditionalEntries = make(map[string]interface{})
}
c.AdditionalEntries[id] = entry
}
func (c *Context) AddArgument(argument string) {
c.AdditionalArguments = append(c.AdditionalArguments, argument)
}
func (c *Context) AddArgumentf(format string, args ...interface{}) {
c.AdditionalArguments = append(c.AdditionalArguments, fmt.Sprintf(format, args...))
}
func (c *Context) AddArguments(arguments ...string) {
c.AdditionalArguments = append(c.AdditionalArguments, arguments...)
}
func (c *Context) AddSystemProperty(name string, value string) {
c.AddArgumentf("-D%s=%s", name, value)
}
func generateProjectStructure(context Context, project Project) error {
if err := util.WriteFileWithBytesMarshallerContent(context.Path, "pom.xml", project); err != nil {
return err
}
if context.SettingsContent != nil {
if err := util.WriteFileWithContent(context.Path, "settings.xml", context.SettingsContent); err != nil {
return err
}
}
for k, v := range context.AdditionalEntries {
var bytes []byte
var err error
if dc, ok := v.([]byte); ok {
bytes = dc
} else if dc, ok := v.(io.Reader); ok {
bytes, err = ioutil.ReadAll(dc)
if err != nil {
return err
}
} else {
return fmt.Errorf("unknown content type: name=%s, content=%+v", k, v)
}
if len(bytes) > 0 {
Log.Infof("write entry: %s (%d bytes)", k, len(bytes))
err = util.WriteFileWithContent(context.Path, k, bytes)
if err != nil {
return err
}
}
}
return nil
}
// ParseGAV decodes the provided Maven GAV into the corresponding Dependency.
//
// The artifact id is in the form of:
//
// <groupId>:<artifactId>[:<packagingType>[:<classifier>]]:(<version>|'?')
//
func ParseGAV(gav string) (Dependency, error) {
// <groupId>:<artifactId>[:<packagingType>[:<classifier>]]:(<version>|'?')
dep := Dependency{}
rex := regexp.MustCompile("([^: ]+):([^: ]+)(:([^: ]*)(:([^: ]+))?)?(:([^: ]+))?")
res := rex.FindStringSubmatch(gav)
if res == nil || len(res) < 9 {
return Dependency{}, errors.New("GAV must match <groupId>:<artifactId>[:<packagingType>[:<classifier>]]:(<version>|'?')")
}
dep.GroupID = res[1]
dep.ArtifactID = res[2]
cnt := strings.Count(gav, ":")
switch cnt {
case 2:
dep.Version = res[4]
case 3:
dep.Type = res[4]
dep.Version = res[6]
default:
dep.Type = res[4]
dep.Classifier = res[6]
dep.Version = res[8]
}
return dep, nil
}