build.ts 11.4 KB
Newer Older
A
Asher 已提交
1 2 3 4 5
import * as cp from "child_process"
import * as fs from "fs-extra"
import Bundler from "parcel-bundler"
import * as path from "path"
import * as util from "util"
A
Asher 已提交
6 7

enum Task {
A
Asher 已提交
8 9
  Build = "build",
  Watch = "watch",
A
Asher 已提交
10 11 12
}

class Builder {
A
Asher 已提交
13 14 15 16 17 18 19 20 21 22
  private readonly rootPath = path.resolve(__dirname, "..")
  private readonly vscodeSourcePath = path.join(this.rootPath, "lib/vscode")
  private readonly buildPath = path.join(this.rootPath, "build")
  private readonly codeServerVersion: string
  private currentTask?: Task

  public constructor() {
    this.ensureArgument("rootPath", this.rootPath)
    this.codeServerVersion = this.ensureArgument(
      "codeServerVersion",
A
Anmol Sethi 已提交
23
      process.env.VERSION || require(path.join(this.rootPath, "package.json")).version,
A
Asher 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36
    )
  }

  public run(task: Task | undefined): void {
    this.currentTask = task
    this.doRun(task).catch((error) => {
      console.error(error.message)
      process.exit(1)
    })
  }

  private async task<T>(message: string, fn: () => Promise<T>): Promise<T> {
    const time = Date.now()
A
Asher 已提交
37
    this.log(`${message}...`, !process.env.CI)
A
Asher 已提交
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
    try {
      const t = await fn()
      process.stdout.write(`took ${Date.now() - time}ms\n`)
      return t
    } catch (error) {
      process.stdout.write("failed\n")
      throw error
    }
  }

  /**
   * Writes to stdout with an optional newline.
   */
  private log(message: string, skipNewline = false): void {
    process.stdout.write(`[${this.currentTask || "default"}] ${message}`)
    if (!skipNewline) {
      process.stdout.write("\n")
    }
  }

  private async doRun(task: Task | undefined): Promise<void> {
    if (!task) {
      throw new Error("No task provided")
    }

    switch (task) {
      case Task.Watch:
        return this.watch()
      case Task.Build:
        return this.build()
      default:
        throw new Error(`No task matching "${task}"`)
    }
  }

  /**
   * Make sure the argument is set. Display the value if it is.
   */
  private ensureArgument(name: string, arg?: string): string {
    if (!arg) {
      throw new Error(`${name} is missing`)
    }
    this.log(`${name} is "${arg}"`)
    return arg
  }

  /**
   * Build VS Code and code-server.
   */
  private async build(): Promise<void> {
    process.env.NODE_OPTIONS = "--max-old-space-size=32384 " + (process.env.NODE_OPTIONS || "")
    process.env.NODE_ENV = "production"

    await this.task("cleaning up old build", async () => {
      if (!process.env.SKIP_VSCODE) {
        return fs.remove(this.buildPath)
      }
      // If skipping VS Code, keep the existing build if any.
      try {
        const files = await fs.readdir(this.buildPath)
        return Promise.all(files.filter((f) => f !== "lib").map((f) => fs.remove(path.join(this.buildPath, f))))
      } catch (error) {
        if (error.code !== "ENOENT") {
          throw error
        }
      }
    })

    const commit = require(path.join(this.vscodeSourcePath, "build/lib/util")).getVersion(this.rootPath) as string
    if (!process.env.SKIP_VSCODE) {
      await this.buildVscode(commit)
    } else {
      this.log("skipping vs code build")
    }
    await this.buildCodeServer(commit)

    this.log(`final build: ${this.buildPath}`)
  }

  private async buildCodeServer(commit: string): Promise<void> {
    await this.task("building code-server", async () => {
      return util.promisify(cp.exec)("tsc --outDir ./out-build --tsBuildInfoFile ./.prod.tsbuildinfo", {
        cwd: this.rootPath,
      })
    })

    await this.task("bundling code-server", async () => {
      return this.createBundler("dist-build", commit).bundle()
    })

    await this.task("copying code-server into build directory", async () => {
      await fs.mkdirp(this.buildPath)
      await Promise.all([
        fs.copy(path.join(this.rootPath, "out-build"), path.join(this.buildPath, "out")),
        fs.copy(path.join(this.rootPath, "dist-build"), path.join(this.buildPath, "dist")),
        // For source maps and images.
        fs.copy(path.join(this.rootPath, "src"), path.join(this.buildPath, "src")),
      ])
    })

138 139
    await this.copyDependencies("code-server", this.rootPath, this.buildPath, {
      commit,
A
Asher 已提交
140
      version: this.codeServerVersion,
A
Asher 已提交
141
    })
A
Asher 已提交
142 143 144 145 146 147 148 149 150
  }

