pax_global_header00006660000000000000000000000064141253047610014515gustar00rootroot0000000000000052 comment=cbd9eff5fdd6bbf2947cf58207a96fe464bd839e config-file-release-1.2.1/000077500000000000000000000000001412530476100153165ustar00rootroot00000000000000config-file-release-1.2.1/.github/000077500000000000000000000000001412530476100166565ustar00rootroot00000000000000config-file-release-1.2.1/.github/workflows/000077500000000000000000000000001412530476100207135ustar00rootroot00000000000000config-file-release-1.2.1/.github/workflows/main.yml000066400000000000000000000013361412530476100223650ustar00rootroot00000000000000name: Main workflow on: pull_request: push: schedule: # Prime the caches every Monday - cron: 0 1 * * MON jobs: build: strategy: fail-fast: false matrix: os: - macos-latest - ubuntu-latest - windows-latest ocaml-compiler: - 4.02.x - 4.13.x runs-on: ${{ matrix.os }} steps: - name: Checkout code uses: actions/checkout@v2 - name: Use OCaml ${{ matrix.ocaml-compiler }} uses: ocaml/setup-ocaml@v2 with: ocaml-compiler: ${{ matrix.ocaml-compiler }} - run: opam install . --deps-only --with-test - run: opam exec -- dune build - run: opam exec -- dune runtest config-file-release-1.2.1/CHANGES.md000066400000000000000000000033761412530476100167210ustar00rootroot00000000000000## release-1.2.1 (2021-09-30) Antonin Décimo * build: switch build system to Dune * build: use cppo and camlp4 for pre-processing * fix: fix warnings ## release-1.2 (2014-03-20) Maxence Guesdon ### 2014-02-11 Maxence Guesdon * add: compile and install .cmxs files ### 2013-02-25 Maxence Guesdon * add: new read_string method, thanks to Armaël Guéneau ## release-1.1 (2012-04-11) Maxence Guesdon * add: use findlib to install ### 2004-11-19 Maxence Guesdon * add: .headache_config ### 2004-11-9 Jean-Baptiste Rouquier * config_file.mli, config_file.ml: removed color_cp (could be string or int) * Minors changes in the documentation. * Header of config_file.ml (TODO and Changelog). ### 2004-11-03 Maxence Guesdon * mod: installation ok * add: configure.in, configure, master.Makefile.in, gpl_header * fix: Makefile ### 2004-09-10 Jean-Baptiste Rouquier * config_file.ml: renamed group#load into group#read. * Customizable behaviour (log file for instance) on error in configuration files. * Configuration file created if it doesn't exist. * Bugfix in Raw.of_file. ### 2004-08-20 Jean-Baptiste Rouquier * config_file.ml: object rewrite, no more Obj.magic. * Lots of comments added (also in config_file.mli). * Interface to module Arg handles not only "simple" configuration parameters, ie also handles configuration parameters inside a Section. * Use of module Format to prettier print the config file and the command_line_args * Use of module Queue to keep the cps in the order they were added to the group. config-file-release-1.2.1/LICENSE000066400000000000000000000612751412530476100163360ustar00rootroot00000000000000 GNU LIBRARY GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1991 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the library GPL. It is numbered 2 because it goes with version 2 of the ordinary GPL.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Library General Public License, applies to some specially designated Free Software Foundation software, and to any other libraries whose authors decide to use it. You can use it for your libraries, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library, or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link a program with the library, you must provide complete object files to the recipients so that they can relink them with the library, after making changes to the library and recompiling it. And you must show them these terms so they know their rights. Our method of protecting your rights has two steps: (1) copyright the library, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the library. Also, for each distributor's protection, we want to make certain that everyone understands that there is no warranty for this free library. If the library is modified by someone else and passed on, we want its recipients to know that what they have is not the original version, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that companies distributing free software will individually obtain patent licenses, thus in effect transforming the program into proprietary software. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License, which was designed for utility programs. This license, the GNU Library General Public License, applies to certain designated libraries. This license is quite different from the ordinary one; be sure to read it in full, and don't assume that anything in it is the same as in the ordinary license. The reason we have a separate public license for some libraries is that they blur the distinction we usually make between modifying or adding to a program and simply using it. Linking a program with a library, without changing the library, is in some sense simply using the library, and is analogous to running a utility program or application program. However, in a textual and legal sense, the linked executable is a combined work, a derivative of the original library, and the ordinary General Public License treats it as such. Because of this blurred distinction, using the ordinary General Public License for libraries did not effectively promote software sharing, because most developers did not use the libraries. We concluded that weaker conditions might promote sharing better. However, unrestricted linking of non-free programs would deprive the users of those programs of all benefit from the free status of the libraries themselves. This Library General Public License is intended to permit developers of non-free programs to use free libraries, while preserving your freedom as a user of such programs to change the free libraries that are incorporated in them. (We have not seen how to achieve this as regards changes in header files, but we have achieved it as regards changes in the actual functions of the Library.) The hope is that this will lead to faster development of free libraries. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, while the latter only works together with the library. Note that it is possible for a library to be covered by the ordinary General Public License rather than by this special one. GNU LIBRARY GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Library General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also compile or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. c) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. d) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Library General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! config-file-release-1.2.1/README.md000066400000000000000000000011451412530476100165760ustar00rootroot00000000000000# Config_file ## What is Config_file Config_file is a library used to manage the configuration file(s) of an application. You simply define your options and it performs the loading and saving of the options in a file. You can also use the same options in the command line. ## Installation Config_file can be installed with opam: opam install config-file If you don't use opam consult the [opam](config-file.opam) file for build instructions. ## Documentation The documentation and API reference is automatically generated by from the source interfaces. It can be consulted via `odig doc config-file`. config-file-release-1.2.1/config-file.opam000066400000000000000000000023141412530476100203560ustar00rootroot00000000000000# This file is generated by dune, edit dune-project instead opam-version: "2.0" synopsis: "A library used to manage configuration files" description: """ Config_file is a library used to manage the configuration file(s) of an application. You simply define your options and it performs the loading and saving of the options in a file. You can also use the same options in the command line. """ maintainer: ["Antonin Décimo "] authors: [ "Antonin Décimo " "Fabrice Le Fessant " "Maxence Guesdon " "Jean-Baptiste Rouquier " ] license: "LGPL-2.0-or-later" homepage: "https://github.com/MisterDA/config-file" bug-reports: "https://github.com/MisterDA/config-file/issues" depends: [ "dune" {>= "2.9"} "ocaml" {>= "4.02"} "camlp4" {build} "cppo" {build} "odoc" {with-doc} ] build: [ ["dune" "subst"] {dev} [ "dune" "build" "-p" name "-j" jobs "--promote-install-files=false" "@install" "@runtest" {with-test} "@doc" {with-doc} ] ["dune" "install" "-p" name "--create-install-files" name] ] dev-repo: "git+https://github.com/MisterDA/config-file.git" config-file-release-1.2.1/config_file.cppo.ml000066400000000000000000000715021412530476100210610ustar00rootroot00000000000000(*********************************************************************************) (* Config_file *) (* *) (* Copyright (C) 2011 Institut National de Recherche en Informatique *) (* et en Automatique. All rights reserved. *) (* *) (* This program is free software; you can redistribute it and/or modify *) (* it under the terms of the GNU Library General Public License as *) (* published by the Free Software Foundation; either version 2 of the *) (* License, or any later version. *) (* *) (* This program is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU Library General Public License for more details. *) (* *) (* You should have received a copy of the GNU Library General Public *) (* License along with this program; if not, write to the Free Software *) (* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA *) (* 02111-1307 USA *) (* *) (*********************************************************************************) (* TODO *) (* section comments *) (* better obsoletes: no "{}", line cuts *) (* possible improvements: *) (* use lex/yacc instead of genlex to be more robust, efficient, allow arrays and other types, read comments. *) (* description and help, level (beginner/advanced/...) for each cp *) (* find an option from its name and group *) (* class hooks *) (* get the sections of a group / of a file *) (* read file format from inifiles and ConfigParser *) (* Read the mli before reading this file! *) (* ******************************************************************************** *) (* ******************************** misc utilities ******************************** *) (* ******************************************************************************** *) (* This code is intended to be usable without any dependencies. *) (* as List.assoc, but applies f to the element matching [key] and returns the list where this element has been replaced by the result of f. *) let rec list_assoc_remove key f = function | [] -> raise Not_found | ((key', value) as elt) :: tail -> ( if key <> key' then elt :: list_assoc_remove key f tail else match f value with None -> tail | Some a -> (key', a) :: tail) (* reminiscent of String.concat. Same as [Queue.iter f1 queue] but calls [f2 ()] between each calls to f1. Does not call f2 before the first call nor after the last call to f2. Could be more efficient with a richer module interface of Queue. *) let queue_iter_between f1 f2 queue = (* let f flag elt = if flag then f2 (); (f1 elt:unit); true in *) let f flag elt = if flag then f2 (); f1 elt; true in ignore (Queue.fold f false queue) let list_iter_between f1 f2 = function | [] -> () | [ a ] -> f1 a | a :: tail -> f1 a; List.iter (fun elt -> (f2 () : unit); f1 elt) tail (* | a::tail -> f1 a; List.iter (fun elt -> f2 (); f1 elt) tail *) (* !! types ??? *) (* to ensure that strings will be parsed correctly by Genlex. It's more comfortable not to have quotes around the string, but sometimes it's necessary. *) exception Unsafe_string let safe_string s = if s = "" then "\"\"" else if try match s.[0] with | 'a' .. 'z' | 'A' .. 'Z' -> for i = 1 to String.length s - 1 do match s.[i] with | 'a' .. 'z' | 'A' .. 'Z' | '_' | '0' .. '9' -> () | _ -> raise Unsafe_string done; false | _ -> ( try string_of_int (int_of_string s) <> s || string_of_float (float_of_string s) <> s with Failure _ -> true) with Unsafe_string -> true then Printf.sprintf "\"%s\"" (String.escaped s) else s (* ******************************************************************************** *) (* ************************************* core ************************************* *) (* ******************************************************************************** *) module Raw = struct type cp = | String of string | Int of int | Float of float | List of cp list | Tuple of cp list | Section of (string * cp) list (* Code generated by camlp4 pa_o.cmo pa_op.cmo pr_o.cmo -- -o config_file_parser.ml -impl config_file_parser.ml4 Unreadable on purpose, edit the file config_file_parser.ml4 rather than editing this (huge) lines. Could be one day rewritten with ocamllex/yacc to be more robust, efficient, allow arrays, read comments… *) #include "config_file_parser.ml" open Format (* formating convention: the caller has to open the box, close it and flush the output *) (* remarks on Format: set_margin impose un appel à set_max_indent sprintf et bprintf sont flushées à chaque appel*) (* pretty print a Raw.cp *) let rec save formatter = function | String s -> fprintf formatter "%s" (safe_string s) (* How can I cut lines and *) | Int i -> fprintf formatter "%d" i (* print backslashes just before the \n? *) | Float f -> fprintf formatter "%g" f | List l -> fprintf formatter "[@["; list_iter_between (fun v -> fprintf formatter "@["; save formatter v; fprintf formatter "@]") (fun () -> fprintf formatter ";@ ") l; fprintf formatter "@]]" | Tuple l -> fprintf formatter "(@["; list_iter_between (fun v -> fprintf formatter "@["; save formatter v; fprintf formatter "@]") (fun () -> fprintf formatter ",@ ") l; fprintf formatter "@])" | Section l -> fprintf formatter "{@;<0 2>@["; list_iter_between (fun (name, value) -> fprintf formatter "@[%s =@ @[" name; save formatter value; fprintf formatter "@]@]") (fun () -> fprintf formatter "@;<2 0>") l; fprintf formatter "@]}" (* let to_string r = save str_formatter r; flush_str_formatter () *) let to_channel out_channel r = let f = formatter_of_out_channel out_channel in fprintf f "@["; save f r; fprintf f "@]@?" let of_string s = s |> Stream.of_string |> Parse.lexer |> Parse.value let of_channel in_channel = let result = in_channel |> Stream.of_channel |> Parse.lexer |> Parse.file [] in close_in in_channel; result end (* print the given string in a way compatible with Format. Truncate the lines when needed, indent the newlines.*) let print_help formatter = String.iter (function | ' ' -> Format.pp_print_space formatter () | '\n' -> Format.pp_force_newline formatter () | c -> Format.pp_print_char formatter c) type 'a wrappers = { to_raw : 'a -> Raw.cp; of_raw : Raw.cp -> 'a } class type ['a] cp = object (* method private to_raw = wrappers.to_raw *) (* method private of_raw = wrappers.of_raw *) (* method private set_string s = s |> Raw.of_string |> self#of_raw |> self#set *) method add_hook : ('a -> 'a -> unit) -> unit method get : 'a method get_default : 'a method set : 'a -> unit method reset : unit method get_formatted : Format.formatter -> unit method get_default_formatted : Format.formatter -> unit method get_help_formatted : Format.formatter -> unit method get_name : string list method get_short_name : string option method set_short_name : string -> unit method get_help : string method get_spec : Arg.spec method set_raw : Raw.cp -> unit end type groupable_cp = < get_name : string list ; get_short_name : string option ; get_help : string ; get_formatted : Format.formatter -> unit ; get_default_formatted : Format.formatter -> unit ; get_help_formatted : Format.formatter -> unit ; get_spec : Arg.spec ; reset : unit ; set_raw : Raw.cp -> unit > exception Double_name exception Missing_cp of groupable_cp exception Wrong_type of (out_channel -> unit) (* Two exceptions to stop the iteration on queues. *) exception Found exception Found_cp of groupable_cp (* The data structure to store the cps. It's a tree, each node is a section, and a queue of sons with their name. Each leaf contains a cp. *) type 'a nametree = | Immediate of 'a | Subsection of (string * 'a nametree) Queue.t (* this Queue must be nonempty for group.read.choose *) class group = object (self) val mutable cps = Queue.create () (* hold all the added cps, in a nametree. *) method add : 'a. 'a cp -> unit = fun original_cp -> let cp = (original_cp :> groupable_cp) in (* function called when we reach the end of the list cp#get_name. *) let add_immediate name cp queue = Queue.iter (fun (name', _) -> if name = name' then raise Double_name) queue; Queue.push (name, Immediate cp) queue in (* adds the cp with name [first_name::last_name] in section [section]. *) let rec add_in_section section first_name last_name cp queue = let sub_add = match last_name with (* what to do once we have find the correct section *) | [] -> add_immediate first_name | middle_name :: last_name -> add_in_section first_name middle_name last_name in try Queue.iter (function | name, Subsection subsection when name = section -> sub_add cp subsection; raise Found | _ -> ()) queue; let sub_queue = Queue.create () in sub_add cp sub_queue; Queue.push (section, Subsection sub_queue) queue with Found -> () in match cp#get_name with | [] -> failwith "empty name" | [ first_name ] -> add_immediate first_name cp cps | first_name :: middle_name :: last_name -> add_in_section first_name middle_name last_name cp cps method write ?(with_help = true) filename = let out_channel = open_out filename in let formatter = Format.formatter_of_out_channel out_channel in let print = Format.fprintf formatter in print "@["; let rec save_queue formatter = queue_iter_between (fun (name, nametree) -> save_nametree name nametree) (Format.pp_print_cut formatter) and save_nametree name = function | Immediate cp -> if with_help && cp#get_help <> "" then ( print "@[(* "; cp#get_help_formatted formatter; print "@ *)@]@,"); Format.fprintf formatter "@[%s =@ @[" (safe_string name); cp#get_formatted formatter; print "@]@]" | Subsection queue -> Format.fprintf formatter "%s = {@;<0 2>@[" (safe_string name); save_queue formatter queue; print "@]@,}" in save_queue formatter cps; print "@]@."; close_out out_channel method private read_from ?obsoletes no_default on_type_error raw_of_input = (* what to do when a cp is missing: *) let missing cp default = if no_default then raise (Missing_cp cp) else default in (* returns a cp contained in the nametree queue, which must be nonempty *) let choose queue = let rec iter q = Queue.iter (function | _, Immediate cp -> raise (Found_cp cp) | _, Subsection q -> iter q) q in try iter queue; failwith "choose" with Found_cp cp -> cp in (* [set_and_remove raw_cps nametree] sets the cp of [nametree] to their value defined in [raw_cps] and returns the remaining raw_cps. *) let set_cp cp value = try cp#set_raw value with Wrong_type output -> on_type_error cp value output in let rec set_and_remove raw_cps = function | name, Immediate cp -> ( try list_assoc_remove name (fun value -> set_cp cp value; None) raw_cps with Not_found -> missing cp raw_cps) | name, Subsection queue -> ( try list_assoc_remove name (function | Raw.Section l -> ( match remainings l queue with | [] -> None | l -> Some (Raw.Section l)) | r -> missing (choose queue) (Some r)) raw_cps with Not_found -> missing (choose queue) raw_cps) and remainings raw_cps queue = Queue.fold set_and_remove raw_cps queue in let remainings = remainings raw_of_input cps in (* Handling of cps defined in filename but not belonging to self. *) if remainings <> [] then match obsoletes with | Some filename -> let out_channel = open_out filename in (* open_out_gen [Open_wronly; Open_creat; Open_append; Open_text] 0o666 filename in *) let formatter = Format.formatter_of_out_channel out_channel in Format.fprintf formatter "@["; Raw.save formatter (Raw.Section remainings); Format.fprintf formatter "@]@."; close_out out_channel | None -> () method read ?obsoletes ?(no_default = false) ?(on_type_error = fun groupable_cp _raw_cp output filename in_channel -> close_in in_channel; Printf.eprintf "Type error while loading configuration parameter %s from file %s.\n\ %!" (String.concat "." groupable_cp#get_name) filename; output stderr; exit 1) filename = (* [filename] is created if it doesn't exist. In this case there is no need to read it. *) match Sys.file_exists filename with | false -> self#write filename | true -> let in_channel = open_in filename in let on_type_error cp value output = on_type_error cp value output filename in_channel in self#read_from ?obsoletes no_default on_type_error (Raw.of_channel in_channel); close_in in_channel method read_string ?obsoletes ?(no_default = false) ?(on_type_error = fun groupable_cp _raw_cp output _string -> Printf.eprintf "Type error while loading configuration parameter %s.\n%!" (String.concat "." groupable_cp#get_name); output stderr; exit 1) input_string = let on_type_error cp value output = on_type_error cp value output input_string in let raw_of_string s = s |> Stream.of_string |> Raw.Parse.lexer |> Raw.Parse.file [] in self#read_from ?obsoletes no_default on_type_error (raw_of_string input_string) method command_line_args ~section_separator = let print = Format.fprintf Format.str_formatter in (* shortcut *) let result = ref [] in let push x = result := x :: !result in let rec iter = function | _, Immediate cp -> let key = "-" ^ String.concat section_separator cp#get_name in let spec = cp#get_spec in let doc = print "@["; Format.pp_print_as Format.str_formatter (String.length key + 3) ""; if cp#get_help <> "" then ( print "@,@["; cp#get_help_formatted Format.str_formatter; print "@]@ ") else print "@,"; print "@[@[current:@;<1 2>@["; cp#get_formatted Format.str_formatter; print "@]@],@ @[default:@;<1 2>@["; cp#get_default_formatted Format.str_formatter; print "@]@]@]@]"; Format.flush_str_formatter () in (match cp#get_short_name with | None -> () | Some short_name -> push ("-" ^ short_name, spec, "")); push (key, spec, doc) | _, Subsection queue -> Queue.iter iter queue in Queue.iter iter cps; List.rev !result end (* Given wrappers for the type 'a, cp_custom_type defines a class 'a cp. *) class ['a] cp_custom_type wrappers ?(group : group option) name ?short_name default help = object (self) method private to_raw = wrappers.to_raw method private of_raw = wrappers.of_raw val mutable value = default (* output *) method get = value method get_default = default method get_formatted formatter = self#get |> self#to_raw |> Raw.save formatter method get_default_formatted formatter = self#get_default |> self#to_raw |> Raw.save formatter (* input *) method set v = let v' = value in value <- v; self#exec_hooks v' v method set_raw v = self#of_raw v |> self#set method private set_string s = s |> Raw.of_string |> self#of_raw |> self#set method reset = self#set self#get_default (* name *) val mutable shortname = short_name method get_name = name method get_short_name = shortname method set_short_name s = shortname <- Some s (* help *) method get_help = help method get_help_formatted formatter = print_help formatter self#get_help method get_spec = Arg.String self#set_string (* hooks *) val mutable hooks = [] method add_hook f = hooks <- (f : 'a -> 'a -> unit) :: hooks method private exec_hooks v' v = List.iter (fun f -> f v' v) hooks initializer match group with Some g -> g#add (self :> 'a cp) | None -> () end (* ******************************************************************************** *) (* ****************************** predefined classes ****************************** *) (* ******************************************************************************** *) let int_wrappers = { to_raw = (fun v -> Raw.Int v); of_raw = (function | Raw.Int v -> v | r -> raise (Wrong_type (fun outchan -> Printf.fprintf outchan "Raw.Int expected, got %a\n%!" Raw.to_channel r))); } class int_cp ?group name ?short_name default help = object (self) inherit [int] cp_custom_type int_wrappers ?group name ?short_name default help method! get_spec = Arg.Int self#set end let float_wrappers = { to_raw = (fun v -> Raw.Float v); of_raw = (function | Raw.Float v -> v | Raw.Int v -> float v | r -> raise (Wrong_type (fun outchan -> Printf.fprintf outchan "Raw.Float expected, got %a\n%!" Raw.to_channel r))); } class float_cp ?group name ?short_name default help = object (self) inherit [float] cp_custom_type float_wrappers ?group name ?short_name default help method! get_spec = Arg.Float self#set end (* The Pervasives version is too restrictive *) let bool_of_string s = #if OCAML_VERSION >= (4, 03, 0) match String.lowercase_ascii s with #else match String.lowercase s with #endif | "false" | "no" | "n" | "0" -> false (* "0" and "1" aren't used. *) | "true" | "yes" | "y" | "1" -> true | r -> raise (Wrong_type (fun outchan -> Printf.fprintf outchan "Raw.Bool expected, got %s\n%!" r)) let bool_wrappers = { to_raw = (fun v -> Raw.String (string_of_bool v)); of_raw = (function | Raw.String v -> bool_of_string v | Raw.Int v -> v <> 0 | r -> raise (Wrong_type (fun outchan -> Printf.fprintf outchan "Raw.Bool expected, got %a\n%!" Raw.to_channel r))); } class bool_cp ?group name ?short_name default help = object (self) inherit [bool] cp_custom_type bool_wrappers ?group name ?short_name default help method! get_spec = Arg.Bool self#set end let string_wrappers = { to_raw = (fun v -> Raw.String v); of_raw = (function | Raw.String v -> v | Raw.Int v -> string_of_int v | Raw.Float v -> string_of_float v | r -> raise (Wrong_type (fun outchan -> Printf.fprintf outchan "Raw.String expected, got %a\n%!" Raw.to_channel r))); } class string_cp ?group name ?short_name default help = object (self) inherit [string] cp_custom_type string_wrappers ?group name ?short_name default help method private of_string s = s method! get_spec = Arg.String self#set end let list_wrappers wrappers = { to_raw = (fun l -> Raw.List (List.map wrappers.to_raw l)); of_raw = (function | Raw.List l -> List.map wrappers.of_raw l | r -> raise (Wrong_type (fun outchan -> Printf.fprintf outchan "Raw.List expected, got %a\n%!" Raw.to_channel r))); } class ['a] list_cp wrappers = ['a list] cp_custom_type (list_wrappers wrappers) let option_wrappers wrappers = { to_raw = (function Some v -> wrappers.to_raw v | None -> Raw.String ""); of_raw = (function | Raw.String s as v -> if s = "" || s = "None" then None else if String.length s >= 5 && String.sub s 0 5 = "Some " then Some (wrappers.of_raw (Raw.String (String.sub s 5 (String.length s - 5)))) else Some (wrappers.of_raw v) | r -> Some (wrappers.of_raw r)); } class ['a] option_cp wrappers = ['a option] cp_custom_type (option_wrappers wrappers) let enumeration_wrappers enum = let switched = List.map (fun (string, cons) -> (cons, string)) enum in { to_raw = (fun v -> Raw.String (List.assq v switched)); of_raw = (function | Raw.String s -> ( try List.assoc s enum with Not_found -> failwith (Printf.sprintf "%s isn't a known constructor" s)) | r -> raise (Wrong_type (fun outchan -> Printf.fprintf outchan "Raw enumeration expected, got %a\n%!" Raw.to_channel r))); } class ['a] enumeration_cp enum ?group name ?short_name default help = object (self) inherit ['a] cp_custom_type (enumeration_wrappers enum) ?group name ?short_name default help method! get_spec = Arg.Symbol (List.map fst enum, fun s -> self#set (List.assoc s enum)) end let tuple2_wrappers wrapa wrapb = { to_raw = (fun (a, b) -> Raw.Tuple [ wrapa.to_raw a; wrapb.to_raw b ]); of_raw = (function | Raw.Tuple [ a; b ] -> (wrapa.of_raw a, wrapb.of_raw b) | r -> raise (Wrong_type (fun outchan -> Printf.fprintf outchan "Raw.Tuple 2 expected, got %a\n%!" Raw.to_channel r))); } class ['a, 'b] tuple2_cp wrapa wrapb = ['a * 'b] cp_custom_type (tuple2_wrappers wrapa wrapb) let tuple3_wrappers wrapa wrapb wrapc = { to_raw = (fun (a, b, c) -> Raw.Tuple [ wrapa.to_raw a; wrapb.to_raw b; wrapc.to_raw c ]); of_raw = (function | Raw.Tuple [ a; b; c ] -> (wrapa.of_raw a, wrapb.of_raw b, wrapc.of_raw c) | r -> raise (Wrong_type (fun outchan -> Printf.fprintf outchan "Raw.Tuple 3 expected, got %a\n%!" Raw.to_channel r))); } class ['a, 'b, 'c] tuple3_cp wrapa wrapb wrapc = ['a * 'b * 'c] cp_custom_type (tuple3_wrappers wrapa wrapb wrapc) let tuple4_wrappers wrapa wrapb wrapc wrapd = { to_raw = (fun (a, b, c, d) -> Raw.Tuple [ wrapa.to_raw a; wrapb.to_raw b; wrapc.to_raw c; wrapd.to_raw d ]); of_raw = (function | Raw.Tuple [ a; b; c; d ] -> (wrapa.of_raw a, wrapb.of_raw b, wrapc.of_raw c, wrapd.of_raw d) | r -> raise (Wrong_type (fun outchan -> Printf.fprintf outchan "Raw.Tuple 4 expected, got %a\n%!" Raw.to_channel r))); } class ['a, 'b, 'c, 'd] tuple4_cp wrapa wrapb wrapc wrapd = ['a * 'b * 'c * 'd] cp_custom_type (tuple4_wrappers wrapa wrapb wrapc wrapd) class string2_cp = [string, string] tuple2_cp string_wrappers string_wrappers (* class color_cp = string_cp *) class font_cp = string_cp class filename_cp = string_cp (* ******************************************************************************** *) (******************** Backward compatibility with module Options ****************** *) (* ******************************************************************************** *) type 'a option_class = 'a wrappers type 'a option_record = 'a cp type options_file = { mutable filename : string; group : group } let create_options_file filename = { filename; group = new group } let set_options_file options_file filename = options_file.filename <- filename let load { filename = f; group = g } = g#read f let append { group = g; _ } filename = g#read filename let save { filename = f; group = g } = g#write ~with_help:false f let save_with_help { filename = f; group = g } = g#write ~with_help:true f let _define_option { group; _ } name help option_class default = new cp_custom_type option_class ~group name default help let option_hook cp f = cp#add_hook (fun _ _ -> f ()) let string_option = string_wrappers let color_option = string_wrappers let font_option = string_wrappers let int_option = int_wrappers let bool_option = bool_wrappers let float_option = float_wrappers let string2_option = tuple2_wrappers string_wrappers string_wrappers let option_option = option_wrappers let list_option = list_wrappers let sum_option = enumeration_wrappers let tuple2_option (a, b) = tuple2_wrappers a b let tuple3_option (a, b, c) = tuple3_wrappers a b c let tuple4_option (a, b, c, d) = tuple4_wrappers a b c d let ( !! ) cp = cp#get let ( =:= ) cp value = cp#set value let shortname cp = String.concat ":" cp#get_name let get_help cp = cp#get_help type option_value = | Module of option_module | StringValue of string | IntValue of int | FloatValue of float | List of option_value list | SmallList of option_value list and option_module = (string * option_value) list let rec value_to_raw = function | Module a -> Raw.Section (List.map (fun (name, value) -> (name, value_to_raw value)) a) | StringValue a -> Raw.String a | IntValue a -> Raw.Int a | FloatValue a -> Raw.Float a | List a -> Raw.List (List.map value_to_raw a) | SmallList a -> Raw.Tuple (List.map value_to_raw a) let rec raw_to_value = function | Raw.String a -> StringValue a | Raw.Int a -> IntValue a | Raw.Float a -> FloatValue a | Raw.List a -> List (List.map raw_to_value a) | Raw.Tuple a -> SmallList (List.map raw_to_value a) | Raw.Section a -> Module (List.map (fun (name, value) -> (name, raw_to_value value)) a) let define_option_class _ of_option_value to_option_value = { to_raw = (fun a -> a |> to_option_value |> value_to_raw); of_raw = (fun a -> a |> raw_to_value |> of_option_value); } let to_value { to_raw; _ } a = a |> to_raw |> raw_to_value let from_value { of_raw; _ } a = a |> value_to_raw |> of_raw let of_value_w wrappers a = a |> value_to_raw |> wrappers.of_raw let to_value_w wrappers a = a |> wrappers.to_raw |> raw_to_value (* fancy indentation when finishing this stub code, not good style :-) *) let value_to_string : option_value -> string = of_value_w string_option let string_to_value = to_value_w string_option let value_to_int = of_value_w int_option let int_to_value = to_value_w int_option let value_to_bool = of_value_w bool_option let bool_to_value = to_value_w bool_option let value_to_float = of_value_w float_option let float_to_value = to_value_w float_option let value_to_string2 = of_value_w string2_option let string2_to_value = to_value_w string2_option let value_to_list of_value = let wrapper = define_option_class "" of_value (fun _ -> failwith "value_to_list") in of_value_w (list_option wrapper) let list_to_value to_value = let wrapper = define_option_class "" (fun _ -> failwith "value_to_list") to_value in to_value_w (list_option wrapper) config-file-release-1.2.1/config_file.mli000066400000000000000000000372571412530476100203030ustar00rootroot00000000000000(*********************************************************************************) (* Config_file *) (* *) (* Copyright (C) 2011 Institut National de Recherche en Informatique *) (* et en Automatique. All rights reserved. *) (* *) (* This program is free software; you can redistribute it and/or modify *) (* it under the terms of the GNU Library General Public License as *) (* published by the Free Software Foundation; either version 2 of the *) (* License, or any later version. *) (* *) (* This program is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU Library General Public License for more details. *) (* *) (* You should have received a copy of the GNU Library General Public *) (* License along with this program; if not, write to the Free Software *) (* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA *) (* 02111-1307 USA *) (* *) (*********************************************************************************) (** This module implements a mechanism to handle configuration files. A configuration file is defined as a set of [variable = value] lines, where value can be - a simple string (types [int], [string], [bool]…); - a list of values between brackets (lists) or parentheses (tuples); - or a set of [variable = value] lines between braces. The configuration file is automatically loaded and saved, and configuration parameters are manipulated inside the program as easily as references. Object implementation by Jean-Baptiste Rouquier. *) (** {1:lowlevelinterface Low level interface} *) (** Skip this section on a first reading... *) (** The type of Configuration Parameter, in short {e cp }, freshly parsed from a configuration file, not yet wrapped in their proper type. *) module Raw : sig type cp = | String of string (** base types, reproducing the tokens of Genlex *) | Int of int | Float of float | List of cp list (** compound types *) | Tuple of cp list | Section of (string * cp) list val of_string : string -> cp (** A parser. *) val to_channel : out_channel -> cp -> unit (** Used to print the values into a log file for instance. *) end type 'a wrappers = { to_raw : 'a -> Raw.cp; of_raw : Raw.cp -> 'a } (** A type used to specialize polymorphics classes and define new classes. {!section:predefined_wrappers} are provided. *) exception Wrong_type of (out_channel -> unit) (** An exception raised by {!Config_file.cp.set_raw} when the argument doesn't have a suitable {!Config_file.Raw.cp} type. The function explains the problem and flushes the output. *) (* (\** {2 Miscellaneous functions} *\) *) (* val bool_of_string : string -> bool *) (** {1 High level interface} *) (** {2 The two main classes} *) (** A Configuration Parameter, in short {e cp}, i.e. a value we can store in and read from a configuration file. *) class type ['a] cp = object (** {1 Accessing methods} *) method get : 'a method set : 'a -> unit method get_default : 'a method get_help : string method get_name : string list method reset : unit (** Resets to the default value. *) (** {1 Miscellaneous} *) method add_hook : ('a -> 'a -> unit) -> unit (** All the hooks are executed each time the method set is called, just after setting the new value.*) method set_short_name : string -> unit (** Used to generate command line arguments in {!Config_file.group.command_line_args}. *) method get_short_name : string option (** [None] if no optional short_name was provided during object creation and [set_short_name] was never called.*) (** {1 Methods for internal use} *) method get_formatted : Format.formatter -> unit method get_default_formatted : Format.formatter -> unit method get_help_formatted : Format.formatter -> unit method get_spec : Arg.spec method set_raw : Raw.cp -> unit end type groupable_cp = < get_name : string list ; get_short_name : string option ; get_help : string ; get_formatted : Format.formatter -> unit ; get_default_formatted : Format.formatter -> unit ; get_help_formatted : Format.formatter -> unit ; get_spec : Arg.spec ; reset : unit ; set_raw : Raw.cp -> unit > (** Unification over all possible ['a cp]: contains the main methods of ['a cp] except the methods using the type ['a]. A [group] manipulates only [groupable_cp] for homogeneity. *) exception Double_name (** Raised in case a name is already used. See {!Config_file.group.add}. *) exception Missing_cp of groupable_cp (** An exception possibly raised if we want to check that every cp is defined in a configuration file. See {!Config_file.group.read}. *) (** A group of cps, that can be loaded and saved, or used to generate command line arguments. The basic usage is to have only one group and one configuration file, but this mechanism allows to have more, for instance to have another smaller group for the options to pass on the command line. *) class group : object (* method add : 'a cp -> 'a cp *) method add : 'a cp -> unit (** Adds a cp to the group. Note that the type ['a] must be lost to allow cps of different types to belong to the same group. @raise Double_name if [cp#get_name] is already used. *) method write : ?with_help:bool -> string -> unit (** [write filename] saves all the cps into the configuration file [filename].*) method read : ?obsoletes:string -> ?no_default:bool -> ?on_type_error: (groupable_cp -> Raw.cp -> (out_channel -> unit) -> string -> in_channel -> unit) -> string -> unit (** [read filename] reads [filename] and stores the values it specifies into the cps belonging to this group. The file is created (and not read) if it doesn't exists. In the default behaviour, no warning is issued. If not all cps are updated or if some values of [filename] aren't used. If [obsoletes] is specified, then prints in this file all the values that are in [filename] but not in this group. Those cps are likely to be erroneous or obsolete. Opens this file only if there is something to write in it. If [no_default] is [true], then raises [Missing_cp foo] if the cp [foo] isn't defined in [filename] but belongs to this group. [on_type_error groupable_cp value output filename in_channel] is called if the file doesn't give suitable value (string instead of int for instance, or a string not belonging to the expected enumeration) for the cp [groupable_cp]. [value] is the value read from the file, [output] is the argument of {!Config_file.Wrong_type}, [filename] is the same argument as the one given to read, and [in_channel] refers to [filename] to allow a function to close it if needed. Default behaviour is to print an error message and call [exit 1]. *) method read_string : ?obsoletes:string -> ?no_default:bool -> ?on_type_error: (groupable_cp -> Raw.cp -> (out_channel -> unit) -> string -> unit) -> string -> unit (** [read_string string] reads the content of [string] and stores the values it specifies into the cps belonging to this group. This method behaves just like read for the others aspects. *) method command_line_args : section_separator:string -> (string * Arg.spec * string) list (** Interface with module Arg. @param section_separator the string used to concatenate the name of a cp, to get the command line option name. ["-"] is a good default. @return a list that can be used with [Arg.parse] and [Arg.usage]. *) end (** {2:predefined_cp_classes Predefined cp classes} *) (** The last three non-optional arguments are always [name] (of type string list), [default_value] and [help] (of type string). [name] is the path to the cp: [["section";"subsection"; ...; "foo"]]. It can consists of a single element but must not be empty. [short_name] will be added a "-" and used in {!Config_file.group.command_line_args}. [group], if provided, adds the freshly defined option to it (something like [initializer group#add self]). [help] needs not contain newlines, it will be automatically truncated where needed. It is mandatory but can be [""]. *) class int_cp : ?group:group -> string list -> ?short_name:string -> int -> string -> [int] cp class float_cp : ?group:group -> string list -> ?short_name:string -> float -> string -> [float] cp class bool_cp : ?group:group -> string list -> ?short_name:string -> bool -> string -> [bool] cp class string_cp : ?group:group -> string list -> ?short_name:string -> string -> string -> [string] cp class ['a] list_cp : 'a wrappers -> ?group:group -> string list -> ?short_name:string -> 'a list -> string -> ['a list] cp class ['a] option_cp : 'a wrappers -> ?group:group -> string list -> ?short_name:string -> 'a option -> string -> ['a option] cp class ['a] enumeration_cp : (string * 'a) list -> ?group:group -> string list -> ?short_name:string -> 'a -> string -> ['a] cp class ['a, 'b] tuple2_cp : 'a wrappers -> 'b wrappers -> ?group:group -> string list -> ?short_name:string -> 'a * 'b -> string -> ['a * 'b] cp class ['a, 'b, 'c] tuple3_cp : 'a wrappers -> 'b wrappers -> 'c wrappers -> ?group:group -> string list -> ?short_name:string -> 'a * 'b * 'c -> string -> ['a * 'b * 'c] cp class ['a, 'b, 'c, 'd] tuple4_cp : 'a wrappers -> 'b wrappers -> 'c wrappers -> 'd wrappers -> ?group:group -> string list -> ?short_name:string -> 'a * 'b * 'c * 'd -> string -> ['a * 'b * 'c * 'd] cp class string2_cp : ?group:group -> string list -> ?short_name:string -> string * string -> string -> [string, string] tuple2_cp (* class color_cp : ?group:group -> string list -> ?short_name:string -> string -> string -> string_cp *) class font_cp : ?group:group -> string list -> ?short_name:string -> string -> string -> string_cp class filename_cp : ?group:group -> string list -> ?short_name:string -> string -> string -> string_cp (** {2:predefined_wrappers Predefined wrappers} *) val int_wrappers : int wrappers val float_wrappers : float wrappers val bool_wrappers : bool wrappers val string_wrappers : string wrappers val list_wrappers : 'a wrappers -> 'a list wrappers val option_wrappers : 'a wrappers -> 'a option wrappers val enumeration_wrappers : (string * 'a) list -> 'a wrappers (** If you have a [type suit = Spades | Hearts | Diamond | Clubs], then {[ enumeration_wrappers ["spades",Spades; "hearts",Hearts; "diamond",Diamond; "clubs",Clubs] ]} will allow you to use cp of this type. For sum types with not only constant constructors, you will need to define your own cp class. *) val tuple2_wrappers : 'a wrappers -> 'b wrappers -> ('a * 'b) wrappers val tuple3_wrappers : 'a wrappers -> 'b wrappers -> 'c wrappers -> ('a * 'b * 'c) wrappers val tuple4_wrappers : 'a wrappers -> 'b wrappers -> 'c wrappers -> 'd wrappers -> ('a * 'b * 'c * 'd) wrappers (** {2 Defining new cp classes} *) class ['a] cp_custom_type : 'a wrappers -> ?group:group -> string list -> ?short_name:string -> 'a -> string -> ['a] cp (** To define a new cp class, you just have to provide an implementation for the wrappers between your type [foo] and the type {!Raw.cp}. Once you have your wrappers [w], write {[ class foo_cp = [foo] cp_custom_type w ]} For further details, have a look at the commented .ml file, section {!section:predefined_cp_classes}. *) (** {1 Backward compatibility} All the functions from the module Options are available, except: - [prune_file]: use [group#write ?obsoletes:"foo.ml"]. - [smalllist_to_value], [smalllist_option]: use lists or tuples. - [get_class]. - [class_hook]: hooks are local to a cp. If you want hooks global to a class, define a new class that inherits from {!Config_file.cp_custom_type}. - [set_simple_option], [get_simple_option], [simple_options], [simple_args]: use {!Config_file.group.write}. - [set_option_hook]: use {!Config_file.cp.add_hook}. - [set_string_wrappers]: define a new class with {!Config_file.cp_custom_type}. The old configurations files are readable by this module. @deprecated *) (**/**) type 'a option_class type 'a option_record type options_file val create_options_file : string -> options_file val set_options_file : options_file -> string -> unit val load : options_file -> unit val append : options_file -> string -> unit val save : options_file -> unit val save_with_help : options_file -> unit (* val define_option : options_file -> *) (* string list -> string -> 'a option_class -> 'a -> 'a option_record *) val option_hook : 'a option_record -> (unit -> unit) -> unit val string_option : string option_class val color_option : string option_class val font_option : string option_class val int_option : int option_class val bool_option : bool option_class val float_option : float option_class val string2_option : (string * string) option_class val option_option : 'a option_class -> 'a option option_class val list_option : 'a option_class -> 'a list option_class val sum_option : (string * 'a) list -> 'a option_class val tuple2_option : 'a option_class * 'b option_class -> ('a * 'b) option_class val tuple3_option : 'a option_class * 'b option_class * 'c option_class -> ('a * 'b * 'c) option_class val tuple4_option : 'a option_class * 'b option_class * 'c option_class * 'd option_class -> ('a * 'b * 'c * 'd) option_class val ( !! ) : 'a option_record -> 'a val ( =:= ) : 'a option_record -> 'a -> unit val shortname : 'a option_record -> string val get_help : 'a option_record -> string type option_value = | Module of option_module | StringValue of string | IntValue of int | FloatValue of float | List of option_value list | SmallList of option_value list and option_module = (string * option_value) list val define_option_class : string -> (option_value -> 'a) -> ('a -> option_value) -> 'a option_class val to_value : 'a option_class -> 'a -> option_value val from_value : 'a option_class -> option_value -> 'a val value_to_string : option_value -> string val string_to_value : string -> option_value val value_to_int : option_value -> int val int_to_value : int -> option_value val bool_of_string : string -> bool val value_to_bool : option_value -> bool val bool_to_value : bool -> option_value val value_to_float : option_value -> float val float_to_value : float -> option_value val value_to_string2 : option_value -> string * string val string2_to_value : string * string -> option_value val value_to_list : (option_value -> 'a) -> option_value -> 'a list val list_to_value : ('a -> option_value) -> 'a list -> option_value config-file-release-1.2.1/config_file_parser.ml4000066400000000000000000000056211412530476100215600ustar00rootroot00000000000000(*********************************************************************************) (* Config_file *) (* *) (* Copyright (C) 2011 Institut National de Recherche en Informatique *) (* et en Automatique. All rights reserved. *) (* *) (* This program is free software; you can redistribute it and/or modify *) (* it under the terms of the GNU Library General Public License as *) (* published by the Free Software Foundation; either version 2 of the *) (* License, or any later version. *) (* *) (* This program is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU Library General Public License for more details. *) (* *) (* You should have received a copy of the GNU Library General Public *) (* License along with this program; if not, write to the Free Software *) (* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA *) (* 02111-1307 USA *) (* *) (*********************************************************************************) (* This file is used to generate the code of the module Config_file.Raw.Parse. *) module Parse = struct let lexer = Genlex.make_lexer ["="; "{"; "}"; "["; "]"; ";"; "("; ")"; ","] (* parsers: *) let rec file l = parser | [< id = ident; 'Genlex.Kwd "="; v = value ; result = file ((id, v) :: l) >] -> result | [< >] -> List.rev l and value = parser | [< 'Genlex.Kwd "{"; v = file []; 'Genlex.Kwd "}" >] -> Section v | [< 'Genlex.Ident s >] -> String s | [< 'Genlex.String s >] -> String s | [< 'Genlex.Int i >] -> Int i | [< 'Genlex.Float f >] -> Float f | [< 'Genlex.Char c >] -> String (String.make 1 c) | [< 'Genlex.Kwd "["; v = list [] >] -> List v | [< 'Genlex.Kwd "("; v = list [] >] -> Tuple v and ident = parser | [< 'Genlex.Ident s >] -> s | [< 'Genlex.String s >] -> s and list l = parser | [< 'Genlex.Kwd ";"; result = list l >] -> result | [< 'Genlex.Kwd ","; result = list l >] -> result | [< v = value; result = list (v :: l) >] -> result | [< 'Genlex.Kwd "]" >] -> List.rev l | [< 'Genlex.Kwd ")" >] -> List.rev l end config-file-release-1.2.1/dune000066400000000000000000000007351412530476100162010ustar00rootroot00000000000000(rule (target config_file_parser.ml) (deps config_file_parser.ml4) (action (chdir %{workspace_root} (run %{bin:camlp4} pa_o.cmo pa_op.cmo pr_o.cmo -- -o %{target} -impl %{deps})))) (rule (target config_file.ml) (deps (:cppo config_file.cppo.ml) config_file_parser.ml) (action (chdir %{workspace_root} (run %{bin:cppo} -V OCAML:%{ocaml_version} -o %{target} %{cppo})))) (library (public_name config-file) (name config_file) (modules Config_file)) config-file-release-1.2.1/dune-project000066400000000000000000000014751412530476100176470ustar00rootroot00000000000000(lang dune 2.9) (name config-file) (generate_opam_files true) (formatting disabled) (source (github MisterDA/config-file)) (license "LGPL-2.0-or-later") (authors "Antonin Décimo " "Fabrice Le Fessant " "Maxence Guesdon " "Jean-Baptiste Rouquier " ) (maintainers "Antonin Décimo ") (package (name config-file) (synopsis "A library used to manage configuration files") (description "\| Config_file is a library used to manage the configuration file(s) of "\| an application. You simply define your options and it performs the "\| loading and saving of the options in a file. You can also use the same "\| options in the command line. ) (depends (ocaml (>= 4.02)) (camlp4 :build) (cppo :build))) config-file-release-1.2.1/example.ml000066400000000000000000000122111412530476100173000ustar00rootroot00000000000000(*********************************************************************************) (* Config_file *) (* *) (* Copyright (C) 2011 Institut National de Recherche en Informatique *) (* et en Automatique. All rights reserved. *) (* *) (* This program is free software; you can redistribute it and/or modify *) (* it under the terms of the GNU Library General Public License as *) (* published by the Free Software Foundation; either version 2 of the *) (* License, or any later version. *) (* *) (* This program is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU Library General Public License for more details. *) (* *) (* You should have received a copy of the GNU Library General Public *) (* License along with this program; if not, write to the Free Software *) (* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA *) (* 02111-1307 USA *) (* *) (*********************************************************************************) open Config_file let group = new group (* We create a cp foo of type int. Its default value is 42: *) let foo = new int_cp ~group [ "foo" ] 42 "Help about foo." (* We create two other cp in section "section1": *) let bar = new list_cp int_wrappers ~group [ "section1"; "bar" ] [ 1; 2; 3; 4 ] "Help about bar." let baz = new tuple2_cp string_wrappers bool_wrappers ~group [ "section1"; "baz" ] ("switch", true) "" ;; (* We save them in file "temp.ml" and check the result: *) group#write "temp.ml";; Printf.printf "edit temp.ml and press enter...\n%!"; ignore (input_line stdin); (* We load the file and play with the value of foo: *) group#read "temp.ml"; Printf.printf "foo is %d\n%!" foo#get; foo#set 28; Printf.printf "foo is %d\n%!" foo#get; (* How to define command line arguments and print them (see module Arg): *) Arg.usage (group#command_line_args ~section_separator:"-") "usage message" (* We define a new type of cp: *) let int64_wrappers = { to_raw = (fun v -> Raw.String (Int64.to_string v)); of_raw = (function | Raw.Int v -> Int64.of_int v | Raw.Float v -> Int64.of_float v | Raw.String v -> Int64.of_string v | r -> raise (Wrong_type (fun outchan -> Printf.fprintf outchan "Raw.Int expected, got %a\n%!" Raw.to_channel r))); } class int64_cp = [int64] cp_custom_type int64_wrappers (* See the implementation for other examples *) (* ********************************************************************** *) (* Advanced usage *) (* How to use group.read without failing on error: In case [groupable_cp] doesn't get a suitable type, we just print a warning in foo.log and discard the value from temp.ml (thus keeping the current value of [groupable_cp])*) let log_file = open_out "foo.log";; group#read ~on_type_error:(fun groupable_cp _raw_cp output filename _in_channel -> Printf.fprintf log_file "Type error while loading configuration parameter %s from file %s.\n%!" (String.concat "." groupable_cp#get_name) filename; output log_file (* get more information into log_file *)) "temp.ml" (* Here is a more complex custom type. *) type myrecord = { a : float; b : int list } let myrecord_wrappers = let b_to_raw = (list_wrappers int_wrappers).to_raw in let b_of_raw = (list_wrappers int_wrappers).of_raw in let field_of_option name = function | Some a -> a | None -> Printf.eprintf "Field %s undefined\n%!" name; exit 1 in let a = ref None and b = ref None in { to_raw = (fun { a; b } -> Raw.Section [ ("a", float_wrappers.to_raw a); ("b", b_to_raw b) ]); of_raw = (function | Raw.Section l -> List.iter (fun (name, value) -> match name with | "a" -> a := Some value | "b" -> b := Some value | s -> Printf.eprintf "Unknown field %s\n%!" s) l; { a = float_wrappers.of_raw (field_of_option "a" !a); b = b_of_raw (field_of_option "b" !b); } | r -> raise (Wrong_type (fun outchan -> Printf.fprintf outchan "Raw.Section expected, got %a\n%!" Raw.to_channel r))); } class myrecord_cp = [myrecord] cp_custom_type myrecord_wrappers