16.8.2.  Find Text in Code

If you want to create metrics or issues based on text contained in source files, the visitor offers the method onSourceFile() and the class SourceFileAccess that provides access to individual lines.

Combined with regular expressions this is a very powerful method to identify anything in the code that is not contained in the model, e.g. FIXME or TODO in comments.

The following is an excerpt from the script FindFixmeAndTodoInComments.scr contained in the "Core" quality model:

def todoPattern = ~/\/\/\s?TODO.?\b/;
ICoreVisitor visitor = coreAccess.createVisitor();
            
visitor.onSourceFile
{
    ISourceFileAccess source ->
    if(source.isExcluded())
    {
        return;
    }
    
    List<ISourceLineAccess> lines = source.getSourceLines();
        ...
}

TIP

The compilation of the regular expression pattern is an expensive operation and should be done in the "global" section of a script, not within a visit() method.

TIP

Limit the number of scripts using SourceFileAccess. Sonargraph does not keep file contents in memory, thus visiting source files and traversing individual lines causes the actual files being opened. This is a costly operation and slows down the execution.

If you notice that various scripts contain source matching and this is time consuming, think about minimizing file operations by violating the "Single Responsibility Principle" and merge the functionality of several scripts into one.