import re


def _GetRcData(comment, rc_path, rc_data, pattern=None):
  """Generates the comment and `source rc_path` lines.

  Args:
    comment: The shell comment string that precedes the source line.
    rc_path: The path of the rc file to source.
    rc_data: The current comment and source rc lines or None.
    pattern: A regex pattern that matches comment, None for exact match on
      comment.

  Returns:
    The comment and `source rc_path` lines to be inserted into a shell rc file.
  """
  if not pattern:
    pattern = re.escape(comment)
  subre = re.compile('\n' + pattern + '\n.*\n', re.MULTILINE)
  # script checks that the rc_path currently exists before sourcing the file
  line = ('{comment}\nif [ -f {rc_path} ]; then\n'
          '  source \'{rc_path}\'\nfi\n').format(
              comment=comment, rc_path=rc_path)
  filtered_data = subre.sub('', rc_data)
  rc_data = '{filtered_data}\n{line}'.format(
      filtered_data=filtered_data, line=line)
  return rc_data