Search in sources :

Example 26 with CString

use of com.laytonsmith.core.constructs.CString in project CommandHelper by EngineHub.

the class BukkitMCCommand method handleCustomCommand.

@Override
public boolean handleCustomCommand(MCCommandSender sender, String label, String[] args) {
    if (Commands.onCommand.containsKey(cmd.getName().toLowerCase())) {
        Target t = Target.UNKNOWN;
        CArray cargs = new CArray(t);
        for (String arg : args) {
            cargs.push(new CString(arg, t), t);
        }
        CClosure closure = Commands.onCommand.get(cmd.getName().toLowerCase());
        CommandHelperEnvironment cEnv = closure.getEnv().getEnv(CommandHelperEnvironment.class);
        cEnv.SetCommandSender(sender);
        cEnv.SetCommand("/" + label + StringUtils.Join(args, " "));
        try {
            closure.execute(new CString(label, t), new CString(sender.getName(), t), cargs, // reserved for an obgen style command array
            new CArray(t));
        } catch (FunctionReturnException e) {
            Construct fret = e.getReturn();
            if (fret instanceof CBoolean) {
                return ((CBoolean) fret).getBoolean();
            }
        } catch (ConfigRuntimeException cre) {
            cre.setEnv(closure.getEnv());
            ConfigRuntimeException.HandleUncaughtException(cre, closure.getEnv());
        }
        return true;
    } else {
        return false;
    }
}
Also used : Target(com.laytonsmith.core.constructs.Target) CClosure(com.laytonsmith.core.constructs.CClosure) CBoolean(com.laytonsmith.core.constructs.CBoolean) CArray(com.laytonsmith.core.constructs.CArray) CommandHelperEnvironment(com.laytonsmith.core.environments.CommandHelperEnvironment) Construct(com.laytonsmith.core.constructs.Construct) CString(com.laytonsmith.core.constructs.CString) FunctionReturnException(com.laytonsmith.core.exceptions.FunctionReturnException) ConfigRuntimeException(com.laytonsmith.core.exceptions.ConfigRuntimeException) CString(com.laytonsmith.core.constructs.CString)

Example 27 with CString

use of com.laytonsmith.core.constructs.CString in project CommandHelper by EngineHub.

the class Interpreter method doBuiltin.

public boolean doBuiltin(String script) {
    List<String> args = StringUtils.ArgParser(script);
    if (args.size() > 0) {
        String command = args.get(0);
        args.remove(0);
        command = command.toLowerCase(Locale.ENGLISH);
        switch(command) {
            case "help":
                pl(getHelpMsg());
                pl("Shell builtins:");
                pl("cd <dir> - Runs cd() with the provided argument.");
                pl("s - equivalent to cd('..').");
                pl("echo - Prints the arguments. If -e is set as the first argument, arguments are sent to colorize() first.");
                pl("exit - Exits shellMode, and returns back to normal mscript mode.");
                pl("logout - Exits the shell entirely with a return code of 0.");
                pl("pwd - Runs pwd()");
                pl("help - Prints this message.");
                return true;
            case "cd":
            case "s":
                if ("s".equals(command)) {
                    args.add("..");
                }
                if (args.size() > 1) {
                    pl(RED + "Too many arguments passed to cd");
                    return true;
                }
                Construct[] a = new Construct[0];
                if (args.size() == 1) {
                    a = new Construct[] { new CString(args.get(0), Target.UNKNOWN) };
                }
                try {
                    new Cmdline.cd().exec(Target.UNKNOWN, env, a);
                } catch (CREIOException ex) {
                    pl(RED + ex.getMessage());
                }
                return true;
            case "pwd":
                pl(new Cmdline.pwd().exec(Target.UNKNOWN, env).val());
                return true;
            case "exit":
                // We need previous code to intercept, we cannot do this here.
                throw new Error("I should not run");
            case "logout":
                new Cmdline.exit().exec(Target.UNKNOWN, env, new CInt(0, Target.UNKNOWN));
                // won't actually run
                return true;
            case "echo":
                // TODO Probably need some variable interpolation maybe? Otherwise, I don't think this command
                // is actually useful as is, because this is not supposed to be a scripting environment.. that's
                // what the normal shell is for.
                boolean colorize = false;
                if (args.size() > 0 && "-e".equals(args.get(0))) {
                    colorize = true;
                    args.remove(0);
                }
                String output = StringUtils.Join(args, " ");
                if (colorize) {
                    output = new Echoes.colorize().exec(Target.UNKNOWN, env, new CString(output, Target.UNKNOWN)).val();
                }
                pl(output);
                return true;
        }
    }
    return false;
}
Also used : CString(com.laytonsmith.core.constructs.CString) CString(com.laytonsmith.core.constructs.CString) Echoes(com.laytonsmith.core.functions.Echoes) CInt(com.laytonsmith.core.constructs.CInt) Construct(com.laytonsmith.core.constructs.Construct) Cmdline(com.laytonsmith.core.functions.Cmdline) CREIOException(com.laytonsmith.core.exceptions.CRE.CREIOException)

Example 28 with CString

use of com.laytonsmith.core.constructs.CString in project CommandHelper by EngineHub.

the class ObjectGenerator method fireworkEffect.

public MCFireworkEffect fireworkEffect(CArray fe, Target t) {
    MCFireworkBuilder builder = StaticLayer.GetConvertor().GetFireworkBuilder();
    if (fe.containsKey("flicker")) {
        builder.setFlicker(Static.getBoolean(fe.get("flicker", t), t));
    }
    if (fe.containsKey("trail")) {
        builder.setTrail(Static.getBoolean(fe.get("trail", t), t));
    }
    if (fe.containsKey("colors")) {
        Construct colors = fe.get("colors", t);
        if (colors instanceof CArray) {
            CArray ccolors = (CArray) colors;
            if (ccolors.size() == 0) {
                builder.addColor(MCColor.WHITE);
            } else {
                for (Construct color : ccolors.asList()) {
                    MCColor mccolor;
                    if (color instanceof CString) {
                        mccolor = StaticLayer.GetConvertor().GetColor(color.val(), t);
                    } else if (color instanceof CArray) {
                        mccolor = color((CArray) color, t);
                    } else if (color instanceof CInt && ccolors.size() == 3) {
                        // Appears to be a single color
                        builder.addColor(color(ccolors, t));
                        break;
                    } else {
                        throw new CREFormatException("Expecting individual color to be an array or string, but found " + color.typeof(), t);
                    }
                    builder.addColor(mccolor);
                }
            }
        } else if (colors instanceof CString) {
            String[] split = colors.val().split("\\|");
            if (split.length == 0) {
                builder.addColor(MCColor.WHITE);
            } else {
                for (String s : split) {
                    builder.addColor(StaticLayer.GetConvertor().GetColor(s, t));
                }
            }
        } else {
            throw new CREFormatException("Expecting an array or string for colors parameter, but found " + colors.typeof(), t);
        }
    } else {
        builder.addColor(MCColor.WHITE);
    }
    if (fe.containsKey("fade")) {
        Construct colors = fe.get("fade", t);
        if (colors instanceof CArray) {
            CArray ccolors = (CArray) colors;
            for (Construct color : ccolors.asList()) {
                MCColor mccolor;
                if (color instanceof CArray) {
                    mccolor = color((CArray) color, t);
                } else if (color instanceof CString) {
                    mccolor = StaticLayer.GetConvertor().GetColor(color.val(), t);
                } else if (color instanceof CInt && ccolors.size() == 3) {
                    // Appears to be a single color
                    builder.addFadeColor(color(ccolors, t));
                    break;
                } else {
                    throw new CREFormatException("Expecting individual color to be an array or string, but found " + color.typeof(), t);
                }
                builder.addFadeColor(mccolor);
            }
        } else if (colors instanceof CString) {
            String[] split = colors.val().split("\\|");
            for (String s : split) {
                builder.addFadeColor(StaticLayer.GetConvertor().GetColor(s, t));
            }
        } else {
            throw new CREFormatException("Expecting an array or string for fade parameter, but found " + colors.typeof(), t);
        }
    }
    if (fe.containsKey("type")) {
        try {
            builder.setType(MCFireworkType.valueOf(fe.get("type", t).val().toUpperCase()));
        } catch (IllegalArgumentException ex) {
            throw new CREFormatException(ex.getMessage(), t, ex);
        }
    }
    return builder.build();
}
Also used : CInt(com.laytonsmith.core.constructs.CInt) MCColor(com.laytonsmith.abstraction.MCColor) CArray(com.laytonsmith.core.constructs.CArray) Construct(com.laytonsmith.core.constructs.Construct) MCFireworkBuilder(com.laytonsmith.abstraction.MCFireworkBuilder) CString(com.laytonsmith.core.constructs.CString) CREFormatException(com.laytonsmith.core.exceptions.CRE.CREFormatException) CString(com.laytonsmith.core.constructs.CString)

Example 29 with CString

use of com.laytonsmith.core.constructs.CString in project CommandHelper by EngineHub.

the class ObjectGenerator method itemMeta.

