Skip to content

Commit

Permalink
feat: support environment variables for ni config (#216)
Browse files Browse the repository at this point in the history
Co-authored-by: Anthony Fu <github@antfu.me>
  • Loading branch information
ghostdevv and antfu authored Jul 24, 2024
1 parent d1584cf commit c408ee6
Show file tree
Hide file tree
Showing 4 changed files with 62 additions and 0 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,10 @@ globalAgent=npm

# custom configuration file path
export NI_CONFIG_FILE="$HOME/.config/ni/nirc"

# environment variables have higher priority than config file if presented
export NI_DEFAULT_AGENT="npm" # default "prompt"
export NI_GLOBAL_AGENT="npm"
```

```ps
Expand Down
7 changes: 7 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,13 @@ export async function getConfig(): Promise<Config> {
? ini.parse(fs.readFileSync(rcPath, 'utf-8'))
: null,
)

if (process.env.NI_DEFAULT_AGENT)
config.defaultAgent = process.env.NI_DEFAULT_AGENT as Agent

if (process.env.NI_GLOBAL_AGENT)
config.globalAgent = process.env.NI_GLOBAL_AGENT as Agent

const agent = await detect({ programmatic: true })
if (agent)
config.defaultAgent = agent
Expand Down
2 changes: 2 additions & 0 deletions test/config/.nirc
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
defaultAgent=npm
globalAgent=pnpm
49 changes: 49 additions & 0 deletions test/config/config.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { beforeEach, expect, it, vi } from 'vitest'

const __dirname = dirname(fileURLToPath(import.meta.url))

beforeEach(() => {
vi.unstubAllEnvs()
vi.resetModules()
})

vi.mock('find-up', () => ({
findUp: vi.fn(),
}))

it('has correct defaults', async () => {
const { getConfig } = await import('../../src/config')
const config = await getConfig()

expect(config).toEqual({
defaultAgent: 'prompt',
globalAgent: 'npm',
})
})

it('loads .nirc', async () => {
vi.stubEnv('NI_CONFIG_FILE', join(__dirname, './.nirc'))

const { getConfig } = await import('../../src/config')
const config = await getConfig()

expect(config).toEqual({
defaultAgent: 'npm',
globalAgent: 'pnpm',
})
})

it('reads environment variable config', async () => {
vi.stubEnv('NI_DEFAULT_AGENT', 'npm')
vi.stubEnv('NI_GLOBAL_AGENT', 'pnpm')

const { getConfig } = await import('../../src/config')
const config = await getConfig()

expect(config).toEqual({
defaultAgent: 'npm',
globalAgent: 'pnpm',
})
})

0 comments on commit c408ee6

Please sign in to comment.