blob: d9116b081c6a7b12ca5cbe16e35b9b8b9032db0d [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
Tony Mak81785002019-07-18 21:36:44 +0100127type HostAndDeviceModuleNames map[string]bool
128
129func (n HostAndDeviceModuleNames) IsHostAndDeviceModule(groupId string, artifactId string) bool {
130 _, found := n[groupId+":"+artifactId]
131
132 return found
133}
134
135func (n HostAndDeviceModuleNames) String() string {
136 return ""
137}
138
139func (n HostAndDeviceModuleNames) Set(v string) error {
140 n[v] = true
141 return nil
142}
143
144var hostAndDeviceModuleNames = HostAndDeviceModuleNames{}
145
Colin Cross70dd38f2018-04-16 13:52:10 -0700146var sdkVersion string
Anton Hanssonc29f0762021-03-29 16:10:06 +0100147var defaultMinSdkVersion string
Colin Cross70dd38f2018-04-16 13:52:10 -0700148var useVersion string
Dan Willemsen52c90d82019-04-21 21:37:39 -0700149var staticDeps bool
Dan Willemsen7fdab6e2019-04-20 21:47:14 -0700150var jetifier bool
Colin Cross70dd38f2018-04-16 13:52:10 -0700151
152func InList(s string, list []string) bool {
153 for _, l := range list {
154 if l == s {
155 return true
156 }
157 }
158
159 return false
160}
161
162type Dependency struct {
163 XMLName xml.Name `xml:"dependency"`
164
165 BpTarget string `xml:"-"`
166
167 GroupId string `xml:"groupId"`
168 ArtifactId string `xml:"artifactId"`
169 Version string `xml:"version"`
170 Type string `xml:"type"`
171 Scope string `xml:"scope"`
172}
173
174func (d Dependency) BpName() string {
175 if d.BpTarget == "" {
176 d.BpTarget = rewriteNames.MavenToBp(d.GroupId, d.ArtifactId)
177 }
178 return d.BpTarget
179}
180
181type Pom struct {
182 XMLName xml.Name `xml:"http://maven.apache.org/POM/4.0.0 project"`
183
Colin Crosscf53e602018-06-26 15:27:20 -0700184 PomFile string `xml:"-"`
185 ArtifactFile string `xml:"-"`
186 BpTarget string `xml:"-"`
187 MinSdkVersion string `xml:"-"`
Colin Cross70dd38f2018-04-16 13:52:10 -0700188
189 GroupId string `xml:"groupId"`
190 ArtifactId string `xml:"artifactId"`
191 Version string `xml:"version"`
192 Packaging string `xml:"packaging"`
193
194 Dependencies []*Dependency `xml:"dependencies>dependency"`
195}
196
197func (p Pom) IsAar() bool {
198 return p.Packaging == "aar"
199}
200
201func (p Pom) IsJar() bool {
202 return p.Packaging == "jar"
203}
204
Jeff Gastond4928532018-08-24 14:30:13 -0400205func (p Pom) IsHostModule() bool {
206 return hostModuleNames.IsHostModule(p.GroupId, p.ArtifactId)
207}
208
209func (p Pom) IsDeviceModule() bool {
210 return !p.IsHostModule()
211}
212
Tony Mak81785002019-07-18 21:36:44 +0100213func (p Pom) IsHostAndDeviceModule() bool {
214 return hostAndDeviceModuleNames.IsHostAndDeviceModule(p.GroupId, p.ArtifactId)
215}
216
Jooyung Han43d30252020-05-22 03:54:24 +0900217func (p Pom) IsHostOnly() bool {
218 return p.IsHostModule() && !p.IsHostAndDeviceModule()
219}
220
Colin Cross632987a2018-08-29 16:17:55 -0700221func (p Pom) ModuleType() string {
222 if p.IsAar() {
223 return "android_library"
Jooyung Han43d30252020-05-22 03:54:24 +0900224 } else if p.IsHostOnly() {
Colin Cross632987a2018-08-29 16:17:55 -0700225 return "java_library_host"
226 } else {
227 return "java_library_static"
228 }
229}
230
231func (p Pom) ImportModuleType() string {
232 if p.IsAar() {
233 return "android_library_import"
Jooyung Han43d30252020-05-22 03:54:24 +0900234 } else if p.IsHostOnly() {
Colin Cross632987a2018-08-29 16:17:55 -0700235 return "java_import_host"
236 } else {
237 return "java_import"
238 }
239}
240
241func (p Pom) ImportProperty() string {
242 if p.IsAar() {
243 return "aars"
244 } else {
245 return "jars"
246 }
247}
248
Colin Cross70dd38f2018-04-16 13:52:10 -0700249func (p Pom) BpName() string {
250 if p.BpTarget == "" {
251 p.BpTarget = rewriteNames.MavenToBp(p.GroupId, p.ArtifactId)
252 }
253 return p.BpTarget
254}
255
256func (p Pom) BpJarDeps() []string {
257 return p.BpDeps("jar", []string{"compile", "runtime"})
258}
259
260func (p Pom) BpAarDeps() []string {
261 return p.BpDeps("aar", []string{"compile", "runtime"})
262}
263
Paul Duffinbabaf072019-04-16 11:35:20 +0100264func (p Pom) BpExtraStaticLibs() []string {
265 return extraStaticLibs[p.BpName()]
266}
267
268func (p Pom) BpExtraLibs() []string {
269 return extraLibs[p.BpName()]
Colin Cross70dd38f2018-04-16 13:52:10 -0700270}
271
272// BpDeps obtains dependencies filtered by type and scope. The results of this
273// method are formatted as Android.bp targets, e.g. run through MavenToBp rules.
274func (p Pom) BpDeps(typeExt string, scopes []string) []string {
275 var ret []string
276 for _, d := range p.Dependencies {
277 if d.Type != typeExt || !InList(d.Scope, scopes) {
278 continue
279 }
280 name := rewriteNames.MavenToBp(d.GroupId, d.ArtifactId)
281 ret = append(ret, name)
282 }
283 return ret
284}
285
286func (p Pom) SdkVersion() string {
287 return sdkVersion
288}
289
Anton Hanssonc29f0762021-03-29 16:10:06 +0100290func (p Pom) DefaultMinSdkVersion() string {
291 return defaultMinSdkVersion
292}
293
Dan Willemsen7fdab6e2019-04-20 21:47:14 -0700294func (p Pom) Jetifier() bool {
295 return jetifier
296}
297
Colin Cross70dd38f2018-04-16 13:52:10 -0700298func (p *Pom) FixDeps(modules map[string]*Pom) {
299 for _, d := range p.Dependencies {
300 if d.Type == "" {
301 if depPom, ok := modules[d.BpName()]; ok {
302 // We've seen the POM for this dependency, use its packaging
303 // as the dependency type rather than Maven spec default.
304 d.Type = depPom.Packaging
305 } else {
306 // Dependency type was not specified and we don't have the POM
307 // for this artifact, use the default from Maven spec.
308 d.Type = "jar"
309 }
310 }
311 if d.Scope == "" {
312 // Scope was not specified, use the default from Maven spec.
313 d.Scope = "compile"
314 }
315 }
316}
317
Colin Crosscf53e602018-06-26 15:27:20 -0700318// ExtractMinSdkVersion extracts the minSdkVersion from the AndroidManifest.xml file inside an aar file, or sets it
319// to "current" if it is not present.
320func (p *Pom) ExtractMinSdkVersion() error {
321 aar, err := zip.OpenReader(p.ArtifactFile)
322 if err != nil {
323 return err
324 }
325 defer aar.Close()
326
327 var manifest *zip.File
328 for _, f := range aar.File {
329 if f.Name == "AndroidManifest.xml" {
330 manifest = f
331 break
332 }
333 }
334
335 if manifest == nil {
336 return fmt.Errorf("failed to find AndroidManifest.xml in %s", p.ArtifactFile)
337 }
338
339 r, err := manifest.Open()
340 if err != nil {
341 return err
342 }
343 defer r.Close()
344
345 decoder := xml.NewDecoder(r)
346
347 manifestData := struct {
348 XMLName xml.Name `xml:"manifest"`
349 Uses_sdk struct {
350 MinSdkVersion string `xml:"http://schemas.android.com/apk/res/android minSdkVersion,attr"`
351 } `xml:"uses-sdk"`
352 }{}
353
354 err = decoder.Decode(&manifestData)
355 if err != nil {
356 return err
357 }
358
359 p.MinSdkVersion = manifestData.Uses_sdk.MinSdkVersion
360 if p.MinSdkVersion == "" {
361 p.MinSdkVersion = "current"
362 }
363
364 return nil
365}
366
Colin Cross70dd38f2018-04-16 13:52:10 -0700367var bpTemplate = template.Must(template.New("bp").Parse(`
Colin Cross632987a2018-08-29 16:17:55 -0700368{{.ImportModuleType}} {
Dan Willemsen52c90d82019-04-21 21:37:39 -0700369 name: "{{.BpName}}",
370 {{.ImportProperty}}: ["{{.ArtifactFile}}"],
371 sdk_version: "{{.SdkVersion}}",
372 {{- if .Jetifier}}
373 jetifier: true,
374 {{- end}}
Tony Mak81785002019-07-18 21:36:44 +0100375 {{- if .IsHostAndDeviceModule}}
376 host_supported: true,
377 {{- end}}
Jooyung Han43d30252020-05-22 03:54:24 +0900378 {{- if not .IsHostOnly}}
379 apex_available: [
380 "//apex_available:platform",
381 "//apex_available:anyapex",
382 ],
383 {{- end}}
Dan Willemsen52c90d82019-04-21 21:37:39 -0700384 {{- if .IsAar}}
385 min_sdk_version: "{{.MinSdkVersion}}",
386 static_libs: [
387 {{- range .BpJarDeps}}
388 "{{.}}",
389 {{- end}}
390 {{- range .BpAarDeps}}
391 "{{.}}",
392 {{- end}}
393 {{- range .BpExtraStaticLibs}}
394 "{{.}}",
395 {{- end}}
396 ],
397 {{- if .BpExtraLibs}}
398 libs: [
399 {{- range .BpExtraLibs}}
400 "{{.}}",
401 {{- end}}
402 ],
403 {{- end}}
404 {{- end}}
405}
406`))
407
408var bpDepsTemplate = template.Must(template.New("bp").Parse(`
409{{.ImportModuleType}} {
Colin Cross70dd38f2018-04-16 13:52:10 -0700410 name: "{{.BpName}}-nodeps",
Colin Cross632987a2018-08-29 16:17:55 -0700411 {{.ImportProperty}}: ["{{.ArtifactFile}}"],
412 sdk_version: "{{.SdkVersion}}",
Dan Willemsen7fdab6e2019-04-20 21:47:14 -0700413 {{- if .Jetifier}}
414 jetifier: true,
415 {{- end}}
Tony Mak81785002019-07-18 21:36:44 +0100416 {{- if .IsHostAndDeviceModule}}
417 host_supported: true,
418 {{- end}}
Jooyung Han43d30252020-05-22 03:54:24 +0900419 {{- if not .IsHostOnly}}
420 apex_available: [
421 "//apex_available:platform",
422 "//apex_available:anyapex",
423 ],
424 {{- end}}
Colin Cross632987a2018-08-29 16:17:55 -0700425 {{- if .IsAar}}
Colin Crosscf53e602018-06-26 15:27:20 -0700426 min_sdk_version: "{{.MinSdkVersion}}",
Colin Cross632987a2018-08-29 16:17:55 -0700427 static_libs: [
Colin Cross1aa7f262019-04-10 11:07:15 -0700428 {{- range .BpJarDeps}}
429 "{{.}}",
430 {{- end}}
Colin Cross632987a2018-08-29 16:17:55 -0700431 {{- range .BpAarDeps}}
432 "{{.}}",
433 {{- end}}
Paul Duffinbabaf072019-04-16 11:35:20 +0100434 {{- range .BpExtraStaticLibs}}
Colin Cross632987a2018-08-29 16:17:55 -0700435 "{{.}}",
436 {{- end}}
437 ],
Paul Duffinbabaf072019-04-16 11:35:20 +0100438 {{- if .BpExtraLibs}}
439 libs: [
440 {{- range .BpExtraLibs}}
441 "{{.}}",
442 {{- end}}
443 ],
444 {{- end}}
Colin Cross632987a2018-08-29 16:17:55 -0700445 {{- end}}
Colin Cross70dd38f2018-04-16 13:52:10 -0700446}
447
Colin Cross632987a2018-08-29 16:17:55 -0700448{{.ModuleType}} {
449 name: "{{.BpName}}",
450 {{- if .IsDeviceModule}}
451 sdk_version: "{{.SdkVersion}}",
Tony Mak81785002019-07-18 21:36:44 +0100452 {{- if .IsHostAndDeviceModule}}
453 host_supported: true,
454 {{- end}}
Jooyung Han43d30252020-05-22 03:54:24 +0900455 {{- if not .IsHostOnly}}
456 apex_available: [
457 "//apex_available:platform",
458 "//apex_available:anyapex",
459 ],
460 {{- end}}
Colin Cross632987a2018-08-29 16:17:55 -0700461 {{- if .IsAar}}
Colin Cross461ba492018-07-10 13:45:30 -0700462 min_sdk_version: "{{.MinSdkVersion}}",
Colin Cross632987a2018-08-29 16:17:55 -0700463 manifest: "manifests/{{.BpName}}/AndroidManifest.xml",
Jooyung Han43d30252020-05-22 03:54:24 +0900464 {{- else if not .IsHostOnly}}
Anton Hanssonc29f0762021-03-29 16:10:06 +0100465 min_sdk_version: "{{.DefaultMinSdkVersion}}",
Colin Cross632987a2018-08-29 16:17:55 -0700466 {{- end}}
467 {{- end}}
Colin Cross70dd38f2018-04-16 13:52:10 -0700468 static_libs: [
Colin Cross632987a2018-08-29 16:17:55 -0700469 "{{.BpName}}-nodeps",
Colin Cross1aa7f262019-04-10 11:07:15 -0700470 {{- range .BpJarDeps}}
Colin Cross632987a2018-08-29 16:17:55 -0700471 "{{.}}",
472 {{- end}}
473 {{- range .BpAarDeps}}
474 "{{.}}",
475 {{- end}}
Paul Duffinbabaf072019-04-16 11:35:20 +0100476 {{- range .BpExtraStaticLibs}}
Colin Cross632987a2018-08-29 16:17:55 -0700477 "{{.}}",
478 {{- end}}
Colin Cross70dd38f2018-04-16 13:52:10 -0700479 ],
Paul Duffinbabaf072019-04-16 11:35:20 +0100480 {{- if .BpExtraLibs}}
481 libs: [
482 {{- range .BpExtraLibs}}
483 "{{.}}",
484 {{- end}}
485 ],
486 {{- end}}
Colin Cross70dd38f2018-04-16 13:52:10 -0700487 java_version: "1.7",
488}
489`))
490
491func parse(filename string) (*Pom, error) {
492 data, err := ioutil.ReadFile(filename)
493 if err != nil {
494 return nil, err
495 }
496
497 var pom Pom
498 err = xml.Unmarshal(data, &pom)
499 if err != nil {
500 return nil, err
501 }
502
503 if useVersion != "" && pom.Version != useVersion {
504 return nil, nil
505 }
506
507 if pom.Packaging == "" {
508 pom.Packaging = "jar"
509 }
510
511 pom.PomFile = filename
512 pom.ArtifactFile = strings.TrimSuffix(filename, ".pom") + "." + pom.Packaging
513
514 return &pom, nil
515}
516
517func rerunForRegen(filename string) error {
518 buf, err := ioutil.ReadFile(filename)
519 if err != nil {
520 return err
521 }
522
523 scanner := bufio.NewScanner(bytes.NewBuffer(buf))
524
525 // Skip the first line in the file
526 for i := 0; i < 2; i++ {
527 if !scanner.Scan() {
528 if scanner.Err() != nil {
529 return scanner.Err()
530 } else {
531 return fmt.Errorf("unexpected EOF")
532 }
533 }
534 }
535
536 // Extract the old args from the file
537 line := scanner.Text()
538 if strings.HasPrefix(line, "// pom2bp ") {
539 line = strings.TrimPrefix(line, "// pom2bp ")
540 } else if strings.HasPrefix(line, "// pom2mk ") {
541 line = strings.TrimPrefix(line, "// pom2mk ")
542 } else if strings.HasPrefix(line, "# pom2mk ") {
543 line = strings.TrimPrefix(line, "# pom2mk ")
544 } else {
545 return fmt.Errorf("unexpected second line: %q", line)
546 }
547 args := strings.Split(line, " ")
548 lastArg := args[len(args)-1]
549 args = args[:len(args)-1]
550
551 // Append all current command line args except -regen <file> to the ones from the file
552 for i := 1; i < len(os.Args); i++ {
Colin Crosscf53e602018-06-26 15:27:20 -0700553 if os.Args[i] == "-regen" || os.Args[i] == "--regen" {
Colin Cross70dd38f2018-04-16 13:52:10 -0700554 i++
555 } else {
556 args = append(args, os.Args[i])
557 }
558 }
559 args = append(args, lastArg)
560
561 cmd := os.Args[0] + " " + strings.Join(args, " ")
562 // Re-exec pom2bp with the new arguments
563 output, err := exec.Command("/bin/sh", "-c", cmd).Output()
564 if exitErr, _ := err.(*exec.ExitError); exitErr != nil {
565 return fmt.Errorf("failed to run %s\n%s", cmd, string(exitErr.Stderr))
566 } else if err != nil {
567 return err
568 }
569
570 // If the old file was a .mk file, replace it with a .bp file
571 if filepath.Ext(filename) == ".mk" {
572 os.Remove(filename)
573 filename = strings.TrimSuffix(filename, ".mk") + ".bp"
574 }
575
576 return ioutil.WriteFile(filename, output, 0666)
577}
578
579func main() {
580 flag.Usage = func() {
581 fmt.Fprintf(os.Stderr, `pom2bp, a tool to create Android.bp files from maven repos
582
583The tool will extract the necessary information from *.pom files to create an Android.bp whose
584aar libraries can be linked against when using AAPT2.
585
Paul Duffinbabaf072019-04-16 11:35:20 +0100586Usage: %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 -0700587
588 -rewrite <regex>=<replace>
589 rewrite can be used to specify mappings between Maven projects and Android.bp modules. The -rewrite
590 option can be specified multiple times. When determining the Android.bp module for a given Maven
591 project, mappings are searched in the order they were specified. The first <regex> matching
592 either the Maven project's <groupId>:<artifactId> or <artifactId> will be used to generate
593 the Android.bp module name using <replace>. If no matches are found, <artifactId> is used.
594 -exclude <module>
595 Don't put the specified module in the Android.bp file.
Paul Duffinbabaf072019-04-16 11:35:20 +0100596 -extra-static-libs <module>=<module>[,<module>]
597 Some Android.bp modules have transitive static dependencies that must be specified when they
598 are depended upon (like android-support-v7-mediarouter requires android-support-v7-appcompat).
599 This may be specified multiple times to declare these dependencies.
600 -extra-libs <module>=<module>[,<module>]
601 Some Android.bp modules have transitive runtime dependencies that must be specified when they
602 are depended upon (like androidx.test.rules requires android.test.base).
Colin Cross70dd38f2018-04-16 13:52:10 -0700603 This may be specified multiple times to declare these dependencies.
604 -sdk-version <version>
Dan Willemsen7fdab6e2019-04-20 21:47:14 -0700605 Sets sdk_version: "<version>" for all modules.
Anton Hanssonc29f0762021-03-29 16:10:06 +0100606 -default-min-sdk-version
607 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 -0700608 -use-version <version>
609 If the maven directory contains multiple versions of artifacts and their pom files,
610 -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 -0700611 -jetifier
612 Sets jetifier: true for all modules.
Colin Cross70dd38f2018-04-16 13:52:10 -0700613 <dir>
614 The directory to search for *.pom files under.
615 The contents are written to stdout, to be put in the current directory (often as Android.bp)
616 -regen <file>
617 Read arguments from <file> and overwrite it (if it ends with .bp) or move it to .bp (if it
618 ends with .mk).
619
620`, os.Args[0])
621 }
622
623 var regen string
624
625 flag.Var(&excludes, "exclude", "Exclude module")
Paul Duffinbabaf072019-04-16 11:35:20 +0100626 flag.Var(&extraStaticLibs, "extra-static-libs", "Extra static dependencies needed when depending on a module")
627 flag.Var(&extraLibs, "extra-libs", "Extra runtime dependencies needed when depending on a module")
Colin Cross70dd38f2018-04-16 13:52:10 -0700628 flag.Var(&rewriteNames, "rewrite", "Regex(es) to rewrite artifact names")
Jeff Gastond4928532018-08-24 14:30:13 -0400629 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 +0100630 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 -0700631 flag.StringVar(&sdkVersion, "sdk-version", "", "What to write to sdk_version")
Anton Hanssonc29f0762021-03-29 16:10:06 +0100632 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 -0700633 flag.StringVar(&useVersion, "use-version", "", "Only read artifacts of a specific version")
Dan Willemsen52c90d82019-04-21 21:37:39 -0700634 flag.BoolVar(&staticDeps, "static-deps", false, "Statically include direct dependencies")
Dan Willemsen7fdab6e2019-04-20 21:47:14 -0700635 flag.BoolVar(&jetifier, "jetifier", false, "Sets jetifier: true on all modules")
Colin Cross70dd38f2018-04-16 13:52:10 -0700636 flag.StringVar(&regen, "regen", "", "Rewrite specified file")
637 flag.Parse()
638
639 if regen != "" {
640 err := rerunForRegen(regen)
641 if err != nil {
642 fmt.Fprintln(os.Stderr, err)
643 os.Exit(1)
644 }
645 os.Exit(0)
646 }
647
648 if flag.NArg() == 0 {
649 fmt.Fprintln(os.Stderr, "Directory argument is required")
650 os.Exit(1)
651 } else if flag.NArg() > 1 {
652 fmt.Fprintln(os.Stderr, "Multiple directories provided:", strings.Join(flag.Args(), " "))
653 os.Exit(1)
654 }
655
656 dir := flag.Arg(0)
657 absDir, err := filepath.Abs(dir)
658 if err != nil {
659 fmt.Fprintln(os.Stderr, "Failed to get absolute directory:", err)
660 os.Exit(1)
661 }
662
663 var filenames []string
664 err = filepath.Walk(absDir, func(path string, info os.FileInfo, err error) error {
665 if err != nil {
666 return err
667 }
668
669 name := info.Name()
670 if info.IsDir() {
671 if strings.HasPrefix(name, ".") {
672 return filepath.SkipDir
673 }
674 return nil
675 }
676
677 if strings.HasPrefix(name, ".") {
678 return nil
679 }
680
681 if strings.HasSuffix(name, ".pom") {
682 path, err = filepath.Rel(absDir, path)
683 if err != nil {
684 return err
685 }
686 filenames = append(filenames, filepath.Join(dir, path))
687 }
688 return nil
689 })
690 if err != nil {
691 fmt.Fprintln(os.Stderr, "Error walking files:", err)
692 os.Exit(1)
693 }
694
695 if len(filenames) == 0 {
696 fmt.Fprintln(os.Stderr, "Error: no *.pom files found under", dir)
697 os.Exit(1)
698 }
699
700 sort.Strings(filenames)
701
702 poms := []*Pom{}
703 modules := make(map[string]*Pom)
704 duplicate := false
705 for _, filename := range filenames {
706 pom, err := parse(filename)
707 if err != nil {
708 fmt.Fprintln(os.Stderr, "Error converting", filename, err)
709 os.Exit(1)
710 }
711
712 if pom != nil {
713 key := pom.BpName()
714 if excludes[key] {
715 continue
716 }
717
718 if old, ok := modules[key]; ok {
719 fmt.Fprintln(os.Stderr, "Module", key, "defined twice:", old.PomFile, pom.PomFile)
720 duplicate = true
721 }
722
723 poms = append(poms, pom)
724 modules[key] = pom
725 }
726 }
727 if duplicate {
728 os.Exit(1)
729 }
730
731 for _, pom := range poms {
Colin Crosscf53e602018-06-26 15:27:20 -0700732 if pom.IsAar() {
733 err := pom.ExtractMinSdkVersion()
734 if err != nil {
Colin Crossfe5a3b72018-07-13 21:25:15 -0700735 fmt.Fprintf(os.Stderr, "Error reading manifest for %s: %s", pom.ArtifactFile, err)
Colin Crosscf53e602018-06-26 15:27:20 -0700736 os.Exit(1)
737 }
738 }
Colin Cross70dd38f2018-04-16 13:52:10 -0700739 pom.FixDeps(modules)
740 }
741
742 buf := &bytes.Buffer{}
743
744 fmt.Fprintln(buf, "// Automatically generated with:")
Colin Cross0b9f31f2019-02-28 11:00:01 -0800745 fmt.Fprintln(buf, "// pom2bp", strings.Join(proptools.ShellEscapeList(os.Args[1:]), " "))
Colin Cross70dd38f2018-04-16 13:52:10 -0700746
747 for _, pom := range poms {
748 var err error
Dan Willemsen52c90d82019-04-21 21:37:39 -0700749 if staticDeps {
750 err = bpDepsTemplate.Execute(buf, pom)
751 } else {
752 err = bpTemplate.Execute(buf, pom)
753 }
Colin Cross70dd38f2018-04-16 13:52:10 -0700754 if err != nil {
755 fmt.Fprintln(os.Stderr, "Error writing", pom.PomFile, pom.BpName(), err)
756 os.Exit(1)
757 }
758 }
759
760 out, err := bpfix.Reformat(buf.String())
761 if err != nil {
762 fmt.Fprintln(os.Stderr, "Error formatting output", err)
763 os.Exit(1)
764 }
765
766 os.Stdout.WriteString(out)
767}