fnos-cli 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,300 @@
1
+ # fnos-cli
2
+
3
+ 飞牛 fnOS 系统的命令行客户端 (CLI)
4
+
5
+ ## 简介
6
+
7
+ fnos-cli 是一个用于与飞牛 fnOS 系统交互的命令行工具,通过 WebSocket 协议连接到 fnOS 服务器,提供资源监控、存储管理、系统信息查询、用户管理、网络管理、文件操作和 UPS 状态监控等功能。
8
+
9
+ ## 功能特性
10
+
11
+ - 🔐 **安全的认证机制** - 支持登录/登出,凭证加密保存
12
+ - 📊 **资源监控** - CPU、GPU、内存、磁盘、网络监控
13
+ - 💾 **存储管理** - 查看存储信息、磁盘列表、SMART 信息
14
+ - ℹ️ **系统信息** - 主机名、版本、硬件信息、运行时间等
15
+ - 👤 **用户管理** - 用户信息、用户组、权限管理
16
+ - 🌐 **网络管理** - 网络接口信息、网络检测
17
+ - 📁 **文件操作** - 文件列表、创建目录、删除文件
18
+ - 🔋 **UPS 监控** - UPS 状态信息
19
+ - 📝 **灵活的输出格式** - 支持 JSON 原始输出和格式化输出
20
+ - 🐛 **多级日志** - 支持 info、debug、silly 三种日志级别
21
+
22
+ ## 安装
23
+
24
+ ### 前置要求
25
+
26
+ - Node.js >= 16.0.0
27
+ - npm >= 8.0.0
28
+
29
+ ### 从 npm 安装
30
+
31
+ ```bash
32
+ npm install -g fnos-cli
33
+ ```
34
+
35
+ ### 从源码安装
36
+
37
+ ```bash
38
+ git clone <repository-url>
39
+ cd fnos-cli
40
+ npm install
41
+ npm link
42
+ ```
43
+
44
+ ## 快速开始
45
+
46
+ ### 1. 登录
47
+
48
+ 首次使用需要登录到 fnOS 系统:
49
+
50
+ ```bash
51
+ fnos login -e <endpoint> -u <username> -p <password>
52
+ ```
53
+
54
+ 例如:
55
+
56
+ ```bash
57
+ fnos login -e nas-9.timandes.net:5666 -u SystemMonitor -p yourpassword
58
+ ```
59
+
60
+ 登录成功后,凭证会保存在 `~/.fnos/settings.json` 文件中,后续命令无需重复输入。
61
+
62
+ ### 2. 使用命令
63
+
64
+ 登录后即可执行各种命令:
65
+
66
+ ```bash
67
+ # 查看 CPU 使用情况
68
+ fnos resmon.cpu
69
+
70
+ # 查看存储信息
71
+ fnos store.general
72
+
73
+ # 查看系统信息
74
+ fnos sysinfo.getHostName
75
+
76
+ # 列出文件
77
+ fnos file.ls --path /home/user
78
+ ```
79
+
80
+ ### 3. 登出
81
+
82
+ 如需清除保存的凭证:
83
+
84
+ ```bash
85
+ fnos logout
86
+ ```
87
+
88
+ ## 命令参考
89
+
90
+ ### 全局选项
91
+
92
+ | 选项 | 说明 |
93
+ |------|------|
94
+ | `--raw` | 输出原始 JSON 响应 |
95
+ | `-v` | 显示 info 级别日志(输出到 stderr) |
96
+ | `-vv` | 显示 debug 级别日志(输出到 stderr) |
97
+ | `-vvv` | 显示 silly 级别日志(输出到 stderr) |
98
+ | `-h, --help` | 显示帮助信息 |
99
+ | `-V, --version` | 显示版本信息 |
100
+
101
+ **注意**:
102
+ - 命令结果输出到 **stdout**
103
+ - 所有日志输出到 **stderr**
104
+ - 默认情况下(无 `-v`),只显示错误日志到 stderr
105
+ - 使用 `-v`、`-vv`、`-vvv` 可以控制日志详细程度
106
+
107
+ **输出重定向示例**:
108
+
109
+ ```bash
110
+ # 只保存命令结果,忽略所有日志
111
+ fnos resmon.cpu > output.json 2>/dev/null
112
+
113
+ # 只保存日志,忽略命令结果
114
+ fnos resmon.cpu -v 2>log.txt 1>/dev/null
115
+
116
+ # 分别保存命令结果和日志
117
+ fnos resmon.cpu -v > output.json 2>log.txt
118
+
119
+ # 查看命令结果,隐藏日志
120
+ fnos resmon.cpu 2>/dev/null
121
+ ```
122
+
123
+ ### 资源监控命令
124
+
125
+ | 命令 | 说明 |
126
+ |------|------|
127
+ | `fnos resmon.cpu` | CPU 资源监控 |
128
+ | `fnos resmon.gpu` | GPU 资源监控 |
129
+ | `fnos resmon.mem` | 内存资源监控 |
130
+ | `fnos resmon.disk` | 磁盘资源监控 |
131
+ | `fnos resmon.net` | 网络资源监控 |
132
+ | `fnos resmon.gen --items <items>` | 通用资源监控 |
133
+
134
+ 示例:
135
+
136
+ ```bash
137
+ fnos resmon.cpu --raw
138
+ fnos resmon.gen --items storeSpeed,netSpeed,cpuBusy,memPercent
139
+ ```
140
+
141
+ ### 存储管理命令
142
+
143
+ | 命令 | 说明 |
144
+ |------|------|
145
+ | `fnos store.general` | 存储通用信息 |
146
+ | `fnos store.calcSpace` | 计算存储空间 |
147
+ | `fnos store.listDisk [--noHotSpare]` | 列出磁盘信息 |
148
+ | `fnos store.diskSmart --disk <disk>` | 获取磁盘 SMART 信息 |
149
+ | `fnos store.state [--name] [--uuid]` | 获取存储状态 |
150
+
151
+ 示例:
152
+
153
+ ```bash
154
+ fnos store.listDisk --noHotSpare false
155
+ fnos store.diskSmart --disk nvme0n1
156
+ ```
157
+
158
+ ### 系统信息命令
159
+
160
+ | 命令 | 说明 |
161
+ |------|------|
162
+ | `fnos sysinfo.getHostName` | 获取主机名 |
163
+ | `fnos sysinfo.getTrimVersion` | 获取 Trim 版本 |
164
+ | `fnos sysinfo.getMachineId` | 获取机器 ID |
165
+ | `fnos sysinfo.getHardwareInfo` | 获取硬件信息 |
166
+ | `fnos sysinfo.getUptime` | 获取系统运行时间 |
167
+
168
+ ### 用户管理命令
169
+
170
+ | 命令 | 说明 |
171
+ |------|------|
172
+ | `fnos user.info` | 获取用户信息 |
173
+ | `fnos user.listUG` | 列出用户和组 |
174
+ | `fnos user.groupUsers` | 获取用户分组信息 |
175
+ | `fnos user.isAdmin` | 检查当前用户是否为管理员 |
176
+
177
+ ### 网络管理命令
178
+
179
+ | 命令 | 说明 |
180
+ |------|------|
181
+ | `fnos network.list [--type]` | 列出网络信息 |
182
+ | `fnos network.detect --ifName <name>` | 检测网络接口 |
183
+
184
+ 示例:
185
+
186
+ ```bash
187
+ fnos network.list --type 0
188
+ fnos network.detect --ifName eth0
189
+ ```
190
+
191
+ ### 文件操作命令
192
+
193
+ | 命令 | 说明 |
194
+ |------|------|
195
+ | `fnos file.ls [--path]` | 列出文件和目录 |
196
+ | `fnos file.mkdir --path <path>` | 创建目录 |
197
+ | `fnos file.rm --files <files> [--moveToTrashbin]` | 删除文件或目录 |
198
+
199
+ 示例:
200
+
201
+ ```bash
202
+ fnos file.ls --path /home/user
203
+ fnos file.mkdir --path /home/user/newdir
204
+ fnos file.rm --files file1.txt,file2.txt --moveToTrashbin false
205
+ ```
206
+
207
+ ### SAC 命令
208
+
209
+ | 命令 | 说明 |
210
+ |------|------|
211
+ | `fnos sac.upsStatus` | 获取 UPS 状态信息 |
212
+
213
+ ## 配置文件
214
+
215
+ fnos 将配置和凭证保存在用户主目录下的 `.fnos` 文件夹中:
216
+
217
+ - `~/.fnos/settings.json` - 登录凭证(文件权限 600)
218
+ - `~/.fnos/logs/` - 日志文件目录
219
+
220
+ ## 日志
221
+
222
+ ### 日志输出
223
+
224
+ - **控制台输出**:所有日志输出到 **stderr**(标准错误流)
225
+ - **文件输出**:日志文件保存在 `~/.fnos/logs/` 目录
226
+ - **命令输出**:命令结果输出到 **stdout**(标准输出流)
227
+
228
+ ### 日志级别
229
+
230
+ | 级别 | 说明 | 使用方式 |
231
+ |------|------|----------|
232
+ | `error` | 仅错误信息 | 默认(无 `-v`) |
233
+ | `info` | 常规信息 | 使用 `-v` |
234
+ | `debug` | 调试信息 | 使用 `-vv` |
235
+ | `silly` | 详细信息 | 使用 `-vvv` |
236
+
237
+ ### 日志文件
238
+
239
+ 日志文件按日期和随机数命名,格式为:`fnos-YYYY-MM-DD-{random}.log`
240
+
241
+ 日志文件始终记录所有级别的日志(从 error 到 silly),不受 `-v` 参数影响。
242
+
243
+ ### 默认行为
244
+
245
+ - **不使用 `-v`**:只显示错误日志到 stderr,命令结果输出到 stdout
246
+ - **使用 `-v`**:显示 info 及以上级别的日志到 stderr
247
+ - **使用 `-vv`**:显示 debug 及以上级别的日志到 stderr
248
+ - **使用 `-vvv`**:显示所有级别的日志到 stderr
249
+
250
+ 这种设计遵循 Unix 工具的最佳实践,让用户可以灵活地分别处理命令输出和日志。
251
+
252
+ ## 开发
253
+
254
+ ### 项目结构
255
+
256
+ ```
257
+ fnos-cli/
258
+ ├── bin/
259
+ │ └── fnos # 可执行文件
260
+ ├── src/
261
+ │ ├── commands/ # 命令实现
262
+ │ │ ├── auth.js # 认证命令
263
+ │ │ └── index.js # 命令注册
264
+ │ ├── utils/ # 工具函数
265
+ │ │ ├── client.js # FnosClient 包装器
266
+ │ │ ├── formatter.js # 输出格式化
267
+ │ │ ├── logger.js # 日志配置
268
+ │ │ └── settings.js # 设置管理
269
+ │ ├── constants.js # 常量定义
270
+ │ └── index.js # CLI 入口
271
+ ├── constitution.md # 项目原则
272
+ ├── package.json # 项目配置
273
+ └── README.md # 本文件
274
+ ```
275
+
276
+ ### 运行测试
277
+
278
+ ```bash
279
+ npm test
280
+ ```
281
+
282
+ ## 依赖项
283
+
284
+ - [fnos](https://www.npmjs.com/package/fnos) @ 0.2.0 - fnOS TypeScript SDK
285
+ - [commander](https://www.npmjs.com/package/commander) @ 11.1.0 - 命令行框架
286
+ - [winston](https://www.npmjs.com/package/winston) @ 3.19.0 - 日志框架
287
+
288
+ ## 许可证
289
+
290
+ Apache License 2.0
291
+
292
+ ## 贡献
293
+
294
+ 欢迎提交 Issue 和 Pull Request!
295
+
296
+
297
+ ## 致谢
298
+
299
+ 感谢 飞牛fnOS 团队提供的优质NAS系统。
300
+
package/bin/fnos ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+
3
+ require('../src/index.js');
package/package.json ADDED
@@ -0,0 +1,3 @@
1
+ {
2
+ "name": "fnos-cli",
3
+ "version": "0.1.0", "description": "CLI client for 飞牛 fnOS system", "main": "src/index.js", "bin": {"fnos": "./bin/fnos"}, "scripts": {"start": "node src/index.js", "test": "mocha test/**/*.test.js"}, "keywords": ["fnos", "cli", "nas"], "author": "", "license": "Apache-2.0", "dependencies": {"commander": "^11.1.0", "fnos": "^0.2.0", "winston": "^3.19.0"}, "devDependencies": {"chai": "^5.3.3", "mocha": "^10.8.2"}}
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Authentication commands (login, logout)
3
+ */
4
+
5
+ const { Command } = require('commander');
6
+ const settings = require('../utils/settings');
7
+ const { createClient } = require('../utils/client');
8
+ const { logger } = require('../utils/logger');
9
+
10
+ /**
11
+ * Register login command
12
+ * @param {Command} program - Commander program instance
13
+ */
14
+ function registerLoginCommand(program) {
15
+ program
16
+ .command('login')
17
+ .description('Login to fnOS system and save credentials')
18
+ .requiredOption('-e, --endpoint <endpoint>', 'Server endpoint (e.g., nas-9.timandes.net:5666)')
19
+ .requiredOption('-u, --username <username>', 'Username')
20
+ .requiredOption('-p, --password <password>', 'Password')
21
+ .action(async (options) => {
22
+ try {
23
+ const { endpoint, username, password } = options;
24
+
25
+ logger.info('Logging in...');
26
+ const client = await createClient({ endpoint, username, password, timeout: 60 });
27
+ logger.info('Login successful! Credentials saved.');
28
+ client.close();
29
+ process.exit(0);
30
+ } catch (error) {
31
+ logger.error(`Login failed: ${error.message}`);
32
+ process.exit(3);
33
+ }
34
+ });
35
+ }
36
+
37
+ /**
38
+ * Register logout command
39
+ * @param {Command} program - Commander program instance
40
+ */
41
+ function registerLogoutCommand(program) {
42
+ program
43
+ .command('logout')
44
+ .description('Logout and clear saved credentials')
45
+ .action(() => {
46
+ try {
47
+ if (settings.exists()) {
48
+ settings.clear();
49
+ console.log('Logged out successfully. Credentials cleared.');
50
+ } else {
51
+ console.log('No saved credentials found.');
52
+ }
53
+ process.exit(0);
54
+ } catch (error) {
55
+ logger.error(`Logout failed: ${error.message}`);
56
+ process.exit(1);
57
+ }
58
+ });
59
+ }
60
+
61
+ module.exports = { registerLoginCommand, registerLogoutCommand };
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Command registration helper
3
+ */
4
+
5
+ const { COMMAND_MAPPING } = require('../constants');
6
+ const { createClient, getSDKInstance } = require('../utils/client');
7
+ const { formatOutput } = require('../utils/formatter');
8
+ const { logger } = require('../utils/logger');
9
+
10
+ /**
11
+ * Register all dynamic commands based on COMMAND_MAPPING
12
+ * @param {Command} program - Commander program instance
13
+ */
14
+ function registerCommands(program) {
15
+ for (const [commandName, config] of Object.entries(COMMAND_MAPPING)) {
16
+ for (const [subCommandName, commandConfig] of Object.entries(config.commands)) {
17
+ // Create combined command name (e.g., "resmon.cpu")
18
+ const fullCommandName = `${commandName}.${subCommandName}`;
19
+
20
+ // Create command
21
+ const cmd = program.command(fullCommandName)
22
+ .description(commandConfig.description);
23
+
24
+ // Add parameters
25
+ if (commandConfig.params) {
26
+ commandConfig.params.forEach(param => {
27
+ const optionName = `--${param}`;
28
+ const description = `${param} parameter`;
29
+ if (param === 'disk' || param === 'path' || param === 'ifName' || param === 'files') {
30
+ cmd.requiredOption(optionName + ' <value>', `${description} (required)`);
31
+ } else {
32
+ cmd.option(optionName + ' <value>', description);
33
+ }
34
+ });
35
+ }
36
+
37
+ // Add action handler
38
+ cmd.action(async (options) => {
39
+ try {
40
+ // Get global options from root command
41
+ const globalOptions = program.opts();
42
+
43
+ // Validate required parameters
44
+ if (commandConfig.params) {
45
+ const requiredParams = ['disk', 'path', 'ifName', 'files'];
46
+ for (const param of requiredParams) {
47
+ if (commandConfig.params.includes(param) && !options[param]) {
48
+ console.error(`Error: --${param} is required for this command.`);
49
+ process.exit(4);
50
+ }
51
+ }
52
+ }
53
+
54
+ // Create client (will use saved credentials from settings)
55
+ const client = await createClient({
56
+ timeout: 60
57
+ });
58
+
59
+ // Get SDK instance
60
+ const sdkInstance = getSDKInstance(client, config.className);
61
+
62
+ // Prepare method arguments
63
+ const args = [];
64
+ const timeoutFirstClasses = ['ResourceMonitor', 'User', 'SystemInfo', 'SAC'];
65
+
66
+ if (commandConfig.params) {
67
+ commandConfig.params.forEach(param => {
68
+ if (options[param] !== undefined) {
69
+ let value = options[param];
70
+ // Handle comma-separated lists
71
+ if (param === 'files' || param === 'items') {
72
+ if (typeof value === 'string') {
73
+ value = value.split(',').map(s => s.trim());
74
+ } else if (!Array.isArray(value)) {
75
+ value = [value];
76
+ }
77
+ }
78
+ // Handle boolean parameters
79
+ if (param === 'noHotSpare' || param === 'moveToTrashbin') {
80
+ value = value === 'false' ? false : value;
81
+ }
82
+ // Handle numeric parameters
83
+ if (param === 'type') {
84
+ value = parseInt(value, 10);
85
+ }
86
+ args.push(value);
87
+ }
88
+ });
89
+ }
90
+
91
+ // Add timeout based on class pattern
92
+ if (timeoutFirstClasses.includes(config.className)) {
93
+ // Timeout first pattern: (timeout, params...)
94
+ args.unshift(10000);
95
+ } else {
96
+ // Timeout last pattern: (params..., timeout)
97
+ args.push(10000);
98
+ }
99
+
100
+ // Execute method
101
+ logger.info(`Executing ${config.className}.${commandConfig.method}...`);
102
+ const result = await sdkInstance[commandConfig.method](...args);
103
+
104
+ // Format output
105
+ console.log(formatOutput(result, globalOptions.raw));
106
+
107
+ // Close connection
108
+ client.close();
109
+ process.exit(0);
110
+ } catch (error) {
111
+ logger.error(`Command failed: ${error.message}`);
112
+ const globalOptions = program.opts();
113
+ if (globalOptions.debug || globalOptions.silly) {
114
+ console.error(error);
115
+ }
116
+ process.exit(1);
117
+ }
118
+ });
119
+ }
120
+ }
121
+ }
122
+
123
+ module.exports = { registerCommands };