Getting Started with coala

Welcome to this little tutorial. It is meant to be a gentle introductionto the usage of coala.

Prerequisites

In order to complete this tutorial you will need coala installed.Installation instructions can be found here.

Note

Here’s a list of oursupported languages.

Get Some Code

In order to perform a static code analysis on your code you will needsome code to check. If you do not have your own code you want to check, youcan retrieve our tutorial samples:

  1. git clone https://github.com/coala/coala-tutorial

Please note that the commands given in this tutorial are intended foruse with this sample code and may need minor adjustments.

Let’s Start!

There are two options how to let coala know what kind of analysis itshould perform on which code.

Command Line Interface

In order to specify the files to analyze, you can use the —filesargument of coala like demonstrated below. For all file paths, you canspecify (recursive) globs.

Because analysis routines can do many various things we named thembears. A bear can check your code for potential problems, calculate metricsand even provide corrections for your code.

You can specify the bears that you want coala to run using the —bearsargument:

  1. cd coala-tutorial
  2. coala --files=src/\*.c --bears=SpaceConsistencyBear --save

Note

You can use comma separated values to specify more than one item inarguments! Do not use spaces as that would start a new argument.Example: SpaceConsistencyBear,PEP8Bear

coala will now ask you for missing values that are needed to perform theanalysis, which in this case is only the use_spaces setting. Werecommend setting it to True.

  1. Please enter a value for the setting "use_spaces" (True if spaces
  2. are to be used instead of tabs.) needed by SpaceConsistencyBear
  3. for section "cli"

coala will now check the code and, in case you use the tutorial code,yield one result. SpaceConsistencyBear will detect a trailing whitespace atthe end of the line, after #include <stdio.h> in the main.c file. coalawill then ask you to remove the trailing space, by applying the suggestedpatch (option 2).

  1. Executing section cli...
  2.  
  3. src/main.c
  4. | 1| #include·<stdio.h
  5. | | [NORMAL] SpaceConsistencyBear:
  6. | | Line contains following spacing inconsistencies:
  7. | | - Trailing whitespaces.
  8. |----| | /path/coala-tutorial/src/main.c
  9. | |++++| /path/coala-tutorial/src/main.c
  10. | 1| |-#include <stdio.h>
  11. | | 1|+#include <stdio.h>
  12. | 2| 2|
  13. | 3| 3| int main(void) {
  14. | 4| 4| printf("Welcome to coala. Keep following the
  15. tutorial, you are doing a great job so far!\n");
  16. | | *0: Do nothing
  17. | | 1: Open file(s)
  18. | | 2: Apply patch
  19. | | 3: Print more info
  20. | | 4: Add ignore comment
  21. | | Enter number (Ctrl-D to exit): 2

If the patch was applied succesfully, you should see something like this:

  1. | | Patch applied successfully.
  2. | | *0: Do nothing
  3. | | 1: Open file(s)
  4. | | 2: Print more info
  5. | | 3: Add ignore comment
  6. | | Enter number (Ctrl-D to exit):

Exit by pressing Ctrl-D.

You can also run coala in non interactive mode (given that all the settingsrequired by the bears you are using are provided in the .coafile)

  1. coala --non-interactive

In this case there won’t be any interaction, the patch will be shown directly.

Feel free to experiment a bit. You’ve successfully analysed some code!But don’t stop reading - you don’t have to enter all those values again!We have given coala the —save argument, which means that it willautomatically generate a .coafile into the current directory. Read on!

Configuration Files - coafiles

coala supports a very simple configuration file. If you’ve executed theinstructions from the CLI section above, coala will already have such afile readily prepared for you. Go, take a look at it:

  1. cat .coafile

Note

If you are using Windows, you should use type .coafile instead!

This should yield something like this:

  1. [cli]
  2. bears = SpaceConsistencyBear
  3. files = src/*.c
  4. use_spaces = True

If you now invoke coala it will parse this .coafile from yourcurrent directory. This makes it easy to specify once for your projectwhat is checked with which bears and make it available to allcontributors.

Feel free to play around with this file. You can either edit it manuallyor add/edit settings via coala —save … invocations. If you wantcoala to save settings every time, you can add save = True manuallyinto your .coafile.

Sections

Thats all nice and well but we also have a Makefile for our project wewant to check. So let us introduce another feature of our configurationsyntax: sections.

The line [cli] in the .coafile implies that everything belowbelongs to the special cli section. You may specify sections whenyou enter the settings via the Command Line Interface (CLI). You willsoon learn all about them. When you don’t specify any sections, thesettings will implicitly belong to the [cli] section.

Next you will see how to specify sections using the command line whenyou are running coala. Let’s check the line lengths of our Makefile:

  1. coala -S Makefiles.bears=LineLengthBear Makefiles.files=Makefile --save

As you can see, the -S (or —settings) option allows to specifyarbitrary settings. Settings can be directly stored into a section withthe section.setting syntax.

By default, the LineLengthBear checks whether each line contains79 chars or less in a line. To change this value, use themax_line_length inside the .coafile.

coala will now yield any result you didn’t correct last time, plus a newone for the Makefile. This time coala (or better, theLineLengthBear) doesn’t know how to fix the issue but still tries toprovide as much helpful information as possible and provides you theoption to directly open the file in an editor of your choice.

Note

If you want to set a default editor and not be asked for one every time,you can simply add editor=$editorName (i.e. editor=vim) to yourproject’s .coafile and it will automatically open in that one.

Note

If your editor is already open this may not work, because the otherprocess will shortly communicate with the existent process andreturn immediately. coala handles this for some editorsautomatically, if yours does not work yet - please file an issue so wecan include it!

If you changed one file in multiple results, coala will merge thechanges if this is possible.

coala should have appended something like this to your .coafile:

  1. [Makefiles]
  2. bears = LineLengthBear
  3. files = Makefile

As you see, sections provide a way to have different configurations forpossibly different languages in one file. They are executedsequentially.

Note

For a list of configuration options for the bears, take a look at ourcoala languages directory.

Auto-applying Results

Often you don’t want to look at trivial results like spacing issues. Forthat purpose coala includes a special setting called default_actionsthat allows you to set the action for a bear that shall be automaticallyapplied on run. We have a command line alias —apply-patches to make iteasier to use.

By using —apply-patches, the user does not have to press2. (A)pply patch for applying a patch. Every patch is appliedautomatically.Alternatively, using the setting default_actions="*: ApplyPatchAction"will automatically apply —apply-patches on run.

Let’s automatically fix Python code. Take a look at our sample Pythoncode:

  1. $ cat src/add.py
  2.  
  3. """
  4. This is a simple library that provides a function that can add numbers.
  5.  
  6. Cheers!
  7. """
  8.  
  9.  
  10.  
  11. def add(a,b):
  12. return a+b;
  13.  
  14. import sys

That looks horrible, doesn’t it? Let’s fix it!

  1. $ coala -S python.bears=PEP8Bear python.files=\*\*/\*.py \
  2. --apply-patches --save
  3. # other output ...
  4. Executing section cli...
  5. Executing section python...
  6. [INFO][11:03:37] Applied 'ApplyPatchAction' for 'PEP8Bear'.
  7. [INFO][11:03:37] Applied 'ApplyPatchAction' for 'PEP8Bear'.

coala would now fix all spacing issues and without bothering you again.

Note

When you try the above example, you may get a warning, saying that allsettings in the cli section are implicitly inherited to allother sections (if they do not override their values). It also advisesus to change the name of that section to avoid unexpected behavior.The next section explains what it means and how you can avoidit.

Setting Inheritance

Let’s first see what inheritance means.

Before proceeding, rename the cli section in the .coafile toall (we will soon explain the reason behind this change).

Lets add the following section to our .coafile:

  1. [all.TODOS]
  2. bears = KeywordBear

And execute coala with the -s argument which is the same as—save. I recommend setting case insensitive keywords toTODO, FIXME and case sensitive keywords empty.

After the results we’ve already seen, we’ll see a new informational onewhich informs us that we have a TODO in our code.

Did you note that we didn’t specify which files to check this time? Thisis because all settings, including files = src/*.c, from the allsection (previously called cli) have been inherited in the newTODOS section that we just added.

You can make a section inherit from any previously defined section usingthis syntax:

  1. [parentSection.childSection]

Note

cli is an internally reserved section name. All of its settingsare implicitly inherited to every other section by default. It isbecause of this implicit inheritance feature that we are adviced torename the cli section to something else. Doing so will save usfrom having unexpected values of cli being implicitly inheritedinto our sections. We strongly suggest renaming it.

Ignoring Issues

There are several ways to ignore certain issues, so you aren’t lost ifany routines yield false positives.

Ignoring Files

coala lets you ignore whole files through the ignore setting. Inaddition to normal globs, coala offers ** to match all directories andsubdirectories:

  1. files = **/*.h
  2. ignore = **/resources.h

This configuration would include all header (.h) files but leavesout resource headers.

Ignoring Code Inside Files

Sometimes you need finer-graded ignores. Imagine you have aLineLengthBear that shall not run on some code segments, because youcan’t wrap them:

  1. code = "that's checked normally"
  2.  
  3. # Ignore LineLengthBear
  4. unwrappable_string = "some string that is long and would exceed the limit"

You can also skip an area:

  1. # Start ignoring LineLengthBear
  2. unwrappable_string_2 = unwrappable_string + "yeah it goes even further..."
  3. another_unwrappable_string = unwrappable_string + unwrappable_string_2
  4. # Stop ignoring

You can also conditionally combine ignore rules! Bear names will besplit by comma and spaces, invalid bear names like and will beignored.

Also note that in the bear names delimited by commas and spaces, you mayspecify glob wildcards that match several bears:

  1. # Start ignoring Line*, Py*
  2. unwrappable_string_2 = unwrappable_string + "yeah it goes even further..."
  3. another_unwrappable_string = unwrappable_string + unwrappable_string_2
  4. # Stop ignoring

In the above example all bears matching the glob Line* and Py* willbe ignored. You may also specify more complex globs here such as# Start ignoring (Line|P[yx]) which will ignore all bears’ names whichstart with Line, Py, and Px.

  1. # Ignore LineLengthBear and SpaceConsistencyBear
  2. variable = "Why the heck are spaces used instead of tabs..." + "so_long"

If you put an all instead of the bear names directly after theignore/ignoring keyword, the results of all bears affectingthose lines will be ignored.

If you’ve used another linter in the past, you don’t have to change yourpre-existing code with the noqa keywords to ignore as the examplesbelow work as well. If no bears are specified, noqa will be applicable towork for all bears.

  1. # noqa
  2. long_line = "This is a long line ... "

If you wish to specify which bear to use with noqa, as is donewith ignore, you would have to proceed as follows:

  1. # noqa LineLengthBear
  2. long_line = "This is a long line ... "

Enabling/Disabling Sections

Now that we have sections we need some way to control, which sectionsare executed. coala provides two ways to do that:

Manual Enabling/Disabling

If you add the line TODOS.enabled=False to some arbitrary place toyour .coafile or just enabled=False into the TODOS section,coala will not show the TODOs on every run.

Especially for those bears yielding informational messages which youmight want to see from time to time this is a good way to silence them.

Specifying Targets

If you provide positional arguments, like coala Makefiles, coalawill execute exclusively those sections that are specified. This willnot get stored in your .coafile and will take precedence over allenabled settings. You can specify several targets separated by a space.

What was that TODO again?

Continuing the Journey

If you want to know about more options, take a look at our coala settings documentation or withcoala -h. If you liked or disliked this tutorial, feel free to dropus a note at our bug tracker or mailing list.

If you need more flexibility, know that coala is extensible in many waysdue to its modular design:

  • If you want to write your own bears, take a look atour tutorial.
  • If you want to add custom actions for results, take a look at thecode in coalib/results/results_actions.
  • If you want to have some custom outputs (e.g. HTML pages, a GUI orvoice interaction) take a look at modules lying in coalib/output.Happy coding!