Convert Figma logo to code with AI

fzipp logogocyclo

Calculate cyclomatic complexities of functions in Go source code.

1,345
80
1,345
8

Top Related Projects

Fast linters runner for Go

Staticcheck - The advanced Go linter

Quick Overview

gocyclo is a Go tool that calculates cyclomatic complexities of functions in Go source code. It helps developers identify complex functions that may need refactoring, improving code maintainability and readability. The tool can be used as a standalone command-line application or integrated into continuous integration pipelines.

Pros

  • Easy to use and integrate into existing workflows
  • Provides clear, actionable output for identifying complex functions
  • Customizable complexity threshold for different project requirements
  • Supports analyzing entire directories or specific files

Cons

  • Limited to cyclomatic complexity analysis only
  • May produce false positives in some cases (e.g., switch statements)
  • Doesn't provide suggestions for refactoring complex functions
  • Requires manual interpretation of results for large codebases

Code Examples

// Example 1: Analyzing a single file
package main

import "github.com/fzipp/gocyclo"

func main() {
    complexities, _ := gocyclo.AnalyzeFile("path/to/file.go", nil)
    for _, c := range complexities {
        println(c.String())
    }
}
// Example 2: Analyzing a directory with a custom threshold
package main

import "github.com/fzipp/gocyclo"

func main() {
    threshold := 10
    complexities, _ := gocyclo.AnalyzeDir("path/to/directory", nil, threshold)
    for _, c := range complexities {
        if c.Complexity > threshold {
            println(c.String())
        }
    }
}
// Example 3: Using custom options for analysis
package main

import "github.com/fzipp/gocyclo"

func main() {
    opts := &gocyclo.Options{
        IgnoreGenerated: true,
        IgnoreTests:     true,
    }
    complexities, _ := gocyclo.AnalyzeDir(".", opts, 0)
    for _, c := range complexities {
        println(c.String())
    }
}

Getting Started

To use gocyclo in your Go project, first install it:

go get github.com/fzipp/gocyclo/cmd/gocyclo

Then, you can run it from the command line:

gocyclo .

Or integrate it into your Go code:

package main

import (
    "fmt"
    "github.com/fzipp/gocyclo"
)

func main() {
    complexities, _ := gocyclo.AnalyzeDir(".", nil, 0)
    for _, c := range complexities {
        fmt.Println(c.String())
    }
}

Competitor Comparisons

Fast linters runner for Go

Pros of golangci-lint

  • Comprehensive linting tool that includes multiple linters, including cyclomatic complexity checks
  • Highly configurable with options to enable/disable specific linters and set custom rules
  • Integrates well with CI/CD pipelines and provides detailed reports

Cons of golangci-lint

  • More complex setup and configuration compared to gocyclo's simplicity
  • Larger resource footprint due to its comprehensive nature
  • May require more time to run full analysis, especially on large codebases

Code Comparison

gocyclo:

package main

import (
    "github.com/fzipp/gocyclo/cmd/gocyclo"
)

func main() {
    gocyclo.Run()
}

golangci-lint:

linters:
  enable:
    - gocyclo
    - govet
    - errcheck
  disable:
    - deadcode

linters-settings:
  gocyclo:
    min-complexity: 10

The code comparison shows the simplicity of using gocyclo as a standalone tool versus the configuration approach of golangci-lint, which allows for more comprehensive and customizable linting.

Staticcheck - The advanced Go linter

Pros of go-tools

  • Comprehensive suite of Go analysis tools, including cyclomatic complexity and much more
  • Actively maintained with frequent updates and improvements
  • Integrates well with popular editors and IDEs

Cons of go-tools

  • More complex setup and usage compared to gocyclo's simplicity
  • Larger codebase and dependencies, potentially slower for quick checks
  • May provide more information than needed for basic cyclomatic complexity analysis

Code Comparison

gocyclo:

func Analyze(filename string, src interface{}) ([]Stat, error) {
    fset := token.NewFileSet()
    f, err := parser.ParseFile(fset, filename, src, parser.ParseComments)
    if err != nil {
        return nil, err
    }
    // ... (additional analysis code)
}

go-tools (staticcheck):

func Analyze(pass *analysis.Pass) (interface{}, error) {
    inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
    nodeFilter := []ast.Node{
        (*ast.FuncDecl)(nil),
        (*ast.FuncLit)(nil),
    }
    inspect.Preorder(nodeFilter, func(n ast.Node) {
        // ... (analysis logic)
    })
    return nil, nil
}

The code comparison shows that go-tools (specifically staticcheck) uses a more sophisticated analysis approach with the analysis.Pass type, while gocyclo uses a simpler file parsing method. This reflects the broader scope and flexibility of go-tools compared to gocyclo's focused functionality.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

gocyclo

PkgGoDev Build Status Go Report Card

Gocyclo calculates cyclomatic complexities of functions in Go source code.

Cyclomatic complexity is a code quality metric which can be used to identify code that needs refactoring. It measures the number of linearly independent paths through a function's source code.

The cyclomatic complexity of a function is calculated according to the following rules:

 1 is the base complexity of a function
+1 for each 'if', 'for', 'case', '&&' or '||'

A function with a higher cyclomatic complexity requires more test cases to cover all possible paths and is potentially harder to understand. The complexity can be reduced by applying common refactoring techniques that lead to smaller functions.

Installation

To install the gocyclo command, run

$ go install github.com/fzipp/gocyclo/cmd/gocyclo@latest

and put the resulting binary in one of your PATH directories if $GOPATH/bin isn't already in your PATH.

Usage

Calculate cyclomatic complexities of Go functions.
Usage:
    gocyclo [flags] <Go file or directory> ...

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

The output fields for each line are:
<complexity> <package> <function> <file:line:column>

Examples

$ 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/

Example output:

9 gocyclo (*complexityVisitor).Visit complexity.go:30:1
8 main main cmd/gocyclo/main.go:53:1
7 gocyclo (*fileAnalyzer).analyzeDecl analyze.go:96:1
4 gocyclo Analyze analyze.go:24:1
4 gocyclo parseDirectives directives.go:27:1
4 gocyclo (Stats).SortAndFilter stats.go:52:1
Average: 2.72

Note that the average is calculated over all analyzed functions, not just the printed ones.

Ignoring individual functions

Individual functions can be ignored with a gocyclo:ignore directive:

//gocyclo:ignore
func f1() {
	// ...
}
    
//gocyclo:ignore
var f2 = func() {
	// ...
}

License

This project is free and open source software licensed under the BSD 3-Clause License.