Skip to content

Instantly share code, notes, and snippets.

@KL13NT
Last active December 30, 2021 13:07
Show Gist options
  • Save KL13NT/5d86ce1eb690717fd1a294e2a40276d1 to your computer and use it in GitHub Desktop.
Save KL13NT/5d86ce1eb690717fd1a294e2a40276d1 to your computer and use it in GitHub Desktop.
A simple NodeJS script to init a git repo with specific gpg credentials and author email for people who have multiple git identities. You need NodeJS and npm to install inquirer first tho.
@echo off
node %~dp0\initrepo.js
const inquirer = require('inquirer')
const path = require('path')
const { execSync } = require('child_process')
const { mkdirSync } = require('fs')
const gpgKeyRegex =
/sec\s+rsa(2048|4096)\/(?<key>[A-Za-z0-9]+) .+\n .+\n.+(?<email><.+>)/g
const commands = {
gpgListKeys: 'gpg --list-secret-keys --keyid-format=long',
init: 'git init',
setGpgSigningOn: `git config commit.gpgSign true`,
setRemote: remote => `git remote add origin ${remote}`,
setUserEmail: email => `git config user.email ${email}`,
setGpgKey: key => `git config user.signingkey ${key}`
}
console.log('Reading available signing keys')
const gpgKeysOutput = execSync(commands.gpgListKeys).toString()
const matches = gpgKeysOutput.matchAll(gpgKeyRegex)
const gpgKeys = []
for (const match of matches) {
gpgKeys.push({
key: match.groups['key'],
email: match.groups['email']
})
}
inquirer
.prompt([
{
type: 'input',
name: 'name',
message: 'What is the repo name? (in lowercase)'
},
{
type: 'list',
name: 'user.signingKey',
message: 'Which gpg key do you want to use with this repo?',
choices: gpgKeys.map(key => ({
name: `${key.key} - ${key.email}`,
value: key.key
}))
},
{
type: 'list',
name: 'user.email',
message: 'What is the author email for this repo?',
choices: ['example@example.com'] // your git emails
},
{
type: 'input',
name: 'remote',
message: 'Is there a remote setup for this repo? If so, what is the link?'
}
])
.then(answers => {
const directory = answers.name
? path.resolve(process.cwd(), answers.name)
: process.cwd()
if (answers.name) {
mkdirSync(answers.name)
process.chdir(directory)
}
console.log('Initializing your repo, just a sec!')
execSync(commands.init)
execSync(commands.setGpgSigningOn)
execSync(commands.setUserEmail(answers.user.email))
execSync(commands.setGpgKey(answers.user.signingKey))
if (answers.remote) execSync(commands.setRemote(answers.remote))
console.log('All done. Enjoy! :D')
})
.catch(error => {
if (error.isTtyError) {
console.log("Prompt couldn't be rendered in the current environment")
} else {
console.log(error)
// Something else went wrong
}
})
#!/bin/bash
# I'm not sure this works, I'm not a Linux user.
parent_path=$( cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P )
cd "$parent_path"
node ./initrepo.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment