MagicDefineGlobal implements SpecialCommand { @Override public StellarResult execute(String command, StellarShellExecutor executor) { String assignExpr = StringUtils.trimToEmpty(command.substring(MAGIC_DEFINE.length())); if(StringUtils.length(assignExpr) < 1) { return error(MAGIC_DEFINE + " missing assignment expression"); } if(!StellarAssignment.isAssignment(assignExpr)) { return error(MAGIC_DEFINE + " expected assignment expression"); } StellarAssignment expr = StellarAssignment.from(assignExpr); StellarResult result = executor.execute(expr.getStatement()); if(!result.isSuccess()) { return error(MAGIC_DEFINE + " expression execution failed"); } if(!result.getValue().isPresent()) { return error(MAGIC_DEFINE + " expression produced no result"); } Object value = result.getValue().get(); executor.getGlobalConfig().put(expr.getVariable(), value); return success(value); }  @Override String getCommand(); @Override Function<String, Boolean> getMatcher(); @Override StellarResult execute(String command, StellarShellExecutor executor); static final String MAGIC_DEFINE; }
@Test public void testDefine() { final int expected = 4; { StellarResult result = magic.execute("%define global := 2 + 2", executor); assertTrue(result.isSuccess()); assertTrue(result.getValue().isPresent()); assertEquals(expected, result.getValue().get()); assertTrue(executor.getGlobalConfig().containsKey("global")); assertEquals(expected, executor.getGlobalConfig().get("global")); } { StellarResult result = executor.execute("%globals"); assertTrue(result.isSuccess()); assertTrue(result.getValue().isPresent()); String out = ConversionUtils.convert(result.getValue().get(), String.class); assertEquals("{global=4}", out); } }
@Test public void testNotAssignmentExpression() { StellarResult result = magic.execute("%define 2 + 2", executor); assertTrue(result.isError()); assertFalse(result.getValue().isPresent()); assertTrue(result.getException().isPresent()); assertEquals(0, executor.getGlobalConfig().size()); }
@Test public void testMissingExpression() { StellarResult result = magic.execute("%define", executor); assertTrue(result.isError()); assertFalse(result.getValue().isPresent()); assertTrue(result.getException().isPresent()); assertEquals(0, executor.getGlobalConfig().size()); }