summaryrefslogtreecommitdiff
path: root/src/cuchaz/enigma/mapping/NameValidator.java
blob: 30982dc6786bb325b729078027045cc8f30fcd74 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*******************************************************************************
 * Copyright (c) 2014 Jeff Martin.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v3.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/gpl.html
 * 
 * Contributors:
 *     Jeff Martin - initial API and implementation
 ******************************************************************************/
package cuchaz.enigma.mapping;

import java.util.regex.Pattern;

public class NameValidator
{
	private static final String IdentifierPattern;
	private static final Pattern ClassPattern;
	
	static
	{
		// java allows all kinds of weird characters...
		StringBuilder startChars = new StringBuilder();
		StringBuilder partChars = new StringBuilder();
		for( int i = Character.MIN_CODE_POINT; i <= Character.MAX_CODE_POINT; i++ )
		{
			if( Character.isJavaIdentifierStart( i ) )
			{
				startChars.appendCodePoint( i );
			}
			if( Character.isJavaIdentifierPart( i ) )
			{
				partChars.appendCodePoint( i );
			}
		}
		
		IdentifierPattern = String.format( "[\\Q%s\\E][\\Q%s\\E]*", startChars.toString(), partChars.toString() );
		ClassPattern = Pattern.compile( String.format( "^(%s(\\.|/))*(%s)$", IdentifierPattern, IdentifierPattern ) );
	}
	
	public String validateClassName( String name )
	{
		if( !ClassPattern.matcher( name ).matches() )
		{
			throw new IllegalArgumentException( "Illegal name: " + name );
		}
		
		return classNameToJavaName( name );
	}
	
	public static String fileNameToClassName( String fileName )
	{
		final String suffix = ".class";
		
		if( !fileName.endsWith( suffix ) )
		{
			return null;
		}
		
		return fileName.substring( 0, fileName.length() - suffix.length() ).replace( "/", "." );
	}
	
	public static String classNameToJavaName( String className )
	{
		return className.replace( ".", "/" );
	}
}