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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
|
use std::{env::current_dir, net::SocketAddr, path::PathBuf};
use just_enough_vcs::{
system::action_system::action::ActionContext,
utils::{cfg_file::config::ConfigFile, tcp_connection::instance::ConnectionInstance},
vcs::{
constants::PORT,
current::current_local_path,
data::{
local::{LocalWorkspace, config::LocalConfig},
member::Member,
user::UserDirectory,
},
},
};
use clap::{Parser, Subcommand, arg, command};
use just_enough_vcs::{
utils::tcp_connection::error::TcpTargetError,
vcs::{actions::local_actions::proc_set_upstream_vault_action, registry::client_registry},
};
use just_enough_vcs_cli::utils::{
lang_selector::current_locales, md_colored::md, socket_addr_helper,
};
use rust_i18n::{set_locale, t};
use tokio::{fs, net::TcpSocket};
// Import i18n files
rust_i18n::i18n!("locales", fallback = "en");
#[derive(Parser, Debug)]
#[command(
disable_help_flag = true,
disable_version_flag = true,
disable_help_subcommand = true,
help_template = "{all-args}"
)]
struct JustEnoughVcsWorkspace {
#[command(subcommand)]
command: JustEnoughVcsWorkspaceCommand,
}
#[derive(Subcommand, Debug)]
enum JustEnoughVcsWorkspaceCommand {
// Member management
/// Manage your local accounts
#[command(subcommand, alias = "acc")]
Account(AccountManage),
/// Create an empty workspace
Create(CreateWorkspaceArgs),
/// Create an empty workspace in the current directory
Init(InitWorkspaceArgs),
/// Get workspace information in the current directory
#[command(alias = "h")]
Here(HereArgs),
// Sheet management
/// Manage sheets in the workspace
#[command(subcommand)]
Sheet(SheetManage),
// File management
/// Track files to the upstream vault
/// First track - Create and upload the "First Version", then hold them
/// Subsequent tracks - Update files with new versions
#[command(alias = "t")]
Track(TrackFileArgs),
/// Hold files for editing
#[command(alias = "hd")]
Hold(HoldFileArgs),
/// Throw files, and release edit rights
#[command(alias = "tr")]
Throw(ThrowFileArgs),
/// Move or rename files safely
#[command(alias = "mv")]
Move(MoveFileArgs),
/// Export files to other worksheet
#[command(alias = "out")]
Export(ExportFileArgs),
/// Import files from reference sheet or import area
#[command(alias = "in")]
Import(ImportFileArgs),
// Connection management
/// Direct to an upstream vault and stain this workspace
Direct(DirectArgs),
/// DANGER ZONE : Unstain this workspace
Unstain(UnstainArgs),
// Other
/// Query built-in documentation
Docs(DocsArgs),
}
#[derive(Subcommand, Debug)]
enum AccountManage {
/// Show help information
#[command(alias = "--help", alias = "-h")]
Help,
/// Register a member to this computer
Add(AccountAddArgs),
/// Remove a account from this computer
#[command(alias = "rm")]
Remove(AccountRemoveArgs),
/// List all accounts in this computer
#[command(alias = "ls")]
List(AccountListArgs),
/// Set current local workspace account
As(SetLocalWorkspaceAccountArgs),
/// Move private key file to account
#[command(alias = "mvkey", alias = "mvk")]
MoveKey(MoveKeyToAccountArgs),
}
#[derive(Subcommand, Debug)]
enum SheetManage {
/// Show help information
#[command(alias = "--help", alias = "-h")]
Help,
}
#[derive(Parser, Debug)]
struct CreateWorkspaceArgs {
/// Show help information
#[arg(short, long)]
help: bool,
/// Workspace directory path
path: PathBuf,
/// Force create, ignore files in the directory
#[arg(short, long)]
force: bool,
}
#[derive(Parser, Debug)]
struct InitWorkspaceArgs {
/// Show help information
#[arg(short, long)]
help: bool,
/// Force create, ignore files in the directory
#[arg(short, long)]
force: bool,
}
#[derive(Parser, Debug)]
struct HereArgs {
/// Show help information
#[arg(short, long)]
help: bool,
}
#[derive(Parser, Debug)]
struct AccountAddArgs {
/// Show help information
#[arg(short, long)]
help: bool,
/// Account name
account_name: String,
}
#[derive(Parser, Debug)]
struct AccountRemoveArgs {
/// Show help information
#[arg(short, long)]
help: bool,
/// Account name
account_name: String,
}
#[derive(Parser, Debug)]
struct AccountListArgs {
/// Show help information
#[arg(short, long)]
help: bool,
}
#[derive(Parser, Debug)]
struct SetLocalWorkspaceAccountArgs {
/// Show help information
#[arg(short, long)]
help: bool,
/// Account name
account_name: String,
}
#[derive(Parser, Debug)]
struct MoveKeyToAccountArgs {
/// Show help information
#[arg(short, long)]
help: bool,
/// Account name
account_name: String,
/// Private key file path
key_path: PathBuf,
}
#[derive(Parser, Debug)]
struct TrackFileArgs {
/// Show help information
#[arg(short, long)]
help: bool,
}
#[derive(Parser, Debug)]
struct HoldFileArgs {
/// Show help information
#[arg(short, long)]
help: bool,
}
#[derive(Parser, Debug)]
struct ThrowFileArgs {
/// Show help information
#[arg(short, long)]
help: bool,
}
#[derive(Parser, Debug)]
struct MoveFileArgs {
/// Show help information
#[arg(short, long)]
help: bool,
}
#[derive(Parser, Debug)]
struct ExportFileArgs {
/// Show help information
#[arg(short, long)]
help: bool,
}
#[derive(Parser, Debug)]
struct ImportFileArgs {
/// Show help information
#[arg(short, long)]
help: bool,
}
#[derive(Parser, Debug)]
struct DirectArgs {
/// Show help information
#[arg(short, long)]
help: bool,
/// Upstream vault address
upstream: String,
}
#[derive(Parser, Debug)]
struct UnstainArgs {
/// Show help information
#[arg(short, long)]
help: bool,
}
#[derive(Parser, Debug)]
struct DocsArgs {
/// Show help information
#[arg(short, long)]
help: bool,
}
#[tokio::main]
async fn main() {
// Init i18n
set_locale(¤t_locales());
// Init colored
#[cfg(windows)]
colored::control::set_virtual_terminal(true).unwrap();
let Ok(parser) = JustEnoughVcsWorkspace::try_parse() else {
println!("{}", md(t!("jv.help")));
return;
};
match parser.command {
JustEnoughVcsWorkspaceCommand::Account(account_manage) => {
let user_dir = match UserDirectory::current_doc_dir() {
Some(dir) => dir,
None => {
eprintln!("{}", t!("jv.fail.account.no_user_dir"));
return;
}
};
match account_manage {
AccountManage::Help => {
println!("{}", md(t!("jv.account")));
}
AccountManage::Add(account_add_args) => {
if account_add_args.help {
println!("{}", md(t!("jv.account")));
return;
}
jv_account_add(user_dir, account_add_args).await;
}
AccountManage::Remove(account_remove_args) => {
if account_remove_args.help {
println!("{}", md(t!("jv.account")));
return;
}
jv_account_remove(user_dir, account_remove_args).await;
}
AccountManage::List(account_list_args) => {
if account_list_args.help {
println!("{}", md(t!("jv.account")));
return;
}
jv_account_list(user_dir, account_list_args).await;
}
AccountManage::As(set_local_workspace_account_args) => {
if set_local_workspace_account_args.help {
println!("{}", md(t!("jv.account")));
return;
}
jv_account_as(user_dir, set_local_workspace_account_args).await;
}
AccountManage::MoveKey(move_key_to_account_args) => {
if move_key_to_account_args.help {
println!("{}", md(t!("jv.account")));
return;
}
jv_account_move_key(user_dir, move_key_to_account_args).await;
}
}
}
JustEnoughVcsWorkspaceCommand::Create(create_workspace_args) => {
if create_workspace_args.help {
println!("{}", md(t!("jv.create")));
return;
}
jv_create(create_workspace_args).await;
}
JustEnoughVcsWorkspaceCommand::Init(init_workspace_args) => {
if init_workspace_args.help {
println!("{}", md(t!("jv.init")));
return;
}
jv_init(init_workspace_args).await;
}
JustEnoughVcsWorkspaceCommand::Here(here_args) => {
if here_args.help {
println!("{}", md(t!("jv.here")));
return;
}
jv_here(here_args).await;
}
JustEnoughVcsWorkspaceCommand::Sheet(sheet_manage) => match sheet_manage {
SheetManage::Help => {
println!("{}", md(t!("jv.sheet")));
return;
}
},
JustEnoughVcsWorkspaceCommand::Track(track_file_args) => {
if track_file_args.help {
println!("{}", md(t!("jv.track")));
return;
}
jv_track(track_file_args).await;
}
JustEnoughVcsWorkspaceCommand::Hold(hold_file_args) => {
if hold_file_args.help {
println!("{}", md(t!("jv.hold")));
return;
}
jv_hold(hold_file_args).await;
}
JustEnoughVcsWorkspaceCommand::Throw(throw_file_args) => {
if throw_file_args.help {
println!("{}", md(t!("jv.throw")));
return;
}
jv_throw(throw_file_args).await;
}
JustEnoughVcsWorkspaceCommand::Move(move_file_args) => {
if move_file_args.help {
println!("{}", md(t!("jv.move")));
return;
}
jv_move(move_file_args).await;
}
JustEnoughVcsWorkspaceCommand::Export(export_file_args) => {
if export_file_args.help {
println!("{}", md(t!("jv.export")));
return;
}
jv_export(export_file_args).await;
}
JustEnoughVcsWorkspaceCommand::Import(import_file_args) => {
if import_file_args.help {
println!("{}", md(t!("jv.import")));
return;
}
jv_import(import_file_args).await;
}
JustEnoughVcsWorkspaceCommand::Direct(direct_args) => {
if direct_args.help {
println!("{}", md(t!("jv.direct")));
return;
}
jv_direct(direct_args).await;
}
JustEnoughVcsWorkspaceCommand::Unstain(unstain_args) => {
if unstain_args.help {
println!("{}", md(t!("jv.unstain")));
return;
}
jv_unstain(unstain_args).await;
}
JustEnoughVcsWorkspaceCommand::Docs(docs_args) => {
if docs_args.help {
println!("{}", md(t!("jv.docs")));
return;
}
jv_docs(docs_args).await;
}
}
}
async fn jv_create(args: CreateWorkspaceArgs) {
let path = args.path;
if !args.force && path.exists() && !is_directory_empty(&path).await {
eprintln!("{}", t!("jv.fail.init_create_dir_not_empty").trim());
return;
}
match LocalWorkspace::setup_local_workspace(path).await {
Ok(_) => {
println!("{}", t!("jv.success.create"));
}
Err(e) => {
eprintln!("{}", t!("jv.fail.create", error = e.to_string()));
}
}
}
async fn jv_init(args: InitWorkspaceArgs) {
let path = match current_dir() {
Ok(path) => path,
Err(e) => {
eprintln!("{}", t!("jv.fail.get_current_dir", error = e.to_string()));
return;
}
};
if !args.force && path.exists() && !is_directory_empty(&path).await {
eprintln!("{}", t!("jv.fail.init_create_dir_not_empty").trim());
return;
}
match LocalWorkspace::setup_local_workspace(path).await {
Ok(_) => {
println!("{}", t!("jv.success.init"));
}
Err(e) => {
eprintln!("{}", t!("jv.fail.init", error = e.to_string()));
}
}
}
async fn is_directory_empty(path: &PathBuf) -> bool {
match fs::read_dir(path).await {
Ok(mut entries) => entries.next_entry().await.unwrap().is_none(),
Err(_) => false,
}
}
async fn jv_here(_args: HereArgs) {
todo!()
}
async fn jv_track(_args: TrackFileArgs) {
todo!()
}
async fn jv_hold(_args: HoldFileArgs) {
todo!()
}
async fn jv_throw(_args: ThrowFileArgs) {
todo!()
}
async fn jv_move(_args: MoveFileArgs) {
todo!()
}
async fn jv_export(_args: ExportFileArgs) {
todo!()
}
async fn jv_import(_args: ImportFileArgs) {
todo!()
}
async fn jv_account_add(user_dir: UserDirectory, args: AccountAddArgs) {
let member = Member::new(args.account_name.clone());
match user_dir.register_account(member).await {
Ok(_) => {
println!(
"{}",
t!("jv.success.account.add", account = args.account_name)
);
}
Err(_) => {
eprintln!("{}", t!("jv.fail.account.add", account = args.account_name));
}
}
}
async fn jv_account_remove(user_dir: UserDirectory, args: AccountRemoveArgs) {
match user_dir.remove_account(&args.account_name) {
Ok(_) => {
println!(
"{}",
t!("jv.success.account.remove", account = args.account_name)
);
}
Err(_) => {
eprintln!(
"{}",
t!("jv.fail.account.remove", account = args.account_name)
);
}
}
}
async fn jv_account_list(user_dir: UserDirectory, _args: AccountListArgs) {
match user_dir.account_ids() {
Ok(account_ids) => {
println!(
"{}",
md(t!(
"jv.success.account.list.header",
num = account_ids.len()
))
);
let mut i = 0;
for account_id in account_ids {
println!("{}. {} {}", i + 1, &account_id, {
if user_dir.has_private_key(&account_id) {
t!("jv.success.account.list.status_has_key")
} else {
std::borrow::Cow::Borrowed("")
}
});
i += 1;
}
}
Err(_) => {
eprintln!("{}", t!("jv.fail.account.list"));
}
}
}
async fn jv_account_as(user_dir: UserDirectory, args: SetLocalWorkspaceAccountArgs) {
// Account exist
let Ok(member) = user_dir.account(&args.account_name).await else {
eprintln!(
"{}",
t!("jv.fail.account.not_found", account = args.account_name)
);
return;
};
let Some(_local_dir) = current_local_path() else {
eprintln!("{}", t!("jv.fail.workspace_not_found").trim());
return;
};
let Ok(mut local_cfg) = LocalConfig::read().await else {
eprintln!("{}", md(t!("jv.fail.read_cfg")));
return;
};
local_cfg.set_current_account(member.id());
let Ok(_) = LocalConfig::write(&local_cfg).await else {
eprintln!("{}", t!("jv.fail.write_cfg").trim());
return;
};
println!(
"{}",
t!("jv.success.account.as", account = member.id()).trim()
);
}
async fn jv_account_move_key(user_dir: UserDirectory, args: MoveKeyToAccountArgs) {
// Key file exist
if !args.key_path.exists() {
eprintln!(
"{}",
t!("jv.fail.path_not_found", path = args.key_path.display())
);
return;
}
// Account exist
let Ok(_member) = user_dir.account(&args.account_name).await else {
eprintln!(
"{}",
t!("jv.fail.account.not_found", account = args.account_name)
);
return;
};
// Rename key file
match fs::rename(
args.key_path,
user_dir.account_private_key_path(&args.account_name),
)
.await
{
Ok(_) => println!("{}", t!("jv.success.account.move_key")),
Err(_) => eprintln!("{}", t!("jv.fail.account.move_key")),
}
}
async fn jv_direct(args: DirectArgs) {
let pool = client_registry::client_action_pool();
let upstream = match socket_addr_helper::get_socket_addr(&args.upstream, PORT).await {
Ok(result) => result,
Err(_) => {
eprintln!(
"{}",
md(t!(
"jv.fail.parse.str_to_sockaddr",
str = &args.upstream.trim()
))
);
return;
}
};
let Some(instance) = connect(upstream).await else {
// Since connect() function already printed error messages, we only handle the return here
return;
};
let ctx = ActionContext::local().insert_instance(instance);
match proc_set_upstream_vault_action(&pool, ctx, upstream).await {
Err(e) => handle_err(e),
_ => {}
};
}
async fn jv_unstain(_args: UnstainArgs) {
todo!()
}
async fn jv_docs(_args: DocsArgs) {
todo!()
}
pub fn handle_err(err: TcpTargetError) {
let e: Option<(String, String, bool)> = match err {
TcpTargetError::Io(err) => Some(fsio(err)),
TcpTargetError::File(err) => Some(fsio(err)),
TcpTargetError::Serialization(err) => Some(serialize(err)),
TcpTargetError::Authentication(err) => Some(auth(err)),
TcpTargetError::Network(err) => Some(connection(err)),
TcpTargetError::Timeout(err) => Some(connection(err)),
TcpTargetError::Protocol(err) => Some(connection(err)),
_ => Some((
err.to_string(),
md(t!("jv.fail.action_operation_fail.type_other")),
false,
)),
};
if let Some((err_text, err_tip, has_tip)) = e {
eprintln!(
"{}\n{}",
md(t!("jv.fail.action_operation_fail.main", err = err_text)),
err_tip,
);
if has_tip {
eprintln!(
"{}",
md(t!("jv.fail.action_operation_fail.info_contact_admin"))
)
}
}
}
type ErrorText = String;
type ErrorTip = String;
type HasTip = bool;
fn fsio(err: String) -> (ErrorText, ErrorTip, HasTip) {
(
err,
md(t!("jv.fail.action_operation_fail.type_fsio")).to_string(),
true,
)
}
fn serialize(err: String) -> (ErrorText, ErrorTip, HasTip) {
(
err,
md(t!("jv.fail.action_operation_fail.type_serialize")).to_string(),
true,
)
}
fn auth(err: String) -> (ErrorText, ErrorTip, HasTip) {
(
err,
md(t!("jv.fail.action_operation_fail.type_auth")).to_string(),
true,
)
}
fn connection(err: String) -> (ErrorText, ErrorTip, HasTip) {
(
err,
md(t!("jv.fail.action_operation_fail.type_connection")).to_string(),
true,
)
}
async fn connect(upstream: SocketAddr) -> Option<ConnectionInstance> {
// Create Socket
let socket = if upstream.is_ipv4() {
match TcpSocket::new_v4() {
Ok(socket) => socket,
Err(_) => {
eprintln!("{}", t!("jv.fail.create_socket").trim());
return None;
}
}
} else {
match TcpSocket::new_v6() {
Ok(socket) => socket,
Err(_) => {
eprintln!("{}", t!("jv.fail.create_socket").trim());
return None;
}
}
};
// Connect
let Ok(stream) = socket.connect(upstream).await else {
eprintln!("{}", t!("jv.fail.connection_failed").trim());
return None;
};
Some(ConnectionInstance::from(stream))
}
|