gocyclo

repository·main·Indexed 23 days ago

https://github.com/fzipp/gocyclo

A tool for calculating the cyclomatic complexity of functions in Go source code to help identify complex code requiring refactoring or testing. It provides a CLI for analyzing files and directories, supporting flags to filter by complexity threshold (-over), limit results (-top), calculate averages (-avg), and ignore files via regex. It also supports a //gocyclo:ignore directive to exclude specific functions and provides a Go API including Analyze(), AnalyzeASTFile(), and Complexity() for programmatic analysis.

Tokens
1.9K
Snippets
6
Records
16
Agent score
82%

What's inside gocyclo

  1. Ignore individual functions with gocyclo:ignore

    main

    You can exclude specific functions from complexity analysis by adding the //gocyclo:ignore directive directly above the function or variable declaration.

    //gocyclo:ignore
    func f1() {
    	// ...
    }
        
    //gocyclo:ignore
    var f2 = func() {
    	// ...
    }
  2. Install the gocyclo CLI

    main

    To install the gocyclo command, use the go install command. Ensure that $GOPATH/bin is in your PATH so you can run the binary directly.

    $ go install github.com/fzipp/gocyclo/cmd/gocyclo@latest
  3. Ignore functions using //gocyclo:ignore directives

    main
    You can prevent specific functions from being included in cyclomatic complexity calculations by adding a //gocyclo:ignore comment directly above the function definition. The gocyclo tool parses these directives from the AST comment groups to identify which functions should be skipped.
  4. Examples of gocyclo usage

    main

    Common usage patterns for gocyclo include:

    • Analyzing the current directory: gocyclo .
    • Finding the top 10 most complex functions: gocyclo -top 10 src/
    • Finding functions with complexity over 25: gocyclo -over 25 docker
    • Calculating average complexity: gocyclo -avg .
    • Filtering out specific directories (like vendor or tests) using regex: gocyclo -top 20 -ignore "_test|Godeps|vendor/" .
    $ gocyclo .
    $ gocyclo main.go
    $ gocyclo -top 10 src/
    $ gocyclo -over 25 docker
    $ gocyclo -avg .
    $ gocyclo -top 20 -ignore "_test|Godeps|vendor/" .
    $ gocyclo -over 3 -avg gocyclo/
  5. Reference gocyclo CLI flags

    main

    Use the following flags to filter or summarize the complexity analysis:

    • -over N: Show only functions with complexity greater than N. Returns exit code 1 if any functions match the criteria.
    • -top N: Show only the top N most complex functions.
    • -avg or -avg-short: Show the average complexity over all analyzed functions. The -avg-short option prints the value without a label.
    • -ignore REGEX: Exclude files that match the provided regular expression.
    Flags:
        -over N               show functions with complexity > N only and
                              return exit code 1 if the set is non-empty
        -top N                show the top N most complex functions only
        -avg, -avg-short      show the average complexity over all functions;
                              the short option prints the value without a label
        -ignore REGEX         exclude files matching the given regular expression
  6. Use gocyclo to calculate cyclomatic complexity

    main

    The gocyclo command calculates the cyclomatic complexity of functions in Go source code. You can provide Go files or directories as arguments.

    Output Format: Each line of output follows this pattern: <complexity> <package> <function> <file:line:column>

    $ gocyclo .
    $ gocyclo main.go
  7. Sort and filter complexity results with SortAndFilter

    main

    The SortAndFilter(top, over int) Stats method sorts the Stats slice in descending order (modifying the original slice) and returns a subset based on the following rules:

    • top: The maximum number of entries to return. If set to -1, the result is not limited by count.
    • over: The minimum complexity threshold. Only functions with a complexity strictly greater than over are included. If over <= 0, the result is not limited by complexity.

    This is useful for identifying the most complex functions in a codebase.

  8. Analyze an AST file with AnalyzeASTFile()

    main
    If you have already parsed a Go file into an Abstract Syntax Tree (AST), use AnalyzeASTFile(f *ast.File, fs *token.FileSet, s Stats) Stats to calculate complexities. This function appends the results to the provided Stats slice and returns the updated slice.
  9. Calculate function complexity with Complexity()

    main

    The Complexity function calculates the cyclomatic complexity of a Go function or method. It accepts an ast.Node which must be either a *ast.FuncDecl (function declaration) or a *ast.FuncLit (function literal/anonymous function).

    Complexity is calculated by starting at 1 and incrementing for each of the following control flow structures:

    • *ast.IfStmt (if statements)
    • *ast.ForStmt (for loops)
    • *ast.RangeStmt (range loops)
    • *ast.CaseClause (switch/select cases, excluding default cases)
    • *ast.CommClause (select communication cases, excluding default cases)
    • *ast.BinaryExpr using token.LAND (&&) or token.LOR (||) operators.
  10. Calculate total and average complexity using Stats

    main

    Use the following methods on a Stats slice to get aggregate metrics:

    • TotalComplexity() uint64: Returns the sum of all cyclomatic complexities in the slice.
    • AverageComplexity() float64: Returns the mean complexity of all functions in the slice.
  11. Analyze Go files and directories with Analyze()

    main

    Use Analyze(paths []string, ignore *regexp.Regexp) Stats to calculate the cyclomatic complexities of functions and methods within specified Go source files or directories. If a path is a directory, the function recursively analyzes all Go files within it.

    You can provide an optional ignore regular expression to skip files that match the pattern. If ignore is nil, no files are skipped.

  12. Configure gocyclo CLI flags

    main

    Use the following flags to filter results or change the output behavior of gocyclo:

    FlagDescription
    -over NShow only functions with complexity > N. If any functions match this criteria, the tool returns exit code 1
    -top NShow only the top N most complex functions
    -avgShow the average complexity of all functions
    -avg-shortShow the average complexity without a label
    -ignore REGEXExclude files matching the provided regular expression