62 lines
1.9 KiB
JavaScript
62 lines
1.9 KiB
JavaScript
"use strict";
|
|
|
|
const fs = require("fs");
|
|
const path = require("path");
|
|
|
|
const ENV_PATH = path.join(__dirname, "..", ".env");
|
|
|
|
function parseLine(line) {
|
|
const trimmed = line.trim();
|
|
if (!trimmed || trimmed.startsWith("#")) return null;
|
|
|
|
const eq = trimmed.indexOf("=");
|
|
if (eq === -1) return null;
|
|
|
|
const key = trimmed.slice(0, eq).trim();
|
|
if (!key || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) return null;
|
|
|
|
let value = trimmed.slice(eq + 1).trim();
|
|
if (
|
|
(value.startsWith('"') && value.endsWith('"')) ||
|
|
(value.startsWith("'") && value.endsWith("'"))
|
|
) {
|
|
value = value.slice(1, -1);
|
|
}
|
|
|
|
return { key, value };
|
|
}
|
|
|
|
// .env を読み込み process.env に反映する。.env ファイルの値を常に正として扱い、
|
|
// 実行環境に同名の変数が既に存在していても .env の値で上書きする。
|
|
function loadEnv(envPath = ENV_PATH) {
|
|
if (!fs.existsSync(envPath)) return;
|
|
|
|
const lines = fs.readFileSync(envPath, "utf8").split(/\r?\n/);
|
|
for (const line of lines) {
|
|
const parsed = parseLine(line);
|
|
if (!parsed) continue;
|
|
process.env[parsed.key] = parsed.value;
|
|
}
|
|
}
|
|
|
|
// .env 内の KEY=... 行を書き換える(無ければ末尾に追加)。process.env も更新する。
|
|
// LW_SHAREDRIVE_ID の永続化に使用する。
|
|
function updateEnvValue(key, value, envPath = ENV_PATH) {
|
|
const text = fs.existsSync(envPath) ? fs.readFileSync(envPath, "utf8") : "";
|
|
const linePattern = new RegExp(`^${key}=.*$`, "m");
|
|
const newLine = `${key}=${value}`;
|
|
|
|
let newText;
|
|
if (linePattern.test(text)) {
|
|
newText = text.replace(linePattern, newLine);
|
|
} else {
|
|
const separator = text.length === 0 || text.endsWith("\n") ? "" : "\n";
|
|
newText = `${text}${separator}${newLine}\n`;
|
|
}
|
|
|
|
fs.writeFileSync(envPath, newText, "utf8");
|
|
process.env[key] = value;
|
|
}
|
|
|
|
module.exports = { loadEnv, updateEnvValue, ENV_PATH };
|