<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def detect_worktree(cls, binary='git', subdir=None):
 """Detect the git working tree above cwd and return it; else, return None. :param string binary: The path to the git binary to use, 'git' by default. :param string subdir: The path to start searching for a git repo. :returns: path to the directory where the git working tree is rooted. :rtype: string """

    # TODO(John Sirois): This is only used as a factory for a Git instance in
    # pants.base.build_environment.get_scm, encapsulate in a true factory method.
    cmd = [binary, 'rev-parse', '--show-toplevel']
    try:
      if subdir:
        with pushd(subdir):
          process, out = cls._invoke(cmd)
      else:
        process, out = cls._invoke(cmd)
      cls._check_result(cmd, process.returncode, raise_type=Scm.ScmException)
    except Scm.ScmException:
      return None
    return cls._cleanse(out)