Beispiel #1
0
 def save(self, event):
     # type: (int) -> None
     config.steam_path = self.steam_path.GetPath()
     self.profile.SetString(self.profile.GetSelection(), self.prof_name.GetValue())
     self.game.name = self.prof_name.GetValue()
     self.game.mod_path = self.game_path.GetPath()
     self.game.audio_dir = self.audio_path.GetPath()
     self.game.audio_rate = self.game_rate.GetValue()
     self.game.relay_key = self.relay_choice.GetStringSelection()
     self.game.play_key = self.play_choice.GetStringSelection()
     self.game.use_aliases = self.aliases_box.IsChecked()
     config.set_games(self.games)
     config.save()
     self.update_profile(event=None)
     if not os.path.exists(self.audio_path.GetPath()):
         os.makedirs(self.audio_path.GetPath())
Beispiel #2
0
def main():
    # 初始化日志
    initLog()

    #TEST
    print("config测试")
    config.set_file("config.ini")
    print(CONFIG_PATH)
    section = 'defaults'
    print(config.sections())
    config.set("log", "config_path", "logging.ini")
    print("test:"),
    print(config.get("defaults", "test"))
    config.set(section, "test", "test2")
    #config.add_section(section)
    config.save()
    return
Beispiel #3
0
    def new(self, event):
        # type: (int) -> None
        new_profile = wx.TextEntryDialog(parent=self, message="Enter the name of your new game.", caption="pyjam")
        if new_profile.ShowModal() != wx.ID_OK:
            new_profile.Destroy()
            return

        name = new_profile.GetValue()
        new_profile.Destroy()

        self.profile.Append(name)
        self.games.append(Game(name=name))
        config.set_games(self.games)
        config.save()

        self.profile.SetSelection(self.profile.GetCount() - 1)
        self.update_profile(event=None)
        logger.info("New game created: {name}".format(name=name))
Beispiel #4
0
    def remove(self, event):
        if len(self.games) <= 1:
            message = wx.MessageDialog(parent=self, message="You can't remove your only game!",
                                       style=wx.OK | wx.ICON_EXCLAMATION)
            message.ShowModal()
            message.Destroy()
            return False

        name = self.game.name
        self.games.pop(self.profile.GetSelection())
        config.set_games(self.games)
        config.save()
        self.games = config.get_games()

        self.profile.Set([game.name for game in self.games])
        self.profile.SetSelection(0)
        self.update_profile(event=None)

        logger.info("Game removed: {name}".format(name=name))
Beispiel #5
0
 def save(data: RecursiveDict[CommentedMap]) -> None:
     config["plugin_config"] = data
     config.save()
parser.add_argument("-b", "--base-config", type=str, default="example-config.yaml",
                    metavar="<path>", help="the path to the example config "
                                           "(for automatic config updates)")
parser.add_argument("-g", "--generate-registration", action="store_true",
                    help="generate registration and quit")
parser.add_argument("-r", "--registration", type=str, default="registration.yaml",
                    metavar="<path>", help="the path to save the generated registration to")
args = parser.parse_args()

config = Config(args.config, args.registration, args.base_config, os.environ)
config.load()
config.update()

if args.generate_registration:
    config.generate_registration()
    config.save()
    print(f"Registration generated and saved to {config.registration_path}")
    sys.exit(0)

logging.config.dictConfig(copy.deepcopy(config["logging"]))
log = logging.getLogger("mau.init")  # type: logging.Logger
log.debug(f"Initializing mautrix-telegram {__version__}")

db_engine = sql.create_engine(config["appservice.database"] or "sqlite:///mautrix-telegram.db")
Base.metadata.bind = db_engine

session_container = AlchemySessionContainer(engine=db_engine, table_base=Base, session=False,
                                            table_prefix="telethon_", manage_tables=False)
session_container.core_mode = True

