Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add any-file-contents rule #290

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions docs/rules.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ Below is a complete list of rules that Repolinter can run, along with their conf
- [`large-file`](#large-file)
- [`license-detectable-by-licensee`](#license-detectable-by-licensee)
- [`best-practices-badge-present`](#best-practices-badge-present)
- [`any-file-contents`](#any-file-contents)

## Reference

Expand Down Expand Up @@ -229,3 +230,15 @@ Check Best Practices Badge is present in README. Optionally check a certain badg
| Input | Required | Type | Default | Description |
| ------------ | -------- | ---------- | ------- | ------------------------------------------------------------------ |
| `minPercentage` | No | `integer` | `null` | Minimum [Tiered Percentage](https://github.com/coreinfrastructure/best-practices-badge/blob/main/doc/api.md#tiered-percentage-in-openssf-best-practices-badge) accomplished by project. `passing=100`, `silver=200`, `gold=300`, set to `0` or `null` to disable check. |

### `any-file-contents`
Checks if the contents of at least one file in a given list match a given regular expression.

| Input | Required | Type | Default | Description |
| ------------------------ | -------- | ---------- | ----------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `globsAny` | **Yes** | `string[]` | | A list of globs to get files for. This rule passes if at least one of the files returned by the globs match the supplied string, or if no files are returned. |
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Quote:

However, for our use case we need to check whether the content is included in at least one of the discovered files.

I think it doesn't make sense for the rule to pass if no files are returned. It would make sense if the rule fails if no files are returned., since we are looking for at least there is one file has this thing there.

That means the fail-on-non-existent would be success-on-non-existent.

| `content` | **Yes** | `string` | | The regular expression to check using `String#search`. This expression should not include the enclosing slashes and may need to be escaped to properly integrate with the JSON config (ex. `".+@.+\\..+"` for an email address). |
| `nocase` | No | `boolean` | `false` | Set to `true` to make the globs case insensitive. This does not effect the case sensitivity of the regular expression. |
| `flags` | No | `string` | `""` | The flags to use for the regular expression in `content` (ex. `"i"` for case insensitivity). |
| `human-readable-content` | No | `string` | The regular expression in `content` | The string to print instead of the regular expression when generating human-readable output. |
| `fail-on-non-existent` | No | `boolean` | `false` | Set to `true` to disable passing if no files are found from `globsAll`. |
24 changes: 24 additions & 0 deletions rules/any-file-contents-config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"$schema": "http://json-schema.org/draft-07/schema",
"$id": "https://raw.githubusercontent.com/todogroup/repolinter/master/rules/any-file-contents-config.json",
"type": "object",
"properties": {
"nocase": {
"type": "boolean",
"default": false
},
"globsAny": {
"type": "array",
"items": { "type": "string" }
},
"content": { "type": "string" },
"flags": { "type": "string" },
"human-readable-content": { "type": "string" },
"fail-on-non-existent": {
"type": "boolean",
"default": false
}
},
"required": ["content"],
"oneOf": [{ "required": ["globsAny"] }, { "required": ["files"] }]
}
21 changes: 21 additions & 0 deletions rules/any-file-contents.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Copyright 2017 TODO Group. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

// eslint-disable-next-line no-unused-vars
const Result = require('../lib/result')
// eslint-disable-next-line no-unused-vars
const FileSystem = require('../lib/file_system')
const fileContents = require('./file-contents')

/**
* Check that at least one file within a list contains a regular expression.
*
* @param {FileSystem} fs A filesystem object configured with filter paths and target directories
* @param {object} options The rule configuration
* @returns {Promise<Result>} The lint rule result
*/
function anyFileContents(fs, options) {
return fileContents(fs, options, false, true)
}

module.exports = anyFileContents
8 changes: 5 additions & 3 deletions rules/file-contents.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@ function getContext(matchedLine, regexMatch, contextLength) {
* @returns {Promise<Result>} The lint rule result
* @ignore
*/
async function fileContents(fs, options, not = false) {
async function fileContents(fs, options, not = false, any = false) {
// support legacy configuration keys
const fileList = options.globsAll || options.files
const fileList = (any ? options.globsAny : options.globsAll) || options.files
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's not change the file-contents function parameter, keep the function always take globsAll and it matches the intention of if all of the files returned by the globs match the supplied string, or if no files are returned..

You can move this part to any-file-contents.js instead.

const files = await fs.findAllFiles(fileList, !!options.nocase)
const regexFlags = options.flags || ''

Expand Down Expand Up @@ -272,7 +272,9 @@ async function fileContents(fs, options, not = false) {
}

const filteredResults = results.filter(r => r !== null)
const passed = !filteredResults.find(r => !r.passed)
const passed = any
? filteredResults.some(r => r.passed)
: !filteredResults.find(r => !r.passed)
return new Result('', filteredResults, passed)
}

Expand Down
6 changes: 6 additions & 0 deletions rules/file-not-contents-config.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@
"type": "string"
}
},
"branches": {
"type": "array",
"items": { "type": "string" },
"default": []
},
"skipDefaultBranch": { "type": "boolean", "default": false },
"flags": { "type": "string" },
"human-readable-content": { "type": "string" },
"fail-on-non-existent": {
Expand Down
3 changes: 2 additions & 1 deletion rules/rules.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,6 @@ module.exports = {
'git-working-tree': require('./git-working-tree'),
'large-file': require('./large-file'),
'license-detectable-by-licensee': require('./license-detectable-by-licensee'),
'json-schema-passes': require('./json-schema-passes')
'json-schema-passes': require('./json-schema-passes'),
'any-file-contents': require('./any-file-contents')
}
12 changes: 12 additions & 0 deletions rulesets/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,18 @@
}
}
}
},
{
"if": {
"properties": { "type": { "const": "any-file-contents" } }
},
"then": {
"properties": {
"options": {
"$ref": "../rules/any-file-contents-config.json"
}
}
}
}
]
},
Expand Down
137 changes: 137 additions & 0 deletions tests/rules/any_file_contents_tests.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
// Copyright 2017 TODO Group. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