public Construct itemMeta(MCItemStack is, Target t) {
    if (!is.hasItemMeta()) {
        return CNull.NULL;
    } else {
        Construct display, lore;
        CArray ma = CArray.GetAssociativeArray(t);
        MCItemMeta meta = is.getItemMeta();
        if (meta.hasDisplayName()) {
            display = new CString(meta.getDisplayName(), t);
        } else {
            display = CNull.NULL;
        }
        if (meta.hasLore()) {
            lore = new CArray(t);
            for (String l : meta.getLore()) {
                ((CArray) lore).push(new CString(l, t), t);
            }
        } else {
            lore = CNull.NULL;
        }
        ma.set("display", display, t);
        ma.set("lore", lore, t);
        ma.set("enchants", enchants(meta.getEnchants(), t), t);
        ma.set("repair", new CInt(meta.getRepairCost(), t), t);
        // Version specific ItemMeta
        if (Static.getServer().getMinecraftVersion().gte(MCVersion.MC1_8)) {
            Set<MCItemFlag> itemFlags = meta.getItemFlags();
            CArray flagArray = new CArray(t);
            if (itemFlags.size() > 0) {
                for (MCItemFlag flag : itemFlags) {
                    flagArray.push(new CString(flag.name(), t), t);
                }
            }
            ma.set("flags", flagArray, t);
            if (Static.getServer().getMinecraftVersion().gte(MCVersion.MC1_11)) {
                ma.set("unbreakable", CBoolean.get(meta.isUnbreakable()), t);
            }
        }
        // Specific ItemMeta
        if (meta instanceof MCBlockStateMeta) {
            MCBlockState bs = ((MCBlockStateMeta) meta).getBlockState();
            if (bs instanceof MCShulkerBox) {
                MCShulkerBox mcsb = (MCShulkerBox) bs;
                MCInventory inv = mcsb.getInventory();
                CArray box = CArray.GetAssociativeArray(t);
                for (int i = 0; i < inv.getSize(); i++) {
                    Construct item = ObjectGenerator.GetGenerator().item(inv.getItem(i), t);
                    if (!(item instanceof CNull)) {
                        box.set(i, item, t);
                    }
                }
                ma.set("inventory", box, t);
            } else if (bs instanceof MCBanner) {
                MCBanner banner = (MCBanner) bs;
                CArray patterns = new CArray(t, banner.numberOfPatterns());
                for (MCPattern p : banner.getPatterns()) {
                    CArray pattern = CArray.GetAssociativeArray(t);
                    pattern.set("shape", new CString(p.getShape().toString(), t), t);
                    pattern.set("color", new CString(p.getColor().toString(), t), t);
                    patterns.push(pattern, t);
                }
                ma.set("patterns", patterns, t);
                MCDyeColor dyeColor = banner.getBaseColor();
                if (dyeColor != null) {
                    ma.set("basecolor", new CString(dyeColor.toString(), t), t);
                }
            } else if (bs instanceof MCCreatureSpawner) {
                MCCreatureSpawner mccs = (MCCreatureSpawner) bs;
                ma.set("spawntype", mccs.getSpawnedType().name());
            }
        } else if (meta instanceof MCFireworkEffectMeta) {
            MCFireworkEffectMeta mcfem = (MCFireworkEffectMeta) meta;
            MCFireworkEffect effect = mcfem.getEffect();
            if (effect == null) {
                ma.set("effect", CNull.NULL, t);
            } else {
                ma.set("effect", fireworkEffect(effect, t), t);
            }
        } else if (meta instanceof MCFireworkMeta) {
            MCFireworkMeta mcfm = (MCFireworkMeta) meta;
            CArray firework = CArray.GetAssociativeArray(t);
            firework.set("strength", new CInt(mcfm.getStrength(), t), t);
            CArray fe = new CArray(t);
            for (MCFireworkEffect effect : mcfm.getEffects()) {
                fe.push(fireworkEffect(effect, t), t);
            }
            firework.set("effects", fe, t);
            ma.set("firework", firework, t);
        } else if (meta instanceof MCLeatherArmorMeta) {
            CArray color = color(((MCLeatherArmorMeta) meta).getColor(), t);
            ma.set("color", color, t);
        } else if (meta instanceof MCBookMeta) {
            Construct title, author, pages;
            if (((MCBookMeta) meta).hasTitle()) {
                title = new CString(((MCBookMeta) meta).getTitle(), t);
            } else {
                title = CNull.NULL;
            }
            if (((MCBookMeta) meta).hasAuthor()) {
                author = new CString(((MCBookMeta) meta).getAuthor(), t);
            } else {
                author = CNull.NULL;
            }
            if (((MCBookMeta) meta).hasPages()) {
                pages = new CArray(t);
                for (String p : ((MCBookMeta) meta).getPages()) {
                    ((CArray) pages).push(new CString(p, t), t);
                }
            } else {
                pages = CNull.NULL;
            }
            ma.set("title", title, t);
            ma.set("author", author, t);
            ma.set("pages", pages, t);
        } else if (meta instanceof MCSkullMeta) {
            if (Static.getServer().getMinecraftVersion().gte(MCVersion.MC1_12_X)) {
                if (((MCSkullMeta) meta).hasOwner()) {
                    MCOfflinePlayer player = ((MCSkullMeta) meta).getOwningPlayer();
                    ma.set("owner", new CString(player.getName(), t), t);
                    ma.set("owneruuid", new CString(player.getUniqueID().toString(), t), t);
                } else {
                    ma.set("owner", CNull.NULL, t);
                    ma.set("owneruuid", CNull.NULL, t);
                }
            } else {
                if (((MCSkullMeta) meta).hasOwner()) {
                    ma.set("owner", new CString(((MCSkullMeta) meta).getOwner(), t), t);
                } else {
                    ma.set("owner", CNull.NULL, t);
                }
            }
        } else if (meta instanceof MCEnchantmentStorageMeta) {
            Construct stored;
            if (((MCEnchantmentStorageMeta) meta).hasStoredEnchants()) {
                stored = enchants(((MCEnchantmentStorageMeta) meta).getStoredEnchants(), t);
            } else {
                stored = CNull.NULL;
            }
            ma.set("stored", stored, t);
        } else if (meta instanceof MCPotionMeta) {
            MCPotionMeta potionmeta = (MCPotionMeta) meta;
            CArray effects = potions(potionmeta.getCustomEffects(), t);
            ma.set("potions", effects, t);
            if (Static.getServer().getMinecraftVersion().gte(MCVersion.MC1_9)) {
                MCPotionData potiondata = potionmeta.getBasePotionData();
                if (potiondata != null) {
                    ma.set("base", potionData(potiondata, t), t);
                }
            } else if (effects.size() > 0) {
                ma.set("main", ((CArray) effects.get(0, t)).get("id", t), t);
            }
        } else if (meta instanceof MCBannerMeta) {
            MCBannerMeta bannermeta = (MCBannerMeta) meta;
            CArray patterns = new CArray(t, bannermeta.numberOfPatterns());
            for (MCPattern p : bannermeta.getPatterns()) {
                CArray pattern = CArray.GetAssociativeArray(t);
                pattern.set("shape", new CString(p.getShape().toString(), t), t);
                pattern.set("color", new CString(p.getColor().toString(), t), t);
                patterns.push(pattern, t);
            }
            ma.set("patterns", patterns, t);
            MCDyeColor dyeColor = bannermeta.getBaseColor();
            if (dyeColor != null) {
                ma.set("basecolor", new CString(dyeColor.toString(), t), t);
            }
        } else if (meta instanceof MCSpawnEggMeta) {
            MCEntityType spawntype = ((MCSpawnEggMeta) meta).getSpawnedType();
            if (spawntype == null) {
                ma.set("spawntype", CNull.NULL, t);
            } else {
                ma.set("spawntype", new CString(spawntype.name(), t), t);
            }
        } else if (meta instanceof MCMapMeta && Static.getServer().getMinecraftVersion().gte(MCVersion.MC1_11)) {
            MCColor mapcolor = ((MCMapMeta) meta).getColor();
            Construct color;
            if (mapcolor == null) {
                color = CNull.NULL;
            } else {
                color = color(mapcolor, t);
            }
            ma.set("color", color, t);
        }
        return ma;
    }
}
Also used : MCBanner(com.laytonsmith.abstraction.blocks.MCBanner) MCEntityType(com.laytonsmith.abstraction.enums.MCEntityType) MCOfflinePlayer(com.laytonsmith.abstraction.MCOfflinePlayer) MCFireworkMeta(com.laytonsmith.abstraction.MCFireworkMeta) CArray(com.laytonsmith.core.constructs.CArray) MCLeatherArmorMeta(com.laytonsmith.abstraction.MCLeatherArmorMeta) MCSpawnEggMeta(com.laytonsmith.abstraction.MCSpawnEggMeta) CString(com.laytonsmith.core.constructs.CString) CString(com.laytonsmith.core.constructs.CString) MCPattern(com.laytonsmith.abstraction.MCPattern) MCFireworkEffect(com.laytonsmith.abstraction.MCFireworkEffect) MCPotionMeta(com.laytonsmith.abstraction.MCPotionMeta) MCMapMeta(com.laytonsmith.abstraction.MCMapMeta) MCColor(com.laytonsmith.abstraction.MCColor) MCItemFlag(com.laytonsmith.abstraction.enums.MCItemFlag) MCDyeColor(com.laytonsmith.abstraction.enums.MCDyeColor) MCBookMeta(com.laytonsmith.abstraction.MCBookMeta) MCBlockStateMeta(com.laytonsmith.abstraction.MCBlockStateMeta) MCFireworkEffectMeta(com.laytonsmith.abstraction.MCFireworkEffectMeta) MCBlockState(com.laytonsmith.abstraction.blocks.MCBlockState) MCBannerMeta(com.laytonsmith.abstraction.MCBannerMeta) MCInventory(com.laytonsmith.abstraction.MCInventory) MCSkullMeta(com.laytonsmith.abstraction.MCSkullMeta) MCItemMeta(com.laytonsmith.abstraction.MCItemMeta) MCPotionData(com.laytonsmith.abstraction.MCPotionData) MCEnchantmentStorageMeta(com.laytonsmith.abstraction.MCEnchantmentStorageMeta) CInt(com.laytonsmith.core.constructs.CInt) MCCreatureSpawner(com.laytonsmith.abstraction.MCCreatureSpawner) Construct(com.laytonsmith.core.constructs.Construct) MCShulkerBox(com.laytonsmith.abstraction.blocks.MCShulkerBox) CNull(com.laytonsmith.core.constructs.CNull)

