Пример #1
0
def cmd_users_fields(config):
    list_exclude = """aboutMe, birthday, hireDate, interests, mySite,
        pastProjects, preferredName, responsibilities, schools, skills,
        mailboxSettings""".replace(",", '').split()

    fields = sorted(get_fields('user'))
    pyaml.p(fields)
def main(config_filename='config.yaml', debug=False, alert_days=None):
    # Browse to a page with an upload form
    config = read_config(config_filename)

    # TODO Search each account in parallel, then show results at the end
    sc = StatusChecker(config)

    for account in config['accounts']:
        status = sc.status(account['username'], account['password'], account.get('name', None))
        print "Status for {}:".format(status.name)
        if len(status.loans) == 0:
            print "No loans."
        else:
            print tabulate(to_rows(status),
                    headers=("Days Left", "Due", "Overdue", "Title", "Author"))
            if alert_days is not None:
                alert_loans(account.get('name', 'Someone'),
                        status.loans,
                        sc.base_url,
                        config['pushbullet']['api_key'],
                        alert_days)

        if status.fees_cents > 0:
            print "You have ${:0.2f} in fees.".format(status.fees_cents/100.0)
        print
        if debug:
            pyaml.p([l.data for l in status.loans_by_due_date])
Пример #3
0
def main(config_filename='config.yaml', debug=False, alert_days=None):
    # Browse to a page with an upload form
    config = read_config(config_filename)

    # TODO Search each account in parallel, then show results at the end
    sc = StatusChecker(config)

    for account in config['accounts']:
        status = sc.status(account['username'], account['password'],
                           account.get('name', None))
        print "Status for {}:".format(status.name)
        if len(status.loans) == 0:
            print "No loans."
        else:
            print tabulate(to_rows(status),
                           headers=("Days Left", "Due", "Renewals", "Overdue",
                                    "Title", "Author"))
            if alert_days is not None:
                alert_loans(account.get('name',
                                        'Someone'), status.loans, sc.base_url,
                            config['pushbullet']['api_key'], alert_days)

        if status.fees_cents > 0:
            print "You have ${:0.2f} in fees.".format(status.fees_cents /
                                                      100.0)
        print
        if debug:
            pyaml.p([l.data for l in status.loans_by_due_date])
Пример #4
0
def get_parent(config):
    """
    Example:
        ct get-parent SPACE:title -F "{page.id} {id}"

    Where page.id is the page's id and id is the parent's id.
    """
    cql = config.confluence_api.resolveCQL(config.get('cql'))

    results = {}
    for page in config.confluence_api.getPages(cql=cql, expand='ancestors'):
        results[page['id']] = page['ancestors'][-1]
        results[page['id']]['page'] = page.dict()

    output_filter = lambda x: x

    if config.get('format'):
        for result in results.values():
            if '{}' in config['format']:
                fields = [result[f] for f in config['field']]
                print config['format'].format(*fields)

            print output_filter(unicode(
                config['format']).format(**result)).encode('utf-8')

    else:
        if config['write'] == 'json':
            import json
            json.dump(results, sys.stdout)

        elif config['write'] == 'yaml':
            import pyaml
            pyaml.p(results)
Пример #5
0
def cmd_alert_expand_rules(config):
    config_factory = ConfigFactory(config)

    #    config = read_config(config)

    for r in Alerter.expand_rules(config_factory):
        print("---")
        pyaml.p(r)
Пример #6
0
def dump(obj):
    if OUTPUT_FORMAT == 'yaml':
        try:
            pyaml.p(obj)
            return
        except ImportError:
            pass

    json.dump(obj, sys.stdout, indent=2)
Пример #7
0
def render(struct, args, networks):
    # Render yaml file
    if args.version == 1:
        pyaml.p(OrderedDict(struct))
    else:
        pyaml.p(
            OrderedDict({
                'version': '"3"',
                'services': struct,
                'networks': networks
            }))
