我这辈子都想不出如何完成这项工作。我正在使用的模块 ( grunt-sloc ) 的 grunt 配置需要 Files Object Format .使用它,我希望能够匹配顶级目录下的所有常规文件(即非目录)。
例如,假设这是我的目录结构,其中 +
表示一个目录,-
表示一个普通文件:
repo
+ dir
- unwanted.js
- server.js
我如何使用 Grunt 的 Files Object Format匹配 server.js
但不匹配 dir
或 dir/unwanted.js
?
这是它在 Compact Fomat 中的样子:
mine: {
src: [
'*'
]
}
或者,在 bash 中,您会像这样得到它们:
ls -p | grep -v /;
这是我对 Files Object Format 的尝试:
这行不通:
mine: { files: { '.': ['*'] } }
这也不是:
mine: { files: { './': ['*'] } }
连这个都不是:
mine: { files: { './': ['*/server.js'] } }
也不是这个:
mine: { files: { './': ['server.js'] } }
这有效,但它递归运行,这是我不想要的:
mine: { files: { './': ['**/server.js'] } }
经过大量测试和代码阅读后,我确认它实际上是 minimatch包(Grunt 的依赖项),它不返回我正在寻找的匹配项。所以这不是我正在使用的 grunt 模块;这是我的 grunt 配置。
由于 Grunt 如此流行并且这似乎是一个非常常见的用例,我猜想有一种方法可以做到这一点。有谁知道那是什么?
更新
正如 RobC
所指出的,我的最后一个示例不 有效。它在我的 node_modules
目录中获取 server.js
,这让我觉得它在工作。
最佳答案
首先,FWIW,您的示例使用 Files Object Format 列出方法对我也不起作用,包括你的最后一个:
// Although this worked for you, this failed for me...
mine: {
files: {
'./': ['**/server.js']
}
}
我能让它工作的唯一方法是匹配所有内容,然后使用 Grunt globbing 否定顶级目录模式。
虽然以下要点演示了对我有用的内容,但它确实需要了解/配置您希望排除的顶级目录的名称:
目录结构
给定一个目录设置如下:
repo
│
├─── dir
│ │
│ └─── unwanted.js
│
├─── foo.js
│
├─── Gruntfile.js
│
├─── node_modules
│ │
│ └─── ...
│
├─── package.json
│
└─── server.js
Gruntfile.js
...和一个配置如下的Gruntfile.js
:
module.exports = function(grunt) {
grunt.initConfig({
sloc: {
mine: {
files: {
'.': [
'**', // Match everything and add to the results set.
// Explicitly state which directories under the top
// level directory to negate from the results set.
'!**/node_modules/**',
'!**/dir/**',
// Files can be negated from the results set too.
'!**/Gruntfile.js' //
]
}
}
}
});
grunt.loadNpmTasks('grunt-sloc');
grunt.registerTask('default', [
'sloc:mine'
]);
};
Sloc 结果
通过 CLI 正确运行 grunt
导致 grunt-sloc仅报告两个文件的统计信息,即 foo.js
和 server.js
。
正如预期的那样,由于 JSON 是 non-supported,因此省略了 package.json
的统计信息语言。
补充说明:
我找到了这个 post 的答案在解释如何从初始返回的数组中排除以 !
开头的模式时提供了相当多的信息。
关于javascript - Grunt 文件对象格式 : All regular files files immediately under top level directory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41227726/