Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

move push to a service largely #21

Merged
merged 2 commits into from
Oct 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
126 changes: 4 additions & 122 deletions src/cli/actions/push.js
Original file line number Diff line number Diff line change
@@ -1,143 +1,25 @@
const fs = require('fs')
const path = require('path')
const { logger } = require('@dotenvx/dotenvx')

const current = require('./../../db/current')
const User = require('./../../db/user')

const isGitRepo = require('./../../lib/helpers/isGitRepo')
const isGithub = require('./../../lib/helpers/isGithub')
const gitUrl = require('./../../lib/helpers/gitUrl')
const gitRoot = require('./../../lib/helpers/gitRoot')
const extractUsernameName = require('./../../lib/helpers/extractUsernameName')
const extractSlug = require('./../../lib/helpers/extractSlug')
const forgivingDirectory = require('./../../lib/helpers/forgivingDirectory')
const { createSpinner } = require('./../../lib/helpers/createSpinner')

// api calls
const PostPush = require('./../../lib/api/postPush')

// SyncOrganization
const SyncOrganization = require('./../../lib/services/syncOrganization')
const Keypair = require('./../../lib/services/keypair')
const Push = require('./../../lib/services/push')

const spinner = createSpinner('pushing')

function _envFilepaths (directory, envFile) {
if (!Array.isArray(envFile)) {
return [path.join(directory, envFile)]
}

return envFile.map(file => path.join(directory, file))
}

