Refactor and make code more robust for git operations