Skip to content

Commit 418e443

Browse files
authored
Merge pull request #39 from adonisjs/feat/empty-example
feat: EnvEditor.add with empty value for .env.example
2 parents aec7917 + 9168360 commit 418e443

File tree

3 files changed

+40
-2
lines changed

3 files changed

+40
-2
lines changed

README.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,18 @@ editor.add('HOST', 'localhost')
139139
await editor.save()
140140
```
141141

142+
You can also insert an empty value for the `.env.example` file by setting the last argument to `true`.
143+
144+
```ts
145+
editor.add('SECRET_VARIABLE', 'secret-value', true)
146+
```
147+
148+
This will add the following line to the `.env.example` file.
149+
150+
```env
151+
SECRET_VARIABLE=
152+
```
153+
142154
## Known Exceptions
143155

144156
### E_INVALID_ENV_VARIABLES

src/editor.ts

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,13 +57,20 @@ export class EnvEditor {
5757

5858
/**
5959
* Add key-value pair to the dot-env files.
60+
* If `withEmptyExampleValue` is true then the key will be added with an empty value
61+
* to the `.env.example` file.
6062
*/
61-
add(key: string, value: string | number | boolean) {
63+
add(key: string, value: string | number | boolean, withEmptyExampleValue = false) {
6264
this.#files.forEach((file) => {
6365
let entryIndex = file.contents.findIndex((line) => line.startsWith(`${key}=`))
6466

6567
entryIndex = entryIndex === -1 ? file.contents.length : entryIndex
66-
lodash.set(file.contents, entryIndex, `${key}=${String(value)}`)
68+
69+
if (withEmptyExampleValue && file.path.endsWith('.env.example')) {
70+
lodash.set(file.contents, entryIndex, `${key}=`)
71+
} else {
72+
lodash.set(file.contents, entryIndex, `${key}=${value}`)
73+
}
6774
})
6875
}
6976

tests/editor.spec.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,4 +129,23 @@ test.group('Env editor | modify', () => {
129129
await assert.fileEquals('.env', ['PORT=3000', '', 'HOST=127.0.0.1'].join('\n'))
130130
await assert.fileEquals('.env.example', ['', 'PORT=3000', 'HOST=127.0.0.1'].join('\n'))
131131
})
132+
133+
test('add key with empty example value', async ({ assert, fs }) => {
134+
await fs.create('.env', '')
135+
await fs.create('.env.example', '')
136+
137+
const editor = await EnvEditor.create(fs.baseUrl)
138+
editor.add('PORT', 3000, true)
139+
140+
assert.deepEqual(editor.toJSON(), [
141+
{
142+
path: join(fs.basePath, '.env'),
143+
contents: ['', 'PORT=3000'],
144+
},
145+
{
146+
path: join(fs.basePath, '.env.example'),
147+
contents: ['', 'PORT='],
148+
},
149+
])
150+
})
132151
})

0 commit comments

Comments
 (0)