package net.morilib.sh;

import java.io.IOException;
import java.io.PushbackReader;
import java.io.StringReader;

import junit.framework.TestCase;

public class ShParserCommandTest extends TestCase {

	public static PushbackReader grd(String s) {
		return new PushbackReader(new StringReader(s));
	}

	public void eqs(String t, String s) {
		try {
			ShLexer r = new ShLexer(grd(t));

			assertEquals(s, ShParser.parseCommand(r, r.nextToken()).toString());
		} catch (IOException e) {
			throw new RuntimeException(e);
		} catch (ShSyntaxException e) {
			throw new RuntimeException(e);
		}
	}

	public void err(String t) {
		try {
			ShLexer r = new ShLexer(grd(t));

			ShParser.parseCommand(r, r.nextToken());
			fail();
		} catch (IOException e) {
			throw new RuntimeException(e);
		} catch (ShSyntaxException e) {
			// OK
		}
	}

	public void testS001() {
		eqs("echo   aaa", "echo aaa");
	}

	public void testS002() {
		eqs("echo aaa  |  cat -n", "echo aaa | cat -n");
		eqs("echo aaa  |  cat -n | wc", "echo aaa | cat -n | wc");
	}

	public void testS003() {
		eqs("echo aaa  |  cat -n >1", "echo aaa | cat -n 1> 1");
		eqs("echo aaa  >1 |  cat -n", "echo aaa 1> 1 | cat -n");
		eqs("echo >1  aaa |  cat -n", "echo aaa 1> 1 | cat -n");
	}

	public void testS004() {
		eqs("echo aaa  |  cat -n && echo bbb", "echo aaa | cat -n && echo bbb");
		eqs("echo aaa && echo bbb  |  cat -n", "echo aaa && echo bbb | cat -n");
	}

	public void testS005() {
		eqs("echo aaa  |  cat -n || echo bbb", "echo aaa | cat -n || echo bbb");
		eqs("echo aaa || echo bbb  |  cat -n", "echo aaa || echo bbb | cat -n");
	}

	public void testS006() {
		eqs("echo aaa &&  cat -n || echo bbb", "echo aaa && cat -n || echo bbb");
		eqs("echo aaa || echo bbb  &&  cat -n", "echo aaa || echo bbb && cat -n");
	}

	public void testS007() {
		eqs("! echo   aaa", "! echo aaa");
		eqs("! echo   aaa || echo bbb", "! echo aaa || echo bbb");
		eqs("echo   aaa || ! echo bbb", "echo aaa || ! echo bbb");
	}

	public void testS008() {
		eqs("echo aaa  2>&1 2>> aaa", "echo aaa 2>&1 2>> aaa");
		eqs("echo aaa  2>> aaa 2>&1", "echo aaa 2>> aaa 2>&1");
	}

	public void testS009() {
		eqs("[ aaa ] && [ bbb ]", "test aaa && test bbb");
		eqs("[ aaa ] || [ bbb ]", "test aaa || test bbb");
		eqs("! [ aaa ]", "! test aaa");
	}

}
