Update a configuration file: Difference between revisions

Content added Content deleted
(add Ruby)
Line 560: Line 560:
$cfg set numberofstrawberries 62000
$cfg set numberofstrawberries 62000
$cfg save</lang>
$cfg save</lang>

{{header|TXR}}
{{works with|TXR git head}}

This is a general solution which implements a command-line tool for updating the config file.
Omitted are the trivial steps for writing the configuration back into the same file; the final result is output
on standard output.

The first argument is the name of the config file. The remaining arguments are of this form:

<pre>
VAR # define or update VAR as a true-valued boolean
VAR= # ensure "; VAR" in the config file.
VAR=VAL # ensure "VAR VAL" in the config file
</pre>

<lang txr>@(next :args)
@configfile
@(maybe)
@ (next configfile)
@ (collect)
@config
@ (end)
@(end)
@(collect)
@ (cases)
@option=
@ (output :into new_opt_line)
; @option
@ (end)
@ (or)
@option=@val
@ (output :into new_opt_line)
@option @val
@ (end)
@ (or)
@option
@ (output :into new_opt_line)
@option
@ (end)
@ (end)
@ (next :var config)
@ (local new_config)
@ (bind new_config ())
@ (collect :vars ((opt_there "")))
@ (block)
@ (cases)
@ (cases)
@{line /[ \t]*/}
@ (or)
@{line /#.*/}
@ (end)
@ (output :append :into new_config)
@line
@ (end)
@ (accept)
@ (or)
@ (maybe)
; @opt_there
@ (or)
@opt_there @(skip)
@ (or)
@opt_there
@ (or)
@original_line
@ (end)
@ (end)
@ (cases)
@ (bind opt_there option)
@ (output :append :into new_config)
@new_opt_line
@ (end)
@ (or)
@ (output :append :into new_config)
@original_line
@ (end)
@ (end)
@ (end)
@ (cases)
@ (bind opt_there option)
@ (or)
@ (output :append :into new_config)
@new_opt_line
@ (end)
@ (end)
@ (set config new_config)
@(end)
@(output)
@ (repeat)
@config
@ (end)
@(end)</lang>

Sample invocation:

<pre>$ txr configfile2.txr configfile NEEDSPEELING= SEEDSREMOVED NUMBEROFBANANAS=1024 NUMBEROFSTRAWBERRIES=62000
# This is a configuration file in standard configuration file format
#
# Lines begininning with a hash or a semicolon are ignored by the application
# program. Blank lines are also ignored by the application program.

# The first word on each non comment line is the configuration option.
# Remaining words or numbers on the line are configuration parameter
# data fields.

# Note that configuration option names are not case sensitive. However,
# configuration parameter data is case sensitive and the lettercase must
# be preserved.

# This is a favourite fruit
FAVOURITEFRUIT banana

# This is a boolean that should be set
; NEEDSPEELING

# This boolean is commented out
SEEDSREMOVED

# How many bananas we have
NUMBEROFBANANAS 1024
NUMBEROFSTRAWBERRIES 62000</pre>



{{omit from|Openscad}}
{{omit from|Openscad}}