-
Notifications
You must be signed in to change notification settings - Fork 350
/
maven_command.go
312 lines (263 loc) · 8.58 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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
/*
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 (
"context"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"github.com/apache/camel-k/v2/pkg/util"
"github.com/apache/camel-k/v2/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
}
if e, ok := os.LookupEnv("MAVEN_WRAPPER"); (ok && e == "true") || !ok {
// Prepare maven wrapper helps when running the builder as Pod as it makes
// the builder container, Maven agnostic
if err := c.prepareMavenWrapper(ctx); err != nil {
return err
}
}
mvnCmd := "./mvnw"
if c, ok := os.LookupEnv("MAVEN_CMD"); ok {
mvnCmd = c
}
args := make([]string, 0)
args = append(args, c.context.AdditionalArguments...)
if c.context.LocalRepository != "" {
if _, err := os.Stat(c.context.LocalRepository); err == nil {
args = append(args, "-Dmaven.repo.local="+c.context.LocalRepository)
}
}
settingsPath := filepath.Join(c.context.Path, "settings.xml")
if settingsExists, err := util.FileExists(settingsPath); err != nil {
return err
} else if settingsExists {
args = append(args, "--global-settings", settingsPath)
}
settingsPath = filepath.Join(c.context.Path, "user-settings.xml")
if settingsExists, err := util.FileExists(settingsPath); err != nil {
return err
} else if settingsExists {
args = append(args, "--settings", settingsPath)
}
settingsSecurityPath := filepath.Join(c.context.Path, "settings-security.xml")
if settingsSecurityExists, err := util.FileExists(settingsSecurityPath); err != nil {
return err
} else if settingsSecurityExists {
args = append(args, "-Dsettings.security="+settingsSecurityPath)
}
if !util.StringContainsPrefix(c.context.AdditionalArguments, "-Dmaven.artifact.threads") {
args = append(args, "-Dmaven.artifact.threads="+strconv.Itoa(runtime.GOMAXPROCS(0)))
}
if !util.StringSliceExists(c.context.AdditionalArguments, "-T") {
args = append(args, "-T", strconv.Itoa(runtime.GOMAXPROCS(0)))
}
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, " "))
// generate maven file
if err := generateMavenContext(c.context.Path, args, mavenOptions); err != nil {
return err
}
return util.RunAndLog(ctx, cmd, MavenLogHandler, MavenLogHandler)
}
func NewContext(buildDir string) Context {
return Context{
Path: buildDir,
AdditionalArguments: make([]string, 0),
AdditionalEntries: make(map[string]interface{}),
}
}
type Context struct {
Path string
ExtraMavenOpts []string
GlobalSettings []byte
UserSettings []byte
SettingsSecurity []byte
AdditionalArguments []string
AdditionalEntries map[string]interface{}
LocalRepository string
}
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.GlobalSettings != nil {
if err := util.WriteFileWithContent(filepath.Join(context.Path, "settings.xml"), context.GlobalSettings); err != nil {
return err
}
}
if context.UserSettings != nil {
if err := util.WriteFileWithContent(filepath.Join(context.Path, "user-settings.xml"), context.UserSettings); err != nil {
return err
}
}
if context.SettingsSecurity != nil {
if err := util.WriteFileWithContent(filepath.Join(context.Path, "settings-security.xml"), context.SettingsSecurity); 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 = io.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(filepath.Join(context.Path, k), bytes)
if err != nil {
return err
}
}
}
return nil
}
// We expect a maven wrapper under /usr/share/maven/mvnw.
func (c *Command) prepareMavenWrapper(ctx context.Context) error {
cmd := exec.CommandContext(ctx, "cp", "--recursive", "/usr/share/maven/mvnw/.", ".")
cmd.Dir = c.context.Path
return util.RunAndLog(ctx, cmd, MavenLogHandler, MavenLogHandler)
}
// ParseGAV decodes the provided Maven GAV into the corresponding Dependency.
//
// The artifact id is in the form of:
//
// <groupId>:<artifactId>[:<packagingType>]:(<version>)[:<classifier>]
func ParseGAV(gav string) (Dependency, error) {
dep := Dependency{}
res := strings.Split(gav, ":")
count := len(res)
if res == nil || count < 2 {
return Dependency{}, errors.New("GAV must match <groupId>:<artifactId>[:<packagingType>]:(<version>)[:<classifier>]")
}
dep.GroupID = res[0]
dep.ArtifactID = res[1]
switch {
case count == 3:
// gav is: org:artifact:<type:version>
numeric := regexp.MustCompile(`\d`)
if numeric.MatchString(res[2]) {
dep.Version = res[2]
} else {
dep.Type = res[2]
}
case count == 4:
// gav is: org:artifact:type:version
dep.Type = res[2]
dep.Version = res[3]
case count == 5:
// gav is: org:artifact:<type>:<version>:classifier
dep.Type = res[2]
dep.Version = res[3]
dep.Classifier = res[4]
}
return dep, nil
}
// Create a MAVEN_CONTEXT file containing all arguments for a maven command.
func generateMavenContext(path string, args []string, options string) error {
// TODO refactor maven code to avoid creating a file to pass command args
return util.WriteToFile(filepath.Join(path, "MAVEN_CONTEXT"), getMavenContext(args, options))
}
func getMavenContext(args []string, options string) string {
commandArgs := make([]string, 0)
for _, arg := range args {
if arg != "package" && len(strings.TrimSpace(arg)) != 0 {
commandArgs = append(commandArgs, strings.TrimSpace(arg))
}
}
mavenContext := strings.Join(commandArgs, " ")
if options != "" {
mavenContext += " " + options
}
return mavenContext
}