Skip to content

Commit

Permalink
Allow to remove section by function (#57)
Browse files Browse the repository at this point in the history
* Allow to remove section by function

* Fix unit Test

Co-authored-by: DELMAS Nicolas <nicolas.delmas@amadeus.com>
  • Loading branch information
colas31 and colas31 committed Jun 30, 2022
1 parent 0682363 commit 6f2a0f1
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 9 deletions.
4 changes: 3 additions & 1 deletion Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,12 +108,14 @@ config.find({ Host: 'example1' })
config.find(line => line.param == 'Host' && line.value == 'example1')
```

### `.remove` sections by Host or other criteria
### `.remove` sections by Host / Match or function

To remove sections, we can pass the section to `.remove(opts)`.

```js
config.remove({ Host: 'example1' })
// or the ES2015 Array.prototype.find
config.remove(line => line.param == 'Host' && line.value == 'example1')
```

### `.append` sections
Expand Down
21 changes: 13 additions & 8 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ class SSHConfig extends Array {
}

/**
* find section by Host or Match
* find section by Host / Match or function
*/
find(opts = {}) {
if (typeof opts === 'function') return super.find(opts)
Expand All @@ -92,17 +92,22 @@ class SSHConfig extends Array {
}

/**
* Remove section
* Remove section by Host / Match or function
*/
remove(opts = {}) {
if (!(opts && ('Host' in opts || 'Match' in opts))) {
throw new Error('Can only remove by Host or Match')
}
let index;

if (typeof opts === 'function') {
index = super.findIndex(opts);

} else if (!(opts && ('Host' in opts || 'Match' in opts))) {
throw new Error('Can only remove by Host or Match');

const index = typeof opts === 'function'
? super.findIndex(opts)
: super.findIndex(line => compare(line, opts))
} else {
index = super.findIndex(line => compare(line, opts));

}

if (index >= 0) return this.splice(index, 1)
}

Expand Down
12 changes: 12 additions & 0 deletions test/unit/ssh-config.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,18 @@ describe('SSHConfig', function() {
assert.throws(function() { config.remove({}) })
})

it('.remove by function', async function() {
const config = SSHConfig.parse(readFile('fixture/config'))
const length = config.length

config.remove((line) => line.param && line.param.toLowerCase() === 'Host'.toLowerCase() && line.value === 'tahoe2')
assert(config.find({ Host: 'tahoe2' }) == null)
assert(config.length === length - 1)

assert.throws(function() { config.remove() })
assert.throws(function() { config.remove({}) })
})

it('.append lines', function() {
const config = SSHConfig.parse(heredoc(function() {/*
Host example
Expand Down

0 comments on commit 6f2a0f1

Please sign in to comment.