从Scala调用clang-format时无法传递复杂style参数
解决Scala中调用clang-format传递复杂style参数的问题
这个问题的核心是shell引号和Scala Process参数传递的差异,咱们一步步理清楚:
问题原因
当你在终端里执行:
clang-format -style='{BasedOnStyle: llvm, IndentWidth: 4}' library-api/src/main/resources/Cols.hpp
这里的单引号是给shell用的——它告诉shell把整个{BasedOnStyle: llvm, IndentWidth: 4}当成一个单一参数,避免空格和逗号被shell拆分成多个参数。但当你在Scala的Process参数列表里写"-style='{BasedOnStyle: llvm, IndentWidth: 4}'"时,单引号会被直接当成参数的一部分传递给clang-format,它自然无法识别带单引号的style配置。
修复方案
直接去掉单引号,把完整的style配置作为-style的参数值即可:
val formatterParams = List( "-i", "-sort-includes", "-style={BasedOnStyle: llvm, IndentWidth: 4}", headerFile.getAbsolutePath ) Process("clang-format", formatterParams).!
为什么这样可行?
Scala的Process是直接构造参数数组传递给clang-format的,每个列表元素对应一个独立的命令行参数,不需要shell来帮忙分割,所以完全不需要额外的引号。clang-format会直接接收-style={BasedOnStyle: llvm, IndentWidth: 4}作为一个参数,正确解析里面的配置内容。
额外选项(可选)
如果你的style配置很复杂,也可以把它写到一个.clang-format文件里,然后用-style=file参数来调用,这样代码会更整洁:
// 假设你已经有了.clang-format文件在指定路径 val formatterParams = List( "-i", "-sort-includes", "-style=file:/path/to/your/.clang-format", headerFile.getAbsolutePath ) Process("clang-format", formatterParams).!
内容的提问来源于stack exchange,提问作者Alexey Romanov
相关产品推荐
相关产品推荐

