|
| 1 | +import fs from 'fs' |
| 2 | +import yaml from 'js-yaml' |
| 3 | +import path from 'path' |
| 4 | +import updateDotenv from 'update-dotenv' |
| 5 | +import { GitHubAPI } from './github' |
| 6 | + |
| 7 | +export class ManifestCreation { |
| 8 | + get pkg () { |
| 9 | + let pkg: any |
| 10 | + try { |
| 11 | + pkg = require(path.join(process.cwd(), 'package.json')) |
| 12 | + } catch (e) { |
| 13 | + pkg = {} |
| 14 | + } |
| 15 | + return pkg |
| 16 | + } |
| 17 | + |
| 18 | + public async createWebhookChannel () { |
| 19 | + try { |
| 20 | + // tslint:disable:no-var-requires |
| 21 | + const SmeeClient = require('smee-client') |
| 22 | + await this.updateEnv({ WEBHOOK_PROXY_URL: await SmeeClient.createChannel() }) |
| 23 | + } catch (err) { |
| 24 | + // Smee is not available, so we'll just move on |
| 25 | + // tslint:disable:no-console |
| 26 | + console.warn('Unable to connect to smee.io, try restarting your server.') |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + public getManifest (pkg: any, baseUrl: any) { |
| 31 | + let manifest: any = {} |
| 32 | + try { |
| 33 | + const file = fs.readFileSync(path.join(process.cwd(), 'app.yml'), 'utf8') |
| 34 | + manifest = yaml.safeLoad(file) |
| 35 | + } catch (err) { |
| 36 | + // App config does not exist, which is ok. |
| 37 | + if (err.code !== 'ENOENT') { |
| 38 | + throw err |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + const generatedManifest = JSON.stringify(Object.assign({ |
| 43 | + description: manifest.description || pkg.description, |
| 44 | + hook_attributes: { |
| 45 | + url: process.env.WEBHOOK_PROXY_URL || `${baseUrl}/` |
| 46 | + }, |
| 47 | + name: manifest.name || pkg.name, |
| 48 | + public: manifest.public || true, |
| 49 | + redirect_url: `${baseUrl}/probot/setup`, |
| 50 | + // TODO: add setup url |
| 51 | + // setup_url:`${baseUrl}/probot/success`, |
| 52 | + url: manifest.url || pkg.homepage || pkg.repository |
| 53 | + }, manifest)) |
| 54 | + |
| 55 | + return generatedManifest |
| 56 | + } |
| 57 | + |
| 58 | + public async createAppFromCode (code: any) { |
| 59 | + const github = GitHubAPI() |
| 60 | + const response = await github.request({ |
| 61 | + headers: { accept: 'application/vnd.github.fury-preview+json' }, |
| 62 | + method: 'POST', |
| 63 | + url: `/app-manifests/${code}/conversions` |
| 64 | + }) |
| 65 | + |
| 66 | + const { id, webhook_secret, pem } = response.data |
| 67 | + await this.updateEnv({ |
| 68 | + APP_ID: id.toString(), |
| 69 | + PRIVATE_KEY: pem, |
| 70 | + WEBHOOK_SECRET: webhook_secret |
| 71 | + }) |
| 72 | + |
| 73 | + return response.data.html_url |
| 74 | + } |
| 75 | + |
| 76 | + private async updateEnv (env: any) { |
| 77 | + return updateDotenv(env) |
| 78 | + } |
| 79 | + |
| 80 | + get createAppUrl () { |
| 81 | + const githubHost = process.env.GHE_HOST || `github.com` |
| 82 | + return `http://${githubHost}/settings/apps/new` |
| 83 | + } |
| 84 | +} |
0 commit comments