Skip to content

Commit

Permalink
Typescript (#12)
Browse files Browse the repository at this point in the history
  • Loading branch information
soberstadt authored Sep 14, 2020
1 parent 703ef27 commit 27eae08
Show file tree
Hide file tree
Showing 11 changed files with 398 additions and 68 deletions.
3 changes: 2 additions & 1 deletion babel.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ module.exports = {
node: '12'
}
}
]
],
['@babel/preset-typescript']
]
}
26 changes: 21 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,15 @@
"probot-app"
],
"scripts": {
"dev": "nodemon",
"start": "probot run ./src/bot.js",
"dev": "npm run build:watch",
"start": "probot run ./dist/bot.js",
"lint": "standard --fix",
"test": "jest && standard",
"jest": "jest --detectOpenHandles",
"test": "tsc && jest && standard",
"test:watch": "jest --watch --notify --notifyMode=change --coverage",
"build": "webpack"
"build": "serverless webpack",
"build:ts": "tsc",
"build:watch": "tsc && (tsc -w --preserveWatchOutput & nodemon)"
},
"dependencies": {
"@probot/serverless-lambda": "^0.5.0",
Expand All @@ -28,8 +31,15 @@
},
"devDependencies": {
"@babel/preset-env": "^7.11.0",
"@babel/preset-typescript": "^7.10.4",
"@types/jest": "^25.1.0",
"@types/nock": "^11.1.0",
"@types/node": "^12.12.0",
"@typescript-eslint/parser": "^2.4.0",
"babel-loader": "^8.1.0",
"babel-plugin-source-map-support": "^2.1.2",
"dotenv": "^8.2.0",
"eslint-plugin-typescript": "^0.14.0",
"jest": "^24.9.0",
"nock": "^11.4.0",
"nodemon": "^2.0.0",
Expand All @@ -39,6 +49,8 @@
"serverless-webpack": "^5.3.1",
"smee-client": "^1.1.0",
"standard": "^14.3.1",
"ts-jest": "^25.1.0",
"typescript": "^3.6.4",
"webpack": "^4.2.0",
"webpack-cli": "^3.3.11",
"webpack-node-externals": "^1.6.0"
Expand All @@ -48,10 +60,14 @@
"npm": ">= 4.0.0"
},
"standard": {
"parser": "@typescript-eslint/parser",
"env": {
"node": true,
"jest": true
}
},
"plugins": [
"typescript"
]
},
"nodemonConfig": {
"exec": "npm start",
Expand Down
41 changes: 27 additions & 14 deletions src/bot.js → src/bot.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
'use strict'
import { Application, Context, ApplicationFunction } from 'probot'
import Webhooks from '@octokit/webhooks'

// const { rollbar } = require('../config/rollbar.js')

module.exports = app => {
interface Config {
enabled: boolean,
label_name: string,
comment: boolean
}

export const MergerBot: ApplicationFunction = (app: Application) => {
const defaultConfig = {
enabled: false,
label_name: 'On Staging',
Expand All @@ -13,13 +20,14 @@ module.exports = app => {

app.log.info('Yay, the app was loaded!')

app.on('pull_request.labeled', async context => {
app.on('pull_request.labeled', async (context) => {
const senderType = context.payload.sender.type
app.log.debug(`New label added by a ${senderType}`)
if (senderType === 'Bot') return

const labelName = context.payload.label.name
const config = await loadConfig(context)
const labelPayload = context.payload as (Webhooks.WebhookPayloadPullRequest & { label: { name: string } })
const labelName = labelPayload.label.name
const config = (await loadConfig(context)) as Config
app.log.debug(`New label: ${config.label_name}, Looking for ${labelName}`)
if (labelName !== config.label_name) return
if (!config.enabled) {
Expand All @@ -38,7 +46,7 @@ module.exports = app => {
app.on(['issue_comment.created', 'issue_comment.edited'], async context => {
const message = context.payload.comment.body
if (message.match(/^merge to stag((ing)|e)$/i)) {
const config = await loadConfig(context)
const config = (await loadConfig(context)) as Config

if (!config.enabled) {
app.log.info('Comment observed, but no action taken because config is disabled.')
Expand All @@ -52,18 +60,18 @@ module.exports = app => {
})

app.on('pull_request.synchronize', async context => {
const config = await loadConfig(context)
const config = (await loadConfig(context)) as Config
if (!config.enabled) return
if (await pullRequestHasLabel(context, config.label_name)) {
await mergeBranchIntoStaging(context)
}
})

async function loadConfig (context) {
async function loadConfig(context: Context) {
return context.config('merge-bot.yml', defaultConfig)
}

async function pullRequestHasLabel (context, labelName) {
async function pullRequestHasLabel(context: Context, labelName: string): Promise<boolean> {
const { data: labels } = await context.github.issues.listLabelsOnIssue(
context.issue()
)
Expand All @@ -72,9 +80,10 @@ module.exports = app => {
return true
}
}
return false
}

async function mergeBranchIntoStaging (context) {
async function mergeBranchIntoStaging(context: Context) {
app.log.debug('attempting to merge branch into staging')
const { data: prDetails } = await context.github.pulls.get(context.issue())
const mergePayload = context.repo({
Expand All @@ -86,21 +95,25 @@ module.exports = app => {
})
}

async function addLabel (context, labelName) {
async function addLabel(context: Context, labelName: string) {
const addLabelPayload = context.issue({ labels: [labelName] })
return context.github.issues.addLabels(addLabelPayload)
}

async function addComment (message, context) {
async function addComment(message: string, context: Context) {
app.log.debug(`attempting to add comment: ${message}`)
const pullRequestComment = context.issue({ body: message })
const { data: result } = await context.github.issues.createComment(pullRequestComment)
const response = await context.github.issues.createComment(pullRequestComment)
.catch(error => { app.log.error(`error posting comment: ${error}`) })
if (response === undefined) {
return false
}
const result = response.data
app.log.debug(`comment creation result: ${result.url}`)
return result
}

async function mergeError (error, context) {
async function mergeError(error: { message: string }, context: Context) {
if (error.message === 'Merge conflict') {
await addComment(
'Merge conflict attempting to merge this into staging. Please fix manually.',
Expand Down
5 changes: 0 additions & 5 deletions src/handlers.js

This file was deleted.

3 changes: 3 additions & 0 deletions src/handlers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const { serverless } = require('@probot/serverless-lambda')
import { MergerBot } from './bot'
export const probot = serverless(MergerBot)
5 changes: 0 additions & 5 deletions src/index.js

This file was deleted.

5 changes: 5 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { Probot } from 'probot'
import { MergerBot } from './bot'

// pass a probot app as a function
Probot.run(MergerBot)
2 changes: 1 addition & 1 deletion test/bot.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { MergerBot as myProbotApp } from '../dist/bot.js'
const nock = require('nock')
// Requiring our app implementation
const myProbotApp = require('../src/bot.js')
const { Probot } = require('probot')
// Requiring our fixtures
const labeledPayload = require('./fixtures/pull_request.labeled')
Expand Down
74 changes: 74 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
{
"compilerOptions": {
/* Basic Options */
"incremental": true /* Enable incremental compilation */,
"target": "es5" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */,
"module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
"lib": [
"es2015",
"es2017"
] /* Specify library files to be included in the compilation. */,
"allowJs": true /* Allow javascript files to be compiled. */,
"checkJs": true /* Report errors in .js files. */,
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
"declaration": true /* Generates corresponding '.d.ts' file. */,
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
"sourceMap": true /* Generates corresponding '.map' file. */,
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./dist" /* Redirect output structure to the directory. */,
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./" /* Specify file to store incremental compilation information */,
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

/* Strict Type-Checking Options */
"strict": true /* Enable all strict type-checking options. */,
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */

/* Additional Checks */
"noUnusedLocals": true /* Report errors on unused locals. */,
"noUnusedParameters": true /* Report errors on unused parameters. */,
"noImplicitReturns": true /* Report error when not all code paths in function return a value. */,
"noFallthroughCasesInSwitch": true /* Report errors for fallthrough cases in switch statement. */,

/* Module Resolution Options */
"moduleResolution": "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */,
// "baseUrl": "./src" /* Base directory to resolve non-absolute module names. */,
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */

/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */

/* Advanced Options */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */,
"resolveJsonModule": true,
"pretty": false,
"skipLibCheck": true
},
"include": ["src/*.ts"],
"compileOnSave": false
}
15 changes: 15 additions & 0 deletions webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,21 @@ module.exports = {
performance: {
hints: false
},
resolve: {
extensions: ['.js', '.jsx', '.ts', '.tsx']
},
module: {
rules: [
{
// Include ts, tsx, js, and jsx files.
test: /\.(ts|js)x?$/,
exclude: /node_modules/,
use: [
'babel-loader'
]
}
]
},
plugins: [
new webpack.EnvironmentPlugin({
SOURCEMAP_VERSION: sourcemapVersion
Expand Down
Loading

0 comments on commit 27eae08

Please sign in to comment.