示例#1
0
def configuration():
    global PARAM
    helpmsg = '''group directories before files.
				augment with a --sort option, but any
				use of --sort=none (-U) disables grouping
			  '''
    default_cfgfile = './test.conf'

    cfgdict = (('MDS_IP', 'M', '192.168.0.149', 'ip address of metadata server'), \
       ('MDS_PORT','m','6789','port of metadata server'), \
       ('CHK_IP','C', '192.168.0.149', helpmsg), \
       ('CHK_PORT','c', '3456', 'the port of chunk server'),\
       ('enablexxx','x',False,'enable x'),\
       ('cfgfile','f', default_cfgfile, 'name of the configuration file'))

    configure, _ = config.config(cfgdict)
    PARAM = util.Object(configure)
    default_cfgfile = './test.conf'
    print '----------------', PARAM.MDS_IP
    print '----------------', PARAM.MDS_PORT
示例#2
0
    def update(self,
               recursive=False,
               init=True,
               to_latest_revision=False,
               progress=None,
               dry_run=False):
        """Update the repository of this submodule to point to the checkout
        we point at with the binsha of this instance.

        :param recursive: if True, we will operate recursively and update child-
            modules as well.
        :param init: if True, the module repository will be cloned into place if necessary
        :param to_latest_revision: if True, the submodule's sha will be ignored during checkout.
            Instead, the remote will be fetched, and the local tracking branch updated.
            This only works if we have a local tracking branch, which is the case
            if the remote repository had a master branch, or of the 'branch' option
            was specified for this submodule and the branch existed remotely
        :param progress: UpdateProgress instance or None of no progress should be shown
        :param dry_run: if True, the operation will only be simulated, but not performed.
            All performed operations are read-only
        :note: does nothing in bare repositories
        :note: method is definitely not atomic if recurisve is True
        :return: self"""
        if self.repo.bare:
            return self
        #END pass in bare mode

        if progress is None:
            progress = UpdateProgress()
        #END handle progress
        prefix = ''
        if dry_run:
            prefix = "DRY-RUN: "
        #END handle prefix

        # to keep things plausible in dry-run mode
        if dry_run:
            mrepo = None
        #END init mrepo

        # ASSURE REPO IS PRESENT AND UPTODATE
        #####################################
        try:
            mrepo = self.module()
            rmts = mrepo.remotes
            len_rmts = len(rmts)
            for i, remote in enumerate(rmts):
                op = FETCH
                if i == 0:
                    op |= BEGIN
                #END handle start

                progress.update(
                    op, i, len_rmts, prefix +
                    "Fetching remote %s of submodule %r" % (remote, self.name))
                #===============================
                if not dry_run:
                    remote.fetch(progress=progress)
                #END handle dry-run
                #===============================
                if i == len_rmts - 1:
                    op |= END
                #END handle end
                progress.update(
                    op, i, len_rmts, prefix +
                    "Done fetching remote of submodule %r" % self.name)
            #END fetch new data
        except InvalidGitRepositoryError:
            if not init:
                return self
            # END early abort if init is not allowed
            import git

            # there is no git-repository yet - but delete empty paths
            module_path = join_path_native(self.repo.working_tree_dir,
                                           self.path)
            if not dry_run and os.path.isdir(module_path):
                try:
                    os.rmdir(module_path)
                except OSError:
                    raise OSError(
                        "Module directory at %r does already exist and is non-empty"
                        % module_path)
                # END handle OSError
            # END handle directory removal

            # don't check it out at first - nonetheless it will create a local
            # branch according to the remote-HEAD if possible
            progress.update(
                BEGIN | CLONE, 0, 1,
                prefix + "Cloning %s to %s in submodule %r" %
                (self.url, module_path, self.name))
            if not dry_run:
                mrepo = git.Repo.clone_from(self.url, module_path, n=True)
            #END handle dry-run
            progress.update(END | CLONE, 0, 1,
                            prefix + "Done cloning to %s" % module_path)

            if not dry_run:
                # see whether we have a valid branch to checkout
                try:
                    # find  a remote which has our branch - we try to be flexible
                    remote_branch = find_first_remote_branch(
                        mrepo.remotes, self.branch_name)
                    local_branch = mkhead(mrepo, self.branch_path)

                    # have a valid branch, but no checkout - make sure we can figure
                    # that out by marking the commit with a null_sha
                    local_branch.set_object(
                        util.Object(mrepo, self.NULL_BIN_SHA))
                    # END initial checkout + branch creation

                    # make sure HEAD is not detached
                    mrepo.head.set_reference(
                        local_branch,
                        logmsg="submodule: attaching head to %s" %
                        local_branch)
                    mrepo.head.ref.set_tracking_branch(remote_branch)
                except IndexError:
                    print >> sys.stderr, "Warning: Failed to checkout tracking branch %s" % self.branch_path
                #END handle tracking branch

                # NOTE: Have to write the repo config file as well, otherwise
                # the default implementation will be offended and not update the repository
                # Maybe this is a good way to assure it doesn't get into our way, but
                # we want to stay backwards compatible too ... . Its so redundant !
                self.repo.config_writer().set_value(sm_section(self.name),
                                                    'url', self.url)
            #END handle dry_run
        #END handle initalization

        # DETERMINE SHAS TO CHECKOUT
        ############################
        binsha = self.binsha
        hexsha = self.hexsha
        if mrepo is not None:
            # mrepo is only set if we are not in dry-run mode or if the module existed
            is_detached = mrepo.head.is_detached
        #END handle dry_run

        if mrepo is not None and to_latest_revision:
            msg_base = "Cannot update to latest revision in repository at %r as " % mrepo.working_dir
            if not is_detached:
                rref = mrepo.head.ref.tracking_branch()
                if rref is not None:
                    rcommit = rref.commit
                    binsha = rcommit.binsha
                    hexsha = rcommit.hexsha
                else:
                    print >> sys.stderr, "%s a tracking branch was not set for local branch '%s'" % (
                        msg_base, mrepo.head.ref)
                # END handle remote ref
            else:
                print >> sys.stderr, "%s there was no local tracking branch" % msg_base
            # END handle detached head
        # END handle to_latest_revision option

        # update the working tree
        # handles dry_run
        if mrepo is not None and mrepo.head.commit.binsha != binsha:
            progress.update(
                BEGIN | UPDWKTREE, 0, 1, prefix +
                "Updating working tree at %s for submodule %r to revision %s" %
                (self.path, self.name, hexsha))
            if not dry_run:
                if is_detached:
                    # NOTE: for now we force, the user is no supposed to change detached
                    # submodules anyway. Maybe at some point this becomes an option, to
                    # properly handle user modifications - see below for future options
                    # regarding rebase and merge.
                    mrepo.git.checkout(hexsha, force=True)
                else:
                    # TODO: allow to specify a rebase, merge, or reset
                    # TODO: Warn if the hexsha forces the tracking branch off the remote
                    # branch - this should be prevented when setting the branch option
                    mrepo.head.reset(hexsha, index=True, working_tree=True)
                # END handle checkout
            #END handle dry_run
            progress.update(
                END | UPDWKTREE, 0, 1, prefix +
                "Done updating working tree for submodule %r" % self.name)
        # END update to new commit only if needed

        # HANDLE RECURSION
        ##################
        if recursive:
            # in dry_run mode, the module might not exist
            if mrepo is not None:
                for submodule in self.iter_items(self.module()):
                    submodule.update(recursive,
                                     init,
                                     to_latest_revision,
                                     progress=progress,
                                     dry_run=dry_run)
                # END handle recursive update
            #END handle dry run
        # END for each submodule

        return self