Example 30 with CString

use of com.laytonsmith.core.constructs.CString in project CommandHelper by EngineHub.

the class Main method main.

@SuppressWarnings("ResultOfObjectAllocationIgnored")
public static void main(String[] args) throws Exception {
    try {
        Implementation.setServerType(Implementation.Type.SHELL);
        CHLog.initialize(MethodScriptFileLocations.getDefault().getJarDirectory());
        Prefs.init(MethodScriptFileLocations.getDefault().getPreferencesFile());
        Prefs.SetColors();
        if (Prefs.UseColors()) {
            // Use jansi to enable output to color properly, even on windows.
            org.fusesource.jansi.AnsiConsole.systemInstall();
        }
        ClassDiscovery cd = ClassDiscovery.getDefaultInstance();
        cd.addDiscoveryLocation(ClassDiscovery.GetClassContainer(Main.class));
        ClassDiscoveryCache cdcCache = new ClassDiscoveryCache(MethodScriptFileLocations.getDefault().getCacheDirectory());
        cd.setClassDiscoveryCache(cdcCache);
        cd.addAllJarsInFolder(MethodScriptFileLocations.getDefault().getExtensionsDirectory());
        ExtensionManager.AddDiscoveryLocation(MethodScriptFileLocations.getDefault().getExtensionsDirectory());
        ExtensionManager.Cache(MethodScriptFileLocations.getDefault().getExtensionCacheDirectory());
        ExtensionManager.Initialize(cd);
        ExtensionManager.Startup();
        if (args.length == 0) {
            args = new String[] { "--help" };
        }
        // I'm not sure why this is in Main, but if this breaks something, it needs to be put back.
        // However, if it is put back, then it needs to be figured out why this causes the terminal
        // to lose focus on mac.
        // AnnotationChecks.checkForceImplementation();
        ArgumentParser mode;
        ArgumentParser.ArgumentParserResults parsedArgs;
        try {
            ArgumentSuite.ArgumentSuiteResults results = ARGUMENT_SUITE.match(args, "help");
            mode = results.getMode();
            parsedArgs = results.getResults();
        } catch (ArgumentParser.ResultUseException | ArgumentParser.ValidationException e) {
            StreamUtils.GetSystemOut().println(TermColors.RED + e.getMessage() + TermColors.RESET);
            mode = helpMode;
            parsedArgs = null;
        }
        if (mode == helpMode) {
            String modeForHelp = null;
            if (parsedArgs != null) {
                modeForHelp = parsedArgs.getStringArgument();
            }
            modeForHelp = ARGUMENT_SUITE.getModeFromAlias(modeForHelp);
            if (modeForHelp == null) {
                // Display the general help
                StreamUtils.GetSystemOut().println(ARGUMENT_SUITE.getBuiltDescription());
                System.exit(0);
                return;
            } else {
                // Display the help for this mode
                StreamUtils.GetSystemOut().println(ARGUMENT_SUITE.getModeFromName(modeForHelp).getBuiltDescription());
                return;
            }
        }
        // if it were, the help command would have run.
        assert parsedArgs != null;
        if (mode == managerMode) {
            Manager.start();
            System.exit(0);
        } else if (mode == coreFunctionsMode) {
            List<String> core = new ArrayList<>();
            for (api.Platforms platform : api.Platforms.values()) {
                for (FunctionBase f : FunctionList.getFunctionList(platform)) {
                    if (f.isCore()) {
                        core.add(f.getName());
                    }
                }
            }
            Collections.sort(core);
            StreamUtils.GetSystemOut().println(StringUtils.Join(core, ", "));
            System.exit(0);
        } else if (mode == interpreterMode) {
            new Interpreter(parsedArgs.getStringListArgument(), parsedArgs.getStringArgument("location-----"));
            System.exit(0);
        } else if (mode == installCmdlineMode) {
            Interpreter.install();
            System.exit(0);
        } else if (mode == uninstallCmdlineMode) {
            Interpreter.uninstall();
            System.exit(0);
        } else if (mode == docgenMode) {
            DocGenUI.main(args);
            System.exit(0);
        } else if (mode == mslpMode) {
            String mslp = parsedArgs.getStringArgument();
            if (mslp.isEmpty()) {
                StreamUtils.GetSystemOut().println("Usage: --mslp path/to/folder");
                System.exit(0);
            }
            MSLPMaker.start(mslp);
            System.exit(0);
        } else if (mode == versionMode) {
            StreamUtils.GetSystemOut().println("You are running " + Implementation.GetServerType().getBranding() + " version " + loadSelfVersion());
            System.exit(0);
        } else if (mode == copyrightMode) {
            StreamUtils.GetSystemOut().println("The MIT License (MIT)\n" + "\n" + "Copyright (c) 2012-2017 Methodscript Contributors\n" + "\n" + "Permission is hereby granted, free of charge, to any person obtaining a copy of \n" + "this software and associated documentation files (the \"Software\"), to deal in \n" + "the Software without restriction, including without limitation the rights to \n" + "use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of \n" + "the Software, and to permit persons to whom the Software is furnished to do so, \n" + "subject to the following conditions:\n" + "\n" + "The above copyright notice and this permission notice shall be included in all \n" + "copies or substantial portions of the Software.\n" + "\n" + "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR \n" + "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS \n" + "FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR \n" + "COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER \n" + "IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN \n" + "CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.");
            System.exit(0);
        } else if (mode == printDBMode) {
            ConnectionMixinFactory.ConnectionMixinOptions options = new ConnectionMixinFactory.ConnectionMixinOptions();
            options.setWorkingDirectory(MethodScriptFileLocations.getDefault().getConfigDirectory());
            PersistenceNetwork pn = new PersistenceNetwork(MethodScriptFileLocations.getDefault().getPersistenceConfig(), new URI("sqlite://" + MethodScriptFileLocations.getDefault().getDefaultPersistenceDBFile().getCanonicalPath().replace('\\', '/')), options);
            Map<String[], String> values = pn.getNamespace(new String[] {});
            for (String[] s : values.keySet()) {
                StreamUtils.GetSystemOut().println(StringUtils.Join(s, ".") + "=" + values.get(s));
            }
            System.exit(0);
        } else if (mode == docsMode) {
            DocGen.MarkupType docs;
            try {
                docs = DocGen.MarkupType.valueOf(parsedArgs.getStringArgument().toUpperCase());
            } catch (IllegalArgumentException e) {
                StreamUtils.GetSystemOut().println("The type of documentation must be one of the following: " + StringUtils.Join(DocGen.MarkupType.values(), ", ", ", or "));
                System.exit(1);
                return;
            }
            // Documentation generator
            StreamUtils.GetSystemErr().print("Creating " + docs + " documentation...");
            DocGen.functions(docs, api.Platforms.INTERPRETER_JAVA, true);
            StreamUtils.GetSystemErr().println("Done.");
            System.exit(0);
        } else if (mode == examplesMode) {
            ExampleLocalPackageInstaller.run(MethodScriptFileLocations.getDefault().getJarDirectory(), parsedArgs.getStringArgument());
        } else if (mode == verifyMode) {
            String file = parsedArgs.getStringArgument();
            if ("".equals(file)) {
                StreamUtils.GetSystemErr().println("File parameter is required.");
                System.exit(1);
            }
            File f = new File(file);
            String script = FileUtil.read(f);
            try {
                try {
                    MethodScriptCompiler.compile(MethodScriptCompiler.lex(script, f, file.endsWith("ms")));
                } catch (ConfigCompileException ex) {
                    Set<ConfigCompileException> s = new HashSet<>(1);
                    s.add(ex);
                    throw new ConfigCompileGroupException(s);
                }
            } catch (ConfigCompileGroupException ex) {
                List<Map<String, Object>> err = new ArrayList<>();
                for (ConfigCompileException e : ex.getList()) {
                    Map<String, Object> error = new HashMap<>();
                    error.put("msg", e.getMessage());
                    error.put("file", e.getFile().getAbsolutePath());
                    error.put("line", e.getLineNum());
                    error.put("col", e.getColumn());
                    // TODO: Need to track target length for this
                    error.put("len", 0);
                    err.add(error);
                }
                String serr = JSONValue.toJSONString(err);
                StreamUtils.GetSystemOut().println(serr);
            }
        } else if (mode == apiMode) {
            String function = parsedArgs.getStringArgument();
            if ("".equals(function)) {
                StreamUtils.GetSystemErr().println("Usage: java -jar CommandHelper.jar --api <function name>");
                System.exit(1);
            }
            FunctionBase f;
            try {
                f = FunctionList.getFunction(function, Target.UNKNOWN);
            } catch (ConfigCompileException e) {
                StreamUtils.GetSystemErr().println("The function '" + function + "' was not found.");
                System.exit(1);
                throw new Error();
            }
            DocGen.DocInfo di = new DocGen.DocInfo(f.docs());
            String ret = di.ret.replaceAll("</?[a-z].*?>", "");
            String args2 = di.args.replaceAll("</?[a-z].*?>", "");
            String desc = (di.desc + (di.extendedDesc != null ? "\n\n" + di.extendedDesc : "")).replaceAll("</?[a-z].*?>", "");
            StreamUtils.GetSystemOut().println(StringUtils.Join(new String[] { function, "Returns " + ret, "Expects " + args2, desc }, " // "));
            System.exit(0);
        } else if (mode == syntaxMode) {
            // TODO: Maybe load extensions here?
            List<String> syntax = parsedArgs.getStringListArgument();
            String type = (syntax.size() >= 1 ? syntax.get(0) : null);
            String theme = (syntax.size() >= 2 ? syntax.get(1) : null);
            StreamUtils.GetSystemOut().println(SyntaxHighlighters.generate(type, theme));
            System.exit(0);
        } else if (mode == optimizerTestMode) {
            String path = parsedArgs.getStringArgument();
            File source = new File(path);
            String plain = FileUtil.read(source);
            Security.setSecurityEnabled(false);
            String optimized;
            try {
                try {
                    optimized = OptimizationUtilities.optimize(plain, source);
                } catch (ConfigCompileException ex) {
                    Set<ConfigCompileException> group = new HashSet<>();
                    group.add(ex);
                    throw new ConfigCompileGroupException(group);
                }
            } catch (ConfigCompileGroupException ex) {
                ConfigRuntimeException.HandleUncaughtException(ex, null);
                System.exit(1);
                return;
            }
            StreamUtils.GetSystemOut().println(optimized);
            System.exit(0);
        } else if (mode == cmdlineMode) {
            // We actually can't use the parsedArgs, because there may be cmdline switches in
            // the arguments that we want to ignore here, but otherwise pass through. parsedArgs
            // will prevent us from seeing those, however.
            List<String> allArgs = new ArrayList<>(Arrays.asList(args));
            // The 0th arg is the cmdline verb though, so remove that.
            allArgs.remove(0);
            if (allArgs.isEmpty()) {
                StreamUtils.GetSystemErr().println("Usage: path/to/file.ms [arg1 arg2]");
                System.exit(1);
            }
            String fileName = allArgs.get(0);
            allArgs.remove(0);
            try {
                Interpreter.startWithTTY(fileName, allArgs);
            } catch (Profiles.InvalidProfileException ex) {
                StreamUtils.GetSystemErr().println("Invalid profile file at " + MethodScriptFileLocations.getDefault().getProfilesFile() + ": " + ex.getMessage());
                System.exit(1);
            }
            StaticLayer.GetConvertor().runShutdownHooks();
            System.exit(0);
        } else if (mode == extensionDocsMode) {
            String inputJarS = parsedArgs.getStringArgument("input-jar");
            String outputFileS = parsedArgs.getStringArgument("output-file");
            if (inputJarS == null) {
                StreamUtils.GetSystemOut().println("Usage: --input-jar extension-docs path/to/extension.jar [--output-file path/to/output.md]\n\tIf the output is blank, it is printed to stdout.");
                System.exit(1);
            }
            File inputJar = new File(inputJarS);
            OutputStream outputFile = StreamUtils.GetSystemOut();
            if (outputFileS != null) {
                outputFile = new FileOutputStream(new File(outputFileS));
            }
            ExtensionDocGen.generate(inputJar, outputFile);
        } else if (mode == docExportMode) {
            String extensionDirS = parsedArgs.getStringArgument("extension-dir");
            String outputFileS = parsedArgs.getStringArgument("output-file");
            OutputStream outputFile = StreamUtils.GetSystemOut();
            if (outputFileS != null) {
                outputFile = new FileOutputStream(new File(outputFileS));
            }
            Implementation.forceServerType(Implementation.Type.BUKKIT);
            File extensionDir = new File(extensionDirS);
            if (extensionDir.exists()) {
                // to stderr.
                for (File f : extensionDir.listFiles()) {
                    if (f.getName().endsWith(".jar")) {
                        cd.addDiscoveryLocation(f.toURI().toURL());
                    }
                }
            } else {
                StreamUtils.GetSystemErr().println("Extension directory specificed doesn't exist: " + extensionDirS + ". Continuing anyways.");
            }
            new DocGenExportTool(cd, outputFile).export();
        } else if (mode == profilerSummaryMode) {
            String input = parsedArgs.getStringArgument();
            if ("".equals(input)) {
                StreamUtils.GetSystemErr().println(TermColors.RED + "No input file specified! Run `help profiler-summary' for usage." + TermColors.RESET);
                System.exit(1);
            }
            double ignorePercentage = parsedArgs.getNumberArgument("ignore-percentage");
            ProfilerSummary summary = new ProfilerSummary(new FileInputStream(input));
            try {
                summary.setIgnorePercentage(ignorePercentage);
            } catch (IllegalArgumentException ex) {
                StreamUtils.GetSystemErr().println(TermColors.RED + ex.getMessage() + TermColors.RESET);
                System.exit(1);
            }
            StreamUtils.GetSystemOut().println(summary.getAnalysis());
            System.exit(0);
        } else if (mode == rsaKeyGenMode) {
            String outputFileString = parsedArgs.getStringArgument('o');
            File privOutputFile = new File(outputFileString);
            File pubOutputFile = new File(outputFileString + ".pub");
            String label = parsedArgs.getStringArgument('l');
            if (privOutputFile.exists() || pubOutputFile.exists()) {
                StreamUtils.GetSystemErr().println("Either the public key or private key file already exists. This utility will not overwrite any existing files.");
                System.exit(1);
            }
            RSAEncrypt enc = RSAEncrypt.generateKey(label);
            FileUtil.write(enc.getPrivateKey(), privOutputFile);
            FileUtil.write(enc.getPublicKey(), pubOutputFile);
            System.exit(0);
        } else if (mode == pnViewerMode) {
            if (parsedArgs.isFlagSet("server")) {
                if (parsedArgs.getNumberArgument("port") == null) {
                    StreamUtils.GetSystemErr().println("When running as a server, port is required.");
                    System.exit(1);
                }
                int port = parsedArgs.getNumberArgument("port").intValue();
                if (port > 65535 || port < 1) {
                    StreamUtils.GetSystemErr().println("Port must be between 1 and 65535.");
                    System.exit(1);
                }
                String password = parsedArgs.getStringArgument("password");
                if ("".equals(password)) {
                    ConsoleReader reader = null;
                    try {
                        reader = new ConsoleReader();
                        reader.setExpandEvents(false);
                        Character cha = new Character((char) 0);
                        password = reader.readLine("Enter password: ", cha);
                    } finally {
                        if (reader != null) {
                            reader.shutdown();
                        }
                    }
                }
                if (password == null) {
                    StreamUtils.GetSystemErr().println("Warning! Running server with no password, anyone will be able to connect!");
                    password = "";
                }
                try {
                    PNViewer.startServer(port, password);
                } catch (IOException ex) {
                    StreamUtils.GetSystemErr().println(ex.getMessage());
                    System.exit(1);
                }
            } else {
                try {
                    PNViewer.main(parsedArgs.getStringListArgument().toArray(ArrayUtils.EMPTY_STRING_ARRAY));
                } catch (HeadlessException ex) {
                    StreamUtils.GetSystemErr().println("The Persistence Network Viewer may not be run from a headless environment.");
                    System.exit(1);
                }
            }
        } else if (mode == uiMode) {
            if (parsedArgs.isFlagSet("in-shell")) {
                // Actually launch the GUI
                UILauncher.main(args);
            } else {
                // Relaunch the jar in a new process with the --run flag set,
                // so that the process will be in its own subshell
                CommandExecutor ce = new CommandExecutor("java -jar " + ClassDiscovery.GetClassContainer(Main.class).getPath() + " " + StringUtils.Join(args, " ") + " --in-shell");
                ce.start();
                System.exit(0);
            }
        } else if (mode == siteDeploy) {
            boolean clearLocalCache = parsedArgs.isFlagSet("clear-local-cache");
            if (clearLocalCache) {
                PersistenceNetwork p = SiteDeploy.getPersistenceNetwork();
                if (p == null) {
                    System.out.println("Cannot get reference to persistence network");
                    System.exit(1);
                    return;
                }
                DaemonManager dm = new DaemonManager();
                p.clearKey(dm, new String[] { "site_deploy", "local_cache" });
                dm.waitForThreads();
                System.out.println("Local cache cleared");
                System.exit(0);
            }
            boolean generatePrefs = parsedArgs.isFlagSet("generate-prefs");
            boolean useLocalCache = parsedArgs.isFlagSet("use-local-cache");
            boolean doValidation = parsedArgs.isFlagSet("do-validation");
            String configString = parsedArgs.getStringArgument("config");
            if ("".equals(configString)) {
                System.err.println("Config file missing, check command and try again");
                System.exit(1);
            }
            File config = new File(configString);
            SiteDeploy.run(generatePrefs, useLocalCache, config, "", doValidation);
        } else if (mode == newMode) {
            String li = OSUtils.GetLineEnding();
            for (String file : parsedArgs.getStringListArgument()) {
                File f = new File(file);
                if (f.exists() && !parsedArgs.isFlagSet('f')) {
                    System.out.println(file + " already exists, refusing to create");
                    continue;
                }
                f.createNewFile();
                f.setExecutable(true);
                FileUtil.write("#!/usr/bin/env /usr/local/bin/mscript" + li + "<!" + li + "\tstrict;" + li + "\tname: " + f.getName() + ";" + li + "\tauthor: " + StaticLayer.GetConvertor().GetUser(null) + ";" + li + "\tcreated: " + new Scheduling.simple_date().exec(Target.UNKNOWN, null, new CString("yyyy-MM-dd", Target.UNKNOWN)).val() + ";" + li + "\tdescription: " + ";" + li + ">" + li + li, f, true);
            }
        } else {
            throw new Error("Should not have gotten here");
        }
    } catch (NoClassDefFoundError error) {
        StreamUtils.GetSystemErr().println(getNoClassDefFoundErrorMessage(error));
    }
}
Also used : DocGenExportTool(com.laytonsmith.tools.docgen.DocGenExportTool) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) ArrayList(java.util.ArrayList) CommandExecutor(com.laytonsmith.PureUtilities.CommandExecutor) CString(com.laytonsmith.core.constructs.CString) PersistenceNetwork(com.laytonsmith.persistence.PersistenceNetwork) ArgumentSuite(com.laytonsmith.PureUtilities.ArgumentSuite) ConnectionMixinFactory(com.laytonsmith.persistence.io.ConnectionMixinFactory) FunctionList(com.laytonsmith.core.functions.FunctionList) List(java.util.List) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ProfilerSummary(com.laytonsmith.tools.ProfilerSummary) ClassDiscovery(com.laytonsmith.PureUtilities.ClassLoading.ClassDiscovery) FileInputStream(java.io.FileInputStream) FileOutputStream(java.io.FileOutputStream) Map(java.util.Map) HashMap(java.util.HashMap) File(java.io.File) ClassDiscoveryCache(com.laytonsmith.PureUtilities.ClassLoading.ClassDiscoveryCache) Set(java.util.Set) HashSet(java.util.HashSet) HeadlessException(java.awt.HeadlessException) FunctionBase(com.laytonsmith.core.functions.FunctionBase) DocGen(com.laytonsmith.tools.docgen.DocGen) ExtensionDocGen(com.laytonsmith.tools.docgen.ExtensionDocGen) ArgumentParser(com.laytonsmith.PureUtilities.ArgumentParser) URI(java.net.URI) ConfigCompileException(com.laytonsmith.core.exceptions.ConfigCompileException) CString(com.laytonsmith.core.constructs.CString) Interpreter(com.laytonsmith.tools.Interpreter) ConsoleReader(jline.console.ConsoleReader) DaemonManager(com.laytonsmith.PureUtilities.DaemonManager) RSAEncrypt(com.laytonsmith.PureUtilities.Common.RSAEncrypt) IOException(java.io.IOException) ConfigCompileGroupException(com.laytonsmith.core.exceptions.ConfigCompileGroupException)