Пример #8
0
    def _color_words_in_text(self, text, occurrencies, fPRINT=False):
        if isinstance(text, list): text=' '.join(text)
        _lpad=self._inp_args.text_size
        _rpad=self._inp_args.text_size
        result = {}

        # - preparazione word colorate
        colors = [C.gMagentaH, C.gYellowH, C.gCyanH, C.gRedH, C.gGreenH, C.gBlueH, C.gWhiteH]
        words=occurrencies.keys()
        tot_counter=0
        for word in words:
            result[word] = {}
            result[word]['counter'] = len(words)
            tot_counter += len(words) # counter totale
            result['data'] = {}
            ptr=result['data']

            word_len=len(word)
            for pos in occurrencies[word]:
                _from, _to = pos
                # - get text around the found word
                _from=0 if _from-_lpad<0 else _from-_lpad
                _to=_to+_rpad
                data=text[_from:_to].replace('\n', ' ')
                data = ' '.join(data.split()) # remove multiple blanks


                '''
                new_text=text.replace(cur_word, colored_word) # no good perché case-sensitive
                redata = re.compile(re.escape(cur_word), re.IGNORECASE)
                new_text = redata.sub(colored_word, text)
                '''

                """
                    replace word(s) with colored_word
                    ruotiamo sulle word in modo da colorarle
                    se fossero presenti nello stesso testo
                """
                for i, w in enumerate(words):
                    colored_word = colors[i](text=w)
                    data = re.sub(w, colored_word, data, flags=re.IGNORECASE)

                # - wrap text to easy displaying
                tb=textwrap.wrap(data, 80, break_long_words=True)

                # - save it into result list
                ptr[tot_counter] = []
                ptr[tot_counter].extend(tb)

                if fPRINT:
                    pyaml.p(result)

        return result
Пример #9
0
def cmd_users_show(config, all_fields, select, user):
    params = get_input_docs(user)[0]
    if select:
        params['select'] = select
    if all_fields:
        params['select'] = ",".join(get_fields('user'))

    api = get_api(config)

    for u in user:
        data = api.get("users/" + u, params).json()
    pyaml.p(data)
Пример #10
0
def search(config):  #host, format, query):
    pyaml.p(config)
    return 0

    format = config.get('search.format')
    query = config.get('search.query')

    content = None
    if query == '-':
        content = sys.stdin.read()
    elif exists(query):
        with open(query, 'r') as f:
            content = f.read()
    else:
        config = {}
        config['query'] = query
        config['format'] = format

    if content is not None:
        if content.startswith("---"):
            import frontmatter
            config, content = frontmatter.loads(content)
            config['template'] = content
        else:
            config = yaml.loads(io.StringIO(content))

    body = build_search_body(config, 'search')
    es = elasticsearch(config)
    results = es.search(index=config.get('index', '*'), body=body)

    if config['format']:
        for hit in results['hits']['hits']:
            print(config['format'].format(hit))

    elif config['template']:
        import chevron
        args = {}
        for k in ('template', 'partials_path', 'partials_ext', 'partials_dict',
                  'padding', 'def_ldel', 'def_rdel'):
            if k in config:
                args[k] = config[k]

        data = config.get('data', {}).copy()
        data.update(results)
        args['data'] = data
        print(chevron.render(**args))

    else:
        pyaml.p(results)
Пример #11
0
def alerter_status(config):
    alerter = Alerter(elasticsearch(config), config=config)
    statuses = {}
    for rule in alerter.iterate_rules():
        key = rule.getval('key')
        status = alerter.read_status(key=key)
        if config['alerter.status.all']:
            statuses[key] = status
        else:
            if status['alerts']:
                statuses[key] = status
#    result = alerter.read_status(key='heartbeat_tcp_cal2')
#    from pprint import pprint
#    pprint(result)
    pyaml.p(statuses)
Пример #12
0
def config(config):
    """\
    Get or set configuration.

    For configuring the default base
    """

    if config.get('update') or config.get('update_password'):
        config.setConfig(config.get('update_password'))
        return

    if config.get('baseurl'):
        config.setConfig()
    else:
        cfg = config.getConfig()

        if cfg.get('show_password') and not config.get('show_password'):
            cfg['password'] = '******'

        pyaml.p(cfg)
