UNPKG

2.63 kBJavaScriptView Raw
1"use strict";
2/*
3 * @adonisjs/sink
4 *
5 * (c) Harminder Virk <virk@adonisjs.com>
6 *
7 * For the full copyright and license information, please view the LICENSE
8 * file that was distributed with this source code.
9 */
10Object.defineProperty(exports, "__esModule", { value: true });
11exports.EnvFile = void 0;
12const NewLine_1 = require("../Formats/NewLine");
13/**
14 * Exposes the API to run mutations on `.env` file. The same variables
15 * will be added to `.env.example` with empty contents.
16 */
17class EnvFile {
18 constructor(basePath) {
19 this.basePath = basePath;
20 this.envContents = new NewLine_1.NewLineFile(this.basePath, '.env');
21 this.exampleEnvContents = new NewLine_1.NewLineFile(this.basePath, '.env.example');
22 }
23 /**
24 * Set key/value pair inside the `.env` file
25 */
26 set(key, value) {
27 const matchingLine = this.envContents.get().find((line) => line.startsWith(`${key}=`));
28 const newText = `${key}=${value}`;
29 if (matchingLine && newText !== matchingLine) {
30 this.envContents.update(matchingLine, newText);
31 return this;
32 }
33 this.envContents.add(newText);
34 this.exampleEnvContents.add(newText);
35 return this;
36 }
37 /**
38 * Returns a key/value pair of the file contents.
39 */
40 get() {
41 return this.envContents.get().reduce((result, line) => {
42 const [key, value] = line.split('=');
43 result[key.trim()] = value.trim();
44 return result;
45 }, {});
46 }
47 /**
48 * Returns a boolean telling if the file exists.
49 */
50 exists() {
51 return this.envContents.exists();
52 }
53 /**
54 * Unset a key/value pair from the `.env` and `.env.example` file
55 */
56 unset(key) {
57 const matchingLine = this.envContents.get().find((line) => line.startsWith(`${key}=`));
58 if (matchingLine) {
59 this.envContents.remove(matchingLine);
60 }
61 const exampleFileMatchingLine = this.exampleEnvContents.get().find((line) => {
62 return line.startsWith(`${key}=`);
63 });
64 if (exampleFileMatchingLine) {
65 this.exampleEnvContents.remove(exampleFileMatchingLine);
66 }
67 return this;
68 }
69 /**
70 * Commit mutations
71 */
72 commit() {
73 this.envContents.commit();
74 this.exampleEnvContents.commit();
75 }
76 /**
77 * Rollback mutations
78 */
79 rollback() {
80 this.envContents.rollback();
81 this.exampleEnvContents.rollback();
82 }
83}
84exports.EnvFile = EnvFile;