Aggregations

CString (com.laytonsmith.core.constructs.CString)34 CArray (com.laytonsmith.core.constructs.CArray)23 Construct (com.laytonsmith.core.constructs.Construct)19 CInt (com.laytonsmith.core.constructs.CInt)12 HashMap (java.util.HashMap)10 IVariable (com.laytonsmith.core.constructs.IVariable)9 ConfigRuntimeException (com.laytonsmith.core.exceptions.ConfigRuntimeException)9 Map (java.util.Map)8 CDouble (com.laytonsmith.core.constructs.CDouble)7 CNull (com.laytonsmith.core.constructs.CNull)7 Variable (com.laytonsmith.core.constructs.Variable)6 CBoolean (com.laytonsmith.core.constructs.CBoolean)5 CFunction (com.laytonsmith.core.constructs.CFunction)5 Target (com.laytonsmith.core.constructs.Target)5 CREFormatException (com.laytonsmith.core.exceptions.CRE.CREFormatException)5 ConfigCompileException (com.laytonsmith.core.exceptions.ConfigCompileException)5 FunctionReturnException (com.laytonsmith.core.exceptions.FunctionReturnException)5 ArrayList (java.util.ArrayList)5 MCItemStack (com.laytonsmith.abstraction.MCItemStack)4 ParseTree (com.laytonsmith.core.ParseTree)4