Package ch.njol.skript.config

Examples of ch.njol.skript.config.Config


      for (int l = 0; l < 2; l++) {
        Language.setUseLocal(l == 1);
        if (l == 1 && !Language.isUsingLocal())
          break;
       
        final Config aliasConfig;
        try {
          final File file = new File(Skript.getInstance().getDataFolder(), "aliases-" + Language.getName() + ".sk");
          if (!file.exists()) {
            Skript.error("Could not find the " + Language.getName() + " aliases file " + file.getName());
          }
          aliasConfig = new Config(file, false, true, "=");
        } catch (final IOException e) {
          Skript.error("Could not load the " + Language.getName() + " aliases config: " + e.getLocalizedMessage());
          return;
        }
       
        final ArrayList<String> aliasNodes = new ArrayList<String>();
       
        aliasConfig.validate(
            new SectionValidator()
                .addEntry("aliases", new Setter<String>() {
                  @Override
                  public void set(final String s) {
                    for (final String n : s.split(","))
                      aliasNodes.add(n.trim());
                  }
                }, false)
                .addEntry("item", new Setter<String>() {
                  @Override
                  public void set(final String s) {
                    final NonNullPair<String, Integer> g = Noun.stripGender(s, "item");
                    itemGender = Noun.getGenderID(g.getSecond());
                    final NonNullPair<String, String> p = Noun.getPlural(g.getFirst());
                    itemSingular = "" + p.getFirst().toLowerCase();
                    itemPlural = "" + p.getSecond().toLowerCase();
                  }
                }, false)
                .addEntry("block", new Setter<String>() {
                  @Override
                  public void set(final String s) {
                    final NonNullPair<String, Integer> g = Noun.stripGender(s, "block");
                    blockGender = Noun.getGenderID(g.getSecond());
                    final NonNullPair<String, String> p = Noun.getPlural(g.getFirst());
                    blockSingular = "" + p.getFirst().toLowerCase();
                    blockPlural = "" + p.getSecond().toLowerCase();
                  }
                }, false)
                .setAllowUndefinedSections(true));
       
        for (final Node node : aliasConfig.getMainNode()) {
          if (node instanceof SectionNode) {
            if (!aliasNodes.contains(node.getKey())) {
              Skript.error(m_invalid_section.toString(node.getKey()));
            }
          }
        }
       
        final Variations variations = new Variations();
        int num = 0;
        for (final String an : aliasNodes) {
          final Node node = aliasConfig.getMainNode().get(an);
          SkriptLogger.setNode(node);
          if (node == null) {
            Skript.error(m_section_not_found.toString(an));
            continue;
          }
View Full Code Here


      if (!configFile.canRead()) {
        Skript.error("Config file 'config.sk' cannot be read!");
        return false;
      }
     
      Config mc;
      try {
        mc = new Config(configFile, false, false, ":");
      } catch (final IOException e) {
        Skript.error("Could not load the main config: " + e.getLocalizedMessage());
        return false;
      }
      mainConfig = mc;
     
      if (!Skript.getVersion().toString().equals(mc.get(version.key))) {
        try {
          final InputStream in = Skript.getInstance().getResource("config.sk");
          if (in == null) {
            Skript.error("Your config is outdated, but Skript couldn't find the newest config in its jar. Please download Skript again from dev.bukkit.org.");
            return false;
          }
          final Config newConfig = new Config(in, "Skript.jar/config.sk", false, false, ":");
          in.close();
         
          boolean forceUpdate = false;
         
          if (mc.getMainNode().get("database") != null) { // old database layout
            forceUpdate = true;
            try {
              final SectionNode oldDB = (SectionNode) mc.getMainNode().get("database");
              assert oldDB != null;
              final SectionNode newDBs = (SectionNode) newConfig.getMainNode().get(databases.key);
              assert newDBs != null;
              final SectionNode newDB = (SectionNode) newDBs.get("database 1");
              assert newDB != null;
             
              newDB.setValues(oldDB);
             
              // '.db' was dynamically added before
              final String file = newDB.getValue("file");
              assert file != null;
              if (!file.endsWith(".db"))
                newDB.set("file", file + ".db");
             
              final SectionNode def = (SectionNode) newDBs.get("default");
              assert def != null;
              def.set("backup interval", "" + mc.get("variables backup interval"));
            } catch (final Exception e) {
              Skript.error("An error occurred while trying to update the config's database section.");
              Skript.error("You'll have to update the config yourself:");
              Skript.error("Open the new config.sk as well as the created backup, and move the 'database' section from the backup to the start of the 'databases' section");
              Skript.error("of the new config (i.e. the line 'databases:' should be directly above 'database:'), and add a tab in front of every line that you just copied.");
              return false;
            }
          }
         
          if (newConfig.setValues(mc, version.key, databases.key) || forceUpdate) { // new config is different
            final File bu = FileUtils.backup(configFile);
            newConfig.getMainNode().set(version.key, Skript.getVersion().toString());
            if (mc.getMainNode().get(databases.key) != null)
              newConfig.getMainNode().set(databases.key, mc.getMainNode().get(databases.key));
            mc = mainConfig = newConfig;
            mc.save(configFile);
            Skript.info("Your configuration has been updated to the latest version. A backup of your old config file has been created as " + bu.getName());
          } else { // only the version changed
            mc.getMainNode().set(version.key, Skript.getVersion().toString());
View Full Code Here

  @Override
  public String toString() {
    final Node n = node;
    if (n == null || level.intValue() < Level.WARNING.intValue())
      return message;
    final Config c = n.getConfig();
    return message + from + " (" + c.getFileName() + ", line " + n.getLine() + ": " + n.save().trim() + "')";
  }
View Full Code Here

    final InputStream din = addon.plugin.getResource(addon.getLanguageFileDirectory() + "/english.lang");
    if (din == null)
      throw new IllegalStateException(addon + " is missing the required english.lang file!");
    HashMap<String, String> en;
    try {
      en = new Config(din, "english.lang", false, false, ":").toMap(".");
    } catch (final Exception e) {
      throw Skript.exception(e, "Could not load " + addon + "'s default language file!");
    } finally {
      try {
        din.close();
View Full Code Here

 
  private static HashMap<String, String> load(final @Nullable InputStream in, final String name) {
    if (in == null)
      return new HashMap<String, String>();
    try {
      return new Config(in, name + ".lang", false, false, ":").toMap(".");
    } catch (final IOException e) {
      Skript.exception(e, "Could not load the language file '" + name + ".lang': " + ExceptionUtils.toString(e));
      return new HashMap<String, String>();
    } finally {
      try {
View Full Code Here

//          }
//        }
//      }
//    }
    try {
      final Config config = new Config(f, true, false, ":");
      if (SkriptConfig.keepConfigsLoaded.value())
        SkriptConfig.configs.add(config);
      int numTriggers = 0;
      int numCommands = 0;
      int numFunctions = 0;
     
      currentAliases.clear();
      currentOptions.clear();
      currentScript = config;
     
//      final SerializedScript script = new SerializedScript();
     
      final CountingLogHandler numErrors = SkriptLogger.startLogHandler(new CountingLogHandler(SkriptLogger.SEVERE));
     
      try {
        for (final Node cnode : config.getMainNode()) {
          if (!(cnode instanceof SectionNode)) {
            Skript.error("invalid line - all code has to be put into triggers");
            continue;
          }
         
          final SectionNode node = ((SectionNode) cnode);
          String event = node.getKey();
          if (event == null)
            continue;
         
          if (event.equalsIgnoreCase("aliases")) {
            node.convertToEntries(0, "=");
            for (final Node n : node) {
              if (!(n instanceof EntryNode)) {
                Skript.error("invalid line in aliases section");
                continue;
              }
              final ItemType t = Aliases.parseAlias(((EntryNode) n).getValue());
              if (t == null)
                continue;
              currentAliases.put(((EntryNode) n).getKey().toLowerCase(), t);
            }
            continue;
          } else if (event.equalsIgnoreCase("options")) {
            node.convertToEntries(0);
            for (final Node n : node) {
              if (!(n instanceof EntryNode)) {
                Skript.error("invalid line in options");
                continue;
              }
              currentOptions.put(((EntryNode) n).getKey(), ((EntryNode) n).getValue());
            }
            continue;
          } else if (event.equalsIgnoreCase("variables")) {
            // TODO allow to make these override existing variables
            node.convertToEntries(0, "=");
            for (final Node n : node) {
              if (!(n instanceof EntryNode)) {
                Skript.error("Invalid line in variables section");
                continue;
              }
              String name = ((EntryNode) n).getKey().toLowerCase(Locale.ENGLISH);
              if (name.startsWith("{") && name.endsWith("}"))
                name = "" + name.substring(1, name.length() - 1);
              final String var = name;
              name = StringUtils.replaceAll(name, "%(.+)?%", new Callback<String, Matcher>() {
                @Override
                @Nullable
                public String run(final Matcher m) {
                  if (m.group(1).contains("{") || m.group(1).contains("}") || m.group(1).contains("%")) {
                    Skript.error("'" + var + "' is not a valid name for a default variable");
                    return null;
                  }
                  final ClassInfo<?> ci = Classes.getClassInfoFromUserInput("" + m.group(1));
                  if (ci == null) {
                    Skript.error("Can't understand the type '" + m.group(1) + "'");
                    return null;
                  }
                  return "<" + ci.getCodeName() + ">";
                }
              });
              if (name == null) {
                continue;
              } else if (name.contains("%")) {
                Skript.error("Invalid use of percent signs in variable name");
                continue;
              }
              if (Variables.getVariable(name, null, false) != null)
                continue;
              Object o;
              final ParseLogHandler log = SkriptLogger.startParseLogHandler();
              try {
                o = Classes.parseSimple(((EntryNode) n).getValue(), Object.class, ParseContext.SCRIPT);
                if (o == null) {
                  log.printError("Can't understand the value '" + ((EntryNode) n).getValue() + "'");
                  continue;
                }
                log.printLog();
              } finally {
                log.stop();
              }
              @SuppressWarnings("null")
              final ClassInfo<?> ci = Classes.getSuperClassInfo(o.getClass());
              if (ci.getSerializer() == null) {
                Skript.error("Can't save '" + ((EntryNode) n).getValue() + "' in a variable");
                continue;
              } else if (ci.getSerializeAs() != null) {
                final ClassInfo<?> as = Classes.getExactClassInfo(ci.getSerializeAs());
                if (as == null) {
                  assert false : ci;
                  continue;
                }
                o = Converters.convert(o, as.getC());
                if (o == null) {
                  Skript.error("Can't save '" + ((EntryNode) n).getValue() + "' in a variable");
                  continue;
                }
              }
              Variables.setVariable(name, o, null, false);
            }
            continue;
          }
         
          if (!SkriptParser.validateLine(event))
            continue;
         
          if (event.toLowerCase().startsWith("command ")) {
           
            setCurrentEvent("command", CommandEvent.class);
           
            final ScriptCommand c = Commands.loadCommand(node);
            if (c != null) {
              numCommands++;
//              script.commands.add(c);
            }
           
            deleteCurrentEvent();
           
            continue;
          } else if (event.toLowerCase().startsWith("function ")) {
           
            setCurrentEvent("function", FunctionEvent.class);
           
            final Function<?> func = Functions.loadFunction(node);
            if (func != null) {
              numFunctions++;
            }
           
            deleteCurrentEvent();
           
            continue;
          }
         
          if (Skript.logVeryHigh() && !Skript.debug())
            Skript.info("loading trigger '" + event + "'");
         
          if (StringUtils.startsWithIgnoreCase(event, "on "))
            event = "" + event.substring("on ".length());
         
          event = replaceOptions(event);
         
          final NonNullPair<SkriptEventInfo<?>, SkriptEvent> parsedEvent = SkriptParser.parseEvent(event, "can't understand this event: '" + node.getKey() + "'");
          if (parsedEvent == null)
            continue;
         
          if (Skript.debug() || node.debug())
            Skript.debug(event + " (" + parsedEvent.getSecond().toString(null, true) + "):");
         
          setCurrentEvent("" + parsedEvent.getFirst().getName().toLowerCase(Locale.ENGLISH), parsedEvent.getFirst().events);
          final Trigger trigger;
          try {
            trigger = new Trigger(config.getFile(), event, parsedEvent.getSecond(), loadItems(node));
          } finally {
            deleteCurrentEvent();
          }
         
          if (parsedEvent.getSecond() instanceof SelfRegisteringSkriptEvent) {
            ((SelfRegisteringSkriptEvent) parsedEvent.getSecond()).register(trigger);
            SkriptEventHandler.addSelfRegisteringTrigger(trigger);
          } else {
            SkriptEventHandler.addTrigger(parsedEvent.getFirst().events, trigger);
          }
         
//          script.triggers.add(trigger);
         
          numTriggers++;
        }
       
        if (Skript.logHigh())
          Skript.info("loaded " + numTriggers + " trigger" + (numTriggers == 1 ? "" : "s") + " and " + numCommands + " command" + (numCommands == 1 ? "" : "s") + " from '" + config.getFileName() + "'");
       
        currentScript = null;
      } finally {
        numErrors.stop();
      }
View Full Code Here

 
  private static void checkVariableConflicts(final String name, final StringMode mode, final @Nullable Iterable<Object> string) {
    if (mode != StringMode.VARIABLE_NAME || variableNames.containsKey(name))
      return;
    if (name.startsWith("%")) {// inside the if to only print this message once per variable
      final Config script = ScriptLoader.currentScript;
      if (script != null)
        Skript.warning("Starting a variable's name with an expression is discouraged ({" + name + "}). You could prefix it with the script's name: {" + StringUtils.substring(script.getFileName(), 0, -3) + "." + name + "}");
    }
   
    final Pattern pattern;
    if (string != null) {
      final StringBuilder p = new StringBuilder();
View Full Code Here

                  sender.sendMessage("Do you want to load it (this will not enable it)?");
                }
                if (waitForAnswer()) {
                  try {
                    sender.sendMessage("loading...");
                    Skript.configs.add(config = new Config(f, true, ":"));
                    node = config.getMainNode();
                    sender.sendMessage("loaded & selected " + f.getName());
                  } catch (final IOException e) {
                    sender.sendMessage("unable to load " + f.getName());
                  }
                }
                ok = true;
              }
            }
            if (!ok) {
              if (!answered)
                sender.sendMessage("file not found. Do you want to create it?");
              if (waitForAnswer()) {
                try {
                  final File f = new File(Skript.skript.getDataFolder(), Skript.TRIGGERFILEFOLDER + File.pathSeparator + p.second);
                  Skript.configs.add(config = new Config(f, true, ":"));
                  node = config.getMainNode();
                  sender.sendMessage("created & selected " + f.getName());
                } catch (final IOException e) {
                  sender.sendMessage("file creation failed. bad filename?");
                }
View Full Code Here

  public static boolean load() {
    assert variables.treeMap.isEmpty();
    assert variables.hashMap.isEmpty();
    assert storages.isEmpty();
   
    final Config c = SkriptConfig.getConfig();
    if (c == null)
      throw new SkriptAPIException("Cannot load variables before the config");
    final Node databases = c.getMainNode().get("databases");
    if (databases == null || !(databases instanceof SectionNode)) {
      Skript.error("The config is missing the required 'databases' section that defines where the variables are saved");
      return false;
    }
   
View Full Code Here

  @SuppressWarnings("null")
  private String name;
 
  @Override
  public boolean init(final Expression<?>[] exprs, final int matchedPattern, final Kleenean isDelayed, final ParseResult parseResult) {
    final Config script = ScriptLoader.currentScript;
    if (script == null) {
      assert false;
      return false;
    }
    String name = script.getFileName();
    if (name.contains("."))
      name = "" + name.substring(0, name.lastIndexOf('.'));
    this.name = name;
    return true;
  }
View Full Code Here

TOP

Related Classes of ch.njol.skript.config.Config

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.