<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.io;

import jline.Terminal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;

/**
 * An input pipe which can be interrupted.
 *
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 * @since 2.0
 */
public class InputPipe
    extends Thread
    implements Closeable
{
    private static final Logger log = LoggerFactory.getLogger(InputPipe.class);

    private final BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(1024);

    private final Terminal term;

    private final StreamSet streams;

    public static interface InterruptHandler
    {
        boolean interrupt() throws Exception;

        boolean stop() throws Exception;
    }

    private final InterruptHandler interruptHandler;

    private final CountDownLatch startSignal = new CountDownLatch(1);

    private volatile boolean interrupt;

    private volatile boolean running;

    public InputPipe(final StreamSet streams, final Terminal terminal, final InterruptHandler interruptHandler) {
        assert streams != null;
        this.streams = streams;
        this.term = terminal;
        assert interruptHandler != null;
        this.interruptHandler = interruptHandler;
    }

    public void close() {
        if (running) {
            log.trace("Closing");
            Thread.currentThread().interrupt();
            running = false;
        }
    }
    
    private int read() throws IOException {
        return term.readCharacter(streams.in);
    }

    @Override
    public void start() {
        super.start();

        // Wait for the run-loop to actually start before we return, to avoid race-conditions
        try {
            startSignal.await();
        }
        catch (InterruptedException e) {
            // ignore
        }
    }

    public void run() {
        log.trace("Running");
        running = true;

        try {
            startSignal.countDown();
            
            while (running) {
                try {
                    int c = read();

                    switch (c) {
                        case -1:
                            queue.put(c);
                            return;

                        case 3:
                            interrupt = interruptHandler.interrupt();
                            break;

                        case 4:
                            running = interruptHandler.stop();
                            break;
                    }

                    queue.put(c);
                }
                catch (IOException e) {
                    log.warn("Pipe read error", e);

                    // HACK: Reset the terminal
                    term.restore();
                    term.init();
                }
            }
        }
        catch (Throwable t) {
            log.error("Pipe read failure", t);
            if (t instanceof RuntimeException) {
                throw (RuntimeException) t;
            }
            else if (t instanceof Error) {
                throw (Error) t;
            }
            else {
                throw new Error(t);
            }
        }
        finally {
            close();
        }
<commit_msg>(MVNSH-37) keep CTRL-D from freaking out the shell, still need a solution to this, but for now... no more infinite loop is good<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.io;

import jline.Terminal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;

/**
 * An input pipe which can be interrupted.
 *
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 * @since 2.0
 */
public class InputPipe
    extends Thread
    implements Closeable
{
    private static final Logger log = LoggerFactory.getLogger(InputPipe.class);

    private final BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(1024);

    private final Terminal term;

    private final StreamSet streams;

    public static interface InterruptHandler
    {
        boolean interrupt() throws Exception;

        boolean stop() throws Exception;
    }

    private final InterruptHandler interruptHandler;

    private final CountDownLatch startSignal = new CountDownLatch(1);

    private volatile boolean interrupt;

    private volatile boolean running;

    public InputPipe(final StreamSet streams, final Terminal terminal, final InterruptHandler interruptHandler) {
        assert streams != null;
        this.streams = streams;
        this.term = terminal;
        assert interruptHandler != null;
        this.interruptHandler = interruptHandler;
    }

    public void close() {
        if (running) {
            log.trace("Closing");
            Thread.currentThread().interrupt();
            running = false;
        }
    }
    
    private int read() throws IOException {
        return term.readCharacter(streams.in);
    }

    @Override
    public void start() {
        super.start();

        // Wait for the run-loop to actually start before we return, to avoid race-conditions
        try {
            startSignal.await();
        }
        catch (InterruptedException e) {
            // ignore
        }
    }

    public void run() {
        log.trace("Running");
        running = true;

        try {
            startSignal.countDown();
            
            while (running) {
                try {
                    int c = read();

                    switch (c) {
                        case -1:
                            queue.put(c);
                            return;

                        case 3: // CTRL-C
                            interrupt = interruptHandler.interrupt();
                            break;

//                        case 4: // CTRL-D
//                            running = interruptHandler.stop();
//                            break;
                    }

                    queue.put(c);
                }
                catch (IOException e) {
                    log.warn("Pipe read error", e);

                    // HACK: Reset the terminal
                    term.restore();
                    term.init();
                }
            }
        }
        catch (Throwable t) {
            log.error("Pipe read failure", t);
            if (t instanceof RuntimeException) {
                throw (RuntimeException) t;
            }
            else if (t instanceof Error) {
                throw (Error) t;
            }
            else {
                throw new Error(t);
            }
        }
        finally {
            close();
        }

{'fraction_non_alphanumeric': 0.08412466520574628, 'fraction_numerical': 0.005113221329437546, 'mean_word_length': 1.6828870019595037, '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': '676623', 'n_tokens_mistral': 2067, 'n_tokens_neox': 1966, 'n_words': 644}