UNPKG

hudada-cli

Version:

专为程序员准备的本地文档搜索,快捷开发工具

3 lines (2 loc) 2.77 kB
#!/usr/bin/env node import o from"fs/promises";import t from"chalk";import r from"os";const e="win32"===r.platform()?"C:\\Windows\\System32\\drivers\\etc\\hosts":"/etc/hosts";async function s(r,s,c){try{try{await o.access(e,o.constants.R_OK|o.constants.W_OK)}catch(o){return void console.error(t.red("无权限访问 hosts 文件,请以管理员权限运行"))}if(!r)return void await n();switch(r.toLowerCase()){case"add":if(!s||!c)return console.error(t.red("请提供 IP 和域名")),void console.log(t.gray("用法: my host add <IP> <域名>"));await async function(r,s){try{if(!function(o){const t=o.split(".");return 4===t.length&&t.every((o=>{const t=parseInt(o);return!isNaN(t)&&t>=0&&t<=255}))}(r))return void console.error(t.red("无效的 IP 地址"));const n=await o.readFile(e,"utf8"),c=n.split("\n");if(c.some((o=>{const t=o.trim().split(/\s+/);return t.length>=2&&t[1]===s})))return void console.log(t.yellow("域名已存在于 hosts 文件中"));await o.writeFile(`${e}.backup`,n);const a=`${r.padEnd(15)} ${s}`,l=n.trim()+"\n"+a+"\n";await o.writeFile(e,l),console.log(t.green("✓ 成功添加 hosts 记录")),console.log(t.gray("IP: "),r),console.log(t.gray("域名: "),s),console.log(t.gray("备份文件:"),`${e}.backup`)}catch(o){console.error(t.red("添加 hosts 记录失败:"),o)}}(s,c);break;case"remove":const r=s;if(!r)return console.error(t.red("请提供要删除的域名")),void console.log(t.gray("用法: my host remove <域名>"));await async function(r){try{const s=await o.readFile(e,"utf8"),n=s.split("\n");let c=!1;const a=n.map((o=>{const t=o.trim();if(!t||t.startsWith("#"))return o;const e=t.split(/\s+/);return e.length>=2&&e.includes(r)?(c=!0,""):o})).filter((o=>""!==o));if(!c)return void console.log(t.yellow(`未找到域名 ${r} 的记录`));await o.writeFile(`${e}.backup`,s);const l=a.join("\n").trim()+"\n";await o.writeFile(e,l),console.log(t.green("✓ 成功删除 hosts 记录")),console.log(t.gray("域名: "),r),console.log(t.gray("备份文件:"),`${e}.backup`)}catch(o){console.error(t.red("删除 hosts 记录失败:"),o)}}(r);break;case"list":await n();break;default:console.error(t.red("无效的操作")),console.log(t.gray("支持的操作: add, remove, list"))}}catch(o){console.error(t.red("操作失败:"),o)}}async function n(){try{const r=(await o.readFile(e,"utf8")).split("\n");console.log(t.cyan("\nhosts 文件内容:")),console.log(t.gray("路径:"),e),console.log(),r.forEach(((o,r)=>{const e=o.trim();e&&!e.startsWith("#")?console.log(t.white(c(`${r+1}.`,4)),o):e.startsWith("#")?console.log(t.gray(c(`${r+1}.`,4)),t.gray(o)):console.log()})),console.log()}catch(o){console.error(t.red("读取 hosts 文件失败:"),o)}}function c(o,t){return String(o).padEnd(t)}export{s as manageHosts};