Skip to content

Commit 587743e

Browse files
NicolasHugfacebook-github-bot
authored andcommitted
Import torchaudio #1233 135e966
Reviewed By: mthrok Differential Revision: D26228762 fbshipit-source-id: 9acc587adb5e7ca7867d8a5df44ba73166099fd9
1 parent d580296 commit 587743e

File tree

16 files changed

+537
-282
lines changed

16 files changed

+537
-282
lines changed
Lines changed: 340 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,340 @@
1+
#!/usr/bin/env python
2+
"""A wrapper script around clang-format, suitable for linting multiple files
3+
and to use for continuous integration.
4+
5+
This is an alternative API for the clang-format command line.
6+
It runs over multiple files and directories in parallel.
7+
A diff output is produced and a sensible exit code is returned.
8+
9+
"""
10+
11+
import argparse
12+
import codecs
13+
import difflib
14+
import fnmatch
15+
import io
16+
import multiprocessing
17+
import os
18+
import signal
19+
import subprocess
20+
import sys
21+
import traceback
22+
23+
from functools import partial
24+
25+
try:
26+
from subprocess import DEVNULL # py3k
27+
except ImportError:
28+
DEVNULL = open(os.devnull, "wb")
29+
30+
31+
DEFAULT_EXTENSIONS = 'c,h,C,H,cpp,hpp,cc,hh,c++,h++,cxx,hxx,cu'
32+
33+
34+
class ExitStatus:
35+
SUCCESS = 0
36+
DIFF = 1
37+
TROUBLE = 2
38+
39+
40+
def list_files(files, recursive=False, extensions=None, exclude=None):
41+
if extensions is None:
42+
extensions = []
43+
if exclude is None:
44+
exclude = []
45+
46+
out = []
47+
for file in files:
48+
if recursive and os.path.isdir(file):
49+
for dirpath, dnames, fnames in os.walk(file):
50+
fpaths = [os.path.join(dirpath, fname) for fname in fnames]
51+
for pattern in exclude:
52+
# os.walk() supports trimming down the dnames list
53+
# by modifying it in-place,
54+
# to avoid unnecessary directory listings.
55+
dnames[:] = [
56+
x for x in dnames
57+
if
58+
not fnmatch.fnmatch(os.path.join(dirpath, x), pattern)
59+
]
60+
fpaths = [
61+
x for x in fpaths if not fnmatch.fnmatch(x, pattern)
62+
]
63+
for f in fpaths:
64+
ext = os.path.splitext(f)[1][1:]
65+
if ext in extensions:
66+
out.append(f)
67+
else:
68+
out.append(file)
69+
return out
70+
71+
72+
def make_diff(file, original, reformatted):
73+
return list(
74+
difflib.unified_diff(
75+
original,
76+
reformatted,
77+
fromfile='{}\t(original)'.format(file),
78+
tofile='{}\t(reformatted)'.format(file),
79+
n=3))
80+
81+
82+
class DiffError(Exception):
83+
def __init__(self, message, errs=None):
84+
super(DiffError, self).__init__(message)
85+
self.errs = errs or []
86+
87+
88+
class UnexpectedError(Exception):
89+
def __init__(self, message, exc=None):
90+
super(UnexpectedError, self).__init__(message)
91+
self.formatted_traceback = traceback.format_exc()
92+
self.exc = exc
93+
94+
95+
def run_clang_format_diff_wrapper(args, file):
96+
try:
97+
ret = run_clang_format_diff(args, file)
98+
return ret
99+
except DiffError:
100+
raise
101+
except Exception as e:
102+
raise UnexpectedError('{}: {}: {}'.format(file, e.__class__.__name__,
103+
e), e)
104+
105+
106+
def run_clang_format_diff(args, file):
107+
try:
108+
with io.open(file, 'r', encoding='utf-8') as f:
109+
original = f.readlines()
110+
except IOError as exc:
111+
raise DiffError(str(exc))
112+
invocation = [args.clang_format_executable, file]
113+
114+
# Use of utf-8 to decode the process output.
115+
#
116+
# Hopefully, this is the correct thing to do.
117+
#
118+
# It's done due to the following assumptions (which may be incorrect):
119+
# - clang-format will returns the bytes read from the files as-is,
120+
# without conversion, and it is already assumed that the files use utf-8.
121+
# - if the diagnostics were internationalized, they would use utf-8:
122+
# > Adding Translations to Clang
123+
# >
124+
# > Not possible yet!
125+
# > Diagnostic strings should be written in UTF-8,
126+
# > the client can translate to the relevant code page if needed.
127+
# > Each translation completely replaces the format string
128+
# > for the diagnostic.
129+
# > -- http://clang.llvm.org/docs/InternalsManual.html#internals-diag-translation
130+
131+
try:
132+
proc = subprocess.Popen(
133+
invocation,
134+
stdout=subprocess.PIPE,
135+
stderr=subprocess.PIPE,
136+
universal_newlines=True,
137+
encoding='utf-8')
138+
except OSError as exc:
139+
raise DiffError(
140+
"Command '{}' failed to start: {}".format(
141+
subprocess.list2cmdline(invocation), exc
142+
)
143+
)
144+
proc_stdout = proc.stdout
145+
proc_stderr = proc.stderr
146+
147+
# hopefully the stderr pipe won't get full and block the process
148+
outs = list(proc_stdout.readlines())
149+
errs = list(proc_stderr.readlines())
150+
proc.wait()
151+
if proc.returncode:
152+
raise DiffError(
153+
"Command '{}' returned non-zero exit status {}".format(
154+
subprocess.list2cmdline(invocation), proc.returncode
155+
),
156+
errs,
157+
)
158+
return make_diff(file, original, outs), errs
159+
160+
161+
def bold_red(s):
162+
return '\x1b[1m\x1b[31m' + s + '\x1b[0m'
163+
164+
165+
def colorize(diff_lines):
166+
def bold(s):
167+
return '\x1b[1m' + s + '\x1b[0m'
168+
169+
def cyan(s):
170+
return '\x1b[36m' + s + '\x1b[0m'
171+
172+
def green(s):
173+
return '\x1b[32m' + s + '\x1b[0m'
174+
175+
def red(s):
176+
return '\x1b[31m' + s + '\x1b[0m'
177+
178+
for line in diff_lines:
179+
if line[:4] in ['--- ', '+++ ']:
180+
yield bold(line)
181+
elif line.startswith('@@ '):
182+
yield cyan(line)
183+
elif line.startswith('+'):
184+
yield green(line)
185+
elif line.startswith('-'):
186+
yield red(line)
187+
else:
188+
yield line
189+
190+
191+
def print_diff(diff_lines, use_color):
192+
if use_color:
193+
diff_lines = colorize(diff_lines)
194+
sys.stdout.writelines(diff_lines)
195+
196+
197+
def print_trouble(prog, message, use_colors):
198+
error_text = 'error:'
199+
if use_colors:
200+
error_text = bold_red(error_text)
201+
print("{}: {} {}".format(prog, error_text, message), file=sys.stderr)
202+
203+
204+
def main():
205+
parser = argparse.ArgumentParser(description=__doc__)
206+
parser.add_argument(
207+
'--clang-format-executable',
208+
metavar='EXECUTABLE',
209+
help='path to the clang-format executable',
210+
default='clang-format')
211+
parser.add_argument(
212+
'--extensions',
213+
help='comma separated list of file extensions (default: {})'.format(
214+
DEFAULT_EXTENSIONS),
215+
default=DEFAULT_EXTENSIONS)
216+
parser.add_argument(
217+
'-r',
218+
'--recursive',
219+
action='store_true',
220+
help='run recursively over directories')
221+
parser.add_argument('files', metavar='file', nargs='+')
222+
parser.add_argument(
223+
'-q',
224+
'--quiet',
225+
action='store_true')
226+
parser.add_argument(
227+
'-j',
228+
metavar='N',
229+
type=int,
230+
default=0,
231+
help='run N clang-format jobs in parallel'
232+
' (default number of cpus + 1)')
233+
parser.add_argument(
234+
'--color',
235+
default='auto',
236+
choices=['auto', 'always', 'never'],
237+
help='show colored diff (default: auto)')
238+
parser.add_argument(
239+
'-e',
240+
'--exclude',
241+
metavar='PATTERN',
242+
action='append',
243+
default=[],
244+
help='exclude paths matching the given glob-like pattern(s)'
245+
' from recursive search')
246+
247+
args = parser.parse_args()
248+
249+
# use default signal handling, like diff return SIGINT value on ^C
250+
# https://bugs.python.org/issue14229#msg156446
251+
signal.signal(signal.SIGINT, signal.SIG_DFL)
252+
try:
253+
signal.SIGPIPE
254+
except AttributeError:
255+
# compatibility, SIGPIPE does not exist on Windows
256+
pass
257+
else:
258+
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
259+
260+
colored_stdout = False
261+
colored_stderr = False
262+
if args.color == 'always':
263+
colored_stdout = True
264+
colored_stderr = True
265+
elif args.color == 'auto':
266+
colored_stdout = sys.stdout.isatty()
267+
colored_stderr = sys.stderr.isatty()
268+
269+
version_invocation = [args.clang_format_executable, str("--version")]
270+
try:
271+
subprocess.check_call(version_invocation, stdout=DEVNULL)
272+
except subprocess.CalledProcessError as e:
273+
print_trouble(parser.prog, str(e), use_colors=colored_stderr)
274+
return ExitStatus.TROUBLE
275+
except OSError as e:
276+
print_trouble(
277+
parser.prog,
278+
"Command '{}' failed to start: {}".format(
279+
subprocess.list2cmdline(version_invocation), e
280+
),
281+
use_colors=colored_stderr,
282+
)
283+
return ExitStatus.TROUBLE
284+
285+
retcode = ExitStatus.SUCCESS
286+
files = list_files(
287+
args.files,
288+
recursive=args.recursive,
289+
exclude=args.exclude,
290+
extensions=args.extensions.split(','))
291+
292+
if not files:
293+
return
294+
295+
njobs = args.j
296+
if njobs == 0:
297+
njobs = multiprocessing.cpu_count() + 1
298+
njobs = min(len(files), njobs)
299+
300+
if njobs == 1:
301+
# execute directly instead of in a pool,
302+
# less overhead, simpler stacktraces
303+
it = (run_clang_format_diff_wrapper(args, file) for file in files)
304+
pool = None
305+
else:
306+
pool = multiprocessing.Pool(njobs)
307+
it = pool.imap_unordered(
308+
partial(run_clang_format_diff_wrapper, args), files)
309+
while True:
310+
try:
311+
outs, errs = next(it)
312+
except StopIteration:
313+
break
314+
except DiffError as e:
315+
print_trouble(parser.prog, str(e), use_colors=colored_stderr)
316+
retcode = ExitStatus.TROUBLE
317+
sys.stderr.writelines(e.errs)
318+
except UnexpectedError as e:
319+
print_trouble(parser.prog, str(e), use_colors=colored_stderr)
320+
sys.stderr.write(e.formatted_traceback)
321+
retcode = ExitStatus.TROUBLE
322+
# stop at the first unexpected error,
323+
# something could be very wrong,
324+
# don't process all files unnecessarily
325+
if pool:
326+
pool.terminate()
327+
break
328+
else:
329+
sys.stderr.writelines(errs)
330+
if outs == []:
331+
continue
332+
if not args.quiet:
333+
print_diff(outs, use_color=colored_stdout)
334+
if retcode == ExitStatus.SUCCESS:
335+
retcode = ExitStatus.DIFF
336+
return retcode
337+
338+
339+
if __name__ == '__main__':
340+
sys.exit(main())

