com.android.tools.lint.detector.api
Class LintUtils

java.lang.Object
  extended by com.android.tools.lint.detector.api.LintUtils

@Beta
public class LintUtils
extends java.lang.Object

Useful utility methods related to lint.

NOTE: This is not a public or final API; if you rely on this be prepared to adjust your code for the next tools release.


Field Summary
static boolean sTryPrefixLookup
          Whether we should attempt to look up the prefix from the model.
 
Method Summary
static boolean assertionsEnabled()
          Returns true if assertions are enabled
static java.lang.String computeResourceName(java.lang.String prefix, java.lang.String name)
          Computes a suggested name given a resource prefix and resource name
static java.lang.String computeResourcePrefix(com.android.builder.model.AndroidProject project)
          Looks up the resource prefix for the given Gradle project, if possible
static com.android.sdklib.AndroidVersion convertVersion(com.android.builder.model.ApiVersion api, com.android.sdklib.IAndroidTarget[] targets)
          Convert an ApiVersion to a AndroidVersion.
static int editDistance(java.lang.String s, java.lang.String t)
          Computes the edit distance (number of insertions, deletions or substitutions to edit one string into the other) between two strings.
static boolean endsWith(java.lang.String string, java.lang.String suffix)
          Case insensitive ends with
static java.lang.String findSubstring(java.lang.String string, java.lang.String prefix, java.lang.String suffix)
          Looks for a certain string within a larger string, which should immediately follow the given prefix and immediately precede the given suffix.
static java.lang.String formatList(java.util.List<java.lang.String> strings, int maxItems)
          Format a list of strings, and cut of the list at maxItems if the number of items are greater.
static java.lang.String getBaseName(java.lang.String fileName)
          Returns the basename of the given filename, unless it's a dot-file such as ".svn".
static int getChildCount(org.w3c.dom.Node node)
          Returns the number of children of the given node
static java.util.List<org.w3c.dom.Element> getChildren(org.w3c.dom.Node node)
          Returns the children elements of the given node
static java.io.File getCommonParent(java.io.File file1, java.io.File file2)
          Computes the closest common parent path between two files.
static java.io.File getCommonParent(java.util.List<java.io.File> files)
          Computes the shared parent among a set of files (which may be null).
static java.lang.String getEncodedString(byte[] data)
          Returns the String corresponding to the given data.
static java.lang.String getEncodedString(LintClient client, java.io.File file)
          Returns the encoded String for the given file.
static java.lang.String getFieldName(java.lang.String styleName)
          Returns the corresponding R field name for the given XML resource name
