<commit_before>/*
 * Copyright (C) 2009 the original author(s).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.sonatype.gshell.shell;

import jline.console.Completer;
import jline.console.ConsoleReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonatype.gshell.branding.Branding;
import org.sonatype.gshell.command.IO;
import org.sonatype.gshell.console.Console;
import org.sonatype.gshell.console.ConsoleErrorHandler;
import org.sonatype.gshell.console.ConsolePrompt;
import org.sonatype.gshell.console.ConsoleTask;
import org.sonatype.gshell.event.EventAware;
import org.sonatype.gshell.event.EventManager;
import org.sonatype.gshell.execute.CommandExecutor;
import org.sonatype.gshell.io.Closer;
import org.sonatype.gshell.io.StreamJack;
import org.sonatype.gshell.notification.ExitNotification;
import org.sonatype.gshell.util.Arguments;
import org.sonatype.gshell.vars.VariableNames;
import org.sonatype.gshell.vars.Variables;
import org.sonatype.gshell.vars.VariablesImpl;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicReference;

/**
 * The default {@link Shell} component.
 *
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 * @since 2.0
 */
public class ShellImpl
    implements Shell, VariableNames
{
    private final Logger log = LoggerFactory.getLogger(getClass());

    private final Branding branding;

    private final CommandExecutor executor;

    private IO io;

    private final Variables variables;

    private final ShellHistory history;

    private List<Completer> completers;

    private ConsolePrompt prompt;

    private ConsoleErrorHandler errorHandler;

    private boolean opened;

    //
    // TODO: Maybe these should be set in variables?  More supportable than adding new methods for little features like this.
    //

    private boolean loadProfileScripts = true;

    private boolean loadInteractiveScripts = true;


    public ShellImpl(final EventManager eventManager, final CommandExecutor executor, final Branding branding,
                     final IO io, final Variables variables) throws IOException
    {
        assert eventManager != null;
        assert executor != null;
        assert branding != null;
        // io and variables may be null

        this.executor = executor;
        this.branding = branding;
        this.io = io != null ? io : new IO();
        this.variables = variables != null ? variables : new VariablesImpl();
        if (variables instanceof EventAware) {
            ((EventAware) variables).setEventManager(eventManager);
        }
        this.history = new ShellHistory(new File(branding.getUserContextDir(), branding.getHistoryFileName()));
    }

    public Branding getBranding() {
        return branding;
    }

    public IO getIo() {
        return io;
    }

    public Variables getVariables() {
        return variables;
    }

    public History getHistory() {
        return history;
    }

    public void setPrompt(final ConsolePrompt prompt) {
        this.prompt = prompt;
    }

    public void setErrorHandler(final ConsoleErrorHandler errorHandler) {
        this.errorHandler = errorHandler;
    }

    public void setCompleters(final List<Completer> completers) {
        this.completers = completers;
    }

    public void setCompleters(final Completer... completers) {
        assert completers != null;
        setCompleters(Arrays.asList(completers));
    }

    public boolean isLoadProfileScripts() {
        return loadProfileScripts;
    }

    public void setLoadProfileScripts(boolean enable) {
        this.loadProfileScripts = enable;
    }

    public boolean isLoadInteractiveScripts() {
        return loadInteractiveScripts;
    }

    public void setLoadInteractiveScripts(boolean enable) {
        this.loadInteractiveScripts = enable;
    }

    public synchronized boolean isOpened() {
        return opened;
    }

    public synchronized void close() {
        opened = false;
    }

    private synchronized void ensureOpened() {
        if (!opened) {
            try {
                open();
            }
            catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    private synchronized void open() throws Exception {
        log.debug("Opening");

        StreamJack.maybeInstall();

        // Customize the shell
        branding.customize(this);

        // Load profile scripts
        loadProfileScripts();

        opened = true;

        log.debug("Opened");
    }

    public boolean isInteractive() {
        return true;
    }

    // FIXME: History should still be appended if not running inside of a JLineConsole

    public Object execute(final String line) throws Exception {
        ensureOpened();
        return executor.execute(this, line);
    }

    public Object execute(final String command, final Object[] args) throws Exception {
        ensureOpened();
        return executor.execute(this, command, args);
    }

    public Object execute(final Object... args) throws Exception {
        ensureOpened();
        return executor.execute(this, args);
    }

    public void run(final Object... args) throws Exception {
        assert args != null;
        ensureOpened();

        log.debug("Starting interactive console; args: {}", Arguments.toStringArray(args));<commit_msg>Load profile scripts after we are marked as opened, else we get nasty stack overflows<commit_after>/*
 * Copyright (C) 2009 the original author(s).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.sonatype.gshell.shell;

import jline.console.Completer;
import jline.console.ConsoleReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonatype.gshell.branding.Branding;
import org.sonatype.gshell.command.IO;
import org.sonatype.gshell.console.Console;
import org.sonatype.gshell.console.ConsoleErrorHandler;
import org.sonatype.gshell.console.ConsolePrompt;
import org.sonatype.gshell.console.ConsoleTask;
import org.sonatype.gshell.event.EventAware;
import org.sonatype.gshell.event.EventManager;
import org.sonatype.gshell.execute.CommandExecutor;
import org.sonatype.gshell.io.Closer;
import org.sonatype.gshell.io.StreamJack;
import org.sonatype.gshell.notification.ExitNotification;
import org.sonatype.gshell.util.Arguments;
import org.sonatype.gshell.vars.VariableNames;
import org.sonatype.gshell.vars.Variables;
import org.sonatype.gshell.vars.VariablesImpl;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicReference;

/**
 * The default {@link Shell} component.
 *
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 * @since 2.0
 */
public class ShellImpl
    implements Shell, VariableNames
{
    private final Logger log = LoggerFactory.getLogger(getClass());

    private final Branding branding;

    private final CommandExecutor executor;

    private IO io;

    private final Variables variables;

    private final ShellHistory history;

    private List<Completer> completers;

    private ConsolePrompt prompt;

    private ConsoleErrorHandler errorHandler;

    private boolean opened;

    //
    // TODO: Maybe these should be set in variables?  More supportable than adding new methods for little features like this.
    //

    private boolean loadProfileScripts = true;

    private boolean loadInteractiveScripts = true;


    public ShellImpl(final EventManager eventManager, final CommandExecutor executor, final Branding branding,
                     final IO io, final Variables variables) throws IOException
    {
        assert eventManager != null;
        assert executor != null;
        assert branding != null;
        // io and variables may be null

        this.executor = executor;
        this.branding = branding;
        this.io = io != null ? io : new IO();
        this.variables = variables != null ? variables : new VariablesImpl();
        if (variables instanceof EventAware) {
            ((EventAware) variables).setEventManager(eventManager);
        }
        this.history = new ShellHistory(new File(branding.getUserContextDir(), branding.getHistoryFileName()));
    }

    public Branding getBranding() {
        return branding;
    }

    public IO getIo() {
        return io;
    }

    public Variables getVariables() {
        return variables;
    }

    public History getHistory() {
        return history;
    }

    public void setPrompt(final ConsolePrompt prompt) {
        this.prompt = prompt;
    }

    public void setErrorHandler(final ConsoleErrorHandler errorHandler) {
        this.errorHandler = errorHandler;
    }

    public void setCompleters(final List<Completer> completers) {
        this.completers = completers;
    }

    public void setCompleters(final Completer... completers) {
        assert completers != null;
        setCompleters(Arrays.asList(completers));
    }

    public boolean isLoadProfileScripts() {
        return loadProfileScripts;
    }

    public void setLoadProfileScripts(boolean enable) {
        this.loadProfileScripts = enable;
    }

    public boolean isLoadInteractiveScripts() {
        return loadInteractiveScripts;
    }

    public void setLoadInteractiveScripts(boolean enable) {
        this.loadInteractiveScripts = enable;
    }

    public synchronized boolean isOpened() {
        return opened;
    }

    public synchronized void close() {
        opened = false;
    }

    private synchronized void ensureOpened() {
        if (!opened) {
            try {
                open();
            }
            catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    private synchronized void open() throws Exception {
        log.debug("Opening");

        StreamJack.maybeInstall();

        // Customize the shell
        branding.customize(this);

        opened = true;
        log.debug("Opened");

        // Do this after we are marked as opened
        loadProfileScripts();
    }

    public boolean isInteractive() {
        return true;
    }

    // FIXME: History should still be appended if not running inside of a JLineConsole

    public Object execute(final String line) throws Exception {
        ensureOpened();
        return executor.execute(this, line);
    }

    public Object execute(final String command, final Object[] args) throws Exception {
        ensureOpened();
        return executor.execute(this, command, args);
    }

    public Object execute(final Object... args) throws Exception {
        ensureOpened();
        return executor.execute(this, args);
    }

    public void run(final Object... args) throws Exception {
        assert args != null;
        ensureOpened();

        log.debug("Starting interactive console; args: {}", Arguments.toStringArray(args));
{'fraction_non_alphanumeric': 0.08712919435889123, 'fraction_numerical': 0.0019452099205705948, 'mean_word_length': 2.979039019671074, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2404458', 'n_tokens_mistral': 3370, 'n_tokens_neox': 3239, 'n_words': 970}