blob: 4fc484cd8a7b58b59142afc1fcfdaa0a9eacdfe5 [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
Dan Willemsen2902fa72017-04-27 21:16:35 -070092type Dependency struct {
93 XMLName xml.Name `xml:"dependency"`
94
Alan Viverette1593d3d2017-12-11 17:14:26 -050095 MakeTarget string `xml:"-"`
96
Dan Willemsen2902fa72017-04-27 21:16:35 -070097 GroupId string `xml:"groupId"`
98 ArtifactId string `xml:"artifactId"`
99 Version string `xml:"version"`
100 Type string `xml:"type"`
Alan Viverette6bd35eb2018-02-13 13:25:24 -0500101 Scope string `xml:"scope"`
Dan Willemsen2902fa72017-04-27 21:16:35 -0700102}
103
Alan Viverette1593d3d2017-12-11 17:14:26 -0500104func (d Dependency) MkName() string {
105 if d.MakeTarget == "" {
106 d.MakeTarget = rewriteNames.MavenToMk(d.GroupId, d.ArtifactId)
107 }
108 return d.MakeTarget
109}
110
Dan Willemsen2902fa72017-04-27 21:16:35 -0700111type Pom struct {
112 XMLName xml.Name `xml:"http://maven.apache.org/POM/4.0.0 project"`
113
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700114 PomFile string `xml:"-"`
Dan Willemsen2902fa72017-04-27 21:16:35 -0700115 ArtifactFile string `xml:"-"`
Alan Viverette75b95f82017-12-04 16:24:07 -0500116 MakeTarget string `xml:"-"`
Dan Willemsen2902fa72017-04-27 21:16:35 -0700117
118 GroupId string `xml:"groupId"`
119 ArtifactId string `xml:"artifactId"`
120 Version string `xml:"version"`
121 Packaging string `xml:"packaging"`
122
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700123 Dependencies []*Dependency `xml:"dependencies>dependency"`
Dan Willemsen2902fa72017-04-27 21:16:35 -0700124}
125
Alan Viverette1593d3d2017-12-11 17:14:26 -0500126func (p Pom) IsAar() bool {
127 return p.Packaging == "aar"
128}
129
130func (p Pom) IsJar() bool {
131 return p.Packaging == "jar"
132}
133
Dan Willemsen2902fa72017-04-27 21:16:35 -0700134func (p Pom) MkName() string {
Alan Viverette75b95f82017-12-04 16:24:07 -0500135 if p.MakeTarget == "" {
136 p.MakeTarget = rewriteNames.MavenToMk(p.GroupId, p.ArtifactId)
137 }
138 return p.MakeTarget
Dan Willemsen2902fa72017-04-27 21:16:35 -0700139}
140
Alan Viverette1593d3d2017-12-11 17:14:26 -0500141func (p Pom) MkJarDeps() []string {
Alan Viverette6bd35eb2018-02-13 13:25:24 -0500142 return p.MkDeps("jar", "compile")
Alan Viverette1593d3d2017-12-11 17:14:26 -0500143}
144
145func (p Pom) MkAarDeps() []string {
Alan Viverette6bd35eb2018-02-13 13:25:24 -0500146 return p.MkDeps("aar", "compile")
Alan Viverette1593d3d2017-12-11 17:14:26 -0500147}
148
Alan Viverette6bd35eb2018-02-13 13:25:24 -0500149// MkDeps obtains dependencies filtered by type and scope. The results of this
150// method are formatted as Make targets, e.g. run through MavenToMk rules.
151func (p Pom) MkDeps(typeExt string, scope string) []string {
Dan Willemsen2902fa72017-04-27 21:16:35 -0700152 var ret []string
153 for _, d := range p.Dependencies {
Alan Viverette6bd35eb2018-02-13 13:25:24 -0500154 if d.Type != typeExt || d.Scope != scope {
Dan Willemsen2902fa72017-04-27 21:16:35 -0700155 continue
156 }
Alan Viverette75b95f82017-12-04 16:24:07 -0500157 name := rewriteNames.MavenToMk(d.GroupId, d.ArtifactId)
Dan Willemsen2902fa72017-04-27 21:16:35 -0700158 ret = append(ret, name)
159 ret = append(ret, extraDeps[name]...)
160 }
161 return ret
162}
163
Dan Willemsen15a8e792017-11-10 14:02:44 -0800164func (p Pom) SdkVersion() string {
165 return sdkVersion
166}
167
Alan Viverette6bd35eb2018-02-13 13:25:24 -0500168func (p *Pom) FixDeps(modules map[string]*Pom) {
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700169 for _, d := range p.Dependencies {
Alan Viverette6bd35eb2018-02-13 13:25:24 -0500170 if d.Type == "" {
171 if depPom, ok := modules[d.MkName()]; ok {
172 // We've seen the POM for this dependency, use its packaging
173 // as the dependency type rather than Maven spec default.
174 d.Type = depPom.Packaging
175 } else {
176 // Dependency type was not specified and we don't have the POM
177 // for this artifact, use the default from Maven spec.
178 d.Type = "jar"
179 }
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700180 }
Alan Viverette6bd35eb2018-02-13 13:25:24 -0500181 if d.Scope == "" {
182 // Scope was not specified, use the default from Maven spec.
183 d.Scope = "compile"
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700184 }
185 }
186}
187
Dan Willemsen2902fa72017-04-27 21:16:35 -0700188var mkTemplate = template.Must(template.New("mk").Parse(`
189include $(CLEAR_VARS)
190LOCAL_MODULE := {{.MkName}}
191LOCAL_MODULE_CLASS := JAVA_LIBRARIES
192LOCAL_UNINSTALLABLE_MODULE := true
193LOCAL_SRC_FILES := {{.ArtifactFile}}
194LOCAL_BUILT_MODULE_STEM := javalib.jar
195LOCAL_MODULE_SUFFIX := .{{.Packaging}}
196LOCAL_USE_AAPT2 := true
Dan Willemsen15a8e792017-11-10 14:02:44 -0800197LOCAL_SDK_VERSION := {{.SdkVersion}}
Alan Viverette2b53a0c2018-03-28 10:32:10 -0400198LOCAL_STATIC_JAVA_LIBRARIES :={{range .MkJarDeps}} \
199 {{.}}{{end}}
200LOCAL_STATIC_ANDROID_LIBRARIES :={{range .MkAarDeps}} \
201 {{.}}{{end}}
Dan Willemsen2902fa72017-04-27 21:16:35 -0700202include $(BUILD_PREBUILT)
203`))
204
Alan Viverette1593d3d2017-12-11 17:14:26 -0500205var mkDepsTemplate = template.Must(template.New("mk").Parse(`
206include $(CLEAR_VARS)
207LOCAL_MODULE := {{.MkName}}-nodeps
208LOCAL_MODULE_CLASS := JAVA_LIBRARIES
209LOCAL_UNINSTALLABLE_MODULE := true
210LOCAL_SRC_FILES := {{.ArtifactFile}}
211LOCAL_BUILT_MODULE_STEM := javalib.jar
212LOCAL_MODULE_SUFFIX := .{{.Packaging}}
213LOCAL_USE_AAPT2 := true
214LOCAL_SDK_VERSION := {{.SdkVersion}}
215LOCAL_STATIC_ANDROID_LIBRARIES :={{range .MkAarDeps}} \
216 {{.}}{{end}}
217include $(BUILD_PREBUILT)
218include $(CLEAR_VARS)
219LOCAL_MODULE := {{.MkName}}
220LOCAL_SDK_VERSION := {{.SdkVersion}}{{if .IsAar}}
221LOCAL_MANIFEST_FILE := manifests/{{.MkName}}/AndroidManifest.xml{{end}}
222LOCAL_STATIC_JAVA_LIBRARIES :={{if .IsJar}} \
223 {{.MkName}}-nodeps{{end}}{{range .MkJarDeps}} \
224 {{.}}{{end}}
225LOCAL_STATIC_ANDROID_LIBRARIES :={{if .IsAar}} \
226 {{.MkName}}-nodeps{{end}}{{range .MkAarDeps}} \
227 {{.}}{{end}}
228LOCAL_JAR_EXCLUDE_FILES := none
229LOCAL_JAVA_LANGUAGE_VERSION := 1.7
230LOCAL_USE_AAPT2 := true
231include $(BUILD_STATIC_JAVA_LIBRARY)
232`))
233
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700234func parse(filename string) (*Pom, error) {
Dan Willemsen2902fa72017-04-27 21:16:35 -0700235 data, err := ioutil.ReadFile(filename)
236 if err != nil {
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700237 return nil, err
Dan Willemsen2902fa72017-04-27 21:16:35 -0700238 }
239
240 var pom Pom
241 err = xml.Unmarshal(data, &pom)
242 if err != nil {
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700243 return nil, err
Dan Willemsen2902fa72017-04-27 21:16:35 -0700244 }
245
Dan Willemsen47e44a42017-10-05 13:28:16 -0700246 if useVersion != "" && pom.Version != useVersion {
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700247 return nil, nil
Dan Willemsen47e44a42017-10-05 13:28:16 -0700248 }
249
Dan Willemsen2902fa72017-04-27 21:16:35 -0700250 if pom.Packaging == "" {
251 pom.Packaging = "jar"
252 }
253
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700254 pom.PomFile = filename
Dan Willemsen2902fa72017-04-27 21:16:35 -0700255 pom.ArtifactFile = strings.TrimSuffix(filename, ".pom") + "." + pom.Packaging
256
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700257 return &pom, nil
Dan Willemsen2902fa72017-04-27 21:16:35 -0700258}
259
260func main() {
261 flag.Usage = func() {
262 fmt.Fprintf(os.Stderr, `pom2mk, a tool to create Android.mk files from maven repos
263
264The tool will extract the necessary information from *.pom files to create an Android.mk whose
265aar libraries can be linked against when using AAPT2.
266
267Usage: %s [--rewrite <regex>=<replace>] [--extra-deps <module>=<module>[,<module>]] <dir>
268
269 -rewrite <regex>=<replace>
Alan Viverette75b95f82017-12-04 16:24:07 -0500270 rewrite can be used to specify mappings between Maven projects and Make modules. The -rewrite
271 option can be specified multiple times. When determining the Make module for a given Maven
272 project, mappings are searched in the order they were specified. The first <regex> matching
273 either the Maven project's <groupId>:<artifactId> or <artifactId> will be used to generate
274 the Make module name using <replace>. If no matches are found, <artifactId> is used.
Dan Willemsen2902fa72017-04-27 21:16:35 -0700275 -extra-deps <module>=<module>[,<module>]
276 Some Android.mk modules have transitive dependencies that must be specified when they are
277 depended upon (like android-support-v7-mediarouter requires android-support-v7-appcompat).
278 This may be specified multiple times to declare these dependencies.
Dan Willemsen15a8e792017-11-10 14:02:44 -0800279 -sdk-version <version>
280 Sets LOCAL_SDK_VERSION := <version> for all modules.
Dan Willemsen47e44a42017-10-05 13:28:16 -0700281 -use-version <version>
282 If the maven directory contains multiple versions of artifacts and their pom files,
283 -use-version can be used to only write makefiles for a specific version of those artifacts.
Alan Viverette1593d3d2017-12-11 17:14:26 -0500284 -static-deps
285 Whether to statically include direct dependencies.
Dan Willemsen2902fa72017-04-27 21:16:35 -0700286 <dir>
287 The directory to search for *.pom files under.
288
289The makefile is written to stdout, to be put in the current directory (often as Android.mk)
290`, os.Args[0])
291 }
292
293 flag.Var(&extraDeps, "extra-deps", "Extra dependencies needed when depending on a module")
294 flag.Var(&rewriteNames, "rewrite", "Regex(es) to rewrite artifact names")
Dan Willemsen15a8e792017-11-10 14:02:44 -0800295 flag.StringVar(&sdkVersion, "sdk-version", "", "What to write to LOCAL_SDK_VERSION")
Dan Willemsen47e44a42017-10-05 13:28:16 -0700296 flag.StringVar(&useVersion, "use-version", "", "Only read artifacts of a specific version")
Alan Viverette1593d3d2017-12-11 17:14:26 -0500297 flag.BoolVar(&staticDeps, "static-deps", false, "Statically include direct dependencies")
Dan Willemsen2902fa72017-04-27 21:16:35 -0700298 flag.Parse()
299
300 if flag.NArg() != 1 {
301 flag.Usage()
302 os.Exit(1)
303 }
304
305 dir := flag.Arg(0)
306 absDir, err := filepath.Abs(dir)
307 if err != nil {
Colin Crossf46e37f2018-03-21 16:25:58 -0700308 fmt.Fprintln(os.Stderr, "Failed to get absolute directory:", err)
Dan Willemsen2902fa72017-04-27 21:16:35 -0700309 os.Exit(1)
310 }
311
312 var filenames []string
313 err = filepath.Walk(absDir, func(path string, info os.FileInfo, err error) error {
314 if err != nil {
315 return err
316 }
317
318 name := info.Name()
319 if info.IsDir() {
320 if strings.HasPrefix(name, ".") {
321 return filepath.SkipDir
322 }
323 return nil
324 }
325
326 if strings.HasPrefix(name, ".") {
327 return nil
328 }
329
330 if strings.HasSuffix(name, ".pom") {
331 path, err = filepath.Rel(absDir, path)
332 if err != nil {
333 return err
334 }
335 filenames = append(filenames, filepath.Join(dir, path))
336 }
337 return nil
338 })
339 if err != nil {
340 fmt.Fprintln(os.Stderr, "Error walking files:", err)
341 os.Exit(1)
342 }
343
344 if len(filenames) == 0 {
345 fmt.Fprintln(os.Stderr, "Error: no *.pom files found under", dir)
346 os.Exit(1)
347 }
348
349 sort.Strings(filenames)
350
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700351 poms := []*Pom{}
352 modules := make(map[string]*Pom)
353 for _, filename := range filenames {
354 pom, err := parse(filename)
355 if err != nil {
356 fmt.Fprintln(os.Stderr, "Error converting", filename, err)
357 os.Exit(1)
358 }
359
360 if pom != nil {
361 poms = append(poms, pom)
Alan Viverette75b95f82017-12-04 16:24:07 -0500362 key := pom.MkName()
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700363
Alan Viverette75b95f82017-12-04 16:24:07 -0500364 if old, ok := modules[key]; ok {
365 fmt.Fprintln(os.Stderr, "Module", key, "defined twice:", old.PomFile, pom.PomFile)
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700366 os.Exit(1)
367 }
368
Alan Viverette75b95f82017-12-04 16:24:07 -0500369 modules[key] = pom
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700370 }
371 }
372
373 for _, pom := range poms {
Alan Viverette6bd35eb2018-02-13 13:25:24 -0500374 pom.FixDeps(modules)
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700375 }
376
Dan Willemsen2902fa72017-04-27 21:16:35 -0700377 fmt.Println("# Automatically generated with:")
378 fmt.Println("# pom2mk", strings.Join(proptools.ShellEscape(os.Args[1:]), " "))
379 fmt.Println("LOCAL_PATH := $(call my-dir)")
380
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700381 for _, pom := range poms {
Alan Viverette1593d3d2017-12-11 17:14:26 -0500382 var err error
383 if staticDeps {
384 err = mkDepsTemplate.Execute(os.Stdout, pom)
385 } else {
386 err = mkTemplate.Execute(os.Stdout, pom)
387 }
Dan Willemsen2902fa72017-04-27 21:16:35 -0700388 if err != nil {
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700389 fmt.Fprintln(os.Stderr, "Error writing", pom.PomFile, pom.MkName(), err)
Dan Willemsen2902fa72017-04-27 21:16:35 -0700390 os.Exit(1)
391 }
392 }
393}