  private async buildVscode(commit: string): Promise<void> {
    await this.task("building vs code", () => {
      return util.promisify(cp.exec)("yarn gulp compile-build", { cwd: this.vscodeSourcePath })
    })

    await this.task("building builtin extensions", async () => {
      const exists = await fs.pathExists(path.join(this.vscodeSourcePath, ".build/extensions"))
A
Asher 已提交
151
      if (exists && !process.env.CI) {
A
Asher 已提交
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
        process.stdout.write("already built, skipping...")
      } else {
        await util.promisify(cp.exec)("yarn gulp compile-extensions-build", { cwd: this.vscodeSourcePath })
      }
    })

    await this.task("optimizing vs code", async () => {
      return util.promisify(cp.exec)("yarn gulp optimize --gulpfile ./coder.js", { cwd: this.vscodeSourcePath })
    })

    if (process.env.MINIFY) {
      await this.task("minifying vs code", () => {
        return util.promisify(cp.exec)("yarn gulp minify --gulpfile ./coder.js", { cwd: this.vscodeSourcePath })
      })
    }

    const vscodeBuildPath = path.join(this.buildPath, "lib/vscode")
    await this.task("copying vs code into build directory", async () => {
A
Asher 已提交
170
      await fs.mkdirp(path.join(vscodeBuildPath, "resources/linux"))
A
Asher 已提交
171
      await Promise.all([
A
Asher 已提交
172 173
        fs.move(
          path.join(this.vscodeSourcePath, `out-vscode${process.env.MINIFY ? "-min" : ""}`),
A
Anmol Sethi 已提交
174
          path.join(vscodeBuildPath, "out"),
A
Asher 已提交
175 176
        ),
        fs.copy(path.join(this.vscodeSourcePath, ".build/extensions"), path.join(vscodeBuildPath, "extensions")),
A
Asher 已提交
177 178 179 180
        fs.copy(
          path.join(this.vscodeSourcePath, "resources/linux/code.png"),
          path.join(vscodeBuildPath, "resources/linux/code.png"),
        ),
A
Asher 已提交
181 182 183
      ])
    })

184 185 186
    await this.copyDependencies("vs code", this.vscodeSourcePath, vscodeBuildPath, {
      commit,
      date: new Date().toISOString(),
A
Asher 已提交
187 188 189
    })
  }

190
  private async copyDependencies(name: string, sourcePath: string, buildPath: string, merge: object): Promise<void> {
A
Asher 已提交
191 192 193 194
    await this.task(`copying ${name} dependencies`, async () => {
      return Promise.all(
        ["node_modules", "package.json", "yarn.lock"].map((fileName) => {
          return fs.copy(path.join(sourcePath, fileName), path.join(buildPath, fileName))
A
Anmol Sethi 已提交
195
        }),
A
Asher 已提交
196 197 198
      )
    })

199 200 201 202 203 204 205 206 207 208 209
    const fileName = name === "code-server" ? "package" : "product"
    await this.task(`writing final ${name} ${fileName}.json`, async () => {
      const json = JSON.parse(await fs.readFile(path.join(sourcePath, `${fileName}.json`), "utf8"))
      return fs.writeFile(
        path.join(buildPath, `${fileName}.json`),
        JSON.stringify(
          {
            ...json,
            ...merge,
          },
          null,
A
Anmol Sethi 已提交
210 211
          2,
        ),
212 213 214
      )
    })

A
Asher 已提交
215 216
    if (process.env.MINIFY) {
      await this.task(`restricting ${name} to production dependencies`, async () => {
A
Asher 已提交
217
        await util.promisify(cp.exec)("yarn --production --ignore-scripts", { cwd: buildPath })
A
Asher 已提交
218 219 220 221 222 223 224 225 226 227
      })
    }
  }

