Skip to content

Instantly share code, notes, and snippets.

@chrisdothtml
Last active May 8, 2019 19:27
Show Gist options
  • Save chrisdothtml/509fdbe3bfec1a11bbc346e4b44c3604 to your computer and use it in GitHub Desktop.
Save chrisdothtml/509fdbe3bfec1a11bbc346e4b44c3604 to your computer and use it in GitHub Desktop.
Simple CLI to switch between npmrc configs

Setup

1. Download script

curl https://gist.githubusercontent.com/chrisdothtml/509fdbe3bfec1a11bbc346e4b44c3604/raw/switch-npmrc.js > "$HOME/switch-npmrc.js"

2. Add alias to .bash_profile or similar

alias npmrc="node $HOME/switch-npmrc.js"

3. Setup your .npmrc sections

###
# Formatting info:
# https://gist.github.com/chrisdothtml/509fdbe3bfec1a11bbc346e4b44c3604#file-readme-md
###

# $personal:
//registry.npmjs.org/:_authToken=[...]
email[email protected]

# $work:
#//registry.npmjs.org/:_authToken=[...]
#[email protected]

Use

# list available sections
npmrc ls

# enable a section (comments-out all other sections, uncomments provided section)
npmrc work
/*
* Installed from:
* https://gist.github.com/chrisdothtml/509fdbe3bfec1a11bbc346e4b44c3604
*/
const fs = require('fs')
const path = require('path')
// update this if yours is different (assumes this script is in the same dir as your .npmrc)
const NPMRC_PATH = path.join(__dirname, '.npmrc')
// format:
// # $sectionName:
function parseSectionName (line) {
const match = /^# \$([^:]+):/.exec(line)
if (match) {
return match[1]
}
}
function main () {
const lines = fs.readFileSync(NPMRC_PATH, 'utf-8').split('\n')
const argv = process.argv.slice(2)
if (argv[0] === 'ls') {
const sections = []
for (const line of lines) {
const sectionName = parseSectionName(line)
if (sectionName) {
sections.push(sectionName)
}
}
console.log(`Section names:\n\n${sections.sort().join('\n')}`)
} else {
const sectionToEnable = argv[0]
let currentSection
const newContent = lines
.map((line, index, lines) => {
if (line) {
const sectionName = parseSectionName(line)
if (sectionName) {
currentSection = sectionName
} else if (currentSection) {
if (currentSection === sectionToEnable) {
line = line.replace(/^#/, '')
} else {
line = line.startsWith('#') ? line : '#' + line
}
}
}
return line
})
.join('\n')
fs.writeFileSync(NPMRC_PATH, newContent)
}
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment