001/*
002 * Copyright (c) 2012-2017 Institut National des Sciences Appliquées de Lyon (INSA-Lyon)
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 */
009
010package org.eclipse.golo.cli.command.spi;
011
012import org.eclipse.golo.compiler.GoloCompilationException;
013import gololang.Messages;
014
015import java.lang.invoke.MethodHandle;
016
017import static java.lang.invoke.MethodHandles.publicLookup;
018import static java.lang.invoke.MethodType.methodType;
019
020
021public interface CliCommand {
022
023  class NoMainMethodException extends NoSuchMethodException {
024  }
025
026  // NOT DOCUMENTED
027  boolean DEBUG = Boolean.valueOf(System.getProperty("golo.debug", "false"));
028  boolean SHOW_TRACE = Boolean.valueOf(System.getProperty("golo.debug.trace", "true"));
029
030  void execute() throws Throwable;
031
032  default void callRun(Class<?> klass, String[] arguments) throws Throwable {
033    MethodHandle main;
034    try {
035      main = publicLookup().findStatic(klass, "main", methodType(void.class, String[].class));
036    } catch (NoSuchMethodException e) {
037      throw new NoMainMethodException().initCause(e);
038    }
039    main.invoke(arguments);
040  }
041
042  default void handleCompilationException(GoloCompilationException e) {
043    handleCompilationException(e, true);
044  }
045
046  default void handleCompilationException(GoloCompilationException e, boolean exit) {
047    handleThrowable(e, false);
048    for (GoloCompilationException.Problem problem : e.getProblems()) {
049      Messages.error(problem.getDescription());
050    }
051    if (exit) {
052      System.exit(1);
053    }
054  }
055
056  default void handleThrowable(Throwable e) {
057    handleThrowable(e, true);
058  }
059
060  default void handleThrowable(Throwable e, boolean exit) {
061    handleThrowable(e, exit,  DEBUG || SHOW_TRACE);
062  }
063
064  default void handleThrowable(Throwable e, boolean exit, boolean withStack) {
065    Messages.error(e);
066    if (e.getCause() != null) {
067      Messages.error(e.getCause().getMessage());
068    }
069    if (withStack) {
070      Messages.printStackTrace(e);
071    }
072    if (exit) {
073      System.exit(1);
074    }
075  }
076}