qnap 0.1.6

CLI for QNAP NAS management — human-friendly output and JSON mode for agent use
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
mod client;
mod commands;
mod config;
mod output;

use anyhow::{Result, bail};
use clap::{Parser, Subcommand};

use client::QnapClient;
use config::{Config, normalize_host_input, read_password_from_stdin};

#[derive(Debug, Parser)]
#[command(name = "qnap", about = "QNAP NAS management CLI", version)]
struct Cli {
    /// Override the NAS host for this command (always HTTPS)
    #[arg(long, global = true)]
    host: Option<String>,

    /// Override the NAS username for this command
    #[arg(long, short = 'u', global = true)]
    username: Option<String>,

    /// Skip TLS certificate verification for this command
    #[arg(long, global = true, conflicts_with = "secure")]
    insecure: bool,

    /// Re-enable TLS certificate verification for this command
    #[arg(long, global = true, conflicts_with = "insecure")]
    secure: bool,

    /// Read the password from stdin instead of the saved credentials file or prompt
    #[arg(long, global = true)]
    password_stdin: bool,

    #[command(subcommand)]
    command: Command,
}

#[derive(Debug, Subcommand)]
enum Command {
    /// Save credentials and verify connectivity
    Login,

    /// Show system information (model, firmware, hostname, uptime)
    Info {
        /// Output as JSON
        #[arg(long)]
        json: bool,
    },

    /// Show system resource usage (CPU, RAM, temperature)
    Status {
        /// Output as JSON
        #[arg(long)]
        json: bool,
    },

    /// List storage volumes and disks
    Volumes {
        /// Output as JSON
        #[arg(long)]
        json: bool,
    },

    /// List shared folders
    Shares {
        /// Output as JSON
        #[arg(long)]
        json: bool,
    },

    /// File operations
    Files {
        #[command(subcommand)]
        action: FilesCommand,
    },

    /// Save raw API responses for debugging and compatibility reporting
    Dump {
        /// Directory to write response files into (created if it does not exist)
        #[arg(default_value = "./qnap-dump")]
        dir: String,
    },

    /// Show network adapter information
    Network {
        /// Output as JSON
        #[arg(long)]
        json: bool,
    },

    /// Show current saved configuration
    Config {
        /// Output as JSON
        #[arg(long)]
        json: bool,
    },

    /// Print command schema for agent use
    Schema,
}

#[derive(Debug, Subcommand)]
enum FilesCommand {
    /// List files and directories at PATH
    Ls {
        /// Remote path (e.g. /Public)
        path: String,

        /// Fetch all results, paginating past the 200-item default limit
        #[arg(long)]
        all: bool,

        /// Output as JSON
        #[arg(long)]
        json: bool,
    },

    /// Show metadata for a file or directory
    Stat {
        /// Remote path
        path: String,

        /// Output as JSON
        #[arg(long)]
        json: bool,
    },

    /// Create a directory
    Mkdir {
        /// Remote path to create (e.g. /Public/newdir)
        path: String,
    },

    /// Delete one or more files or directories
    Rm {
        /// Remote paths to delete
        #[arg(required = true)]
        paths: Vec<String>,
    },

    /// Move or rename a file or directory
    Mv {
        /// Source remote path
        src: String,
        /// Destination remote path
        dst: String,
    },

    /// Copy a file or directory
    Cp {
        /// Source remote path
        src: String,
        /// Destination remote path
        dst: String,
        /// Overwrite if destination exists
        #[arg(long)]
        overwrite: bool,
    },

    /// Upload a local file or directory to the NAS
    Upload {
        /// Local file or directory to upload
        local: std::path::PathBuf,
        /// Remote directory to upload into (e.g. /Public)
        remote_dir: String,
        /// Overwrite if file already exists
        #[arg(long)]
        overwrite: bool,
        /// Recursively upload a directory and its contents
        #[arg(long, short = 'r')]
        recursive: bool,
    },

    /// Download a file or directory from the NAS
    Download {
        /// Remote file or directory path (e.g. /Public/photos)
        remote: String,
        /// Local path to save to (defaults to name in current directory)
        local: Option<std::path::PathBuf>,
        /// Recursively download a directory and its contents
        #[arg(long, short = 'r')]
        recursive: bool,
    },

    /// Search for files matching a pattern
    Find {
        /// Remote path to search under (e.g. /Public)
        path: String,
        /// Glob pattern to match filenames (e.g. "*.txt", "backup*")
        pattern: String,
        /// Output as JSON
        #[arg(long)]
        json: bool,
    },
}

fn password_override(password_stdin: bool) -> Result<Option<String>> {
    if password_stdin {
        return Ok(Some(read_password_from_stdin()?));
    }
    Ok(None)
}

fn apply_runtime_overrides(mut config: Config, cli: &Cli) -> Result<Config> {
    if let Some(host) = &cli.host {
        config.host = Some(normalize_host_input(host)?);
    }

    if let Some(username) = &cli.username {
        let username = username.trim();
        if username.is_empty() {
            bail!("username must not be empty");
        }
        config.username = Some(username.to_string());
    }

    if cli.insecure {
        config.insecure = Some(true);
    } else if cli.secure {
        config.insecure = Some(false);
    }

    Ok(config)
}

async fn authenticated_client(
    config: &Config,
    password_override: Option<&str>,
) -> Result<QnapClient> {
    let mut client = QnapClient::new(config)?;
    let password = match password_override {
        Some(password) => password.to_string(),
        None => config.password()?,
    };
    client.login(&config.username()?, &password).await?;
    Ok(client)
}