async function push (directory) {
try {
spinner.start()

directory = forgivingDirectory(directory)

// debug args
logger.debug(`directory: ${directory}`)

// debug opts
const options = this.opts()
logger.debug(`options: ${JSON.stringify(options)}`)

// must be a git repo
if (!isGitRepo()) {
spinner.fail('oops, must be a git repository')
logger.help('? create one with [git init .]')
process.exit(1)
}

// must be a git root
const gitroot = gitRoot()
if (!gitroot) {
spinner.fail('oops, could not determine git repository\'s root')
logger.help('? create one with [git init .]')
process.exit(1)
}

// must have a remote origin url
const giturl = gitUrl()
if (!giturl) {
spinner.fail('oops, must have a remote origin (git remote -v)')
logger.help('? create it at [github.com/new] and then run [git remote add origin git@github.com:username/repository.git]')
process.exit(1)
}

// must be a github remote
if (!isGithub(giturl)) {
spinner.fail('oops, must be a github.com remote origin (git remote -v)')
logger.help('? create it at [github.com/new] and then run [git remote add origin git@github.com:username/repository.git]')
logger.help2('ℹ need support for other origins? [please tell us](/~https://github.com/dotenvx/dotenvx/issues)')
process.exit(1)
}

// find organization locally
const usernameName = extractUsernameName(giturl)
const slug = extractSlug(usernameName)
const user = new User()
const lookups = user.lookups()
const organizationId = lookups[`lookup/organizationIdBySlug/${slug}`]
if (!organizationId) {
spinner.fail(`oops, can't find organization [@${slug}]`)
logger.help('? try running [dotenvx pro sync] or joining organization [dotenvx pro settings orgjoin]')
process.exit(1)
}

// sync org
const organization = await new SyncOrganization(options.hostname, current.token(), organizationId).run()

// check for publicKey
if (!organization.publicKey()) {
spinner.fail(`oops, can't find orgpublickey for [@${slug}]`)
logger.help('? try running [dotenvx pro sync]')
process.exit(1)
}

// -f .env,etc
const envFilepaths = _envFilepaths(directory, options.envFile)
for (const envFilepath of envFilepaths) {
const filepath = path.resolve(envFilepath)

// file must exist
if (!fs.existsSync(filepath)) {
spinner.fail(`oops, missing ${envFilepath} file (${filepath})`)
logger.help(`? add one with [echo "HELLO=World" > ${envFilepath}]`)
process.exit(1)
}

// get keypairs
const keypairs = new Keypair(envFilepath).run()

// publicKey must exist
const publicKeyName = Object.keys(keypairs).find(key => key.startsWith('DOTENV_PUBLIC_KEY'))
const publicKey = keypairs[publicKeyName]
if (!publicKey) {
spinner.fail(`oops, could not locate ${publicKeyName}`)
logger.help(`? generate ${publicKeyName} (.env.keys) with [dotenvx encrypt]`)
process.exit(1)
}

// privateKey
const privateKeyName = Object.keys(keypairs).find(key => key.startsWith('DOTENV_PRIVATE_KEY'))
const privateKey = keypairs[privateKeyName]
const privateKeyEncryptedWithOrganizationPublicKey = organization.encrypt(privateKey)

// filepath
const relativeFilepath = path.relative(gitroot, path.join(process.cwd(), directory, envFilepath)).replace(/\\/g, '/') // smartly determine path/to/.env file from repository root - where user is cd-ed inside a folder or at repo root

// text
const text = fs.readFileSync(filepath, 'utf8')

await new PostPush(options.hostname, current.token(), 'github', organization.publicKey(), usernameName, relativeFilepath, publicKeyName, privateKeyName, publicKey, privateKeyEncryptedWithOrganizationPublicKey, text).run()

// sync org
await new SyncOrganization(options.hostname, current.token(), organizationId).run()

spinner.succeed(`pushed (${relativeFilepath})`)
const pushedFilepaths = await new Push(options.hostname, options.envFile).run()
for (const filepath of pushedFilepaths) {
spinner.succeed(`pushed (${filepath})`)
}
} catch (error) {
if (error.message) {
Expand Down
21 changes: 17 additions & 4 deletions src/lib/helpers/validateGit.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,37 @@ const isGithub = require('./isGithub')
function validateGit () {
// must be a git repo
if (!isGitRepo()) {
throw new Error('oops, must be a git repository')
const error = new Error('oops, must be a git repository')
error.help = '? create one with [git init .]'

throw error
}

// must be a git root
const gitroot = gitRoot()
if (!gitroot) {
throw new Error('oops, could not determine git repository\'s root')
const error = new Error('oops, could not determine git repository\'s root')
error.help = '? create one with [git init .]'

throw error
}

// must have a remote origin url
const giturl = gitUrl()
if (!giturl) {
throw new Error('oops, must have a remote origin (git remote -v)')
const error = new Error('oops, must have a remote origin (git remote -v)')
error.help = '? create it at [github.com/new] and then run [git remote add origin git@github.com:username/repository.git]'

throw error
}

// must be a github remote
if (!isGithub(giturl)) {
throw new Error('oops, must be a github.com remote origin (git remote -v)')
const error = new Error('oops, must be a github.com remote origin (git remote -v)')
error.help = '? create it at [github.com/new] and then run [git remote add origin git@github.com:username/repository.git]'
error.help2 = 'ℹ need support for other origins? [please tell us](/~https://github.com/dotenvx/dotenvx/issues)'

throw error
}
}

Expand Down
141 changes: 141 additions & 0 deletions src/lib/services/push.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
const fs = require('fs')
const path = require('path')

const gitUrl = require('./../helpers/gitUrl')
const gitRoot = require('./../helpers/gitRoot')
const validateGit = require('./../helpers/validateGit')
const extractSlug = require('./../helpers/extractSlug')
const extractUsernameName = require('./../helpers/extractUsernameName')
const forgivingDirectory = require('./../helpers/forgivingDirectory')

// services
const SyncOrganization = require('./syncOrganization')
const Keypair = require('./keypair')

// db
const User = require('./../../db/user')
const current = require('./../../db/current')

// api calls
const PostPush = require('./../../lib/api/postPush')

class Push {
constructor (hostname = current.hostname(), envFile = '.env', directory = '.') {
this.hostname = hostname
this.envFile = envFile
this.directory = forgivingDirectory(directory)

this.user = new User()
this._mem = {}
}

async run () {
validateGit()

const organization = await new SyncOrganization(this.hostname, current.token(), this.organizationId()).run()

// check for publicKey
if (!organization.publicKey()) {
const error = new Error(`oops, can't find orgpublickey for [@${this.slug()}]`)
error.help = '? try running [dotenvx pro sync]'
throw error
}

const pushedFilepaths = []
for (const envFilepath of this._envFilepaths()) {
const filepath = path.resolve(envFilepath)

// file must exist
if (!fs.existsSync(filepath)) {
const error = new Error(`oops, missing ${envFilepath} file (${filepath})`)
error.help = `? add one with [echo "HELLO=World" > ${envFilepath}]`
throw error
}

// get keypairs
const keypairs = new Keypair(envFilepath).run()

// publicKey must exist
const publicKeyName = Object.keys(keypairs).find(key => key.startsWith('DOTENV_PUBLIC_KEY'))
const publicKey = keypairs[publicKeyName]
if (!publicKey) {
const error = new Error(`oops, could not locate ${publicKeyName}`)
error.help = `? generate ${publicKeyName} (.env.keys) with [dotenvx encrypt]`
throw error
}

// privateKey
const privateKeyName = Object.keys(keypairs).find(key => key.startsWith('DOTENV_PRIVATE_KEY'))
const privateKey = keypairs[privateKeyName]
const privateKeyEncryptedWithOrganizationPublicKey = organization.encrypt(privateKey)

// filepath
const relativeFilepath = path.relative(gitRoot(), path.join(process.cwd(), this.directory, envFilepath)).replace(/\\/g, '/') // smartly determine path/to/.env file from repository root - where user is cd-ed inside a folder or at repo root

// text
const text = fs.readFileSync(filepath, 'utf8')

await new PostPush(this.hostname, current.token(), 'github', organization.publicKey(), this.usernameName(), relativeFilepath, publicKeyName, privateKeyName, publicKey, privateKeyEncryptedWithOrganizationPublicKey, text).run()

// sync org
await new SyncOrganization(this.hostname, current.token(), this.organizationId()).run()

pushedFilepaths.push(relativeFilepath)
}

return pushedFilepaths
}

slug () {
if (this._mem.slug) {
return this._mem.slug
}

const result = extractSlug(this.usernameName())
this._mem.slug = result
return result
}

usernameName () {
if (this._mem.usernameName) {
return this._mem.usernameName
}

const result = extractUsernameName(gitUrl())
this._mem.usernameName = result
return result
}

lookups () {
if (this._mem.lookups) {
return this._mem.lookups
}

const result = this.user.lookups()
this._mem.lookups = result
return result
}

organizationId () {
const id = this.lookups()[`lookup/organizationIdBySlug/${this.slug()}`]

if (!id) {
const error = new Error(`oops, can't find organization [@${this.slug()}]`)
error.help = '? try running [dotenvx pro sync] or joining organization [dotenvx pro settings orgjoin]'

throw error
}

return id
}

_envFilepaths () {
if (!Array.isArray(this.envFile)) {
return [path.join(this.directory, this.envFile)]
}

return this.envFile.map(file => path.join(this.directory, file))
}
}

module.exports = Push