Skip to content

Commit

Permalink
Handle relative path resolving
Browse files Browse the repository at this point in the history
  • Loading branch information
orta committed Sep 19, 2017
1 parent ee23f44 commit c56d816
Show file tree
Hide file tree
Showing 7 changed files with 57 additions and 170 deletions.
54 changes: 24 additions & 30 deletions dangerfile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,21 @@

import { DangerDSL } from "./source/dsl/DangerDSL"
declare var danger: DangerDSL
declare var results: any
// declare var results: any
declare function warn(params: string): void
declare function fail(params: string): void
declare function message(params: string): void
declare function markdown(params: string): void
// declare function message(params: string): void
// declare function markdown(params: string): void
declare function schedule(promise: Promise<any | void>): void
declare function schedule(promise: () => Promise<any | void>): void
declare function schedule(callback: (resolve) => void): void
declare function schedule(callback: (resolve: any) => void): void

import * as fs from "fs"
import * as child_process from "child_process"
import { distanceInWords } from "date-fns"

// For some reason we're getting type errors on this includes module?
// Wonder if we could move to the includes function in ES2015?
import * as includes from "lodash.includes"
const sentence = danger.utils.sentence

schedule(async () => {
// Request a CHANGELOG entry if not declared #trivial
const hasChangelog = includes(danger.git.modified_files, "changelog.md")
const isTrivial = includes(danger.github.pr.body + danger.github.pr.title, "#trivial")
const hasChangelog = danger.git.modified_files.includes("changelog.md")
const isTrivial = (danger.github.pr.body + danger.github.pr.title).includes("#trivial")
const isGreenkeeper = danger.github.pr.user.login === "greenkeeper"

if (!hasChangelog && !isTrivial && !isGreenkeeper) {
Expand All @@ -33,7 +27,7 @@ schedule(async () => {
// Politely ask for their name on the entry too
const changelogDiff = await danger.git.diffForFile("changelog.md")
const contributorName = danger.github.pr.user.login
if (changelogDiff && !includes(changelogDiff.diff, contributorName)) {
if (changelogDiff && changelogDiff.diff.includes(contributorName)) {
warn("Please add your GitHub name to the changelog entry, so we can attribute you correctly.")
}
}
Expand All @@ -48,23 +42,23 @@ schedule(yarn())
// This also serves as the "one true DSL" for a Danger run against a PR
// which tools can then work against.

// import dtsGenerator from "./scripts/danger-dts"
// const currentDTS = dtsGenerator()
// const savedDTS = fs.readFileSync("source/danger.d.ts").toString()
// if (currentDTS !== savedDTS) {
// const message = "There are changes to the Danger DSL which are not reflected in the current danger.d.ts."
// const idea = "Please run <code>yarn declarations</code> and update this PR."
// fail(`${message}<br/><i>${idea}</i>`)
// }
import dtsGenerator from "./scripts/danger-dts"
const currentDTS = dtsGenerator()
const savedDTS = fs.readFileSync("source/danger.d.ts").toString()
if (currentDTS !== savedDTS) {
const message = "There are changes to the Danger DSL which are not reflected in the current danger.d.ts."
const idea = "Please run <code>yarn declarations</code> and update this PR."
fail(`${message}<br/><i>${idea}</i>`)
}

// Always ensure we name all CI providers in the README. These
// regularly get forgotten on a PR adding a new one.
const sentence = danger.utils.sentence

// import { realProviders } from "./source/ci_source/providers"
// import Fake from "./source/ci_source/providers/Fake"
// const readme = fs.readFileSync("README.md").toString()
// const names = realProviders.map(p => new p({}).name)
// const missing = names.filter(n => !readme.includes(n))
// if (missing.length) {
// warn(`These providers are missing from the README: ${sentence(missing)}`)
// }
import { realProviders } from "./source/ci_source/providers"
const readme = fs.readFileSync("README.md").toString()
const names = realProviders.map(p => new p({}).name)
const missing = names.filter(n => !readme.includes(n))
if (missing.length) {
warn(`These providers are missing from the README: ${sentence(missing)}`)
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@
"parse-link-header": "^1.0.1",
"pinpoint": "^1.1.0",
"rfc6902": "^1.3.0",
"vm2": "patriksimek/vm2",
"vm2": "patriksimek/vm2#custom_files",
"voca": "^1.2.0"
},
"optionalDependencies": {}
Expand Down
129 changes: 0 additions & 129 deletions source/ambient.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,132 +14,3 @@ declare module "parse-link-header"
declare module "pinpoint"

declare module "*/package.json"

declare module "vm2" {
/**
* Require options for a VM
*/
export interface VMRequire {
/** Array of allowed builtin modules, accepts ["*"] for all (default: none) */
builtin?: string[]
/*
* `host` (default) to require modules in host and proxy them to sandbox. `sandbox` to load, compile and
* require modules in sandbox. Builtin modules except `events` always required in host and proxied to sandbox
*/
context?: "host" | "sandbox"
/** `true` or an array of allowed external modules (default: `false`) */
external?: boolean | string[]
/** Array of modules to be loaded into NodeVM on start. */
import?: string[]
/** Restricted path where local modules can be required (default: every path). */
root?: string
/** Collection of mock modules (both external or builtin). */
mock?: any
}

/**
* A custom compiler function for all of the JS that comes
* into the VM
*/
type CompilerFunction = (code: string, filename: string) => string

/**
* Options for creating a NodeVM
*/
export interface VMOptions {
/**
* `javascript` (default) or `coffeescript` or custom compiler function (which receives the code, and it's filepath).
* The library expects you to have coffee-script pre-installed if the compiler is set to `coffeescript`.
*/
compiler?: "javascript" | "coffeescript" | CompilerFunction
/** VM's global object. */
sandbox?: any
/**
* Script timeout in milliseconds. Timeout is only effective on code you run through `run`.
* Timeout is NOT effective on any method returned by VM.
*/
timeout?: number
}

/**
* Options specific o
*/
export interface NodeVMOptions extends VMOptions {
/** `inherit` to enable console, `redirect` to redirect to events, `off` to disable console (default: `inherit`). */
console?: "inherit" | "redirect"
/** `true` or an object to enable `require` optionss (default: `false`). */
require?: true | VMRequire
/** `true` to enable VMs nesting (default: `false`). */
nesting?: boolean
/** `commonjs` (default) to wrap script into CommonJS wrapper, `none` to retrieve value returned by the script. */
wrapper?: "commonjs" | "none"
}

/**
* A VM with behavior more similar to running inside Node.
*/
export class NodeVM {
constructor(options?: NodeVMOptions)
/** Runs the code */
run(js: string, path: string): any
/** Runs the VMScript object */
run(script: VMScript): any

/** Freezes the object inside VM making it read-only. Not available for primitive values. */
freeze(object: any, name: string): any
/** Protects the object inside VM making impossible to set functions as it's properties. Not available for primitive values. */
protect(object: any, name: string): any
/** Require a module in VM and return it's exports. */
require(module: string): any
}

/**
* VM is a simple sandbox, without `require` feature, to synchronously run an untrusted code.
* Only JavaScript built-in objects + Buffer are available. Scheduling functions
* (`setInterval`, `setTimeout` and `setImmediate`) are not available by default.
*/
export class VM {
constructor(options?: VMOptions)
/** Runs the code */
run(js: string): any
/** Runs the VMScript object */
run(script: VMScript): any
/** Freezes the object inside VM making it read-only. Not available for primitive values. */
freeze(object: any, name: string): any
/** Protects the object inside VM making impossible to set functions as it's properties. Not available for primitive values */
protect(object: any, name: string): any

/**
* Create NodeVM and run code inside it.
*
* @param {String} script Javascript code.
* @param {String} [filename] File name (used in stack traces only).
* @param {Object} [options] VM options.
*/
static code(script: string, filename: string, options: NodeVMOptions): NodeVM

/**
* Create NodeVM and run script from file inside it.
*
* @param {String} [filename] File name (used in stack traces only).
* @param {Object} [options] VM options.
*/
static file(filename: string, options: NodeVMOptions): NodeVM
}

/**
* You can increase performance by using pre-compiled scripts.
* The pre-compiled VMScript can be run later multiple times. It is important to note that the code is not bound
* to any VM (context); rather, it is bound before each run, just for that run.
*/
export class VMScript {
constructor(code: string, path: string)
/** Wraps the code */
wrap(prefix: string, postfix: string): VMScript
/** Compiles the code. If called multiple times, the code is only compiled once. */
compile(): any
}

/** Custom Error class */
export class VMError extends Error {}
}
2 changes: 1 addition & 1 deletion source/danger.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ declare module "danger" {
after: any
/** If both before & after are arrays, then you optionally get what is added. Empty if no additional objects. */
added?: any[]
/** If both before & after are arrays, then you optionally get what is removed. Empty ig no removed objects. */
/** If both before & after are arrays, then you optionally get what is removed. Empty if no removed objects. */
removed?: any[]
}

Expand Down
19 changes: 18 additions & 1 deletion source/runner/DangerfileRunner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ export async function createDangerfileRuntimeEnvironment(dangerfileContext: Dang
}

function compile(code: string, filename: string) {
console.log("Compile: ", filename)
const filetype = path.extname(filename)
let result = code
if (hasNativeTypeScript && !filename.includes("node_modules") && filetype.startsWith(".ts")) {
Expand Down Expand Up @@ -92,23 +93,38 @@ export async function runDangerfileEnvironment(
originalContents: string | undefined,
environment: NodeVMOptions
): Promise<DangerResults> {
;(environment as any).sourceExtensions = ["ts"]
const vm = new NodeVM(environment)

// Require our dangerfile
originalContents = originalContents || fs.readFileSync(filename, "utf8")
let content = cleanDangerfile(originalContents)

// TODO: Relative imports get TS/Babel
console.log("STARTED")

// var Module = require("module")
// var originalRequire = Module.prototype.require

// https://medium.freecodecamp.org/requiring-modules-in-node-js-everything-you-need-to-know-e7fbd119be8
// Module.prototype.require = function() {
// //do your thing here
// console.log(arguments)
// console.log("HI")
// return originalRequire.apply(this, arguments)
// }

// if (hasNativeTypeScript) {
console.log("TS!")
const originalJsHandler = require.extensions[".js"]

require.extensions["ts"] = (_: NodeModule, filename: string) => {
console.log("TS ext")
const file = fs.readFileSync(filename, "utf8")
const compiled = typescriptify(file)
originalJsHandler(compiled, filename)
}
console.log("TS?")

try {
vm.run(content, filename)

Expand Down Expand Up @@ -176,6 +192,7 @@ export function cleanDangerfile(contents: string): string {
}

const typescriptify = (content: string): string => {
console.log("typescriptify")
const ts = require("typescript") // tslint:disable-line
let result = ts.transpileModule(content, {})
return result.outputText
Expand Down
6 changes: 3 additions & 3 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,16 @@
"module": "commonjs",
"moduleResolution": "node",
"pretty": true,
"target": "es5",
"target": "es2015",
"outDir": "distribution",
"lib": ["es5", "es2015"]
"lib": ["es5", "es2017"]
},
"formatCodeOptions": {
"indentSize": 2,
"tabSize": 2
},
"exclude": [
"dangerfile.ts",
// "dangerfile.ts",
"scripts",
"node_modules",
"source/**/fixtures/*",
Expand Down
15 changes: 10 additions & 5 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1271,13 +1271,14 @@ cssom@0.3.x, "cssom@>= 0.3.0 < 0.4.0", "cssom@>= 0.3.2 < 0.4.0":
cssom "0.3.x"

danger-plugin-yarn@^1.0.0:
version "1.1.1"
resolved "https://registry.yarnpkg.com/danger-plugin-yarn/-/danger-plugin-yarn-1.1.1.tgz#6ecd03e221ae8b71f51e089150a766e8c8d4b2c3"
version "1.2.0"
resolved "https://registry.yarnpkg.com/danger-plugin-yarn/-/danger-plugin-yarn-1.2.0.tgz#3681db67f71e65dc6dd7a0a31ef3e7f56e9b29d3"
dependencies:
date-fns "^1.28.5"
lodash.flatten "^4.4.0"
lodash.includes "^4.3.0"
node-fetch "^1.7.1"
semver "^5.4.1"
optionalDependencies:
esdoc "^0.5.2"

Expand Down Expand Up @@ -3935,6 +3936,10 @@ sax@^1.1.4, sax@^1.2.1:
version "5.3.0"
resolved "https://registry.yarnpkg.com/semver/-/semver-5.3.0.tgz#9b2ce5d3de02d17c6012ad326aa6b4d0cf54f94f"

semver@^5.4.1:
version "5.4.1"
resolved "https://registry.yarnpkg.com/semver/-/semver-5.4.1.tgz#e059c09d8571f0540823733433505d3a2f00b18e"

semver@~5.0.1:
version "5.0.3"
resolved "https://registry.yarnpkg.com/semver/-/semver-5.0.3.tgz#77466de589cd5d3c95f138aa78bc569a3cb5d27a"
Expand Down Expand Up @@ -4462,9 +4467,9 @@ verror@1.3.6:
dependencies:
extsprintf "1.0.2"

vm2@patriksimek/vm2:
version "3.4.6"
resolved "https://codeload.github.com/patriksimek/vm2/tar.gz/0711926ba6e6fbfb89277d8033cfd11b69888e46"
vm2@patriksimek/vm2#custom_files:
version "3.5.0"
resolved "https://codeload.github.com/patriksimek/vm2/tar.gz/7e82f90ac705fc44fad044147cb0df09b4c79a57"

voca@^1.2.0:
version "1.3.0"
Expand Down

0 comments on commit c56d816

Please sign in to comment.