#[tokio::main]
async fn main() -> Result<()> {
    let cli = Cli::parse();

    match &cli.command {
        Command::Login => {
            commands::login::run(
                cli.host.clone(),
                cli.username.clone(),
                cli.insecure,
                cli.secure,
                cli.password_stdin,
            )
            .await?;
        }

        Command::Schema => {
            commands::schema::run();
        }

        Command::Config { json } => {
            let config = apply_runtime_overrides(Config::load()?, &cli)?;
            commands::config_show::run(&config, *json)?;
        }

        Command::Network { json } => {
            let config = apply_runtime_overrides(Config::load()?, &cli)?;
            let password = password_override(cli.password_stdin)?;
            let client = authenticated_client(&config, password.as_deref()).await?;
            commands::network::run(&client, *json).await?;
        }

        Command::Info { json } => {
            let config = apply_runtime_overrides(Config::load()?, &cli)?;
            let password = password_override(cli.password_stdin)?;
            let client = authenticated_client(&config, password.as_deref()).await?;
            commands::info::run(&client, *json).await?;
        }

        Command::Status { json } => {
            let config = apply_runtime_overrides(Config::load()?, &cli)?;
            let password = password_override(cli.password_stdin)?;
            let client = authenticated_client(&config, password.as_deref()).await?;
            commands::status::run(&client, *json).await?;
        }

        Command::Volumes { json } => {
            let config = apply_runtime_overrides(Config::load()?, &cli)?;
            let password = password_override(cli.password_stdin)?;
            let client = authenticated_client(&config, password.as_deref()).await?;
            commands::volumes::run(&client, *json).await?;
        }

        Command::Shares { json } => {
            let config = apply_runtime_overrides(Config::load()?, &cli)?;
            let password = password_override(cli.password_stdin)?;
            let client = authenticated_client(&config, password.as_deref()).await?;
            commands::shares::run(&client, *json).await?;
        }

        Command::Dump { dir } => {
            let config = apply_runtime_overrides(Config::load()?, &cli)?;
            let password = password_override(cli.password_stdin)?;
            let client = authenticated_client(&config, password.as_deref()).await?;
            commands::dump::run(&client, std::path::Path::new(dir)).await?;
        }

        Command::Files { action } => {
            let config = apply_runtime_overrides(Config::load()?, &cli)?;
            let password = password_override(cli.password_stdin)?;
            let client = authenticated_client(&config, password.as_deref()).await?;
            match action {
                FilesCommand::Ls { path, all, json } => {
                    commands::files::list(&client, path, *all, *json).await?;
                }
                FilesCommand::Stat { path, json } => {
                    commands::files::stat(&client, path, *json).await?;
                }
                FilesCommand::Mkdir { path } => {
                    commands::files::mkdir(&client, path).await?;
                }
                FilesCommand::Rm { paths } => {
                    for path in paths {
                        commands::files::rm(&client, path).await?;
                    }
                }
                FilesCommand::Mv { src, dst } => {
                    commands::files::mv(&client, src, dst).await?;
                }
                FilesCommand::Cp {
                    src,
                    dst,
                    overwrite,
                } => {
                    commands::files::cp(&client, src, dst, *overwrite).await?;
                }
                FilesCommand::Upload {
                    local,
                    remote_dir,
                    overwrite,
                    recursive,
                } => {
                    if *recursive {
                        commands::files::upload_recursive(&client, local, remote_dir, *overwrite)
                            .await?;
                    } else {
                        commands::files::upload(&client, local, remote_dir, *overwrite).await?;
                    }
                }
                FilesCommand::Download {
                    remote,
                    local,
                    recursive,
                } => {
                    if *recursive {
                        let local_path = local.clone().unwrap_or_else(|| {
                            let name = remote
                                .trim_end_matches('/')
                                .rsplit('/')
                                .next()
                                .unwrap_or("download");
                            std::path::PathBuf::from(name)
                        });
                        commands::files::download_recursive(&client, remote, &local_path).await?;
                    } else {
                        commands::files::download(&client, remote, local.as_deref()).await?;
                    }
                }
                FilesCommand::Find {
                    path,
                    pattern,
                    json,
                } => {
                    commands::files::find(&client, path, pattern, *json).await?;
                }
            }
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::Cli;
    use clap::{Parser, error::ErrorKind};

    #[test]
    fn files_ls_requires_a_path_argument() {
        let err = Cli::try_parse_from(["qnap", "files", "ls"]).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument);
    }

    #[test]
    fn login_tls_flags_conflict() {
        let err = Cli::try_parse_from(["qnap", "login", "--insecure", "--secure"]).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::ArgumentConflict);
    }

    #[test]
    fn global_password_stdin_flag_parses_before_subcommand() {
        Cli::try_parse_from(["qnap", "--password-stdin", "info"]).unwrap();
    }

    #[test]
    fn global_host_override_parses_after_subcommand() {
        Cli::try_parse_from(["qnap", "info", "--host", "nas.local"]).unwrap();
    }

    #[test]
    fn files_rm_requires_at_least_one_path() {
        let err = Cli::try_parse_from(["qnap", "files", "rm"]).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument);
    }

    #[test]
    fn files_rm_accepts_multiple_paths() {
        Cli::try_parse_from(["qnap", "files", "rm", "/Public/a.txt", "/Public/b.txt"]).unwrap();
    }
}