All files / src/reader reader.ts

91.18% Statements 31/34
93.33% Branches 14/15
60% Functions 3/5
91.18% Lines 31/34
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 7813x 13x 13x         13x         13x 34x 34x 34x 34x 34x   34x   34x 763x 744x     763x 19x 12x   19x 19x     763x 34x 34x   34x 34x 34x       34x                 34x     53x         3x   50x                     13x      
import * as fs from "fs";
import { Line } from "./line";
import { Query } from "./query";
 
/**
 * Grabs the querie(s) from the --file flag
 */
export function getQueryFromFile(file: string): Query[] {
  const contents = fs.readFileSync(file, "utf8");
  return putContentIntoLines(contents);
}
 
export function putContentIntoLines(contents: string): Query[] {
  let lineNumber = 1;
  const queriesFromFile: Query[] = [];
  let currentQueryContent: string = "";
  let query = new Query();
  const skipChars = ["", "\n", "\r\n"];
 
  contents = stripComments(contents);
 
  for (let i = 0; i < contents.length; i++) {
    if (!skipChars.includes(contents[i])) {
      currentQueryContent += contents[i];
    }
 
    if (contents[i] === "\n") {
      if (currentQueryContent.length > 0) {
        query.lines.push(new Line(currentQueryContent, lineNumber));
      }
      currentQueryContent = "";
      lineNumber++;
    }
 
    if (contents[i] === ";") {
      Eif (currentQueryContent.length > 0) {
        query.lines.push(new Line(currentQueryContent, lineNumber));
      }
      queriesFromFile.push(query);
      query = new Query();
      currentQueryContent = "";
    }
  }
 
  return queriesFromFile;
}
 
/**
 * 1. Split on new line
 * 2. Filter out any lines that start with a comment
 * 3. Rejoin the lines together as a single string.
 */
function stripComments(content: string): string {
  return content
    .split("\n")
    .map(line => {
      if (
        line.startsWith("--") ||
        line.startsWith("#") ||
        line.startsWith("/*")
      ) {
        return "";
      } else {
        return line;
      }
    })
    .join("\n");
}
 
/**
 * Grabs the query from the --query flag
 * Line is always 0 since there are no
 * lines on the terminal.
 */
export function getQueryFromLine(query: string): Query[] {
  return putContentIntoLines(query);
}