Ejemplo n.º 1
0
def __enrichMessage(msg, withGamePrefix=True):
    """
    Add some optional prefixes to msg: S/C, process id, time, git commit.

    @param msg: The original message.
    @type msg: C{str}
    @param withGamePrefix: If set, prepend the game prefix.
    @type withGamePrefix: C{Boolean}
    @rtype: C{str}
    """
    result = msg  # set the default
    if withGamePrefix and Internal.logPrefix:
        result = '{prefix}{process}: {msg}'.format(
            prefix=Internal.logPrefix,
            process=os.getpid() if Debug.process else '',
            msg=msg)
    if Debug.time:
        result = '{:08.4f} {}'.format(elapsedSince(Debug.time), result)
    if Debug.git:
        head = gitHead()
        if head not in ('current', None):
            result = 'git:{}/p3 {}'.format(head, result)
    if int(Debug.callers):
        result = '  ' + result
    return result
Ejemplo n.º 2
0
def doJobs():
    """now execute all jobs"""
    # pylint: disable=too-many-branches, too-many-locals, too-many-statements

    if not OPTIONS.git and OPTIONS.csv:
        if gitHead() in ('current', None):
            print(
                'Disabling CSV output: %s' %
                ('You have uncommitted changes' if gitHead() == 'current' else 'No git'))
            print()
            OPTIONS.csv = None

    try:
        jobs = []
        while getJobs(jobs):
            for checkJob in Server.allRunningJobs()[:]:
                checkJob.check()
            try:
                jobs[0].start()
                jobs = jobs[1:]
            except TooManyServers:
                time.sleep(3)
            except TooManyClients:
                time.sleep(3)
    except KeyboardInterrupt:
        Server.stopAll()
    except BaseException as exc:
        print(exc)
        raise exc
    finally:
        while True:
            running = Server.allRunningJobs()
            if not running:
                break
            for job in running:
                if not job.started:
                    if job.server:
                        job.server.jobs.remove(job)
                else:
                    job.check()
                    if job.process:
                        print('Waiting for   %s' % job)
                        job.process.wait()
            time.sleep(1)
Ejemplo n.º 3
0
 def writeCsv(self):
     """write game summary to Options.csv"""
     if self.finished() and Options.csv:
         gameWinner = max(self.players, key=lambda x: x.balance)
         writer = CsvWriter(Options.csv, mode='a')
         if Debug.process and os.name != 'nt':
             self.csvTags.append(
                 'MEM:%s' %
                 resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
         if Options.rounds:
             self.csvTags.append('ROUNDS:%s' % Options.rounds)
         row = [
             self.ruleset.name, Options.AI,
             gitHead(), '3',
             str(self.seed), ','.join(self.csvTags)
         ]
         for player in sorted(self.players, key=lambda x: x.name):
             row.append(player.name)
             row.append(player.balance)
             row.append(player.wonCount)
             row.append(1 if player == gameWinner else 0)
         writer.writerow(row)
         del writer
Ejemplo n.º 4
0
ABOUT = About()
KCmdLineArgs.init(sys.argv, ABOUT.about)
KCmdLineArgs.addCmdLineOptions(defineOptions())
APP = KApplication()
parseOptions()

if hasattr(QGuiApplication, 'setDesktopFileName'):
    QGuiApplication.setDesktopFileName('org.kde.kajongg')

if Debug.neutral:
    KGlobal.translation = None

if Debug.events:
    EVHANDLER = EvHandler()
    APP.installEventFilter(EVHANDLER)

from config import SetupPreferences
SetupPreferences()

if Options.csv:
    if gitHead() == 'current':
        Internal.logger.debug(
            'You cannot write to %s with changes uncommitted to git',
            Options.csv)
        sys.exit(2)
from mainwindow import MainWindow
QGuiApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, True)
MainWindow()
Internal.app.exec_()
Ejemplo n.º 5
0
def improve_options():
    """add sensible defaults"""
    # pylint: disable=too-many-branches,too-many-statements
    if OPTIONS.servers < 1:
        OPTIONS.servers = 1

    cmdPath = os.path.join(startingDir(), 'kajongg.py')
    cmd = ['python3', cmdPath, '--rulesets']
    OPTIONS.knownRulesets = list(popenReadlines(cmd))
    if OPTIONS.rulesets == 'ALL':
        OPTIONS.rulesets = OPTIONS.knownRulesets
    else:
        wantedRulesets = OPTIONS.rulesets.split(',')
        usingRulesets = []
        wrong = False
        for ruleset in wantedRulesets:
            matches = list(x for x in OPTIONS.knownRulesets if ruleset in x)
            if len(matches) == 0:
                print('ruleset', ruleset, 'is not known', end=' ')
                wrong = True
            elif len(matches) > 1:
                exactMatch = list(
                    x for x in OPTIONS.knownRulesets if ruleset == x)
                if len(exactMatch) == 1:
                    usingRulesets.append(exactMatch[0])
                else:
                    print('ruleset', ruleset, 'is ambiguous:', matches)
                    wrong = True
            else:
                usingRulesets.append(matches[0])
        if wrong:
            sys.exit(1)
        OPTIONS.rulesets = usingRulesets
    if OPTIONS.git is not None:
        if '..' in OPTIONS.git:
            if '^' not in OPTIONS.git:
                OPTIONS.git = OPTIONS.git.replace('..', '^..')
            commits = subprocess.check_output(
                'git log --pretty=%h {range}'.format(
                    range=OPTIONS.git).split()).decode()
            OPTIONS.git = list(reversed(list(x.strip()
                                             for x in commits.split('\n') if x.strip())))
        else:
            OPTIONS.git = onlyExistingCommits(OPTIONS.git.split(','))
            if not OPTIONS.git:
                sys.exit(1)
    if OPTIONS.debug is None:
        OPTIONS.debug = []
    else:
        OPTIONS.debug = [OPTIONS.debug]
    if OPTIONS.log:
        OPTIONS.servers = OPTIONS.clients
        OPTIONS.debug.extend(
            'neutral,dangerousGame,explain,originalCall,robbingKong,robotAI,scores,traffic,hand'.split(','))
    if gitHead() not in ('current', None) and not OPTIONS.log:
        OPTIONS.debug.append('git')
    if not OPTIONS.aiVariants:
        OPTIONS.aiVariants = 'Default'
    OPTIONS.allAis = OPTIONS.aiVariants.split(',')
    if OPTIONS.count:
        print('rulesets:', ', '.join(OPTIONS.rulesets))
        _ = ' '.join(OPTIONS.allAis)
        if _ != 'Default':
            print('AIs:', _)
    if OPTIONS.git:
        print('commits:', ' '.join(OPTIONS.git))
        # since we order jobs by game, commit we want one permanent server per
        # commit
    OPTIONS.jobs = allJobs()
    OPTIONS.games = allGames()
    OPTIONS.jobCount = 0
    OPTIONS.usePort = os.name == 'nt'