blob: f8844fc94798c40329ec6172a16cd33baeb9eb42 [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"
Romain Jobredeaux89cb2242021-09-20 14:14:22 +000027 "path"
Colin Cross70dd38f2018-04-16 13:52:10 -070028 "path/filepath"
29 "regexp"
30 "sort"
31 "strings"
32 "text/template"
33
34 "github.com/google/blueprint/proptools"
35
36 "android/soong/bpfix/bpfix"
37)
38
39type RewriteNames []RewriteName
40type RewriteName struct {
41 regexp *regexp.Regexp
42 repl string
43}
44
45func (r *RewriteNames) String() string {
46 return ""
47}
48
49func (r *RewriteNames) Set(v string) error {
50 split := strings.SplitN(v, "=", 2)
51 if len(split) != 2 {
52 return fmt.Errorf("Must be in the form of <regex>=<replace>")
53 }
54 regex, err := regexp.Compile(split[0])
55 if err != nil {
56 return nil
57 }
58 *r = append(*r, RewriteName{
59 regexp: regex,
60 repl: split[1],
61 })
62 return nil
63}
64
65func (r *RewriteNames) MavenToBp(groupId string, artifactId string) string {
66 for _, r := range *r {
67 if r.regexp.MatchString(groupId + ":" + artifactId) {
68 return r.regexp.ReplaceAllString(groupId+":"+artifactId, r.repl)
69 } else if r.regexp.MatchString(artifactId) {
70 return r.regexp.ReplaceAllString(artifactId, r.repl)
71 }
72 }
73 return artifactId
74}
75
76var rewriteNames = RewriteNames{}
77
78type ExtraDeps map[string][]string
79
80func (d ExtraDeps) String() string {
81 return ""
82}
83
84func (d ExtraDeps) Set(v string) error {
85 split := strings.SplitN(v, "=", 2)
86 if len(split) != 2 {
87 return fmt.Errorf("Must be in the form of <module>=<module>[,<module>]")
88 }
89 d[split[0]] = strings.Split(split[1], ",")
90 return nil
91}
92
Paul Duffinbabaf072019-04-16 11:35:20 +010093var extraStaticLibs = make(ExtraDeps)
94
95var extraLibs = make(ExtraDeps)
Colin Cross70dd38f2018-04-16 13:52:10 -070096
Alan Viverette24658d02021-08-31 20:00:52 +000097var optionalUsesLibs = make(ExtraDeps)
98
Colin Cross70dd38f2018-04-16 13:52:10 -070099type Exclude map[string]bool
100
101func (e Exclude) String() string {
102 return ""
103}
104
105func (e Exclude) Set(v string) error {
106 e[v] = true
107 return nil
108}
109
110var excludes = make(Exclude)
111
Jeff Gastond4928532018-08-24 14:30:13 -0400112type HostModuleNames map[string]bool
113
114func (n HostModuleNames) IsHostModule(groupId string, artifactId string) bool {
Colin Cross86bc9d42018-08-29 15:36:33 -0700115 _, found := n[groupId+":"+artifactId]
Jeff Gastond4928532018-08-24 14:30:13 -0400116 return found
117}
118
119func (n HostModuleNames) String() string {
120 return ""
121}
122
123func (n HostModuleNames) Set(v string) error {
124 n[v] = true
125 return nil
126}
127
128var hostModuleNames = HostModuleNames{}
129
Tony Mak81785002019-07-18 21:36:44 +0100130type HostAndDeviceModuleNames map[string]bool
131
132func (n HostAndDeviceModuleNames) IsHostAndDeviceModule(groupId string, artifactId string) bool {
133 _, found := n[groupId+":"+artifactId]
134
135 return found
136}
137
138func (n HostAndDeviceModuleNames) String() string {
139 return ""
140}
141
142func (n HostAndDeviceModuleNames) Set(v string) error {
143 n[v] = true
144 return nil
145}
146
147var hostAndDeviceModuleNames = HostAndDeviceModuleNames{}
148
Colin Cross70dd38f2018-04-16 13:52:10 -0700149var sdkVersion string
Anton Hanssonc29f0762021-03-29 16:10:06 +0100150var defaultMinSdkVersion string
Colin Cross70dd38f2018-04-16 13:52:10 -0700151var useVersion string
Dan Willemsen52c90d82019-04-21 21:37:39 -0700152var staticDeps bool
Dan Willemsen7fdab6e2019-04-20 21:47:14 -0700153var jetifier bool
Colin Cross70dd38f2018-04-16 13:52:10 -0700154
155func InList(s string, list []string) bool {
156 for _, l := range list {
157 if l == s {
158 return true
159 }
160 }
161
162 return false
163}
164
165type Dependency struct {
166 XMLName xml.Name `xml:"dependency"`
167
Romain Jobredeaux89cb2242021-09-20 14:14:22 +0000168 BpTarget string `xml:"-"`
169 BazelTarget string `xml:"-"`
Colin Cross70dd38f2018-04-16 13:52:10 -0700170
171 GroupId string `xml:"groupId"`
172 ArtifactId string `xml:"artifactId"`
173 Version string `xml:"version"`
174 Type string `xml:"type"`
175 Scope string `xml:"scope"`
176}
177
178func (d Dependency) BpName() string {
179 if d.BpTarget == "" {
180 d.BpTarget = rewriteNames.MavenToBp(d.GroupId, d.ArtifactId)
181 }
182 return d.BpTarget
183}
184
185type Pom struct {
186 XMLName xml.Name `xml:"http://maven.apache.org/POM/4.0.0 project"`
187
Colin Crosscf53e602018-06-26 15:27:20 -0700188 PomFile string `xml:"-"`
189 ArtifactFile string `xml:"-"`
190 BpTarget string `xml:"-"`
191 MinSdkVersion string `xml:"-"`
Colin Cross70dd38f2018-04-16 13:52:10 -0700192
193 GroupId string `xml:"groupId"`
194 ArtifactId string `xml:"artifactId"`
195 Version string `xml:"version"`
196 Packaging string `xml:"packaging"`
197
198 Dependencies []*Dependency `xml:"dependencies>dependency"`
199}
200
201func (p Pom) IsAar() bool {
202 return p.Packaging == "aar"
203}
204
205func (p Pom) IsJar() bool {
206 return p.Packaging == "jar"
207}
208
Jeff Gastond4928532018-08-24 14:30:13 -0400209func (p Pom) IsHostModule() bool {
210 return hostModuleNames.IsHostModule(p.GroupId, p.ArtifactId)
211}
212
213func (p Pom) IsDeviceModule() bool {
214 return !p.IsHostModule()
215}
216
Tony Mak81785002019-07-18 21:36:44 +0100217func (p Pom) IsHostAndDeviceModule() bool {
218 return hostAndDeviceModuleNames.IsHostAndDeviceModule(p.GroupId, p.ArtifactId)
219}
220
Jooyung Han43d30252020-05-22 03:54:24 +0900221func (p Pom) IsHostOnly() bool {
222 return p.IsHostModule() && !p.IsHostAndDeviceModule()
223}
224
Colin Cross632987a2018-08-29 16:17:55 -0700225func (p Pom) ModuleType() string {
226 if p.IsAar() {
227 return "android_library"
Jooyung Han43d30252020-05-22 03:54:24 +0900228 } else if p.IsHostOnly() {
Colin Cross632987a2018-08-29 16:17:55 -0700229 return "java_library_host"
230 } else {
231 return "java_library_static"
232 }
233}
234
Romain Jobredeaux89cb2242021-09-20 14:14:22 +0000235func (p Pom) BazelTargetType() string {
236 if p.IsAar() {
237 return "android_library"
238 } else {
239 return "java_library"
240 }
241}
242
Colin Cross632987a2018-08-29 16:17:55 -0700243func (p Pom) ImportModuleType() string {
244 if p.IsAar() {
245 return "android_library_import"
Jooyung Han43d30252020-05-22 03:54:24 +0900246 } else if p.IsHostOnly() {
Colin Cross632987a2018-08-29 16:17:55 -0700247 return "java_import_host"
248 } else {
249 return "java_import"
250 }
251}
252
Romain Jobredeaux89cb2242021-09-20 14:14:22 +0000253func (p Pom) BazelImportTargetType() string {
254 if p.IsAar() {
255 return "aar_import"
256 } else {
257 return "java_import"
258 }
259}
260
Colin Cross632987a2018-08-29 16:17:55 -0700261func (p Pom) ImportProperty() string {
262 if p.IsAar() {
263 return "aars"
264 } else {
265 return "jars"
266 }
267}
268
Romain Jobredeaux89cb2242021-09-20 14:14:22 +0000269func (p Pom) BazelImportProperty() string {
270 if p.IsAar() {
271 return "aar"
272 } else {
273 return "jars"
274 }
275}
276
Colin Cross70dd38f2018-04-16 13:52:10 -0700277func (p Pom) BpName() string {
278 if p.BpTarget == "" {
279 p.BpTarget = rewriteNames.MavenToBp(p.GroupId, p.ArtifactId)
280 }
281 return p.BpTarget
282}
283
284func (p Pom) BpJarDeps() []string {
285 return p.BpDeps("jar", []string{"compile", "runtime"})
286}
287
288func (p Pom) BpAarDeps() []string {
289 return p.BpDeps("aar", []string{"compile", "runtime"})
290}
291
Romain Jobredeaux89cb2242021-09-20 14:14:22 +0000292func (p Pom) BazelJarDeps() []string {
293 return p.BazelDeps("jar", []string{"compile", "runtime"})
294}
295
296func (p Pom) BazelAarDeps() []string {
297 return p.BazelDeps("aar", []string{"compile", "runtime"})
298}
299
Paul Duffinbabaf072019-04-16 11:35:20 +0100300func (p Pom) BpExtraStaticLibs() []string {
301 return extraStaticLibs[p.BpName()]
302}
303
304func (p Pom) BpExtraLibs() []string {
305 return extraLibs[p.BpName()]
Colin Cross70dd38f2018-04-16 13:52:10 -0700306}
307
Alan Viverette24658d02021-08-31 20:00:52 +0000308func (p Pom) BpOptionalUsesLibs() []string {
309 return optionalUsesLibs[p.BpName()]
310}
311
Colin Cross70dd38f2018-04-16 13:52:10 -0700312// BpDeps obtains dependencies filtered by type and scope. The results of this
313// method are formatted as Android.bp targets, e.g. run through MavenToBp rules.
314func (p Pom) BpDeps(typeExt string, scopes []string) []string {
315 var ret []string
316 for _, d := range p.Dependencies {
317 if d.Type != typeExt || !InList(d.Scope, scopes) {
318 continue
319 }
320 name := rewriteNames.MavenToBp(d.GroupId, d.ArtifactId)
321 ret = append(ret, name)
322 }
323 return ret
324}
325
Romain Jobredeaux89cb2242021-09-20 14:14:22 +0000326// BazelDeps obtains dependencies filtered by type and scope. The results of this
327// method are formatted as Bazel BUILD targets.
328func (p Pom) BazelDeps(typeExt string, scopes []string) []string {
329 var ret []string
330 for _, d := range p.Dependencies {
331 if d.Type != typeExt || !InList(d.Scope, scopes) {
332 continue
333 }
334 ret = append(ret, d.BazelTarget)
335 }
336 return ret
337}
338
339func PathModVars() (string, string, string) {
340 cmd := "/bin/bash"
341 androidTop := os.Getenv("ANDROID_BUILD_TOP")
342 envSetupSh := path.Join(androidTop, "build/envsetup.sh")
343 return cmd, androidTop, envSetupSh
344}
345
346func InitRefreshMod(poms []*Pom) error {
347 cmd, _, envSetupSh := PathModVars()
348 // refreshmod is expensive, so if pathmod is already working we can skip it.
349 _, err := exec.Command(cmd, "-c", ". "+envSetupSh+" && pathmod "+poms[0].BpName()).Output()
350 if exitErr, _ := err.(*exec.ExitError); exitErr != nil || err != nil {
351 _, err := exec.Command(cmd, "-c", ". "+envSetupSh+" && refreshmod").Output()
352 if exitErr, _ := err.(*exec.ExitError); exitErr != nil {
353 return fmt.Errorf("failed to run %s\n%s\ntry running lunch.", cmd, string(exitErr.Stderr))
354 } else if err != nil {
355 return err
356 }
357 }
358 return nil
359}
360
361func BazelifyExtraDeps(extraDeps ExtraDeps, modules map[string]*Pom) error {
362 for _, deps := range extraDeps {
363 for _, dep := range deps {
364 bazelName, err := BpNameToBazelTarget(dep, modules)
365 if err != nil {
366 return err
367 }
368 dep = bazelName
369 }
370
371 }
372 return nil
373}
374
375func (p *Pom) GetBazelDepNames(modules map[string]*Pom) error {
376 for _, d := range p.Dependencies {
377 bazelName, err := BpNameToBazelTarget(d.BpName(), modules)
378 if err != nil {
379 return err
380 }
381 d.BazelTarget = bazelName
382 }
383 return nil
384}
385
386func BpNameToBazelTarget(bpName string, modules map[string]*Pom) (string, error) {
387 cmd, androidTop, envSetupSh := PathModVars()
388
389 if _, ok := modules[bpName]; ok {
390 // We've seen the POM for this dependency, it will be local to the output BUILD file
391 return ":" + bpName, nil
392 } else {
393 // we don't have the POM for this artifact, find and use the fully qualified target name.
394 output, err := exec.Command(cmd, "-c", ". "+envSetupSh+" && pathmod "+bpName).Output()
395 if exitErr, _ := err.(*exec.ExitError); exitErr != nil {
396 return "", fmt.Errorf("failed to run %s %s\n%s", cmd, bpName, string(exitErr.Stderr))
397 } else if err != nil {
398 return "", err
399 }
400 relPath := ""
401 for _, line := range strings.Fields(string(output)) {
402 if strings.Contains(line, androidTop) {
403 relPath = strings.TrimPrefix(line, androidTop)
404 relPath = strings.TrimLeft(relPath, "/")
405 }
406 }
407 return "//" + relPath + ":" + bpName, nil
408 }
409}
410
Colin Cross70dd38f2018-04-16 13:52:10 -0700411func (p Pom) SdkVersion() string {
412 return sdkVersion
413}
414
Anton Hanssonc29f0762021-03-29 16:10:06 +0100415func (p Pom) DefaultMinSdkVersion() string {
416 return defaultMinSdkVersion
417}
418
Dan Willemsen7fdab6e2019-04-20 21:47:14 -0700419func (p Pom) Jetifier() bool {
420 return jetifier
421}
422
Colin Cross70dd38f2018-04-16 13:52:10 -0700423func (p *Pom) FixDeps(modules map[string]*Pom) {
424 for _, d := range p.Dependencies {
425 if d.Type == "" {
426 if depPom, ok := modules[d.BpName()]; ok {
427 // We've seen the POM for this dependency, use its packaging
428 // as the dependency type rather than Maven spec default.
429 d.Type = depPom.Packaging
430 } else {
431 // Dependency type was not specified and we don't have the POM
432 // for this artifact, use the default from Maven spec.
433 d.Type = "jar"
434 }
435 }
436 if d.Scope == "" {
437 // Scope was not specified, use the default from Maven spec.
438 d.Scope = "compile"
439 }
440 }
441}
442
Colin Crosscf53e602018-06-26 15:27:20 -0700443// ExtractMinSdkVersion extracts the minSdkVersion from the AndroidManifest.xml file inside an aar file, or sets it
444// to "current" if it is not present.
445func (p *Pom) ExtractMinSdkVersion() error {
446 aar, err := zip.OpenReader(p.ArtifactFile)
447 if err != nil {
448 return err
449 }
450 defer aar.Close()
451
452 var manifest *zip.File
453 for _, f := range aar.File {
454 if f.Name == "AndroidManifest.xml" {
455 manifest = f
456 break
457 }
458 }
459
460 if manifest == nil {
461 return fmt.Errorf("failed to find AndroidManifest.xml in %s", p.ArtifactFile)
462 }
463
464 r, err := manifest.Open()
465 if err != nil {
466 return err
467 }
468 defer r.Close()
469
470 decoder := xml.NewDecoder(r)
471
472 manifestData := struct {
473 XMLName xml.Name `xml:"manifest"`
474 Uses_sdk struct {
475 MinSdkVersion string `xml:"http://schemas.android.com/apk/res/android minSdkVersion,attr"`
476 } `xml:"uses-sdk"`
477 }{}
478
479 err = decoder.Decode(&manifestData)
480 if err != nil {
481 return err
482 }
483
484 p.MinSdkVersion = manifestData.Uses_sdk.MinSdkVersion
485 if p.MinSdkVersion == "" {
486 p.MinSdkVersion = "current"
487 }
488
489 return nil
490}
491
Colin Cross70dd38f2018-04-16 13:52:10 -0700492var bpTemplate = template.Must(template.New("bp").Parse(`
Colin Cross632987a2018-08-29 16:17:55 -0700493{{.ImportModuleType}} {
Dan Willemsen52c90d82019-04-21 21:37:39 -0700494 name: "{{.BpName}}",
495 {{.ImportProperty}}: ["{{.ArtifactFile}}"],
496 sdk_version: "{{.SdkVersion}}",
497 {{- if .Jetifier}}
498 jetifier: true,
499 {{- end}}
Tony Mak81785002019-07-18 21:36:44 +0100500 {{- if .IsHostAndDeviceModule}}
501 host_supported: true,
502 {{- end}}
Jooyung Han43d30252020-05-22 03:54:24 +0900503 {{- if not .IsHostOnly}}
504 apex_available: [
505 "//apex_available:platform",
506 "//apex_available:anyapex",
507 ],
508 {{- end}}
Dan Willemsen52c90d82019-04-21 21:37:39 -0700509 {{- if .IsAar}}
510 min_sdk_version: "{{.MinSdkVersion}}",
511 static_libs: [
512 {{- range .BpJarDeps}}
513 "{{.}}",
514 {{- end}}
515 {{- range .BpAarDeps}}
516 "{{.}}",
517 {{- end}}
518 {{- range .BpExtraStaticLibs}}
519 "{{.}}",
520 {{- end}}
521 ],
522 {{- if .BpExtraLibs}}
523 libs: [
524 {{- range .BpExtraLibs}}
525 "{{.}}",
526 {{- end}}
527 ],
Alan Viverettebcbfc5f2021-09-13 17:12:28 +0000528 {{- end}}
Alan Viverette24658d02021-08-31 20:00:52 +0000529 {{- if .BpOptionalUsesLibs}}
530 optional_uses_libs: [
531 {{- range .BpOptionalUsesLibs}}
532 "{{.}}",
533 {{- end}}
534 ],
Dan Willemsen52c90d82019-04-21 21:37:39 -0700535 {{- end}}
Anton Hanssonebfbad22021-04-06 19:21:34 +0000536 {{- else if not .IsHostOnly}}
537 min_sdk_version: "{{.DefaultMinSdkVersion}}",
Dan Willemsen52c90d82019-04-21 21:37:39 -0700538 {{- end}}
539}
540`))
541
542var bpDepsTemplate = template.Must(template.New("bp").Parse(`
543{{.ImportModuleType}} {
Colin Cross70dd38f2018-04-16 13:52:10 -0700544 name: "{{.BpName}}-nodeps",
Colin Cross632987a2018-08-29 16:17:55 -0700545 {{.ImportProperty}}: ["{{.ArtifactFile}}"],
546 sdk_version: "{{.SdkVersion}}",
Dan Willemsen7fdab6e2019-04-20 21:47:14 -0700547 {{- if .Jetifier}}
548 jetifier: true,
549 {{- end}}
Tony Mak81785002019-07-18 21:36:44 +0100550 {{- if .IsHostAndDeviceModule}}
551 host_supported: true,
552 {{- end}}
Jooyung Han43d30252020-05-22 03:54:24 +0900553 {{- if not .IsHostOnly}}
554 apex_available: [
555 "//apex_available:platform",
556 "//apex_available:anyapex",
557 ],
558 {{- end}}
Colin Cross632987a2018-08-29 16:17:55 -0700559 {{- if .IsAar}}
Colin Crosscf53e602018-06-26 15:27:20 -0700560 min_sdk_version: "{{.MinSdkVersion}}",
Colin Cross632987a2018-08-29 16:17:55 -0700561 static_libs: [
Colin Cross1aa7f262019-04-10 11:07:15 -0700562 {{- range .BpJarDeps}}
563 "{{.}}",
564 {{- end}}
Colin Cross632987a2018-08-29 16:17:55 -0700565 {{- range .BpAarDeps}}
566 "{{.}}",
567 {{- end}}
Paul Duffinbabaf072019-04-16 11:35:20 +0100568 {{- range .BpExtraStaticLibs}}
Colin Cross632987a2018-08-29 16:17:55 -0700569 "{{.}}",
570 {{- end}}
571 ],
Paul Duffinbabaf072019-04-16 11:35:20 +0100572 {{- if .BpExtraLibs}}
573 libs: [
574 {{- range .BpExtraLibs}}
575 "{{.}}",
576 {{- end}}
577 ],
578 {{- end}}
Anton Hanssonebfbad22021-04-06 19:21:34 +0000579 {{- else if not .IsHostOnly}}
580 min_sdk_version: "{{.DefaultMinSdkVersion}}",
Colin Cross632987a2018-08-29 16:17:55 -0700581 {{- end}}
Colin Cross70dd38f2018-04-16 13:52:10 -0700582}
583
Colin Cross632987a2018-08-29 16:17:55 -0700584{{.ModuleType}} {
585 name: "{{.BpName}}",
586 {{- if .IsDeviceModule}}
587 sdk_version: "{{.SdkVersion}}",
Tony Mak81785002019-07-18 21:36:44 +0100588 {{- if .IsHostAndDeviceModule}}
589 host_supported: true,
590 {{- end}}
Jooyung Han43d30252020-05-22 03:54:24 +0900591 {{- if not .IsHostOnly}}
592 apex_available: [
593 "//apex_available:platform",
594 "//apex_available:anyapex",
595 ],
596 {{- end}}
Colin Cross632987a2018-08-29 16:17:55 -0700597 {{- if .IsAar}}
Colin Cross461ba492018-07-10 13:45:30 -0700598 min_sdk_version: "{{.MinSdkVersion}}",
Colin Cross632987a2018-08-29 16:17:55 -0700599 manifest: "manifests/{{.BpName}}/AndroidManifest.xml",
Jooyung Han43d30252020-05-22 03:54:24 +0900600 {{- else if not .IsHostOnly}}
Anton Hanssonc29f0762021-03-29 16:10:06 +0100601 min_sdk_version: "{{.DefaultMinSdkVersion}}",
Colin Cross632987a2018-08-29 16:17:55 -0700602 {{- end}}
603 {{- end}}
Colin Cross70dd38f2018-04-16 13:52:10 -0700604 static_libs: [
Colin Cross632987a2018-08-29 16:17:55 -0700605 "{{.BpName}}-nodeps",
Colin Cross1aa7f262019-04-10 11:07:15 -0700606 {{- range .BpJarDeps}}
Colin Cross632987a2018-08-29 16:17:55 -0700607 "{{.}}",
608 {{- end}}
609 {{- range .BpAarDeps}}
610 "{{.}}",
611 {{- end}}
Paul Duffinbabaf072019-04-16 11:35:20 +0100612 {{- range .BpExtraStaticLibs}}
Colin Cross632987a2018-08-29 16:17:55 -0700613 "{{.}}",
614 {{- end}}
Colin Cross70dd38f2018-04-16 13:52:10 -0700615 ],
Paul Duffinbabaf072019-04-16 11:35:20 +0100616 {{- if .BpExtraLibs}}
617 libs: [
618 {{- range .BpExtraLibs}}
619 "{{.}}",
620 {{- end}}
621 ],
Alan Viverettebcbfc5f2021-09-13 17:12:28 +0000622 {{- end}}
Alan Viverette24658d02021-08-31 20:00:52 +0000623 {{- if .BpOptionalUsesLibs}}
624 optional_uses_libs: [
625 {{- range .BpOptionalUsesLibs}}
626 "{{.}}",
627 {{- end}}
628 ],
Paul Duffinbabaf072019-04-16 11:35:20 +0100629 {{- end}}
Colin Cross70dd38f2018-04-16 13:52:10 -0700630 java_version: "1.7",
631}
632`))
633
Romain Jobredeaux89cb2242021-09-20 14:14:22 +0000634var bazelTemplate = template.Must(template.New("bp").Parse(`
635{{.BazelImportTargetType}} (
636 name = "{{.BpName}}",
637 {{.BazelImportProperty}}: {{- if not .IsAar}}[{{- end}}"{{.ArtifactFile}}"{{- if not .IsAar}}]{{- end}},
638 visibility = ["//visibility:public"],
639 {{- if .IsAar}}
640 deps = [
641 {{- range .BazelJarDeps}}
642 "{{.}}",
643 {{- end}}
644 {{- range .BazelAarDeps}}
645 "{{.}}",
646 {{- end}}
647 {{- range .BpExtraStaticLibs}}
648 "{{.}}",
649 {{- end}}
650 {{- range .BpExtraLibs}}
651 "{{.}}",
652 {{- end}}
653 {{- range .BpOptionalUsesLibs}}
654 "{{.}}",
655 {{- end}}
656 ],
657 {{- end}}
658)
659`))
660
661var bazelDepsTemplate = template.Must(template.New("bp").Parse(`
662{{.BazelImportTargetType}} (
663 name = "{{.BpName}}",
664 {{.BazelImportProperty}} = {{- if not .IsAar}}[{{- end}}"{{.ArtifactFile}}"{{- if not .IsAar}}]{{- end}},
665 visibility = ["//visibility:public"],
Romain Jobredeaux89cb2242021-09-20 14:14:22 +0000666 exports = [
667 {{- range .BazelJarDeps}}
668 "{{.}}",
669 {{- end}}
670 {{- range .BazelAarDeps}}
671 "{{.}}",
672 {{- end}}
673 {{- range .BpExtraStaticLibs}}
674 "{{.}}",
675 {{- end}}
676 {{- range .BpExtraLibs}}
677 "{{.}}",
678 {{- end}}
679 {{- range .BpOptionalUsesLibs}}
680 "{{.}}",
681 {{- end}}
682 ],
683)
684`))
685
Colin Cross70dd38f2018-04-16 13:52:10 -0700686func parse(filename string) (*Pom, error) {
687 data, err := ioutil.ReadFile(filename)
688 if err != nil {
689 return nil, err
690 }
691
692 var pom Pom
693 err = xml.Unmarshal(data, &pom)
694 if err != nil {
695 return nil, err
696 }
697
698 if useVersion != "" && pom.Version != useVersion {
699 return nil, nil
700 }
701
702 if pom.Packaging == "" {
703 pom.Packaging = "jar"
704 }
705
706 pom.PomFile = filename
707 pom.ArtifactFile = strings.TrimSuffix(filename, ".pom") + "." + pom.Packaging
708
709 return &pom, nil
710}
711
712func rerunForRegen(filename string) error {
713 buf, err := ioutil.ReadFile(filename)
714 if err != nil {
715 return err
716 }
717
718 scanner := bufio.NewScanner(bytes.NewBuffer(buf))
719
720 // Skip the first line in the file
721 for i := 0; i < 2; i++ {
722 if !scanner.Scan() {
723 if scanner.Err() != nil {
724 return scanner.Err()
725 } else {
726 return fmt.Errorf("unexpected EOF")
727 }
728 }
729 }
730
731 // Extract the old args from the file
732 line := scanner.Text()
Romain Jobredeaux89cb2242021-09-20 14:14:22 +0000733 if strings.HasPrefix(line, "// pom2bp ") { // .bp file
Colin Cross70dd38f2018-04-16 13:52:10 -0700734 line = strings.TrimPrefix(line, "// pom2bp ")
Romain Jobredeaux89cb2242021-09-20 14:14:22 +0000735 } else if strings.HasPrefix(line, "// pom2mk ") { // .bp file converted from .mk file
Colin Cross70dd38f2018-04-16 13:52:10 -0700736 line = strings.TrimPrefix(line, "// pom2mk ")
Romain Jobredeaux89cb2242021-09-20 14:14:22 +0000737 } else if strings.HasPrefix(line, "# pom2mk ") { // .mk file
Colin Cross70dd38f2018-04-16 13:52:10 -0700738 line = strings.TrimPrefix(line, "# pom2mk ")
Romain Jobredeaux89cb2242021-09-20 14:14:22 +0000739 } else if strings.HasPrefix(line, "# pom2bp ") { // Bazel BUILD file
740 line = strings.TrimPrefix(line, "# pom2bp ")
Colin Cross70dd38f2018-04-16 13:52:10 -0700741 } else {
742 return fmt.Errorf("unexpected second line: %q", line)
743 }
744 args := strings.Split(line, " ")
745 lastArg := args[len(args)-1]
746 args = args[:len(args)-1]
747
748 // Append all current command line args except -regen <file> to the ones from the file
749 for i := 1; i < len(os.Args); i++ {
Colin Crosscf53e602018-06-26 15:27:20 -0700750 if os.Args[i] == "-regen" || os.Args[i] == "--regen" {
Colin Cross70dd38f2018-04-16 13:52:10 -0700751 i++
752 } else {
753 args = append(args, os.Args[i])
754 }
755 }
756 args = append(args, lastArg)
757
758 cmd := os.Args[0] + " " + strings.Join(args, " ")
759 // Re-exec pom2bp with the new arguments
760 output, err := exec.Command("/bin/sh", "-c", cmd).Output()
761 if exitErr, _ := err.(*exec.ExitError); exitErr != nil {
762 return fmt.Errorf("failed to run %s\n%s", cmd, string(exitErr.Stderr))
763 } else if err != nil {
764 return err
765 }
766
767 // If the old file was a .mk file, replace it with a .bp file
768 if filepath.Ext(filename) == ".mk" {
769 os.Remove(filename)
770 filename = strings.TrimSuffix(filename, ".mk") + ".bp"
771 }
772
773 return ioutil.WriteFile(filename, output, 0666)
774}
775
776func main() {
777 flag.Usage = func() {
778 fmt.Fprintf(os.Stderr, `pom2bp, a tool to create Android.bp files from maven repos
779
780The tool will extract the necessary information from *.pom files to create an Android.bp whose
781aar libraries can be linked against when using AAPT2.
782
Alan Viverette24658d02021-08-31 20:00:52 +0000783Usage: %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 -0700784
785 -rewrite <regex>=<replace>
786 rewrite can be used to specify mappings between Maven projects and Android.bp modules. The -rewrite
787 option can be specified multiple times. When determining the Android.bp module for a given Maven
788 project, mappings are searched in the order they were specified. The first <regex> matching
789 either the Maven project's <groupId>:<artifactId> or <artifactId> will be used to generate
790 the Android.bp module name using <replace>. If no matches are found, <artifactId> is used.
791 -exclude <module>
792 Don't put the specified module in the Android.bp file.
Paul Duffinbabaf072019-04-16 11:35:20 +0100793 -extra-static-libs <module>=<module>[,<module>]
794 Some Android.bp modules have transitive static dependencies that must be specified when they
795 are depended upon (like android-support-v7-mediarouter requires android-support-v7-appcompat).
796 This may be specified multiple times to declare these dependencies.
797 -extra-libs <module>=<module>[,<module>]
798 Some Android.bp modules have transitive runtime dependencies that must be specified when they
799 are depended upon (like androidx.test.rules requires android.test.base).
Colin Cross70dd38f2018-04-16 13:52:10 -0700800 This may be specified multiple times to declare these dependencies.
Alan Viverette24658d02021-08-31 20:00:52 +0000801 -optional-uses-libs <module>=<module>[,<module>]
802 Some Android.bp modules have optional dependencies (typically specified with <uses-library> in
803 the module's AndroidManifest.xml) that must be specified when they are depended upon (like
804 androidx.window:window optionally requires androidx.window:window-extensions).
805 This may be specified multiple times to declare these dependencies.
Colin Cross70dd38f2018-04-16 13:52:10 -0700806 -sdk-version <version>
Dan Willemsen7fdab6e2019-04-20 21:47:14 -0700807 Sets sdk_version: "<version>" for all modules.
Anton Hanssonc29f0762021-03-29 16:10:06 +0100808 -default-min-sdk-version
809 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 -0700810 -use-version <version>
811 If the maven directory contains multiple versions of artifacts and their pom files,
812 -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 -0700813 -jetifier
814 Sets jetifier: true for all modules.
Colin Cross70dd38f2018-04-16 13:52:10 -0700815 <dir>
816 The directory to search for *.pom files under.
817 The contents are written to stdout, to be put in the current directory (often as Android.bp)
818 -regen <file>
819 Read arguments from <file> and overwrite it (if it ends with .bp) or move it to .bp (if it
820 ends with .mk).
821
822`, os.Args[0])
823 }
824
825 var regen string
Romain Jobredeaux89cb2242021-09-20 14:14:22 +0000826 var pom2build bool
Colin Cross70dd38f2018-04-16 13:52:10 -0700827
828 flag.Var(&excludes, "exclude", "Exclude module")
Paul Duffinbabaf072019-04-16 11:35:20 +0100829 flag.Var(&extraStaticLibs, "extra-static-libs", "Extra static dependencies needed when depending on a module")
830 flag.Var(&extraLibs, "extra-libs", "Extra runtime dependencies needed when depending on a module")
Alan Viverette24658d02021-08-31 20:00:52 +0000831 flag.Var(&optionalUsesLibs, "optional-uses-libs", "Extra optional dependencies needed when depending on a module")
Colin Cross70dd38f2018-04-16 13:52:10 -0700832 flag.Var(&rewriteNames, "rewrite", "Regex(es) to rewrite artifact names")
Jeff Gastond4928532018-08-24 14:30:13 -0400833 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 +0100834 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 -0700835 flag.StringVar(&sdkVersion, "sdk-version", "", "What to write to sdk_version")
Anton Hanssonc29f0762021-03-29 16:10:06 +0100836 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 -0700837 flag.StringVar(&useVersion, "use-version", "", "Only read artifacts of a specific version")
Dan Willemsen52c90d82019-04-21 21:37:39 -0700838 flag.BoolVar(&staticDeps, "static-deps", false, "Statically include direct dependencies")
Dan Willemsen7fdab6e2019-04-20 21:47:14 -0700839 flag.BoolVar(&jetifier, "jetifier", false, "Sets jetifier: true on all modules")
Colin Cross70dd38f2018-04-16 13:52:10 -0700840 flag.StringVar(&regen, "regen", "", "Rewrite specified file")
Romain Jobredeaux89cb2242021-09-20 14:14:22 +0000841 flag.BoolVar(&pom2build, "pom2build", false, "If true, will generate a Bazel BUILD file *instead* of a .bp file")
Colin Cross70dd38f2018-04-16 13:52:10 -0700842 flag.Parse()
843
844 if regen != "" {
845 err := rerunForRegen(regen)
846 if err != nil {
847 fmt.Fprintln(os.Stderr, err)
848 os.Exit(1)
849 }
850 os.Exit(0)
851 }
852
853 if flag.NArg() == 0 {
854 fmt.Fprintln(os.Stderr, "Directory argument is required")
855 os.Exit(1)
856 } else if flag.NArg() > 1 {
857 fmt.Fprintln(os.Stderr, "Multiple directories provided:", strings.Join(flag.Args(), " "))
858 os.Exit(1)
859 }
860
861 dir := flag.Arg(0)
862 absDir, err := filepath.Abs(dir)
863 if err != nil {
864 fmt.Fprintln(os.Stderr, "Failed to get absolute directory:", err)
865 os.Exit(1)
866 }
867
868 var filenames []string
869 err = filepath.Walk(absDir, func(path string, info os.FileInfo, err error) error {
870 if err != nil {
871 return err
872 }
873
874 name := info.Name()
875 if info.IsDir() {
876 if strings.HasPrefix(name, ".") {
877 return filepath.SkipDir
878 }
879 return nil
880 }
881
882 if strings.HasPrefix(name, ".") {
883 return nil
884 }
885
886 if strings.HasSuffix(name, ".pom") {
887 path, err = filepath.Rel(absDir, path)
888 if err != nil {
889 return err
890 }
891 filenames = append(filenames, filepath.Join(dir, path))
892 }
893 return nil
894 })
895 if err != nil {
896 fmt.Fprintln(os.Stderr, "Error walking files:", err)
897 os.Exit(1)
898 }
899
900 if len(filenames) == 0 {
901 fmt.Fprintln(os.Stderr, "Error: no *.pom files found under", dir)
902 os.Exit(1)
903 }
904
905 sort.Strings(filenames)
906
907 poms := []*Pom{}
908 modules := make(map[string]*Pom)
909 duplicate := false
910 for _, filename := range filenames {
911 pom, err := parse(filename)
912 if err != nil {
913 fmt.Fprintln(os.Stderr, "Error converting", filename, err)
914 os.Exit(1)
915 }
916
917 if pom != nil {
918 key := pom.BpName()
919 if excludes[key] {
920 continue
921 }
922
923 if old, ok := modules[key]; ok {
924 fmt.Fprintln(os.Stderr, "Module", key, "defined twice:", old.PomFile, pom.PomFile)
925 duplicate = true
926 }
927
928 poms = append(poms, pom)
929 modules[key] = pom
930 }
931 }
932 if duplicate {
933 os.Exit(1)
934 }
935
Romain Jobredeaux89cb2242021-09-20 14:14:22 +0000936 if pom2build {
937 if err := InitRefreshMod(poms); err != nil {
938 fmt.Fprintf(os.Stderr, "Error in refreshmod: %s", err)
939 os.Exit(1)
940 }
941 BazelifyExtraDeps(extraStaticLibs, modules)
942 BazelifyExtraDeps(extraLibs, modules)
943 BazelifyExtraDeps(optionalUsesLibs, modules)
944 }
945
Colin Cross70dd38f2018-04-16 13:52:10 -0700946 for _, pom := range poms {
Colin Crosscf53e602018-06-26 15:27:20 -0700947 if pom.IsAar() {
948 err := pom.ExtractMinSdkVersion()
949 if err != nil {
Colin Crossfe5a3b72018-07-13 21:25:15 -0700950 fmt.Fprintf(os.Stderr, "Error reading manifest for %s: %s", pom.ArtifactFile, err)
Colin Crosscf53e602018-06-26 15:27:20 -0700951 os.Exit(1)
952 }
953 }
Colin Cross70dd38f2018-04-16 13:52:10 -0700954 pom.FixDeps(modules)
Romain Jobredeaux89cb2242021-09-20 14:14:22 +0000955 if pom2build {
956 pom.GetBazelDepNames(modules)
957 }
Colin Cross70dd38f2018-04-16 13:52:10 -0700958 }
959
960 buf := &bytes.Buffer{}
Romain Jobredeaux89cb2242021-09-20 14:14:22 +0000961 commentString := "//"
962 if pom2build {
963 commentString = "#"
964 }
965 fmt.Fprintln(buf, commentString, "Automatically generated with:")
966 fmt.Fprintln(buf, commentString, "pom2bp", strings.Join(proptools.ShellEscapeList(os.Args[1:]), " "))
Colin Cross70dd38f2018-04-16 13:52:10 -0700967
Romain Jobredeaux89cb2242021-09-20 14:14:22 +0000968 depsTemplate := bpDepsTemplate
969 template := bpTemplate
970 if pom2build {
971 depsTemplate = bazelDepsTemplate
972 template = bazelTemplate
973 }
Colin Cross70dd38f2018-04-16 13:52:10 -0700974
975 for _, pom := range poms {
976 var err error
Dan Willemsen52c90d82019-04-21 21:37:39 -0700977 if staticDeps {
Romain Jobredeaux89cb2242021-09-20 14:14:22 +0000978 err = depsTemplate.Execute(buf, pom)
Dan Willemsen52c90d82019-04-21 21:37:39 -0700979 } else {
Romain Jobredeaux89cb2242021-09-20 14:14:22 +0000980 err = template.Execute(buf, pom)
Dan Willemsen52c90d82019-04-21 21:37:39 -0700981 }
Colin Cross70dd38f2018-04-16 13:52:10 -0700982 if err != nil {
983 fmt.Fprintln(os.Stderr, "Error writing", pom.PomFile, pom.BpName(), err)
984 os.Exit(1)
985 }
986 }
987
Romain Jobredeaux89cb2242021-09-20 14:14:22 +0000988 if pom2build {
989 os.Stdout.WriteString(buf.String())
990 } else {
991 out, err := bpfix.Reformat(buf.String())
992 if err != nil {
993 fmt.Fprintln(os.Stderr, "Error formatting output", err)
994 os.Exit(1)
995 }
996 os.Stdout.WriteString(out)
Colin Cross70dd38f2018-04-16 13:52:10 -0700997 }
998
Colin Cross70dd38f2018-04-16 13:52:10 -0700999}