Skip to content

Commit

Permalink
Add an init method to the module that do all the hard work.
Browse files Browse the repository at this point in the history
This is for simplifying the usage and allowing access to some elements
(like the initial configuration or and ``CommandLine`` object) from plugins.

This `init` method initialize the ``CommandLine`` object, parse the
arguments and set the configuration and the initialized instance to the module
namespace.

It takes five parameters:

    * `format`: format of the configuration (*yaml*, *json* or *raw*),
    * `data`: a filepath for *yaml* and *json* format and a dictionnary
      for *raw* format,
    * `completion`: allows to initialize argcomplete for bash/zsh
      completion,
    * `subcommands_keyword`: *keyword* parameter of the ``CommandLine``
      object,
    * `deepcopy`: *deepcopy* parameter of the ``CommandLine`` object

By default, the configuration is loaded from the YAML file *cmd.yml* on
the program directory.
  • Loading branch information
fmenabe committed Jan 20, 2017
1 parent bb49cd4 commit 43fefa6
Showing 1 changed file with 41 additions and 1 deletion.
42 changes: 41 additions & 1 deletion clg/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# -*- coding: utf-8 -*-
# coding: utf-8

"""This module is a wrapper to ``argparse`` module. It allow to generate a
command-line from a predefined directory (ie: a YAML, JSON, ... file)."""
Expand Down Expand Up @@ -742,3 +742,43 @@ def print_line(cmd, line, first_line, has_childs):
else:
print(output)
sys.exit(0)


def init(format='yaml', data=os.path.join(sys.path[0], 'cmd.yml'),
completion=False, subcommands_keyword='command', deepcopy=True):
"""Wrapping method that initialize the command-line and export the input
configuration and the **CommandLine** object at the module level.
The configuration is loaded based on the format `format` and `data`. `data`
is a filepath if `format` is *yaml* or *json* and a dictionnary if `format`
is *raw*. By default, the configuration is loaded from the file *cmd.yml* in
the program directory.
`completion` parameter allows to initialize ``argcomplete`` for completion.
"""
# Get command-line configuration based on format and data and initialize CommandLine.
if format == 'yaml':
import yaml, yamlordereddictloader
config = yaml.load(open(data), Loader=yamlordereddictloader.Loader)
elif format == 'json':
import json
config = json.load(open('cmd.json'), object_pairs_hook=OrderedDict)
elif format == 'raw':
config = data
else:
raise CLGError('unsupported format: %s' % format)
cmd = CommandLine(config, subcommands_keyword, deepcopy)

# Activate completion if wished.
if completion:
import argcomplete
argcomplete.autocomplete(cmd.parser)

# Set attributes to the module itself.
setattr(_SELF, 'config', config)
setattr(_SELF, 'cmd', cmd)

# Parse arguments.
args = cmd.parse()

return args

0 comments on commit 43fefa6

Please sign in to comment.