过滤 grunt 任务的输出

Filter output of a grunt task

我有几个内部使用 grunt-shell 执行各种 CLI 命令的 grunt 任务。

我想隐藏通过这些 CLI 命令打印到输出控制台的某些日志。

我正在尝试为此使用 grunt-reporter,但无法正常工作。

Gruntfile.js

reporter: {
            shell:{
                options: {
                    tasks: ['shell'],
                    header: false
                }
            }
        }

简短的回答... grunt-reporter 本身不可能隐藏由 grunt-shell 命令生成的日志。

包含解决方法的长答案... 来自 grunt-shell 命令的日志由 shell/bash 命令本身生成,而不是通过节点 package/script。 grunt-reporter 主页上显示的 examples 是 intercepting/manipulating 来自节点包的消息写入 stdout

考虑以下...

简单的要点

module.exports = function(grunt) {

    grunt.initConfig({

        shell: {
            listFiles: {
                command: 'ls src/js/*.js'
            }
        }
    });

    require('load-grunt-tasks')(grunt);

    grunt.registerTask('default', [
        'shell:listFiles'
    ]);
};

运行 $ grunt 通过 CLI 输出如下内容:

Running "shell:listFiles" (shell) task

src/js/a.js

src/js/b.js

src/js/c.js

Done.


隐藏 header...

利用 grunt-reporter 可以 (在这种情况下最好),使用如下配置隐藏 header:

module.exports = function(grunt) {

    grunt.initConfig({

        reporter: {
            shell: {
                options: {
                    tasks: ['shell:listFiles'],
                    header: false      
                }
            }
        },

        shell: {
            listFiles: {
                command: 'ls src/js/*.js'
            }
        }

    });

    require('load-grunt-tasks')(grunt);

    grunt.registerTask('default', [
        'reporter:shell', //<-- Note: The reporter task is called first.
        'shell:listFiles'
    ]);

};

运行 $ grunt 通过 CLI 现在将输出类似这样的内容 (注意:header 已被隐藏,但是来自 ls 命令仍然存在,因为它直接来自 bash/shell 命令):

src/js/a.js

src/js/b.js

src/js/c.js

Done.

即使将 suppress: true 添加到 reporter 选项后,来自 ls 命令的路径日志仍然存在。


解决方法

我认为从 CLI 命令隐藏日志的唯一方法是将输出消息重定向到 'grunt-shell' 命令中的 /dev/null

module.exports = function(grunt) {

    grunt.initConfig({

        reporter: {
            shell: {
                options: {
                    tasks: ['shell:listFiles'],
                    header: false,
                    
                }
            }
        },

        shell: {
            listFiles: {
                command: 'ls src/js/*.js > /dev/null' //<-- redirect the output messages
            }
        }

    });

    require('load-grunt-tasks')(grunt);

    grunt.registerTask('default', [
        'reporter:shell', //<-- Note: The reporter task is called first.
        'shell:listFiles'
    ]);

};

这次 运行 $ grunt 通过 CLI 成功隐藏了 messages/logs 并且只报告:

Done.

注意: 添加 > /dev/null 只会重定向 messages/logs 并且会继续报告任何错误。使用 > /dev/null 2>&1 也会隐藏任何错误。