blob: 191b919e92d9e867db44fe04727132c815961761 [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
147var useVersion string
Dan Willemsen52c90d82019-04-21 21:37:39 -0700148var staticDeps bool
Dan Willemsen7fdab6e2019-04-20 21:47:14 -0700149var jetifier bool
Colin Cross70dd38f2018-04-16 13:52:10 -0700150
151func InList(s string, list []string) bool {
152 for _, l := range list {
153 if l == s {
154 return true
155 }
156 }
157
158 return false
159}
160
161type Dependency struct {
162 XMLName xml.Name `xml:"dependency"`
163
164 BpTarget string `xml:"-"`
165
166 GroupId string `xml:"groupId"`
167 ArtifactId string `xml:"artifactId"`
168 Version string `xml:"version"`
169 Type string `xml:"type"`
170 Scope string `xml:"scope"`
171}
172
173func (d Dependency) BpName() string {
174 if d.BpTarget == "" {
175 d.BpTarget = rewriteNames.MavenToBp(d.GroupId, d.ArtifactId)
176 }
177 return d.BpTarget
178}
179
180type Pom struct {
181 XMLName xml.Name `xml:"http://maven.apache.org/POM/4.0.0 project"`
182
Colin Crosscf53e602018-06-26 15:27:20 -0700183 PomFile string `xml:"-"`
184 ArtifactFile string `xml:"-"`
185 BpTarget string `xml:"-"`
186 MinSdkVersion string `xml:"-"`
Colin Cross70dd38f2018-04-16 13:52:10 -0700187
188 GroupId string `xml:"groupId"`
189 ArtifactId string `xml:"artifactId"`
190 Version string `xml:"version"`
191 Packaging string `xml:"packaging"`
192
193 Dependencies []*Dependency `xml:"dependencies>dependency"`
194}
195
196func (p Pom) IsAar() bool {
197 return p.Packaging == "aar"
198}
199
200func (p Pom) IsJar() bool {
201 return p.Packaging == "jar"
202}
203
Jeff Gastond4928532018-08-24 14:30:13 -0400204func (p Pom) IsHostModule() bool {
205 return hostModuleNames.IsHostModule(p.GroupId, p.ArtifactId)
206}
207
208func (p Pom) IsDeviceModule() bool {
209 return !p.IsHostModule()
210}
211
Tony Mak81785002019-07-18 21:36:44 +0100212func (p Pom) IsHostAndDeviceModule() bool {
213 return hostAndDeviceModuleNames.IsHostAndDeviceModule(p.GroupId, p.ArtifactId)
214}
215
Colin Cross632987a2018-08-29 16:17:55 -0700216func (p Pom) ModuleType() string {
217 if p.IsAar() {
218 return "android_library"
Tony Mak81785002019-07-18 21:36:44 +0100219 } else if p.IsHostModule() && !p.IsHostAndDeviceModule() {
Colin Cross632987a2018-08-29 16:17:55 -0700220 return "java_library_host"
221 } else {
222 return "java_library_static"
223 }
224}
225
226func (p Pom) ImportModuleType() string {
227 if p.IsAar() {
228 return "android_library_import"
Tony Mak81785002019-07-18 21:36:44 +0100229 } else if p.IsHostModule() && !p.IsHostAndDeviceModule() {
Colin Cross632987a2018-08-29 16:17:55 -0700230 return "java_import_host"
231 } else {
232 return "java_import"
233 }
234}
235
236func (p Pom) ImportProperty() string {
237 if p.IsAar() {
238 return "aars"
239 } else {
240 return "jars"
241 }
242}
243
Colin Cross70dd38f2018-04-16 13:52:10 -0700244func (p Pom) BpName() string {
245 if p.BpTarget == "" {
246 p.BpTarget = rewriteNames.MavenToBp(p.GroupId, p.ArtifactId)
247 }
248 return p.BpTarget
249}
250
251func (p Pom) BpJarDeps() []string {
252 return p.BpDeps("jar", []string{"compile", "runtime"})
253}
254
255func (p Pom) BpAarDeps() []string {
256 return p.BpDeps("aar", []string{"compile", "runtime"})
257}
258
Paul Duffinbabaf072019-04-16 11:35:20 +0100259func (p Pom) BpExtraStaticLibs() []string {
260 return extraStaticLibs[p.BpName()]
261}
262
263func (p Pom) BpExtraLibs() []string {
264 return extraLibs[p.BpName()]
Colin Cross70dd38f2018-04-16 13:52:10 -0700265}
266
267// BpDeps obtains dependencies filtered by type and scope. The results of this
268// method are formatted as Android.bp targets, e.g. run through MavenToBp rules.
269func (p Pom) BpDeps(typeExt string, scopes []string) []string {
270 var ret []string
271 for _, d := range p.Dependencies {
272 if d.Type != typeExt || !InList(d.Scope, scopes) {
273 continue
274 }
275 name := rewriteNames.MavenToBp(d.GroupId, d.ArtifactId)
276 ret = append(ret, name)
277 }
278 return ret
279}
280
281func (p Pom) SdkVersion() string {
282 return sdkVersion
283}
284
Dan Willemsen7fdab6e2019-04-20 21:47:14 -0700285func (p Pom) Jetifier() bool {
286 return jetifier
287}
288
Colin Cross70dd38f2018-04-16 13:52:10 -0700289func (p *Pom) FixDeps(modules map[string]*Pom) {
290 for _, d := range p.Dependencies {
291 if d.Type == "" {
292 if depPom, ok := modules[d.BpName()]; ok {
293 // We've seen the POM for this dependency, use its packaging
294 // as the dependency type rather than Maven spec default.
295 d.Type = depPom.Packaging
296 } else {
297 // Dependency type was not specified and we don't have the POM
298 // for this artifact, use the default from Maven spec.
299 d.Type = "jar"
300 }
301 }
302 if d.Scope == "" {
303 // Scope was not specified, use the default from Maven spec.
304 d.Scope = "compile"
305 }
306 }
307}
308
Colin Crosscf53e602018-06-26 15:27:20 -0700309// ExtractMinSdkVersion extracts the minSdkVersion from the AndroidManifest.xml file inside an aar file, or sets it
310// to "current" if it is not present.
311func (p *Pom) ExtractMinSdkVersion() error {
312 aar, err := zip.OpenReader(p.ArtifactFile)
313 if err != nil {
314 return err
315 }
316 defer aar.Close()
317
318 var manifest *zip.File
319 for _, f := range aar.File {
320 if f.Name == "AndroidManifest.xml" {
321 manifest = f
322 break
323 }
324 }
325
326 if manifest == nil {
327 return fmt.Errorf("failed to find AndroidManifest.xml in %s", p.ArtifactFile)
328 }
329
330 r, err := manifest.Open()
331 if err != nil {
332 return err
333 }
334 defer r.Close()
335
336 decoder := xml.NewDecoder(r)
337
338 manifestData := struct {
339 XMLName xml.Name `xml:"manifest"`
340 Uses_sdk struct {
341 MinSdkVersion string `xml:"http://schemas.android.com/apk/res/android minSdkVersion,attr"`
342 } `xml:"uses-sdk"`
343 }{}
344
345 err = decoder.Decode(&manifestData)
346 if err != nil {
347 return err
348 }
349
350 p.MinSdkVersion = manifestData.Uses_sdk.MinSdkVersion
351 if p.MinSdkVersion == "" {
352 p.MinSdkVersion = "current"
353 }
354
355 return nil
356}
357
Colin Cross70dd38f2018-04-16 13:52:10 -0700358var bpTemplate = template.Must(template.New("bp").Parse(`
Colin Cross632987a2018-08-29 16:17:55 -0700359{{.ImportModuleType}} {
Dan Willemsen52c90d82019-04-21 21:37:39 -0700360 name: "{{.BpName}}",
361 {{.ImportProperty}}: ["{{.ArtifactFile}}"],
362 sdk_version: "{{.SdkVersion}}",
363 {{- if .Jetifier}}
364 jetifier: true,
365 {{- end}}
Tony Mak81785002019-07-18 21:36:44 +0100366 {{- if .IsHostAndDeviceModule}}
367 host_supported: true,
368 {{- end}}
Dan Willemsen52c90d82019-04-21 21:37:39 -0700369 {{- if .IsAar}}
370 min_sdk_version: "{{.MinSdkVersion}}",
371 static_libs: [
372 {{- range .BpJarDeps}}
373 "{{.}}",
374 {{- end}}
375 {{- range .BpAarDeps}}
376 "{{.}}",
377 {{- end}}
378 {{- range .BpExtraStaticLibs}}
379 "{{.}}",
380 {{- end}}
381 ],
382 {{- if .BpExtraLibs}}
383 libs: [
384 {{- range .BpExtraLibs}}
385 "{{.}}",
386 {{- end}}
387 ],
388 {{- end}}
389 {{- end}}
390}
391`))
392
393var bpDepsTemplate = template.Must(template.New("bp").Parse(`
394{{.ImportModuleType}} {
Colin Cross70dd38f2018-04-16 13:52:10 -0700395 name: "{{.BpName}}-nodeps",
Colin Cross632987a2018-08-29 16:17:55 -0700396 {{.ImportProperty}}: ["{{.ArtifactFile}}"],
397 sdk_version: "{{.SdkVersion}}",
Dan Willemsen7fdab6e2019-04-20 21:47:14 -0700398 {{- if .Jetifier}}
399 jetifier: true,
400 {{- end}}
Tony Mak81785002019-07-18 21:36:44 +0100401 {{- if .IsHostAndDeviceModule}}
402 host_supported: true,
403 {{- end}}
Colin Cross632987a2018-08-29 16:17:55 -0700404 {{- if .IsAar}}
Colin Crosscf53e602018-06-26 15:27:20 -0700405 min_sdk_version: "{{.MinSdkVersion}}",
Colin Cross632987a2018-08-29 16:17:55 -0700406 static_libs: [
Colin Cross1aa7f262019-04-10 11:07:15 -0700407 {{- range .BpJarDeps}}
408 "{{.}}",
409 {{- end}}
Colin Cross632987a2018-08-29 16:17:55 -0700410 {{- range .BpAarDeps}}
411 "{{.}}",
412 {{- end}}
Paul Duffinbabaf072019-04-16 11:35:20 +0100413 {{- range .BpExtraStaticLibs}}
Colin Cross632987a2018-08-29 16:17:55 -0700414 "{{.}}",
415 {{- end}}
416 ],
Paul Duffinbabaf072019-04-16 11:35:20 +0100417 {{- if .BpExtraLibs}}
418 libs: [
419 {{- range .BpExtraLibs}}
420 "{{.}}",
421 {{- end}}
422 ],
423 {{- end}}
Colin Cross632987a2018-08-29 16:17:55 -0700424 {{- end}}
Colin Cross70dd38f2018-04-16 13:52:10 -0700425}
426
Colin Cross632987a2018-08-29 16:17:55 -0700427{{.ModuleType}} {
428 name: "{{.BpName}}",
429 {{- if .IsDeviceModule}}
430 sdk_version: "{{.SdkVersion}}",
Tony Mak81785002019-07-18 21:36:44 +0100431 {{- if .IsHostAndDeviceModule}}
432 host_supported: true,
433 {{- end}}
Colin Cross632987a2018-08-29 16:17:55 -0700434 {{- if .IsAar}}
Colin Cross461ba492018-07-10 13:45:30 -0700435 min_sdk_version: "{{.MinSdkVersion}}",
Colin Cross632987a2018-08-29 16:17:55 -0700436 manifest: "manifests/{{.BpName}}/AndroidManifest.xml",
437 {{- end}}
438 {{- end}}
Colin Cross70dd38f2018-04-16 13:52:10 -0700439 static_libs: [
Colin Cross632987a2018-08-29 16:17:55 -0700440 "{{.BpName}}-nodeps",
Colin Cross1aa7f262019-04-10 11:07:15 -0700441 {{- range .BpJarDeps}}
Colin Cross632987a2018-08-29 16:17:55 -0700442 "{{.}}",
443 {{- end}}
444 {{- range .BpAarDeps}}
445 "{{.}}",
446 {{- end}}
Paul Duffinbabaf072019-04-16 11:35:20 +0100447 {{- range .BpExtraStaticLibs}}
Colin Cross632987a2018-08-29 16:17:55 -0700448 "{{.}}",
449 {{- end}}
Colin Cross70dd38f2018-04-16 13:52:10 -0700450 ],
Paul Duffinbabaf072019-04-16 11:35:20 +0100451 {{- if .BpExtraLibs}}
452 libs: [
453 {{- range .BpExtraLibs}}
454 "{{.}}",
455 {{- end}}
456 ],
457 {{- end}}
Colin Cross70dd38f2018-04-16 13:52:10 -0700458 java_version: "1.7",
459}
460`))
461
462func parse(filename string) (*Pom, error) {
463 data, err := ioutil.ReadFile(filename)
464 if err != nil {
465 return nil, err
466 }
467
468 var pom Pom
469 err = xml.Unmarshal(data, &pom)
470 if err != nil {
471 return nil, err
472 }
473
474 if useVersion != "" && pom.Version != useVersion {
475 return nil, nil
476 }
477
478 if pom.Packaging == "" {
479 pom.Packaging = "jar"
480 }
481
482 pom.PomFile = filename
483 pom.ArtifactFile = strings.TrimSuffix(filename, ".pom") + "." + pom.Packaging
484
485 return &pom, nil
486}
487
488func rerunForRegen(filename string) error {
489 buf, err := ioutil.ReadFile(filename)
490 if err != nil {
491 return err
492 }
493
494 scanner := bufio.NewScanner(bytes.NewBuffer(buf))
495
496 // Skip the first line in the file
497 for i := 0; i < 2; i++ {
498 if !scanner.Scan() {
499 if scanner.Err() != nil {
500 return scanner.Err()
501 } else {
502 return fmt.Errorf("unexpected EOF")
503 }
504 }
505 }
506
507 // Extract the old args from the file
508 line := scanner.Text()
509 if strings.HasPrefix(line, "// pom2bp ") {
510 line = strings.TrimPrefix(line, "// pom2bp ")
511 } else if strings.HasPrefix(line, "// pom2mk ") {
512 line = strings.TrimPrefix(line, "// pom2mk ")
513 } else if strings.HasPrefix(line, "# pom2mk ") {
514 line = strings.TrimPrefix(line, "# pom2mk ")
515 } else {
516 return fmt.Errorf("unexpected second line: %q", line)
517 }
518 args := strings.Split(line, " ")
519 lastArg := args[len(args)-1]
520 args = args[:len(args)-1]
521
522 // Append all current command line args except -regen <file> to the ones from the file
523 for i := 1; i < len(os.Args); i++ {
Colin Crosscf53e602018-06-26 15:27:20 -0700524 if os.Args[i] == "-regen" || os.Args[i] == "--regen" {
Colin Cross70dd38f2018-04-16 13:52:10 -0700525 i++
526 } else {
527 args = append(args, os.Args[i])
528 }
529 }
530 args = append(args, lastArg)
531
532 cmd := os.Args[0] + " " + strings.Join(args, " ")
533 // Re-exec pom2bp with the new arguments
534 output, err := exec.Command("/bin/sh", "-c", cmd).Output()
535 if exitErr, _ := err.(*exec.ExitError); exitErr != nil {
536 return fmt.Errorf("failed to run %s\n%s", cmd, string(exitErr.Stderr))
537 } else if err != nil {
538 return err
539 }
540
541 // If the old file was a .mk file, replace it with a .bp file
542 if filepath.Ext(filename) == ".mk" {
543 os.Remove(filename)
544 filename = strings.TrimSuffix(filename, ".mk") + ".bp"
545 }
546
547 return ioutil.WriteFile(filename, output, 0666)
548}
549
550func main() {
551 flag.Usage = func() {
552 fmt.Fprintf(os.Stderr, `pom2bp, a tool to create Android.bp files from maven repos
553
554The tool will extract the necessary information from *.pom files to create an Android.bp whose
555aar libraries can be linked against when using AAPT2.
556
Paul Duffinbabaf072019-04-16 11:35:20 +0100557Usage: %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 -0700558
559 -rewrite <regex>=<replace>
560 rewrite can be used to specify mappings between Maven projects and Android.bp modules. The -rewrite
561 option can be specified multiple times. When determining the Android.bp module for a given Maven
562 project, mappings are searched in the order they were specified. The first <regex> matching
563 either the Maven project's <groupId>:<artifactId> or <artifactId> will be used to generate
564 the Android.bp module name using <replace>. If no matches are found, <artifactId> is used.
565 -exclude <module>
566 Don't put the specified module in the Android.bp file.
Paul Duffinbabaf072019-04-16 11:35:20 +0100567 -extra-static-libs <module>=<module>[,<module>]
568 Some Android.bp modules have transitive static dependencies that must be specified when they
569 are depended upon (like android-support-v7-mediarouter requires android-support-v7-appcompat).
570 This may be specified multiple times to declare these dependencies.
571 -extra-libs <module>=<module>[,<module>]
572 Some Android.bp modules have transitive runtime dependencies that must be specified when they
573 are depended upon (like androidx.test.rules requires android.test.base).
Colin Cross70dd38f2018-04-16 13:52:10 -0700574 This may be specified multiple times to declare these dependencies.
575 -sdk-version <version>
Dan Willemsen7fdab6e2019-04-20 21:47:14 -0700576 Sets sdk_version: "<version>" for all modules.
Colin Cross70dd38f2018-04-16 13:52:10 -0700577 -use-version <version>
578 If the maven directory contains multiple versions of artifacts and their pom files,
579 -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 -0700580 -jetifier
581 Sets jetifier: true for all modules.
Colin Cross70dd38f2018-04-16 13:52:10 -0700582 <dir>
583 The directory to search for *.pom files under.
584 The contents are written to stdout, to be put in the current directory (often as Android.bp)
585 -regen <file>
586 Read arguments from <file> and overwrite it (if it ends with .bp) or move it to .bp (if it
587 ends with .mk).
588
589`, os.Args[0])
590 }
591
592 var regen string
593
594 flag.Var(&excludes, "exclude", "Exclude module")
Paul Duffinbabaf072019-04-16 11:35:20 +0100595 flag.Var(&extraStaticLibs, "extra-static-libs", "Extra static dependencies needed when depending on a module")
596 flag.Var(&extraLibs, "extra-libs", "Extra runtime dependencies needed when depending on a module")
Colin Cross70dd38f2018-04-16 13:52:10 -0700597 flag.Var(&rewriteNames, "rewrite", "Regex(es) to rewrite artifact names")
Jeff Gastond4928532018-08-24 14:30:13 -0400598 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 +0100599 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 -0700600 flag.StringVar(&sdkVersion, "sdk-version", "", "What to write to sdk_version")
Colin Cross70dd38f2018-04-16 13:52:10 -0700601 flag.StringVar(&useVersion, "use-version", "", "Only read artifacts of a specific version")
Dan Willemsen52c90d82019-04-21 21:37:39 -0700602 flag.BoolVar(&staticDeps, "static-deps", false, "Statically include direct dependencies")
Dan Willemsen7fdab6e2019-04-20 21:47:14 -0700603 flag.BoolVar(&jetifier, "jetifier", false, "Sets jetifier: true on all modules")
Colin Cross70dd38f2018-04-16 13:52:10 -0700604 flag.StringVar(&regen, "regen", "", "Rewrite specified file")
605 flag.Parse()
606
607 if regen != "" {
608 err := rerunForRegen(regen)
609 if err != nil {
610 fmt.Fprintln(os.Stderr, err)
611 os.Exit(1)
612 }
613 os.Exit(0)
614 }
615
616 if flag.NArg() == 0 {
617 fmt.Fprintln(os.Stderr, "Directory argument is required")
618 os.Exit(1)
619 } else if flag.NArg() > 1 {
620 fmt.Fprintln(os.Stderr, "Multiple directories provided:", strings.Join(flag.Args(), " "))
621 os.Exit(1)
622 }
623
624 dir := flag.Arg(0)
625 absDir, err := filepath.Abs(dir)
626 if err != nil {
627 fmt.Fprintln(os.Stderr, "Failed to get absolute directory:", err)
628 os.Exit(1)
629 }
630
631 var filenames []string
632 err = filepath.Walk(absDir, func(path string, info os.FileInfo, err error) error {
633 if err != nil {
634 return err
635 }
636
637 name := info.Name()
638 if info.IsDir() {
639 if strings.HasPrefix(name, ".") {
640 return filepath.SkipDir
641 }
642 return nil
643 }
644
645 if strings.HasPrefix(name, ".") {
646 return nil
647 }
648
649 if strings.HasSuffix(name, ".pom") {
650 path, err = filepath.Rel(absDir, path)
651 if err != nil {
652 return err
653 }
654 filenames = append(filenames, filepath.Join(dir, path))
655 }
656 return nil
657 })
658 if err != nil {
659 fmt.Fprintln(os.Stderr, "Error walking files:", err)
660 os.Exit(1)
661 }
662
663 if len(filenames) == 0 {
664 fmt.Fprintln(os.Stderr, "Error: no *.pom files found under", dir)
665 os.Exit(1)
666 }
667
668 sort.Strings(filenames)
669
670 poms := []*Pom{}
671 modules := make(map[string]*Pom)
672 duplicate := false
673 for _, filename := range filenames {
674 pom, err := parse(filename)
675 if err != nil {
676 fmt.Fprintln(os.Stderr, "Error converting", filename, err)
677 os.Exit(1)
678 }
679
680 if pom != nil {
681 key := pom.BpName()
682 if excludes[key] {
683 continue
684 }
685
686 if old, ok := modules[key]; ok {
687 fmt.Fprintln(os.Stderr, "Module", key, "defined twice:", old.PomFile, pom.PomFile)
688 duplicate = true
689 }
690
691 poms = append(poms, pom)
692 modules[key] = pom
693 }
694 }
695 if duplicate {
696 os.Exit(1)
697 }
698
699 for _, pom := range poms {
Colin Crosscf53e602018-06-26 15:27:20 -0700700 if pom.IsAar() {
701 err := pom.ExtractMinSdkVersion()
702 if err != nil {
Colin Crossfe5a3b72018-07-13 21:25:15 -0700703 fmt.Fprintf(os.Stderr, "Error reading manifest for %s: %s", pom.ArtifactFile, err)
Colin Crosscf53e602018-06-26 15:27:20 -0700704 os.Exit(1)
705 }
706 }
Colin Cross70dd38f2018-04-16 13:52:10 -0700707 pom.FixDeps(modules)
708 }
709
710 buf := &bytes.Buffer{}
711
712 fmt.Fprintln(buf, "// Automatically generated with:")
Colin Cross0b9f31f2019-02-28 11:00:01 -0800713 fmt.Fprintln(buf, "// pom2bp", strings.Join(proptools.ShellEscapeList(os.Args[1:]), " "))
Colin Cross70dd38f2018-04-16 13:52:10 -0700714
715 for _, pom := range poms {
716 var err error
Dan Willemsen52c90d82019-04-21 21:37:39 -0700717 if staticDeps {
718 err = bpDepsTemplate.Execute(buf, pom)
719 } else {
720 err = bpTemplate.Execute(buf, pom)
721 }
Colin Cross70dd38f2018-04-16 13:52:10 -0700722 if err != nil {
723 fmt.Fprintln(os.Stderr, "Error writing", pom.PomFile, pom.BpName(), err)
724 os.Exit(1)
725 }
726 }
727
728 out, err := bpfix.Reformat(buf.String())
729 if err != nil {
730 fmt.Fprintln(os.Stderr, "Error formatting output", err)
731 os.Exit(1)
732 }
733
734 os.Stdout.WriteString(out)
735}