@milkmaccya2/hostswitch
Version:
A simple CLI tool to manage and switch between multiple hosts file profiles for different development environments
112 lines • 4.67 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.PermissionChecker = void 0;
const node_child_process_1 = require("node:child_process");
const fs = __importStar(require("fs-extra"));
class PermissionChecker {
async canWriteToFile(filePath) {
try {
// copySync操作に必要な権限をテストする
// 一時的なバックアップファイルでcopySync操作をシミュレート
const tempPath = `${filePath}.hostswitch-test`;
// 元ファイルの内容を読み取り
const originalContent = await fs.readFile(filePath, 'utf8');
// 一時ファイルに書き込み
await fs.writeFile(tempPath, originalContent);
// copySync操作をテスト(実際にunlink/copyを実行)
await fs.copy(tempPath, filePath, { overwrite: true });
// テスト用一時ファイルを削除
await fs.unlink(tempPath);
return true;
}
catch (_error) {
// EACCES (Permission denied) またはその他のエラーの場合はfalse
return false;
}
}
requiresSudo(_filePath) {
// sudoで実行中の場合は不要
if (this.isRunningAsSudo()) {
return false;
}
// デフォルトでhostsファイルへの書き込みはsudoが必要
return true;
}
async checkPermissions(path) {
// ファイルへの書き込み権限をチェック
return await this.canWriteToFile(path);
}
isRunningAsSudo() {
// process.getuid()が0(root)の場合、またはSUDO_USER環境変数が設定されている場合
return process.getuid?.() === 0 || process.env.SUDO_USER !== undefined;
}
async rerunWithSudo(args) {
return new Promise((resolve) => {
const command = this.buildSudoCommand(args);
const child = (0, node_child_process_1.spawn)(command[0], command.slice(1), {
stdio: 'inherit',
env: process.env,
});
child.on('exit', (code) => {
resolve({
success: code === 0,
message: code === 0 ? 'Operation completed successfully.' : 'Operation failed with sudo.',
});
});
child.on('error', (error) => {
resolve({
success: false,
message: `Failed to execute sudo: ${error.message}`,
});
});
});
}
buildSudoCommand(args) {
const executablePath = process.argv[0]; // node path
const scriptPath = process.argv[1]; // hostswitch.js path
// npm経由で実行されている場合の検出
if (scriptPath.includes('npm') || process.env.npm_execpath) {
// npm start -- switch profile -> sudo npm start -- switch profile
return ['sudo', 'npm', 'start', '--', ...args];
}
else {
// direct execution -> sudo node hostswitch.js switch profile
return ['sudo', executablePath, scriptPath, ...args];
}
}
}
exports.PermissionChecker = PermissionChecker;
//# sourceMappingURL=PermissionChecker.js.map