Пример #13
0
def move(config):
    confluence = config.getConfluenceAPI()
    first = True

    parent = confluence.getPage(confluence.resolveCQL(config.parent))
    cql = confluence.resolveCQL(config.cql)
    filter = config.filter

    for page in confluence.getPages(cql, filter=filter, expand=['version']):
        result = confluence.movePage(page, parent=parent)

        if not first:
            print("---")

        pyaml.p(result)

        first = False

    if first:
        print("could not find a page matching %s (%s)" % (cql, filter))
Пример #14
0
def cmd_page_prop_get(config):
    confluence = config.getConfluenceAPI()
    results = []
    config['cql'] = confluence.resolveCQL(config['cql'])
    first = True
    for pp in confluence.getPages(**config.dict('cql', 'filter')):
        if first:
            first = False
        else:
            print "---"

        if config.get('add'):
            results.append(confluence.addLabels(pp.id, config['add']))
        if config.get('remove'):
            try:
                results.append(confluence.deleteLabels(pp.id,
                                                       config['remove']))
            except ConfluenceError as e:
                print "Warning: %s" % e
                continue

        pyaml.p(pp.dict('id', 'spacekey', 'title', 'labels'))
Пример #15
0
def cmd_users_ls(config, all_fields, select, filter, param):
    params = get_input_docs(param)[0]
    if all:
        params['$select'] = ",".join(get_fields('user'))

    if filter:
        params['$filter'] = filter

    # see https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user_list
    exclude = """aboutMe, birthday, hireDate, interests, mySite,
        pastProjects, preferredName, responsibilities, schools, skills,
        mailboxSettings""".replace(",", '').split()
    select = []
    for field in params['$select'].split(","):
        if field not in exclude:
            select.append(field)
    params['$select'] = ",".join(select)

    api = get_api(config)

    data = api.get("users", params).json()
    pyaml.p(data)
Пример #16
0
def cmd_plans_ls(config, query, full):
    from .service_plans import SERVICE_PLANS
    if query:
        _matches = create_matcher(query)

        results = []
        for k, v in SERVICE_PLANS['skus_by_string_id'].items():
            if _matches(v):
                results.append(v)
    else:
        results = SERVICE_PLANS['skus_by_string_id'].values()

    if not full:
        _results = {}
        for v in results:
            _name = v['productName']
            _plans = [p['stringId'] for p in v['availablePlans'].values()]
            _results[_name] = _plans

        return pyaml.p(_results)
    else:
        return pyaml.p(dict((x['productName'], x) for x in results))
Пример #17
0
def alerter_expand_rules(config):
    """Expand rules, that you can check, if they are correct

    This command expands the rules like in a regular alerter run and prints
    them to stdout in YAML format.  This way you can check, if all variables
    and defaults are expanded as expected.
    """
    expanded_rules = Alerter.expand_rules(config)
    if config['alerter.expand-rules.list']:
        expand = config['alerter.expand-rules.list']

        if expand in ('names', 'keys', 'types'):
            for name in set([ rule[expand[:-1]] for rule in expanded_rules ]):
                print(name)

        if expand == 'alerts':
            for name in set([ "%s-%s" % (rule['type'], rule['key']) for rule in expanded_rules ]):
                print(name)

    elif config['alerter.expand-rules.format']:
        for rule in expanded_rules:
            print(config['alerter.expand-rules.format'].format(**rule))
    else:
        pyaml.p(expanded_rules)
Пример #18
0
def handle_response(response, quiet=False, verbose=False):
    if isinstance(response, list):
        assert len(response) == 1, "Response list not yet supported"
        response = response[0]

    try:
        result = response.json()
    except:
        result = make_response_dict(response)

    if verbose:
        # result = {"request": { "headers", response.request.headers}
        #
        # add request and response
        #
        pass

    if not quiet:
        pyaml.p(result)

    if 200 <= int(response.status_code) < 300:
        return 0
    else:
        return 1
