今天调试 lint-staged@12.5.0 接入时,遇到了问题,以下是对比图:

    通过 pre-commit 钩子触发 npx lint-staged 结果如下:
    image.png
    直接调用 npx lint-staged 结果如下:
    image.png
    体验上通过 git hooks 钩子触发的,无法展现友好交互
    但同事的电脑是好的,我很郁闷。

    简单对比了一些系统环境版本,git,node,npm 等,大体一致,略有不同

    跟踪排查下,经过一番对比,发现问题出在 supports-color 这个包上,进一步定位到问题

    1. import tty from 'node:tty';
    2. const supportsColor = {
    3. stdout: createSupportsColor({isTTY: tty.isatty(1)}),
    4. stderr: createSupportsColor({isTTY: tty.isatty(2)}),
    5. };
    • 通过git hooks 钩子触发 npx lint-staged 时,tty.isatty(1) 为 false
    • 直接调用 npx lint-staged,tty.isatty(1) 为 true, 最终导致了交互结果不一样。

    看了下 node:tty 的官方文档,没发现什么有用信息

    继续排查,发现一个类似的 ISSUE: regression with tty detection
    关联的一个 issue:pre-commit with git hooks do not show proper colours in terminal#2356
    还有个:https://github.com/okonet/lint-staged/issues/1164

    这里有一条评论这样写的:this is a regression in git 2.36.0 — for more info see here: https://twitter.com/pre_commit/status/1516492899306909696
    最终问题根源:https://public-inbox.org/git/CA+dzEBn108QoMA28f0nC8K21XT+Afua0V2Qv8XkR8rAeqUCCZw@mail.gmail.com/T/
    git 2.36.0 regression: pre-commit hooks no longer have stdout/stderr as tty 这里有更具体的描述

    1. in 2.36.0+ isatty is false for stdout and
    2. stderr causing coloring to be turned off.

    与 git 有关系,之前对比版本时,我的 git 是 2.36.1 版本,同事的大概是 2. 5,这里修正下,同事使用的 2.35.1

    更多相关git changelog:

    解决方案
    方案一:git 的版本降级应该可以解决此问题,我没测试,同事的低版本是好的。
    注意,husky 使用 core.hooksPath 实现 git hooks,要求 git 版本大于 2.9+
    方案二:升级 lint-staged 到 13 版本。使用 npx lint-staged -- --color
    注意,lint-staged 不再支持 node@12,至少需要 node@14.13.1 版本

    我在跟踪 supports-color 问题时,发现 lint-staged 在 21 天前刚好改动了这块逻辑, 移除了 supports-color 模块,底层将 supports-color 替换为了 import { isColorSupported } from 'colorette'
    于是,我就测试了 lint-staged 的 13 版本,可以通过 pre-commit 钩子触发 npx lint-staged — —color 来解决此问题

    备注:

    https://stackoverflow.com/questions/39332407/git-hooks-applying-git-config-core-hookspath 该core.hooksPath支持是Git 版本 2.9 中的新支持,已通过commit867ad08a2610526edb5723804723d371136fc643 加入。 如果您的 Git 版本不是至少 2.9.0,则设置 hooks-path 变量将完全没有效果。

    其他