package Mnemosyne::Config; use strict; use warnings; # Loads mnemosyne.conf (INI-style) and exposes a simple accessor. # Usage: # my $cfg = Mnemosyne::Config->new('/path/to/mnemosyne.conf'); # my $token = $cfg->get('bot', 'token'); # my $href = $cfg->section('bot'); # all keys in [bot] sub new { my ($class, $path) = @_; die "Config file not specified\n" unless defined $path; die "Config file not found: $path\n" unless -f $path; my $self = bless { _path => $path, _data => {} }, $class; $self->_parse; return $self; } sub _parse { my ($self) = @_; open my $fh, '<', $self->{_path} or die "Cannot open config '$self->{_path}': $!\n"; my $section = '_default'; while (my $line = <$fh>) { chomp $line; $line =~ s/\s*#.*$//; # strip inline comments $line =~ s/^\s+|\s+$//g; # trim next unless length $line; if ($line =~ /^\[(\w+)\]$/) { $section = lc $1; } elsif ($line =~ /^([\w_]+)\s*=\s*(.*)$/) { my ($key, $val) = (lc $1, $2); $val =~ s/\s+$//; $self->{_data}{$section}{$key} = $val; } else { warn "Config: unrecognised line in $self->{_path}: $line\n"; } } close $fh; } sub get { my ($self, $section, $key) = @_; $section = lc $section; $key = lc $key; return $self->{_data}{$section}{$key}; } sub section { my ($self, $section) = @_; return { %{ $self->{_data}{lc $section} // {} } }; } # Returns the list of allowed chat IDs as an array ref (parsed from the # comma-separated 'allowed_chat_ids' value in [bot]). sub allowed_chat_ids { my ($self) = @_; my $raw = $self->get('bot', 'allowed_chat_ids') // ''; my @ids = grep { /^\d+$/ } map { s/^\s+|\s+$//gr } split /,/, $raw; return \@ids; } 1;