update async functions

This commit is contained in:
Philipp Kunz 2017-03-08 14:50:41 +01:00
parent d9b8eb3bf0
commit a54015da16
10 changed files with 197 additions and 236 deletions

View File

@ -1,15 +1,13 @@
import * as plugins from './npmci.plugins' import * as plugins from './npmci.plugins'
import {bash} from './npmci.bash' import { bash } from './npmci.bash'
export let command = () => { export let command = async () => {
let done = plugins.q.defer() let wrappedCommand: string = ''
let wrappedCommand: string = '' let argvArray = process.argv
let argvArray = process.argv for (let i = 3; i < argvArray.length; i++) {
for (let i = 3; i < argvArray.length; i++) { wrappedCommand = wrappedCommand + argvArray[i]
wrappedCommand = wrappedCommand + argvArray[i] if (i + 1 !== argvArray.length) { wrappedCommand = wrappedCommand + ' ' }
if (i + 1 !== argvArray.length) { wrappedCommand = wrappedCommand + ' ' } }
} await bash(wrappedCommand)
bash(wrappedCommand) return
done.resolve()
return done.promise
} }

View File

@ -4,16 +4,14 @@ import * as plugins from './npmci.plugins'
import * as paths from './npmci.paths' import * as paths from './npmci.paths'
export interface INpmciOptions { export interface INpmciOptions {
globalNpmTools: string[] globalNpmTools: string[]
} }
export let getConfig = () => { export let getConfig = async (): Promise<INpmciOptions> => {
let done = q.defer<INpmciOptions>() let npmciNpmextra = new plugins.npmextra.Npmextra(paths.cwd)
let npmciNpmextra = new plugins.npmextra.Npmextra(paths.cwd) let defaultConfig: INpmciOptions = {
let defaultConfig: INpmciOptions = { globalNpmTools: []
globalNpmTools: [] }
} let npmciConfig = npmciNpmextra.dataFor<INpmciOptions>('npmci', defaultConfig)
let npmciConfig = npmciNpmextra.dataFor<INpmciOptions>('npmci', defaultConfig) return npmciConfig
done.resolve(npmciConfig)
return done.promise
} }

View File

@ -1,7 +1,7 @@
import * as plugins from './npmci.plugins' import * as plugins from './npmci.plugins'
import * as paths from './npmci.paths' import * as paths from './npmci.paths'
import {GitRepo} from 'smartstring' import { GitRepo } from 'smartstring'
import {Dockerfile} from './npmci.build.docker' import { Dockerfile } from './npmci.build.docker'
export let repo: GitRepo export let repo: GitRepo
if (process.env.CI_BUILD_REPO) repo = new GitRepo(process.env.CI_BUILD_REPO) if (process.env.CI_BUILD_REPO) repo = new GitRepo(process.env.CI_BUILD_REPO)
@ -11,48 +11,47 @@ export let buildStage: string = process.env.CI_BUILD_STAGE
// handling config between commands // handling config between commands
export let dockerRegistry: string // will be set by npmci.prepare export let dockerRegistry: string // will be set by npmci.prepare
export let setDockerRegistry = (dockerRegistryArg: string) => { export let setDockerRegistry = (dockerRegistryArg: string) => {
dockerRegistry = dockerRegistryArg dockerRegistry = dockerRegistryArg
} }
export let dockerFilesBuilt: Dockerfile[] = [] export let dockerFilesBuilt: Dockerfile[] = []
export let dockerFiles: Dockerfile[] = [] export let dockerFiles: Dockerfile[] = []
export let config = { export let config = {
dockerRegistry: undefined, // this will be set later on store dockerRegistry: undefined, // this will be set later on store
dockerFilesBuilt: dockerFilesBuilt, dockerFilesBuilt: dockerFilesBuilt,
dockerFiles: dockerFiles, dockerFiles: dockerFiles,
project: undefined project: undefined
} }
export let configStore = () => { export let configStore = () => {
config.dockerRegistry = dockerRegistry config.dockerRegistry = dockerRegistry
plugins.smartfile.memory.toFsSync( plugins.smartfile.memory.toFsSync(
JSON.stringify(config), JSON.stringify(config),
paths.NpmciPackageConfig paths.NpmciPackageConfig
) )
} }
let configLoad = () => { let configLoad = () => {
// internal config to transfer information in between npmci shell calls // internal config to transfer information in between npmci shell calls
try { try {
plugins.lodash.assign(config,plugins.smartfile.fs.toObjectSync(paths.NpmciPackageConfig,'json')) plugins.lodash.assign(config, plugins.smartfile.fs.toObjectSync(paths.NpmciPackageConfig, 'json'))
} } catch (err) {
catch (err) { configStore()
configStore() plugins.beautylog.log('config initialized!')
plugins.beautylog.log('config initialized!') }
}
// project config // project config
try { try {
if (!config.project) { if (!config.project) {
config.project = plugins.smartfile.fs.toObjectSync(paths.NpmciProjectDir,'npmci.json') config.project = plugins.smartfile.fs.toObjectSync(paths.NpmciProjectDir, 'npmci.json')
plugins.beautylog.ok('project config found!') plugins.beautylog.ok('project config found!')
}; };
} }
catch (err) { catch (err) {
config.project = {} config.project = {}
plugins.beautylog.log('no project config found, so proceeding with default behaviour!') plugins.beautylog.log('no project config found, so proceeding with default behaviour!')
} }
config.dockerRegistry ? dockerRegistry = config.dockerRegistry : void(0) config.dockerRegistry ? dockerRegistry = config.dockerRegistry : void (0)
config.dockerFilesBuilt ? dockerFilesBuilt = config.dockerFilesBuilt : void(0) config.dockerFilesBuilt ? dockerFilesBuilt = config.dockerFilesBuilt : void (0)
} }
configLoad() configLoad()

