### Install gocyclo Source: https://github.com/fzipp/gocyclo/blob/main/README.md Use the go install command to download and install the latest version of the gocyclo binary. ```bash $ go install github.com/fzipp/gocyclo/cmd/gocyclo@latest ``` -------------------------------- ### GitHub Actions CI/CD Example for Gocyclo Source: https://context7.com/fzipp/gocyclo/llms.txt Example configuration for a GitHub Actions workflow to integrate gocyclo for checking cyclomatic complexity. It demonstrates installing gocyclo and running checks to fail builds over a certain complexity or to show the top N most complex functions. ```yaml name: Code Quality on: [push, pull_request] jobs: complexity: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-go@v4 with: go-version: '1.21' - name: Install gocyclo run: go install github.com/fzipp/gocyclo/cmd/gocyclo@latest - name: Check cyclomatic complexity run: | # Fail if any function has complexity > 15 gocyclo -over 15 . # Show top 10 most complex functions for review echo "Top 10 most complex functions:" gocyclo -top 10 . ``` -------------------------------- ### Run gocyclo Examples Source: https://github.com/fzipp/gocyclo/blob/main/README.md Common command-line patterns for analyzing Go files and directories. ```bash $ 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/ ``` -------------------------------- ### Install Gocyclo CLI Source: https://context7.com/fzipp/gocyclo/llms.txt Use the Go toolchain to install the command-line utility. ```bash go install github.com/fzipp/gocyclo/cmd/gocyclo@latest ``` -------------------------------- ### CI/CD Integration - GitHub Actions Source: https://context7.com/fzipp/gocyclo/llms.txt Provides an example of how to integrate Gocyclo into a GitHub Actions workflow to enforce code complexity limits. ```APIDOC ## CI/CD Integration ### GitHub Actions Example ### Description This example demonstrates setting up a GitHub Actions workflow to automatically check cyclomatic complexity on every push or pull request. ### Workflow Configuration ```yaml name: Code Quality on: [push, pull_request] jobs: complexity: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-go@v4 with: go-version: '1.21' - name: Install gocyclo run: go install github.com/fzipp/gocyclo/cmd/gocyclo@latest - name: Check cyclomatic complexity run: | # Fail if any function has complexity > 15 gocyclo -over 15 . # Show top 10 most complex functions for review echo "Top 10 most complex functions:" gocyclo -top 10 . ``` ### Explanation - The workflow triggers on `push` and `pull_request` events. - It checks out the code, sets up the Go environment. - Installs the `gocyclo` CLI tool. - Runs `gocyclo -over 15 .` which will cause the job to fail if any function exceeds a complexity of 15. - Additionally, it prints the top 10 most complex functions for review purposes. ``` -------------------------------- ### Sort and Filter Stats by Complexity Source: https://context7.com/fzipp/gocyclo/llms.txt Sorts stats by complexity in descending order and filters by top N and minimum threshold. Use -1 for top to get all results. ```go package main import ( "fmt" "github.com/fzipp/gocyclo" ) func main() { stats := gocyclo.Analyze([]string{"./src"}, nil) // Get top 5 functions with complexity > 3 filtered := stats.SortAndFilter(5, 3) for _, stat := range filtered { fmt.Printf("%d %s.%s\n", stat.Complexity, stat.PkgName, stat.FuncName) } // Use -1 for top to get all results allOverThreshold := stats.SortAndFilter(-1, 10) fmt.Printf("Functions with complexity > 10: %d\n", len(allOverThreshold)) } ``` -------------------------------- ### gocyclo Command Usage Source: https://github.com/fzipp/gocyclo/blob/main/README.md Displays the command-line interface help, including available flags and output format. ```text Calculate cyclomatic complexities of Go functions. Usage: gocyclo [flags] ... 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: ``` -------------------------------- ### Analyze Pre-parsed AST File Source: https://context7.com/fzipp/gocyclo/llms.txt Use gocyclo.AnalyzeASTFile to calculate complexities from an existing AST. ```go package main import ( "fmt" "go/parser" "go/token" "github.com/fzipp/gocyclo" ) func main() { fset := token.NewFileSet() f, err := parser.ParseFile(fset, "myfile.go", nil, parser.ParseComments) if err != nil { panic(err) } // Analyze the parsed AST var stats gocyclo.Stats stats = gocyclo.AnalyzeASTFile(f, fset, stats) for _, stat := range stats { fmt.Println(stat.String()) } } ``` -------------------------------- ### Combined CLI Options Source: https://context7.com/fzipp/gocyclo/llms.txt Use multiple flags together for comprehensive analysis. ```bash gocyclo -over 3 -avg -top 20 ./src ``` -------------------------------- ### gocyclo.AnalyzeASTFile Source: https://context7.com/fzipp/gocyclo/llms.txt Calculates cyclomatic complexities from a pre-parsed AST file. ```APIDOC ## gocyclo.AnalyzeASTFile ### Description Calculates cyclomatic complexities from a pre-parsed AST file. Useful when you already have parsed Go AST. ### Parameters - **f** (*ast.File) - Required - The parsed AST file. - **fset** (*token.FileSet) - Required - The file set associated with the AST. - **stats** (gocyclo.Stats) - Required - The existing stats collection to append results to. ### Response - **stats** (gocyclo.Stats) - The updated collection of function statistics. ``` -------------------------------- ### Analyze Specific File Source: https://context7.com/fzipp/gocyclo/llms.txt Analyze a single Go source file. ```bash gocyclo main.go ``` -------------------------------- ### Analyze Current Directory Source: https://context7.com/fzipp/gocyclo/llms.txt Calculate cyclomatic complexity for all Go files in the current directory. ```bash gocyclo . ``` -------------------------------- ### Analyze with Library API Source: https://context7.com/fzipp/gocyclo/llms.txt Use the gocyclo.Analyze function to programmatically scan directories and filter files. ```go package main import ( "fmt" "regexp" "github.com/fzipp/gocyclo" ) func main() { // Analyze multiple paths (files or directories) paths := []string{"./src", "./cmd"} // Optional: ignore files matching a regex pattern ignore := regexp.MustCompile(`_test\.go|vendor/`) // Analyze and get stats for all functions stats := gocyclo.Analyze(paths, ignore) // Print all function complexities for _, stat := range stats { fmt.Printf("%d %s %s %s\n", stat.Complexity, stat.PkgName, stat.FuncName, stat.Pos) } // Output: // 4 main handleRequest cmd/server/main.go:25:1 // 3 utils parseConfig src/utils/config.go:12:1 // 2 main main cmd/server/main.go:10:1 } ``` -------------------------------- ### Access Stat Structure Fields Source: https://context7.com/fzipp/gocyclo/llms.txt Demonstrates accessing individual fields of the Stat struct, including PkgName, FuncName, Complexity, and Pos. Also shows using the String() method for formatted output. ```go package main import ( "fmt" "github.com/fzipp/gocyclo" ) func main() { stats := gocyclo.Analyze([]string{"./src"}, nil) for _, stat := range stats { // Access individual fields fmt.Printf("Package: %s\n", stat.PkgName) fmt.Printf("Function: %s\n", stat.FuncName) fmt.Printf("Complexity: %d\n", stat.Complexity) fmt.Printf("Position: %s\n", stat.Pos) // Use String() for formatted output // Format: " " fmt.Println(stat.String()) } } ``` -------------------------------- ### gocyclo.Analyze Source: https://context7.com/fzipp/gocyclo/llms.txt Analyzes Go source files or directories recursively to calculate cyclomatic complexities, supporting regex-based file filtering. ```APIDOC ## gocyclo.Analyze ### Description Calculates cyclomatic complexities of functions and methods in Go source files or directories. It recursively scans directories and supports regex-based file filtering. ### Parameters - **paths** ([]string) - Required - A slice of file paths or directory paths to analyze. - **ignore** (*regexp.Regexp) - Optional - A regular expression to exclude specific files from the analysis. ### Response - **stats** (gocyclo.Stats) - A collection of function statistics including Complexity, PkgName, FuncName, and Pos. ``` -------------------------------- ### Show Average Complexity Source: https://context7.com/fzipp/gocyclo/llms.txt Display the average cyclomatic complexity across all analyzed functions. ```bash # Full format with label gocyclo -avg . # Output: Average: 2.72 # Short format without label gocyclo -avg-short . # Output: 2.72 ``` -------------------------------- ### Ignore Functions with gocyclo:ignore Directive Source: https://context7.com/fzipp/gocyclo/llms.txt Shows how to exclude individual functions and function literals from analysis using the `//gocyclo:ignore` directive. ```go package main // This function will be analyzed normally func normalFunction() { // complexity: 1 } //gocyclo:ignore func complexButIgnored() { // This function is skipped in analysis if true { for i := 0; i < 10; i++ { switch i { case 1, 2, 3: // lots of complexity... } } } } //gocyclo:ignore var ignoredFuncLiteral = func() { // Function literals can also be ignored } ``` -------------------------------- ### gocyclo.Complexity Source: https://context7.com/fzipp/gocyclo/llms.txt Calculates the cyclomatic complexity of a single function AST node. ```APIDOC ## gocyclo.Complexity ### Description Calculates the cyclomatic complexity of a single function AST node. Accepts either *ast.FuncDecl or *ast.FuncLit. ### Parameters - **node** (ast.Node) - Required - The AST node representing the function or function literal. ### Response - **complexity** (int) - The calculated cyclomatic complexity value. ``` -------------------------------- ### Ignore Functions with Directives Source: https://github.com/fzipp/gocyclo/blob/main/README.md Use the //gocyclo:ignore directive to exclude specific functions from complexity analysis. ```go //gocyclo:ignore func f1() { // ... } //gocyclo:ignore var f2 = func() { // ... } ``` -------------------------------- ### Show Top N Most Complex Functions Source: https://context7.com/fzipp/gocyclo/llms.txt Display only the top N most complex functions using the -top flag. ```bash gocyclo -top 10 src/ ``` -------------------------------- ### Calculate Average Complexity Source: https://context7.com/fzipp/gocyclo/llms.txt Calculates the mean complexity across all analyzed functions. ```go package main import ( "fmt" "github.com/fzipp/gocyclo" ) func main() { stats := gocyclo.Analyze([]string{"."}, nil) avg := stats.AverageComplexity() fmt.Printf("Average complexity: %.2f\n", avg) // Output: Average complexity: 2.72 } ``` -------------------------------- ### Calculate Complexity of AST Node Source: https://context7.com/fzipp/gocyclo/llms.txt Calculate the cyclomatic complexity of a single function AST node using gocyclo.Complexity. ```go package main import ( "fmt" "go/parser" "go/token" "github.com/fzipp/gocyclo" ) func main() { src := ` package example func complexFunc(x int) int { if x > 0 { for i := 0; i < x; i++ { if i%2 == 0 && i > 5 { return i } } } return 0 } ` fset := token.NewFileSet() f, _ := parser.ParseFile(fset, "example.go", src, 0) // Get the function declaration funcDecl := f.Decls[0] // Calculate complexity complexity := gocyclo.Complexity(funcDecl) fmt.Printf("Complexity: %d\n", complexity) // Output: Complexity: 4 // (1 base + 1 if + 1 for + 1 if + 1 && = 5, but nested if counts as 1) } ``` -------------------------------- ### Ignoring Functions Source: https://context7.com/fzipp/gocyclo/llms.txt Explains how to exclude specific functions from Gocyclo analysis using the `//gocyclo:ignore` directive. ```APIDOC ## Ignoring Functions ### Using `//gocyclo:ignore` Directive ### Description Individual functions can be excluded from analysis by adding the `//gocyclo:ignore` comment directive before their declaration. ### Usage Place `//gocyclo:ignore` on a line immediately preceding the function or variable declaration you wish to ignore. ### Example ```go // This function will be analyzed normally func normalFunction() { // complexity: 1 } //gocyclo:ignore func complexButIgnored() { // This function is skipped in analysis if true { for i := 0; i < 10; i++ { switch i { case 1, 2, 3: // lots of complexity... } } } } //gocyclo:ignore var ignoredFuncLiteral = func() { // Function literals can also be ignored } ``` ``` -------------------------------- ### Calculate Total Complexity Source: https://context7.com/fzipp/gocyclo/llms.txt Returns the sum of all cyclomatic complexities across analyzed functions. ```go package main import ( "fmt" "github.com/fzipp/gocyclo" ) func main() { stats := gocyclo.Analyze([]string{"./src"}, nil) total := stats.TotalComplexity() fmt.Printf("Total complexity: %d across %d functions\n", total, len(stats)) // Output: Total complexity: 156 across 42 functions } ``` -------------------------------- ### Ignore Files with Regex Source: https://context7.com/fzipp/gocyclo/llms.txt Exclude files matching a regular expression pattern. ```bash # Ignore test files, Godeps, and vendor directories gocyclo -top 20 -ignore "_test|Godeps|vendor/" . ``` -------------------------------- ### Filter by Complexity Threshold Source: https://context7.com/fzipp/gocyclo/llms.txt Show only functions with complexity greater than N. Returns exit code 1 if any functions exceed the threshold. ```bash # Show functions with complexity > 25 gocyclo -over 25 ./myproject # Useful in CI pipelines - fails if any function is too complex gocyclo -over 10 . || echo "Code too complex!" ``` -------------------------------- ### Stats.AverageComplexity Source: https://context7.com/fzipp/gocyclo/llms.txt Calculates and returns the average cyclomatic complexity across all analyzed functions. ```APIDOC ## Stats.AverageComplexity ### Description Returns the mean complexity across all analyzed functions. ### Method (Implicitly called on a `Stats` object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go stats := gocyclo.Analyze([]string{"."}, nil) avg := stats.AverageComplexity() ``` ### Response #### Success Response (200) - **float64**: The average cyclomatic complexity. #### Response Example ``` 2.72 ``` ``` -------------------------------- ### Stats.SortAndFilter Source: https://context7.com/fzipp/gocyclo/llms.txt Sorts and filters complexity statistics. It can sort by complexity in descending order and filter by a top N count and a minimum complexity threshold. ```APIDOC ## Stats.SortAndFilter ### Description Sorts stats by complexity in descending order and filters by top N and minimum threshold. ### Method (Implicitly called on a `Stats` object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go stats := gocyclo.Analyze([]string{"./src"}, nil) filtered := stats.SortAndFilter(5, 3) // Get top 5 functions with complexity > 3 ``` ### Response #### Success Response (200) - **[]Stat** (slice of Stat structs): A slice containing the filtered and sorted complexity statistics. #### Response Example ```go // Example output for each stat in the filtered slice: // {"Complexity": 5, "PkgName": "main", "FuncName": "myFunction", "Pos": "main.go:10:1"} ``` ``` -------------------------------- ### Stats.TotalComplexity Source: https://context7.com/fzipp/gocyclo/llms.txt Calculates and returns the sum of all cyclomatic complexities for the analyzed functions. ```APIDOC ## Stats.TotalComplexity ### Description Returns the sum of all cyclomatic complexities. ### Method (Implicitly called on a `Stats` object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go stats := gocyclo.Analyze([]string{"./src"}, nil) total := stats.TotalComplexity() ``` ### Response #### Success Response (200) - **int**: The total sum of cyclomatic complexities. #### Response Example ``` 156 ``` ``` -------------------------------- ### Stat Structure Source: https://context7.com/fzipp/gocyclo/llms.txt Details the fields available within the Stat struct, which represents the complexity information for a single function. ```APIDOC ## Stat Structure ### Description The Stat struct holds complexity information for a single function. ### Fields - **PkgName** (string): The name of the package the function belongs to. - **FuncName** (string): The name of the function. - **Complexity** (int): The cyclomatic complexity of the function. - **Pos** (string): The position of the function in the source code (file:line:column). ### String() Method - **String()** (string): Returns a formatted string representation of the Stat, typically in the format " ". ### Request Example ```go stats := gocyclo.Analyze([]string{"./src"}, nil) for _, stat := range stats { fmt.Printf("Package: %s\n", stat.PkgName) fmt.Printf("Function: %s\n", stat.FuncName) fmt.Printf("Complexity: %d\n", stat.Complexity) fmt.Printf("Position: %s\n", stat.Pos) fmt.Println(stat.String()) } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.