const chai = require('chai')
const expect = chai.expect
const FileSystem = require('../../lib/file_system')

describe('rule', () => {
describe('any_file_contents', () => {
const anyFileContents = require('../../rules/any-file-contents')

it('returns passes if requested file contents exists in exactly one file', async () => {
/** @type {any} */
const mockfs = {
findAllFiles() {
return ['x.md', 'CONTRIBUTING.md', 'README.md']
},
getFileContents(file) {
return file === 'README.md' ? 'foo' : 'bar'
},
targetDir: '.'
}
const ruleopts = {
globsAny: ['README*', 'x.md', 'CONTRIBUTING.md'],
content: '[abcdef][oO0][^q]'
}

const actual = await anyFileContents(mockfs, ruleopts)
expect(actual.passed).to.equal(true)
expect(actual.targets).to.have.length(3)
expect(actual.targets[2]).to.deep.include({
passed: true,
path: 'README.md'
})
})

it('returns passes if requested file contents exists in two files', async () => {
/** @type {any} */
const mockfs = {
findAllFiles() {
return ['x.md', 'CONTRIBUTING.md', 'README.md']
},
getFileContents(file) {
return file === 'README.md' ? 'bar' : 'foo'
},
targetDir: '.'
}
const ruleopts = {
globsAny: ['README*', 'x.md', 'CONTRIBUTING.md'],
content: '[abcdef][oO0][^q]'
}

const actual = await anyFileContents(mockfs, ruleopts)

expect(actual.passed).to.equal(true)
expect(actual.targets).to.have.length(3)
expect(actual.targets[0]).to.deep.include({
passed: true,
path: 'x.md'
})
expect(actual.targets[1]).to.deep.include({
passed: true,
path: 'CONTRIBUTING.md'
})
expect(actual.targets[2]).to.deep.include({
passed: false,
path: 'README.md'
})
})

it('returns fails if the requested file contents does not exist in any file', async () => {
/** @type {any} */
const mockfs = {
findAllFiles() {
return ['x.md', 'CONTRIBUTING.md', 'README.md']
},
getFileContents() {
return 'bar'
},
targetDir: '.'
}
const ruleopts = {
globsAny: ['README*', 'x.md', 'CONTRIBUTING.md'],
content: '[abcdef][oO0][^q]'
}

const actual = await anyFileContents(mockfs, ruleopts)
expect(actual.passed).to.equal(false)
expect(actual.targets).to.have.length(3)
expect(actual.targets[0]).to.deep.include({
passed: false,
path: 'x.md'
})
expect(actual.targets[1]).to.deep.include({
passed: false,
path: 'CONTRIBUTING.md'
})
})

it('returns failure if no file exists with failure flag enabled', async () => {
/** @type {any} */
const mockfs = {
findAllFiles() {
return []
},
getFileContents() {},
targetDir: '.'
}

const ruleopts = {
globsAny: ['README.md', 'READMOI.md'],
content: 'foo',
'fail-on-non-existent': true
}

const actual = await anyFileContents(mockfs, ruleopts)

expect(actual.passed).to.equal(false)
})

it('should handle broken symlinks', async () => {
const brokenSymlink = './tests/rules/broken_symlink_for_test'
const stat = require('fs').lstatSync(brokenSymlink)
expect(stat.isSymbolicLink()).to.equal(true)
const fs = new FileSystem(require('path').resolve('.'))

const ruleopts = {
globsAny: [brokenSymlink],
lineCount: 1,
patterns: ['something'],
'fail-on-non-existent': true
}
const actual = await anyFileContents(fs, ruleopts)
expect(actual.passed).to.equal(false)
})
})
})