Пример #19
0
def cmd_create_command(config, mailNickname, displayName, internal):
    data = dict(
        displayName=displayName,
        mailEnabled=True,
        mailNickname=mailNickname,
        securityEnabled=False,
        groupTypes=["Unified"],
    )

    api = get_api(config)
    response = api.post('groups', data)

    try:
        data = response.json()
        pyaml.p(data)
    except:
        return handle_response(response)

    response = api.patch('groups/%(id)s' % data,
                         dict(allowExternalSenders=not internal, ))
    handle_response(response)
    response = api.patch('groups/%(id)s' % data,
                         dict(autoSubscribeNewMembers=True, ))
    return handle_response(response)
Пример #20
0
def space_list(config):
    # type, status, label, expand
    kwargs = config.dict('expand', 'status', 'type', 'label')
    if kwargs['type'] == 'all':
        del kwargs['type']

    results = [ r for r in config.confluence_api.listSpaces(**kwargs) ]

    if config.get('write') == 'format':
        if config.get('format'):
            for result in results:
                if '{}' in config['format']:
                    fields = [ result[f] for f in config['field'] ]
                    print(config['format'].format(*fields))
                else:
                    print(unicode(config['format']).format(**result))
    else:
        if config['write'] == 'json':
            import json
            json.dump(results, sys.stdout)

        elif config['write'] == 'yaml':
            import pyaml
            pyaml.p(results)
Пример #21
0
def alerter_show(config):
    alerter = Alerter(elasticsearch(config), config)
    if config['alerter.show.item'] == 'rules':
        data = dict((r['name'], r)
            for r in [rule.format() for rule in alerter.iterate_rules(ordered=False)])

        if config['alerter.show.details']:
            pyaml.p(data)
        else:
            pyaml.p(sorted([data[k].get('key') for k in data.keys()]))
            #pyaml.p(sorted([k for k in data.keys()]))
    elif config['alerter.show.item'] == 'alerts':
        data = dict(('{}.{}'.format(*alerter.get_alert_key_type(alert)), alert)
            for rule,alerts in alerter.iterate_alerts()
            for alert in alerts
        )
        if config['alerter.show.details']:
            pyaml.p(data)
        else:
            pyaml.p(sorted([k for k in data.keys()]))
Пример #22
0
    def _color_words_in_text(self, text, occurrencies, fPRINT=False):
        """
            occurrencies=
                    { 'word1': [
                        (2553, 2561),
                        (2678, 3456)
                        ]
                    }
         - return = {
                       word1: []     # text con le occorrensze colorate
                       word2: []     # text con le occorrensze colorate
                       wordn...
         - return = {
                       word1:
                           counter: x  # numero di occoorrenze
                           data: []     # text con le occorrensze colorate
                       word2:
                           counter: x
                           data: []
                       wordn...
        """
        if isinstance(text, list): text=' '.join(text)
        text_before=self._inp_args.text_size
        text_after=self._inp_args.text_size
        result = {}

        # - preparazione word colorate
        colors = [C.gMagentaH, C.gYellowH, C.gCyanH, C.gRedH, C.gGreenH, C.gBlueH, C.gWhiteH]
        words=occurrencies.keys()
        tot_counter=0
        for word in words:
            result[word] = []
            ptr=result[word]

            word_len=len(word)
            for pos in occurrencies[word]:
                _from, _to = pos
                # - get text around the word
                _from -= text_before
                if _from<0: _from=0
                _to=_to+text_after
                data=text[_from:_to].replace('\n', ' ')
                data = ' '.join(data.split()) # remove multiple blanks

                '''
                new_text=text.replace(cur_word, colored_word) # no good perché case-sensitive
                redata = re.compile(re.escape(cur_word), re.IGNORECASE)
                new_text = redata.sub(colored_word, text)
                '''

                """
                    replace word(s) with colored_word
                    ruotiamo sulle word in modo da colorarle
                    se fossero presenti nello stesso testo
                """
                for i, w in enumerate(words):
                    colored_word = colors[i](text=w)
                    data = re.sub(w, colored_word, data, flags=re.IGNORECASE)

                # - wrap text to easy displaying
                tb=textwrap.wrap(data, 80, break_long_words=True)

                # - save it into result list
                # ptr[tot_counter] = []
                # ptr[tot_counter].extend(tb)
                result[word]=data
                if fPRINT:
                    pyaml.p(result)

        return result