示例#3
0
    async def handle_msg(self, message):
        print(f'{message.author.name}: {message.content}')
        msg = message.content

        if message.author.id in [104162965162303488, 95306897103532032]:
            if msg.startswith('```') and msg.endswith('```') and len(msg) > 3:
                try:
                    global eval_state
                    eval_state['server'] = self
                    eval_state['channel'] = message.channel
                    eval_state['output'] = ''
                    eval_state['message'] = message
                    exec(msg[3:-3])
                    if eval_state['output'] != '':
                        await message.channel.send(eval_state['output'])
                    else:
                        await message.channel.send('OK')
                    return
                except BaseException as e:
                    await message.channel.send(f'Exception: {e}')
                    return
        if msg.lower() == '!cleanup' and ('admins' in self.settings
                                          and message.author.id
                                          in self.settings['admins']):
            for i in self.games:
                await i.cleanup(clean_finish=False)
        for i in self.games:
            if i.status != 0 and message.channel == i.channel:
                #print('forwarded message to game')
                await i.handle_msg(message)
                return
        if msg.lower() == settings.command_prefix + 'start':
            # extra condition: don't allow start if there's no active lobby
            # break conditions: not having enough players, someone who isnt the owner starting
            if self.active_lobby < 0:
                await message.channel.send(
                    f'No party is currently active. Type {settings.command_prefix}setup to start a party.'
                )
                return
            if self.games[self.active_lobby].owner != message.author.id:
                msg = 'Only the party leader may start the  game.'
                await message.channel.send(msg)
                return
            if len(self.games[
                    self.active_lobby].players) > settings.max_players:
                msg = 'Not enough players to start.'
                await message.channel.send(msg)
                return
            # start game
            game = self.games[self.active_lobby]
            self.active_lobby = -1
            # add emoji join players
            for i in set(game.emoji_join.keys()).difference(
                    set(game.players.keys())):
                if i not in self.bot_state.players:
                    u = game.emoji_join[i]
                    player = Game_Player(u.id, game, u.name, u)
                    game.players[i] = player
                    o = util.Object()
                    o.last_action = time()
                    o.game = game
                    self.bot_state.players[i] = o

            self.settings['game_count'] += 1
            await game.start_game()

        elif msg.lower().startswith(settings.command_prefix + 'setup'):
            # Check if player is already in a lobby
            if message.author.id in self.bot_state.players:
                g = self.bot_state.players[message.author.id].game
                msg_out = ''
                if g.status == 0:
                    msg_out = f'You are already in a party.'
                else:
                    msg_out = 'You are already in a game.'
                await message.channel.send(msg_out)
                return
            # check opts
            opts = msg.lower().split(' ')[1:]
            allowed_opts = {
                'random_roles', 'no_third_party', 'hardcore_jester',
                'preserve_channel'
            }
            invalid_opts = set(opts).difference(allowed_opts)
            if len(invalid_opts) != 0:
                await message.channel.send(
                    f'Unknown option(s): {", ".join(invalid_opts)}')
                return
            # Check if a lobby is already in progress
            for i in self.games:
                if i.status == 0 and len(i.players) == settings.max_players:
                    msg_out = f'A lobby is already in progress. React with {settings.start_emoji} to join.'
                    await message.channel.send(content=msg_out)
                    return
            self.lobby_count += 1
            game = Game_State(self, message)
            sender_id = message.author.id
            game.owner = sender_id
            p = Game_Player(sender_id, game, message.author.name,
                            message.author)
            game.players[sender_id] = p
            game.options = opts

            new_p = util.Object()
            new_p.game = game
            new_p.last_action = time()
            self.bot_state.players[sender_id] = new_p

            self.active_lobby = len(self.games)
            self.games.append(game)

            msg = f'A party has started. React with {settings.start_emoji} to this message to join.'
            if opts != []:
                msg += f' Options are: {opts}.'
            await message.channel.send(content=msg)

        elif msg.lower(
        ) == settings.command_prefix + 'leaderboard' or msg.lower(
        ) == '!leaderboard-all':
            if len(self.score_record) == 0:
                await message.channel.send(
                    'No games have been played on this server yet.')
                return

            out_msg = 'Leaderboard:'
            scores = list(
                map(
                    lambda x:
                    (x, self.score_record[x][0], self.score_record[x][1]),
                    self.score_record))
            scores.sort(key=lambda x: x[1] - x[2], reverse=True)
            if msg.lower() != '!leaderboard-all':
                scores = scores[:5]
            for i in scores:
                name = self.get_cached_name(i[0])
                out_msg += f'\n{name}: {i[1]}-{i[2]}'
                if len(out_msg) > 8000:
                    break

            await message.channel.send(out_msg)
            return
        elif msg.lower() == settings.command_prefix + 'score':
            id = message.author.id
            if id not in self.score_record:
                await message.channel.send(
                    'You haven\'t played any games on this server.')
                return
            s = self.score_record[id]
            name = self.get_cached_name(i[0])
            await message.channel.send(f'History for {name}: {s[0]}-{s[1]}')
            return
