#!/usr/bin/env python2
# Copyright 2020 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.

import os
import subprocess
import sys

args = sys.argv[1:]
inputfiles = [a for a in args if not a.startswith('-')]

contents = ''
if '-' in args or not inputfiles:
    contents = sys.stdin.read()

# Tarball builds may or may not have depot_tools in $PATH. In the former case,
# running 'clang-format' will call back into this script infinitely. Strip off
# directories from $PATH one-by-one until either the system clang-format is
# used or there's no usable clang-format.
env = os.environ.copy()
if 'TARBALL_CLANG_FORMAT_WRAPPER' in env:
    env['PATH'] = os.pathsep.join(env['PATH'].split(os.pathsep)[1:])
env['TARBALL_CLANG_FORMAT_WRAPPER'] = ''

# Try formatting with the system clang-format.
try:
    proc = subprocess.Popen(
        ['clang-format'] + args,
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        env=env)
    stdout, stderr = proc.communicate(input=contents)
    # Ignore if clang-format fails. Eg: it may be too old to support C++14.
    if proc.returncode == 0:
        sys.stdout.write(stdout)
        sys.stderr.write(stderr)
        sys.exit(0)
except OSError:
    # Ignore if clang-format is not installed.
    pass

# If any failure happens, continue with unformatted files.
sys.stdout.write(contents)
for inputfile in inputfiles:
    sys.stdout.write(open(inputfile).read())