Пример #23
0
def cmd_page_prop_get(config):
    """\
    Get page properties.

    For each page there is printed a YAML document with `id`, `title` and
    `spacekey`.  Page properties are printed under `pageProperties`.

    Optionally you can pass some page property filter expressions to filter
    pages on page properties additionally to CQL query.

    Please note, when using `--format`:

    For convenience in format string, you can directly refer to page properties
    in format string.  Items referring to page can be fetched with `page_id`,
    `page_title` and `page_spacekey`.

    Examples:

     - `ct page-prop-get "SpaceName:Some Title"`

        gets all page properties from "Some title" in space "Space Name"

     - `ct page-prop-get "SpaceName:Some Title" Pageproperty1 Pageproperty2`

       get Pageproperty1 and Pageproperty2 from "Some title" in space "Space Name"

     - `ct page-prop-get "label = 'some-label'"`

        gets all page properties for all pages with label 'some-label'
    """
    confluence = config.getConfluenceAPI()
    first = True

    if config.get('dict'):
        results = {}

    kwargs = config.dict('cql', 'filter', 'state')
    kwargs['expand'] = ['ancestors']

    for pp in confluence.getPagesWithProperties(**kwargs):

        parent = pp['ancestors'][-1]
        parent = dict(id=parent['id'],
                      title=parent['title'],
                      spacekey=pp.spacekey)
        if config.get('format'):
            try:

                if '{}' in config['format']:
                    fields = [
                        pp.pageProperty.get(f, '') for f in config['props']
                    ]
                    if six.PY3:
                        print(config['format'].format(*fields))
                    else:
                        print(
                            unicode(config['format']).format(
                                *fields).encode('utf-8'))
                else:
                    _props = dict(pp.getPageProperties())
                    _props.update(
                        dict([(k.lower(), v) for (k, v) in _props.items()]))
                    _props.update(page_id=pp.id,
                                  page_title=pp.title,
                                  page_spacekey=pp.spacekey)
                    _props.update(parent=parent)

                    if six.PY3:
                        print(config['format'].format(*fields))
                    else:
                        print(
                            unicode(config['format']).format(
                                **_props).encode('utf-8'))

            except UnicodeEncodeError:
                import traceback
                sys.stderr.write("Error formatting %s:%s\n %s\n" %
                                 (pp.spacekey, pp.title,
                                  repr(dict(pp.getPageProperties()))))
        else:
            result = pp.dict("id", "spacekey", "title")
            if config.get('ordered'):
                result['pageProperties'] = []
                for item in pp.getPageProperties(*config.props):
                    result['pageProperties'].append(dict([item]))
            else:
                result['pageProperties'] = dict(
                    pp.getPageProperties(*config.props))

            result['parent'] = "{spacekey}:{title}".format(**parent)

            if config.get('dict'):
                results[result['id']] = result
            else:
                if not first:
                    print("---")
                else:
                    first = False

                #result = pp.dict("id", "spacekey", "title")
                #result['pageProperties'] = dict(pp.getPageProperties(*config.props))

                pyaml.p(result)

    if config.get('dict'):
        pyaml.p(results)
def print_info(page, result):
    pyaml.p(
        dict(id=page.id,
             spacekey=page.spacekey,
             title=page.title,
             cwInfo=result))
Пример #25
0
def cmd_indices(config):
    from .connection import elasticsearch
    es = elasticsearch(config)
    pyaml.p([idx for idx in es.indices.get('_all').keys()])
Пример #26
0
def show_user(api, userPrincipalName):
    userPrincipalName = api.getUserPrincipalName(userPrincipalName)
    data = api.get(f("users/{userPrincipalName}")).json()
    pyaml.p(data)