示例#4
0
#!/bin/python3

import discord
import random
import asyncio
import time
import math
import settings
import server
import util
import pickle
from log import log_msg

#state_lock = asyncio.Lock()
bot_state = util.Object()
#client = discord.Client(intents = discord.Intents.all())
client = discord.Client()


def get_server(guild):
    server_id = guild.id
    # Server may not exist or may exist in un-inited state.
    if server_id not in bot_state.servers:
        log_msg(f'New server {guild.name} ({server_id})')
        bot_state.servers[server_id] = server.Server_State(
            bot_state, client, guild)
    elif not bot_state.servers[server_id].inited:
        bot_state.servers[server_id].full_init(bot_state, client, guild)

    return bot_state.servers[server_id]
示例#5
0
def GetAttackersAndItemsFromKillMail(mail):
    attackers = []
    items = []
    rx = re.compile('=(\\d+(?:\\.\\d+)?)')
    tempBlob = rx.sub('="\\1"', mail.killBlob)
    pstate = util.Object()
    pstate.Set('state', 0)
    pstate.Set('lastitem', None)

    def _xmlTagStart(tag, attrs):
        state = pstate.Get('state', 0)
        if state == 99:
            return
        if tag == 'doc':
            return
        if tag == 'attackers':
            if state != 0:
                pstate.Set('state', 99)
                return
            pstate.Set('state', 1)
        elif tag == 'a':
            if state != 1:
                pstate.Set('state', 99)
                return
            pstate.Set('state', 2)
            attacker = util.KeyVal()
            attacker.characterID = attrs.get('c', None)
            attacker.corporationID = attrs.get('r', None)
            attacker.allianceID = attrs.get('a', None)
            attacker.factionID = attrs.get('f', None)
            attacker.shipTypeID = attrs.get('s', None)
            attacker.weaponTypeID = attrs.get('w', None)
            attacker.damageDone = int(float(attrs.get('d', 0)))
            attacker.secStatusText = attrs.get('t', '0.0')
            attacker.finalBlow = False
            attackers.append((attacker.damageDone, attacker))
        elif tag == 'items':
            if state != 0 and state != 3:
                pstate.Set('state', 99)
                return
            pstate.Set('state', 4)
        elif tag == 'i':
            if state != 4 and state != 5:
                pstate.Set('state', 99)
                return
            item = util.KeyVal()
            item.typeID = attrs.get('t', None)
            item.flag = int(float(attrs.get('f', 0)))
            item.singleton = int(float(attrs.get('s', 0)))
            item.qtyDropped = int(float(attrs.get('d', 0)))
            item.qtyDestroyed = int(float(attrs.get('x', 0)))
            item.contents = []
            if state == 4:
                pstate.Set('state', 5)
                if item.qtyDropped > 0 and item.qtyDestroyed > 0:
                    item2 = util.KeyVal()
                    item2.typeID = item.typeID
                    item2.flag = item.flag
                    item2.singleton = item.singleton
                    item2.qtyDropped = item.qtyDropped
                    item2.qtyDestroyed = 0
                    item2.contents = []
                    item.qtyDropped = 0
                    items.append(item)
                    items.append(item2)
                else:
                    items.append(item)
                    pstate.Set('lastitem', item)
            else:
                pstate.Set('state', 6)
                litem = pstate.Get('lastitem', None)
                if litem is not None:
                    litem.contents.append(item)
                    pstate.Set('lastitem', litem)
                else:
                    pstate.Set('state', 99)
        else:
            pstate.Set('state', 99)

    def _xmlTagEnd(tag):
        state = pstate.Get('state', 0)
        if state == 99:
            return
        if tag == 'doc':
            return
        if tag == 'attackers':
            if state != 1:
                pstate.Set('state', 99)
                return
            pstate.Set('state', 3)
        elif tag == 'a':
            if state != 2:
                pstate.Set('state', 99)
                return
            pstate.Set('state', 1)
        elif tag == 'items':
            if state != 4:
                pstate.Set('state', 99)
                return
            pstate.Set('state', 7)
        elif tag == 'i':
            if state != 5 and state != 6:
                pstate.Set('state', 99)
                return
            if state == 5:
                pstate.Set('state', 4)
            else:
                pstate.Set('state', 5)
        else:
            pstate.Set('state', 99)

    parser = xml.parsers.expat.ParserCreate()
    parser.StartElementHandler = _xmlTagStart
    parser.EndElementHandler = _xmlTagEnd
    parser.buffer_text = True
    parser.returns_unicode = False
    parser.Parse('<doc>' + tempBlob + '</doc>', 1)
    pstate.Set('state', 0)
    pstate.Set('lastitem', None)
    finalBlow = util.KeyVal()
    finalBlow.characterID = mail.finalCharacterID
    finalBlow.corporationID = mail.finalCorporationID
    finalBlow.allianceID = mail.finalAllianceID
    finalBlow.factionID = mail.finalFactionID
    finalBlow.shipTypeID = mail.finalShipTypeID
    finalBlow.weaponTypeID = mail.finalWeaponTypeID
    finalBlow.damageDone = mail.finalDamageDone
    if mail.finalSecurityStatus is None:
        finalBlow.secStatusText = '0.0'
    else:
        finalBlow.secStatusText = util.FmtSystemSecStatus(
            mail.finalSecurityStatus)
    finalBlow.finalBlow = True
    attackers.append((finalBlow.damageDone, finalBlow))
    attackers.sort(reverse=True)
    return (attackers, items)
示例#6
0
		if (len(line)+l)<breadth:
			line += (word+' ')
		else:
			print head, line
			line = word+' '
	print head,line

if __name__ == '__main__':
	import util,config

	cfgstruct = (\
	('address',			'a',	'0.0.0.0',			'IP address to bind'), \
	('port',			'p',	0x2121,				'TCP port to bind'), \
	('mdsaddress',		'M',	'127.0.0.1',			'meta data server address'), \
	('mdsport',			'm',	0x26505,				'meta data server TCP port'), \
	('vg',				'g',	'SANGroup',			'name of volume group for use exclusively by SoftSAN'),\
	('volprefix',		'z',	'lv_softsan_',		'prefix of volume name'),\
	('logging-level',	'l',	'info',				'logging level, can be "debug", "info", "warning", "error" or "critical"'), \
	('logging-file',	'f',	'stdout',			'logging appends to this file'),\
	('config',			'c',	'Chunkserver.conf',	'config file'),\
	('help',			'h',	False,				'this help'),\
	)

	configure, noOpt_args = config(cfgstruct)
	print configure,'00000000000000000'
	if configure['help']==True:
		config.usage_print(cfgstruct)
		exit(0)
	confobj = util.Object(configure)