package org.apache.maven.simian;

/* ====================================================================
 *   Copyright 2001-2004 The Apache Software Foundation.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 * ====================================================================
 */

import java.util.StringTokenizer;
import java.io.File;
import java.net.URL;

/**
 *
 * @author Aslak Hellesoy
 * @version $Revision$
 */
public class FileUtils {
    /**
     * Returns the root directory of the package hierarchy where this class is
     * located. This will either be a directory or a jar file.
     *
     * @return the root directory or jar file where the class is located.
     */
    public static File getRoot(Class clazz)
    {
        File dir;
        URL classURL = clazz.getResource( "/" + clazz.getName().replace( '.', '/' ) + ".class" );
        String classFile = classURL.getFile();

        if( classFile.indexOf('!') != -1 ) {
            // Sometimes (at least on windows) we get file:F:\bla. Convert to file:/F:/bla
            if( classFile.charAt(5) != '/' ) {
                classFile = "file:/" + classFile.substring(5);
            }
            classFile = classFile.replace( '\\','/' );
            String uriSpec = classFile.substring(0, classFile.indexOf('!'));
            dir = new File( uriSpec  );
            // NOTE: This used to be here, but I've replaced it with the above single
            //       line without understanding the ramifications. The code below needs JDK1.4
            //try {
            //    dir = new File( new URL( uriSpec ) );
            //} catch (URISyntaxException e) {
            //    System.err.println("Couldn't create URI for " + uriSpec);
            //    throw new IllegalStateException(e.getMessage());
            //}
        } else {
            dir = new File( classFile ).getParentFile();
            StringTokenizer st = new StringTokenizer( clazz.getName(), "." );

            for( int i = 0; i < st.countTokens() - 1; i++ )
            {
                dir = dir.getParentFile();
            }
        }
        return dir;
    }
}