try:
Beispiel #7
0
def cli():
    """Command line interface of :mod:`wowplug`. Run

    .. code-block:: sh

        $ wowplug --help

    for an extensive description.
    """
    doc = """
An addon manager for World of Warcraft.

Usage:
    wowplug -h
    wowplug --help
    wowplug (-v|--version)
    wowplug [(-d|--debug)] [(-n|--ignore-config)] <command> [<args>...]

Options:
    -h                  Show this message.
    --help              Show a more detailed help message
    -v --version        Show version.
    -d --debug          Show debug messages.
    -n --ignore-config  Ignore previously saved config file
"""

    cmderr_fmt = "ERROR: {}"
    cmds = OrderedDict()

    def register_cmd(cmd):
        def wrapper(func):
            cmds[cmd] = func
            return func

        return wrapper

    @register_cmd('scan')
    def cmd_scan(args):
        """
Scan <dir> to get a list of installed addons. If no <dir> is
given, try to scan the previously scanned one if applicable.

Usage:
    wowplug scan [<dir>] [--output=<file>]

Options:
    -h --help           Show this message.
    -o <file> --output=<file>
                        Dump the scan result to a file.
                        This file can be used for `sync`.
"""
        def find_addondir(path):
            path = expanded_abspath(path)
            parent, base = os.path.split(path)
            if base == "AddOns":
                return path
            if base == "Interface":
                return os.path.join(path, 'AddOns')
            _path = os.path.join(path, 'Interface', 'AddOns')
            if os.path.exists(_path):
                return _path
            return path

        args, fc, tc = _sync_args_with_config(
            args,
            config,
            {
                # use config entry if <dir> not specified
                # update to config entry if specified
                '<dir>': {
                    'key': 'scan.dir',
                    'norm': find_addondir,
                    'from': lambda a, c: a is None,
                    'to': lambda a, c: a is not None,
                },
                # do not use config entry
                # update to config entry if specified
                '--output': {
                    'key': 'sync.file',
                    'norm': expanded_abspath,
                    'from': lambda a, c: False,
                    'to': lambda a, c: a is not None,
                },
            })
        # validate the args
        args = Schema(
            {
                '<dir>':
                Or(os.path.isdir,
                   error="`{}` is not a valid directory".format(args['<dir>'])
                   if '<dir>' not in fc else
                   "no valid directory found in saved config {} from"
                   " previous scan. one has to be specified via"
                   " command line".format(config.filepath)),
                '--output':
                object,
            },
            ignore_extra_keys=True).validate(args)
        from . import scan
        scan.scan(args['<dir>'], output=args['--output'])

    @register_cmd('sync')
    def cmd_sync(args):
        """
Sync the addons listed in <file> to an AddOns directory. If
no <file> is given, sync the previously synced one or the one
generated by the last run of `scan`. Addons that are not in the
list will be moved to directory `wowplugcache`. Addons that
are in the list but do not exist in the AddOns directory or
`wowplugcache` will be downloaded and installed.

Usage:
    wowplug sync [<file>] [--update] [--delete] [--target=<dir>]

Options:
    -h --help           Show an extensive help message
    -u --update         Update outdated addons if possible.
    -d --delete         Delete the unused addons instead of
                        placing them in `wowplugcache`.
    -t <dir> --target=<dir>
                        Sync to the set <dir> instead of the
                        `config.scan.dir` specified in <file>.
"""
        logger = logging.getLogger(LOGGER_NAME)
        args, fc, tc = _sync_args_with_config(
            args,
            config,
            {
                # use config entry if <file> not specified
                # always update to config entry if specified
                '<file>': {
                    'key': 'sync.file',
                    'norm': expanded_abspath,
                    'from': lambda a, c: a is None,
                    'to': lambda a, c: a is not None,
                },
                # use config entry if not specified
                # update to config entry if specified
                '--target': {
                    'key': 'scan.dir',
                    'norm': expanded_abspath,
                    'from': lambda a, c: a is None,
                    'to': lambda a, c: a is not None,
                },
            })

        # validate the args

        def load_yaml(f):
            if not os.path.exists(f):
                raise SchemaError()
            with open(f, 'r') as fo:
                y = yaml.safe_load(fo)
            return y

        args = Schema(
            {
                '<file>':
                Use(load_yaml,
                    error="`{}` does not exist or is not a valid YAML file".
                    format(args['<file>']) if '<file>' not in fc else
                    "no valid sync file found in saved config {} from"
                    " previous sync or scan. one has to be specified via"
                    " command line".format(config.filepath)),
                '--target':
                Or(None, expanded_abspath),
                '--update':
                object,
                '--delete':
                object,
            },
            ignore_extra_keys=True).validate(args)
        # we need to check sync result fc. in case target is pulled from
        # config, we use the entry from <file>
        if '--target' in fc:
            args['--target'] = args['<file>']['config']['scan']['dir']
            logger.debug(
                "use --target=`{}` from <file>.config.scan.dir".format(
                    args['--target']))
        from . import sync
        sync.sync(args['<file>'],
                  target=args['--target'],
                  update=args['--update'],
                  delete=args['--delete'])

    @register_cmd('clean')
    def cmd_clean(args):
        """
Sync the <file> as if all addons listed in <file> were
disabled. This will move all addons to `.wowplugcache`

Usage:
    wowplug clean [<file>] [--delete]

Options:
    -h --help           Show this message.
    -d --delete         Delete the unused addons instead of
                        placing them in `.wowplugcache`
"""
        pass

    # process main doc
    version = pkg_resources.get_distribution("wowplug").version
    args = docopt(doc, version=version, options_first=True, help=False)
    logging.config.dictConfig({
        'version': 1,
        'formatters': {
            'standard': {
                'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s'
            },
            'short': {
                'format': '%(levelname)s: %(name)s: %(message)s'
            },
        },
        'handlers': {
            'default': {
                '()': LoggingHandler,
                'formatter': 'short',  # standard
            },
        },
        'loggers': {
            '': {
                'handlers': ['default'],
                'level': "DEBUG" if args['--debug'] else "INFO",
                'propagate': False
            },
        }
    })
    if args['-h']:
        print(doc.strip("\n"))
        sys.exit(0)
    if args['--help']:
        # concat all docs in cmds
        fdoc = "{}\nAvailable commands:\n\n".format(doc)
        for cmd, cmd_func in cmds.items():
            fdoc += "{}:\n\n{}\n".format(
                cmd,
                indent(cmd_func.__doc__, "    ").strip('\n'))
        print(fdoc.strip("\n"))
        sys.exit(0)
    # execute command
    from .config import config
    config.load_saved_config = not args['--ignore-config']
    cmd = args['<command>']
    argv = [
        cmd,
    ] + args['<args>']
    if cmd in cmds:
        cmd_func = cmds[cmd]
        try:
            cmd_func(docopt(cmd_func.__doc__, argv=argv))
        except SchemaError as e:
            sys.exit("{}\n\n{}".format(
                cmderr_fmt.format(e.code),
                cmds[cmd].__doc__.strip("\n"),
            ))
        except Exception as e:
            f_locals = inspect.trace()[-1][0].f_locals
            if 'logger' in f_locals:
                logger = f_locals['logger']
            elif 'self' in f_locals:
                logger = getattr(f_locals['self'], "logger", None)
            else:
                logger = None
            if logger is not None:
                sys.exit(logger.exception(e))
            else:
                raise
    else:
        sys.exit(
            cmderr_fmt.format(
                "`{}` is not a valid wowplug command. See 'wowplug -h'.".
                format(cmd)))
    # save config file on exit
    config.save()