### Install Octocov using go install Source: https://github.com/k1low/octocov/blob/main/README.md Install Octocov directly using the Go toolchain. This requires Go to be installed on your system. ```bash $ go install github.com/k1LoW/octocov@latest ``` -------------------------------- ### Coverage Acceptable Conditions Examples Source: https://github.com/k1low/octocov/blob/main/_autodocs/08-expressions-acceptables.md Demonstrates various ways to define acceptable code coverage thresholds using simplified, comparison, and full expression syntaxes. Includes examples for simple thresholds, improvement requirements, preventing regression, and conditional logic based on environment variables. ```yaml coverage: acceptable: 75% # With improvement requirement coverage: acceptable: "current >= 70% && diff >= 2%" # Prevent regression coverage: acceptable: "current >= prev && diff >= -1%" # Conditional by branch coverage: acceptable: "env.GITHUB_REF == 'refs/heads/main' ? 85% : 70%" ``` -------------------------------- ### Code-to-Test Ratio Acceptable Conditions Examples Source: https://github.com/k1low/octocov/blob/main/_autodocs/08-expressions-acceptables.md Illustrates defining acceptable code-to-test ratios. Examples show minimum ratio requirements, allowing reductions on non-default branches, and requiring improvements. ```yaml codeToTestRatio: acceptable: 1:1.5 # Allow reduction on non-main branches codeToTestRatio: acceptable: | is_default_branch ? (current >= 1.5 && diff >= 0) : (current >= 1.0) # Require improvement codeToTestRatio: acceptable: "current > prev" ``` -------------------------------- ### Install Octocov using apk package Source: https://github.com/k1low/octocov/blob/main/README.md Install Octocov using an apk package. Ensure the OCTOCOV_VERSION environment variable is set. ```bash $ export OCTOCOV_VERSION=X.X.X $ curl -o octocov.apk -L https://github.com/k1LoW/octocov/releases/download/v$OCTOCOV_VERSION/octocov_$OCTOCOV_VERSION-1_amd64.apk $ apk add octocov.apk ``` -------------------------------- ### Example: Creating an S3 Datastore Instance Source: https://github.com/k1low/octocov/blob/main/_autodocs/04-datastore.md Demonstrates how to create a datastore instance for S3 using the New constructor function with a provided URL. Error handling is included. ```go ctx := context.Background() ds, err := datastore.New(ctx, "s3://my-bucket/reports") if err != nil { log.Fatal(err) } ``` -------------------------------- ### Test Execution Time Acceptable Conditions Examples Source: https://github.com/k1low/octocov/blob/main/_autodocs/08-expressions-acceptables.md Provides examples for setting acceptable test execution times. Covers maximum execution time, allowing a percentage of regression, and applying stricter limits on the main branch. ```yaml testExecutionTime: acceptable: 3min # Allow 10% regression testExecutionTime: acceptable: "current <= prev * 1.1" # Stricter on main branch testExecutionTime: acceptable: | is_default_branch ? (current <= 1min && diff <= 5sec) : (current <= 5min) ``` -------------------------------- ### Install Octocov using aqua Source: https://github.com/k1low/octocov/blob/main/README.md Install Octocov using the aqua package manager. This command fetches and installs the tool. ```bash $ aqua g -i k1LoW/octocov ``` -------------------------------- ### Custom Metric Acceptable Conditions Examples Source: https://github.com/k1low/octocov/blob/main/_autodocs/08-expressions-acceptables.md Shows example conditions for custom metrics, demonstrating checks on response time, memory usage, error rates, and throughput differences. ```json "acceptables": [ "current.response_time < 500", "current.memory_usage <= prev.memory_usage", "current.error_rate < 1.0", "diff.throughput >= 0" ] ``` -------------------------------- ### Install Octocov using Homebrew tap Source: https://github.com/k1low/octocov/blob/main/README.md Install Octocov using a Homebrew tap. This is a convenient method for macOS and Linux users. ```bash $ brew install k1LoW/tap/octocov ``` -------------------------------- ### Display Coverage Badges in README Source: https://github.com/k1low/octocov/blob/main/README.md Markdown example for displaying generated coverage badges. ```markdown # mytool ![coverage](docs/coverage.svg) ![coverage](docs/ratio.svg) ![coverage](docs/time.svg) ``` -------------------------------- ### Go Usage Example for Octocov GitHub Client Source: https://github.com/k1low/octocov/blob/main/_autodocs/09-github-integration.md Demonstrates how to initialize the Octocov GitHub client, fetch the default branch, post a comment on a pull request, retrieve job step durations, and push files using local Git. ```go package main import ( "context" "log" "github.com/k1LoW/octocov/gh" ) func main() { ctx := context.Background() // Create client ghClient, err := gh.New() if err != nil { log.Fatal(err) } // Get default branch branch, _ := ghClient.FetchDefaultBranch(ctx, "owner", "repo") log.Printf("Default branch: %s", branch) // Post comment id, _ := ghClient.PutComment( ctx, "owner", "repo", "123", "## Metrics\nCoverage: 85%", ) log.Printf("Comment posted: %s", id) // Get steps for timing steps, _ := ghClient.GetJobSteps(ctx, "owner", "repo") for _, step := range steps { duration := step.CompletedAt.Sub(step.StartedAt) log.Printf("%s: %v", step.Name, duration) } // Push files count, _ := gh.PushUsingLocalGit( ctx, "/repo", []string{"/repo/coverage.svg"}, "Update coverage", ) log.Printf("Pushed %d files", count) } ``` -------------------------------- ### Local File System Datastore Scheme Source: https://github.com/k1low/octocov/blob/main/README.md Use `local://` or `file://` schemes for local file system paths. Examples show how relative and absolute paths are resolved. ```text local://[path] ``` -------------------------------- ### Install Octocov using RPM package Source: https://github.com/k1low/octocov/blob/main/README.md Install Octocov using an RPM package. Ensure the OCTOCOV_VERSION environment variable is set. ```bash $ export OCTOCOV_VERSION=X.X.X $ yum install https://github.com/k1LoW/octocov/releases/download/v$OCTOCOV_VERSION/octocov_$OCTOCOV_VERSION-1_amd64.rpm ``` -------------------------------- ### Go Usage Example Source: https://github.com/k1low/octocov/blob/main/_autodocs/03-coverage.md Illustrates how to use the Octocov library in Go to parse coverage reports, normalize paths, and query coverage percentages. Ensure coverage files are present and correctly formatted. ```go package main import ( "log" "github.com/k1LoW/octocov/coverage" ) func main() { // Create and measure coverage cov := coverage.New() // Parse coverage file (auto-detect format) var err error *cov, _, err = coverage.ParseReport("coverage.out") if err != nil { log.Fatal(err) } // Normalize paths cov.NormalizePaths("/repo", fsFiles) // Query coverage fc, _ := cov.Files.FindByFile("cmd/main.go") percent := float64(fc.Covered) / float64(fc.Total) * 100 log.Printf("Coverage: %.1f%%", percent) // Remove block details before storage cov.DeleteBlockCoverages() } ``` -------------------------------- ### Install Octocov using deb package Source: https://github.com/k1low/octocov/blob/main/README.md Install Octocov using a .deb package. Ensure the OCTOCOV_VERSION environment variable is set. ```bash $ export OCTOCOV_VERSION=X.X.X $ curl -o octocov.deb -L https://github.com/k1LoW/octocov/releases/download/v$OCTOCOV_VERSION/octocov_$OCTOCOV_VERSION-1_amd64.deb $ dpkg -i octocov.deb ``` -------------------------------- ### Octocov CLI Usage Locally Source: https://github.com/k1low/octocov/blob/main/_autodocs/README.md Examples of common Octocov CLI commands for local use, including listing files, viewing details, comparing reports, and initializing configuration. ```bash octocov ls-files # List files in coverage octocov view cmd/main.go # View file details octocov diff old.json new.json # Compare reports octocov init # Create .octocov.yml ``` -------------------------------- ### Check Code to Test Ratio Source: https://github.com/k1low/octocov/blob/main/README.md Example of the command output when the code to test ratio condition is not met. ```console $ octocov Error: code to test ratio is 1:1.1, the condition in the `codeToTestRatio.acceptable:` section is not met (`1:1.2`) ``` -------------------------------- ### Get Configuration Working Directory Source: https://github.com/k1low/octocov/blob/main/_autodocs/01-config.md Retrieves the absolute path to the working directory from which the configuration was loaded. This is an alias for the Root() method. ```go func (c *Config) Wd() string {} ``` -------------------------------- ### Path Normalization Example Source: https://github.com/k1low/octocov/blob/main/_autodocs/03-coverage.md Demonstrates how Octocov normalizes file paths in coverage reports based on filesystem files. Useful for aligning report paths with actual project structure. ```text github.com/owner/repo/cmd/main.go (Go format) src/utils/file.ts (LCOV format) ``` ```text /repo/cmd/main.go /repo/src/utils/file.ts ``` ```text File="github.com/owner/repo/cmd/main.go" NormalizedPath="cmd/main.go" File="src/utils/file.ts" NormalizedPath="src/utils/file.ts" ``` -------------------------------- ### Octocov Programmatic Usage in Go Source: https://github.com/k1low/octocov/blob/main/_autodocs/README.md Example of using Octocov as a Go library to load configuration, create a report, measure metrics, check acceptability, and output results. ```go import ( "github.com/k1LoW/octocov/config" "github.com/k1LoW/octocov/report" ) // Load config cfg := config.New() cfg.Load(".octocov.yml") cfg.Build() // Create report r, err := report.New(cfg.Repository) // Measure metrics r.MeasureCoverage(cfg.Coverage.Paths, cfg.Coverage.Exclude) r.MeasureCodeToTestRatio(".", cfg.CodeToTestRatio.Code, cfg.CodeToTestRatio.Test) // Check acceptable if err := cfg.Acceptable(r, nil); err != nil { log.Fatal(err) } // Output r.Out(os.Stdout) ``` -------------------------------- ### Go: Generate and Output Octocov Report Source: https://github.com/k1low/octocov/blob/main/_autodocs/02-report.md This Go code snippet demonstrates the complete workflow for using the Octocov library. It includes creating a new report, measuring coverage and code-to-test ratio, attempting to measure test execution time, validating the report, and outputting it to stdout. Ensure you have a 'coverage.out' file and Go source files in the current directory for this example to run successfully. ```go package main import ( "context" "log" "github.com/k1LoW/octocov/report" "golang.org/x/text/language" ) func main() { // Create report r, err := report.New("owner/myrepo", report.Locale(language.English)) if err != nil { log.Fatal(err) } // Measure metrics if err := r.MeasureCoverage([]string{"coverage.out"}, nil); err != nil { log.Fatal(err) } if err := r.MeasureCodeToTestRatio(".", []string{"**/*.go", "!**/*_test.go"}, []string{"**/*_test.go"}); err != nil { log.Fatal(err) } if err := r.MeasureTestExecutionTime(context.Background(), nil); err != nil { log.Printf("Test time not available: %v", err) } // Validate if err := r.Validate(); err != nil { log.Fatal(err) } // Output if err := r.Out(os.Stdout); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Create New Coverage Structure Source: https://github.com/k1low/octocov/blob/main/_autodocs/03-coverage.md Use this function to initialize an empty Coverage structure. It's the starting point for building coverage reports. ```go func New() *Coverage ``` ```go c := coverage.New() c.Type = coverage.TypeStmt c.Format = "Custom" ``` -------------------------------- ### Valid Type Coercion Examples Source: https://github.com/k1low/octocov/blob/main/_autodocs/08-expressions-acceptables.md Demonstrates how Octocov's expression engine handles type coercion for comparisons and parsing. ```go // These are valid "60" >= 60.0 // string "60" coerced to float current >= 60% // "60%" parsed as 60.0 1:1.5 // "1:1.5" parsed as 1.5 ``` -------------------------------- ### Octocov YAML Configuration Source: https://github.com/k1low/octocov/blob/main/_autodocs/README.md Example of the .octocov.yml configuration file, specifying repository, coverage, code-to-test ratio, test execution time, report storage, and PR comments. ```yaml repository: owner/repo # Required for CI coverage: # Code coverage paths: [coverage.out] acceptable: 80% badge: path: docs/coverage.svg codeToTestRatio: # Code-to-test ratio code: ['**/*.go', '!**/*_test.go'] test: ['**/*_test.go'] acceptable: 1:1.2 testExecutionTime: # Test timing acceptable: 2min report: # Store reports datastores: - s3://my-bucket/reports comment: # PR comments if: is_pull_request ``` -------------------------------- ### Config Initialization Source: https://github.com/k1low/octocov/blob/main/_autodocs/01-config.md Demonstrates how to create a new configuration instance and load settings from a YAML file. ```APIDOC ## New() ### Description Create a new empty Config instance. Working directory is automatically set from current directory. ### Returns `*Config` - New configuration instance ### Example ```go c := config.New() if err := c.Load(".octocov.yml"); err != nil { log.Fatal(err) } c.Build() ``` ``` -------------------------------- ### Initialize Multiple Datastores Source: https://github.com/k1low/octocov/blob/main/_autodocs/04-datastore.md Demonstrates iterating through a list of datastore URLs to initialize and use multiple datastores for storing reports. Useful for distributed or multi-backend storage strategies. ```go datastores := []string{ "s3://my-bucket/reports", "github://owner/central-repo/reports", } for _, url := range datastores { ds, _ := datastore.New(ctx, url) ds.StoreReport(ctx, r) } ``` -------------------------------- ### Create New Config Instance Source: https://github.com/k1low/octocov/blob/main/_autodocs/01-config.md Initializes a new, empty Config instance. The working directory is automatically set to the current directory. Load configuration from a file after creating the instance. ```go c := config.New() if err := c.Load(".octocov.yml"); err != nil { log.Fatal(err) } c.Build() ``` -------------------------------- ### Get GitHub Actions Job Steps Source: https://github.com/k1low/octocov/blob/main/_autodocs/09-github-integration.md Retrieves GitHub Actions job steps for test execution time measurement. Requires running within GitHub Actions with the GITHUB_ACTIONS environment variable set. ```go func (g *Gh) GetJobSteps(ctx context.Context, owner, repo string) ([]Step, error) ``` ```go type Step struct { Name string // Step name Number int // Step number Status string // success, failure, skipped, etc. StartedAt time.Time // Step start time CompletedAt time.Time // Step completion time } ``` ```go steps, _ := gh.GetJobSteps(ctx, "owner", "repo") for _, step := range steps { duration := step.CompletedAt.Sub(step.StartedAt) fmt.Printf("%s: %v\n", step.Name, duration) } ``` -------------------------------- ### Using Octocov as a Library Source: https://github.com/k1low/octocov/blob/main/_autodocs/10-module-index.md Demonstrates how to load configuration, create a report, measure coverage, and access coverage percentage when using octocov as a library in a Go application. ```go package main import ( "context" "github.com/k1LoW/octocov/config" "github.com/k1LoW/octocov/report" ) func main() { // Load config cfg := config.New() cfg.Load(".octocov.yml") cfg.Build() // Create and measure report r, _ := report.New(cfg.Repository) r.MeasureCoverage(cfg.Coverage.Paths, cfg.Coverage.Exclude) // Use report if r.IsMeasuredCoverage() { println(r.CoveragePercent()) } } ``` -------------------------------- ### Provide Report Object for Datastore Initialization Source: https://github.com/k1low/octocov/blob/main/_autodocs/04-datastore.md Use the `Report` hint function to provide the current report object during datastore initialization, which is utilized by certain backends. ```go ds, _ := datastore.New(ctx, "artifact://owner/repo", datastore.Report(r)) ``` -------------------------------- ### Getting Color Codes for Metrics Source: https://github.com/k1low/octocov/blob/main/_autodocs/01-config.md Provides methods to get color codes for coverage percentage and code-to-test ratio, useful for badges. ```APIDOC ## CoverageColor(percent float64) string ### Description Get color code for coverage percentage (used in badges). ### Parameters #### Path Parameters - **percent** (float64) - Required - Coverage percentage 0-100 ### Returns `string` - Hex color code (#RRGGBB) ## CodeToTestRatioColor(ratio float64) string ### Description Get color code for code-to-test ratio (used in badges). ### Parameters #### Path Parameters - **ratio** (float64) - Required - Test-to-code ratio ### Returns `string` - Hex color code ``` -------------------------------- ### Datastore Constructor Function Source: https://github.com/k1low/octocov/blob/main/_autodocs/04-datastore.md The New function creates a datastore instance from a URL, automatically detecting the type and initializing the appropriate client. Optional configuration hints can be provided. ```go func New(ctx context.Context, u string, hints ...HintFunc) (Datastore, error) ``` -------------------------------- ### Conditional Report Storage Example Source: https://github.com/k1low/octocov/blob/main/README.md Example of configuring conditional report storage based on environment variables using the `report.if:` directive. This snippet specifies that reports should only be stored if the GitHub reference is the main branch. ```yaml # .octocov.yml report: if: env.GITHUB_REF == 'refs/heads/main' datastores: - github://owner/coverages/reports ``` -------------------------------- ### Build Configuration Source: https://github.com/k1low/octocov/blob/main/_autodocs/01-config.md Validates and prepares the configuration after it has been loaded. This method must be called after Load() and before using the configuration. ```go func (c *Config) Build() {} ``` -------------------------------- ### Bytes() []byte Source: https://github.com/k1low/octocov/blob/main/_autodocs/02-report.md Get report as pretty-printed JSON bytes. ```APIDOC ## Bytes() []byte ### Description Get report as pretty-printed JSON bytes. ### Returns - []byte - Pretty-printed JSON ``` -------------------------------- ### Recommended Project Structure Source: https://github.com/k1low/octocov/blob/main/_autodocs/10-module-index.md Illustrates the recommended directory structure for a project using octocov, including placement for configuration and internal/pkg directories. ```text my-app/ ├─ main.go # Entry point ├─ go.mod ├─ internal/ │ ├─ metrics/ │ │ └─ reporter.go # Uses report package │ └─ ci/ │ └─ github.go # Uses gh package ├─ pkg/ │ └─ storage/ │ └─ store.go # Uses datastore package └─ config/ └─ octocov/ └─ .octocov.yml # Configuration file ``` -------------------------------- ### String() string Source: https://github.com/k1low/octocov/blob/main/_autodocs/02-report.md Get report as a pretty-printed JSON string. ```APIDOC ## String() string ### Description Get report as a pretty-printed JSON string. ### Returns - string - Pretty-printed JSON ``` -------------------------------- ### Create and Customize a Badge Source: https://github.com/k1low/octocov/blob/main/_autodocs/05-badge-ratio-central.md Demonstrates creating a new badge with a label and message, setting a custom message color, and adding an icon from a file. The badge is then rendered to an SVG file. ```go b := badge.New("coverage", "85.3%") b.MessageColor = "#97CA00" // green b.AddIconFile("octocov.png") f, _ := os.Create("docs/coverage.svg") defer f.Close() b.Render(f) ``` -------------------------------- ### TestExecutionTime Configuration Source: https://github.com/k1low/octocov/blob/main/_autodocs/01-config.md Sets up the measurement of test execution time, including badge generation, acceptable time limits, and specific steps to monitor. ```go type TestExecutionTime struct { Badge TestExecutionTimeBadge Acceptable string Steps []string If string } ``` -------------------------------- ### Table() string Source: https://github.com/k1low/octocov/blob/main/_autodocs/02-report.md Get report as an ASCII table for terminal output. ```APIDOC ## Table() string ### Description Get report as an ASCII table for terminal output. ### Returns - string - Formatted table ``` -------------------------------- ### Create a New Badge Source: https://github.com/k1low/octocov/blob/main/_autodocs/05-badge-ratio-central.md Illustrates the basic creation of a badge object using the New constructor, specifying the label and message. ```go b := badge.New("coverage", "85.3%") b.MessageColor = "#97CA00" // green ``` -------------------------------- ### Get Coverage Percentage Source: https://github.com/k1low/octocov/blob/main/_autodocs/02-report.md Retrieves the coverage percentage as a float64. Returns 0 if coverage was not measured. ```Go func (r *Report) CoveragePercent() float64 ``` -------------------------------- ### Set Coverage Measurement Condition Source: https://github.com/k1low/octocov/blob/main/README.md Defines the condition under which code coverage should be measured. For example, 'is_default_branch'. ```yaml coverage: if: is_default_branch ``` -------------------------------- ### Store a Report to Datastore Source: https://github.com/k1low/octocov/blob/main/_autodocs/04-datastore.md Initializes a new datastore connection and stores a generated report. Ensure the datastore URL is correctly formatted. ```go ctx := context.Background() ds, err := datastore.New(ctx, "s3://my-bucket/reports") if err != nil { log.Fatal(err) } r, _ := report.New("owner/repo") r.MeasureCoverage([]string{"coverage.out"}, nil) if err := ds.StoreReport(ctx, r); err != nil { log.Fatal(err) } ``` -------------------------------- ### Octocov CLI Error Output Source: https://github.com/k1low/octocov/blob/main/README.md Example of an error message when custom metrics do not meet acceptable conditions. ```console $ octocov Error: custom metrics "performance_metrics" not acceptable condition (`current.response_time < 300`) ``` -------------------------------- ### Set Working Directory Root for Local Datastore Source: https://github.com/k1low/octocov/blob/main/_autodocs/04-datastore.md Use the `Root` hint function to specify the working directory for resolving relative paths when using the `local://` datastore. ```go ds, _ := datastore.New(ctx, "local://reports", datastore.Root(c.Root())) ``` -------------------------------- ### Check Test Execution Time Source: https://github.com/k1low/octocov/blob/main/README.md Example of the command output when the test execution time condition is not met. ```console $ octocov Error: test execution time is 1m15s, the condition in the `testExecutionTime.acceptable:` section is not met (`1 min`) ``` -------------------------------- ### Get Code-to-Test Ratio Source: https://github.com/k1low/octocov/blob/main/_autodocs/02-report.md Retrieves the code-to-test ratio (test lines / code lines). Returns 0 if not measured. ```Go func (r *Report) CodeToTestRatioRatio() float64 ``` -------------------------------- ### Set Code to Test Ratio Measurement Condition Source: https://github.com/k1low/octocov/blob/main/README.md Defines the condition under which the code-to-test ratio should be measured. For example, 'is_default_branch'. ```yaml codeToTestRatio: if: is_default_branch ``` -------------------------------- ### Get Report Title Source: https://github.com/k1low/octocov/blob/main/_autodocs/02-report.md Retrieves the display title for the report. This may include the project key if it's part of a monorepo. ```Go func (r *Report) Title() string ``` -------------------------------- ### New Datastore Constructor Source: https://github.com/k1low/octocov/blob/main/_autodocs/04-datastore.md Creates a new datastore instance by parsing a URL. The constructor auto-detects the datastore type and initializes the appropriate client based on the URL scheme. ```APIDOC ## New Datastore Constructor ### Description Create a datastore instance from a URL. Auto-detects type and initializes with the appropriate client. Supports various URL schemes for different backends. ### Method Signature `New(ctx context.Context, u string, hints ...HintFunc) (Datastore, error)` ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Parameters - **ctx** (`context.Context`) - Required - Context for API operations. - **u** (`string`) - Required - Datastore URL. Supported schemes include `github://`, `artifact://`, `s3://`, `gs://`, `bq://`, `mackerel://` or `mkr://`, and `local://` or `file://`. - **hints** (`...HintFunc`) - Optional - Optional configuration hints for the datastore. ### Returns - `(Datastore, error)` - An initialized datastore instance or an error if initialization fails. ### URL Schemes - **github://** - Format: `owner/repo[@branch]/prefix` - Example: `github://owner/coverage/reports` - **artifact://** - Format: `owner/repo[/artifactName]` - Example: `artifact://owner/repo` - **s3://** - Format: `bucket/prefix` - Example: `s3://my-bucket/reports` - **gs://** - Format: `bucket/prefix` - Example: `gs://my-bucket/reports` - **bq://** - Format: `project/dataset/table` - Example: `bq://my-project/my-dataset/reports` - **mackerel://** or **mkr://** - Format: `service-name` - Example: `mackerel://my-service` - **local://** or **file://** - Format: `path` - Example: `local://./reports` ### Example ```go ctx := context.Background() ds, err := datastore.New(ctx, "s3://my-bucket/reports") if err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### New Ratio Constructor Source: https://github.com/k1low/octocov/blob/main/_autodocs/05-badge-ratio-central.md Creates and returns an empty Ratio object. ```go func New() *Ratio ``` -------------------------------- ### Set Test Execution Time Measurement Condition Source: https://github.com/k1low/octocov/blob/main/README.md Defines the condition under which test execution time should be measured. For example, 'is_pull_request'. ```yaml testExecutionTime: if: is_pull_request ``` -------------------------------- ### Get Count of Measured Metrics Source: https://github.com/k1low/octocov/blob/main/_autodocs/02-report.md Returns the number of distinct metric types (coverage, ratio, execution time) that have been measured for this report. ```Go func (r *Report) CountMeasured() int ``` -------------------------------- ### Load Configuration from YAML Source: https://github.com/k1low/octocov/blob/main/_autodocs/01-config.md Loads configuration settings from a YAML file. If no path is provided, it searches default locations in the current and parent directories. Ensure this is called before building or accessing configuration. ```go c := config.New() err := c.Load("") // Auto-detect .octocov.yml ``` -------------------------------- ### Get Report Key for Monorepo Source: https://github.com/k1low/octocov/blob/main/_autodocs/02-report.md Retrieves the unique key identifying a project within a monorepo. Returns an empty string if the report is not from a monorepo. ```Go func (r *Report) Key() string ``` -------------------------------- ### Building Configuration Source: https://github.com/k1low/octocov/blob/main/_autodocs/01-config.md Describes the process of validating and preparing the configuration after it has been loaded. ```APIDOC ## Build() ### Description Validate and prepare configuration after loading. Must be called after Load() and before accessing configuration. ``` -------------------------------- ### Get Code-to-Test Ratio Color Source: https://github.com/k1low/octocov/blob/main/_autodocs/01-config.md Returns the hex color code for a given code-to-test ratio, used for generating badges. Input is the ratio value. ```go func (c *Config) CodeToTestRatioColor(ratio float64) string {} ``` -------------------------------- ### Initialize Octocov Configuration Source: https://github.com/k1low/octocov/blob/main/README.md Generate the default .octocov.yml configuration file. This file is used to customize Octocov's behavior. ```bash octocov init ``` -------------------------------- ### Get Report as JSON String Source: https://github.com/k1low/octocov/blob/main/_autodocs/02-report.md Use the String() method to retrieve the report data formatted as a pretty-printed JSON string. This is useful for logging or simple display. ```go func (r *Report) String() string ``` -------------------------------- ### Get Effective File Path Source: https://github.com/k1low/octocov/blob/main/_autodocs/03-coverage.md Retrieves the normalized path if it exists; otherwise, it returns the original path. This is useful for consistent path handling in matching and display. ```go func (fc *FileCoverage) EffectivePath() string ``` -------------------------------- ### Check if Configuration is Loaded Source: https://github.com/k1low/octocov/blob/main/_autodocs/01-config.md Determines if the configuration has been successfully loaded from a file. Returns true if loaded, false otherwise. ```go func (c *Config) Loaded() bool {} ``` -------------------------------- ### Octocov Environment Variables Source: https://github.com/k1low/octocov/blob/main/_autodocs/README.md Examples of environment variables used to override Octocov configuration, including GitHub token, repository, AWS credentials, and debug logging. ```bash OCTOCOV_GITHUB_TOKEN=ghp_... OCTOCOV_GITHUB_REPOSITORY=owner/repo OCTOCOV_AWS_ACCESS_KEY_ID=AKIA... DEBUG=1 # Enable debug logging ``` -------------------------------- ### New Source: https://github.com/k1low/octocov/blob/main/_autodocs/05-badge-ratio-central.md Creates a new Central aggregator with the provided configuration. This is the entry point for setting up the central aggregation process. ```APIDOC ## New ### Description Creates a new Central aggregator with the provided configuration. This is the entry point for setting up the central aggregation process. ### Signature ```go func New(c *Config) *Central ``` ### Parameters #### Parameters - **c** (*Config) - Configuration for the Central aggregator. ``` -------------------------------- ### Get Report as ASCII Table Source: https://github.com/k1low/octocov/blob/main/_autodocs/02-report.md Use the Table() method to generate a formatted ASCII table representation of the report. This is ideal for displaying report summaries directly in a terminal. ```go func (r *Report) Table() string ``` -------------------------------- ### Programmatic Usage (Go Library) Source: https://github.com/k1low/octocov/blob/main/_autodocs/README.md This section demonstrates how to use Octocov as a Go library to load configuration, create reports, measure various code metrics, check acceptable thresholds, and output the results. ```APIDOC ## Programmatic Usage (Go Library) This section demonstrates how to use Octocov as a Go library to load configuration, create reports, measure various code metrics, check acceptable thresholds, and output the results. ### Import necessary packages ```go import ( "github.com/k1LoW/octocov/config" "github.com/k1LoW/octocov/report" ) ``` ### Load and build configuration ```go // Load config cfg := config.New() cfg.Load(".octocov.yml") cfg.Build() ``` ### Create a new report ```go // Create report r, err := report.New(cfg.Repository) ``` ### Measure metrics ```go // Measure metrics r.MeasureCoverage(cfg.Coverage.Paths, cfg.Coverage.Exclude) r.MeasureCodeToTestRatio(".", cfg.CodeToTestRatio.Code, cfg.CodeToTestRatio.Test) ``` ### Check acceptable thresholds ```go // Check acceptable if err := cfg.Acceptable(r, nil); err != nil { log.Fatal(err) } ``` ### Output the report ```go // Output r.Out(os.Stdout) ``` ``` -------------------------------- ### Get Coverage Percentage Color Source: https://github.com/k1low/octocov/blob/main/_autodocs/01-config.md Returns the hex color code corresponding to a given coverage percentage, typically used for generating badges. Input should be between 0 and 100. ```go func (c *Config) CoverageColor(percent float64) string {} ``` -------------------------------- ### GitHub Actions Workflow Permissions Source: https://github.com/k1low/octocov/blob/main/_autodocs/09-github-integration.md Example of setting necessary permissions in a GitHub Actions workflow file for Octocov to perform comment operations and manage job steps/artifacts. ```yaml permissions: contents: read pull-requests: write actions: read ``` -------------------------------- ### New Report Constructor Function Source: https://github.com/k1low/octocov/blob/main/_autodocs/02-report.md Creates a new Report instance, automatically detecting Git information from environment variables or git commands. Use this to initialize a report with optional configurations like locale. ```go func New(ownerrepo string, opts ...Option) (*Report, error) ``` ```go r, err := report.New("owner/repo", report.Locale(language.English)) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Check Diff Configuration Readiness Source: https://github.com/k1low/octocov/blob/main/_autodocs/01-config.md Validates if the diff configuration is ready and all specified conditions are met. Returns an error if validation fails. ```go func (c *Config) DiffConfigReady() error {} ``` -------------------------------- ### Get Report as JSON Bytes Source: https://github.com/k1low/octocov/blob/main/_autodocs/02-report.md Use the Bytes() method to obtain the report data as a byte slice, formatted as pretty-printed JSON. This is suitable for network transmission or binary storage. ```go func (r *Report) Bytes() []byte ``` -------------------------------- ### Measure and Comment with GitHub Actions Source: https://github.com/k1low/octocov/blob/main/_autodocs/06-cli-commands.md Run Go tests to generate coverage data and then execute the octocov command to perform the full workflow: measure, generate a badge, add a comment to the pull request, and store the report. ```bash go test ./... -coverprofile=coverage.out octocov # Runs full flow: measure, badge, comment, store ``` -------------------------------- ### Loading Configuration Source: https://github.com/k1low/octocov/blob/main/_autodocs/01-config.md Explains how to load Octocov configuration from a specified YAML file path. ```APIDOC ## Load(path string) error ### Description Load configuration from YAML file. If path is empty, searches default paths in current and parent directories. ### Parameters #### Path Parameters - **path** (string) - Required - YAML file path, or empty to auto-detect ### Returns `error` - Parse or I/O error, nil on success ### Example ```go c := config.New() err := c.Load("") // Auto-detect .octocov.yml ``` ``` -------------------------------- ### Central Repository Datastore Configuration Source: https://github.com/k1low/octocov/blob/main/README.md Configure Octocov's central mode to use a GitHub repository as a datastore. This setup is used when the central repository itself serves as the datastore for other reports. ```yaml # .octocov.yml for central repo central: reports: datastores: - github://owner/central-repo/reports push: ``` -------------------------------- ### Define Per-File Coverage Metrics Source: https://github.com/k1low/octocov/blob/main/_autodocs/07-types.md Details coverage metrics for individual files, including the metric type, original and normalized paths, total and covered units, and optional line-level block coverage. ```go type FileCoverage struct { Type Type File string NormalizedPath string Total int Covered int Blocks BlockCoverages cache map[int]BlockCoverages // private } ``` -------------------------------- ### Render Badge to Writer Source: https://github.com/k1low/octocov/blob/main/_autodocs/05-badge-ratio-central.md Shows how to render a configured badge object into an SVG format and write it to a specified output writer, such as a file. ```go f, _ := os.Create("coverage.svg") defer f.Close() b.Render(f) ``` -------------------------------- ### Expression Language Configuration Source: https://github.com/k1low/octocov/blob/main/_autodocs/README.md Example of using the expr-lang/expr for dynamic conditions in Octocov configuration. This snippet shows how to set coverage thresholds based on pull request status and environment variables. ```yaml coverage: if: is_pull_request && !is_draft && env.GITHUB_REF == 'refs/heads/main' acceptable: "is_default_branch ? (current >= 85) : (current >= 70)" ``` -------------------------------- ### Compare Two Coverage Reports Source: https://github.com/k1low/octocov/blob/main/_autodocs/06-cli-commands.md Compares two coverage reports and displays the differences. Reports can be local files or S3 URLs. The --config option can be used for datastore credentials. ```bash octocov diff coverage.old.json coverage.new.json ``` ```bash octocov diff s3://bucket/owner/repo/report.json ./coverage.json ``` -------------------------------- ### Merge Reports from GitHub Actions Jobs Source: https://github.com/k1low/octocov/blob/main/README.md Example GitHub Actions workflow to merge coverage reports from multiple jobs. Upload coverage artifacts from test jobs and use octocov-action for aggregation. ```yaml # .github/workflows/ci.yml name: merge coverages from multiple jobs on: push: branches: - main - master pull_request: jobs: test: strategy: fail-fast: true matrix: shard: [1, 2, 3] runs-on: ubuntu-latest permissions: contents: read # to checkout steps: - uses: actions/checkout@v4 - run: YOUR TEST HERE - name: Upload coverage to workspace uses: actions/upload-artifact@v4 with: path: lcov.info # adjust this path to your coverage file name: octocov-${{ matrix.shard }} if-no-files-found: error coverage-aggregation: runs-on: ubuntu-latest permissions: contents: read # to checkout pull-requests: write # for octocov to post comments actions: read # for octocov to parse test execution time needs: - test steps: - uses: actions/checkout@v4 - uses: actions/download-artifact@v5 with: pattern: octocov-* - uses: k1LoW/octocov-action@v1 ``` -------------------------------- ### List Files with Coverage Metrics Source: https://github.com/k1low/octocov/blob/main/_autodocs/06-cli-commands.md Lists files tracked in the coverage report along with their per-file metrics. Use --report to specify the coverage report file. ```bash octocov ls-files ``` ```bash octocov ls-files --report coverage.out ``` -------------------------------- ### New Ratio Constructor Source: https://github.com/k1low/octocov/blob/main/_autodocs/05-badge-ratio-central.md Creates and returns a new, empty Ratio object. ```APIDOC ## New() ### Description Creates an empty Ratio. ### Returns - `*Ratio`: A pointer to a new Ratio object. ``` -------------------------------- ### Central Repository Artifacts Datastore Configuration Source: https://github.com/k1low/octocov/blob/main/README.md Configure Octocov's central mode to use GitHub Actions Artifacts from other repositories as datastores. This setup is typically used for aggregating reports from multiple sources. ```yaml # .octocov.yml for central repo central: reports: datastores: - artifact://owner/repo - artifact://owner/other-repo - artifact://owner/another-repo [...] push: ``` -------------------------------- ### Configure S3 Bucket as Datastore Source: https://github.com/k1low/octocov/blob/main/README.md Use an S3 bucket as a datastore for reports. Badge generation should be performed via on.schedule. Requires AWS credentials. ```yaml # .octocov.yml report: datastores: - s3://my-s3-bucket/reports ``` ```yaml # .octocov.yml for central repo central: reports: datastores: - s3://my-s3-bucket/reports push: ``` -------------------------------- ### Central Mode Datastore Configuration Source: https://github.com/k1low/octocov/blob/main/_autodocs/04-datastore.md Configure Octocov in central mode to use S3 for reports and Google Cloud Storage for badges. This setup defines the sources and destinations for collected reports and generated badge SVGs. ```yaml central: reports: datastores: - s3://source-bucket/reports badges: datastores: - gs://badge-bucket/badges ``` -------------------------------- ### Check Code-to-Test Ratio Configuration Readiness Source: https://github.com/k1low/octocov/blob/main/_autodocs/01-config.md Validates if the code-to-test ratio configuration is complete and valid. Returns an error if validation fails. ```go func (c *Config) CodeToTestRatioConfigReady() error {} ``` -------------------------------- ### Central Mode Configuration Source: https://github.com/k1low/octocov/blob/main/_autodocs/05-badge-ratio-central.md Configure Octocov to run in central mode by specifying the root directory, report datastores (S3, GitHub Artifacts), and badge datastores (local). This setup collects reports, generates badges, and updates README.md. ```yaml # .octocov.yml for central repository central: root: . reports: datastores: - s3://reports-bucket/reports - artifact://owner/repo1 - artifact://owner/repo2 badges: datastores: - local://badges push: ``` -------------------------------- ### Coverage Configuration Source: https://github.com/k1low/octocov/blob/main/_autodocs/01-config.md Defines options for coverage measurement, including paths, exclusions, badges, and acceptance conditions. ```go type Coverage struct { Path string Paths []string Exclude []string Badge CoverageBadge Acceptable string If string } ``` -------------------------------- ### New() *Coverage Source: https://github.com/k1low/octocov/blob/main/_autodocs/03-coverage.md Creates an empty Coverage structure. This is the entry point for initializing coverage data. ```APIDOC ## New() *Coverage ### Description Create empty Coverage structure. ### Returns `*Coverage` ### Example ```go c := coverage.New() c.Type = coverage.TypeStmt c.Format = "Custom" ``` ``` -------------------------------- ### Configuration Condition Checking Source: https://github.com/k1low/octocov/blob/main/_autodocs/07-types.md Verifies if the coverage acceptable condition is configured. ```go if c.Coverage != nil && c.Coverage.Acceptable != "" { // Acceptable condition configured } ``` -------------------------------- ### Create New Gh Client Source: https://github.com/k1low/octocov/blob/main/_autodocs/09-github-integration.md Initializes a GitHub API client using auto-detected credentials. It attempts to use GITHUB_TOKEN, OCTOCOV_GITHUB_TOKEN, or GitHub CLI token. API endpoints default to GitHub's public API unless GITHUB_API_URL or OCTOCOV_GITHUB_API_URL are set. ```go func New() (*Gh, error) ``` ```go gh, err := gh.New() if err != nil { log.Fatal(err) } ``` -------------------------------- ### Migrate BigQuery Table Command Source: https://github.com/k1low/octocov/blob/main/README.md Command to execute for creating a BigQuery table if it doesn't exist. Requires `bigquery.datasets.create` permission. ```bash $ octocov migrate-bq-table ``` -------------------------------- ### Datastore Interface Methods Source: https://github.com/k1low/octocov/blob/main/_autodocs/04-datastore.md The core interface for all datastores includes methods for writing raw bytes, storing structured reports, and accessing the underlying filesystem. ```APIDOC ## Datastore Interface Methods ### Description Core interface all datastores implement. Provides methods for writing raw bytes to a path, storing structured reports (potentially compressed), and obtaining a filesystem interface for reading. ### Methods - **Put** (`ctx context.Context`, `path string`, `content []byte`) `error` Write raw bytes to the specified path. - **StoreReport** (`ctx context.Context`, `r *report.Report`) `error` Store a structured report. This operation may involve compression. - **FS** (`ctx context.Context`) `fs.FS, error` Get the filesystem interface for reading data from the datastore. ``` -------------------------------- ### Configure Datastores for Badges Source: https://github.com/k1low/octocov/blob/main/README.md Specify datastore paths (URLs) where badges are generated. Defaults to `local://badges`. ```yaml central: badges: datastores: - local://badges - s3://my-s3-buckets/badges ``` -------------------------------- ### Octocov CLI: List Files Source: https://github.com/k1low/octocov/blob/main/README.md List files that Octocov will process. This command is useful for verifying configuration. ```bash octocov ls-files ``` -------------------------------- ### Run Go Tests with Coverage Output Source: https://github.com/k1low/octocov/blob/main/README.md Execute Go tests and generate a coverage profile. This is a prerequisite for using Octocov to analyze coverage. ```bash go test ./... -coverprofile=coverage.out ``` -------------------------------- ### View Local Code Metrics Source: https://github.com/k1low/octocov/blob/main/_autodocs/06-cli-commands.md After running Go tests, use octocov to list all files included in the coverage report or to view detailed metrics for a specific file. ```bash go test ./... -coverprofile=coverage.out octocov ls-files # List all files octocov view cmd/main.go # Details for one file ``` -------------------------------- ### Check Comment Configuration Readiness Source: https://github.com/k1low/octocov/blob/main/_autodocs/01-config.md Validates if the comment configuration is ready and all specified conditions are met. Returns an error if validation fails. ```go func (c *Config) CommentConfigReady() error {} ``` -------------------------------- ### New Central Constructor Source: https://github.com/k1low/octocov/blob/main/_autodocs/05-badge-ratio-central.md Creates a new Central aggregator instance with the provided configuration. ```go func New(c *Config) *Central ``` -------------------------------- ### Mackerel Datastore Scheme Source: https://github.com/k1low/octocov/blob/main/README.md Use `mackerel://` or `mkr://` schemes for Mackerel. Requires `read` and `write` permissions. Set the `MACKEREL_API_KEY` environment variable. ```text mackerel://[Service Name] ``` -------------------------------- ### Configure BigQuery Table as Datastore Source: https://github.com/k1low/octocov/blob/main/README.md Use a BigQuery table as a datastore for reports. Badge generation should be performed via on.schedule. Requires Google Cloud credentials. ```yaml # .octocov.yml report: datastores: - bq://my-project/my-dataset/reports ``` ```yaml # .octocov.yml for central repo central: reports: datastores: - bq://my-project/my-dataset/reports push: ``` -------------------------------- ### Commit and Push Local Git Files Source: https://github.com/k1low/octocov/blob/main/_autodocs/09-github-integration.md Commits and pushes specified files using the local git command. Requires a configured local git repository with authentication and write access to the branch. ```go func PushUsingLocalGit(ctx context.Context, gitRoot string, paths []string, message string) (int, error) ``` ```go count, err := gh.PushUsingLocalGit( ctx, "/repo", []string{"/repo/coverage.svg", "/repo/report.json"}, "Update by octocov", ) if err != nil { log.Fatal(err) } fmt.Printf("Committed %d files\n", count) ``` -------------------------------- ### Configure Code to Test Ratio Files Source: https://github.com/k1low/octocov/blob/main/README.md Specifies the files to be counted as 'Code' and 'Test' for calculating the code-to-test ratio. Uses glob patterns. ```yaml codeToTestRatio: code: # files to count as "Code" - '**/*.go' - '!**/*_test.go' test: # files to count as "Test" - '**/*_test.go' ``` -------------------------------- ### Recommended Import Paths for Octocov Source: https://github.com/k1low/octocov/blob/main/_autodocs/10-module-index.md Import these packages when building applications on top of the Octocov library. Ensure all necessary modules are included for your use case. ```go import ( "github.com/k1LoW/octocov/config" "github.com/k1LoW/octocov/report" "github.com/k1LoW/octocov/coverage" "github.com/k1LoW/octocov/ratio" "github.com/k1LoW/octocov/datastore" "github.com/k1LoW/octocov/badge" "github.com/k1LoW/octocov/gh" ) ``` -------------------------------- ### Configure GitHub Enterprise Server API URL and Token Source: https://github.com/k1low/octocov/blob/main/_autodocs/09-github-integration.md Set environment variables to point to your GitHub Enterprise Server instance and provide an authentication token. This is typically used when not using the default GitHub Cloud API. ```bash export GITHUB_API_URL="https://ghes.internal/api/v3" export GITHUB_TOKEN="ghp_..." ``` -------------------------------- ### Check Coverage Configuration Readiness Source: https://github.com/k1low/octocov/blob/main/_autodocs/01-config.md Validates if the coverage configuration is complete and suitable for CI execution. Returns an error if validation fails. ```go func (c *Config) CoverageConfigReady() error {} ```