blob: 63bcbb65646b3c8b6251498b2eb98c6122e9e37b [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}}
Dan Willemsen2902fa72017-04-27 21:16:35 -0700198LOCAL_STATIC_ANDROID_LIBRARIES := \
Alan Viverette1593d3d2017-12-11 17:14:26 -0500199{{range .MkAarDeps}} {{.}} \
Dan Willemsen2902fa72017-04-27 21:16:35 -0700200{{end}}
201include $(BUILD_PREBUILT)
202`))
203
Alan Viverette1593d3d2017-12-11 17:14:26 -0500204var mkDepsTemplate = template.Must(template.New("mk").Parse(`
205include $(CLEAR_VARS)
206LOCAL_MODULE := {{.MkName}}-nodeps
207LOCAL_MODULE_CLASS := JAVA_LIBRARIES
208LOCAL_UNINSTALLABLE_MODULE := true
209LOCAL_SRC_FILES := {{.ArtifactFile}}
210LOCAL_BUILT_MODULE_STEM := javalib.jar
211LOCAL_MODULE_SUFFIX := .{{.Packaging}}
212LOCAL_USE_AAPT2 := true
213LOCAL_SDK_VERSION := {{.SdkVersion}}
214LOCAL_STATIC_ANDROID_LIBRARIES :={{range .MkAarDeps}} \
215 {{.}}{{end}}
216include $(BUILD_PREBUILT)
217include $(CLEAR_VARS)
218LOCAL_MODULE := {{.MkName}}
219LOCAL_SDK_VERSION := {{.SdkVersion}}{{if .IsAar}}
220LOCAL_MANIFEST_FILE := manifests/{{.MkName}}/AndroidManifest.xml{{end}}
221LOCAL_STATIC_JAVA_LIBRARIES :={{if .IsJar}} \
222 {{.MkName}}-nodeps{{end}}{{range .MkJarDeps}} \
223 {{.}}{{end}}
224LOCAL_STATIC_ANDROID_LIBRARIES :={{if .IsAar}} \
225 {{.MkName}}-nodeps{{end}}{{range .MkAarDeps}} \
226 {{.}}{{end}}
227LOCAL_JAR_EXCLUDE_FILES := none
228LOCAL_JAVA_LANGUAGE_VERSION := 1.7
229LOCAL_USE_AAPT2 := true
230include $(BUILD_STATIC_JAVA_LIBRARY)
231`))
232
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700233func parse(filename string) (*Pom, error) {
Dan Willemsen2902fa72017-04-27 21:16:35 -0700234 data, err := ioutil.ReadFile(filename)
235 if err != nil {
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700236 return nil, err
Dan Willemsen2902fa72017-04-27 21:16:35 -0700237 }
238
239 var pom Pom
240 err = xml.Unmarshal(data, &pom)
241 if err != nil {
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700242 return nil, err
Dan Willemsen2902fa72017-04-27 21:16:35 -0700243 }
244
Dan Willemsen47e44a42017-10-05 13:28:16 -0700245 if useVersion != "" && pom.Version != useVersion {
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700246 return nil, nil
Dan Willemsen47e44a42017-10-05 13:28:16 -0700247 }
248
Dan Willemsen2902fa72017-04-27 21:16:35 -0700249 if pom.Packaging == "" {
250 pom.Packaging = "jar"
251 }
252
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700253 pom.PomFile = filename
Dan Willemsen2902fa72017-04-27 21:16:35 -0700254 pom.ArtifactFile = strings.TrimSuffix(filename, ".pom") + "." + pom.Packaging
255
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700256 return &pom, nil
Dan Willemsen2902fa72017-04-27 21:16:35 -0700257}
258
259func main() {
260 flag.Usage = func() {
261 fmt.Fprintf(os.Stderr, `pom2mk, a tool to create Android.mk files from maven repos
262
263The tool will extract the necessary information from *.pom files to create an Android.mk whose
264aar libraries can be linked against when using AAPT2.
265
266Usage: %s [--rewrite <regex>=<replace>] [--extra-deps <module>=<module>[,<module>]] <dir>
267
268 -rewrite <regex>=<replace>
Alan Viverette75b95f82017-12-04 16:24:07 -0500269 rewrite can be used to specify mappings between Maven projects and Make modules. The -rewrite
270 option can be specified multiple times. When determining the Make module for a given Maven
271 project, mappings are searched in the order they were specified. The first <regex> matching
272 either the Maven project's <groupId>:<artifactId> or <artifactId> will be used to generate
273 the Make module name using <replace>. If no matches are found, <artifactId> is used.
Dan Willemsen2902fa72017-04-27 21:16:35 -0700274 -extra-deps <module>=<module>[,<module>]
275 Some Android.mk modules have transitive dependencies that must be specified when they are
276 depended upon (like android-support-v7-mediarouter requires android-support-v7-appcompat).
277 This may be specified multiple times to declare these dependencies.
Dan Willemsen15a8e792017-11-10 14:02:44 -0800278 -sdk-version <version>
279 Sets LOCAL_SDK_VERSION := <version> for all modules.
Dan Willemsen47e44a42017-10-05 13:28:16 -0700280 -use-version <version>
281 If the maven directory contains multiple versions of artifacts and their pom files,
282 -use-version can be used to only write makefiles for a specific version of those artifacts.
Alan Viverette1593d3d2017-12-11 17:14:26 -0500283 -static-deps
284 Whether to statically include direct dependencies.
Dan Willemsen2902fa72017-04-27 21:16:35 -0700285 <dir>
286 The directory to search for *.pom files under.
287
288The makefile is written to stdout, to be put in the current directory (often as Android.mk)
289`, os.Args[0])
290 }
291
292 flag.Var(&extraDeps, "extra-deps", "Extra dependencies needed when depending on a module")
293 flag.Var(&rewriteNames, "rewrite", "Regex(es) to rewrite artifact names")
Dan Willemsen15a8e792017-11-10 14:02:44 -0800294 flag.StringVar(&sdkVersion, "sdk-version", "", "What to write to LOCAL_SDK_VERSION")
Dan Willemsen47e44a42017-10-05 13:28:16 -0700295 flag.StringVar(&useVersion, "use-version", "", "Only read artifacts of a specific version")
Alan Viverette1593d3d2017-12-11 17:14:26 -0500296 flag.BoolVar(&staticDeps, "static-deps", false, "Statically include direct dependencies")
Dan Willemsen2902fa72017-04-27 21:16:35 -0700297 flag.Parse()
298
299 if flag.NArg() != 1 {
300 flag.Usage()
301 os.Exit(1)
302 }
303
304 dir := flag.Arg(0)
305 absDir, err := filepath.Abs(dir)
306 if err != nil {
307 fmt.Println(os.Stderr, "Failed to get absolute directory:", err)
308 os.Exit(1)
309 }
310
311 var filenames []string
312 err = filepath.Walk(absDir, func(path string, info os.FileInfo, err error) error {
313 if err != nil {
314 return err
315 }
316
317 name := info.Name()
318 if info.IsDir() {
319 if strings.HasPrefix(name, ".") {
320 return filepath.SkipDir
321 }
322 return nil
323 }
324
325 if strings.HasPrefix(name, ".") {
326 return nil
327 }
328
329 if strings.HasSuffix(name, ".pom") {
330 path, err = filepath.Rel(absDir, path)
331 if err != nil {
332 return err
333 }
334 filenames = append(filenames, filepath.Join(dir, path))
335 }
336 return nil
337 })
338 if err != nil {
339 fmt.Fprintln(os.Stderr, "Error walking files:", err)
340 os.Exit(1)
341 }
342
343 if len(filenames) == 0 {
344 fmt.Fprintln(os.Stderr, "Error: no *.pom files found under", dir)
345 os.Exit(1)
346 }
347
348 sort.Strings(filenames)
349
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700350 poms := []*Pom{}
351 modules := make(map[string]*Pom)
352 for _, filename := range filenames {
353 pom, err := parse(filename)
354 if err != nil {
355 fmt.Fprintln(os.Stderr, "Error converting", filename, err)
356 os.Exit(1)
357 }
358
359 if pom != nil {
360 poms = append(poms, pom)
Alan Viverette75b95f82017-12-04 16:24:07 -0500361 key := pom.MkName()
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700362
Alan Viverette75b95f82017-12-04 16:24:07 -0500363 if old, ok := modules[key]; ok {
364 fmt.Fprintln(os.Stderr, "Module", key, "defined twice:", old.PomFile, pom.PomFile)
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700365 os.Exit(1)
366 }
367
Alan Viverette75b95f82017-12-04 16:24:07 -0500368 modules[key] = pom
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700369 }
370 }
371
372 for _, pom := range poms {
Alan Viverette6bd35eb2018-02-13 13:25:24 -0500373 pom.FixDeps(modules)
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700374 }
375
Dan Willemsen2902fa72017-04-27 21:16:35 -0700376 fmt.Println("# Automatically generated with:")
377 fmt.Println("# pom2mk", strings.Join(proptools.ShellEscape(os.Args[1:]), " "))
378 fmt.Println("LOCAL_PATH := $(call my-dir)")
379
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700380 for _, pom := range poms {
Alan Viverette1593d3d2017-12-11 17:14:26 -0500381 var err error
382 if staticDeps {
383 err = mkDepsTemplate.Execute(os.Stdout, pom)
384 } else {
385 err = mkTemplate.Execute(os.Stdout, pom)
386 }
Dan Willemsen2902fa72017-04-27 21:16:35 -0700387 if err != nil {
Dan Willemsen5f9d8a62017-10-05 14:01:31 -0700388 fmt.Fprintln(os.Stderr, "Error writing", pom.PomFile, pom.MkName(), err)
Dan Willemsen2902fa72017-04-27 21:16:35 -0700389 os.Exit(1)
390 }
391 }
392}