Пример #27
0
def generate(args):
    c = Client(base_url='unix://var/run/docker.sock')

    try:
        cid = [x['Id'] for x in c.containers() if args.cname in x['Names'][0]][0]
    except IndexError:
        print("That container is not running.")
        sys.exit(1)

    cinspect = c.inspect_container(cid)


    # Build yaml dict structure

    cfile = {}
    cfile[args.cname] = {}
    ct = cfile[args.cname]

    values = {
        'cap_add': cinspect['HostConfig']['CapAdd'],
        'cap_drop': cinspect['HostConfig']['CapDrop'],
        'cgroup_parent': cinspect['HostConfig']['CgroupParent'],
        'container_name': args.cname,
        'devices': cinspect['HostConfig']['Devices'],
        'dns': cinspect['HostConfig']['Dns'],
        'dns_search': cinspect['HostConfig']['DnsSearch'],
        'environment': cinspect['Config']['Env'],
        'extra_hosts': cinspect['HostConfig']['ExtraHosts'],
        'image': cinspect['Config']['Image'],
        'labels': cinspect['Config']['Labels'],
        'links': cinspect['HostConfig']['Links'],
        'log_driver': cinspect['HostConfig']['LogConfig']['Type'],
        'log_opt': cinspect['HostConfig']['LogConfig']['Config'],
        'net': cinspect['HostConfig']['NetworkMode'],
        'security_opt': cinspect['HostConfig']['SecurityOpt'],
        'ulimits': cinspect['HostConfig']['Ulimits'],
        'volumes': cinspect['HostConfig']['Binds'],
        'volume_driver': cinspect['HostConfig']['VolumeDriver'],
        'volumes_from': cinspect['HostConfig']['VolumesFrom'],
        'cpu_shares': cinspect['HostConfig']['CpuShares'],
        'cpuset': cinspect['HostConfig']['CpusetCpus']+','+cinspect['HostConfig']['CpusetMems'],
        'entrypoint': cinspect['Config']['Entrypoint'],
        'user': cinspect['Config']['User'],
        'working_dir': cinspect['Config']['WorkingDir'],
        'domainname': cinspect['Config']['Domainname'],
        'hostname': cinspect['Config']['Hostname'],
        'ipc': cinspect['HostConfig']['IpcMode'],
        'mac_address': cinspect['NetworkSettings']['MacAddress'],
        'mem_limit': cinspect['HostConfig']['Memory'],
        'memswap_limit': cinspect['HostConfig']['MemorySwap'],
        'privileged': cinspect['HostConfig']['Privileged'],
        'restart': cinspect['HostConfig']['RestartPolicy']['Name'],
        'read_only': cinspect['HostConfig']['ReadonlyRootfs'],
        'stdin_open': cinspect['Config']['OpenStdin'],
        'tty': cinspect['Config']['Tty']
    }

    # Check for command and add it if present.
    if cinspect['Config']['Cmd'] != None:
        values['command'] = " ".join(cinspect['Config']['Cmd']),

    # Check for exposed/bound ports and add them if needed.
    try:
        expose_value =  list(cinspect['Config']['ExposedPorts'].keys())
        ports_value = [cinspect['HostConfig']['PortBindings'][key][0]['HostIp']+':'+cinspect['HostConfig']['PortBindings'][key][0]['HostPort']+':'+key for key in cinspect['HostConfig']['PortBindings']]

        # If bound ports found, don't use the 'expose' value.
        if (ports_value != None) and (ports_value != "") and (ports_value != []) and (ports_value != 'null') and (ports_value != {}) and (ports_value != "default") and (ports_value != 0) and (ports_value != ",") and (ports_value != "no"):
            for index, port in enumerate(ports_value):
                if port[0] == ':':
                    ports_value[index] = port[1:]

            values['ports'] = ports_value
        else:
            values['expose'] = expose_value

    except KeyError:
        # No ports exposed/bound. Continue without them.
        ports = None

    # Iterate through values to finish building yaml dict.
    for key in values:
        value = values[key]
        if (value != None) and (value != "") and (value != []) and (value != 'null') and (value != {}) and (value != "default") and (value != 0) and (value != ",") and (value != "no"):
            ct[key] = value

    # Render yaml file
    pyaml.p(cfile)
