From: Oleg Broytman Date: Sat, 11 Jun 2016 00:41:55 +0000 (+0300) Subject: Add option -C|--config file X-Git-Tag: 0.0.13~1 X-Git-Url: https://git.phdru.name/?p=m_librarian.git;a=commitdiff_plain;h=2b29248d0a515b4e0b33183eae584511bf399bfd Add option -C|--config file Document configuration file. Test config --- diff --git a/docs-ru/before_begin.rst b/docs-ru/before_begin.rst index 3af1db0..213183f 100644 --- a/docs-ru/before_begin.rst +++ b/docs-ru/before_begin.rst @@ -44,6 +44,26 @@ m_Librarian пока не научился индексировать архив | http://home-lib.net/download/inpx/librusec_local_all.inpx +Файл конфигурации +----------------- + +Файл конфигурации по умолчанию ищется в $HOME/.config/ (если у вас +POSIX-совместимая ОС). Файл должен называться ``m_librarian.conf``. Это +должен быть файл в формате ``ini``. В настоящий момент m_librarian +понимает следующие секции и ключи в них:: + + [database] + URI = "DB URI" + + [library] + path = "путь к архивам библиотеки" + + [download] + format = "формат имён сохраняемых файлов" + +Большинство программ имею опцию `-C|--config config`, которая позволяет +использовать файл произвольный конфигурации. + База данных ----------- @@ -56,12 +76,10 @@ m_Librarian пока не научился индексировать архив Database URI ^^^^^^^^^^^^ -Чтобы m_Librarian использовал сервер SQL создайте файл конфигурации и -поместите его в $HOME/.config/ (если у вас POSIX-совместимая ОС). Файл -должен называться ``m_librarian.conf``. Это должен быть файл в формате -``ini``, в нём должна быть единственная секция ``[database]`` с -единственным ключом ``URI``. Значением ключа должно быть Database URI в -формате, который понимает SQLObject. Вот несколько примеров:: +Чтобы m_Librarian использовал сервер SQL в файле конфигурации должна +быть секция ``[database]`` с единственным ключом ``URI``. Значением +ключа должно быть Database URI в формате, который понимает SQLObject. +Вот несколько примеров:: [database] URI = mysql://user:password@host/database diff --git a/docs-ru/command_line.rst b/docs-ru/command_line.rst index cbaad64..70cd7cf 100644 --- a/docs-ru/command_line.rst +++ b/docs-ru/command_line.rst @@ -13,10 +13,11 @@ ml-initdb.py Использование:: - ml-initdb.py [-D] + ml-initdb.py [-C] [-D] Опции:: + -C, --config config Путь к файлу конфигурации -D, --database database Использовать указанную БД Инициализирует базу данных и импортирует список жанров. Этот скрипт не @@ -28,10 +29,11 @@ ml-import.py Использование:: - ml-import.py [-D] [file.inpx ...] + ml-import.py [-C] [-D] [file.inpx ...] Опции:: + -C, --config config Путь к файлу конфигурации -D, --database database Использовать указанную БД Инициализирует базу данных, импортирует список жанров и список файлов @@ -45,13 +47,14 @@ ml-search.py Использование:: - ml-search.py [-D] [-i] [-I] [-t] [-s] [-f] [-v] [-c] ... + ml-search.py [-C] [-D] [-i] [-I] [-t] [-s] [-f] [-v] [-c] ... Программа выполняет поиск по базе данных и показывает список результатов. В настоящее время может искать только в списке авторов. Глобальные опции:: + -C, --config config Путь к файлу конфигурации -D, --database database Использовать указанную БД -i, --ignore-case независимо от регистра (по умолчанию: угадать) -I, --case-sensitive с учётом регистра @@ -159,8 +162,8 @@ ml-search.py была ли книга помечена как удалённая. Опция `-P` задаёт путь к директории с архивами библиотеки. По умолчанию -этот путь берётся из файла конфигурации `m_librarian`, секция -`[library]`, ключ `path`, например:: +этот путь берётся из файла конфигурации, секция `[library]`, ключ +`path`, например:: [library] path = /var/lib/archives @@ -173,7 +176,7 @@ ml-search.py использовать эту команду — совместно с опцией `--id`. Файл сохраняется в текущую директорию с тем именем, под которым он храниться в библиотеке. -Ключ `format` в секции `[download]` файла конфигурации m_librarian.conf +Ключ `format` в секции `[download]` файла конфигурации | [download] | format = %a/%s/%n %t diff --git a/docs/before_begin.rst b/docs/before_begin.rst index a2c13b0..abbb118 100644 --- a/docs/before_begin.rst +++ b/docs/before_begin.rst @@ -24,6 +24,25 @@ The program works with local library archives so download some. In addition to the very libraries you need to get INPX indices for them — m_Librarian cannot index libraries yet. +Configuration file +------------------ + +m_librarian looks up configuration file in $HOME/.config/ (if your OS is +POSIX-compatible). The configuration file must be named +``m_librarian.conf``. It must be in ``ini``-file format. The following +sections and keys are now understood:: + + [database] + URI = "database URI" + + [library] + path = "path to the library archives" + + [download] + format = "download file format" + +Most programs have an option `-C|--config file` to use a non-default +configuration file. Database -------- @@ -37,10 +56,7 @@ way of using m_Librarian. Database URI ^^^^^^^^^^^^ -For m_Librarian to use an SQL server create a configuration file and put -it in $HOME/.config/ (if your OS is POSIX-compatible). Name the -configuration file ``m_librarian.conf``. It must be in ``ini``-file -format and must have the only section ``[database]`` with the only key +In configuration file define section ``[database]`` with the only key ``URI``. The value for the key must be a Database URI in format accepted by SQLObject. Some examples:: diff --git a/docs/command_line.rst b/docs/command_line.rst index 99b5c84..6258443 100644 --- a/docs/command_line.rst +++ b/docs/command_line.rst @@ -13,10 +13,11 @@ ml-initdb.py Usage:: - ml-initdb.py [-D] + ml-initdb.py [-C] [-D] Options:: + -C, --config config Configuration file -D, --database database Open this database by pathname/db uri Initialize database and import genres list. Isn’t really needed as @@ -28,10 +29,11 @@ ml-import.py Usage:: - ml-import.py [-D] [file.inpx ...] + ml-import.py [-C] [-D] [file.inpx ...] Options:: + -C, --config config Configuration file -D, --database database Open this database by pathname/db uri Initialize database, import genres list and import a list of INPX files @@ -44,13 +46,14 @@ ml-search.py Usage:: - ml-search.py [-D] [-i] [-I] [-t] [-s] [-f] [-v] [-c] ... + ml-search.py [-C] [-D] [-i] [-I] [-t] [-s] [-f] [-v] [-c] ... Search through the database and display results. Currently can only search authors by name. Global options:: + -C, --config config Configuration file -D, --database database Open this database by pathname/db uri -i, --ignore-case ignore case (default is to guess) -I, --case-sensitive don’t ignore case @@ -157,7 +160,7 @@ archive name, file name, extension and size, and flag if the book is marked to be deleted. Option `-P` provides the path to the directory with the library -archives. By default the path is extracted from `m_librarian.conf`, +archives. By default the path is extracted from configuration file, section `[library]`, key `path`:: [library] diff --git a/m_librarian/config.py b/m_librarian/config.py index ca7eadd..fed06ae 100755 --- a/m_librarian/config.py +++ b/m_librarian/config.py @@ -38,13 +38,13 @@ def find_config_file(config_dirs=None): _ml_config = None -def get_config(config_filename=None): +def get_config(config_path=None): global _ml_config if _ml_config is None: - if config_filename is None: - config_filename = find_config_file() + if config_path is None: + config_path = find_config_file() _ml_config = RawConfigParser() - _ml_config.read(config_filename) + _ml_config.read(config_path) return _ml_config diff --git a/scripts/ml-import.py b/scripts/ml-import.py index f154841..3ccbd31 100755 --- a/scripts/ml-import.py +++ b/scripts/ml-import.py @@ -1,16 +1,21 @@ #! /usr/bin/env python import argparse +from m_librarian.config import get_config from m_librarian.db import open_db, init_db, update_counters from m_librarian.glst import import_glst from m_librarian.inp import import_inpx if __name__ == '__main__': parser = argparse.ArgumentParser(description='Import') + parser.add_argument('-C', '--config', help='configuration file') parser.add_argument('-D', '--database', help='database URI') parser.add_argument('inpx', nargs='+', help='INPX files to import') args = parser.parse_args() + if args.config: + get_config(args.config) # Get and cache config file + open_db(args.database) init_db() import_glst() diff --git a/scripts/ml-initdb.py b/scripts/ml-initdb.py index f46b7c2..0d4e73b 100755 --- a/scripts/ml-initdb.py +++ b/scripts/ml-initdb.py @@ -1,14 +1,19 @@ #! /usr/bin/env python import argparse +from m_librarian.config import get_config from m_librarian.db import open_db, init_db from m_librarian.glst import import_glst if __name__ == '__main__': parser = argparse.ArgumentParser(description='Init') + parser.add_argument('-C', '--config', help='configuration file') parser.add_argument('-D', '--database', help='database URI') args = parser.parse_args() + if args.config: + get_config(args.config) # Get and cache config file + open_db(args.database) init_db() old, new = import_glst() diff --git a/scripts/ml-search.py b/scripts/ml-search.py index 0742a53..bd5df8c 100755 --- a/scripts/ml-search.py +++ b/scripts/ml-search.py @@ -5,6 +5,7 @@ import sys from sqlobject.sqlbuilder import CONCAT from m_lib.defenc import default_encoding +from m_librarian.config import get_config from m_librarian.db import Author, Book, Extension, Genre, Language, open_db from m_librarian.download import download from m_librarian.search import mk_search_conditions, \ @@ -261,6 +262,7 @@ def _search_languages(case_sensitive, search_type, args): if __name__ == '__main__': main_parser = argparse.ArgumentParser(description='Search') + main_parser.add_argument('-C', '--config', help='configuration file') main_parser.add_argument('-D', '--database', help='database URI') main_parser.add_argument('-i', '--ignore-case', action='store_true', help='ignore case ' @@ -334,6 +336,9 @@ if __name__ == '__main__': args = main_parser.parse_args() + if args.config: + get_config(args.config) # Get and cache config file + if args.case_sensitive: if args.ignore_case: sys.stderr.write( diff --git a/tests/test_config.conf b/tests/test_config.conf new file mode 100644 index 0000000..8154b2b --- /dev/null +++ b/tests/test_config.conf @@ -0,0 +1,2 @@ +[library] +path = /home/test-config diff --git a/tests/test_config.py b/tests/test_config.py new file mode 100755 index 0000000..6e0c6a3 --- /dev/null +++ b/tests/test_config.py @@ -0,0 +1,19 @@ +#! /usr/bin/env python + +import os +import unittest +from tests import main +from m_librarian.config import get_config + + +class TestFormat(unittest.TestCase): + def test_config(self): + config_path = os.path.join( + os.path.dirname(__file__), 'test_config.conf') + get_config(config_path) + ml_conf = get_config() + self.assertEqual(ml_conf.get('library', 'path'), '/home/test-config') + + +if __name__ == "__main__": + main()