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