blob: 2de0f7d7e9eefb222d60126eddddb7acae23a397 [file] [log] [blame]
Colin Cross70dd38f2018-04-16 13:52:10 -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 (
Colin Crosscf53e602018-06-26 15:27:20 -070018 "archive/zip"
Colin Cross70dd38f2018-04-16 13:52:10 -070019 "bufio"
20 "bytes"
21 "encoding/xml"
22 "flag"
23 "fmt"
24 "io/ioutil"
25 "os"
26 "os/exec"
27 "path/filepath"
28 "regexp"
29 "sort"
30 "strings"
31 "text/template"
32
33 "github.com/google/blueprint/proptools"
34
35 "android/soong/bpfix/bpfix"
36)
37
38type RewriteNames []RewriteName
39type RewriteName struct {
40 regexp *regexp.Regexp
41 repl string
42}
43
44func (r *RewriteNames) String() string {
45 return ""
46}
47
48func (r *RewriteNames) Set(v string) error {
49 split := strings.SplitN(v, "=", 2)
50 if len(split) != 2 {
51 return fmt.Errorf("Must be in the form of <regex>=<replace>")
52 }
53 regex, err := regexp.Compile(split[0])
54 if err != nil {
55 return nil
56 }
57 *r = append(*r, RewriteName{
58 regexp: regex,
59 repl: split[1],
60 })
61 return nil
62}
63
64func (r *RewriteNames) MavenToBp(groupId string, artifactId string) string {
65 for _, r := range *r {
66 if r.regexp.MatchString(groupId + ":" + artifactId) {
67 return r.regexp.ReplaceAllString(groupId+":"+artifactId, r.repl)
68 } else if r.regexp.MatchString(artifactId) {
69 return r.regexp.ReplaceAllString(artifactId, r.repl)
70 }
71 }
72 return artifactId
73}
74
75var rewriteNames = RewriteNames{}
76
77type ExtraDeps map[string][]string
78
79func (d ExtraDeps) String() string {
80 return ""
81}
82
83func (d ExtraDeps) Set(v string) error {
84 split := strings.SplitN(v, "=", 2)
85 if len(split) != 2 {
86 return fmt.Errorf("Must be in the form of <module>=<module>[,<module>]")
87 }
88 d[split[0]] = strings.Split(split[1], ",")
89 return nil
90}
91
Paul Duffinbabaf072019-04-16 11:35:20 +010092var extraStaticLibs = make(ExtraDeps)
93
94var extraLibs = make(ExtraDeps)
Colin Cross70dd38f2018-04-16 13:52:10 -070095
96type Exclude map[string]bool
97
98func (e Exclude) String() string {
99 return ""
100}
101
102func (e Exclude) Set(v string) error {
103 e[v] = true
104 return nil
105}
106
107var excludes = make(Exclude)
108
Jeff Gastond4928532018-08-24 14:30:13 -0400109type HostModuleNames map[string]bool
110
111func (n HostModuleNames) IsHostModule(groupId string, artifactId string) bool {
Colin Cross86bc9d42018-08-29 15:36:33 -0700112 _, found := n[groupId+":"+artifactId]
Jeff Gastond4928532018-08-24 14:30:13 -0400113 return found
114}
115
116func (n HostModuleNames) String() string {
117 return ""
118}
119
120func (n HostModuleNames) Set(v string) error {
121 n[v] = true
122 return nil
123}
124
125var hostModuleNames = HostModuleNames{}
126
Colin Cross70dd38f2018-04-16 13:52:10 -0700127var sdkVersion string
128var useVersion string
129
130func InList(s string, list []string) bool {
131 for _, l := range list {
132 if l == s {
133 return true
134 }
135 }
136
137 return false
138}
139
140type Dependency struct {
141 XMLName xml.Name `xml:"dependency"`
142
143 BpTarget string `xml:"-"`
144
145 GroupId string `xml:"groupId"`
146 ArtifactId string `xml:"artifactId"`
147 Version string `xml:"version"`
148 Type string `xml:"type"`
149 Scope string `xml:"scope"`
150}
151
152func (d Dependency) BpName() string {
153 if d.BpTarget == "" {
154 d.BpTarget = rewriteNames.MavenToBp(d.GroupId, d.ArtifactId)
155 }
156 return d.BpTarget
157}
158
159type Pom struct {
160 XMLName xml.Name `xml:"http://maven.apache.org/POM/4.0.0 project"`
161
Colin Crosscf53e602018-06-26 15:27:20 -0700162 PomFile string `xml:"-"`
163 ArtifactFile string `xml:"-"`
164 BpTarget string `xml:"-"`
165 MinSdkVersion string `xml:"-"`
Colin Cross70dd38f2018-04-16 13:52:10 -0700166
167 GroupId string `xml:"groupId"`
168 ArtifactId string `xml:"artifactId"`
169 Version string `xml:"version"`
170 Packaging string `xml:"packaging"`
171
172 Dependencies []*Dependency `xml:"dependencies>dependency"`
173}
174
175func (p Pom) IsAar() bool {
176 return p.Packaging == "aar"
177}
178
179func (p Pom) IsJar() bool {
180 return p.Packaging == "jar"
181}
182
Jeff Gastond4928532018-08-24 14:30:13 -0400183func (p Pom) IsHostModule() bool {
184 return hostModuleNames.IsHostModule(p.GroupId, p.ArtifactId)
185}
186
187func (p Pom) IsDeviceModule() bool {
188 return !p.IsHostModule()
189}
190
Colin Cross632987a2018-08-29 16:17:55 -0700191func (p Pom) ModuleType() string {
192 if p.IsAar() {
193 return "android_library"
194 } else if p.IsHostModule() {
195 return "java_library_host"
196 } else {
197 return "java_library_static"
198 }
199}
200
201func (p Pom) ImportModuleType() string {
202 if p.IsAar() {
203 return "android_library_import"
204 } else if p.IsHostModule() {
205 return "java_import_host"
206 } else {
207 return "java_import"
208 }
209}
210
211func (p Pom) ImportProperty() string {
212 if p.IsAar() {
213 return "aars"
214 } else {
215 return "jars"
216 }
217}
218
Colin Cross70dd38f2018-04-16 13:52:10 -0700219func (p Pom) BpName() string {
220 if p.BpTarget == "" {
221 p.BpTarget = rewriteNames.MavenToBp(p.GroupId, p.ArtifactId)
222 }
223 return p.BpTarget
224}
225
226func (p Pom) BpJarDeps() []string {
227 return p.BpDeps("jar", []string{"compile", "runtime"})
228}
229
230func (p Pom) BpAarDeps() []string {
231 return p.BpDeps("aar", []string{"compile", "runtime"})
232}
233
Paul Duffinbabaf072019-04-16 11:35:20 +0100234func (p Pom) BpExtraStaticLibs() []string {
235 return extraStaticLibs[p.BpName()]
236}
237
238func (p Pom) BpExtraLibs() []string {
239 return extraLibs[p.BpName()]
Colin Cross70dd38f2018-04-16 13:52:10 -0700240}
241
242// BpDeps obtains dependencies filtered by type and scope. The results of this
243// method are formatted as Android.bp targets, e.g. run through MavenToBp rules.
244func (p Pom) BpDeps(typeExt string, scopes []string) []string {
245 var ret []string
246 for _, d := range p.Dependencies {
247 if d.Type != typeExt || !InList(d.Scope, scopes) {
248 continue
249 }
250 name := rewriteNames.MavenToBp(d.GroupId, d.ArtifactId)
251 ret = append(ret, name)
252 }
253 return ret
254}
255
256func (p Pom) SdkVersion() string {
257 return sdkVersion
258}
259
260func (p *Pom) FixDeps(modules map[string]*Pom) {
261 for _, d := range p.Dependencies {
262 if d.Type == "" {
263 if depPom, ok := modules[d.BpName()]; ok {
264 // We've seen the POM for this dependency, use its packaging
265 // as the dependency type rather than Maven spec default.
266 d.Type = depPom.Packaging
267 } else {
268 // Dependency type was not specified and we don't have the POM
269 // for this artifact, use the default from Maven spec.
270 d.Type = "jar"
271 }
272 }
273 if d.Scope == "" {
274 // Scope was not specified, use the default from Maven spec.
275 d.Scope = "compile"
276 }
277 }
278}
279
Colin Crosscf53e602018-06-26 15:27:20 -0700280// ExtractMinSdkVersion extracts the minSdkVersion from the AndroidManifest.xml file inside an aar file, or sets it
281// to "current" if it is not present.
282func (p *Pom) ExtractMinSdkVersion() error {
283 aar, err := zip.OpenReader(p.ArtifactFile)
284 if err != nil {
285 return err
286 }
287 defer aar.Close()
288
289 var manifest *zip.File
290 for _, f := range aar.File {
291 if f.Name == "AndroidManifest.xml" {
292 manifest = f
293 break
294 }
295 }
296
297 if manifest == nil {
298 return fmt.Errorf("failed to find AndroidManifest.xml in %s", p.ArtifactFile)
299 }
300
301 r, err := manifest.Open()
302 if err != nil {
303 return err
304 }
305 defer r.Close()
306
307 decoder := xml.NewDecoder(r)
308
309 manifestData := struct {
310 XMLName xml.Name `xml:"manifest"`
311 Uses_sdk struct {
312 MinSdkVersion string `xml:"http://schemas.android.com/apk/res/android minSdkVersion,attr"`
313 } `xml:"uses-sdk"`
314 }{}
315
316 err = decoder.Decode(&manifestData)
317 if err != nil {
318 return err
319 }
320
321 p.MinSdkVersion = manifestData.Uses_sdk.MinSdkVersion
322 if p.MinSdkVersion == "" {
323 p.MinSdkVersion = "current"
324 }
325
326 return nil
327}
328
Colin Cross70dd38f2018-04-16 13:52:10 -0700329var bpTemplate = template.Must(template.New("bp").Parse(`
Colin Cross632987a2018-08-29 16:17:55 -0700330{{.ImportModuleType}} {
Colin Cross70dd38f2018-04-16 13:52:10 -0700331 name: "{{.BpName}}-nodeps",
Colin Cross632987a2018-08-29 16:17:55 -0700332 {{.ImportProperty}}: ["{{.ArtifactFile}}"],
333 sdk_version: "{{.SdkVersion}}",
334 {{- if .IsAar}}
Colin Crosscf53e602018-06-26 15:27:20 -0700335 min_sdk_version: "{{.MinSdkVersion}}",
Colin Cross632987a2018-08-29 16:17:55 -0700336 static_libs: [
Colin Cross1aa7f262019-04-10 11:07:15 -0700337 {{- range .BpJarDeps}}
338 "{{.}}",
339 {{- end}}
Colin Cross632987a2018-08-29 16:17:55 -0700340 {{- range .BpAarDeps}}
341 "{{.}}",
342 {{- end}}
Paul Duffinbabaf072019-04-16 11:35:20 +0100343 {{- range .BpExtraStaticLibs}}
Colin Cross632987a2018-08-29 16:17:55 -0700344 "{{.}}",
345 {{- end}}
346 ],
Paul Duffinbabaf072019-04-16 11:35:20 +0100347 {{- if .BpExtraLibs}}
348 libs: [
349 {{- range .BpExtraLibs}}
350 "{{.}}",
351 {{- end}}
352 ],
353 {{- end}}
Colin Cross632987a2018-08-29 16:17:55 -0700354 {{- end}}
Colin Cross70dd38f2018-04-16 13:52:10 -0700355}
356
Colin Cross632987a2018-08-29 16:17:55 -0700357{{.ModuleType}} {
358 name: "{{.BpName}}",
359 {{- if .IsDeviceModule}}
360 sdk_version: "{{.SdkVersion}}",
361 {{- if .IsAar}}
Colin Cross461ba492018-07-10 13:45:30 -0700362 min_sdk_version: "{{.MinSdkVersion}}",
Colin Cross632987a2018-08-29 16:17:55 -0700363 manifest: "manifests/{{.BpName}}/AndroidManifest.xml",
364 {{- end}}
365 {{- end}}
Colin Cross70dd38f2018-04-16 13:52:10 -0700366 static_libs: [
Colin Cross632987a2018-08-29 16:17:55 -0700367 "{{.BpName}}-nodeps",
Colin Cross1aa7f262019-04-10 11:07:15 -0700368 {{- range .BpJarDeps}}
Colin Cross632987a2018-08-29 16:17:55 -0700369 "{{.}}",
370 {{- end}}
371 {{- range .BpAarDeps}}
372 "{{.}}",
373 {{- end}}
Paul Duffinbabaf072019-04-16 11:35:20 +0100374 {{- range .BpExtraStaticLibs}}
Colin Cross632987a2018-08-29 16:17:55 -0700375 "{{.}}",
376 {{- end}}
Colin Cross70dd38f2018-04-16 13:52:10 -0700377 ],
Paul Duffinbabaf072019-04-16 11:35:20 +0100378 {{- if .BpExtraLibs}}
379 libs: [
380 {{- range .BpExtraLibs}}
381 "{{.}}",
382 {{- end}}
383 ],
384 {{- end}}
Colin Cross70dd38f2018-04-16 13:52:10 -0700385 java_version: "1.7",
386}
387`))
388
389func parse(filename string) (*Pom, error) {
390 data, err := ioutil.ReadFile(filename)
391 if err != nil {
392 return nil, err
393 }
394
395 var pom Pom
396 err = xml.Unmarshal(data, &pom)
397 if err != nil {
398 return nil, err
399 }
400
401 if useVersion != "" && pom.Version != useVersion {
402 return nil, nil
403 }
404
405 if pom.Packaging == "" {
406 pom.Packaging = "jar"
407 }
408
409 pom.PomFile = filename
410 pom.ArtifactFile = strings.TrimSuffix(filename, ".pom") + "." + pom.Packaging
411
412 return &pom, nil
413}
414
415func rerunForRegen(filename string) error {
416 buf, err := ioutil.ReadFile(filename)
417 if err != nil {
418 return err
419 }
420
421 scanner := bufio.NewScanner(bytes.NewBuffer(buf))
422
423 // Skip the first line in the file
424 for i := 0; i < 2; i++ {
425 if !scanner.Scan() {
426 if scanner.Err() != nil {
427 return scanner.Err()
428 } else {
429 return fmt.Errorf("unexpected EOF")
430 }
431 }
432 }
433
434 // Extract the old args from the file
435 line := scanner.Text()
436 if strings.HasPrefix(line, "// pom2bp ") {
437 line = strings.TrimPrefix(line, "// pom2bp ")
438 } else if strings.HasPrefix(line, "// pom2mk ") {
439 line = strings.TrimPrefix(line, "// pom2mk ")
440 } else if strings.HasPrefix(line, "# pom2mk ") {
441 line = strings.TrimPrefix(line, "# pom2mk ")
442 } else {
443 return fmt.Errorf("unexpected second line: %q", line)
444 }
445 args := strings.Split(line, " ")
446 lastArg := args[len(args)-1]
447 args = args[:len(args)-1]
448
449 // Append all current command line args except -regen <file> to the ones from the file
450 for i := 1; i < len(os.Args); i++ {
Colin Crosscf53e602018-06-26 15:27:20 -0700451 if os.Args[i] == "-regen" || os.Args[i] == "--regen" {
Colin Cross70dd38f2018-04-16 13:52:10 -0700452 i++
453 } else {
454 args = append(args, os.Args[i])
455 }
456 }
457 args = append(args, lastArg)
458
459 cmd := os.Args[0] + " " + strings.Join(args, " ")
460 // Re-exec pom2bp with the new arguments
461 output, err := exec.Command("/bin/sh", "-c", cmd).Output()
462 if exitErr, _ := err.(*exec.ExitError); exitErr != nil {
463 return fmt.Errorf("failed to run %s\n%s", cmd, string(exitErr.Stderr))
464 } else if err != nil {
465 return err
466 }
467
468 // If the old file was a .mk file, replace it with a .bp file
469 if filepath.Ext(filename) == ".mk" {
470 os.Remove(filename)
471 filename = strings.TrimSuffix(filename, ".mk") + ".bp"
472 }
473
474 return ioutil.WriteFile(filename, output, 0666)
475}
476
477func main() {
478 flag.Usage = func() {
479 fmt.Fprintf(os.Stderr, `pom2bp, a tool to create Android.bp files from maven repos
480
481The tool will extract the necessary information from *.pom files to create an Android.bp whose
482aar libraries can be linked against when using AAPT2.
483
Paul Duffinbabaf072019-04-16 11:35:20 +0100484Usage: %s [--rewrite <regex>=<replace>] [-exclude <module>] [--extra-static-libs <module>=<module>[,<module>]] [--extra-libs <module>=<module>[,<module>]] [<dir>] [-regen <file>]
Colin Cross70dd38f2018-04-16 13:52:10 -0700485
486 -rewrite <regex>=<replace>
487 rewrite can be used to specify mappings between Maven projects and Android.bp modules. The -rewrite
488 option can be specified multiple times. When determining the Android.bp module for a given Maven
489 project, mappings are searched in the order they were specified. The first <regex> matching
490 either the Maven project's <groupId>:<artifactId> or <artifactId> will be used to generate
491 the Android.bp module name using <replace>. If no matches are found, <artifactId> is used.
492 -exclude <module>
493 Don't put the specified module in the Android.bp file.
Paul Duffinbabaf072019-04-16 11:35:20 +0100494 -extra-static-libs <module>=<module>[,<module>]
495 Some Android.bp modules have transitive static dependencies that must be specified when they
496 are depended upon (like android-support-v7-mediarouter requires android-support-v7-appcompat).
497 This may be specified multiple times to declare these dependencies.
498 -extra-libs <module>=<module>[,<module>]
499 Some Android.bp modules have transitive runtime dependencies that must be specified when they
500 are depended upon (like androidx.test.rules requires android.test.base).
Colin Cross70dd38f2018-04-16 13:52:10 -0700501 This may be specified multiple times to declare these dependencies.
502 -sdk-version <version>
503 Sets LOCAL_SDK_VERSION := <version> for all modules.
504 -use-version <version>
505 If the maven directory contains multiple versions of artifacts and their pom files,
506 -use-version can be used to only write Android.bp files for a specific version of those artifacts.
507 <dir>
508 The directory to search for *.pom files under.
509 The contents are written to stdout, to be put in the current directory (often as Android.bp)
510 -regen <file>
511 Read arguments from <file> and overwrite it (if it ends with .bp) or move it to .bp (if it
512 ends with .mk).
513
514`, os.Args[0])
515 }
516
517 var regen string
518
519 flag.Var(&excludes, "exclude", "Exclude module")
Paul Duffinbabaf072019-04-16 11:35:20 +0100520 flag.Var(&extraStaticLibs, "extra-static-libs", "Extra static dependencies needed when depending on a module")
521 flag.Var(&extraLibs, "extra-libs", "Extra runtime dependencies needed when depending on a module")
Colin Cross70dd38f2018-04-16 13:52:10 -0700522 flag.Var(&rewriteNames, "rewrite", "Regex(es) to rewrite artifact names")
Jeff Gastond4928532018-08-24 14:30:13 -0400523 flag.Var(&hostModuleNames, "host", "Specifies that the corresponding module (specified in the form 'module.group:module.artifact') is a host module")
Colin Cross70dd38f2018-04-16 13:52:10 -0700524 flag.StringVar(&sdkVersion, "sdk-version", "", "What to write to LOCAL_SDK_VERSION")
525 flag.StringVar(&useVersion, "use-version", "", "Only read artifacts of a specific version")
526 flag.Bool("static-deps", false, "Ignored")
527 flag.StringVar(&regen, "regen", "", "Rewrite specified file")
528 flag.Parse()
529
530 if regen != "" {
531 err := rerunForRegen(regen)
532 if err != nil {
533 fmt.Fprintln(os.Stderr, err)
534 os.Exit(1)
535 }
536 os.Exit(0)
537 }
538
539 if flag.NArg() == 0 {
540 fmt.Fprintln(os.Stderr, "Directory argument is required")
541 os.Exit(1)
542 } else if flag.NArg() > 1 {
543 fmt.Fprintln(os.Stderr, "Multiple directories provided:", strings.Join(flag.Args(), " "))
544 os.Exit(1)
545 }
546
547 dir := flag.Arg(0)
548 absDir, err := filepath.Abs(dir)
549 if err != nil {
550 fmt.Fprintln(os.Stderr, "Failed to get absolute directory:", err)
551 os.Exit(1)
552 }
553
554 var filenames []string
555 err = filepath.Walk(absDir, func(path string, info os.FileInfo, err error) error {
556 if err != nil {
557 return err
558 }
559
560 name := info.Name()
561 if info.IsDir() {
562 if strings.HasPrefix(name, ".") {
563 return filepath.SkipDir
564 }
565 return nil
566 }
567
568 if strings.HasPrefix(name, ".") {
569 return nil
570 }
571
572 if strings.HasSuffix(name, ".pom") {
573 path, err = filepath.Rel(absDir, path)
574 if err != nil {
575 return err
576 }
577 filenames = append(filenames, filepath.Join(dir, path))
578 }
579 return nil
580 })
581 if err != nil {
582 fmt.Fprintln(os.Stderr, "Error walking files:", err)
583 os.Exit(1)
584 }
585
586 if len(filenames) == 0 {
587 fmt.Fprintln(os.Stderr, "Error: no *.pom files found under", dir)
588 os.Exit(1)
589 }
590
591 sort.Strings(filenames)
592
593 poms := []*Pom{}
594 modules := make(map[string]*Pom)
595 duplicate := false
596 for _, filename := range filenames {
597 pom, err := parse(filename)
598 if err != nil {
599 fmt.Fprintln(os.Stderr, "Error converting", filename, err)
600 os.Exit(1)
601 }
602
603 if pom != nil {
604 key := pom.BpName()
605 if excludes[key] {
606 continue
607 }
608
609 if old, ok := modules[key]; ok {
610 fmt.Fprintln(os.Stderr, "Module", key, "defined twice:", old.PomFile, pom.PomFile)
611 duplicate = true
612 }
613
614 poms = append(poms, pom)
615 modules[key] = pom
616 }
617 }
618 if duplicate {
619 os.Exit(1)
620 }
621
622 for _, pom := range poms {
Colin Crosscf53e602018-06-26 15:27:20 -0700623 if pom.IsAar() {
624 err := pom.ExtractMinSdkVersion()
625 if err != nil {
Colin Crossfe5a3b72018-07-13 21:25:15 -0700626 fmt.Fprintf(os.Stderr, "Error reading manifest for %s: %s", pom.ArtifactFile, err)
Colin Crosscf53e602018-06-26 15:27:20 -0700627 os.Exit(1)
628 }
629 }
Colin Cross70dd38f2018-04-16 13:52:10 -0700630 pom.FixDeps(modules)
631 }
632
633 buf := &bytes.Buffer{}
634
635 fmt.Fprintln(buf, "// Automatically generated with:")
Colin Cross0b9f31f2019-02-28 11:00:01 -0800636 fmt.Fprintln(buf, "// pom2bp", strings.Join(proptools.ShellEscapeList(os.Args[1:]), " "))
Colin Cross70dd38f2018-04-16 13:52:10 -0700637
638 for _, pom := range poms {
639 var err error
640 err = bpTemplate.Execute(buf, pom)
641 if err != nil {
642 fmt.Fprintln(os.Stderr, "Error writing", pom.PomFile, pom.BpName(), err)
643 os.Exit(1)
644 }
645 }
646
647 out, err := bpfix.Reformat(buf.String())
648 if err != nil {
649 fmt.Fprintln(os.Stderr, "Error formatting output", err)
650 os.Exit(1)
651 }
652
653 os.Stdout.WriteString(out)
654}