Пример #28
0
def show(config):
    """show a confluence item


    """
    """show a confluence item

    If specifying data selector file, there is added a special field
    body['data'] to each page.

    Format of selector file:

    select: <CSS Selector for jQuery>
    list:
        - attr: href
          name: href

    Following keys:

    - list: each item produces a list item.  Input is current selected element.
    - object: each item produces a object property.  Each item must have "name"
        key for specifing the properties name
    - attr: read named attribute from current selected element
    - select: find elements using this selector.  For each of them apply current
      spec
    - text: 'text' or 'html'.  this is the default and default is to return
        'text'.

    Examples:

     - `ct show "SpaceName:Some Title"`

        gets page information which can be expanded

     - `ct show "SpaceName:Some Title" -e body`

        gets page information with expanded body (can also be expanded)

     - `ct show "SpaceName:Some Title" -e body,container`

        gets page information and expand more than one

     - `ct show "SpaceName:Some Title" -e 'body.view' -F '{body[view][value]}'`

        gets page information with more detailed expanded body (this is --html)

     - `ct show "SpaceName:Some Title" -F {_links[self]}`

        gets "self"-link expanded from "_links" from "Some Title"
    """
    first = True

    mustache, format, printf = None, None, None

    output_filter = lambda x: x

    if not config.get('format') and not config.get('expand'):
        if config.get('html'):
            config['format'] = u'{body[view][value]}'
            config['expand'] = 'body.view'

            from html5print import HTMLBeautifier
            output_filter = lambda x: HTMLBeautifier.beautify(x, 4)

        elif config.get('storage'):
            config['format'] = u'{body[storage][value]}'
            config['expand'] = 'body.storage'

            from html5print import HTMLBeautifier
            output_filter = lambda x: HTMLBeautifier.beautify(x, 4)

        elif config.get('ls'):
            config['format'] = u'{id}  {spacekey}  {title}'
            config['field'] = ['id', 'spacekey', 'title']

    results = []
    log.debug('config: %s', config.args)
    kwargs = config.dict('cql', 'expand', 'filter', 'state')
    log.debug('kwargs: %s', kwargs)
    kwargs['cql'] = config.confluence_api.resolveCQL(kwargs['cql'])

    for page in config.confluence_api.getPages(**kwargs):
        rec = page.dict(*config['field'])
        if config.get('beautify'):
            from html5print import HTMLBeautifier
            if rec.get('body', {}).get('storage', {}).get('value'):
                rec['body']['storage']['value'] = HTMLBeautifier.beautify(
                    rec['body']['storage']['value'], 4)
            if rec.get('body', {}).get('view', {}).get('value'):
                rec['body']['view']['value'] = HTMLBeautifier.beautify(
                    rec['body']['view']['value'], 4)

        results.append(rec)

    if config.get('format'):
        for result in results:
            if '{}' in config['format']:
                fields = [result[f] for f in config['field']]
                print config['format'].format(*fields)

            print output_filter(unicode(
                config['format']).format(**result)).encode('utf-8')

    elif config.get('data'):
        if config.get('data') == '-':
            data = get_list_data(sys.stdin.read())
        else:
            with open(config.get('data'), 'r') as f:
                data = get_list_data(f.read())

        from ..data_generator import generate_data

        pyaml.p(generate_data(data, results))

    else:
        if len(results) == 1:
            results = results[0]

        if config['write'] == 'json':
            import json
            json.dump(results, sys.stdout)

        elif config['write'] == 'yaml':
            import pyaml
            pyaml.p(results)
