#!/usr/bin/env python

"""
 cercaClasseJava.py
 
 Script Python che permette di sapere in quale archivio jar
 \xe8 presente una determinata classe Java (cerca all'interno 
 di tutti gli archivi del CLASSPATH)
	
 Copyright (C) 2000-2003 Michele Ferretti
 black.bird@tiscali.it
 http://www.blackbirdblog.it

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; either version 2
 of the License, or any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

"""

import zipfile
import re
import sys
import os
import time

tempo_inizio = time.time()

classpath_var = 'CLASSPATH'

# parola da cercare all'interno dei jar
searchName = sys.argv[1]

# prendo la lista dei jar dalla variabile d'ambiente CLASSPATH
if not os.environ.has_key(classpath_var):
	print 'ERRORE!'
	print 'la variabile d\'ambiente %s non \xe8 presente!' % classpath_var
	sys.exit(1)
	
classpath = os.environ[classpath_var]


# aggiungo al CLASSPATH anche le librerie standard dell'istallazione della Java VM
if os.environ.has_key('JAVA_HOME'):
	java_home = os.environ['JAVA_HOME']
	rtjar = '%s%sjre%slib%srt.jar' % (java_home, os.sep, os.sep, os.sep)
	classpath += '%s%s' % (os.pathsep, rtjar)

	
# cerco in tutti i jar una classe che contenga la classe
nTrovati, nClassi = 1, 1
for j in classpath.split(os.pathsep):
	
	if re.compile(r'.*\.(zip|jar)$').search(j):
		
		zf = zipfile.ZipFile(j, 'r')
		
		for i in zf.infolist():
			if re.compile(r'.*\.class$').search(i.filename):
				nClassi += 1
				if re.compile(searchName).search(i.filename):
					print '%s "%s" in "%s"\n' % (nTrovati, i.filename.replace('/', '.').replace('.class', ''), j)
					nTrovati += 1
				
		zf.close()
		del zf
		
		
print 'Ricerca effettuata in %f s.' % (time.time()-tempo_inizio)
print 'Ho cercato in %d archivi contenenti %d classi' % (len(classpath.split(os.pathsep)), nClassi)


