blob: fe567a97616a2115bb50cc3f351313f35c2d4b73 [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
Alan Viverette24658d02021-08-31 20:00:52 +000096var optionalUsesLibs = make(ExtraDeps)
97
Colin Cross70dd38f2018-04-16 13:52:10 -070098type Exclude map[string]bool
99
100func (e Exclude) String() string {
101 return ""
102}
103
104func (e Exclude) Set(v string) error {
105 e[v] = true
106 return nil
107}
108
109var excludes = make(Exclude)
110
Jeff Gastond4928532018-08-24 14:30:13 -0400111type HostModuleNames map[string]bool
112
113func (n HostModuleNames) IsHostModule(groupId string, artifactId string) bool {
Colin Cross86bc9d42018-08-29 15:36:33 -0700114 _, found := n[groupId+":"+artifactId]
Jeff Gastond4928532018-08-24 14:30:13 -0400115 return found
116}
117
118func (n HostModuleNames) String() string {
119 return ""
120}
121
122func (n HostModuleNames) Set(v string) error {
123 n[v] = true
124 return nil
125}
126
127var hostModuleNames = HostModuleNames{}
128
Tony Mak81785002019-07-18 21:36:44 +0100129type HostAndDeviceModuleNames map[string]bool
130
131func (n HostAndDeviceModuleNames) IsHostAndDeviceModule(groupId string, artifactId string) bool {
132 _, found := n[groupId+":"+artifactId]
133
134 return found
135}
136
137func (n HostAndDeviceModuleNames) String() string {
138 return ""
139}
140
141func (n HostAndDeviceModuleNames) Set(v string) error {
142 n[v] = true
143 return nil
144}
145
146var hostAndDeviceModuleNames = HostAndDeviceModuleNames{}
147
Colin Cross70dd38f2018-04-16 13:52:10 -0700148var sdkVersion string
Anton Hanssonc29f0762021-03-29 16:10:06 +0100149var defaultMinSdkVersion string
Colin Cross70dd38f2018-04-16 13:52:10 -0700150var useVersion string
Dan Willemsen52c90d82019-04-21 21:37:39 -0700151var staticDeps bool
Dan Willemsen7fdab6e2019-04-20 21:47:14 -0700152var jetifier bool
Colin Cross70dd38f2018-04-16 13:52:10 -0700153
154func InList(s string, list []string) bool {
155 for _, l := range list {
156 if l == s {
157 return true
158 }
159 }
160
161 return false
162}
163
164type Dependency struct {
165 XMLName xml.Name `xml:"dependency"`
166
167 BpTarget string `xml:"-"`
168
169 GroupId string `xml:"groupId"`
170 ArtifactId string `xml:"artifactId"`
171 Version string `xml:"version"`
172 Type string `xml:"type"`
173 Scope string `xml:"scope"`
174}
175
176func (d Dependency) BpName() string {
177 if d.BpTarget == "" {
178 d.BpTarget = rewriteNames.MavenToBp(d.GroupId, d.ArtifactId)
179 }
180 return d.BpTarget
181}
182
183type Pom struct {
184 XMLName xml.Name `xml:"http://maven.apache.org/POM/4.0.0 project"`
185
Colin Crosscf53e602018-06-26 15:27:20 -0700186 PomFile string `xml:"-"`
187 ArtifactFile string `xml:"-"`
188 BpTarget string `xml:"-"`
189 MinSdkVersion string `xml:"-"`
Colin Cross70dd38f2018-04-16 13:52:10 -0700190
191 GroupId string `xml:"groupId"`
192 ArtifactId string `xml:"artifactId"`
193 Version string `xml:"version"`
194 Packaging string `xml:"packaging"`
195
196 Dependencies []*Dependency `xml:"dependencies>dependency"`
197}
198
199func (p Pom) IsAar() bool {
200 return p.Packaging == "aar"
201}
202
203func (p Pom) IsJar() bool {
204 return p.Packaging == "jar"
205}
206
Jeff Gastond4928532018-08-24 14:30:13 -0400207func (p Pom) IsHostModule() bool {
208 return hostModuleNames.IsHostModule(p.GroupId, p.ArtifactId)
209}
210
211func (p Pom) IsDeviceModule() bool {
212 return !p.IsHostModule()
213}
214
Tony Mak81785002019-07-18 21:36:44 +0100215func (p Pom) IsHostAndDeviceModule() bool {
216 return hostAndDeviceModuleNames.IsHostAndDeviceModule(p.GroupId, p.ArtifactId)
217}
218
Jooyung Han43d30252020-05-22 03:54:24 +0900219func (p Pom) IsHostOnly() bool {
220 return p.IsHostModule() && !p.IsHostAndDeviceModule()
221}
222
Colin Cross632987a2018-08-29 16:17:55 -0700223func (p Pom) ModuleType() string {
224 if p.IsAar() {
225 return "android_library"
Jooyung Han43d30252020-05-22 03:54:24 +0900226 } else if p.IsHostOnly() {
Colin Cross632987a2018-08-29 16:17:55 -0700227 return "java_library_host"
228 } else {
229 return "java_library_static"
230 }
231}
232
233func (p Pom) ImportModuleType() string {
234 if p.IsAar() {
235 return "android_library_import"
Jooyung Han43d30252020-05-22 03:54:24 +0900236 } else if p.IsHostOnly() {
Colin Cross632987a2018-08-29 16:17:55 -0700237 return "java_import_host"
238 } else {
239 return "java_import"
240 }
241}
242
243func (p Pom) ImportProperty() string {
244 if p.IsAar() {
245 return "aars"
246 } else {
247 return "jars"
248 }
249}
250
Colin Cross70dd38f2018-04-16 13:52:10 -0700251func (p Pom) BpName() string {
252 if p.BpTarget == "" {
253 p.BpTarget = rewriteNames.MavenToBp(p.GroupId, p.ArtifactId)
254 }
255 return p.BpTarget
256}
257
258func (p Pom) BpJarDeps() []string {
259 return p.BpDeps("jar", []string{"compile", "runtime"})
260}
261
262func (p Pom) BpAarDeps() []string {
263 return p.BpDeps("aar", []string{"compile", "runtime"})
264}
265
Paul Duffinbabaf072019-04-16 11:35:20 +0100266func (p Pom) BpExtraStaticLibs() []string {
267 return extraStaticLibs[p.BpName()]
268}
269
270func (p Pom) BpExtraLibs() []string {
271 return extraLibs[p.BpName()]
Colin Cross70dd38f2018-04-16 13:52:10 -0700272}
273
Alan Viverette24658d02021-08-31 20:00:52 +0000274func (p Pom) BpOptionalUsesLibs() []string {
275 return optionalUsesLibs[p.BpName()]
276}
277
Colin Cross70dd38f2018-04-16 13:52:10 -0700278// BpDeps obtains dependencies filtered by type and scope. The results of this
279// method are formatted as Android.bp targets, e.g. run through MavenToBp rules.
280func (p Pom) BpDeps(typeExt string, scopes []string) []string {
281 var ret []string
282 for _, d := range p.Dependencies {
283 if d.Type != typeExt || !InList(d.Scope, scopes) {
284 continue
285 }
286 name := rewriteNames.MavenToBp(d.GroupId, d.ArtifactId)
287 ret = append(ret, name)
288 }
289 return ret
290}
291
292func (p Pom) SdkVersion() string {
293 return sdkVersion
294}
295
Anton Hanssonc29f0762021-03-29 16:10:06 +0100296func (p Pom) DefaultMinSdkVersion() string {
297 return defaultMinSdkVersion
298}
299
Dan Willemsen7fdab6e2019-04-20 21:47:14 -0700300func (p Pom) Jetifier() bool {
301 return jetifier
302}
303
Colin Cross70dd38f2018-04-16 13:52:10 -0700304func (p *Pom) FixDeps(modules map[string]*Pom) {
305 for _, d := range p.Dependencies {
306 if d.Type == "" {
307 if depPom, ok := modules[d.BpName()]; ok {
308 // We've seen the POM for this dependency, use its packaging
309 // as the dependency type rather than Maven spec default.
310 d.Type = depPom.Packaging
311 } else {
312 // Dependency type was not specified and we don't have the POM
313 // for this artifact, use the default from Maven spec.
314 d.Type = "jar"
315 }
316 }
317 if d.Scope == "" {
318 // Scope was not specified, use the default from Maven spec.
319 d.Scope = "compile"
320 }
321 }
322}
323
Colin Crosscf53e602018-06-26 15:27:20 -0700324// ExtractMinSdkVersion extracts the minSdkVersion from the AndroidManifest.xml file inside an aar file, or sets it
325// to "current" if it is not present.
326func (p *Pom) ExtractMinSdkVersion() error {
327 aar, err := zip.OpenReader(p.ArtifactFile)
328 if err != nil {
329 return err
330 }
331 defer aar.Close()
332
333 var manifest *zip.File
334 for _, f := range aar.File {
335 if f.Name == "AndroidManifest.xml" {
336 manifest = f
337 break
338 }
339 }
340
341 if manifest == nil {
342 return fmt.Errorf("failed to find AndroidManifest.xml in %s", p.ArtifactFile)
343 }
344
345 r, err := manifest.Open()
346 if err != nil {
347 return err
348 }
349 defer r.Close()
350
351 decoder := xml.NewDecoder(r)
352
353 manifestData := struct {
354 XMLName xml.Name `xml:"manifest"`
355 Uses_sdk struct {
356 MinSdkVersion string `xml:"http://schemas.android.com/apk/res/android minSdkVersion,attr"`
357 } `xml:"uses-sdk"`
358 }{}
359
360 err = decoder.Decode(&manifestData)
361 if err != nil {
362 return err
363 }
364
365 p.MinSdkVersion = manifestData.Uses_sdk.MinSdkVersion
366 if p.MinSdkVersion == "" {
367 p.MinSdkVersion = "current"
368 }
369
370 return nil
371}
372
Colin Cross70dd38f2018-04-16 13:52:10 -0700373var bpTemplate = template.Must(template.New("bp").Parse(`
Colin Cross632987a2018-08-29 16:17:55 -0700374{{.ImportModuleType}} {
Dan Willemsen52c90d82019-04-21 21:37:39 -0700375 name: "{{.BpName}}",
376 {{.ImportProperty}}: ["{{.ArtifactFile}}"],
377 sdk_version: "{{.SdkVersion}}",
378 {{- if .Jetifier}}
379 jetifier: true,
380 {{- end}}
Tony Mak81785002019-07-18 21:36:44 +0100381 {{- if .IsHostAndDeviceModule}}
382 host_supported: true,
383 {{- end}}
Jooyung Han43d30252020-05-22 03:54:24 +0900384 {{- if not .IsHostOnly}}
385 apex_available: [
386 "//apex_available:platform",
387 "//apex_available:anyapex",
388 ],
389 {{- end}}
Dan Willemsen52c90d82019-04-21 21:37:39 -0700390 {{- if .IsAar}}
391 min_sdk_version: "{{.MinSdkVersion}}",
392 static_libs: [
393 {{- range .BpJarDeps}}
394 "{{.}}",
395 {{- end}}
396 {{- range .BpAarDeps}}
397 "{{.}}",
398 {{- end}}
399 {{- range .BpExtraStaticLibs}}
400 "{{.}}",
401 {{- end}}
402 ],
403 {{- if .BpExtraLibs}}
404 libs: [
405 {{- range .BpExtraLibs}}
406 "{{.}}",
407 {{- end}}
408 ],
Alan Viverettebcbfc5f2021-09-13 17:12:28 +0000409 {{- end}}
Alan Viverette24658d02021-08-31 20:00:52 +0000410 {{- if .BpOptionalUsesLibs}}
411 optional_uses_libs: [
412 {{- range .BpOptionalUsesLibs}}
413 "{{.}}",
414 {{- end}}
415 ],
Dan Willemsen52c90d82019-04-21 21:37:39 -0700416 {{- end}}
Anton Hanssonebfbad22021-04-06 19:21:34 +0000417 {{- else if not .IsHostOnly}}
418 min_sdk_version: "{{.DefaultMinSdkVersion}}",
Dan Willemsen52c90d82019-04-21 21:37:39 -0700419 {{- end}}
420}
421`))
422
423var bpDepsTemplate = template.Must(template.New("bp").Parse(`
424{{.ImportModuleType}} {
Colin Cross70dd38f2018-04-16 13:52:10 -0700425 name: "{{.BpName}}-nodeps",
Colin Cross632987a2018-08-29 16:17:55 -0700426 {{.ImportProperty}}: ["{{.ArtifactFile}}"],
427 sdk_version: "{{.SdkVersion}}",
Dan Willemsen7fdab6e2019-04-20 21:47:14 -0700428 {{- if .Jetifier}}
429 jetifier: true,
430 {{- end}}
Tony Mak81785002019-07-18 21:36:44 +0100431 {{- if .IsHostAndDeviceModule}}
432 host_supported: true,
433 {{- end}}
Jooyung Han43d30252020-05-22 03:54:24 +0900434 {{- if not .IsHostOnly}}
435 apex_available: [
436 "//apex_available:platform",
437 "//apex_available:anyapex",
438 ],
439 {{- end}}
Colin Cross632987a2018-08-29 16:17:55 -0700440 {{- if .IsAar}}
Colin Crosscf53e602018-06-26 15:27:20 -0700441 min_sdk_version: "{{.MinSdkVersion}}",
Colin Cross632987a2018-08-29 16:17:55 -0700442 static_libs: [
Colin Cross1aa7f262019-04-10 11:07:15 -0700443 {{- range .BpJarDeps}}
444 "{{.}}",
445 {{- end}}
Colin Cross632987a2018-08-29 16:17:55 -0700446 {{- range .BpAarDeps}}
447 "{{.}}",
448 {{- end}}
Paul Duffinbabaf072019-04-16 11:35:20 +0100449 {{- range .BpExtraStaticLibs}}
Colin Cross632987a2018-08-29 16:17:55 -0700450 "{{.}}",
451 {{- end}}
452 ],
Paul Duffinbabaf072019-04-16 11:35:20 +0100453 {{- if .BpExtraLibs}}
454 libs: [
455 {{- range .BpExtraLibs}}
456 "{{.}}",
457 {{- end}}
458 ],
459 {{- end}}
Anton Hanssonebfbad22021-04-06 19:21:34 +0000460 {{- else if not .IsHostOnly}}
461 min_sdk_version: "{{.DefaultMinSdkVersion}}",
Colin Cross632987a2018-08-29 16:17:55 -0700462 {{- end}}
Colin Cross70dd38f2018-04-16 13:52:10 -0700463}
464
Colin Cross632987a2018-08-29 16:17:55 -0700465{{.ModuleType}} {
466 name: "{{.BpName}}",
467 {{- if .IsDeviceModule}}
468 sdk_version: "{{.SdkVersion}}",
Tony Mak81785002019-07-18 21:36:44 +0100469 {{- if .IsHostAndDeviceModule}}
470 host_supported: true,
471 {{- end}}
Jooyung Han43d30252020-05-22 03:54:24 +0900472 {{- if not .IsHostOnly}}
473 apex_available: [
474 "//apex_available:platform",
475 "//apex_available:anyapex",
476 ],
477 {{- end}}
Colin Cross632987a2018-08-29 16:17:55 -0700478 {{- if .IsAar}}
Colin Cross461ba492018-07-10 13:45:30 -0700479 min_sdk_version: "{{.MinSdkVersion}}",
Colin Cross632987a2018-08-29 16:17:55 -0700480 manifest: "manifests/{{.BpName}}/AndroidManifest.xml",
Jooyung Han43d30252020-05-22 03:54:24 +0900481 {{- else if not .IsHostOnly}}
Anton Hanssonc29f0762021-03-29 16:10:06 +0100482 min_sdk_version: "{{.DefaultMinSdkVersion}}",
Colin Cross632987a2018-08-29 16:17:55 -0700483 {{- end}}
484 {{- end}}
Colin Cross70dd38f2018-04-16 13:52:10 -0700485 static_libs: [
Colin Cross632987a2018-08-29 16:17:55 -0700486 "{{.BpName}}-nodeps",
Colin Cross1aa7f262019-04-10 11:07:15 -0700487 {{- range .BpJarDeps}}
Colin Cross632987a2018-08-29 16:17:55 -0700488 "{{.}}",
489 {{- end}}
490 {{- range .BpAarDeps}}
491 "{{.}}",
492 {{- end}}
Paul Duffinbabaf072019-04-16 11:35:20 +0100493 {{- range .BpExtraStaticLibs}}
Colin Cross632987a2018-08-29 16:17:55 -0700494 "{{.}}",
495 {{- end}}
Colin Cross70dd38f2018-04-16 13:52:10 -0700496 ],
Paul Duffinbabaf072019-04-16 11:35:20 +0100497 {{- if .BpExtraLibs}}
498 libs: [
499 {{- range .BpExtraLibs}}
500 "{{.}}",
501 {{- end}}
502 ],
Alan Viverettebcbfc5f2021-09-13 17:12:28 +0000503 {{- end}}
Alan Viverette24658d02021-08-31 20:00:52 +0000504 {{- if .BpOptionalUsesLibs}}
505 optional_uses_libs: [
506 {{- range .BpOptionalUsesLibs}}
507 "{{.}}",
508 {{- end}}
509 ],
Paul Duffinbabaf072019-04-16 11:35:20 +0100510 {{- end}}
Colin Cross70dd38f2018-04-16 13:52:10 -0700511 java_version: "1.7",
512}
513`))
514
515func parse(filename string) (*Pom, error) {
516 data, err := ioutil.ReadFile(filename)
517 if err != nil {
518 return nil, err
519 }
520
521 var pom Pom
522 err = xml.Unmarshal(data, &pom)
523 if err != nil {
524 return nil, err
525 }
526
527 if useVersion != "" && pom.Version != useVersion {
528 return nil, nil
529 }
530
531 if pom.Packaging == "" {
532 pom.Packaging = "jar"
533 }
534
535 pom.PomFile = filename
536 pom.ArtifactFile = strings.TrimSuffix(filename, ".pom") + "." + pom.Packaging
537
538 return &pom, nil
539}
540
541func rerunForRegen(filename string) error {
542 buf, err := ioutil.ReadFile(filename)
543 if err != nil {
544 return err
545 }
546
547 scanner := bufio.NewScanner(bytes.NewBuffer(buf))
548
549 // Skip the first line in the file
550 for i := 0; i < 2; i++ {
551 if !scanner.Scan() {
552 if scanner.Err() != nil {
553 return scanner.Err()
554 } else {
555 return fmt.Errorf("unexpected EOF")
556 }
557 }
558 }
559
560 // Extract the old args from the file
561 line := scanner.Text()
562 if strings.HasPrefix(line, "// pom2bp ") {
563 line = strings.TrimPrefix(line, "// pom2bp ")
564 } else if strings.HasPrefix(line, "// pom2mk ") {
565 line = strings.TrimPrefix(line, "// pom2mk ")
566 } else if strings.HasPrefix(line, "# pom2mk ") {
567 line = strings.TrimPrefix(line, "# pom2mk ")
568 } else {
569 return fmt.Errorf("unexpected second line: %q", line)
570 }
571 args := strings.Split(line, " ")
572 lastArg := args[len(args)-1]
573 args = args[:len(args)-1]
574
575 // Append all current command line args except -regen <file> to the ones from the file
576 for i := 1; i < len(os.Args); i++ {
Colin Crosscf53e602018-06-26 15:27:20 -0700577 if os.Args[i] == "-regen" || os.Args[i] == "--regen" {
Colin Cross70dd38f2018-04-16 13:52:10 -0700578 i++
579 } else {
580 args = append(args, os.Args[i])
581 }
582 }
583 args = append(args, lastArg)
584
585 cmd := os.Args[0] + " " + strings.Join(args, " ")
586 // Re-exec pom2bp with the new arguments
587 output, err := exec.Command("/bin/sh", "-c", cmd).Output()
588 if exitErr, _ := err.(*exec.ExitError); exitErr != nil {
589 return fmt.Errorf("failed to run %s\n%s", cmd, string(exitErr.Stderr))
590 } else if err != nil {
591 return err
592 }
593
594 // If the old file was a .mk file, replace it with a .bp file
595 if filepath.Ext(filename) == ".mk" {
596 os.Remove(filename)
597 filename = strings.TrimSuffix(filename, ".mk") + ".bp"
598 }
599
600 return ioutil.WriteFile(filename, output, 0666)
601}
602
603func main() {
604 flag.Usage = func() {
605 fmt.Fprintf(os.Stderr, `pom2bp, a tool to create Android.bp files from maven repos
606
607The tool will extract the necessary information from *.pom files to create an Android.bp whose
608aar libraries can be linked against when using AAPT2.
609
Alan Viverette24658d02021-08-31 20:00:52 +0000610Usage: %s [--rewrite <regex>=<replace>] [--exclude <module>] [--extra-static-libs <module>=<module>[,<module>]] [--extra-libs <module>=<module>[,<module>]] [--optional-uses-libs <module>=<module>[,<module>]] [<dir>] [-regen <file>]
Colin Cross70dd38f2018-04-16 13:52:10 -0700611
612 -rewrite <regex>=<replace>
613 rewrite can be used to specify mappings between Maven projects and Android.bp modules. The -rewrite
614 option can be specified multiple times. When determining the Android.bp module for a given Maven
615 project, mappings are searched in the order they were specified. The first <regex> matching
616 either the Maven project's <groupId>:<artifactId> or <artifactId> will be used to generate
617 the Android.bp module name using <replace>. If no matches are found, <artifactId> is used.
618 -exclude <module>
619 Don't put the specified module in the Android.bp file.
Paul Duffinbabaf072019-04-16 11:35:20 +0100620 -extra-static-libs <module>=<module>[,<module>]
621 Some Android.bp modules have transitive static dependencies that must be specified when they
622 are depended upon (like android-support-v7-mediarouter requires android-support-v7-appcompat).
623 This may be specified multiple times to declare these dependencies.
624 -extra-libs <module>=<module>[,<module>]
625 Some Android.bp modules have transitive runtime dependencies that must be specified when they
626 are depended upon (like androidx.test.rules requires android.test.base).
Colin Cross70dd38f2018-04-16 13:52:10 -0700627 This may be specified multiple times to declare these dependencies.
Alan Viverette24658d02021-08-31 20:00:52 +0000628 -optional-uses-libs <module>=<module>[,<module>]
629 Some Android.bp modules have optional dependencies (typically specified with <uses-library> in
630 the module's AndroidManifest.xml) that must be specified when they are depended upon (like
631 androidx.window:window optionally requires androidx.window:window-extensions).
632 This may be specified multiple times to declare these dependencies.
Colin Cross70dd38f2018-04-16 13:52:10 -0700633 -sdk-version <version>
Dan Willemsen7fdab6e2019-04-20 21:47:14 -0700634 Sets sdk_version: "<version>" for all modules.
Anton Hanssonc29f0762021-03-29 16:10:06 +0100635 -default-min-sdk-version
636 The default min_sdk_version to use for a module if one cannot be mined from AndroidManifest.xml
Colin Cross70dd38f2018-04-16 13:52:10 -0700637 -use-version <version>
638 If the maven directory contains multiple versions of artifacts and their pom files,
639 -use-version can be used to only write Android.bp files for a specific version of those artifacts.
Dan Willemsen7fdab6e2019-04-20 21:47:14 -0700640 -jetifier
641 Sets jetifier: true for all modules.
Colin Cross70dd38f2018-04-16 13:52:10 -0700642 <dir>
643 The directory to search for *.pom files under.
644 The contents are written to stdout, to be put in the current directory (often as Android.bp)
645 -regen <file>
646 Read arguments from <file> and overwrite it (if it ends with .bp) or move it to .bp (if it
647 ends with .mk).
648
649`, os.Args[0])
650 }
651
652 var regen string
653
654 flag.Var(&excludes, "exclude", "Exclude module")
Paul Duffinbabaf072019-04-16 11:35:20 +0100655 flag.Var(&extraStaticLibs, "extra-static-libs", "Extra static dependencies needed when depending on a module")
656 flag.Var(&extraLibs, "extra-libs", "Extra runtime dependencies needed when depending on a module")
Alan Viverette24658d02021-08-31 20:00:52 +0000657 flag.Var(&optionalUsesLibs, "optional-uses-libs", "Extra optional dependencies needed when depending on a module")
Colin Cross70dd38f2018-04-16 13:52:10 -0700658 flag.Var(&rewriteNames, "rewrite", "Regex(es) to rewrite artifact names")
Jeff Gastond4928532018-08-24 14:30:13 -0400659 flag.Var(&hostModuleNames, "host", "Specifies that the corresponding module (specified in the form 'module.group:module.artifact') is a host module")
Tony Mak81785002019-07-18 21:36:44 +0100660 flag.Var(&hostAndDeviceModuleNames, "host-and-device", "Specifies that the corresponding module (specified in the form 'module.group:module.artifact') is both a host and device module.")
Dan Willemsen7fdab6e2019-04-20 21:47:14 -0700661 flag.StringVar(&sdkVersion, "sdk-version", "", "What to write to sdk_version")
Anton Hanssonc29f0762021-03-29 16:10:06 +0100662 flag.StringVar(&defaultMinSdkVersion, "default-min-sdk-version", "24", "Default min_sdk_version to use, if one is not available from AndroidManifest.xml. Default: 24")
Colin Cross70dd38f2018-04-16 13:52:10 -0700663 flag.StringVar(&useVersion, "use-version", "", "Only read artifacts of a specific version")
Dan Willemsen52c90d82019-04-21 21:37:39 -0700664 flag.BoolVar(&staticDeps, "static-deps", false, "Statically include direct dependencies")
Dan Willemsen7fdab6e2019-04-20 21:47:14 -0700665 flag.BoolVar(&jetifier, "jetifier", false, "Sets jetifier: true on all modules")
Colin Cross70dd38f2018-04-16 13:52:10 -0700666 flag.StringVar(&regen, "regen", "", "Rewrite specified file")
667 flag.Parse()
668
669 if regen != "" {
670 err := rerunForRegen(regen)
671 if err != nil {
672 fmt.Fprintln(os.Stderr, err)
673 os.Exit(1)
674 }
675 os.Exit(0)
676 }
677
678 if flag.NArg() == 0 {
679 fmt.Fprintln(os.Stderr, "Directory argument is required")
680 os.Exit(1)
681 } else if flag.NArg() > 1 {
682 fmt.Fprintln(os.Stderr, "Multiple directories provided:", strings.Join(flag.Args(), " "))
683 os.Exit(1)
684 }
685
686 dir := flag.Arg(0)
687 absDir, err := filepath.Abs(dir)
688 if err != nil {
689 fmt.Fprintln(os.Stderr, "Failed to get absolute directory:", err)
690 os.Exit(1)
691 }
692
693 var filenames []string
694 err = filepath.Walk(absDir, func(path string, info os.FileInfo, err error) error {
695 if err != nil {
696 return err
697 }
698
699 name := info.Name()
700 if info.IsDir() {
701 if strings.HasPrefix(name, ".") {
702 return filepath.SkipDir
703 }
704 return nil
705 }
706
707 if strings.HasPrefix(name, ".") {
708 return nil
709 }
710
711 if strings.HasSuffix(name, ".pom") {
712 path, err = filepath.Rel(absDir, path)
713 if err != nil {
714 return err
715 }
716 filenames = append(filenames, filepath.Join(dir, path))
717 }
718 return nil
719 })
720 if err != nil {
721 fmt.Fprintln(os.Stderr, "Error walking files:", err)
722 os.Exit(1)
723 }
724
725 if len(filenames) == 0 {
726 fmt.Fprintln(os.Stderr, "Error: no *.pom files found under", dir)
727 os.Exit(1)
728 }
729
730 sort.Strings(filenames)
731
732 poms := []*Pom{}
733 modules := make(map[string]*Pom)
734 duplicate := false
735 for _, filename := range filenames {
736 pom, err := parse(filename)
737 if err != nil {
738 fmt.Fprintln(os.Stderr, "Error converting", filename, err)
739 os.Exit(1)
740 }
741
742 if pom != nil {
743 key := pom.BpName()
744 if excludes[key] {
745 continue
746 }
747
748 if old, ok := modules[key]; ok {
749 fmt.Fprintln(os.Stderr, "Module", key, "defined twice:", old.PomFile, pom.PomFile)
750 duplicate = true
751 }
752
753 poms = append(poms, pom)
754 modules[key] = pom
755 }
756 }
757 if duplicate {
758 os.Exit(1)
759 }
760
761 for _, pom := range poms {
Colin Crosscf53e602018-06-26 15:27:20 -0700762 if pom.IsAar() {
763 err := pom.ExtractMinSdkVersion()
764 if err != nil {
Colin Crossfe5a3b72018-07-13 21:25:15 -0700765 fmt.Fprintf(os.Stderr, "Error reading manifest for %s: %s", pom.ArtifactFile, err)
Colin Crosscf53e602018-06-26 15:27:20 -0700766 os.Exit(1)
767 }
768 }
Colin Cross70dd38f2018-04-16 13:52:10 -0700769 pom.FixDeps(modules)
770 }
771
772 buf := &bytes.Buffer{}
773
774 fmt.Fprintln(buf, "// Automatically generated with:")
Colin Cross0b9f31f2019-02-28 11:00:01 -0800775 fmt.Fprintln(buf, "// pom2bp", strings.Join(proptools.ShellEscapeList(os.Args[1:]), " "))
Colin Cross70dd38f2018-04-16 13:52:10 -0700776
777 for _, pom := range poms {
778 var err error
Dan Willemsen52c90d82019-04-21 21:37:39 -0700779 if staticDeps {
780 err = bpDepsTemplate.Execute(buf, pom)
781 } else {
782 err = bpTemplate.Execute(buf, pom)
783 }
Colin Cross70dd38f2018-04-16 13:52:10 -0700784 if err != nil {
785 fmt.Fprintln(os.Stderr, "Error writing", pom.PomFile, pom.BpName(), err)
786 os.Exit(1)
787 }
788 }
789
790 out, err := bpfix.Reformat(buf.String())
791 if err != nil {
792 fmt.Fprintln(os.Stderr, "Error formatting output", err)
793 os.Exit(1)
794 }
795
796 os.Stdout.WriteString(out)
797}