Skip to content

Commit

Permalink
Merge pull request #528 from brelian/pylon/support-homedir
Browse files Browse the repository at this point in the history
feat: support to parse home directory
  • Loading branch information
motdotla authored May 19, 2021
2 parents a70b641 + a3e2a1e commit 8dc2e71
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
7 changes: 6 additions & 1 deletion lib/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ type DotenvConfigOutput = {

const fs = require('fs')
const path = require('path')
const os = require('os')

function log (message /*: string */) {
console.log(`[dotenv][DEBUG] ${message}`)
Expand Down Expand Up @@ -73,6 +74,10 @@ function parse (src /*: string | Buffer */, options /*: ?DotenvParseOptions */)
return obj
}

function resolveHome (envPath) {
return envPath[0] === '~' ? path.join(os.homedir(), envPath.slice(1)) : envPath
}

// Populates process.env from .env file
function config (options /*: ?DotenvConfigOptions */) /*: DotenvConfigOutput */ {
let dotenvPath = path.resolve(process.cwd(), '.env')
Expand All @@ -81,7 +86,7 @@ function config (options /*: ?DotenvConfigOptions */) /*: DotenvConfigOutput */

if (options) {
if (options.path != null) {
dotenvPath = options.path
dotenvPath = resolveHome(options.path)
}
if (options.encoding != null) {
encoding = options.encoding
Expand Down
16 changes: 15 additions & 1 deletion tests/test-config.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
/* @flow */

const fs = require('fs')
const os = require('os')
const path = require('path')

const sinon = require('sinon')
const t = require('tap')
Expand All @@ -11,7 +13,7 @@ const mockParseResponse = { test: 'foo' }
let readFileSyncStub
let parseStub

t.plan(8)
t.plan(9)

t.beforeEach(done => {
readFileSyncStub = sinon.stub(fs, 'readFileSync').returns('test=foo')
Expand All @@ -34,6 +36,18 @@ t.test('takes option for path', ct => {
ct.equal(readFileSyncStub.args[0][0], testPath)
})

t.test('takes option for path along with home directory char ~', ct => {
ct.plan(2)
const mockedHomedir = '/Users/dummy'
const homedirStub = sinon.stub(os, 'homedir').returns(mockedHomedir)
const testPath = '~/.env'
dotenv.config({ path: testPath })

ct.equal(readFileSyncStub.args[0][0], path.join(mockedHomedir, '.env'))
ct.ok(homedirStub.called)
homedirStub.restore()
})

t.test('takes option for encoding', ct => {
ct.plan(1)

Expand Down

0 comments on commit 8dc2e71

Please sign in to comment.