def CleanIndent(text, prefix=''):
  """Remove extra indentation from comments or code.

  This allows code to be written as triple-quoted strings with natural
  indentation in the python file, and that indentation will be removed
  and replaced with the provided prefix.

  Args:
    text: Input code
    prefix: will be added to the start of each line.

  Returns:
    Code text with indentation regenerated.
  """
  if text:
    text = text.strip()
    lines = text.split('\n')

    def NumLeadingSpaces(line):
      num = 0
      for c in line:
        if c.isspace():
          num += 1
        else:
          break
      return num

    # Compute the indentation we will strip off.  Do it by looking at the
    # minimum indentation on non-empty lines after the first line.
    # (The first line will have already been stripped.)
    # This is assuming there is a uniform indentation on the left of the
    # comment that we should strip off, but there could be additional
    # indentation on some lines that we'd rather keep.
    non_empty_lines = [line for line in lines[1:] if line.strip()]
    if non_empty_lines:
      leading_spaces = min(NumLeadingSpaces(line) for line in non_empty_lines)
      strip_prefix = ' ' * leading_spaces
    else:
      strip_prefix = ''

    def Unindent(line):
      if line.startswith(strip_prefix):
        line = line[len(strip_prefix):]
      return line

    # Remove leading spaces from each line and add prefix.
    text = '\n'.join(prefix + Unindent(line.rstrip()) for line in lines)
  return text