import pathlib


def ExpandFileUrl(url: str):
  """Expand URLs which begin with 'file://' by reading the file contents.

  If the URL does not begin with `file://`, it is returned unmodified.

  Args:
    url: The URL to expand, e.g. `file://path/to/file.txt?arg'

  Returns:
    The URL as interpreted by reading any URL file.

  Raises:
    ValueError: If the file path is invalid.
    FileNotFoundError: IF the file path does not exist.
  """
  if not url.startswith('file://'):
    return url

  # Split the URL into the file path, and the optional suffix.
  components = url.split('?')
  path, suffix = components[0], '?'.join(components[1:])

  # Strip the file:// prefix from the path.
  path = pathlib.Path(path[len('file://'):])

  if not path.is_absolute():
    raise ValueError('Relative path to file:// is not allowed')

  if not path.is_file():
    raise FileNotFoundError(f"File '{path}' not found")

  # Read the contents of the file, ignoring lines starting with '#'.
  with open(path) as f:
    file_url = '\n'.join(x for x in f.read().split('\n')
                         if not x.lstrip().startswith('#')).strip()

  # Append the suffix.
  file_url += suffix

  return file_url