  private async watch(): Promise<void> {
    let server: cp.ChildProcess | undefined
    const restartServer = (): void => {
      if (server) {
        server.kill()
      }
A
Asher 已提交
228
      const s = cp.fork(path.join(this.rootPath, "out/node/entry.js"), process.argv.slice(3))
A
Asher 已提交
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
      console.log(`[server] spawned process ${s.pid}`)
      s.on("exit", () => console.log(`[server] process ${s.pid} exited`))
      server = s
    }

    const vscode = cp.spawn("yarn", ["watch"], { cwd: this.vscodeSourcePath })
    const tsc = cp.spawn("tsc", ["--watch", "--pretty", "--preserveWatchOutput"], { cwd: this.rootPath })
    const bundler = this.createBundler()

    const cleanup = (code?: number | null): void => {
      this.log("killing vs code watcher")
      vscode.removeAllListeners()
      vscode.kill()

      this.log("killing tsc")
      tsc.removeAllListeners()
      tsc.kill()

      if (server) {
        this.log("killing server")
        server.removeAllListeners()
        server.kill()
      }

      this.log("killing bundler")
      process.exit(code || 0)
    }

    process.on("SIGINT", () => cleanup())
    process.on("SIGTERM", () => cleanup())

    vscode.on("exit", (code) => {
      this.log("vs code watcher terminated unexpectedly")
      cleanup(code)
    })
    tsc.on("exit", (code) => {
      this.log("tsc terminated unexpectedly")
      cleanup(code)
    })
    const bundle = bundler.bundle().catch(() => {
      this.log("parcel watcher terminated unexpectedly")
      cleanup(1)
    })
    bundler.on("buildEnd", () => {
      console.log("[parcel] bundled")
    })
A
Asher 已提交
275 276 277
    bundler.on("buildError", (error) => {
      console.error("[parcel]", error)
    })
A
Asher 已提交
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314

    vscode.stderr.on("data", (d) => process.stderr.write(d))
    tsc.stderr.on("data", (d) => process.stderr.write(d))

    // From https://github.com/chalk/ansi-regex
    const pattern = [
      "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
      "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))",
    ].join("|")
    const re = new RegExp(pattern, "g")

    /**
     * Split stdout on newlines and strip ANSI codes.
     */
    const onLine = (proc: cp.ChildProcess, callback: (strippedLine: string, originalLine: string) => void): void => {
      let buffer = ""
      if (!proc.stdout) {
        throw new Error("no stdout")
      }
      proc.stdout.setEncoding("utf8")
      proc.stdout.on("data", (d) => {
        const data = buffer + d
        const split = data.split("\n")
        const last = split.length - 1

        for (let i = 0; i < last; ++i) {
          callback(split[i].replace(re, ""), split[i])
        }

        // The last item will either be an empty string (the data ended with a
        // newline) or a partial line (did not end with a newline) and we must
        // wait to parse it until we get a full line.
        buffer = split[last]
      })
    }

    let startingVscode = false
A
Asher 已提交
315
    let startedVscode = false
A
Asher 已提交
316 317 318 319 320 321
    onLine(vscode, (line, original) => {
      console.log("[vscode]", original)
      // Wait for watch-client since "Finished compilation" will appear multiple
      // times before the client starts building.
      if (!startingVscode && line.includes("Starting watch-client")) {
        startingVscode = true
A
Asher 已提交
322 323 324 325 326
      } else if (startingVscode && line.includes("Finished compilation")) {
        if (startedVscode) {
          bundle.then(restartServer)
        }
        startedVscode = true
A
Asher 已提交
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
      }
    })

    onLine(tsc, (line, original) => {
      // tsc outputs blank lines; skip them.
      if (line !== "") {
        console.log("[tsc]", original)
      }
      if (line.includes("Watching for file changes")) {
        bundle.then(restartServer)
      }
    })
  }

  private createBundler(out = "dist", commit?: string): Bundler {
A
Asher 已提交
342 343 344 345 346 347 348 349 350 351 352 353 354 355
    return new Bundler(
      [
        path.join(this.rootPath, "src/browser/pages/app.ts"),
        path.join(this.rootPath, "src/browser/register.ts"),
        path.join(this.rootPath, "src/browser/serviceWorker.ts"),
      ],
      {
        cache: true,
        cacheDir: path.join(this.rootPath, ".cache"),
        detailedReport: true,
        minify: !!process.env.MINIFY,
        hmr: false,
        logLevel: 1,
        outDir: path.join(this.rootPath, out),
A
Asher 已提交
356
        publicUrl: `/static/${commit || "development"}/dist`,
A
Asher 已提交
357 358 359
        target: "browser",
      },
    )
A
Asher 已提交
360
  }
A
Asher 已提交
361 362
}

A
Asher 已提交
363 364
const builder = new Builder()
builder.run(process.argv[2] as Task)