.circleci/unittest/linux/scripts/run_style_checks.sh

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ if [ "${status}" -ne 0 ]; then
3737
fi
3838

3939
printf "\x1b[34mRunning clang-format:\x1b[0m\n"
40-
"${this_dir}"/run-clang-format.py \
40+
"${this_dir}"/run_clang_format.py \
4141
-r torchaudio/csrc \
4242
--clang-format-executable "${clangformat_path}" \
4343
&& git diff --exit-code

.circleci/unittest/linux/scripts/run_test.sh

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,15 @@ set -e
55
eval "$(./conda/bin/conda shell.bash hook)"
66
conda activate ./env
77

8+
case "$(uname -s)" in
9+
Darwin*) os=MacOSX;;
10+
*) os=Linux
11+
esac
12+
813
python -m torch.utils.collect_env
14+
if [ "${os}" == Linux ]; then
15+
cat /proc/cpuinfo
16+
fi
917
export TORCHAUDIO_TEST_FAIL_IF_NO_EXTENSION=1
1018
export PATH="${PWD}/third_party/install/bin/:${PATH}"
1119

torchaudio/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,11 @@
33
from torchaudio import (
44
compliance,
55
datasets,
6+
functional,
67
kaldi_io,
78
utils,
89
sox_effects,
9-
transforms
10+
transforms,
1011
)
1112

1213
USE_SOUNDFILE_LEGACY_INTERFACE = None

0 commit comments

Comments
 (0)