blob: 5842f70633e0aec492947da61947021c200b6c60 [file] [log] [blame]
Dan Willemsen2902fa72017-04-27 21:16:35 -07001// Copyright 2017 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package main
16
17import (
18 "encoding/xml"
19 "flag"
20 "fmt"
Dan Willemsen2902fa72017-04-27 21:16:35 -070021 "io/ioutil"
22 "os"
23 "path/filepath"
24 "regexp"
25 "sort"
26 "strings"
27 "text/template"
28
29 "github.com/google/blueprint/proptools"
30)
31
32type RewriteNames []RewriteName
33type RewriteName struct {
34 regexp *regexp.Regexp
35 repl string
36}
37
38func (r *RewriteNames) String() string {
39 return ""
40}
41
42func (r *RewriteNames) Set(v string) error {
43 split := strings.SplitN(v, "=", 2)
44 if len(split) != 2 {
45 return fmt.Errorf("Must be in the form of <regex>=<replace>")
46 }
47 regex, err := regexp.Compile(split[0])
48 if err != nil {
49 return nil
50 }
51 *r = append(*r, RewriteName{
52 regexp: regex,
53 repl: split[1],
54 })
55 return nil
56}
57
Alan Viverette75b95f82017-12-04 16:24:07 -050058func (r *RewriteNames) MavenToMk(groupId string, artifactId string) string {
Dan Willemsen2902fa72017-04-27 21:16:35 -070059 for _, r := range *r {
Alan Viverette75b95f82017-12-04 16:24:07 -050060 if r.regexp.MatchString(groupId + ":" + artifactId) {
61 return r.regexp.ReplaceAllString(groupId+":"+artifactId, r.repl)
62 } else if r.regexp.MatchString(artifactId) {
63 return r.regexp.ReplaceAllString(artifactId, r.repl)
Dan Willemsen2902fa72017-04-27 21:16:35 -070064 }
65 }
Alan Viverette75b95f82017-12-04 16:24:07 -050066 return artifactId
Dan Willemsen2902fa72017-04-27 21:16:35 -070067}
68
69var rewriteNames = RewriteNames{}
70
71type ExtraDeps map[string][]string
72
73func (d ExtraDeps) String() string {
74 return ""
75}
76
77func (d ExtraDeps) Set(v string) error {
78 split := strings.SplitN(v, "=", 2)
79 if len(split) != 2 {
80 return fmt.Errorf("Must be in the form of <module>=<module>[,<module>]")
81 }
82 d[split[0]] = strings.Split(split[1], ",")
83 return nil
84}
85
86var extraDeps = make(ExtraDeps)
87
Dan Willemsen15a8e792017-11-10 14:02:44 -080088var sdkVersion string
Dan Willemsen47e44a42017-10-05 13:28:16 -070089var useVersion string
Alan Viverette1593d3d2017-12-11 17:14:26 -050090var staticDeps bool
Dan Willemsen47e44a42017-10-05 13:28:16 -070091
Jeff Gaston8f084822018-03-29 14:58:50 -040092func InList(s string, list []string) bool {
93 for _, l := range list {
94 if l == s {
95 return true
96 }
97 }
98
99 return false
100}
101
Dan Willemsen2902fa72017-04-27 21:16:35 -0700102type Dependency struct {
103 XMLName xml.Name `xml:"dependency"`
104
Alan Viverette1593d3d2017-12-11 17:14:26 -0500105 MakeTarget string `xml:"-"`
106
Dan Willemsen2902fa72017-04-27 21:16:35 -0700107 GroupId string `xml:"groupId"`
108 ArtifactId string `xml:"artifactId"`
109 Version string `xml:"version"`
110 Type string `xml:"type"`
Alan Viverette6bd35eb2018-02-13 13:25:24 -0500111 Scope string `xml:"scope"`
Dan Willemsen2902fa72017-04-27 21:16:35 -0700112}
113
Alan Viverette1593d3d2017-12-11 17:14:26 -0500114func (d Dependency) MkName() string {
115 if d.MakeTarget == "" {
116 d.MakeTarget = rewriteNames.MavenToMk(d.GroupId, d.ArtifactId)
117 }
118 return d.MakeTarget
119}
120
Dan Willemsen2902fa72017-04-27 21:16:35 -0700121type Pom struct {
122 XMLName xml.Name `xml:"http://maven.apache.org/POM/4.0.0 project"`
123
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700124 PomFile string `xml:"-"`
Dan Willemsen2902fa72017-04-27 21:16:35 -0700125 ArtifactFile string `xml:"-"`
Alan Viverette75b95f82017-12-04 16:24:07 -0500126 MakeTarget string `xml:"-"`
Dan Willemsen2902fa72017-04-27 21:16:35 -0700127
128 GroupId string `xml:"groupId"`
129 ArtifactId string `xml:"artifactId"`
130 Version string `xml:"version"`
131 Packaging string `xml:"packaging"`
132
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700133 Dependencies []*Dependency `xml:"dependencies>dependency"`
Dan Willemsen2902fa72017-04-27 21:16:35 -0700134}
135
Alan Viverette1593d3d2017-12-11 17:14:26 -0500136func (p Pom) IsAar() bool {
137 return p.Packaging == "aar"
138}
139
140func (p Pom) IsJar() bool {
141 return p.Packaging == "jar"
142}
143
Dan Willemsen2902fa72017-04-27 21:16:35 -0700144func (p Pom) MkName() string {
Alan Viverette75b95f82017-12-04 16:24:07 -0500145 if p.MakeTarget == "" {
146 p.MakeTarget = rewriteNames.MavenToMk(p.GroupId, p.ArtifactId)
147 }
148 return p.MakeTarget
Dan Willemsen2902fa72017-04-27 21:16:35 -0700149}
150
Alan Viverette1593d3d2017-12-11 17:14:26 -0500151func (p Pom) MkJarDeps() []string {
Jeff Gaston8f084822018-03-29 14:58:50 -0400152 return p.MkDeps("jar", []string{"compile", "runtime"})
Alan Viverette1593d3d2017-12-11 17:14:26 -0500153}
154
155func (p Pom) MkAarDeps() []string {
Jeff Gaston8f084822018-03-29 14:58:50 -0400156 return p.MkDeps("aar", []string{"compile", "runtime"})
Alan Viverette1593d3d2017-12-11 17:14:26 -0500157}
158
Alan Viverette6bd35eb2018-02-13 13:25:24 -0500159// MkDeps obtains dependencies filtered by type and scope. The results of this
160// method are formatted as Make targets, e.g. run through MavenToMk rules.
Jeff Gaston8f084822018-03-29 14:58:50 -0400161func (p Pom) MkDeps(typeExt string, scopes []string) []string {
Dan Willemsen2902fa72017-04-27 21:16:35 -0700162 var ret []string
163 for _, d := range p.Dependencies {
Jeff Gaston8f084822018-03-29 14:58:50 -0400164 if d.Type != typeExt || !InList(d.Scope, scopes) {
Dan Willemsen2902fa72017-04-27 21:16:35 -0700165 continue
166 }
Alan Viverette75b95f82017-12-04 16:24:07 -0500167 name := rewriteNames.MavenToMk(d.GroupId, d.ArtifactId)
Dan Willemsen2902fa72017-04-27 21:16:35 -0700168 ret = append(ret, name)
169 ret = append(ret, extraDeps[name]...)
170 }
171 return ret
172}
173
Dan Willemsen15a8e792017-11-10 14:02:44 -0800174func (p Pom) SdkVersion() string {
175 return sdkVersion
176}
177
Alan Viverette6bd35eb2018-02-13 13:25:24 -0500178func (p *Pom) FixDeps(modules map[string]*Pom) {
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700179 for _, d := range p.Dependencies {
Alan Viverette6bd35eb2018-02-13 13:25:24 -0500180 if d.Type == "" {
181 if depPom, ok := modules[d.MkName()]; ok {
182 // We've seen the POM for this dependency, use its packaging
183 // as the dependency type rather than Maven spec default.
184 d.Type = depPom.Packaging
185 } else {
186 // Dependency type was not specified and we don't have the POM
187 // for this artifact, use the default from Maven spec.
188 d.Type = "jar"
189 }
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700190 }
Alan Viverette6bd35eb2018-02-13 13:25:24 -0500191 if d.Scope == "" {
192 // Scope was not specified, use the default from Maven spec.
193 d.Scope = "compile"
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700194 }
195 }
196}
197
Dan Willemsen2902fa72017-04-27 21:16:35 -0700198var mkTemplate = template.Must(template.New("mk").Parse(`
199include $(CLEAR_VARS)
200LOCAL_MODULE := {{.MkName}}
201LOCAL_MODULE_CLASS := JAVA_LIBRARIES
202LOCAL_UNINSTALLABLE_MODULE := true
203LOCAL_SRC_FILES := {{.ArtifactFile}}
204LOCAL_BUILT_MODULE_STEM := javalib.jar
205LOCAL_MODULE_SUFFIX := .{{.Packaging}}
206LOCAL_USE_AAPT2 := true
Dan Willemsen15a8e792017-11-10 14:02:44 -0800207LOCAL_SDK_VERSION := {{.SdkVersion}}
Alan Viverette2b53a0c2018-03-28 10:32:10 -0400208LOCAL_STATIC_JAVA_LIBRARIES :={{range .MkJarDeps}} \
209 {{.}}{{end}}
210LOCAL_STATIC_ANDROID_LIBRARIES :={{range .MkAarDeps}} \
211 {{.}}{{end}}
Dan Willemsen2902fa72017-04-27 21:16:35 -0700212include $(BUILD_PREBUILT)
213`))
214
Alan Viverette1593d3d2017-12-11 17:14:26 -0500215var mkDepsTemplate = template.Must(template.New("mk").Parse(`
216include $(CLEAR_VARS)
217LOCAL_MODULE := {{.MkName}}-nodeps
218LOCAL_MODULE_CLASS := JAVA_LIBRARIES
219LOCAL_UNINSTALLABLE_MODULE := true
220LOCAL_SRC_FILES := {{.ArtifactFile}}
221LOCAL_BUILT_MODULE_STEM := javalib.jar
222LOCAL_MODULE_SUFFIX := .{{.Packaging}}
223LOCAL_USE_AAPT2 := true
224LOCAL_SDK_VERSION := {{.SdkVersion}}
225LOCAL_STATIC_ANDROID_LIBRARIES :={{range .MkAarDeps}} \
226 {{.}}{{end}}
227include $(BUILD_PREBUILT)
228include $(CLEAR_VARS)
229LOCAL_MODULE := {{.MkName}}
230LOCAL_SDK_VERSION := {{.SdkVersion}}{{if .IsAar}}
231LOCAL_MANIFEST_FILE := manifests/{{.MkName}}/AndroidManifest.xml{{end}}
232LOCAL_STATIC_JAVA_LIBRARIES :={{if .IsJar}} \
233 {{.MkName}}-nodeps{{end}}{{range .MkJarDeps}} \
234 {{.}}{{end}}
235LOCAL_STATIC_ANDROID_LIBRARIES :={{if .IsAar}} \
236 {{.MkName}}-nodeps{{end}}{{range .MkAarDeps}} \
237 {{.}}{{end}}
238LOCAL_JAR_EXCLUDE_FILES := none
239LOCAL_JAVA_LANGUAGE_VERSION := 1.7
240LOCAL_USE_AAPT2 := true
241include $(BUILD_STATIC_JAVA_LIBRARY)
242`))
243
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700244func parse(filename string) (*Pom, error) {
Dan Willemsen2902fa72017-04-27 21:16:35 -0700245 data, err := ioutil.ReadFile(filename)
246 if err != nil {
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700247 return nil, err
Dan Willemsen2902fa72017-04-27 21:16:35 -0700248 }
249
250 var pom Pom
251 err = xml.Unmarshal(data, &pom)
252 if err != nil {
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700253 return nil, err
Dan Willemsen2902fa72017-04-27 21:16:35 -0700254 }
255
Dan Willemsen47e44a42017-10-05 13:28:16 -0700256 if useVersion != "" && pom.Version != useVersion {
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700257 return nil, nil
Dan Willemsen47e44a42017-10-05 13:28:16 -0700258 }
259
Dan Willemsen2902fa72017-04-27 21:16:35 -0700260 if pom.Packaging == "" {
261 pom.Packaging = "jar"
262 }
263
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700264 pom.PomFile = filename
Dan Willemsen2902fa72017-04-27 21:16:35 -0700265 pom.ArtifactFile = strings.TrimSuffix(filename, ".pom") + "." + pom.Packaging
266
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700267 return &pom, nil
Dan Willemsen2902fa72017-04-27 21:16:35 -0700268}
269
270func main() {
271 flag.Usage = func() {
272 fmt.Fprintf(os.Stderr, `pom2mk, a tool to create Android.mk files from maven repos
273
274The tool will extract the necessary information from *.pom files to create an Android.mk whose
275aar libraries can be linked against when using AAPT2.
276
277Usage: %s [--rewrite <regex>=<replace>] [--extra-deps <module>=<module>[,<module>]] <dir>
278
279 -rewrite <regex>=<replace>
Alan Viverette75b95f82017-12-04 16:24:07 -0500280 rewrite can be used to specify mappings between Maven projects and Make modules. The -rewrite
281 option can be specified multiple times. When determining the Make module for a given Maven
282 project, mappings are searched in the order they were specified. The first <regex> matching
283 either the Maven project's <groupId>:<artifactId> or <artifactId> will be used to generate
284 the Make module name using <replace>. If no matches are found, <artifactId> is used.
Dan Willemsen2902fa72017-04-27 21:16:35 -0700285 -extra-deps <module>=<module>[,<module>]
286 Some Android.mk modules have transitive dependencies that must be specified when they are
287 depended upon (like android-support-v7-mediarouter requires android-support-v7-appcompat).
288 This may be specified multiple times to declare these dependencies.
Dan Willemsen15a8e792017-11-10 14:02:44 -0800289 -sdk-version <version>
290 Sets LOCAL_SDK_VERSION := <version> for all modules.
Dan Willemsen47e44a42017-10-05 13:28:16 -0700291 -use-version <version>
292 If the maven directory contains multiple versions of artifacts and their pom files,
293 -use-version can be used to only write makefiles for a specific version of those artifacts.
Alan Viverette1593d3d2017-12-11 17:14:26 -0500294 -static-deps
295 Whether to statically include direct dependencies.
Dan Willemsen2902fa72017-04-27 21:16:35 -0700296 <dir>
297 The directory to search for *.pom files under.
298
299The makefile is written to stdout, to be put in the current directory (often as Android.mk)
300`, os.Args[0])
301 }
302
303 flag.Var(&extraDeps, "extra-deps", "Extra dependencies needed when depending on a module")
304 flag.Var(&rewriteNames, "rewrite", "Regex(es) to rewrite artifact names")
Dan Willemsen15a8e792017-11-10 14:02:44 -0800305 flag.StringVar(&sdkVersion, "sdk-version", "", "What to write to LOCAL_SDK_VERSION")
Dan Willemsen47e44a42017-10-05 13:28:16 -0700306 flag.StringVar(&useVersion, "use-version", "", "Only read artifacts of a specific version")
Alan Viverette1593d3d2017-12-11 17:14:26 -0500307 flag.BoolVar(&staticDeps, "static-deps", false, "Statically include direct dependencies")
Dan Willemsen2902fa72017-04-27 21:16:35 -0700308 flag.Parse()
309
310 if flag.NArg() != 1 {
311 flag.Usage()
312 os.Exit(1)
313 }
314
315 dir := flag.Arg(0)
316 absDir, err := filepath.Abs(dir)
317 if err != nil {
Colin Crossf46e37f2018-03-21 16:25:58 -0700318 fmt.Fprintln(os.Stderr, "Failed to get absolute directory:", err)
Dan Willemsen2902fa72017-04-27 21:16:35 -0700319 os.Exit(1)
320 }
321
322 var filenames []string
323 err = filepath.Walk(absDir, func(path string, info os.FileInfo, err error) error {
324 if err != nil {
325 return err
326 }
327
328 name := info.Name()
329 if info.IsDir() {
330 if strings.HasPrefix(name, ".") {
331 return filepath.SkipDir
332 }
333 return nil
334 }
335
336 if strings.HasPrefix(name, ".") {
337 return nil
338 }
339
340 if strings.HasSuffix(name, ".pom") {
341 path, err = filepath.Rel(absDir, path)
342 if err != nil {
343 return err
344 }
345 filenames = append(filenames, filepath.Join(dir, path))
346 }
347 return nil
348 })
349 if err != nil {
350 fmt.Fprintln(os.Stderr, "Error walking files:", err)
351 os.Exit(1)
352 }
353
354 if len(filenames) == 0 {
355 fmt.Fprintln(os.Stderr, "Error: no *.pom files found under", dir)
356 os.Exit(1)
357 }
358
359 sort.Strings(filenames)
360
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700361 poms := []*Pom{}
362 modules := make(map[string]*Pom)
363 for _, filename := range filenames {
364 pom, err := parse(filename)
365 if err != nil {
366 fmt.Fprintln(os.Stderr, "Error converting", filename, err)
367 os.Exit(1)
368 }
369
370 if pom != nil {
371 poms = append(poms, pom)
Alan Viverette75b95f82017-12-04 16:24:07 -0500372 key := pom.MkName()
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700373
Alan Viverette75b95f82017-12-04 16:24:07 -0500374 if old, ok := modules[key]; ok {
375 fmt.Fprintln(os.Stderr, "Module", key, "defined twice:", old.PomFile, pom.PomFile)
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700376 }
377
Alan Viverette75b95f82017-12-04 16:24:07 -0500378 modules[key] = pom
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700379 }
380 }
381
382 for _, pom := range poms {
Alan Viverette6bd35eb2018-02-13 13:25:24 -0500383 pom.FixDeps(modules)
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700384 }
385
Dan Willemsen2902fa72017-04-27 21:16:35 -0700386 fmt.Println("# Automatically generated with:")
387 fmt.Println("# pom2mk", strings.Join(proptools.ShellEscape(os.Args[1:]), " "))
388 fmt.Println("LOCAL_PATH := $(call my-dir)")
389
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700390 for _, pom := range poms {
Alan Viverette1593d3d2017-12-11 17:14:26 -0500391 var err error
392 if staticDeps {
393 err = mkDepsTemplate.Execute(os.Stdout, pom)
394 } else {
395 err = mkTemplate.Execute(os.Stdout, pom)
396 }
Dan Willemsen2902fa72017-04-27 21:16:35 -0700397 if err != nil {
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700398 fmt.Fprintln(os.Stderr, "Error writing", pom.PomFile, pom.MkName(), err)
Dan Willemsen2902fa72017-04-27 21:16:35 -0700399 os.Exit(1)
400 }
401 }
402}