1Config::GitLike(3)    User Contributed Perl Documentation   Config::GitLike(3)
2
3
4

NAME

6       Config::GitLike - git-compatible config file parsing
7

SYNOPSIS

9       This module parses git-style config files, which look like this:
10
11           [core]
12               repositoryformatversion = 0
13               filemode = true
14               bare = false
15               logallrefupdates = true
16           [remote "origin"]
17               url = spang.cc:/srv/git/home.git
18               fetch = +refs/heads/*:refs/remotes/origin/*
19           [another-section "subsection"]
20               key = test
21               key = multiple values are OK
22               emptyvalue =
23               novalue
24
25       Code that uses this config module might look like:
26
27           use Config::GitLike;
28
29           # just load a specific file
30           my $data = Config::GitLike->load_file("~/.fooconf");
31
32           # or use the object interface to load /etc/config, ~/.config, and
33           # `pwd`/.config
34           my $c = Config::GitLike->new(confname => 'config');
35
36           $c->get( key => 'section.name' );
37           # make the return value a Perl true/false value
38           $c->get( key => 'core.filemode', as => 'bool' );
39
40           # replace the old value
41           $c->set(
42               key => 'section.name',
43               value => 'val1',
44               filename => '/home/user/.config',
45           );
46
47           # make this key have multiple values rather than replacing the
48           # old value
49           $c->set(
50               key => 'section.name',
51               value => 'val2',
52               filename => '/home/user/.config',
53               multiple => 1,
54           );
55
56           # replace all occurrences of the old value for section.name with a new one
57           $c->set(
58               key => 'section.name',
59               value => 'val3',
60               filename => '/home/user/.config',
61               multiple => 1,
62               replace_all => 1,
63           );
64
65           # make sure to reload the config files before reading if you've set
66           # any variables!
67           $c->load;
68
69           # get only the value of 'section.name' that matches '2'
70           $c->get( key => 'section.name', filter => '2' );
71           $c->get_all( key => 'section.name' );
72           # prefixing a search regexp with a ! negates it
73           $c->get_regexp( key => '!na' );
74
75           $c->rename_section(
76               from => 'section',
77               to => 'new-section',
78               filename => '/home/user/.config'
79           );
80
81           $c->remove_section(
82               section => 'section',
83               filename => '/home/user/.config'
84           );
85
86           # unsets all instances of the given key
87           $c->set( key => 'section.name', filename => '/home/user/.config' );
88
89           my %config_vals = $config->dump;
90           # string representation of config data
91           my $str = $config->dump;
92           # prints rather than returning
93           $config->dump;
94

DESCRIPTION

96       This module handles interaction with configuration files of the style
97       used by the version control system Git. It can both parse and modify
98       these files, as well as create entirely new ones.
99
100       You only need to know a few things about the configuration format in
101       order to use this module. First, a configuration file is made up of
102       key/value pairs. Every key must be contained in a section. Sections can
103       have subsections, but they don't have to. For the purposes of setting
104       and getting configuration variables, we join the section name,
105       subsection name, and variable name together with dots to get a key name
106       that looks like "section.subsection.variable". These are the strings
107       that you'll be passing in to "key" arguments.
108
109       Configuration files inherit from each other. By default,
110       "Config::GitLike" loads data from a system-wide configuration file, a
111       per-user configuration file, and a per-directory configuration file,
112       but by subclassing and overriding methods you can obtain any
113       combination of configuration files. By default, configuration files
114       that don't exist are just skipped.
115
116       See
117       <http://www.kernel.org/pub/software/scm/git/docs/git-config.html#_configuration_file>
118       for details on the syntax of git configuration files. We won't waste
119       pixels on the nitty gritty here.
120
121       While the behavior of a couple of this module's methods differ slightly
122       from the "git config" equivalents, this module can read any config file
123       written by git. The converse is usually true, but only if you don't
124       take advantage of this module's increased permissiveness when it comes
125       to key names. (See "DIFFERENCES FROM GIT-CONFIG" for details.)
126
127       This is an object-oriented module using Moo. All subroutines are object
128       method calls.
129
130       A few methods have parameters that are always used for the same
131       purpose:
132
133   Filenames
134       All methods that change things in a configuration file require a
135       filename to write to, via the "filename" parameter. Since a
136       "Config::GitLike" object can be working with multiple config files that
137       inherit from each other, we don't try to figure out which one to write
138       to automatically and let you specify instead.
139
140   Casting
141       All get and set methods can make sure the values they're returning or
142       setting are valid values of a certain type: "bool", "int", "num", or
143       "bool-or-int" (or at least as close as Perl can get to having these
144       types). Do this by passing one of these types in via the "as"
145       parameter. The set method, if told to write bools, will always write
146       "true" or "false" (not anything else that "cast" considers a valid
147       bool).
148
149       Methods that are told to cast values will throw exceptions if the
150       values they're trying to cast aren't valid values of the given type.
151
152       See the "cast" method documentation for more on what is considered
153       valid for each type.
154
155   Filtering
156       All get and set methods can filter what values they return via their
157       "filter" parameter, which is expected to be a string that is a valid
158       regex. If you want to filter items OUT instead of IN, you can prefix
159       your regex with a ! and that will do the trick.
160
161       Now, on the the methods!
162

MAIN METHODS

164       There are the methods you're likely to use the most.
165
166   new( confname => 'config', encoding => 'UTF-8' )
167       Create a new configuration object with the base config name "confname".
168       If you are interested simply in loading one specific file, and not in
169       automatically loading a global file, a per-user file, and a per-
170       directory file, see "load_file", below.
171
172       "confname" is used to construct the filenames that will be loaded; by
173       default, these are "/etc/confname" (global configuration file),
174       "~/.confname" (user configuration file), and "<Cwd"/.confname>
175       (directory configuration file).
176
177       You can override these defaults by subclassing "Config::GitLike" and
178       overriding the methods "global_file", "user_file", and "dir_file". (See
179       "METHODS YOU MAY WISH TO OVERRIDE" for details.)
180
181       If you wish to enforce only being able to read/write config files that
182       git can read or write, pass in "compatible => 1" to this constructor.
183       The default rules for some components of the config file are more
184       permissive than git's (see "DIFFERENCES FROM GIT-CONFIG").
185
186       If you know that your Git config files are encoded with a known
187       character encoding, pass in "encoding => $encoding" to specify the name
188       of the encoding. Config::GitLike will then properly serialize and
189       deserialize the files with that encoding.  Note that configutation
190       files written with "git config" are usually, but are not required to
191       be, in UTF-8.
192
193   confname
194       The configuration filename that you passed in when you created the
195       "Config::GitLike" object. You can change it if you want by passing in a
196       new name (and then reloading via "load").
197
198   load
199       This method is usually called implicitly on the first "get", "get_all",
200       "get_regex", or "dump" call used, and is only necessary if you want to
201       explicitly reload the data.
202
203       Load the global, local, and directory configuration file with the
204       filename "confname"(if they exist). Configuration variables loaded
205       later override those loaded earlier, so variables from the directory
206       configuration file have the highest precedence.
207
208       Pass in an optional path, and it will be passed on to "load_dirs"
209       (which loads the directory configuration file(s)).
210
211       Returns a hash copy of all loaded configuration data stored in the
212       module after the files have been loaded, or a hashref to this hash in
213       scalar context.
214
215   config_files
216       An array reference containing the absolute filenames of all config
217       files that are currently loaded, in the order they were loaded.
218
219   get
220       Parameters:
221
222           key => 'sect.subsect.key'
223           as => 'int'
224           human => 1
225           filter => '!foo'
226
227       Return the config value associated with "key" cast as an "as".
228
229       The "key" option is required (will return undef if unspecified); the
230       "as" amd "human" options are not (see cast for their meaning). Sections
231       and subsections are specified in the key by separating them from the
232       key name with a "." character. Sections, subsections, and keys may all
233       be quoted (double or single quotes).
234
235       If "key" doesn't exist in the config, or has no values which match the
236       filter, undef is returned. Dies with the exception "Multiple values" if
237       the given key has more than one value associated with it which match
238       the filter. (Use "get_all" to retrieve multiple values.)
239
240       Calls "load" if it hasn't been done already. Note that if you've run
241       any "set" calls to the loaded configuration files since the last time
242       they were loaded, you MUST call "load" again before getting, or the
243       returned configuration data may not match the configuration variables
244       on-disk.
245
246   get_all
247       Parameters:
248
249           key => 'section.sub'
250           as => 'int'
251           human => 1
252           filter => 'regex'
253
254       Like "get" but does not fail if the number of values for the key is not
255       exactly one.
256
257       Returns a list of values (or an arrayref in scalar context).
258
259   get_regexp
260       Parameters:
261
262           key => 'regex'
263           as => 'bool'
264           human => 1
265           filter => 'regex'
266
267       Similar to "get_all" but searches for values based on a key regex.
268
269       Returns a hash of name/value pairs (or a hashref in scalar context).
270
271   dump
272       In scalar context, return a string containing all configuration data,
273       sorted in ASCII order, in the form:
274
275           section.key=value
276           section2.key=value
277
278       If called in void context, this string is printed instead.
279
280       In list context, returns a hash containing all the configuration data.
281
282   set
283       Parameters:
284
285           key => 'section.name'
286           value => 'bar'
287           filename => File::Spec->catfile(qw/home user/, '.'.$config->confname)
288           filter => 'regex'
289           as => 'bool'
290           multiple => 1
291           replace_all => 1
292
293       Set the key "foo" in the configuration section "section" to the value
294       "bar" in the given filename.
295
296       Replace "key"'s value if "key" already exists.
297
298       To unset a key, pass in "key" but not "value".
299
300       Returns true on success.
301
302       If you need to have a . character in your variable name, you can
303       surround the name with quotes (single or double): "key =&gt
304       'section."foo.bar.com"'" Don't do this unless you really have to.
305
306       multiple values
307
308       By default, set will replace the old value rather than giving a key
309       multiple values. To override this, pass in "multiple => 1". If you want
310       to replace all instances of a multiple-valued key with a new value, you
311       need to pass in "replace_all => 1" as well.
312
313   group_set( $filename, $array_ref )
314       Same as "set", but set a group of variables at the same time without
315       writing to disk separately for each.
316
317       $array_ref contains a list of hash references which are essentially
318       hashes of arguments to "set", excluding the $filename argument since
319       that is specified separately and the same file is used for all
320       variables to be set at once.
321
322   rename_section
323       Parameters:
324
325           from => 'name.subname'
326           to => 'new.subname'
327           filename => '/file/to/edit'
328
329       Rename the section existing in "filename" given by "from" to the
330       section given by "to".
331
332       Throws an exception "No such section" if the section in "from" doesn't
333       exist in "filename".
334
335       If no value is given for "to", the section is removed instead of
336       renamed.
337
338       Returns true on success, false if "filename" didn't exist and thus the
339       rename did nothing.
340
341   remove_section
342       Parameters:
343
344           section => 'section.subsection'
345           filename => '/file/to/edit'
346
347       Just a convenience wrapper around "rename_section" for readability's
348       sake.  Removes the given section (which you can do by renaming to
349       nothing as well).
350
351   add_comment
352       Parameters:
353
354            comment   => "Begin editing here\n and then stop",
355            filename  => '/file/to/edit'
356            indented  => 1,
357            semicolon => 0,
358
359       Add a comment to the specified configuration file. The "comment" and
360       "filename" parameters are required. Comments will be added to the file
361       with "# " at the begnning of each line of the comment. Pass a true
362       value to "semicolon" if you'd rather they start with "; ". If your
363       comments are indented with leading white space, and you want that white
364       space to appear in front of the comment character, rather than after,
365       pass a true value to "indented".
366
367   cascade( $bool )
368       Gets or sets if only the deepest configuration file in a directory tree
369       is loaded, or if all of them are loaded, shallowest to deepest.
370       Alternately, "cascade => 1" can be passed to "new".
371
372   origins
373       Returns a hash mapping each config key with the file it was loaded
374       from.
375

METHODS YOU MAY WISH TO OVERRIDE

377       If your application's configuration layout is different from the
378       default, e.g.  if its home directory config files are in a directory
379       within the home directory (like "~/.git/config") instead of just dot-
380       prefixed, override these methods to return the right directory names.
381       For fancier things like altering precedence, you'll need to override
382       "load" as well.
383
384   dir_file
385       Return a string containing the path to a configuration file with the
386       name "confname" in a directory.  Called with no arguments, returns the
387       path for a generic directory; if called with a directory as an
388       argument, returns the path for that directory.
389
390   global_file
391       Return the string "/etc/confname", the absolute name of the system-wide
392       configuration file with name "confname".
393
394   user_file
395       Return a string containing the path to a configuration file in the
396       current user's home directory with filename "confname".
397
398   load_dirs
399       Parameters:
400
401           '/path/to/look/in/'
402
403       Load the configuration file with the filename "dir_file" in the current
404       working directory into the memory or, if there is no config matching
405       "dir_file" in the current working directory, walk up the directory tree
406       until one is found. (No error is thrown if none is found.) If an
407       optional path is passed in, that directory will be used as the base
408       directory instead of the working directory.
409
410       You'll want to use "load_file" to load config files from your
411       overridden version of this subroutine.
412
413       Returns nothing of note.
414

OTHER METHODS

416       These are mostly used internally in other methods, but could be useful
417       anyway.
418
419   load_global
420       If a global configuration file with the absolute name given by
421       "global_file" exists, load its configuration variables into memory.
422
423       Returns the current contents of all the loaded configuration variables
424       after the file has been loaded, or undef if no global config file is
425       found.
426
427   load_user
428       If a configuration file with the absolute name given by "user_file"
429       exists, load its config variables into memory.
430
431       Returns the current contents of all the loaded configuration variables
432       after the file has been loaded, or undef if no user config file is
433       found.
434
435   load_file( $filename )
436       Takes a string containing the path to a file, opens it if it exists,
437       loads its config variables into memory, and returns the currently
438       loaded config variables (a hashref).
439
440       This method can also be called as a class method, which will die if the
441       file cannot be read.  If called as an instance method, returns undef on
442       failure.
443
444       This method may also be passed additional key-value parameters which
445       control how the file is loaded:
446
447       silent
448           Defaults to off; if set, merely returns instead of die'ing if the
449           file cannot be found or read.
450
451       includes
452           Defaults to on; if passed a false value, ignores the "include"
453           directive.
454
455       force
456           Defaults to off; if set, will re-load a file even if it was
457           previously loaded.
458
459   parse_content
460       Parameters:
461
462           content => 'str'
463           callback => sub {}
464           error => sub {}
465
466       Parses the given content and runs callbacks as it finds valid
467       information.
468
469       Returns undef on success and error($content) (the original content) on
470       failure.
471
472       "callback" is called like:
473
474           callback(section => $str, offset => $num, length => $num, name => $str, value => $str)
475
476       "name" and "value" may be omitted if the callback is not being called
477       on a key/value pair, or if it is being called on a key with no value.
478
479       "error" is called like:
480
481           error( content => $content, offset => $offset )
482
483       Where "offset" is the point in the content where the parse error
484       occurred.
485
486       If you need to use this method, you might be interested in
487       "error_callback" as well.
488
489   error_callback
490       Parameters:
491
492           content => 'str'
493           offset => 45
494           filename => '/foo/bar/.baz'
495
496       Made especially for passing to "parse_content", passed through the
497       "error" parameter like this:
498
499           error => sub {
500               error_callback( @_, filename => '/file/you/were/parsing' )
501           }
502
503       It's used internally wherever "parse_content" is used and will throw an
504       exception with a useful message detailing the line number, position on
505       the line, and contents of the bad line; if you find the need to use
506       "parse_content" elsewhere, you may find it useful as well.
507
508   include ( $name )
509       When reading configuration files, Git versions 1.7.10 and later parse
510       the "include.path" key as a directive to include an additional
511       configuration file.  This option controls the equivalent behavior;
512       setting it to a false value will disable inclusion, and any true value
513       will be taken as the name of the configuration parameter which controls
514       inclusion.  Defaults to "include.path", as Git does.
515
516   set_multiple( $name )
517       Mark the key string $name as containing multiple values.
518
519       Returns nothing.
520
521   is_multiple( $name )
522       Return a true value if the key string $name contains multiple values;
523       false otherwise.
524
525   define
526       Parameters:
527
528           section => 'str'
529           name => 'str'
530           value => 'str'
531
532       Given a section, a key name, and a value, store this information in
533       memory in the config object.
534
535       Returns the value that was just defined on success, or undef if no name
536       and section were given and thus the key cannot be defined.
537
538   cast
539       Parameters:
540
541           value => 'foo'
542           as => 'int'
543           human => 1
544
545       Return "value" cast into the type specified by "as".
546
547       Valid values for "as" are "bool", "int", "num", or "bool-or-num". For
548       "bool", "true", "yes", "on", 1, and undef are translated into a true
549       value (for Perl); anything else is false. Specifying a true value for
550       the "human" argument will get you a human-readable 'true' or 'false'
551       rather than a value that plays along with Perl's definition of
552       truthiness (0 or 1).
553
554       For "int"s and "num"s, if "value" ends in "k", "m", or "g", it will be
555       multiplied by 1024, 1048576, and 1073741824, respectively, before being
556       returned. "int"s are truncated after being multiplied, if they have a
557       decimal portion.
558
559       "bool-or-int", as you might have guessed, gives you either a bool or an
560       int depending on which one applies.
561
562       If "as" is unspecified, "value" is returned unchanged.
563
564   format_section
565       Parameters:
566
567           section => 'section.subsection'
568           base => 1
569
570       Return a string containing the section/subsection header, formatted as
571       it should appear in a config file. If "bare" is true, the returned
572       value is not followed be a newline.
573
574   format_definition
575       Parameters:
576
577           key => 'str'
578           value => 'str'
579           bare => 1
580
581       Return a string containing the key/value pair as they should be printed
582       in the config file. If "bare" is true, the returned value is not tab-
583       indented nor followed by a newline.
584
585   canonical_case( $name )
586       Given a full key name, returns the canonical name of the key; this is
587       the key with the section and name lower-cased; the subsection is left
588       as-is.
589
590   original_key( $name )
591       Given a full key name, returns the key as it was last loaded from the
592       file, retaining what ever upper/lower case was used.  Note that for
593       multiple-valued keys, this returns an array reference of key names, as
594       each definition may have been provided in a different choice of case.
595

DIFFERENCES FROM GIT-CONFIG

597       This module does the following things differently from git-config:
598
599       We are much more permissive about valid key names and section names.
600       For variables, instead of limiting variable names to alphanumeric
601       characters and -, we allow any characters except for = and newlines,
602       including spaces as long as they are not leading or trailing, and . as
603       long as the key name is quoted. For sections, any characters but
604       whitespace, [], and " are allowed.  You can enforce reading/writing
605       only git-compatible variable names and section headers by passing
606       "compatible => 1" to the constructor.
607
608       When replacing variable values and renaming sections, we merely use a
609       substring replacement rather than writing out new lines formatted in
610       the default manner for new lines. Git's replacement/renaming (as of
611       1.6.3.2) is currently buggy and loses trailing comments and variables
612       that are defined on the same line as a section being renamed. Our
613       method preserves original formatting and surrounding information.
614
615       We also allow the 'num' type for casting, since in many cases we might
616       want to be more lenient on numbers.
617
618       We truncate decimal numbers that are cast to "int"s, whereas Git just
619       rejects them.
620
621       We don't support NUL-terminating output (the --null flag to git-
622       config). Who needs it?
623
624       Git only supports reading UNIX- and DOS-style newlines ("\n" and
625       "\r\n"), and always uses "\n" when modifying files.  We also support
626       reading Mac-style newlines ("\r"), and write updates to files using the
627       same newlines as they were read with.
628

BUGS

630       If you find any bugs in this module, report them at:
631
632         http://rt.cpan.org/
633
634       Include the version of the module you're using and any relevant
635       problematic configuration files or code snippets.
636

SEE ALSO

638       <http://www.kernel.org/pub/software/scm/git/docs/git-config.html#_configuration_file>,
639       Config::GitLike::Git, <http://syncwith.us/> ("Config::GitLike" is used
640       in Prophet/SD and provides a working example)
641

LICENSE

643       This program is free software; you may modify and/or redistribute it
644       under the same terms as Perl itself.
645
647       Copyright 2010 Best Practical Solutions, LLC
648

AUTHORS

650       Alex Vandiver <alexmv@bestpractical.com>, Christine Spang
651       <spang@bestpractical.com>
652
653
654
655perl v5.36.0                      2023-01-20                Config::GitLike(3)
Impressum