【问题标题】:Enable SwiftLint only for the new files仅为新文件启用 SwiftLint
【发布时间】:2021-10-13 19:11:24
【问题描述】:

我有一个非常庞大的 iOS(遗留)项目,我想在其中添加 SwiftLint。我希望强制执行的所有规则,我只会对新创建的文件强制执行。这样我就不必回去解决所有可能出现的问题,因为过去没有遵循规则(因为没有使用 SwiftLint)。我不确定如何实现这一目标?

【问题讨论】:

  • Swiftlint 有包含/排除指令来选择文件。但是,通常最好至少修复旧代码中的基本问题。很多问题都可以自动解决,坦白说,没那么难。我已经用这种方法修复了大项目。
  • @Sulthan 不幸的是,有太多警告和错误需要修复。它们中的大多数都不容易修复,因为它们需要更改逻辑。使用排除指令也没有帮助,因为我无法排除文件夹(例如)。将来可能会向其中添加新文件。此外,将每个文件都添加到排除列表不是一种选择,因为它们太多了。
  • 你必须选择。要么您在新旧代码之间创建明确的区别,例如使用文件夹,或者开始修复旧代码。
  • 我明白了。所以没有简单的方法对 SwiftLint 说:嘿,我把你加到项目中了,请不要看旧文件,只看新文件?
  • 也许创建一个 bash 脚本来循环使用最近 mtime 的文件(或 git 更改的文件),然后在该循​​环中执行 swiftlint lint --path "$filename"

标签: ios swift swiftlint


【解决方案1】:

你可以运行这样的脚本

    # Run SwiftLint
    START_DATE=$(date +"%s")
    
    SWIFT_LINT=/usr/local/bin/swiftlint
    
    # Run SwiftLint for given filename
    run_swiftlint() {
        local filename="${1}"
        if [[ "${filename##*.}" == "swift" ]]; then
            #${SWIFT_LINT} autocorrect --path "${filename}"
            ${SWIFT_LINT} lint --path "${filename}"
        fi
    }

    if [[ -e "${SWIFT_LINT}" ]]; then
        echo "SwiftLint version: $(${SWIFT_LINT} version)"
        # Run for both staged and unstaged files
        git diff --name-only | while read filename; do run_swiftlint                 "${filename}"; done
        git diff --cached --name-only | while read filename; do                 run_swiftlint "${filename}"; done
    else
        echo "${SWIFT_LINT} is not installed."
        exit 0
    fi

    END_DATE=$(date +"%s")

    DIFF=$(($END_DATE - $START_DATE))
    echo "SwiftLint took $(($DIFF / 60)) minutes and $(($DIFF % 60)) seconds to complete."

只需将构建阶段运行脚本添加到 Xcode 中

"${SRCROOT}/Scripts/swiftlint.sh"

来自这里https://github.com/realm/SwiftLint/issues/413#issuecomment-184077062

它在M1芯片上不起作用,因为你需要这样说

if test -d "/opt/homebrew/bin/"; then
  PATH="/opt/homebrew/bin/:${PATH}"
fi

export PATH

if which swiftlint >/dev/null; then
  swiftlint
else
  echo "warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint"
fine

基于此博客https://www.anotheriosdevblog.com/installing-swiftlint-on-a-m1/

【讨论】:

  • 它的作用是只在未提交的文件上运行。因此,如果您触摸旧文件,它将在其上运行 lint。不完全是答案,但它确实解决了我们将 SwiftLint 添加到旧项目的问题
猜你喜欢
  • 2019-09-21
  • 2018-12-29
  • 2018-02-07
  • 2020-12-01
  • 2023-01-13
  • 2021-03-28
  • 2017-01-31
  • 2016-07-02
  • 2017-02-01
相关资源
最近更新 更多