Пример #29
0
def cmd_edit(config):
    """\
    edit a confluence page using CSS selections

    Pass a dictionary in YAML or JSON format via STDIN or file to
    confluence-tool, which defines edit actions to edit all matching pages.
    """

    confluence = config.getConfluenceAPI()
    first = True

    if not config['file']:
        content = sys.stdin.read()
    else:
        with open(config['file'], 'r') as f:
            content = f.read()

    try:
        editor_config = yaml.safe_load(content)
    except:
        editor_config = dict(actions=[dict(content=content)])

    if isinstance(editor_config, basestring):
        editor_config = dict(actions=[dict(content=editor_config)])

    if 'page' in editor_config:
        cql = confluence.resolveCQL(editor_config.pop('page'))

    if 'cql' in editor_config:
        cql = editor_config.pop('cql')
    if config['cql']:
        cql = config['cql']

    #editor = StorageEditor(confluence, **editor_config)

    found = False
    for page,content in confluence.editPages(confluence.resolveCQL(cql), filter=config.filter, editor=editor_config):
        found = True
        if not first:
            print("---")
        first = False

        from html5print import HTMLBeautifier
        b = HTMLBeautifier.beautify

        if config.show:
            p = page.dict('id', 'spacekey', 'title')

            p['content'] = b(content, 2)
            pyaml.p(p)

        elif config.diff:
            p = page.dict('id', 'spacekey', 'title')

            old = b(page['body']['storage']['value']).splitlines(1)
            new = b(content).splitlines(1)

            d = Differ()
            result = list(d.compare(old, new))

            p['diff'] = ''.join(result)
            pyaml.p(p)

        else:
            p = page.dict('id', 'title', 'version')
            p['storage'] = content
            p['version'] = int(page['version']['number'])+1

            result = confluence.updatePage(**p)
            pyaml.p(result)

    if not found:
        space, title = cql.split(':', 1)

        editor = StorageEditor(confluence, **editor_config)
        content = editor.edit('<R></R>')[3:-4]
        data = dict(
            page    = dict(
                spacekey = space,
                title    = title,
            ),
            content = content,
            result  = confluence.createPage(
                space = space,
                title = title,
                storage = content,
                parent = config.parent
            ))
Пример #30
0
def cmd_update(config):
    """\
    edit a confluence page using CSS selections

    Pass a dictionary in YAML or JSON format via STDIN or file to
    confluence-tool, which defines edit actions to edit all matching pages.

    """

    confluence = config.getConfluenceAPI()
    first = True

    if not config['file'] or config['file'] == '-':
        content = sys.stdin.read()
    else:
        with open(config['file'], 'r') as f:
            content = f.read()

    # if 'page' in editor_config:
    #     cql = confluence.resolveCQL(editor_config.pop('page'))

    if config.get('pagename'):
        cql = config['pagename']

    if config.get('cql'):
        cql = config['cql']

    representation = 'storage'
    if config['wiki']:
        representation = 'wiki'

    found = False
    for page in confluence.getPages(confluence.resolveCQL(cql), filter=config.filter, expand=['version']):
        p = page.dict('id', 'title', 'version')
        p['storage'] = content
        p['version'] = int(page['version']['number'])+1
        # Not needed at the moment, as representation is based on parameters
        # wiki and storage.
        #p['representation'] = representation

        result = confluence.updatePage(**p)
        found = True

        if not config['quiet']:
            pyaml.p(result)

        if config['label']:
            confluence.addLabels(p['id'], config['label'])

    if not found:
        space, title = cql.split(':', 1)

        data = dict(
            page    = dict(
                spacekey = space,
                title    = title,
            ),
            content = content,
            result  = confluence.createPage(
                space = space,
                title = title,
                type = config['page_type'],
                storage = content,
                parent = config.parent,
                representation = representation
            ))

        if config['label']:
            data['labels'] = confluence.addLabels(data['result']['id'], config['label'])

        if not config['quiet']:
            pyaml.p(data)
Пример #31
0
 def writeConfig(self):
     with open(self.config_file, 'w') as f:
         pyaml.p(self.config, file=f)
Пример #32
0
def cmd_group_ls(config):
    api = get_api(config)
    data = api.get("groups").json()
    pyaml.p(data)