### Setup ini-parser Project Source: https://github.com/notfounnd/ini-parser/blob/master/README.md Commands to clone the repository, install dependencies, and run development tasks like tests and linting. ```bash # Clone repository git clone https://github.com/notfounnd/ini-parser.git cd ini-parser # Install dependencies npm install # Run tests npm test # Run tests with coverage npm run test:coverage # Run linter npm run lint:check # Format code npm run format ``` -------------------------------- ### Installation Commands Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/INDEX.md Provides commands for installing the ini-parser as a library, a global CLI tool, or via npx. ```bash # As library npm install @notfounnd/ini-parser # As CLI tool npm install -g @notfounnd/ini-parser # Via npx npx @notfounnd/ini-parser config.ini ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/notfounnd/ini-parser/blob/master/CONTRIBUTING.md Install all necessary project dependencies using npm. ```bash npm install ``` -------------------------------- ### Quick Start: Parse INI Content Source: https://github.com/notfounnd/ini-parser/blob/master/docs/API.md A quick example demonstrating how to parse INI content into a JavaScript object using the `parse` function. ```javascript const { parse } = require('@notfounnd/ini-parser'); const content = ` [database] host=localhost port=5432 `; const result = parse(content); console.log(result); // Output: { database: { host: ['localhost'], port: ['5432'] } } ``` -------------------------------- ### Install and Use INI Parser in Docker Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/usage-examples.md A Dockerfile demonstrating how to install the ini-parser globally using npm, copy a configuration file, parse it during the build process, and then run a Node.js application. ```dockerfile FROM node:18 # Install ini-parser globally RUN npm install -g @notfounnd/ini-parser WORKDIR /app # Copy config file COPY app.ini . # Parse during build RUN ini-parser app.ini -o config.json COPY . . CMD ["node", "app.js"] ``` -------------------------------- ### Display Help Information Source: https://github.com/notfounnd/ini-parser/blob/master/docs/CLI.md Shows usage information, lists all available options, and displays examples for the CLI tool. Exits with code 0 after displaying help. ```bash ini-parser --help ``` ```bash ini-parser -h ``` ```bash ini-parser --help ``` -------------------------------- ### Commit Message Examples Source: https://github.com/notfounnd/ini-parser/blob/master/CONTRIBUTING.md Provides examples of well-formatted commit messages for various types of changes. These examples illustrate the expected structure and content for effective commit messages. ```markdown feat: add support for multi-line values with custom delimiters fix: correct parsing of empty sections docs: update API.md with TypeScript examples test: add edge case tests for comment handling refactor: simplify line classification logic using strategy pattern ``` -------------------------------- ### Parse INI Content (Basic Example) Source: https://github.com/notfounnd/ini-parser/blob/master/docs/API.md Demonstrates parsing a simple INI string with a single section and key. ```javascript const content = ` [section] key=value `; const result = parse(content); ``` -------------------------------- ### Install INI Parser as a Library Source: https://github.com/notfounnd/ini-parser/blob/master/README.md Use this command to install the package as a dependency for your Node.js project. ```bash npm install @notfounnd/ini-parser ``` -------------------------------- ### INI Sections Example Source: https://github.com/notfounnd/ini-parser/blob/master/docs/PARSER_RULES.md Demonstrates how sections are defined using `[section_name]` and how empty sections are parsed. ```ini [database] host=localhost [empty_section] ``` ```json { "database": { "host": ["localhost"] }, "empty_section": {} } ``` -------------------------------- ### Using CLI Locally with npx Source: https://github.com/notfounnd/ini-parser/blob/master/docs/CLI.md Execute the locally installed CLI using npx for parsing a configuration file. ```bash npx ini-parser config.ini ``` -------------------------------- ### Using the INI Parser CLI Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/module-structure.md Demonstrates various ways to execute the INI Parser command-line tool, including global installation, npx, and local execution. ```bash # Global installation npm install -g @notfounnd/ini-parser ini-parser config.ini # Via npx npx @notfounnd/ini-parser config.ini # Local node_modules ./node_modules/.bin/ini-parser config.ini ``` -------------------------------- ### Display Version Source: https://github.com/notfounnd/ini-parser/blob/master/docs/CLI.md Outputs the current installed version of the CLI tool. Exits with code 0 after displaying the version. ```bash ini-parser --version ``` ```bash ini-parser -v ``` ```bash ini-parser --version ``` -------------------------------- ### INI Line Comments Example Source: https://github.com/notfounnd/ini-parser/blob/master/docs/PARSER_RULES.md Demonstrates how lines starting with `#` or `;` are ignored as comments. ```ini # This is a comment ; This is also a comment [section] key=value ``` ```json { "section": { "key": ["value"] } } ``` -------------------------------- ### JavaScript Configuration Manager with INI Parsing Source: https://github.com/notfounnd/ini-parser/blob/master/docs/API.md A complete example demonstrating how to build a configuration manager in JavaScript using the INI parser. It includes loading, validation, and type-safe retrieval of configuration values. ```javascript const { parse } = require('@notfounnd/ini-parser'); const fs = require('fs'); const path = require('path'); /** * Configuration manager with INI file support */ class ConfigManager { constructor(configPath) { this.configPath = configPath; this.config = {}; } /** * Load configuration from INI file */ load() { try { const content = fs.readFileSync(this.configPath, 'utf8'); this.config = parse(content); // Validate configuration this.validate(); return this.config; } catch (error) { if (error.code === 'ENOENT') { throw new Error(`Config file not found: ${this.configPath}`); } throw new Error(`Failed to load config: ${error.message}`); } } /** * Validate required configuration sections */ validate() { const required = ['database', 'server']; const missing = required.filter(section => !this.config[section]); if (missing.length > 0) { throw new Error(`Missing required sections: ${missing.join(', ')}`); } } /** * Get configuration value with default fallback */ get(section, key, defaultValue = null) { if (!this.config[section]) { return defaultValue; } const value = this.config[section][key]; if (!value || value.length === 0) { return defaultValue; } // Return first value for single values return value.length === 1 ? value[0] : value; } /** * Get configuration value as number */ getNumber(section, key, defaultValue = 0) { const value = this.get(section, key); if (value === null) { return defaultValue; } const parsed = Number(value); return isNaN(parsed) ? defaultValue : parsed; } /** * Get configuration value as boolean */ getBoolean(section, key, defaultValue = false) { const value = this.get(section, key); if (value === null) { return defaultValue; } return value.toLowerCase() === 'true' || value === '1'; } /** * Get all values for a key (array) */ getArray(section, key, defaultValue = []) { if (!this.config[section]) { return defaultValue; } return this.config[section][key] || defaultValue; } } // Usage example function main() { const configPath = path.join(__dirname, 'app.ini'); const manager = new ConfigManager(configPath); try { manager.load(); // Get configuration values with proper types const dbHost = manager.get('database', 'host', 'localhost'); const dbPort = manager.getNumber('database', 'port', 5432); const debugMode = manager.getBoolean('app', 'debug', false); const allowedHosts = manager.getArray('server', 'allowed_hosts', []); console.log('Database:', { host: dbHost, port: dbPort }); console.log('Debug mode:', debugMode); console.log('Allowed hosts:', allowedHosts); } catch (error) { console.error('Configuration error:', error.message); process.exit(1); } } main(); ``` -------------------------------- ### Install INI Parser as a CLI Tool Source: https://github.com/notfounnd/ini-parser/blob/master/README.md Use this command to install the package globally, making the `ini-parser` command available in your terminal. ```bash npm install -g @notfounnd/ini-parser ``` -------------------------------- ### Usage of parse() function Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/types.md Demonstrates how to use the parse() function with different configuration options to get simplified or metadata output. ```javascript const { parse } = require('@notfounnd/ini-parser'); // Default simplified format const simple = parse(content); // With options object (explicitly false is same as default) const simple2 = parse(content, { meta: false }); // With metadata format const withMeta = parse(content, { meta: true }); ``` -------------------------------- ### INI Global Keys Example Source: https://github.com/notfounnd/ini-parser/blob/master/docs/PARSER_RULES.md Shows how keys defined before any section are treated as global and appear at the root level. ```ini app_name=MyApp version=1.0.0 [database] host=localhost ``` ```json { "app_name": ["MyApp"], "version": ["1.0.0"], "database": { "host": ["localhost"] } } ``` -------------------------------- ### Indentation Detection Example Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/parser-rules.md Demonstrates how the parser identifies indented lines based on leading whitespace characters. ```ini value # Indented (1 space) value # Indented (1 tab) value # Indented (2 spaces) value # Not indented ``` -------------------------------- ### Parse INI Content as a Library (Simplified) Source: https://github.com/notfounnd/ini-parser/blob/master/README.md Demonstrates parsing INI content using the library's `parse` function. This example shows the default simplified output format. ```javascript const { parse } = require('@notfounnd/ini-parser'); // Example INI content const content = ` # Database configuration [database] host=localhost port=5432 name=myapp [server] port=3000 workers=4 8 16 32 `; // Parse with simplified format (default) const result = parse(content); console.log(result); // Output: // { // database: { // host: ['localhost'], // port: ['5432'], // name: ['myapp'] // }, // server: { // port: ['3000'], // workers: ['4', '8', '16', '32'] // } // } ``` -------------------------------- ### Build Configuration Object with Defaults Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/usage-examples.md Combine default settings with parsed INI content to create a final configuration object. This example shows how to override defaults with values from the INI file, including boolean parsing and integer conversion. ```javascript const { parse } = require('@notfounnd/ini-parser'); const defaults = { debug: false, port: 3000, host: 'localhost' }; function loadConfig(iniContent) { const parsed = parse(iniContent); // Build final config from parsed data const config = { ...defaults }; // Override with global keys if (parsed.debug) { config.debug = parsed.debug[0] === 'true'; } // Override with section values if (parsed.server) { config.port = parseInt(parsed.server.port[0], 10); config.host = parsed.server.host[0]; } return config; } const iniContent = ` debug=true [server] port=8080 host=0.0.0.0 `; const config = loadConfig(iniContent); console.log(config); // { debug: true, port: 8080, host: '0.0.0.0' } ``` -------------------------------- ### Example of Metadata to Simplified Format Conversion Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/implementation-details.md Illustrates the input and output of the metadata conversion process. Section entries have their nested content extracted, while configuration entries have their content array directly assigned. ```javascript // Input (metadata format) { database: { type: 'section', content: { host: { type: 'configuration', content: ['localhost'] } } } } // Output (simplified format) { database: { host: ['localhost'] } } ``` -------------------------------- ### Example MetadataResult Structure Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/types.md Illustrates the structure of a MetadataResult object, showing global configuration entries, section entries, and nested configuration entries. ```javascript { // Global key (configuration entry) app_name: { type: 'configuration', content: ['MyApp'] }, // Section entry database: { type: 'section', content: { // Configuration entries within section host: { type: 'configuration', content: ['localhost'] }, port: { type: 'configuration', content: ['5432'] }, workers: { type: 'configuration', content: ['4', '8', '16'] } } }, // Empty section cache: { type: 'section', content: {} } } ``` -------------------------------- ### Extract Section with jq Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/cli-reference.md Example of piping the CLI output to `jq` to extract a specific section, such as 'database', from the parsed JSON. ```bash ini-parser config.ini | jq '.database' ``` -------------------------------- ### Integrate INI Parsing into Bash Scripts Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/usage-examples.md A bash script example that first validates a configuration file using '--check' and then parses it to extract specific settings using 'jq'. ```bash #!/bin/bash # Parse config and check for required sections CONFIG_FILE="app.ini" # Validate file first if ! ini-parser "$CONFIG_FILE" --check > /dev/null 2>&1; then echo "Configuration file is invalid" exit 1 fi # Parse and extract database config DB_CONFIG=$(ini-parser "$CONFIG_FILE" | jq '.database') DB_HOST=$(echo "$DB_CONFIG" | jq -r '.host[0]') DB_PORT=$(echo "$DB_CONFIG" | jq -r '.port[0]') echo "Connecting to database at $DB_HOST:$DB_PORT" ``` -------------------------------- ### Mixed Global and Sectioned Keys Parsing Source: https://github.com/notfounnd/ini-parser/blob/master/docs/PARSER_RULES.md Illustrates parsing an INI file containing both global metadata and section-specific configurations, including multi-line values for lists. This example demonstrates flexibility in configuration structure. ```ini ; Application metadata title=Configuration Parser author=NotFound [server] host=0.0.0.0 port=8080 allowed_origins=http://localhost:3000 http://localhost:8080 [logging] level=info format=json outputs= console file ``` ```json { "title": ["Configuration Parser"], "author": ["NotFound"], "server": { "host": ["0.0.0.0"], "port": ["8080"], "allowed_origins": ["http://localhost:3000", "http://localhost:8080"] }, "logging": { "level": ["info"], "format": ["json"], "outputs": ["console", "file"] } } ``` -------------------------------- ### File Path Examples Source: https://github.com/notfounnd/ini-parser/blob/master/docs/CLI.md The `` argument is a required string representing the path to the INI file. It supports relative or absolute paths and various file extensions. Ensure the file exists and is readable. ```bash # Relative path ini-parser config.ini ``` ```bash # Absolute path (Windows) ini-parser C:\projects\app\config.ini ``` ```bash # Absolute path (Unix/Linux) ini-parser /etc/app/config.ini ``` ```bash ini-parser app.config ``` ```bash ini-parser database.properties ``` -------------------------------- ### Parse INI Content (Simplified Format) Source: https://github.com/notfounnd/ini-parser/blob/master/docs/API.md Example of parsing INI content using the default simplified format. All values are returned as arrays. ```javascript const content = ` [db] host=localhost port=5432 `; const ini = parse(content); // { // db: { // host: ['localhost'], // port: ['5432'] // } // } ``` -------------------------------- ### INI Variable Substitution Example Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/implementation-details.md Shows that the parser does not support variable substitution like `${variable}`. These are treated as literal strings. ```ini basedir=/var logdir=${basedir}/log # Results in ["${basedir}/log"] ``` -------------------------------- ### Simple Unit Test with Inline Content Source: https://github.com/notfounnd/ini-parser/blob/master/CONTRIBUTING.md Provides examples for simple unit tests where inline content is acceptable due to the brevity of the input. Use this for very focused tests with minimal data. ```javascript it('should return empty object for empty string', () => { const result = parse(''); expect(result).toEqual({}); }); ``` ```javascript it('should return empty object for null input', () => { const result = parse(null); expect(result).toEqual({}); }); ``` -------------------------------- ### AAA Test Structure Example Source: https://github.com/notfounnd/ini-parser/blob/master/CONTRIBUTING.md Demonstrates the Arrange-Act-Assert pattern for writing clear and readable tests. Use this structure to set up test data, execute the code under test, and verify the expected outcome. ```javascript describe('Feature or Module', () => { describe('Specific functionality', () => { it('should do something specific', () => { // Arrange: Set up test data const input = '...'; // Act: Execute the function const result = parse(input); // Assert: Verify the result expect(result).toEqual({...}); }); }); }); ``` -------------------------------- ### Automatically Format Code Source: https://github.com/notfounnd/ini-parser/blob/master/CONTRIBUTING.md Use Prettier to automatically format the codebase according to the project's style guide. This command ensures consistent code style across the project. ```bash npm run format:fix ``` -------------------------------- ### INI Case Sensitivity Example Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/implementation-details.md Demonstrates that section names in the INI parser are case-sensitive. This differs from some common INI behaviors but is supported by this implementation. ```ini [Section] [section] ``` -------------------------------- ### Clone Repository and Navigate Source: https://github.com/notfounnd/ini-parser/blob/master/CONTRIBUTING.md Clone your fork of the repository and navigate into the project directory. ```bash git clone https://github.com/YOUR-USERNAME/ini-parser.git cd ini-parser ``` -------------------------------- ### Verify global npm installation Source: https://github.com/notfounnd/ini-parser/blob/master/docs/CLI.md Check if the ini-parser package is installed globally using npm. ```bash npm list -g @notfounnd/ini-parser ``` -------------------------------- ### Configuration with Sections and Globals Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/parser-rules.md Demonstrates a typical INI file structure with global settings and distinct sections for different application parts. ```ini # Application configuration app_name=MyApp version=1.0 [database] host=localhost port=5432 [server] host=0.0.0.0 port=8080 ``` -------------------------------- ### Package JSON Main and Bin Configuration Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/module-structure.md Defines the main entry point for library usage and the executable for the command-line interface. ```json { "main": "src/lib/parser.js", "bin": { "ini-parser": "bin/ini-parser.js" } } ``` -------------------------------- ### Test with Fixture File Source: https://github.com/notfounnd/ini-parser/blob/master/CONTRIBUTING.md Illustrates how to use fixture files for test data instead of inline content. This approach is recommended for INI content exceeding 2-3 lines to maintain test clarity and reusability. ```javascript const fs = require('fs'); const path = require('path'); const { parse } = require('../../src/lib/parser'); describe('parse()', () => { describe('Multi-line values', () => { it('should parse indented continuation lines as array values', () => { // Read from fixture file instead of inline content const fixturePath = path.join(__dirname, '../__fixtures__/valid-multiline.ini'); const content = fs.readFileSync(fixturePath, 'utf8'); const result = parse(content); expect(result).toHaveProperty('pytest'); expect(result.pytest.addopts).toEqual(['-rA', '--cov=package', '--cov-config=.coveragerc']); }); }); }); ``` -------------------------------- ### INI Inline Comments Example Source: https://github.com/notfounnd/ini-parser/blob/master/docs/PARSER_RULES.md Shows how content after `#` or `;` on a line is treated as an inline comment and removed. ```ini host=localhost # this is the local server port=5432 ; default PostgreSQL port ``` ```json { "host": ["localhost"], "port": ["5432"] } ``` -------------------------------- ### Display CLI Help Information Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/cli-reference.md Provides detailed usage instructions and available options for the INI Parser CLI. This is helpful for understanding how to use the tool effectively. ```bash ini-parser --help ``` ```bash ini-parser -h ``` -------------------------------- ### Line Comments Ignored Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/parser-rules.md Shows that lines starting with '#' or ';' are completely ignored by the parser, including indented comments. ```ini # This entire line is a comment ; This is also a comment # Indented comments are also ignored ; Tab-indented comment too ``` -------------------------------- ### Parse INI with Comments Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/api-reference.md Ignores lines starting with '#' or ';'. Inline comments following a value are also removed. ```javascript const content = `# This is a comment [section] key=value # inline comment ; Semicolon comment another=test `; const result = parse(content); console.log(result); // Output: { section: { key: ['value'], another: ['test'] } } ``` -------------------------------- ### Parse INI with Global Keys Source: https://github.com/notfounnd/ini-parser/blob/master/README.md Demonstrates parsing an INI file with global configuration keys and a section. ```ini # Global configuration debug=true log_level=info [database] host=localhost ``` ```javascript { debug: ['true'], log_level: ['info'], database: { host: ['localhost'] } } ``` -------------------------------- ### Check if CLI command is found Source: https://github.com/notfounnd/ini-parser/blob/master/docs/CLI.md If the 'ini-parser: command not found' error appears, verify your installation and PATH configuration. ```bash ini-parser: command not found ``` -------------------------------- ### Troubleshooting Unknown Option Errors Source: https://github.com/notfounnd/ini-parser/blob/master/docs/CLI.md Shows how to correct typos in option names and use the `--help` flag to find available command-line options. ```bash # Incorrect ini-parser config.ini --quite # typo # Correct ini-parser config.ini --quiet # Get help ini-parser --help ``` -------------------------------- ### Create and parse a minimal INI file Source: https://github.com/notfounnd/ini-parser/blob/master/docs/CLI.md Create a simple INI file with basic content and parse it to test the CLI functionality. ```bash echo "[test]" > test.ini echo "key=value" >> test.ini ini-parser test.ini ``` -------------------------------- ### Indented Continuation for Multi-line Values Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/parser-rules.md Lines starting with whitespace following a key are treated as continuation values, forming an array. ```ini [section] key=initial continued1 continued2 ``` -------------------------------- ### INI Parser Initial State Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/implementation-details.md The initial state object for the INI parser before any content is processed. It defines the starting context for parsing. ```javascript const state = { result: {}, currentSection: null, currentKey: null, expectingUnindentedValues: false }; ``` -------------------------------- ### Multi-environment Support Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/parser-rules.md Shows how to structure an INI file for supporting multiple environments (e.g., development and production) by overriding base configurations. ```ini # Base configuration debug=false [dev] db_host=localhost db_port=5432 [prod] db_host=db.example.com db_port=5432 ``` -------------------------------- ### Debug INI parsing process Source: https://github.com/notfounnd/ini-parser/blob/master/docs/CLI.md A sequence of commands to debug INI parsing issues, starting with validation and progressing to detailed output. ```bash # 1. Check file is valid ini-parser config.ini --check # 2. Parse and review output ini-parser config.ini # 3. Try with metadata to see structure ini-parser config.ini --meta # 4. Save to file for detailed inspection ini-parser config.ini --output debug.json ``` -------------------------------- ### Migrate Configuration Format Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/usage-examples.md Convert an old INI configuration file to a new JSON format using ini-parser, and then demonstrate loading it with Node.js. ```bash # Convert old format to new JSON format ini-parser old-config.ini -o new-config.json # Then use in application node -e "const c = require('./new-config.json'); console.log(c)" ``` -------------------------------- ### Full Configuration File Parsing Source: https://github.com/notfounnd/ini-parser/blob/master/docs/PARSER_RULES.md Demonstrates parsing a comprehensive INI file with global settings, a database section, and features section into a JSON object. Handles multi-line values and comments. ```ini # Global configuration app_name=MyApp version=1.0.0 [database] host=localhost port=5432 ; default PostgreSQL port users= admin readonly backup [features] enabled_modules=auth api logging ``` ```json { "app_name": ["MyApp"], "version": ["1.0.0"], "database": { "host": ["localhost"], "port": ["5432"], "users": ["admin", "readonly", "backup"] }, "features": { "enabled_modules": ["auth", "api", "logging"] } } ``` -------------------------------- ### INI Escape Sequence Example Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/implementation-details.md Illustrates that backslashes are treated as literal characters, not escape sequences. This means paths with spaces will be split into multiple values. ```ini path=C:\Program Files # Results in ["C:\\Program", "Files"] ``` -------------------------------- ### Standard Library Import for ini-parser Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/module-structure.md Use this import pattern for standard usage within your project. It assumes the package is installed via npm or yarn. ```javascript const { parse } = require('@notfounnd/ini-parser'); const result = parse(iniContent); ``` -------------------------------- ### List Configuration Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/parser-rules.md Illustrates how to define lists of values within an INI file, supporting both multi-line and space-separated formats. ```ini [servers] hosts= server1.example.com server2.example.com server3.example.com ports=8080 8081 8082 ``` -------------------------------- ### Load Configuration from File Source: https://github.com/notfounnd/ini-parser/blob/master/docs/API.md Safely loads INI configuration from a file. It reads the file content, checks for emptiness, and parses it. Includes error handling for file reading and returns default configuration on error or if the file is empty. Requires the `fs` module. ```javascript const fs = require('fs'); function loadConfig(filePath) { try { const content = fs.readFileSync(filePath, 'utf8'); if (!content || content.trim() === '') { console.warn('Configuration file is empty'); return getDefaultConfig(); } return parse(content); } catch (error) { console.error('Error loading config:', error.message); return getDefaultConfig(); } } ``` -------------------------------- ### INI Empty Section Example Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/parser-rules.md Sections declared without any key-value pairs are represented as empty objects in the parsed result. This demonstrates how an empty section is handled. ```ini [empty] [another] key=value ``` ```javascript { empty: {}, another: { key: ['value'] } } ``` -------------------------------- ### Example of Simplified Parsed Result Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/types.md Illustrates the structure of the ParsedResult object, showing global keys, section keys with nested objects, and handling of multiple values. ```javascript { // Global key app_name: ['MyApp'], version: ['1.0.0'], // Section with keys database: { host: ['localhost'], port: ['5432'], name: ['myapp'] }, // Another section server: { address: ['0.0.0.0'], port: ['8080'], workers: ['4', '8', '16'] // Multiple values from space-splitting }, // Empty section cache: {} } ``` -------------------------------- ### Accessing Metadata from Result Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/types.md Demonstrates how to check the type of an entry, access configuration content, and iterate through metadata entries with type awareness. ```javascript // Check entry type if (result.database?.type === 'section') { console.log('Is a section'); } // Access configuration content const dbHost = result.database.content.host.content[0]; // 'localhost' // Iterate with type awareness for (const key in result) { const entry = result[key]; if (entry.type === 'configuration') { console.log(`Global key: ${key} = ${entry.content.join(', ')}`); } else if (entry.type === 'section') { console.log(`Section: ${key}`); } } ``` -------------------------------- ### Remove Inline Comments from Value Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/implementation-details.md Removes inline comments (starting with '#' or ';') from the end of a string value. Handles cases where multiple comment characters might appear. ```javascript function _removeInlineComment(value) { const commentChars = ['#', ';']; const indices = commentChars .map(char => value.indexOf(char)) .filter(index => index !== -1); // Guard: No comment found if (indices.length === 0) { return value; } // Find earliest comment and remove from there const firstCommentIndex = Math.min(...indices); return value.substring(0, firstCommentIndex).trim(); } ``` -------------------------------- ### Get Metadata with Type Information Source: https://github.com/notfounnd/ini-parser/blob/master/docs/CLI.md Returns a JSON object with type information for each entry, distinguishing between sections and configuration keys. Useful for tools processing INI structure. ```bash ini-parser --meta ``` ```bash ini-parser config.ini --meta ``` -------------------------------- ### Project File Organization Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/module-structure.md Illustrates the directory and file structure of the INI parser project, including source code, tests, fixtures, and documentation. ```tree ini-parser/ └─ bin/ │ └─ ini-parser.js # CLI executable entry point └─ src/ │ └─ lib/ │ │ └─ parser.js # Main parser library (public API) │ └─ cli/ │ └─ index.js # CLI implementation └─ test/ │ └─ lib/ │ │ └─ parser.test.js # Parser tests │ └─ cli/ │ │ └─ index.test.js # CLI tests │ └─ __fixtures__/ │ └─ valid-simple.ini │ └─ valid-complete.ini │ └─ valid-global-keys.ini │ └─ valid-multiline.ini │ └─ valid-simple.config │ └─ valid-simple.properties │ └─ edge-cases.ini │ └─ empty.ini │ └─ bin/ │ └─ bin-test.sh # CLI bash tests └─ .agents/ │ └─ parse-fixtures.js # Development agent script └─ docs/ # Documentation └─ package.json # Package metadata └─ jest.config.js # Jest configuration └─ README.md # Project README ``` -------------------------------- ### Configuration with Defaults in JavaScript Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/usage-examples.md Merges default configuration with parsed INI content. Ensures essential settings are always present. ```javascript const defaultConfig = { port: 3000, host: 'localhost', debug: false }; function getConfig(iniContent) { const parsed = parse(iniContent); return { ...defaultConfig, ...simplifySection(parsed.server || {}) }; } function simplifySection(section) { const result = {}; for (const key in section) { result[key] = section[key][0]; } return result; } ``` -------------------------------- ### Custom Type Definitions for Type Safety Source: https://github.com/notfounnd/ini-parser/blob/master/docs/API.md Provides an example of defining custom TypeScript interfaces to achieve better type safety when parsing INI content with specific structures. ```typescript interface AppConfig { database?: { host?: string[]; port?: string[]; name?: string[]; }; server?: { port?: string[]; host?: string[]; }; } const config = parse(content) as AppConfig; // Now you have full type safety for your specific structure ``` -------------------------------- ### INI Type Coercion Example Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/implementation-details.md Highlights that all values parsed from INI files are treated as strings, regardless of their apparent type. Consumers must perform explicit type conversion. ```javascript port: ['8080'] // String, not number enabled: ['true'] // String, not boolean ``` -------------------------------- ### Properties Files Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/parser-rules.md Presents a common format for properties files, often used for build tools and project configurations, using key-value pairs. ```ini sonar.projectKey=my-project sonar.projectName=My Project sonar.sources=src sonar.tests=test sonar.coverage.exclusions=**/*.test.js ``` -------------------------------- ### INI Quoted Value Example Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/implementation-details.md Demonstrates how quoted values are treated as literal strings in the INI parser. This behavior is due to the INI format not standardizing quotes, simplifying the implementation. ```ini quoted="value" # Results in ["'\"value\"'"] ``` -------------------------------- ### Build Configuration with Defaults from INI Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/usage-examples.md Creates a configuration object that merges parsed INI content with provided default values. Allows retrieval of values from INI, defaults, or a fallback. ```javascript const { parse } = require('@notfounnd/ini-parser'); class Config { constructor(iniContent, defaults = {}) { this.data = parse(iniContent); this.defaults = defaults; } get(key, defaultValue = undefined) { // Check global key if (this.data[key] && Array.isArray(this.data[key])) { return this.data[key][0]; } // Check defaults if (key in this.defaults) { return this.defaults[key]; } return defaultValue; } getSection(sectionName) { if (!this.data[sectionName]) { return null; } const section = {}; for (const key in this.data[sectionName]) { section[key] = this.data[sectionName][key][0]; } return section; } getList(key) { if (this.data[key] && Array.isArray(this.data[key])) { return this.data[key]; } return []; } } const iniContent = ` app_name=MyApp debug=true [server] port=8080 host=localhost [paths] includes=/usr/local/bin /usr/bin /bin `; const config = new Config(iniContent, { app_name: 'DefaultApp', debug: false, port: 3000 }); console.log(config.get('app_name')); // 'MyApp' (from INI) console.log(config.get('missing_key', 'default')); // 'default' (from default) console.log(config.getSection('server')); // { port: '8080', host: 'localhost' } console.log(config.getList('paths.includes')); // ['/usr/local/bin', '/usr/bin', '/bin'] ``` -------------------------------- ### Handle Indented Multi-line Values in INI Source: https://github.com/notfounnd/ini-parser/blob/master/docs/PARSER_RULES.md Lines starting with spaces or tabs are treated as continuations of the previous key's value. This is useful for defining multi-line strings or lists. ```ini [section] key= value1 value2 value3 ``` -------------------------------- ### Validate INI File and Get Statistics Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/cli-reference.md Checks the validity of an INI file, including its existence, readability, and successful parsing. It also provides counts of sections and keys found. ```bash ini-parser config.ini --check ``` ```text [ SUCCESS ] File found: config.ini [ SUCCESS ] File readable: yes [ SUCCESS ] Parsed successfully: 3 sections, 12 keys ``` -------------------------------- ### Load Environment-Specific Configuration Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/usage-examples.md Dynamically load configuration files based on the environment (e.g., 'development', 'production'). This pattern helps manage different settings for various deployment stages. ```javascript const fs = require('fs'); const path = require('path'); const { parse } = require('@notfounnd/ini-parser'); function loadAppConfig(env = 'development') { const configPath = path.join(__dirname, `config.${env}.ini`); const content = fs.readFileSync(configPath, 'utf8'); return parse(content); } // Load configuration for specific environment const devConfig = loadAppConfig('development'); const prodConfig = loadAppConfig('production'); // Use environment-specific config if (process.env.NODE_ENV === 'production') { startServer(prodConfig.server.port[0]); } else { startServer(devConfig.server.port[0]); } ``` -------------------------------- ### Combine Parsing Options Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/cli-reference.md Demonstrates combining multiple options to parse an INI file, include metadata, save to a file, and suppress stdout output. ```bash ini-parser config.ini --meta --output meta.json --quiet ``` -------------------------------- ### Importing the Parser Library Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/module-structure.md Shows how to import the main parsing function from the library using CommonJS. ```javascript // CommonJS const { parse } = require('@notfounnd/ini-parser'); // Via main entry point const { parse } = require('@notfounnd/ini-parser/src/lib/parser.js'); ``` -------------------------------- ### Add and Commit Changes Source: https://github.com/notfounnd/ini-parser/blob/master/CONTRIBUTING.md Stage all changes and commit them with a descriptive message following the conventional commit format. ```bash git add . git commit -m "feat: add your feature description" ``` -------------------------------- ### INI Section Declaration Rules Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/parser-rules.md Lines starting with '[' and ending with ']' are recognized as section headers. The content between the brackets is the section name. Invalid formats include missing brackets or empty names. ```ini [database] # Valid [ database ] # Valid — name is "database" [db-server:1] # Valid — name is "db-server:1" [section[nested]] # Valid — name is "section[nested]" [] # Invalid — no name [database # Invalid — missing closing bracket database] # Invalid — missing opening bracket ``` -------------------------------- ### Executable Entry Point for CLI Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/module-structure.md This script is the executable entry point for the command-line interface, invoking the CLI's main function. ```javascript const { runCli } = require('../src/cli/index.js'); runCli(process.argv); ``` -------------------------------- ### Output Format with Metadata Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/INDEX.md This snippet illustrates the output format that includes metadata, such as type information for sections and configuration values. ```javascript { section_name: { type: 'section', content: { key: { type: 'configuration', content: ['value1', 'value2'] } } }, global_key: { type: 'configuration', content: ['value3'] } } ``` -------------------------------- ### Parse INI Content as a Library (Metadata) Source: https://github.com/notfounnd/ini-parser/blob/master/README.md Demonstrates parsing INI content using the library's `parse` function with the `meta: true` option to include metadata in the output. ```javascript const { parse } = require('@notfounnd/ini-parser'); // Example INI content const content = ` # Database configuration [database] host=localhost port=5432 name=myapp [server] port=3000 workers=4 8 16 32 `; // Parse with metadata format const metaResult = parse(content, { meta: true }); console.log(metaResult); // Output includes type information: // { // database: { // type: 'section', // content: { // host: { type: 'configuration', content: ['localhost'] }, // port: { type: 'configuration', content: ['5432'] }, // name: { type: 'configuration', content: ['myapp'] } // } // }, // ... // } ``` -------------------------------- ### Troubleshooting File Not Found or Not Readable Errors Source: https://github.com/notfounnd/ini-parser/blob/master/docs/CLI.md Provides commands to verify file existence, check paths, and inspect permissions when encountering file-related errors. ```bash # Check if file exists ls config.ini ``` ```bash # Use absolute path ini-parser /full/path/to/config.ini ``` ```bash # Check permissions (Unix/Linux) ls -l config.ini # Should show: -rw-r--r-- or similar with 'r' in user permissions ``` -------------------------------- ### Get Configuration Value with Default Source: https://github.com/notfounnd/ini-parser/blob/master/docs/API.md Retrieves a configuration value from a nested structure, providing a default if the key or section is missing. Handles cases where the value might be an array and returns the first element or the default. ```javascript function getConfigValue(config, section, key, defaultValue) { if (!config[section] || !config[section][key]) { return defaultValue; } const value = config[section][key]; return value.length > 0 ? value[0] : defaultValue; } const host = getConfigValue(config, 'database', 'host', 'localhost'); ``` -------------------------------- ### Verify input file content on Windows Source: https://github.com/notfounnd/ini-parser/blob/master/docs/CLI.md Display the content of the input INI file on Windows to verify its validity. ```cmd type config.ini ``` -------------------------------- ### Multi-environment Build Script Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/usage-examples.md A bash script that iterates through different environments, parsing and creating environment-specific JSON configuration files in a 'dist' directory. ```bash #!/bin/bash ENVIRONMENTS=("development" "staging" "production") for env in "${ENVIRONMENTS[@]}"; do echo "Building config for $env..." ini-parser "config.$env.ini" \ -o "dist/config.$env.json" \ --quiet echo "✓ Created dist/config.$env.json" done ``` -------------------------------- ### Run Full Validation Suite Source: https://github.com/notfounnd/ini-parser/blob/master/CONTRIBUTING.md Execute this command to run all validation checks, including formatting, linting, and tests, before committing changes. All checks must pass. ```bash npm run validate ``` -------------------------------- ### Format and Lint Everything Source: https://github.com/notfounnd/ini-parser/blob/master/CONTRIBUTING.md Run both Prettier formatting and ESLint checks on the entire codebase. This command ensures the code is both well-formatted and lint-free. ```bash npm run format ``` -------------------------------- ### npm Script for Parsing Config Source: https://github.com/notfounnd/ini-parser/blob/master/docs/CLI.md Define an npm script in `package.json` to parse a configuration file and output to JSON. ```json { "scripts": { "parse-config": "ini-parser config.ini --output config.json" } } ``` -------------------------------- ### INI Parser Test Directory Structure Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/implementation-details.md Illustrates the standard directory structure for testing the ini-parser project, including unit tests for the parser and CLI, end-to-end bash tests, and fixture files. ```bash test/ ├── lib/parser.test.js # Parser unit tests ├── cli/index.test.js # CLI unit tests ├── bin/bin-test.sh # E2E bash tests └── __fixtures__/ # Test data ├── valid-simple.ini ├── valid-complete.ini ├── edge-cases.ini └── ... ``` -------------------------------- ### Logging Configuration from INI in JavaScript Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/usage-examples.md Configures logging based on INI content, supporting custom levels, formats, and outputs. Uses 'meta: true' for structured parsing. ```javascript const { parse } = require('@notfounnd/ini-parser'); function configureLogging(iniContent) { const config = parse(iniContent, { meta: true }); if (config.logging?.type === 'section') { const logConfig = config.logging.content; return { level: logConfig.level?.content[0] || 'info', format: logConfig.format?.content[0] || 'json', outputs: logConfig.outputs?.content || ['stdout'], timestamp: logConfig.timestamp?.content[0] === 'true' }; } return { level: 'info', format: 'json', outputs: ['stdout'] }; } ``` -------------------------------- ### CLI Usage Source: https://github.com/notfounnd/ini-parser/blob/master/README.md Command-line interface for parsing INI files. Allows specifying input files, output files, and various options for processing and validation. ```APIDOC ## CLI Usage ### Syntax ```bash ini-parser [options] ``` ### Arguments - ``: Path to INI file (required) ### Options | Flag | Alias | Description | |------|-------|-------------| | `--output ` | `-o` | Save output to JSON file | | `--meta` | - | Return metadata format with type information | | `--quiet` | `-q` | Suppress stdout output when saving to file | | `--check` | - | Check INI file and display statistics without full output | | `--version` | `-v` | Output the current version | | `--help` | `-h` | Display help information | ### Exit Codes - `0`: Success - `1`: File error (not found, not readable, parse error) - `2`: Argument error (invalid arguments, missing file) ### Examples ```bash # Basic parsing ini-parser config.ini # Save to file ini-parser config.ini -o output.json # Validate file ini-parser config.ini --check # Output: # [ SUCCESS ] File found: config.ini # [ SUCCESS ] File readable: yes # [ SUCCESS ] Parsed successfully: 3 sections, 12 keys # Quiet mode (save without stdout) ini-parser config.ini --output data.json --quiet # Metadata format ini-parser config.ini --meta --output meta.json ``` ``` -------------------------------- ### Equivalent Splitting for Values with Spaces in INI Source: https://github.com/notfounnd/ini-parser/blob/master/docs/PARSER_RULES.md This demonstrates an equivalent representation for values with spaces, using indented lines to achieve the same splitting behavior as values on a single line. ```ini params= timeout=30 retry=3 ``` -------------------------------- ### INI Key-Value Pair Parsing Source: https://github.com/notfounnd/ini-parser/blob/master/docs/PARSER_RULES.md Illustrates the parsing of key-value pairs, including handling of spaces around the equals sign. ```ini host=localhost port = 5432 name = test ``` ```json { "host": ["localhost"], "port": ["5432"], "name": ["test"] } ``` -------------------------------- ### Basic CLI Usage Source: https://github.com/notfounnd/ini-parser/blob/master/docs/CLI.md The ini-parser command takes a file path as its primary argument. Options can be appended for specific actions like outputting to a file, checking the file's validity, or displaying version and help information. ```bash ini-parser [options] ``` ```bash ini-parser ``` ```bash ini-parser --output ``` ```bash ini-parser --check ``` ```bash ini-parser --version ``` ```bash ini-parser --help ``` -------------------------------- ### No Splitting Cases for Values Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/parser-rules.md Demonstrates scenarios where values are not split into array elements, such as indented or unindented continuation lines, values without spaces, and inline comments. ```ini path=/usr/bin # ['/usr/bin'] (no space, no split) indented= /usr/local/bin # ['/usr/local/bin'] /usr/bin # ['/usr/bin'] ``` -------------------------------- ### Pipe INI Parser Output to jq Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/usage-examples.md Demonstrates piping the JSON output of ini-parser to the 'jq' command for advanced filtering and pretty-printing. ```bash # Extract specific section using jq ini-parser config.ini | jq '.database' # Pretty-print with jq ini-parser config.ini | jq '.' # Filter and process ini-parser config.ini | jq '.database.host[0]' ``` -------------------------------- ### Using with TypeScript Projects Source: https://github.com/notfounnd/ini-parser/blob/master/docs/API.md Illustrates how to import and use the parse function directly within a TypeScript project, with type inference for the returned configuration object. ```typescript import { parse } from '@notfounnd/ini-parser'; const content: string = ` [db] host=localhost `; const config = parse(content); // config is inferred as 'object' ``` -------------------------------- ### Resolving Cannot Write to File Errors Source: https://github.com/notfounnd/ini-parser/blob/master/docs/CLI.md Provides commands to create directories and verify permissions to resolve issues when the CLI cannot write output files. ```bash # Create output directory mkdir -p output/ # Verify directory exists ls -d output/ # Try again ini-parser config.ini --output output/result.json ``` -------------------------------- ### Exporting the CLI Run Function Source: https://github.com/notfounnd/ini-parser/blob/master/_autodocs/module-structure.md This code snippet shows how the main CLI entry point function is exported from the CLI module. ```javascript module.exports = { runCli }; ```