All files / src ditaa.ts

23.81% Statements 5/21
0% Branches 0/9
0% Functions 0/1
23.81% Lines 5/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 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        1x   1x 1x               1x               1x                                                                                                              
/**
 * ditaa API:
 *     https://github.com/stathissideris/ditaa
 */
import * as path from "path";
 
import * as utility from "./utility";
import computeChecksum from "./lib/compute-checksum";
 
const CACHE: {
  [key: string]: {
    code: string;
    args: any[];
    svg: string;
  };
} = {};
 
/**
 * Render ditaa diagrams with `code` to svg.
 * @param code the ditaa code
 * @param args args passed to ditaa.jar
 * @return rendered svg
 */
export async function render(code: string = "", args = []): Promise<string> {
  try {
    const info = await utility.tempOpen({
      prefix: "mume_ditaa",
      suffix: ".ditaa",
    });
    await utility.writeFile(info.fd, code);
 
    const dest = (
      await utility.tempOpen({
        prefix: "mume_ditaa",
        suffix: ".svg",
      })
    ).path;
 
    let codes = code;
    if (args.length > 0) {
      codes = args.join() + code;
    }
    const checksum = computeChecksum(codes);
 
    if (
      checksum in CACHE &&
      CACHE[checksum].code === code &&
      utility.isArrayEqual(args, CACHE[checksum].args)
    ) {
      // already rendered
      return CACHE[checksum].svg;
    }
 
    await utility.execFile(
      "java",
      [
        "-Djava.awt.headless=true",
        "-jar",
        path.resolve(
          utility.extensionDirectoryPath,
          "./dependencies/ditaa/ditaa.jar",
        ),
        info.path,
        dest,
        "--svg",
      ].concat(args),
    );
    const pathToSvgWithoutVersion = dest.replace(/\?[\d\.]+$/, "");
    const svg = await utility.readFile(pathToSvgWithoutVersion);
 
    // save to cache
    CACHE[checksum] = { code, args, svg };
 
    return svg;
  } catch (error) {
    throw new Error(`Java is required to be installed.\n${error.toString()}`);
  }
}