diff options
Diffstat (limited to 'tools')
26 files changed, 1380 insertions, 18 deletions
diff --git a/tools/HPMHookGen/HPMHookGen.pl b/tools/HPMHookGen/HPMHookGen.pl index e5a5c1914..46cae36cb 100755 --- a/tools/HPMHookGen/HPMHookGen.pl +++ b/tools/HPMHookGen/HPMHookGen.pl @@ -371,7 +371,8 @@ foreach my $file (@files) { # Loop through the xml files $t = ')(int fd, struct login_session_data *sd)'; # typedef LoginParseFunc $def =~ s/^LoginParseFunc\s*\*\s*(.*)$/enum parsefunc_rcode(* $1) (int fd, struct login_session_data *sd)/; } - next unless ref $t ne 'HASH' and $t =~ /^[^\[]/; # If it's not a string, or if it starts with an array subscript, we can skip it + next if ref $t eq 'HASH'; # Skip if it's not a string + next if $t =~ /^\)?\[.*\]$/; # Skip arrays or pointers to array my $if = parse($t, $def); next unless scalar keys %$if; # If it returns an empty hash reference, an error must've occurred diff --git a/tools/HPMHookGen/doxygen.conf b/tools/HPMHookGen/doxygen.conf index ec55967b1..c302f7f2f 100644 --- a/tools/HPMHookGen/doxygen.conf +++ b/tools/HPMHookGen/doxygen.conf @@ -269,7 +269,9 @@ INCLUDE_PATH = ../../src \ ../../3rdparty INCLUDE_FILE_PATTERNS = PREDEFINED = __attribute__(x)= \ - HPMHOOKGEN + HPMHOOKGEN \ + PACKETVER=20031028 \ + PACKETVER_MAIN_NUM=20031028 EXPAND_AS_DEFINED = SKIP_FUNCTION_MACROS = NO #--------------------------------------------------------------------------- diff --git a/tools/checksql.sh b/tools/checksql.sh new file mode 100755 index 000000000..f7fb23700 --- /dev/null +++ b/tools/checksql.sh @@ -0,0 +1,13 @@ +#!/bin/bash + +function checkdir { + for sql in $1/*.sql + do + echo "checking ${sql}" + php -d memory_limit=4G ./tools/php-sqllint/bin/php-sqllint "${sql}" || exit 1 + done +} + +checkdir "sql-files" +checkdir "sql-files/upgrades" +checkdir "sql-files/tools" diff --git a/tools/ci/travis.sh b/tools/ci/travis.sh index fa7d5be93..22f523bdf 100755 --- a/tools/ci/travis.sh +++ b/tools/ci/travis.sh @@ -47,7 +47,8 @@ function aborterror { function run_server { echo "Running: $1 --run-once $2" - $1 --run-once $2 2>runlog.txt + rm -rf core* || true + CRASH_PLEASE=1 $1 --run-once $2 2>runlog.txt export errcode=$? export teststr=$(head -c 10000 runlog.txt) if [[ -n "${teststr}" ]]; then @@ -59,12 +60,17 @@ function run_server { fi if [ ${errcode} -ne 0 ]; then echo "server $1 terminated with exit code ${errcode}" + COREFILE=$(find . -maxdepth 1 -name "core*" | head -n 1) + if [[ -f "$COREFILE" ]]; then + gdb -c "$COREFILE" $1 -ex "thread apply all bt" -ex "set pagination 0" -batch + fi aborterror "Test failed" fi } function run_test { echo "Running: test_$1" + sysctl -w kernel.core_pattern=core || true ./test_$1 2>runlog.txt export errcode=$? export teststr=$(head -c 10000 runlog.txt) diff --git a/tools/configconverter.pl b/tools/configconverter.pl index dc511aaef..20f5f4cfb 100755 --- a/tools/configconverter.pl +++ b/tools/configconverter.pl @@ -554,7 +554,6 @@ my @defaults = ( guild_exp_limit => {parse => \&parsecfg_int, print => \&printcfg_int, path => "guild:", default => 50}, guild_max_castles => {parse => \&parsecfg_int, print => \&printcfg_int, path => "guild:", default => 0}, guild_skill_relog_delay => {parse => \&parsecfg_bool, print => \&printcfg_bool, path => "guild:", default => "false"}, - castle_defense_rate => {parse => \&parsecfg_int, print => \&printcfg_int, path => "guild:", default => 100}, gvg_flee_penalty => {parse => \&parsecfg_int, print => \&printcfg_int, path => "guild:", default => 20}, require_glory_guild => {parse => \&parsecfg_bool, print => \&printcfg_bool, path => "guild:", default => "false"}, max_guild_alliance => {parse => \&parsecfg_int, print => \&printcfg_int, path => "guild:", default => 3}, diff --git a/tools/install_mariadb.bat b/tools/install_mariadb.bat new file mode 100644 index 000000000..cfe2ce3b7 --- /dev/null +++ b/tools/install_mariadb.bat @@ -0,0 +1,7 @@ +@echo off + +:: this file installs the mariadb service + +if not "%1"=="am_admin" (powershell start -verb runas '%0' am_admin & exit /b) +mysqld.exe --install "MySQL" +net start MySQL diff --git a/tools/itemcombodbconverter.py b/tools/itemcombodbconverter.py new file mode 100644 index 000000000..ae4deeba3 --- /dev/null +++ b/tools/itemcombodbconverter.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python3 +# -*- coding: utf8 -*- +# +# This file is part of Hercules. +# http://herc.ws - http://github.com/HerculesWS/Hercules +# +# Copyright (C) 2019 Hercules Dev Team +# Copyright (C) 2019 Asheraf +# +# Hercules is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# + +import argparse +import json +import re +from utils import libconf +import utils.common as Tools + + +def ConvertFile(args): + print(r'''//================= Hercules Database ===================================== +//= _ _ _ +//= | | | | | | +//= | |_| | ___ _ __ ___ _ _| | ___ ___ +//= | _ |/ _ \ '__/ __| | | | |/ _ \/ __| +//= | | | | __/ | | (__| |_| | | __/\__ \ +//= \_| |_/\___|_| \___|\__,_|_|\___||___/ +//================= License =============================================== +//= This file is part of Hercules. +//= http://herc.ws - http://github.com/HerculesWS/Hercules +//= +//= Copyright (C) 2019 Hercules Dev Team +//= +//= Hercules is free software: you can redistribute it and/or modify +//= it under the terms of the GNU General Public License as published by +//= the Free Software Foundation, either version 3 of the License, or +//= (at your option) any later version. +//= +//= This program is distributed in the hope that it will be useful, +//= but WITHOUT ANY WARRANTY; without even the implied warranty of +//= MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +//= GNU General Public License for more details. +//= +//= You should have received a copy of the GNU General Public License +//= along with this program. If not, see <http://www.gnu.org/licenses/>. +//================= Description =========================================== +// Configurations file for status effects +//========================================================================= + +combo_db: ( +/************************************************************************** + ************* Entry structure ******************************************** + ************************************************************************** +{ + // ================ Mandatory fields =============================== + Items: ["item_list"] (string, array) list of items + Script: <" + Script + (it can be multi-line) + "> +} +**************************************************************************/''') + ItemDB = Tools.LoadDBConsts('item_db', f'{args.mode}', '../') + with open (f'../db/{args.mode}/item_combo_db.txt') as dbfile: + line = 0 + for entry in dbfile: + line = line + 1 + if not entry.strip() or entry.startswith('//'): + continue + m = re.search(r'(^[0-9:]+),\{(.*)\}$', entry) + if not m: + print(f'Error: Invalid pattern in entry {entry}, line {line}, aborting..') + exit() + + items_list = m.group(1).split(':') + script = m.group(2) + for item in range(len(items_list)): + if int(items_list[item]) not in ItemDB: + print(f'Error: invalid item {item} found in line {line}, aborting..') + exit() + items_list[item] = ItemDB[int(items_list[item])] + + if args.enable_jsbeautifier: + import jsbeautifier + opts = jsbeautifier.default_options() + opts.indent_with_tabs = True + opts.indent_level = 2 + script = jsbeautifier.beautify(script, opts) + print( +f'''{{ + Items: {json.dumps(items_list)} + Script: <"\n{script}\n\t"> +}},''') + print(')') + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='Convert item combo db to new format') + parser.add_argument('--mode', type=str, dest='mode', help='Define usage mode re/pre-re.') + parser.add_argument('--enable-jsbeautifier', type=bool, dest='enable_jsbeautifier', help='Use jsbeautifier to auto format script fields.') + parsed_args = parser.parse_args() + ConvertFile(parsed_args) diff --git a/tools/itemdbconverter.pl b/tools/itemdbconverter.pl index 58cb08bc1..fe30ce24e 100755 --- a/tools/itemdbconverter.pl +++ b/tools/itemdbconverter.pl @@ -109,9 +109,9 @@ sub parsedb (@) { (?<eLV>[0-9]*)[^,:]*(?<hasmaxlv>:[\s\t]*(?<eLVmax>[0-9]*))?[^,]*,[\s\t]* (?<Refineable>[0-9]*)[^,]*,[\s\t]* (?<View>[0-9]*)[^,]*,[\s\t]* - {(?<Script>.*)}, - {(?<OnEquip>.*)}, - {(?<OnUnequip>.*)} + \{(?<Script>.*)}, + \{(?<OnEquip>.*)}, + \{(?<OnUnequip>.*)} /x ) { my %cols = map { $_ => $+{$_} } keys %+; print "/*\n" if $cols{prefix}; diff --git a/tools/mobavailconverter.py b/tools/mobavailconverter.py new file mode 100644 index 000000000..44a3cd2eb --- /dev/null +++ b/tools/mobavailconverter.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python +# -*- coding: utf8 -*- +# +# This file is part of Hercules. +# http://herc.ws - http://github.com/HerculesWS/Hercules +# +# Copyright (C) 2019 Hercules Dev Team +# Copyright (C) 2019 Asheraf +# +# Hercules is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# + +import re +import csv + +f = open('../db/re/mob_db.conf') +mob_db = f.read() + +with open('../db/mob_avail.txt') as dbfile: + mob_avail = csv.reader(dbfile, delimiter=',') + + for mob in mob_avail: + if len(mob) == 0 or mob[0].startswith('//'): + continue + + mob = [re.sub(r'//.*', '', i).strip() for i in mob] + + mob_id = int(mob[0]) + sprite_id = int(mob[1]) + weapon = 0 + shield = 0 + head_top = 0 + head_mid = 0 + head_bottom = 0 + hair_style = 0 + hair_color = 0 + cloth_color = 0 + gender = 0 + option = 0 + if len(mob) == 3: + head_bottom = int(mob[2]) + elif len(mob) == 12: + gender = int(mob[2]) + hair_style = int(mob[3]) + hair_color = int(mob[4]) + weapon = int(mob[5]) + shield = int(mob[6]) + head_top = int(mob[7]) + head_mid = int(mob[8]) + head_bottom = int(mob[9]) + option = int(mob[10]) + cloth_color = int(mob[11]) + + s = '' + s += '\tViewData: {\n' + s += '\t\tSpriteId: {}\n'.format(sprite_id) + if weapon != 0: + s += '\t\tWeaponId: {}\n'.format(weapon) + if shield != 0: + s += '\t\tShieldId: {}\n'.format(shield) + if head_top != 0: + s += '\t\tHeadTopId: {}\n'.format(head_top) + if head_mid != 0: + s += '\t\tHeadMidId: {}\n'.format(head_mid) + if head_bottom != 0: + s += '\t\tHeadLowId: {}\n'.format(head_bottom) + if hair_style != 0: + s += '\t\tHairStyleId: {}\n'.format(hair_style) + if hair_color != 0: + s += '\t\tHairColorId: {}\n'.format(hair_color) + if cloth_color != 0: + s += '\t\tBodyColorId: {}\n'.format(cloth_color) + if gender != 0: + s += '\t\tGender: SEX_MALE\n' + if option != 0: + s += '\t\tOptions: {}\n'.format(option) + s += '\t}' + + mob_db = re.sub( + r'(\tId: ' + str(mob_id) + r'\n([\S\s]*?)(?=},))},', + r'\1' + str(s) + r'\n},', + mob_db) + print(mob_db) diff --git a/tools/mobdbconverter.py b/tools/mobdbconverter.py index 78047aed9..683e28274 100755 --- a/tools/mobdbconverter.py +++ b/tools/mobdbconverter.py @@ -188,7 +188,7 @@ def convertFile(inFile, itemDb): printField("ChaseRange", fields[21]) printField("Size", fields[22]) printField("Race", fields[23]) - print("\tElement: ({0}, {1})".format(int(fields[24]) % 10, int(fields[24]) / 20)); + print("\tElement: ({0}, {1})".format(int(fields[24]) % 10, int(int(fields[24]) / 20))); mode = int(fields[25], 0) if mode != 0: startGroup("Mode") @@ -260,7 +260,7 @@ def readItemDB(inFile, itemDb): elif line[:3] == "Id:": try: itemId = int(line[4:]) - except: + except ValueError: started = False if itemId != 0 and itemName != "": # was need for remove wrong characters diff --git a/tools/mobskilldbconverter.py b/tools/mobskilldbconverter.py index 310331043..4ba042062 100644..100755 --- a/tools/mobskilldbconverter.py +++ b/tools/mobskilldbconverter.py @@ -206,7 +206,7 @@ def LoadOldDB(mode, serverpath): continue try: Db[MonsterId][skillidx]['val{}'.format(i)] = int(entry[12 + i]) - except: + except ValueError: Db[MonsterId][skillidx]['val{}'.format(i)] = int(entry[12 + i], 16) Db[MonsterId][skillidx]['Emotion'] = entry[17] Db[MonsterId][skillidx]['ChatMsgID'] = entry[18] diff --git a/tools/petdbconverter.py b/tools/petdbconverter.py index 261c1e6ad..1b7d2e4d6 100644 --- a/tools/petdbconverter.py +++ b/tools/petdbconverter.py @@ -175,7 +175,7 @@ def readItemDB(inFile, itemDb): elif line[:3] == "Id:": try: itemId = int(line[4:]) - except: + except ValueError: started = False if itemId != 0 and itemName != "": # was need for remove wrong characters diff --git a/tools/php-sqllint/bin/php-sqllint b/tools/php-sqllint/bin/php-sqllint new file mode 100755 index 000000000..fd766bc07 --- /dev/null +++ b/tools/php-sqllint/bin/php-sqllint @@ -0,0 +1,31 @@ +#!/usr/bin/env php +<?php +/** + * SQL linter (syntax checker) written in PHP + * + * PHP version 5 + * + * @category Tools + * @package PHP-SQLlint + * @author Christian Weiske <cweiske@cweiske.de> + * @license http://www.gnu.org/licenses/agpl.html GNU AGPL v3 + * @link http://cweiske.de/php-sqllint.htm + */ +namespace phpsqllint; + +if (file_exists(__DIR__ . '/../vendor/autoload.php')) { + //local git checkout + include_once __DIR__ . '/../vendor/autoload.php'; +} else if (file_exists('vendor/autoload.php')) { + //dependency composer installation + include_once 'vendor/autoload.php'; +} + +if (file_exists(__DIR__ . '/../src/phpsqllint/Autoloader.php')) { + include_once __DIR__ . '/../src/phpsqllint/Autoloader.php'; + Autoloader::register(); +} + +$cli = new Cli(); +$cli->run(); +?>
\ No newline at end of file diff --git a/tools/php-sqllint/build.xml b/tools/php-sqllint/build.xml new file mode 100644 index 000000000..e1f45f0a4 --- /dev/null +++ b/tools/php-sqllint/build.xml @@ -0,0 +1,103 @@ +<?xml version="1.0" encoding="utf-8"?> +<project name="php-sqllint" default="phar" basedir="."> + + <!--<property name="version" value="dev" />--> + <loadfile property="version" file="VERSION"> + <filterchain> + <striplinebreaks /> + </filterchain> + </loadfile> + + <property name="pharfile" value="${phing.dir}/dist/${phing.project.name}-${version}.phar" /> + <property name="pharfilebz2" value="${phing.dir}/dist/${phing.project.name}-${version}.bz2.phar" /> + <property name="libdir" value="${phing.dir}/lib"/> + + <fileset id="fs.phar" dir="${phing.dir}"> + <include name="bin/**"/> + <include name="lib/**"/> + <include name="src/**"/> + + <include name="README.rst"/> + <include name="VERSION"/> + + <include name="vendor/autoload.php"/> + <include name="vendor/composer/*.php"/> + <include name="vendor/pear/console_commandline/Console/**"/> + <include name="vendor/pear/pear_exception/PEAR/**"/> + <include name="vendor/phpmyadmin/sql-parser/src/**"/> + </fileset> + + + <typedef name="pearPackageFileSet" classname="phing.types.PearPackageFileSet" /> + + <target name="phar" depends="collectdeps" + description="Create zip file for release" + > + <!-- strip the shebang from bin script --> + <copy file="${phing.dir}/bin/php-sqllint" tofile="${phing.dir}/bin/phar-php-sqllint.php"> + <filterchain> + <striplinecomments> + <comment value="#" /> + </striplinecomments> + </filterchain> + </copy> + + <mkdir dir="${phing.dir}/dist"/> + <delete file="${pharfile}"/> + <pharpackage basedir="${phing.dir}" + destfile="${pharfile}" + stub="${phing.dir}/src/stub-phar.php" + alias="php-sqllint.phar" + compression="none" + > + <fileset refid="fs.phar"/> + </pharpackage> + + <pharpackage basedir="${phing.dir}" + destfile="${pharfilebz2}" + stub="${phing.dir}/src/stub-phar.php" + alias="php-sqllint.phar" + compression="bzip2" + > + <fileset refid="fs.phar"/> + </pharpackage> + + <exec executable="chmod"> + <arg value="+x"/> + <arg value="${pharfile}"/> + <arg value="${pharfilebz2}"/> + </exec> + </target> + + + <target name="collectdeps" description="Copy package dependencies to lib/"> + <exec command="composer install"/> + <!-- + <delete dir="${libdir}"/> + <mkdir dir="${libdir}"/> + + <pearPackageFileset id="dep-Console_CommandLine" package="pear.php.net/Console_CommandLine"/> + <pearPackageFileset id="dep-PEAR" package="pear.php.net/PEAR"> + <include name="PEAR/Exception.php"/> + </pearPackageFileset> + + <copy todir="${libdir}"> + <fileset refid="dep-Console_CommandLine"/> + <fileset refid="dep-PEAR"/> + </copy> + --> + </target> + + + <target name="docs" description="render documentation"> + <rst file="README.rst"/> + </target> + + <target name="update-website" depends="docs"> + <exec command="xmlstarlet sel -t -c '/_:html/_:body/_:div' README.html + | xmllint --format - + |grep -v '?xml version' + > ~/Dev/html/cweiske.de/www/php-sqllint.htm"/> + </target> + +</project> diff --git a/tools/php-sqllint/composer.json b/tools/php-sqllint/composer.json new file mode 100644 index 000000000..bde2da14d --- /dev/null +++ b/tools/php-sqllint/composer.json @@ -0,0 +1,22 @@ +{ + "name": "cweiske/php-sqllint", + "description": "Command line tool to validate (syntax check) SQL files", + "type": "project", + "bin": ["bin/php-sqllint"], + "require": { + "phpmyadmin/sql-parser": "^4.1.1", + "pear/console_commandline": "^1.2" + }, + "homepage": "http://cweiske.de/php-sqllint.htm", + "license": "AGPL-3.0", + "authors": [ + { + "name": "Christian Weiske", + "email": "cweiske@cweiske.de", + "homepage": "http://cweiske.de/" + } + ], + "support": { + "issues": "https://github.com/cweiske/php-sqllint/issues" + } +} diff --git a/tools/php-sqllint/composer.lock b/tools/php-sqllint/composer.lock new file mode 100644 index 000000000..a30dda3bf --- /dev/null +++ b/tools/php-sqllint/composer.lock @@ -0,0 +1,186 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", + "This file is @generated automatically" + ], + "hash": "642c0759e68495342f0e4ec0a8b45575", + "content-hash": "e52fa298a0c5ce2ff75067ab99b00ce7", + "packages": [ + { + "name": "pear/console_commandline", + "version": "v1.2.2", + "source": { + "type": "git", + "url": "https://github.com/pear/Console_CommandLine.git", + "reference": "7a8afa50bdc8dbfdc0cf394f1101106e8b8f8e67" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/pear/Console_CommandLine/zipball/7a8afa50bdc8dbfdc0cf394f1101106e8b8f8e67", + "reference": "7a8afa50bdc8dbfdc0cf394f1101106e8b8f8e67", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-xml": "*", + "pear/pear_exception": "^1.0.0", + "php": ">=5.3.0" + }, + "require-dev": { + "phpunit/phpunit": "*" + }, + "type": "library", + "autoload": { + "psr-0": { + "Console": "./" + } + }, + "notification-url": "https://packagist.org/downloads/", + "include-path": [ + "" + ], + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Richard Quadling", + "email": "rquadling@gmail.com" + }, + { + "name": "David Jean Louis", + "email": "izimobil@gmail.com" + } + ], + "description": "A full featured command line options and arguments parser.", + "homepage": "https://github.com/pear/Console_CommandLine", + "keywords": [ + "console" + ], + "time": "2016-07-14 06:00:57" + }, + { + "name": "pear/pear_exception", + "version": "v1.0.0", + "source": { + "type": "git", + "url": "https://github.com/pear/PEAR_Exception.git", + "reference": "8c18719fdae000b690e3912be401c76e406dd13b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/pear/PEAR_Exception/zipball/8c18719fdae000b690e3912be401c76e406dd13b", + "reference": "8c18719fdae000b690e3912be401c76e406dd13b", + "shasum": "" + }, + "require": { + "php": ">=4.4.0" + }, + "require-dev": { + "phpunit/phpunit": "*" + }, + "type": "class", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-0": { + "PEAR": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "include-path": [ + "." + ], + "license": [ + "BSD-2-Clause" + ], + "authors": [ + { + "name": "Helgi Thormar", + "email": "dufuz@php.net" + }, + { + "name": "Greg Beaver", + "email": "cellog@php.net" + } + ], + "description": "The PEAR Exception base class.", + "homepage": "https://github.com/pear/PEAR_Exception", + "keywords": [ + "exception" + ], + "time": "2015-02-10 20:07:52" + }, + { + "name": "phpmyadmin/sql-parser", + "version": "v4.1.9", + "source": { + "type": "git", + "url": "https://github.com/phpmyadmin/sql-parser.git", + "reference": "deac47217144b21056271674533b289239e1b279" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpmyadmin/sql-parser/zipball/deac47217144b21056271674533b289239e1b279", + "reference": "deac47217144b21056271674533b289239e1b279", + "shasum": "" + }, + "require": { + "ext-mbstring": "*", + "php": ">=5.3.0" + }, + "conflict": { + "phpmyadmin/motranslator": "<3.0" + }, + "require-dev": { + "phpunit/php-code-coverage": "*", + "phpunit/phpunit": "~4.8 || ~5.7" + }, + "suggest": { + "phpmyadmin/motranslator": "Translate messages to your favorite locale" + }, + "bin": [ + "bin/highlight-query", + "bin/lint-query" + ], + "type": "library", + "autoload": { + "psr-4": { + "PhpMyAdmin\\SqlParser\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "GPL-2.0+" + ], + "authors": [ + { + "name": "The phpMyAdmin Team", + "email": "developers@phpmyadmin.net", + "homepage": "https://www.phpmyadmin.net/team/" + } + ], + "description": "A validating SQL lexer and parser with a focus on MySQL dialect.", + "homepage": "https://github.com/phpmyadmin/sql-parser", + "keywords": [ + "analysis", + "lexer", + "parser", + "sql" + ], + "time": "2017-07-12 14:54:33" + } + ], + "packages-dev": [], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": [], + "prefer-stable": false, + "prefer-lowest": false, + "platform": [], + "platform-dev": [] +} diff --git a/tools/php-sqllint/src/phpsqllint/Autoloader.php b/tools/php-sqllint/src/phpsqllint/Autoloader.php new file mode 100644 index 000000000..6811b82f1 --- /dev/null +++ b/tools/php-sqllint/src/phpsqllint/Autoloader.php @@ -0,0 +1,57 @@ +<?php +/** + * Part of php-sqllint + * + * PHP version 5 + * + * @category Tools + * @package PHP-SQLlint + * @author Christian Weiske <cweiske@cweiske.de> + * @copyright 2014 Christian Weiske + * @license http://www.gnu.org/licenses/agpl.html GNU AGPL v3 + * @link http://cweiske.de/php-sqllint.htm + */ +namespace phpsqllint; + +/** + * Class autoloader, PSR-0 compliant. + * + * @category Tools + * @package PHP-SQLlint + * @author Christian Weiske <cweiske@cweiske.de> + * @copyright 2014 Christian Weiske + * @license http://www.gnu.org/licenses/agpl.html GNU AGPL v3 + * @version Release: @package_version@ + * @link http://cweiske.de/php-sqllint.htm + */ +class Autoloader +{ + /** + * Load the given class + * + * @param string $class Class name + * + * @return void + */ + public function load($class) + { + $file = strtr($class, '_\\', '//') . '.php'; + if (stream_resolve_include_path($file)) { + include $file; + } + } + + /** + * Register this autoloader + * + * @return void + */ + public static function register() + { + set_include_path( + get_include_path() . PATH_SEPARATOR . __DIR__ . '/../' + ); + spl_autoload_register(array(new self(), 'load')); + } +} +?>
\ No newline at end of file diff --git a/tools/php-sqllint/src/phpsqllint/Cli.php b/tools/php-sqllint/src/phpsqllint/Cli.php new file mode 100644 index 000000000..1501815eb --- /dev/null +++ b/tools/php-sqllint/src/phpsqllint/Cli.php @@ -0,0 +1,280 @@ +<?php +/** + * Part of php-sqllint + * + * PHP version 5 + * + * @category Tools + * @package PHP-SQLlint + * @author Christian Weiske <cweiske@cweiske.de> + * @license http://www.gnu.org/licenses/agpl.html GNU AGPL v3 + * @link http://cweiske.de/php-sqllint.htm + */ +namespace phpsqllint; +use PhpMyAdmin\SqlParser\Parser; + +/** + * Command line interface + * + * @category Tools + * @package PHP-SQLlint + * @author Christian Weiske <cweiske@cweiske.de> + * @license http://www.gnu.org/licenses/agpl.html GNU AGPL v3 + * @link http://www.emacswiki.org/emacs/CreatingYourOwnCompileErrorRegexp + */ +class Cli +{ + protected $renderer; + + protected $format = false; + + /** + * What syntax highlighting mode should be used + * + * none, ansi, html + */ + protected $highlight = 'none'; + + + /** + * Start processing. + * + * @return void + */ + public function run() + { + try { + $parser = $this->loadOptionParser(); + $files = $this->parseParameters($parser); + + $allfine = true; + foreach ($files as $filename) { + if ($this->format) { + $allfine &= $this->formatFile($filename); + } else { + $allfine &= $this->checkFile($filename); + } + } + + if ($allfine == true) { + exit(0); + } else { + exit(10); + } + } catch (\Exception $e) { + echo 'Error: ' . $e->getMessage() . "\n"; + exit(1); + } + } + + /** + * Check a .sql file for syntax errors + * + * @param string $filename File path + * + * @return boolean True if there were no errors, false if there were some + */ + public function checkFile($filename) + { + $this->renderer->startRendering($filename); + $sql = $this->loadSql($filename); + if ($sql === false) { + return false; + } + + $parser = new \PhpMyAdmin\SqlParser\Parser($sql); + if (count($parser->errors) == 0) { + $this->renderer->finishOk(); + return true; + } + + $lines = array(1 => 0); + $pos = -1; + $line = 1; + while (false !== $pos = strpos($sql, "\n", ++$pos)) { + $lines[++$line] = $pos; + } + + foreach ($parser->errors as $error) { + /* @var PhpMyAdmin\SqlParser\Exceptions\ParserException $error) */ + reset($lines); + $line = 1; + while (next($lines) && $error->token->position >= current($lines)) { + ++$line; + } + $col = $error->token->position - $lines[$line]; + + $this->renderer->displayError( + $error->getMessage(), + //FIXME: ->token or ->value? + $error->token->token, + $line, + $col + ); + } + + return false; + } + + /** + * Reformat the given file + */ + protected function formatFile($filename) + { + $this->renderer->startRendering($filename); + $sql = $this->loadSql($filename); + if ($sql === false) { + return false; + } + + $typeMap = array( + 'none' => 'text', + 'ansi' => 'cli', + 'html' => 'html', + ); + $options = array( + 'type' => $typeMap[$this->highlight], + ); + echo \PhpMyAdmin\SqlParser\Utils\Formatter::format($sql, $options) . "\n"; + } + + protected function loadSql($filename) + { + if ($filename == '-') { + $sql = file_get_contents('php://stdin'); + } else { + $sql = file_get_contents($filename); + } + if (trim($sql) == '') { + $this->renderer->displayError('SQL file empty', '', 0, 0); + return false; + } + return $sql; + } + + /** + * Load parameters for the CLI option parser. + * + * @return \Console_CommandLine CLI option parser + */ + protected function loadOptionParser() + { + $parser = new \Console_CommandLine(); + $parser->description = 'php-sqllint'; + $parser->version = 'dev'; + $parser->avoid_reading_stdin = true; + + $versionFile = __DIR__ . '/../../VERSION'; + if (file_exists($versionFile)) { + $parser->version = trim(file_get_contents($versionFile)); + } + + $parser->addOption( + 'format', + array( + 'short_name' => '-f', + 'long_name' => '--format', + 'description' => 'Reformat SQL instead of checking', + 'action' => 'StoreTrue', + 'default' => false, + ) + ); + $parser->addOption( + 'highlight', + array( + 'short_name' => '-h', + 'long_name' => '--highlight', + 'description' => 'Highlighting mode (when using --format)', + 'action' => 'StoreString', + 'choices' => array( + 'none', + 'ansi', + 'html', + 'auto', + ), + 'default' => 'auto', + 'add_list_option' => true, + ) + ); + $parser->addOption( + 'renderer', + array( + 'short_name' => '-r', + 'long_name' => '--renderer', + 'description' => 'Output mode', + 'action' => 'StoreString', + 'choices' => array( + 'emacs', + 'text', + ), + 'default' => 'text', + 'add_list_option' => true, + ) + ); + + $parser->addArgument( + 'sql_files', + array( + 'description' => 'SQL files, "-" for stdin', + 'multiple' => true + ) + ); + + return $parser; + } + + /** + * Let the CLI option parser parse the options. + * + * @param object $parser Option parser + * + * @return array Array of file names + */ + protected function parseParameters(\Console_CommandLine $parser) + { + try { + $result = $parser->parse(); + + $rendClass = '\\phpsqllint\\Renderer_' + . ucfirst($result->options['renderer']); + $this->renderer = new $rendClass(); + + $this->format = $result->options['format']; + + $this->highlight = $result->options['highlight']; + if ($this->highlight == 'auto') { + if (php_sapi_name() == 'cli') { + //default coloring to enabled, except + // when piping | to another tool + $this->highlight = 'ansi'; + if (function_exists('posix_isatty') + && !posix_isatty(STDOUT) + ) { + $this->highlight = 'none'; + } + } else { + //no idea where we are, so do not highlight + $this->highlight = 'none'; + } + } + + foreach ($result->args['sql_files'] as $filename) { + if ($filename == '-') { + continue; + } + if (!file_exists($filename)) { + throw new \Exception('File does not exist: ' . $filename); + } + if (!is_file($filename)) { + throw new \Exception('Not a file: ' . $filename); + } + } + + return $result->args['sql_files']; + } catch (\Exception $exc) { + $parser->displayError($exc->getMessage()); + } + } + +} +?> diff --git a/tools/php-sqllint/src/phpsqllint/Renderer.php b/tools/php-sqllint/src/phpsqllint/Renderer.php new file mode 100644 index 000000000..5b68ee11a --- /dev/null +++ b/tools/php-sqllint/src/phpsqllint/Renderer.php @@ -0,0 +1,54 @@ +<?php +/** + * Part of php-sqllint + * + * PHP version 5 + * + * @category Tools + * @package PHP-SQLlint + * @author Christian Weiske <cweiske@cweiske.de> + * @license http://www.gnu.org/licenses/agpl.html GNU AGPL v3 + * @link http://cweiske.de/php-sqllint.htm + */ +namespace phpsqllint; + +/** + * What every renderer has to implement + * + * @category Tools + * @package PHP-SQLlint + * @author Christian Weiske <cweiske@cweiske.de> + * @license http://www.gnu.org/licenses/agpl.html GNU AGPL v3 + * @link http://www.emacswiki.org/emacs/CreatingYourOwnCompileErrorRegexp + */ +interface Renderer +{ + /** + * Begin syntax check output rendering + * + * @param string $filename Path to the SQL file + * + * @return void + */ + public function startRendering($filename); + + /** + * Output errors in GNU style; see emacs compilation.txt + * + * @param string $msg Error message + * @param string $token Character which caused the error + * @param integer $line Line at which the error occured + * @param integer $col Column at which the error occured + * + * @return void + */ + public function displayError($msg, $token, $line, $col); + + /** + * Finish syntax check output rendering; no syntax errors found + * + * @return void + */ + public function finishOk(); +} +?> diff --git a/tools/php-sqllint/src/phpsqllint/Renderer/Emacs.php b/tools/php-sqllint/src/phpsqllint/Renderer/Emacs.php new file mode 100644 index 000000000..3a667c7f6 --- /dev/null +++ b/tools/php-sqllint/src/phpsqllint/Renderer/Emacs.php @@ -0,0 +1,70 @@ +<?php +/** + * Part of php-sqllint + * + * PHP version 5 + * + * @category Tools + * @package PHP-SQLlint + * @author Christian Weiske <cweiske@cweiske.de> + * @license http://www.gnu.org/licenses/agpl.html GNU AGPL v3 + * @link http://cweiske.de/php-sqllint.htm + */ +namespace phpsqllint; + +/** + * Output for emacs' compilation mode + * + * @category Tools + * @package PHP-SQLlint + * @author Christian Weiske <cweiske@cweiske.de> + * @license http://www.gnu.org/licenses/agpl.html GNU AGPL v3 + * @link http://www.emacswiki.org/emacs/CreatingYourOwnCompileErrorRegexp + */ +class Renderer_Emacs implements Renderer +{ + protected $filename; + + /** + * Begin syntax check output rendering + * + * @param string $filename Path to the SQL file + * + * @return void + */ + public function startRendering($filename) + { + $this->filename = $filename; + } + + /** + * Output errors in GNU style; see emacs compilation.txt + * + * @param string $msg Error message + * @param string $token Character which caused the error + * @param integer $line Line at which the error occured + * @param integer $col Column at which the error occured + * + * @return void + */ + public function displayError($msg, $token, $line, $col) + { + echo $this->filename + . ':' . $line + . '.' . $col + . ':Error:' + . ' '. $msg + . "\n"; + } + + /** + * Finish syntax check output rendering; no syntax errors found + * + * @return void + */ + public function finishOk() + { + //do nothing + } +} +?> diff --git a/tools/php-sqllint/src/phpsqllint/Renderer/Text.php b/tools/php-sqllint/src/phpsqllint/Renderer/Text.php new file mode 100644 index 000000000..44e7ecbd4 --- /dev/null +++ b/tools/php-sqllint/src/phpsqllint/Renderer/Text.php @@ -0,0 +1,102 @@ +<?php +/** + * Part of php-sqllint + * + * PHP version 5 + * + * @category Tools + * @package PHP-SQLlint + * @author Christian Weiske <cweiske@cweiske.de> + * @license http://www.gnu.org/licenses/agpl.html GNU AGPL v3 + * @link http://cweiske.de/php-sqllint.htm + */ +namespace phpsqllint; + +/** + * Textual output, easily readable by humans. + * + * @category Tools + * @package PHP-SQLlint + * @author Christian Weiske <cweiske@cweiske.de> + * @license http://www.gnu.org/licenses/agpl.html GNU AGPL v3 + * @link http://www.emacswiki.org/emacs/CreatingYourOwnCompileErrorRegexp + */ +class Renderer_Text implements Renderer +{ + protected $fileshown = false; + protected $filename = null; + + /** + * Begin syntax check output rendering + * + * @param string $filename Path to the SQL file + * + * @return void + */ + public function startRendering($filename) + { + $this->filename = $filename; + $this->fileshown = false; + } + + + protected function showFile() + { + if ($this->fileshown) { + return; + } + + echo "Checking SQL syntax of " . $this->filename . "\n"; + $this->fileshown = true; + } + + /** + * Show the error to the user. + * + * @param string $msg Error message + * @param string $token Character which caused the error + * @param integer $line Line at which the error occured + * @param integer $col Column at which the error occured + * + * @return void + */ + public function displayError($msg, $token, $line, $col) + { + $this->showFile(); + echo ' Line ' . $line + . ', col ' . $col + . ' at "' . $this->niceToken($token) . '":' + . ' ' . $msg + . "\n"; + } + + /** + * Finish syntax check output rendering; no syntax errors found + * + * @return void + */ + public function finishOk() + { + if ($this->fileshown) { + echo " OK\n"; + } + } + + /** + * Convert the token string to a readable one, especially special + * characters like newline and tabs + * + * @param string $str String with possibly special characters + * + * @return string Escaped string + */ + protected function niceToken($str) + { + return str_replace( + ["\n", "\r", "\t"], + ['\n', '\r', '\t'], + $str + ); + } +} +?> diff --git a/tools/php-sqllint/src/stub-phar.php b/tools/php-sqllint/src/stub-phar.php new file mode 100644 index 000000000..5c8629e23 --- /dev/null +++ b/tools/php-sqllint/src/stub-phar.php @@ -0,0 +1,18 @@ +#!/usr/bin/env php +<?php +/** + * Phar stub file for php-sqllint. Handles startup of the .phar file. + * + * PHP version 5 + * + * @category Tools + * @package PHP-SQLlint + * @author Christian Weiske <cweiske@cweiske.de> + * @copyright 2015 Christian Weiske + * @license http://www.gnu.org/licenses/agpl.html GNU AGPL v3 + * @link http://cweiske.de/php-sqllint.htm + */ +Phar::mapPhar('php-sqllint.phar'); +require 'phar://php-sqllint.phar/bin/phar-php-sqllint.php'; +__HALT_COMPILER(); +?> diff --git a/tools/scconfigconverter.py b/tools/scconfigconverter.py new file mode 100644 index 000000000..9216fa3b5 --- /dev/null +++ b/tools/scconfigconverter.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python +# -*- coding: utf8 -*- +# +# This file is part of Hercules. +# http://herc.ws - http://github.com/HerculesWS/Hercules +# +# Copyright (C) 2019 Hercules Dev Team +# Copyright (C) 2019 Asheraf +# +# Hercules is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# + +import csv + +with open('../db/sc_config.txt') as dbfile: + sc_config = csv.reader(dbfile, delimiter=',') + + print(r'''//================= Hercules Database ===================================== +//= _ _ _ +//= | | | | | | +//= | |_| | ___ _ __ ___ _ _| | ___ ___ +//= | _ |/ _ \ '__/ __| | | | |/ _ \/ __| +//= | | | | __/ | | (__| |_| | | __/\__ \ +//= \_| |_/\___|_| \___|\__,_|_|\___||___/ +//================= License =============================================== +//= This file is part of Hercules. +//= http://herc.ws - http://github.com/HerculesWS/Hercules +//= +//= Copyright (C) 2019 Hercules Dev Team +//= +//= Hercules is free software: you can redistribute it and/or modify +//= it under the terms of the GNU General Public License as published by +//= the Free Software Foundation, either version 3 of the License, or +//= (at your option) any later version. +//= +//= This program is distributed in the hope that it will be useful, +//= but WITHOUT ANY WARRANTY; without even the implied warranty of +//= MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +//= GNU General Public License for more details. +//= +//= You should have received a copy of the GNU General Public License +//= along with this program. If not, see <http://www.gnu.org/licenses/>. +//================= Description =========================================== +// Configurations file for status effects +//========================================================================= +''') + print('''/************************************************************************** + ************* Entry structure ******************************************** + ************************************************************************** +SC_TYPE: { + // ================ Optional fields =============================== + Visible: (bool) SC can be visible for all players + Flags: { + NoDeathReset: (bool) SC cannot be removed by death. + NoSave: (bool) SC cannot be saved. + NoDispelReset: (bool) SC cannot be reset by dispell. + NoClearanceReset: (bool) SC cannot be reset by clearance. + Buff: (bool) SC considered as buff and be removed by Hermode and etc. + Debuff: (bool) SC considered as debuff and be removed by Gospel and etc. + NoMadoReset: (bool) SC cannot be reset when MADO Gear is taken off. + NoAllReset: (bool) SC cannot be reset by 'sc_end SC_ALL' and status change clear. + } +} +**************************************************************************/''') + flags = [ + ('NoDeathReset', 1), + ('NoSave', 2), + ('NoDispelReset', 4), + ('NoClearanceReset', 8), + ('Buff', 16), + ('Debuff', 32), + ('NoMadoReset', 64), + ('NoAllReset', 128) + ] + + for sc in sc_config: + if len(sc) != 2 or sc[0].startswith('//'): + continue + value = int(sc[1]) + print('{}: {{'.format(sc[0])) + if value & 256: + print('\tVisible: true') + value &= ~256; + + print('\tFlags: {') + for flag in flags: + if value & flag[1]: + print('\t\t{}: true'.format(flag[0])) + value &= ~flag[1]; + if value != 0: + print('Error: invalid value ({}) for status ({}), aborting.'.format(int(sc[1]), sc[0])) + exit() + print('\t}') + print('}') diff --git a/tools/setup_mariadb.ps1 b/tools/setup_mariadb.ps1 new file mode 100644 index 000000000..709a5cf93 --- /dev/null +++ b/tools/setup_mariadb.ps1 @@ -0,0 +1,90 @@ +#Requires -Version 5.1 + +function Ask-Continue { Write-Output ""; pause; Write-Output "" } + +Write-Output "This script will automatically install MariaDB and configure it for you." +Write-Output "You may interrupt the installation by pressing CTRL+C or closing this window." +Ask-Continue + +if (-Not (Select-String -Quiet -SimpleMatch -Pattern "db_password: ""ragnarok""" -LiteralPath "$PSScriptRoot\..\conf\global\sql_connection.conf")) { + Write-Output "WARNING: It seems you already configured the sql connection for your server." + Write-Output "If you decide to continue, your settings will be overwritten." + Ask-Continue +} + +# step 1: install scoop +if (-Not (Get-Command scoop -errorAction SilentlyContinue)) { + Set-ExecutionPolicy RemoteSigned -scope Process -Force # <= this will trigger a yes/no prompt if not already authorized + Invoke-Expression (new-object net.webclient).downloadstring('https://get.scoop.sh') + scoop update +} + +# step 2: install mariadb +if (Test-Path $env:USERPROFILE\scoop\apps\mariadb) { + # usually we'd want to capture the output of "scoop list mariadb", but it uses + # Write-Host, so we can't, hence why we check manually for the folder + Write-Output "WARNING: MariaDB is already installed!" + Write-Output "If you decide to continue, your hercules user password will be overwritten." + Ask-Continue +} elseif (Get-Command mysqld -errorAction SilentlyContinue) { + Write-Output "ERROR: You already have a MySQL provider installed. To avoid conflict, MariaDB will not be installed." + Write-Output "If you wish to continue you will have to uninstall your current MySQL provider." + exit 1 +} else { + scoop install mariadb +} + +# step 3: add the herc user, set up the new database +$userpw = -join ((48..57) + (97..122) | Get-Random -Count 32 | % {[char]$_}) +$rootpw = -join ((48..57) + (97..122) | Get-Random -Count 32 | % {[char]$_}) +$maria_job = Start-Process -NoNewWindow -FilePath "mysqld.exe" -ArgumentList "--console" -PassThru -RedirectStandardError "$PSScriptRoot\maria.out" + +while (-Not $maria_job.HasExited) { + if ($lt -Lt 1 -And (Select-String -Quiet -SimpleMatch -Pattern "ready for connections" -LiteralPath "$PSScriptRoot\maria.out")) { +@" +CREATE DATABASE IF NOT EXISTS hercules; +DROP USER IF EXISTS 'hercules'@'localhost'; +DROP USER IF EXISTS 'hercules'@'127.0.0.1'; +CREATE USER 'hercules'@'localhost' IDENTIFIED BY '$userpw'; +CREATE USER 'hercules'@'127.0.0.1' IDENTIFIED BY '$userpw'; +-- ALTER USER 'root'@'localhost' IDENTIFIED BY '$rootpw'; +GRANT ALTER,CREATE,SELECT,INSERT,UPDATE,DELETE,DROP,INDEX ON `hercules`.* TO 'hercules'@'localhost'; +GRANT ALTER,CREATE,SELECT,INSERT,UPDATE,DELETE,DROP,INDEX ON `hercules`.* TO 'hercules'@'127.0.0.1'; +FLUSH PRIVILEGES; +USE `hercules`; +\. $PSScriptRoot\..\sql-files\main.sql +\. $PSScriptRoot\..\sql-files\logs.sql +shutdown; +\q +"@ | mysql.exe -u root + $lt++ + } + Start-Sleep 1 +} + +if ($lt -Lt 1) { + Write-Output "ERROR: MariaDB could not execute the query." + Write-Output "This might happen if your root user already has a password, or if the MySQL service is currently running." + $maria_job.close() + exit 1 +} + +# step 4: finish up +@" +sql_connection: { + db_username: "hercules" + db_password: "$userpw" + db_database: "hercules" +} +"@ | Out-File -Encoding UTF8 -LiteralPath "$PSScriptRoot\..\conf\global\sql_connection.conf" +Remove-Item -Force -errorAction SilentlyContinue "$PSScriptRoot\maria.out" +& "$PSScriptRoot\install_mariadb.bat" # <= we need admin permissions, so we use an external script +Write-Output "========= ALL DONE =========" +Write-Output "" +Write-Output "Your hercules installation is now configured to use MariaDB." +Write-Output "You can find the password in conf\global\sql_connection.conf." +Write-Output "" +Write-Output "If you want to start MariaDB on boot, use services.msc and set ""MySQL"" to Automatic." +Write-Output "" +Write-Output "Make sure you set a password for the root user. You can do this from the command line or from HeidiSQL." +Write-Output "You can obtain HeidiSQL at https://www.microsoft.com/store/productId/9NXPRT2T0ZJF" diff --git a/tools/utils/common.py b/tools/utils/common.py index 7b7811654..06695751a 100644 --- a/tools/utils/common.py +++ b/tools/utils/common.py @@ -21,7 +21,11 @@ # along with this program. If not, see <http://www.gnu.org/licenses/>. import io -import libconf as libconf +import sys +if sys.version_info >= (3, 0): + from utils import libconf as libconf +else: + import libconf as libconf import os.path def LoadDBConsts(DBname, mode, serverpath): @@ -35,13 +39,13 @@ def LoadDBConsts(DBname, mode, serverpath): with io.open(filename) as f: config = libconf.load(f) db = config[DBname] - if DBname is 'item_db': + if DBname == 'item_db': for i, v in enumerate(db): consts[db[i].Id] = db[i].AegisName - elif DBname is 'mob_db': + elif DBname == 'mob_db': for i, v in enumerate(db): consts[db[i].Id] = db[i].SpriteName - elif DBname is 'skill_db': + elif DBname == 'skill_db': for i, v in enumerate(db): consts[db[i].Id] = db[i].Name else: @@ -55,7 +59,6 @@ def LoadDB(DBname, mode, serverpath): if os.path.isfile(serverpath + 'db/{}2.conf'.format(DBname)): filenames.append(serverpath + 'db/{}2.conf'.format(DBname)) - consts = dict() for filename in filenames: with io.open(filename) as f: config = libconf.load(f) diff --git a/tools/utils/libconf.py b/tools/utils/libconf.py index 635efd07d..7f9d6de90 100644 --- a/tools/utils/libconf.py +++ b/tools/utils/libconf.py @@ -226,8 +226,15 @@ class Tokenizer: for cls, type, regex in self.token_map: m = regex.match(string, pos=pos) if m: - yield cls(type, m.group(0), - self.filename, self.row, self.column) + try: + yield cls(type, m.group(0), + self.filename, self.row, self.column) + except ValueError as e: + print("Error parsing file " + "{0}, in line:\n{1}\n{2}".format(self.filename, + m.group(0), + self.row)) + raise self.column += len(m.group(0)) pos = m.end() break |