All files / lib/env merger.ts

100% Statements 120/120
100% Branches 44/44
100% Functions 18/18
100% Lines 109/109

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 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 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238    1x                           1x 1x         1x           1x                         1x 8x 8x     1x 8x 8x     1x 8x 8x     1x 8x 8x     1x 8x 8x     1x 8x 8x     1x 8x 7x 7x   7x     1x 8x 8x   7x 7x     1x 7x 7x   1x 1x     1x       7x   7x     1x         7x   7x   7x 25x 9x 9x   8x 2x 2x     8x 8x   8x 14x 2x       2x     8x 8x     7x     1x 8x 8x 7x     1x 7x 7x 7x   1x   1x       8x   8x 8x   8x 8x     1x 8x 8x   7x 7x 1x 1x     6x 6x 6x   5x     1x     8x   8x 8x 8x   7x 7x 7x 7x 7x 5x   5x       5x   5x       5x         5x         5x             2x 2x     1x 2x 2x 2x    
import { CliPrompterInterface } from "lib/cli";
import { Token, AnalyzeEnvSourceCode } from "lib/env/lexer";
import {
  ParsedEnvDocument,
  ParseEnvTokens,
  VariableDeclarationNode,
  RawLiteralNode,
  QuotedLiteralNode,
  NodeType,
  IdentifierNode,
  QuoteType,
  NewlineNode,
} from "lib/env/parser";
import { Render } from "lib/env/renderer";
import fs from "fs";
import path from "path";
import { NewlineType, Options } from "lib/options";
import { FileNotFoundError } from "./error";
 
export type NodeFs = Pick<typeof fs, "existsSync" | "readFileSync" | "writeFileSync">;
export type NodePath = Pick<typeof path, "resolve">
 
const ENCODING = "utf8";
 
export interface MergerInterface {
  merge: (options: Options) => void
}
 
export class Merger implements MergerInterface {
  private cliPrompter: CliPrompterInterface
 
  private analyzeEnvSourceCode: AnalyzeEnvSourceCode
 
  private parseEnvTokens: ParseEnvTokens
 
  private render: Render
 
  private fs: NodeFs
 
  private path: NodePath
 
  public setCliPrompter(cliPrompter: CliPrompterInterface): this {
    this.cliPrompter = cliPrompter
    return this
  }
 
  public setAnalyzeEnvSourceCode(analyzeEnvSourceCode: AnalyzeEnvSourceCode): this {
    this.analyzeEnvSourceCode = analyzeEnvSourceCode
    return this
  }
 
  public setParseEnvTokens(parseEnvTokens: ParseEnvTokens): this {
    this.parseEnvTokens = parseEnvTokens
    return this
  }
 
  public setRender(render: Render): this {
    this.render = render
    return this
  }
 
  public setFs(fs: NodeFs): this {
    this.fs = fs
    return this
  }
 
  public setPath(path: NodePath): this {
    this.path = path
    return this
  }
  
  public async merge (options: Options) {
    const distDocument = this.parseDistDocument(options);
    const localDocument = this.parseLocalDocument(options);
    const mergedDocument = await this.mergeDocuments(distDocument, localDocument, options);
 
    this.writeLocalEnvFile(options, mergedDocument);
  }
 
  private analyzeDistEnvFile (path: string): Token[] {
    const exists = this.fs.existsSync(path);
    if (!exists) throw new FileNotFoundError().setFilePath(path);
 
    const src = this.fs.readFileSync(path, { encoding: ENCODING }).toString();
    return this.analyzeEnvSourceCode(path, src);
  }
 
  private analyzeLocalEnvFile (path: string): Token[] {
    const exists = this.fs.existsSync(path);
    if (!exists) return [];
 
    const src = this.fs.readFileSync(path, { encoding: ENCODING }).toString();
    return this.analyzeEnvSourceCode(path, src);
  }
 
  private writeLocalEnvFile (
    options: Options,
    document: ParsedEnvDocument
  ) {
    const fileContent = this.render(document.abstractSyntaxTree, options);
    // TODO use resolved absolute path here
    this.fs.writeFileSync(options.localFilePath, fileContent, { encoding: ENCODING });
  }
 
