#!/usr/bin/env python
# Copyright (c) 2021 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Creates a dummy RTS filter file if a real one doesn't exist yes.
  Real filter files are  generated by the RTS binary for suites with any
  skippable tests. The rest of the suites need to have dummy files because gn
  will expect the file to be present.

  Implementation uses try / except because the filter files are written
  relatively close to when this code creates the dummy files.

  The following type of implementation would have a race condition:
  if not os.path.isfile(filter_file):
    open(filter_file, 'w') as fp:
      fp.write('*')
"""
import errno
import os
import sys


def main():
  filter_file = sys.argv[1]
  directory = os.path.dirname(filter_file)
  try:
    os.makedirs(directory)
  except OSError as err:
    if err.errno == errno.EEXIST:
      pass
    else:
      raise

  try:
    fp = os.open(filter_file, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
  except OSError as err:
    if err.errno == errno.EEXIST:
      pass
    else:
      raise
  else:
    with os.fdopen(fp, 'w') as file_obj:
      file_obj.write('*')  # '*' is a dummy that means run everything


if __name__ == '__main__':
  sys.exit(main())
