|
| 1 | +# |
| 2 | +# PHASE: phase scalafmt |
| 3 | +# |
| 4 | +# Outputs to format the scala files when it is explicitly specified |
| 5 | +# |
| 6 | +def phase_scalafmt(ctx, p): |
| 7 | + if ctx.attr.format: |
| 8 | + manifest, files = _build_format(ctx) |
| 9 | + _formatter(ctx, manifest, files, ctx.file._runner, ctx.outputs.scalafmt_runner) |
| 10 | + _formatter(ctx, manifest, files, ctx.file._testrunner, ctx.outputs.scalafmt_testrunner) |
| 11 | + else: |
| 12 | + _write_empty_content(ctx, ctx.outputs.scalafmt_runner) |
| 13 | + _write_empty_content(ctx, ctx.outputs.scalafmt_testrunner) |
| 14 | + |
| 15 | +def _build_format(ctx): |
| 16 | + files = [] |
| 17 | + manifest_content = [] |
| 18 | + for src in ctx.files.srcs: |
| 19 | + # only format scala source files, not generated files |
| 20 | + if src.path.endswith(".scala") and src.is_source: |
| 21 | + file = ctx.actions.declare_file("{}.fmt.output".format(src.short_path)) |
| 22 | + files.append(file) |
| 23 | + ctx.actions.run( |
| 24 | + arguments = ["--jvm_flag=-Dfile.encoding=UTF-8", _format_args(ctx, src, file)], |
| 25 | + executable = ctx.executable._fmt, |
| 26 | + outputs = [file], |
| 27 | + inputs = [ctx.file.config, src], |
| 28 | + execution_requirements = {"supports-workers": "1"}, |
| 29 | + mnemonic = "ScalaFmt", |
| 30 | + ) |
| 31 | + manifest_content.append("{} {}".format(src.short_path, file.short_path)) |
| 32 | + |
| 33 | + # record the source path and the formatted file path |
| 34 | + # so that we know where to copy the formatted file to replace the source file |
| 35 | + manifest = ctx.actions.declare_file("format/{}/manifest.txt".format(ctx.label.name)) |
| 36 | + ctx.actions.write(manifest, "\n".join(manifest_content) + "\n") |
| 37 | + |
| 38 | + return manifest, files |
| 39 | + |
| 40 | +def _formatter(ctx, manifest, files, template, output_runner): |
| 41 | + ctx.actions.run_shell( |
| 42 | + inputs = [template, manifest] + files, |
| 43 | + outputs = [output_runner], |
| 44 | + # replace %workspace% and %manifest% in template and rewrite it to output_runner |
| 45 | + command = "cat $1 | sed -e s#%workspace%#$2# -e s#%manifest%#$3# > $4", |
| 46 | + arguments = [ |
| 47 | + template.path, |
| 48 | + ctx.workspace_name, |
| 49 | + manifest.short_path, |
| 50 | + output_runner.path, |
| 51 | + ], |
| 52 | + execution_requirements = {}, |
| 53 | + ) |
| 54 | + |
| 55 | +def _write_empty_content(ctx, output_runner): |
| 56 | + ctx.actions.write( |
| 57 | + output = output_runner, |
| 58 | + content = "", |
| 59 | + ) |
| 60 | + |
| 61 | +def _format_args(ctx, src, file): |
| 62 | + args = ctx.actions.args() |
| 63 | + args.add(ctx.file.config.path) |
| 64 | + args.add(src.path) |
| 65 | + args.add(file.path) |
| 66 | + args.set_param_file_format("multiline") |
| 67 | + args.use_param_file("@%s", use_always = True) |
| 68 | + return args |
0 commit comments