package de.retest.recheck.persistence;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class GitExecutor {

	protected static final String GIT_COMMAND_VERSION = "git --version";
	protected static final String GIT_COMMAND_BRANCH_NAME = "git rev-parse --abbrev-ref HEAD";
	protected static final String GIT_COMMAND_COMMIT_HASH = "git rev-parse HEAD";

	private final boolean localGit;

	public GitExecutor() {
		localGit = isGitInstalled();
	}

	protected boolean isGitInstalled() {
		try {
			final String result = executeGitCommand( GIT_COMMAND_VERSION );
			return result != null && result.contains( "git version" );
		} catch ( final Exception e ) {
			log.debug( "`{}` resulted in exception {}, assuming no git installed.", GIT_COMMAND_VERSION,
					e.getMessage() );
			return false;
		}
	}

	protected String executeGitCommand( final String command ) throws IOException, InterruptedException {
		final Process process = Runtime.getRuntime().exec( command );
		try {
			process.waitFor();

			final BufferedReader reader = new BufferedReader( new InputStreamReader( process.getInputStream() ) );

			return reader.readLine();
		} finally {
			process.getInputStream().close();
			process.destroy();
		}
	}

	public String getCurrentBranch() {
		if ( localGit ) {
			try {
				final String result = executeGitCommand( GIT_COMMAND_BRANCH_NAME );
				if ( result.contains( " " ) ) {
					return null;
				}
				return result;
			} catch ( final Exception e ) {
				log.error( "Exception retrieving Git branch.", e );
			}
		}
		return null;
	}

	public String getCurrentCommit() {
		if ( localGit ) {
			try {
				final String result = executeGitCommand( GIT_COMMAND_COMMIT_HASH );
				if ( result.contains( " " ) ) {
					return null;
				}
				return result;
			} catch ( final Exception e ) {
				log.error( "Exception retrieving Git branch.", e );
			}
		}
		return null;
	}
}

@@ -437,16 +437,82 @@
 e HEAD%22;
+%0A%09protected static final String GIT_COMMAND_STATUS = %22git status%22;
 %0A%0A%09priva
@@ -592,16 +592,31 @@
 talled()
+ && isGitUsed()
 ;%0A%09%7D%0A%0A%09p
@@ -918,16 +918,16 @@
 ERSION,%0A
-
 %09%09%09%09%09e.g
@@ -962,24 +962,377 @@
 se;%0A%09%09%7D%0A%09%7D%0A%0A
+%09protected boolean isGitUsed() %7B%0A%09%09try %7B%0A%09%09%09final String result = executeGitCommand( GIT_COMMAND_STATUS );%0A%09%09%09return result != null && !result.contains( %22fatal: not a git repository%22 );%0A%09%09%7D catch ( final Exception e ) %7B%0A%09%09%09log.debug( %22%60%7B%7D%60 resulted in exception %7B%7D, assuming no git used.%22, GIT_COMMAND_STATUS, e.getMessage() );%0A%09%09%09return false;%0A%09%09%7D%0A%09%7D%0A%0A
 %09protected S

Check if git is installed and used