### Example: Basic hook setup and execution tracking Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/hook.md Demonstrates the complete setup for tracking code execution using luacov. Requires initializing the runner, creating the hook, and registering it for line events. Any code executed after this setup will have its lines tracked. ```lua local runner = require("luacov.runner") local hook = require("luacov.hook") -- Create hook bound to runner local debug_hook = hook.new(runner) -- Register for line events debug.sethook(debug_hook, "l") -- Code execution is now tracked print("This line is tracked") ``` -------------------------------- ### Configuration Table Example Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/types.md An example configuration table demonstrating user overrides for stats file, report file, include/exclude patterns, and module mappings. ```lua { statsfile = "coverage.stats", reportfile = "coverage.report", include = {"myapp.*", "lib.*"}, exclude = {"test"}, modules = { ["myapp"] = "src/myapp.lua", ["myapp.*"] = "src" } } ``` -------------------------------- ### File Stats Table Example Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/types.md An example of a file_stats table showing hit counts for specific lines. ```lua { max = 50, max_hits = 7, [1] = 1, [5] = 3, [10] = 7, [20] = 2, -- Lines 2, 3, 4, 6-9, 11-19, 21-50 not present (hit count 0) } ``` -------------------------------- ### Custom Reporter Example Source: https://github.com/lunarmodules/luacov/blob/master/docs/doc/modules/luacov.reporter.html Example of creating a custom reporter by extending ReporterBase and overriding the on_hit_line method to write custom output. ```lua local MyReporter = setmetatable({}, ReporterBase) MyReporter.__index = MyReporter function MyReporter:on_hit_line(...) self:write(("File %s: hit line %s %d times"):format(...)) end ``` -------------------------------- ### Custom Reporter Implementation Example Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/reporter.md A complete example of a custom reporter class that extends ReporterBase, implementing methods to format and display coverage results. ```lua local ReporterBase = require("luacov.reporter").ReporterBase local MyReporter = setmetatable({}, ReporterBase) MyReporter.__index = MyReporter function MyReporter:on_start() self:write("COVERAGE REPORT\n") self._total_lines = 0 self._covered_lines = 0 end function MyReporter:on_new_file(filename) self:write("\nFile: " .. filename .. "\n") self._file_lines = 0 self._file_covered = 0 end function MyReporter:on_empty_line(filename, lineno, line) -- Skip empty lines from count end function MyReporter:on_mis_line(filename, lineno, line) self._file_lines = self._file_lines + 1 self._total_lines = self._total_lines + 1 self:write(" " .. string.format("%4d", lineno) .. " MISS: " .. line .. "\n") end function MyReporter:on_hit_line(filename, lineno, line, hits) self._file_lines = self._file_lines + 1 self._file_covered = self._file_covered + 1 self._covered_lines = self._covered_lines + 1 self:write(" " .. string.format("%4d", lineno) .. " OK(" .. hits .. "): " .. line .. "\n") end function MyReporter:on_end_file(filename, hits, miss) local coverage = (hits / (hits + miss) * 100) self:write(string.format(" Coverage: %.1f%%\n", coverage)) end function MyReporter:on_end() self:write("\nTotal Coverage: " .. string.format("%.1f%%\n", (self._covered_lines / self._total_lines * 100))) end return MyReporter ``` -------------------------------- ### Complete LuaCOV Configuration Example Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/defaults.md A comprehensive example of a .luacov configuration file, detailing settings for stats and reporting, HTML report generation, automatic reporting, coverage collection, file inclusion/exclusion patterns, module location mapping, and handling of untested files and dynamically loaded code. ```lua -- .luacov - Complete example for a test suite return { -- Stats and reporting statsfile = "coverage/test.stats", reportfile = "coverage/test.report", -- Generate HTML report automatically reporter = "html", reportfile = "coverage/test.html", -- Auto-run reporter and clean up runreport = true, deletestats = false, -- Keep stats for inspection -- Coverage collection tick = false, -- Not a daemon -- Files to include include = { "myapp$", "myapp%/.+$", }, -- Files to exclude exclude = { "myapp%/test", "myapp%/debug", }, -- Module location mapping modules = { ["myapp"] = "src/myapp.lua", ["myapp.*"] = "src" }, -- Include untested files includeuntestedfiles = true, -- Don't track dynamically loaded code codefromstrings = false, } ``` -------------------------------- ### ReporterBase:on_start Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/reporter.md Lifecycle method called once before any files are processed. Intended for reporter-specific setup. ```APIDOC ## ReporterBase:on_start ### Description Lifecycle method called once before any files are processed. Intended for reporter-specific setup. ### Method `on_start` ### Returns nil ``` -------------------------------- ### Example: Using Default and Custom Reporters Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/reporter.md Demonstrates how to use the default LuaCov reporter and how to instantiate and use a custom reporter by overriding its methods. ```lua local reporter = require("luacov.reporter") -- Use default reporter reporter.report() -- Use custom reporter local MyReporter = setmetatable({}, reporter.ReporterBase) MyReporter.__index = MyReporter function MyReporter:on_hit_line(filename, lineno, line, hits) self:write(string.format("[%s:%d] \u2713 %s\n", filename, lineno, line)) end reporter.report(MyReporter) ``` -------------------------------- ### Configuration Merging Example Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/configuration.md Illustrates how user-provided configuration overrides default settings for LuaCov. ```lua -- Defaults provide: -- statsfile = "luacov.stats.out" -- reportfile = "luacov.report.out" -- include = {} -- User .luacov provides: -- include = {"myapp.*"} -- Result includes both: -- statsfile = "luacov.stats.out" (from default) -- reportfile = "luacov.report.out" (from default) -- include = {"myapp.*"} (from user) ``` -------------------------------- ### Complete LineScanner Usage Example Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/linescanner.md Provides a full example of using the LineScanner to process a Lua source string. It demonstrates initializing the scanner, consuming lines, and determining the coverage status (ALWAYS_EXCLUDED, EXCLUDED_IF_NOT_HIT, TRACKED) for each line. ```lua local LineScanner = require("luacov.linescanner") local source = [[ if condition then print("yes") else -- luacov: disable error("should not happen") -- luacov: enable end ]] local scanner = LineScanner:new() local lines = {} for line in source:gmatch("[^ ]+") do table.insert(lines, line) end for i, line in ipairs(lines) do local always, not_hit = scanner:consume(line) local status if always then status = "ALWAYS_EXCLUDED" elseif not_hit then status = "EXCLUDED_IF_NOT_HIT" else status = "TRACKED" end print(string.format("%d: %-10s %s", i, status, line)) end -- Output: -- 1: ALWAYS_EXCLUDED if condition then -- 2: TRACKED print("yes") -- 3: ALWAYS_EXCLUDED else -- 4: ALWAYS_EXCLUDED -- luacov: disable -- 5: ALWAYS_EXCLUDED error("should not happen") -- 6: ALWAYS_EXCLUDED -- luacov: enable -- 7: ALWAYS_EXCLUDED end ``` -------------------------------- ### Included Line Examples Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/linescanner.md Presents examples of lines that are always included for coverage tracking. These are typically executable statements with potential side effects. ```lua "print('hello')" -- Function call ``` ```lua "x = 5" -- Assignment ``` ```lua "local x = compute()" -- Local with side effect ``` ```lua "a = b + c" -- Expression ``` -------------------------------- ### Coverage Data Table Example Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/types.md An example of the coverage_data table containing statistics for multiple Lua files. ```lua { ["src/main.lua"] = { max = 100, max_hits = 5, [1] = 1, [10] = 2, }, ["src/utils.lua"] = { max = 50, max_hits = 3, [5] = 1, } } ``` -------------------------------- ### init Source: https://github.com/lunarmodules/luacov/blob/master/docs/doc/modules/luacov.runner.html Initializes the LuaCov runner, starting the process of collecting coverage data. ```APIDOC ## init ([configuration]) ### Description Initializes the LuaCov runner to start collecting coverage data. This function can optionally accept a configuration table or filename to customize the initialization process. ### Parameters * **configuration** (table | string, optional) - User-provided configuration (can be a config table or a filename). ``` -------------------------------- ### Install LuaCov using Luarocks Source: https://github.com/lunarmodules/luacov/blob/master/README.md Install the LuaCov package using the Luarocks package manager. This is the standard method for installation. ```bash luarocks install luacov ``` -------------------------------- ### Lua Pattern Matching Examples Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/types.md Demonstrates the usage of Lua pattern strings for file inclusion and exclusion, including exact matches, directory patterns, and wildcards. ```lua -- Exact match "mymodule$" ``` ```lua -- Pattern with directory "mymodule%/utils$" ``` ```lua -- Wildcard "mymodule%/.+$" ``` ```lua -- Multiple alternatives (need separate patterns) include = { "src/.+$", "lib/.+$" } ``` -------------------------------- ### Install CLuaCov with C Extensions Source: https://github.com/lunarmodules/luacov/blob/master/README.md Install the CLuaCov package to get experimental C extensions that enhance performance and analysis accuracy. This replaces the standard LuaCov installation. ```bash luarocks install cluacov ``` -------------------------------- ### Custom Reporter Initialization Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/errors.md Implement custom reporter initialization logic, handling potential errors like missing stats files. This example shows how to create a custom reporter with error handling. ```lua local reporter = require("luacov.reporter") local ReporterBase = reporter.ReporterBase local MyReporter = setmetatable({}, ReporterBase) MyReporter.__index = MyReporter function MyReporter:new(conf) if not conf.statsfile then return nil, "No statsfile configured" end return ReporterBase.new(self, conf) end ``` -------------------------------- ### init Source: https://github.com/lunarmodules/luacov/blob/master/docs/doc/modules/luacov.runner.html Initializes the LuaCov runner to start collecting coverage data. It can accept a configuration file path or a configuration table. ```APIDOC ## init (configuration) ### Description Initializes LuaCov runner to start collecting data. ### Parameters * **configuration** (string | table) - Optional. If a string, it's treated as the filename of the configuration file (used to call `load_config`). If a table, it's the configuration table itself (see `luacov.default.lua` for an example). ### Returns: existing configuration if already set, otherwise loads a new config from the provided data or the defaults. When loading a new config, if some options are missing, default values from [luacov.defaults](../modules/luacov.defaults.html#) are used instead. ``` -------------------------------- ### LuaCov Configuration: Return Table Style Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/configuration.md Example of a .luacov configuration file using a return table, which is another supported syntax style for defining settings. ```lua -- .luacov (return table style) return { statsfile = "coverage.stats", reportfile = "coverage.report", tick = true, include = {"myapp.*"} } ``` -------------------------------- ### Exclude Overrides Include Example Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/configuration.md Illustrates how the 'exclude' configuration takes precedence over 'include' when both patterns match a file. ```lua include = {"src/.+"} exclude = {"src/test"} -- This takes effect! ``` -------------------------------- ### Monitor Coverage Growth in a Running Daemon Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/tick.md Example script to periodically check and report coverage progress from a running daemon that uses tick mode. ```lua #!/usr/bin/env lua -lluacov.tick -- monitor.lua -- With tick enabled, you can check coverage progress without stopping daemon while true do local stats = require("luacov.stats").load("luacov.stats.out") if stats then local count = 0 for _ in pairs(stats) do count = count + 1 end print("Covered " .. count .. " files at " .. os.date()) end os.execute("sleep 60") end ``` -------------------------------- ### Create LineScanner Instance Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/linescanner.md Instantiates a new LineScanner object. This is the starting point for analyzing source code lines. ```lua function LineScanner:new() ``` -------------------------------- ### ReporterBase:run Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/reporter.md Executes the full report generation process, including starting, processing files, and ending the report. ```APIDOC ## ReporterBase:run ### Description Executes the full report generation process, including starting, processing files, and ending the report. ### Method `run` ### Returns nil ``` -------------------------------- ### LuaCov Configuration: reporter Option Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/configuration.md Example of setting the 'reporter' option to choose the reporting module. Built-in reporters include default text and HTML. ```lua reporter = nil ``` ```lua -- Generate HTML report reporter = "html" reportfile = "coverage.html" ``` ```lua -- Generate text report (explicit) reporter = nil -- or omit this line reportfile = "coverage.txt" ``` -------------------------------- ### Example: Custom hook integration with original hook call Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/hook.md Demonstrates how to wrap the original `luacov` hook with custom logic. This allows adding extra processing while ensuring that the original coverage tracking functionality is still executed by calling `original_hook`. ```lua local runner = require("luacov.runner") local hook = require("luacov.hook") runner.init() -- If you need to integrate custom processing: local original_hook = runner.debug_hook local function my_hook(event, line, level) -- Call original hook original_hook(event, line, level or 2) -- Add custom processing if event == "line" then -- Custom logic here end end -- Register custom hook (but coverage still works) debug.sethook(my_hook, "l") ``` -------------------------------- ### LuaCov Configuration: Global Variables Style Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/configuration.md Example of a .luacov configuration file using global variables for settings like statsfile, reportfile, tick, and include paths. ```lua -- .luacov (global style) statsfile = "coverage.stats" reportfile = "coverage.report" tick = true include = {"myapp.*"} ``` -------------------------------- ### LuaCov Configuration: statsfile Option Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/configuration.md Example of setting the 'statsfile' option to specify the output file for coverage data. Relative paths are converted to absolute upon initialization. ```lua statsfile = "luacov.stats.out" ``` ```lua -- Separate stats for different test suites statsfile = "coverage/unit_tests.stats" ``` ```lua -- In .luacov or code: runner.init({statsfile = "custom.stats"}) ``` -------------------------------- ### Example: Multi-line String Handling Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/linescanner.md Illustrates how the LineScanner handles multi-line strings, including those enclosed in long brackets with equals signs. The scanner's state tracks entry into and exit from these string constructs. ```lua local x = [[ This string spans multiple lines ]] -- The scanner state tracks: -- Line 1: Sets quote = "[" -- Line 2-3: In string (equals set) -- Line 3: Finds closing ]] and clears equals ``` -------------------------------- ### LuaCov Configuration: reportfile Option Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/configuration.md Example of setting the 'reportfile' option to specify the output file for the coverage report. The file is overwritten each time the reporter runs. ```lua reportfile = "luacov.report.out" ``` ```lua reporter = "html" reportfile = "coverage/report.html" ``` ```lua -- Or default text report: reportfile = "coverage.txt" ``` -------------------------------- ### Long-Running Server with Tick Mode Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/tick.md Example of a daemon server script that automatically enables tick mode via a command-line flag for periodic coverage saves. ```lua #!/usr/bin/env lua -lluacov.tick -- server.lua -- This daemon will save coverage data periodically local http = require("http") local server = http.new_server("localhost", 8080) function server:handle_request(request) return {status = 200, body = "OK"} end server:run() -- Runs forever; coverage saved periodically ``` -------------------------------- ### Lua Configuration for LuaCov Tick Mode Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/tick.md Example of a .luacov configuration file to enable tick mode, set save step size, specify stats and report files, and define include/exclude patterns. ```lua -- .luacov for daemon with tick mode return { tick = true, savestepsize = 100, statsfile = "daemon_coverage.stats", reportfile = "daemon_coverage.report", runreport = false, -- Don't auto-run reporter include = {"myapp.*"}, exclude = {"test", "debug"} } ``` -------------------------------- ### LuaCov Initialization via Code Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/configuration.md Shows how to initialize LuaCov programmatically using runner.init() with configuration loaded from a file, a table, or environment variables. ```lua local runner = require("luacov.runner") -- From file runner.init("path/to/config.lua") -- From table runner.init({ include = {"mymodule.*"}, tick = true }) -- From environment runner.init() -- Uses LUACOV_CONFIG or .luacov ``` -------------------------------- ### Example LuaCov Report Output Source: https://github.com/lunarmodules/luacov/blob/master/README.md An example of the output generated by the luacov report file. It shows line execution counts for a Lua script. ```text ============================================================================== test.lua ============================================================================== 1 if 10 > 100 then *0 print("I don't think this line will execute.") else 1 print("Hello, LuaCov!") end ``` -------------------------------- ### Excluded When Not Hit Line Examples Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/linescanner.md Shows examples of lines that might be excluded from coverage reporting if they are not executed. This includes constant expressions and table assignments. ```lua "{ }" -- Empty table ``` ```lua "function" -- Function keyword ``` ```lua "x" -- Single identifier ``` ```lua "return function(...)" -- Return function ``` ```lua "[key] = value," -- Table field ``` ```lua "break" -- Break statement ``` -------------------------------- ### ReporterBase on_start Lifecycle Method Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/reporter.md Callback function invoked before any files are processed during report generation. ```lua function ReporterBase:on_start() end ``` -------------------------------- ### Always Excluded Line Examples Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/linescanner.md Provides examples of source code lines that are always excluded from coverage reporting. These lines typically do not generate executable bytecode. ```lua "" -- Empty ``` ```lua "if 10 > 5 then" -- Control flow keyword only ``` ```lua "end" -- Closing keyword ``` ```lua "else" -- Alternative keyword ``` ```lua "local x" -- Local declaration ``` ```lua "local function f()" -- Local function ``` -------------------------------- ### Instantiate ReporterBase Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/reporter.md Creates a new reporter instance with specified configuration. Ensure the configuration includes paths for stats and report files. The reporter can be run and then closed to finalize the report. ```lua local reporter = require("luacov.reporter") local config = { statsfile = "luacov.stats.out", reportfile = "luacov.report.out", includeuntestedfiles = false } local rep, err = reporter.ReporterBase:new(config) if not rep then print("Error: " .. err) else rep:run() rep:close() end ``` -------------------------------- ### Custom Debug Hook Example Source: https://github.com/lunarmodules/luacov/blob/master/docs/doc/modules/luacov.runner.html Example of how to use the runner.debug_hook within a custom debug hook function. This allows for additional processing while still enabling LuaCov's coverage tracking. Ensure the level parameter is adjusted if calling from another hook. ```lua local function custom_hook(_, line) runner.debug_hook(_, line, 3) extra_processing(line) end ``` -------------------------------- ### ReporterBase config Method Signature Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/reporter.md Returns the configuration table associated with the reporter instance. ```lua function ReporterBase:config() ``` -------------------------------- ### Initialize and Use LineScanner Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/linescanner.md Demonstrates initializing a LineScanner and processing lines from a file. It reads lines, consumes them with the scanner, and prints the exclusion status. ```lua local LineScanner = require("luacov.linescanner") local scanner = LineScanner:new() while true do local line = file:read("*l") if not line then break end local always_excluded, excluded_when_not_hit = scanner:consume(line) print(always_excluded, excluded_when_not_hit) end ``` -------------------------------- ### Standard hook registration via runner.init() Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/hook.md Demonstrates the simplest way to enable coverage tracking, where the hook is automatically registered internally when `runner.init()` is called. No explicit `debug.sethook` call is needed. ```lua local runner = require("luacov.runner") runner.init() -- Hook is automatically registered by runner.init() -- debug.sethook(runner.debug_hook, "l") is called internally ``` -------------------------------- ### util.unprefix Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/util.md Removes a specified prefix from the beginning of a string. If the string does not start with the prefix, the original string is returned. ```APIDOC ## util.unprefix(str, prefix) ### Description Removes a prefix from a string if present. ### Parameters #### Path Parameters - **str** (string) - Required - String to process - **prefix** (string) - Required - Prefix to remove ### Returns string (original string if prefix not found, or string without prefix) ### Example ```lua local util = require("luacov.util") util.unprefix("file.lua: error message", "file.lua: ") -- Returns: "error message" util.unprefix("no match", "prefix: ") -- Returns: "no match" ``` ``` -------------------------------- ### ReporterBase:new Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/reporter.md Creates a new reporter instance with the provided configuration. It loads statistics, filters files, and prepares the report file. ```APIDOC ## ReporterBase:new ### Description Creates a new reporter instance with the provided configuration. It loads statistics, filters files, and prepares the report file. ### Method `new` ### Parameters #### Path Parameters - **conf** (table) - Required - Configuration table (see luacov.defaults) ### Request Example ```lua local reporter = require("luacov.reporter") local config = { statsfile = "luacov.stats.out", reportfile = "luacov.report.out", includeuntestedfiles = false } local rep, err = reporter.ReporterBase:new(config) if not rep then print("Error: " .. err) else rep:run() rep:close() end ``` ### Returns ReporterBase instance or nil, error message ``` -------------------------------- ### ReporterBase files Method Signature Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/reporter.md Returns an array containing the names of all files that will be included in the report. ```lua function ReporterBase:files() ``` -------------------------------- ### Load Configuration File Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/util.md Loads and executes a configuration file from disk within a provided environment. Handles file reading, Lua parsing, and execution errors. ```lua local util = require("luacov.util") -- Successful load local ok, config = util.load_config(".luacov", {}) if ok then print("statsfile:", config.statsfile) else print("Error loading config: " .. error_type) end -- Config file example (.luacov): -- return { -- statsfile = "custom.stats", -- reportfile = "custom.report" -- } ``` -------------------------------- ### LuaCov Defaults Module Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/README.md The `defaults.md` module documents all configuration options, their default values, types, purposes, and usage examples. ```APIDOC ## LuaCov Configuration Defaults ### Description This module provides comprehensive documentation for all available LuaCov configuration options. It details each option's default value, data type, purpose, and includes usage examples. ### Configuration Options - `statsfile`: Path to the statistics file. - `reportfile`: Path for the generated report file. - `reporter`: Specifies the report format (e.g., 'default'). - `runreport`: Automatically run the report generator after collection. - `deletestats`: Delete statistics file after report generation. - `codefromstrings`: Enable coverage collection for code loaded from strings. - `include`: Table of file patterns to include. - `exclude`: Table of file patterns to exclude. - `modules`: Table of module patterns to include. - `includeuntestedfiles`: Include files that have no coverage data. - `tick`: Enable periodic saving of statistics. - `savestepsize`: Interval for periodic statistics saving. ``` -------------------------------- ### Load Config Success Return Values Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/types.md Illustrates the return values when util.load_config successfully loads a configuration. ```lua ok, result = true, value -- result is the return value from the config file ``` -------------------------------- ### Automatic Initialization via Command Line Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/INDEX.md Initialize LuaCov coverage tracking automatically by loading the luacov module when running a script from the command line. ```lua -- Automatic initialization (command line) lua -lluacov script.lua ``` -------------------------------- ### LuaCov Configuration: tick Option Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/configuration.md Example of enabling the 'tick' option for periodic saving of statistics, primarily for daemon processes that do not exit. ```lua -- For daemon processes tick = true savestepsize = 100 ``` ```lua -- Or load module: -- lua -lluacov.tick daemon.lua ``` -------------------------------- ### Pause and Resume Coverage Collection Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/tick.md Example of pausing and resuming coverage collection to minimize overhead during critical computation sections in tick mode. ```lua local runner = require("luacov.runner") runner.pause() -- Critical section with minimal coverage overhead local result = critical_computation() runner.resume() return result ``` -------------------------------- ### Initialize LuaCOV Runner Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/defaults.md Demonstrates different ways to initialize the luacov runner. You can specify an explicit configuration file path, rely on default file locations (.luacov or LUACOV_CONFIG environment variable), or provide a configuration table directly. ```lua local runner = require("luacov.runner") -- Explicit file runner.init("project/coverage.config") -- From default location (.luacov or LUACOV_CONFIG) runner.init() -- Table directly runner.init({ include = {"mymodule.*"}, savestepsize = 50 }) ``` -------------------------------- ### Create Custom Reporter Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/INDEX.md Extend the ReporterBase class to create a custom reporter for LuaCov. This example defines a reporter that writes hit line information. ```lua local ReporterBase = require("luacov.reporter").ReporterBase local MyReporter = setmetatable({}, ReporterBase) MyReporter.__index = MyReporter function MyReporter:on_hit_line(filename, lineno, line, hits) self:write(string.format("%s:%d [%d hits] %s\n", filename, lineno, hits, line)) end ``` -------------------------------- ### Debug LuaCov Configuration Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/configuration.md Initialize LuaCov and print the loaded configuration and module mappings for debugging purposes. This helps verify that your settings are applied correctly. ```lua local runner = require("luacov.runner") runner.init() -- or specify config print("Configuration:") for key, value in pairs(runner.configuration) do print(" " .. key .. " = " .. tostring(value)) end print("\nModules:") for i, pattern in ipairs(runner.modules.patterns) do print(" " .. pattern .. " => " .. runner.modules.filenames[i]) end ``` -------------------------------- ### LuaCov Configuration: deletestats Option Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/configuration.md Example of setting 'deletestats' to true to automatically delete the stats file after report generation. This requires 'runreport' to be true. ```lua runreport = true deletestats = true -- Each run generates fresh report with no accumulation ``` -------------------------------- ### LuaCov Configuration: runreport Option Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/configuration.md Example of setting 'runreport' to true to automatically generate a report after coverage collection finishes. This is useful for test suites. ```lua -- Auto-generate report in test suite runreport = true reporter = "html" reportfile = "coverage.html" ``` -------------------------------- ### Generate Coverage Report Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/INDEX.md Use the runner module to initialize and run the coverage report. A custom reporter can also be provided. ```lua local runner = require("luacov.runner") runner.init() runner.run_report() -- or with custom reporter: runner.run_report(CustomReporter) ``` -------------------------------- ### Return Configuration Table Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/defaults.md Configure LuaCov by returning a table of settings from the `.luacov` file. This is another supported format for the configuration script. ```lua return { statsfile = "coverage.stats", tick = true, savestepsize = 50 } ``` -------------------------------- ### luacov.defaults Configuration Options Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/MANIFEST.txt Documentation for the configuration options available in the luacov.defaults module. ```APIDOC ## Module: luacov.defaults ### Description Documents the default configuration options for LuaCov, detailing their types, default values, purpose, and usage examples. ### Configuration Options (11 total) - **statsfile**: Path to the statistics file. - **reportfile**: Path for the generated report. - **reporter**: Specifies the reporter to use (e.g., 'default'). - **runreport**: Boolean to indicate if a report should be run automatically. - **deletestats**: Boolean to delete stats files after reporting. - **tick**: Enables periodic statistics saving. - **savestepsize**: Interval for periodic statistics saving. - **codefromstrings**: Enables coverage for code loaded from strings. - **include**: Pattern for files to include in coverage. - **exclude**: Pattern for files to exclude from coverage. - **modules**: Specifies modules to include in coverage. - **includeuntestedfiles**: Boolean to include files not covered by tests. ``` -------------------------------- ### Manual Initialization Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/INDEX.md Manually initialize LuaCov coverage tracking by calling the init function from the luacov.runner module. ```lua -- Or manual require("luacov.runner").init() -- Code runs with coverage tracking -- Stats saved on exit automatically ``` -------------------------------- ### Verifying LuaCov Coverage Collection Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/errors.md This function initializes LuaCov, creates a dummy test file, requires and runs it, saves stats, and then loads the stats to verify if coverage collection is working correctly. ```lua local function verify_coverage() local stats = require("luacov.stats") local runner = require("luacov.runner") runner.init() -- Check if stats are being collected local sample = io.open("test.lua", "w") sample:write("print('test')\n") sample:close() require("luacov") dofile("test.lua") runner.save_stats() local data = stats.load(runner.configuration.statsfile) if data and data["test.lua"] then print("✓ Coverage collection working") return true else print("✗ Coverage collection not working") return false end end ``` -------------------------------- ### Use Custom Reporter Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/INDEX.md Run a coverage report using a custom reporter implementation. ```lua runner.run_report(MyReporter) ``` -------------------------------- ### Set LUACOV_CONFIG Environment Variable Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/configuration.md Override the default LuaCov configuration file location using the LUACOV_CONFIG environment variable. Useful for system-wide or CI/CD setups. ```bash export LUACOV_CONFIG=/etc/myapp/luacov.config lua -lluacov test.lua ``` -------------------------------- ### Configure Coverage with .luacov File Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/INDEX.md Create a .luacov configuration file to customize coverage collection behavior, such as include/exclude patterns and reporter settings. ```lua include = {"mymodule.*"} exclude = {"test"} reporter = "html" reportfile = "coverage.html" ``` -------------------------------- ### Correct LuaCov Include Patterns Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/configuration.md Demonstrates the correct way to specify include patterns in LuaCov configuration, avoiding common mistakes like including file extensions or using backslashes. ```lua -- WRONG: include = {"mymodule.lua"} -- RIGHT: include = {"mymodule"} ``` ```lua -- WRONG: include = {"mymodule\utils"} -- RIGHT: include = {"mymodule/utils"} ``` ```lua -- WRONG (regex): include = {"myapp.+"} -- RIGHT (Lua pattern): include = {"myapp%/.+"} ``` -------------------------------- ### Lua Test Suite Integration with Tick Mode Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/tick.md Example of integrating LuaCov's tick mode into a test suite. This ensures coverage is saved periodically even if tests encounter errors or crashes. ```lua -- test.lua require("luacov.tick") local function run_test(test_func) xpcall(test_func, function(err) print("Test failed: " .. err) end) end -- Run many tests; coverage saves periodically even if tests crash for test_name, test_func in pairs(all_tests) do run_test(test_func) end ``` -------------------------------- ### Handle Source File Not Found Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/errors.md Run the reporter from the same directory as coverage collection or use absolute paths in the configuration to resolve 'Source File Not Found' errors. ```lua -- Run reporter from same directory as collection cd /project lua -lluacov test.lua luacov -- Run from same directory -- Or use absolute paths in config: runner.init({ modules = { ["myapp"] = "/absolute/path/src/myapp.lua" } }) ``` -------------------------------- ### Load LuaCov Configuration from File Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/util.md Loads LuaCov configuration settings from a specified file into a provided environment table. This is useful for initializing LuaCov with custom settings before running tests. Ensure the configuration file exists and is correctly formatted. ```lua local util = require("luacov.util") local runner = require("luacov.runner") -- Prepare environment with globals local conf = setmetatable({}, {__index = _G}) -- Load from file local ok, config = util.load_config(".luacov", conf) if not ok then io.stderr:write("Error loading config: " .. error_message .. "\n") os.exit(1) end -- Now conf contains all settings from file runner.load_config(conf) ``` -------------------------------- ### Get Real Filename with LuaCov Mappings Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/runner.md Resolves a given filename to its canonical or real name based on module mappings defined in the LuaCov configuration. This is helpful when dealing with aliased or wildcard module names. ```lua local runner = require("luacov.runner") runner.load_config({ modules = { ["mylib"] = "src/mylib.lua", ["mylib.*"] = "src" } }) print(runner.real_name("mylib")) -- src/mylib.lua print(runner.real_name("mylib/utils")) -- src/utils.lua ``` -------------------------------- ### Example Exclusion Patterns Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/linescanner.md Shows a table of simplified Lua patterns used by the scanner for excluding lines. These patterns cover common Lua constructs like empty lines, end statements, local declarations, and function returns. ```lua local patterns = { "", -- Empty line "end[,; %)]*", -- Close with optional punctuation "local x", -- Local declaration "return function", -- Function return "break", -- Break statement } ``` -------------------------------- ### util.load_config Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/util.md Loads a configuration file from the specified path and executes it within a given environment. It returns the configuration result on success or an error type and message on failure. ```APIDOC ## util.load_config(name, env) ### Description Loads a configuration file from disk and executes it in an environment. ### Parameters #### Path Parameters - **name** (string) - Required - Path to configuration file - **env** (table) - Required - Environment table for execution ### Returns true, result or nil, error_type, error_message ### Return Values - Success: `true, return_value` where return_value is what config file returned - Failure: `nil, error_type, error_message` where error_type is "read", "load", or "run" ### Example ```lua local util = require("luacov.util") -- Successful load local ok, config = util.load_config(".luacov", {}) if ok then print("statsfile:", config.statsfile) else print("Error loading config: " .. error_type) end -- Config file example (.luacov): -- return { -- statsfile = "custom.stats", -- reportfile = "custom.report" -- } ``` ### Error Types #### read File cannot be opened or read #### load File contains invalid Lua syntax #### run File executes but raises an error ``` -------------------------------- ### ReporterBase Instance Structure Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/types.md An instance created by ReporterBase:new(config), holding output file handle, configuration, coverage data, and file lists for reporting. ```lua reporter_instance = { _out = file_handle, -- Output file for report _cfg = config, -- Configuration table _data = coverage_data, -- Filtered coverage data _files = filename_array, -- Array of files to report _mhit = number, -- Maximum hits across all files } ``` -------------------------------- ### Example: Handling Rare Error Conditions Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/linescanner.md Demonstrates how to use inline directives to disable coverage tracking for a rare error condition within a function. This ensures that the error handling code, even if not frequently executed in tests, does not negatively impact coverage metrics. ```lua function handle_error(error_code) if error_code == 0 then return true end -- luacov: disable -- This is a rare condition in tests but important in production if error_code == CRITICAL_ERROR_CODE then os.exit(1) end -- luacov: enable return false end ``` -------------------------------- ### Configure LuaCov Modules and Paths Source: https://github.com/lunarmodules/luacov/blob/master/README.md Specify modules and their corresponding source paths for coverage. Use glob patterns for submodules. ```lua modules = { ["foo"] = "src/foo/init.lua", ["foo.*"] = "src" } ``` -------------------------------- ### Safely Loading LuaCov Configuration Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/errors.md This function attempts to load the .luacov configuration file. If loading fails, it prints a warning and initializes LuaCov with default settings. Otherwise, it initializes with the loaded configuration. ```lua local function safe_init() local runner = require("luacov.runner") local util = require("luacov.util") -- Try to load config local conf = setmetatable({}, {__index = _G}) local ok, config = util.load_config(".luacov", conf) if not ok then io.stderr:write("Warning: Could not load .luacov: " .. tostring(config) .. "\n") runner.init() -- Use defaults else runner.init(conf) end return runner end local runner = safe_init() ``` -------------------------------- ### Test Suite with HTML Report Configuration Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/INDEX.md Configuration for a test suite, enabling report generation, specifying HTML reporter, setting report file, and defining file inclusion/exclusion patterns. ```lua -- .luacov runreport = true reporter = "html" reportfile = "coverage/report.html" deletestats = false includeuntestedfiles = true include = {"myapp.*"} exclude = {"myapp%/test"} ``` -------------------------------- ### ReporterBase on_new_file Lifecycle Method Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/reporter.md Callback function invoked before processing a specific file. It receives the filename as an argument. ```lua function ReporterBase:on_new_file(filename) end ``` -------------------------------- ### runner.load_config Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/runner.md Loads and merges configuration settings, either from a specified file path or a configuration table. It handles default configurations and environment variables. ```APIDOC ## runner.load_config ### Description Loads and merges configuration from file or table. ### Method `runner.load_config(configuration)` ### Parameters #### Path Parameters - **configuration** (string|table|nil) - Optional - Config file path, config table, or nil to load from defaults ### Request Example ```lua local runner = require("luacov.runner") local config = runner.load_config(".luacov") local config = runner.load_config({ include = {"mymodule.*"}, exclude = {"test"}, statsfile = "coverage.stats" }) ``` ### Response #### Success Response - table (configuration table) ### Raises: - Exits with code 1 if config file cannot be read or parsed ### Behavior: - Returns cached configuration if already loaded - Searches for LUACOV_CONFIG environment variable or `.luacov` file - Merges user config with defaults from luacov.defaults - Converts relative paths to absolute paths - Calls acknowledge_modules() to process module mappings ``` -------------------------------- ### ReporterBase run Method Signature Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/reporter.md Executes the main report generation process, including lifecycle method calls. ```lua function ReporterBase:run() ``` -------------------------------- ### runner(configfile) Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/runner.md Initializes the LuaCov runner with a configuration file. This is a callable alias for runner.init(configfile). ```APIDOC ## runner(configfile) ### Description Initializes the LuaCov runner with a configuration file. This is a callable alias for runner.init(configfile). ### Method `function` ### Parameters #### Path Parameters - **configfile** (string) - Optional - Path to the configuration file. ### Example ```lua -- These are equivalent: require("luacov.runner").init(".luacov") require("luacov.runner")(".luacov") ``` ``` -------------------------------- ### Typical Coverage Collection Flow Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/stats.md Illustrates the standard process for collecting and reporting code coverage using luacov. This involves initializing the runner, running the code, saving statistics, and then generating a report. ```lua -- Step 1: Initialize runner with coverage tracking local runner = require("luacov.runner") runner.init() -- Step 2: Run code under test -- (debug hook tracks all line executions) -- Step 3: Exit normally or call shutdown -- runner.save_stats() is called automatically on exit -- or manually: runner.save_stats() -- Step 4: Analyze stats file local stats = require("luacov.stats") local data = stats.load("luacov.stats.out") -- Step 5: Generate report runner.run_report() -- Processes data to create human-readable report ``` ``` -------------------------------- ### LuaCov Configuration Options Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/INDEX.md This snippet shows the various configuration options available in the .luacov file, covering input/output, collection, filtering, and reporting settings. ```lua -- Input statsfile = "luacov.stats.out" -- Output reportfile = "luacov.report.out" reporter = nil -- default, "html", etc. -- Collection tick = false savestepsize = 100 codefromstrings = false -- Filtering include = {} exclude = {} modules = {} includeuntestedfiles = false -- Reporting runreport = false deletestats = false ``` -------------------------------- ### Map Module Names to File Locations Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/defaults.md Configure the `modules` table to map module names (used in `require()`) to their corresponding source file paths. Wildcards can be used for submodules. ```lua modules = {} ``` ```lua -- Project structure: -- src/ -- mylib.lua -- mylib/ -- utils.lua -- helpers.lua modules = { ["mylib"] = "src/mylib.lua", ["mylib.*"] = "src", -- mylib.utils resolves to src/utils.lua } ``` -------------------------------- ### stats.load(statsfile) Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/stats.md Loads coverage statistics from a specified file. It returns a table containing the statistics data for each file, or nil if the file cannot be loaded. ```APIDOC ## stats.load(statsfile) ### Description Loads coverage statistics from a file. ### Method `stats.load(statsfile)` ### Parameters #### Path Parameters - **statsfile** (string) - Required - Path to the stats file to load ### Returns table (statistics data) or nil ### Return Value Structure: ```lua { [filename] = { max = number, -- Highest line number in the file max_hits = number, -- Highest hit count for any line [1] = number, -- Hit count for line 1 (if > 0) [2] = number, -- Hit count for line 2 (if > 0) -- ... only lines with hits > 0 are stored }, -- ... more files } ``` ### Example: ```lua local stats = require("luacov.stats") local data = stats.load("luacov.stats.out") if not data then print("No stats file found") else for filename, filedata in pairs(data) do print(filename .. ": " .. filedata.max .. " lines") print(" max hits on a line: " .. filedata.max_hits) end end ``` ``` -------------------------------- ### ReporterBase Constructor Signature Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/reporter.md Defines the constructor for the ReporterBase class, accepting a configuration table. ```lua function ReporterBase:new(conf) ``` -------------------------------- ### Check File Existence Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/api-reference/util.md Verifies if a file exists and is readable by attempting to open it. Returns true if accessible, false otherwise. ```lua local util = require("luacov.util") if util.file_exists("myfile.lua") then print("File found") else print("File not found") end ``` -------------------------------- ### DefaultReporter Instance Additions Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/types.md Extends the ReporterBase with specific state for tracking coverage summaries and formatting output. ```lua default_reporter = ReporterBase_instance with additions: { _summary = {}, -- Maps filename to {hits, miss} _empty_format = " ", -- Format string for empty lines _zero_format = "*0", -- Format string for missed lines _count_format = "% 2d", -- Format string for hit counts _printed_first_header = false, } ``` -------------------------------- ### Generate Report with Custom Config Source: https://github.com/lunarmodules/luacov/blob/master/_autodocs/INDEX.md Command to generate a coverage report using a specific configuration file. ```bash # Generate from specific config luacov -c custom_config.lua ``` -------------------------------- ### Configure HTML Report Generation Source: https://github.com/lunarmodules/luacov/blob/master/README.md Set the reporter to 'html' and specify the output file name for the HTML report. ```lua reporter = "html" reportfile = "luacov.report.html" ```