import { program as app, Command } from '@/program.ts'; import { getConfig, writeConfig } from '@/module/get-config.ts'; import { queryLogin, queryMe, switchOrg, switchMe } from '@/query/index.ts'; import inquirer from 'inquirer'; // 导入 login 命令 // 定义login命令,支持 `-u` 和 `-p` 参数来输入用户名和密码 const loginCommand = new Command('login') .description('Login to the application') .option('-u, --username ', 'Specify username') .option('-p, --password ', 'Specify password') .action(async (options) => { const config = getConfig(); let { username, password } = options; // 如果没有传递参数,则通过交互式输入 if (!username || !password) { const answers = await inquirer.prompt([ { type: 'input', name: 'username', message: 'Enter your username:', when: () => !username, // 当 username 为空时,提示用户输入 }, { type: 'password', name: 'password', message: 'Enter your password:', mask: '*', // 隐藏输入的字符 when: () => !password, // 当 password 为空时,提示用户输入 }, ]); username = answers.username || username; password = answers.password || password; } if (config.token) { const res = await queryMe(); if (res.code === 200) { const data = res.data; if (data.username === username) { console.log('Already Login For', data.username); return; } } } const res = await queryLogin(username, password); if (res.code === 200) { console.log('登录成功'); const { token } = res.data; writeConfig({ ...config, token }); } else { console.log('登录失败', res.message || ''); } console.log('welcome', username); }); app.addCommand(loginCommand); const showMe = async () => { const me = await queryMe(); if (me.code === 200) { console.log('Me', me.data); } else { console.log('Me failed', me.message); } }; const switchOrgCommand = new Command('switchOrg').argument('', 'Switch to another organization').action(async (options) => { // console.log('options', options); const config = getConfig(); if (!config.token) { console.log('Please login first'); return; } const res = await switchOrg(options); if (res.code === 200) { const token = res.data.token; writeConfig({ ...config, token }); console.log('Switch Org Success'); showMe(); } else { console.log('Switch Org Failed', res.message || ''); } }); app.addCommand(switchOrgCommand); const switchMeCommand = new Command('switchMe').action(async () => { const config = getConfig(); if (!config.token) { console.log('Please login first'); return; } const res = await switchMe(); if (res.code === 200) { const token = res.data.token; writeConfig({ ...config, token }); console.log('Switch Me Success'); showMe(); } else { console.log('Switch Me Failed', res.message || ''); } }); app.addCommand(switchMeCommand);