  private async mergeDocuments (
    distributedDocument: ParsedEnvDocument,
    localDocument: ParsedEnvDocument,
    options: Options
  ): Promise<ParsedEnvDocument> {
    const newLocalDocument: ParsedEnvDocument = { ...localDocument };
 
    let hasBeenPrompted = false;
 
    const variableNames = Object.keys(distributedDocument.variablesByName);
    for (const name of variableNames) {
      const existsLocally = name in localDocument.variablesByName;
      if (existsLocally) continue;
 
      if (!hasBeenPrompted && options.prompts) {
        this.cliPrompter.promptUserAboutNewVariables();
        hasBeenPrompted = true;
      }
 
      const distributedVariable = distributedDocument.variablesByName[name];
      const defaultValue = getValueFromVariable(distributedVariable);
 
      let value = defaultValue
      if (options.prompts) {
        const userInputEnvironmentVariable = await this.cliPrompter.promptUserForEnvironmentVariable({
          name,
          value: defaultValue,
        });
        value = userInputEnvironmentVariable.value
      }
      
      const variable = createVariableDeclaration(name, value, options);
      addVariableToDocument(variable, newLocalDocument);
    }
 
    return newLocalDocument;
  }
 
  private parseDistDocument (options: Options): ParsedEnvDocument {
    const path = this.path.resolve(options.distFilePath)
    const tokens = this.analyzeDistEnvFile(path);
    return this.parseEnvTokens(path, tokens, options);
  }
 
  private parseLocalDocument (options: Options): ParsedEnvDocument {
    const path = this.path.resolve(options.localFilePath)
    const tokens = this.analyzeLocalEnvFile(path);
    return this.parseEnvTokens(path, tokens, options);
  }
}
 
const addVariableToDocument = (
  variable: VariableDeclarationNode,
  document: ParsedEnvDocument
) => {
  document.abstractSyntaxTree.statements.push(variable);
 
  const newline: NewlineNode = { type: NodeType.newline };
  document.abstractSyntaxTree.statements.push(newline);
 
  const { name } = variable.identifier;
  document.variablesByName[name] = variable;
};
 
const getValueFromVariable = (variable: VariableDeclarationNode): string => {
  const hasValue = !!variable.value;
  if (!hasValue) return "";
 
  const hasRawLiteral = variable.value.type === NodeType.literal;
  if (hasRawLiteral) {
    const rawLiteral = variable.value as RawLiteralNode;
    return rawLiteral.value;
  }
 
  const quotedLiteral = variable.value as QuotedLiteralNode;
  const hasContent = !!quotedLiteral.content;
  if (!hasContent) return "";
 
  return quotedLiteral.content.value;
};
 
const createVariableDeclaration = (
  name: string,
  value: string,
  { newlineType }: Options
): VariableDeclarationNode => {
  const identifier: IdentifierNode = { type: NodeType.identifier, name };
  const isEmpty = !value;
  if (isEmpty) return { type: NodeType.variableDeclaration, identifier };
 
  const hasNewlines = value.indexOf('\n') > -1 || value.indexOf('\r') > -1
  const hasSingleQuotes = value.indexOf("'") > -1;
  const hasDoubleQuotes = value.indexOf('"') > -1;
  const isQuoted = hasSingleQuotes || hasDoubleQuotes;
  if (hasNewlines || isQuoted) {
    const hasSingleAndDoubleQuotes = hasSingleQuotes && hasDoubleQuotes;
    const quoteType =
      hasSingleAndDoubleQuotes || hasSingleQuotes || hasNewlines
        ? QuoteType.double
        : QuoteType.single;
    const valueWithSafeDoubleQuotes =
      hasSingleAndDoubleQuotes ? value.replace(/"/g, '\\"') : value;
    const valueWithConvertedNewlines =
      hasNewlines
        ? getContentWithNewlineType(valueWithSafeDoubleQuotes, newlineType)
        : valueWithSafeDoubleQuotes;
 
    const rawLiteral: RawLiteralNode = {
      type: NodeType.literal,
      value: valueWithConvertedNewlines,
    };
 
    const quotedLiteral: QuotedLiteralNode = {
      type: NodeType.quotedLiteral,
      quoteType,
      content: rawLiteral,
    };
    return {
      type: NodeType.variableDeclaration,
      identifier,
      value: quotedLiteral,
    };
  }
 
  const rawLiteral: RawLiteralNode = { type: NodeType.literal, value };
  return { type: NodeType.variableDeclaration, identifier, value: rawLiteral };
};
 
const getContentWithNewlineType = (content: string, newlineType: NewlineType): string => {
  const isWindows = newlineType === NewlineType.windows
  const newlineChar = isWindows ? '\r\n' : '\n'
  return content.replace(/(?:\r\n)|(?:\r)|(?:\n)/g, newlineChar)
}