hudada-cli
Version:
专为程序员准备的本地文档搜索,快捷开发工具
3 lines (2 loc) • 3.29 kB
JavaScript
import{exec as o}from"child_process";import{promisify as e}from"util";import r from"chalk";import s from"path";import c from"fs/promises";import{existsSync as l}from"fs";const n=e(o);async function t(o,e){try{if(!o)return void await i();switch(o.toLowerCase()){case"add":if(!e)return console.error(r.red("请提供要添加的路径")),void console.log(r.gray("用法: my path add <路径>"));await async function(o){try{const e=s.isAbsolute(o)?o:s.resolve(process.cwd(),o);if(!l(e))return void console.error(r.red("路径不存在:"),e);const c=process.env.PATH||"";if(c.split(s.delimiter).includes(e))return void console.log(r.yellow("路径已存在于 PATH 中"));if("win32"===process.platform){const o=`setx PATH "%PATH%;${e};"`;console.log(o,"command"),await n(o)}else{const o=process.env.SHELL?.includes("zsh")?"zsh":"bash",r=`echo 'export PATH="$PATH:${e}"' >> ${"zsh"===o?"~/.zshrc":"~/.bashrc"}`;await n(r)}console.log(r.green("✓ 成功添加路径到 PATH")),console.log(r.gray("新添加:"),e),console.log(r.gray("注意: 可能需要重新打开终端才能生效"))}catch(o){console.error(r.red("添加路径失败:"),o)}}(e);break;case"remove":if(!e)return console.error(r.red("请提供要删除的路径")),void console.log(r.gray("用法: my path remove <路径>"));await async function(o){try{const e=s.isAbsolute(o)?o:s.resolve(process.cwd(),o),l=(process.env.PATH||"").split(s.delimiter);if(!l.includes(e))return void console.log(r.yellow("路径不存在于 PATH 中"));const t=l.filter((o=>o!==e)).join(s.delimiter);if("win32"===process.platform){console.log(t,"newPathString");const o=`setx PATH "${t}"`;await n(o)}else{const o=process.env.HOME,l=process.env.SHELL?.includes("zsh")?"zsh":"bash",n=s.join(o,"zsh"===l?".zshrc":".bashrc");try{const o=await c.readFile(n,"utf8");await c.writeFile(`${n}.backup`,o);const s=o.split("\n").filter((o=>{const r=o.includes("export PATH=")||o.includes("PATH="),s=o.includes(e);return!(r&&s)}));await c.writeFile(n,s.join("\n")),console.log(r.green("✓ 成功从 PATH 中移除路径")),console.log(r.gray("已移除:"),e),console.log(r.gray("配置文件已更新:"),n),console.log(r.gray("备份文件已创建:"),`${n}.backup`),console.log(r.gray("注意: 需要重新加载配置文件或重新打开终端才能生效")),console.log(r.gray("可以使用以下命令立即生效:")),console.log(r.gray(" "+("zsh"===l?"source ~/.zshrc":"source ~/.bashrc")))}catch(o){console.error(r.red("更新配置文件失败:"),o),console.log(r.yellow("建议手动编辑配置文件删除相关路径"))}}}catch(o){console.error(r.red("移除路径失败:"),o)}}(e);break;case"list":await i();break;default:console.error(r.red("无效的操作")),console.log(r.gray("支持的操作: add, remove, list"))}}catch(o){console.error(r.red("操作失败:"),o)}}async function i(){try{const o=(process.env.PATH||"").split(s.delimiter);console.log(r.cyan("\n当前系统 PATH:")),console.log(r.gray("总计: "),o.length,"个路径\n");for(let e=0;e<o.length;e++){const s=o[e],c=l(s),n=r.gray(`${(e+1).toString().padStart(2,"0")}.`);console.log(n,c?r.green("✓"):r.red("✗"),c?s:r.dim(s),c?"":r.red("(路径不存在)"))}console.log()}catch(o){console.error(r.red("获取 PATH 失败:"),o)}}export{t as managePath};