View File

@ -2,8 +2,12 @@ import * as plugins from './npmci.plugins'
import * as configModule from './npmci.config' import * as configModule from './npmci.config'
import { bash, bashNoError } from './npmci.bash' import { bash, bashNoError } from './npmci.bash'
import { nvmAvailable } from './npmci.bash' import { nvmAvailable } from './npmci.bash'
export let install = (versionArg) => {
let done = plugins.q.defer() /**
* Install a specific version of node
* @param versionArg
*/
export let install = async (versionArg) => {
plugins.beautylog.log(`now installing node version ${versionArg}`) plugins.beautylog.log(`now installing node version ${versionArg}`)
let version: string let version: string
if (versionArg === 'stable') { if (versionArg === 'stable') {
@ -16,30 +20,28 @@ export let install = (versionArg) => {
version = versionArg version = versionArg
}; };
if (nvmAvailable) { if (nvmAvailable) {
bash(`nvm install ${version} && nvm alias default ${version}`) await bash(`nvm install ${version} && nvm alias default ${version}`)
plugins.beautylog.success(`Node version ${version} successfully installed!`) plugins.beautylog.success(`Node version ${version} successfully installed!`)
} else { } else {
plugins.beautylog.warn('Nvm not in path so staying at installed node version!') plugins.beautylog.warn('Nvm not in path so staying at installed node version!')
}; };
bash('node -v') await bash('node -v')
bash('npm -v') await bash('npm -v')
// lets look for further config // lets look for further config
configModule.getConfig() configModule.getConfig()
.then(configArg => { .then(async configArg => {
plugins.beautylog.log('Now checking for needed global npm tools...') plugins.beautylog.log('Now checking for needed global npm tools...')
for (let npmTool of configArg.globalNpmTools) { for (let npmTool of configArg.globalNpmTools) {
plugins.beautylog.info(`Checking for global "${npmTool}"`) plugins.beautylog.info(`Checking for global "${npmTool}"`)
let whichOutput = bashNoError(`which ${npmTool}`) let whichOutput: string = await bashNoError(`which ${npmTool}`)
let toolAvailable: boolean = !((/not\sfound/.test(whichOutput)) || whichOutput === '') let toolAvailable: boolean = !((/not\sfound/.test(whichOutput)) || whichOutput === '')
if (toolAvailable) { if (toolAvailable) {
plugins.beautylog.log(`Tool ${npmTool} is available`) plugins.beautylog.log(`Tool ${npmTool} is available`)
} else { } else {
plugins.beautylog.info(`globally installing ${npmTool} from npm`) plugins.beautylog.info(`globally installing ${npmTool} from npm`)
bash(`npm install ${npmTool} -q -g`) await bash(`npm install ${npmTool} -q -g`)
} }
} }
plugins.beautylog.success('all global npm tools specified in npmextra.json are now available!') plugins.beautylog.success('all global npm tools specified in npmextra.json are now available!')
done.resolve()
}) })
return done.promise
} }

View File

@ -1,5 +1,5 @@
import * as plugins from './npmci.plugins' import * as plugins from './npmci.plugins'
import {bash} from './npmci.bash' import { bash } from './npmci.bash'
import * as env from './npmci.env' import * as env from './npmci.env'
import * as sshModule from './npmci.ssh' import * as sshModule from './npmci.ssh'
@ -9,85 +9,74 @@ import * as sshModule from './npmci.ssh'
/** /**
* defines possible prepare services * defines possible prepare services
*/ */
export type TPrepService = 'npm' | 'docker' | 'docker-gitlab' | 'ssh'; export type TPrepService = 'npm' | 'docker' | 'docker-gitlab' | 'ssh'
/** /**
* authenticates npm with token from env var * authenticates npm with token from env var
*/ */
let npm = function(){ let npm = async () => {
let done = plugins.q.defer() let npmrcPrefix: string = '//registry.npmjs.org/:_authToken='
let npmToken: string = process.env.NPMCI_TOKEN_NPM
let npmrcPrefix: string = '//registry.npmjs.org/:_authToken=' let npmrcFileString: string = npmrcPrefix + npmToken
let npmToken: string = process.env.NPMCI_TOKEN_NPM if (npmToken) {
let npmrcFileString = npmrcPrefix + npmToken plugins.beautylog.info('found access token')
} else {
if (npmToken) { plugins.beautylog.error('no access token found! Exiting!')
plugins.beautylog.info('found access token') process.exit(1)
} else { }
plugins.beautylog.error('no access token found! Exiting!') plugins.smartfile.memory.toFsSync(npmrcFileString, '/root/.npmrc')
process.exit(1) return
}
plugins.smartfile.memory.toFsSync(npmrcFileString,'/root/.npmrc')
done.resolve()
return done.promise
} }
/** /**
* logs in docker * logs in docker
*/ */
let docker = function(){ let docker = async () => {
let done = plugins.q.defer() env.setDockerRegistry('docker.io')
env.setDockerRegistry('docker.io') let dockerRegex = /^([a-zA-Z0-9\.]*)\|([a-zA-Z0-9\.]*)/
let dockerRegex = /^([a-zA-Z0-9\.]*)\|([a-zA-Z0-9\.]*)/ if (!process.env.NPMCI_LOGIN_DOCKER) {
if (!process.env.NPMCI_LOGIN_DOCKER) { plugins.beautylog.error('You have to specify Login Data to the Docker Registry')
plugins.beautylog.error('You have to specify Login Data to the Docker Registry') process.exit(1)
process.exit(1) }
} plugins.shelljs.exec('docker login -u gitlab-ci-token -p ' + process.env.CI_BUILD_TOKEN + ' ' + 'registry.gitlab.com') // Always also login to GitLab Registry
plugins.shelljs.exec('docker login -u gitlab-ci-token -p ' + process.env.CI_BUILD_TOKEN + ' ' + 'registry.gitlab.com') // Always also login to GitLab Registry let dockerRegexResultArray = dockerRegex.exec(process.env.NPMCI_LOGIN_DOCKER)
let dockerRegexResultArray = dockerRegex.exec(process.env.NPMCI_LOGIN_DOCKER) let username = dockerRegexResultArray[1]
let username = dockerRegexResultArray[1] let password = dockerRegexResultArray[2]
let password = dockerRegexResultArray[2] plugins.shelljs.exec('docker login -u ' + username + ' -p ' + password)
plugins.shelljs.exec('docker login -u ' + username + ' -p ' + password) return
done.resolve()
return done.promise
} }
/** /**
* prepare docker for gitlab registry * prepare docker for gitlab registry
*/ */
let dockerGitlab = function(){ let dockerGitlab = async () => {
let done = plugins.q.defer() env.setDockerRegistry('registry.gitlab.com')
env.setDockerRegistry('registry.gitlab.com') plugins.shelljs.exec('docker login -u gitlab-ci-token -p ' + process.env.CI_BUILD_TOKEN + ' ' + 'registry.gitlab.com')
plugins.shelljs.exec('docker login -u gitlab-ci-token -p ' + process.env.CI_BUILD_TOKEN + ' ' + 'registry.gitlab.com') return
done.resolve()
return done.promise
} }
/** /**
* prepare ssh * prepare ssh
*/ */
let ssh = function(){ let ssh = async () => {
let done = plugins.q.defer() await sshModule.ssh()
sshModule.ssh()
.then(done.resolve)
return done.promise
} }
/** /**
* the main exported prepare function * the main exported prepare function
* @param servieArg describes the service to prepare * @param servieArg describes the service to prepare
*/ */
export let prepare = function(serviceArg: TPrepService){ export let prepare = async (serviceArg: TPrepService) => {
switch (serviceArg) { switch (serviceArg) {
case 'npm': case 'npm':
return npm() return await npm()
case 'docker': case 'docker':
return docker() return await docker()
case 'docker-gitlab': case 'docker-gitlab':
return dockerGitlab() return await dockerGitlab()
case 'ssh': case 'ssh':
return ssh() return await ssh()
default: default:
break break
} }
} }

View File

@ -1,49 +1,46 @@
import * as plugins from './npmci.plugins' import * as plugins from './npmci.plugins'
import {prepare} from './npmci.prepare' import { prepare } from './npmci.prepare'
import {bash} from './npmci.bash' import { bash } from './npmci.bash'
import * as NpmciEnv from './npmci.env' import * as NpmciEnv from './npmci.env'
import * as NpmciBuildDocker from './npmci.build.docker' import * as NpmciBuildDocker from './npmci.build.docker'
/** /**
* type of supported services * type of supported services
*/ */
export type TPubService = 'npm' | 'docker'; export type TPubService = 'npm' | 'docker'
/** /**
* the main exported publish function. * the main exported publish function.
* @param pubServiceArg references targeted service to publish to * @param pubServiceArg references targeted service to publish to
*/ */
export let publish = (pubServiceArg: TPubService = 'npm') => { export let publish = async (pubServiceArg: TPubService = 'npm') => {
switch (pubServiceArg) { switch (pubServiceArg) {
case 'npm': case 'npm':
return publishNpm() return await publishNpm()
case 'docker': case 'docker':
return publishDocker() return await publishDocker()
} }
} }
/** /**
* tries to publish current cwd to NPM registry * tries to publish current cwd to NPM registry
*/ */
let publishNpm = function(){ let publishNpm = async () => {
let done = plugins.q.defer() await prepare('npm')
prepare('npm') .then(async function () {
.then(function(){ await bash('npm publish')
bash('npm publish') plugins.beautylog.ok('Done!')
plugins.beautylog.ok('Done!') })
done.resolve()
})
return done.promise
} }
/** /**
* tries to pubish current cwd to Docker registry * tries to pubish current cwd to Docker registry
*/ */
let publishDocker = function(){ let publishDocker = async () => {
let done = plugins.q.defer() return await NpmciBuildDocker.readDockerfiles()
NpmciBuildDocker.readDockerfiles() .then(NpmciBuildDocker.pullDockerfileImages)
.then(NpmciBuildDocker.pullDockerfileImages) .then(NpmciBuildDocker.pushDockerfiles)
.then(NpmciBuildDocker.pushDockerfiles) .then(dockerfileArray => {
.then(done.resolve) return dockerfileArray
return done.promise })
} }

View File

@ -25,7 +25,7 @@ let smartsocketClientConstructorOptions = {
/** /**
* the main run function to submit a service to a servezone * the main run function to submit a service to a servezone
*/ */
export let run = (configArg) => { export let run = async (configArg) => {
new plugins.smartsocket.SmartsocketClient( new plugins.smartsocket.SmartsocketClient(
smartsocketClientConstructorOptions smartsocketClientConstructorOptions
) )

View File

@ -6,45 +6,43 @@ let sshInstance: plugins.smartssh.SshInstance
/** /**
* checks for ENV vars in form of NPMCI_SSHKEY_* and deploys any found ones * checks for ENV vars in form of NPMCI_SSHKEY_* and deploys any found ones
*/ */
export let ssh = () => { export let ssh = async () => {
let done = plugins.q.defer() sshInstance = new plugins.smartssh.SshInstance() // init ssh instance
sshInstance = new plugins.smartssh.SshInstance() // init ssh instance plugins.smartparam.forEachMinimatch(process.env, 'NPMCI_SSHKEY_*', evaluateSshEnv)
plugins.smartparam.forEachMinimatch(process.env,'NPMCI_SSHKEY_*',evaluateSshEnv) if (!process.env.NPMTS_TEST) {
if (!process.env.NPMTS_TEST) { sshInstance.writeToDisk()
sshInstance.writeToDisk() } else {
} else { plugins.beautylog.log('In test mode, so not storing SSH keys to disk!')
plugins.beautylog.log('In test mode, so not storing SSH keys to disk!') };
};
done.resolve()
return done.promise
} }
/** /**
* gets called for each found SSH ENV Var and deploys it * gets called for each found SSH ENV Var and deploys it
*/ */
let evaluateSshEnv = (sshkeyEnvVarArg) => { let evaluateSshEnv = async (sshkeyEnvVarArg) => {
let resultArray = sshRegex.exec(sshkeyEnvVarArg) let resultArray = sshRegex.exec(sshkeyEnvVarArg)
let sshKey = new plugins.smartssh.SshKey() let sshKey = new plugins.smartssh.SshKey()
plugins.beautylog.info('Found SSH identity for ' + resultArray[1]) plugins.beautylog.info('Found SSH identity for ' + resultArray[1])
if (notUndefined(resultArray[1])) { if (notUndefined(resultArray[1])) {
plugins.beautylog.log('---> host defined!') plugins.beautylog.log('---> host defined!')
sshKey.host = resultArray[1] sshKey.host = resultArray[1]
} }
if (notUndefined(resultArray[2])) { if (notUndefined(resultArray[2])) {
plugins.beautylog.log('---> privKey defined!') plugins.beautylog.log('---> privKey defined!')
sshKey.privKeyBase64 = resultArray[2] sshKey.privKeyBase64 = resultArray[2]
}; };
if (notUndefined(resultArray[3])) { if (notUndefined(resultArray[3])) {
'---> pubKey defined!' '---> pubKey defined!'
sshKey.pubKeyBase64 = resultArray[3] sshKey.pubKeyBase64 = resultArray[3]
}; };
sshInstance.addKey(sshKey) sshInstance.addKey(sshKey)
return
} }
/** /**
* checks if not undefined * checks if not undefined
*/ */
let notUndefined = (stringArg: string) => { let notUndefined = (stringArg: string) => {
return (stringArg && stringArg !== 'undefined' && stringArg !== '##') return (stringArg && stringArg !== 'undefined' && stringArg !== '##')
} }

View File

@ -1,49 +1,32 @@
import * as plugins from './npmci.plugins' import * as plugins from './npmci.plugins'
import {bash} from './npmci.bash' import { bash } from './npmci.bash'
import {install} from './npmci.install' import { install } from './npmci.install'
import * as env from './npmci.env' import * as env from './npmci.env'
import * as NpmciBuildDocker from './npmci.build.docker' import * as NpmciBuildDocker from './npmci.build.docker'
export let test = (versionArg) => { export let test = async (versionArg): Promise<void> => {
let done = plugins.q.defer() if (versionArg === 'docker') {
if (versionArg === 'docker') { await testDocker()
testDocker() } else {
.then(() => { await install(versionArg)
done.resolve() .then(npmDependencies)
}) .then(npmTest)
} else { }
install(versionArg)
.then(npmDependencies)
.then(npmTest)
.then(() => {
done.resolve()
})
}
return done.promise
} }
let npmDependencies = function(){ let npmDependencies = async () => {
let done = plugins.q.defer() plugins.beautylog.info('now installing dependencies:')
plugins.beautylog.info('now installing dependencies:') await bash('npm install')
bash('npm install')
done.resolve()
return done.promise
} }
let npmTest = () => { let npmTest = async () => {
let done = plugins.q.defer() plugins.beautylog.info('now starting tests:')
plugins.beautylog.info('now starting tests:') await bash('npm test')
bash('npm test')
done.resolve()
return done.promise
} }
let testDocker = function(){ let testDocker = async (): Promise<NpmciBuildDocker.Dockerfile[]> => {
let done = plugins.q.defer() return await NpmciBuildDocker.readDockerfiles()
NpmciBuildDocker.readDockerfiles() .then(NpmciBuildDocker.pullDockerfileImages)
.then(NpmciBuildDocker.pullDockerfileImages) .then(NpmciBuildDocker.testDockerfiles)
.then(NpmciBuildDocker.testDockerfiles)
.then(done.resolve)
return done.promise
} }

View File

@ -4,27 +4,24 @@ import { bash } from './npmci.bash'
let triggerValueRegex = /^([a-zA-Z0-9\.]*)\|([a-zA-Z0-9\.]*)\|([a-zA-Z0-9\.]*)\|([a-zA-Z0-9\.]*)\|?([a-zA-Z0-9\.\-\/]*)/ let triggerValueRegex = /^([a-zA-Z0-9\.]*)\|([a-zA-Z0-9\.]*)\|([a-zA-Z0-9\.]*)\|([a-zA-Z0-9\.]*)\|?([a-zA-Z0-9\.\-\/]*)/
export let trigger = function () { export let trigger = async () => {
let done = plugins.q.defer() plugins.beautylog.info('now running triggers')
plugins.beautylog.info('now running triggers') plugins.smartparam.forEachMinimatch(process.env, 'NPMCI_TRIGGER_*', evaluateTrigger)
plugins.smartparam.forEachMinimatch(process.env, 'NPMCI_TRIGGER_*', evaluateTrigger)
done.resolve()
return done.promise
} }
let evaluateTrigger = (triggerEnvVarArg) => { let evaluateTrigger = async (triggerEnvVarArg) => {
let triggerRegexResultArray = triggerValueRegex.exec(triggerEnvVarArg) let triggerRegexResultArray = triggerValueRegex.exec(triggerEnvVarArg)
let regexDomain = triggerRegexResultArray[1] let regexDomain = triggerRegexResultArray[1]
let regexProjectId = triggerRegexResultArray[2] let regexProjectId = triggerRegexResultArray[2]
let regexProjectTriggerToken = triggerRegexResultArray[3] let regexProjectTriggerToken = triggerRegexResultArray[3]
let regexRefName = triggerRegexResultArray[4] let regexRefName = triggerRegexResultArray[4]
let regexTriggerName let regexTriggerName
if (triggerRegexResultArray.length === 6) { if (triggerRegexResultArray.length === 6) {
regexTriggerName = triggerRegexResultArray[5] regexTriggerName = triggerRegexResultArray[5]
} else { } else {
regexTriggerName = 'Unnamed Trigger' regexTriggerName = 'Unnamed Trigger'
} }
plugins.beautylog.info('Found Trigger!') plugins.beautylog.info('Found Trigger!')
plugins.beautylog.log('triggering build for ref ' + regexRefName + ' of ' + regexTriggerName) plugins.beautylog.log('triggering build for ref ' + regexRefName + ' of ' + regexTriggerName)
plugins.request.post('https://gitlab.com/api/v3/projects/' + regexProjectId + '/trigger/builds', { form: { token: regexProjectTriggerToken, ref: regexRefName } }) plugins.request.post('https://gitlab.com/api/v3/projects/' + regexProjectId + '/trigger/builds', { form: { token: regexProjectTriggerToken, ref: regexRefName } })
} }