static java.util.List<java.lang.String> getFormattedParameters(java.lang.String format, java.lang.String errorMessage)
          Splits up the given message coming from a given string format (where the string format follows the very specific convention of having only strings formatted exactly with the format %n$s where n is between 1 and 9 inclusive, and each formatting parameter appears exactly once, and in increasing order.
static java.util.List<com.android.ide.common.rendering.api.StyleResourceValue> getInheritedStyles(Project project, LintClient client, java.lang.String styleUrl)
           
static java.lang.String getLayoutName(java.io.File layoutFile)
          Returns the layout resource name for the given layout file
static com.android.ide.common.resources.configuration.LocaleQualifier getLocale(java.lang.String parent)
          Returns the locale for the given parent folder.
static com.android.ide.common.resources.configuration.LocaleQualifier getLocale(XmlContext context)
          Returns the locale for the given context.
static java.lang.String getLocaleAndRegion(java.lang.String folderName)
          Look up the locale and region from the given parent folder name and return it as a combined string, such as "en", "en-rUS", b+eng-US, etc, or null if no language is specified.
static org.objectweb.asm.tree.AbstractInsnNode getNextInstruction(org.objectweb.asm.tree.AbstractInsnNode node)
          Returns the next instruction after to the given node, ignoring label and line number nodes.
static int getNextOpcode(org.objectweb.asm.tree.AbstractInsnNode node)
          Returns the next opcode after to the given node, ignoring label and line number nodes
static org.objectweb.asm.tree.AbstractInsnNode getPrevInstruction(org.objectweb.asm.tree.AbstractInsnNode node)
          Returns the previous instruction prior to the given node, ignoring label and line number nodes.
static int getPrevOpcode(org.objectweb.asm.tree.AbstractInsnNode node)
          Returns the previous opcode prior to the given node, ignoring label and line number nodes
static java.util.List<com.android.ide.common.rendering.api.ResourceValue> getStyleAttributes(Project project, LintClient client, java.lang.String styleUrl, java.lang.String namespace, java.lang.String attribute)
          Looks up the resource values for the given attribute given a style.
static Location guessGradleLocation(Project project)
          Create a Location for an error in the top level build.gradle file.
static boolean idReferencesMatch(java.lang.String id1, java.lang.String id2)
          Returns true if the given two id references match.
static boolean isAnonymousClass(org.objectweb.asm.tree.ClassNode classNode)
          Returns true if the given class node represents an anonymous inner class
static boolean isBitmapFile(java.io.File file)
          Returns true if the given file represents a bitmap drawable file
static boolean isEnglishResource(XmlContext context, boolean assumeForBase)
          Check whether the given resource file is in an English locale
static boolean isFileBasedResourceType(com.android.resources.ResourceType type)
          Determine if the given type corresponds to a resource that has a unique file
static boolean isImported(lombok.ast.Node compilationUnit, java.lang.String fullyQualifiedName)
          Returns true if the given class (specified by a fully qualified class name) name is imported in the given compilation unit either through a fully qualified import or by a wildcard import.
static boolean isManifestFolder(java.io.File dir)
          Returns true if the given directory is a lint manifest file directory.
static boolean isModelOlderThan(com.android.builder.model.AndroidProject project, int major, int minor, int micro)
          Returns true if the given Gradle model is older than the given version number
static boolean isRootElement(org.w3c.dom.Element element)
          Returns true if the given element is the root element of its document
static boolean isSameResourceFile(java.io.File file1, java.io.File file2)
          Returns true if the given two paths point to the same logical resource file within a source set.
static boolean isStaticInnerClass(org.objectweb.asm.tree.ClassNode classNode)
          Returns true if the given class node represents a static inner class.
static boolean isXmlFile(java.io.File file)
          Returns true if the given file represents an XML file
static java.lang.Iterable<java.lang.String> splitPath(java.lang.String path)
          Splits the given path into its individual parts, attempting to be tolerant about path separators (: or ;).
static boolean startsWith(java.lang.String string, java.lang.String prefix, int offset)
          Case insensitive starts with
static java.lang.String stripIdPrefix(java.lang.String id)
          Returns the given id without an @id/ or @+id prefix
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

sTryPrefixLookup

public static boolean sTryPrefixLookup
Whether we should attempt to look up the prefix from the model. Set to false if we encounter a model which is too old.

This is public such that code which for example syncs to a new gradle model can reset it.

Method Detail

formatList

@NonNull
public static java.lang.String formatList(@NonNull
                                                  java.util.List<java.lang.String> strings,
                                                  int maxItems)
Format a list of strings, and cut of the list at maxItems if the number of items are greater.

Parameters:
strings - the list of strings to print out as a comma separated list
maxItems - the maximum number of items to print
Returns:
a comma separated list

isFileBasedResourceType

public static boolean isFileBasedResourceType(@NonNull
                                              com.android.resources.ResourceType type)
Determine if the given type corresponds to a resource that has a unique file

Parameters:
type - the resource type to check
Returns:
true if the given type corresponds to a file-type resource

isXmlFile

public static boolean isXmlFile(@NonNull
                                java.io.File file)
Returns true if the given file represents an XML file

Parameters:
file - the file to be checked
Returns:
true if the given file is an xml file

isBitmapFile

public static boolean isBitmapFile(@NonNull
                                   java.io.File file)
Returns true if the given file represents a bitmap drawable file

Parameters:
file - the file to be checked
Returns:
true if the given file is an xml file

endsWith

public static boolean endsWith(@NonNull
                               java.lang.String string,
                               @NonNull
                               java.lang.String suffix)
Case insensitive ends with

Parameters:
string - the string to be tested whether it ends with the given suffix
suffix - the suffix to check
Returns:
true if string ends with suffix, case-insensitively.

startsWith

public static boolean startsWith(@NonNull
                                 java.lang.String string,
                                 @NonNull
                                 java.lang.String prefix,
                                 int offset)
Case insensitive starts with

Parameters:
string - the string to be tested whether it starts with the given prefix
prefix - the prefix to check
offset - the offset to start checking with
Returns:
true if string starts with prefix, case-insensitively.

getBaseName

public static java.lang.String getBaseName(@NonNull
                                           java.lang.String fileName)
Returns the basename of the given filename, unless it's a dot-file such as ".svn".

Parameters:
fileName - the file name to extract the basename from
Returns:
the basename (the filename without the file extension)

getChildren

@NonNull
public static java.util.List<org.w3c.dom.Element> getChildren(@NonNull
                                                                      org.w3c.dom.Node node)
Returns the children elements of the given node

Parameters:
node - the parent node
Returns:
a list of element children, never null

getChildCount

public static int getChildCount(@NonNull
                                org.w3c.dom.Node node)
Returns the number of children of the given node

Parameters:
node - the parent node
Returns:
the count of element children

isRootElement

public static boolean isRootElement(org.w3c.dom.Element element)
Returns true if the given element is the root element of its document

Parameters:
element - the element to test
Returns:
true if the element is the root element

getFieldName

public static java.lang.String getFieldName(@NonNull
                                            java.lang.String styleName)
Returns the corresponding R field name for the given XML resource name

Parameters:
styleName - the XML name
Returns:
the corresponding R field name

stripIdPrefix

@NonNull
public static java.lang.String stripIdPrefix(@Nullable
                                                     java.lang.String id)
Returns the given id without an @id/ or @+id prefix

Parameters:
id - the id to strip
Returns:
the stripped id, never null

idReferencesMatch

public static boolean idReferencesMatch(@Nullable
                                        java.lang.String id1,
                                        @Nullable
                                        java.lang.String id2)
Returns true if the given two id references match. This is similar to String equality, but it also considers "@+id/foo == @id/foo.

Parameters:
id1 - the first id to compare
id2 - the second id to compare
Returns:
true if the two id references refer to the same id

editDistance

public static int editDistance(@NonNull
                               java.lang.String s,
                               @NonNull
                               java.lang.String t)
Computes the edit distance (number of insertions, deletions or substitutions to edit one string into the other) between two strings. In particular, this will compute the Levenshtein distance.

See http://en.wikipedia.org/wiki/Levenshtein_distance for details.

Parameters:
s - the first string to compare
t - the second string to compare
Returns:
the edit distance between the two strings

assertionsEnabled

public static boolean assertionsEnabled()
Returns true if assertions are enabled

Returns:
true if assertions are enabled

getLayoutName

public static java.lang.String getLayoutName(java.io.File layoutFile)
Returns the layout resource name for the given layout file

Parameters:
layoutFile - the file pointing to the layout
Returns:
the layout resource name, not including the @layout prefix

splitPath

public static java.lang.Iterable<java.lang.String> splitPath(@NonNull
                                                             java.lang.String path)
Splits the given path into its individual parts, attempting to be tolerant about path separators (: or ;). It can handle possibly ambiguous paths, such as c:\foo\bar:\other, though of course these are to be avoided if possible.

Parameters:
path - the path variable to split, which can use both : and ; as path separators.
Returns:
the individual path components as an Iterable of strings

getCommonParent

@Nullable
public static java.io.File getCommonParent(@NonNull
                                                    java.util.List<java.io.File> files)
Computes the shared parent among a set of files (which may be null).

Parameters:
files - the set of files to be checked
Returns:
the closest common ancestor file, or null if none was found

getCommonParent

@Nullable
public static java.io.File getCommonParent(@NonNull
                                                    java.io.File file1,
                                                    @NonNull
                                                    java.io.File file2)
Computes the closest common parent path between two files.

Parameters:
file1 - the first file to be compared
file2 - the second file to be compared
Returns:
the closest common ancestor file, or null if the two files have no common parent

getEncodedString

@NonNull
public static java.lang.String getEncodedString(@NonNull
                                                        LintClient client,
                                                        @NonNull
                                                        java.io.File file)
                                         throws java.io.IOException
Returns the encoded String for the given file. This is usually the same as Files.toString(file, Charsets.UTF8, but if there's a UTF byte order mark (for UTF8, UTF_16 or UTF_16LE), use that instead.

Parameters:
client - the client to use for I/O operations
file - the file to read from
Returns:
the string
Throws:
java.io.IOException - if the file cannot be read properly

getEncodedString

@NonNull
public static java.lang.String getEncodedString(@Nullable
                                                        byte[] data)
Returns the String corresponding to the given data. This is usually the same as new String(data), but if there's a UTF byte order mark (for UTF8, UTF_16 or UTF_16LE), use that instead.

NOTE: For XML files, there is the additional complication that there could be a encoding= attribute in the prologue. For those files, use PositionXmlParser.getXmlString(byte[]) instead.

Parameters:
data - the byte array to construct the string from
Returns:
the string

isStaticInnerClass

public static boolean isStaticInnerClass(@NonNull
                                         org.objectweb.asm.tree.ClassNode classNode)
Returns true if the given class node represents a static inner class.

Parameters:
classNode - the inner class to be checked
Returns:
true if the class node represents an inner class that is static

isAnonymousClass

public static boolean isAnonymousClass(@NonNull
                                       org.objectweb.asm.tree.ClassNode classNode)
Returns true if the given class node represents an anonymous inner class

Parameters:
classNode - the class to be checked
Returns:
true if the class appears to be an anonymous class

getPrevOpcode

public static int getPrevOpcode(@NonNull
                                org.objectweb.asm.tree.AbstractInsnNode node)
Returns the previous opcode prior to the given node, ignoring label and line number nodes

Parameters:
node - the node to look up the previous opcode for
Returns:
the previous opcode, or Opcodes.NOP if no previous node was found

getPrevInstruction

@Nullable
public static org.objectweb.asm.tree.AbstractInsnNode getPrevInstruction(@NonNull
                                                                                  org.objectweb.asm.tree.AbstractInsnNode node)
Returns the previous instruction prior to the given node, ignoring label and line number nodes.

Parameters:
node - the node to look up the previous instruction for
Returns:
the previous instruction, or null if no previous node was found

getNextOpcode

public static int getNextOpcode(@NonNull
                                org.objectweb.asm.tree.AbstractInsnNode node)
Returns the next opcode after to the given node, ignoring label and line number nodes

Parameters:
node - the node to look up the next opcode for
Returns:
the next opcode, or Opcodes.NOP if no next node was found

getNextInstruction

@Nullable
public static org.objectweb.asm.tree.AbstractInsnNode getNextInstruction(@NonNull
                                                                                  org.objectweb.asm.tree.AbstractInsnNode node)
Returns the next instruction after to the given node, ignoring label and line number nodes.

Parameters:
node - the node to look up the next node for
Returns:
the next instruction, or null if no next node was found

isManifestFolder

public static boolean isManifestFolder(java.io.File dir)
Returns true if the given directory is a lint manifest file directory.

Parameters:
dir - the directory to check
Returns:
true if the directory contains a manifest file

getLocaleAndRegion

@Nullable
public static java.lang.String getLocaleAndRegion(@NonNull
                                                           java.lang.String folderName)
Look up the locale and region from the given parent folder name and return it as a combined string, such as "en", "en-rUS", b+eng-US, etc, or null if no language is specified.

Parameters:
folderName - the folder name
Returns:
the locale+region string or null

isImported

public static boolean isImported(@Nullable
                                 lombok.ast.Node compilationUnit,
                                 @NonNull
                                 java.lang.String fullyQualifiedName)
Returns true if the given class (specified by a fully qualified class name) name is imported in the given compilation unit either through a fully qualified import or by a wildcard import.

Parameters:
compilationUnit - the compilation unit
fullyQualifiedName - the fully qualified class name
Returns:
true if the given imported name refers to the given fully qualified name

getStyleAttributes

@Nullable
public static java.util.List<com.android.ide.common.rendering.api.ResourceValue> getStyleAttributes(@NonNull
                                                                                                             Project project,
                                                                                                             @NonNull
                                                                                                             LintClient client,
                                                                                                             @NonNull
                                                                                                             java.lang.String styleUrl,
                                                                                                             @NonNull
                                                                                                             java.lang.String namespace,
                                                                                                             @NonNull
                                                                                                             java.lang.String attribute)
Looks up the resource values for the given attribute given a style. Note that this only looks project-level style values, it does not resume into the framework styles.


getInheritedStyles

@Nullable
public static java.util.List<com.android.ide.common.rendering.api.StyleResourceValue> getInheritedStyles(@NonNull
                                                                                                                  Project project,
                                                                                                                  @NonNull
                                                                                                                  LintClient client,
                                                                                                                  @NonNull
                                                                                                                  java.lang.String styleUrl)

isSameResourceFile

public static boolean isSameResourceFile(@Nullable
                                         java.io.File file1,
                                         @Nullable
                                         java.io.File file2)
Returns true if the given two paths point to the same logical resource file within a source set. This means that it only checks the parent folder name and individual file name, not the path outside the parent folder.

Parameters:
file1 - the first file to compare
file2 - the second file to compare
Returns:
true if the two files have the same parent and file names

computeResourcePrefix

@Nullable
public static java.lang.String computeResourcePrefix(@Nullable
                                                              com.android.builder.model.AndroidProject project)
Looks up the resource prefix for the given Gradle project, if possible


computeResourceName

public static java.lang.String computeResourceName(@NonNull
                                                   java.lang.String prefix,
                                                   @NonNull
                                                   java.lang.String name)
Computes a suggested name given a resource prefix and resource name


convertVersion

@NonNull
public static com.android.sdklib.AndroidVersion convertVersion(@NonNull
                                                                       com.android.builder.model.ApiVersion api,
                                                                       @Nullable
                                                                       com.android.sdklib.IAndroidTarget[] targets)
Convert an ApiVersion to a AndroidVersion. The chief problem here is that the ApiVersion, when using a codename, will not encode the corresponding API level (it just reflects the string entered by the user in the gradle file) so we perform a search here (since lint really wants to know the actual numeric API level)

Parameters:
api - the api version to convert
targets - if known, the installed targets (used to resolve platform codenames, only needed to resolve platforms newer than the tools since SdkVersionInfo knows the rest)
Returns:
the corresponding version

isModelOlderThan

public static boolean isModelOlderThan(@Nullable
                                       com.android.builder.model.AndroidProject project,
                                       int major,
                                       int minor,
                                       int micro)
Returns true if the given Gradle model is older than the given version number


findSubstring

@Nullable
public static java.lang.String findSubstring(@NonNull
                                                      java.lang.String string,
                                                      @Nullable
                                                      java.lang.String prefix,
                                                      @Nullable
                                                      java.lang.String suffix)
Looks for a certain string within a larger string, which should immediately follow the given prefix and immediately precede the given suffix.

Parameters:
string - the full string to search
prefix - the optional prefix to follow
suffix - the optional suffix to precede
Returns:
the corresponding substring, if present

getFormattedParameters

@NonNull
public static java.util.List<java.lang.String> getFormattedParameters(@NonNull
                                                                              java.lang.String format,
                                                                              @NonNull
                                                                              java.lang.String errorMessage)
Splits up the given message coming from a given string format (where the string format follows the very specific convention of having only strings formatted exactly with the format %n$s where n is between 1 and 9 inclusive, and each formatting parameter appears exactly once, and in increasing order.

Parameters:
format - the format string responsible for creating the error message
errorMessage - an error message formatted with the format string
Returns:
the specific values inserted into the format

getLocale

@Nullable
public static com.android.ide.common.resources.configuration.LocaleQualifier getLocale(@NonNull
                                                                                                java.lang.String parent)
Returns the locale for the given parent folder.

Parameters:
parent - the name of the parent folder
Returns:
null if the locale is not known, or a locale qualifier providing the language and possibly region

getLocale

@Nullable
public static com.android.ide.common.resources.configuration.LocaleQualifier getLocale(@NonNull
                                                                                                XmlContext context)
Returns the locale for the given context.

Parameters:
context - the context to look up the locale for
Returns:
null if the locale is not known, or a locale qualifier providing the language and possibly region

isEnglishResource

public static boolean isEnglishResource(@NonNull
                                        XmlContext context,
                                        boolean assumeForBase)
Check whether the given resource file is in an English locale

Parameters:
context - the XML context for the resource file
assumeForBase - whether the base folder (e.g. no locale specified) should be treated as English

guessGradleLocation

public static Location guessGradleLocation(@NonNull
                                           Project project)
Create a Location for an error in the top level build.gradle file. This is necessary when we're doing an analysis based on the Gradle interpreted model, not from parsing Gradle files - and the model doesn't provide source positions.

Parameters:
project - the project containing the gradle file being analyzed
Returns:
location for the top level gradle file if it exists, otherwise fall back to the project directory.