extract_jar_packages.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // Copyright 2018 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. package main
  15. import (
  16. "archive/zip"
  17. "flag"
  18. "fmt"
  19. "io/ioutil"
  20. "log"
  21. "os"
  22. "path/filepath"
  23. "sort"
  24. "strings"
  25. )
  26. var (
  27. outputFile = flag.String("o", "", "output file")
  28. prefix = flag.String("prefix", "", "prefix for each entry in the output file")
  29. inputFile = flag.String("i", "", "input jar or srcjar")
  30. )
  31. func must(err error) {
  32. if err != nil {
  33. log.Fatal(err)
  34. }
  35. }
  36. func fileToPackage(file string) string {
  37. dir := filepath.Dir(file)
  38. return strings.Replace(dir, "/", ".", -1)
  39. }
  40. func main() {
  41. flag.Usage = func() {
  42. fmt.Fprintln(os.Stderr, "usage: extract_jar_packages -i <input file> -o <output -file> [-prefix <prefix>]")
  43. flag.PrintDefaults()
  44. }
  45. flag.Parse()
  46. if *outputFile == "" || *inputFile == "" {
  47. flag.Usage()
  48. os.Exit(1)
  49. }
  50. pkgSet := make(map[string]bool)
  51. reader, err := zip.OpenReader(*inputFile)
  52. if err != nil {
  53. log.Fatal(err)
  54. }
  55. defer reader.Close()
  56. for _, f := range reader.File {
  57. ext := filepath.Ext(f.Name)
  58. if ext == ".java" || ext == ".class" {
  59. pkgSet[fileToPackage(f.Name)] = true
  60. }
  61. }
  62. var pkgs []string
  63. for k := range pkgSet {
  64. pkgs = append(pkgs, k)
  65. }
  66. sort.Strings(pkgs)
  67. var data []byte
  68. for _, pkg := range pkgs {
  69. data = append(data, *prefix...)
  70. data = append(data, pkg...)
  71. data = append(data, "\n"...)
  72. }
  73. must(ioutil.WriteFile(*outputFile, data, 0666))
  74. }