gocyclo

package module
v0.0.0-...-c0e470d Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 30, 2023 License: BSD-3-Clause Imports: 12 Imported by: 0

README

gocyclo

Cyclomatic complexity & maintainability index library for go language
This repository forked from https://github.com/fzipp/gocyclo and is enhanced with additional features

PkgGoDev Build Status Go Report Card

Gocyclo calculates cyclomatic complexities & maintaninability index of functions in Go source code.

Cyclomatic complexity is a software metric used to measure the complexity of a program's source code. It provides a quantitative measure of the number of independent paths through a program's control flow. In other words, it measures how many different possible paths the program can take based on different conditions and decisions.

A higher cyclomatic complexity value indicates that a program has more complex control flow and is likely to be more difficult to understand, test, and maintain. This metric helps software developers identify code that may be more prone to errors, as complex code paths can increase the likelihood of bugs.

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.

The maintainability index is a software metric used to assess the maintainability of a software system's source code. It provides a numerical rating that indicates how easy or difficult it is to maintain and modify the codebase. The maintainability index takes into account various factors such as code complexity, size, and code structure.

The maintainability index is typically calculated using a formula that incorporates metrics such as cyclomatic complexity, lines of code, and code duplication. The formula varies depending on the tool or methodology used, but the resulting index is usually represented as a score between 0 and 100, with higher scores indicating better maintainability.

A higher maintainability index implies that the codebase is easier to understand, modify, and enhance. It suggests that the code has clear structure, low complexity, and is well-documented. On the other hand, a lower maintainability index indicates that the code may be more convoluted, harder to comprehend, and prone to errors.

Maintainability Index = MAX(0, (171 - 5.2 * ln(Halstead Volume) - 0.23 * (Cyclomatic Complexity) - 16.2 * ln(LOC)) * 100 / 171)

Installation

To install the gocyclo command, run

go install github.com/dwarakauttarkar/gocyclo/cmd/gocyclo@latest

Place 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;
    
    -format             define the output format. Default is json. For csv 
                        the -file needs to be specified. if file is not specified 
                        then the output file is saved in /tmp/gocyclo-<datetime>.csv.
                        the short option prints the value without a label.
                        supported formats: tabular, json, csv(file output)
    
    -file               define the output file location. Default is /tmp/gocyclo-<datetime>.csv                          
    
    -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 -avg .
gocyclo -top 20 -ignore "_test|Godeps|vendor/" .
gocyclo -over 3 -avg gocyclo/
gocyclo -format <json/tabular/csv> graph.go
gocyclo -format csv -file /<file_path>/code_analysis.csv graph.go
Tabular Output

gocyclo -format tabular graph.go

PackageName  FunctionName       CyclomaticComplexity  MaintainabilityIndex
-----------  ------------       --------------------  --------------------
graph        (*Graph).Dijkstra  8                     41
graph        (Item).More        1                     74
graph        (Item).Idx         1                     78

JSON Format

gocyclo -format json graph.go


[
  {
    "PkgName": "graph",
    "FuncName": "(*Graph).Dijkstra",
    "CyclomaticComplexity": 8,
    "MaintainabilityIndex": 41,
    "Pos": {
      "Filename": "graph.go",
      "Offset": 372,
      "Line": 24,
      "Column": 1
    }
  },
  {
    "PkgName": "graph",
    "FuncName": "(Item).More",
    "CyclomaticComplexity": 1,
    "MaintainabilityIndex": 74,
    "Pos": {
      "Filename": "graph.go",
      "Offset": 228,
      "Line": 16,
      "Column": 1
    }
  },
  {
    "PkgName": "graph",
    "FuncName": "(Item).Idx",
    "CyclomaticComplexity": 1,
    "MaintainabilityIndex": 78,
    "Pos": {
      "Filename": "graph.go",
      "Offset": 328,
      "Line": 20,
      "Column": 1
    }
  }
]

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.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Stat

type Stat struct {
	PkgName              string
	FuncName             string
	CyclomaticComplexity int
	MaintainabilityIndex int
	Pos                  token.Position
}

Stat holds the cyclomatic complexity of a function, along with its package and and function name and its position in the source code.

func (Stat) String

func (s Stat) String() string

String formats the cyclomatic complexity information of a function in the following format: "<complexity> <package> <function> <file:line:column>"

type Stats

type Stats []Stat

Stats hold the cyclomatic complexities of many functions.

func Analyze

func Analyze(paths []string, ignore *regexp.Regexp) (Stats, error)

Analyze calculates the cyclomatic complexities of the functions and methods in the Go source code files in the given paths. If a path is a directory all Go files under that directory are analyzed recursively. Files with paths matching the 'ignore' regular expressions are skipped. The 'ignore' parameter can be nil, meaning that no files are skipped.

func AnalyzeASTFile

func AnalyzeASTFile(f *ast.File, fs *token.FileSet, s Stats) Stats

AnalyzeASTFile calculates the cyclomatic complexities of the functions and methods in the abstract syntax tree (AST) of a parsed Go file and appends the results to the given Stats slice.

func (Stats) AverageComplexity

func (s Stats) AverageComplexity() float64

AverageComplexity calculates the average cyclomatic complexity of the cyclomatic complexities in s.

func (Stats) SortAndFilter

func (s Stats) SortAndFilter(top int) Stats

SortAndFilter sorts the cyclomatic complexities in s in descending order and returns a slice of s limited to the 'top' N entries with a cyclomatic complexity greater than 'over'. If 'top' is negative, i.e. -1, it does not limit the result. If 'over' is <= 0 it does not limit the result either, because a function has a base cyclomatic complexity of at least 1.

func (Stats) TotalCyclomaticComplexity

func (s Stats) TotalCyclomaticComplexity() uint64

TotalCyclomaticComplexity calculates the total sum of all cyclomatic complexities in s.

Directories

Path Synopsis
cmd
gocyclo
Gocyclo calculates the cyclomatic complexities of functions and methods in Go source code.
Gocyclo calculates the cyclomatic complexities of functions and methods in Go source code.
Package gocyclo calculates the cyclomatic complexities of functions and methods in Go source code.
Package gocyclo calculates the cyclomatic complexities of functions and methods in Go source code.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL