Пример #1
0
def main(argv=None):
    args = docpie(__doc__, argv=argv)
    if args['--list']:
        list_all()
        return 0
    elif args['--delete']:
        to_delete = int(args['--delete'])
        delete(to_delete)
        return 0
    else:
        fname = None if args['-'] else args['<file>']
        content = get_data(fname)
        raw_color = args['--color']
        if raw_color is None:
            if has_index_table:
                color_index = get_color_next_index() or 1
                color = get_color(index=color_index)['color']
            else:
                color = random.choice(colors)['color']
        elif raw_color.startswith('#'):
            color = raw_color
        elif raw_color.isdigit():
            color = get_color(index=int(raw_color))['color']
        else:
            color = get_color(name=raw_color)['color']
        raw_pagenr = args['--index']
        if raw_pagenr is None:
            pagenr = get_page_index() + 1
        else:
            pagenr = int(raw_pagenr)

        insert(color=color, body=content, pagenr=pagenr)
        return 0
Пример #2
0
def main(argv=sys.argv):
    version = pkg_resources.require("aws-glacier-tool")[0].version
    args = docpie(__doc__, argv=argv, version=version)

    try:
        if args['create']:
            create.handler(args)
        elif args['list']:
            list.handler(args)
        elif args['upload']:
            upload.handler(args)
        elif args['delete']:
            delete.handler(args)
        else:
            print(__doc__)
    except botocore.exceptions.NoRegionError:
        fatal(
            'You must specify a region. You can also configure your region by running "aws configure".'
        )
    except botocore.exceptions.NoCredentialsError:
        fatal(
            'Unable to locate credentials. You can configure credentials by running "aws configure".'
        )
    except Exception as ex:
        fatal(str(ex))
Пример #3
0
def get_command():
    pie = docpie.docpie(__doc__)

    if pie['--debug']:
        filelogger(pie['--debug'], logger)

    stdoutlogger(logger, INFO)

    logger.debug(pie)
    type_ = []
    if pie['--choose-word']:
        type_.append(Config.CHOOSE_WORD)
    if pie['--choose-meaning']:
        type_.append(Config.CHOOSE_MEANING)
    if not type_:
        type_.append(Config.SPELL)

    assert type_, type_

    if pie['--ascend']:
        order = Config.ASCEND
    elif pie['--descend']:
        order = Config.DESCEND
    else:
        order = Config.SHUFFLE

    config = Config.manual_init(type_=type_,
                                order=order,
                                repeat=not pie['--no-repeat'])

    outfile = pie['--out']
    if outfile:
        config.save_file = outfile
    else:
        config.save_file = StringIO()

    files = pie['<file>']
    start = int(pie['--skip'])
    count = pie['--limit']
    if count.lower() == 'inf':
        end = None
    else:
        count = int(count)
        end = start + count

    words = Words(files, start, end)

    return config, words
Пример #4
0
def trydocpie(doc, argv, *a, **k):

    with StdoutRedirect() as stdout:
        error = False
        try:
            pie = docpie.docpie(doc, argv, *a, **k)
        except (docpie.DocpieExit, SystemExit) as e:
            error = True
            output = str(e)
        else:
            output = str(pie)

        if not output.strip():
            output = stdout.getvalue()

    return error, output
Пример #5
0
    -c, --cover=<cover>
    -l, --local
"""

import os
import json
import docpie
import logging
import requests
from login import login_jolla
from parse import parse
from requests.packages.urllib3.exceptions import InsecureRequestWarning

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

args = docpie.docpie(__doc__)

logger = logging.getLogger()
logging.basicConfig(level=logging.DEBUG)
logging.getLogger('docpie').setLevel(logging.CRITICAL)
logger.setLevel(logging.DEBUG)

with open(os.path.normpath(os.path.join(__file__, '..', 'config.conf')),
          'r',
          encoding='utf-8') as f:
    config = json.load(f)

# login
user = args['--user'] or config['user']
pwd = args['--pwd'] or config['pwd']
if args['--local']:
Пример #6
0
"""
usage:
  python git.py add [options] [--] [<filepattern>...]

Options:
    -h, --help
    -n, --dry-run        dry run
    -v, --verbose        be verbose
    -i, --interactive    interactive picking
    -p, --patch          select hunks interactively
    -e, --edit           edit current diff and apply
    -f, --force          allow adding otherwise ignored files
    -u, --update         update tracked files
    -N, --intent-to-add  record only the fact that the path will be added later
    -A, --all            add all, noticing removal of tracked files
    --refresh            don't add, only refresh the index
    --ignore-errors      just skip files which cannot be added because of errors
    --ignore-missing     check if - even missing - files are ignored in dry run
"""

from docpie import docpie

if __name__ == "__main__":
    print(docpie(__doc__, name="git.py"))
Пример #7
0
'''
Naval Fate.
Usage:
  naval_fate.py ship new <name>...
  naval_fate.py ship <name> move <x> <y> [--speed=<kn>]
  naval_fate.py ship shoot <x> <y>
  naval_fate.py mine (set|remove) <x> <y> [--moored|--drifting]
  naval_fate.py -h | --help
  naval_fate.py --version
Options:
  -h --help     Show this screen.
  --version     Show version.
  --speed=<kn>  Speed in knots [default: 10].
  --moored      Moored (anchored) mine.
  --drifting    Drifting mine.
'''

from docpie import docpie

if __name__ == '__main__':
    print(docpie(__doc__, version='Naval Fate 2.0'))
Пример #8
0
   commit     Record changes to the repository
   push       Update remote refs along with associated objects
   remote     Manage set of tracked repositories
See 'git help <command>' for more information on a specific command.
'''

from subprocess import call
from docpie import docpie
import sys
import os

if __name__ == '__main__':

    top_dir = os.path.abspath(os.path.dirname(__file__))

    args = docpie(__doc__, name='git.py',
                  version='git version 1.7.4.4', optionsfirst=True)

    print('global arguments:')
    print(args)
    print('command arguments:')

    argv = [args['<command>']] + args['<args>']
    print('argv: %s' % argv)
    if args['<command>'] == 'add':
        # In case subcommand is implemented as python module:
        sys.path.insert(0, top_dir)
        import git_add
        sys.path.pop(0)
        argv.insert(0, sys.argv[0])
        print(docpie(git_add.__doc__, name='git.py', argv=argv))
        sys.exit()
Пример #9
0
                inner_pre = pre.decode_contents()
                pre_class = pre.get('class') or []
                inner_break = inner_pre.replace('\n', '<br />')
                pre_soup = BeautifulSoup(
                    '<pre class="{classes}">{content}</pre>'.format(
                        classes=' '.join(pre_class), content=inner_break),
                    'html5lib')
                pre.replace_with(pre_soup.find('pre'))

            body = soup.body.decode_contents()

            target_filename = filebase + '.html'
            logger.info('saving %s', target_filename)
            with open(os.path.join(target_folder, target_filename),
                      'w',
                      encoding='utf-8') as t:
                t.write(body)


if __name__ == '__main__':
    args = docpie.docpie(__doc__)
    logging.basicConfig()
    logger.setLevel(logging.DEBUG)
    if args['web']:
        args_port = args['<port>']
        port = int(args_port) if args_port is not None else 8080
        app.run(debug=False, port=port)
    elif args['gen']:
        # folder = args['<folder>']
        gen_folder()
Пример #10
0
    else:
        print(pie.usage_text)
        for title, content in pie.option_sections.items():
            if title.lower() == 'hidden':
                continue
            print(content)

        print(
            '\nActually one option section is hidden. Try `--help` to see it')
    sys.exit()


try:
    args = docpie(__doc__,
                  version=__version__,
                  extra={
                      ('-h', '--help', '-?'): help_handler,
                      ('-v', '--version'): version_handler,
                  })
except UnknownOptionExit as e:
    sys.stderr.write('What do you mean by %r?\n' % e.option)
    sys.exit(1)
except ExceptNoArgumentExit as e:
    sys.stderr.write(
        ('"%s" can not follows "%s".\n'
         "Do you mean `my --%s name is ...`?\n") %
        (e.hit, '/'.join(e.option), '/'.join(e.option).split('-')[2]))
    sys.exit(2)
except ExpectArgumentHitDoubleDashesExit as e:
    sys.stderr.write('NO, no. put your name directly after %s, not "--"\n' %
                     '/'.join(e.option))
    sys.exit(3)
Пример #11
0
   push       Update remote refs along with associated objects
   remote     Manage set of tracked repositories
See 'git help <command>' for more information on a specific command.
'''

from subprocess import call
from docpie import docpie
import sys
import os

if __name__ == '__main__':

    top_dir = os.path.abspath(os.path.dirname(__file__))

    args = docpie(__doc__,
                  name='git.py',
                  version='git version 1.7.4.4',
                  optionsfirst=True)

    print('global arguments:')
    print(args)
    print('command arguments:')

    argv = [args['<command>']] + args['<args>']
    print('argv: %s' % argv)
    if args['<command>'] == 'add':
        # In case subcommand is implemented as python module:
        sys.path.insert(0, top_dir)
        import git_add
        sys.path.pop(0)
        argv.insert(0, sys.argv[0])
        print(docpie(git_add.__doc__, name='git.py', argv=argv))
Пример #12
0
def parse():
    return docpie.docpie(__doc__)
'''
Example of program which uses [options] shortcut in pattern.

Usage:
  options_shortcut_example.py [options] <port>

Options:
  -h --help                show this help message and exit
  --version                show version and exit
  -n, --number N           use N as a number
  -t, --timeout TIMEOUT    set timeout TIMEOUT seconds
  --apply                  apply changes to database
  -q                       operate in quiet mode
'''

from docpie import docpie

if __name__ == '__main__':
    print(docpie(__doc__, version='0.0.1'))
Пример #14
0
'''
usage: python git.py remote [-v | --verbose]
       python git.py remote add [-t <branch>] [-m <master>] [-f] [--mirror] <name> <url>
       python git.py remote rename <old> <new>
       python git.py remote rm <name>
       python git.py remote set-head <name> (-a | -d | <branch>)
       python git.py remote [-v | --verbose] show [-n] <name>
       python git.py remote prune [-n | --dry-run] <name>
       python git.py remote [-v | --verbose] update [-p | --prune] [(<group> | <remote>)...]
       python git.py remote set-branches <name> [--add] <branch>...
       python git.py remote set-url <name> <newurl> [<oldurl>]
       python git.py remote set-url --add <name> <newurl>
       python git.py remote set-url --delete <name> <url>

options:
    -v, --verbose         be verbose; must be placed before a subcommand
'''

from docpie import docpie

if __name__ == '__main__':
    print(docpie(__doc__, name='git.py'))
Пример #15
0
    def get(self):
        example = self.get_argument('example', None)
        result = dict(self.default)
        result['file_name'] = 'pie.py'
        output = None
        if example:
            target_example = self.get_example(example)
            result.update(target_example)
        else:
            doc = self.get_argument('doc', None)
            if doc:
                doc = self.replace(doc)

            result['doc'] = doc
            argv = self.get_argument('argv', None)
            result['argv'] = argv
            if self.get_argument('run', False):
                name = self.get_argument('name', None) or None
                config = {
                    'help': self.get_bool('help'),
                    # may be empty str
                    'version': self.get_argument('version', None) or None,
                    'stdopt': self.get_bool('stdopt'),
                    'attachopt': self.get_bool('attachopt'),
                    'attachvalue': self.get_bool('attachvalue'),
                    'auto2dashes': self.get_bool('auto2dashes'),
                    'name': name,
                    'case_sensitive': self.get_bool('case_sensitive'),
                    'optionsfirst': self.get_bool('optionsfirst'),
                    'appearedonly': self.get_bool('appearedonly')
                }

                if name is not None:
                    result['file_name'] = name

                with StdoutRedirect() as stdout:
                    args = shlex.split('pie.py ' + (argv or ''))
                    try:
                        pie = docpie.docpie(doc, args, **config)
                    except BaseException as e:
                        # in pypy3, sys.exit() gives e.args[0] = None
                        output = (e.args[0] if e.args else '') or ''
                    else:
                        output = str(pie)

                    if not output.strip():
                        output = stdout.getvalue()

                result.update(config)

        if self.is_ajax():
            return self.write({'output': output})

        return self.render(
            'project/docpie/try.html',
            version=docpie.__version__,
            time=self.get_time(),
            doc=result.pop('doc'),
            argv=result.pop('argv'),
            file_name=result.pop('file_name'),
            output=output,
            modified=self.diff_config(result),
            config=result,
            jsonlize=json.dumps
        )
Пример #16
0
'''
Usage: option_format_example.py [options]

Options: -h, -?, --help        print this screen
         --verbose             print more message
         -a --arg=<arg>        this flag accept argument
         -b <arg>, --br=<arg>  you can announce argument twice
'''

from docpie import docpie

if __name__ == '__main__':
    print(docpie(__doc__))
Пример #17
0
import os
import requests
import docpie

try:
    from urllib.parse import quote
except ImportError:
    from urllib import quote

from md import jolla_md_to_html
from jwt_login import LoginReq

# import logging
# logging.basicConfig(level=logging.DEBUG)

args = docpie.docpie(__doc__, appearedonly=True, help=False)
host = args.get('--host', 'https://notexists.top') + '/api'
if not host.startswith('http'):
    host = 'http://' + host

print('get host {}'.format(host))
user = args.get('--user', None)
if user:
    print('get user from input')
    pwd = args['--pwd']
else:
    print('get user from account.json')
    with open(os.path.normpath(os.path.join(__file__, '..', 'account.json')),
              'r',
              encoding='utf-8') as f:
        account = json.load(f)