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. The directory isn't specified here.
387
388   global_file
389       Return the string "/etc/confname", the absolute name of the system-wide
390       configuration file with name "confname".
391
392   user_file
393       Return a string containing the path to a configuration file in the
394       current user's home directory with filename "confname".
395
396   load_dirs
397       Parameters:
398
399           '/path/to/look/in/'
400
401       Load the configuration file with the filename "dir_file" in the current
402       working directory into the memory or, if there is no config matching
403       "dir_file" in the current working directory, walk up the directory tree
404       until one is found. (No error is thrown if none is found.) If an
405       optional path is passed in, that directory will be used as the base
406       directory instead of the working directory.
407
408       You'll want to use "load_file" to load config files from your
409       overridden version of this subroutine.
410
411       Returns nothing of note.
412

OTHER METHODS

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

DIFFERENCES FROM GIT-CONFIG

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

BUGS

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

SEE ALSO

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

LICENSE

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

AUTHORS

648       Alex Vandiver <alexmv@bestpractical.com>, Christine Spang
649       <spang@bestpractical.com>
650
651
652
653perl v5.30.0                      2019-07-26                Config::GitLike(3)
Impressum