253 Commits

Author SHA1 Message Date
veeso
08c42e5acf release date 2022-06-18 13:35:03 +02:00
veeso
aac9cf4fa0 features updated 2022-06-10 12:18:38 +02:00
veeso
a26b21da89 0.9.0 2022-06-09 17:45:17 +02:00
veeso
bb95c9a4d0 updated dependencies 2022-06-09 15:11:55 +02:00
veeso
80dea3f71a Fixed SSH key list showing {hostname} at {username} instead of {username} at {hostname} 2022-06-09 15:08:02 +02:00
veeso
0057a657d2 removed license headers 2022-06-09 14:28:02 +02:00
Christian Visintin
816270d545 Fs watcher (#113)
fs watcher
2022-06-09 13:03:02 +02:00
veeso
2caa0432df Remote directory path in authentication form and in bookmarks parameters 2022-05-03 15:37:00 +02:00
Christian Visintin
e0d8b80cdf Bookmark name as hostname for cli args (#111)
bookmark name as hostname for cli args
2022-05-03 11:54:48 +02:00
veeso
f094979ddb working on 0.9.0 2022-05-03 09:16:38 +02:00
veeso
0c8144aaa8 0.8.2 2022-04-26 21:41:21 +02:00
veeso
3249e82873 lint 2022-04-22 09:56:10 +02:00
veeso
66adad3135 Fixed termscp panics when displaying long non-ascii filenames 2022-04-20 12:09:33 +02:00
veeso
f2e5bf4441 Working on 0.8.2 2022-04-07 11:08:47 +02:00
veeso
601b0595d4 Write exitcode on exit 2022-04-07 11:07:41 +02:00
veeso
c47fcb2225 fixed install script 2022-04-07 10:24:54 +02:00
veeso
550c7ca62a upcoming features 2022-03-22 20:55:54 +01:00
veeso
3256c276b4 0.8.1 2022-03-22 20:45:24 +01:00
veeso
04f43fff63 boolean release 2022-03-19 10:35:36 +01:00
veeso
82e8c84000 fixed make_pkg 2022-03-15 12:22:43 +01:00
veeso
31203d76ce install.sh m1 macos 2022-03-15 11:25:50 +01:00
veeso
572a948f2c macos arm64 build 2022-03-15 11:25:50 +01:00
veeso
b6ee49cfa6 updated donation link in install.sh 2022-03-09 17:07:35 +01:00
veeso
0334c5db78 Updated dependencies 2022-03-09 16:19:57 +01:00
veeso
c45ebec261 Fixed AltGr characters not allowed in auth form 2022-03-09 15:13:08 +01:00
veeso
ad2781b62c use latest rust in macos/windows ci 2022-03-09 11:27:26 +01:00
veeso
35dc11cce3 Strip binary with new 1.59 feature 2022-03-05 11:11:07 +01:00
veeso
8d9e7443ec updated user manuals 2022-03-05 11:06:14 +01:00
veeso
697ab225ea clippy 2022-03-05 11:06:14 +01:00
veeso
babbc5eadb new-path-style and endpoint s3 params 2022-03-05 11:06:14 +01:00
veeso
f28dba7660 added new s3 params 2022-03-05 11:06:14 +01:00
veeso
c5eba4b56a changed 'AWS S3' to 'S3' in forms 2022-03-05 11:06:14 +01:00
veeso
0b70819781 wtf git? 2022-02-06 11:09:44 +01:00
veeso
069fe8cae2 Merge branch '0.8.1' of github.com:veeso/termscp into 0.8.1 2022-02-06 10:57:44 +01:00
veeso
043f54e707 removed freebsd workflow. It is not supported anymore 2022-02-06 10:57:27 +01:00
veeso
b635554e52 updated freebsd vm version 2022-02-04 15:16:07 +01:00
veeso
9e35616568 updated dependencies 2022-02-04 15:14:11 +01:00
veeso
615dbda583 clippy 2022-02-04 15:06:11 +01:00
veeso
4b421a4a87 issue 94: color not reset after leaving text editor (SORCERY!!!) 2022-01-29 19:26:37 +01:00
veeso
0fe06eb52b updated deps 2022-01-29 19:04:22 +01:00
veeso
e8c6b8306f working on 0.8.1 2022-01-29 19:03:12 +01:00
Pascal Sommer
d1457253c4 fix: footer listed "Delete" shortcut as "Make Dir" 2022-01-12 21:03:15 +01:00
ImgBotApp
1bcdaa5614 [ImgBot] Optimize images
*Total -- 1,968.08kb -> 1,553.38kb (21.07%)

/assets/images/termscp-96.png -- 4.01kb -> 2.78kb (30.66%)
/assets/images/termscp-128.png -- 5.41kb -> 3.75kb (30.66%)
/assets/images/termscp-512.png -- 24.29kb -> 16.96kb (30.17%)
/assets/images/termscp-64.png -- 2.77kb -> 1.96kb (29.32%)
/assets/images/config.gif -- 1,246.97kb -> 937.11kb (24.85%)
/assets/images/auth.gif -- 420.79kb -> 335.62kb (20.24%)
/assets/images/flags/jp.png -- 7.43kb -> 6.19kb (16.64%)
/assets/images/flags/cn.png -- 6.80kb -> 5.78kb (15.07%)
/assets/images/flags/br.png -- 10.83kb -> 9.35kb (13.67%)
/assets/images/flags/kr.png -- 10.04kb -> 8.72kb (13.17%)
/assets/images/termscp.svg -- 1.39kb -> 1.25kb (10.08%)
/assets/images/themes.gif -- 227.34kb -> 223.90kb (1.52%)

Signed-off-by: ImgBotApp <ImgBotHelp@gmail.com>
2022-01-06 11:15:26 +01:00
veeso
85dd67721f new gifs 2022-01-06 11:07:29 +01:00
veeso
a25ee67cd3 use branch in docker build 2022-01-06 10:44:34 +01:00
veeso
67d48e7a79 readme 2022-01-06 10:44:34 +01:00
veeso
49e69277af Updated deps 2022-01-06 10:44:34 +01:00
veeso
332284fec3 keyring 1.0.0 2022-01-06 10:44:34 +01:00
veeso
4897253932 2022-01-05 review 2022-01-06 10:44:34 +01:00
veeso
6559c6b083 Error popup message height is now calculated based on the content it must display 2022-01-06 10:44:34 +01:00
veeso
587d7da2cb re-use code with handle input ev 2022-01-06 10:44:34 +01:00
Christian Visintin
7d55563556 Aws s3 connection parameters extension (#89)
* Aws s3 connection parameters extension

* Changed 'save password?' popup to 'change secrets?'

* missing docs
2022-01-06 10:44:34 +01:00
veeso
53271966da Changed buffer size to 65535 2022-01-06 10:44:34 +01:00
veeso
ec4daf8e25 remotefs 0.2.0 2022-01-06 10:44:34 +01:00
veeso
edd0842273 Redraw UI on window resize 2022-01-06 10:44:34 +01:00
veeso
c1edc20462 symlink command 2022-01-06 10:44:34 +01:00
veeso
ced7573241 symlink command 2022-01-06 10:44:34 +01:00
veeso
24788fa894 remove temp archive once installation has finished 2022-01-06 10:44:34 +01:00
veeso
dab98f4292 F2 to save file as 2022-01-06 10:44:34 +01:00
veeso
84cb775679 Categorize Auth activity msg 2022-01-06 10:44:34 +01:00
veeso
4e802f1dc5 Use tui-realm color parser 2022-01-06 10:44:34 +01:00
veeso
b8efe6985f Removed storage key for filetransfer terminal width 2022-01-06 10:44:34 +01:00
veeso
e047179ea0 Remove pending transfer with storage (use action) 2022-01-06 10:44:34 +01:00
veeso
197b3095b6 Disable sync browsing when found explorer is mounted 2022-01-06 10:44:34 +01:00
Christian Visintin
54c23079be Sync browsing prompts to create dir (#85) 2022-01-06 10:44:34 +01:00
veeso
a93dbde0c8 Added help footers 2022-01-06 10:44:34 +01:00
veeso
2a3d4f2670 Default log level changed to INFO; added option to enable TRACE log level 2022-01-06 10:44:34 +01:00
Christian Visintin
e6ba4d8430 SSH configuration path (#84)
SSH configuration
2022-01-06 10:44:34 +01:00
veeso
9284f101c8 mode 2022-01-06 10:44:34 +01:00
veeso
685444655c Ux improvements (described in issue #80) 2022-01-06 10:44:34 +01:00
veeso
027545f14c Removed docs headers 2022-01-06 10:44:34 +01:00
veeso
2e0322bc0e dir size is 0 on Windows 2022-01-06 10:44:34 +01:00
veeso
df7a4381c4 Removed filetransfer module; migrated to remotefs crate 2022-01-06 10:44:34 +01:00
veeso
25dd1b9b0a updated donation link in help 2022-01-06 10:44:34 +01:00
veeso
a1a1631fd2 Removed unused focus, fixed partial prog bar alignment 2022-01-06 10:44:34 +01:00
veeso
47f3ffef7b Removed key modifiers none on popups, since on windows they won't work 2022-01-06 10:44:34 +01:00
veeso
54b5583d1a Migrated termscp to tui-realm 1.x 2022-01-06 10:44:34 +01:00
veeso
30851a78e8 serial test for env paths 2022-01-06 10:44:34 +01:00
veeso
bc6b7b582e Files found from search are now displayed with their relative path from working directory 2022-01-06 10:44:34 +01:00
veeso
3927fb2a39 Files found from search are now displayed with their absolute path 2022-01-06 10:44:34 +01:00
veeso
028f64a588 Windows opts 2022-01-06 10:44:34 +01:00
veeso
26ff496829 It is now possible to keep navigating on the other explorer while 'found tab' is open 2022-01-06 10:44:34 +01:00
veeso
cb583f305c If find command doesn't return any result show an info dialog and not an empty explorer 2022-01-06 10:44:34 +01:00
veeso
88b29d3183 A "wait popup" will now be displayed while searching files 2022-01-06 10:44:34 +01:00
veeso
02fdb27cc5 Removed lib.rs 2022-01-06 10:44:34 +01:00
veeso
5fd53c1b2b -Dwarnings for clippy on windows/macos ci 2022-01-06 10:44:34 +01:00
veeso
696e3ae582 Rust 2021 2022-01-06 10:44:34 +01:00
veeso
e7a29b7f1a 0.8.0 setup 2022-01-06 10:44:34 +01:00
veeso
e53120f3c2 arch: install rust only if not found on local system 2021-12-21 09:05:34 +01:00
veeso
3f463f4b73 ko-fi 2021-12-04 10:46:22 +01:00
veeso
83964026ec new donations banners 2021-10-30 15:54:02 +02:00
veeso
f79658a93c new donations banners 2021-10-30 15:49:35 +02:00
veeso
23fd37559e Fixed install script 2021-10-12 10:54:33 +02:00
veeso
1fadc53743 Merge branch 'main' of github.com:veeso/termscp into main 2021-10-12 10:54:18 +02:00
veeso
0eaa898e15 Fixed docker.sh 2021-10-12 09:09:57 +02:00
veeso
0aeca76f63 Fixed bash 2021-10-11 20:40:20 +02:00
veeso
8cf6c1fce3 freebsd pkg 2021-10-11 09:30:21 +02:00
veeso
736dd820a6 donate links 2021-10-10 09:52:49 +02:00
veeso
db73d1e45f gitignore 2021-10-09 10:58:38 +02:00
veeso
6c31c1f2d8 deb readme 2021-10-09 10:55:21 +02:00
veeso
fcce9b778b typos 2021-10-09 10:47:07 +02:00
veeso
b309a55ed6 Merge branch 'md-translations' into 0.7.0 2021-10-07 11:22:14 +02:00
veeso
8b2b834818 User manuals 2021-10-07 09:37:34 +02:00
veeso
9a63f5b2cc copy template 2021-10-06 11:12:15 +02:00
veeso
a7a116cb33 Badges aligned 2021-10-06 10:38:57 +02:00
veeso
bc90fb1038 Align badges 2021-10-06 10:38:03 +02:00
veeso
e307b6a8ac Align badges 2021-10-06 10:37:36 +02:00
veeso
c9e8589689 readmes 2021-10-06 10:30:24 +02:00
veeso
e09682c219 wip 2021-10-06 08:45:02 +02:00
Christian Visintin
967babbcb7 Merge pull request #71 from veeso/issue-70-cant-enter-@-in-password-input-box
Issue 70 cant enter @ in password input box
2021-10-04 21:03:58 +02:00
veeso
4973bf8cbe Fixed issue 70: Unable to type characters with CTRL+ALT 2021-10-04 21:03:17 +02:00
veeso
6421b74c66 typo 2021-10-04 17:50:07 +02:00
veeso
463329a080 docs url 2021-10-04 16:11:45 +02:00
veeso
fd2144f8e9 It, zh-CN 2021-10-04 16:02:40 +02:00
veeso
18a579a204 Flags 2021-10-04 10:48:56 +02:00
veeso
58d5ea264f docs 2021-09-30 09:56:20 +02:00
veeso
4b9d23cc3a Reuse mounts 2021-09-30 09:33:34 +02:00
veeso
f3e694d3d6 File list can now be rewinded 2021-09-28 12:59:43 +02:00
Christian Visintin
b9a0e516c6 Merge pull request #68 from veeso/notifications
Notifications
2021-09-28 12:58:11 +02:00
veeso
198d421ab0 Notifications 2021-09-28 12:44:51 +02:00
veeso
6caf34b17a Added dbus to deps for FreeBSD 2021-09-27 22:38:08 +02:00
veeso
f0a91b1579 Merge remote-tracking branch 'origin/main' into 0.7.0 2021-09-27 11:48:36 +02:00
veeso
c3e5663cf4 New logo 2021-09-27 11:48:22 +02:00
veeso
bcc6fcd2e7 Added file replace prompt also for 'Many' 2021-09-25 20:18:50 +02:00
veeso
3c3d681ca0 Updated chinese manual 2021-09-25 14:29:48 +02:00
veeso
3e83c26cd5 Merge branch 'main' into 0.7.0 2021-09-25 13:59:58 +02:00
veeso
ec841d5382 Some flags are controversial :rolling_eyes 2021-09-25 13:58:27 +02:00
veeso
d2e4252487 there's no need to specify language 2021-09-25 13:57:24 +02:00
veeso
7660dad4eb man-en 2021-09-25 13:56:40 +02:00
Christian Visintin
ddfa973c19 Merge pull request #67 from flashlab/main
Translate doc into simplified Chinese
2021-09-25 11:16:47 +02:00
Jeff
def0eb8586 small fix to the image path 2021-09-25 14:20:19 +08:00
flashlab
c39ee82ac5 translate doc into simplified Chinese 2021-09-25 14:10:46 +08:00
Christian Visintin
e1bde1971d Merge pull request #65 from veeso/prompt-when-replacing-files
Prompt user when about to replace an existing file
2021-09-24 09:22:50 +02:00
veeso
79c90c5b97 install with cargo --locked 2021-09-19 15:02:14 +02:00
veeso
06ffbaa2f4 Option: prompt user when about to replace an existing file caused by a file transfer 2021-09-19 11:18:52 +02:00
veeso
63e7023342 Re-use mounts in UI 2021-09-19 11:16:18 +02:00
veeso
88a0685097 Added misc_info_dialog to themes 2021-09-19 10:48:16 +02:00
veeso
ed3225ed84 User manual updates 2021-09-18 22:07:59 +02:00
veeso
96c997c38a dirs 4.0.0 2021-09-18 14:22:00 +02:00
veeso
c824d00986 Removed auto-update test for macos (blocks on github/CI) 2021-09-17 09:52:35 +02:00
veeso
c052796d52 Merge remote-tracking branch 'origin/main' into 0.7.0 2021-09-16 17:07:13 +02:00
Christian Visintin
1077204965 Merge pull request #64 from veeso/self-update
Self update
2021-09-16 17:05:07 +02:00
veeso
77476596f4 Fixed new version check 2021-09-16 16:54:43 +02:00
Christian Visintin
efd5443be4 choco install 2021-09-16 09:30:19 +02:00
veeso
8c88fbe10f cargo lock update 2021-09-12 10:01:52 +02:00
veeso
06a67de14f Auto update (w/ cli) 2021-09-12 10:00:56 +02:00
veeso
8bb05406c8 upcoming features 2021-09-11 22:06:18 +02:00
veeso
3f31800158 Updated dependencies 2021-09-11 21:53:38 +02:00
veeso
f69489fc8f FileTransferResult 2021-09-10 20:58:26 +02:00
veeso
1f115dea92 Strip executables when making release 2021-09-10 20:51:05 +02:00
Christian Visintin
f81424f1db Merge pull request #63 from veeso/aws-s3
Aws s3
2021-09-10 17:32:28 +02:00
veeso
1d09095ab9 Aws s3 support 2021-09-01 15:20:05 +02:00
Christian Visintin
bf6f25310c Update README.md 2021-08-31 16:24:26 +02:00
veeso
4c1e4fef7a Removed BSD packages 2021-08-30 15:03:53 +02:00
Christian Visintin
ddd4824567 Merge pull request #62 from veeso/0.6.1
0.6.1
2021-08-30 15:00:06 +02:00
veeso
f31f58aa79 working on 0.7.0 2021-08-26 10:42:46 +02:00
veeso
22bb143820 0.6.1 2021-08-24 15:03:20 +02:00
veeso
78b918087e absolutize path common functions 2021-08-24 09:29:40 +02:00
veeso
91ce709d7b lint 2021-08-24 09:29:23 +02:00
veeso
214ec0c5a5 absolutize path common functions 2021-08-24 09:28:49 +02:00
veeso
0cb9254e63 fmt 2021-08-23 18:01:45 +02:00
veeso
4bbb339844 test fixed 2021-08-23 17:57:18 +02:00
veeso
92b081c076 Replaced u8 pex with UnixPex struct 2021-08-23 17:52:55 +02:00
veeso
32ab0267fb Removed unused readonly attribute for FsEntry 2021-08-23 17:18:27 +02:00
Christian Visintin
8a0f190474 Merge pull request #61 from veeso/issue-59-when-copying-files-with-tricky-copy-the-upper-progress-bar-shows-no-text
Fix: When copying files with tricky copy, the upper progress bar shows no text
2021-08-23 15:32:27 +02:00
veeso
a189a4c754 Changelog 2021-08-23 14:59:47 +02:00
veeso
b7b765c16e Fixed: When copying files with tricky copy, the upper progress bar shows no text 2021-08-23 14:56:27 +02:00
veeso
7713c6c21d suppaftp 4.1.2 2021-08-23 12:20:25 +02:00
Christian Visintin
c49184dcb1 Merge pull request #60 from veeso/issue-58-possible-to-upload-a-directory-that-already-exists-on-remote
Issue 58 possible to upload a directory that already exists on remote
2021-08-23 12:12:07 +02:00
veeso
fc3803991a Fixed scp transfer non returning DirectoryAlreadyExists 2021-08-23 11:38:41 +02:00
veeso
f6011543c0 Fixed ui test units 2021-08-23 11:18:11 +02:00
veeso
7390bb58c5 Changed FTP library from ftp4 to suppaftp; Handle directory already exists on FTP transfer; mkdir already exists test units 2021-08-23 11:11:14 +02:00
veeso
81482b47f4 Merged 0.6.1; added new DirectoryAlreadyExists; return new variant for SFTP/SCP 2021-08-18 09:33:27 +02:00
veeso
6cb1dcaa43 upcoming features 2021-08-17 18:05:02 +02:00
veeso
78e4a4899c Rewind radio groups 2021-08-17 12:44:23 +02:00
veeso
d15997cca0 Updated dependencies; migrated tui-realm to 0.6.0 2021-08-17 12:38:24 +02:00
veeso
1558f4ffe4 init 0.6.1 2021-08-17 11:03:35 +02:00
veeso
764cca73d1 linter 2021-08-10 22:27:20 +02:00
veeso
1757eb5bec When uploading a directory, create directory only if it doesn't exist 2021-08-10 22:17:36 +02:00
veeso
6cfac57162 Shortened url for install.sh 2021-08-03 17:09:37 +02:00
veeso
d36d330244 badge 2021-07-23 21:37:12 +02:00
veeso
4203de6d3f Merge branch 'main' of github.com:veeso/termscp into main 2021-07-23 21:05:19 +02:00
veeso
098e3c709a fixed deps rpm 2021-07-23 21:05:11 +02:00
Christian Visintin
1a8e151efb Merge pull request #57 from veeso/imgbot
[ImgBot] Optimize images
2021-07-23 21:05:03 +02:00
ImgBotApp
6c8d22d396 [ImgBot] Optimize images
*Total -- 565.02kb -> 417.74kb (26.07%)

/assets/images/themes.gif -- 327.91kb -> 227.34kb (30.67%)
/assets/images/auth.gif -- 237.10kb -> 190.40kb (19.7%)

Signed-off-by: ImgBotApp <ImgBotHelp@gmail.com>
2021-07-23 18:36:46 +00:00
Christian Visintin
a0ee1d886a Merge pull request #56 from veeso/0.6.0
0.6.0
2021-07-23 20:36:25 +02:00
veeso
bf6f1625ec 0.6.0 release notes 2021-07-23 14:32:50 +02:00
veeso
3271377b7e Removed redundant remoteOpts struct; use FileTransferParams only 2021-07-23 14:32:15 +02:00
veeso
f36bb65b45 Removed redundant remoteOpts struct; use FileTransferParams only 2021-07-23 14:31:29 +02:00
veeso
c722982c39 Removed unecessary Option<&ConfigClient> in filetransfer; use degraded mode instead 2021-07-16 15:49:00 +02:00
veeso
e1109fff15 From now on, if you try to leave setup without making any change, you won't be prompted whether to save configuration or not 2021-07-16 15:32:39 +02:00
veeso
59c6567ff3 Auth view enhanchements: check if port and host are valid 2021-07-15 13:00:55 +02:00
veeso
61f6901767 Save both theme and config at the same time 2021-07-15 12:47:47 +02:00
veeso
8277c80860 Fixed config save and theme layout 2021-07-15 12:33:15 +02:00
veeso
4093ba169c Replaced '...' with '…' in texts 2021-07-15 12:24:20 +02:00
veeso
e3a9d253f7 Show a 'wait' message when deleting, copying and moving files and when executing commands 2021-07-15 11:58:57 +02:00
veeso
80c67c8aa8 Fixed transfer interruption: it was not possible to abort a transfer if the size of the file was less than 65k 2021-07-13 16:43:27 +02:00
veeso
421969c3da argh instead of getopts 2021-07-10 20:19:29 +02:00
veeso
e15b79750b main() refactoring 2021-07-08 16:21:39 +02:00
veeso
37abe596c7 context getters 2021-07-08 15:43:23 +02:00
veeso
e6b44e1461 ConfigClient is an option no more; config client degraded mode 2021-07-08 15:07:24 +02:00
veeso
b9cb961da6 full and partial progress bar colors 2021-07-08 14:29:28 +02:00
veeso
55c4b777fb Fixed save bookmark dialog: you could switch out from dialog with <TAB> 2021-07-07 21:03:21 +02:00
Christian Visintin
2231727adb Merge pull request #55 from veeso/theme-provider
Theme provider and '-t' and '-c' CLI options
2021-07-07 14:38:22 +02:00
veeso
0a7e29d92f Theme provider and '-t' and '-c' CLI options 2021-07-07 12:54:30 +02:00
veeso
a105a42519 Dependencies 2021-07-03 15:56:26 +02:00
Christian Visintin
d20c2c786b Merge pull request #53 from veeso/keyring-rs-linux
Keyring-rs for linux
2021-07-03 15:15:00 +02:00
veeso
14abed44a5 Keyring-rs support for Linux 2021-07-03 14:43:31 +02:00
veeso
65fee64132 Merged 0.6.0 in keyring-rs-linux 2021-07-03 14:35:17 +02:00
Christian Visintin
348688b5ce Merge pull request #54 from veeso/release-notes-in-app
Release notes in-app
2021-06-26 19:18:39 +02:00
veeso
0cb84fc531 I've no idea of what user input buffer was meant to be 2021-06-26 18:26:21 +02:00
veeso
8a36c459d5 Restored version from env 2021-06-26 18:06:16 +02:00
veeso
c7414ab070 Release notes in-app 2021-06-26 18:00:03 +02:00
veeso
d16f9e7ad8 Merge branch '0.6.0' into keyring-rs-linux 2021-06-26 15:13:31 +02:00
veeso
3cbd2ed013 Removed archlinux build stuff 2021-06-26 14:40:23 +02:00
veeso
398f518b2f test_utils_git_check_for_updates not when github and mac and bsd 2021-06-26 14:39:09 +02:00
veeso
97a62def11 Brought all extern crate to top level 2021-06-26 12:32:11 +02:00
veeso
7ed49126a4 security policy 2021-06-26 12:25:24 +02:00
veeso
d976a34705 --lib tests 2021-06-26 12:08:05 +02:00
veeso
8b01c71819 Coverage 2021-06-26 12:06:49 +02:00
veeso
1ee5e368f6 Install cargo dependencies when building with cargo (rust too); build without default features on bsd 2021-06-26 11:02:07 +02:00
veeso
8fc71aae66 Merge branch '0.6.0' into keyring-rs-linux 2021-06-26 10:00:22 +02:00
veeso
0589cc2f0c Merge branch 'main' into 0.6.0 2021-06-26 10:00:08 +02:00
veeso
931a66498f filemode manifest freebsd 2021-06-26 09:51:13 +02:00
veeso
8ec0a0289a AUR distro: install rust too; fixed tempfile rpm 2021-06-22 09:35:52 +02:00
veeso
2d8ce475f8 Merge branch '0.6.0' into keyring-rs-linux 2021-06-21 20:51:24 +02:00
veeso
f8766722d4 Merge branch 'main' into 0.6.0 2021-06-21 20:46:10 +02:00
veeso
1319e0b17b Fixed install for freebsd 2021-06-21 20:45:20 +02:00
veeso
5e17bf0736 Merge branch '0.5.1' into 0.6.0 2021-06-21 18:23:01 +02:00
veeso
ca50bddc56 Merge branch '0.5.1' into 0.6.0 2021-06-21 18:22:19 +02:00
veeso
f8300fa587 fixed tests 2021-06-20 17:00:35 +02:00
veeso
407ca567f1 keyring-rs-linux docs 2021-06-20 16:55:17 +02:00
veeso
320fd5c2dd Updated dockerfiles for dbus 2021-06-20 15:13:20 +02:00
veeso
5986130dfa Unused variant if keyring is not enabled 2021-06-20 15:08:35 +02:00
veeso
19610479bd keyring support for linux 2021-06-20 15:04:16 +02:00
veeso
15d13af7d5 wip 2021-06-20 11:00:31 +02:00
Christian Visintin
3df8ed13a4 Merge pull request #41 from veeso/open-rs
Open-rs
2021-06-19 15:35:48 +02:00
veeso
00bee04c2c open-rs fixes 2021-06-19 15:03:56 +02:00
veeso
b73c3228e4 manual 2021-06-12 09:26:33 +02:00
veeso
99d4177e89 changelog 2021-06-11 15:20:49 +02:00
veeso
d07b1c86be tui-realm 0.4.1 2021-06-11 14:48:38 +02:00
veeso
fe494c52b1 Clear screen once opened file, to prevent crap on stderr 2021-06-11 14:46:20 +02:00
veeso
bc50328006 open-rs docs 2021-06-11 13:01:28 +02:00
veeso
90afe204b1 Open files with <V>; fixed cache file names 2021-06-11 09:52:50 +02:00
veeso
d981b77ed7 Working on open 2021-06-10 22:36:29 +02:00
veeso
541a9a55b5 Handle shift enter (file list) 2021-06-10 20:55:12 +02:00
veeso
cd3fc15bcb Fmt symlink with len 48 in found dialog 2021-06-10 12:16:48 +02:00
veeso
4e50038b41 Open file with 2021-06-10 12:14:09 +02:00
veeso
a8354ee38f Open file on <SUBMIT> 2021-06-10 11:08:17 +02:00
veeso
c4907c8ce5 Added open-rs to deps 2021-06-07 22:28:52 +02:00
veeso
3c3c680b00 tui-realm 0.4.0 2021-06-07 22:09:33 +02:00
veeso
3a32f45334 tui-realm 0.3.2 2021-06-06 14:19:20 +02:00
veeso
8e1843f90b Working on 0.6.0 2021-06-02 22:32:52 +02:00
192 changed files with 29246 additions and 18034 deletions

2
.github/FUNDING.yml vendored
View File

@@ -1 +1 @@
custom: ['https://www.buymeacoffee.com/veeso']
ko_fi: veeso

35
.github/ISSUE_TEMPLATE/copy.md vendored Normal file
View File

@@ -0,0 +1,35 @@
---
name: Copy
about: Report a typo/error in a repository document
title: "[COPY] - ISSUE_TITLE"
labels: documentation
assignees: veeso
---
## Report
### DOCUMENT NAME
This sentence at row ROW_NUMBER doesn't seem right:
> Write down here the wrong sentence
and I think it should be changed to:
> Write down here the correct sentence
`Copy paste the template above for all the sentences to fix`
---
`Copy paste the template above for all the documents to fix`
## Additional information
> ❗ Report LANGUAGE checks only if it concerns the documents above
> ❗ If the documents concerns more than one language, copy paste the checks below for each check you want to report
> ❗ The PR mention regards the indicated language. If you check the box, I may add you to a PR where I need to translate a new section of the user manual/README or other documents. I promise I won't stress you anyway.
- [ ] I am C1/C2 speaker for this language: LANGUAGE
- [ ] You can mention me in a PR in case a review for translations is needed

23
.github/ISSUE_TEMPLATE/security.md vendored Normal file
View File

@@ -0,0 +1,23 @@
---
name: Security report
about: Create a report of a security vulnerability
title: "[SECURITY] - ISSUE_TITLE"
labels: security
assignees: veeso
---
## Description
Severity:
- [ ] **critical**
- [ ] high
- [ ] medium
- [ ] low
A clear and concise description of the security vulnerability.
## Additional information
Add any other context about the problem here.

View File

@@ -3,12 +3,14 @@ ignore-not-existing: true
llvm: true
output-type: lcov
ignore:
- "/*"
- "C:/*"
- "../*"
- src/main.rs
- src/lib.rs
- src/activity_manager.rs
- "src/ui/activities/*"
- src/ui/context.rs
- src/ui/input.rs
- "/*"
- "C:/*"
- "../*"
- src/main.rs
- src/activity_manager.rs
- src/cli_opts.rs
- src/support.rs
- src/system/notifications.rs
- "src/ui/activities/*"
- src/ui/context.rs
- src/ui/input.rs

View File

@@ -1,21 +0,0 @@
name: aur-pub
on:
push:
tags:
- "*"
jobs:
aur-publish:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Publish AUR package
uses: KSXGitHub/github-actions-deploy-aur@v2.2.4
with:
pkgname: termscp
pkgbuild: ./dist/pkgs/arch/PKGBUILD
commit_username: ${{ secrets.AUR_USERNAME }}
commit_email: ${{ secrets.AUR_EMAIL }}
ssh_private_key: ${{ secrets.AUR_KEY }}
commit_message: Update AUR package
ssh_keyscan_types: rsa,dsa,ecdsa,ed25519

View File

@@ -11,8 +11,8 @@ jobs:
steps:
- uses: actions/checkout@v2
- name: Setup containers
run: docker-compose -f "tests/docker-compose.yml" up -d --build
- name: Install dependencies
run: sudo apt update && sudo apt install -y libdbus-1-dev libssh2-1-dev libssl-dev
- name: Setup nightly toolchain
uses: actions-rs/toolchain@v1
with:
@@ -22,7 +22,7 @@ jobs:
uses: actions-rs/cargo@v1
with:
command: test
args: --all-features --lib --no-fail-fast
args: --no-default-features --features github-actions --no-fail-fast
env:
CARGO_INCREMENTAL: "0"
RUSTFLAGS: "-Zprofile -Ccodegen-units=1 -Cinline-threshold=0 -Clink-dead-code -Coverflow-checks=off -Cpanic=abort -Zpanic_abort_tests"

View File

@@ -1,22 +0,0 @@
name: FreeBSD
on: [push, pull_request]
jobs:
build:
runs-on: macos-latest
steps:
- uses: actions/checkout@v2
- name: FreeBSD build
id: test
uses: vmactions/freebsd-vm@v0.1.4
with:
usesh: true
prepare: pkg install -y curl wget libssh gcc vim
run: |
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs > /tmp/rustup.sh && \
chmod +x /tmp/rustup.sh && \
/tmp/rustup.sh -y
. $HOME/.cargo/env
cargo build
cargo test --verbose --lib --features github-actions -- --test-threads 1

View File

@@ -11,8 +11,8 @@ jobs:
steps:
- uses: actions/checkout@v2
- name: Setup containers
run: docker-compose -f "tests/docker-compose.yml" up -d --build
- name: Install dependencies
run: sudo apt update && sudo apt install -y libdbus-1-dev libssh2-1-dev libssl-dev
- uses: actions-rs/toolchain@v1
with:
toolchain: stable
@@ -22,7 +22,7 @@ jobs:
uses: actions-rs/cargo@v1
with:
command: test
args: --all-features --lib --no-fail-fast
args: --no-default-features --features github-actions --no-fail-fast
- name: Format
run: cargo fmt --all -- --check
- name: Clippy

View File

@@ -11,9 +11,14 @@ jobs:
steps:
- uses: actions/checkout@v2
- uses: actions-rs/toolchain@v1
with:
toolchain: stable
override: true
components: rustfmt, clippy
- name: Build
run: cargo build
- name: Run tests
run: cargo test --verbose --lib --features github-actions -- --test-threads 1
run: cargo test --verbose --features github-actions
- name: Clippy
run: cargo clippy
run: cargo clippy -- -Dwarnings

View File

@@ -11,9 +11,14 @@ jobs:
steps:
- uses: actions/checkout@v2
- uses: actions-rs/toolchain@v1
with:
toolchain: stable
override: true
components: rustfmt, clippy
- name: Build
run: cargo build
- name: Run tests
run: cargo test --verbose --lib --features github-actions -- --test-threads 1
run: cargo test --verbose --features github-actions
- name: Clippy
run: cargo clippy
run: cargo clippy -- -Dwarnings

3
.gitignore vendored
View File

@@ -21,3 +21,6 @@ dist/pkgs/arch/*.tar.gz
# Macos
.DS_Store
dist/pkgs/
dist/build/macos/openssl/

View File

@@ -1,6 +1,13 @@
# Changelog
- [Changelog](#changelog)
- [0.9.0](#090)
- [0.8.2](#082)
- [0.8.1](#081)
- [0.8.0](#080)
- [0.7.0](#070)
- [0.6.1](#061)
- [0.6.0](#060)
- [0.5.1](#051)
- [0.5.0](#050)
- [0.4.2](#042)
@@ -18,6 +25,252 @@
---
## 0.9.0
Released on 18/06/2022
> 🏖️ Tenerife Update 🍹
- **Bookmark name as hostname for CLI arguments**
- It is now possible to provide the name of the bookmark you want to connect to, instead of the address in command line arguments
To do so it is enough to run termscp as follows:
```sh
termscp -b <bookmark-name>
```
If the password is stored in the bookmark, it will be used, otherwise you will be prompted to type the password in.
- **Remote directory path in authentication form and in bookmarks parameters**:
- It is now possible to configure the directory path you want to enter when you connect to the remote host from the authentication form
- This parameter can be stored into bookmarks as you already do with the other parameters
- You can find this field scrolling down in the authentication form
- **File system watcher**:
- It is now possible to synchronize changes from a local path to the remote host
- Press `<T>` to start synchronizing changes from the selected directory/file to the remote directory
- The changes will be automatically applied to the remote host with a maximum delay of 5 seconds
- These changes are (if possible) applied: file removed, file changed, file renamed
- Press `<CTRL+T>` to show all the currently synchronized files
- **Enhancements**:
- Improved s3 auth form scrolling
- **Bugfix**:
- Fixed SSH key list showing `{hostname} at {username}` instead of `{username} at {hostname}`
- Dependencies:
- Updated `edit` to `0.1.4`
- Updated `log` to `0.4.17`
- Updated `magic-crypt` to `3.1.10`
- Updated `open` to `2.1.3`
- Updated `regex` to `1.5.6`
- Updated `rpassword` to `6.0.1`
- Updated `self_update` to `0.30.0`
- Updated `simplelog` to `0.12.0`
- Updated `toml` to `0.5.9`
- Updated `tui-realm` to `1.6.0`
## 0.8.2
Released on 26/04/2022
- **Enhancements**
- Write exitcode to log when termscp terminates
- Bugfix:
- [Issue 104](https://github.com/veeso/termscp/issues/104): Fixed termscp panics when displaying long non-ascii filenames
## 0.8.1
Released on 22/03/2022
- **Added support for S3 compatible backends**
- Changed `AWS S3` to `S3` in ui
- Added new `endpoint` and `new-path-style` to s3 connection parameters
- Bugfix:
- [Issue 92](https://github.com/veeso/termscp/issues/92): updated ssh2-config to 0.1.3, which solves this issue.
- [Issue 99](https://github.com/veeso/termscp/issues/99): Fixed AltGr characters not allowed in auth form
- Dependencies:
- Updated `keyring` to `1.1.2`
- Updated `notify-rust` to `4.5.6`
- Updated `open` to `2.0.3`
- Updated `rand` to `0.8.5`
- Updated `regex` to `1.5.5`
- Updated `remotefs-rs-aws-s3` to `0.2.0`
- Updated `tui-realm` to `1.5.0`
- Updated `tui-realm-stdlib` to `1.1.6`
## 0.8.0
Released on 06/01/2022
> ❄️ Winter update 2022 ⛄
- **Enhancements**:
- **Synchronized browsing**:
- From now on, if synchronized browsing is *enabled* and you try to enter a directory that doesn't exist on the other host, you will be asked whether you'd like to create the directory.
- **Find** feature:
- A "wait popup" will now be displayed while searching files
- If find command doesn't return any result show an info dialog and not an empty explorer
- It is now possible to keep navigating on the other explorer while "found tab" is open
- ❗ It is not possible though to have the "found tab" on both explorers (otherwise you wouldn't be able to tell whether you're transferring files)
- Files found from search are now displayed with their relative path from working directory
- **Ui**:
- Transfer abortion is now more responsive
- Selected files will now be rendered with **Reversed, underlined and italic** text modifiers instead of being prepended with `*`.
- Error popup message height is now calculated based on the content it must display.
- **Midnight commander keys**
- `<F1>`: Show help
- `<F2>`: Save file as (actually I invented this)
- `<F3>`: View file
- `<F4>`: Open file (with text editor)
- `<F5>`: Copy file
- `<F6>`: Rename file
- `<F7>`: Make directory
- `<F8>`: Remove file
- `<F10>`: Quit
- Added footer with most used key bindings
- ❗ `<TAB>` will now switch explorer tab (will do what `<LEFT>` and `<RIGHT>` currently do)
- ❗ Use `<BACKTAB>` to switch between explorer tab and log tab. ❗ Backtab is `<SHIFT + TAB>`
- **Tui-realm migration**:
- migrated application to tui-realm 1.x
- Improved application performance
- Changed the buffer size to **65535** (was 65536) for transfer I/O
- **Aws s3 connection parameters extension** 🦊:
- Added `Access Key` to Aws-s3 connection parameters
- Added `Security Access Key` to Aws-s3 connection parameters
- Added `Security token` to Aws-s3 connection parameters
- Added `Session token` to Aws-s3 connection parameters
- **SSH Config**
- Added `ssh config` parameter in configuration
- It is now possible to specify the ssh configuration file to use
- The supported parameters are described at <https://github.com/veeso/ssh2-config>.
- If the field is left empty, **no file will be loaded**.
- **By default, no file will be used**.
- **Symlink command**:
- You can now create symlinks, pressing `<K>` key on the file explorer.
- **Less verbose logging**:
- By default the log level is now set to `INFO`
- It is now possible to enable the `TRACE` level with the `-D` CLI option.
- Dependencies:
- Added `unicode-width 0.1.8`
- Updated `argh` to `0.1.7`
- Updated `keyring` to `1.0.0`
- Updated `magic-crypt` to `3.1.9`
- Updated `open` to `2.0.2`
- Updated `notify-rust` to `4.5.5`
- Updated `self_update` to `0.28.0`
- Updated `simplelog` to `0.11.1`
- Updated `tempfile` to `3.2.0`
- Updated `tui-realm` to `1.4.2`
- Updated `tui-realm-stdlib` to `1.1.5`
- Updated `whoami` to `1.2.1`
- Updated `wildmatch` to `2.1.0`
- Removed `rust-s3`, `ssh2`, `suppaftp`; replaced by `remotefs 0.2.0`, `remotefs-aws-s3 0.1.0`, `remotefs-ftp 0.1.0` and `remotefs-ssh 0.1.0`
- Removed `crossterm` (since bridged by tui-realm)
- Removed `textwrap` (unused)
## 0.7.0
Released on 12/10/2021
> 🍁 Autumn update 2021 🍇
- **Aws S3** 🪣
- Added support for the aws-s3 protocol.
- Operate on your bucket directly from the file explorer.
- You can also save your buckets as bookmarks.
- Aws s3 reads credentials directly from your credentials file at `$HOME/.aws/credentials` or from environment. Read more in the user manual.
- **Auto update** ⬇️
- Possibility to update termscp directly via GUI or CLI.
- Install update via CLI running `(sudo) termscp --update`.
- Install update via GUI from auth form: when the "new version message" is displayed press `<CTRL+R>`, then enter `YES` in the radio input asking whether to install the update.
- **Notifications** 📫
- termscp will now send Desktop notifications in these cases
- on transfer completed (minimum transfer size can be specified in configuration; default 512MB)
- on transfer error (same as above)
- on update available
- Added "notifications enabled" in configuration (Default enabled)
- Added "Notifications: minimum transfer size": if transfer size is greater or equal than the specified value, notifications for transfer will be displayed.
- **Prompt user when about to replace existing file on a file transfer** ❓
- Whenever a file transfer is about to replace an existing file on local/remote host, you will be prompted if you're sure you really want to replace that file.
- You may want to disable this option. You can go to configuration and set "Prompt when replacing existing files?" to "NO"
- **❗ BREAKING CHANGES ❗**:
- Added a new key in themes: `misc_info_dialog`: if your theme won't load, just reload it. If you're using a customised theme, you can add to it the missing key via a text editor. Just edit the `theme.toml` in your `$CONFIG_DIR/termscp/theme.toml` and add `misc_info_dialog` (Read more in manual at Themes).
- Enhancements:
- Reuse mounts in UI, in order to reduce executable size
- File list can now be "rewinded", which means that moving with arrows will now allow you to go from top to bottom of the list pressing `<UP>` and viceversa pressing `<DOWN>`.
- Bugfix:
- Fixed [Issue 70](https://github.com/veeso/termscp/issues/70): Unable to type characters with `CTRL+ALT` (e.g. italian layout `CTRL+ALT+ò` => `@`) due to a crossterm issue. Fixed with tui-realm-stdlib `0.6.3`.
- Dependencies:
- Added `notify_rust 4.5.3`
- Added `rust-s3 0.27-rc4`
- Added `self_update 0.27.0`
- Updated `argh` to `0.1.6`
- Updated `dirs` to `4.0.0`
- Updated `tui-realm-stdlib` to `0.6.3`
- Removed `ureq`
## 0.6.1
Released on 31/08/2021
- Enhancements:
- Now that tui-rs supports title alignment, UI has been improved
- Added new `Directory already exists` variant for file transfer errors
- Bugfix:
- Fixed [Issue 58](https://github.com/veeso/termscp/issues/58):When uploading a directory, create directory only if it doesn't exist
- Fixed [Issue 59](https://github.com/veeso/termscp/issues/59): When copying files with tricky copy, the upper progress bar shows no text
- Dependencies:
- Updated `bitflags` to `1.3.2`
- Updated `bytesize` to `1.1.0`
- Updated `crossterm` to `0.20`
- Updated `open` to `2.0.1`
- Added `tui-realm-stdlib 0.6.0`
- Replaced `ftp4` with `suppaftp 4.1.2`
- Updated `tui-realm` to `0.6.0`
## 0.6.0
Released on 23/07/2021
> 🍹 Summer update 2021 🍨
- **Open any file** in explorer:
- Open file with default program for file type with `<V>`
- Open file with a specific program with `<W>`
- **Themes**:
- You can now set colors for 26 elements in the application
- Colors can be any RGB, also **CSS colors** syntax is supported (e.g. `aquamarine`)
- Configure theme from settings or import from CLI using the `-t <theme file>` argument
- You can find several themes in the `themes/` directory
- **Keyring support for Linux**
- From now on keyring will be available for Linux only
- Read the manual to find out if your system supports the keyring and how you can enable it
- libdbus is now a dependency
- added `with-keyring` feature
- **❗ BREAKING CHANGE ❗**: if you start using keyring on Linux, all the saved password will be lost
- **In-app release notes**
- Possibility to see the release note of the new available release whenever a new version is available
- Just press `<CTRL+R>` when a new version is available from the auth activity to read the release notes
- **Installation script**:
- From now on, in case cargo is used to install termscp, all the cargo dependencies will be installed
- **Start termscp from configuration**: Start termscp with `-c` or `--config` to start termscp from configuration page
- Enhancements:
- Show a "wait" message when deleting, copying and moving files and when executing commands
- Replaced all `...` with `` in texts
- Check if remote host is valid in authentication form
- Check if port number is valid in authentication form
- From now on, if you try to leave setup without making any change, you won't be prompted whether to save configuration or not
- Bugfix:
- Fixed broken input cursor when typing UTF8 characters (tui-realm 0.3.2)
- Fixed save bookmark dialog: you could switch out from dialog with `<TAB>`
- Fixed transfer interruption: it was not possible to abort a transfer if the size of the file was less than 65k
- Changed `Remote address` to `Remote host` in authentication form
- Dependencies:
- Added `argh 0.1.5`
- Added `open 1.7.0`
- Removed `getopts`
- Updated `rand` to `0.8.4`
- Updated `textwrap` to `0.14.2`
- Updated `tui-realm` to `0.4.3`
## 0.5.1
Released on 21/06/2021

View File

@@ -9,6 +9,7 @@ Please note we have a [code of conduct](CODE_OF_CONDUCT.md), please follow it in
- [Open an issue](#open-an-issue)
- [Questions](#questions)
- [Bug reports](#bug-reports)
- [Copy error](#copy-error)
- [Feature requests](#feature-requests)
- [Preferred contributions](#preferred-contributions)
- [Pull Request Process](#pull-request-process)
@@ -45,6 +46,7 @@ Open an issue when:
- You have questions or concerns regarding the project or the application itself.
- You have a bug to report.
- You have a copy error to report. (Error in documentation; bad translation or sentence)
- You have a feature or a suggestion to improve termscp to submit.
### Questions
@@ -61,7 +63,7 @@ Don't set other labels to your issue, not even priority.
When you open a bug try to be the most precise as possible in describing your issue. I'm not saying you should always be that precise, since sometimes it's very easy for maintainers to understand what you're talking about. Just try to be reasonable to understand sometimes we might not know what you're talking about or we just don't have the technical knowledge you might think.
Please always provide the environment you're working on and consider that we don't provide any support for older version of termscp, at least for those not classified as LTS (if we'll ever have them).
If you can, provide the log file or the snippet involving your issue. You can find in the [user manual](docs/man.md) the location of the log file.
If you can, provide the log file or the snippet involving your issue. You can find in the [user manual](docs/man.md) the location of the log file. Please, if you can, enable the **debug mode**, before submitting the log, in order to provide us with a better overview of the problem.
Last but not least: the template I've written must be used. Full stop.
Maintainers will may add additional labels to your issue:
@@ -71,6 +73,15 @@ Maintainers will may add additional labels to your issue:
- **sorcery**: it is not possible to find out what's causing your bug, nor is reproducible on our test environments.
- **wontfix**: your bug has a very high ratio between the difficulty to fix it and the probability to encounter it, or it just isn't a bug, but a feature.
### Copy error
If you want to report a copy error, create an issue using the `copy` template.
The `Documentation` label should already be set and the issue should already be assigned to `veeso`.
If you want to fix the copy by yourself you can fork the project and open a PR, otherwise I will fix it by myself.
The copy issue is accepted **also if you're not a C1/C2 speaker**, but a speaker of that level in case the language is different from Italian/English is preferred.
Please fullfil the form on the bottom of the template if you want.
### Feature requests
Whenever you have a good idea which chould improve the project, it is a good idea to submit it to the project owner.
@@ -84,8 +95,6 @@ Said so, follow these steps:
- Open an issue using the `feature request` template describing with accuracy your suggestion
- Wait for the maintainer feedback on your idea
If you want to implement the feature by yourself and your suggestion gets approved, start writing the code. Remember that on [docs.rs](https://docs.rs/termscp) there is the documentation for the project. Open a PR related to your issue. See [Pull request process for more details](#pull-request-process)
It is very important to follow these steps, since it will prevent you from working on a feature that will be rejected and trust me, none of us wants to deal with this situation.
Always mind that your suggestion, may be rejected: I'll always provide a feedback on the reasons that brought me to reject your feature, just try not to get mad about that.
@@ -97,9 +106,10 @@ Always mind that your suggestion, may be rejected: I'll always provide a feedbac
At the moment, these kind of contributions are more appreciated and should be preferred:
- Fix for issues described in [Known Issues](./README.md#known-issues-) or [issues reported by the community](https://github.com/veeso/termscp/issues)
- New file transfers: for further details see [Implementing File Transfer](#implementing-file-transfers)
- Code optimizations: any optimization to the code is welcome
- **New file transfers**: for further details see [Implementing File Transfer](#implementing-file-transfers). ⚠️ this is going to be deprecated SOON! We're moving the file transfers into another library. Please see [remotefs-rs](https://github.com/veeso/remotefs-rs).
- **Code optimizations**: any optimization to the code is welcome
- See also features described in [Upcoming features](./README.md##upcoming-features-). Open an issue first though.
- README/User manual **translations**: really appreciated atm. Please just add a folder into `docs/` with the language code. Language code with two characters is used in case the language is understandable by all the countries where this language is spoken (e.g. `it-CH`, `it-IT` are not really different, so I just created `it`, but there is a big difference from `zh-CN` and `zh-TW` for instance). Don't worry about flags in README, I will implement that part if it's too complicated.
For any other kind of contribution, especially for new features, please submit a new issue first.

2579
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,9 +1,8 @@
[package]
authors = ["Christian Visintin"]
categories = ["command-line-utilities"]
description = "termscp is a feature rich terminal file transfer and explorer with support for SCP/SFTP/FTP"
documentation = "https://docs.rs/termscp"
edition = "2018"
description = "termscp is a feature rich terminal file transfer and explorer with support for SCP/SFTP/FTP/S3"
edition = "2021"
homepage = "https://veeso.github.io/termscp/"
include = ["src/**/*", "LICENSE", "README.md", "CHANGELOG.md"]
keywords = ["scp-client", "sftp-client", "ftp-client", "winscp", "command-line-utility"]
@@ -11,7 +10,7 @@ license = "MIT"
name = "termscp"
readme = "README.md"
repository = "https://github.com/veeso/termscp"
version = "0.5.1"
version = "0.9.0"
[package.metadata.rpm]
package = "termscp"
@@ -22,54 +21,65 @@ buildflags = ["--release"]
[package.metadata.rpm.targets]
termscp = { path = "/usr/bin/termscp" }
[package.metadata.deb]
maintainer = "Christian Visintin <christian.visintin1997@gmail.com>"
copyright = "2022, Christian Visintin <christian.visintin1997@gmail.com>"
extended-description-file = "docs/misc/README.deb.txt"
[[bin]]
name = "termscp"
path = "src/main.rs"
[dependencies]
bitflags = "1.2.1"
bytesize = "1.0.1"
argh = "0.1.7"
bitflags = "1.3.2"
bytesize = "1.1.0"
chrono = "0.4.19"
content_inspector = "0.2.4"
crossterm = "0.19.0"
dirs = "3.0.1"
edit = "0.1.3"
ftp4 = { version = "4.0.2", features = [ "secure" ] }
getopts = "0.2.21"
dirs = "4.0.0"
edit = "0.1.4"
hostname = "0.3.1"
keyring = { version = "1.1.2", optional = true }
lazy_static = "1.4.0"
log = "0.4.14"
magic-crypt = "3.1.7"
rand = "0.8.3"
regex = "1.5.4"
rpassword = "5.0.1"
log = "0.4.17"
magic-crypt = "3.1.10"
notify = "4.0.17"
notify-rust = { version = "4.5.6", default-features = false, features = [ "d" ] }
open = "2.1.3"
rand = "0.8.5"
regex = "1.5.6"
remotefs = "^0.2.0"
remotefs-aws-s3 = "^0.2.0"
remotefs-ftp = { version = "^0.1.0", features = [ "secure" ] }
remotefs-ssh = "^0.1.0"
rpassword = "6.0.1"
self_update = { version = "0.30.0", features = [ "archive-tar", "archive-zip", "compression-flate2", "compression-zip-deflate" ] }
serde = { version = "^1.0.0", features = [ "derive" ] }
simplelog = "0.10.0"
ssh2 = "0.9.0"
tempfile = "3.1.0"
textwrap = "0.14.0"
simplelog = "0.12.0"
tempfile = "3.2.0"
thiserror = "^1.0.0"
toml = "0.5.8"
tuirealm = { version = "0.4.2", features = [ "with-components" ] }
ureq = { version = "2.1.0", features = [ "json" ] }
whoami = "1.1.1"
wildmatch = "2.0.0"
toml = "0.5.0"
tui-realm-stdlib = "1.1.6"
tuirealm = "1.6.0"
unicode-width = "0.1.8"
whoami = "1.2.1"
wildmatch = "2.1.0"
[dev-dependencies]
pretty_assertions = "0.7.2"
pretty_assertions = "1.2.1"
serial_test = "^0.7.0"
[features]
github-actions = []
with-containers = []
default = [ "with-keyring" ]
github-actions = [ ]
with-keyring = [ "keyring" ]
[target."cfg(target_family = \"unix\")"]
[target."cfg(target_family = \"unix\")".dependencies]
users = "0.11.0"
[target."cfg(any(target_os = \"windows\", target_os = \"macos\"))"]
[target."cfg(any(target_os = \"windows\", target_os = \"macos\"))".dependencies]
keyring = "0.10.1"
[profile.dev]
incremental = true
[target."cfg(target_os = \"windows\")"]
[target."cfg(target_os = \"windows\")".dependencies]
path-slash = "0.1.4"
[profile.release]
strip = true

212
README.md
View File

@@ -13,18 +13,113 @@
<a href="https://veeso.github.io/termscp/#user-manual" target="_blank">User manual</a>
</p>
<p align="center">Developed by <a href="https://veeso.github.io/">@veeso</a></p>
<p align="center">Current version: 0.5.1 (21/06/2021)</p>
<p align="center">
<a href="https://github.com/veeso/termscp"
><img
height="20"
src="/assets/images/flags/us.png"
alt="English"
/></a>
&nbsp;
<a
href="/docs/de/README.md"
><img
height="20"
src="/assets/images/flags/de.png"
alt="Deutsch"
/></a>
&nbsp;
<a
href="/docs/es/README.md"
><img
height="20"
src="/assets/images/flags/es.png"
alt="Español"
/></a>
&nbsp;
<a
href="/docs/fr/README.md"
><img
height="20"
src="/assets/images/flags/fr.png"
alt="Français"
/></a>
&nbsp;
<a
href="/docs/it/README.md"
><img
height="20"
src="/assets/images/flags/it.png"
alt="Italiano"
/></a>
&nbsp;
<a
href="/docs/zh-CN/README.md"
><img
height="20"
src="/assets/images/flags/cn.png"
alt="简体中文"
/></a>
</p>
[![License: MIT](https://img.shields.io/badge/License-MIT-teal.svg)](https://opensource.org/licenses/MIT) [![Stars](https://img.shields.io/github/stars/veeso/termscp.svg)](https://github.com/veeso/termscp) [![Downloads](https://img.shields.io/crates/d/termscp.svg)](https://crates.io/crates/termscp) [![Crates.io](https://img.shields.io/badge/crates.io-v0.5.1-orange.svg)](https://crates.io/crates/termscp) [![Docs](https://docs.rs/termscp/badge.svg)](https://docs.rs/termscp)
<p align="center">Developed by <a href="https://veeso.github.io/" target="_blank">@veeso</a></p>
<p align="center">Current version: 0.9.0 (18/06/2022)</p>
[![Linux](https://github.com/veeso/termscp/workflows/Linux/badge.svg)](https://github.com/veeso/termscp/actions) [![MacOs](https://github.com/veeso/termscp/workflows/MacOS/badge.svg)](https://github.com/veeso/termscp/actions) [![Windows](https://github.com/veeso/termscp/workflows/Windows/badge.svg)](https://github.com/veeso/termscp/actions) [![FreeBSD](https://github.com/veeso/termscp/workflows/FreeBSD/badge.svg)](https://github.com/veeso/termscp/actions) [![Coverage Status](https://coveralls.io/repos/github/veeso/termscp/badge.svg)](https://coveralls.io/github/veeso/termscp)
<p align="center">
<a href="https://opensource.org/licenses/MIT"
><img
src="https://img.shields.io/badge/License-MIT-teal.svg"
alt="License-MIT"
/></a>
<a href="https://github.com/veeso/termscp/stargazers"
><img
src="https://img.shields.io/github/stars/veeso/termscp.svg"
alt="Repo stars"
/></a>
<a href="https://crates.io/crates/termscp"
><img
src="https://img.shields.io/crates/d/termscp.svg"
alt="Downloads counter"
/></a>
<a href="https://crates.io/crates/termscp"
><img
src="https://img.shields.io/crates/v/termscp.svg"
alt="Latest version"
/></a>
<a href="https://ko-fi.com/veeso">
<img
src="https://img.shields.io/badge/donate-ko--fi-red"
alt="Ko-fi"
/></a>
</p>
<p align="center">
<a href="https://github.com/veeso/termscp/actions"
><img
src="https://github.com/veeso/termscp/workflows/Linux/badge.svg"
alt="Linux CI"
/></a>
<a href="https://github.com/veeso/termscp/actions"
><img
src="https://github.com/veeso/termscp/workflows/MacOS/badge.svg"
alt="MacOS CI"
/></a>
<a href="https://github.com/veeso/termscp/actions"
><img
src="https://github.com/veeso/termscp/workflows/Windows/badge.svg"
alt="Windows CI"
/></a>
<a href="https://coveralls.io/github/veeso/termscp"
><img
src="https://coveralls.io/repos/github/veeso/termscp/badge.svg"
alt="Coveralls"
/></a>
</p>
---
## About termscp 🖥
Termscp is a feature rich terminal file transfer and explorer, with support for SCP/SFTP/FTP. So basically is a terminal utility with an TUI to connect to a remote server to retrieve and upload files and to interact with the local file system. It is **Linux**, **MacOS**, **BSD** and **Windows** compatible and supports SFTP, SCP, FTP and FTPS.
Termscp is a feature rich terminal file transfer and explorer, with support for SCP/SFTP/FTP/S3. So basically is a terminal utility with an TUI to connect to a remote server to retrieve and upload files and to interact with the local file system. It is **Linux**, **MacOS**, **FreeBSD** and **Windows** compatible.
![Explorer](assets/images/explorer.gif)
@@ -32,23 +127,27 @@ Termscp is a feature rich terminal file transfer and explorer, with support for
## Features 🎁
- 📁 Different communication protocols support
- SFTP
- SCP
- FTP and FTPS
- 📁 Different communication protocols
- **SFTP**
- **SCP**
- **FTP** and **FTPS**
- **S3**
- 🖥 Explore and operate on the remote and on the local machine file system with a handy UI
- Create, remove, rename, search, view and edit files
- ⭐ Connect to your favourite hosts through built-in bookmarks and recent connections
- 📝 View and edit text files with your favourite text editor
- 💁 SFTP/SCP authentication through SSH keys and username/password
- 🐧 Compatible with Windows, Linux, BSD and MacOS
- Customizable
- 📝 View and edit files with your favourite applications
- 💁 SFTP/SCP authentication with SSH keys and username/password
- 🐧 Compatible with Windows, Linux, FreeBSD and MacOS
- 🎨 Make it yours!
- Themes
- Custom file explorer format
- Customizable text editor
- Customizable file sorting
- and many other parameters...
- 📫 Get notified via Desktop Notifications when a large file has been transferred
- 🔭 Keep file changes synchronized with the remote host
- 🔐 Save your password in your operating system key vault
- 🦀 Rust-powered
- 🤝 Easy to extend with new file transfers protocols
- 👀 Developed keeping an eye on performance
- 🦄 Frequent awesome updates
@@ -57,57 +156,86 @@ Termscp is a feature rich terminal file transfer and explorer, with support for
## Get started 🚀
If you're considering to install termscp I want to thank you 💜 ! I hope you will enjoy termscp!
If you want to contribute to this project, don't forget to check out our contribute guide. [Read More](CONTRIBUTING.md)
If you want to contribute to this project, don't forget to check out our [contribute guide](CONTRIBUTING.md).
If you are a Linux, a FreeBSD or a MacOS user this simple shell script will install termscp on your system with a single command:
```sh
curl --proto '=https' --tlsv1.2 -sSf "https://raw.githubusercontent.com/veeso/termscp/main/install.sh" | sh
curl --proto '=https' --tlsv1.2 -sSLf "https://git.io/JBhDb" | sh
```
while if you're a Windows user, you can install termscp with [Chocolatey](https://chocolatey.org/).
while if you're a Windows user, you can install termscp with [Chocolatey](https://chocolatey.org/):
```sh
choco install termscp
```
For more information or other platforms, please visit [veeso.github.io](https://veeso.github.io/termscp/#get-started) to view all installation methods.
---
⚠️ If you're looking on how to update termscp just run termscp from CLI with: `(sudo) termscp --update` ⚠️
## Buy me a coffee ☕
### Requirements ❗
If you like termscp and you'd love to see the project to grow, please consider a little donation 🥳
- **Linux** users:
- libssh
- libdbus-1
- pkg-config
- **FreeBSD** users:
- libssh
- dbus
- pkgconf
[![Buy-me-a-coffee](https://img.buymeacoffee.com/button-api/?text=Buy%20me%20a%20coffee&emoji=&slug=veeso&button_colour=404040&font_colour=ffffff&font_family=Comic&outline_colour=ffffff&coffee_colour=FFDD00)](https://www.buymeacoffee.com/veeso)
### Optional Requirements ✔️
These requirements are not forced required to run termscp, but to enjoy all of its features
- **Linux/FreeBSD** users:
- To **open** files via `V` (at least one of these)
- *xdg-open*
- *gio*
- *gnome-open*
- *kde-open*
- **Linux** users:
- A keyring manager: read more in the [User manual](docs/man.md#linux-keyring)
- **WSL** users
- To **open** files via `V` (at least one of these)
- [wslu](https://github.com/wslutilities/wslu)
---
## Documentation 📚
## Support the developer ☕
The developer documentation can be found on Rust Docs at <https://docs.rs/termscp>
If you like termscp and you're grateful for the work I've done, please consider a little donation 🥳
You can make a donation with one of these platforms:
[![ko-fi](https://img.shields.io/badge/Ko--fi-F16061?style=for-the-badge&logo=ko-fi&logoColor=white)](https://ko-fi.com/veeso)
[![PayPal](https://img.shields.io/badge/PayPal-00457C?style=for-the-badge&logo=paypal&logoColor=white)](https://www.paypal.me/chrisintin)
---
## Known issues 🧻
## User manual 📚
- `NoSuchFileOrDirectory` on connect (WSL1): I know about this issue and it's a glitch of WSL I guess. Don't worry about it, just move the termscp executable into another PATH location, such as `/usr/bin`, or install it through the appropriate package format (e.g. deb).
The user manual can be found on the [termscp's website](https://veeso.github.io/termscp/#user-manual) or on [Github](docs/man.md).
---
## Upcoming Features 🧪
Major termscp releases will now be seasonal, so expect 4 major updates during the year.
For **2022** there will be two major updates during the year.
Planned for *🏄 Summer update 🌴*:
Planned for *future updates ⏲️*:
- **Keyring-rs on Linux 🔐**: Check for updates in [this issue](https://github.com/veeso/termscp/issues/2)
- **SMB Support 🎉**: This will require a long time to be implemented, since I'm currently working on a Rust native SMB library, since I don't want to add new C-bindings. ~~Fear the 🦚~~
- **Open files with any application ☄️**: possibility to open files of any kind and with any application directly inside termscp. This will be achieved through this awesome crate [open-rs](https://github.com/Byron/open-rs).
- **Translations 🌐**: The feature consists in the possibility for the user to install the language pack for the language he prefers in order to replace the default English interface. The following language will be provided along to English:
- 🇨🇳 Chinese
- 🇫🇷 French
- 🇩🇪 German
- 🇮🇹 Italian
- 🇳🇱 Dutch
- 🇪🇸 Spanish
- **Configuration profile for bookmarks 📚**: Basically this feature adds the possibility to have a specific setup for a certain host, instead of having only one global configuration. (Maybe will be postponed to spring 2022).
To be planned:
- **Themes provider 🎨**: I'm still thinking about how I will implement this, but basically the idea is to have a configuration file where it will be possible to define the color schema for the entire application. I haven't planned this release yet
- **Configuration profile for bookmarks 📚**: I would like to, but I still have to analyze it.
- **AWS S3 support 🪣**: There is already a library for AWS S3, but this is really on bottom of my implementation list at the moment, due to interest and I don't really have a system where to test it.
Along to new features, termscp developments is now focused on UI and performance improvements, so if you have any suggestion, feel free to open an issue.
Along to new features, termscp developments is now focused on UX and performance improvements, so if you have any suggestion, feel free to open an issue.
---
@@ -116,6 +244,8 @@ Along to new features, termscp developments is now focused on UI and performance
Contributions, bug reports, new features and questions are welcome! 😉
If you have any question or concern, or you want to suggest a new feature, or you want just want to improve termscp, feel free to open an issue or a PR.
An **appreciated** contribution would be a translation of the user manual and readme in **other languages**
Please follow [our contributing guidelines](CONTRIBUTING.md)
---
@@ -128,16 +258,16 @@ View termscp's changelog [HERE](CHANGELOG.md)
## Powered by 💪
termscp is powered by these aweseome projects:
termscp is powered by these awesome projects:
- [bytesize](https://github.com/hyunsik/bytesize)
- [crossterm](https://github.com/crossterm-rs/crossterm)
- [edit](https://github.com/milkey-mouse/edit)
- [keyring-rs](https://github.com/hwchen/keyring-rs)
- [open-rs](https://github.com/Byron/open-rs)
- [remotefs](https://github.com/veeso/remotefs-rs)
- [rpassword](https://github.com/conradkleinespel/rpassword)
- [rust-ftp](https://github.com/mattnenterprise/rust-ftp)
- [ssh2-rs](https://github.com/alexcrichton/ssh2-rs)
- [textwrap](https://github.com/mgeisler/textwrap)
- [self_update](https://github.com/jaemk/self_update)
- [tui-rs](https://github.com/fdehau/tui-rs)
- [tui-realm](https://github.com/veeso/tui-realm)
- [whoami](https://github.com/libcala/whoami)

10
SECURITY.md Normal file
View File

@@ -0,0 +1,10 @@
# Security Policy
## Supported Versions
Only latst version of termscp has the latest security updates.
Because of that, **you should always consider updating termscp to the latest version**.
## Reporting a Vulnerability
If you have any security vulnerability or concern to report, please open an issue using the `Security report` template.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 237 KiB

After

Width:  |  Height:  |  Size: 336 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 313 KiB

After

Width:  |  Height:  |  Size: 937 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 MiB

After

Width:  |  Height:  |  Size: 3.2 MiB

BIN
assets/images/flags/br.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.3 KiB

BIN
assets/images/flags/cn.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

BIN
assets/images/flags/de.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

BIN
assets/images/flags/dk.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.9 KiB

BIN
assets/images/flags/es.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

BIN
assets/images/flags/fr.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

BIN
assets/images/flags/it.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

BIN
assets/images/flags/jp.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.2 KiB

BIN
assets/images/flags/kr.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.7 KiB

BIN
assets/images/flags/nl.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

BIN
assets/images/flags/ru.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

BIN
assets/images/flags/us.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 484 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 KiB

After

Width:  |  Height:  |  Size: 2.8 KiB

View File

@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:bx="https://boxy-svg.com" viewBox="0 0 500 500"><path style="fill:#404040" d="M 15 0 H 484 A 16 16 0 0 1 500 16 V 47.312 H 0 V 15 A 15 15 0 0 1 15 0 Z" bx:shape="rect 0 0 500 47.312 15 16 0 0 1@05baa068"/><circle style="fill:#ea4444" cx="29.473" cy="23.011" r="7.344"/><circle style="fill:#eac944" cx="58.177" cy="22.543" r="7.344" transform="matrix(1, 0, 0, 1.031863, -5.389861, -0.016285)"/><circle style="fill:#34b938" cx="58.177" cy="22.543" r="7.344" transform="matrix(1, 0, 0, 1.031863, 17.888227, -0.016285)"/><rect width="500" height="452.688" y="47.312" style="fill:#31363b"/><polygon style="stroke:#000;fill:#f0f0f0" points="71.581 100 224.35 252.769 77.119 400 25.235 348.115 122.193 251.156 22.129 151.093"/><rect style="fill:#f0f0f0" width="242.408" height="49.262" x="235.188" y="381.519" rx="10" ry="10"/><g transform="matrix(0.513677, 0, 0, 0.513677, 257.101013, 152.253387)"><polygon style="fill:#f0f0f0" points="196.4 0 292 49.2 388 98 292 147.2 196.4 196.4 100.8 147.2 4.8 98 100.8 49.2"/><polygon style="fill:#31363b" points="316 179.6 316 135.2 268 159.6 268 204 294.4 171.6"/><polygon style="fill:#f0f0f0" points="196.4 196.4 196.4 392.8 388 294.8 388 98 316 135.2 314.4 136 314.4 179.2 294.4 171.6 268 204 268 159.6"/><polygon style="fill:#f0f0f0" points="196.4 392.8 196.4 196.4 100.8 147.2 4.8 98 4.8 294.8"/><polygon style="fill:#31363b" points="76.8 61.2 268 159.6 314.4 136 316 135.2 124.8 36.8 100.8 49.2"/></g></svg>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 500 500"><circle style="fill:#31363b" cx="250" cy="250" r="250"/><circle style="fill:#ea4444" cx="225" cy="40" r="7.344"/><circle style="fill:#eac944" cx="58.177" cy="22.745" r="7.344" transform="matrix(1, 0, 0, 1.031863, 191.822998, 16.530386)"/><circle style="fill:#34b938" cx="57.564" cy="22.269" r="7.344" transform="matrix(1, 0, 0, 1.031863, 217.43605, 17.021263)"/><polygon style="stroke:#000;fill:#f0f0f0" points="83.462 135.575 200 252.112 87.687 364.425 48.108 324.846 122.07 250.881 45.738 174.55"/><g transform="matrix(0.408921, 0, 0, 0.408921, 241.338654, 169.687912)"><polygon style="fill:#f0f0f0" points="196.4 0 292 49.2 388 98 292 147.2 196.4 196.4 100.8 147.2 4.8 98 100.8 49.2"/><polygon style="fill:#31363b" points="316 179.6 316 135.2 268 159.6 268 204 294.4 171.6"/><polygon style="fill:#f0f0f0" points="196.4 196.4 196.4 392.8 388 294.8 388 98 316 135.2 314.4 136 314.4 179.2 294.4 171.6 268 204 268 159.6"/><polygon style="fill:#f0f0f0" points="196.4 392.8 196.4 196.4 100.8 147.2 4.8 98 4.8 294.8"/><polygon style="fill:#31363b" points="76.8 61.2 268 159.6 314.4 136 316 135.2 124.8 36.8 100.8 49.2"/></g><rect style="fill:#f0f0f0" width="200" height="35.702" x="222.229" y="364.298" rx="10" ry="10"/></svg>

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

BIN
assets/images/themes.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 224 KiB

47
dist/build/deploy.sh vendored
View File

@@ -1,47 +0,0 @@
#!/bin/bash
if [ -z "$1" ]; then
echo "Usage: deploy.sh <version>"
exit 1
fi
VERSION=$1
set -e # Don't fail
# Create pkgs directory
cd ..
PKGS_DIR=$(pwd)/pkgs
cd -
mkdir -p ${PKGS_DIR}/
# Build x86_64_deb
cd x86_64_debian9/
docker build --tag termscp-${VERSION}-x86_64_debian9 .
cd -
mkdir -p ${PKGS_DIR}/deb/
CONTAINER_NAME=$(docker create termscp-${VERSION}-x86_64_debian9 termscp-${VERSION}-x86_64_debian9)
docker cp ${CONTAINER_NAME}:/usr/src/termscp/target/debian/termscp_${VERSION}_amd64.deb ${PKGS_DIR}/deb/
# Build x86_64_centos7
cd x86_64_centos7/
docker build --tag termscp-${VERSION}-x86_64_centos7 .
cd -
mkdir -p ${PKGS_DIR}/rpm/
CONTAINER_NAME=$(docker create termscp-${VERSION}-x86_64_centos7 termscp-${VERSION}-x86_64_centos7)
docker cp ${CONTAINER_NAME}:/usr/src/termscp/target/release/rpmbuild/RPMS/x86_64/termscp-${VERSION}-1.el7.x86_64.rpm ${PKGS_DIR}/rpm/termscp-${VERSION}-1.x86_64.rpm
# Build x86_64_archlinux
##################### TEMP REMOVED ###################################
# cd x86_64_archlinux/
# docker build --tag termscp-${VERSION}-x86_64_archlinux .
# # Create container and get AUR pkg
# cd -
# mkdir -p ${PKGS_DIR}/arch/
# CONTAINER_NAME=$(docker create termscp-${VERSION}-x86_64_archlinux termscp-${VERSION}-x86_64_archlinux)
# docker cp ${CONTAINER_NAME}:/usr/src/termscp/termscp-${VERSION}-x86_64.tar.gz ${PKGS_DIR}/arch/
# docker cp ${CONTAINER_NAME}:/usr/src/termscp/PKGBUILD ${PKGS_DIR}/arch/
# docker cp ${CONTAINER_NAME}:/usr/src/termscp/.SRCINFO ${PKGS_DIR}/arch/
# # Replace termscp-bin with termscp in PKGBUILD
# sed -i 's/termscp-bin/termscp/g' ${PKGS_DIR}/arch/PKGBUILD
##################### TEMP REMOVED ###################################
exit $?

39
dist/build/docker.sh vendored Executable file
View File

@@ -0,0 +1,39 @@
#!/bin/bash
if [ -z "$1" ]; then
echo "Usage: docker.sh <version>"
exit 1
fi
VERSION=$1
set -e # Don't fail
# Create pkgs directory
cd ..
PKGS_DIR=$(pwd)/pkgs
cd -
mkdir -p ${PKGS_DIR}/
# Build x86_64_deb
cd x86_64_debian9/
docker build --build-arg branch=${VERSION} --tag termscp-${VERSION}-x86_64_debian9 .
cd -
mkdir -p ${PKGS_DIR}/deb/
mkdir -p ${PKGS_DIR}/x86_64-unknown-linux-gnu/
CONTAINER_NAME=$(docker create termscp-${VERSION}-x86_64_debian9 /bin/bash)
docker cp ${CONTAINER_NAME}:/usr/src/termscp/target/debian/termscp_${VERSION}_amd64.deb ${PKGS_DIR}/deb/
docker cp ${CONTAINER_NAME}:/usr/src/termscp/target/release/termscp ${PKGS_DIR}/x86_64-unknown-linux-gnu/
# Make tar.gz
cd ${PKGS_DIR}/x86_64-unknown-linux-gnu/
tar cvzf termscp-v${VERSION}-x86_64-unknown-linux-gnu.tar.gz termscp
rm termscp
cd -
# Build x86_64_centos7
cd x86_64_centos7/
docker build --build-arg branch=${VERSION} --tag termscp-${VERSION}-x86_64_centos7 .
cd -
mkdir -p ${PKGS_DIR}/rpm/
CONTAINER_NAME=$(docker create termscp-${VERSION}-x86_64_centos7 /bin/bash)
docker cp ${CONTAINER_NAME}:/usr/src/termscp/target/release/rpmbuild/RPMS/x86_64/termscp-${VERSION}-1.el7.x86_64.rpm ${PKGS_DIR}/rpm/termscp-${VERSION}-1.x86_64.rpm
exit $?

53
dist/build/freebsd.sh vendored Executable file
View File

@@ -0,0 +1,53 @@
#!/bin/sh
if [ -z "$1" ]; then
echo "Usage: freebsd.sh <version>"
exit 1
fi
VERSION=$1
set -e # Don't fail
# Go to root dir
cd ../../
# Check if in correct directory
if [ ! -f Cargo.toml ]; then
echo "Please start freebsd.sh from dist/build/ directory"
exit 1
fi
# Build release
cargo build --release && cargo strip
# Make pkg
cd target/release/
PKG="termscp-v${VERSION}-x86_64-unknown-freebsd.tar.gz"
tar czf $PKG termscp
sha256sum $PKG
# Calc sha256 of exec and copy to path
HASH=`sha256sum termscp | cut -d ' ' -f1`
sudo cp termscp /usr/local/bin/termscp
mkdir -p ../../dist/pkgs/freebsd/
mv $PKG ../../dist/pkgs/freebsd/$PKG
cd ../../dist/pkgs/freebsd/
rm manifest
echo -e "name: \"termscp\"" > manifest
echo -e "version: $VERSION" >> manifest
echo -e "origin: veeso/termscp" >> manifest
echo -e "comment: \"A feature rich terminal UI file transfer and explorer with support for SCP/SFTP/FTP/S3\"" >> manifest
echo -e "desc: <<EOD\n\
A feature rich terminal UI file transfer and explorer with support for SCP/SFTP/FTP/S3\n\
EOD\n\
arch: \"amd64\"\n\
www: \"https://veeso.github.io/termscp/\"\n\
maintainer: \"christian.visintin1997@gmail.com\"\n\
prefix: \"/usr/local/bin\"\n\
deps: {\n\
libssh: {origin: security/libssh, version: 0.9.5}\n\
}\n\
files: {\n\
/usr/local/bin/termscp: \"$HASH\"\n\
}\n\
" >> manifest
exit $?

95
dist/build/macos.sh vendored Executable file
View File

@@ -0,0 +1,95 @@
#!/bin/sh
make_pkg() {
ARCH=$1
VERSION=$2
TARGET_DIR="$3"
if [ -z "$TARGET_DIR" ]; then
TARGET_DIR=target/release/
fi
ROOT_DIR=$(pwd)
cd $TARGET_DIR
PKG="termscp-v${VERSION}-${ARCH}-apple-darwin.tar.gz"
tar czf $PKG termscp
HASH=$(sha256sum $PKG)
mkdir -p ${ROOT_DIR}/dist/pkgs/macos/
mv $PKG ${ROOT_DIR}/dist/pkgs/macos/$PKG
cd -
echo "$HASH"
}
build_openssl_arm64() {
# setup dirs
BUILD_DIR=$(pwd)
OPENSSL_BUILD_DIR=/tmp/openssl-build/
# setup openssl dir
mkdir -p $OPENSSL_DIR
cd $OPENSSL_DIR
# check if openssl has already been compiled
if [ -e ./include/ ]; then
return 0
fi
# download package
TEMP_TGZ=/tmp/openssl.tar.gz
wget https://www.openssl.org/source/openssl-1.1.1m.tar.gz -O $TEMP_TGZ
# setup build dir
mkdir -p $OPENSSL_BUILD_DIR
cd $OPENSSL_BUILD_DIR
# extract sources
tar xzvf $TEMP_TGZ
rm $TEMP_TGZ
# build
cd openssl-1.1.1m/
export MACOSX_DEPLOYMENT_TARGET=10.15
./Configure enable-rc5 zlib darwin64-arm64-cc no-asm
make
make install DESTDIR=$(pwd)/out/
# copy compiled assets to openssl dir
cp -r out/usr/local/* $OPENSSL_DIR/
# go back to build dir
cd $BUILD_DIR
# delete temp dir
rm -rf $OPENSSL_BUILD_DIR
return 0
}
if [ -z "$1" ]; then
echo "Usage: macos.sh <version>"
exit 1
fi
VERSION=$1
export BUILD_ROOT=$(pwd)/../../
set -e # Don't fail
# Go to root dir
cd ../../
# Check if in correct directory
if [ ! -f Cargo.toml ]; then
echo "Please start macos.sh from dist/build/ directory"
exit 1
fi
# Build release (x86_64)
cargo build --release
# Make pkg
X86_64_HASH=$(make_pkg "x86_64" $VERSION)
# set openssl dir
export OPENSSL_DIR=$BUILD_ROOT/dist/build/macos/openssl/
export OPENSSL_STATIC=1
export OPENSSL_LIB_DIR=${OPENSSL_DIR}/lib/
export OPENSSL_INCLUDE_DIR=${OPENSSL_DIR}/include/
# build openssl
build_openssl_arm64
cd $BUILD_ROOT
# Build ARM64 pkg
cargo build --release --target aarch64-apple-darwin
# Make pkg
ARM64_HASH=$(make_pkg "arm64" $VERSION "target/aarch64-apple-darwin/release/")
echo "x86_64 hash: $X86_64_HASH"
echo "arm64 hash: $ARM64_HASH"
exit $?

20
dist/build/windows.ps1 vendored Executable file
View File

@@ -0,0 +1,20 @@
$ErrorActionPreference = 'Stop';
if ($args.Count -eq 0) {
Write-Output "Usage: windows.ps1 <version>"
exit 1
}
$version = $args[0]
# Go to root directory
Set-Location ..\..\
# Build
cargo build --release
# Make zip
$zipName = "termscp-v$version-x86_64-pc-windows-msvc.zip"
Set-Location .\target\release\
Compress-Archive termscp.exe $zipName
# Get checksum
checksum.exe -t sha256 $zipName
Move-Item $zipName .\..\..\dist\pkgs\windows\$zipName

View File

@@ -1,19 +1,24 @@
FROM rust:1.48.0 AS builder
FROM rust:1.55.0 AS builder
WORKDIR /usr/src/
# Add toolchains
RUN rustup target add x86_64-unknown-linux-gnu
# Install dependencies
RUN apt update && apt install -y rpm
RUN apt update && apt install -y \
git \
gcc \
pkg-config \
libssl-dev \
libssh2-1-dev \
libdbus-1-dev \
curl
# Clone repository
RUN git clone https://github.com/veeso/termscp.git
# Set workdir to termscp
WORKDIR /usr/src/termscp/
# Install cargo RPM/Deb
RUN cargo install cargo-deb cargo-rpm
RUN cargo install cargo-strip
# Build for x86_64
RUN cargo build --release --target x86_64-unknown-linux-gnu
# Build pkgs
RUN cargo deb && cargo rpm init && cargo rpm build
RUN cargo build --release --target x86_64-unknown-linux-gnu && cargo strip
CMD ["sh"]

View File

@@ -1,33 +0,0 @@
FROM archlinux:latest as builder
WORKDIR /usr/src/
# Install dependencies
RUN pacman -Syu --noconfirm \
git \
gcc \
openssl \
pkg-config \
sudo
# Install rust
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs > /tmp/rust.sh && \
chmod +x /tmp/rust.sh && \
/tmp/rust.sh -y
# Create build user
RUN useradd build -m && \
passwd -d build && \
mkdir -p termscp && \
chown -R build.build termscp/
# Clone repository
RUN git clone https://github.com/veeso/termscp.git
# Set workdir to termscp
WORKDIR /usr/src/termscp/
# Install cargo arxch
RUN source $HOME/.cargo/env && cargo install cargo-aur
# Build for x86_64
RUN source $HOME/.cargo/env && cargo build --release
# Build pkgs
RUN source $HOME/.cargo/env && cargo aur
# Create SRCINFO
RUN chown -R build.build ../termscp/ && sudo -u build bash -c 'makepkg --printsrcinfo > .SRCINFO'
CMD ["sh"]

View File

@@ -1,5 +1,7 @@
FROM centos:centos7 as builder
ARG branch
ENV branch=$branch
WORKDIR /usr/src/
# Install dependencies
RUN yum -y install \
@@ -7,13 +9,15 @@ RUN yum -y install \
gcc \
openssl \
pkgconfig \
openssl-devel
dbus-devel \
openssl-devel \
bash
# Install rust
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs > /tmp/rust.sh && \
chmod +x /tmp/rust.sh && \
/tmp/rust.sh -y
# Clone repository
RUN git clone https://github.com/veeso/termscp.git
RUN git clone --branch $branch https://github.com/veeso/termscp.git
# Set workdir to termscp
WORKDIR /usr/src/termscp/
# Install cargo arxch

View File

@@ -8,6 +8,7 @@ RUN apt update && apt install -y \
pkg-config \
libssl-dev \
libssh2-1-dev \
libdbus-1-dev \
curl
# Install rust

View File

@@ -1,5 +1,7 @@
FROM debian:stretch
ARG branch
ENV branch=$branch
WORKDIR /usr/src/
# Install dependencies
RUN apt update && apt install -y \
@@ -8,6 +10,8 @@ RUN apt update && apt install -y \
pkg-config \
libssl-dev \
libssh2-1-dev \
libdbus-1-dev \
bash \
curl
# Install rust
@@ -15,7 +19,7 @@ RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs > /tmp/rust.sh &&
chmod +x /tmp/rust.sh && \
/tmp/rust.sh -y
# Clone repository
RUN git clone https://github.com/veeso/termscp.git
RUN git clone --branch $branch https://github.com/veeso/termscp.git
# Set workdir to termscp
WORKDIR /usr/src/termscp/
# Install cargo deb
@@ -25,4 +29,4 @@ RUN . $HOME/.cargo/env && cargo build --release
# Build pkgs
RUN . $HOME/.cargo/env && cargo deb
CMD ["sh"]
CMD ["bash"]

View File

@@ -1,14 +0,0 @@
pkgbase = termscp
pkgdesc = termscp is a SCP/SFTP/FTPS client for command line with an integrated UI to explore the remote file system. Basically WinSCP on a terminal.
pkgver = 0.5.1
pkgrel = 1
url = https://github.com/veeso/termscp
arch = x86_64
license = MIT
provides = termscp
options = strip
source = https://github.com/veeso/termscp/releases/download/v0.5.1/termscp-0.5.1-x86_64.tar.gz
sha256sums = f66a1d1602dc8ea336ba4a42bfbe818edc9c20722e1761b471b76109c272094c
pkgname = termscp

View File

@@ -1,16 +0,0 @@
# Maintainer: Christian Visintin
pkgname=termscp
pkgver=0.5.1
pkgrel=1
pkgdesc="termscp is a SCP/SFTP/FTPS client for command line with an integrated UI to explore the remote file system. Basically WinSCP on a terminal."
url="https://github.com/veeso/termscp"
license=("MIT")
arch=("x86_64")
provides=("termscp")
options=("strip")
source=("https://github.com/veeso/termscp/releases/download/v$pkgver/termscp-$pkgver-x86_64.tar.gz")
sha256sums=("f66a1d1602dc8ea336ba4a42bfbe818edc9c20722e1761b471b76109c272094c")
package() {
install -Dm755 termscp -t "$pkgdir/usr/bin/"
}

View File

@@ -1,17 +0,0 @@
name: "termscp"
version: 0.5.1
origin: veeso/termscp
comment: "A feature rich terminal UI file transfer and explorer with support for SCP/SFTP/FTP"
desc: <<EOD
A feature rich terminal UI file transfer and explorer with support for SCP/SFTP/FTP
EOD
arch: "amd64"
www: "https://veeso.github.io/termscp/"
maintainer: "christian.visintin1997@gmail.com"
prefix: "/usr/local/bin"
deps: {
libssh: {origin: security/libssh, version: 0.9.5}
}
files: {
/usr/local/bin/termscp: "87543d13b11b6e601ba8cdde9d704c80dc3515f1681fbf71fd0b31d7206efc09"
}

288
docs/de/README.md Normal file
View File

@@ -0,0 +1,288 @@
# termscp
<p align="center">
<img src="/assets/images/termscp.svg" width="256" height="256" />
</p>
<p align="center">~ Eine funktionsreiche Terminal-Dateiübertragung ~</p>
<p align="center">
<a href="https://veeso.github.io/termscp/" target="_blank">Webseite</a>
·
<a href="https://veeso.github.io/termscp/#get-started" target="_blank">Installation</a>
·
<a href="https://veeso.github.io/termscp/#user-manual" target="_blank">Benutzerhandbuch</a>
</p>
<p align="center">
<a href="https://github.com/veeso/termscp"
><img
height="20"
src="/assets/images/flags/us.png"
alt="English"
/></a>
&nbsp;
<a
href="/docs/de/README.md"
><img
height="20"
src="/assets/images/flags/de.png"
alt="Deutsch"
/></a>
&nbsp;
<a
href="/docs/es/README.md"
><img
height="20"
src="/assets/images/flags/es.png"
alt="Español"
/></a>
&nbsp;
<a
href="/docs/fr/README.md"
><img
height="20"
src="/assets/images/flags/fr.png"
alt="Français"
/></a>
&nbsp;
<a
href="/docs/it/README.md"
><img
height="20"
src="/assets/images/flags/it.png"
alt="Italiano"
/></a>
&nbsp;
<a
href="/docs/zh-CN/README.md"
><img
height="20"
src="/assets/images/flags/cn.png"
alt="简体中文"
/></a>
</p>
<p align="center">Entwickelt von <a href="https://veeso.github.io/" target="_blank">@veeso</a></p>
<p align="center">Aktuelle Version: 0.9.0 (18/06/2022)</p>
<p align="center">
<a href="https://opensource.org/licenses/MIT"
><img
src="https://img.shields.io/badge/License-MIT-teal.svg"
alt="License-MIT"
/></a>
<a href="https://github.com/veeso/termscp/stargazers"
><img
src="https://img.shields.io/github/stars/veeso/termscp.svg"
alt="Repo stars"
/></a>
<a href="https://crates.io/crates/termscp"
><img
src="https://img.shields.io/crates/d/termscp.svg"
alt="Downloads counter"
/></a>
<a href="https://crates.io/crates/termscp"
><img
src="https://img.shields.io/crates/v/termscp.svg"
alt="Latest version"
/></a>
<a href="https://ko-fi.com/veeso">
<img
src="https://img.shields.io/badge/donate-ko--fi-red"
alt="Ko-fi"
/></a>
</p>
<p align="center">
<a href="https://github.com/veeso/termscp/actions"
><img
src="https://github.com/veeso/termscp/workflows/Linux/badge.svg"
alt="Linux CI"
/></a>
<a href="https://github.com/veeso/termscp/actions"
><img
src="https://github.com/veeso/termscp/workflows/MacOS/badge.svg"
alt="MacOS CI"
/></a>
<a href="https://github.com/veeso/termscp/actions"
><img
src="https://github.com/veeso/termscp/workflows/Windows/badge.svg"
alt="Windows CI"
/></a>
<a href="https://github.com/veeso/termscp/actions"
><img
src="https://github.com/veeso/termscp/workflows/FreeBSD/badge.svg"
alt="FreeBSD CI"
/></a>
<a href="https://coveralls.io/github/veeso/termscp"
><img
src="https://coveralls.io/repos/github/veeso/termscp/badge.svg"
alt="Coveralls"
/></a>
</p>
---
## Über termscp 🖥
Termscp ist ein funktionsreicher Terminal-Dateitransfer und Explorer mit Unterstützung für SCP/SFTP/FTP/S3. Im Grunde handelt es sich also um ein Terminal-Dienstprogramm mit einer TUI, um eine Verbindung zu einem Remote-Server herzustellen, um Dateien abzurufen und hochzuladen und mit dem lokalen Dateisystem zu interagieren. Es ist **Linux**, **MacOS**, **FreeBSD** und **Windows** kompatibel.
![Explorer](/assets/images/explorer.gif)
---
## Features 🎁
- 📁 Verschiedene Kommunikationsprotokolle
- **SFTP**
- **SCP**
- **FTP** und **FTPS**
- **S3**
- 🖥 Erkunden und bedienen Sie das Dateisystem der Fernbedienung und des lokalen Computers mit einer praktischen Benutzeroberfläche
- Erstellen, Entfernen, Umbenennen, Suchen, Anzeigen und Bearbeiten von Dateien
- ⭐ Verbinden Sie sich über integrierte Lesezeichen und aktuelle Verbindungen mit Ihren Lieblingshosts
- 📝 Anzeigen und Bearbeiten von Dateien mit Ihren bevorzugten Anwendungen
- 💁 SFTP/SCP-Authentifizierung mit SSH-Schlüsseln und Benutzername/Passwort
- 🐧 Kompatibel mit Windows, Linux, FreeBSD und MacOS
- 🎨 Mach es zu deinem!
- Themen
- Benutzerdefiniertes Datei-Explorer-Format
- Anpassbarer Texteditor
- Anpassbare Dateisortierung
- und viele andere Parameter...
- 📫 Lassen Sie sich benachrichtigen, wenn eine große Datei übertragen wurde
- 🔭 Halten Sie Dateiänderungen mit dem Remote-Host synchron
- 🔐 Speichern Sie Ihr Passwort in Ihrem Betriebssystem-Schlüsseltresor
- 🦀 Rust-powered
- 👀 Entwickelt, um die Leistung im Auge zu behalten
- 🦄 Häufige tolle Updates
---
## Loslegen 🚀
Wenn Sie überlegen, termscp zu installieren, möchte ich Ihnen danken 💜 ! Ich hoffe, Sie werden Termscp genießen!
Wenn Sie zu diesem Projekt beitragen möchten, vergessen Sie nicht, unseren [Beitragsleitfaden](../../CONTRIBUTING.md) zu lesen.
Wenn Sie ein Linux-, FreeBSD- oder MacOS-Benutzer sind, installiert dieses einfache Shell-Skript termscp mit einem einzigen Befehl auf Ihrem System:
```sh
curl --proto '=https' --tlsv1.2 -sSLf "https://git.io/JBhDb" | sh
```
Wenn Sie ein Windows-Benutzer sind, können Sie termscp mit [Chocolatey](https://chocolatey.org/) installieren:
```sh
choco install termscp
```
Für weitere Informationen oder andere Plattformen besuchen Sie bitte [veeso.github.io](https://veeso.github.io/termscp/#get-started), um alle Installationsmethoden anzuzeigen.
⚠️ Wenn Sie wissen möchten, wie Sie termscp aktualisieren können, führen Sie einfach termscp über die CLI aus mit: `(sudo) termscp --update` ⚠️
### Softwareanforderungen ❗
- **Linux** Benutzer:
- libssh
- libdbus-1
- pkg-config
- **FreeBSD** Benutzer:
- libssh
- dbus
- pkgconf
### Optionale Softwareanforderungen ✔️
Diese Anforderungen sind nicht zwingend erforderlich, um termscp auszuführen, sondern um alle Funktionen nutzen zu können
- **Linux/FreeBSD** Benutzer:
- Um Dateien mit `V` zu **öffnen** (mindestens eines davon)
- *xdg-open*
- *gio*
- *gnome-open*
- *kde-open*
- **Linux** Benutzer:
- Ein Keyring-manager: Lesen Sie mehr in der [Bedienungsanleitung](man.md#linux-keyring)
- **WSL** Benutzer
- Um Dateien mit `V` zu **öffnen** (mindestens eines davon)
- [wslu](https://github.com/wslutilities/wslu)
---
## Unterstütze mich ☕
Wenn Ihnen termscp gefällt und Sie für die Arbeit, die ich geleistet habe, dankbar sind, denken Sie bitte über eine kleine Spende nach 🥳
Sie können mit einer dieser Plattformen spenden:
[![ko-fi](https://img.shields.io/badge/Ko--fi-F16061?style=for-the-badge&logo=ko-fi&logoColor=white)](https://ko-fi.com/veeso)
[![PayPal](https://img.shields.io/badge/PayPal-00457C?style=for-the-badge&logo=paypal&logoColor=white)](https://www.paypal.me/chrisintin)
---
## User manual 📚
Das Benutzerhandbuch finden Sie auf der [termscp-Website](https://veeso.github.io/termscp/#user-manual) oder auf [Github](man.md).
---
## Contributing and issues 🤝🏻
Beiträge, Fehlerberichte, neue Funktionen und Fragen sind willkommen! 😉
Wenn Sie Fragen oder Bedenken haben, eine neue Funktion vorschlagen oder einfach nur die Bedingungen verbessern möchten, können Sie ein Problem oder eine PR erstellen.
Bitte befolgen Sie [unsere Beitragsrichtlinien](../../CONTRIBUTING.md)
---
## Changelog ⏳
Änderungsprotokoll von termscp ansehen [HIER](../../CHANGELOG.md)
---
## Powered by 💪
termscp wird von diesen großartigen Projekten unterstützt:
- [bytesize](https://github.com/hyunsik/bytesize)
- [crossterm](https://github.com/crossterm-rs/crossterm)
- [edit](https://github.com/milkey-mouse/edit)
- [keyring-rs](https://github.com/hwchen/keyring-rs)
- [open-rs](https://github.com/Byron/open-rs)
- [rpassword](https://github.com/conradkleinespel/rpassword)
- [rust-s3](https://github.com/durch/rust-s3)
- [self_update](https://github.com/jaemk/self_update)
- [ssh2-rs](https://github.com/alexcrichton/ssh2-rs)
- [suppaftp](https://github.com/veeso/suppaftp)
- [tui-rs](https://github.com/fdehau/tui-rs)
- [tui-realm](https://github.com/veeso/tui-realm)
- [whoami](https://github.com/libcala/whoami)
- [wildmatch](https://github.com/becheran/wildmatch)
---
## Galerie 🎬
> Termscp Home
![Auth](/assets/images/auth.gif)
> Bookmarks
![Bookmarks](/assets/images/bookmarks.gif)
> Setup
![Setup](/assets/images/config.gif)
> Text editor
![TextEditor](/assets/images/text-editor.gif)
---
## License 📃
termscp ist unter der MIT-Lizenz lizenziert.
Du kannst die gesamte Lizenz [HIER](../../LICENSE) lesen

540
docs/de/man.md Normal file
View File

@@ -0,0 +1,540 @@
# User manual 🎓
- [User manual 🎓](#user-manual-)
- [Usage ❓](#usage-)
- [Address argument 🌎](#address-argument-)
- [AWS S3 address argument](#aws-s3-address-argument)
- [How Password can be provided 🔐](#how-password-can-be-provided-)
- [S3 connection parameters](#s3-connection-parameters)
- [S3 credentials 🦊](#s3-credentials-)
- [File explorer 📂](#file-explorer-)
- [Keybindings ⌨](#keybindings-)
- [Work on multiple files 🥷](#work-on-multiple-files-)
- [Synchronized browsing ⏲️](#synchronized-browsing-)
- [Open and Open With 🚪](#open-and-open-with-)
- [Bookmarks ⭐](#bookmarks-)
- [Are my passwords Safe 😈](#are-my-passwords-safe-)
- [Linux Keyring](#linux-keyring)
- [KeepassXC setup for termscp](#keepassxc-setup-for-termscp)
- [Configuration ⚙️](#configuration-)
- [SSH Key Storage 🔐](#ssh-key-storage-)
- [File Explorer Format](#file-explorer-format)
- [Themes 🎨](#themes-)
- [My theme won't load 😱](#my-theme-wont-load-)
- [Styles 💈](#styles-)
- [Authentication page](#authentication-page)
- [Transfer page](#transfer-page)
- [Misc](#misc)
- [Text Editor ✏](#text-editor-)
- [Logging 🩺](#logging-)
- [Notifications 📫](#notifications-)
- [File watcher 🔭](#file-watcher-)
> ❗ I need a help to translate this manual into German. If you want to contribute to the translations, please open a PR 🙏
## Usage ❓
termscp can be started with the following options:
`termscp [options]... [protocol://user@address:port:wrkdir] [local-wrkdir]`
OR
`termscp [options]... -b [bookmark-name] [local-wrkdir]`
- `-P, --password <password>` if address is provided, password will be this argument
- `-b, --address-as-bookmark` resolve address argument as a bookmark name
- `-c, --config` Open termscp starting from the configuration page
- `-q, --quiet` Disable logging
- `-t, --theme <path>` Import specified theme
- `-u, --update` Update termscp to latest version
- `-v, --version` Print version info
- `-h, --help` Print help page
termscp can be started in three different modes, if no extra arguments is provided, termscp will show the authentication form, where the user will be able to provide the parameters required to connect to the remote peer.
Alternatively, the user can provide an address as argument to skip the authentication form and starting directly the connection to the remote server.
If address argument or bookmark name is provided you can also provide the start working directory for local host
### Address argument 🌎
The address argument has the following syntax:
```txt
[protocol://][username@]<address>[:port][:wrkdir]
```
Let's see some example of this particular syntax, since it's very comfortable and you'll probably going to use this instead of the other one...
- Connect using default protocol (*defined in configuration*) to 192.168.1.31, port if not provided is default for the selected protocol (in this case depends on your configuration); username is current user's name
```sh
termscp 192.168.1.31
```
- Connect using default protocol (*defined in configuration*) to 192.168.1.31; username is `root`
```sh
termscp root@192.168.1.31
```
- Connect using scp to 192.168.1.31, port is 4022; username is `omar`
```sh
termscp scp://omar@192.168.1.31:4022
```
- Connect using scp to 192.168.1.31, port is 4022; username is `omar`. You will start in directory `/tmp`
```sh
termscp scp://omar@192.168.1.31:4022:/tmp
```
#### AWS S3 address argument
Aws S3 has a different syntax for CLI address argument, for obvious reasons, but I managed to keep it the more similar as possible to the generic address argument:
```txt
s3://<bucket-name>@<region>[:profile][:/wrkdir]
```
e.g.
```txt
s3://buckethead@eu-central-1:default:/assets
```
#### How Password can be provided 🔐
You have probably noticed, that, when providing the address as argument, there's no way to provide the password.
Password can be basically provided through 3 ways when address argument is provided:
- `-P, --password` option: just use this CLI option providing the password. I strongly unrecommend this method, since it's very unsecure (since you might keep the password in the shell history)
- Via `sshpass`: you can provide password via `sshpass`, e.g. `sshpass -f ~/.ssh/topsecret.key termscp cvisintin@192.168.1.31`
- You will be prompted for it: if you don't use any of the previous methods, you will be prompted for the password, as happens with the more classics tools such as `scp`, `ssh`, etc.
---
## S3 connection parameters
These parameters are required to connect to aws s3 and other s3 compatible servers:
- AWS S3:
- **bucket name**
- **region**
- *profile* (if not provided: "default")
- *access key* (unless if public)
- *secret access key* (unless if public)
- *security token* (if required)
- *session token* (if required)
- new path style: **NO**
- Other S3 endpoints:
- **bucket name**
- **endpoint**
- *access key* (unless if public)
- *secret access key* (unless if public)
- new path style: **YES**
### S3 credentials 🦊
In order to connect to an Aws S3 bucket you must obviously provide some credentials.
There are basically three ways to achieve this.
So these are the ways you can provide the credentials for s3:
1. Authentication form:
1. You can provide the `access_key` (should be mandatory), the `secret_access_key` (should be mandatory), `security_token` and the `session_token`
2. If you save the s3 connection as a bookmark, these credentials will be saved as an encrypted AES-256/BASE64 string in your bookmarks file (except for the security token and session token which are meant to be temporary credentials).
2. Use your credentials file: just configure the AWS cli via `aws configure` and your credentials should already be located at `~/.aws/credentials`. In case you're using a profile different from `default`, just provide it in the profile field in the authentication form.
3. **Environment variables**: you can always provide your credentials as environment variables. Keep in mind that these credentials **will always override** the credentials located in the `credentials` file. See how to configure the environment below:
These should always be mandatory:
- `AWS_ACCESS_KEY_ID`: aws access key ID (usually starts with `AKIA...`)
- `AWS_SECRET_ACCESS_KEY`: the secret access key
In case you've configured a stronger security, you *may* require these too:
- `AWS_SECURITY_TOKEN`: security token
- `AWS_SESSION_TOKEN`: session token
⚠️ Your credentials are safe: termscp won't manipulate these values directly! Your credentials are directly consumed by the **s3** crate.
In case you've got some concern regarding security, please contact the library author on [Github](https://github.com/durch/rust-s3) ⚠️
---
## File explorer 📂
When we refer to file explorers in termscp, we refer to the panels you can see after establishing a connection with the remote.
These panels are basically 3 (yes, three actually):
- Local explorer panel: it is displayed on the left of your screen and shows the current directory entries for localhost
- Remote explorer panel: it is displayed on the right of your screen and shows the current directory entries for the remote host.
- Find results panel: depending on where you're searching for files (local/remote) it will replace the local or the explorer panel. This panel shows the entries matching the search query you performed.
In order to change panel you need to type `<LEFT>` to move the remote explorer panel and `<RIGHT>` to move back to the local explorer panel. Whenever you are in the find results panel, you need to press `<ESC>` to exit panel and go back to the previous panel.
### Keybindings ⌨
| Key | Command | Reminder |
|---------------|-------------------------------------------------------|-------------|
| `<ESC>` | Disconnect from remote; return to authentication page | |
| `<BACKSPACE>` | Go to previous directory in stack | |
| `<TAB>` | Switch explorer tab | |
| `<RIGHT>` | Move to remote explorer tab | |
| `<LEFT>` | Move to local explorer tab | |
| `<UP>` | Move up in selected list | |
| `<DOWN>` | Move down in selected list | |
| `<PGUP>` | Move up in selected list by 8 rows | |
| `<PGDOWN>` | Move down in selected list by 8 rows | |
| `<ENTER>` | Enter directory | |
| `<SPACE>` | Upload / download selected file | |
| `<BACKTAB>` | Switch between log tab and explorer | |
| `<A>` | Toggle hidden files | All |
| `<B>` | Sort files by | Bubblesort? |
| `<C|F5>` | Copy file/directory | Copy |
| `<D|F7>` | Make directory | Directory |
| `<E|F8|DEL>` | Delete file | Erase |
| `<F>` | Search for files (wild match is supported) | Find |
| `<G>` | Go to supplied path | Go to |
| `<H|F1>` | Show help | Help |
| `<K>` | Create symlink pointing to the currently selected entry | symlinK |
| `<I>` | Show info about selected file or directory | Info |
| `<L>` | Reload current directory's content / Clear selection | List |
| `<M>` | Select a file | Mark |
| `<N>` | Create new file with provided name | New |
| `<O|F4>` | Edit file; see Text editor | Open |
| `<Q|F10>` | Quit termscp | Quit |
| `<R|F6>` | Rename file | Rename |
| `<S|F2>` | Save file as... | Save |
| `<T>` | Synchronize changes to selected path to remote | Track |
| `<U>` | Go to parent directory | Upper |
| `<V|F3>` | Open file with default program for filetype | View |
| `<W>` | Open file with provided program | With |
| `<X>` | Execute a command | eXecute |
| `<Y>` | Toggle synchronized browsing | sYnc |
| `<CTRL+A>` | Select all files | |
| `<CTRL+C>` | Abort file transfer process | |
| `<CTRL+T>` | Show all synchronized paths | Track |
### Work on multiple files 🥷
You can opt to work on multiple files, selecting them pressing `<M>`, in order to select the current file, or pressing `<CTRL+A>`, which will select all the files in the working directory.
Once a file is marked for selection, it will be displayed with a `*` on the left.
When working on selection, only selected file will be processed for actions, while the current highlighted item will be ignored.
It is possible to work on multiple files also when in the find result panel.
All the actions are available when working with multiple files, but be aware that some actions work in a slightly different way. Let's dive in:
- *Copy*: whenever you copy a file, you'll be prompted to insert the destination name. When working with multiple file, this name refers to the destination directory where all these files will be copied.
- *Rename*: same as copy, but will move files there.
- *Save as*: same as copy, but will write them there.
### Synchronized browsing ⏲️
When enabled, synchronized browsing, will allow you to synchronize the navigation between the two panels.
This means that whenever you'll change the working directory on one panel, the same action will be reproduced on the other panel. If you want to enable synchronized browsing just press `<Y>`; press twice to disable. While enabled, the synchronized browsing state will be reported on the status bar on `ON`.
### Open and Open With 🚪
Open and open with commands are powered by [open-rs](https://docs.rs/crate/open/1.7.0).
When opening files with View command (`<V>`), the system default application for the file type will be used. To do so, the default operting system service will be used, so be sure to have at least one of these installed on your system:
- **Windows** users: you don't have to worry about it, since the crate will use the `start` command.
- **MacOS** users: you don't have to worry either, since the crate will use `open`, which is already installed on your system.
- **Linux** users: one of these should be installed
- *xdg-open*
- *gio*
- *gnome-open*
- *kde-open*
- **WSL** users: *wslview* is required, you must install [wslu](https://github.com/wslutilities/wslu).
> Q: Can I edit remote files using the view command?
> A: No, at least not directly from the "remote panel". You have to download it to a local directory first, that's due to the fact that when you open a remote file, the file is downloaded into a temporary directory, but there's no way to create a watcher for the file to check when the program you used to open it was closed, so termscp is not able to know when you're done editing the file.
---
## Bookmarks ⭐
In termscp it is possible to save favourites hosts, which can be then loaded quickly from the main layout of termscp.
termscp will also save the last 16 hosts you connected to.
This feature allows you to load all the parameters required to connect to a certain remote, simply selecting the bookmark in the tab under the authentication form.
Bookmarks will be saved, if possible at:
- `$HOME/.config/termscp/` on Linux/BSD
- `$HOME/Library/Application Support/termscp` on MacOs
- `FOLDERID_RoamingAppData\termscp\` on Windows
For bookmarks only (this won't apply to recent hosts) it is also possible to save the password used to authenticate. The password is not saved by default and must be specified through the prompt when saving a new Bookmark.
If you're concerned about the security of the password saved for your bookmarks, please read the [chapter below 👀](#are-my-passwords-safe-).
In order to create a new bookmark, just follow these steps:
1. Type in the authentication form the parameters to connect to your remote server
2. Press `<CTRL+S>`
3. Type in the name you want to give to the bookmark
4. Choose whether to remind the password or not
5. Press `<ENTER>` to submit
whenever you want to use the previously saved connection, just press `<TAB>` to navigate to the bookmarks list and load the bookmark parameters into the form pressing `<ENTER>`.
![Bookmarks](https://github.com/veeso/termscp/blob/main/assets/images/bookmarks.gif?raw=true)
### Are my passwords Safe 😈
Sure 😉.
As said before, bookmarks are saved in your configuration directory along with passwords. Passwords are obviously not plain text, they are encrypted with **AES-128**. Does this make them safe? Absolutely! (except for BSD and WSL users 😢)
On **Windows**, **Linux** and **MacOS** the key used to encrypt passwords is stored, if possible (but should be), respectively in the *Windows Vault*, in the *system keyring* and into the *Keychain*. This is actually super-safe and is directly managed by your operating system.
❗ Please, notice that if you're a Linux user, you'd better to read the [chapter below 👀](#linux-keyring), because the keyring might not be enabled or supported on your system!
On *BSD* and *WSL*, on the other hand, the key used to encrypt your passwords is stored on your drive (at $HOME/.config/termscp). It is then, still possible to retrieve the key to decrypt passwords. Luckily, the location of the key guarantees your key can't be read by users different from yours, but yeah, I still wouldn't save the password for a server exposed on the internet 😉.
#### Linux Keyring
We all love Linux thanks to the freedom it gives to the users. You can basically do anything you want as a Linux user, but this has also some cons, such as the fact that often there is no standard applications across different distributions. And this involves keyring too.
This means that on Linux there might be no keyring installed on your system. Unfortunately the library we use to work with the key storage requires a service which exposes `org.freedesktop.secrets` on D-BUS and the worst fact is that there only two services exposing it.
- ❗ If you use GNOME as desktop environment (e.g. ubuntu users), you should already be fine, since keyring is already provided by `gnome-keyring` and everything should already be working.
- ❗ For other desktop environment users there is a nice program you can use to get a keyring which is [KeepassXC](https://keepassxc.org/), which I use on my Manjaro installation (with KDE) and works fine. The only problem is that you have to setup it to be used along with termscp (but it's quite simple). To get started with KeepassXC read more [here](#keepassxc-setup-for-termscp).
- ❗ What about you don't want to install any of these services? Well, there's no problem! **termscp will keep working as usual**, but it will save the key in a file, as it usually does for BSD and WSL.
##### KeepassXC setup for termscp
Follow these steps in order to setup keepassXC for termscp:
1. Install KeepassXC
2. Go to "tools" > "settings" in toolbar
3. Select "Secret service integration" and toggle "Enable KeepassXC freedesktop.org secret service integration"
4. Create a database, if you don't have one yet: from toolbar "Database" > "New database"
5. From toolbar: "Database" > "Database settings"
6. Select "Secret service integration" and toggle "Expose entries under this group"
7. Select the group in the list where you want the termscp secret to be kept. Remember that this group might be used by any other application to store secrets via DBUS.
---
## Configuration ⚙️
termscp supports some user defined parameters, which can be defined in the configuration.
Underhood termscp has a TOML file and some other directories where all the parameters will be saved, but don't worry, you won't touch any of these files manually, since I made possible to configure termscp from its user interface entirely.
termscp, like for bookmarks, just requires to have these paths accessible:
- `$HOME/.config/termscp/` on Linux/BSD
- `$HOME/Library/Application Support/termscp` on MacOs
- `FOLDERID_RoamingAppData\termscp\` on Windows
To access configuration, you just have to press `<CTRL+C>` from the home of termscp.
These parameters can be changed:
- **Text Editor**: the text editor to use. By default termscp will find the default editor for you; with this option you can force an editor to be used (e.g. `vim`). **Also GUI editors are supported**, unless they `nohup` from the parent process so if you ask: yes, you can use `notepad.exe`, and no: **Visual Studio Code doesn't work**.
- **Default Protocol**: the default protocol is the default value for the file transfer protocol to be used in termscp. This applies for the login page and for the address CLI argument.
- **Show Hidden Files**: select whether hidden files shall be displayed by default. You will be able to decide whether to show or not hidden files at runtime pressing `A` anyway.
- **Check for updates**: if set to `yes`, termscp will fetch the Github API to check if there is a new version of termscp available.
- **Prompt when replacing existing files?**: If set to `yes`, termscp will prompt for confirmation you whenever a file transfer would cause an existing file on target host to be replaced.
- **Group Dirs**: select whether directories should be groupped or not in file explorers. If `Display first` is selected, directories will be sorted using the configured method but displayed before files, viceversa if `Display last` is selected.
- **Remote File formatter syntax**: syntax to display file info for each file in the remote explorer. See [File explorer format](#file-explorer-format)
- **Local File formatter syntax**: syntax to display file info for each file in the local explorer. See [File explorer format](#file-explorer-format)
- **Enable notifications?**: If set to `Yes`, notifications will be displayed.
- **Notifications: minimum transfer size**: if transfer size is greater or equal than the specified value, notifications for transfer will be displayed. The accepted values are in format `{UNSIGNED} B/KB/MB/GB/TB/PB`
- **SSH configuration path**: Set SSH configuration file to use when connecting to a SCP/SFTP server. If unset (empty) no file will be used. You can specify a path starting with `~` to indicate the home path (e.g. `~/.ssh/config`)
### SSH Key Storage 🔐
Along with configuration, termscp provides also an **essential** feature for **SFTP/SCP clients**: the SSH key storage.
You can access the SSH key storage, from configuration moving to the `SSH Keys` tab, once there you can:
- **Add a new key**: just press `<CTRL+N>` and you will be prompted to create a new key. Provide the hostname/ip address and the username associated to the key and finally a text editor will open up: paste the **PRIVATE** ssh key into the text editor, save and quit.
- **Remove an existing key**: just press `<DEL>` or `<CTRL+E>` on the key you want to remove, to delete persistently the key from termscp.
- **Edit an existing key**: just press `<ENTER>` on the key you want to edit, to change the private key.
> Q: Wait, my private key is protected with password, can I use it?
> A: Of course you can. The password provided for authentication in termscp, is valid both for username/password authentication and for RSA key authentication.
### File Explorer Format
It is possible through configuration to define a custom format for the file explorer. This is possible both for local and remote host, so you can have two different syntax in use. These fields, with name `File formatter syntax (local)` and `File formatter syntax (remote)` will define how the file entries will be displayed in the file explorer.
The syntax for the formatter is the following `{KEY1}... {KEY2:LENGTH}... {KEY3:LENGTH:EXTRA} {KEYn}...`.
Each key in bracket will be replaced with the related attribute, while everything outside brackets will be left unchanged.
- The key name is mandatory and must be one of the keys below
- The length describes the length reserved to display the field. Static attributes doesn't support this (GROUP, PEX, SIZE, USER)
- Extra is supported only by some parameters and is an additional options. See keys to check if extra is supported.
These are the keys supported by the formatter:
- `ATIME`: Last access time (with default syntax `%b %d %Y %H:%M`); Extra might be provided as the time syntax (e.g. `{ATIME:8:%H:%M}`)
- `CTIME`: Creation time (with syntax `%b %d %Y %H:%M`); Extra might be provided as the time syntax (e.g. `{CTIME:8:%H:%M}`)
- `GROUP`: Owner group
- `MTIME`: Last change time (with syntax `%b %d %Y %H:%M`); Extra might be provided as the time syntax (e.g. `{MTIME:8:%H:%M}`)
- `NAME`: File name (Elided if longer than LENGTH)
- `PATH`: File absolute path (Elided if longer than LENGHT)
- `PEX`: File permissions (UNIX format)
- `SIZE`: File size (omitted for directories)
- `SYMLINK`: Symlink (if any `-> {FILE_PATH}`)
- `USER`: Owner user
If left empty, the default formatter syntax will be used: `{NAME:24} {PEX} {USER} {SIZE} {MTIME:17:%b %d %Y %H:%M}`
---
## Themes 🎨
Termscp provides you with an awesome feature: the possibility to set the colors for several components in the application.
If you want to customize termscp there are two available ways to do so:
- From the **configuration menu**
- Importing a **theme file**
In order to create your own customization from termscp, all you have to do so is to enter the configuration from the auth activity, pressing `<CTRL+C>` and then `<TAB>` twice. You should have now moved to the `themes` panel.
Here you can move with `<UP>` and `<DOWN>` to change the style you want to change, as shown in the gif below:
![Themes](https://github.com/veeso/termscp/blob/main/assets/images/themes.gif?raw=true)
termscp supports both the traditional explicit hex (`#rrggbb`) and rgb `rgb(r, g, b)` syntax to provide colors, but also **[css colors](https://www.w3schools.com/cssref/css_colors.asp)** (such as `crimson`) are accepted 😉. There is also a special keywork which is `Default`. Default means that the color used will be the default foreground or background color based on the situation (foreground for texts and lines, background for well, guess what).
As said before, you can also import theme files. You can take inspiration from or directly use one of the themes provided along with termscp, located in the `themes/` directory of this repository and import them running termscp as `termscp -t <theme_file>`. If everything was fine, it should tell you the theme has successfully been imported.
### My theme won't load 😱
This is probably due to a recent update which has broken the theme. Whenever I add a new key to themes, the saved theme won't load. To fix this issues there are two really quick-fix solutions:
1. Reload theme: whenever I release an update I will also patch the "official" themes, so you just have to download it from the repository again and re-import the theme via `-t` option
```sh
termscp -t <theme.toml>
```
2. Fix your theme: If you're using a custom theme, then you can edit via `vim` and add the missing key. The theme is located at `$CONFIG_DIR/termscp/theme.toml` where `$CONFIG_DIR` is:
- FreeBSD/GNU-Linux: `$HOME/.config/`
- MacOs: `$HOME/Library/Application Support`
- Windows: `%appdata%`
❗ Missing keys are reported in the CHANGELOG under `BREAKING CHANGES` for the version you've just installed.
### Styles 💈
You can find in the table below, the description for each style field.
Please, notice that **styles won't apply to configuration page**, in order to make it always accessible in case you mess everything up
#### Authentication page
| Key | Description |
|----------------|------------------------------------------|
| auth_address | Color of the input field for IP address |
| auth_bookmarks | Color of the bookmarks panel |
| auth_password | Color of the input field for password |
| auth_port | Color of the input field for port number |
| auth_protocol | Color of the radio group for protocol |
| auth_recents | Color of the recents panel |
| auth_username | Color of the input field for username |
#### Transfer page
| Key | Description |
|--------------------------------------|---------------------------------------------------------------------------|
| transfer_local_explorer_background | Background color of localhost explorer |
| transfer_local_explorer_foreground | Foreground coloor of localhost explorer |
| transfer_local_explorer_highlighted | Border and highlighted color for localhost explorer |
| transfer_remote_explorer_background | Background color of remote explorer |
| transfer_remote_explorer_foreground | Foreground coloor of remote explorer |
| transfer_remote_explorer_highlighted | Border and highlighted color for remote explorer |
| transfer_log_background | Background color for log panel |
| transfer_log_window | Window color for log panel |
| transfer_progress_bar_partial | Partial progress bar color |
| transfer_progress_bar_total | Total progress bar color |
| transfer_status_hidden | Color for status bar "hidden" label |
| transfer_status_sorting | Color for status bar "sorting" label; applies also to file sorting dialog |
| transfer_status_sync_browsing | Color for status bar "sync browsing" label |
#### Misc
These styles applie to different part of the application.
| Key | Description |
|-------------------|---------------------------------------------|
| misc_error_dialog | Color for error messages |
| misc_info_dialog | Color for info dialogs |
| misc_input_dialog | Color for input dialogs (such as copy file) |
| misc_keys | Color of text for key strokes |
| misc_quit_dialog | Color for quit dialogs |
| misc_save_dialog | Color for save dialogs |
| misc_warn_dialog | Color for warn dialogs |
---
## Text Editor ✏
termscp has, as you might have noticed, many features, one of these is the possibility to view and edit text file. It doesn't matter if the file is located on the local host or on the remote host, termscp provides the possibility to open a file in your favourite text editor.
In case the file is located on remote host, the file will be first downloaded into your temporary file directory and then, **only** if changes were made to the file, re-uploaded to the remote host. termscp checks if you made changes to the file verifying the last modification time of the file.
Just a reminder: **you can edit only textual file**; binary files are not supported.
---
## Logging 🩺
termscp writes a log file for each session, which is written at
- `$HOME/.config/termscp/termscp.log` on Linux/BSD
- `$HOME/Library/Application Support/termscp/termscp.log` on MacOs
- `FOLDERID_RoamingAppData\termscp\termscp.log` on Windows
the log won't be rotated, but will just be truncated after each launch of termscp, so if you want to report an issue and you want to attach your log file, keep in mind to save the log file in a safe place before using termscp again.
The logging by default reports in *INFO* level, so it is not very verbose.
If you want to submit an issue, please, if you can, reproduce the issue with the level set to `TRACE`, to do so, launch termscp with
the `-D` CLI option.
I know you might have some questions regarding log files, so I made a kind of a Q/A:
> I don't want logging, can I turn it off?
Yes, you can. Just start termscp with `-q or --quiet` option. You can alias termscp to make it persistent. Remember that logging is used to diagnose issues, so since behind every open source project, there should always be this kind of mutual help, keeping log files might be your way to support the project 😉. I don't want you to feel guilty, but just to say.
> Is logging safe?
If you're concerned about security, the log file doesn't contain any plain password, so don't worry and exposes the same information the sibling file `bookmarks` reports.
## Notifications 📫
Termscp will send Desktop notifications for these kind of events:
- on **Transfer completed**: The notification will be sent once a transfer has been successfully completed.
- ❗ The notification will be displayed only if the transfer total size is at least the specified `Notifications: minimum transfer size` in the configuration.
- on **Transfer failed**: The notification will be sent once a transfer has failed due to an error.
- ❗ The notification will be displayed only if the transfer total size is at least the specified `Notifications: minimum transfer size` in the configuration.
- on **Update available**: Whenever a new version of termscp is available, a notification will be displayed.
- on **Update installed**: Whenever a new version of termscp has been installed, a notification will be displayed.
- on **Update failed**: Whenever the installation of the update fails, a notification will be displayed.
❗ If you prefer to keep notifications turned off, you can just enter setup and set `Enable notifications?` to `No` 😉.
❗ If you want to change the minimum transfer size to display notifications, you can change the value in the configuration with key `Notifications: minimum transfer size` and set it to whatever suits better for you 🙂.
## File watcher 🔭
The file watcher allows you to setup a list of paths to synchronize with the remote hosts.
This means that whenever a change on the local file system will be detected on the synchronized path, the change will be automatically reported to the configured remote host path, within 5 seconds.
You can set as many paths to synchronize as you prefer:
1. Put the cursor on the local explorer on the directory/file you want to keep synchronized
2. Go to the directory you want the changes to be reported to on the remote host
3. Press `<T>`
4. Answer `<YES>` to the radio popup
To unwatch, just press `<T>` on the local synchronized path (or to any of its subfolders)
OR you can just press `<CTRL+T>` and press `<ENTER>` to the synchronized path you want to unwatch.
These changes will be reported to the remote host:
- New files, file changes
- File moved/renamed
- File removed/unlinked
> ❗ The watcher works only in one direction (local > remote). It is NOT possible to synchronize automatically the changes from remote to local.

View File

@@ -1,35 +0,0 @@
# Deploy checklist
Document audience: project maintainers
- [Deploy checklist](#deploy-checklist)
- [Description](#description)
- [Checklist](#checklist)
## Description
This document describes the checklist that must be fulfilled before releasing a new version of termscp.
## Checklist
- [ ] The latest build didn't report any error in the CI
- [ ] All commands when using SFTP work
- [ ] All commands when using SCP work
- [ ] All commands when using FTP work
- [ ] It is possible to load bookmarks
- [ ] Recent connections get saved
- [ ] Update versions and release date in readme, changelog and cargo.toml
- [ ] Build on MacOS
- [ ] Update sha256 and version on homebrew repository
- [ ] Build on Windows
- [ ] Update sha256 and version in chocolatey repository
- [ ] Create chocolatey package
- [ ] Build Linux version using docker from `dist/build/build.sh`
- [ ] Update sha256 and version in AUR files
- [ ] Create release and attach the following artifacts
- [ ] Deb package
- [ ] RPM package
- [ ] MacOs tar.gz
- [ ] Windows nupkg
- [ ] Windows zip
- [ ] AUR tar.gz

View File

@@ -1,42 +1,33 @@
# Developer Manual
Document audience: developers
Revision: 2022-01-05
- [Developer Manual](#developer-manual)
- [How to test](#how-to-test)
- [How termscp works](#how-termscp-works)
- [Activities](#activities)
- [The Context](#the-context)
- [Achieving an abstract file transfer client](#achieving-an-abstract-file-transfer-client)
Welcome to the developer manual for termscp. This chapter DOESN'T contain the documentation for termscp modules, which can instead be found on Rust Docs at <https://docs.rs/termscp>
This chapter describes how termscp works and the guide lines to implement stuff such as file transfers and add features to the user interface.
## How to test
First an introduction to tests.
Usually it's enough to run `cargo test`, but please note that whenever you're working on file transfer you'll need one more step.
In order to run tests with file transfers, you need to start the file transfer server containers, which can be started via `docker`.
To run all tests with file transfers just run: `./tests/test.sh`
---
## How termscp works
termscp is basically made up of 4 components:
termscp is basically made up of 3 core modules:
- the **filetransfer**: the filetransfer takes care of managing the remote file system; it provides function to establish a connection with the remote, operating on the remote server file system (e.g. remove files, make directories, rename files, ...), read files and write files. The FileTransfer, as we'll see later, is actually a trait, and for each protocol a FileTransfer must be implement the trait.
- the **host**: the host module provides functions to interact with the local host file system.
- the **ui**: this module contains the implementation of the user interface, as we'll see in the next chapter, this is achieved through **activities**.
- the **activity_manager**: the activity manager takes care of managing activities, basically it runs the activities of the user interface, and chooses, based on their state, when is the moment to terminate the current activity and which activity to run after the current one.
In addition to the 4 main components, other have been added through the time:
In addition to the 3 core modules, other have been added through the time:
- **config**: this module provides the configuration schema and serialization methods for it.
- **fs**: this modules exposes the FsEntry entity and the explorers. The explorers are structs which hold the content of the current directory; they also they take of filtering files up to your preferences and format file entries based on your configuration.
- **system**: the system module provides a way to actually interact with the configuration, the ssh key storage and with the bookmarks.
- **utils**: contains the utilities used by pretty much all the project.
- **explorer**: this modules exposes the explorer structures, which are used to handle the file explorer in the ui. So, basically they store the current directory model and the view states (e.g. sorting, whether to display hidden files, ...).
- **system**: the system module provides a way to interact with the configuration, with the ssh key storage and with the bookmarks.
- **utils**: contains the utilities used by pretty much all of the project.
## Activities
@@ -45,10 +36,10 @@ I think there are many ways to implement a user interface and I've worked with d
My approach was this:
- **Activities on top**: each "page" is an Activity and an `Activity Manager` handles them. I got inspired by Android for this case. I think that's a good way to implement the ui in case like this, where you have different pages, each one with their view, their components and their logics. Activities work with the `Context`, which is a data holder for different data, which are shared and common between the activities.
- **Activities display Views**: Each activity can show different views. A view is basically a list of **components**, each one with its properties. The view is a facade to the components and also handles the focus, which is the current active component. You cannot have more than one component active, so you need to handle this; but at the same time you also have to give focus to the previously active component if the current one is destroyed. So basically view takes care of all this stuff.
- **Components**: I've decided to write around `tui` in order to re-use widgets. To do so I've implemented the `Component` trait. To implement traits I got inspired by [React](https://reactjs.org/). Each component has its *Properties* and can have its *States*. Then each component must be able to handle input events and to be updated with new properties. Last but not least, each component must provide a method to **render** itself.
- **Messages: an Elm based approach**: I was really satisfied with my implementation choices; the problem at this point was solving one of the biggest teardrops I've ever had with this project: **events**. Input events were really a pain to handle, since I had to handle states in the activity to handle which component was enabled etc. To solve this I got inspired by a wonderful language I had recently studied, which is [Elm](https://elm-lang.org/). Basically in Elm you implement your ui using three basic functions: **update**, **view** and **init**. View and init were pretty much already implemented here, but at this point I decided to implement also something like the **elm update function**. I came out with a huge match case to handle events inside a recursive function, which you can basically find in the `update.rs` file inside each activity. This match case handles a tuple, made out of the **component id** and the **input event** received from the view. It matches the two propeties against the input event we want to handle for each component *et voilà*.
- **Activities on top**: each "view" is an Activity and an `Activity Manager` handles them. I got inspired by Android for this case. I think that's a good way to implement the ui in case like this, where you have different views, each one with their view, their components and their logic. Activities work with the `Context`, which is a data holder to share data between the activities.
- **Activities display Applications**: Each activity can show different **Applications**. An application, contains a **View** is basically a list of **components**, each one with its properties. The view is a facade to the components and also handles the focus, which is the current active component. You cannot have more than one component active, so you need to handle this; but at the same time you also have to give focus to the previously active component if the current one is destroyed. So basically **Application** takes care of all this stuff. If you're interested on how this works, you can read more on <https://github.com/veeso/tui-realm>.
- **Components**: I've decided to write around `tui` in order to re-use widgets. To do so I've implemented the `Component` trait. To implement traits I got inspired by [React](https://reactjs.org/). Each component has its *Properties* and can have its *States*. Then each component must be able to handle input events and to be updated with new properties. Last but not least, each component must provide a method to **render** itself. At the beginning this was implemented inside of termscp, but now this has been moved to [tui-realm](https://github.com/veeso/tui-realm).
- **Messages: an Elm based approach**: I was really satisfied with my implementation choices; the problem at this point was solving one of the biggest teardrops I've ever had with this project: **events**. Input events were really a pain to handle, since I had to handle states in the activity to handle which component was enabled etc. To solve this I got inspired by a wonderful language I had recently studied, which is [Elm](https://elm-lang.org/). Basically in Elm you implement your ui using three basic functions: **update**, **view** and **init**. View and init were pretty much already implemented here, but at this point I decided to implement also something like the **elm update function**. I came out with a huge match case to handle messages inside a recursive function, which you can basically find in the `update.rs` file inside each activity. This match case handles the messages produced by the components in front of an incoming input event. It matches the messages causing the activity to change its states *et voilà*.
I've implemented a Trait called `Activity`, which, is a very very reduced version of the Android activity of course.
This trait provides only 3 methods:
@@ -67,7 +58,16 @@ The context basically holds the following data:
- The **File Transfer Params**: the current parameters set to connect to the remote
- The **Config Client**: the configuration client is a structure which provides functions to access the user configuration
- The **Store**: the store is a key-value storage which can hold any kind of data. This can be used to store states to share between activities or to keep persistence for heavy/slow tasks (such as checking for updates).
- The **Input handler**: the input handler is used to read input events from the keyboard
- The **Terminal**: the terminal is used to view the tui on the terminal
---
## Achieving an abstract file transfer client
When I started to implement termscp, in december 2020, the file transfer was at the core of my implementation focus, since, for obvious reasons, it is at the heart of termscp.
The first implementation consisted of a `filetransfer` module, which exposed a trait called `FileTransfer`, which exposed different methods to generically interact with the remote file system.
This thing has changed over the last year, since different users has asked me to implement a dedicated library to implement this.
So in the last quarter of 2021, I dedicated part of my time in implementing an abstract library to work with remote device file systems, and this is how [remotefs](https://github.com/veeso/remotefs-rs) was born.
Remotefs provides a `RemoteFs` trait which exposes all of the core file-system functionalities and this has since 0.8.0 version, replaced the `FileTransfer` trait.
The file transfer module, still exists though, but its only task is to create a builder from the "file transfer parameters" into the `RemoteFs` client implementation.

288
docs/es/README.md Normal file
View File

@@ -0,0 +1,288 @@
# termscp
<p align="center">
<img src="/assets/images/termscp.svg" width="256" height="256" />
</p>
<p align="center">~ Una transferencia de archivos de terminal rica en funciones ~</p>
<p align="center">
<a href="https://veeso.github.io/termscp/" target="_blank">Sitio Web</a>
·
<a href="https://veeso.github.io/termscp/#get-started" target="_blank">Instalación</a>
·
<a href="https://veeso.github.io/termscp/#user-manual" target="_blank">Manual de usuario</a>
</p>
<p align="center">
<a href="https://github.com/veeso/termscp"
><img
height="20"
src="/assets/images/flags/us.png"
alt="English"
/></a>
&nbsp;
<a
href="/docs/de/README.md"
><img
height="20"
src="/assets/images/flags/de.png"
alt="Deutsch"
/></a>
&nbsp;
<a
href="/docs/es/README.md"
><img
height="20"
src="/assets/images/flags/es.png"
alt="Español"
/></a>
&nbsp;
<a
href="/docs/fr/README.md"
><img
height="20"
src="/assets/images/flags/fr.png"
alt="Français"
/></a>
&nbsp;
<a
href="/docs/it/README.md"
><img
height="20"
src="/assets/images/flags/it.png"
alt="Italiano"
/></a>
&nbsp;
<a
href="/docs/zh-CN/README.md"
><img
height="20"
src="/assets/images/flags/cn.png"
alt="简体中文"
/></a>
</p>
<p align="center">Desarrollado por <a href="https://veeso.github.io/" target="_blank">@veeso</a></p>
<p align="center">Versión actual: 0.9.0 (18/06/2022)</p>
<p align="center">
<a href="https://opensource.org/licenses/MIT"
><img
src="https://img.shields.io/badge/License-MIT-teal.svg"
alt="License-MIT"
/></a>
<a href="https://github.com/veeso/termscp/stargazers"
><img
src="https://img.shields.io/github/stars/veeso/termscp.svg"
alt="Repo stars"
/></a>
<a href="https://crates.io/crates/termscp"
><img
src="https://img.shields.io/crates/d/termscp.svg"
alt="Downloads counter"
/></a>
<a href="https://crates.io/crates/termscp"
><img
src="https://img.shields.io/crates/v/termscp.svg"
alt="Latest version"
/></a>
<a href="https://ko-fi.com/veeso">
<img
src="https://img.shields.io/badge/donate-ko--fi-red"
alt="Ko-fi"
/></a>
</p>
<p align="center">
<a href="https://github.com/veeso/termscp/actions"
><img
src="https://github.com/veeso/termscp/workflows/Linux/badge.svg"
alt="Linux CI"
/></a>
<a href="https://github.com/veeso/termscp/actions"
><img
src="https://github.com/veeso/termscp/workflows/MacOS/badge.svg"
alt="MacOS CI"
/></a>
<a href="https://github.com/veeso/termscp/actions"
><img
src="https://github.com/veeso/termscp/workflows/Windows/badge.svg"
alt="Windows CI"
/></a>
<a href="https://github.com/veeso/termscp/actions"
><img
src="https://github.com/veeso/termscp/workflows/FreeBSD/badge.svg"
alt="FreeBSD CI"
/></a>
<a href="https://coveralls.io/github/veeso/termscp"
><img
src="https://coveralls.io/repos/github/veeso/termscp/badge.svg"
alt="Coveralls"
/></a>
</p>
---
## Sobre termscp 🖥
Termscp es un explorador y transferencia de archivos de terminal rico en funciones, con apoyo para SCP/SFTP/FTP/S3. Básicamente, es una utilidad de terminal con una TUI para conectarse a un servidor remoto para recuperar y cargar archivos e interactuar con el sistema de archivos local. Es compatible con **Linux**, **MacOS**, **FreeBSD** y **Windows**.
![Explorer](/assets/images/explorer.gif)
---
## Características 🎁
- 📁 Diferentes protocolos de comunicación
- **SFTP**
- **SCP**
- **FTP** y **FTPS**
- **S3**
- 🖥 Explore y opere en el sistema de archivos de la máquina local y remota con una interfaz de usuario práctica
- Cree, elimine, cambie el nombre, busque, vea y edite archivos
- ⭐ Conéctese a sus hosts favoritos y conexiones recientes
- 📝 Ver y editar archivos con sus aplicaciones favoritas
- 💁 Autenticación SFTP / SCP con claves SSH y nombre de usuario / contraseña
- 🐧 compatible con Linux, MacOS, FreeBSD y Windows
- 🎨 Haz lo tuyo!
- Temas
- Formato de explorador de archivos personalizado
- Editor de texto personalizable
- Clasificación de archivos personalizable
- y muchos otros parámetros ...
- 📫 Reciba una notificación cuando se haya transferido un archivo grande
- 🔭 Mantenga los cambios de archivos sincronizados con el host remoto
- 🔐 Guarde su contraseña en el almacén de claves de su sistema operativo
- 🦀 Rust-powered
- 👀 Desarrollado sin perder de vista el rendimiento
- 🦄 Actualizaciones frecuentes
---
## Para iniciar 🚀
Si estás considerando instalar termscp, ¡quiero darte las gracias 💜! ¡Espero que disfrutes de termscp!
Si desea contribuir a este proyecto, no olvide consultar nuestra [guía de contribución](../../CONTRIBUTING.md).
Si tu eres un usuario de Linux, FreeBSD o MacOS, este sencillo script de shell instalará termscp en tu sistema con un solo comando:
```sh
curl --proto '=https' --tlsv1.2 -sSLf "https://git.io/JBhDb" | sh
```
mientras que si eres un usuario de Windows, puedes instalar termscp con [Chocolatey](https://chocolatey.org/):
```sh
choco install termscp
```
Para obtener más información u otras plataformas, visite [veeso.github.io](https://veeso.github.io/termscp/#get-started) para ver todos los métodos de instalación.
⚠️ Si estás buscando cómo actualizar termscp, simplemente ejecute termscp desde CLI con:: `(sudo) termscp --update` ⚠️
### Requisitos ❗
- Usuarios **Linux**:
- libssh
- libdbus-1
- pkg-config
- Usuarios **FreeBSD**:
- libssh
- dbus
- pkgconf
### Requisitos opcionales ✔️
These requirements are not forced required to run termscp, but to enjoy all of its features
- Usuarios **Linux/FreeBSD**:
- Para **abrir** archivos con `V` (al menos uno de estos)
- *xdg-open*
- *gio*
- *gnome-open*
- *kde-open*
- Usuarios **Linux**:
- Un keyring manager: leer más en el [manual de usuario](man.md#linux-keyring)
- Usuarios **WSL**
- Para **abrir** archivos con `V` (al menos uno de estos)
- [wslu](https://github.com/wslutilities/wslu)
---
## Apoyame ☕
Si te gusta termscp y te encantaría que el proyecto crezca y mejore, considera una pequeña donación para apoyarme 🥳
Puedes hacer una donación con una de estas plataformas:
[![ko-fi](https://img.shields.io/badge/Ko--fi-F16061?style=for-the-badge&logo=ko-fi&logoColor=white)](https://ko-fi.com/veeso)
[![PayPal](https://img.shields.io/badge/PayPal-00457C?style=for-the-badge&logo=paypal&logoColor=white)](https://www.paypal.me/chrisintin)
---
## Manual de usuario y documentación 📚
El manual del usuario se puede encontrar en el [sitio web de termscp](https://veeso.github.io/termscp/#user-manual) o en [Github](man.md).
---
## Contribuir y problemas 🤝🏻
¡Las contribuciones, los informes de errores, las nuevas funciones y las preguntas son bienvenidas! 😉
Si tiene alguna pregunta o inquietud, o si desea sugerir una nueva función, o simplemente desea mejorar termscp, no dude en abrir un problema o un PR.
Sigue [nuestras pautas de contribución](../../CONTRIBUTING.md)
---
## Changelog ⏳
Ver registro de cambios de termscp [AQUÍ](../../CHANGELOG.md)
---
## Powered by 💪
termscp funciona con estos increíbles proyectos:
- [bytesize](https://github.com/hyunsik/bytesize)
- [crossterm](https://github.com/crossterm-rs/crossterm)
- [edit](https://github.com/milkey-mouse/edit)
- [keyring-rs](https://github.com/hwchen/keyring-rs)
- [open-rs](https://github.com/Byron/open-rs)
- [rpassword](https://github.com/conradkleinespel/rpassword)
- [rust-s3](https://github.com/durch/rust-s3)
- [self_update](https://github.com/jaemk/self_update)
- [ssh2-rs](https://github.com/alexcrichton/ssh2-rs)
- [suppaftp](https://github.com/veeso/suppaftp)
- [tui-rs](https://github.com/fdehau/tui-rs)
- [tui-realm](https://github.com/veeso/tui-realm)
- [whoami](https://github.com/libcala/whoami)
- [wildmatch](https://github.com/becheran/wildmatch)
---
## Galería 🎬
> Termscp Home
![Auth](/assets/images/auth.gif)
> Bookmarks
![Bookmarks](/assets/images/bookmarks.gif)
> Setup
![Setup](/assets/images/config.gif)
> Text editor
![TextEditor](/assets/images/text-editor.gif)
---
## Licencia 📃
termscp tiene la licencia MIT.
Puede leer la licencia completa [AQUÍ](../../LICENSE)

539
docs/es/man.md Normal file
View File

@@ -0,0 +1,539 @@
# User manual 🎓
- [User manual 🎓](#user-manual-)
- [Uso ❓](#uso-)
- [Argumento dirección 🌎](#argumento-dirección-)
- [Argumento dirección por AWS S3](#argumento-dirección-por-aws-s3)
- [Cómo se puede proporcionar la contraseña 🔐](#cómo-se-puede-proporcionar-la-contraseña-)
- [S3 parámetros de conexión](#s3-parámetros-de-conexión)
- [Credenciales de S3 🦊](#credenciales-de-s3-)
- [Explorador de archivos 📂](#explorador-de-archivos-)
- [Keybindings ⌨](#keybindings-)
- [Trabaja en varios archivos 🥷](#trabaja-en-varios-archivos-)
- [Navegación sincronizada ⏲️](#navegación-sincronizada-)
- [Abierta y abierta con 🚪](#abierta-y-abierta-con-)
- [Marcadores ⭐](#marcadores-)
- [¿Son seguras mis contraseñas? 😈](#son-seguras-mis-contraseñas-)
- [Linux Keyring](#linux-keyring)
- [KeepassXC setup por termscp](#keepassxc-setup-por-termscp)
- [Configuración ⚙️](#configuración--)
- [SSH Key Storage 🔐](#ssh-key-storage-)
- [Formato del explorador de archivos](#formato-del-explorador-de-archivos)
- [Temas 🎨](#temas-)
- [Mi tema no se carga 😱](#mi-tema-no-se-carga-)
- [Estilos 💈](#estilos-)
- [Authentication page](#authentication-page)
- [Transfer page](#transfer-page)
- [Misc](#misc)
- [Text Editor ✏](#text-editor-)
- [Logging 🩺](#logging-)
- [Notificaciones 📫](#notificaciones-)
- [Observador de archivos 🔭](#observador-de-archivos-)
> ❗ Este documento ha sido traducido con Google Translator (y luego lo he revisado a grandes rasgos, pero no puedo hablar el idioma muy bien). Si habla l'idioma, abra un [issue](https://github.com/veeso/termscp/issues/new/choose) utilizando la label COPY o abra un PR 🙏
## Uso ❓
termscp se puede iniciar con las siguientes opciones:
`termscp [options]... [protocol://user@address:port:wrkdir] [local-wrkdir]`
OR
`termscp [options]... -b [bookmark-name] [local-wrkdir]`
- `-P, --password <password>` si se proporciona la dirección, la contraseña será este argumento
- `-b, --address-as-bookmark` resuelve el argumento de la dirección como un nombre de marcador
- `-c, --config` Abrir termscp comenzando desde la página de configuración
- `-q, --quiet` Deshabilitar el registro
- `-t, --theme <path>` Importar tema especificado
- `-u, --update` Actualizar termscp a la última versión
- `-v, --version` Imprimir información de la versión
- `-h, --help` Imprimir página de ayuda
termscp se puede iniciar en dos modos diferentes, si no se proporcionan argumentos adicionales, termscp mostrará el formulario de autenticación, donde el usuario podrá proporcionar los parámetros necesarios para conectarse al par remoto.
Alternativamente, el usuario puede proporcionar una dirección como argumento para omitir el formulario de autenticación e iniciar directamente la conexión al servidor remoto.
Si se proporciona un argumento de dirección, también puede proporcionar el directorio de inicio de trabajo para el host local
### Argumento dirección 🌎
El argumento dirección tiene la siguiente sintaxis:
```txt
[protocol://][username@]<address>[:port][:wrkdir]
```
Veamos algún ejemplo de esta sintaxis en particular, ya que es muy cómoda y probablemente usarás esta en lugar de la otra ...
- Conéctese usando el protocolo predeterminado (*definido en la configuración*) a 192.168.1.31, el puerto, si no se proporciona, es el predeterminado para el protocolo seleccionado (en este caso, depende de su configuración); nombre de usuario es el nombre del usuario actual
```sh
termscp 192.168.1.31
```
- Conéctese usando el protocolo predeterminado (*definido en la configuración*) a 192.168.1.31; el nombre de usuario es `root`
```sh
termscp root@192.168.1.31
```
- Conéctese usando scp a 192.168.1.31, el puerto es 4022; nombre de usuario es `omar`
```sh
termscp scp://omar@192.168.1.31:4022
```
- Conéctese usando scp a 192.168.1.31, el puerto es 4022; El nombre de usuario es `omar`. Comenzará en el directorio `/ tmp`
```sh
termscp scp://omar@192.168.1.31:4022:/tmp
```
#### Argumento dirección por AWS S3
Aws S3 tiene una sintaxis diferente para el argumento de la dirección CLI, por razones obvias, pero logré mantenerlo lo más similar posible al argumento de la dirección genérica:
```txt
s3://<bucket-name>@<region>[:profile][:/wrkdir]
```
por ejemplo
```txt
s3://buckethead@eu-central-1:default:/assets
```
#### Cómo se puede proporcionar la contraseña 🔐
Probablemente haya notado que, al proporcionar la dirección como argumento, no hay forma de proporcionar la contraseña.
La contraseña se puede proporcionar básicamente a través de 3 formas cuando se proporciona un argumento de dirección:
- `-P, --password` opción: simplemente use esta opción CLI proporcionando la contraseña. No recomiendo este método, ya que es muy inseguro (ya que puede mantener la contraseña en el historial de shell)
- Con `sshpass`: puede proporcionar la contraseña a través de `sshpass`, p. ej. `sshpass -f ~/.ssh/topsecret.key termscp cvisintin@192.168.1.31`
- Se te pedirá que ingreses: si no utilizas ninguno de los métodos anteriores, se te pedirá la contraseña, como ocurre con las herramientas más clásicas como `scp`, `ssh`, etc.
---
## S3 parámetros de conexión
Estos parámetros son necesarios para conectarse a aws s3 y otros servidores compatibles con s3:
- AWS S3:
- **bucket name**
- **region**
- *profile* (si no se proporciona: "default")
- *access key* (A menos que sea pública)
- *secret access key* (A menos que sea pública)
- *security token* (si es requerido)
- *session token* (si es requerido)
- new path style: **NO**
- Otros puntos finales de S3:
- **bucket name**
- **endpoint**
- *access key* (A menos que sea pública)
- *secret access key* (A menos que sea pública)
- new path style: **YES**
### Credenciales de S3 🦊
Para conectarse a un bucket de Aws S3, obviamente debe proporcionar algunas credenciales.
Básicamente, hay tres formas de lograr esto.
Entonces, estas son las formas en que puede proporcionar las credenciales para s3:
1. Authentication form:
1. Puede proporcionar la `access_key` (debería ser obligatoria), la `secret_access_kedy` (debería ser obligatoria), el `security_token` y el `session_token`
2. Si guarda la conexión s3 como marcador, estas credenciales se guardarán como una cadena AES-256 / BASE64 cifrada en su archivo de marcadores (excepto el token de seguridad y el token de sesión, que deben ser credenciales temporales).
2. Use su archivo de credenciales: simplemente configure la cli de AWS a través de `aws configure` y sus credenciales ya deberían estar ubicadas en`~/.aws/credentials`. En caso de que esté usando un perfil diferente al "predeterminado", simplemente proporciónelo en el campo de perfil en el formulario de autenticación.
3. **Variables de entorno**: siempre puede proporcionar sus credenciales como variables de entorno. Tenga en cuenta que estas credenciales **siempre anularán** las credenciales ubicadas en el archivo `credentials`. Vea cómo configurar el entorno a continuación:
Estos siempre deben ser obligatorios:
- `AWS_ACCESS_KEY_ID`: aws access key ID (generalmente comienza con `AKIA...`)
- `AWS_SECRET_ACCESS_KEY`: la secret access key
En caso de que haya configurado una seguridad más fuerte, *puede* requerir estos también:
- `AWS_SECURITY_TOKEN`: security token
- `AWS_SESSION_TOKEN`: session token
⚠️ Sus credenciales están seguras: ¡termscp no manipulará estos valores directamente! Sus credenciales son consumidas directamente por la caja **s3**.
En caso de que tenga alguna inquietud con respecto a la seguridad, comuníquese con el autor de la biblioteca en [Github](https://github.com/durch/rust-s3) ⚠️
---
## Explorador de archivos 📂
Cuando nos referimos a exploradores de archivos en termscp, nos referimos a los paneles que puede ver después de establecer una conexión con el control remoto.
Estos paneles son básicamente 3:
- Panel del explorador local: se muestra a la izquierda de la pantalla y muestra las entradas del directorio actual para localhost
- Panel del explorador remoto: se muestra a la derecha de la pantalla y muestra las entradas del directorio actual para el host remoto.
- Panel de resultados de búsqueda: dependiendo de dónde esté buscando archivos (local / remoto), reemplazará el panel local o del explorador. Este panel muestra las entradas que coinciden con la consulta de búsqueda que realizó.
Para cambiar de panel, debe escribir `<LEFT>` para mover el panel del explorador remoto y `<RIGHT>` para volver al panel del explorador local. Siempre que se encuentre en el panel de resultados de búsqueda, debe presionar `<ESC>` para salir del panel y volver al panel anterior.
### Keybindings ⌨
| Key | Command | Reminder |
|---------------|----------------------------------------------------------------------------|-------------|
| `<ESC>` | Desconecte; volver a la página de autenticación | |
| `<BACKSPACE>` | Ir al directorio anterior en la pila | |
| `<TAB>` | Cambiar pestaña del explorador | |
| `<RIGHT>` | Mover a la pestaña del explorador remoto | |
| `<LEFT>` | Mover a la pestaña del explorador local | |
| `<UP>` | Subir en la lista seleccionada | |
| `<DOWN>` | Bajar en la lista seleccionada | |
| `<PGUP>` | Subir 8 filas en la lista seleccionada | |
| `<PGDOWN>` | Bajar 8 filas en la lista seleccionada | |
| `<ENTER>` | Entrar directorio | |
| `<SPACE>` | Cargar / descargar el archivo seleccionado | |
| `<BACKTAB>` | Cambiar entre la pestaña de registro y el explorador | |
| `<A>` | Alternar archivos ocultos | All |
| `<B>` | Ordenar archivos por | Bubblesort? |
| `<C|F5>` | Copiar archivo / directorio | Copy |
| `<D|F7>` | Hacer directorio | Directory |
| `<E|F8|DEL>` | Eliminar archivo | Erase |
| `<F>` | Búsqueda de archivos | Find |
| `<G>` | Ir a la ruta proporcionada | Go to |
| `<H|F1>` | Mostrar ayuda | Help |
| `<I>` | Mostrar información sobre el archivo | Info |
| `<K>` | Crear un enlace simbólico que apunte a la entrada seleccionada actualmente | symlinK |
| `<L>` | Recargar contenido del directorio / Borrar selección | List |
| `<M>` | Seleccione un archivo | Mark |
| `<N>` | Crear un nuevo archivo con el nombre proporcionado | New |
| `<O|F4>` | Editar archivo | Open |
| `<Q|F10>` | Salir de termscp | Quit |
| `<R|F6>` | Renombrar archivo | Rename |
| `<S|F2>` | Guardar archivo como... | Save |
| `<T>` | Sincronizar los cambios en la ruta seleccionada con el control remoto | Track |
| `<U>` | Ir al directorio principal | Upper |
| `<V|F3>` | Abrir archivo con el programa predeterminado | View |
| `<W>` | Abrir archivo con el programa proporcionado | With |
| `<X>` | Ejecutar un comando | eXecute |
| `<Y>` | Alternar navegación sincronizada | sYnc |
| `<CTRL+A>` | Seleccionar todos los archivos | |
| `<CTRL+C>` | Abortar el proceso de transferencia de archivos | |
| `<CTRL+T>` | Mostrar todas las rutas sincronizadas | Track |
### Trabaja en varios archivos 🥷
Puede optar por trabajar en varios archivos, seleccionándolos presionando `<M>`, para seleccionar el archivo actual, o presionando `<CTRL + A>`, que seleccionará todos los archivos en el directorio de trabajo.
Una vez que un archivo está marcado para su selección, se mostrará con un `*` a la izquierda.
Al trabajar en la selección, solo se procesará el archivo seleccionado para las acciones, mientras que el elemento resaltado actual se ignorará.
También es posible trabajar en varios archivos desde el panel de resultados de búsqueda.
Todas las acciones están disponibles cuando se trabaja con varios archivos, pero tenga en cuenta que algunas acciones funcionan de forma ligeramente diferente. Vamos a sumergirnos en:
- *Copy*: cada vez que copie un archivo, se le pedirá que inserte el nombre de destino. Cuando se trabaja con varios archivos, este nombre se refiere al directorio de destino donde se copiarán todos estos archivos.
- *Rename*: igual que copiar, pero moverá archivos allí.
- *Save as*: igual que copiar, pero los escribirá allí.
### Navegación sincronizada ⏲️
Cuando está habilitada, la navegación sincronizada le permitirá sincronizar la navegación entre los dos paneles.
Esto significa que siempre que cambie el directorio de trabajo en un panel, la misma acción se reproducirá en el otro panel. Si desea habilitar la navegación sincronizada, simplemente presione `<Y>`; presione dos veces para deshabilitar. Mientras está habilitado, el estado de navegación sincronizada se informará en la barra de estado en "ON".
### Abierta y abierta con 🚪
Al abrir archivos con el comando Ver (`<V>`), se utilizará la aplicación predeterminada del sistema para el tipo de archivo. Para hacerlo, se utilizará el servicio del sistema operativo predeterminado, así que asegúrese de tener al menos uno de estos instalado en su sistema:
- Usuarios **Windows**: no tiene que preocuparse por eso, ya que la caja usará el comando `start`.
- Usuarios **MacOS**: tampoco tiene que preocuparse, ya que la caja usará `open`, que ya está instalado en su sistema.
- Usuarios **Linux**: uno de estos debe estar instalado
- *xdg-open*
- *gio*
- *gnome-open*
- *kde-open*
- Usuarios **WSL**: *wslview* es obligatorio, debe instalar [wslu](https://github.com/wslutilities/wslu).
> Q: ¿Puedo editar archivos remotos usando el comando de vista?
> A: No, al menos no directamente desde el "panel remoto". Primero debe descargarlo en un directorio local, eso se debe al hecho de que cuando abre un archivo remoto, el archivo se descarga en un directorio temporal, pero no hay forma de crear un observador para que el archivo verifique cuándo el programa utilizado para abrirlo estaba cerrado, por lo que termscp no puede saber cuándo ha terminado de editar el archivo.
---
## Marcadores ⭐
En termscp es posible guardar hosts favoritos, que luego se pueden cargar rápidamente desde el diseño principal de termscp.
termscp también guardará los últimos 16 hosts a los que se conectó.
Esta función le permite cargar todos los parámetros necesarios para conectarse a un determinado control remoto, simplemente seleccionando el marcador en la pestaña debajo del formulario de autenticación.
Los marcadores se guardarán, si es posible, en:
- `$HOME/.config/termscp/` en Linux/BSD
- `$HOME/Library/Application Support/termscp` en MacOs
- `FOLDERID_RoamingAppData\termscp\` en Windows
Solo para marcadores (esto no se aplicará a hosts recientes) también es posible guardar la contraseña utilizada para autenticarse. La contraseña no se guarda de forma predeterminada y debe especificarse a través del indicador al guardar un nuevo marcador.
Si le preocupa la seguridad de la contraseña guardada para sus marcadores, lea el [capítulo siguiente 👀](#are-my-passwords-safe-).
Para crear un nuevo marcador, simplemente siga estos pasos:
1. Escriba en el formulario de autenticación los parámetros para conectarse a su servidor remoto
2. Presionar `<CTRL + S>`
3. Escriba el nombre que desea darle al marcador
4. Elija si recordar la contraseña o no
5. Presionar `<ENTER>`
siempre que desee utilizar la conexión previamente guardada, simplemente presione `<TAB>` para navegar a la lista de marcadores y cargue los parámetros del marcador en el formulario presionando `<ENTER>`.
![Bookmarks](https://github.com/veeso/termscp/blob/main/assets/images/bookmarks.gif?raw=true)
### ¿Son seguras mis contraseñas? 😈
Seguro 😉.
Como se dijo antes, los marcadores se guardan en su directorio de configuración junto con las contraseñas. Las contraseñas obviamente no son texto sin formato, están encriptadas con **AES-128**. ¿Esto los hace seguros? ¡Absolutamente! (excepto para usuarios de BSD y WSL 😢)
En **Windows**, **Linux** y **MacOS**, la clave utilizada para cifrar las contraseñas se almacena, si es posible (pero debería estar), respectivamente, en *Windows Vault*, en el *anillo de claves del sistema* y en el *Llavero*. Esto es realmente muy seguro y lo administra directamente su sistema operativo.
❗ Por favor, tenga en cuenta que si es un usuario de Linux, es mejor que lea el [capítulo siguiente 👀](#linux-keyring), ¡porque es posible que el llavero no esté habilitado o no sea compatible con su sistema!
En *BSD* y *WSL*, por otro lado, la clave utilizada para cifrar sus contraseñas se almacena en su disco (en `$HOME/.config/ termscp`). Entonces, todavía es posible recuperar la clave para descifrar las contraseñas. Afortunadamente, la ubicación de la clave garantiza que su clave no pueda ser leída por usuarios diferentes al suyo, pero sí, todavía no guardaría la contraseña para un servidor expuesto en Internet 😉.
#### Linux Keyring
A todos nos encanta Linux gracias a la libertad que ofrece a los usuarios. Básicamente, puede hacer lo que quiera como usuario de Linux, pero esto también tiene algunas desventajas, como el hecho de que a menudo no hay aplicaciones estándar en las diferentes distribuciones. Y esto también implica el llavero.
Esto significa que en Linux puede que no haya un llavero instalado en su sistema. Desafortunadamente, la biblioteca que usamos para trabajar con el almacenamiento de claves requiere un servicio que exponga `org.freedesktop.secrets` en D-BUS y el peor hecho es que solo hay dos servicios que lo exponen.
- ❗ Si usa GNOME como entorno de escritorio (por ejemplo, usuarios de ubuntu), ya debería estar bien, ya que `gnome-keyring` ya proporciona el llavero y todo debería estar funcionando.
- ❗ Para otros usuarios de entornos de escritorio, hay un buen programa que pueden usar para obtener un llavero que es [KeepassXC](https://keepassxc.org/), que utilizo en mi instalación de Manjaro (con KDE) y funciona bien. El único problema es que debe configurarlo para que se use junto con termscp (pero es bastante simple). Para comenzar con KeepassXC, lea más [aquí](#keepassxc-setup-por-termscp).
- ❗ ¿Qué pasa si no desea instalar ninguno de estos servicios? Bueno, ¡no hay problema! **termscp seguirá funcionando como de costumbre**, pero guardará la clave en un archivo, como suele hacer para BSD y WSL.
##### KeepassXC setup por termscp
Siga estos pasos para configurar keepassXC para termscp:
1. Instalar KeepassXC
2. Vaya a "tools" > "settings" en la barra de herramientas
3. Seleccione "Secret service integration" y abilita "Enable KeepassXC freedesktop.org secret service integration"
4. Cree una base de datos, si aún no tiene una: desde la barra de herramientas "Database" > "New database"
5. Desde la barra de herramientas: "Database" > "Database settings"
6. Seleccione "Secret service integration" y abilita "Expose entries under this group"
7. Seleccione el grupo de la lista donde desea que se mantenga el secreto de termscp. Recuerde que este grupo puede ser utilizado por cualquier otra aplicación para almacenar secretos a través de DBUS.
---
## Configuración ⚙️
termscp admite algunos parámetros definidos por el usuario, que se pueden definir en la configuración.
Underhood termscp tiene un archivo TOML y algunos otros directorios donde se guardarán todos los parámetros, pero no se preocupe, no tocará ninguno de estos archivos manualmente, ya que hice posible configurar termscp desde su interfaz de usuario por completo.
termscp, al igual que para los marcadores, solo requiere tener estas rutas accesibles:
- `$HOME/.config/termscp/` en Linux/BSD
- `$HOME/Library/Application Support/termscp` en MacOs
- `FOLDERID_RoamingAppData\termscp\` en Windows
Para acceder a la configuración, solo tiene que presionar `<CTRL + C>` desde el inicio de termscp.
Estos parámetros se pueden cambiar:
- **Text Editor**: l editor de texto a utilizar. Por defecto, termscp encontrará el editor predeterminado para usted; con esta opción puede forzar el uso de un editor (por ejemplo, `vim`). **También se admiten los editores de GUI**, a menos que hagan "nohup" del proceso principal.
- **Default Protocol**: el protocolo predeterminado es el valor predeterminado para el protocolo de transferencia de archivos que se utilizará en termscp. Esto se aplica a la página de inicio de sesión y al argumento de la CLI de la dirección.
- **Show Hidden Files**: seleccione si los archivos ocultos se mostrarán de forma predeterminada. Podrás decidir si mostrar o no archivos ocultos en tiempo de ejecución presionando "A" de todos modos.
- **Check for updates**: si se establece en `yes`, termscp buscará la API de Github para comprobar si hay una nueva versión de termscp disponible.
- **Prompt when replacing existing files?**: Si se establece en "sí", termscp le pedirá confirmación cada vez que una transferencia de archivo provoque la sustitución de un archivo existente en el host de destino.
- **Group Dirs**: seleccione si los directorios deben agruparse o no en los exploradores de archivos. Si se selecciona `Display first`, los directorios se ordenarán usando el método configurado pero se mostrarán antes de los archivos, y viceversa si se selecciona`Display last`.
- **Remote File formatter syntax**: sintaxis para mostrar información de archivo para cada archivo en el explorador remoto. Consulte [Formato del explorador de archivos](#formato-del-explorador-de-archivos).
- **Local File formatter syntax**: sintaxis para mostrar información de archivo para cada archivo en el explorador local. Consulte [Formato del explorador de archivos](#formato-del-explorador-de-archivos).
- **Enable notifications?**: Si se establece en "Sí", se mostrarán las notificaciones.
- **Notifications: minimum transfer size**: si el tamaño de la transferencia es mayor o igual que el valor especificado, se mostrarán notificaciones de transferencia. Los valores aceptados están en formato `{UNSIGNED} B/KB/MB/GB/TB/PB`
- **SSH configuration path**: Configure el archivo de configuración SSH para usar al conectarse a un servidor SCP / SFTP. Si no se configura (está vacío), no se utilizará ningún archivo. Puede especificar una ruta que comience con `~` para indicar la ruta de inicio (por ejemplo, `~/.ssh/config`)
### SSH Key Storage 🔐
Junto con la configuración, termscp también proporciona una característica **esencial** para **clientes SFTP / SCP**: el almacenamiento de claves SSH.
Puede acceder al almacenamiento de claves SSH, desde la configuración pasando a la pestaña `Claves SSH`, una vez allí puede:
- **Agregar una nueva clave**: simplemente presione `<CTRL + N>` y se le pedirá que cree una nueva clave. Proporcione el nombre de host / dirección IP y el nombre de usuario asociado a la clave y finalmente se abrirá un editor de texto: pegue la clave ssh **PRIVATE** en el editor de texto, guarde y salga.
- **Eliminar una clave existente**: simplemente presione `<DEL>` o `<CTRL + E>` en la clave que desea eliminar, para eliminar persistentemente la clave de termscp.
- **Editar una clave existente**: simplemente presione `<ENTER>` en la clave que desea editar, para cambiar la clave privada.
> Q: Mi clave privada está protegida con contraseña, ¿puedo usarla?
> A: Por supuesto que puede. La contraseña proporcionada para la autenticación en termscp es válida tanto para la autenticación de nombre de usuario / contraseña como para la autenticación de clave RSA.
### Formato del explorador de archivos
Es posible a través de la configuración definir un formato personalizado para el explorador de archivos. Esto es posible tanto para el host local como para el remoto, por lo que puede tener dos sintaxis diferentes en uso. Estos campos, con el nombre `File formatter syntax (local)` y `File formatter syntax (remote)` definirán cómo se mostrarán las entradas del archivo en el explorador de archivos.
La sintaxis del formateador es la siguiente `{KEY1} ... {KEY2:LENGTH} ... {KEY3:LENGTH:EXTRA} {KEYn} ...`.
Cada clave entre corchetes se reemplazará con el atributo relacionado, mientras que todo lo que esté fuera de los corchetes se dejará sin cambios.
- El nombre de la clave es obligatorio y debe ser una de las claves siguientes
- La longitud describe la longitud reservada para mostrar el campo. Los atributos estáticos no admiten esto (GROUP, PEX, SIZE, USER)
- Extra es compatible solo con algunos parámetros y es una opción adicional. Consulte las claves para comprobar si se admite extra.
Estas son las claves admitidas por el formateador:
- `ATIME`: Hora del último acceso (con la sintaxis predeterminada`%b %d %Y %H:%M`); Se puede proporcionar un extra como la sintaxis de tiempo (por ejemplo, "{ATIME: 8:% H:% M}")
- `CTIME`: Hora de creación (con sintaxis`%b %d %Y %H:%M`); Se puede proporcionar un extra como sintaxis de tiempo (p. Ej., `{CTIME:8:%H:%M}`)
- `GROUP`: Grupo propietario
- `MTIME`: Hora del último cambio (con sintaxis`%b %d %Y %H:%M`); Se puede proporcionar extra como sintaxis de tiempo (p. Ej., `{MTIME: 8:% H:% M}`)
- `NAME`: nombre de archivo (Las carpetas entre la raíz y los primeros antepasados se eliminan si es más largo que LENGTH)
- `PATH`: Percorso completo de archivo (Las carpetas entre la raíz y los primeros antepasados se eliminan si es màs largo que LENGHT)
- `PEX`: permisos de archivo (formato UNIX)
- `SIZE`: Tamaño del archivo (se omite para directorios)
- `SYMLINK`: Symlink (si existe` -> {FILE_PATH} `)
- `USER`: Usuario propietario
Si se deja vacío, se utilizará la sintaxis del formateador predeterminada: `{NAME:24} {PEX} {USER} {SIZE} {MTIME:17:%b %d %Y %H:%M}`
---
## Temas 🎨
Termscp le ofrece una característica asombrosa: la posibilidad de configurar los colores para varios componentes de la aplicación.
Si desea personalizar termscp, hay dos formas disponibles de hacerlo:
- Desde el **menú de configuración**
- Importando un **archivo de tema**
Para crear su propia personalización desde termscp, todo lo que tiene que hacer es ingresar a la configuración desde la actividad de autenticación, presionando `<CTRL + C>` y luego `<TAB>` dos veces. Deberías haberte movido ahora al panel de `temas`.
Aquí puede moverse con `<UP>` y `<DOWN>` para cambiar el estilo que desea cambiar, como se muestra en el siguiente gif:
![Themes](https://github.com/veeso/termscp/blob/main/assets/images/themes.gif?raw=true)
termscp admite la sintaxis tradicional hexadecimal explícita (`#rrggbb`) y rgb `rgb(r, g, b)` para proporcionar colores, pero se aceptan también **[colores css](https://www.w3schools.com/cssref/css_colors.asp)** (como `crimson`) 😉. También hay un teclado especial que es `Default`. Predeterminado significa que el color utilizado será el color de primer plano o de fondo predeterminado según la situación (primer plano para textos y líneas, fondo para bien, adivinen qué).
Como se dijo antes, también puede importar archivos de temas. Puede inspirarse o utilizar directamente uno de los temas proporcionados junto con termscp, ubicado en el directorio `themes/` de este repositorio e importarlos ejecutando termscp como `termscp -t <theme_file>`. Si todo estuvo bien, debería decirle que el tema se ha importado correctamente.
### Mi tema no se carga 😱
Esto probablemente se deba a una actualización reciente que ha roto el tema. Siempre que agrego una nueva clave a los temas, el tema guardado no se carga. Para solucionar este problema, existen dos soluciones realmente rápidas:
1. Recargar tema: cada vez que publique una actualización, también parchearé los temas "oficiales", por lo que solo tiene que descargarlo del repositorio nuevamente y volver a importar el tema a través de la opción `-t`
```sh
termscp -t <theme.toml>
```
2. Corrija su tema: si está utilizando un tema personalizado, puede editarlo a través de `vim` y agregar la clave que falta. El tema se encuentra en `$CONFIG_DIR/termscp/theme.toml` donde `$CONFIG_DIR` es:
- FreeBSD/GNU-Linux: `$HOME/.config/`
- MacOs: `$HOME/Library/Application Support`
- Windows: `%appdata%`
❗ Las claves que faltan se informan en el CAMBIO en `BREAKING CHANGES` para la versión que acaba de instalar.
### Estilos 💈
Puede encontrar en la tabla siguiente la descripción de cada campo de estilo.
Tenga en cuenta que **los estilos no se aplicarán a la página de configuración**, para que sea siempre accesible en caso de que lo estropee todo
#### Authentication page
| Key | Description |
|----------------|------------------------------------------|
| auth_address | Color of the input field for IP address |
| auth_bookmarks | Color of the bookmarks panel |
| auth_password | Color of the input field for password |
| auth_port | Color of the input field for port number |
| auth_protocol | Color of the radio group for protocol |
| auth_recents | Color of the recents panel |
| auth_username | Color of the input field for username |
#### Transfer page
| Key | Description |
|--------------------------------------|---------------------------------------------------------------------------|
| transfer_local_explorer_background | Background color of localhost explorer |
| transfer_local_explorer_foreground | Foreground coloor of localhost explorer |
| transfer_local_explorer_highlighted | Border and highlighted color for localhost explorer |
| transfer_remote_explorer_background | Background color of remote explorer |
| transfer_remote_explorer_foreground | Foreground coloor of remote explorer |
| transfer_remote_explorer_highlighted | Border and highlighted color for remote explorer |
| transfer_log_background | Background color for log panel |
| transfer_log_window | Window color for log panel |
| transfer_progress_bar_partial | Partial progress bar color |
| transfer_progress_bar_total | Total progress bar color |
| transfer_status_hidden | Color for status bar "hidden" label |
| transfer_status_sorting | Color for status bar "sorting" label; applies also to file sorting dialog |
| transfer_status_sync_browsing | Color for status bar "sync browsing" label |
#### Misc
These styles applie to different part of the application.
| Key | Description |
|-------------------|---------------------------------------------|
| misc_error_dialog | Color for error messages |
| misc_info_dialog | Color for info dialogs |
| misc_input_dialog | Color for input dialogs (such as copy file) |
| misc_keys | Color of text for key strokes |
| misc_quit_dialog | Color for quit dialogs |
| misc_save_dialog | Color for save dialogs |
| misc_warn_dialog | Color for warn dialogs |
---
## Text Editor ✏
termscp tiene, como habrás notado, muchas características, una de ellas es la posibilidad de ver y editar archivos de texto. No importa si el archivo está ubicado en el host local o en el host remoto, termscp brinda la posibilidad de abrir un archivo en su editor de texto favorito.
En caso de que el archivo esté ubicado en un host remoto, el archivo se descargará primero en su directorio de archivos temporales y luego, **solo** si se realizaron cambios en el archivo, se volverá a cargar en el host remoto. termscp comprueba si realizó cambios en el archivo verificando la última hora de modificación del archivo.
> ❗ Just a reminder: **you can edit only textual file**; binary files are not supported.
---
## Logging 🩺
termscp escribe un archivo de registro para cada sesión, que se escribe en
- `$HOME/.config/termscp/termscp.log` en Linux/BSD
- `$HOME/Library/Application Support/termscp/termscp.log` en MacOs
- `FOLDERID_RoamingAppData\termscp\termscp.log` en Windows
el registro no se rotará, sino que se truncará después de cada lanzamiento de termscp, por lo que si desea informar un problema y desea adjuntar su archivo de registro, recuerde guardar el archivo de registro en un lugar seguro antes de usar termscp de nuevo.
El registro por defecto informa en el nivel *INFO*, por lo que no es muy detallado.
Si desea enviar un problema, por favor, si puede, reproduzca el problema con el nivel establecido en "TRACE", para hacerlo, inicie termscp con
la opción CLI `-D`.
Sé que es posible que tenga algunas preguntas sobre los archivos de registro, así que hice una especie de Q/A:
> No quiero el registro, ¿puedo apagarlo?
Sí tu puedes. Simplemente inicie termscp con la opción `-q o --quiet`. Puede alias termscp para que sea persistente. Recuerde que el registro se usa para diagnosticar problemas, por lo que, dado que detrás de cada proyecto de código abierto, siempre debe haber este tipo de ayuda mutua, mantener los archivos de registro puede ser su forma de respaldar el proyecto 😉.
> ¿Es seguro el registro?
Si le preocupa la seguridad, el archivo de registro no contiene ninguna contraseña simple, así que no se preocupe y expone la misma información que informa el archivo hermano `marcadores`.
## Notificaciones 📫
Termscp enviará notificaciones de escritorio para este tipo de eventos:
- en **Transferencia completada**: la notificación se enviará una vez que la transferencia se haya completado con éxito.
- ❗ La notificación se mostrará solo si el tamaño total de la transferencia es al menos el `Notifications: minimum transfer size` especificado en la configuración.
- en **Transferencia fallida**: la notificación se enviará una vez que la transferencia haya fallado debido a un error.
- ❗ La notificación se mostrará solo si el tamaño total de la transferencia es al menos el `Notifications: minimum transfer size` especificado en la configuración.
- en **Actualización disponible**: siempre que haya una nueva versión de termscp disponible, se mostrará una notificación.
- en **Actualización instalada**: siempre que se haya instalado una nueva versión de termscp, se mostrará una notificación.
- en **Actualización fallida**: siempre que falle la instalación de la actualización, se mostrará una notificación.
❗ Si prefiere mantener las notificaciones desactivadas, puede simplemente ingresar a la configuración y configurar `Enable notifications?` En `No` 😉.
❗ Si desea cambiar el tamaño mínimo de transferencia para mostrar notificaciones, puede cambiar el valor en la configuración con la tecla `Notifications: minimum transfer size` y configurarlo como mejor le convenga 🙂.
## Observador de archivos 🔭
El observador de archivos le permite configurar una lista de rutas para sincronizar con los hosts remotos.
Esto significa que siempre que se detecte un cambio en el sistema de archivos local en la ruta sincronizada, el cambio se informará automáticamente a la ruta del host remoto configurado, dentro de los 5 segundos.
Puede establecer tantas rutas para sincronizar como prefiera:
1. Coloque el cursor en el explorador local en el directorio/archivo que desea mantener sincronizado
2. Vaya al directorio en el que desea que se informen los cambios en el host remoto
3. Presione `<T>`
4. Responda `<YES>` a la ventana emergente de radio
Para dejar de mirar, simplemente presione `<T>` en la ruta sincronizada local (o en cualquiera de sus subcarpetas)
O simplemente puede presionar `<CTRL + T>` y presionar `<ENTER>` en la ruta sincronizada que desea dejar de ver.
Estos cambios se informarán al host remoto:
- Nuevos archivos, cambios de archivos
- Archivo movido / renombrado
- Archivo eliminado/desvinculado
> ❗ El vigilante trabaja solo en una dirección (local > remota). NO es posible sincronizar automáticamente los cambios de remoto a local.

290
docs/fr/README.md Normal file
View File

@@ -0,0 +1,290 @@
# termscp
<p align="center">
<img src="/assets/images/termscp.svg" width="256" height="256" />
</p>
<p align="center">~ Un file transfer de terminal riche en fonctionnalités ~</p>
<p align="center">
<a href="https://veeso.github.io/termscp/" target="_blank">Site internet</a>
·
<a href="https://veeso.github.io/termscp/#get-started" target="_blank">Installation</a>
·
<a href="https://veeso.github.io/termscp/#user-manual" target="_blank">Manuel de l'Utilisateur</a>
</p>
<p align="center">
<a href="https://github.com/veeso/termscp"
><img
height="20"
src="/assets/images/flags/us.png"
alt="English"
/></a>
&nbsp;
<a
href="/docs/de/README.md"
><img
height="20"
src="/assets/images/flags/de.png"
alt="Deutsch"
/></a>
&nbsp;
<a
href="/docs/es/README.md"
><img
height="20"
src="/assets/images/flags/es.png"
alt="Español"
/></a>
&nbsp;
<a
href="/docs/fr/README.md"
><img
height="20"
src="/assets/images/flags/fr.png"
alt="Français"
/></a>
&nbsp;
<a
href="/docs/it/README.md"
><img
height="20"
src="/assets/images/flags/it.png"
alt="Italiano"
/></a>
&nbsp;
<a
href="/docs/zh-CN/README.md"
><img
height="20"
src="/assets/images/flags/cn.png"
alt="简体中文"
/></a>
</p>
<p align="center">Développé par <a href="https://veeso.github.io/" target="_blank">@veeso</a></p>
<p align="center">Version actuelle: 0.9.0 (18/06/2022)</p>
<p align="center">
<a href="https://opensource.org/licenses/MIT"
><img
src="https://img.shields.io/badge/License-MIT-teal.svg"
alt="License-MIT"
/></a>
<a href="https://github.com/veeso/termscp/stargazers"
><img
src="https://img.shields.io/github/stars/veeso/termscp.svg"
alt="Repo stars"
/></a>
<a href="https://crates.io/crates/termscp"
><img
src="https://img.shields.io/crates/d/termscp.svg"
alt="Downloads counter"
/></a>
<a href="https://crates.io/crates/termscp"
><img
src="https://img.shields.io/crates/v/termscp.svg"
alt="Latest version"
/></a>
<a href="https://ko-fi.com/veeso">
<img
src="https://img.shields.io/badge/donate-ko--fi-red"
alt="Ko-fi"
/></a>
</p>
<p align="center">
<a href="https://github.com/veeso/termscp/actions"
><img
src="https://github.com/veeso/termscp/workflows/Linux/badge.svg"
alt="Linux CI"
/></a>
<a href="https://github.com/veeso/termscp/actions"
><img
src="https://github.com/veeso/termscp/workflows/MacOS/badge.svg"
alt="MacOS CI"
/></a>
<a href="https://github.com/veeso/termscp/actions"
><img
src="https://github.com/veeso/termscp/workflows/Windows/badge.svg"
alt="Windows CI"
/></a>
<a href="https://github.com/veeso/termscp/actions"
><img
src="https://github.com/veeso/termscp/workflows/FreeBSD/badge.svg"
alt="FreeBSD CI"
/></a>
<a href="https://coveralls.io/github/veeso/termscp"
><img
src="https://coveralls.io/repos/github/veeso/termscp/badge.svg"
alt="Coveralls"
/></a>
</p>
---
## À propos des termscp 🖥
Termscp est un file transfer et explorateur de fichiers de terminal riche en fonctionnalités, avec support pour SCP/SFTP/FTP/S3. Essentiellement c'est une utilitaire terminal avec une TUI pour se connecter à un serveur distant pour télécharger de fichiers et interagir avec le système de fichiers local. Il est compatible avec **Linux**, **MacOS**, **FreeBSD** et **Windows**.
![Explorer](/assets/images/explorer.gif)
---
## Fonctionnalités 🎁
- 📁 Différents protocoles de communication
- **SFTP**
- **SCP**
- **FTP** et **FTPS**
- **S3**
- 🖥 Explorer et opérer sur le système de fichiers distant et local avec une interface utilisateur pratique.
- Créer, supprimer, renommer, rechercher, afficher et modifier des fichiers
- ⭐ Connectez-vous à vos hôtes préférés via des signets et des connexions récentes.
- 📝 Affichez et modifiez des fichiers avec vos applications préférées
- 💁 Authentication SFTP/SCP avec des clés SSH et nom/mot de passe
- 🐧 Compatible avec Windows, Linux, FreeBSD et MacOS
- 🎨 Faites en vôtre !
- thèmes
- format d'explorateur de fichiers personnalisé
- éditeur de texte personnalisable
- tri de fichiers personallisable
- et bien d'autres paramètres...
- 📫 Recevez une notification quande un gros fichier est télécharger.
- 🔭 Gardez les modifications de fichiers synchronisées avec l'hôte distant
- 🔐 Enregistre tes mots de passe dans le key vault du systeme.
- 🦀 Rust-powered
- 👀 Développé en gardant un œil sur les performances
- 🦄 Mises à jour fréquentes
---
## Pour commencer 🚀
Si tu envisage d'installer termscp, je veux te remercier 💜 ! J'espère que tu vas apprécier termscp !
Si tu veux contribuer à ce projet, n'oublié pas de consulter notre [guide de contribution](../../CONTRIBUTING.md).
Si tu es un utilisateur Linux, FreeBSD ou MacOS ce simple shell script installera termscp sur te système en un seule commande:
```sh
curl --proto '=https' --tlsv1.2 -sSLf "https://git.io/JBhDb" | sh
```
tandis que si tu es un utilisateur Windows, tu peux installer termscp avec [Chocolatey](https://chocolatey.org/):
```sh
choco install termscp
```
Pour plus d'informations sur les autres méthodes d'installation, veuillez visiter [veeso.github.io](https://veeso.github.io/termscp/#get-started).
⚠️ Si tu cherche comme de mettre à jour termscp, tu dois exécuter cette commande dans le terminal: `(sudo) termscp --update` ⚠️
### Requis ❗
- utilisateurs **Linux**:
- libssh
- libdbus-1
- pkg-config
- utilisateurs **FreeBSD**:
- libssh
- dbus
- pkgconf
### Requis facultatives ✔️
Ces requis ne sont pas obligatoires d'exécuter termscp, mais seulement à toutes ses fonctionnalités
- utilisateurs **Linux/FreeBSD**:
- Pour **ouvrir** les fichiers via `V` (au moins un de ces)
- *xdg-open*
- *gio*
- *gnome-open*
- *kde-open*
- utilisateurs **Linux**:
- Un keyring manager: lire plus dans le [manuel d'utilisateur](man.md#linux-keyring)
- utilisateurs **WSL**
- Pour **ouvrir** les fichiers via `V` (au moins un de ces)
- [wslu](https://github.com/wslutilities/wslu)
---
## Me soutenir ☕
Si tu aime termscp et que tu aimerais voir le projet grandir et s'améliorer, voudrais considérer un petit don pour me soutenir
Tu peux faire un don avec l'une de ces plateformes:
[![ko-fi](https://img.shields.io/badge/Ko--fi-F16061?style=for-the-badge&logo=ko-fi&logoColor=white)](https://ko-fi.com/veeso)
[![PayPal](https://img.shields.io/badge/PayPal-00457C?style=for-the-badge&logo=paypal&logoColor=white)](https://www.paypal.me/chrisintin)
---
## Manuel d'utilisateur et Documentation 📚
Le manuel d'utilisateur peut être trouvé sur le [site de termscp](https://veeso.github.io/termscp/#user-manual) ou sur [Github](man.md).
La documentation peut être trouvé sur Rust Docs <https://docs.rs/termscp>
---
## Contribution et enjeux 🤝🏻
Les contributions, les rapports de bugs, les nouvelles fonctionnalités et les questions sont les bienvenus ! 😉
Si tu ai des questions ou des préoccupations, ou si tu souhaite suggérer une nouvelle fonctionnalité, ou si tu souhaite simplement améliorer les conditions de termscp, n'hésite pas à ouvrir un problème ou un PR.
Veuillez suivre [nos directives de contribution](../../CONTRIBUTING.md)
---
## Journal des modifications ⏳
Afficher le journal des modifications [ICI](../../CHANGELOG.md)
---
## Powered by 💪
termscp est soutenu par ces projets impressionnants:
- [bytesize](https://github.com/hyunsik/bytesize)
- [crossterm](https://github.com/crossterm-rs/crossterm)
- [edit](https://github.com/milkey-mouse/edit)
- [keyring-rs](https://github.com/hwchen/keyring-rs)
- [open-rs](https://github.com/Byron/open-rs)
- [rpassword](https://github.com/conradkleinespel/rpassword)
- [rust-s3](https://github.com/durch/rust-s3)
- [self_update](https://github.com/jaemk/self_update)
- [ssh2-rs](https://github.com/alexcrichton/ssh2-rs)
- [suppaftp](https://github.com/veeso/suppaftp)
- [tui-rs](https://github.com/fdehau/tui-rs)
- [tui-realm](https://github.com/veeso/tui-realm)
- [whoami](https://github.com/libcala/whoami)
- [wildmatch](https://github.com/becheran/wildmatch)
---
## Gallerie 🎬
> Termscp Home
![Auth](/assets/images/auth.gif)
> Bookmarks
![Bookmarks](/assets/images/bookmarks.gif)
> Setup
![Setup](/assets/images/config.gif)
> Text editor
![TextEditor](/assets/images/text-editor.gif)
---
## Licence 📃
termscp est sous licence MIT.
Vous pouvez lire l'intégralité de la licence [ICI](../../LICENSE)

538
docs/fr/man.md Normal file
View File

@@ -0,0 +1,538 @@
# User manual 🎓
- [User manual 🎓](#user-manual-)
- [Usage ❓](#usage-)
- [Argument d'adresse 🌎](#argument-dadresse-)
- [Argument d'adresse AWS S3](#argument-dadresse-aws-s3)
- [Comment le mot de passe peut être fourni 🔐](#comment-le-mot-de-passe-peut-être-fourni-)
- [S3 paramètres de connexion](#s3-paramètres-de-connexion)
- [Identifiants S3 🦊](#identifiants-s3-)
- [Explorateur de fichiers 📂](#explorateur-de-fichiers-)
- [Raccourcis clavier ⌨](#raccourcis-clavier-)
- [Travailler sur plusieurs fichiers 🥷](#travailler-sur-plusieurs-fichiers-)
- [Navigation synchronisée ⏲️](#navigation-synchronisée-)
- [Ouvrir et ouvrir avec 🚪](#ouvrir-et-ouvrir-avec-)
- [Signets ⭐](#signets-)
- [Mes mots de passe sont-ils sûrs 😈](#mes-mots-de-passe-sont-ils-sûrs-)
- [Linux Keyring](#linux-keyring)
- [Configuration de KeepassXC pour termscp](#configuration-de-keepassxc-pour-termscp)
- [Configuration ⚙️](#configuration-)
- [SSH Key Storage 🔐](#ssh-key-storage-)
- [Format de l'explorateur de fichiers](#format-de-lexplorateur-de-fichiers)
- [Thèmes 🎨](#thèmes-)
- [Mon thème ne se charge pas 😱](#mon-thème-ne-se-charge-pas-)
- [Modes 💈](#modes-)
- [Authentication page](#authentication-page)
- [Transfer page](#transfer-page)
- [Misc](#misc)
- [Éditeur de texte ✏](#éditeur-de-texte-)
- [Fichier Journal 🩺](#fichier-journal-)
- [Notifications 📫](#notifications-)
- [Observateur de fichiers 🔭](#observateur-de-fichiers-)
## Usage ❓
termscp peut être démarré avec les options suivantes :
`termscp [options]... [protocol://user@address:port:wrkdir] [local-wrkdir]`
ou
`termscp [options]... -b [bookmark-name] [local-wrkdir]`
- `-P, --password <password>` si l'adresse est fournie, le mot de passe sera cet argument
- `-b, --address-as-bookmark` résoudre l'argument d'adresse en tant que nom de signet
- `-c, --config` Ouvrir termscp à partir de la page de configuration
- `-q, --quiet` Désactiver la journalisation
- `-t, --theme <path>` Importer le thème spécifié
- `-u, --update` Mettre à jour termscp vers la dernière version
- `-v, --version` Imprimer les informations sur la version
- `-h, --help` Imprimer la page d'aide
termscp peut être démarré dans deux modes différents, si aucun argument supplémentaire n'est fourni, termscp affichera le formulaire d'authentification, où l'utilisateur pourra fournir les paramètres requis pour se connecter au pair distant.
Alternativement, l'utilisateur peut fournir une adresse comme argument pour ignorer le formulaire d'authentification et démarrer directement la connexion au serveur distant.
Si l'argument d'adresse est fourni, vous pouvez également fournir le répertoire de démarrage de l'hôte local
### Argument d'adresse 🌎
L'argument adresse a la syntaxe suivante :
```txt
[protocole://][nom-utilisateur@]<adresse>[:port][:wrkdir]
```
Voyons un exemple de cette syntaxe particulière, car elle est très confortable et vous allez probablement l'utiliser à la place de l'autre...
- Se connecter en utilisant le protocole par défaut (*défini dans la configuration*) à 192.168.1.31, le port s'il n'est pas fourni est par défaut pour le protocole sélectionné (dans ce cas dépend de votre configuration) ; nom d'utilisateur est le nom de l'utilisateur actuel
```sh
termscp 192.168.1.31
```
- Se connecter en utilisant le protocole par défaut (*défini dans la configuration*) à 192.168.1.31 ; le nom d'utilisateur est "root"
```sh
termscp root@192.168.1.31
```
- Se connecter en utilisant scp à 192.168.1.31, le port est 4022 ; le nom d'utilisateur est "omar"
```sh
termscp scp://omar@192.168.1.31:4022
```
- Se connecter en utilisant scp à 192.168.1.31, le port est 4022 ; le nom d'utilisateur est "omar". Vous commencerez dans le répertoire `/tmp`
```sh
termscp scp://omar@192.168.1.31:4022:/tmp
```
#### Argument d'adresse AWS S3
Aws S3 a une syntaxe différente pour l'argument d'adresse CLI, pour des raisons évidentes, mais j'ai réussi à le garder le plus similaire possible à l'argument d'adresse générique :
```txt
s3://<bucket-name>@<region>[:profile][:/wrkdir]
```
e.g.
```txt
s3://buckethead@eu-central-1:default:/assets
```
#### Comment le mot de passe peut être fourni 🔐
Vous avez probablement remarqué que, lorsque vous fournissez l'adresse comme argument, il n'y a aucun moyen de fournir le mot de passe.
Le mot de passe peut être fourni de 3 manières lorsque l'argument d'adresse est fourni :
- `-P, --password` option : utilisez simplement cette option CLI en fournissant le mot de passe. Je déconseille fortement cette méthode, car elle n'est pas sécurisée (puisque vous pouvez conserver le mot de passe dans l'historique du shell)
- Avec `sshpass`: vous pouvez fournir un mot de passe via `sshpass`, par ex. `sshpass -f ~/.ssh/topsecret.key termscp cvisintin@192.168.1.31`
- Il vous sera demandé : si vous n'utilisez aucune des méthodes précédentes, le mot de passe vous sera demandé, comme c'est le cas avec les outils plus classiques tels que `scp`, `ssh`, etc.
---
## S3 paramètres de connexion
Ces paramètres sont requis pour se connecter à aws s3 et à d'autres serveurs compatibles s3 :
- AWS S3:
- **bucket name**
- **region**
- *profile* (si non fourni : "par défaut")
- *access key* (sauf si public)
- *secret access key* (sauf si public)
- *security token* (si nécessaire)
- *session token* (si nécessaire)
- new path style: **NO**
- Autres points de terminaison S3:
- **bucket name**
- **endpoint**
- *access key* (sauf si public)
- *secret access key* (sauf si public)
- new path style: **YES**
### Identifiants S3 🦊
Afin de vous connecter à un compartiment Aws S3, vous devez évidemment fournir des informations d'identification.
Il existe essentiellement trois manières d'y parvenir.
Voici donc les moyens de fournir les informations d'identification pour s3 :
1. Authentication form:
1. Vous pouvez fournir le `access_key` (devrait être obligatoire), le `secret_access_key` (devrait être obligatoire), `security_token` et le `session_token`
2. Si vous enregistrez la connexion s3 en tant que signet, ces informations d'identification seront enregistrées en tant que chaîne AES-256/BASE64 cryptée dans votre fichier de signets (à l'exception du jeton de sécurité et du jeton de session qui sont censés être des informations d'identification temporaires).
2. Utilisez votre fichier d'informations d'identification : configurez simplement l'AWS cli via `aws configure` et vos informations d'identification doivent déjà se trouver dans `~/.aws/credentials`. Si vous utilisez un profil différent de "default", fournissez-le simplement dans le champ profile du formulaire d'authentification.
3. **Variables d'environnement** : vous pouvez toujours fournir vos informations d'identification en tant que variables d'environnement. Gardez à l'esprit que ces informations d'identification **remplaceront toujours** les informations d'identification situées dans le fichier « credentials ». Voir comment configurer l'environnement ci-dessous :
Ceux-ci devraient toujours être obligatoires:
- `AWS_ACCESS_KEY_ID`: aws access key ID (commence généralement par `AKIA...`)
- `AWS_SECRET_ACCESS_KEY`: la secret access key
Au cas où vous auriez configuré une sécurité renforcée, vous *pourriez* également en avoir besoin :
- `AWS_SECURITY_TOKEN`: security token
- `AWS_SESSION_TOKEN`: session token
⚠️ Vos identifiants sont en sécurité : les termscp ne manipuleront pas ces valeurs directement ! Vos identifiants sont directement consommés par la caisse **s3**.
Si vous avez des inquiétudes concernant la sécurité, veuillez contacter l'auteur de la bibliothèque sur [Github](https://github.com/durch/rust-s3) ⚠️
---
## Explorateur de fichiers 📂
Lorsque nous nous référons aux explorateurs de fichiers en termscp, nous nous référons aux panneaux que vous pouvez voir après avoir établi une connexion avec la télécommande.
Ces panneaux sont essentiellement 3 (oui, trois en fait):
- Panneau de l'explorateur local : il s'affiche sur la gauche de votre écran et affiche les entrées du répertoire en cours pour localhost
- Panneau de l'explorateur distant : il s'affiche à droite de votre écran et affiche les entrées du répertoire en cours pour l'hôte distant.
- Panneau de résultats de recherche : selon l'endroit où vous recherchez des fichiers (local/distant), il remplacera le panneau local ou l'explorateur. Ce panneau affiche les entrées correspondant à la requête de recherche que vous avez effectuée.
Pour changer de panneau, vous devez taper `<LEFT>` pour déplacer le panneau de l'explorateur distant et `<RIGHT>` pour revenir au panneau de l'explorateur local. Chaque fois que vous êtes dans le panneau des résultats de recherche, vous devez appuyer sur `<ESC>` pour quitter le panneau et revenir au panneau précédent.
### Raccourcis clavier ⌨
| Key | Command | Reminder |
|---------------|---------------------------------------------------------------------------|-------------|
| `<ESC>` | Se Déconnecter de le serveur; retour à la page d'authentification | |
| `<BACKSPACE>` | Aller au répertoire précédent dans la pile | |
| `<TAB>` | Changer d'onglet explorateur | |
| `<RIGHT>` | Déplacer vers l'onglet explorateur distant | |
| `<LEFT>` | Déplacer vers l'onglet explorateur local | |
| `<UP>` | Remonter dans la liste sélectionnée | |
| `<DOWN>` | Descendre dans la liste sélectionnée | |
| `<PGUP>` | Remonter dans la liste sélectionnée de 8 lignes | |
| `<PGDOWN>` | Descendre dans la liste sélectionnée de 8 lignes | |
| `<ENTER>` | Entrer dans le directoire | |
| `<SPACE>` | Télécharger le fichier sélectionné | |
| `<BACKTAB>` | Basculer entre l'onglet journal et l'explorateur | |
| `<A>` | Basculer les fichiers cachés | All |
| `<B>` | Trier les fichiers par | Bubblesort? |
| `<C|F5>` | Copier le fichier/répertoire | Copy |
| `<D|F7>` | Créer un dossier | Directory |
| `<E|F8|DEL>` | Supprimer le fichier (Identique à `DEL`) | Erase |
| `<F>` | Rechercher des fichiers | Find |
| `<G>` | Aller au chemin fourni | Go to |
| `<H|F1>` | Afficher l'aide | Help |
| `<I>` | Afficher les informations sur le fichier ou le dossier sélectionné | Info |
| `<K>` | Créer un lien symbolique pointant vers l'entrée actuellement sélectionnée | symlinK |
| `<L>` | Recharger le contenu du répertoire actuel / Effacer la sélection | List |
| `<M>` | Sélectionner un fichier | Mark |
| `<N>` | Créer un nouveau fichier avec le nom fourni | New |
| `<O|F4>` | Modifier le fichier | Open |
| `<Q|F10>` | Quitter termscp | Quit |
| `<R|F6>` | Renommer le fichier | Rename |
| `<S|F2>` | Enregistrer le fichier sous... | Save |
| `<T>` | Synchroniser les modifications apportées au chemin sélectionné | Track |
| `<U>` | Aller dans le répertoire parent | Upper |
| `<V|F3>` | Ouvrir le fichier avec le programme défaut pour le type de fichier | View |
| `<W>` | Ouvrir le fichier avec le programme spécifié | With |
| `<X>` | Exécuter une commande | eXecute |
| `<Y>` | Basculer la navigation synchronisée | sYnc |
| `<CTRL+A>` | Sélectionner tous les fichiers | |
| `<CTRL+C>` | Abandonner le processus de transfert de fichiers | |
| `<CTRL+T>` | Afficher tous les chemins synchronisés | Track |
### Travailler sur plusieurs fichiers 🥷
Vous pouvez choisir de travailler sur plusieurs fichiers, en les sélectionnant en appuyant sur `<M>`, afin de sélectionner le fichier actuel, ou en appuyant sur `<CTRL+A>`, ce qui sélectionnera tous les fichiers dans le répertoire de travail.
Une fois qu'un fichier est marqué pour la sélection, il sera affiché avec un `*` sur la gauche.
Lorsque vous travaillez sur la sélection, seul le fichier sélectionné sera traité pour les actions, tandis que l'élément en surbrillance actuel sera ignoré.
Il est également possible de travailler sur plusieurs fichiers dans le panneau des résultats de recherche.
Toutes les actions sont disponibles lorsque vous travaillez avec plusieurs fichiers, mais sachez que certaines actions fonctionnent de manière légèrement différente. Plongeons dans:
- *Copy*: chaque fois que vous copiez un fichier, vous serez invité à insérer le nom de destination. Lorsque vous travaillez avec plusieurs fichiers, ce nom fait référence au répertoire de destination où tous ces fichiers seront copiés.
- *Rename*: identique à la copie, mais y déplacera les fichiers.
- *Save as*: identique à la copie, mais les y écrira.
### Navigation synchronisée ⏲️
Lorsqu'elle est activée, la navigation synchronisée vous permettra de synchroniser la navigation entre les deux panneaux.
Cela signifie que chaque fois que vous changerez de répertoire de travail sur un panneau, la même action sera reproduite sur l'autre panneau. Si vous souhaitez activer la navigation synchronisée, appuyez simplement sur `<Y>` ; appuyez deux fois pour désactiver. Lorsqu'il est activé, l'état de navigation synchronisé sera signalé dans la barre d'état sur `ON`
### Ouvrir et ouvrir avec 🚪
Lors de l'ouverture de fichiers avec la commande Afficher (`<V>`), l'application par défaut du système pour le type de fichier sera utilisée. Pour ce faire, le service du système d'exploitation par défaut sera utilisé, alors assurez-vous d'avoir au moins l'un de ceux-ci installé sur votre système :
- Utilisateurs **Windows** : vous n'avez pas à vous en soucier, puisque la caisse utilisera la commande `start`.
- Utilisateurs **MacOS** : vous n'avez pas à vous inquiéter non plus, puisque le crate utilisera `open`, qui est déjà installé sur votre système.
- Utilisateurs **Linux** : l'un d'eux doit être installé
- *xdg-open*
- *gio*
- *gnome-open*
- *kde-open*
- Utilisateurs **WSL** : *wslview* est requis, vous devez installer [wslu](https://github.com/wslutilities/wslu).
> Q: Puis-je modifier des fichiers distants à l'aide de la commande view ?
> A: Non, du moins pas directement depuis le "panneau distant". Vous devez d'abord le télécharger dans un répertoire local, cela est dû au fait que lorsque vous ouvrez un fichier distant, le fichier est téléchargé dans un répertoire temporaire, mais il n'y a aucun moyen de créer un observateur pour que le fichier vérifie quand le programme que vous utilisé pour l'ouvrir était fermé, donc termscp n'est pas en mesure de savoir quand vous avez fini de modifier le fichier.
---
## Signets ⭐
Dans termscp, il est possible de sauvegarder les hôtes favoris, qui peuvent ensuite être chargés rapidement à partir de la mise en page principale de termscp.
termscp enregistrera également les 16 derniers hôtes auxquels vous vous êtes connecté.
Cette fonctionnalité vous permet de charger tous les paramètres nécessaires pour vous connecter à une certaine télécommande, en sélectionnant simplement le signet dans l'onglet sous le formulaire d'authentification.
Les signets seront enregistrés, si possible à l'adresse :
- `$HOME/.config/termscp/` sous Linux/BSD
- `$HOME/Library/Application Support/termscp` sous MacOs
- `FOLDERID_RoamingAppData\termscp\` sous Windows
Pour les signets uniquement (cela ne s'appliquera pas aux hôtes récents), il est également possible de sauvegarder le mot de passe utilisé pour s'authentifier. Le mot de passe n'est pas enregistré par défaut et doit être spécifié via l'invite lors de l'enregistrement d'un nouveau signet.
Si vous êtes préoccupé par la sécurité du mot de passe enregistré pour vos favoris, veuillez lire le [chapitre ci-dessous 👀](#mes-mots-de-passe-sont-ils-sûrs-).
Pour créer un nouveau signet, suivez simplement ces étapes :
1. Tapez dans le formulaire d'authentification les paramètres pour vous connecter à votre serveur distant
2. Appuyez sur `<CTRL+S>`
3. Tapez le nom que vous souhaitez donner au signet
4. Choisissez de rappeler ou non le mot de passe
5. Appuyez sur `<ENTER>` pour soumettre
chaque fois que vous souhaitez utiliser la connexion précédemment enregistrée, appuyez simplement sur `<TAB>` pour accéder à la liste des signets et chargez les paramètres des signets dans le formulaire en appuyant sur `<ENTER>`.
![Bookmarks](https://github.com/veeso/termscp/blob/main/assets/images/bookmarks.gif?raw=true)
### Mes mots de passe sont-ils sûrs 😈
Bien sûr 😉.
Comme dit précédemment, les signets sont enregistrés dans votre répertoire de configuration avec les mots de passe. Les mots de passe ne sont évidemment pas en texte brut, ils sont cryptés avec **AES-128**. Est-ce que cela les sécurise ? Absolument! (sauf pour les utilisateurs BSD et WSL 😢)
Sous **Windows**, **Linux** et **MacOS**, la clé utilisée pour crypter les mots de passe est stockée, si possible (mais devrait l'être), respectivement dans le *Windows Vault*, dans le *porte-clés système* et dans le *Porte-clés*. Ceci est en fait super sûr et est directement géré par votre système d'exploitation.
❗ Veuillez noter que si vous êtes un utilisateur Linux, vous feriez mieux de lire le [chapitre ci-dessous 👀](#linux-keyring), car le trousseau peut ne pas être activé ou pris en charge sur votre système !
Sur *BSD* et *WSL*, en revanche, la clé utilisée pour crypter vos mots de passe est stockée sur votre disque (dans $HOME/.config/termscp). Il est alors, toujours possible de récupérer la clé pour déchiffrer les mots de passe. Heureusement, l'emplacement de la clé garantit que votre clé ne peut pas être lue par des utilisateurs différents du vôtre, mais oui, je n'enregistrerais toujours pas le mot de passe pour un serveur exposé sur Internet 😉.
#### Linux Keyring
Nous aimons tous Linux grâce à la liberté qu'il donne aux utilisateurs. En tant qu'utilisateur Linux, vous pouvez essentiellement faire tout ce que vous voulez, mais cela présente également des inconvénients, tels que le fait qu'il n'y a souvent pas d'applications standard dans différentes distributions. Et cela implique aussi un porte-clés.
Cela signifie que sous Linux, aucun trousseau de clés n'est peut-être installé sur votre système. Malheureusement, la bibliothèque que nous utilisons pour travailler avec le stockage des clés nécessite un service qui expose `org.freedesktop.secrets` sur D-BUS et le pire est qu'il n'y a que deux services qui l'exposent.
- ❗ Si vous utilisez GNOME comme environnement de bureau (par exemple, les utilisateurs d'ubuntu), ça devrait déjà aller, car le trousseau de clés est déjà fourni par `gnome-keyring` et tout devrait déjà fonctionner.
- ❗ Pour les autres utilisateurs d'environnement de bureau, il existe un programme sympa que vous pouvez utiliser pour obtenir un trousseau de clés qui est [KeepassXC](https://keepassxc.org/), que j'utilise sur mon installation Manjaro (avec KDE) et qui fonctionne bien. Le seul problème est que vous devez le configurer pour qu'il soit utilisé avec termscp (mais c'est assez simple). Pour commencer avec KeepassXC, lisez la suite [ici](#configuration-de-keepassxc-pour-termscp).
- ❗ Et si vous ne souhaitez installer aucun de ces services ? Eh bien, il n'y a pas de problème ! **termscp continuera à fonctionner comme d'habitude**, mais il enregistrera la clé dans un fichier, comme il le fait habituellement pour BSD et WSL.
##### Configuration de KeepassXC pour termscp
Suivez ces étapes afin de configurer keepassXC pour termscp :
1. Installer KeepassXC
2. Allez dans "outils" > "paramètres" dans la barre d'outils
3. Selectioner "Secret service integration" et basculer "Enable KeepassXC freedesktop.org secret service integration"
4. Creer une base de données, si vous n'en avez pas encore : à partir de la barre d'outils "Database" > "New database"
5. De la barre d'outils: "Database" > "Database settings"
6. Selectioner "Secret service integration" et basculer "Expose entries under this group"
7. Sélectionnez le groupe dans la liste où vous souhaitez conserver le secret du termscp. N'oubliez pas que ce groupe peut être utilisé par toute autre application pour stocker des secrets via DBUS.
---
## Configuration ⚙️
termscp prend en charge certains paramètres définis par l'utilisateur, qui peuvent être définis dans la configuration.
Underhood termscp a un fichier TOML et quelques autres répertoires où tous les paramètres seront enregistrés, mais ne vous inquiétez pas, vous ne toucherez à aucun de ces fichiers manuellement, car j'ai rendu possible la configuration complète de termscp à partir de son interface utilisateur.
termscp, comme pour les signets, nécessite juste d'avoir ces chemins accessibles :
- `$HOME/.config/termscp/` sous Linux/BSD
- `$HOME/Library/Application Support/termscp` sous MacOs
- `FOLDERID_RoamingAppData\termscp\` sous Windows
Pour accéder à la configuration, il vous suffit d'appuyer sur `<CTRL+C>` depuis l'accueil de termscp.
Ces paramètres peuvent être modifiés :
- **Text Editor**: l'éditeur de texte à utiliser. Par défaut, termscp trouvera l'éditeur par défaut pour vous ; avec cette option, vous pouvez forcer l'utilisation d'un éditeur (par exemple `vim`). **Les éditeurs d'interface graphique sont également pris en charge**, à moins qu'ils ne soient `nohup` à partir du processus parent.
- **Default Protocol**: le protocole par défaut est la valeur par défaut du protocole de transfert de fichiers à utiliser dans termscp. Cela s'applique à la page de connexion et à l'argument de l'adresse CLI.
- **Show Hidden Files**: sélectionnez si les fichiers cachés doivent être affichés par défaut. Vous pourrez décider d'afficher ou non les fichiers cachés au moment de l'exécution en appuyant sur `A` de toute façon.
- **Check for updates**: s'il est défini sur `yes`, Termscp récupère l'API Github pour vérifier si une nouvelle version de Termscp est disponible.
- **Prompt when replacing existing files?**: S'il est défini sur `yes`, Termscp vous demandera une confirmation chaque fois qu'un transfert de fichier entraînera le remplacement d'un fichier existant sur l'hôte cible.
- **Group Dirs**: sélectionnez si les répertoires doivent être regroupés ou non dans les explorateurs de fichiers. Si `Display first` est sélectionné, les répertoires seront triés en utilisant la méthode configurée mais affichés avant les fichiers, vice-versa si `Display last` est sélectionné.
- **Remote File formatter syntax**: syntaxe pour afficher les informations de fichier pour chaque fichier dans l'explorateur distant. Voir [File explorer format](#format-de-lexplorateur-de-fichiers)
- **Local File formatter syntax**: syntaxe pour afficher les informations de fichier pour chaque fichier dans l'explorateur local. Voir [File explorer format](#format-de-lexplorateur-de-fichiers)
- **Enable notifications?**: S'il est défini sur `Yes`, les notifications seront affichées.
- **Notifications: minimum transfer size**: si la taille du transfert est supérieure ou égale à la valeur spécifiée, les notifications de transfert seront affichées. Les valeurs acceptées sont au format `{UNSIGNED} B/KB/MB/GB/TB/PB`
- **SSH configuration path** : définissez le fichier de configuration SSH à utiliser lors de la connexion à un serveur SCP/SFTP. S'il n'est pas défini (vide), aucun fichier ne sera utilisé. Vous pouvez spécifier un chemin commençant par `~` pour indiquer le chemin d'accueil (par exemple `~/.ssh/config`)
### SSH Key Storage 🔐
n plus de la configuration, termscp fournit également une fonctionnalité **essentielle** pour les **clients SFTP/SCP** : le stockage de clés SSH.
Vous pouvez accéder au stockage des clés SSH, de la configuration à l'onglet « Clés SSH », une fois là-bas, vous pouvez :
- **Ajouter une neuf clé SSH**: appuyez simplement sur `<CTRL+N>` et vous serez invité à créer une nouvelle clé. Fournissez le nom d'hôte/l'adresse IP et le nom d'utilisateur associé à la clé et enfin un éditeur de texte s'ouvrira : collez la clé ssh **PRIVÉE** dans l'éditeur de texte, enregistrez et quittez.
- **Supprimer une clé existante**: appuyez simplement sur `<DEL>` ou `<CTRL+E>` sur la clé que vous souhaitez supprimer, pour supprimer de manière persistante la clé de termscp.
- **Modifier une clé existante**: appuyez simplement sur `<ENTER>` sur la clé que vous souhaitez modifier, pour changer la clé privée.
> Q: Ma clé privée est protégée par mot de passe, puis-je l'utiliser ?
> A: Bien sûr vous pouvez. Le mot de passe fourni pour l'authentification dans termscp est valide à la fois pour l'authentification par nom d'utilisateur/mot de passe et pour l'authentification par clé RSA.
### Format de l'explorateur de fichiers
Il est possible via la configuration de définir un format personnalisé pour l'explorateur de fichiers. Ceci est possible à la fois pour l'hôte local et distant, vous pouvez donc utiliser deux syntaxes différentes. Ces champs, nommés `File formatter syntax (local)` et `File formatter syntax (remote)` définiront comment les entrées de fichier seront affichées dans l'explorateur de fichiers.
La syntaxe du formateur est la suivante `{KEY1}... {KEY2:LENGTH}... {KEY3:LENGTH:EXTRA} {KEYn}...`.
Chaque clé entre crochets sera remplacée par l'attribut associé, tandis que tout ce qui se trouve en dehors des crochets restera inchangé.
- Le nom de la clé est obligatoire et doit être l'une des clés ci-dessous
- La longueur décrit la longueur réservée pour afficher le champ. Les attributs statiques ne prennent pas en charge cela (GROUP, PEX, SIZE, USER)
- Extra n'est pris en charge que par certains paramètres et constitue une option supplémentaire. Voir les touches pour vérifier si les extras sont pris en charge.
Voici les clés prises en charge par le formateur :
- `ATIME`: Heure du dernier accès (avec la syntaxe par défaut `%b %d %Y %H:%M`) ; Un supplément peut être fourni comme syntaxe de l'heure (par exemple, `{ATIME:8:%H:%M}`)
- `CTIME`: Heure de création (avec la syntaxe `%b %d %Y %H:%M`); Un supplément peut être fourni comme syntaxe de l'heure (par exemple, `{CTIME:8:%H:%M}`)
- `GROUP`: Groupe de propriétaires
- `MTIME`: Heure du dernier changement (avec la syntaxe `%b %d %Y %H:%M`); Un supplément peut être fourni comme syntaxe de l'heure (par exemple, `{MTIME:8:%H:%M}`)
- `NAME`: Nom du fichier (élidé si plus long que LENGTH)
- `PATH`: Chemin absolu du fichier (les dossiers entre la racine et les premiers ancêtres sont éludés s'ils sont plus longs que LENGTH)
- `PEX`: Autorisations de fichiers (format UNIX)
- `SIZE`: Taille du fichier (omis pour les répertoires)
- `SYMLINK`: Lien symbolique (le cas échéant `-> {FILE_PATH}`)
- `USER`: Utilisateur propriétaire
Si elle est laissée vide, la syntaxe par défaut du formateur sera utilisée : `{NAME:24} {PEX} {USER} {SIZE} {MTIME:17:%b %d %Y %H:%M}`
---
## Thèmes 🎨
Termscp vous offre une fonctionnalité géniale : la possibilité de définir les couleurs de plusieurs composants de l'application.
Si vous souhaitez personnaliser termscp, il existe deux manières de le faire :
- Depuis le **menu de configuration**
- Importation d'un **fichier de thème**
Afin de créer votre propre personnalisation à partir de termscp, il vous suffit de saisir la configuration à partir de l'activité d'authentification, en appuyant sur `<CTRL+C>` puis sur `<TAB>` deux fois. Vous devriez être maintenant passé au panneau `thèmes`.
Ici, vous pouvez vous déplacer avec `<UP>` et `<DOWN>` pour changer le style que vous souhaitez modifier, comme indiqué dans le gif ci-dessous :
![Themes](https://github.com/veeso/termscp/blob/main/assets/images/themes.gif?raw=true)
termscp prend en charge à la fois la syntaxe hexadécimale explicite traditionnelle (`#rrggbb`) et rgb `rgb(r, g, b)` pour fournir des couleurs, mais aussi **[couleurs css](https://www.w3schools.com/cssref/css_colors.asp)** (comme `crimson`) sont acceptés 😉. Il y a aussi un keywork spécial qui est `Default`. Par défaut signifie que la couleur utilisée sera la couleur de premier plan ou d'arrière-plan par défaut en fonction de la situation (premier plan pour les textes et les lignes, arrière-plan pour bien, devinez quoi)
Comme dit précédemment, vous pouvez également importer des fichiers de thème. Vous pouvez vous inspirer de ou utiliser directement l'un des thèmes fournis avec termscp, situé dans le répertoire `themes/` de ce référentiel et les importer en exécutant termscp en tant que `termscp -t <theme_file>`. Si tout allait bien, cela devrait vous dire que le thème a été importé avec succès.
### Mon thème ne se charge pas 😱
Cela est probablement dû à une mise à jour récente qui a cassé le thème. Chaque fois que j'ajoute une nouvelle clé aux thèmes, le thème enregistré ne se charge pas. Pour résoudre ces problèmes, il existe deux solutions vraiment rapides :
1. Recharger le thème : chaque fois que je publie une mise à jour, je corrige également les thèmes "officiels", il vous suffit donc de le télécharger à nouveau depuis le référentiel et de réimporter le thème via l'option `-t`
```sh
termscp -t <theme.toml>
```
2. Corrigez votre thème : si vous utilisez un thème personnalisé, vous pouvez le modifier via `vim` et ajouter la clé manquante. Le thème est situé dans `$CONFIG_DIR/termscp/theme.toml` où `$CONFIG_DIR` est :
- FreeBSD/GNU-Linux: `$HOME/.config/`
- MacOs: `$HOME/Library/Application Support`
- Windows: `%appdata%`
❗ Les clés manquantes sont signalées dans le CHANGELOG sous `BREAKING CHANGES` pour la version que vous venez d'installer.
### Modes 💈
Vous pouvez trouver dans le tableau ci-dessous, la description de chaque champ de style.
Veuillez noter que **les styles ne s'appliqueront pas à la page de configuration**, afin de la rendre toujours accessible au cas où vous gâcheriez tout
#### Authentication page
| Key | Description |
|----------------|------------------------------------------|
| auth_address | Couleur du champ pour adresse IP |
| auth_bookmarks | Couleur du panneau des signets |
| auth_password | Couleur du champ pour mot de passe |
| auth_port | Couleur du champ pour nombre de port |
| auth_protocol | Couleur du groupe radio pour protocole |
| auth_recents | Couleur du panneau récent |
| auth_username | Couleur du champ pour nom d'utilisateur |
#### Transfer page
| Key | Description |
|--------------------------------------|---------------------------------------------------------------------------|
| transfer_local_explorer_background | Couleur d'arrière-plan de l'explorateur localhost |
| transfer_local_explorer_foreground | Couleur de premier plan de l'explorateur localhost |
| transfer_local_explorer_highlighted | Bordure et couleur surlignée pour l'explorateur localhost |
| transfer_remote_explorer_background | Couleur d'arrière-plan de l'explorateur distant |
| transfer_remote_explorer_foreground | Couleur de premier plan de l'explorateur distant |
| transfer_remote_explorer_highlighted | Bordure et couleur en surbrillance pour l'explorateur distant |
| transfer_log_background | Couleur d'arrière-plan du panneau de journal |
| transfer_log_window | Couleur de la fenêtre du panneau de journal |
| transfer_progress_bar_partial | Couleur de la barre de progression partielle |
| transfer_progress_bar_total | Couleur de la barre de progression totale |
| transfer_status_hidden | Couleur de l'étiquette "hidden" de la barre d'état |
| transfer_status_sorting | Couleur de l'étiquette "sorting" de la barre d'état |
| transfer_status_sync_browsing | Couleur de l'étiquette "sync browsing" de la barre d'état |
#### Misc
These styles applie to different part of the application.
| Key | Description |
|-------------------|---------------------------------------------|
| misc_error_dialog | Couleur des messages d'erreur |
| misc_info_dialog | Couleur des messages d'info |
| misc_input_dialog | Couleur des messages de input |
| misc_keys | Couleur du texte pour les frappes de touches|
| misc_quit_dialog | Couleur des messages de quit |
| misc_save_dialog | Couleur des messages d'enregistrement |
| misc_warn_dialog | Couleur des messages de attention |
---
## Éditeur de texte ✏
termscp a, comme vous l'avez peut-être remarqué, de nombreuses fonctionnalités, l'une d'entre elles est la possibilité de visualiser et de modifier un fichier texte. Peu importe que le fichier se trouve sur l'hôte local ou sur l'hôte distant, termscp offre la possibilité d'ouvrir un fichier dans votre éditeur de texte préféré.
Si le fichier se trouve sur l'hôte distant, le fichier sera d'abord téléchargé dans votre répertoire de fichiers temporaires, puis **uniquement** si des modifications ont été apportées au fichier, rechargé sur l'hôte distant. termscp vérifie si vous avez apporté des modifications au fichier en vérifiant l'heure de la dernière modification du fichier.
> ❗ Juste un rappel : **vous ne pouvez éditer que des fichiers texte** ; les fichiers binaires ne sont pas pris en charge.
---
## Fichier Journal 🩺
termscp écrit un fichier journal pour chaque session, qui est écrit à
- `$HOME/.config/termscp/termscp.log` sous Linux/BSD
- `$HOME/Library/Application Support/termscp/termscp.log` sous MacOs
- `FOLDERID_RoamingAppData\termscp\termscp.log` sous Windows
le journal ne sera pas tourné, mais sera simplement tronqué après chaque lancement de termscp, donc si vous souhaitez signaler un problème et que vous souhaitez joindre votre fichier journal, n'oubliez pas de sauvegarder le fichier journal dans un endroit sûr avant de l'utiliser termescp à nouveau.
La journalisation par défaut se rapporte au niveau *INFO*, elle n'est donc pas très détaillée.
Si vous souhaitez soumettre un problème, veuillez, si vous le pouvez, reproduire le problème avec le niveau défini sur `TRACE`, pour ce faire, lancez termscp avec
l'option CLI `-D`.
Je sais que vous pourriez avoir des questions concernant les fichiers journaux, alors j'ai fait une sorte de Q/R :
> Je ne veux pas me connecter, puis-je le désactiver ?
Oui, vous pouvez. Démarrez simplement termscp avec l'option `-q ou --quiet`. Vous pouvez créer un alias termcp pour le rendre persistant. N'oubliez pas que la journalisation est utilisée pour diagnostiquer les problèmes, donc puisque derrière chaque projet open source, il devrait toujours y avoir ce genre d'aide mutuelle, la conservation des fichiers journaux peut être votre moyen de soutenir le projet 😉. Je ne veux pas que tu te sentes coupable, mais juste pour dire.
> La journalisation est-elle sûre ?
Si vous êtes préoccupé par la sécurité, le fichier journal ne contient aucun mot de passe simple, alors ne vous inquiétez pas et expose les mêmes informations que le fichier frère "signets".
## Notifications 📫
Termscp enverra des notifications de bureau pour ce type d'événements :
- sur **Transfert terminé** : La notification sera envoyée une fois le transfert terminé avec succès.
- ❗ La notification ne s'affichera que si la taille totale du transfert est au moins la `Notifications: minimum transfer size` spécifiée dans la configuration.
- sur **Transfert échoué** : La notification sera envoyée une fois qu'un transfert a échoué en raison d'une erreur.
- ❗ La notification ne s'affichera que si la taille totale du transfert est au moins la `Notifications: minimum transfer size` spécifiée dans la configuration.
- sur **Mise à jour disponible** : chaque fois qu'une nouvelle version de Termscp est disponible, une notification s'affiche.
- sur **Mise à jour installée** : chaque fois qu'une nouvelle version de Termscp est installée, une notification s'affiche.
- sur **Échec de la mise à jour** : chaque fois que l'installation de la mise à jour échoue, une notification s'affiche.
❗ Si vous préférez désactiver les notifications, vous pouvez simplement accéder à la configuration et définir `Enable notifications?` sur `No` 😉.
❗ Si vous souhaitez modifier la taille de transfert minimale pour afficher les notifications, vous pouvez modifier la valeur dans la configuration avec la touche `Notifications: minimum transfer size` et la définir sur ce qui vous convient le mieux 🙂.
## Observateur de fichiers 🔭
L'observateur de fichiers vous permet de configurer une liste de chemins à synchroniser avec les hôtes distants.
Cela signifie que chaque fois qu'un changement sur le système de fichiers local sera détecté sur le chemin synchronisé, le changement sera automatiquement signalé au chemin de l'hôte distant configuré, dans les 5 secondes.
Vous pouvez définir autant de chemins à synchroniser que vous préférez :
1. Placez le curseur de l'explorateur local sur le répertoire/fichier que vous souhaitez conserver synchronisé
2. Accédez au répertoire dans lequel vous souhaitez que les modifications soient signalées sur l'hôte distant
3. Appuyez sur `<T>`
4. Répondez `<YES>` à la fenêtre contextuelle de la radio
Pour annuler la surveillance, appuyez simplement sur `<T>` sur le chemin synchronisé local (ou sur l'un de ses sous-dossiers)
OU vous pouvez simplement appuyer sur `<CTRL + T>` et appuyer sur `<ENTER>` jusqu'au chemin synchronisé que vous souhaitez désactiver.
Ces modifications seront signalées à l'hôte distant :
- Nouveaux fichiers, modifications de fichiers
- Fichier déplacé / renommé
- Fichier supprimé / dissocié
> ❗ Le watcher ne fonctionne que dans un sens (local > distant). Il n'est PAS possible de synchroniser automatiquement les changements de distant à local.

288
docs/it/README.md Normal file
View File

@@ -0,0 +1,288 @@
# termscp
<p align="center">
<img src="/assets/images/termscp.svg" width="256" height="256" />
</p>
<p align="center">~ Un file transfer ricco di funzionalità ~</p>
<p align="center">
<a href="https://veeso.github.io/termscp/" target="_blank">Sito</a>
·
<a href="https://veeso.github.io/termscp/#get-started" target="_blank">Installazione</a>
·
<a href="https://veeso.github.io/termscp/#user-manual" target="_blank">Manuale utente</a>
</p>
<p align="center">
<a href="https://github.com/veeso/termscp"
><img
height="20"
src="/assets/images/flags/us.png"
alt="English"
/></a>
&nbsp;
<a
href="https://github.com/veeso/termscp/blob/main/docs/de/README.md"
><img
height="20"
src="/assets/images/flags/de.png"
alt="Deutsch"
/></a>
&nbsp;
<a
href="https://github.com/veeso/termscp/blob/main/docs/es/README.md"
><img
height="20"
src="/assets/images/flags/es.png"
alt="Español"
/></a>
&nbsp;
<a
href="https://github.com/veeso/termscp/blob/main/docs/fr/README.md"
><img
height="20"
src="/assets/images/flags/fr.png"
alt="Français"
/></a>
&nbsp;
<a
href="https://github.com/veeso/termscp/blob/main/docs/it/README.md"
><img
height="20"
src="/assets/images/flags/it.png"
alt="Italiano"
/></a>
&nbsp;
<a
href="https://github.com/veeso/termscp/blob/main/docs/zh-CN/README.md"
><img
height="20"
src="/assets/images/flags/cn.png"
alt="简体中文"
/></a>
</p>
<p align="center">Sviluppato da <a href="https://veeso.github.io/" target="_blank">@veeso</a></p>
<p align="center">Versione corrente: 0.9.0 (18/06/2022)</p>
<p align="center">
<a href="https://opensource.org/licenses/MIT"
><img
src="https://img.shields.io/badge/License-MIT-teal.svg"
alt="License-MIT"
/></a>
<a href="https://github.com/veeso/termscp/stargazers"
><img
src="https://img.shields.io/github/stars/veeso/termscp.svg"
alt="Repo stars"
/></a>
<a href="https://crates.io/crates/termscp"
><img
src="https://img.shields.io/crates/d/termscp.svg"
alt="Downloads counter"
/></a>
<a href="https://crates.io/crates/termscp"
><img
src="https://img.shields.io/crates/v/termscp.svg"
alt="Latest version"
/></a>
<a href="https://ko-fi.com/veeso">
<img
src="https://img.shields.io/badge/donate-ko--fi-red"
alt="Ko-fi"
/></a>
</p>
<p align="center">
<a href="https://github.com/veeso/termscp/actions"
><img
src="https://github.com/veeso/termscp/workflows/Linux/badge.svg"
alt="Linux CI"
/></a>
<a href="https://github.com/veeso/termscp/actions"
><img
src="https://github.com/veeso/termscp/workflows/MacOS/badge.svg"
alt="MacOS CI"
/></a>
<a href="https://github.com/veeso/termscp/actions"
><img
src="https://github.com/veeso/termscp/workflows/Windows/badge.svg"
alt="Windows CI"
/></a>
<a href="https://github.com/veeso/termscp/actions"
><img
src="https://github.com/veeso/termscp/workflows/FreeBSD/badge.svg"
alt="FreeBSD CI"
/></a>
<a href="https://coveralls.io/github/veeso/termscp"
><img
src="https://coveralls.io/repos/github/veeso/termscp/badge.svg"
alt="Coveralls"
/></a>
</p>
---
## Riguardo a termscp 🖥
Termscp è un file transfer ed explorer ricco di funzionalità, con supporto a SCP/SFTP/FTP/S3. In pratica è un utility su terminale con una terminal user-interface per connettersi a server remoti per scambiare file ed interagire con il file system sia locale che remoto. È compatibile con **Linux**, **MacOS**, **FreeBSD** e **Windows**.
![Explorer](/assets/images/explorer.gif)
---
## Funzionalità 🎁
- 📁 Diversi protocolli di comunicazione
- **SFTP**
- **SCP**
- **FTP** and **FTPS**
- **S3**
- 🖥 Esplora e opera sia sul file system locale che su quello remoto con una UI di facile utilizzo.
- Crea, rimuove, rinomina, cerca, visualizza e modifica file
- ⭐ Connettiti ai tuoi host preferiti tramite la funzionalità integrata dei segnalibri e delle connessioni recenti.
- 📝 Visualizza e modifica i file tramite le tue applicazioni preferite.
- 💁 Autenticazione su server SFTP/SCP tramite chiavi SSH e/o username/password
- 🐧 Compatibile con Windows, Linux, FreeBSD e MacOS
- 🎨 Customizzalo!
- Temi
- Formattazione dell'explorer
- Impostazione del text editor predefinito
- Imposta l'ordinamento di file e cartelle
- e tanto altro...
- 📫 Ricevi notifiche desktop quando un file di cospicue dimensioni è stato trasferito
- 🔭 Mantieni sincronizzate le modifiche con l'host remoto
- 🔐 Salva le password degli host remoti nel keyring predefinito dal tuo sistema operativo
- 🦀 Rust-powered
- 👀 Progettato tenendo conto delle performance
- 🦄 Aggiornamenti frequenti con nuove funzionalità
---
## Per iniziare 🚀
Intanto se stai considerando di installare termscp, ti voglio ringraziare 💜 e spero che termscp ti piacerà!
Se vuoi contribuire al progetto, non dimenticarti di leggere la [contribute guide](../../CONTRIBUTING.md).
Se sei un utente che utilizza Linux, FreeBSD o MacOS, questo shell script installerà termscp sul tuo sistema con un comando secco:
```sh
curl --proto '=https' --tlsv1.2 -sSLf "https://git.io/JBhDb" | sh
```
mentre se sei un utente Windows, puoi installare termscp con [Chocolatey](https://chocolatey.org/):
```sh
choco install termscp
```
Per ulteriori informazioni sui metodi di installazione su altre piattaforme, visita [veeso.github.io](https://veeso.github.io/termscp/#get-started).
⚠️ Se stavi cercando come aggiornare la tua versione di termscp, puoi semplicemente lanciare termscp con questi argomenti: `(sudo) termscp --update` ⚠️
### Requisiti ❗
- Utenti **Linux**:
- libssh
- libdbus-1
- pkg-config
- Utenti **FreeBSD**:
- libssh
- dbus
- pkgconf
### Requisiti opzionali ✔️
Questi requisiti non sono per forza necessari, ma lo sono per sfruttare tutte le sue funzionalità:
- Utenti **Linux/FreeBSD**:
- Per **aprire** i file con `V` (almeno uno di questi)
- *xdg-open*
- *gio*
- *gnome-open*
- *kde-open*
- Utenti **Linux**:
- Un keyring manager: Approfondisci nel [Manuale](man.md#linux-keyring)
- Utenti **WSL**
- Per **aprire** i file con `V` (almeno uno di questi)
- [wslu](https://github.com/wslutilities/wslu)
---
## Supporta lo sviluppatore ☕
Se ti piace termscp e ti piacerebbe vedere il progetto crescere e migliorare, considera una piccola donazione 🥳.
Puoi fare una donazione tramite una di queste piattaforme:
[![ko-fi](https://img.shields.io/badge/Ko--fi-F16061?style=for-the-badge&logo=ko-fi&logoColor=white)](https://ko-fi.com/veeso)
[![PayPal](https://img.shields.io/badge/PayPal-00457C?style=for-the-badge&logo=paypal&logoColor=white)](https://www.paypal.me/chrisintin)
---
## Manuale utente 📚
Il manuale utente lo puoi trovare sul [sito di termscp](https://veeso.github.io/termscp/#user-manual) o su [Github](man.md).
---
## Contributi e issues 🤝🏻
Contributi, report di bug, nuove funzionalità e domande sono i benvenuti! 😉
Se hai qualche domanda o dubbio o vuoi suggerire una nuova funzionalità, sentiti libero di aprire un issue o una PR.
Per favore segui le nostre [contributing guidelines](../../CONTRIBUTING.md)
---
## Changelog ⏳
Visualizza [Qui](../../CHANGELOG.md) il changelog
---
## Un grazie a questi progetti 💪
se termscp esiste, è anche grazie a questi fantastici progetti:
- [bytesize](https://github.com/hyunsik/bytesize)
- [crossterm](https://github.com/crossterm-rs/crossterm)
- [edit](https://github.com/milkey-mouse/edit)
- [keyring-rs](https://github.com/hwchen/keyring-rs)
- [open-rs](https://github.com/Byron/open-rs)
- [rpassword](https://github.com/conradkleinespel/rpassword)
- [rust-s3](https://github.com/durch/rust-s3)
- [self_update](https://github.com/jaemk/self_update)
- [ssh2-rs](https://github.com/alexcrichton/ssh2-rs)
- [suppaftp](https://github.com/veeso/suppaftp)
- [tui-rs](https://github.com/fdehau/tui-rs)
- [tui-realm](https://github.com/veeso/tui-realm)
- [whoami](https://github.com/libcala/whoami)
- [wildmatch](https://github.com/becheran/wildmatch)
---
## Galleria 🎬
> Termscp Home
![Auth](/assets/images/auth.gif)
> Bookmarks
![Bookmarks](/assets/images/bookmarks.gif)
> Configurazione
![Setup](/assets/images/config.gif)
> Text editor
![TextEditor](/assets/images/text-editor.gif)
---
## Licenza 📃
termscp è fornito sotto licenza MIT.
Puoi leggere l'intero documento di licenza [Qui](../../LICENSE)

536
docs/it/man.md Normal file
View File

@@ -0,0 +1,536 @@
# Manuale utente 🎓
- [Manuale utente 🎓](#manuale-utente-)
- [Argomenti da linea di comando ❓](#argomenti-da-linea-di-comando-)
- [Argomento indirizzo 🌎](#argomento-indirizzo-)
- [Argomento indirizzo per AWS S3](#argomento-indirizzo-per-aws-s3)
- [Come fornire la password 🔐](#come-fornire-la-password-)
- [Parametri di connessione S3](#parametri-di-connessione-s3)
- [Credenziali S3 🦊](#credenziali-s3-)
- [File explorer 📂](#file-explorer-)
- [Abbinamento tasti ⌨](#abbinamento-tasti-)
- [Lavora su più file 🥷](#lavora-su-più-file-)
- [Synchronized browsing ⏲️](#synchronized-browsing-)
- [Apri e apri con 🚪](#apri-e-apri-con-)
- [Segnalibri ⭐](#segnalibri-)
- [Le mie password sono al sicuro 😈](#le-mie-password-sono-al-sicuro-)
- [Linux Keyring](#linux-keyring)
- [KeepassXC setup per termscp](#keepassxc-setup-per-termscp)
- [Configurazione ⚙️](#configurazione-)
- [SSH Key Storage 🔐](#ssh-key-storage-)
- [File Explorer Format](#file-explorer-format)
- [Temi 🎨](#temi-)
- [Il tema non carica 😱](#il-tema-non-carica-)
- [Stili 💈](#stili-)
- [Pagina autenticazione](#pagina-autenticazione)
- [Pagina explorer e trasferimento](#pagina-explorer-e-trasferimento)
- [Misc](#misc)
- [Editor di testo ✏](#editor-di-testo-)
- [Logging 🩺](#logging-)
- [Notifiche 📫](#notifiche-)
- [File watcher 🔭](#file-watcher-)
## Argomenti da linea di comando ❓
termscp può essere lanciato con questi argomenti:
`termscp [options]... [protocol://user@address:port:wrkdir] [local-wrkdir]`
O
`termscp [options]... -b [bookmark-name] [local-wrkdir]`
- `-P, --password <password>` Se viene fornito l'argomento indirizzo, questa sarà la password utilizzata per autenticarsi
- `-b, --address-as-bookmark` risolve l'argomento indirizzo come nome di un segnalibro
- `-c, --config` Apri la configurazione di termscp
- `-q, --quiet` Disabilita i log
- `-t, --theme <path>` Importa il tema al percorso fornito
- `-u, --update` Aggiorna termscp all'ultima versione
- `-v, --version` Mostra a video le informazioni sulla versione attualmente installata
- `-h, --help` Mostra la pagina di aiuto.
termscp può venire lanciato in due modalità diverse. Se nessun argomento posizionale viene fornito, termscp mostrerà il form di autenticazione, dove l'utente potrà fornire i parametri di connessione necessari.
Alternativamente, l'utente può fornire l'argomento posizionale "indirizzo" per connettersi direttamente all'host fornito.
Se viene fornito anche il secondo argomento posizionale, ovvero la directory locale, termscp avvierà l'explorer locale sul percorso fornito.
### Argomento indirizzo 🌎
L'argomento indirizzo ha la sintassi seguente:
```txt
[protocollo://][username@]<indirizzo>[:porta][:wrkdir]
```
Vediamo qualche esempio per questa sintassi, dal momento che risulta molto comodo connettersi tramite questa modalità:
- Connessione utilizzando il protocollo di default (definito in configurazione) a 192.168.1.31, la porta sarà quella di default per il protocollo di default. Il nome utente è quello attualmente attivo sulla propria macchina:
```sh
termscp 192.168.1.31
```
- Connessione con protocollo di default a 192.168.1.31, utente è `root`:
```sh
termscp root@192.168.1.31
```
- Connessione usando `scp`, la porta è 4022, l'utente è `omar`:
```sh
termscp scp://omar@192.168.1.31:4022
```
- Connessione via `scp`, porta 4022, utente `omar`, l'explorer si avvierà in `/tmp`:
```sh
termscp scp://omar@192.168.1.31:4022:/tmp
```
#### Argomento indirizzo per AWS S3
Aws S3 ha una sintassi differente dal classico argomento indirizzo, per ovvie ragioni, in quanto S3 non ha la porta o l'host o l'utente. Ho deciso però di mantenere una sintassi il più simile possibile a quella "tradizionale":
```txt
s3://<bucket-name>@<region>[:profile][:/wrkdir]
```
e.g.
```txt
s3://buckethead@eu-central-1:default:/assets
```
#### Come fornire la password 🔐
Quando si usa l'argomento indirizzo non è possibile fornire la password direttamente nell'argomento, esistono però altri metodi per farlo:
- Argomento `-P, --password <password>`: Passa direttamente la password nell'argomento. Non lo consiglio particolarmente questo metodo, in quanto la password rimarrebbe nella history della shell in chiaro.
- Tramite `sshpass`: puoi fornire la password tramite l'applicazione GNU/Linux sshpass `sshpass -f ~/.ssh/topsecret.key termscp cvisintin@192.168.1.31`
- Forniscila quando richiesta: se non la fornisci tramite nessun metodo precedente, alla connessione ti verrà richiesto di fornirla in un prompt che la oscurerà (come avviene con sudo tipo).
---
## Parametri di connessione S3
Questi parametri sono necessari per connettersi ad un bucket Aws s3 o ad uno storage compatibile:
- AWS S3:
- **bucket name**
- **region**
- *profile* (se non fornito: "default")
- *access key* (a meno che non sia pubblico)
- *secret access key* (a meno che non sia pubblico)
- *security token* (se necessario)
- *session token* (se necessario)
- new path style: **NO**
- Other S3 endpoints:
- **bucket name**
- **endpoint**
- *access key* (a meno che non sia pubblico)
- *secret access key* (a meno che non sia pubblico)
- new path style: **YES**
### Credenziali S3 🦊
Per connettersi ad un bucket S3 devi come già saprai fornire le credenziali fornite da AWS.
Ci sono tre modi per passare queste credenziali a termscp.
Questi sono quindi i tre modi per passare le chiavi:
1. Form di autenticazione:
1. Puoi fornire la `access_key` (dovrebbe essere obbligatoria), la `secret_access_key` (dovrebbe essere obbligatoria), il `security_token` ed il `session_token`
2. Se salvi la connessione s3 come segnalibro e decidi di salvare la password, questi parametri verranno salvati nel file dei segnalibri criptati con AES-256/BASE64; ad eccezion fatta per i due token, che dovrebbero essere credenziali temporanee, quindi inutili da salvare.
2. Utilizza il file delle credenziali s3: configurando aws via `aws configure` le tue credenziali dovrebbero già venir salvate in `~/.aws/credentials`. Nel caso tu debba usare un profile diverso da `default`, puoi fornire un profilo diverso nell'authentication form.
3. **Variabili d'ambiente**: nel caso il primo metodo non sia utilizzabile, puoi comunque fornirle come variabili d'ambiente. Considera però che queste variabili sovrascriveranno sempre le credenziali situate nel file credentials. Vediamo come impostarle:
Queste sono sempre obbligatorie:
- `AWS_ACCESS_KEY_ID`: aws access key ID (di solito inizia per `AKIA...`)
- `AWS_SECRET_ACCESS_KEY`: la secret access key
nel caso tu abbia impostato un maggiore livello di sicurezza, potrebbero servirti anche queste:
- `AWS_SECURITY_TOKEN`: security token
- `AWS_SESSION_TOKEN`: session token
⚠️ le tue credenziali sono al sicuro: termscp non manipola direttamente questi dati! Le credenziali sono direttamente lette dal crate di **s3**. Nel caso tu abbia dei dubbi sulla sicurezza, puoi contattare l'autore della libreria su [Github](https://github.com/durch/rust-s3) ⚠️
---
## File explorer 📂
Quando ci riferiamo al file explorer in termscp, intendiamo i pannelli che puoi vedere quando stabilisci una connessione con il server remoto.
Questi pannelli sono 3 (e non 2 come sembra):
- Pannello locale: viene visualizzato sulla sinistra del tuo schermo e mostra la cartella sul file system locale.
- Pannello remoto: viene visualizzato sulla destra del tuo schermo e mostra la cartella sul file system remoto.
- Pannello di ricerca: viene visualizzato a destra o a sinistra in base a dove stai cercando dei file. Questo pannello mostra i file che matchano al pattern cercato sull'host.
Per cambiare pannello ti puoi muovere con le frecce, `<LEFT>` per andare sul pannello locale e `<RIGHT>` per andare su quello remoto. Attenzione che quando è attivo il pannello ricerca non puoi spostarti sugli altri pannelli e devi prima chiuderlo con `<ESC>`.
### Abbinamento tasti ⌨
| Key | Command | Reminder |
|---------------|-------------------------------------------------------|-------------|
| `<ESC>` | Disconnettiti; chiudi popup | |
| `<BACKSPACE>` | Vai alla directory precedente | |
| `<TAB>` | Cambia pannello remoto | |
| `<RIGHT>` | Vai al pannello remoto | |
| `<LEFT>` | Vai al pannello locale | |
| `<UP>` | Muovi il cursore verso l'alto | |
| `<DOWN>` | Muovi il cursore verso il basso | |
| `<PGUP>` | Muovi il cursore verso l'alto di 8 | |
| `<PGDOWN>` | Muovi il cursore verso il basso di 8 | |
| `<ENTER>` | Entra nella directory | |
| `<SPACE>` | Upload / download file selezionato/i | |
| `<BACKTAB>` | Cambia tra explorer e pannello di log | |
| `<A>` | Mostra/nascondi file nascosti | All |
| `<B>` | Ordina file per | Bubblesort? |
| `<C|F5>` | Copia file/directory | Copy |
| `<D|F7>` | Crea directory | Directory |
| `<E|F8|DEL>` | Elimina file | Erase |
| `<F>` | Cerca file (wild match supportato) | Find |
| `<G>` | Vai al percorso indicato | Go to |
| `<H|F1>` | Mostra help | Help |
| `<I>` | Mostra informazioni per il file selezionato | Info |
| `<K>` | Crea un link simbolico che punta al file selezionato | symlinK |
| `<L>` | Ricarica posizione corrente / pulisci selezione file | List |
| `<M>` | Seleziona file | Mark |
| `<N>` | Crea nuovo file con il nome fornito | New |
| `<O|F4>` | Modifica file; Vedi text editor | Open |
| `<Q|F10>` | Termina termscp | Quit |
| `<R|F6>` | Rinomina file | Rename |
| `<S|F2>` | Salva file con nome | Save |
| `<T>` | Sincronizza il percorso locale con l'host remoto | Track |
| `<U>` | Vai alla directory padre | Upper |
| `<V|F3>` | Apri il file con il programma definito dal sistema | View |
| `<W>` | Apri il file con il programma specificato | With |
| `<X>` | Esegui comando shell | eXecute |
| `<Y>` | Abilita/disabilita Sync-Browsing | sYnc |
| `<CTRL+A>` | Seleziona tutti i file | |
| `<CTRL+C>` | Annulla trasferimento file | |
| `<CTRL+T>` | Visualizza tutti i percorsi sincronizzati | Track |
### Lavora su più file 🥷
Puoi lavorare su una selezione di file, marcandoli come selezionati tramite `<M>`, per selezionare il file corrente o con `<CTRL+A` per selezionarli tutti.
Una volta che un file è marcato, sarà visualizzato con un `*` prima del nome.
Quando lavori con una selezioni, solo i file selezionati saranno presi in considerazione (l'eventuale file evidenziato sarà ignorato).
È possibile operare su più file anche nel pannello di ricerca.
Tutte le azioni sono disponibili quando si lavora sulle selezioni, ma occhio, che alcune azioni si comporteranno in maniera leggermente differente. Vediamo quali e come:
- *Copia*: Se copi un file, ti verrà richiesto di inserire il nome delle destinazione, ma quando lavori con la selezione, il nome si riferisce alla directory di destinazione, mentre il nome del file rimarrà inviariato.
- *Rinomina*: Come il copia, ma li sposterà.
- *Salva con nome*: Come il copia, ma li trasferirà.
### Synchronized browsing ⏲️
Quando abilitato, ti permetterà di sincronizzare la navigazione tra i due pannelli.
Ciò comporta che quando cambierai directory in uno dei due pannelli, lo stesso verrà fatto nell'altro. Per abilitare la modalità è sufficiente premere `<Y>`; fai lo stesso per disabilitarlo. Mentre abilitato, sull'interfaccia dovrebbe essere visualizzato `Sync Browsing: ON` nella barra di stato.
### Apri e apri con 🚪
I comandi "apri" e "apri con" sono forniti da [open-rs](https://docs.rs/crate/open/2.1.0).
Quando apri un file (`<V>`), l'applicazione predefinita di sistema sarà utilizzata per aprire il file. Per fare ciò, sul tuo sistema dovrà essere usato il servizio di default del sistema.
- **Windows**: non devi installare niente, è già presente sul sistema.
- **MacOS**: non devi installare niente, è già presente sul sistema.
- **Linux**: uno di questi dev'essere presente (potrebbe già esserlo):
- *xdg-open*
- *gio*
- *gnome-open*
- *kde-open*
- **WSL**: *wslview* è richiesto, lo puoi installare tramite questa suite [wslu](https://github.com/wslutilities/wslu).
> Q: Posso modificare i file su remoto tramite la funzionalità "apri" / "apri con"?
> A: No, almeno non direttamente dal pannello remoto. Devi prima scaricarlo in locale, modificarlo e poi ricaricarlo. Questo perché il file remoto viene scaricato come file temporaneo in locale, ma non esiste poi un modo per sapere quando è stato modificato e quando l'utente ha effettivamente finito di lavorarci.
---
## Segnalibri ⭐
In termscp è possibile salvare i tuoi host preferiti tramite i segnalibri al fine di connettersi velocemente ad essi.
Termscp salverà anche gli ultimi 16 host ai quali ti sei connesso.
Questa funzionalità ti permette di caricare tutti i parametri necessari per connettersi ad un certo host, semplicemente selezioandolo dal tab dei preferiti nel form di autenticazione.
I preferiti saranno salvati se possibile presso:
- `$HOME/.config/termscp/` su Linux/BSD
- `$HOME/Library/Application Support/termscp` su MacOs
- `FOLDERID_RoamingAppData\termscp\` su Windows
Per i segnalibri (ma non per le connessioni recenti), è anche possibile salvare la password. La password non viene salvata di default e deve essere specificato tramite apposita opzione, al momento della creazione del segnalibro stesso.
Se sei preoccupato riguardo alla sicurezza della password per i segnalibri, dai un'occhiata al capitolo qui sotto 👀.
Per creare un segnalibro, segui questa procedura:
1. Inserisci i parametri per connetterti all'host che vuoi inserire come segnalibro nell'authentication form.
2. Premi `<CTRL+S>`
3. Inserisci il nome che vuoi dare al bookmark
4. Seleziona nel radio button se salvare la password
5. Premi `<ENTER>` per salvare
Quando vuoi caricare un segnalibro, premi `<TAB>` e naviga nella lista dei segnalibri fino al segnalibro che vuoi caricare, quindi premi `<ENTER>`.
![Bookmarks](https://github.com/veeso/termscp/blob/main/assets/images/bookmarks.gif?raw=true)
### Le mie password sono al sicuro 😈
Certo 😉.
Come detto in precedenza, i segnalibri sono salvati nella cartella delle configurazioni insieme alle password. Le password però non sono in chiaro, ma bensì sono criptate con **AES-128**. Questo le rende sicure? Sì! Does this make them safe? (salvo che per gli utenti di FreeBSD e WSL 😢)
In **Windows**, **Linux** and **MacOS** la chiave per criptare le password è salvata, se possibile, rispettivamente nel *Windows Vault*, nel *system keyring* e nel *Keychain*. Questo sistema è super-sicuro, in quanto garantito direttamente dal tuo sistema operativo.
❗ Attenzione che se sei un utente Linux, dovresti leggere il capitolo qui sotto riguardante il linux keyring 👀, questo perché il keyring potrebbe non essere ancora presente sul tuo sistema.
Su *FreeBSD* e *WSL*, d'altro canto, la chiave utilizzata per criptare le password è salvata su file presso (at $HOME/.config/termscp). È quindi possibile per un malintenzionato ottenere la chiave. Per fortuna essendo sotto la tua home, non dovrebbe essere possibile accedere al file, se non con il tuo utente, ma comunque per sicurezza ti consiglio di non salvare dati sensibili 😉.
#### Linux Keyring
Tutti gli amanti di Linux lo preferiscono per la libertà che questo dà agli utenti nella personalizzazione. Allo stesso tempo però questo spesso comporta degli effetti collaterali, tra cui la mancanza spesso di un'imposizione da parte dei creatori delle distro di standard e applicazioni e questo fatto coinvolge anche la questione del keyring.
Su alcuni sistemi di default, non c'è nessun provider di keyring, perché la distro dà all'utente la possibilità di sceglierne uno.
termscp richiede un servizio D-BUS che fornisce `org.freedesktop.secrets` e purtroppo ci sono ad oggi solo due servizi mantenuti che lo supportano.
- ❗ Se usi GNOME come Desktop environment (come gli utenti Ubuntu), dovresti già averne uno installato sul sistema, chiamato `gnome-keyring` e quindi dovrebbe già funzionare tutto.
- ❗ Se invece usi un altro DE, dovresti installare [KeepassXC](https://keepassxc.org/), che io per esempio utilizzo sul mio Manjaro Linux (con KDE) e funziona piuttosto bene. L'unico problema è che dovrai fare il setup per farlo funzionare. Per farlo puoi leggere il tutorial [qui](#keepassxc-setup-per-termscp)
- ❗ Se non volessi installare uno di questi servizi, termscp funzionerà come sempre, l'unica differenza sarà che salverà la chiave di crittazione su un file, come fa per FreeBSD e WSL.
##### KeepassXC setup per termscp
Questo tutorial spiega come impostare KeepassXC per termscp.
1. Installa KeepassXC dal sito ufficiale <https://keepassxc.org/>
2. Una volta avviato, vai su "strumenti" > "impostazioni" nella toolbar
3. Seleziona "Secret service integration" e abilita "Enable KeepassXC freedesktop.org secret service integration"
4. Crea un database se non ne hai già uno: dalla toolbar "Database" > "Nuovo database"
5. Dalla toolbar: "Database" > "Impostazioni database"
6. Seleziona "Secret service integration" e abilita "Expose entries under this group"
7. Seleziona il gruppo in cui vuoi salvare le chiavi di termscp. Attenzione che questo gruppo sarà utilizzato da tutte le altre eventuali applicazioni che salvano le password via D-BUS.
---
## Configurazione ⚙️
termscp supporta diversi parametri definiti dall'utente, che possono essere impostati nella configurazione.
termscp usa un file TOML e altre directory per salvare tutti i parametri, ma non preoccuparti, tutto può essere comodamente configurato da interfaccia grafica.
Per la configurazione, termscp richiede che i seguenti percorsi siano accessibili (termscp proverà a crearli per te):
- `$HOME/.config/termscp/` su Linux/BSD
- `$HOME/Library/Application Support/termscp` su MacOs
- `FOLDERID_RoamingAppData\termscp\` su Windows
Per accedere alla configurazione è sufficiente premere `<CTRL+C>` dall'authentication form.
Questi parametri possono essere impostati:
- **Text Editor**: l'editor di testo da utilizzare per aprire i file. Di default termscp userà quello definito nella variabile `EDITOR` od il primo che troverà installato tra quelli più popolari. Puoi tuttavia definire quello che vuoi (ad esempio `vim`). **Anche gli editor GUI sono supportati**, a meno che loro non partano in `nohup` dal processo padre.
- **Default Protocol**: il protocollo di default da visualizzare come prima opzione nell'authentication form. Questa opzione sarà anche utilizzata quando si usa l'argomento indirizzo da CLI e non si specifica un protocollo.
- **Show Hidden Files**: seleziona se mostrare di default i file nascosti. A runtime potrai comunque scegliere se visualizzarli o meno premendo `<A>`.
- **Check for updates**: se impostato a `YES` all'avvio termscp controllerà l'eventuale presenza di aggiornamenti. Per farlo utilizzerà una chiamata GET all'API di Github.
- **Prompt when replacing existing files?**: se impostato a `yes`, termscp ti chiederà una conferma prima di sovrascrivere un file a seguito di un download/upload.
- **Group Dirs**: seleziona se e come raggruppare le cartelle negli explorer. Se `Display first` è impostato, le directory verranno ordinate secondo quanto stabilito nel `sort by`, ma verranno messe prima dei file, viceversa se `Display last` è utilizzato. Se invece metti `no`, le cartelle verrano messe in ordine assieme ad i file.
- **Remote File formatter syntax**: La formattazione da usare per formattare i file sull'explorer remoto. Vedi [File explorer format](#file-explorer-format)
- **Local File formatter syntax**: La formattazione da usare per formattare i file sull'explorer locale. Vedi [File explorer format](#file-explorer-format)
- **Enable notifications?**: Se impostato a `yes`, le notifiche desktop saranno abilitate.
- **Notifications: minimum transfer size**: se la dimensione di un trasferimento supera o è uguale al valore impostato, al termine del trasferimento riceverai una notifica desktop (se queste sono abilitate). Il formato del valore dev'essere `{UNSIGNED} B/KB/MB/GB/TB/PB`
- **SSH configuration path**: Imposta il percorso del file di configurazione per SSH, per quando ci si connette ad un server SFTP/SCP. Se lasciato vuoto, nessun file verrà usato. Il percorso può anche iniziare con `~` per indicare il percorso della home dell'utente attuale (e.s. `~/.ssh/config`).
### SSH Key Storage 🔐
Assieme alla configurazione termscp supporta anche una feature essenziale per i client **SFTP/SCP**: lo storage di chiavi SSH.
Puoi accedere allo storage muovendoti nel tab delle chiavi SSH tramite `<TAB>` dalla configurazione.
- **Aggiungere chiavi**: premi `<CTRL+N>` e ti verrà chiesto di creare una nuova chiave. Inserisci l'hostname/indirizzo ed il nome utente, infine una volta che premerai invio, ti si aprirà l'editor di testo: incolla la chiave SSH **PRIVATA**, salva ed esci.
- **Rimuovi una chiave esistente**: premi `<DEL>` o `<CTRL+E>` selezionando la chiave da rimuovere.
- **Aggiorna una chiave esistente**: premi `<ENTER>` sulla chiave che vuoi modificare.
> Q: Se la mia chiave è protetta da password, posso comunque usarla?
> A: Sì, certo. In questo caso dovrai fornire la password come faresti per autenticarti con utente/password, ma in questo caso la password sarà usata per decrittare la chiave.
### File Explorer Format
È possibile dalla configurazione impostare la formattazione dei file sull'explorer. È possibile sia farlo per il pannello locale, che per quello remoto; quindi puoi avere due sintassi diverse. Questi campi, con nome `File formatter syntax (local)` and `File formatter syntax (remote)` definiranno come i file devono essere formattati sull'explorer.
La sintassi è la seguente `{KEY1}... {KEY2:LENGTH}... {KEY3:LENGTH:EXTRA} {KEYn}...`.
Ogni chiave sarà rimpiazzata dal formatter con il relativo attributo, mentre tutto ciò che è fuori dalle parentesi graffe rimarrà inviariato (quindi puoi metterci del testo arbitratio).
- Il nome della chiave è obbligatorio e dev'essere uno di quelli sotto.
- La lunghezza descrive quanto spazio in caratteri riservare al campo. Attributi con dimensione statico (GROUP, PEX, SIZE, USER) non supportano la lunghezza.
- L'extra serve a definire degli attributi in più. Solo alcuni lo supportano.
These are the keys supported by the formatter:
- `ATIME`: Last access time (con sintassi di default `%b %d %Y %H:%M`); Extra definisce il formato data (e.g. `{ATIME:8:%H:%M}`)
- `CTIME`: Creation time (con sintassi di default `%b %d %Y %H:%M`); Extra definisce il formato data (e.g. `{CTIME:8:%H:%M}`)
- `GROUP`: Owner group
- `MTIME`: Last change time (con sintassi di default `%b %d %Y %H:%M`); Extra definisce il formato data (e.g. `{MTIME:8:%H:%M}`)
- `NAME`: Nome file (Le cartelle comprese tra la root ed il genitore del file sono omessi se la lunghezza è maggiore di LENGTH)
- `PATH`: Percorso assoluto del file (Le cartelle comprese tra la root ed il genitore del file sono omessi se la lunghezza è maggiore di LENGHT)
- `PEX`: Permessi utente (formato UNIX)
- `SIZE`: Dimensione file (omesso per le directory)
- `SYMLINK`: Link simbolico (se presente `-> {FILE_PATH}`)
- `USER`: Owner user
Se lasciata vuota, la sintassi di default sarà utilizzata: `{NAME:24} {PEX} {USER} {SIZE} {MTIME:17:%b %d %Y %H:%M}`
---
## Temi 🎨
termscp fornisce anche una funzionalità strafiga: la possibilità di impostare i colori per tutta l'interfaccia.
Se vuoi impostare i colori, ci sono due modi per farlo:
- dal **menù di configurazione**
- importando un **tema** da file
Per personalizzare i colori dovrai andare nella configurazione temi, partendo dal menù di autenticazione, premendo `<CTRL+C>` e premendo due volte `<TAB>`. Dovresti essere quindi in configurazione nel tab `themes`.
Da qui puoi spostarti con le frecce per cambiare lo stile che vuoi, come mostrato nella GIF qua sotto:
![Themes](https://github.com/veeso/termscp/blob/main/assets/images/themes.gif?raw=true)
termscp supporta diverse sintassi per i colori, sia il formato hex (`#rrggbb`) che rgb `rgb(r, g, b)`, ma anche i **[colori CSS](https://www.w3schools.com/cssref/css_colors.asp)** (tipo `crimson`) 😉. C'è anche una chiave speciale `Default`. Default significa che per il colore verrà usato il default in base al tipo di elemento (foreground per i testi e linee, background per gli sfondi e i riempimenti).
Come detto già in precedenza, puoi anche importare i temi da file. Volendo puoi anche creare un tema prendendo ispirazione da quelli situati nella cartella `themes/` del repository ed importarli su termscp con `termscp -t <theme_file>`. Se l'operazione va a buon fine dovrebbe dirti che l'ha importato con successo.
### Il tema non carica 😱
Probabilmente è dovuto ad un aggiornamento che ha rotto il tema. Se viene aggiunta una nuova chiave nel tema (ma questo accade molto raramente), il tema non verrà più caricato. Ci sono diverse soluzioni veloci per questo problema.
1. Ricarica il tema: se stai usando un tema "ufficiale" fornito nel repository, basterà ricaricarlo, perché li aggiorno sempre quando modifico i temi:
```sh
termscp -t <theme.toml>
```
2. Sistema il tuo tema a mano: puoi modificare il tuo tema con un editor di testo tipo `vim` e aggiungere la chiave mancante. Il il tema si trova in `$CONFIG_DIR/termscp/theme.toml` dove `$CONFIG_DIR` è:
- FreeBSD/GNU-Linux: `$HOME/.config/`
- MacOs: `$HOME/Library/Application Support`
- Windows: `%appdata%`
❗ Le chiavi mancanti vengono riportate nel CHANGELOG sotto `BREAKING CHANGES` per la versione installata.
### Stili 💈
Puoi trovare qui sotto la definizione per ogni chiave.
Attenzione che gli stili **non coinvolgono la pagina di configurazione**, per renderla sempre accessibile nel caso gli stili siano inutilizzabili.
#### Pagina autenticazione
| Key | Description |
|----------------|------------------------------------|
| auth_address | Colore del campo indirizzo IP |
| auth_bookmarks | Colore del pannello segnalibri |
| auth_password | Colore del campo password |
| auth_port | Colore del campo numero porta |
| auth_protocol | Colore del selettore di protocollo |
| auth_recents | Colore del pannello recenti |
| auth_username | Colore del campo nome utente |
#### Pagina explorer e trasferimento
| Key | Description |
|--------------------------------------|---------------------------------------------------------------------------|
| transfer_local_explorer_background | Sfondo explorer locale |
| transfer_local_explorer_foreground | Foreground explorer locale |
| transfer_local_explorer_highlighted | Colore bordo e file selezionato explorer locale |
| transfer_remote_explorer_background | Sfondo explorer remoto |
| transfer_remote_explorer_foreground | Foreground explorer remoto |
| transfer_remote_explorer_highlighted | Colore bordo e file selezionato explorer remoto |
| transfer_log_background | Sfondo pannello di log |
| transfer_log_window | Colore bordi e testo log |
| transfer_progress_bar_partial | Colore barra progresso parziale |
| transfer_progress_bar_total | Colore barra progresso totale |
| transfer_status_hidden | Colore status bar file nascosti |
| transfer_status_sorting | Colore status bar ordinamento file; si applica anche al popup ordinamento |
| transfer_status_sync_browsing | Colore status bar per sync browsing |
#### Misc
Questi stili si applicano a varie componenti dell'applicazione.
| Key | Description |
|-------------------|---------------------------------------------|
| misc_error_dialog | Colore dialoghi errore |
| misc_info_dialog | Colore per dialoghi informazioni |
| misc_input_dialog | Colore per dialoghi input (tipo copia file) |
| misc_keys | Colore per abbinamento tasti |
| misc_quit_dialog | Colore per dialogo quit |
| misc_save_dialog | Colore per dialogo salva |
| misc_warn_dialog | Colore per dialoghi avvertimento |
---
## Editor di testo ✏
Con termscp puoi anche modificare i file di testo direttamente da terminale, utilizzando il tuo editor preferito.
Non importa se il file si trova in locale od in remoto, termscp ti consente di modificare e sincronizzare le modifiche per entrambi.
Nel caso il file si trovi su host remoto, il file verrà prima scaricato temporaneamente in locale, modificato e poi nel caso ci siano state modifiche, reinviato in remoto.
> ❗ Ricorda: **puoi modificare solo i file testuali**; non puoi modificare i file binari.
---
## Logging 🩺
termscp scrive un file di log per ogni sessione, nel percorso seguente:
- `$HOME/.config/termscp/termscp.log` su Linux/BSD
- `$HOME/Library/Application Support/termscp/termscp.log` su MacOs
- `FOLDERID_RoamingAppData\termscp\termscp.log` su Windows
Il log non viene ruotato, ma viene troncato ad ogni lancio di termscp, quindi se devi riportare un issue, non avviare termscp fino a che non avrai salvato il file di log.
I log sono di default riportati a livello *INFO*, quindi non sono particolarmente parlanti.
Se vuoi riportare un problema, se riesci, riproduci l'errore lanciando termscp in modalità di debug, in modo da fornire un log più dettagliato.
Per farlo, lancia termscp con l'opzione `-D`.
Ho scritto questo FAQ sui log, visto che potresti avere qualche dubbio:
> Non voglio il log, posso disabilitarlo?
Sì, puoi. Basta lanciare termscp con `-q or --quiet` come opzione. Puoi mantenerlo persistente salvandolo come alias nella tua shell. Ricorda che i log vengono usati per diagnosticare problemi e considerando che questo è un progetto open-source è anche un modo per contribuire al progetto 😉. Non voglio far sentire in colpa nessuno, ma tanto per dire.
> Il log è sicuro?
Se ti chiedi se il log espone dati sensibili, il log non espone nessuna password o dato sensibile.
## Notifiche 📫
termscp invierà notifiche destkop per i seguenti eventi:
- a **Transferimento completato**: La notifica verrà inviata a seguito di un trasferimento completato.
- ❗ La notifica verrà mostrata solo se la dimensione totale del trasferimento è uguale o maggiore al parametro `Notifications: minimum transfer size` definito in configurazione.
- a **Transferimento fallito**: La notifica verrà inviata a seguito di un trasferimento fallito.
- ❗ La notifica verrà mostrata solo se la dimensione totale del trasferimento è uguale o maggiore al parametro `Notifications: minimum transfer size` definito in configurazione.
- ad **Aggiornamento disponibile**: Ogni volta che una nuova versione di termscp è disponibile, verrà mostrata una notifica.
- ad **Aggiornamento installato**: Al termine dell'installazione di un aggiornamento, verrà mostrata una notifica.
- ad **Aggiornamento fallito**: Al fallimento dell'installazione di un aggiornamento, verrà mostrata una notifica.
❗ Se vuoi disabilitare le notifiche, è sufficiente andare in configurazione ed impostare `Enable notifications?` a `No` 😉.
❗ Se vuoi modificare la soglia minima per le notifiche dei trasferimenti, puoi impostare il valore di `Notifications: minimum transfer size` in configurazione 🙂.
## File watcher 🔭
Il file watcher ti permette di impostare una lista di percorsi da sincronizzare con l'host remoto.
Ciò implica che ogni volta che una modifica verrà rilevata al percorso sincronizzato, la modifica verrà automaticamente sincronizzata con l'host remoto, entro 5 secondi.
Puoi impostare quanti percorsi preferisci da sincronizzare:
1. Porta il cursore dell'explorer sulla cartella/file che vuoi sincronizzare
2. Vai alla directory sull'explorer remoto dove vuoi riportare le modifiche
3. Premi `<T>`
4. Rispondi `<YES>` alla domanda se vuoi sincronizzare il percorso
Per terminare la sincronizzazione, premi `<T>`, al percorso locale sincronizzato (od in qualsiasi sua sottocartella)
OPPURE, puoi semplicemente premere `<CTRL+T>` e premi `<ENTER>` sul percorso che vuoi desincronizzare.
Queste modifiche verranno applicate sull'host remoto:
- Nuovi file, modifiche
- File spostati o rinominati
- File rimossi
> ❗ Il watcher funziona solo in maniera unidirezionale locale > remoto. NON è possibile tracciare le modifiche da remoto a locale.

View File

@@ -1,21 +1,59 @@
# User manual 🎓
- [User manual 🎓](#user-manual-)
- [Usage ❓](#usage-)
- [Address argument 🌎](#address-argument-)
- [AWS S3 address argument](#aws-s3-address-argument)
- [How Password can be provided 🔐](#how-password-can-be-provided-)
- [S3 connection parameters](#s3-connection-parameters)
- [S3 credentials 🦊](#s3-credentials-)
- [File explorer 📂](#file-explorer-)
- [Keybindings ⌨](#keybindings-)
- [Work on multiple files 🥷](#work-on-multiple-files-)
- [Synchronized browsing ⏲️](#synchronized-browsing-)
- [Open and Open With 🚪](#open-and-open-with-)
- [Bookmarks ⭐](#bookmarks-)
- [Are my passwords Safe 😈](#are-my-passwords-safe-)
- [Linux Keyring](#linux-keyring)
- [KeepassXC setup for termscp](#keepassxc-setup-for-termscp)
- [Configuration ⚙️](#configuration-)
- [SSH Key Storage 🔐](#ssh-key-storage-)
- [File Explorer Format](#file-explorer-format)
- [Themes 🎨](#themes-)
- [My theme won't load 😱](#my-theme-wont-load-)
- [Styles 💈](#styles-)
- [Authentication page](#authentication-page)
- [Transfer page](#transfer-page)
- [Misc](#misc)
- [Text Editor ✏](#text-editor-)
- [Logging 🩺](#logging-)
- [Notifications 📫](#notifications-)
- [File watcher 🔭](#file-watcher-)
## Usage ❓
termscp can be started with the following options:
`termscp [options]... [protocol://user@address:port:wrkdir] [local-wrkdir]`
OR
`termscp [options]... -b [bookmark-name] [local-wrkdir]`
- `-P, --password <password>` if address is provided, password will be this argument
- `-b, --address-as-bookmark` resolve address argument as a bookmark name
- `-c, --config` Open termscp starting from the configuration page
- `-q, --quiet` Disable logging
- `-t, --theme <path>` Import specified theme
- `-u, --update` Update termscp to latest version
- `-v, --version` Print version info
- `-h, --help` Print help page
termscp can be started in two different mode, if no extra arguments is provided, termscp will show the authentication form, where the user will be able to provide the parameters required to connect to the remote peer.
termscp can be started in three different modes, if no extra arguments is provided, termscp will show the authentication form, where the user will be able to provide the parameters required to connect to the remote peer.
Alternatively, the user can provide an address as argument to skip the authentication form and starting directly the connection to the remote server.
If address argument is provided you can also provide the start working directory for local host
If address argument or bookmark name is provided you can also provide the start working directory for local host
### Address argument 🌎
@@ -51,17 +89,78 @@ Let's see some example of this particular syntax, since it's very comfortable an
termscp scp://omar@192.168.1.31:4022:/tmp
```
#### AWS S3 address argument
Aws S3 has a different syntax for CLI address argument, for obvious reasons, but I managed to keep it the more similar as possible to the generic address argument:
```txt
s3://<bucket-name>@<region>[:profile][:/wrkdir]
```
e.g.
```txt
s3://buckethead@eu-central-1:default:/assets
```
#### How Password can be provided 🔐
You have probably noticed, that, when providing the address as argument, there's no way to provide the password.
Password can be basically provided through 3 ways when address argument is provided:
- `-P, --password` option: just use this CLI option providing the password. I strongly unrecommend this method, since it's very unsecure (since you might keep the password in the shell history)
- `-P, --password` option: just use this CLI option providing the password. I strongly unrecommend this method, since it's very insecure (since you might keep the password in the shell history)
- Via `sshpass`: you can provide password via `sshpass`, e.g. `sshpass -f ~/.ssh/topsecret.key termscp cvisintin@192.168.1.31`
- You will be prompted for it: if you don't use any of the previous methods, you will be prompted for the password, as happens with the more classics tools such as `scp`, `ssh`, etc.
---
## S3 connection parameters
These parameters are required to connect to aws s3 and other s3 compatible servers:
- AWS S3:
- **bucket name**
- **region**
- *profile* (if not provided: "default")
- *access key* (unless if public)
- *secret access key* (unless if public)
- *security token* (if required)
- *session token* (if required)
- new path style: **NO**
- Other S3 endpoints:
- **bucket name**
- **endpoint**
- *access key* (unless if public)
- *secret access key* (unless if public)
- new path style: **YES**
### S3 credentials 🦊
In order to connect to an Aws S3 bucket you must obviously provide some credentials.
There are basically three ways to achieve this:
So these are the ways you can provide the credentials for s3:
1. Authentication form:
1. You can provide the `access_key` (should be mandatory), the `secret_access_key` (should be mandatory), `security_token` and the `session_token`
2. If you save the s3 connection as a bookmark, these credentials will be saved as an encrypted AES-256/BASE64 string in your bookmarks file (except for the security token and session token which are meant to be temporary credentials).
2. Use your credentials file: just configure the AWS cli via `aws configure` and your credentials should already be located at `~/.aws/credentials`. In case you're using a profile different from `default`, just provide it in the profile field in the authentication form.
3. **Environment variables**: you can always provide your credentials as environment variables. Keep in mind that these credentials **will always override** the credentials located in the `credentials` file. See how to configure the environment below:
These should always be mandatory:
- `AWS_ACCESS_KEY_ID`: aws access key ID (usually starts with `AKIA...`)
- `AWS_SECRET_ACCESS_KEY`: the secret access key
In case you've configured a stronger security, you *may* require these too:
- `AWS_SECURITY_TOKEN`: security token
- `AWS_SESSION_TOKEN`: session token
⚠️ Your credentials are safe: termscp won't manipulate these values directly! Your credentials are directly consumed by the **s3** crate.
In case you've got some concern regarding security, please contact the library author on [Github](https://github.com/durch/rust-s3) ⚠️
---
## File explorer 📂
When we refer to file explorers in termscp, we refer to the panels you can see after establishing a connection with the remote.
@@ -75,41 +174,46 @@ In order to change panel you need to type `<LEFT>` to move the remote explorer p
### Keybindings ⌨
| Key | Command | Reminder |
|---------------|-------------------------------------------------------|-------------|
| `<ESC>` | Disconnect from remote; return to authentication page | |
| `<TAB>` | Switch between log tab and explorer | |
| `<BACKSPACE>` | Go to previous directory in stack | |
| `<RIGHT>` | Move to remote explorer tab | |
| `<LEFT>` | Move to local explorer tab | |
| `<UP>` | Move up in selected list | |
| `<DOWN>` | Move down in selected list | |
| `<PGUP>` | Move up in selected list by 8 rows | |
| `<PGDOWN>` | Move down in selected list by 8 rows | |
| `<ENTER>` | Enter directory | |
| `<SPACE>` | Upload / download selected file | |
| `<A>` | Toggle hidden files | All |
| `<B>` | Sort files by | Bubblesort? |
| `<C>` | Copy file/directory | Copy |
| `<D>` | Make directory | Directory |
| `<E>` | Delete file (Same as `DEL`) | Erase |
| `<F>` | Search for files (wild match is supported) | Find |
| `<G>` | Go to supplied path | Go to |
| `<H>` | Show help | Help |
| `<I>` | Show info about selected file or directory | Info |
| `<L>` | Reload current directory's content / Clear selection | List |
| `<M>` | Select a file | Mark |
| `<N>` | Create new file with provided name | New |
| `<O>` | Edit file; see Text editor | Open |
| `<Q>` | Quit termscp | Quit |
| `<R>` | Rename file | Rename |
| `<S>` | Save file as... | Save |
| `<U>` | Go to parent directory | Upper |
| `<X>` | Execute a command | eXecute |
| `<Y>` | Toggle synchronized browsing | sYnc |
| `<DEL>` | Delete file | |
| `<CTRL+A>` | Select all files | |
| `<CTRL+C>` | Abort file transfer process | |
| Key | Command | Reminder |
|---------------|---------------------------------------------------------|-------------|
| `<ESC>` | Disconnect from remote; return to authentication page | |
| `<BACKSPACE>` | Go to previous directory in stack | |
| `<TAB>` | Switch explorer tab | |
| `<RIGHT>` | Move to remote explorer tab | |
| `<LEFT>` | Move to local explorer tab | |
| `<UP>` | Move up in selected list | |
| `<DOWN>` | Move down in selected list | |
| `<PGUP>` | Move up in selected list by 8 rows | |
| `<PGDOWN>` | Move down in selected list by 8 rows | |
| `<ENTER>` | Enter directory | |
| `<SPACE>` | Upload / download selected file | |
| `<BACKTAB>` | Switch between log tab and explorer | |
| `<A>` | Toggle hidden files | All |
| `<B>` | Sort files by | Bubblesort? |
| `<C|F5>` | Copy file/directory | Copy |
| `<D|F7>` | Make directory | Directory |
| `<E|F8|DEL>` | Delete file | Erase |
| `<F>` | Search for files (wild match is supported) | Find |
| `<G>` | Go to supplied path | Go to |
| `<H|F1>` | Show help | Help |
| `<I>` | Show info about selected file or directory | Info |
| `<K>` | Create symlink pointing to the currently selected entry | symlinK |
| `<L>` | Reload current directory's content / Clear selection | List |
| `<M>` | Select a file | Mark |
| `<N>` | Create new file with provided name | New |
| `<O|F4>` | Edit file; see Text editor | Open |
| `<Q|F10>` | Quit termscp | Quit |
| `<R|F6>` | Rename file | Rename |
| `<S|F2>` | Save file as... | Save |
| `<T>` | Synchronize changes to selected path to remote | Track |
| `<U>` | Go to parent directory | Up |
| `<V|F3>` | Open file with default program for filetype | View |
| `<W>` | Open file with provided program | With |
| `<X>` | Execute a command | eXecute |
| `<Y>` | Toggle synchronized browsing | sYnc |
| `<CTRL+A>` | Select all files | |
| `<CTRL+C>` | Abort file transfer process | |
| `<CTRL+T>` | Show all synchronized paths | Track |
### Work on multiple files 🥷
@@ -126,9 +230,24 @@ All the actions are available when working with multiple files, but be aware tha
### Synchronized browsing ⏲️
When enabled, synchronized browsing, will allow you to synchronize the navigation between the two panels.
This means that whenever you'll change the working directory on one panel, the same action will be reproduced on the other panel. If you want to enable synchronized browsing just press `<Y>`; press twice to disable. While enabled, the synchronized browising state will be reported on the status bar on `ON`.
This means that whenever you'll change the working directory on one panel, the same action will be reproduced on the other panel. If you want to enable synchronized browsing just press `<Y>`; press twice to disable. While enabled, the synchronized browsing state will be reported on the status bar on `ON`.
*Warning*: at the moment, whenever you try to access an unexisting directory, you won't be prompted to create it. This might change in a future update.
### Open and Open With 🚪
Open and open with commands are powered by [open-rs](https://docs.rs/crate/open/1.7.0).
When opening files with View command (`<V>`), the system default application for the file type will be used. To do so, the default operting system service will be used, so be sure to have at least one of these installed on your system:
- **Windows** users: you don't have to worry about it, since the crate will use the `start` command.
- **MacOS** users: you don't have to worry either, since the crate will use `open`, which is already installed on your system.
- **Linux** users: one of these should be installed
- *xdg-open*
- *gio*
- *gnome-open*
- *kde-open*
- **WSL** users: *wslview* is required, you must install [wslu](https://github.com/wslutilities/wslu).
> Q: Can I edit remote files using the view command?
> A: No, at least not directly from the "remote panel". You have to download it to a local directory first, that's due to the fact that when you open a remote file, the file is downloaded into a temporary directory, but there's no way to create a watcher for the file to check when the program you used to open it was closed, so termscp is not able to know when you're done editing the file.
---
@@ -145,14 +264,7 @@ Bookmarks will be saved, if possible at:
- `FOLDERID_RoamingAppData\termscp\` on Windows
For bookmarks only (this won't apply to recent hosts) it is also possible to save the password used to authenticate. The password is not saved by default and must be specified through the prompt when saving a new Bookmark.
> I was very undecided about storing passwords in termscp. The reason? Saving a password on your computer might give access to a hacker to any server you've registered. But I must admit by myself that for many machines typing the password everytime is really boring, also many times I have to work with machines in LAN, which wouldn't provide any advantage to an attacker, So I came out with a good compromise for passwords.
I warmly suggest you to follow these guidelines in order to decide whether you should or you shouldn't save passwords:
- **DON'T** save passwords for machines which are exposed on the internet, save passwords only for machines in LAN
- Make sure your machine is protected by attackers. If possible encrypt your disk and don't leave your PC unlocked while you're away.
- Preferably, save passwords only when a compromising of the target machine wouldn't be a problem.
If you're concerned about the security of the password saved for your bookmarks, please read the [chapter below 👀](#are-my-passwords-safe-).
In order to create a new bookmark, just follow these steps:
@@ -168,13 +280,35 @@ whenever you want to use the previously saved connection, just press `<TAB>` to
### Are my passwords Safe 😈
Well, kinda.
As said before, bookmarks are saved in your configuration directory along with passwords. Passwords are obviously not plain text, they are encrypted with **AES-128**. Does this make them safe? Well, depends on your operating system:
Sure 😉.
As said before, bookmarks are saved in your configuration directory along with passwords. Passwords are obviously not plain text, they are encrypted with **AES-128**. Does this make them safe? Absolutely! (except for BSD and WSL users 😢)
On Windows and MacOS the passwords are stored, if possible (but should be), in respectively the Windows Vault and the Keychain. This is actually super-safe and is directly managed by your operating system.
On **Windows**, **Linux** and **MacOS** the key used to encrypt passwords is stored, if possible (but should be), respectively in the *Windows Vault*, in the *system keyring* and into the *Keychain*. This is actually super-safe and is directly managed by your operating system.
On Linux and BSD, on the other hand, the key used to encrypt your passwords is stored on your drive (at $HOME/.config/termscp). It is then, still possible to retrieve the key to decrypt passwords. Luckily, the location of the key guarantees your key can't be read by users different from yours, but yeah, I still wouldn't save the password for a server exposed on the internet 😉.
Actually [keyring-rs](https://github.com/hwchen/keyring-rs), supports Linux, but for different reasons I preferred not to make it available for this configuration. If you want to read more about my decision read [this issue](https://github.com/veeso/termscp/issues/2), while if you think this might have been implemented differently feel free to open an issue with your proposal.
❗ Please, notice that if you're a Linux user, you'd better to read the [chapter below 👀](#linux-keyring), because the keyring might not be enabled or supported on your system!
On *BSD* and *WSL*, on the other hand, the key used to encrypt your passwords is stored on your drive (at $HOME/.config/termscp). It is then, still possible to retrieve the key to decrypt passwords. Luckily, the location of the key guarantees your key can't be read by users different from yours, but yeah, I still wouldn't save the password for a server exposed on the internet 😉.
#### Linux Keyring
We all love Linux thanks to the freedom it gives to the users. You can basically do anything you want as a Linux user, but this has also some cons, such as the fact that often there is no standard applications across different distributions. And this involves keyring too.
This means that on Linux there might be no keyring installed on your system. Unfortunately the library we use to work with the key storage requires a service which exposes `org.freedesktop.secrets` on D-BUS and the worst fact is that there only two services exposing it.
- ❗ If you use GNOME as desktop environment (e.g. ubuntu users), you should already be fine, since keyring is already provided by `gnome-keyring` and everything should already be working.
- ❗ For other desktop environment users there is a nice program you can use to get a keyring which is [KeepassXC](https://keepassxc.org/), which I use on my Manjaro installation (with KDE) and works fine. The only problem is that you have to setup it to be used along with termscp (but it's quite simple). To get started with KeepassXC read more [here](#keepassxc-setup-for-termscp).
- ❗ What about you don't want to install any of these services? Well, there's no problem! **termscp will keep working as usual**, but it will save the key in a file, as it usually does for BSD and WSL.
##### KeepassXC setup for termscp
Follow these steps in order to setup keepassXC for termscp:
1. Install KeepassXC
2. Go to "tools" > "settings" in toolbar
3. Select "Secret service integration" and toggle "Enable KeepassXC freedesktop.org secret service integration"
4. Create a database, if you don't have one yet: from toolbar "Database" > "New database"
5. From toolbar: "Database" > "Database settings"
6. Select "Secret service integration" and toggle "Expose entries under this group"
7. Select the group in the list where you want the termscp secret to be kept. Remember that this group might be used by any other application to store secrets via DBUS.
---
@@ -193,12 +327,17 @@ To access configuration, you just have to press `<CTRL+C>` from the home of term
These parameters can be changed:
- **Text Editor**: the text editor to use. By default termscp will find the default editor for you; with this option you can force an editor to be used (e.g. `vim`). **Also GUI editors are supported**, unless they `nohup` from the parent process so if you ask: yes, you can use `notepad.exe`, and no: **Visual Studio Code doesn't work**.
- **Text Editor**: the text editor to use. By default termscp will find the default editor for you; with this option you can force an editor to be used (e.g. `vim`). **Also GUI editors are supported**, unless they `nohup` from the parent process.
- **Default Protocol**: the default protocol is the default value for the file transfer protocol to be used in termscp. This applies for the login page and for the address CLI argument.
- **Show Hidden Files**: select whether hidden files shall be displayed by default. You will be able to decide whether to show or not hidden files at runtime pressing `A` anyway.
- **Check for updates**: if set to `yes`, termscp will fetch the Github API to check if there is a new version of termscp available.
- **Prompt when replacing existing files?**: If set to `yes`, termscp will prompt for confirmation you whenever a file transfer would cause an existing file on target host to be replaced.
- **Group Dirs**: select whether directories should be groupped or not in file explorers. If `Display first` is selected, directories will be sorted using the configured method but displayed before files, viceversa if `Display last` is selected.
- **File formatter syntax**: syntax to display file info for each file in the explorer. See [File explorer format](#file-explorer-format)
- **Remote File formatter syntax**: syntax to display file info for each file in the remote explorer. See [File explorer format](#file-explorer-format)
- **Local File formatter syntax**: syntax to display file info for each file in the local explorer. See [File explorer format](#file-explorer-format)
- **Enable notifications?**: If set to `Yes`, notifications will be displayed.
- **Notifications: minimum transfer size**: if transfer size is greater or equal than the specified value, notifications for transfer will be displayed. The accepted values are in format `{UNSIGNED} B/KB/MB/GB/TB/PB`
- **SSH configuration path**: Set SSH configuration file to use when connecting to a SCP/SFTP server. If unset (empty) no file will be used. You can specify a path starting with `~` to indicate the home path (e.g. `~/.ssh/config`)
### SSH Key Storage 🔐
@@ -229,7 +368,8 @@ These are the keys supported by the formatter:
- `CTIME`: Creation time (with syntax `%b %d %Y %H:%M`); Extra might be provided as the time syntax (e.g. `{CTIME:8:%H:%M}`)
- `GROUP`: Owner group
- `MTIME`: Last change time (with syntax `%b %d %Y %H:%M`); Extra might be provided as the time syntax (e.g. `{MTIME:8:%H:%M}`)
- `NAME`: File name (Elided if longer than 24)
- `NAME`: File name (Folders between root and first ancestors are elided if longer than LENGTH)
- `PATH`: File absolute path (Folders between root and first ancestors are elided if longer than LENGHT)
- `PEX`: File permissions (UNIX format)
- `SIZE`: File size (omitted for directories)
- `SYMLINK`: Symlink (if any `-> {FILE_PATH}`)
@@ -239,16 +379,99 @@ If left empty, the default formatter syntax will be used: `{NAME:24} {PEX} {USER
---
## Themes 🎨
Termscp provides you with an awesome feature: the possibility to set the colors for several components in the application.
If you want to customize termscp there are two available ways to do so:
- From the **configuration menu**
- Importing a **theme file**
In order to create your own customization from termscp, all you have to do so is to enter the configuration from the auth activity, pressing `<CTRL+C>` and then `<TAB>` twice. You should have now moved to the `themes` panel.
Here you can move with `<UP>` and `<DOWN>` to change the style you want to change, as shown in the gif below:
![Themes](https://github.com/veeso/termscp/blob/main/assets/images/themes.gif?raw=true)
termscp supports both the traditional explicit hex (`#rrggbb`) and rgb `rgb(r, g, b)` syntax to provide colors, but also **[css colors](https://www.w3schools.com/cssref/css_colors.asp)** (such as `crimson`) are accepted 😉. There is also a special keywork which is `Default`. Default means that the color used will be the default foreground or background color based on the situation (foreground for texts and lines, background for well, guess what).
As said before, you can also import theme files. You can take inspiration from or directly use one of the themes provided along with termscp, located in the `themes/` directory of this repository and import them running termscp as `termscp -t <theme_file>`. If everything was fine, it should tell you the theme has successfully been imported.
### My theme won't load 😱
This is probably due to a recent update which has broken the theme. Whenever I add a new key to themes, the saved theme won't load. To fix this issues there are two really quick-fix solutions:
1. Reload theme: whenever I release an update I will also patch the "official" themes, so you just have to download it from the repository again and re-import the theme via `-t` option
```sh
termscp -t <theme.toml>
```
2. Fix your theme: If you're using a custom theme, then you can edit via `vim` and add the missing key. The theme is located at `$CONFIG_DIR/termscp/theme.toml` where `$CONFIG_DIR` is:
- FreeBSD/GNU-Linux: `$HOME/.config/`
- MacOs: `$HOME/Library/Application Support`
- Windows: `%appdata%`
❗ Missing keys are reported in the CHANGELOG under `BREAKING CHANGES` for the version you've just installed.
### Styles 💈
You can find in the table below, the description for each style field.
Please, notice that **styles won't apply to configuration page**, in order to make it always accessible in case you mess everything up
#### Authentication page
| Key | Description |
|----------------|------------------------------------------|
| auth_address | Color of the input field for IP address |
| auth_bookmarks | Color of the bookmarks panel |
| auth_password | Color of the input field for password |
| auth_port | Color of the input field for port number |
| auth_protocol | Color of the radio group for protocol |
| auth_recents | Color of the recents panel |
| auth_username | Color of the input field for username |
#### Transfer page
| Key | Description |
|--------------------------------------|---------------------------------------------------------------------------|
| transfer_local_explorer_background | Background color of localhost explorer |
| transfer_local_explorer_foreground | Foreground color of localhost explorer |
| transfer_local_explorer_highlighted | Border and highlighted color for localhost explorer |
| transfer_remote_explorer_background | Background color of remote explorer |
| transfer_remote_explorer_foreground | Foreground color of remote explorer |
| transfer_remote_explorer_highlighted | Border and highlighted color for remote explorer |
| transfer_log_background | Background color for log panel |
| transfer_log_window | Window color for log panel |
| transfer_progress_bar_partial | Partial progress bar color |
| transfer_progress_bar_total | Total progress bar color |
| transfer_status_hidden | Color for status bar "hidden" label |
| transfer_status_sorting | Color for status bar "sorting" label; applies also to file sorting dialog |
| transfer_status_sync_browsing | Color for status bar "sync browsing" label |
#### Misc
These styles applie to different part of the application.
| Key | Description |
|-------------------|---------------------------------------------|
| misc_error_dialog | Color for error messages |
| misc_info_dialog | Color for info dialogs |
| misc_input_dialog | Color for input dialogs (such as copy file) |
| misc_keys | Color of text for key strokes |
| misc_quit_dialog | Color for quit dialogs |
| misc_save_dialog | Color for save dialogs |
| misc_warn_dialog | Color for warn dialogs |
---
## Text Editor ✏
termscp has, as you might have noticed, many features, one of these is the possibility to view and edit text file. It doesn't matter if the file is located on the local host or on the remote host, termscp provides the possibility to open a file in your favourite text editor.
In case the file is located on remote host, the file will be first downloaded into your temporary file directory and then, **only** if changes were made to the file, re-uploaded to the remote host. termscp checks if you made changes to the file verifying the last modification time of the file.
Just a reminder: **you can edit only textual file**; binary files are not supported.
### How do I configure the text editor 🦥
Text editor is automatically found using this [awesome crate](https://github.com/milkey-mouse/edit), if you want to change the text editor to use, change it in termscp configuration. [Read more](#configuration-)
> ❗ Just a reminder: **you can edit only textual file**; binary files are not supported.
---
@@ -261,17 +484,13 @@ termscp writes a log file for each session, which is written at
- `FOLDERID_RoamingAppData\termscp\termscp.log` on Windows
the log won't be rotated, but will just be truncated after each launch of termscp, so if you want to report an issue and you want to attach your log file, keep in mind to save the log file in a safe place before using termscp again.
The log file always reports in *trace* level, so it is kinda verbose.
The logging by default reports in *INFO* level, so it is not very verbose.
If you want to submit an issue, please, if you can, reproduce the issue with the level set to `TRACE`, to do so, launch termscp with
the `-D` CLI option.
I know you might have some questions regarding log files, so I made a kind of a Q/A:
> Is it possible to reduce verbosity?
No. The reason is quite simple: when an issue happens, you must be able to know what's causing it and the only way to do that, is to have the log file with the maximum verbosity level set.
> If trace level is set for logging, is the file going to reach a huge size?
Probably not, unless you never quit termscp, but I think that's likely to happne. A long session may produce up to 10MB of log files (I said a long session), but I think a normal session won't exceed 2MB.
> I don't want logging, can I turn it off?
Yes, you can. Just start termscp with `-q or --quiet` option. You can alias termscp to make it persistent. Remember that logging is used to diagnose issues, so since behind every open source project, there should always be this kind of mutual help, keeping log files might be your way to support the project 😉. I don't want you to feel guilty, but just to say.
@@ -279,3 +498,43 @@ Yes, you can. Just start termscp with `-q or --quiet` option. You can alias term
> Is logging safe?
If you're concerned about security, the log file doesn't contain any plain password, so don't worry and exposes the same information the sibling file `bookmarks` reports.
## Notifications 📫
Termscp will send Desktop notifications for these kind of events:
- on **Transfer completed**: The notification will be sent once a transfer has been successfully completed.
- ❗ The notification will be displayed only if the transfer total size is at least the specified `Notifications: minimum transfer size` in the configuration.
- on **Transfer failed**: The notification will be sent once a transfer has failed due to an error.
- ❗ The notification will be displayed only if the transfer total size is at least the specified `Notifications: minimum transfer size` in the configuration.
- on **Update available**: Whenever a new version of termscp is available, a notification will be displayed.
- on **Update installed**: Whenever a new version of termscp has been installed, a notification will be displayed.
- on **Update failed**: Whenever the installation of the update fails, a notification will be displayed.
❗ If you prefer to keep notifications turned off, you can just enter setup and set `Enable notifications?` to `No` 😉.
❗ If you want to change the minimum transfer size to display notifications, you can change the value in the configuration with key `Notifications: minimum transfer size` and set it to whatever suits better for you 🙂.
---
## File watcher 🔭
The file watcher allows you to setup a list of paths to synchronize with the remote hosts.
This means that whenever a change on the local file system will be detected on the synchronized path, the change will be automatically reported to the configured remote host path, within 5 seconds.
You can set as many paths to synchronize as you prefer:
1. Put the cursor on the local explorer on the directory/file you want to keep synchronized
2. Go to the directory you want the changes to be reported to on the remote host
3. Press `<T>`
4. Answer `<YES>` to the radio popup
To unwatch, just press `<T>` on the local synchronized path (or to any of its subfolders)
OR you can just press `<CTRL+T>` and press `<ENTER>` to the synchronized path you want to unwatch.
These changes will be reported to the remote host:
- New files, file changes
- File moved/renamed
- File removed/unlinked
> ❗ The watcher works only in one direction (local > remote). It is NOT possible to synchronize automatically the changes from remote to local.

28
docs/misc/README.deb.txt Normal file
View File

@@ -0,0 +1,28 @@
Termscp is a feature rich terminal file transfer and explorer, with support for SCP/SFTP/FTP/S3.
Basically is a terminal utility with an TUI to connect to a remote server to retrieve and upload files and
to interact with the local file system.
Features:
- 📁 Different communication protocols
- SFTP
- SCP
- FTP and FTPS
- S3
- 🖥 Explore and operate on the remote and on the local machine file system with a handy UI
- Create, remove, rename, search, view and edit files
- ⭐ Connect to your favourite hosts through built-in bookmarks and recent connections
- 📝 View and edit files with your favourite applications
- 💁 SFTP/SCP authentication with SSH keys and username/password
- 🐧 Compatible with Windows, Linux, FreeBSD and MacOS
- 🎨 Make it yours!
- Themes
- Custom file explorer format
- Customizable text editor
- Customizable file sorting
- and many other parameters...
- 📫 Get notified via Desktop Notifications when a large file has been transferred
- 🔐 Save your password in your operating system key vault
- 🦀 Rust-powered
- 👀 Developed keeping an eye on performance
- 🦄 Frequent awesome updates

290
docs/zh-CN/README.md Normal file
View File

@@ -0,0 +1,290 @@
# termscp
<p align="center">
<img src="/assets/images/termscp.svg" width="256" height="256" />
</p>
<p align="center">~ 功能丰富的终端文件传输 ~</p>
<p align="center">
<a href="https://veeso.github.io/termscp/" target="_blank">网站</a>
·
<a href="https://veeso.github.io/termscp/#get-started" target="_blank">安装</a>
·
<a href="https://veeso.github.io/termscp/#user-manual" target="_blank">用户手册</a>
</p>
<p align="center">
<a href="https://github.com/veeso/termscp"
><img
height="20"
src="/assets/images/flags/us.png"
alt="English"
/></a>
&nbsp;
<a
href="https://github.com/veeso/termscp/blob/main/docs/de/README.md"
><img
height="20"
src="/assets/images/flags/de.png"
alt="Deutsch"
/></a>
&nbsp;
<a
href="https://github.com/veeso/termscp/blob/main/docs/es/README.md"
><img
height="20"
src="/assets/images/flags/es.png"
alt="Español"
/></a>
&nbsp;
<a
href="https://github.com/veeso/termscp/blob/main/docs/fr/README.md"
><img
height="20"
src="/assets/images/flags/fr.png"
alt="Français"
/></a>
&nbsp;
<a
href="https://github.com/veeso/termscp/blob/main/docs/it/README.md"
><img
height="20"
src="/assets/images/flags/it.png"
alt="Italiano"
/></a>
&nbsp;
<a
href="https://github.com/veeso/termscp/blob/main/docs/zh-CN/README.md"
><img
height="20"
src="/assets/images/flags/cn.png"
alt="简体中文"
/></a>
</p>
<p align="center"><a href="https://veeso.github.io/" target="_blank">@veeso</a> 开发</p>
<p align="center">当前版本: 0.9.0 (18/06/2022)</p>
<p align="center">
<a href="https://opensource.org/licenses/MIT"
><img
src="https://img.shields.io/badge/License-MIT-teal.svg"
alt="License-MIT"
/></a>
<a href="https://github.com/veeso/termscp/stargazers"
><img
src="https://img.shields.io/github/stars/veeso/termscp.svg"
alt="Repo stars"
/></a>
<a href="https://crates.io/crates/termscp"
><img
src="https://img.shields.io/crates/d/termscp.svg"
alt="Downloads counter"
/></a>
<a href="https://crates.io/crates/termscp"
><img
src="https://img.shields.io/crates/v/termscp.svg"
alt="Latest version"
/></a>
<a href="https://ko-fi.com/veeso">
<img
src="https://img.shields.io/badge/donate-ko--fi-red"
alt="Ko-fi"
/></a>
</p>
<p align="center">
<a href="https://github.com/veeso/termscp/actions"
><img
src="https://github.com/veeso/termscp/workflows/Linux/badge.svg"
alt="Linux CI"
/></a>
<a href="https://github.com/veeso/termscp/actions"
><img
src="https://github.com/veeso/termscp/workflows/MacOS/badge.svg"
alt="MacOS CI"
/></a>
<a href="https://github.com/veeso/termscp/actions"
><img
src="https://github.com/veeso/termscp/workflows/Windows/badge.svg"
alt="Windows CI"
/></a>
<a href="https://github.com/veeso/termscp/actions"
><img
src="https://github.com/veeso/termscp/workflows/FreeBSD/badge.svg"
alt="FreeBSD CI"
/></a>
<a href="https://coveralls.io/github/veeso/termscp"
><img
src="https://coveralls.io/repos/github/veeso/termscp/badge.svg"
alt="Coveralls"
/></a>
</p>
---
## 关于 termscp 🖥
termscp 是一个功能丰富的终端文件传输和浏览器,支持 SCP/SFTP/FTP/S3。 所以基本上是一个带有 TUI 的终端实用程序,用于连接到远程服务器以检索和上传文件并与本地文件系统进行交互。
它与 **Linux**、**MacOS**、**FreeBSD** 和 **Windows** 兼容。
![Explorer](/assets/images/explorer.gif)
---
## 特征 🎁
- 📁 不同的通讯协议
- **SFTP**
- **SCP**
- **FTP** and **FTPS**
- **S3**
- 🖥 使用方便的 UI 在远程和本地机器文件系统上探索和操作
- 创建、删除、重命名、搜索、查看和编辑文件
- ⭐ 通过内置书签和最近的连接连接到您最喜欢的主机
- 📝 使用您喜欢的应用程序查看和编辑文件
- 💁 使用 SSH 密钥和用户名/密码进行 SFTP/SCP 身份验证
- 🐧 与 Windows、Linux、FreeBSD 和 MacOS 兼容
- 🎨 让它成为你的!
- 主题
- 自定义文件浏览器格式
- 可定制的文本编辑器
- 可定制的文件排序
- 和许多其他参数...
- 📫 传输大文件时通过桌面通知获得通知
- 🔭 保持文件更改与远程主机同步
- 🔐 将密码保存在操作系统密钥保管库中
- 🦀 Rust 动力
- 👀 开发时注意性能
- 🦄 频繁的精彩更新
---
## 开始 🚀
如果您正在考虑安装termscp我要感谢您💜 我希望你会喜欢termscp
如果您想为此项目做出贡献,请不要忘记查看我们的贡献指南。 [阅读更多](../../CONTRIBUTING.md)
如果您是 Linux、FreeBSD 或 MacOS 用户,这个简单的 shell 脚本将使用单个命令在您的系统上安装 termscp
```sh
curl --proto '=https' --tlsv1.2 -sSLf "https://git.io/JBhDb" | sh
```
如果您是 Windows 用户,则可以使用 [Chocolatey](https://chocolatey.org/) 安装 termscp
```sh
choco install termscp
```
如需更多信息或其他平台,请访问 [veeso.github.io](https://veeso.github.io/termscp/#get-started) 查看所有安装方法。
⚠️ 如果您正在寻找如何更新 termscp 只需从 CLI 运行 termscp `(sudo) termscp --update` ⚠️
### 要求 ❗
- **Linux** 用户:
- libssh
- libdbus-1
- pkg-config
- **FreeBSD** 用户:
- libssh
- dbus
- pkgconf
### 可选要求 ✔️
这些要求不是运行 termscp 的强制要求,而是要享受它的所有功能
- **Linux/FreeBSD** 用户:
-`V` **打开** 文件(至少其中之一)
- *xdg-open*
- *gio*
- *gnome-open*
- *kde-open*
- **Linux** 用户:
- keyring manager: [在用户手册中阅读更多内容](man.md#linux-keyring)
- **WSL** 用户
-`V` **打开** 文件(至少其中之一)
- [wslu](https://github.com/wslutilities/wslu)
---
## 支持我 ☕
如果您喜欢 termscp 并且希望看到该项目不断发展和改进,请考虑在 **Buy me a coffee** 上捐款以支持我🥳
[![ko-fi](https://img.shields.io/badge/Ko--fi-F16061?style=for-the-badge&logo=ko-fi&logoColor=white)](https://ko-fi.com/veeso)
或者,如果您愿意,您也可以在 PayPal 上捐款:
[![PayPal](https://img.shields.io/badge/PayPal-00457C?style=for-the-badge&logo=paypal&logoColor=white)](https://www.paypal.me/chrisintin)
---
## 用户手册和文档 📚
用户手册可以在[termscp的网站](https://veeso.github.io/termscp/#user-manual)上找到 或者在[Github](man.md)上。s
---
## 贡献和问题 🤝🏻
欢迎贡献、错误报告、新功能和问题! 😉
如果您有任何问题或疑虑或者您想建议新功能或者您只想改进termscp请随时打开问题或 PR。
请遵循 [我们的贡献指南](../../CONTRIBUTING.md)
---
## 变更日志 ⏳
查看termscp的更新日志 [这里](../../CHANGELOG.md)
---
## 供电 💪
termscp 由这些很棒的项目提供支持:
- [bytesize](https://github.com/hyunsik/bytesize)
- [crossterm](https://github.com/crossterm-rs/crossterm)
- [edit](https://github.com/milkey-mouse/edit)
- [keyring-rs](https://github.com/hwchen/keyring-rs)
- [open-rs](https://github.com/Byron/open-rs)
- [rpassword](https://github.com/conradkleinespel/rpassword)
- [rust-s3](https://github.com/durch/rust-s3)
- [self_update](https://github.com/jaemk/self_update)
- [ssh2-rs](https://github.com/alexcrichton/ssh2-rs)
- [suppaftp](https://github.com/veeso/suppaftp)
- [tui-rs](https://github.com/fdehau/tui-rs)
- [tui-realm](https://github.com/veeso/tui-realm)
- [whoami](https://github.com/libcala/whoami)
- [wildmatch](https://github.com/becheran/wildmatch)
---
## 画廊 🎬
>
![Auth](/assets/images/auth.gif)
> 书签
![Bookmarks](/assets/images/bookmarks.gif)
> 设置
![Setup](/assets/images/config.gif)
> 文本编辑器
![TextEditor](/assets/images/text-editor.gif)
---
## 执照 📃
“termscp”在 MIT 许可下获得许可。
您可以阅读整个许可证 [这里](../../LICENSE)

530
docs/zh-CN/man.md Normal file
View File

@@ -0,0 +1,530 @@
# 操作指南 🎓
- [操作指南 🎓](#操作指南-)
- [用法](#用法)
- [地址参数](#地址参数)
- [AWS S3 地址参数](#aws-s3-地址参数)
- [如何输入密码](#如何输入密码)
- [S3 连接参数](#s3-连接参数)
- [Aws S3 凭证](#aws-s3-凭证)
- [文件浏览](#文件浏览)
- [快捷键](#快捷键)
- [处理多个文件](#处理多个文件)
- [同步浏览](#同步浏览)
- [打开/打开方式](#打开打开方式)
- [书签](#书签)
- [我的密码安全吗?](#我的密码安全吗)
- [Linux Keyring](#linux-keyring)
- [用于 termscp 的 KeepassXC 设置](#用于-termscp-的-keepassxc-设置)
- [配置](#配置)
- [SSH Key Storage](#ssh-key-storage)
- [资源管理器格式](#资源管理器格式)
- [主题](#主题)
- [样式](#样式)
- [我的主题无法加载](#我的主题无法加载)
- [登录页](#登录页)
- [文件传输页](#文件传输页)
- [Misc](#misc)
- [文本编辑器](#文本编辑器)
- [日志](#日志)
- [通知](#通知)
- [文件观察者🔭](#文件观察者)
## 用法
termscp启动时可以使用以下选项:
`termscp [options]... [protocol://user@address:port:wrkdir] [local-wrkdir]`
或作为
`termscp [options]... -b [bookmark-name] [local-wrkdir]`
- `-P, --password <password>` 登陆密码
- `-b, --address-as-bookmark` 将地址参数解析为书签名称
- `-c, --config` 打开termscp时打开配置页面
- `-q, --quiet` 禁用日志
- `-t, --theme <path>` 导入自定义主题
- `-v, --version` 打印版本信息
- `-h, --help` 打开帮助
termscp有两种不同的启动模式不带参数时termscp将显示登录表单页用户可以填写连接到远程服务端所需的参数。
或者用户可以提供一个url作为参数跳过认证页直接与远程服务器进行连接。
如果提供了url参数你也可以提供本地主机的起始工作目录。
### 地址参数
地址参数的格式如下:
```txt
[protocol://][username@]<address>[:port][:wrkdir]
```
让我们通过一些例子熟悉这个特殊语法,它很好上手,你会很快习惯并且替代其他工具......
- 使用默认协议(*在配置中定义*连接到192.168.1.31,如果没有提供端口,则为所选协议的默认端口(取决于你的配置);用户名是系统当前用户名
```sh
termscp 192.168.1.31
```
- 使用默认协议(*在配置中定义*连接到192.168.1.31,用户名为`root`
```sh
termscp root@192.168.1.31
```
- 使用scp连接到192.168.1.31, 端口号为4022; 用户名为 `omar`
```sh
termscp scp://omar@192.168.1.31:4022
```
- 使用scp连接到192.168.1.31, 端口号为4022; 用户名为 `omar`。工作目录为 `/tmp`
```sh
termscp scp://omar@192.168.1.31:4022:/tmp
```
#### AWS S3 地址参数
出于显而易见的原因Aws S3 对 CLI 地址参数有不同的语法,但我设法使其与通用地址参数尽可能相似:
```txt
s3://<bucket-name>@<region>[:profile][:/wrkdir]
```
例如
```txt
s3://buckethead@eu-central-1:default:/assets
```
#### 如何输入密码
你可能已经注意到url参数中没有办法直接附加密码你可以通过以下三种方式提供密码
- `-P, --password` 不推荐直接在参数中填写明文密码。强烈不推荐这种方法因为它非常不安全因为你可能会把密码保留在shell历史记录中
- 通过 `sshpass`: 你可以通过 `sshpass` 传入密码, 例如: `sshpass -f ~/.ssh/topsecret.key termscp cvisintin@192.168.1.31`
- 提示输入密码:如果你不使用前面的任何方法,你会被提示输入密码,就像 `scp`、`ssh` 等比较经典的工具上一样。
---
## S3 连接参数
这些参数是连接到 aws s3 和其他 s3 兼容服务器所必需的:
- AWS S3:
- **bucket name**
- **region**
- *profile* (如果未提供“default”)
- *access key* (除非公开)
- *secret access key* (除非公开)
- *security token* (如果需要的话)
- *session token* (如果需要的话)
- new path style: **NO**
- 其他 S3 端点:
- **bucket name**
- **endpoint**
- *access key* (如果需要的话)
- *secret access key* (如果需要的话)
- new path style: **YES**
### Aws S3 凭证
为了连接到 Aws S3 存储桶,您显然必须提供一些凭据。
因此,您可以通过以下方式为 s3 提供凭据:
1. 认证形式:
1. 您可以提供 `access_key`(应该是强制性的)、`secret_access_key`(应该是强制性的)、`security_token` 和`session_token`
2. 如果您将 s3 连接保存为书签,这些凭据将在您的书签文件中保存为加密的 AES-256/BASE64 字符串(安全令牌和会话令牌除外,它们是临时凭据)。.
2. 使用您的凭证文件:只需通过`aws configure` 配置AWS cli您的凭证应该已经位于`~/.aws/credentials`。 如果您使用的配置文件不同于“默认”,只需在身份验证表单的配置文件字段中提供它。
3. **环境变量**: 您始终可以将您的凭据作为环境变量提供。 请记住,这些凭据**将始终覆盖**位于 `credentials` 文件中的凭据。 下面看看如何配置环境:
这些应该始终是强制性的:
- `AWS_ACCESS_KEY_ID`: aws 访问密钥 ID通常以 `AKIA...` 开头)
- `AWS_SECRET_ACCESS_KEY`: 秘密访问密钥
如果您配置了更强的安全性,您*可能*也需要这些:
- `AWS_SECURITY_TOKEN`: 安全令牌
- `AWS_SESSION_TOKEN`: 会话令牌
⚠️ 您的凭据是安全的termscp 不会直接操作这些值! 您的凭据直接由 **s3** crate 使用。
如果您对安全有一些担忧,请联系 [Github](https://github.com/durch/rust-s3) 上的库作者 ⚠️
---
## 文件浏览
termscp中的文件资源管理器是指你与远程建立连接后可以看到的面板。
面板由3个部分组成是的就这三个
- 本地资源管理器面板它显示在你的屏幕左侧显示localhost的当前目录文件列表。
- 远程资源管理器面板:它显示在你屏幕的右边,显示远程主机的当前目录文件列表。
- 查找结果面板:根据你搜索文件的位置(本地/远程),它将取代对应资源管理器面板。这个面板显示与你执行的搜索查询相匹配的条目。
为了切换面板,你需要输入 `<LEFT>` 来移动远程资源管理器面板,`<RIGHT>` 来移动回本地资源管理器面板。当在查找结果面板时,你需要按`<ESC>`来退出面板,回到前一个面板。
### 快捷键
| 按键 | 命令 | 助记词 |
|---------------|-------------------------------------------------------|-------------|
| `<ESC>` | 断开远程连接;回到登录页 | |
| `<BACKSPACE>` | 返回上一次目录 | |
| `<TAB>` | 切换资源管理器选项卡 | |
| `<RIGHT>` | 切换到远程管理器面板 | |
| `<LEFT>` | 切换到本地管理器面板 | |
| `<UP>` | 在当前列表中向上移动光标 | |
| `<DOWN>` | 在当前列表中向下移动光标 | |
| `<PGUP>` | 在当前列表中光标上移8行 | |
| `<PGDOWN>` | 在当前列表中光标下移8行 | |
| `<ENTER>` | 进入文件夹 | |
| `<SPACE>` | 上传 / 下载选中文件 | |
| `<BACKTAB>` | 在日志面板和管理器面板之间切换 | |
| `<A>` | 是否显示隐藏文件 | All |
| `<B>` | 按..排序 | Bubblesort? |
| `<C|F5>` | 复制文件(夹) | Copy |
| `<D|F7>` | 创建文件夹 | Directory |
| `<E|F8|DEL>` | 删除文件 | Erase |
| `<F>` | 文件搜索 (支持通配符) | Find |
| `<G>` | 跳转到指定路径 | Go to |
| `<H|F1>` | 显示帮助 | Help |
| `<I>` | 显示选中文件(夹)信息 | Info |
| `<K>` | 创建指向当前选定条目的符号链接 | symlinK |
| `<L>` | 刷新当前目录列表 / 清除选中状态 | List |
| `<M>` | 选中文件 | Mark |
| `<N>` | 使用键入的名称新建文件 | New |
| `<O|F4>` | 编辑文件;参考文本编辑器文档 | Open |
| `<Q|F10>` | 退出termscp | Quit |
| `<R|F7>` | 重命名文件 | Rename |
| `<S|F2>` | 另存为... | Save |
| `<T>` | 显示所有同步路径 | Track |
| `<U>` | 进入上层目录 | Upper |
| `<V|F3>` | 使用默认方式打开文件 | View |
| `<W>` | 使用指定程序打开文件 | With |
| `<X>` | 运行命令 | eXecute |
| `<Y>` | 是否开启同步浏览 | sYnc |
| `<CTRL+A>` | 选中所有文件 | |
| `<CTRL+C>` | 终止文件传输 | |
| `<CTRL+T>` | 显示所有同步路径 | Track |
### 处理多个文件
你可以同时操作多个文件,按`<M>`选定它们,或者按`<CTRL+A>` 全选当前工作目录中的所有文件。一旦一个文件被标记为选择,它将在左边显示一个 "*"。在这种模式下,只有选定的文件会被处理,而当前光标高亮显示的项目会被忽略。在查找结果面板中,也可以对多个文件进行处理。
在处理多个文件时,所有的操作都是可用的,但请注意,有些操作的工作方式略有不同。让我们深入了解一下:
- *复制*: 当你复制一个文件时,你会被提示输入完整目标路径名。当处理多个文件时,这个名称指的是所有这些文件将被复制到的目标目录。
- *重命名*: 和复制操作类似, 但是会移动文件到目标路径。
- *保存为*: 和复制操作类似, 但是会写入文件到目标路径。
### 同步浏览
启用时,同步浏览将允许你在两个面板之间同步导航操作。这意味着,每当你在一个面板上改变工作目录时,同样的动作会在另一个面板上重现。如果你想启用同步浏览,只需按下`<Y>`;按两次就可以禁用。当启用时,同步浏览的状态将在状态栏上显示为`ON`。
### 打开/打开方式
打开和打开方式的功能是由 [open-rs](https://docs.rs/crate/open/2.1.0)提供的。
执行视图命令(`<V>`)时,关联该文件类型的系统默认应用程序会被调用以打开当前文件。这依赖于操作系统默认的服务,所以要确保你的系统中至少安装了一个这样的服务:
- **Windows** 用户: 无需额外操作,程序内部会调用 `start` 命令。
- **MacOS** 用户: 同样无需额外操作,程序内部会调用系统内置的 `open` 命令。
- **Linux** 用户: 以下程序之一需要被安装:
- *xdg-open*
- *gio*
- *gnome-open*
- *kde-open*
- **WSL** 用户: *wslview* 是必要的,你需要安装 [wslu](https://github.com/wslutilities/wslu).
> Q: 我可以使用V命令编辑远程文件吗
> A: 不可以,至少不能在 "远程管理面板 "上直接操作。你必须先把它下载到本地目录这是由于当你打开一个远程文件时该文件会被下载到一个临时目录中但没有办法监控这个文件的状态同时也无法得知你用来打开它的程序何时被关闭。也就是说termscp无法获知你何时完成对该文件的编辑。
---
## 书签
在termscp中你可以保存常用的服务器随后可以从termscp的主界面中快速连接到这些服务器。termscp也会在历史记录中保存你最后连接的16个主机。这个功能保留了连接到某个远程服务器的所有参数只需在登录页下方的Tab中选中书签即可。
书签会尝试被保存在以下路径:
- `$HOME/.config/termscp/` -- Linux/BSD
- `$HOME/Library/Application Support/termscp` -- MacOs
- `FOLDERID_RoamingAppData\termscp\` -- Windows
对于书签(不包括服务器连接历史记录)而言,也可以保存用于验证的密码。注意默认情况下不保存密码,必须在保存新书签时通过提示指定密码。
如果您担心为您的书签保存的密码的安全性,请阅读[以下章节](#我的密码安全吗?)👀
请按照以下步骤新建书签:
1. 在认证页中输入待连接服务器的参数
2.`<CTRL+S>`
3. 输入书签名称
4. 选择是否保留密码
5.`<ENTER>` 提交
无论何时你想使用以前保存的连接,只需按下`<TAB>`导航到书签列表,然后按`<ENTER>`将书签参数加载到表格中。
![Bookmarks](https://github.com/veeso/termscp/blob/main/assets/images/bookmarks.gif?raw=true)
### 我的密码安全吗?
这是当然 😉。
如前所述,书签与密码一起保存在你的配置目录中。密码显然不是纯文本,它们是用**AES-128**加密的。这够不够安全?绝对够 (BSD和WSL用户除外😢)
在**Windows**、**Linux**和**MacOS**上,如果可能的话(但应该是),密码会被分别存储在*Windows Vault*、*系统钥匙串*和*Keychain*中。这实际上是超级安全的,并且是由你的操作系统直接管理的。
❗请注意如果你是一个Linux用户你真的应该阅读[下面的章节👀](#linux-keyring),因为你的系统可能没有启用或支持钥匙串功能
另一方面,在*BSD*和*WSL*上,用于加密密码的密钥是存储在你的驱动器上的(在$HOME/.config/termscp。那么仍然有可能检索到密钥来解密密码。幸运的是密钥的位置保证了你的密钥不能被与你不同的用户读取但是是的我仍然不会为暴露在互联网上的服务器保存密码😉。
#### Linux Keyring
我们都喜欢Linux因为它给了用户自由。作为一个Linux用户你基本上可以做任何你想做的事情但这也有一些缺点比如说不同的发行版之间往往没有标准的应用程序。这也涉及到钥匙串。
这意味着在Linux上你的系统可能没有安装钥匙串。不幸的是我们用来处理钥匙存储的库需要一个在D-BUS上公开`org.freedesktop.secrets`的服务,而最糟糕的事实是,只有两个服务在公开它。
- ❗ 如果你使用GNOME作为桌面环境例如ubuntu用户那么你是幸运的因为钥匙串已经由`gnome-keyring`提供,一切都应该已经准备就绪了。
- ❗对于其他桌面环境的用户,有一个很好的程序,你可以用它来获得钥匙串,这就是[KeepassXC](https://keepassxc.org/)我在我的Manjaro中使用它带KDE一切都很正常。唯一的问题是你必须设置它与termscp一起使用但这很简单。要开始使用KeepassXC请阅读更多[这里]#keepassxc-setup-for-termscp
- ❗如果你不想安装任何这些服务呢?好吧,这没有问题! **termscp依然能正常工作**但它会将密钥保存在一个文件中就像它通常为BSD和WSL做的那样。
##### 用于 termscp 的 KeepassXC 设置
参照以下步骤为termscp配置keepassXC
1. 安装KeepassXC
2. 进入工具栏的 "工具">"设置"。
3. 选择 "秘密服务集成 "并切换 "启用KeepassXC freedesktop.org secret服务集成"
4. 创建一个数据库,如果你还没有:在工具栏的 "数据库">"新数据库"
5. 从工具条上 "数据库" > "数据库设置"
6. 选择 "secret服务集成 "并切换 "在此组下暴露条目"
7. 7.在列表中选择你希望termscp secret保存到的组。记住这个组可能被任何其他应用程序通过DBUS存储密钥。
---
## 配置
termscp支持一些用户定义参数这些参数可以通过配置来修改。
termscp有一个TOML文件和一些其他的目录所有的参数都会被保存在这些目录中但是不用担心你不必手动编辑这些文件因为我为termscp制作了可交互的用户界面。
termscp和书签一样只需要保证这些路径是可访问的
- `$HOME/.config/termscp/` -- Linux/BSD
- `$HOME/Library/Application Support/termscp` -- MacOs
- `FOLDERID_RoamingAppData\termscp\` -- Windows
要访问配置你只需在termscp的主界面上按`<CTRL+C>`
这些参数可以自定义:
- **Text Editor**使用的文本编辑器。默认情况下termscp将为你找到默认的编辑器通过这个选项你可以强制使用一个编辑器`vim`)。**也支持GUI编辑器**,除非它们从父进程中`nohup`。所以,如果这是你的问题:是的,你可以使用`notepad.exe`,然而,**Visual Studio Code不工作**。
- **Default Protocol**默认协议是termscp中默认使用的文件传输协议。这适用于登录页和地址中的CLI参数。
- **Show Hidden Files**:选择是否应默认显示隐藏文件。你可以在运行时按 `A` 来切换是否显示隐藏的文件。
- **Check for updates**:如果设置为 `yes`termscp将通过Github API检查是否有新版本的termscp。
- **Prompt when replacing existing files?**: 如果设置为 `yes`则在文件传输会导致目标主机上的现有文件被替换时termscp 将提示您确认。
- **Group Dirs**:选择在文件浏览器中是否对文件夹进行分组。如果选择 `Display first`,目录将根据设置的方法排序,但仍显示在文件之前;如果选择 `Display last`,则正好相反。
- **Remote File formatter syntax**:在远程资源管理器中为每个文件显示文件信息的语法。参见[资源管理器格式](#资源管理器格式)
- **Local File formatter syntax**:在本地资源管理器中显示每个文件的文件信息的语法。参见[资源管理器格式](#资源管理器格式)
- **Enable notifications?**: 如果设置为 `Yes`,则会显示通知。
- **Notifications: minimum transfer size**: 如果传输大小大于或等于指定值,将显示传输通知。 接受的值格式为 `{UNSIGNED} B/KB/MB/GB/TB/PB`
- **SSH Configuration path**:设置连接到 SCP/SFTP 服务器时使用的 SSH 配置文件。 如果未设置(空),则不会使用任何文件。 你可以指定一个以 `~` 开头的路径来表示主路径(例如 `~/.ssh/config`
### SSH Key Storage
配置选项还包括termscp为**SFTP/SCP客户端**提供的一个**必要**功能SSH密钥存储。
你可以从配置中切换到到 `SSH Keys` tab页来访问SSH密钥存储在那里你可以
- **添加新密钥**:只需按下`<CTRL+N>`,你将被提示创建一个新的密钥。提供主机名/ip地址和与该钥匙关联的用户名最后会打开一个文本编辑器将**PRIVATE** SSH key粘贴到文本编辑器中保存并退出。
- **删除现有密钥**:只要在你想删除的密钥上按下`<DEL>``<CTRL+E>`,就可以从 termscp 中永久删除该密钥。
- **编辑现有密钥**:只需在你想编辑的密钥上按下`<ENTER>`,就可以修改私钥。
> 问:等等,我的私钥受密码保护,也是可以用的吗?
> 当然可以。termscp中提供的认证密码对用户名/密码认证和RSA密钥认证都有效。
### 资源管理器格式
可以为文件浏览器配置自定义的格式,本地和远程主机允许进行单独设定,所以你可以使用两种不同的语法。这些字段的名称为 `File formatter syntax (local)``File formatter syntax (remote)`,将定义文件条目如何在文件资源管理器中显示。
格式化的语法如下 `{KEY1}... {KEY2:LENGTH}... {KEY3:LENGTH:EXTRA} {KEYn}...`
花括号内的每个键将被替换成相关的属性,而括号外的所有内容将保持不变。
- 键名是固定的,必须是下面的关键字之一
- 长度指定了为显示该字段而保留的长度。静态属性不支持这个参数GROUP、PEX、SIZE、USER
- Extra只被一些特定字段支持也是可选的。请看各字段详细描述来判断是否支持Extra参数。
以下是自定义格式支持的键名:
- `ATIME`: 最后访问时间(默认语法为`%b %d %Y %H:%M`Extra参数可以指定时间显示语法例如`{ATIME:8:%H:%M}`
- `CTIME`: 创建时间(语法为`%b %d %Y %H:%M`Extra参数可以指定时间显示语法例如`{CTIME:8:%H:%M}`
- `GROUP`: 所属组
- `MTIME`: 最后修改时间(语法为`%b %d %Y %H:%M`Extra参数可以指定时间显示语法例如`{MTIME:8:%H:%M}`
- `NAME`: 文件名(超过 LENGTH 个字符的部分会被省略)
- `PATH`:文件绝对路径(如果长于 LENGTH则根目录和第一个祖先之间的文件夹将被排除
- `PEX`: 文件权限UNIX格式
- `SIZE`: 文件大小(目录不显示)
- `SYMLINK`: 超链接(如果存在的话`-> {FILE_PATH}`)。
- `USER`: 所属用户
如果留空,将使用默认的格式化语法。`{NAME:24} {PEX} {USER} {SIZE} {MTIME:17:%b %d %Y %H:%M}`
---
## 主题
Termscp为你提供了一个很棒的功能可以为应用程序中的几个组件配置颜色。
如果你想自定义termscp有两种可用的途径
- 从**配置菜单**
- 导入一个**配置文件**
为了从termscp创建你的私人定制你所要做的就是从auth活动页进入配置`<CTRL+C>`,然后`<TAB>`两次。你现在应该已经移到了 `themes` 面板。
在这里你可以用`<UP>``<DOWN>`移动来选择你想改变的样式,如下图所示:
![Themes](https://github.com/veeso/termscp/blob/main/assets/images/themes.gif?raw=true)
termscp支持传统的十六进制`#rrggbb`和RGB`rgb(r, g, b)`语法来表示颜色,但也接受 **[css颜色](https://www.w3schools.com/cssref/css_colors.asp)**(如`crimson`)😉。还有一个特殊的关键词是`Default`,意味着使用的颜色将是基于情景的默认前景或背景颜色(文本和线条的前景色,以及容器的背景色,你猜是什么)。
如前所述你也可以导入主题文件。你可以从themscp提供的主题中获取灵感或直接使用其中的一个位于这个代码仓库的`themes/`目录下运行themscp以导入它们 `termscp -t <theme_file>`。最后,如果一切正常,它应该提示你主题已经成功导入。
### 样式
你可以在下面的表格中找到每个样式字段的描述。
请注意,**样式在配置页面不起作用**,以保证它总是可以访问,以防你把一切都弄乱了。
### 我的主题无法加载
这可能是由于最近的更新破坏了主题。 每当我向主题添加新密钥时,保存的主题都不会加载。 要解决此问题,有两个真正的快速修复解决方案:
1. 重新加载主题:每当我发布更新时,我也会修补“官方”主题,因此您只需再次从存储库下载它并通过 `-t` 选项重新导入主题
```sh
termscp -t <theme.toml>
```
2. 修复您的主题:如果您使用自定义主题,那么您可以通过 `vim` 进行编辑并添加缺少的键。 主题位于 `$CONFIG_DIR/termscp/theme.toml`,其中 `$CONFIG_DIR` 是:
- FreeBSD/GNU-Linux: `$HOME/.config/`
- MacOs: `$HOME/Library/Application Support`
- Windows: `%appdata%`
❗ 对于您刚刚安装的版本,在 `BREAKING CHANGES` 下的 `CHANGELOG` 中报告了丢失的键。
#### 登录页
| 字段 | 描述 |
|----------------|------------------------------------------|
| auth_address | IP地址输入框的颜色 |
| auth_bookmarks | 书签面板的颜色 |
| auth_password | 密码输入框的颜色 |
| auth_port | 端口输入框的颜色 |
| auth_protocol | 协议选项组的颜色 |
| auth_recents | 历史记录面板的颜色 |
| auth_username | 用户名输入框的颜色 |
#### 文件传输页
| 字段 | 描述 |
|--------------------------------------|---------------------------------------------------------------------------|
| transfer_local_explorer_background | 本地资源浏览器的背景色 |
| transfer_local_explorer_foreground | 本地资源浏览器的前景色 |
| transfer_local_explorer_highlighted | 本地资源浏览器的边框和高亮色 |
| transfer_remote_explorer_background | 远程资源浏览器的背景色 |
| transfer_remote_explorer_foreground | 远程资源浏览器的前景色 |
| transfer_remote_explorer_highlighted | 远程资源浏览器的边框和高亮色 |
| transfer_log_background | 日志面板的背景色 |
| transfer_log_window | 日志面板的窗口颜色 |
| transfer_progress_bar_partial | 进度条完成部分颜色 |
| transfer_progress_bar_total | 进度条背景色颜色 |
| transfer_status_hidden | 状态栏 "hidden" 标签的颜色 |
| transfer_status_sorting | 状态栏 "sorting" 标签的颜色;同时适用于文件排序对话框 |
| transfer_status_sync_browsing | 状态栏 "sync browsing" 标签的颜色 |
#### Misc
以下这些样式会在程序不同的位置起作用:
| 字段 | 描述 |
|-------------------|---------------------------------------------|
| misc_error_dialog | 报错信息的颜色 |
| misc_info_dialog | 信息对话框的颜色 |
| misc_input_dialog | 输入对话框的颜色(比如拷贝文件时) |
| misc_keys | 键盘输入文字的颜色 |
| misc_quit_dialog | 退出窗口的颜色 |
| misc_save_dialog | 保存窗口的颜色 |
| misc_warn_dialog | 警告窗口的颜色 |
---
## 文本编辑器
Termscp有很多功能你可能已经注意到了其中之一就是可以查看和编辑文本文件。不管文件是在本地主机还是在远程主机上termscp都提供了在你喜欢的文本编辑器中打开文件的功能。
如果文件位于远程主机上,该文件将首先被下载到你的临时文件目录中,然后,**只有**在对该文件进行了修改的情况下,才会重新上传至远程主机上。
> ❗ 多说一句,**你只能编辑文本文件**;二进制文件是不可以的。
---
## 日志
termscp会为每个会话创建一个日志文件该文件在
- `$HOME/.config/termscp/termscp.log` -- Linux/BSD
- `$HOME/Library/Application Support/termscp/termscp.log` -- MacOs
- `FOLDERID_RoamingAppData\termscp\termscp.log` -- Windows
日志不会被轮换,但只会在每次启动 termcp 后被截断,因此如果您想报告问题并希望附加您的日志文件,请记住在使用前将日志文件保存在安全的地方 再次termscp。
默认情况下,日志记录在 *INFO* 级别报告,因此它不是很详细。
如果你想提交一个问题,如果可以的话,请在级别设置为`TRACE`的情况下重现问题为此启动termscp
`-D` CLI 选项。
我知道您可能对日志文件有一些疑问,所以我做了一个问答:
> 我不希望有日志记录,我可以把它关掉吗?
可以的。只要用`-q or --quiet`选项启动termscp。你可以用别名来启动termscp从而使这个选项一直生效。记住日志是用来诊断故障的所以在每个开源项目的背后都应该有这样的互动反馈保留日志文件可能是你支持项目的途径😉。我不想让你感到内疚只是想提一句。
> 日志是安全的吗?
如果你担心安全问题,日志文件不包含任何普通的密码,所以不用担心,它暴露的信息与同级文件 `书签` 报告的信息相同。
## 通知
termscp 将针对这些类型的事件发送桌面通知:
- **传输完成** 传输成功完成后将发送通知。
- ❗ 仅当传输总大小至少为配置中指定的 `Notifications: minimum transfer size` 时才会显示通知。
- **传输失败**:一旦传输因错误而失败,将发送通知。
- ❗ 仅当传输总大小至少为配置中指定的 `Notifications: minimum transfer size` 时才会显示通知。
- **更新可用**每当有新版本的termscp 可用时,都会显示通知。
- **更新已安装**每当安装了新版本的termscp 时,都会显示通知。
- **更新失败**:每当更新安装失败时,都会显示通知。
❗ 如果您希望保持关闭通知,您只需进入设置并将 `Enable notifications?` 设置为 `No`😉。
❗ 如果您想更改最小传输大小以显示通知,您可以使用键 `Notifications: minimum transfer size` 更改配置中的值,并将其设置为更适合您的任何值🙂。
## 文件观察者🔭
文件观察器允许您设置与远程主机同步的路径列表。
这意味着每当在同步路径上检测到本地文件系统的更改时,该更改将在 5 秒内自动报告给配置的远程主机路径。
您可以根据需要设置尽可能多的同步路径:
1.将光标放在本地资源管理器上要保持同步的目录/文件上
2. 转到远程主机上要向其报告更改的目录
3. 按`<T>`
4. 对无线电弹出窗口回答 `<YES>`
要取消观看,只需在本地同步路径(或其任何子文件夹)上按 `<T>`
或者,您可以按 `<CTRL + T>` 并按 `<ENTER>` 进入要取消观看的同步路径。
这些更改将报告给远程主机:
- 新文件,文件更改
- 文件移动/重命名
- 文件删除/取消链接
> ❗ 观察者只在一个方向工作(本地>远程)。不可能自动同步远程到本地的更改。

View File

@@ -8,10 +8,9 @@
# -f, -y, --force, --yes
# Skip the confirmation prompt during installation
TERMSCP_VERSION="0.5.1"
TERMSCP_VERSION="0.9.0"
GITHUB_URL="https://github.com/veeso/termscp/releases/download/v${TERMSCP_VERSION}"
DEB_URL="${GITHUB_URL}/termscp_${TERMSCP_VERSION}_amd64.deb"
FREEBSD_URL="${GITHUB_URL}/termscp-${TERMSCP_VERSION}.txz"
RPM_URL="${GITHUB_URL}/termscp-${TERMSCP_VERSION}-1.x86_64.rpm"
set -eu
@@ -81,6 +80,17 @@ download() {
return $rc
}
test_writeable() {
local path
path="${1:-}/test.txt"
if touch "${path}" 2>/dev/null; then
rm "${path}"
return 0
else
return 1
fi
}
elevate_priv() {
if ! has sudo; then
error 'Could not find the command "sudo", needed to install termscp on your system.'
@@ -95,15 +105,16 @@ elevate_priv() {
fi
}
test_writeable() {
local path
path="${1:-}/test.txt"
if touch "${path}" 2>/dev/null; then
rm "${path}"
return 0
else
return 1
fi
elevate_priv_ex() {
check_dir="$1"
if test_writeable "$check_dir"; then
sudo=""
else
warn "Root permissions are required to install dependecies"
elevate_priv
sudo="sudo"
fi
echo $sudo
}
# Currently supporting:
@@ -171,87 +182,83 @@ confirm() {
# Installers
install_on_bsd() {
info "Installing termscp via FreeBSD pkg"
archive=$(get_tmpfile "txz")
download "${archive}" "${FREEBSD_URL}"
info "Downloaded FreeBSD package to ${archive}"
if test_writeable "/usr/local/bin"; then
sudo=""
msg="Installing termscp, please wait…"
else
warn "Root permissions are required to install termscp…"
elevate_priv
sudo="sudo"
msg="Installing termscp as root, please wait…"
try_with_cargo "packages for freeBSD are distribuited no more. Only cargo installations are supported."
}
install_on_arch_linux() {
pkg="$1"
info "Detected ${YELLOW}${pkg}${NO_COLOR} on your system"
# check if rust is already installed
has cargo
CARGO=$?
if [ $CARGO -ne 0 ]; then
confirm "${YELLOW}rust${NO_COLOR} is required to install ${GREEN}termscp${NO_COLOR}; would you like to proceed?"
$pkg -S rust
fi
info "$msg"
$sudo pkg install "${archive}"
info "Installing ${GREEN}termscp${NO_COLOR} AUR package…"
$pkg -S termscp
}
install_on_linux() {
local msg
local sudo
local archive
if [ "${ARCH}" != "x86_64" ]; then
try_with_cargo "we don't distribute packages for ${ARCH} at the moment"
elif has yay; then
info "Detected yay on your system"
info "Installing termscp AUR package"
yay -S termscp
if has yay; then
install_on_arch_linux yay
elif has pakku; then
info "Detected pakku on your system"
info "Installing termscp AUR package"
pakku -S termscp
install_on_arch_linux pakku
elif has paru; then
info "Detected paru on your system"
info "Installing termscp AUR package"
paru -S termscp
install_on_arch_linux paru
elif has aurutils; then
info "Detected aurutils on your system"
info "Installing termscp AUR package"
aurutils -S termscp
install_on_arch_linux aurutils
elif has pamac; then
info "Detected pamac on your system"
info "Installing termscp AUR package"
pamac -S termscp
install_on_arch_linux pamac
elif has pikaur; then
info "Detected pikaur on your system"
info "Installing termscp AUR package"
pikaur -S termscp
install_on_arch_linux pikaur
elif has dpkg; then
info "Detected dpkg on your system"
info "Installing termscp via Debian package"
archive=$(get_tmpfile "deb")
download "${archive}" "${DEB_URL}"
info "Downloaded debian package to ${archive}"
if test_writeable "/usr/bin"; then
sudo=""
msg="Installing termscp, please wait…"
if [ "${ARCH}" != "x86_64" ]; then # It's okay on AUR; not on other distros
try_with_cargo "we don't distribute packages for ${ARCH} at the moment"
else
warn "Root permissions are required to install termscp…"
elevate_priv
sudo="sudo"
msg="Installing termscp as root, please wait…"
info "Detected dpkg on your system"
info "Installing ${GREEN}termscp${NO_COLOR} via Debian package"
archive=$(get_tmpfile "deb")
download "${archive}" "${DEB_URL}"
info "Downloaded debian package to ${archive}"
if test_writeable "/usr/bin"; then
sudo=""
msg="Installing ${GREEN}termscp${NO_COLOR}, please wait…"
else
warn "Root permissions are required to install ${GREEN}termscp${NO_COLOR}"
elevate_priv
sudo="sudo"
msg="Installing ${GREEN}termscp${NO_COLOR} as root, please wait…"
fi
info "$msg"
$sudo dpkg -i "${archive}"
rm -f ${archive}
fi
info "$msg"
$sudo dpkg -i "${archive}"
elif has rpm; then
info "Detected rpm on your system"
info "Installing termscp via RPM package"
archive=$(get_tempfile "rpm")
download "${archive}" "${RPM_URL}"
info "Downloaded rpm package to ${archive}"
if test_writeable "/usr/bin"; then
sudo=""
msg="Installing termscp, please wait…"
if [ "${ARCH}" != "x86_64" ]; then # It's okay on AUR; not on other distros
try_with_cargo "we don't distribute packages for ${ARCH} at the moment"
else
warn "Root permissions are required to install termscp…"
elevate_priv
sudo="sudo"
msg="Installing termscp as root, please wait…"
info "Detected rpm on your system"
info "Installing ${GREEN}termscp${NO_COLOR} via RPM package"
archive=$(get_tmpfile "rpm")
download "${archive}" "${RPM_URL}"
info "Downloaded rpm package to ${archive}"
if test_writeable "/usr/bin"; then
sudo=""
msg="Installing ${GREEN}termscp${NO_COLOR}, please wait…"
else
warn "Root permissions are required to install ${GREEN}termscp${NO_COLOR}"
elevate_priv
sudo="sudo"
msg="Installing ${GREEN}termscp${NO_COLOR} as root, please wait…"
fi
info "$msg"
$sudo rpm -U "${archive}"
rm -f ${archive}
fi
info "$msg"
$sudo rpm -U "${archive}"
else
try_with_cargo "No suitable installation method found for your Linux distribution; if you're running on Arch linux, please install an AUR package manager (such as yay). Currently only Arch, Debian based and Red Hat based distros are supported"
fi
@@ -259,24 +266,112 @@ install_on_linux() {
install_on_macos() {
if has brew; then
if has termscp; then
info "Upgrading termscp..."
# The OR is used since someone could have installed via cargo previously
brew update && brew upgrade termscp || brew install veeso/termscp/termscp
# get homebrew formula name
if [ "${ARCH}" == "x86_64" ]; then
FORMULA="termscp"
else
info "Installing termscp..."
brew install veeso/termscp/termscp
FORMULA="termscp-m1"
fi
if has termscp; then
info "Upgrading ${GREEN}termscp${NO_COLOR}"
# The OR is used since someone could have installed via cargo previously
brew update && brew upgrade ${FORMULA} || brew install veeso/termscp/${FORMULA}
else
info "Installing ${GREEN}termscp${NO_COLOR}"
brew install veeso/termscp/${FORMULA}
fi
else
try_with_cargo "brew is missing on your system; please install it from <https://brew.sh/>"
fi
}
# -- cargo installation
install_bsd_cargo_deps() {
set -e
confirm "${YELLOW}libssh, gcc${NO_COLOR} are required to install ${GREEN}termscp${NO_COLOR}; would you like to proceed?"
sudo="$(elevate_priv_ex /usr/local/bin)"
$sudo pkg install -y curl wget libssh gcc dbus pkgconf
info "Dependencies installed successfully"
}
install_linux_cargo_deps() {
local debian_deps="gcc pkg-config libssl-dev libssh2-1-dev libdbus-1-dev"
local rpm_deps="gcc openssl pkgconfig libdbus-devel openssl-devel"
local arch_deps="gcc openssl pkg-config dbus"
local deps_cmd=""
# Get pkg manager
if has apt; then
deps_cmd="apt install -y $debian_deps"
elif has apt-get; then
deps_cmd="apt-get install -y $debian_deps"
elif has yum; then
deps_cmd="yum -y install $rpm_deps"
elif has dnf; then
deps_cmd="dnf -y install $rpm_deps"
elif has pacman; then
deps_cmd="pacman -S --noconfirm $arch_deps"
else
error "Could not find any suitable package manager for your linux distro 🙄"
error "Supported package manager are: 'apt', 'apt-get', 'yum', 'dnf', 'pacman'"
exit 1
fi
set -e
confirm "${YELLOW}libssh, gcc, openssl, pkg-config, libdbus${NO_COLOR} are required to install ${GREEN}termscp${NO_COLOR}. The following command will be used to install the dependencies: '${BOLD}${YELLOW}${deps_cmd}${NO_COLOR}'. Would you like to proceed?"
sudo="$(elevate_priv_ex /usr/local/bin)"
$sudo $deps_cmd
info "Dependencies installed successfully"
}
install_cargo() {
if has cargo; then
return 0
fi
cargo_env="$HOME/.cargo/env"
# Check if cargo is already installed (actually), but not loaded
if [ -f $cargo_env ]; then
. $cargo_env
fi
# Check again cargo
if has cargo; then
return 0
else
confirm "${YELLOW}rust${NO_COLOR} is required to build termscp with cargo; would you like to install it now?"
set -e
rustup=$(get_tmpfile "sh")
info "Downloading rustup.sh…"
download "${rustup}" "https://sh.rustup.rs"
chmod +x $rustup
$rustup -y
rm -f ${archive}
info "Rust installed with success"
. $cargo_env
fi
}
try_with_cargo() {
err="$1"
# Install cargo
install_cargo
if has cargo; then
info "Installing termscp via Cargo..."
cargo install termscp
info "Installing ${GREEN}termscp${NO_COLOR} via Cargo"
case $PLATFORM in
"freebsd")
install_bsd_cargo_deps
cargo install --locked --no-default-features termscp
;;
"linux")
install_linux_cargo_deps
cargo install --locked termscp
;;
*)
cargo install --locked termscp
;;
esac
else
error "$err"
error "Alternatively you can opt for installing Cargo <https://www.rust-lang.org/tools/install>"
@@ -367,7 +462,7 @@ info "If you're a new user, you might be interested in reading the user manual <
info "While if you've just updated your termscp version, you can find the changelog at this link <https://veeso.github.io/termscp/#changelog>"
info "Remember that if you encounter any issue, you can report them on Github <https://github.com/veeso/termscp/issues/new>"
info "Feel free to open an issue also if you have an idea which could improve the project"
info "If you want to support the project, please, consider a little donation <https://www.buymeacoffee.com/veeso>"
info "If you want to support the project, please, consider a little donation <https://ko-fi.com/veeso>"
info "I hope you'll enjoy using termscp :D"
exit 0

View File

@@ -2,48 +2,28 @@
//!
//! `activity_manager` is the module which provides run methods and handling for activities
/**
* MIT License
*
* termscp - Copyright (c) 2021 Christian Visintin
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// Deps
use crate::filetransfer::FileTransferProtocol;
use crate::filetransfer::FileTransferParams;
use crate::host::{HostError, Localhost};
use crate::system::bookmarks_client::BookmarksClient;
use crate::system::config_client::ConfigClient;
use crate::system::environment;
use crate::system::theme_provider::ThemeProvider;
use crate::ui::activities::{
auth::AuthActivity, filetransfer::FileTransferActivity, setup::SetupActivity, Activity,
ExitReason,
};
use crate::ui::context::{Context, FileTransferParams};
use crate::ui::context::Context;
use crate::utils::fmt;
use crate::utils::tty;
// Namespaces
use std::path::{Path, PathBuf};
use std::thread::sleep;
use std::time::Duration;
/// ### NextActivity
///
/// NextActivity identified the next identity to run once the current has ended
/// NextActivity identifies the next identity to run once the current has ended
pub enum NextActivity {
Authentication,
FileTransfer,
@@ -55,58 +35,88 @@ pub enum NextActivity {
/// The activity manager takes care of running activities and handling them until the application has ended
pub struct ActivityManager {
context: Option<Context>,
interval: Duration,
ticks: Duration,
local_dir: PathBuf,
}
impl ActivityManager {
/// ### new
///
/// Initializes a new Activity Manager
pub fn new(local_dir: &Path, interval: Duration) -> Result<ActivityManager, HostError> {
pub fn new(local_dir: &Path, ticks: Duration) -> Result<ActivityManager, HostError> {
// Prepare Context
// Initialize configuration client
let (config_client, error): (Option<ConfigClient>, Option<String>) =
let (config_client, error_config): (ConfigClient, Option<String>) =
match Self::init_config_client() {
Ok(cli) => (Some(cli), None),
Ok(cli) => (cli, None),
Err(err) => {
error!("Failed to initialize config client: {}", err);
(None, Some(err))
(ConfigClient::degraded(), Some(err))
}
};
let ctx: Context = Context::new(config_client, error);
let (bookmarks_client, error_bookmark) = match Self::init_bookmarks_client() {
Ok(cli) => (cli, None),
Err(err) => (None, Some(err)),
};
let error = error_config.or(error_bookmark);
let theme_provider: ThemeProvider = Self::init_theme_provider();
let ctx: Context = Context::new(bookmarks_client, config_client, theme_provider, error);
Ok(ActivityManager {
context: Some(ctx),
local_dir: local_dir.to_path_buf(),
interval,
ticks,
})
}
/// ### set_filetransfer_params
///
/// Set file transfer params
pub fn set_filetransfer_params(
&mut self,
address: String,
port: u16,
protocol: FileTransferProtocol,
username: Option<String>,
password: Option<String>,
entry_directory: Option<PathBuf>,
) {
mut params: FileTransferParams,
password: Option<&str>,
) -> Result<(), String> {
// Set password if provided
if params.password_missing() {
if let Some(password) = password {
params.set_default_secret(password.to_string());
} else {
match tty::read_secret_from_tty("Password: ") {
Err(err) => return Err(format!("Could not read password: {}", err)),
Ok(Some(secret)) => {
debug!(
"Read password from tty: {}",
fmt::shadow_password(secret.as_str())
);
params.set_default_secret(secret);
}
Ok(None) => {}
}
}
}
// Put params into the context
self.context.as_mut().unwrap().ft_params = Some(FileTransferParams {
address,
port,
protocol,
username,
password,
entry_directory,
});
self.context.as_mut().unwrap().set_ftparams(params);
Ok(())
}
/// Resolve provided bookmark name and set it as file transfer params.
/// Returns error if bookmark is not found
pub fn resolve_bookmark_name(
&mut self,
bookmark_name: &str,
password: Option<&str>,
) -> Result<(), String> {
if let Some(bookmarks_client) = self.context.as_mut().unwrap().bookmarks_client_mut() {
match bookmarks_client.get_bookmark(bookmark_name) {
None => Err(format!(
r#"Could not resolve bookmark name: "{}" no such bookmark"#,
bookmark_name
)),
Some(params) => self.set_filetransfer_params(params, password),
}
} else {
Err(String::from(
"Could not resolve bookmark name: bookmarks client not initialized",
))
}
}
/// ### run
///
///
/// Loop for activity manager. You need to provide the activity to start with
/// Returns the exitcode
@@ -128,15 +138,13 @@ impl ActivityManager {
// -- Activity Loops
/// ### run_authentication
///
/// Loop for Authentication activity.
/// Returns when activity terminates.
/// Returns the next activity to run
fn run_authentication(&mut self) -> Option<NextActivity> {
info!("Starting AuthActivity...");
// Prepare activity
let mut activity: AuthActivity = AuthActivity::default();
let mut activity: AuthActivity = AuthActivity::new(self.ticks);
// Prepare result
let result: Option<NextActivity>;
// Get context
@@ -175,8 +183,6 @@ impl ActivityManager {
_ => { /* Nothing to do */ }
}
}
// Sleep for ticks
sleep(self.interval);
}
// Destroy activity
self.context = activity.on_destroy();
@@ -184,8 +190,6 @@ impl ActivityManager {
result
}
/// ### run_filetransfer
///
/// Loop for FileTransfer activity.
/// Returns when activity terminates.
/// Returns the next activity to run
@@ -200,15 +204,14 @@ impl ActivityManager {
}
};
// If ft params is None, return None
let ft_params: &FileTransferParams = match ctx.ft_params.as_ref() {
Some(ft_params) => &ft_params,
let ft_params: &FileTransferParams = match ctx.ft_params() {
Some(ft_params) => ft_params,
None => {
error!("Failed to start FileTransferActivity: file transfer params is None");
return None;
}
};
// Prepare activity
let protocol: FileTransferProtocol = ft_params.protocol;
let host: Localhost = match Localhost::new(self.local_dir.clone()) {
Ok(host) => host,
Err(err) => {
@@ -218,7 +221,8 @@ impl ActivityManager {
return None;
}
};
let mut activity: FileTransferActivity = FileTransferActivity::new(host, protocol);
let mut activity: FileTransferActivity =
FileTransferActivity::new(host, ft_params, self.ticks);
// Prepare result
let result: Option<NextActivity>;
// Create activity
@@ -243,22 +247,18 @@ impl ActivityManager {
_ => { /* Nothing to do */ }
}
}
// Sleep for ticks
sleep(self.interval);
}
// Destroy activity
self.context = activity.on_destroy();
result
}
/// ### run_setup
///
/// `SetupActivity` run loop.
/// Returns when activity terminates.
/// Returns the next activity to run
fn run_setup(&mut self) -> Option<NextActivity> {
// Prepare activity
let mut activity: SetupActivity = SetupActivity::default();
let mut activity: SetupActivity = SetupActivity::new(self.ticks);
// Get context
let ctx: Context = match self.context.take() {
Some(ctx) => ctx,
@@ -277,8 +277,6 @@ impl ActivityManager {
info!("SetupActivity terminated due to 'Quit'");
break;
}
// Sleep for ticks
sleep(self.interval);
}
// Destroy activity
self.context = activity.on_destroy();
@@ -288,8 +286,33 @@ impl ActivityManager {
// -- misc
/// ### init_config_client
///
fn init_bookmarks_client() -> Result<Option<BookmarksClient>, String> {
// Get config dir
match environment::init_config_dir() {
Ok(path) => {
// If some configure client, otherwise do nothing; don't bother users telling them that bookmarks are not supported on their system.
if let Some(config_dir_path) = path {
let bookmarks_file: PathBuf =
environment::get_bookmarks_paths(config_dir_path.as_path());
// Initialize client
BookmarksClient::new(bookmarks_file.as_path(), config_dir_path.as_path(), 16)
.map(Option::Some)
.map_err(|e| {
format!(
"Could not initialize bookmarks (at \"{}\", \"{}\"): {}",
bookmarks_file.display(),
config_dir_path.display(),
e
)
})
} else {
Ok(None)
}
}
Err(err) => Err(err),
}
}
/// Initialize configuration client
fn init_config_client() -> Result<ConfigClient, String> {
// Get config dir
@@ -306,7 +329,7 @@ impl ActivityManager {
}
}
None => Err(String::from(
"Your system doesn't support configuration paths",
"Your system doesn't provide a configuration directory",
)),
}
}
@@ -316,4 +339,32 @@ impl ActivityManager {
)),
}
}
fn init_theme_provider() -> ThemeProvider {
match environment::init_config_dir() {
Ok(config_dir) => {
match config_dir {
Some(config_dir) => {
// Get config client paths
let theme_path: PathBuf = environment::get_theme_path(config_dir.as_path());
match ThemeProvider::new(theme_path.as_path()) {
Ok(provider) => provider,
Err(err) => {
error!("Could not initialize theme provider with file '{}': {}; using theme provider in degraded mode", theme_path.display(), err);
ThemeProvider::degraded()
}
}
}
None => {
error!("This system doesn't provide a configuration directory; using theme provider in degraded mode");
ThemeProvider::degraded()
}
}
}
Err(err) => {
error!("Could not initialize configuration directory: {}; using theme provider in degraded mode", err);
ThemeProvider::degraded()
}
}
}
}

View File

@@ -1,197 +0,0 @@
//! ## Bookmarks
//!
//! `bookmarks` is the module which provides data types and de/serializer for bookmarks
/**
* MIT License
*
* termscp - Copyright (c) 2021 Christian Visintin
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pub mod serializer;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use thiserror::Error;
#[derive(Deserialize, Serialize, std::fmt::Debug)]
/// ## UserHosts
///
/// UserHosts contains all the hosts saved by the user in the data storage
/// It contains both `Bookmark`
pub struct UserHosts {
pub bookmarks: HashMap<String, Bookmark>,
pub recents: HashMap<String, Bookmark>,
}
#[derive(Deserialize, Serialize, std::fmt::Debug, PartialEq)]
/// ## Bookmark
///
/// Bookmark describes a single bookmark entry in the user hosts storage
pub struct Bookmark {
pub address: String,
pub port: u16,
pub protocol: String,
pub username: String,
pub password: Option<String>, // Password is optional; base64, aes-128 encrypted password
}
// Errors
/// ## SerializerError
///
/// Contains the error for serializer/deserializer
#[derive(std::fmt::Debug)]
pub struct SerializerError {
kind: SerializerErrorKind,
msg: Option<String>,
}
/// ## SerializerErrorKind
///
/// Describes the kind of error for the serializer/deserializer
#[derive(Error, Debug)]
pub enum SerializerErrorKind {
#[error("IO error")]
IoError,
#[error("Serialization error")]
SerializationError,
#[error("Syntax error")]
SyntaxError,
}
impl Default for UserHosts {
fn default() -> Self {
UserHosts {
bookmarks: HashMap::new(),
recents: HashMap::new(),
}
}
}
impl SerializerError {
/// ### new
///
/// Instantiate a new `SerializerError`
pub fn new(kind: SerializerErrorKind) -> SerializerError {
SerializerError { kind, msg: None }
}
/// ### new_ex
///
/// Instantiates a new `SerializerError` with description message
pub fn new_ex(kind: SerializerErrorKind, msg: String) -> SerializerError {
let mut err: SerializerError = SerializerError::new(kind);
err.msg = Some(msg);
err
}
}
impl std::fmt::Display for SerializerError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match &self.msg {
Some(msg) => write!(f, "{} ({})", self.kind, msg),
None => write!(f, "{}", self.kind),
}
}
}
// Tests
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn test_bookmarks_bookmark_new() {
let bookmark: Bookmark = Bookmark {
address: String::from("192.168.1.1"),
port: 22,
protocol: String::from("SFTP"),
username: String::from("root"),
password: Some(String::from("password")),
};
let recent: Bookmark = Bookmark {
address: String::from("192.168.1.2"),
port: 22,
protocol: String::from("SCP"),
username: String::from("admin"),
password: Some(String::from("password")),
};
let mut bookmarks: HashMap<String, Bookmark> = HashMap::with_capacity(1);
bookmarks.insert(String::from("test"), bookmark);
let mut recents: HashMap<String, Bookmark> = HashMap::with_capacity(1);
recents.insert(String::from("ISO20201218T181432"), recent);
let hosts: UserHosts = UserHosts {
bookmarks: bookmarks,
recents: recents,
};
// Verify
let bookmark: &Bookmark = hosts.bookmarks.get(&String::from("test")).unwrap();
assert_eq!(bookmark.address, String::from("192.168.1.1"));
assert_eq!(bookmark.port, 22);
assert_eq!(bookmark.protocol, String::from("SFTP"));
assert_eq!(bookmark.username, String::from("root"));
assert_eq!(
*bookmark.password.as_ref().unwrap(),
String::from("password")
);
let bookmark: &Bookmark = hosts
.recents
.get(&String::from("ISO20201218T181432"))
.unwrap();
assert_eq!(bookmark.address, String::from("192.168.1.2"));
assert_eq!(bookmark.port, 22);
assert_eq!(bookmark.protocol, String::from("SCP"));
assert_eq!(bookmark.username, String::from("admin"));
assert_eq!(
*bookmark.password.as_ref().unwrap(),
String::from("password")
);
}
#[test]
fn test_bookmarks_bookmark_errors() {
let error: SerializerError = SerializerError::new(SerializerErrorKind::SyntaxError);
assert!(error.msg.is_none());
assert_eq!(format!("{}", error), String::from("Syntax error"));
let error: SerializerError =
SerializerError::new_ex(SerializerErrorKind::SyntaxError, String::from("bad syntax"));
assert!(error.msg.is_some());
assert_eq!(
format!("{}", error),
String::from("Syntax error (bad syntax)")
);
// Fmt
assert_eq!(
format!("{}", SerializerError::new(SerializerErrorKind::IoError)),
String::from("IO error")
);
assert_eq!(
format!(
"{}",
SerializerError::new(SerializerErrorKind::SerializationError)
),
String::from("Serialization error")
);
}
}

View File

@@ -1,228 +0,0 @@
//! ## Serializer
//!
//! `serializer` is the module which provides the serializer/deserializer for bookmarks
/**
* MIT License
*
* termscp - Copyright (c) 2021 Christian Visintin
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
use super::{SerializerError, SerializerErrorKind, UserHosts};
use std::io::{Read, Write};
pub struct BookmarkSerializer;
impl BookmarkSerializer {
/// ### serialize
///
/// Serialize `UserHosts` into TOML and write content to writable
pub fn serialize(
&self,
mut writable: Box<dyn Write>,
hosts: &UserHosts,
) -> Result<(), SerializerError> {
// Serialize content
let data: String = match toml::ser::to_string(hosts) {
Ok(dt) => dt,
Err(err) => {
return Err(SerializerError::new_ex(
SerializerErrorKind::SerializationError,
err.to_string(),
))
}
};
trace!("Serialized new bookmarks data: {}", data);
// Write file
match writable.write_all(data.as_bytes()) {
Ok(_) => Ok(()),
Err(err) => Err(SerializerError::new_ex(
SerializerErrorKind::IoError,
err.to_string(),
)),
}
}
/// ### deserialize
///
/// Read data from readable and deserialize its content as TOML
pub fn deserialize(&self, mut readable: Box<dyn Read>) -> Result<UserHosts, SerializerError> {
// Read file content
let mut data: String = String::new();
if let Err(err) = readable.read_to_string(&mut data) {
return Err(SerializerError::new_ex(
SerializerErrorKind::IoError,
err.to_string(),
));
}
trace!("Read bookmarks from file: {}", data);
// Deserialize
match toml::de::from_str(data.as_str()) {
Ok(bookmarks) => {
debug!("Read bookmarks from file {:?}", bookmarks);
Ok(bookmarks)
}
Err(err) => Err(SerializerError::new_ex(
SerializerErrorKind::SyntaxError,
err.to_string(),
)),
}
}
}
// Tests
#[cfg(test)]
mod tests {
use super::super::Bookmark;
use super::*;
use pretty_assertions::assert_eq;
use std::collections::HashMap;
use std::io::{Seek, SeekFrom};
#[test]
fn test_bookmarks_serializer_deserialize_ok() {
let toml_file: tempfile::NamedTempFile = create_good_toml();
toml_file.as_file().sync_all().unwrap();
toml_file.as_file().seek(SeekFrom::Start(0)).unwrap();
// Parse
let deserializer: BookmarkSerializer = BookmarkSerializer {};
let hosts = deserializer.deserialize(Box::new(toml_file));
assert!(hosts.is_ok());
let hosts: UserHosts = hosts.ok().unwrap();
// Verify hosts
// Verify recents
assert_eq!(hosts.recents.len(), 1);
let host: &Bookmark = hosts.recents.get("ISO20201215T094000Z").unwrap();
assert_eq!(host.address, String::from("172.16.104.10"));
assert_eq!(host.port, 22);
assert_eq!(host.protocol, String::from("SCP"));
assert_eq!(host.username, String::from("root"));
assert_eq!(host.password, None);
// Verify bookmarks
assert_eq!(hosts.bookmarks.len(), 3);
let host: &Bookmark = hosts.bookmarks.get("raspberrypi2").unwrap();
assert_eq!(host.address, String::from("192.168.1.31"));
assert_eq!(host.port, 22);
assert_eq!(host.protocol, String::from("SFTP"));
assert_eq!(host.username, String::from("root"));
assert_eq!(*host.password.as_ref().unwrap(), String::from("mypassword"));
let host: &Bookmark = hosts.bookmarks.get("msi-estrem").unwrap();
assert_eq!(host.address, String::from("192.168.1.30"));
assert_eq!(host.port, 22);
assert_eq!(host.protocol, String::from("SFTP"));
assert_eq!(host.username, String::from("cvisintin"));
assert_eq!(*host.password.as_ref().unwrap(), String::from("mysecret"));
let host: &Bookmark = hosts.bookmarks.get("aws-server-prod1").unwrap();
assert_eq!(host.address, String::from("51.23.67.12"));
assert_eq!(host.port, 21);
assert_eq!(host.protocol, String::from("FTPS"));
assert_eq!(host.username, String::from("aws001"));
assert_eq!(host.password, None);
}
#[test]
fn test_bookmarks_serializer_deserialize_nok() {
let toml_file: tempfile::NamedTempFile = create_bad_toml();
toml_file.as_file().sync_all().unwrap();
toml_file.as_file().seek(SeekFrom::Start(0)).unwrap();
// Parse
let deserializer: BookmarkSerializer = BookmarkSerializer {};
assert!(deserializer.deserialize(Box::new(toml_file)).is_err());
}
#[test]
fn test_bookmarks_serializer_serialize() {
let mut bookmarks: HashMap<String, Bookmark> = HashMap::with_capacity(2);
// Push two samples
bookmarks.insert(
String::from("raspberrypi2"),
Bookmark {
address: String::from("192.168.1.31"),
port: 22,
protocol: String::from("SFTP"),
username: String::from("root"),
password: None,
},
);
bookmarks.insert(
String::from("msi-estrem"),
Bookmark {
address: String::from("192.168.1.30"),
port: 4022,
protocol: String::from("SFTP"),
username: String::from("cvisintin"),
password: Some(String::from("password")),
},
);
let mut recents: HashMap<String, Bookmark> = HashMap::with_capacity(1);
recents.insert(
String::from("ISO20201215T094000Z"),
Bookmark {
address: String::from("192.168.1.254"),
port: 3022,
protocol: String::from("SCP"),
username: String::from("omar"),
password: Some(String::from("aaa")),
},
);
let tmpfile: tempfile::NamedTempFile = tempfile::NamedTempFile::new().unwrap();
// Serialize
let deserializer: BookmarkSerializer = BookmarkSerializer {};
let hosts: UserHosts = UserHosts { bookmarks, recents };
assert!(deserializer.serialize(Box::new(tmpfile), &hosts).is_ok());
}
fn create_good_toml() -> tempfile::NamedTempFile {
// Write
let mut tmpfile: tempfile::NamedTempFile = tempfile::NamedTempFile::new().unwrap();
let file_content: &str = r#"
[bookmarks]
raspberrypi2 = { address = "192.168.1.31", port = 22, protocol = "SFTP", username = "root", password = "mypassword" }
msi-estrem = { address = "192.168.1.30", port = 22, protocol = "SFTP", username = "cvisintin", password = "mysecret" }
aws-server-prod1 = { address = "51.23.67.12", port = 21, protocol = "FTPS", username = "aws001" }
[recents]
ISO20201215T094000Z = { address = "172.16.104.10", port = 22, protocol = "SCP", username = "root" }
"#;
tmpfile.write_all(file_content.as_bytes()).unwrap();
//write!(tmpfile, "[bookmarks]\nraspberrypi2 = {{ address = \"192.168.1.31\", port = 22, protocol = \"SFTP\", username = \"root\" }}\nmsi-estrem = {{ address = \"192.168.1.30\", port = 22, protocol = \"SFTP\", username = \"cvisintin\" }}\naws-server-prod1 = {{ address = \"51.23.67.12\", port = 21, protocol = \"FTPS\", username = \"aws001\" }}\n\n[recents]\nISO20201215T094000Z = {{ address = \"172.16.104.10\", port = 22, protocol = \"SCP\", username = \"root\" }}\n");
tmpfile
}
fn create_bad_toml() -> tempfile::NamedTempFile {
// Write
let mut tmpfile: tempfile::NamedTempFile = tempfile::NamedTempFile::new().unwrap();
let file_content: &str = r#"
[bookmarks]
raspberrypi2 = { address = "192.168.1.31", port = 22, protocol = "SFTP", username = "root"}
msi-estrem = { address = "192.168.1.30", port = 22, protocol = "SFTP" }
aws-server-prod1 = { address = "51.23.67.12", port = 21, protocol = "FTPS", username = "aws001" }
[recents]
ISO20201215T094000Z = { address = "172.16.104.10", protocol = "SCP", username = "root", port = 22 }
"#;
tmpfile.write_all(file_content.as_bytes()).unwrap();
tmpfile
}
}

125
src/cli_opts.rs Normal file
View File

@@ -0,0 +1,125 @@
//! ## CLI opts
//!
//! defines the types for main.rs types
use argh::FromArgs;
use crate::activity_manager::NextActivity;
use crate::filetransfer::FileTransferParams;
use crate::system::logging::LogLevel;
use std::path::PathBuf;
use std::time::Duration;
pub enum Task {
Activity(NextActivity),
ImportTheme(PathBuf),
InstallUpdate,
}
#[derive(FromArgs)]
#[argh(description = "
where positional can be:
- [address] [local-wrkdir]
OR
- [bookmark-Name] [local-wrkdir]
Address syntax can be:
- `protocol://user@address:port:wrkdir` for protocols such as Sftp, Scp, Ftp
- `s3://bucket-name@region:profile:/wrkdir` for Aws S3 protocol
Please, report issues to <https://github.com/veeso/termscp>
Please, consider supporting the author <https://ko-fi.com/veeso>")]
pub struct Args {
#[argh(
switch,
short = 'b',
description = "resolve address argument as a bookmark name"
)]
pub address_as_bookmark: bool,
#[argh(switch, short = 'c', description = "open termscp configuration")]
pub config: bool,
#[argh(switch, short = 'D', description = "enable TRACE log level")]
pub debug: bool,
#[argh(option, short = 'P', description = "provide password from CLI")]
pub password: Option<String>,
#[argh(switch, short = 'q', description = "disable logging")]
pub quiet: bool,
#[argh(option, short = 't', description = "import specified theme")]
pub theme: Option<String>,
#[argh(
switch,
short = 'u',
description = "update termscp to the latest version"
)]
pub update: bool,
#[argh(
option,
short = 'T',
default = "10",
description = "set UI ticks; default 10ms"
)]
pub ticks: u64,
#[argh(switch, short = 'v', description = "print version")]
pub version: bool,
// -- positional
#[argh(
positional,
description = "protocol://user@address:port:wrkdir local-wrkdir"
)]
pub positional: Vec<String>,
}
pub struct RunOpts {
pub remote: Remote,
pub ticks: Duration,
pub log_level: LogLevel,
pub task: Task,
}
impl Default for RunOpts {
fn default() -> Self {
Self {
remote: Remote::None,
ticks: Duration::from_millis(10),
log_level: LogLevel::Info,
task: Task::Activity(NextActivity::Authentication),
}
}
}
#[allow(clippy::large_enum_variant)]
pub enum Remote {
Bookmark(BookmarkParams),
Host(HostParams),
None,
}
pub struct BookmarkParams {
pub name: String,
pub password: Option<String>,
}
pub struct HostParams {
pub params: FileTransferParams,
pub password: Option<String>,
}
impl BookmarkParams {
pub fn new<S: AsRef<str>>(name: S, password: Option<S>) -> Self {
Self {
name: name.as_ref().to_string(),
password: password.map(|x| x.as_ref().to_string()),
}
}
}
impl HostParams {
pub fn new<S: AsRef<str>>(params: FileTransferParams, password: Option<S>) -> Self {
Self {
params,
password: password.map(|x| x.as_ref().to_string()),
}
}
}

323
src/config/bookmarks.rs Normal file
View File

@@ -0,0 +1,323 @@
//! ## Bookmarks
//!
//! `bookmarks` is the module which provides data types and de/serializer for bookmarks
use crate::filetransfer::params::{AwsS3Params, GenericProtocolParams, ProtocolParams};
use crate::filetransfer::{FileTransferParams, FileTransferProtocol};
use serde::{de::Error as DeError, Deserialize, Deserializer, Serialize, Serializer};
use std::collections::HashMap;
use std::path::PathBuf;
use std::str::FromStr;
/// UserHosts contains all the hosts saved by the user in the data storage
/// It contains both `Bookmark`
#[derive(Deserialize, Serialize, Debug, Default)]
pub struct UserHosts {
pub bookmarks: HashMap<String, Bookmark>,
pub recents: HashMap<String, Bookmark>,
}
/// Bookmark describes a single bookmark entry in the user hosts storage
#[derive(Clone, Deserialize, Serialize, Debug, PartialEq)]
pub struct Bookmark {
#[serde(
deserialize_with = "deserialize_protocol",
serialize_with = "serialize_protocol"
)]
pub protocol: FileTransferProtocol,
/// Address for generic parameters
pub address: Option<String>,
/// Port number for generic parameters
pub port: Option<u16>,
/// Username for generic parameters
pub username: Option<String>,
/// Password is optional; base64, aes-128 encrypted password
pub password: Option<String>,
/// Remote folder to connect to
pub directory: Option<PathBuf>,
/// S3 params; optional. When used other fields are empty for sure
pub s3: Option<S3Params>,
}
/// Connection parameters for Aws s3 protocol
#[derive(Clone, Deserialize, Serialize, Debug, PartialEq, Default)]
pub struct S3Params {
pub bucket: String,
pub region: Option<String>,
pub endpoint: Option<String>,
pub profile: Option<String>,
pub access_key: Option<String>,
pub secret_access_key: Option<String>,
/// NOTE: there are no session token and security token since they are always temporary
pub new_path_style: Option<bool>,
}
// -- impls
impl From<FileTransferParams> for Bookmark {
fn from(params: FileTransferParams) -> Self {
let protocol = params.protocol;
let directory = params.entry_directory;
// Create generic or others
match params.params {
ProtocolParams::Generic(params) => Self {
protocol,
address: Some(params.address),
port: Some(params.port),
username: params.username,
password: params.password,
directory,
s3: None,
},
ProtocolParams::AwsS3(params) => Self {
protocol,
address: None,
port: None,
username: None,
password: None,
directory,
s3: Some(S3Params::from(params)),
},
}
}
}
impl From<Bookmark> for FileTransferParams {
fn from(bookmark: Bookmark) -> Self {
// Create generic or others based on protocol
match bookmark.protocol {
FileTransferProtocol::AwsS3 => {
let params = bookmark.s3.unwrap_or_default();
let params = AwsS3Params::from(params);
Self::new(FileTransferProtocol::AwsS3, ProtocolParams::AwsS3(params))
}
FileTransferProtocol::Ftp(_)
| FileTransferProtocol::Scp
| FileTransferProtocol::Sftp => {
let params = GenericProtocolParams::default()
.address(bookmark.address.unwrap_or_default())
.port(bookmark.port.unwrap_or(22))
.username(bookmark.username)
.password(bookmark.password);
Self::new(bookmark.protocol, ProtocolParams::Generic(params))
}
}
.entry_directory(bookmark.directory) // Set entry directory
}
}
impl From<AwsS3Params> for S3Params {
fn from(params: AwsS3Params) -> Self {
S3Params {
bucket: params.bucket_name,
region: params.region,
endpoint: params.endpoint,
profile: params.profile,
access_key: params.access_key,
secret_access_key: params.secret_access_key,
new_path_style: Some(params.new_path_style),
}
}
}
impl From<S3Params> for AwsS3Params {
fn from(params: S3Params) -> Self {
AwsS3Params::new(params.bucket, params.region, params.profile)
.endpoint(params.endpoint)
.access_key(params.access_key)
.secret_access_key(params.secret_access_key)
.new_path_style(params.new_path_style.unwrap_or(false))
}
}
fn deserialize_protocol<'de, D>(deserializer: D) -> Result<FileTransferProtocol, D::Error>
where
D: Deserializer<'de>,
{
let s: &str = Deserialize::deserialize(deserializer)?;
// Parse color
match FileTransferProtocol::from_str(s) {
Err(err) => Err(DeError::custom(err)),
Ok(protocol) => Ok(protocol),
}
}
fn serialize_protocol<S>(protocol: &FileTransferProtocol, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(protocol.to_string().as_str())
}
// Tests
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn test_bookmarks_default() {
let bookmarks: UserHosts = UserHosts::default();
assert_eq!(bookmarks.bookmarks.len(), 0);
assert_eq!(bookmarks.recents.len(), 0);
}
#[test]
fn test_bookmarks_bookmark_new() {
let bookmark: Bookmark = Bookmark {
address: Some(String::from("192.168.1.1")),
port: Some(22),
protocol: FileTransferProtocol::Sftp,
username: Some(String::from("root")),
password: Some(String::from("password")),
directory: Some(PathBuf::from("/tmp")),
s3: None,
};
let recent: Bookmark = Bookmark {
address: Some(String::from("192.168.1.2")),
port: Some(22),
protocol: FileTransferProtocol::Scp,
username: Some(String::from("admin")),
password: Some(String::from("password")),
directory: Some(PathBuf::from("/home")),
s3: None,
};
let mut bookmarks: HashMap<String, Bookmark> = HashMap::with_capacity(1);
bookmarks.insert(String::from("test"), bookmark);
let mut recents: HashMap<String, Bookmark> = HashMap::with_capacity(1);
recents.insert(String::from("ISO20201218T181432"), recent);
let hosts: UserHosts = UserHosts { bookmarks, recents };
// Verify
let bookmark: &Bookmark = hosts.bookmarks.get(&String::from("test")).unwrap();
assert_eq!(bookmark.address.as_deref().unwrap(), "192.168.1.1");
assert_eq!(bookmark.port.unwrap(), 22);
assert_eq!(bookmark.protocol, FileTransferProtocol::Sftp);
assert_eq!(bookmark.username.as_deref().unwrap(), "root");
assert_eq!(bookmark.password.as_deref().unwrap(), "password");
assert_eq!(
bookmark.directory.as_deref().unwrap(),
std::path::Path::new("/tmp")
);
let bookmark: &Bookmark = hosts
.recents
.get(&String::from("ISO20201218T181432"))
.unwrap();
assert_eq!(bookmark.address.as_deref().unwrap(), "192.168.1.2");
assert_eq!(bookmark.port.unwrap(), 22);
assert_eq!(bookmark.protocol, FileTransferProtocol::Scp);
assert_eq!(bookmark.username.as_deref().unwrap(), "admin");
assert_eq!(bookmark.password.as_deref().unwrap(), "password");
assert_eq!(
bookmark.directory.as_deref().unwrap(),
std::path::Path::new("/home")
);
}
#[test]
fn bookmark_from_generic_ftparams() {
let params = ProtocolParams::Generic(GenericProtocolParams {
address: "127.0.0.1".to_string(),
port: 10222,
username: Some(String::from("root")),
password: Some(String::from("omar")),
});
let params: FileTransferParams = FileTransferParams::new(FileTransferProtocol::Scp, params)
.entry_directory(Some(PathBuf::from("/home")));
let bookmark = Bookmark::from(params);
assert_eq!(bookmark.protocol, FileTransferProtocol::Scp);
assert_eq!(bookmark.address.as_deref().unwrap(), "127.0.0.1");
assert_eq!(bookmark.port.unwrap(), 10222);
assert_eq!(bookmark.username.as_deref().unwrap(), "root");
assert_eq!(bookmark.password.as_deref().unwrap(), "omar");
assert_eq!(
bookmark.directory.as_deref().unwrap(),
std::path::Path::new("/home")
);
assert!(bookmark.s3.is_none());
}
#[test]
fn bookmark_from_s3_ftparams() {
let params = ProtocolParams::AwsS3(
AwsS3Params::new("omar", Some("eu-west-1"), Some("test"))
.access_key(Some("pippo"))
.secret_access_key(Some("pluto")),
);
let params: FileTransferParams =
FileTransferParams::new(FileTransferProtocol::AwsS3, params);
let bookmark = Bookmark::from(params);
assert_eq!(bookmark.protocol, FileTransferProtocol::AwsS3);
assert!(bookmark.address.is_none());
assert!(bookmark.port.is_none());
assert!(bookmark.username.is_none());
assert!(bookmark.password.is_none());
let s3: &S3Params = bookmark.s3.as_ref().unwrap();
assert_eq!(s3.bucket.as_str(), "omar");
assert_eq!(s3.region.as_deref().unwrap(), "eu-west-1");
assert_eq!(s3.profile.as_deref().unwrap(), "test");
assert_eq!(s3.access_key.as_deref().unwrap(), "pippo");
assert_eq!(s3.secret_access_key.as_deref().unwrap(), "pluto");
}
#[test]
fn ftparams_from_generic_bookmark() {
let bookmark: Bookmark = Bookmark {
address: Some(String::from("192.168.1.1")),
port: Some(22),
protocol: FileTransferProtocol::Sftp,
username: Some(String::from("root")),
password: Some(String::from("password")),
directory: Some(PathBuf::from("/tmp")),
s3: None,
};
let params = FileTransferParams::from(bookmark);
assert_eq!(params.protocol, FileTransferProtocol::Sftp);
assert_eq!(
params.entry_directory.as_deref().unwrap(),
std::path::Path::new("/tmp")
);
let gparams = params.params.generic_params().unwrap();
assert_eq!(gparams.address.as_str(), "192.168.1.1");
assert_eq!(gparams.port, 22);
assert_eq!(gparams.username.as_deref().unwrap(), "root");
assert_eq!(gparams.password.as_deref().unwrap(), "password");
}
#[test]
fn ftparams_from_s3_bookmark() {
let bookmark: Bookmark = Bookmark {
protocol: FileTransferProtocol::AwsS3,
address: None,
port: None,
username: None,
password: None,
directory: Some(PathBuf::from("/tmp")),
s3: Some(S3Params {
bucket: String::from("veeso"),
region: Some(String::from("eu-west-1")),
endpoint: Some(String::from("omar")),
profile: Some(String::from("default")),
access_key: Some(String::from("pippo")),
secret_access_key: Some(String::from("pluto")),
new_path_style: Some(true),
}),
};
let params = FileTransferParams::from(bookmark);
assert_eq!(params.protocol, FileTransferProtocol::AwsS3);
assert_eq!(
params.entry_directory.as_deref().unwrap(),
std::path::Path::new("/tmp")
);
let gparams = params.params.s3_params().unwrap();
assert_eq!(gparams.bucket_name.as_str(), "veeso");
assert_eq!(gparams.region.as_deref().unwrap(), "eu-west-1");
assert_eq!(gparams.endpoint.as_deref().unwrap(), "omar");
assert_eq!(gparams.profile.as_deref().unwrap(), "default");
assert_eq!(gparams.access_key.as_deref().unwrap(), "pippo");
assert_eq!(gparams.secret_access_key.as_deref().unwrap(), "pluto");
assert_eq!(gparams.new_path_style, true);
}
}

View File

@@ -1,264 +1,11 @@
//! ## Config
//!
//! `config` is the module which provides access to termscp configuration
//! `config` is the module which provides access to all the termscp configurations
/**
* MIT License
*
* termscp - Copyright (c) 2021 Christian Visintin
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// Modules
pub mod serializer;
// export
pub use params::*;
// Deps
extern crate edit;
// Locals
use crate::filetransfer::FileTransferProtocol;
// Ext
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
use thiserror::Error;
#[derive(Deserialize, Serialize, std::fmt::Debug)]
/// ## UserConfig
///
/// UserConfig contains all the configurations for the user,
/// supported by termscp
pub struct UserConfig {
pub user_interface: UserInterfaceConfig,
pub remote: RemoteConfig,
}
#[derive(Deserialize, Serialize, std::fmt::Debug)]
/// ## UserInterfaceConfig
///
/// UserInterfaceConfig provides all the keys to configure the user interface
pub struct UserInterfaceConfig {
pub text_editor: PathBuf,
pub default_protocol: String,
pub show_hidden_files: bool,
pub check_for_updates: Option<bool>, // @! Since 0.3.3
pub group_dirs: Option<String>,
pub file_fmt: Option<String>, // Refers to local host (for backward compatibility)
pub remote_file_fmt: Option<String>, // @! Since 0.5.0
}
#[derive(Deserialize, Serialize, std::fmt::Debug)]
/// ## RemoteConfig
///
/// Contains configuratio related to remote hosts
pub struct RemoteConfig {
pub ssh_keys: HashMap<String, PathBuf>, // Association between host name and path to private key
}
impl Default for UserConfig {
fn default() -> Self {
UserConfig {
user_interface: UserInterfaceConfig::default(),
remote: RemoteConfig::default(),
}
}
}
impl Default for UserInterfaceConfig {
fn default() -> Self {
UserInterfaceConfig {
text_editor: match edit::get_editor() {
Ok(p) => p,
Err(_) => PathBuf::from("nano"), // Default to nano
},
default_protocol: FileTransferProtocol::Sftp.to_string(),
show_hidden_files: false,
check_for_updates: Some(true),
group_dirs: None,
file_fmt: None,
remote_file_fmt: None,
}
}
}
impl Default for RemoteConfig {
fn default() -> Self {
RemoteConfig {
ssh_keys: HashMap::new(),
}
}
}
// Errors
/// ## SerializerError
///
/// Contains the error for serializer/deserializer
#[derive(std::fmt::Debug)]
pub struct SerializerError {
kind: SerializerErrorKind,
msg: Option<String>,
}
/// ## SerializerErrorKind
///
/// Describes the kind of error for the serializer/deserializer
#[derive(Error, Debug)]
pub enum SerializerErrorKind {
#[error("IO error")]
IoError,
#[error("Serialization error")]
SerializationError,
#[error("Syntax error")]
SyntaxError,
}
impl SerializerError {
/// ### new
///
/// Instantiate a new `SerializerError`
pub fn new(kind: SerializerErrorKind) -> SerializerError {
SerializerError { kind, msg: None }
}
/// ### new_ex
///
/// Instantiates a new `SerializerError` with description message
pub fn new_ex(kind: SerializerErrorKind, msg: String) -> SerializerError {
let mut err: SerializerError = SerializerError::new(kind);
err.msg = Some(msg);
err
}
}
impl std::fmt::Display for SerializerError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match &self.msg {
Some(msg) => write!(f, "{} ({})", self.kind, msg),
None => write!(f, "{}", self.kind),
}
}
}
// Tests
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
use std::env;
#[test]
fn test_config_mod_new() {
let mut keys: HashMap<String, PathBuf> = HashMap::with_capacity(1);
keys.insert(
String::from("192.168.1.31"),
PathBuf::from("/tmp/private.key"),
);
let remote: RemoteConfig = RemoteConfig { ssh_keys: keys };
let ui: UserInterfaceConfig = UserInterfaceConfig {
default_protocol: String::from("SFTP"),
text_editor: PathBuf::from("nano"),
show_hidden_files: true,
check_for_updates: Some(true),
group_dirs: Some(String::from("first")),
file_fmt: Some(String::from("{NAME}")),
remote_file_fmt: Some(String::from("{USER}")),
};
assert_eq!(ui.default_protocol, String::from("SFTP"));
assert_eq!(ui.text_editor, PathBuf::from("nano"));
assert_eq!(ui.show_hidden_files, true);
assert_eq!(ui.check_for_updates, Some(true));
assert_eq!(ui.group_dirs, Some(String::from("first")));
assert_eq!(ui.file_fmt, Some(String::from("{NAME}")));
let cfg: UserConfig = UserConfig {
user_interface: ui,
remote: remote,
};
assert_eq!(
*cfg.remote
.ssh_keys
.get(&String::from("192.168.1.31"))
.unwrap(),
PathBuf::from("/tmp/private.key")
);
assert_eq!(cfg.user_interface.default_protocol, String::from("SFTP"));
assert_eq!(cfg.user_interface.text_editor, PathBuf::from("nano"));
assert_eq!(cfg.user_interface.show_hidden_files, true);
assert_eq!(cfg.user_interface.check_for_updates, Some(true));
assert_eq!(cfg.user_interface.group_dirs, Some(String::from("first")));
assert_eq!(cfg.user_interface.file_fmt, Some(String::from("{NAME}")));
assert_eq!(
cfg.user_interface.remote_file_fmt,
Some(String::from("{USER}"))
);
}
#[test]
fn test_config_mod_new_default() {
// Force vim editor
env::set_var(String::from("EDITOR"), String::from("vim"));
// Get default
let cfg: UserConfig = UserConfig::default();
assert_eq!(cfg.user_interface.default_protocol, String::from("SFTP"));
// Text editor
#[cfg(target_os = "windows")]
assert_eq!(
PathBuf::from(cfg.user_interface.text_editor.file_name().unwrap()), // NOTE: since edit 0.1.3 real path is used
PathBuf::from("vim.EXE")
);
#[cfg(target_family = "unix")]
assert_eq!(
PathBuf::from(cfg.user_interface.text_editor.file_name().unwrap()), // NOTE: since edit 0.1.3 real path is used
PathBuf::from("vim")
);
assert_eq!(cfg.user_interface.check_for_updates.unwrap(), true);
assert_eq!(cfg.remote.ssh_keys.len(), 0);
assert!(cfg.user_interface.file_fmt.is_none());
assert!(cfg.user_interface.remote_file_fmt.is_none());
}
#[test]
fn test_config_mod_errors() {
let error: SerializerError = SerializerError::new(SerializerErrorKind::SyntaxError);
assert!(error.msg.is_none());
assert_eq!(format!("{}", error), String::from("Syntax error"));
let error: SerializerError =
SerializerError::new_ex(SerializerErrorKind::SyntaxError, String::from("bad syntax"));
assert!(error.msg.is_some());
assert_eq!(
format!("{}", error),
String::from("Syntax error (bad syntax)")
);
// Fmt
assert_eq!(
format!("{}", SerializerError::new(SerializerErrorKind::IoError)),
String::from("IO error")
);
assert_eq!(
format!(
"{}",
SerializerError::new(SerializerErrorKind::SerializationError)
),
String::from("Serialization error")
);
}
}
pub mod bookmarks;
pub mod params;
pub mod serialization;
pub mod themes;

139
src/config/params.rs Normal file
View File

@@ -0,0 +1,139 @@
//! ## Config
//!
//! `config` is the module which provides access to termscp configuration
// Locals
use crate::filetransfer::FileTransferProtocol;
// Ext
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
pub const DEFAULT_NOTIFICATION_TRANSFER_THRESHOLD: u64 = 536870912; // 512MB
#[derive(Deserialize, Serialize, Debug, Default)]
/// UserConfig contains all the configurations for the user,
/// supported by termscp
pub struct UserConfig {
pub user_interface: UserInterfaceConfig,
pub remote: RemoteConfig,
}
#[derive(Deserialize, Serialize, Debug)]
/// UserInterfaceConfig provides all the keys to configure the user interface
pub struct UserInterfaceConfig {
pub text_editor: PathBuf,
pub default_protocol: String,
pub show_hidden_files: bool,
pub check_for_updates: Option<bool>, // @! Since 0.3.3
pub prompt_on_file_replace: Option<bool>, // @! Since 0.7.0; Default True
pub group_dirs: Option<String>,
/// file fmt. Refers to local host (for backward compatibility)
pub file_fmt: Option<String>,
pub remote_file_fmt: Option<String>, // @! Since 0.5.0
pub notifications: Option<bool>, // @! Since 0.7.0; Default true
pub notification_threshold: Option<u64>, // @! Since 0.7.0; Default 512MB
}
#[derive(Deserialize, Serialize, Debug, Default)]
/// Contains configuratio related to remote hosts
pub struct RemoteConfig {
/// Ssh configuration path. If NONE, won't be read
pub ssh_config: Option<String>,
/// Association between host name and path to private key
/// NOTE: this parameter must stay as last: <https://github.com/alexcrichton/toml-rs/issues/142>
pub ssh_keys: HashMap<String, PathBuf>,
}
impl Default for UserInterfaceConfig {
fn default() -> Self {
UserInterfaceConfig {
text_editor: match edit::get_editor() {
Ok(p) => p,
Err(_) => PathBuf::from("nano"), // Default to nano
},
default_protocol: FileTransferProtocol::Sftp.to_string(),
show_hidden_files: false,
check_for_updates: Some(true),
prompt_on_file_replace: Some(true),
group_dirs: None,
file_fmt: None,
remote_file_fmt: None,
notifications: Some(true),
notification_threshold: Some(DEFAULT_NOTIFICATION_TRANSFER_THRESHOLD),
}
}
}
// Tests
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn test_config_mod_new() {
let mut keys: HashMap<String, PathBuf> = HashMap::with_capacity(1);
keys.insert(
String::from("192.168.1.31"),
PathBuf::from("/tmp/private.key"),
);
let remote: RemoteConfig = RemoteConfig {
ssh_keys: keys,
ssh_config: Some(String::from("~/.ssh/config")),
};
let ui: UserInterfaceConfig = UserInterfaceConfig {
default_protocol: String::from("SFTP"),
text_editor: PathBuf::from("nano"),
show_hidden_files: true,
check_for_updates: Some(true),
prompt_on_file_replace: Some(true),
group_dirs: Some(String::from("first")),
file_fmt: Some(String::from("{NAME}")),
remote_file_fmt: Some(String::from("{USER}")),
notifications: Some(true),
notification_threshold: Some(DEFAULT_NOTIFICATION_TRANSFER_THRESHOLD),
};
assert_eq!(ui.default_protocol, String::from("SFTP"));
assert_eq!(ui.text_editor, PathBuf::from("nano"));
assert_eq!(ui.show_hidden_files, true);
assert_eq!(ui.check_for_updates, Some(true));
assert_eq!(ui.prompt_on_file_replace, Some(true));
assert_eq!(ui.group_dirs, Some(String::from("first")));
assert_eq!(ui.file_fmt, Some(String::from("{NAME}")));
let cfg: UserConfig = UserConfig {
user_interface: ui,
remote: remote,
};
assert_eq!(
*cfg.remote
.ssh_keys
.get(&String::from("192.168.1.31"))
.unwrap(),
PathBuf::from("/tmp/private.key")
);
assert_eq!(
cfg.remote.ssh_config.as_deref().unwrap(),
String::from("~/.ssh/config")
);
assert_eq!(cfg.user_interface.default_protocol, String::from("SFTP"));
assert_eq!(cfg.user_interface.text_editor, PathBuf::from("nano"));
assert_eq!(cfg.user_interface.show_hidden_files, true);
assert_eq!(cfg.user_interface.check_for_updates, Some(true));
assert_eq!(cfg.user_interface.prompt_on_file_replace, Some(true));
assert_eq!(cfg.user_interface.group_dirs, Some(String::from("first")));
assert_eq!(cfg.user_interface.file_fmt, Some(String::from("{NAME}")));
assert_eq!(
cfg.user_interface.remote_file_fmt,
Some(String::from("{USER}"))
);
assert_eq!(cfg.user_interface.notifications, Some(true));
assert_eq!(
cfg.user_interface.notification_threshold,
Some(DEFAULT_NOTIFICATION_TRANSFER_THRESHOLD)
);
}
}

619
src/config/serialization.rs Normal file
View File

@@ -0,0 +1,619 @@
//! ## Serialization
//!
//! `serialization` provides serialization and deserialization for configurations
use serde::{de::DeserializeOwned, Serialize};
use std::io::{Read, Write};
use thiserror::Error;
/// Contains the error for serializer/deserializer
#[derive(std::fmt::Debug)]
pub struct SerializerError {
kind: SerializerErrorKind,
msg: Option<String>,
}
/// Describes the kind of error for the serializer/deserializer
#[derive(Error, Debug)]
pub enum SerializerErrorKind {
#[error("Operation failed")]
Generic,
#[error("IO error")]
Io,
#[error("Serialization error")]
Serialization,
#[error("Syntax error")]
Syntax,
}
impl SerializerError {
/// Instantiate a new `SerializerError`
pub fn new(kind: SerializerErrorKind) -> SerializerError {
SerializerError { kind, msg: None }
}
/// Instantiates a new `SerializerError` with description message
pub fn new_ex(kind: SerializerErrorKind, msg: String) -> SerializerError {
let mut err: SerializerError = SerializerError::new(kind);
err.msg = Some(msg);
err
}
}
impl std::fmt::Display for SerializerError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match &self.msg {
Some(msg) => write!(f, "{} ({})", self.kind, msg),
None => write!(f, "{}", self.kind),
}
}
}
/// ### serialize
///
/// Serialize `UserHosts` into TOML and write content to writable
pub fn serialize<S>(serializable: &S, mut writable: Box<dyn Write>) -> Result<(), SerializerError>
where
S: Serialize + Sized,
{
// Serialize content
let data: String = match toml::ser::to_string(serializable) {
Ok(dt) => dt,
Err(err) => {
return Err(SerializerError::new_ex(
SerializerErrorKind::Serialization,
err.to_string(),
))
}
};
trace!("Serialized new bookmarks data: {}", data);
// Write file
match writable.write_all(data.as_bytes()) {
Ok(_) => Ok(()),
Err(err) => Err(SerializerError::new_ex(
SerializerErrorKind::Io,
err.to_string(),
)),
}
}
/// ### deserialize
///
/// Read data from readable and deserialize its content as TOML
pub fn deserialize<S>(mut readable: Box<dyn Read>) -> Result<S, SerializerError>
where
S: DeserializeOwned + Sized + std::fmt::Debug,
{
// Read file content
let mut data: String = String::new();
if let Err(err) = readable.read_to_string(&mut data) {
return Err(SerializerError::new_ex(
SerializerErrorKind::Io,
err.to_string(),
));
}
trace!("Read bookmarks from file: {}", data);
// Deserialize
match toml::de::from_str(data.as_str()) {
Ok(deserialized) => {
debug!("Read bookmarks from file {:?}", deserialized);
Ok(deserialized)
}
Err(err) => Err(SerializerError::new_ex(
SerializerErrorKind::Syntax,
err.to_string(),
)),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::bookmarks::{Bookmark, S3Params, UserHosts};
use crate::config::params::UserConfig;
use crate::config::themes::Theme;
use crate::filetransfer::FileTransferProtocol;
use crate::utils::test_helpers::create_file_ioers;
use pretty_assertions::assert_eq;
use std::collections::HashMap;
use std::io::{Seek, SeekFrom};
use std::path::PathBuf;
use tuirealm::tui::style::Color;
#[test]
fn test_config_serialization_errors() {
let error: SerializerError = SerializerError::new(SerializerErrorKind::Syntax);
assert!(error.msg.is_none());
assert_eq!(format!("{}", error), String::from("Syntax error"));
let error: SerializerError =
SerializerError::new_ex(SerializerErrorKind::Syntax, String::from("bad syntax"));
assert!(error.msg.is_some());
assert_eq!(
format!("{}", error),
String::from("Syntax error (bad syntax)")
);
// Fmt
assert_eq!(
format!("{}", SerializerError::new(SerializerErrorKind::Generic)),
String::from("Operation failed")
);
assert_eq!(
format!("{}", SerializerError::new(SerializerErrorKind::Io)),
String::from("IO error")
);
assert_eq!(
format!(
"{}",
SerializerError::new(SerializerErrorKind::Serialization)
),
String::from("Serialization error")
);
}
// -- Serialization of params
#[test]
fn test_config_serialization_params_deserialize_ok() {
let toml_file: tempfile::NamedTempFile = create_good_toml_bookmarks_params();
toml_file.as_file().sync_all().unwrap();
toml_file.as_file().seek(SeekFrom::Start(0)).unwrap();
// Parse
let cfg = deserialize(Box::new(toml_file));
assert!(cfg.is_ok());
let cfg: UserConfig = cfg.ok().unwrap();
// Verify configuration
// Verify ui
assert_eq!(cfg.user_interface.default_protocol, String::from("SCP"));
assert_eq!(cfg.user_interface.text_editor, PathBuf::from("vim"));
assert_eq!(cfg.user_interface.show_hidden_files, true);
assert_eq!(cfg.user_interface.check_for_updates.unwrap(), true);
assert_eq!(cfg.user_interface.prompt_on_file_replace.unwrap(), false);
assert_eq!(cfg.user_interface.notifications.unwrap(), false);
assert_eq!(cfg.user_interface.notification_threshold.unwrap(), 1024);
assert_eq!(cfg.user_interface.group_dirs, Some(String::from("last")));
// Remote
assert_eq!(
cfg.remote.ssh_config.as_deref(),
Some("/home/omar/.ssh/config")
);
assert_eq!(
cfg.user_interface.file_fmt,
Some(String::from("{NAME} {PEX}"))
);
assert_eq!(
cfg.user_interface.remote_file_fmt,
Some(String::from("{NAME} {USER}")),
);
// Verify keys
assert_eq!(
*cfg.remote
.ssh_keys
.get(&String::from("192.168.1.31"))
.unwrap(),
PathBuf::from("/home/omar/.ssh/raspberry.key")
);
assert_eq!(
*cfg.remote
.ssh_keys
.get(&String::from("192.168.1.32"))
.unwrap(),
PathBuf::from("/home/omar/.ssh/beaglebone.key")
);
assert!(cfg.remote.ssh_keys.get(&String::from("1.1.1.1")).is_none());
}
#[test]
fn test_config_serialization_params_deserialize_ok_no_opts() {
let toml_file: tempfile::NamedTempFile = create_good_toml_bookmarks_params_no_opts();
toml_file.as_file().sync_all().unwrap();
toml_file.as_file().seek(SeekFrom::Start(0)).unwrap();
// Parse
let cfg = deserialize(Box::new(toml_file));
assert!(cfg.is_ok());
let cfg: UserConfig = cfg.ok().unwrap();
// Verify configuration
// Verify ui
assert_eq!(cfg.user_interface.default_protocol, String::from("SCP"));
assert_eq!(cfg.user_interface.text_editor, PathBuf::from("vim"));
assert_eq!(cfg.user_interface.show_hidden_files, true);
assert_eq!(cfg.user_interface.group_dirs, None);
assert!(cfg.user_interface.check_for_updates.is_none());
assert!(cfg.user_interface.prompt_on_file_replace.is_none());
assert!(cfg.user_interface.file_fmt.is_none());
assert!(cfg.user_interface.remote_file_fmt.is_none());
assert!(cfg.user_interface.notifications.is_none());
assert!(cfg.user_interface.notification_threshold.is_none());
assert!(cfg.remote.ssh_config.is_none());
// Verify keys
assert_eq!(
*cfg.remote
.ssh_keys
.get(&String::from("192.168.1.31"))
.unwrap(),
PathBuf::from("/home/omar/.ssh/raspberry.key")
);
assert_eq!(
*cfg.remote
.ssh_keys
.get(&String::from("192.168.1.32"))
.unwrap(),
PathBuf::from("/home/omar/.ssh/beaglebone.key")
);
assert!(cfg.remote.ssh_keys.get(&String::from("1.1.1.1")).is_none());
}
#[test]
fn test_config_serialization_params_deserialize_nok() {
let toml_file: tempfile::NamedTempFile = create_bad_toml_bookmarks_params();
toml_file.as_file().sync_all().unwrap();
toml_file.as_file().seek(SeekFrom::Start(0)).unwrap();
// Parse
assert!(deserialize::<UserConfig>(Box::new(toml_file)).is_err());
}
#[test]
fn test_config_serialization_params_serialize() {
let mut cfg: UserConfig = UserConfig::default();
let toml_file: tempfile::NamedTempFile = tempfile::NamedTempFile::new().ok().unwrap();
// Insert key
cfg.remote.ssh_keys.insert(
String::from("192.168.1.31"),
PathBuf::from("/home/omar/.ssh/id_rsa"),
);
// Serialize
let writer: Box<dyn Write> = Box::new(std::fs::File::create(toml_file.path()).unwrap());
assert!(serialize(&cfg, writer).is_ok());
// Reload configuration and check if it's ok
toml_file.as_file().sync_all().unwrap();
toml_file.as_file().seek(SeekFrom::Start(0)).unwrap();
assert!(deserialize::<UserConfig>(Box::new(toml_file)).is_ok());
}
#[test]
fn test_config_serialization_params_fail_write() {
let toml_file: tempfile::NamedTempFile = tempfile::NamedTempFile::new().ok().unwrap();
let writer: Box<dyn Write> = Box::new(std::fs::File::open(toml_file.path()).unwrap());
// Try to write unexisting file
let cfg: UserConfig = UserConfig::default();
assert!(serialize(&cfg, writer).is_err());
}
#[test]
fn test_config_serialization_params_fail_read() {
let toml_file: tempfile::NamedTempFile = tempfile::NamedTempFile::new().ok().unwrap();
let reader: Box<dyn Read> = Box::new(std::fs::File::open(toml_file.path()).unwrap());
// Try to write unexisting file
assert!(deserialize::<UserConfig>(reader).is_err());
}
fn create_good_toml_bookmarks_params() -> tempfile::NamedTempFile {
// Write
let mut tmpfile: tempfile::NamedTempFile = tempfile::NamedTempFile::new().unwrap();
let file_content: &str = r#"
[user_interface]
default_protocol = "SCP"
text_editor = "vim"
show_hidden_files = true
check_for_updates = true
prompt_on_file_replace = false
group_dirs = "last"
file_fmt = "{NAME} {PEX}"
remote_file_fmt = "{NAME} {USER}"
notifications = false
notification_threshold = 1024
[remote]
ssh_config = "/home/omar/.ssh/config"
[remote.ssh_keys]
"192.168.1.31" = "/home/omar/.ssh/raspberry.key"
"192.168.1.32" = "/home/omar/.ssh/beaglebone.key"
"#;
tmpfile.write_all(file_content.as_bytes()).unwrap();
tmpfile
}
fn create_good_toml_bookmarks_params_no_opts() -> tempfile::NamedTempFile {
// Write
let mut tmpfile: tempfile::NamedTempFile = tempfile::NamedTempFile::new().unwrap();
let file_content: &str = r#"
[user_interface]
default_protocol = "SCP"
text_editor = "vim"
show_hidden_files = true
[remote.ssh_keys]
"192.168.1.31" = "/home/omar/.ssh/raspberry.key"
"192.168.1.32" = "/home/omar/.ssh/beaglebone.key"
"#;
tmpfile.write_all(file_content.as_bytes()).unwrap();
tmpfile
}
fn create_bad_toml_bookmarks_params() -> tempfile::NamedTempFile {
// Write
let mut tmpfile: tempfile::NamedTempFile = tempfile::NamedTempFile::new().unwrap();
let file_content: &str = r#"
[user_interface]
default_protocol = "SFTP"
[remote.ssh_keys]
"192.168.1.31" = "/home/omar/.ssh/raspberry.key"
"#;
tmpfile.write_all(file_content.as_bytes()).unwrap();
tmpfile
}
// -- bookmarks
#[test]
fn test_config_serializer_bookmarks_serializer_deserialize_ok() {
let toml_file: tempfile::NamedTempFile = create_good_toml_bookmarks();
toml_file.as_file().sync_all().unwrap();
toml_file.as_file().seek(SeekFrom::Start(0)).unwrap();
// Parse
let hosts = deserialize(Box::new(toml_file));
assert!(hosts.is_ok());
let hosts: UserHosts = hosts.ok().unwrap();
// Verify hosts
// Verify recents
assert_eq!(hosts.recents.len(), 1);
let host: &Bookmark = hosts.recents.get("ISO20201215T094000Z").unwrap();
assert_eq!(host.address.as_deref().unwrap(), "172.16.104.10");
assert_eq!(host.port.unwrap(), 22);
assert_eq!(host.protocol, FileTransferProtocol::Scp);
assert_eq!(host.username.as_deref().unwrap(), "root");
assert_eq!(host.password, None);
// Verify bookmarks
assert_eq!(hosts.bookmarks.len(), 4);
let host: &Bookmark = hosts.bookmarks.get("raspberrypi2").unwrap();
assert_eq!(host.address.as_deref().unwrap(), "192.168.1.31");
assert_eq!(host.port.unwrap(), 22);
assert_eq!(host.protocol, FileTransferProtocol::Sftp);
assert_eq!(host.username.as_deref().unwrap(), "root");
assert_eq!(host.password.as_deref().unwrap(), "mypassword");
let host: &Bookmark = hosts.bookmarks.get("msi-estrem").unwrap();
assert_eq!(host.address.as_deref().unwrap(), "192.168.1.30");
assert_eq!(host.port.unwrap(), 22);
assert_eq!(host.protocol, FileTransferProtocol::Sftp);
assert_eq!(host.username.as_deref().unwrap(), "cvisintin");
assert_eq!(host.password.as_deref().unwrap(), "mysecret");
assert_eq!(
host.directory.as_deref().unwrap(),
std::path::Path::new("/tmp")
);
let host: &Bookmark = hosts.bookmarks.get("aws-server-prod1").unwrap();
assert_eq!(host.address.as_deref().unwrap(), "51.23.67.12");
assert_eq!(host.port.unwrap(), 21);
assert_eq!(host.protocol, FileTransferProtocol::Ftp(true));
assert_eq!(host.username.as_deref().unwrap(), "aws001");
assert_eq!(host.password, None);
// Aws s3 bucket
let host: &Bookmark = hosts.bookmarks.get("my-bucket").unwrap();
assert_eq!(host.address, None);
assert_eq!(host.port, None);
assert_eq!(host.username, None);
assert_eq!(host.password, None);
assert_eq!(host.protocol, FileTransferProtocol::AwsS3);
let s3 = host.s3.as_ref().unwrap();
assert_eq!(s3.bucket.as_str(), "veeso");
assert_eq!(s3.region.as_deref().unwrap(), "eu-west-1");
assert_eq!(s3.profile.as_deref().unwrap(), "default");
assert_eq!(s3.endpoint.as_deref().unwrap(), "http://localhost:9000");
assert_eq!(s3.access_key.as_deref().unwrap(), "pippo");
assert_eq!(s3.secret_access_key.as_deref().unwrap(), "pluto");
assert_eq!(s3.new_path_style.unwrap(), true);
}
#[test]
fn test_config_serializer_bookmarks_serializer_deserialize_nok() {
let toml_file: tempfile::NamedTempFile = create_bad_toml_bookmarks();
toml_file.as_file().sync_all().unwrap();
toml_file.as_file().seek(SeekFrom::Start(0)).unwrap();
// Parse
assert!(deserialize::<UserHosts>(Box::new(toml_file)).is_err());
}
#[test]
fn test_config_serializer_bookmarks_serializer_serialize() {
let mut bookmarks: HashMap<String, Bookmark> = HashMap::with_capacity(2);
// Push two samples
bookmarks.insert(
String::from("raspberrypi2"),
Bookmark {
address: Some(String::from("192.168.1.31")),
port: Some(22),
protocol: FileTransferProtocol::Sftp,
username: Some(String::from("root")),
password: None,
directory: None,
s3: None,
},
);
bookmarks.insert(
String::from("msi-estrem"),
Bookmark {
address: Some(String::from("192.168.1.30")),
port: Some(4022),
protocol: FileTransferProtocol::Sftp,
username: Some(String::from("cvisintin")),
password: Some(String::from("password")),
directory: Some(PathBuf::from("/tmp")),
s3: None,
},
);
bookmarks.insert(
String::from("my-bucket"),
Bookmark {
address: None,
port: None,
protocol: FileTransferProtocol::AwsS3,
username: None,
password: None,
directory: None,
s3: Some(S3Params {
bucket: "veeso".to_string(),
region: Some("eu-west-1".to_string()),
endpoint: None,
profile: None,
access_key: None,
secret_access_key: None,
new_path_style: None,
}),
},
);
let mut recents: HashMap<String, Bookmark> = HashMap::with_capacity(1);
recents.insert(
String::from("ISO20201215T094000Z"),
Bookmark {
address: Some(String::from("192.168.1.254")),
port: Some(3022),
protocol: FileTransferProtocol::Scp,
username: Some(String::from("omar")),
password: Some(String::from("aaa")),
directory: Some(PathBuf::from("/tmp")),
s3: None,
},
);
let tmpfile: tempfile::NamedTempFile = tempfile::NamedTempFile::new().unwrap();
// Serialize
let hosts: UserHosts = UserHosts { bookmarks, recents };
assert!(serialize(&hosts, Box::new(tmpfile)).is_ok());
}
#[test]
fn test_config_serialization_theme_serialize() {
let mut theme: Theme = Theme::default();
theme.auth_address = Color::Rgb(240, 240, 240);
let tmpfile: tempfile::NamedTempFile = tempfile::NamedTempFile::new().unwrap();
let (reader, writer) = create_file_ioers(tmpfile.path());
assert!(serialize(&theme, Box::new(writer)).is_ok());
// Try to deserialize
let deserialized_theme: Theme = deserialize(Box::new(reader)).ok().unwrap();
assert_eq!(theme, deserialized_theme);
}
#[test]
fn test_config_serialization_theme_deserialize() {
let toml_file = create_good_toml_theme();
toml_file.as_file().sync_all().unwrap();
toml_file.as_file().seek(SeekFrom::Start(0)).unwrap();
assert!(deserialize::<Theme>(Box::new(toml_file)).is_ok());
let toml_file = create_bad_toml_theme();
toml_file.as_file().sync_all().unwrap();
toml_file.as_file().seek(SeekFrom::Start(0)).unwrap();
assert!(deserialize::<Theme>(Box::new(toml_file)).is_err());
}
fn create_good_toml_bookmarks() -> tempfile::NamedTempFile {
// Write
let mut tmpfile: tempfile::NamedTempFile = tempfile::NamedTempFile::new().unwrap();
let file_content: &str = r#"
[bookmarks]
raspberrypi2 = { address = "192.168.1.31", port = 22, protocol = "SFTP", username = "root", password = "mypassword" }
msi-estrem = { address = "192.168.1.30", port = 22, protocol = "SFTP", username = "cvisintin", password = "mysecret", directory = "/tmp" }
aws-server-prod1 = { address = "51.23.67.12", port = 21, protocol = "FTPS", username = "aws001" }
[bookmarks.my-bucket]
protocol = "S3"
[bookmarks.my-bucket.s3]
bucket = "veeso"
region = "eu-west-1"
endpoint = "http://localhost:9000"
profile = "default"
access_key = "pippo"
secret_access_key = "pluto"
new_path_style = true
[recents]
ISO20201215T094000Z = { address = "172.16.104.10", port = 22, protocol = "SCP", username = "root" }
"#;
tmpfile.write_all(file_content.as_bytes()).unwrap();
//write!(tmpfile, "[bookmarks]\nraspberrypi2 = {{ address = \"192.168.1.31\", port = 22, protocol = \"SFTP\", username = \"root\" }}\nmsi-estrem = {{ address = \"192.168.1.30\", port = 22, protocol = \"SFTP\", username = \"cvisintin\" }}\naws-server-prod1 = {{ address = \"51.23.67.12\", port = 21, protocol = \"FTPS\", username = \"aws001\" }}\n\n[recents]\nISO20201215T094000Z = {{ address = \"172.16.104.10\", port = 22, protocol = \"SCP\", username = \"root\" }}\n");
tmpfile
}
fn create_bad_toml_bookmarks() -> tempfile::NamedTempFile {
// Write
let mut tmpfile: tempfile::NamedTempFile = tempfile::NamedTempFile::new().unwrap();
let file_content: &str = r#"
[bookmarks]
raspberrypi2 = { address = "192.168.1.31", port = 22, protocol = "SFTP", username = "root"}
msi-estrem = { address = "192.168.1.30", port = 22 }
aws-server-prod1 = { address = "51.23.67.12", port = 21, protocol = "FTPS", username = "aws001" }
[recents]
ISO20201215T094000Z = { address = "172.16.104.10", protocol = "SCP", username = "root", port = 22 }
"#;
tmpfile.write_all(file_content.as_bytes()).unwrap();
tmpfile
}
fn create_good_toml_theme() -> tempfile::NamedTempFile {
let mut tmpfile: tempfile::NamedTempFile = tempfile::NamedTempFile::new().unwrap();
let file_content: &str = r##"auth_address = "Yellow"
auth_bookmarks = "LightGreen"
auth_password = "LightBlue"
auth_port = "LightCyan"
auth_protocol = "LightGreen"
auth_recents = "LightBlue"
auth_username = "LightMagenta"
misc_error_dialog = "Red"
misc_info_dialog = "LightYellow"
misc_input_dialog = "240,240,240"
misc_keys = "Cyan"
misc_quit_dialog = "Yellow"
misc_save_dialog = "Cyan"
misc_warn_dialog = "LightRed"
transfer_local_explorer_background = "rgb(240, 240, 240)"
transfer_local_explorer_foreground = "rgb(60, 60, 60)"
transfer_local_explorer_highlighted = "Yellow"
transfer_log_background = "255, 255, 255"
transfer_log_window = "LightGreen"
transfer_progress_bar_full = "forestgreen"
transfer_progress_bar_partial = "Green"
transfer_remote_explorer_background = "#f0f0f0"
transfer_remote_explorer_foreground = "rgb(40, 40, 40)"
transfer_remote_explorer_highlighted = "LightBlue"
transfer_status_hidden = "LightBlue"
transfer_status_sorting = "LightYellow"
transfer_status_sync_browsing = "LightGreen"
"##;
tmpfile.write_all(file_content.as_bytes()).unwrap();
tmpfile
}
fn create_bad_toml_theme() -> tempfile::NamedTempFile {
let mut tmpfile: tempfile::NamedTempFile = tempfile::NamedTempFile::new().unwrap();
let file_content: &str = r#"
auth_address = "Yellow"
auth_bookmarks = "LightGreen"
auth_password = "LightBlue"
auth_port = "LightCyan"
auth_protocol = "LightGreen"
auth_recents = "LightBlue"
auth_username = "LightMagenta"
misc_error_dialog = "Red"
misc_input_dialog = "240,240,240"
misc_keys = "Cyan"
misc_quit_dialog = "Yellow"
misc_warn_dialog = "LightRed"
transfer_local_explorer_text = "rgb(240, 240, 240)"
transfer_local_explorer_window = "Yellow"
transfer_log_text = "255, 255, 255"
transfer_log_window = "LightGreen"
transfer_progress_bar = "Green"
transfer_remote_explorer_text = "verdazzurro"
transfer_remote_explorer_window = "LightBlue"
transfer_status_hidden = "LightBlue"
transfer_status_sorting = "LightYellow"
transfer_status_sync_browsing = "LightGreen"
"#;
tmpfile.write_all(file_content.as_bytes()).unwrap();
tmpfile
}
}

View File

@@ -1,281 +0,0 @@
//! ## Serializer
//!
//! `serializer` is the module which provides the serializer/deserializer for configuration
/**
* MIT License
*
* termscp - Copyright (c) 2021 Christian Visintin
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
use super::{SerializerError, SerializerErrorKind, UserConfig};
use std::io::{Read, Write};
pub struct ConfigSerializer;
impl ConfigSerializer {
/// ### serialize
///
/// Serialize `UserConfig` into TOML and write content to writable
pub fn serialize(
&self,
mut writable: Box<dyn Write>,
cfg: &UserConfig,
) -> Result<(), SerializerError> {
// Serialize content
let data: String = match toml::ser::to_string(cfg) {
Ok(dt) => dt,
Err(err) => {
return Err(SerializerError::new_ex(
SerializerErrorKind::SerializationError,
err.to_string(),
))
}
};
trace!("Serialized new configuration data: {}", data);
// Write file
match writable.write_all(data.as_bytes()) {
Ok(_) => Ok(()),
Err(err) => Err(SerializerError::new_ex(
SerializerErrorKind::IoError,
err.to_string(),
)),
}
}
/// ### deserialize
///
/// Read data from readable and deserialize its content as TOML
pub fn deserialize(&self, mut readable: Box<dyn Read>) -> Result<UserConfig, SerializerError> {
// Read file content
let mut data: String = String::new();
if let Err(err) = readable.read_to_string(&mut data) {
return Err(SerializerError::new_ex(
SerializerErrorKind::IoError,
err.to_string(),
));
}
trace!("Read configuration from file: {}", data);
// Deserialize
match toml::de::from_str(data.as_str()) {
Ok(config) => {
debug!("Read config from file {:?}", config);
Ok(config)
}
Err(err) => Err(SerializerError::new_ex(
SerializerErrorKind::SyntaxError,
err.to_string(),
)),
}
}
}
// Tests
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
use std::io::{Seek, SeekFrom};
use std::path::PathBuf;
#[test]
fn test_config_serializer_deserialize_ok() {
let toml_file: tempfile::NamedTempFile = create_good_toml();
toml_file.as_file().sync_all().unwrap();
toml_file.as_file().seek(SeekFrom::Start(0)).unwrap();
// Parse
let deserializer: ConfigSerializer = ConfigSerializer {};
let cfg = deserializer.deserialize(Box::new(toml_file));
assert!(cfg.is_ok());
let cfg: UserConfig = cfg.ok().unwrap();
// Verify configuration
// Verify ui
assert_eq!(cfg.user_interface.default_protocol, String::from("SCP"));
assert_eq!(cfg.user_interface.text_editor, PathBuf::from("vim"));
assert_eq!(cfg.user_interface.show_hidden_files, true);
assert_eq!(cfg.user_interface.check_for_updates.unwrap(), true);
assert_eq!(cfg.user_interface.group_dirs, Some(String::from("last")));
assert_eq!(
cfg.user_interface.file_fmt,
Some(String::from("{NAME} {PEX}"))
);
assert_eq!(
cfg.user_interface.remote_file_fmt,
Some(String::from("{NAME} {USER}")),
);
// Verify keys
assert_eq!(
*cfg.remote
.ssh_keys
.get(&String::from("192.168.1.31"))
.unwrap(),
PathBuf::from("/home/omar/.ssh/raspberry.key")
);
assert_eq!(
*cfg.remote
.ssh_keys
.get(&String::from("192.168.1.32"))
.unwrap(),
PathBuf::from("/home/omar/.ssh/beaglebone.key")
);
assert!(cfg.remote.ssh_keys.get(&String::from("1.1.1.1")).is_none());
}
#[test]
fn test_config_serializer_deserialize_ok_no_opts() {
let toml_file: tempfile::NamedTempFile = create_good_toml_no_opts();
toml_file.as_file().sync_all().unwrap();
toml_file.as_file().seek(SeekFrom::Start(0)).unwrap();
// Parse
let deserializer: ConfigSerializer = ConfigSerializer {};
let cfg = deserializer.deserialize(Box::new(toml_file));
assert!(cfg.is_ok());
let cfg: UserConfig = cfg.ok().unwrap();
// Verify configuration
// Verify ui
assert_eq!(cfg.user_interface.default_protocol, String::from("SCP"));
assert_eq!(cfg.user_interface.text_editor, PathBuf::from("vim"));
assert_eq!(cfg.user_interface.show_hidden_files, true);
assert_eq!(cfg.user_interface.group_dirs, None);
assert!(cfg.user_interface.check_for_updates.is_none());
assert!(cfg.user_interface.file_fmt.is_none());
assert!(cfg.user_interface.remote_file_fmt.is_none());
// Verify keys
assert_eq!(
*cfg.remote
.ssh_keys
.get(&String::from("192.168.1.31"))
.unwrap(),
PathBuf::from("/home/omar/.ssh/raspberry.key")
);
assert_eq!(
*cfg.remote
.ssh_keys
.get(&String::from("192.168.1.32"))
.unwrap(),
PathBuf::from("/home/omar/.ssh/beaglebone.key")
);
assert!(cfg.remote.ssh_keys.get(&String::from("1.1.1.1")).is_none());
}
#[test]
fn test_config_serializer_deserialize_nok() {
let toml_file: tempfile::NamedTempFile = create_bad_toml();
toml_file.as_file().sync_all().unwrap();
toml_file.as_file().seek(SeekFrom::Start(0)).unwrap();
// Parse
let deserializer: ConfigSerializer = ConfigSerializer {};
assert!(deserializer.deserialize(Box::new(toml_file)).is_err());
}
#[test]
fn test_config_serializer_serialize() {
let mut cfg: UserConfig = UserConfig::default();
let toml_file: tempfile::NamedTempFile = tempfile::NamedTempFile::new().ok().unwrap();
// Insert key
cfg.remote.ssh_keys.insert(
String::from("192.168.1.31"),
PathBuf::from("/home/omar/.ssh/id_rsa"),
);
// Serialize
let serializer: ConfigSerializer = ConfigSerializer {};
let writer: Box<dyn Write> = Box::new(std::fs::File::create(toml_file.path()).unwrap());
assert!(serializer.serialize(writer, &cfg).is_ok());
// Reload configuration and check if it's ok
toml_file.as_file().sync_all().unwrap();
toml_file.as_file().seek(SeekFrom::Start(0)).unwrap();
assert!(serializer.deserialize(Box::new(toml_file)).is_ok());
}
#[test]
fn test_config_serializer_fail_write() {
let toml_file: tempfile::NamedTempFile = tempfile::NamedTempFile::new().ok().unwrap();
let writer: Box<dyn Write> = Box::new(std::fs::File::open(toml_file.path()).unwrap());
// Try to write unexisting file
let serializer: ConfigSerializer = ConfigSerializer {};
let cfg: UserConfig = UserConfig::default();
assert!(serializer.serialize(writer, &cfg).is_err());
}
#[test]
fn test_config_serializer_fail_read() {
let toml_file: tempfile::NamedTempFile = tempfile::NamedTempFile::new().ok().unwrap();
let reader: Box<dyn Read> = Box::new(std::fs::File::open(toml_file.path()).unwrap());
// Try to write unexisting file
let serializer: ConfigSerializer = ConfigSerializer {};
assert!(serializer.deserialize(reader).is_err());
}
fn create_good_toml() -> tempfile::NamedTempFile {
// Write
let mut tmpfile: tempfile::NamedTempFile = tempfile::NamedTempFile::new().unwrap();
let file_content: &str = r#"
[user_interface]
default_protocol = "SCP"
text_editor = "vim"
show_hidden_files = true
check_for_updates = true
group_dirs = "last"
file_fmt = "{NAME} {PEX}"
remote_file_fmt = "{NAME} {USER}"
[remote.ssh_keys]
"192.168.1.31" = "/home/omar/.ssh/raspberry.key"
"192.168.1.32" = "/home/omar/.ssh/beaglebone.key"
"#;
tmpfile.write_all(file_content.as_bytes()).unwrap();
tmpfile
}
fn create_good_toml_no_opts() -> tempfile::NamedTempFile {
// Write
let mut tmpfile: tempfile::NamedTempFile = tempfile::NamedTempFile::new().unwrap();
let file_content: &str = r#"
[user_interface]
default_protocol = "SCP"
text_editor = "vim"
show_hidden_files = true
[remote.ssh_keys]
"192.168.1.31" = "/home/omar/.ssh/raspberry.key"
"192.168.1.32" = "/home/omar/.ssh/beaglebone.key"
"#;
tmpfile.write_all(file_content.as_bytes()).unwrap();
tmpfile
}
fn create_bad_toml() -> tempfile::NamedTempFile {
// Write
let mut tmpfile: tempfile::NamedTempFile = tempfile::NamedTempFile::new().unwrap();
let file_content: &str = r#"
[user_interface]
default_protocol = "SFTP"
[remote.ssh_keys]
"192.168.1.31" = "/home/omar/.ssh/raspberry.key"
"#;
tmpfile.write_all(file_content.as_bytes()).unwrap();
tmpfile
}
}

251
src/config/themes.rs Normal file
View File

@@ -0,0 +1,251 @@
//! ## Themes
//!
//! `themes` is the module which provides the themes configurations and the serializers
// locals
use crate::utils::fmt::fmt_color;
use crate::utils::parser::parse_color;
// ext
use serde::{de::Error as DeError, Deserialize, Deserializer, Serialize, Serializer};
use tuirealm::tui::style::Color;
/// ### Theme
///
/// Theme contains all the colors lookup table for termscp
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct Theme {
// -- auth
#[serde(
deserialize_with = "deserialize_color",
serialize_with = "serialize_color"
)]
pub auth_address: Color,
#[serde(
deserialize_with = "deserialize_color",
serialize_with = "serialize_color"
)]
pub auth_bookmarks: Color,
#[serde(
deserialize_with = "deserialize_color",
serialize_with = "serialize_color"
)]
pub auth_password: Color,
#[serde(
deserialize_with = "deserialize_color",
serialize_with = "serialize_color"
)]
pub auth_port: Color,
#[serde(
deserialize_with = "deserialize_color",
serialize_with = "serialize_color"
)]
pub auth_protocol: Color,
#[serde(
deserialize_with = "deserialize_color",
serialize_with = "serialize_color"
)]
pub auth_recents: Color,
#[serde(
deserialize_with = "deserialize_color",
serialize_with = "serialize_color"
)]
pub auth_username: Color,
// -- misc
#[serde(
deserialize_with = "deserialize_color",
serialize_with = "serialize_color"
)]
pub misc_error_dialog: Color,
#[serde(
deserialize_with = "deserialize_color",
serialize_with = "serialize_color"
)]
pub misc_info_dialog: Color,
#[serde(
deserialize_with = "deserialize_color",
serialize_with = "serialize_color"
)]
pub misc_input_dialog: Color,
#[serde(
deserialize_with = "deserialize_color",
serialize_with = "serialize_color"
)]
pub misc_keys: Color,
#[serde(
deserialize_with = "deserialize_color",
serialize_with = "serialize_color"
)]
pub misc_quit_dialog: Color,
#[serde(
deserialize_with = "deserialize_color",
serialize_with = "serialize_color"
)]
pub misc_save_dialog: Color,
#[serde(
deserialize_with = "deserialize_color",
serialize_with = "serialize_color"
)]
pub misc_warn_dialog: Color,
// -- transfer
#[serde(
deserialize_with = "deserialize_color",
serialize_with = "serialize_color"
)]
pub transfer_local_explorer_background: Color,
#[serde(
deserialize_with = "deserialize_color",
serialize_with = "serialize_color"
)]
pub transfer_local_explorer_foreground: Color,
#[serde(
deserialize_with = "deserialize_color",
serialize_with = "serialize_color"
)]
pub transfer_local_explorer_highlighted: Color,
#[serde(
deserialize_with = "deserialize_color",
serialize_with = "serialize_color"
)]
pub transfer_log_background: Color,
#[serde(
deserialize_with = "deserialize_color",
serialize_with = "serialize_color"
)]
pub transfer_log_window: Color,
#[serde(
deserialize_with = "deserialize_color",
serialize_with = "serialize_color"
)]
pub transfer_progress_bar_full: Color,
#[serde(
deserialize_with = "deserialize_color",
serialize_with = "serialize_color"
)]
pub transfer_progress_bar_partial: Color,
#[serde(
deserialize_with = "deserialize_color",
serialize_with = "serialize_color"
)]
pub transfer_remote_explorer_background: Color,
#[serde(
deserialize_with = "deserialize_color",
serialize_with = "serialize_color"
)]
pub transfer_remote_explorer_foreground: Color,
#[serde(
deserialize_with = "deserialize_color",
serialize_with = "serialize_color"
)]
pub transfer_remote_explorer_highlighted: Color,
#[serde(
deserialize_with = "deserialize_color",
serialize_with = "serialize_color"
)]
pub transfer_status_hidden: Color,
#[serde(
deserialize_with = "deserialize_color",
serialize_with = "serialize_color"
)]
pub transfer_status_sorting: Color,
#[serde(
deserialize_with = "deserialize_color",
serialize_with = "serialize_color"
)]
pub transfer_status_sync_browsing: Color,
}
impl Default for Theme {
fn default() -> Self {
Self {
auth_address: Color::Yellow,
auth_bookmarks: Color::LightGreen,
auth_password: Color::LightBlue,
auth_port: Color::LightCyan,
auth_protocol: Color::LightGreen,
auth_recents: Color::LightBlue,
auth_username: Color::LightMagenta,
misc_error_dialog: Color::Red,
misc_info_dialog: Color::LightYellow,
misc_input_dialog: Color::Reset,
misc_keys: Color::Cyan,
misc_quit_dialog: Color::Yellow,
misc_save_dialog: Color::LightCyan,
misc_warn_dialog: Color::LightRed,
transfer_local_explorer_background: Color::Reset,
transfer_local_explorer_foreground: Color::Reset,
transfer_local_explorer_highlighted: Color::Yellow,
transfer_log_background: Color::Reset,
transfer_log_window: Color::LightGreen,
transfer_progress_bar_partial: Color::Green,
transfer_progress_bar_full: Color::Green,
transfer_remote_explorer_background: Color::Reset,
transfer_remote_explorer_foreground: Color::Reset,
transfer_remote_explorer_highlighted: Color::LightBlue,
transfer_status_hidden: Color::LightBlue,
transfer_status_sorting: Color::LightYellow,
transfer_status_sync_browsing: Color::LightGreen,
}
}
}
// -- deserializer
fn deserialize_color<'de, D>(deserializer: D) -> Result<Color, D::Error>
where
D: Deserializer<'de>,
{
let s: &str = Deserialize::deserialize(deserializer)?;
// Parse color
match parse_color(s) {
None => Err(DeError::custom("Invalid color")),
Some(color) => Ok(color),
}
}
fn serialize_color<S>(color: &Color, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
// Convert color to string
let s: String = fmt_color(color);
serializer.serialize_str(s.as_str())
}
#[cfg(test)]
mod test {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn test_config_themes_default() {
let theme: Theme = Theme::default();
assert_eq!(theme.auth_address, Color::Yellow);
assert_eq!(theme.auth_bookmarks, Color::LightGreen);
assert_eq!(theme.auth_password, Color::LightBlue);
assert_eq!(theme.auth_port, Color::LightCyan);
assert_eq!(theme.auth_protocol, Color::LightGreen);
assert_eq!(theme.auth_recents, Color::LightBlue);
assert_eq!(theme.auth_username, Color::LightMagenta);
assert_eq!(theme.misc_error_dialog, Color::Red);
assert_eq!(theme.misc_info_dialog, Color::LightYellow);
assert_eq!(theme.misc_input_dialog, Color::Reset);
assert_eq!(theme.misc_keys, Color::Cyan);
assert_eq!(theme.misc_quit_dialog, Color::Yellow);
assert_eq!(theme.misc_save_dialog, Color::LightCyan);
assert_eq!(theme.misc_warn_dialog, Color::LightRed);
assert_eq!(theme.transfer_local_explorer_background, Color::Reset);
assert_eq!(theme.transfer_local_explorer_foreground, Color::Reset);
assert_eq!(theme.transfer_local_explorer_highlighted, Color::Yellow);
assert_eq!(theme.transfer_log_background, Color::Reset);
assert_eq!(theme.transfer_log_window, Color::LightGreen);
assert_eq!(theme.transfer_progress_bar_full, Color::Green);
assert_eq!(theme.transfer_progress_bar_partial, Color::Green);
assert_eq!(theme.transfer_remote_explorer_background, Color::Reset);
assert_eq!(theme.transfer_remote_explorer_foreground, Color::Reset);
assert_eq!(theme.transfer_remote_explorer_highlighted, Color::LightBlue);
assert_eq!(theme.transfer_status_hidden, Color::LightBlue);
assert_eq!(theme.transfer_status_sorting, Color::LightYellow);
assert_eq!(theme.transfer_status_sync_browsing, Color::LightGreen);
}
}

View File

@@ -2,45 +2,18 @@
//!
//! `builder` is the module which provides a builder for FileExplorer
/**
* MIT License
*
* termscp - Copyright (c) 2021 Christian Visintin
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// Locals
use super::formatter::Formatter;
use super::{ExplorerOpts, FileExplorer, FileSorting, GroupDirs};
// Ext
use std::collections::VecDeque;
/// ## FileExplorerBuilder
///
/// Struct used to create a `FileExplorer`
pub struct FileExplorerBuilder {
explorer: Option<FileExplorer>,
}
impl FileExplorerBuilder {
/// ### new
///
/// Build a new `FileExplorerBuilder`
pub fn new() -> Self {
FileExplorerBuilder {
@@ -48,15 +21,11 @@ impl FileExplorerBuilder {
}
}
/// ### build
///
/// Take FileExplorer out of builder
pub fn build(&mut self) -> FileExplorer {
self.explorer.take().unwrap()
}
/// ### with_hidden_files
///
/// Enable HIDDEN_FILES option
pub fn with_hidden_files(&mut self, val: bool) -> &mut FileExplorerBuilder {
if let Some(e) = self.explorer.as_mut() {
@@ -68,8 +37,6 @@ impl FileExplorerBuilder {
self
}
/// ### with_file_sorting
///
/// Set sorting method
pub fn with_file_sorting(&mut self, sorting: FileSorting) -> &mut FileExplorerBuilder {
if let Some(e) = self.explorer.as_mut() {
@@ -78,8 +45,6 @@ impl FileExplorerBuilder {
self
}
/// ### with_dirs_first
///
/// Enable DIRS_FIRST option
pub fn with_group_dirs(&mut self, group_dirs: Option<GroupDirs>) -> &mut FileExplorerBuilder {
if let Some(e) = self.explorer.as_mut() {
@@ -88,8 +53,6 @@ impl FileExplorerBuilder {
self
}
/// ### with_stack_size
///
/// Set stack size for FileExplorer
pub fn with_stack_size(&mut self, sz: usize) -> &mut FileExplorerBuilder {
if let Some(e) = self.explorer.as_mut() {
@@ -99,8 +62,6 @@ impl FileExplorerBuilder {
self
}
/// ### with_formatter
///
/// Set formatter for FileExplorer
pub fn with_formatter(&mut self, fmt_str: Option<&str>) -> &mut FileExplorerBuilder {
if let Some(e) = self.explorer.as_mut() {
@@ -124,7 +85,7 @@ mod tests {
let explorer: FileExplorer = FileExplorerBuilder::new().build();
// Verify
assert!(!explorer.opts.intersects(ExplorerOpts::SHOW_HIDDEN_FILES));
assert_eq!(explorer.file_sorting, FileSorting::ByName); // Default
assert_eq!(explorer.file_sorting, FileSorting::Name); // Default
assert_eq!(explorer.group_dirs, None);
assert_eq!(explorer.stack_size, 16);
}
@@ -132,7 +93,7 @@ mod tests {
#[test]
fn test_fs_explorer_builder_new_all() {
let explorer: FileExplorer = FileExplorerBuilder::new()
.with_file_sorting(FileSorting::ByModifyTime)
.with_file_sorting(FileSorting::ModifyTime)
.with_group_dirs(Some(GroupDirs::First))
.with_hidden_files(true)
.with_stack_size(24)
@@ -140,7 +101,7 @@ mod tests {
.build();
// Verify
assert!(explorer.opts.intersects(ExplorerOpts::SHOW_HIDDEN_FILES));
assert_eq!(explorer.file_sorting, FileSorting::ByModifyTime); // Default
assert_eq!(explorer.file_sorting, FileSorting::ModifyTime); // Default
assert_eq!(explorer.group_dirs, Some(GroupDirs::First));
assert_eq!(explorer.stack_size, 24);
}

File diff suppressed because it is too large Load Diff

View File

@@ -2,38 +2,13 @@
//!
//! `explorer` is the module which provides an Helper in handling Directory status through
/**
* MIT License
*
* termscp - Copyright (c) 2021 Christian Visintin
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// Mods
pub(crate) mod builder;
mod formatter;
// Deps
extern crate bitflags;
// Locals
use super::FsEntry;
use formatter::Formatter;
// Ext
use remotefs::fs::File;
use std::cmp::Reverse;
use std::collections::VecDeque;
use std::path::{Path, PathBuf};
@@ -49,19 +24,15 @@ bitflags! {
}
}
/// ## FileSorting
///
/// FileSorting defines the criteria for sorting files
#[derive(Copy, Clone, PartialEq, std::fmt::Debug)]
pub enum FileSorting {
ByName,
ByModifyTime,
ByCreationTime,
BySize,
Name,
ModifyTime,
CreationTime,
Size,
}
/// ## GroupDirs
///
/// GroupDirs defines how directories should be grouped in sorting files
#[derive(PartialEq, std::fmt::Debug)]
pub enum GroupDirs {
@@ -69,8 +40,6 @@ pub enum GroupDirs {
Last,
}
/// ## FileExplorer
///
/// File explorer states
pub struct FileExplorer {
pub wrkdir: PathBuf, // Current directory
@@ -79,8 +48,8 @@ pub struct FileExplorer {
pub(crate) file_sorting: FileSorting, // File sorting criteria
pub(crate) group_dirs: Option<GroupDirs>, // If Some, defines how to group directories
pub(crate) opts: ExplorerOpts, // Explorer options
pub(crate) fmt: Formatter, // FsEntry formatter
files: Vec<FsEntry>, // Files in directory
pub(crate) fmt: Formatter, // File formatter
files: Vec<File>, // Files in directory
}
impl Default for FileExplorer {
@@ -89,7 +58,7 @@ impl Default for FileExplorer {
wrkdir: PathBuf::from("/"),
dirstack: VecDeque::with_capacity(16),
stack_size: 16,
file_sorting: FileSorting::ByName,
file_sorting: FileSorting::Name,
group_dirs: None,
opts: ExplorerOpts::empty(),
fmt: Formatter::default(),
@@ -99,8 +68,6 @@ impl Default for FileExplorer {
}
impl FileExplorer {
/// ### pushd
///
/// push directory to stack
pub fn pushd(&mut self, dir: &Path) {
// Check if stack would overflow the size
@@ -111,26 +78,20 @@ impl FileExplorer {
self.dirstack.push_back(PathBuf::from(dir));
}
/// ### popd
///
/// Pop directory from the stack and return the directory
pub fn popd(&mut self) -> Option<PathBuf> {
self.dirstack.pop_back()
}
/// ### set_files
///
/// Set Explorer files
/// This method will also sort entries based on current options
/// Once all sorting have been performed, index is moved to first valid entry.
pub fn set_files(&mut self, files: Vec<FsEntry>) {
pub fn set_files(&mut self, files: Vec<File>) {
self.files = files;
// Sort
self.sort();
}
/// ### del_entry
///
/// Delete file at provided index
pub fn del_entry(&mut self, idx: usize) {
if self.files.len() > idx {
@@ -139,19 +100,15 @@ impl FileExplorer {
}
/*
/// ### count
///
/// Return amount of files
pub fn count(&self) -> usize {
self.files.len()
}
*/
/// ### iter_files
///
/// Iterate over files
/// Filters are applied based on current options (e.g. hidden files not returned)
pub fn iter_files(&self) -> impl Iterator<Item = &FsEntry> + '_ {
pub fn iter_files(&self) -> impl Iterator<Item = &File> + '_ {
// Filter
let opts: ExplorerOpts = self.opts;
Box::new(self.files.iter().filter(move |x| {
@@ -165,17 +122,13 @@ impl FileExplorer {
}))
}
/// ### iter_files_all
///
/// Iterate all files; doesn't care about options
pub fn iter_files_all(&self) -> impl Iterator<Item = &FsEntry> + '_ {
pub fn iter_files_all(&self) -> impl Iterator<Item = &File> + '_ {
Box::new(self.files.iter())
}
/// ### get
///
/// Get file at relative index
pub fn get(&self, idx: usize) -> Option<&FsEntry> {
pub fn get(&self, idx: usize) -> Option<&File> {
let opts: ExplorerOpts = self.opts;
let filtered = self
.files
@@ -195,17 +148,13 @@ impl FileExplorer {
// Formatting
/// ### fmt_file
///
/// Format a file entry
pub fn fmt_file(&self, entry: &FsEntry) -> String {
pub fn fmt_file(&self, entry: &File) -> String {
self.fmt.fmt(entry)
}
// Sorting
/// ### sort_by
///
/// Choose sorting method; then sort files
pub fn sort_by(&mut self, sorting: FileSorting) {
// If method HAS ACTUALLY CHANGED, sort (performance!)
@@ -215,15 +164,11 @@ impl FileExplorer {
}
}
/// ### get_file_sorting
///
/// Get current file sorting method
pub fn get_file_sorting(&self) -> FileSorting {
self.file_sorting
}
/// ### group_dirs_by
///
/// Choose group dirs method; then sort files
pub fn group_dirs_by(&mut self, group_dirs: Option<GroupDirs>) {
// If method HAS ACTUALLY CHANGED, sort (performance!)
@@ -233,16 +178,14 @@ impl FileExplorer {
}
}
/// ### sort
///
/// Sort files based on Explorer options.
fn sort(&mut self) {
// Choose sorting method
match &self.file_sorting {
FileSorting::ByName => self.sort_files_by_name(),
FileSorting::ByCreationTime => self.sort_files_by_creation_time(),
FileSorting::ByModifyTime => self.sort_files_by_mtime(),
FileSorting::BySize => self.sort_files_by_size(),
FileSorting::Name => self.sort_files_by_name(),
FileSorting::CreationTime => self.sort_files_by_creation_time(),
FileSorting::ModifyTime => self.sort_files_by_mtime(),
FileSorting::Size => self.sort_files_by_size(),
}
// Directories first (NOTE: MUST COME AFTER OTHER SORTING)
// Group directories if necessary
@@ -254,61 +197,44 @@ impl FileExplorer {
}
}
/// ### sort_files_by_name
///
/// Sort explorer files by their name. All names are converted to lowercase
fn sort_files_by_name(&mut self) {
self.files
.sort_by_key(|x: &FsEntry| x.get_name().to_lowercase());
self.files.sort_by_key(|x: &File| x.name().to_lowercase());
}
/// ### sort_files_by_mtime
///
/// Sort files by mtime; the newest comes first
fn sort_files_by_mtime(&mut self) {
self.files.sort_by(|a: &FsEntry, b: &FsEntry| {
b.get_last_change_time().cmp(&a.get_last_change_time())
});
self.files
.sort_by_key(|b: &File| Reverse(b.metadata().modified));
}
/// ### sort_files_by_creation_time
///
/// Sort files by creation time; the newest comes first
fn sort_files_by_creation_time(&mut self) {
self.files
.sort_by_key(|b: &FsEntry| Reverse(b.get_creation_time()));
.sort_by_key(|b: &File| Reverse(b.metadata().created));
}
/// ### sort_files_by_size
///
/// Sort files by size
fn sort_files_by_size(&mut self) {
self.files.sort_by_key(|b: &FsEntry| Reverse(b.get_size()));
self.files
.sort_by_key(|b: &File| Reverse(b.metadata().size));
}
/// ### sort_files_directories_first
///
/// Sort files; directories come first
fn sort_files_directories_first(&mut self) {
self.files.sort_by_key(|x: &FsEntry| x.is_file());
self.files.sort_by_key(|x: &File| !x.is_dir());
}
/// ### sort_files_directories_last
///
/// Sort files; directories come last
fn sort_files_directories_last(&mut self) {
self.files.sort_by_key(|x: &FsEntry| x.is_dir());
self.files.sort_by_key(|x: &File| x.is_dir());
}
/// ### toggle_hidden_files
///
/// Enable/disable hidden files
pub fn toggle_hidden_files(&mut self) {
self.opts.toggle(ExplorerOpts::SHOW_HIDDEN_FILES);
}
/// ### hidden_files_visible
///
/// Returns whether hidden files are visible
pub fn hidden_files_visible(&self) -> bool {
self.opts.intersects(ExplorerOpts::SHOW_HIDDEN_FILES)
@@ -320,10 +246,10 @@ impl FileExplorer {
impl ToString for FileSorting {
fn to_string(&self) -> String {
String::from(match self {
FileSorting::ByCreationTime => "by_creation_time",
FileSorting::ByModifyTime => "by_mtime",
FileSorting::ByName => "by_name",
FileSorting::BySize => "by_size",
FileSorting::CreationTime => "by_creation_time",
FileSorting::ModifyTime => "by_mtime",
FileSorting::Name => "by_name",
FileSorting::Size => "by_size",
})
}
}
@@ -332,10 +258,10 @@ impl FromStr for FileSorting {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_ascii_lowercase().as_str() {
"by_creation_time" => Ok(FileSorting::ByCreationTime),
"by_mtime" => Ok(FileSorting::ByModifyTime),
"by_name" => Ok(FileSorting::ByName),
"by_size" => Ok(FileSorting::BySize),
"by_creation_time" => Ok(FileSorting::CreationTime),
"by_mtime" => Ok(FileSorting::ModifyTime),
"by_name" => Ok(FileSorting::Name),
"by_size" => Ok(FileSorting::Size),
_ => Err(()),
}
}
@@ -365,10 +291,10 @@ impl FromStr for GroupDirs {
mod tests {
use super::*;
use crate::fs::{FsDirectory, FsFile};
use crate::utils::fmt::fmt_time;
use pretty_assertions::assert_eq;
use remotefs::fs::{File, FileType, Metadata, UnixPex};
use std::thread::sleep;
use std::time::{Duration, SystemTime};
@@ -382,8 +308,8 @@ mod tests {
assert_eq!(explorer.wrkdir, PathBuf::from("/"));
assert_eq!(explorer.stack_size, 16);
assert_eq!(explorer.group_dirs, None);
assert_eq!(explorer.file_sorting, FileSorting::ByName);
assert_eq!(explorer.get_file_sorting(), FileSorting::ByName);
assert_eq!(explorer.file_sorting, FileSorting::Name);
assert_eq!(explorer.get_file_sorting(), FileSorting::Name);
}
#[test]
@@ -422,8 +348,8 @@ mod tests {
// Create files
explorer.set_files(vec![
make_fs_entry("README.md", false),
make_fs_entry("src/", true),
make_fs_entry(".git/", true),
make_fs_entry("src", true),
make_fs_entry(".git", true),
make_fs_entry("CONTRIBUTING.md", false),
make_fs_entry("codecov.yml", false),
make_fs_entry(".gitignore", false),
@@ -432,10 +358,7 @@ mod tests {
assert!(explorer.get(100).is_none());
//assert_eq!(explorer.count(), 6);
// Verify (files are sorted by name)
assert_eq!(
explorer.files.get(0).unwrap().get_name(),
String::from(".git/")
);
assert_eq!(explorer.files.get(0).unwrap().name(), ".git");
// Iter files (all)
assert_eq!(explorer.iter_files_all().count(), 6);
// Iter files (hidden excluded) (.git, .gitignore are hidden)
@@ -452,7 +375,7 @@ mod tests {
// Create files (files are then sorted by name)
explorer.set_files(vec![
make_fs_entry("README.md", false),
make_fs_entry("src/", true),
make_fs_entry("src", true),
make_fs_entry("CONTRIBUTING.md", false),
make_fs_entry("CODE_OF_CONDUCT.md", false),
make_fs_entry("CHANGELOG.md", false),
@@ -461,49 +384,43 @@ mod tests {
make_fs_entry("Cargo.lock", false),
make_fs_entry("codecov.yml", false),
]);
explorer.sort_by(FileSorting::ByName);
explorer.sort_by(FileSorting::Name);
// First entry should be "Cargo.lock"
assert_eq!(explorer.files.get(0).unwrap().get_name(), "Cargo.lock");
// Last should be "src/"
assert_eq!(explorer.files.get(8).unwrap().get_name(), "src/");
assert_eq!(explorer.files.get(0).unwrap().name(), "Cargo.lock");
// Last should be "src"
assert_eq!(explorer.files.get(8).unwrap().name(), "src");
}
#[test]
fn test_fs_explorer_sort_by_mtime() {
let mut explorer: FileExplorer = FileExplorer::default();
let entry1: FsEntry = make_fs_entry("README.md", false);
let entry1: File = make_fs_entry("README.md", false);
// Wait 1 sec
sleep(Duration::from_secs(1));
let entry2: FsEntry = make_fs_entry("CODE_OF_CONDUCT.md", false);
let entry2: File = make_fs_entry("CODE_OF_CONDUCT.md", false);
// Create files (files are then sorted by name)
explorer.set_files(vec![entry1, entry2]);
explorer.sort_by(FileSorting::ByModifyTime);
explorer.sort_by(FileSorting::ModifyTime);
// First entry should be "CODE_OF_CONDUCT.md"
assert_eq!(
explorer.files.get(0).unwrap().get_name(),
"CODE_OF_CONDUCT.md"
);
// Last should be "src/"
assert_eq!(explorer.files.get(1).unwrap().get_name(), "README.md");
assert_eq!(explorer.files.get(0).unwrap().name(), "CODE_OF_CONDUCT.md");
// Last should be "src"
assert_eq!(explorer.files.get(1).unwrap().name(), "README.md");
}
#[test]
fn test_fs_explorer_sort_by_creation_time() {
let mut explorer: FileExplorer = FileExplorer::default();
let entry1: FsEntry = make_fs_entry("README.md", false);
let entry1: File = make_fs_entry("README.md", false);
// Wait 1 sec
sleep(Duration::from_secs(1));
let entry2: FsEntry = make_fs_entry("CODE_OF_CONDUCT.md", false);
let entry2: File = make_fs_entry("CODE_OF_CONDUCT.md", false);
// Create files (files are then sorted by name)
explorer.set_files(vec![entry1, entry2]);
explorer.sort_by(FileSorting::ByCreationTime);
explorer.sort_by(FileSorting::CreationTime);
// First entry should be "CODE_OF_CONDUCT.md"
assert_eq!(
explorer.files.get(0).unwrap().get_name(),
"CODE_OF_CONDUCT.md"
);
// Last should be "src/"
assert_eq!(explorer.files.get(1).unwrap().get_name(), "README.md");
assert_eq!(explorer.files.get(0).unwrap().name(), "CODE_OF_CONDUCT.md");
// Last should be "src"
assert_eq!(explorer.files.get(1).unwrap().name(), "README.md");
}
#[test]
@@ -512,14 +429,14 @@ mod tests {
// Create files (files are then sorted by name)
explorer.set_files(vec![
make_fs_entry_with_size("README.md", false, 1024),
make_fs_entry("src/", true),
make_fs_entry_with_size("src", true, 4096),
make_fs_entry_with_size("CONTRIBUTING.md", false, 256),
]);
explorer.sort_by(FileSorting::BySize);
explorer.sort_by(FileSorting::Size);
// Directory has size 4096
assert_eq!(explorer.files.get(0).unwrap().get_name(), "src/");
assert_eq!(explorer.files.get(1).unwrap().get_name(), "README.md");
assert_eq!(explorer.files.get(2).unwrap().get_name(), "CONTRIBUTING.md");
assert_eq!(explorer.files.get(0).unwrap().name(), "src");
assert_eq!(explorer.files.get(1).unwrap().name(), "README.md");
assert_eq!(explorer.files.get(2).unwrap().name(), "CONTRIBUTING.md");
}
#[test]
@@ -528,8 +445,8 @@ mod tests {
// Create files (files are then sorted by name)
explorer.set_files(vec![
make_fs_entry("README.md", false),
make_fs_entry("src/", true),
make_fs_entry("docs/", true),
make_fs_entry("src", true),
make_fs_entry("docs", true),
make_fs_entry("CONTRIBUTING.md", false),
make_fs_entry("CODE_OF_CONDUCT.md", false),
make_fs_entry("CHANGELOG.md", false),
@@ -538,15 +455,15 @@ mod tests {
make_fs_entry("Cargo.lock", false),
make_fs_entry("codecov.yml", false),
]);
explorer.sort_by(FileSorting::ByName);
explorer.sort_by(FileSorting::Name);
explorer.group_dirs_by(Some(GroupDirs::First));
// First entry should be "docs"
assert_eq!(explorer.files.get(0).unwrap().get_name(), "docs/");
assert_eq!(explorer.files.get(1).unwrap().get_name(), "src/");
assert_eq!(explorer.files.get(0).unwrap().name(), "docs");
assert_eq!(explorer.files.get(1).unwrap().name(), "src");
// 3rd is file first for alphabetical order
assert_eq!(explorer.files.get(2).unwrap().get_name(), "Cargo.lock");
assert_eq!(explorer.files.get(2).unwrap().name(), "Cargo.lock");
// Last should be "README.md" (last file for alphabetical ordening)
assert_eq!(explorer.files.get(9).unwrap().get_name(), "README.md");
assert_eq!(explorer.files.get(9).unwrap().name(), "README.md");
}
#[test]
@@ -555,8 +472,8 @@ mod tests {
// Create files (files are then sorted by name)
explorer.set_files(vec![
make_fs_entry("README.md", false),
make_fs_entry("src/", true),
make_fs_entry("docs/", true),
make_fs_entry("src", true),
make_fs_entry("docs", true),
make_fs_entry("CONTRIBUTING.md", false),
make_fs_entry("CODE_OF_CONDUCT.md", false),
make_fs_entry("CHANGELOG.md", false),
@@ -565,15 +482,15 @@ mod tests {
make_fs_entry("Cargo.lock", false),
make_fs_entry("codecov.yml", false),
]);
explorer.sort_by(FileSorting::ByName);
explorer.sort_by(FileSorting::Name);
explorer.group_dirs_by(Some(GroupDirs::Last));
// Last entry should be "src"
assert_eq!(explorer.files.get(8).unwrap().get_name(), "docs/");
assert_eq!(explorer.files.get(9).unwrap().get_name(), "src/");
assert_eq!(explorer.files.get(8).unwrap().name(), "docs");
assert_eq!(explorer.files.get(9).unwrap().name(), "src");
// first is file for alphabetical order
assert_eq!(explorer.files.get(0).unwrap().get_name(), "Cargo.lock");
assert_eq!(explorer.files.get(0).unwrap().name(), "Cargo.lock");
// Last in files should be "README.md" (last file for alphabetical ordening)
assert_eq!(explorer.files.get(7).unwrap().get_name(), "README.md");
assert_eq!(explorer.files.get(7).unwrap().name(), "README.md");
}
#[test]
@@ -581,20 +498,20 @@ mod tests {
let explorer: FileExplorer = FileExplorer::default();
// Create fs entry
let t: SystemTime = SystemTime::now();
let entry: FsEntry = FsEntry::File(FsFile {
name: String::from("bar.txt"),
abs_path: PathBuf::from("/bar.txt"),
last_change_time: t,
last_access_time: t,
creation_time: t,
size: 8192,
readonly: false,
ftype: Some(String::from("txt")),
symlink: None, // UNIX only
user: Some(0), // UNIX only
group: Some(0), // UNIX only
unix_pex: Some((6, 4, 4)), // UNIX only
});
let entry = File {
path: PathBuf::from("/bar.txt"),
metadata: Metadata {
accessed: Some(t),
created: Some(t),
modified: Some(t),
file_type: FileType::File,
size: 8192,
symlink: None,
uid: Some(0),
gid: Some(0),
mode: Some(UnixPex::from(0o644)),
},
};
#[cfg(target_family = "unix")]
assert_eq!(
explorer.fmt_file(&entry),
@@ -616,25 +533,25 @@ mod tests {
#[test]
fn test_fs_explorer_to_string_from_str_traits() {
// File Sorting
assert_eq!(FileSorting::ByCreationTime.to_string(), "by_creation_time");
assert_eq!(FileSorting::ByModifyTime.to_string(), "by_mtime");
assert_eq!(FileSorting::ByName.to_string(), "by_name");
assert_eq!(FileSorting::BySize.to_string(), "by_size");
assert_eq!(FileSorting::CreationTime.to_string(), "by_creation_time");
assert_eq!(FileSorting::ModifyTime.to_string(), "by_mtime");
assert_eq!(FileSorting::Name.to_string(), "by_name");
assert_eq!(FileSorting::Size.to_string(), "by_size");
assert_eq!(
FileSorting::from_str("by_creation_time").ok().unwrap(),
FileSorting::ByCreationTime
FileSorting::CreationTime
);
assert_eq!(
FileSorting::from_str("by_mtime").ok().unwrap(),
FileSorting::ByModifyTime
FileSorting::ModifyTime
);
assert_eq!(
FileSorting::from_str("by_name").ok().unwrap(),
FileSorting::ByName
FileSorting::Name
);
assert_eq!(
FileSorting::from_str("by_size").ok().unwrap(),
FileSorting::BySize
FileSorting::Size
);
assert!(FileSorting::from_str("omar").is_err());
// Group dirs
@@ -651,78 +568,60 @@ mod tests {
// Create files (files are then sorted by name)
explorer.set_files(vec![
make_fs_entry("CONTRIBUTING.md", false),
make_fs_entry("docs/", true),
make_fs_entry("src/", true),
make_fs_entry("docs", true),
make_fs_entry("src", true),
make_fs_entry("README.md", false),
]);
explorer.del_entry(0);
assert_eq!(explorer.files.len(), 3);
assert_eq!(explorer.files[0].get_name(), "docs/");
assert_eq!(explorer.files[0].name(), "docs");
explorer.del_entry(5);
assert_eq!(explorer.files.len(), 3);
}
fn make_fs_entry(name: &str, is_dir: bool) -> FsEntry {
let t_now: SystemTime = SystemTime::now();
match is_dir {
false => FsEntry::File(FsFile {
name: name.to_string(),
abs_path: PathBuf::from(name),
last_change_time: t_now,
last_access_time: t_now,
creation_time: t_now,
size: 64,
ftype: None, // File type
readonly: false,
symlink: None, // UNIX only
user: Some(0), // UNIX only
group: Some(0), // UNIX only
unix_pex: Some((6, 4, 4)), // UNIX only
}),
true => FsEntry::Directory(FsDirectory {
name: name.to_string(),
abs_path: PathBuf::from(name),
last_change_time: t_now,
last_access_time: t_now,
creation_time: t_now,
readonly: false,
symlink: None, // UNIX only
user: Some(0), // UNIX only
group: Some(0), // UNIX only
unix_pex: Some((7, 5, 5)), // UNIX only
}),
fn make_fs_entry(name: &str, is_dir: bool) -> File {
let t: SystemTime = SystemTime::now();
let metadata = Metadata {
accessed: Some(t),
created: Some(t),
modified: Some(t),
file_type: if is_dir {
FileType::Directory
} else {
FileType::File
},
symlink: None,
gid: Some(0),
uid: Some(0),
mode: Some(UnixPex::from(if is_dir { 0o755 } else { 0o644 })),
size: 64,
};
File {
path: PathBuf::from(name),
metadata,
}
}
fn make_fs_entry_with_size(name: &str, is_dir: bool, size: usize) -> FsEntry {
let t_now: SystemTime = SystemTime::now();
match is_dir {
false => FsEntry::File(FsFile {
name: name.to_string(),
abs_path: PathBuf::from(name),
last_change_time: t_now,
last_access_time: t_now,
creation_time: t_now,
size: size,
ftype: None, // File type
readonly: false,
symlink: None, // UNIX only
user: Some(0), // UNIX only
group: Some(0), // UNIX only
unix_pex: Some((6, 4, 4)), // UNIX only
}),
true => FsEntry::Directory(FsDirectory {
name: name.to_string(),
abs_path: PathBuf::from(name),
last_change_time: t_now,
last_access_time: t_now,
creation_time: t_now,
readonly: false,
symlink: None, // UNIX only
user: Some(0), // UNIX only
group: Some(0), // UNIX only
unix_pex: Some((7, 5, 5)), // UNIX only
}),
fn make_fs_entry_with_size(name: &str, is_dir: bool, size: usize) -> File {
let t: SystemTime = SystemTime::now();
let metadata = Metadata {
accessed: Some(t),
created: Some(t),
modified: Some(t),
file_type: if is_dir {
FileType::Directory
} else {
FileType::File
},
symlink: None,
gid: Some(0),
uid: Some(0),
mode: Some(UnixPex::from(if is_dir { 0o755 } else { 0o644 })),
size: size as u64,
};
File {
path: PathBuf::from(name),
metadata,
}
}
}

218
src/filetransfer/builder.rs Normal file
View File

@@ -0,0 +1,218 @@
//! ## builder
//!
//! Remotefs client builder
use super::params::{AwsS3Params, GenericProtocolParams};
use super::{FileTransferProtocol, ProtocolParams};
use crate::system::config_client::ConfigClient;
use crate::system::sshkey_storage::SshKeyStorage;
use remotefs::RemoteFs;
use remotefs_aws_s3::AwsS3Fs;
use remotefs_ftp::FtpFs;
use remotefs_ssh::{ScpFs, SftpFs, SshOpts};
use std::path::PathBuf;
/// Remotefs builder
pub struct Builder;
impl Builder {
/// Build RemoteFs client from protocol and params.
///
/// if protocol and parameters are inconsistent, the function will panic.
pub fn build(
protocol: FileTransferProtocol,
params: ProtocolParams,
config_client: &ConfigClient,
) -> Box<dyn RemoteFs> {
match (protocol, params) {
(FileTransferProtocol::AwsS3, ProtocolParams::AwsS3(params)) => {
Box::new(Self::aws_s3_client(params))
}
(FileTransferProtocol::Ftp(secure), ProtocolParams::Generic(params)) => {
Box::new(Self::ftp_client(params, secure))
}
(FileTransferProtocol::Scp, ProtocolParams::Generic(params)) => {
Box::new(Self::scp_client(params, config_client))
}
(FileTransferProtocol::Sftp, ProtocolParams::Generic(params)) => {
Box::new(Self::sftp_client(params, config_client))
}
(protocol, params) => {
error!("Invalid params for protocol '{:?}'", protocol);
panic!(
"Invalid protocol '{:?}' with parameters of type {:?}",
protocol, params
)
}
}
}
/// Build aws s3 client from parameters
fn aws_s3_client(params: AwsS3Params) -> AwsS3Fs {
let mut client = AwsS3Fs::new(params.bucket_name).new_path_style(params.new_path_style);
if let Some(region) = params.region {
client = client.region(region);
}
if let Some(profile) = params.profile {
client = client.profile(profile);
}
if let Some(endpoint) = params.endpoint {
client = client.endpoint(endpoint);
}
if let Some(access_key) = params.access_key {
client = client.access_key(access_key);
}
if let Some(secret_access_key) = params.secret_access_key {
client = client.secret_access_key(secret_access_key);
}
if let Some(security_token) = params.security_token {
client = client.security_token(security_token);
}
if let Some(session_token) = params.session_token {
client = client.session_token(session_token);
}
client
}
/// Build ftp client from parameters
fn ftp_client(params: GenericProtocolParams, secure: bool) -> FtpFs {
let mut client = FtpFs::new(params.address, params.port).passive_mode();
if let Some(username) = params.username {
client = client.username(username);
}
if let Some(password) = params.password {
client = client.password(password);
}
if secure {
client = client.secure(true, true);
}
client
}
/// Build scp client
fn scp_client(params: GenericProtocolParams, config_client: &ConfigClient) -> ScpFs {
Self::build_ssh_opts(params, config_client).into()
}
/// Build sftp client
fn sftp_client(params: GenericProtocolParams, config_client: &ConfigClient) -> SftpFs {
Self::build_ssh_opts(params, config_client).into()
}
/// Build ssh options from generic protocol params and client configuration
fn build_ssh_opts(params: GenericProtocolParams, config_client: &ConfigClient) -> SshOpts {
let mut opts = SshOpts::new(params.address)
.key_storage(Box::new(Self::make_ssh_storage(config_client)))
.port(params.port);
if let Some(username) = params.username {
opts = opts.username(username);
}
if let Some(password) = params.password {
opts = opts.password(password);
}
if let Some(config_path) = config_client.get_ssh_config() {
opts = opts.config_file(PathBuf::from(config_path));
}
opts
}
/// Make ssh storage from `ConfigClient` if possible, empty otherwise (empty is implicit if degraded)
fn make_ssh_storage(config_client: &ConfigClient) -> SshKeyStorage {
SshKeyStorage::from(config_client)
}
}
#[cfg(test)]
mod test {
use super::*;
use std::path::{Path, PathBuf};
use tempfile::TempDir;
#[test]
fn should_build_aws_s3_fs() {
let params = ProtocolParams::AwsS3(
AwsS3Params::new("omar", Some("eu-west-1"), Some("test"))
.endpoint(Some("http://localhost:9000"))
.new_path_style(true)
.access_key(Some("pippo"))
.secret_access_key(Some("pluto"))
.security_token(Some("omar"))
.session_token(Some("gerry-scotti")),
);
let config_client = get_config_client();
let _ = Builder::build(FileTransferProtocol::AwsS3, params, &config_client);
}
#[test]
fn should_build_ftp_fs() {
let params = ProtocolParams::Generic(
GenericProtocolParams::default()
.address("127.0.0.1")
.port(21)
.username(Some("omar"))
.password(Some("qwerty123")),
);
let config_client = get_config_client();
let _ = Builder::build(FileTransferProtocol::Ftp(true), params, &config_client);
}
#[test]
fn should_build_scp_fs() {
let params = ProtocolParams::Generic(
GenericProtocolParams::default()
.address("127.0.0.1")
.port(22)
.username(Some("omar"))
.password(Some("qwerty123")),
);
let config_client = get_config_client();
let _ = Builder::build(FileTransferProtocol::Scp, params, &config_client);
}
#[test]
fn should_build_sftp_fs() {
let params = ProtocolParams::Generic(
GenericProtocolParams::default()
.address("127.0.0.1")
.port(22)
.username(Some("omar"))
.password(Some("qwerty123")),
);
let config_client = get_config_client();
let _ = Builder::build(FileTransferProtocol::Sftp, params, &config_client);
}
#[test]
#[should_panic]
fn should_not_build_fs() {
let params = ProtocolParams::Generic(
GenericProtocolParams::default()
.address("127.0.0.1")
.port(22)
.username(Some("omar"))
.password(Some("qwerty123")),
);
let config_client = get_config_client();
let _ = Builder::build(FileTransferProtocol::AwsS3, params, &config_client);
}
fn get_config_client() -> ConfigClient {
let tmp_dir: TempDir = TempDir::new().ok().unwrap();
let (cfg_path, ssh_keys_path): (PathBuf, PathBuf) = get_paths(tmp_dir.path());
ConfigClient::new(cfg_path.as_path(), ssh_keys_path.as_path())
.ok()
.unwrap()
}
/// Get paths for configuration and keys directory
fn get_paths(dir: &Path) -> (PathBuf, PathBuf) {
let mut k: PathBuf = PathBuf::from(dir);
let mut c: PathBuf = k.clone();
k.push("ssh-keys/");
c.push("config.toml");
(c, k)
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,303 +1,22 @@
//! ## FileTransfer
//!
//! `filetransfer` is the module which provides the trait file transfers must implement and the different file transfers
//! `filetransfer` is the module which provides the file transfer protocols and remotefs builders
/**
* MIT License
*
* termscp - Copyright (c) 2021 Christian Visintin
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// dependencies
extern crate wildmatch;
// locals
use crate::fs::{FsEntry, FsFile};
// ext
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use thiserror::Error;
use wildmatch::WildMatch;
// exports
pub mod ftp_transfer;
pub mod scp_transfer;
pub mod sftp_transfer;
mod builder;
pub mod params;
// -- export types
pub use builder::Builder;
pub use params::{FileTransferParams, ProtocolParams};
/// ## FileTransferProtocol
///
/// This enum defines the different transfer protocol available in termscp
#[derive(PartialEq, std::fmt::Debug, std::clone::Clone, Copy)]
#[derive(PartialEq, Debug, Clone, Copy)]
pub enum FileTransferProtocol {
Sftp,
Scp,
Ftp(bool), // Bool is for secure (true => ftps)
}
/// ## FileTransferError
///
/// FileTransferError defines the possible errors available for a file transfer
#[derive(std::fmt::Debug)]
pub struct FileTransferError {
code: FileTransferErrorType,
msg: Option<String>,
}
impl FileTransferError {
/// ### kind
///
/// Returns the error kind
pub fn kind(&self) -> FileTransferErrorType {
self.code
}
}
/// ## FileTransferErrorType
///
/// FileTransferErrorType defines the possible errors available for a file transfer
#[derive(Error, Debug, Clone, Copy, PartialEq)]
pub enum FileTransferErrorType {
#[error("Authentication failed")]
AuthenticationFailed,
#[error("Bad address syntax")]
BadAddress,
#[error("Connection error")]
ConnectionError,
#[error("SSL error")]
SslError,
#[error("Could not stat directory")]
DirStatFailed,
#[error("Failed to create file")]
FileCreateDenied,
#[error("No such file or directory")]
NoSuchFileOrDirectory,
#[error("Not enough permissions")]
PexError,
#[error("Protocol error")]
ProtocolError,
#[error("Uninitialized session")]
UninitializedSession,
#[error("Unsupported feature")]
UnsupportedFeature,
}
impl FileTransferError {
/// ### new
///
/// Instantiates a new FileTransferError
pub fn new(code: FileTransferErrorType) -> FileTransferError {
FileTransferError { code, msg: None }
}
/// ### new_ex
///
/// Instantiates a new FileTransferError with message
pub fn new_ex(code: FileTransferErrorType, msg: String) -> FileTransferError {
let mut err: FileTransferError = FileTransferError::new(code);
err.msg = Some(msg);
err
}
}
impl std::fmt::Display for FileTransferError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match &self.msg {
Some(msg) => write!(f, "{} ({})", self.code, msg),
None => write!(f, "{}", self.code),
}
}
}
/// ## FileTransfer
///
/// File transfer trait must be implemented by all the file transfers and defines the method used by a generic file transfer
pub trait FileTransfer {
/// ### connect
///
/// Connect to the remote server
/// Can return banner / welcome message on success
fn connect(
&mut self,
address: String,
port: u16,
username: Option<String>,
password: Option<String>,
) -> Result<Option<String>, FileTransferError>;
/// ### disconnect
///
/// Disconnect from the remote server
fn disconnect(&mut self) -> Result<(), FileTransferError>;
/// ### is_connected
///
/// Indicates whether the client is connected to remote
fn is_connected(&self) -> bool;
/// ### pwd
///
/// Print working directory
fn pwd(&mut self) -> Result<PathBuf, FileTransferError>;
/// ### change_dir
///
/// Change working directory
fn change_dir(&mut self, dir: &Path) -> Result<PathBuf, FileTransferError>;
/// ### copy
///
/// Copy file to destination
fn copy(&mut self, src: &FsEntry, dst: &Path) -> Result<(), FileTransferError>;
/// ### list_dir
///
/// List directory entries
fn list_dir(&mut self, path: &Path) -> Result<Vec<FsEntry>, FileTransferError>;
/// ### mkdir
///
/// Make directory
/// You must return error in case the directory already exists
fn mkdir(&mut self, dir: &Path) -> Result<(), FileTransferError>;
/// ### remove
///
/// Remove a file or a directory
fn remove(&mut self, file: &FsEntry) -> Result<(), FileTransferError>;
/// ### rename
///
/// Rename file or a directory
fn rename(&mut self, file: &FsEntry, dst: &Path) -> Result<(), FileTransferError>;
/// ### stat
///
/// Stat file and return FsEntry
fn stat(&mut self, path: &Path) -> Result<FsEntry, FileTransferError>;
/// ### exec
///
/// Execute a command on remote host
fn exec(&mut self, cmd: &str) -> Result<String, FileTransferError>;
/// ### send_file
///
/// Send file to remote
/// File name is referred to the name of the file as it will be saved
/// Data contains the file data
/// Returns file and its size
fn send_file(
&mut self,
local: &FsFile,
file_name: &Path,
) -> Result<Box<dyn Write>, FileTransferError>;
/// ### recv_file
///
/// Receive file from remote with provided name
/// Returns file and its size
fn recv_file(&mut self, file: &FsFile) -> Result<Box<dyn Read>, FileTransferError>;
/// ### on_sent
///
/// Finalize send method.
/// This method must be implemented only if necessary; in case you don't need it, just return `Ok(())`
/// The purpose of this method is to finalize the connection with the peer when writing data.
/// This is necessary for some protocols such as FTP.
/// You must call this method each time you want to finalize the write of the remote file.
fn on_sent(&mut self, writable: Box<dyn Write>) -> Result<(), FileTransferError>;
/// ### on_recv
///
/// Finalize recv method.
/// This method must be implemented only if necessary; in case you don't need it, just return `Ok(())`
/// The purpose of this method is to finalize the connection with the peer when reading data.
/// This mighe be necessary for some protocols.
/// You must call this method each time you want to finalize the read of the remote file.
fn on_recv(&mut self, readable: Box<dyn Read>) -> Result<(), FileTransferError>;
/// ### find
///
/// Find files from current directory (in all subdirectories) whose name matches the provided search
/// Search supports wildcards ('?', '*')
fn find(&mut self, search: &str) -> Result<Vec<FsEntry>, FileTransferError> {
match self.is_connected() {
true => {
// Starting from current directory, iter dir
match self.pwd() {
Ok(p) => self.iter_search(p.as_path(), &WildMatch::new(search)),
Err(err) => Err(err),
}
}
false => Err(FileTransferError::new(
FileTransferErrorType::UninitializedSession,
)),
}
}
/// ### iter_search
///
/// Search recursively in `dir` for file matching the wildcard.
/// NOTE: DON'T RE-IMPLEMENT THIS FUNCTION, unless the file transfer provides a faster way to do so
/// NOTE: don't call this method from outside; consider it as private
fn iter_search(
&mut self,
dir: &Path,
filter: &WildMatch,
) -> Result<Vec<FsEntry>, FileTransferError> {
let mut drained: Vec<FsEntry> = Vec::new();
// Scan directory
match self.list_dir(dir) {
Ok(entries) => {
/* For each entry:
- if is dir: call iter_search with `dir`
- push `iter_search` result to `drained`
- if is file: check if it matches `filter`
- if it matches `filter`: push to to filter
*/
for entry in entries.iter() {
match entry {
FsEntry::Directory(dir) => {
// If directory name, matches wildcard, push it to drained
if filter.matches(dir.name.as_str()) {
drained.push(FsEntry::Directory(dir.clone()));
}
drained.append(&mut self.iter_search(dir.abs_path.as_path(), filter)?);
}
FsEntry::File(file) => {
if filter.matches(file.name.as_str()) {
drained.push(FsEntry::File(file.clone()));
}
}
}
}
Ok(drained)
}
Err(err) => Err(err),
}
}
AwsS3,
}
// Traits
@@ -311,6 +30,7 @@ impl std::string::ToString for FileTransferProtocol {
},
FileTransferProtocol::Scp => "SCP",
FileTransferProtocol::Sftp => "SFTP",
FileTransferProtocol::AwsS3 => "S3",
})
}
}
@@ -323,6 +43,7 @@ impl std::str::FromStr for FileTransferProtocol {
"FTPS" => Ok(FileTransferProtocol::Ftp(true)),
"SCP" => Ok(FileTransferProtocol::Scp),
"SFTP" => Ok(FileTransferProtocol::Sftp),
"S3" => Ok(FileTransferProtocol::AwsS3),
_ => Err(s.to_string()),
}
}
@@ -382,6 +103,14 @@ mod tests {
FileTransferProtocol::from_str("scp").ok().unwrap(),
FileTransferProtocol::Scp
);
assert_eq!(
FileTransferProtocol::from_str("S3").ok().unwrap(),
FileTransferProtocol::AwsS3
);
assert_eq!(
FileTransferProtocol::from_str("s3").ok().unwrap(),
FileTransferProtocol::AwsS3
);
// Error
assert!(FileTransferProtocol::from_str("dummy").is_err());
// To String
@@ -395,97 +124,6 @@ mod tests {
);
assert_eq!(FileTransferProtocol::Scp.to_string(), String::from("SCP"));
assert_eq!(FileTransferProtocol::Sftp.to_string(), String::from("SFTP"));
}
#[test]
fn test_filetransfer_mod_error() {
let err: FileTransferError = FileTransferError::new_ex(
FileTransferErrorType::NoSuchFileOrDirectory,
String::from("non va una mazza"),
);
assert_eq!(*err.msg.as_ref().unwrap(), String::from("non va una mazza"));
assert_eq!(
format!("{}", err),
String::from("No such file or directory (non va una mazza)")
);
assert_eq!(
format!(
"{}",
FileTransferError::new(FileTransferErrorType::AuthenticationFailed)
),
String::from("Authentication failed")
);
assert_eq!(
format!(
"{}",
FileTransferError::new(FileTransferErrorType::BadAddress)
),
String::from("Bad address syntax")
);
assert_eq!(
format!(
"{}",
FileTransferError::new(FileTransferErrorType::ConnectionError)
),
String::from("Connection error")
);
assert_eq!(
format!(
"{}",
FileTransferError::new(FileTransferErrorType::DirStatFailed)
),
String::from("Could not stat directory")
);
assert_eq!(
format!(
"{}",
FileTransferError::new(FileTransferErrorType::FileCreateDenied)
),
String::from("Failed to create file")
);
assert_eq!(
format!(
"{}",
FileTransferError::new(FileTransferErrorType::NoSuchFileOrDirectory)
),
String::from("No such file or directory")
);
assert_eq!(
format!(
"{}",
FileTransferError::new(FileTransferErrorType::PexError)
),
String::from("Not enough permissions")
);
assert_eq!(
format!(
"{}",
FileTransferError::new(FileTransferErrorType::ProtocolError)
),
String::from("Protocol error")
);
assert_eq!(
format!(
"{}",
FileTransferError::new(FileTransferErrorType::SslError)
),
String::from("SSL error")
);
assert_eq!(
format!(
"{}",
FileTransferError::new(FileTransferErrorType::UninitializedSession)
),
String::from("Uninitialized session")
);
assert_eq!(
format!(
"{}",
FileTransferError::new(FileTransferErrorType::UnsupportedFeature)
),
String::from("Unsupported feature")
);
let err = FileTransferError::new(FileTransferErrorType::UnsupportedFeature);
assert_eq!(err.kind(), FileTransferErrorType::UnsupportedFeature);
assert_eq!(FileTransferProtocol::AwsS3.to_string(), String::from("S3"));
}
}

399
src/filetransfer/params.rs Normal file
View File

@@ -0,0 +1,399 @@
//! ## Params
//!
//! file transfer parameters
use super::FileTransferProtocol;
use std::path::{Path, PathBuf};
/// ### FileTransferParams
///
/// Holds connection parameters for file transfers
#[derive(Debug, Clone)]
pub struct FileTransferParams {
pub protocol: FileTransferProtocol,
pub params: ProtocolParams,
pub entry_directory: Option<PathBuf>,
}
/// Container for protocol params
#[derive(Debug, Clone)]
pub enum ProtocolParams {
Generic(GenericProtocolParams),
AwsS3(AwsS3Params),
}
/// Protocol params used by most common protocols
#[derive(Debug, Clone)]
pub struct GenericProtocolParams {
pub address: String,
pub port: u16,
pub username: Option<String>,
pub password: Option<String>,
}
/// Connection parameters for AWS S3 protocol
#[derive(Debug, Clone)]
pub struct AwsS3Params {
pub bucket_name: String,
pub region: Option<String>,
pub endpoint: Option<String>,
pub profile: Option<String>,
pub access_key: Option<String>,
pub secret_access_key: Option<String>,
pub security_token: Option<String>,
pub session_token: Option<String>,
pub new_path_style: bool,
}
impl FileTransferParams {
/// Instantiates a new `FileTransferParams`
pub fn new(protocol: FileTransferProtocol, params: ProtocolParams) -> Self {
Self {
protocol,
params,
entry_directory: None,
}
}
/// Set entry directory
pub fn entry_directory<P: AsRef<Path>>(mut self, dir: Option<P>) -> Self {
self.entry_directory = dir.map(|x| x.as_ref().to_path_buf());
self
}
/// Returns whether a password is supposed to be required for this protocol params.
/// The result true is returned ONLY if the supposed secret is MISSING!!!
pub fn password_missing(&self) -> bool {
match &self.params {
ProtocolParams::AwsS3(params) => params.password_missing(),
ProtocolParams::Generic(params) => params.password_missing(),
}
}
/// Set the secret to ft params for the default secret field for this protocol
pub fn set_default_secret(&mut self, secret: String) {
match &mut self.params {
ProtocolParams::AwsS3(params) => params.set_default_secret(secret),
ProtocolParams::Generic(params) => params.set_default_secret(secret),
}
}
}
impl Default for FileTransferParams {
fn default() -> Self {
Self::new(FileTransferProtocol::Sftp, ProtocolParams::default())
}
}
impl Default for ProtocolParams {
fn default() -> Self {
Self::Generic(GenericProtocolParams::default())
}
}
impl ProtocolParams {
#[cfg(test)]
/// Retrieve generic parameters from protocol params if any
pub fn generic_params(&self) -> Option<&GenericProtocolParams> {
match self {
ProtocolParams::Generic(params) => Some(params),
_ => None,
}
}
#[cfg(test)]
/// Get a mutable reference to the inner generic protocol params
pub fn mut_generic_params(&mut self) -> Option<&mut GenericProtocolParams> {
match self {
ProtocolParams::Generic(params) => Some(params),
_ => None,
}
}
#[cfg(test)]
/// Retrieve AWS S3 parameters if any
pub fn s3_params(&self) -> Option<&AwsS3Params> {
match self {
ProtocolParams::AwsS3(params) => Some(params),
_ => None,
}
}
}
// -- Generic protocol params
impl Default for GenericProtocolParams {
fn default() -> Self {
Self {
address: "localhost".to_string(),
port: 22,
username: None,
password: None,
}
}
}
impl GenericProtocolParams {
/// Set address to params
pub fn address<S: AsRef<str>>(mut self, address: S) -> Self {
self.address = address.as_ref().to_string();
self
}
/// Set port to params
pub fn port(mut self, port: u16) -> Self {
self.port = port;
self
}
/// Set username for params
pub fn username<S: AsRef<str>>(mut self, username: Option<S>) -> Self {
self.username = username.map(|x| x.as_ref().to_string());
self
}
/// Set password for params
pub fn password<S: AsRef<str>>(mut self, password: Option<S>) -> Self {
self.password = password.map(|x| x.as_ref().to_string());
self
}
/// Returns whether a password is supposed to be required for this protocol params.
/// The result true is returned ONLY if the supposed secret is MISSING!!!
pub fn password_missing(&self) -> bool {
self.password.is_none()
}
/// Set password
pub fn set_default_secret(&mut self, secret: String) {
self.password = Some(secret);
}
}
// -- S3 params
impl AwsS3Params {
/// Instantiates a new `AwsS3Params` struct
pub fn new<S: AsRef<str>>(bucket: S, region: Option<S>, profile: Option<S>) -> Self {
Self {
bucket_name: bucket.as_ref().to_string(),
region: region.map(|x| x.as_ref().to_string()),
profile: profile.map(|x| x.as_ref().to_string()),
endpoint: None,
access_key: None,
secret_access_key: None,
security_token: None,
session_token: None,
new_path_style: false,
}
}
/// Construct aws s3 params with specified endpoint
pub fn endpoint<S: AsRef<str>>(mut self, endpoint: Option<S>) -> Self {
self.endpoint = endpoint.map(|x| x.as_ref().to_string());
self
}
/// Construct aws s3 params with provided access key
pub fn access_key<S: AsRef<str>>(mut self, key: Option<S>) -> Self {
self.access_key = key.map(|x| x.as_ref().to_string());
self
}
/// Construct aws s3 params with provided secret_access_key
pub fn secret_access_key<S: AsRef<str>>(mut self, key: Option<S>) -> Self {
self.secret_access_key = key.map(|x| x.as_ref().to_string());
self
}
/// Construct aws s3 params with provided security_token
pub fn security_token<S: AsRef<str>>(mut self, key: Option<S>) -> Self {
self.security_token = key.map(|x| x.as_ref().to_string());
self
}
/// Construct aws s3 params with provided session_token
pub fn session_token<S: AsRef<str>>(mut self, key: Option<S>) -> Self {
self.session_token = key.map(|x| x.as_ref().to_string());
self
}
/// Specify new path style when constructing aws s3 params
pub fn new_path_style(mut self, new_path_style: bool) -> Self {
self.new_path_style = new_path_style;
self
}
/// Returns whether a password is supposed to be required for this protocol params.
/// The result true is returned ONLY if the supposed secret is MISSING!!!
pub fn password_missing(&self) -> bool {
self.secret_access_key.is_none() && self.security_token.is_none()
}
/// Set password
pub fn set_default_secret(&mut self, secret: String) {
self.secret_access_key = Some(secret);
}
}
#[cfg(test)]
mod test {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn test_filetransfer_params() {
let params: FileTransferParams =
FileTransferParams::new(FileTransferProtocol::Scp, ProtocolParams::default())
.entry_directory(Some(&Path::new("/tmp")));
assert_eq!(
params.params.generic_params().unwrap().address.as_str(),
"localhost"
);
assert_eq!(params.protocol, FileTransferProtocol::Scp);
assert_eq!(
params.entry_directory.as_deref().unwrap(),
Path::new("/tmp")
);
}
#[test]
fn params_default() {
let params: GenericProtocolParams = ProtocolParams::default()
.generic_params()
.unwrap()
.to_owned();
assert_eq!(params.address.as_str(), "localhost");
assert_eq!(params.port, 22);
assert!(params.username.is_none());
assert!(params.password.is_none());
}
#[test]
fn should_init_aws_s3_params() {
let params: AwsS3Params = AwsS3Params::new("omar", Some("eu-west-1"), Some("test"));
assert_eq!(params.bucket_name.as_str(), "omar");
assert_eq!(params.region.as_deref().unwrap(), "eu-west-1");
assert_eq!(params.profile.as_deref().unwrap(), "test");
assert!(params.endpoint.is_none());
assert!(params.access_key.is_none());
assert!(params.secret_access_key.is_none());
assert!(params.security_token.is_none());
assert!(params.session_token.is_none());
assert_eq!(params.new_path_style, false);
}
#[test]
fn should_init_aws_s3_params_with_optionals() {
let params: AwsS3Params = AwsS3Params::new("omar", Some("eu-west-1"), Some("test"))
.endpoint(Some("http://omar.it"))
.access_key(Some("pippo"))
.secret_access_key(Some("pluto"))
.security_token(Some("omar"))
.session_token(Some("gerry-scotti"))
.new_path_style(true);
assert_eq!(params.bucket_name.as_str(), "omar");
assert_eq!(params.region.as_deref().unwrap(), "eu-west-1");
assert_eq!(params.profile.as_deref().unwrap(), "test");
assert_eq!(params.endpoint.as_deref().unwrap(), "http://omar.it");
assert_eq!(params.access_key.as_deref().unwrap(), "pippo");
assert_eq!(params.secret_access_key.as_deref().unwrap(), "pluto");
assert_eq!(params.security_token.as_deref().unwrap(), "omar");
assert_eq!(params.session_token.as_deref().unwrap(), "gerry-scotti");
assert_eq!(params.new_path_style, true);
}
#[test]
fn references() {
let mut params =
ProtocolParams::AwsS3(AwsS3Params::new("omar", Some("eu-west-1"), Some("test")));
assert!(params.s3_params().is_some());
assert!(params.generic_params().is_none());
assert!(params.mut_generic_params().is_none());
let mut params = ProtocolParams::default();
assert!(params.s3_params().is_none());
assert!(params.generic_params().is_some());
assert!(params.mut_generic_params().is_some());
}
#[test]
fn password_missing() {
assert!(FileTransferParams::new(
FileTransferProtocol::Scp,
ProtocolParams::AwsS3(AwsS3Params::new("omar", Some("eu-west-1"), Some("test")))
)
.password_missing());
assert_eq!(
FileTransferParams::new(
FileTransferProtocol::Scp,
ProtocolParams::AwsS3(
AwsS3Params::new("omar", Some("eu-west-1"), Some("test"))
.secret_access_key(Some("test"))
)
)
.password_missing(),
false
);
assert_eq!(
FileTransferParams::new(
FileTransferProtocol::Scp,
ProtocolParams::AwsS3(
AwsS3Params::new("omar", Some("eu-west-1"), Some("test"))
.security_token(Some("test"))
)
)
.password_missing(),
false
);
assert!(
FileTransferParams::new(FileTransferProtocol::Scp, ProtocolParams::default())
.password_missing()
);
assert_eq!(
FileTransferParams::new(
FileTransferProtocol::Scp,
ProtocolParams::Generic(GenericProtocolParams::default().password(Some("Hello")))
)
.password_missing(),
false
);
}
#[test]
fn set_default_secret_aws_s3() {
let mut params = FileTransferParams::new(
FileTransferProtocol::Scp,
ProtocolParams::AwsS3(AwsS3Params::new("omar", Some("eu-west-1"), Some("test"))),
);
params.set_default_secret(String::from("secret"));
assert_eq!(
params
.params
.s3_params()
.unwrap()
.secret_access_key
.as_deref()
.unwrap(),
"secret"
);
}
#[test]
fn set_default_secret_generic() {
let mut params =
FileTransferParams::new(FileTransferProtocol::Scp, ProtocolParams::default());
params.set_default_secret(String::from("secret"));
assert_eq!(
params
.params
.generic_params()
.unwrap()
.password
.as_deref()
.unwrap(),
"secret"
);
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,501 +0,0 @@
//! ## Fs
//!
//! `fs` is the module which provides file system entities
/**
* MIT License
*
* termscp - Copyright (c) 2021 Christian Visintin
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// Mod
pub mod explorer;
// Ext
use std::path::PathBuf;
use std::time::SystemTime;
/// ## FsEntry
///
/// FsEntry represents a generic entry in a directory
#[derive(Clone, std::fmt::Debug)]
pub enum FsEntry {
Directory(FsDirectory),
File(FsFile),
}
/// ## FsDirectory
///
/// Directory provides an interface to file system directories
#[derive(Clone, std::fmt::Debug)]
pub struct FsDirectory {
pub name: String,
pub abs_path: PathBuf,
pub last_change_time: SystemTime,
pub last_access_time: SystemTime,
pub creation_time: SystemTime,
pub readonly: bool,
pub symlink: Option<Box<FsEntry>>, // UNIX only
pub user: Option<u32>, // UNIX only
pub group: Option<u32>, // UNIX only
pub unix_pex: Option<(u8, u8, u8)>, // UNIX only
}
/// ### FsFile
///
/// FsFile provides an interface to file system files
#[derive(Clone, std::fmt::Debug)]
pub struct FsFile {
pub name: String,
pub abs_path: PathBuf,
pub last_change_time: SystemTime,
pub last_access_time: SystemTime,
pub creation_time: SystemTime,
pub size: usize,
pub ftype: Option<String>, // File type
pub readonly: bool,
pub symlink: Option<Box<FsEntry>>, // UNIX only
pub user: Option<u32>, // UNIX only
pub group: Option<u32>, // UNIX only
pub unix_pex: Option<(u8, u8, u8)>, // UNIX only
}
impl FsEntry {
/// ### get_abs_path
///
/// Get absolute path from `FsEntry`
pub fn get_abs_path(&self) -> PathBuf {
match self {
FsEntry::Directory(dir) => dir.abs_path.clone(),
FsEntry::File(file) => file.abs_path.clone(),
}
}
/// ### get_name
///
/// Get file name from `FsEntry`
pub fn get_name(&self) -> &'_ str {
match self {
FsEntry::Directory(dir) => dir.name.as_ref(),
FsEntry::File(file) => file.name.as_ref(),
}
}
/// ### get_last_change_time
///
/// Get last change time from `FsEntry`
pub fn get_last_change_time(&self) -> SystemTime {
match self {
FsEntry::Directory(dir) => dir.last_change_time,
FsEntry::File(file) => file.last_change_time,
}
}
/// ### get_last_access_time
///
/// Get access time from `FsEntry`
pub fn get_last_access_time(&self) -> SystemTime {
match self {
FsEntry::Directory(dir) => dir.last_access_time,
FsEntry::File(file) => file.last_access_time,
}
}
/// ### get_creation_time
///
/// Get creation time from `FsEntry`
pub fn get_creation_time(&self) -> SystemTime {
match self {
FsEntry::Directory(dir) => dir.creation_time,
FsEntry::File(file) => file.creation_time,
}
}
/// ### get_size
///
/// Get size from `FsEntry`. For directories is always 4096
pub fn get_size(&self) -> usize {
match self {
FsEntry::Directory(_) => 4096,
FsEntry::File(file) => file.size,
}
}
/// ### get_ftype
///
/// Get file type from `FsEntry`. For directories is always None
pub fn get_ftype(&self) -> Option<String> {
match self {
FsEntry::Directory(_) => None,
FsEntry::File(file) => file.ftype.clone(),
}
}
/// ### get_user
///
/// Get uid from `FsEntry`
pub fn get_user(&self) -> Option<u32> {
match self {
FsEntry::Directory(dir) => dir.user,
FsEntry::File(file) => file.user,
}
}
/// ### get_group
///
/// Get gid from `FsEntry`
pub fn get_group(&self) -> Option<u32> {
match self {
FsEntry::Directory(dir) => dir.group,
FsEntry::File(file) => file.group,
}
}
/// ### get_unix_pex
///
/// Get unix pex from `FsEntry`
pub fn get_unix_pex(&self) -> Option<(u8, u8, u8)> {
match self {
FsEntry::Directory(dir) => dir.unix_pex,
FsEntry::File(file) => file.unix_pex,
}
}
/// ### is_symlink
///
/// Returns whether the `FsEntry` is a symlink
pub fn is_symlink(&self) -> bool {
match self {
FsEntry::Directory(dir) => dir.symlink.is_some(),
FsEntry::File(file) => file.symlink.is_some(),
}
}
/// ### is_dir
///
/// Returns whether a FsEntry is a directory
pub fn is_dir(&self) -> bool {
matches!(self, FsEntry::Directory(_))
}
/// ### is_file
///
/// Returns whether a FsEntry is a File
pub fn is_file(&self) -> bool {
matches!(self, FsEntry::File(_))
}
/// ### is_hidden
///
/// Returns whether FsEntry is hidden
pub fn is_hidden(&self) -> bool {
self.get_name().starts_with('.')
}
/// ### get_realfile
///
/// Return the real file pointed by a `FsEntry`
pub fn get_realfile(&self) -> FsEntry {
match self {
FsEntry::Directory(dir) => match &dir.symlink {
Some(symlink) => symlink.get_realfile(),
None => self.clone(),
},
FsEntry::File(file) => match &file.symlink {
Some(symlink) => symlink.get_realfile(),
None => self.clone(),
},
}
}
/// ### unwrap_file
///
/// Unwrap FsEntry as FsFile
pub fn unwrap_file(self) -> FsFile {
match self {
FsEntry::File(file) => file,
_ => panic!("unwrap_file: not a file"),
}
}
#[cfg(test)]
/// ### unwrap_dir
///
/// Unwrap FsEntry as FsDirectory
pub fn unwrap_dir(self) -> FsDirectory {
match self {
FsEntry::Directory(dir) => dir,
_ => panic!("unwrap_dir: not a directory"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn test_fs_fsentry_dir() {
let t_now: SystemTime = SystemTime::now();
let entry: FsEntry = FsEntry::Directory(FsDirectory {
name: String::from("foo"),
abs_path: PathBuf::from("/foo"),
last_change_time: t_now,
last_access_time: t_now,
creation_time: t_now,
readonly: false,
symlink: None, // UNIX only
user: Some(0), // UNIX only
group: Some(0), // UNIX only
unix_pex: Some((7, 5, 5)), // UNIX only
});
assert_eq!(entry.get_abs_path(), PathBuf::from("/foo"));
assert_eq!(entry.get_name(), String::from("foo"));
assert_eq!(entry.get_last_access_time(), t_now);
assert_eq!(entry.get_last_change_time(), t_now);
assert_eq!(entry.get_creation_time(), t_now);
assert_eq!(entry.get_size(), 4096);
assert_eq!(entry.get_ftype(), None);
assert_eq!(entry.get_user(), Some(0));
assert_eq!(entry.get_group(), Some(0));
assert_eq!(entry.is_symlink(), false);
assert_eq!(entry.is_dir(), true);
assert_eq!(entry.is_file(), false);
assert_eq!(entry.get_unix_pex(), Some((7, 5, 5)));
assert_eq!(entry.unwrap_dir().abs_path, PathBuf::from("/foo"));
}
#[test]
fn test_fs_fsentry_file() {
let t_now: SystemTime = SystemTime::now();
let entry: FsEntry = FsEntry::File(FsFile {
name: String::from("bar.txt"),
abs_path: PathBuf::from("/bar.txt"),
last_change_time: t_now,
last_access_time: t_now,
creation_time: t_now,
size: 8192,
readonly: false,
ftype: Some(String::from("txt")),
symlink: None, // UNIX only
user: Some(0), // UNIX only
group: Some(0), // UNIX only
unix_pex: Some((6, 4, 4)), // UNIX only
});
assert_eq!(entry.get_abs_path(), PathBuf::from("/bar.txt"));
assert_eq!(entry.get_name(), String::from("bar.txt"));
assert_eq!(entry.get_last_access_time(), t_now);
assert_eq!(entry.get_last_change_time(), t_now);
assert_eq!(entry.get_creation_time(), t_now);
assert_eq!(entry.get_size(), 8192);
assert_eq!(entry.get_ftype(), Some(String::from("txt")));
assert_eq!(entry.get_user(), Some(0));
assert_eq!(entry.get_group(), Some(0));
assert_eq!(entry.get_unix_pex(), Some((6, 4, 4)));
assert_eq!(entry.is_symlink(), false);
assert_eq!(entry.is_dir(), false);
assert_eq!(entry.is_file(), true);
assert_eq!(entry.unwrap_file().abs_path, PathBuf::from("/bar.txt"));
}
#[test]
#[should_panic]
fn test_fs_fsentry_file_unwrap_bad() {
let t_now: SystemTime = SystemTime::now();
let entry: FsEntry = FsEntry::File(FsFile {
name: String::from("bar.txt"),
abs_path: PathBuf::from("/bar.txt"),
last_change_time: t_now,
last_access_time: t_now,
creation_time: t_now,
size: 8192,
readonly: false,
ftype: Some(String::from("txt")),
symlink: None, // UNIX only
user: Some(0), // UNIX only
group: Some(0), // UNIX only
unix_pex: Some((6, 4, 4)), // UNIX only
});
entry.unwrap_dir();
}
#[test]
#[should_panic]
fn test_fs_fsentry_dir_unwrap_bad() {
let t_now: SystemTime = SystemTime::now();
let entry: FsEntry = FsEntry::Directory(FsDirectory {
name: String::from("foo"),
abs_path: PathBuf::from("/foo"),
last_change_time: t_now,
last_access_time: t_now,
creation_time: t_now,
readonly: false,
symlink: None, // UNIX only
user: Some(0), // UNIX only
group: Some(0), // UNIX only
unix_pex: Some((7, 5, 5)), // UNIX only
});
entry.unwrap_file();
}
#[test]
fn test_fs_fsentry_hidden_files() {
let t_now: SystemTime = SystemTime::now();
let entry: FsEntry = FsEntry::File(FsFile {
name: String::from("bar.txt"),
abs_path: PathBuf::from("/bar.txt"),
last_change_time: t_now,
last_access_time: t_now,
creation_time: t_now,
size: 8192,
readonly: false,
ftype: Some(String::from("txt")),
symlink: None, // UNIX only
user: Some(0), // UNIX only
group: Some(0), // UNIX only
unix_pex: Some((6, 4, 4)), // UNIX only
});
assert_eq!(entry.is_hidden(), false);
let entry: FsEntry = FsEntry::File(FsFile {
name: String::from(".gitignore"),
abs_path: PathBuf::from("/.gitignore"),
last_change_time: t_now,
last_access_time: t_now,
creation_time: t_now,
size: 8192,
readonly: false,
ftype: Some(String::from("txt")),
symlink: None, // UNIX only
user: Some(0), // UNIX only
group: Some(0), // UNIX only
unix_pex: Some((6, 4, 4)), // UNIX only
});
assert_eq!(entry.is_hidden(), true);
let entry: FsEntry = FsEntry::Directory(FsDirectory {
name: String::from(".git"),
abs_path: PathBuf::from("/.git"),
last_change_time: t_now,
last_access_time: t_now,
creation_time: t_now,
readonly: false,
symlink: None, // UNIX only
user: Some(0), // UNIX only
group: Some(0), // UNIX only
unix_pex: Some((7, 5, 5)), // UNIX only
});
assert_eq!(entry.is_hidden(), true);
}
#[test]
fn test_fs_fsentry_realfile_none() {
let t_now: SystemTime = SystemTime::now();
// With file...
let entry: FsEntry = FsEntry::File(FsFile {
name: String::from("bar.txt"),
abs_path: PathBuf::from("/bar.txt"),
last_change_time: t_now,
last_access_time: t_now,
creation_time: t_now,
size: 8192,
readonly: false,
ftype: Some(String::from("txt")),
symlink: None, // UNIX only
user: Some(0), // UNIX only
group: Some(0), // UNIX only
unix_pex: Some((6, 4, 4)), // UNIX only
});
// Symlink is None...
assert_eq!(
entry.get_realfile().get_abs_path(),
PathBuf::from("/bar.txt")
);
// With directory...
let entry: FsEntry = FsEntry::Directory(FsDirectory {
name: String::from("foo"),
abs_path: PathBuf::from("/foo"),
last_change_time: t_now,
last_access_time: t_now,
creation_time: t_now,
readonly: false,
symlink: None, // UNIX only
user: Some(0), // UNIX only
group: Some(0), // UNIX only
unix_pex: Some((7, 5, 5)), // UNIX only
});
assert_eq!(entry.get_realfile().get_abs_path(), PathBuf::from("/foo"));
}
#[test]
fn test_fs_fsentry_realfile_some() {
let t_now: SystemTime = SystemTime::now();
// Prepare entries
// root -> child -> target
let entry_target: FsEntry = FsEntry::Directory(FsDirectory {
name: String::from("projects"),
abs_path: PathBuf::from("/home/cvisintin/projects"),
last_change_time: t_now,
last_access_time: t_now,
creation_time: t_now,
readonly: false,
symlink: None, // UNIX only
user: Some(0), // UNIX only
group: Some(0), // UNIX only
unix_pex: Some((7, 7, 7)), // UNIX only
});
let entry_child: FsEntry = FsEntry::Directory(FsDirectory {
name: String::from("projects"),
abs_path: PathBuf::from("/develop/projects"),
last_change_time: t_now,
last_access_time: t_now,
creation_time: t_now,
readonly: false,
symlink: Some(Box::new(entry_target)),
user: Some(0),
group: Some(0),
unix_pex: Some((7, 7, 7)),
});
let entry_root: FsEntry = FsEntry::File(FsFile {
name: String::from("projects"),
abs_path: PathBuf::from("/projects"),
last_change_time: t_now,
last_access_time: t_now,
creation_time: t_now,
size: 8,
readonly: false,
ftype: None,
symlink: Some(Box::new(entry_child)),
user: Some(0),
group: Some(0),
unix_pex: Some((7, 7, 7)),
});
assert_eq!(entry_root.is_symlink(), true);
// get real file
let real_file: FsEntry = entry_root.get_realfile();
// real file must be projects in /home/cvisintin
assert_eq!(
real_file.get_abs_path(),
PathBuf::from("/home/cvisintin/projects")
);
}
}

View File

@@ -2,48 +2,23 @@
//!
//! `host` is the module which provides functionalities to host file system
/**
* MIT License
*
* termscp - Copyright (c) 2021 Christian Visintin
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// dependencies
extern crate wildmatch;
// ext
use std::fs::{self, File, Metadata, OpenOptions};
#[cfg(target_family = "unix")]
use remotefs::fs::UnixPex;
use remotefs::fs::{File, FileType, Metadata};
use std::fs::{self, File as StdFile, OpenOptions};
use std::path::{Path, PathBuf};
use std::time::SystemTime;
use thiserror::Error;
use wildmatch::WildMatch;
// Metadata ext
#[cfg(target_family = "unix")]
use std::fs::set_permissions;
#[cfg(target_family = "unix")]
use std::os::unix::fs::{MetadataExt, PermissionsExt};
use std::os::unix::fs::PermissionsExt;
// Locals
use crate::fs::{FsDirectory, FsEntry, FsFile};
use crate::utils::path;
/// ## HostErrorType
///
/// HostErrorType provides an overview of the specific host error
#[derive(Error, Debug)]
pub enum HostErrorType {
@@ -76,8 +51,6 @@ pub struct HostError {
}
impl HostError {
/// ### new
///
/// Instantiates a new HostError
pub(crate) fn new(error: HostErrorType, errno: Option<std::io::Error>, p: &Path) -> Self {
HostError {
@@ -102,7 +75,7 @@ impl std::fmt::Display for HostError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let p_str: String = match self.path.as_ref() {
None => String::new(),
Some(p) => format!(" ({})", p.display().to_string()),
Some(p) => format!(" ({})", p.display()),
};
match &self.ioerr {
Some(err) => write!(f, "{}: {}{}", self.error, err, p_str),
@@ -111,18 +84,14 @@ impl std::fmt::Display for HostError {
}
}
/// ## Localhost
///
/// Localhost is the entity which holds the information about the current directory and host.
/// It provides functions to navigate across the local host file system
pub struct Localhost {
wrkdir: PathBuf,
files: Vec<FsEntry>,
files: Vec<File>,
}
impl Localhost {
/// ### new
///
/// Instantiates a new Localhost struct
pub fn new(wrkdir: PathBuf) -> Result<Localhost, HostError> {
debug!("Initializing localhost at {}", wrkdir.display());
@@ -157,26 +126,20 @@ impl Localhost {
Ok(host)
}
/// ### pwd
///
/// Print working directory
pub fn pwd(&self) -> PathBuf {
self.wrkdir.clone()
}
/// ### list_dir
///
/// List files in current directory
#[allow(dead_code)]
pub fn list_dir(&self) -> Vec<FsEntry> {
pub fn list_dir(&self) -> Vec<File> {
self.files.clone()
}
/// ### change_wrkdir
///
/// Change working directory with the new provided directory
pub fn change_wrkdir(&mut self, new_dir: &Path) -> Result<PathBuf, HostError> {
let new_dir: PathBuf = self.to_abs_path(new_dir);
let new_dir: PathBuf = self.to_path(new_dir);
info!("Changing localhost directory to {}...", new_dir.display());
// Check whether directory exists
if !self.file_exists(new_dir.as_path()) {
@@ -214,19 +177,15 @@ impl Localhost {
Ok(self.wrkdir.clone())
}
/// ### mkdir
///
/// Make a directory at path and update the file list (only if relative)
pub fn mkdir(&mut self, dir_name: &Path) -> Result<(), HostError> {
self.mkdir_ex(dir_name, false)
}
/// ### mkdir_ex
///
/// Extended option version of makedir.
/// ignex: don't report error if directory already exists
pub fn mkdir_ex(&mut self, dir_name: &Path, ignex: bool) -> Result<(), HostError> {
let dir_path: PathBuf = self.to_abs_path(dir_name);
let dir_path: PathBuf = self.to_path(dir_name);
info!("Making directory {}", dir_path.display());
// If dir already exists, return Error
if dir_path.exists() {
@@ -261,84 +220,76 @@ impl Localhost {
}
}
/// ### remove
///
/// Remove file entry
pub fn remove(&mut self, entry: &FsEntry) -> Result<(), HostError> {
match entry {
FsEntry::Directory(dir) => {
// If file doesn't exist; return error
debug!("Removing directory {}", dir.abs_path.display());
if !dir.abs_path.as_path().exists() {
error!("Directory doesn't exist");
return Err(HostError::new(
HostErrorType::NoSuchFileOrDirectory,
None,
dir.abs_path.as_path(),
));
pub fn remove(&mut self, entry: &File) -> Result<(), HostError> {
if entry.is_dir() {
// If file doesn't exist; return error
debug!("Removing directory {}", entry.path().display());
if !entry.path().exists() {
error!("Directory doesn't exist");
return Err(HostError::new(
HostErrorType::NoSuchFileOrDirectory,
None,
entry.path(),
));
}
// Remove
match std::fs::remove_dir_all(entry.path()) {
Ok(_) => {
// Update dir
self.files = self.scan_dir(self.wrkdir.as_path())?;
info!("Removed directory {}", entry.path().display());
Ok(())
}
// Remove
match std::fs::remove_dir_all(dir.abs_path.as_path()) {
Ok(_) => {
// Update dir
self.files = self.scan_dir(self.wrkdir.as_path())?;
info!("Removed directory {}", dir.abs_path.display());
Ok(())
}
Err(err) => {
error!("Could not remove directory: {}", err);
Err(HostError::new(
HostErrorType::DeleteFailed,
Some(err),
dir.abs_path.as_path(),
))
}
Err(err) => {
error!("Could not remove directory: {}", err);
Err(HostError::new(
HostErrorType::DeleteFailed,
Some(err),
entry.path(),
))
}
}
FsEntry::File(file) => {
// If file doesn't exist; return error
debug!("Removing file {}", file.abs_path.display());
if !file.abs_path.as_path().exists() {
error!("File doesn't exist");
return Err(HostError::new(
HostErrorType::NoSuchFileOrDirectory,
None,
file.abs_path.as_path(),
));
} else {
// If file doesn't exist; return error
debug!("Removing file {}", entry.path().display());
if !entry.path().exists() {
error!("File doesn't exist");
return Err(HostError::new(
HostErrorType::NoSuchFileOrDirectory,
None,
entry.path(),
));
}
// Remove
match std::fs::remove_file(entry.path()) {
Ok(_) => {
// Update dir
self.files = self.scan_dir(self.wrkdir.as_path())?;
info!("Removed file {}", entry.path().display());
Ok(())
}
// Remove
match std::fs::remove_file(file.abs_path.as_path()) {
Ok(_) => {
// Update dir
self.files = self.scan_dir(self.wrkdir.as_path())?;
info!("Removed file {}", file.abs_path.display());
Ok(())
}
Err(err) => {
error!("Could not remove file: {}", err);
Err(HostError::new(
HostErrorType::DeleteFailed,
Some(err),
file.abs_path.as_path(),
))
}
Err(err) => {
error!("Could not remove file: {}", err);
Err(HostError::new(
HostErrorType::DeleteFailed,
Some(err),
entry.path(),
))
}
}
}
}
/// ### rename
///
/// Rename file or directory to new name
pub fn rename(&mut self, entry: &FsEntry, dst_path: &Path) -> Result<(), HostError> {
let abs_path: PathBuf = entry.get_abs_path();
match std::fs::rename(abs_path.as_path(), dst_path) {
pub fn rename(&mut self, entry: &File, dst_path: &Path) -> Result<(), HostError> {
match std::fs::rename(entry.path(), dst_path) {
Ok(_) => {
// Scan dir
self.files = self.scan_dir(self.wrkdir.as_path())?;
debug!(
"Moved file {} to {}",
entry.get_abs_path().display(),
entry.path().display(),
dst_path.display()
);
Ok(())
@@ -346,71 +297,66 @@ impl Localhost {
Err(err) => {
error!(
"Failed to move {} to {}: {}",
entry.get_abs_path().display(),
entry.path().display(),
dst_path.display(),
err
);
Err(HostError::new(
HostErrorType::CouldNotCreateFile,
Some(err),
abs_path.as_path(),
entry.path(),
))
}
}
}
/// ### copy
///
/// Copy file to destination path
pub fn copy(&mut self, entry: &FsEntry, dst: &Path) -> Result<(), HostError> {
pub fn copy(&mut self, entry: &File, dst: &Path) -> Result<(), HostError> {
// Get absolute path of dest
let dst: PathBuf = self.to_abs_path(dst);
let dst: PathBuf = self.to_path(dst);
info!(
"Copying file {} to {}",
entry.get_abs_path().display(),
entry.path().display(),
dst.display()
);
// Match entry
match entry {
FsEntry::File(file) => {
// Copy file
// If destination path is a directory, push file name
let dst: PathBuf = match dst.as_path().is_dir() {
true => {
let mut p: PathBuf = dst.clone();
p.push(file.name.as_str());
p
}
false => dst.clone(),
};
// Copy entry path to dst path
if let Err(err) = std::fs::copy(file.abs_path.as_path(), dst.as_path()) {
error!("Failed to copy file: {}", err);
return Err(HostError::new(
HostErrorType::CouldNotCreateFile,
Some(err),
file.abs_path.as_path(),
));
}
info!("File copied");
if entry.is_dir() {
// If destination path doesn't exist, create destination
if !dst.exists() {
debug!("Directory {} doesn't exist; creating it", dst.display());
self.mkdir(dst.as_path())?;
}
FsEntry::Directory(dir) => {
// If destination path doesn't exist, create destination
if !dst.exists() {
debug!("Directory {} doesn't exist; creating it", dst.display());
self.mkdir(dst.as_path())?;
}
// Scan dir
let dir_files: Vec<FsEntry> = self.scan_dir(dir.abs_path.as_path())?;
// Iterate files
for dir_entry in dir_files.iter() {
// Calculate dst
let mut sub_dst: PathBuf = dst.clone();
sub_dst.push(dir_entry.get_name());
// Call function recursively
self.copy(dir_entry, sub_dst.as_path())?;
}
// Scan dir
let dir_files: Vec<File> = self.scan_dir(entry.path())?;
// Iterate files
for dir_entry in dir_files.iter() {
// Calculate dst
let mut sub_dst: PathBuf = dst.clone();
sub_dst.push(dir_entry.name());
// Call function recursively
self.copy(dir_entry, sub_dst.as_path())?;
}
} else {
// Copy file
// If destination path is a directory, push file name
let dst: PathBuf = match dst.as_path().is_dir() {
true => {
let mut p: PathBuf = dst.clone();
p.push(entry.name().as_str());
p
}
false => dst.clone(),
};
// Copy entry path to dst path
if let Err(err) = std::fs::copy(entry.path(), dst.as_path()) {
error!("Failed to copy file: {}", err);
return Err(HostError::new(
HostErrorType::CouldNotCreateFile,
Some(err),
entry.path(),
));
}
info!("File copied");
}
// Reload directory if dst is pwd
match dst.is_dir() {
@@ -436,14 +382,11 @@ impl Localhost {
Ok(())
}
/// ### stat
///
/// Stat file and create a FsEntry
#[cfg(target_family = "unix")]
pub fn stat(&self, path: &Path) -> Result<FsEntry, HostError> {
/// Stat file and create a File
pub fn stat(&self, path: &Path) -> Result<File, HostError> {
info!("Stating file {}", path.display());
let path: PathBuf = self.to_abs_path(path);
let attr: Metadata = match fs::metadata(path.as_path()) {
let path: PathBuf = self.to_path(path);
let attr = match fs::metadata(path.as_path()) {
Ok(metadata) => metadata,
Err(err) => {
error!("Could not read file metadata: {}", err);
@@ -454,128 +397,15 @@ impl Localhost {
));
}
};
let file_name: String = String::from(path.file_name().unwrap().to_str().unwrap_or(""));
let mut metadata = Metadata::from(attr);
if let Ok(symlink) = fs::read_link(path.as_path()) {
metadata.set_symlink(symlink);
metadata.file_type = FileType::Symlink;
}
// Match dir / file
Ok(match path.is_dir() {
true => FsEntry::Directory(FsDirectory {
name: file_name,
abs_path: path.clone(),
last_change_time: attr.modified().unwrap_or(SystemTime::UNIX_EPOCH),
last_access_time: attr.accessed().unwrap_or(SystemTime::UNIX_EPOCH),
creation_time: attr.created().unwrap_or(SystemTime::UNIX_EPOCH),
readonly: attr.permissions().readonly(),
symlink: match fs::read_link(path.as_path()) {
Ok(p) => match self.stat(p.as_path()) {
Ok(entry) => Some(Box::new(entry)),
Err(_) => None,
},
Err(_) => None,
},
user: Some(attr.uid()),
group: Some(attr.gid()),
unix_pex: Some(self.u32_to_mode(attr.mode())),
}),
false => {
// Is File
let extension: Option<String> = path
.extension()
.map(|s| String::from(s.to_str().unwrap_or("")));
FsEntry::File(FsFile {
name: file_name,
abs_path: path.clone(),
last_change_time: attr.modified().unwrap_or(SystemTime::UNIX_EPOCH),
last_access_time: attr.accessed().unwrap_or(SystemTime::UNIX_EPOCH),
creation_time: attr.created().unwrap_or(SystemTime::UNIX_EPOCH),
readonly: attr.permissions().readonly(),
size: attr.len() as usize,
ftype: extension,
symlink: match fs::read_link(path.as_path()) {
Ok(p) => match self.stat(p.as_path()) {
Ok(entry) => Some(Box::new(entry)),
Err(_) => None,
},
Err(_) => None, // Ignore errors
},
user: Some(attr.uid()),
group: Some(attr.gid()),
unix_pex: Some(self.u32_to_mode(attr.mode())),
})
}
})
Ok(File { path, metadata })
}
/// ### stat
///
/// Stat file and create a FsEntry
#[cfg(target_os = "windows")]
#[cfg(not(tarpaulin_include))]
pub fn stat(&self, path: &Path) -> Result<FsEntry, HostError> {
let path: PathBuf = self.to_abs_path(path);
info!("Stating file {}", path.display());
let attr: Metadata = match fs::metadata(path.as_path()) {
Ok(metadata) => metadata,
Err(err) => {
error!("Could not read file metadata: {}", err);
return Err(HostError::new(
HostErrorType::FileNotAccessible,
Some(err),
path.as_path(),
));
}
};
let file_name: String = String::from(path.file_name().unwrap().to_str().unwrap_or(""));
// Match dir / file
Ok(match path.is_dir() {
true => FsEntry::Directory(FsDirectory {
name: file_name,
abs_path: path.clone(),
last_change_time: attr.modified().unwrap_or(SystemTime::UNIX_EPOCH),
last_access_time: attr.accessed().unwrap_or(SystemTime::UNIX_EPOCH),
creation_time: attr.created().unwrap_or(SystemTime::UNIX_EPOCH),
readonly: attr.permissions().readonly(),
symlink: match fs::read_link(path.as_path()) {
Ok(p) => match self.stat(p.as_path()) {
Ok(entry) => Some(Box::new(entry)),
Err(_) => None, // Ignore errors
},
Err(_) => None,
},
user: None,
group: None,
unix_pex: None,
}),
false => {
// Is File
let extension: Option<String> = match path.extension() {
Some(s) => Some(String::from(s.to_str().unwrap_or(""))),
None => None,
};
FsEntry::File(FsFile {
name: file_name,
abs_path: path.clone(),
last_change_time: attr.modified().unwrap_or(SystemTime::UNIX_EPOCH),
last_access_time: attr.accessed().unwrap_or(SystemTime::UNIX_EPOCH),
creation_time: attr.created().unwrap_or(SystemTime::UNIX_EPOCH),
readonly: attr.permissions().readonly(),
size: attr.len() as usize,
ftype: extension,
symlink: match fs::read_link(path.as_path()) {
Ok(p) => match self.stat(p.as_path()) {
Ok(entry) => Some(Box::new(entry)),
Err(_) => None,
},
Err(_) => None,
},
user: None,
group: None,
unix_pex: None,
})
}
})
}
/// ### exec
///
/// Execute a command on localhost
pub fn exec(&self, cmd: &str) -> Result<String, HostError> {
// Make command
@@ -602,17 +432,15 @@ impl Localhost {
}
}
/// ### chmod
///
/// Change file mode to file, according to UNIX permissions
#[cfg(target_family = "unix")]
pub fn chmod(&self, path: &Path, pex: (u8, u8, u8)) -> Result<(), HostError> {
let path: PathBuf = self.to_abs_path(path);
pub fn chmod(&self, path: &Path, pex: UnixPex) -> Result<(), HostError> {
let path: PathBuf = self.to_path(path);
// Get metadta
match fs::metadata(path.as_path()) {
Ok(metadata) => {
let mut mpex = metadata.permissions();
mpex.set_mode(self.mode_to_u32(pex));
mpex.set_mode(pex.into());
match set_permissions(path.as_path(), mpex) {
Ok(_) => {
info!("Changed mode for {} to {:?}", path.display(), pex);
@@ -643,11 +471,9 @@ impl Localhost {
}
}
/// ### open_file_read
///
/// Open file for read
pub fn open_file_read(&self, file: &Path) -> Result<File, HostError> {
let file: PathBuf = self.to_abs_path(file);
pub fn open_file_read(&self, file: &Path) -> Result<StdFile, HostError> {
let file: PathBuf = self.to_path(file);
info!("Opening file {} for read", file.display());
if !self.file_exists(file.as_path()) {
error!("File doesn't exist!");
@@ -675,11 +501,9 @@ impl Localhost {
}
}
/// ### open_file_write
///
/// Open file for write
pub fn open_file_write(&self, file: &Path) -> Result<File, HostError> {
let file: PathBuf = self.to_abs_path(file);
pub fn open_file_write(&self, file: &Path) -> Result<StdFile, HostError> {
let file: PathBuf = self.to_path(file);
info!("Opening file {} for write", file.display());
match OpenOptions::new()
.create(true)
@@ -706,21 +530,17 @@ impl Localhost {
}
}
/// ### file_exists
///
/// Returns whether provided file path exists
pub fn file_exists(&self, path: &Path) -> bool {
path.exists()
}
/// ### scan_dir
///
/// Get content of the current directory as a list of fs entry
pub fn scan_dir(&self, dir: &Path) -> Result<Vec<FsEntry>, HostError> {
pub fn scan_dir(&self, dir: &Path) -> Result<Vec<File>, HostError> {
info!("Reading directory {}", dir.display());
match std::fs::read_dir(dir) {
Ok(e) => {
let mut fs_entries: Vec<FsEntry> = Vec::new();
let mut fs_entries: Vec<File> = Vec::new();
for entry in e.flatten() {
// NOTE: 0.4.1, don't fail if stat for one file fails
match self.stat(entry.path().as_path()) {
@@ -738,24 +558,35 @@ impl Localhost {
}
}
/// ### find
///
/// Find files matching `search` on localhost starting from current directory. Search supports recursive search of course.
/// The `search` argument supports wilcards ('*', '?')
pub fn find(&self, search: &str) -> Result<Vec<FsEntry>, HostError> {
pub fn find(&self, search: &str) -> Result<Vec<File>, HostError> {
self.iter_search(self.wrkdir.as_path(), &WildMatch::new(search))
}
/// Create a symlink at path pointing at target
#[cfg(target_family = "unix")]
pub fn symlink(&self, path: &Path, target: &Path) -> Result<(), HostError> {
let path = self.to_path(path);
std::os::unix::fs::symlink(target, path.as_path()).map_err(|e| {
error!(
"Failed to create symlink at {} pointing at {}: {}",
path.display(),
target.display(),
e
);
HostError::new(HostErrorType::CouldNotCreateFile, Some(e), path.as_path())
})
}
// -- privates
/// ### iter_search
///
/// Recursive call for `find` method.
/// Search in current directory for files which match `filter`.
/// If a directory is found in current directory, `iter_search` will be called using that dir as argument.
fn iter_search(&self, dir: &Path, filter: &WildMatch) -> Result<Vec<FsEntry>, HostError> {
fn iter_search(&self, dir: &Path, filter: &WildMatch) -> Result<Vec<File>, HostError> {
// Scan directory
let mut drained: Vec<FsEntry> = Vec::new();
let mut drained: Vec<File> = Vec::new();
match self.scan_dir(dir) {
Err(err) => Err(err),
Ok(entries) => {
@@ -766,20 +597,16 @@ impl Localhost {
- if is file: check if it matches `filter`
- if it matches `filter`: push to to filter
*/
for entry in entries.iter() {
match entry {
FsEntry::Directory(dir) => {
// If directory matches; push directory to drained
if filter.matches(dir.name.as_str()) {
drained.push(FsEntry::Directory(dir.clone()));
}
drained.append(&mut self.iter_search(dir.abs_path.as_path(), filter)?);
}
FsEntry::File(file) => {
if filter.matches(file.name.as_str()) {
drained.push(FsEntry::File(file.clone()));
}
for entry in entries.into_iter() {
if entry.is_dir() {
// If directory matches; push directory to drained
let next_path = entry.path().to_path_buf();
if filter.matches(entry.name().as_str()) {
drained.push(entry);
}
drained.append(&mut self.iter_search(next_path.as_path(), filter)?);
} else if filter.matches(entry.name().as_str()) {
drained.push(entry);
}
}
Ok(drained)
@@ -787,38 +614,9 @@ impl Localhost {
}
}
/// ### u32_to_mode
///
/// Return string with format xxxxxx to tuple of permissions (user, group, others)
#[cfg(target_family = "unix")]
fn u32_to_mode(&self, mode: u32) -> (u8, u8, u8) {
let user: u8 = ((mode >> 6) & 0x7) as u8;
let group: u8 = ((mode >> 3) & 0x7) as u8;
let others: u8 = (mode & 0x7) as u8;
(user, group, others)
}
/// mode_to_u32
///
/// Convert owner,group,others to u32
#[cfg(target_family = "unix")]
fn mode_to_u32(&self, mode: (u8, u8, u8)) -> u32 {
((mode.0 as u32) << 6) + ((mode.1 as u32) << 3) + mode.2 as u32
}
/// ### to_abs_path
///
/// Convert path to absolute path
fn to_abs_path(&self, p: &Path) -> PathBuf {
// Convert to abs path
match p.is_relative() {
true => {
let mut path: PathBuf = self.wrkdir.clone();
path.push(p);
path
}
false => PathBuf::from(p),
}
fn to_path(&self, p: &Path) -> PathBuf {
path::absolutize(self.wrkdir.as_path(), p)
}
}
@@ -832,7 +630,7 @@ mod tests {
use pretty_assertions::assert_eq;
#[cfg(target_family = "unix")]
use std::fs::File;
use std::fs::File as StdFile;
#[cfg(target_family = "unix")]
use std::io::Write;
@@ -983,7 +781,7 @@ mod tests {
fn test_host_localhost_symlinks() {
let tmpdir: tempfile::TempDir = tempfile::TempDir::new().unwrap();
// Create sample file
assert!(File::create(format!("{}/foo.txt", tmpdir.path().display()).as_str()).is_ok());
assert!(StdFile::create(format!("{}/foo.txt", tmpdir.path().display()).as_str()).is_ok());
// Create symlink
assert!(symlink(
format!("{}/foo.txt", tmpdir.path().display()),
@@ -992,37 +790,27 @@ mod tests {
.is_ok());
// Get dir
let host: Localhost = Localhost::new(PathBuf::from(tmpdir.path())).ok().unwrap();
let files: Vec<FsEntry> = host.list_dir();
let files: Vec<File> = host.list_dir();
// Verify files
let file_0: &FsEntry = files.get(0).unwrap();
match file_0 {
FsEntry::File(file_0) => {
if file_0.name == String::from("foo.txt") {
assert!(file_0.symlink.is_none());
} else {
assert_eq!(
*file_0.symlink.as_ref().unwrap().get_abs_path(),
PathBuf::from(format!("{}/foo.txt", tmpdir.path().display()))
);
}
}
_ => panic!("expected entry 0 to be file: {:?}", file_0),
};
let file_0: &File = files.get(0).unwrap();
if file_0.name() == String::from("foo.txt") {
assert!(file_0.metadata.symlink.is_none());
} else {
assert_eq!(
file_0.metadata.symlink.as_ref().unwrap(),
&PathBuf::from(format!("{}/foo.txt", tmpdir.path().display()))
);
}
// Verify simlink
let file_1: &FsEntry = files.get(1).unwrap();
match file_1 {
FsEntry::File(file_1) => {
if file_1.name == String::from("bar.txt") {
assert_eq!(
*file_1.symlink.as_ref().unwrap().get_abs_path(),
PathBuf::from(format!("{}/foo.txt", tmpdir.path().display()))
);
} else {
assert!(file_1.symlink.is_none());
}
}
_ => panic!("expected entry 0 to be file: {:?}", file_1),
};
let file_1: &File = files.get(1).unwrap();
if file_1.name() == String::from("bar.txt") {
assert_eq!(
file_1.metadata.symlink.as_ref().unwrap(),
&PathBuf::from(format!("{}/foo.txt", tmpdir.path().display()))
);
} else {
assert!(file_1.metadata.symlink.is_none());
}
}
#[test]
@@ -1030,10 +818,10 @@ mod tests {
fn test_host_localhost_mkdir() {
let tmpdir: tempfile::TempDir = tempfile::TempDir::new().unwrap();
let mut host: Localhost = Localhost::new(PathBuf::from(tmpdir.path())).ok().unwrap();
let files: Vec<FsEntry> = host.list_dir();
let files: Vec<File> = host.list_dir();
assert_eq!(files.len(), 0); // There should be 0 files now
assert!(host.mkdir(PathBuf::from("test_dir").as_path()).is_ok());
let files: Vec<FsEntry> = host.list_dir();
let files: Vec<File> = host.list_dir();
assert_eq!(files.len(), 1); // There should be 1 file now
// Try to re-create directory
assert!(host.mkdir(PathBuf::from("test_dir").as_path()).is_err());
@@ -1055,19 +843,19 @@ mod tests {
fn test_host_localhost_remove() {
let tmpdir: tempfile::TempDir = tempfile::TempDir::new().unwrap();
// Create sample file
assert!(File::create(format!("{}/foo.txt", tmpdir.path().display()).as_str()).is_ok());
assert!(StdFile::create(format!("{}/foo.txt", tmpdir.path().display()).as_str()).is_ok());
let mut host: Localhost = Localhost::new(PathBuf::from(tmpdir.path())).ok().unwrap();
let files: Vec<FsEntry> = host.list_dir();
let files: Vec<File> = host.list_dir();
assert_eq!(files.len(), 1); // There should be 1 file now
// Remove file
assert!(host.remove(files.get(0).unwrap()).is_ok());
// There should be 0 files now
let files: Vec<FsEntry> = host.list_dir();
let files: Vec<File> = host.list_dir();
assert_eq!(files.len(), 0); // There should be 0 files now
// Create directory
assert!(host.mkdir(PathBuf::from("test_dir").as_path()).is_ok());
// Delete directory
let files: Vec<FsEntry> = host.list_dir();
let files: Vec<File> = host.list_dir();
assert_eq!(files.len(), 1); // There should be 1 file now
assert!(host.remove(files.get(0).unwrap()).is_ok());
// Remove unexisting directory
@@ -1086,11 +874,11 @@ mod tests {
// Create sample file
let src_path: PathBuf =
PathBuf::from(format!("{}/foo.txt", tmpdir.path().display()).as_str());
assert!(File::create(src_path.as_path()).is_ok());
assert!(StdFile::create(src_path.as_path()).is_ok());
let mut host: Localhost = Localhost::new(PathBuf::from(tmpdir.path())).ok().unwrap();
let files: Vec<FsEntry> = host.list_dir();
let files: Vec<File> = host.list_dir();
assert_eq!(files.len(), 1); // There should be 1 file now
assert_eq!(files.get(0).unwrap().get_name(), "foo.txt");
assert_eq!(files.get(0).unwrap().name(), "foo.txt");
// Rename file
let dst_path: PathBuf =
PathBuf::from(format!("{}/bar.txt", tmpdir.path().display()).as_str());
@@ -1098,9 +886,9 @@ mod tests {
.rename(files.get(0).unwrap(), dst_path.as_path())
.is_ok());
// There should be still 1 file now, but named bar.txt
let files: Vec<FsEntry> = host.list_dir();
let files: Vec<File> = host.list_dir();
assert_eq!(files.len(), 1); // There should be 0 files now
assert_eq!(files.get(0).unwrap().get_name(), "bar.txt");
assert_eq!(files.get(0).unwrap().name(), "bar.txt");
// Fail
let bad_path: PathBuf = PathBuf::from("/asdailsjoidoewojdijow/ashdiuahu");
assert!(host
@@ -1114,16 +902,16 @@ mod tests {
let tmpdir: tempfile::TempDir = tempfile::TempDir::new().unwrap();
let file: tempfile::NamedTempFile = create_sample_file();
let host: Localhost = Localhost::new(PathBuf::from(tmpdir.path())).ok().unwrap();
// mode_to_u32
assert_eq!(host.mode_to_u32((6, 4, 4)), 0o644);
assert_eq!(host.mode_to_u32((7, 7, 5)), 0o775);
// Chmod to file
assert!(host.chmod(file.path(), (7, 7, 5)).is_ok());
assert!(host.chmod(file.path(), UnixPex::from(0o755)).is_ok());
// Chmod to dir
assert!(host.chmod(tmpdir.path(), (7, 5, 0)).is_ok());
assert!(host.chmod(tmpdir.path(), UnixPex::from(0o750)).is_ok());
// Error
assert!(host
.chmod(Path::new("/tmp/krgiogoiegj/kwrgnoerig"), (7, 7, 7))
.chmod(
Path::new("/tmp/krgiogoiegj/kwrgnoerig"),
UnixPex::from(0o777)
)
.is_err());
}
@@ -1135,15 +923,15 @@ mod tests {
let mut file1_path: PathBuf = PathBuf::from(tmpdir.path());
file1_path.push("foo.txt");
// Write file 1
let mut file1: File = File::create(file1_path.as_path()).ok().unwrap();
let mut file1 = StdFile::create(file1_path.as_path()).ok().unwrap();
assert!(file1.write_all(b"Hello world!\n").is_ok());
// Get file 2 path
let mut file2_path: PathBuf = PathBuf::from(tmpdir.path());
file2_path.push("bar.txt");
// Create host
let mut host: Localhost = Localhost::new(PathBuf::from(tmpdir.path())).ok().unwrap();
let file1_entry: FsEntry = host.files.get(0).unwrap().clone();
assert_eq!(file1_entry.get_name(), String::from("foo.txt"));
let file1_entry: File = host.files.get(0).unwrap().clone();
assert_eq!(file1_entry.name(), String::from("foo.txt"));
// Copy
assert!(host.copy(&file1_entry, file2_path.as_path()).is_ok());
// Verify host has two files
@@ -1165,14 +953,14 @@ mod tests {
let mut file1_path: PathBuf = PathBuf::from(tmpdir.path());
file1_path.push("foo.txt");
// Write file 1
let mut file1: File = File::create(file1_path.as_path()).ok().unwrap();
let mut file1 = StdFile::create(file1_path.as_path()).ok().unwrap();
assert!(file1.write_all(b"Hello world!\n").is_ok());
// Get file 2 path
let file2_path: PathBuf = PathBuf::from("bar.txt");
// Create host
let mut host: Localhost = Localhost::new(PathBuf::from(tmpdir.path())).ok().unwrap();
let file1_entry: FsEntry = host.files.get(0).unwrap().clone();
assert_eq!(file1_entry.get_name(), String::from("foo.txt"));
let file1_entry: File = host.files.get(0).unwrap().clone();
assert_eq!(file1_entry.name(), String::from("foo.txt"));
// Copy
assert!(host.copy(&file1_entry, file2_path.as_path()).is_ok());
// Verify host has two files
@@ -1191,15 +979,15 @@ mod tests {
let mut file1_path: PathBuf = dir_src.clone();
file1_path.push("foo.txt");
// Write file 1
let mut file1: File = File::create(file1_path.as_path()).ok().unwrap();
let mut file1 = StdFile::create(file1_path.as_path()).ok().unwrap();
assert!(file1.write_all(b"Hello world!\n").is_ok());
// Copy dir src to dir ddest
let mut dir_dest: PathBuf = PathBuf::from(tmpdir.path());
dir_dest.push("test_dest_dir/");
// Create host
let mut host: Localhost = Localhost::new(PathBuf::from(tmpdir.path())).ok().unwrap();
let dir_src_entry: FsEntry = host.files.get(0).unwrap().clone();
assert_eq!(dir_src_entry.get_name(), String::from("test_dir"));
let dir_src_entry: File = host.files.get(0).unwrap().clone();
assert_eq!(dir_src_entry.name(), String::from("test_dir"));
// Copy
assert!(host.copy(&dir_src_entry, dir_dest.as_path()).is_ok());
// Verify host has two files
@@ -1222,14 +1010,14 @@ mod tests {
let mut file1_path: PathBuf = dir_src.clone();
file1_path.push("foo.txt");
// Write file 1
let mut file1: File = File::create(file1_path.as_path()).ok().unwrap();
let mut file1 = StdFile::create(file1_path.as_path()).ok().unwrap();
assert!(file1.write_all(b"Hello world!\n").is_ok());
// Copy dir src to dir ddest
let dir_dest: PathBuf = PathBuf::from("test_dest_dir/");
// Create host
let mut host: Localhost = Localhost::new(PathBuf::from(tmpdir.path())).ok().unwrap();
let dir_src_entry: FsEntry = host.files.get(0).unwrap().clone();
assert_eq!(dir_src_entry.get_name(), String::from("test_dir"));
let dir_src_entry: File = host.files.get(0).unwrap().clone();
assert_eq!(dir_src_entry.name(), String::from("test_dir"));
// Copy
assert!(host.copy(&dir_src_entry, dir_dest.as_path()).is_ok());
// Verify host has two files
@@ -1268,20 +1056,39 @@ mod tests {
assert!(make_file_at(subdir.as_path(), "examples.csv").is_ok());
let host: Localhost = Localhost::new(PathBuf::from(dir_path)).ok().unwrap();
// Find txt files
let mut result: Vec<FsEntry> = host.find("*.txt").ok().unwrap();
result.sort_by_key(|x: &FsEntry| x.get_name().to_lowercase());
let mut result: Vec<File> = host.find("*.txt").ok().unwrap();
result.sort_by_key(|x: &File| x.name().to_lowercase());
// There should be 3 entries
assert_eq!(result.len(), 3);
// Check names (they should be sorted alphabetically already; NOTE: examples/ comes before pippo.txt)
assert_eq!(result[0].get_name(), "errors.txt");
assert_eq!(result[1].get_name(), "omar.txt");
assert_eq!(result[2].get_name(), "pippo.txt");
assert_eq!(result[0].name(), "errors.txt");
assert_eq!(result[1].name(), "omar.txt");
assert_eq!(result[2].name(), "pippo.txt");
// Search for directory
let mut result: Vec<FsEntry> = host.find("examples*").ok().unwrap();
result.sort_by_key(|x: &FsEntry| x.get_name().to_lowercase());
let mut result: Vec<File> = host.find("examples*").ok().unwrap();
result.sort_by_key(|x: &File| x.name().to_lowercase());
assert_eq!(result.len(), 2);
assert_eq!(result[0].get_name(), "examples");
assert_eq!(result[1].get_name(), "examples.csv");
assert_eq!(result[0].name(), "examples");
assert_eq!(result[1].name(), "examples.csv");
}
#[cfg(target_family = "unix")]
#[test]
fn should_create_symlink() {
let tmpdir: tempfile::TempDir = tempfile::TempDir::new().unwrap();
let dir_path: &Path = tmpdir.path();
// Make file
assert!(make_file_at(dir_path, "pippo.txt").is_ok());
let host: Localhost = Localhost::new(PathBuf::from(dir_path)).ok().unwrap();
let mut p = dir_path.to_path_buf();
p.push("pippo.txt");
// Make symlink
assert!(host.symlink(Path::new("link.txt"), p.as_path()).is_ok());
// Fail symlink
assert!(host.symlink(Path::new("link.txt"), p.as_path()).is_err());
assert!(host
.symlink(Path::new("/tmp/oooo/aaaa"), p.as_path())
.is_err());
}
#[test]

View File

@@ -1,50 +0,0 @@
#![doc(html_playground_url = "https://play.rust-lang.org")]
#![doc(
html_favicon_url = "https://raw.githubusercontent.com/veeso/termscp/main/assets/images/termscp-128.png"
)]
#![doc(
html_logo_url = "https://raw.githubusercontent.com/veeso/termscp/main/assets/images/termscp-512.png"
)]
/**
* MIT License
*
* termscp - Copyright (c) 2021 Christian Visintin
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#[macro_use]
extern crate bitflags;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
#[macro_use]
extern crate magic_crypt;
pub mod activity_manager;
pub mod bookmarks;
pub mod config;
pub mod filetransfer;
pub mod fs;
pub mod host;
pub mod system;
pub mod ui;
pub mod utils;

View File

@@ -1,32 +1,7 @@
/**
* MIT License
*
* termscp - Copyright (c) 2021 Christian Visintin
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
const TERMSCP_VERSION: &str = env!("CARGO_PKG_VERSION");
const TERMSCP_AUTHORS: &str = env!("CARGO_PKG_AUTHORS");
// Crates
extern crate getopts;
#[macro_use]
extern crate bitflags;
#[macro_use]
@@ -35,185 +10,189 @@ extern crate lazy_static;
extern crate log;
#[macro_use]
extern crate magic_crypt;
extern crate rpassword;
// External libs
use getopts::Options;
use std::env;
use std::path::PathBuf;
use std::time::Duration;
// Include
mod activity_manager;
mod bookmarks;
mod cli_opts;
mod config;
mod explorer;
mod filetransfer;
mod fs;
mod host;
mod support;
mod system;
mod ui;
mod utils;
// namespaces
use activity_manager::{ActivityManager, NextActivity};
use filetransfer::FileTransferProtocol;
use system::logging;
/// ### print_usage
///
/// Print usage
fn print_usage(opts: Options) {
let brief = String::from(
"Usage: termscp [options]... [protocol://user@address:port:wrkdir] [local-wrkdir]",
);
print!("{}", opts.usage(&brief));
println!("\nPlease, report issues to <https://github.com/veeso/termscp>");
println!("Please, consider supporting the author <https://www.buymeacoffee.com/veeso>")
}
use cli_opts::{Args, BookmarkParams, HostParams, Remote, RunOpts, Task};
use filetransfer::FileTransferParams;
use system::logging::{self, LogLevel};
fn main() {
let args: Vec<String> = env::args().collect();
//Program CLI options
let mut address: Option<String> = None; // None
let mut port: u16 = 22; // Default port
let mut username: Option<String> = None; // Default username
let mut password: Option<String> = None; // Default password
let mut remote_wrkdir: Option<PathBuf> = None;
let mut protocol: FileTransferProtocol = FileTransferProtocol::Sftp; // Default protocol
let mut ticks: Duration = Duration::from_millis(10);
let mut log_enabled: bool = true;
//Process options
let mut opts = Options::new();
opts.optopt("P", "password", "Provide password from CLI", "<password>");
opts.optopt("T", "ticks", "Set UI ticks; default 10ms", "<ms>");
opts.optflag("q", "quiet", "Disable logging");
opts.optflag("v", "version", "");
opts.optflag("h", "help", "Print this menu");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => {
println!("{}", f.to_string());
let args: Args = argh::from_env();
// Parse args
let run_opts: RunOpts = match parse_args(args) {
Ok(opts) => opts,
Err(err) => {
eprintln!("{}", err);
std::process::exit(255);
}
};
// Help
if matches.opt_present("h") {
print_usage(opts);
std::process::exit(255);
// Setup logging
if let Err(err) = logging::init(run_opts.log_level) {
eprintln!("Failed to initialize logging: {}", err);
}
info!("termscp {} started!", TERMSCP_VERSION);
// Run
info!("Starting activity manager...");
let rc = run(run_opts);
info!("termscp terminated with exitcode {}", rc);
// Then return
std::process::exit(rc);
}
/// Parse arguments
/// In case of success returns `RunOpts`
/// in case something is wrong returns the error message
fn parse_args(args: Args) -> Result<RunOpts, String> {
let mut run_opts: RunOpts = RunOpts::default();
// Version
if matches.opt_present("v") {
eprintln!(
if args.version {
return Err(format!(
"termscp - {} - Developed by {}",
TERMSCP_VERSION, TERMSCP_AUTHORS,
);
std::process::exit(255);
));
}
// Setup activity?
if args.config {
run_opts.task = Task::Activity(NextActivity::SetupActivity);
}
// Logging
if matches.opt_present("q") {
log_enabled = false;
}
// Match password
if let Some(passwd) = matches.opt_str("P") {
password = Some(passwd);
if args.debug {
run_opts.log_level = LogLevel::Trace;
} else if args.quiet {
run_opts.log_level = LogLevel::Off;
}
// Match ticks
if let Some(val) = matches.opt_str("T") {
match val.parse::<usize>() {
Ok(val) => ticks = Duration::from_millis(val as u64),
Err(_) => {
eprintln!("Ticks is not a number '{}'", val);
print_usage(opts);
std::process::exit(255);
}
}
run_opts.ticks = Duration::from_millis(args.ticks);
// @! extra modes
if let Some(theme) = args.theme.as_deref() {
run_opts.task = Task::ImportTheme(PathBuf::from(theme));
}
// Check free args
let extra_args: Vec<String> = matches.free;
if args.update {
run_opts.task = Task::InstallUpdate;
}
// @! Ordinary mode
// Remote argument
if let Some(remote) = extra_args.get(0) {
// Parse address
match utils::parser::parse_remote_opt(remote) {
Ok(host_opts) => {
// Set params
address = Some(host_opts.hostname);
port = host_opts.port;
protocol = host_opts.protocol;
username = host_opts.username;
remote_wrkdir = host_opts.wrkdir;
}
Err(err) => {
eprintln!("Bad address option: {}", err);
print_usage(opts);
std::process::exit(255);
}
match parse_address_arg(&args) {
Err(err) => return Err(err),
Ok(Remote::None) => {}
Ok(remote) => {
// Set params
run_opts.remote = remote;
// In this case the first activity will be FileTransfer
run_opts.task = Task::Activity(NextActivity::FileTransfer);
}
}
// Local directory
if let Some(localdir) = extra_args.get(1) {
if let Some(localdir) = args.positional.get(1) {
// Change working directory if local dir is set
let localdir: PathBuf = PathBuf::from(localdir);
if let Err(err) = env::set_current_dir(localdir.as_path()) {
eprintln!("Bad working directory argument: {}", err);
std::process::exit(255);
return Err(format!("Bad working directory argument: {}", err));
}
}
// Get working directory
let wrkdir: PathBuf = match env::current_dir() {
Ok(dir) => dir,
Err(_) => PathBuf::from("/"),
};
// Setup logging
if log_enabled {
if let Err(err) = logging::init() {
eprintln!("Failed to initialize logging: {}", err);
Ok(run_opts)
}
/// Parse address argument from cli args
fn parse_address_arg(args: &Args) -> Result<Remote, String> {
if let Some(remote) = args.positional.get(0) {
if args.address_as_bookmark {
Ok(Remote::Bookmark(BookmarkParams::new(
remote,
args.password.as_ref(),
)))
} else {
// Parse address
parse_remote_address(remote.as_str())
.map(|x| Remote::Host(HostParams::new(x, args.password.as_deref())))
}
} else {
Ok(Remote::None)
}
info!("termscp {} started!", TERMSCP_VERSION);
// Initialize client if necessary
let mut start_activity: NextActivity = NextActivity::Authentication;
if address.is_some() {
debug!("User has specified remote options: address: {:?}, port: {:?}, protocol: {:?}, user: {:?}, password: {}", address, port, protocol, username, utils::fmt::shadow_password(password.as_deref().unwrap_or("")));
if password.is_none() {
// Ask password if unspecified
password = match rpassword::read_password_from_tty(Some("Password: ")) {
Ok(p) => {
if p.is_empty() {
None
} else {
Some(p)
}
/// Parse remote address
fn parse_remote_address(remote: &str) -> Result<FileTransferParams, String> {
utils::parser::parse_remote_opt(remote).map_err(|e| format!("Bad address option: {}", e))
}
/// ### run
///
/// Run task and return rc
fn run(run_opts: RunOpts) -> i32 {
match run_opts.task {
Task::ImportTheme(theme) => match support::import_theme(theme.as_path()) {
Ok(_) => {
println!("Theme has been successfully imported!");
0
}
Err(err) => {
eprintln!("{}", err);
1
}
},
Task::InstallUpdate => match support::install_update() {
Ok(msg) => {
println!("{}", msg);
0
}
Err(err) => {
eprintln!("Could not install update: {}", err);
1
}
},
Task::Activity(activity) => {
// Get working directory
let wrkdir: PathBuf = match env::current_dir() {
Ok(dir) => dir,
Err(_) => PathBuf::from("/"),
};
// Create activity manager (and context too)
let mut manager: ActivityManager =
match ActivityManager::new(wrkdir.as_path(), run_opts.ticks) {
Ok(m) => m,
Err(err) => {
eprintln!("Could not start activity manager: {}", err);
return 1;
}
};
// Set file transfer params if set
match run_opts.remote {
Remote::Bookmark(BookmarkParams { name, password }) => {
if let Err(err) = manager.resolve_bookmark_name(&name, password.as_deref()) {
eprintln!("{}", err);
return 1;
}
}
Err(_) => {
eprintln!("Could not read password from prompt");
std::process::exit(255);
Remote::Host(HostParams { params, password }) => {
if let Err(err) = manager.set_filetransfer_params(params, password.as_deref()) {
eprintln!("{}", err);
return 1;
}
}
};
debug!(
"Read password from tty: {}",
utils::fmt::shadow_password(password.as_deref().unwrap_or(""))
);
Remote::None => {}
}
manager.run(activity);
0
}
// In this case the first activity will be FileTransfer
start_activity = NextActivity::FileTransfer;
}
// Create activity manager (and context too)
let mut manager: ActivityManager = match ActivityManager::new(&wrkdir, ticks) {
Ok(m) => m,
Err(err) => {
eprintln!("Could not start activity manager: {}", err);
std::process::exit(255);
}
};
// Set file transfer params if set
if let Some(address) = address {
manager.set_filetransfer_params(address, port, protocol, username, password, remote_wrkdir);
}
// Run
info!("Starting activity manager...");
manager.run(start_activity);
info!("termscp terminated");
// Then return
std::process::exit(0);
}

98
src/support.rs Normal file
View File

@@ -0,0 +1,98 @@
//! ## Support
//!
//! this module exposes some extra run modes for termscp, meant to be used for "support", such as installing themes
// mod
use crate::system::{
auto_update::{Update, UpdateStatus},
config_client::ConfigClient,
environment,
notifications::Notification,
theme_provider::ThemeProvider,
};
use std::fs;
use std::path::{Path, PathBuf};
/// ### import_theme
///
/// Import theme at provided path into termscp
pub fn import_theme(p: &Path) -> Result<(), String> {
if !p.exists() {
return Err(String::from(
"Could not import theme: No such file or directory",
));
}
// Validate theme file
ThemeProvider::new(p).map_err(|e| format!("Invalid theme error: {}", e))?;
// get config dir
let cfg_dir: PathBuf = get_config_dir()?;
// Get theme directory
let theme_file: PathBuf = environment::get_theme_path(cfg_dir.as_path());
// Copy theme to theme_dir
fs::copy(p, theme_file.as_path())
.map(|_| ())
.map_err(|e| format!("Could not import theme: {}", e))
}
/// ### install_update
///
/// Install latest version of termscp if an update is available
pub fn install_update() -> Result<String, String> {
match Update::default()
.show_progress(true)
.ask_confirm(true)
.upgrade()
{
Ok(UpdateStatus::AlreadyUptodate) => Ok("termscp is already up to date".to_string()),
Ok(UpdateStatus::UpdateInstalled(v)) => {
if get_config_client()
.map(|x| x.get_notifications())
.unwrap_or(true)
{
Notification::update_installed(v.as_str());
}
Ok(format!("termscp has been updated to version {}", v))
}
Err(err) => {
if get_config_client()
.map(|x| x.get_notifications())
.unwrap_or(true)
{
Notification::update_failed(err.to_string());
}
Err(err.to_string())
}
}
}
/// ### get_config_dir
///
/// Get configuration directory
fn get_config_dir() -> Result<PathBuf, String> {
match environment::init_config_dir() {
Ok(Some(config_dir)) => Ok(config_dir),
Ok(None) => Err(String::from(
"Your system doesn't provide a configuration directory",
)),
Err(err) => Err(format!(
"Could not initialize configuration directory: {}",
err
)),
}
}
/// ### get_config_client
///
/// Get configuration client
fn get_config_client() -> Option<ConfigClient> {
match get_config_dir() {
Err(_) => None,
Ok(dir) => {
let (cfg_path, ssh_key_dir) = environment::get_config_paths(dir.as_path());
match ConfigClient::new(cfg_path.as_path(), ssh_key_dir.as_path()) {
Err(_) => None,
Ok(c) => Some(c),
}
}
}
}

196
src/system/auto_update.rs Normal file
View File

@@ -0,0 +1,196 @@
//! ## Auto update
//!
//! Automatic update module. This module is used to upgrade the current version of termscp to the latest available on Github
use crate::utils::parser::parse_semver;
pub use self_update::errors::Error as UpdateError;
use self_update::{
backends::github::Update as GithubUpdater, cargo_crate_version, update::Release as UpdRelease,
Status,
};
/// ### UpdateStatus
///
/// The status of the update in case of success
#[derive(Debug, Eq, PartialEq)]
pub enum UpdateStatus {
/// Termscp is already up to date
AlreadyUptodate,
/// The update has been correctly installed
UpdateInstalled(String),
}
/// Info related to a github release
#[derive(Debug)]
pub struct Release {
pub version: String,
pub body: String,
}
/// The update structure defines the options used to install the update.
/// Once you're fine with the options, just call the `upgrade()` method to upgrade termscp.
#[derive(Debug, Default)]
pub struct Update {
ask_confirm: bool,
progress: bool,
}
impl Update {
/// Set whether to show or not the progress bar
pub fn show_progress(mut self, opt: bool) -> Self {
self.progress = opt;
self
}
/// Set whether to ask for confirm when updating
pub fn ask_confirm(mut self, opt: bool) -> Self {
self.ask_confirm = opt;
self
}
pub fn upgrade(self) -> Result<UpdateStatus, UpdateError> {
info!("Updating termscp...");
GithubUpdater::configure()
// Set default options
.repo_owner("veeso")
.repo_name("termscp")
.bin_name("termscp")
.current_version(cargo_crate_version!())
.no_confirm(!self.ask_confirm)
.show_download_progress(self.progress)
.show_output(self.progress)
.build()?
.update()
.map(UpdateStatus::from)
}
/// Returns whether a new version of termscp is available
/// In case of success returns Ok(Option<Release>), where the Option is Some(new_version);
/// otherwise if no version is available, return None
/// In case of error returns Error with the error description
pub fn is_new_version_available() -> Result<Option<Release>, UpdateError> {
info!("Checking whether a new version is available...");
GithubUpdater::configure()
// Set default options
.repo_owner("veeso")
.repo_name("termscp")
.bin_name("termscp")
.current_version(cargo_crate_version!())
.no_confirm(true)
.show_download_progress(false)
.show_output(false)
.build()?
.get_latest_release()
.map(Release::from)
.map(Self::check_version)
}
/// In case received version is newer than current one, version as Some is returned; otherwise None
fn check_version(r: Release) -> Option<Release> {
match parse_semver(r.version.as_str()) {
Some(new_version) => {
// Check if version is different
debug!(
"New version: {}; current version: {}",
new_version,
cargo_crate_version!()
);
if new_version.as_str() > cargo_crate_version!() {
Some(r) // New version is available
} else {
None // No new version
}
}
None => None,
}
}
}
impl From<Status> for UpdateStatus {
fn from(s: Status) -> Self {
match s {
Status::UpToDate(_) => Self::AlreadyUptodate,
Status::Updated(v) => Self::UpdateInstalled(v),
}
}
}
impl From<UpdRelease> for Release {
fn from(r: UpdRelease) -> Self {
Self {
version: r.version,
body: r.body.unwrap_or_default(),
}
}
}
#[cfg(test)]
mod test {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn auto_update_default() {
let upd: Update = Update::default();
assert_eq!(upd.ask_confirm, false);
assert_eq!(upd.progress, false);
let upd = upd.ask_confirm(true).show_progress(true);
assert_eq!(upd.ask_confirm, true);
assert_eq!(upd.progress, true);
}
#[test]
#[cfg(not(all(
any(target_os = "macos", target_os = "freebsd"),
feature = "github-actions"
)))]
fn auto_update() {
// Wno version
assert_eq!(
Update::default()
.show_progress(true)
.upgrade()
.ok()
.unwrap(),
UpdateStatus::AlreadyUptodate,
);
}
#[test]
#[cfg(not(all(
any(target_os = "macos", target_os = "freebsd"),
feature = "github-actions"
)))]
fn check_for_updates() {
println!("{:?}", Update::is_new_version_available());
assert!(Update::is_new_version_available().is_ok());
}
#[test]
fn update_status() {
assert_eq!(
UpdateStatus::from(Status::Updated(String::from("0.6.0"))),
UpdateStatus::UpdateInstalled(String::from("0.6.0"))
);
assert_eq!(
UpdateStatus::from(Status::UpToDate(String::from("0.6.0"))),
UpdateStatus::AlreadyUptodate
);
}
#[test]
fn release() {
let release: UpdRelease = UpdRelease {
name: String::from("termscp 0.7.0"),
version: String::from("0.7.0"),
date: String::from("2021-09-12T00:00:00Z"),
body: Some(String::from("fixed everything")),
assets: vec![],
};
let release: Release = Release::from(release);
assert_eq!(release.body.as_str(), "fixed everything");
assert_eq!(release.version.as_str(), "0.7.0");
}
}

View File

@@ -2,51 +2,25 @@
//!
//! `bookmarks_client` is the module which provides an API between the Bookmarks module and the system
/**
* MIT License
*
* termscp - Copyright (c) 2021 Christian Visintin
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// Deps
extern crate whoami;
// Crate
#[cfg(any(target_os = "windows", target_os = "macos"))]
#[cfg(feature = "with-keyring")]
use super::keys::keyringstorage::KeyringStorage;
use super::keys::{filestorage::FileStorage, KeyStorage, KeyStorageError};
// Local
use crate::bookmarks::serializer::BookmarkSerializer;
use crate::bookmarks::{Bookmark, SerializerError, SerializerErrorKind, UserHosts};
use crate::filetransfer::FileTransferProtocol;
use crate::config::{
bookmarks::{Bookmark, UserHosts},
serialization::{deserialize, serialize, SerializerError, SerializerErrorKind},
};
use crate::filetransfer::FileTransferParams;
use crate::utils::crypto;
use crate::utils::fmt::fmt_time;
use crate::utils::random::random_alphanumeric_with_len;
// Ext
use std::fs::OpenOptions;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::string::ToString;
use std::time::SystemTime;
/// ## BookmarksClient
///
/// BookmarksClient provides a layer between the host system and the bookmarks module
pub struct BookmarksClient {
hosts: UserHosts,
@@ -56,8 +30,6 @@ pub struct BookmarksClient {
}
impl BookmarksClient {
/// ### BookmarksClient
///
/// Instantiates a new BookmarksClient
/// Bookmarks file path must be provided
/// Storage path for file provider must be provided
@@ -67,10 +39,10 @@ impl BookmarksClient {
recents_size: usize,
) -> Result<BookmarksClient, SerializerError> {
// Create default hosts
let default_hosts: UserHosts = Default::default();
let default_hosts: UserHosts = UserHosts::default();
debug!("Setting up bookmarks client...");
// Make a key storage (windows / macos)
#[cfg(any(target_os = "windows", target_os = "macos"))]
// Make a key storage (with-keyring)
#[cfg(feature = "with-keyring")]
let (key_storage, service_id): (Box<dyn KeyStorage>, &str) = {
debug!("Setting up KeyStorage");
let username: String = whoami::username();
@@ -91,13 +63,8 @@ impl BookmarksClient {
}
}
};
// Make a key storage (linux / unix)
#[cfg(any(
target_os = "linux",
target_os = "freebsd",
target_os = "netbsd",
target_os = "netbsd"
))]
// Make a key storage (wno-keyring)
#[cfg(not(feature = "with-keyring"))]
let (key_storage, service_id): (Box<dyn KeyStorage>, &str) = {
#[cfg(not(test))]
let app_name: &str = "bookmarks";
@@ -120,7 +87,7 @@ impl BookmarksClient {
if let Err(e) = key_storage.set_key(service_id, key.as_str()) {
error!("Failed to set new key into storage: {}", e);
return Err(SerializerError::new_ex(
SerializerErrorKind::IoError,
SerializerErrorKind::Io,
format!("Could not write key to storage: {}", e),
));
}
@@ -130,7 +97,7 @@ impl BookmarksClient {
_ => {
error!("Failed to get key from storage: {}", e);
return Err(SerializerError::new_ex(
SerializerErrorKind::IoError,
SerializerErrorKind::Io,
format!("Could not get key from storage: {}", e),
));
}
@@ -161,126 +128,119 @@ impl BookmarksClient {
Ok(client)
}
/// ### iter_bookmarks
///
/// Iterate over bookmarks keys
pub fn iter_bookmarks(&self) -> impl Iterator<Item = &String> + '_ {
Box::new(self.hosts.bookmarks.keys())
}
/// ### get_bookmark
///
/// Get bookmark associated to key
pub fn get_bookmark(
&self,
key: &str,
) -> Option<(String, u16, FileTransferProtocol, String, Option<String>)> {
let entry: &Bookmark = self.hosts.bookmarks.get(key)?;
pub fn get_bookmark(&self, key: &str) -> Option<FileTransferParams> {
debug!("Getting bookmark {}", key);
Some((
entry.address.clone(),
entry.port,
match FileTransferProtocol::from_str(entry.protocol.as_str()) {
Ok(proto) => proto,
Err(err) => {
error!(
"Found invalid protocol in bookmarks: {}; defaulting to SFTP",
err
);
FileTransferProtocol::Sftp // Default
let mut entry: Bookmark = self.hosts.bookmarks.get(key).cloned()?;
// Decrypt password first
if let Some(pwd) = entry.password.as_mut() {
match self.decrypt_str(pwd.as_str()) {
Ok(decrypted_pwd) => {
*pwd = decrypted_pwd;
}
},
entry.username.clone(),
match &entry.password {
// Decrypted password if Some; if decryption fails return None
Some(pwd) => match self.decrypt_str(pwd.as_str()) {
Ok(decrypted_pwd) => Some(decrypted_pwd),
Err(err) => {
error!("Failed to decrypt password for bookmark: {}", err);
None
Err(err) => {
error!("Failed to decrypt `password` for bookmark {}: {}", key, err);
}
}
}
// Decrypt AWS-S3 params
if let Some(s3) = entry.s3.as_mut() {
// Access key
if let Some(access_key) = s3.access_key.as_mut() {
match self.decrypt_str(access_key.as_str()) {
Ok(plain) => {
*access_key = plain;
}
},
None => None,
},
))
Err(err) => {
error!(
"Failed to decrypt `access_key` for bookmark {}: {}",
key, err
);
}
}
}
// Secret access key
if let Some(secret_access_key) = s3.secret_access_key.as_mut() {
match self.decrypt_str(secret_access_key.as_str()) {
Ok(plain) => {
*secret_access_key = plain;
}
Err(err) => {
error!(
"Failed to decrypt `secret_access_key` for bookmark {}: {}",
key, err
);
}
}
}
}
// Then convert into
Some(FileTransferParams::from(entry))
}
/// ### add_recent
///
/// Add a new recent to bookmarks
pub fn add_bookmark(
pub fn add_bookmark<S: AsRef<str>>(
&mut self,
name: String,
addr: String,
port: u16,
protocol: FileTransferProtocol,
username: String,
password: Option<String>,
name: S,
params: FileTransferParams,
save_password: bool,
) {
let name: String = name.as_ref().to_string();
if name.is_empty() {
error!("Fatal error; bookmark name is empty");
panic!("Bookmark name can't be empty");
}
// Make bookmark
info!("Added bookmark {} with address {}", name, addr);
let host: Bookmark = self.make_bookmark(addr, port, protocol, username, password);
info!("Added bookmark {}", name);
let mut host: Bookmark = self.make_bookmark(params);
// If not save_password, set secrets to `None`
if !save_password {
host.password = None;
if let Some(s3) = host.s3.as_mut() {
s3.access_key = None;
s3.secret_access_key = None;
}
}
self.hosts.bookmarks.insert(name, host);
}
/// ### del_bookmark
///
/// Delete entry from bookmarks
pub fn del_bookmark(&mut self, name: &str) {
let _ = self.hosts.bookmarks.remove(name);
info!("Removed bookmark {}", name);
}
/// ### iter_recents
///
/// Iterate over recents keys
pub fn iter_recents(&self) -> impl Iterator<Item = &String> + '_ {
Box::new(self.hosts.recents.keys())
}
/// ### get_recent
///
/// Get recent associated to key
pub fn get_recent(&self, key: &str) -> Option<(String, u16, FileTransferProtocol, String)> {
pub fn get_recent(&self, key: &str) -> Option<FileTransferParams> {
// NOTE: password is not decrypted; recents will never have password
info!("Getting bookmark {}", key);
let entry: &Bookmark = self.hosts.recents.get(key)?;
Some((
entry.address.clone(),
entry.port,
match FileTransferProtocol::from_str(entry.protocol.as_str()) {
Ok(proto) => proto,
Err(err) => {
error!(
"Found invalid protocol in bookmarks: {}; defaulting to SFTP",
err
);
FileTransferProtocol::Sftp // Default
}
},
entry.username.clone(),
))
let entry: Bookmark = self.hosts.recents.get(key).cloned()?;
Some(FileTransferParams::from(entry))
}
/// ### add_recent
///
/// Add a new recent to bookmarks
pub fn add_recent(
&mut self,
addr: String,
port: u16,
protocol: FileTransferProtocol,
username: String,
) {
pub fn add_recent(&mut self, params: FileTransferParams) {
// Make bookmark
let host: Bookmark = self.make_bookmark(addr, port, protocol, username, None);
let mut host: Bookmark = self.make_bookmark(params);
// Null password for recents
host.password = None;
if let Some(s3) = host.s3.as_mut() {
s3.access_key = None;
s3.secret_access_key = None;
}
// Check if duplicated
for recent_host in self.hosts.recents.values() {
if *recent_host == host {
debug!("Discarding recent since duplicated ({})", host.address);
for (key, value) in &self.hosts.recents {
if *value == host {
debug!("Discarding recent since duplicated ({})", key);
// Don't save duplicates
return;
}
@@ -305,20 +265,16 @@ impl BookmarksClient {
}
}
let name: String = fmt_time(SystemTime::now(), "ISO%Y%m%dT%H%M%S");
info!("Saved recent host {} ({})", name, host.address);
info!("Saved recent host {}", name);
self.hosts.recents.insert(name, host);
}
/// ### del_recent
///
/// Delete entry from recents
pub fn del_recent(&mut self, name: &str) {
let _ = self.hosts.recents.remove(name);
info!("Removed recent host {}", name);
}
/// ### write_bookmarks
///
/// Write bookmarks to file
pub fn write_bookmarks(&self) -> Result<(), SerializerError> {
// Open file
@@ -329,22 +285,17 @@ impl BookmarksClient {
.truncate(true)
.open(self.bookmarks_file.as_path())
{
Ok(writer) => {
let serializer: BookmarkSerializer = BookmarkSerializer {};
serializer.serialize(Box::new(writer), &self.hosts)
}
Ok(writer) => serialize(&self.hosts, Box::new(writer)),
Err(err) => {
error!("Failed to write bookmarks: {}", err);
Err(SerializerError::new_ex(
SerializerErrorKind::IoError,
SerializerErrorKind::Io,
err.to_string(),
))
}
}
}
/// ### read_bookmarks
///
/// Read bookmarks from file
fn read_bookmarks(&mut self) -> Result<(), SerializerError> {
// Open bookmarks file for read
@@ -355,8 +306,7 @@ impl BookmarksClient {
{
Ok(reader) => {
// Deserialize
let deserializer: BookmarkSerializer = BookmarkSerializer {};
match deserializer.deserialize(Box::new(reader)) {
match deserialize(Box::new(reader)) {
Ok(hosts) => {
self.hosts = hosts;
Ok(())
@@ -367,56 +317,49 @@ impl BookmarksClient {
Err(err) => {
error!("Failed to read bookmarks: {}", err);
Err(SerializerError::new_ex(
SerializerErrorKind::IoError,
SerializerErrorKind::Io,
err.to_string(),
))
}
}
}
/// ### generate_key
///
/// Generate a new AES key
fn generate_key() -> String {
// Generate 256 bytes (2048 bits) key
random_alphanumeric_with_len(256)
}
/// ### make_bookmark
///
/// Make bookmark from credentials
fn make_bookmark(
&self,
addr: String,
port: u16,
protocol: FileTransferProtocol,
username: String,
password: Option<String>,
) -> Bookmark {
Bookmark {
address: addr,
port,
username,
protocol: protocol.to_string(),
password: password.map(|p| self.encrypt_str(p.as_str())),
fn make_bookmark(&self, params: FileTransferParams) -> Bookmark {
let mut bookmark: Bookmark = Bookmark::from(params);
// Encrypt password
if let Some(pwd) = bookmark.password {
bookmark.password = Some(self.encrypt_str(pwd.as_str()));
}
// Encrypt aws s3 params
if let Some(s3) = bookmark.s3.as_mut() {
if let Some(access_key) = s3.access_key.as_mut() {
*access_key = self.encrypt_str(access_key.as_str());
}
if let Some(secret_access_key) = s3.secret_access_key.as_mut() {
*secret_access_key = self.encrypt_str(secret_access_key.as_str());
}
}
bookmark
}
/// ### encrypt_str
///
/// Encrypt provided string using AES-128. Encrypted buffer is then converted to BASE64
fn encrypt_str(&self, txt: &str) -> String {
crypto::aes128_b64_crypt(self.key.as_str(), txt)
}
/// ### decrypt_str
///
/// Decrypt provided string using AES-128
fn decrypt_str(&self, secret: &str) -> Result<String, SerializerError> {
match crypto::aes128_b64_decrypt(self.key.as_str(), secret) {
Ok(txt) => Ok(txt),
Err(err) => Err(SerializerError::new_ex(
SerializerErrorKind::SyntaxError,
SerializerErrorKind::Syntax,
err.to_string(),
)),
}
@@ -428,6 +371,8 @@ impl BookmarksClient {
mod tests {
use super::*;
use crate::filetransfer::params::{AwsS3Params, GenericProtocolParams};
use crate::filetransfer::{FileTransferProtocol, ProtocolParams};
use pretty_assertions::assert_eq;
use std::thread::sleep;
@@ -455,7 +400,7 @@ mod tests {
target_os = "linux",
target_os = "freebsd",
target_os = "netbsd",
target_os = "netbsd"
target_os = "openbsd"
))]
fn test_system_bookmarks_new_err() {
assert!(BookmarksClient::new(
@@ -482,19 +427,23 @@ mod tests {
BookmarksClient::new(cfg_path.as_path(), key_path.as_path(), 16).unwrap();
// Add some bookmarks
client.add_bookmark(
String::from("raspberry"),
String::from("192.168.1.31"),
22,
FileTransferProtocol::Sftp,
String::from("pi"),
Some(String::from("mypassword")),
"raspberry",
make_generic_ftparams(
FileTransferProtocol::Sftp,
"192.168.1.31",
22,
"pi",
Some("mypassword"),
),
true,
);
client.add_recent(
String::from("192.168.1.31"),
22,
client.add_recent(make_generic_ftparams(
FileTransferProtocol::Sftp,
String::from("pi"),
);
"192.168.1.31",
22,
"pi",
Some("mypassword"),
));
let recent_key: String = String::from(client.iter_recents().next().unwrap());
assert!(client.write_bookmarks().is_ok());
let key: String = client.key.clone();
@@ -503,19 +452,81 @@ mod tests {
BookmarksClient::new(cfg_path.as_path(), key_path.as_path(), 16).unwrap();
// Verify it loaded parameters correctly
assert_eq!(client.key, key);
let bookmark: (String, u16, FileTransferProtocol, String, Option<String>) =
client.get_bookmark(&String::from("raspberry")).unwrap();
let bookmark = ftparams_to_tup(client.get_bookmark("raspberry").unwrap());
assert_eq!(bookmark.0, String::from("192.168.1.31"));
assert_eq!(bookmark.1, 22);
assert_eq!(bookmark.2, FileTransferProtocol::Sftp);
assert_eq!(bookmark.3, String::from("pi"));
assert_eq!(*bookmark.4.as_ref().unwrap(), String::from("mypassword"));
let bookmark: (String, u16, FileTransferProtocol, String) =
client.get_recent(&recent_key).unwrap();
let bookmark = ftparams_to_tup(client.get_recent(&recent_key).unwrap());
assert_eq!(bookmark.0, String::from("192.168.1.31"));
assert_eq!(bookmark.1, 22);
assert_eq!(bookmark.2, FileTransferProtocol::Sftp);
assert_eq!(bookmark.3, String::from("pi"));
assert_eq!(bookmark.4, None);
}
#[test]
fn should_make_s3_bookmark_with_secrets() {
let tmp_dir: tempfile::TempDir = TempDir::new().ok().unwrap();
let (cfg_path, key_path): (PathBuf, PathBuf) = get_paths(tmp_dir.path());
// Initialize a new bookmarks client
let mut client: BookmarksClient =
BookmarksClient::new(cfg_path.as_path(), key_path.as_path(), 16).unwrap();
// Add s3 bookmark
client.add_bookmark("my-bucket", make_s3_ftparams(), true);
// Verify bookmark
let bookmark = client.get_bookmark("my-bucket").unwrap();
assert_eq!(bookmark.protocol, FileTransferProtocol::AwsS3);
let params = bookmark.params.s3_params().unwrap();
assert_eq!(params.access_key.as_deref().unwrap(), "pippo");
assert_eq!(params.profile.as_deref().unwrap(), "test");
assert_eq!(params.secret_access_key.as_deref().unwrap(), "pluto");
assert_eq!(params.bucket_name.as_str(), "omar");
assert_eq!(params.region.as_deref().unwrap(), "eu-west-1");
}
#[test]
fn should_make_s3_bookmark_without_secrets() {
let tmp_dir: tempfile::TempDir = TempDir::new().ok().unwrap();
let (cfg_path, key_path): (PathBuf, PathBuf) = get_paths(tmp_dir.path());
// Initialize a new bookmarks client
let mut client: BookmarksClient =
BookmarksClient::new(cfg_path.as_path(), key_path.as_path(), 16).unwrap();
// Add s3 bookmark
client.add_bookmark("my-bucket", make_s3_ftparams(), false);
// Verify bookmark
let bookmark = client.get_bookmark("my-bucket").unwrap();
assert_eq!(bookmark.protocol, FileTransferProtocol::AwsS3);
let params = bookmark.params.s3_params().unwrap();
assert_eq!(params.profile.as_deref().unwrap(), "test");
assert_eq!(params.bucket_name.as_str(), "omar");
assert_eq!(params.region.as_deref().unwrap(), "eu-west-1");
// secrets
assert_eq!(params.access_key, None);
assert_eq!(params.secret_access_key, None);
}
#[test]
fn should_make_s3_recent() {
let tmp_dir: tempfile::TempDir = TempDir::new().ok().unwrap();
let (cfg_path, key_path): (PathBuf, PathBuf) = get_paths(tmp_dir.path());
// Initialize a new bookmarks client
let mut client: BookmarksClient =
BookmarksClient::new(cfg_path.as_path(), key_path.as_path(), 16).unwrap();
// Add s3 bookmark
client.add_recent(make_s3_ftparams());
// Verify bookmark
let bookmark = client.iter_recents().next().unwrap();
let bookmark = client.get_recent(bookmark).unwrap();
assert_eq!(bookmark.protocol, FileTransferProtocol::AwsS3);
let params = bookmark.params.s3_params().unwrap();
assert_eq!(params.profile.as_deref().unwrap(), "test");
assert_eq!(params.bucket_name.as_str(), "omar");
assert_eq!(params.region.as_deref().unwrap(), "eu-west-1");
// secrets
assert_eq!(params.access_key, None);
assert_eq!(params.secret_access_key, None);
}
#[test]
@@ -528,26 +539,31 @@ mod tests {
BookmarksClient::new(cfg_path.as_path(), key_path.as_path(), 16).unwrap();
// Add bookmark
client.add_bookmark(
String::from("raspberry"),
String::from("192.168.1.31"),
22,
FileTransferProtocol::Sftp,
String::from("pi"),
Some(String::from("mypassword")),
"raspberry",
make_generic_ftparams(
FileTransferProtocol::Sftp,
"192.168.1.31",
22,
"pi",
Some("mypassword"),
),
true,
);
client.add_bookmark(
String::from("raspberry2"),
String::from("192.168.1.32"),
22,
FileTransferProtocol::Sftp,
String::from("pi"),
Some(String::from("mypassword2")),
"raspberry2",
make_generic_ftparams(
FileTransferProtocol::Sftp,
"192.168.1.31",
22,
"pi",
Some("mypassword2"),
),
true,
);
// Iter
assert_eq!(client.iter_bookmarks().count(), 2);
// Get bookmark
let bookmark: (String, u16, FileTransferProtocol, String, Option<String>) =
client.get_bookmark(&String::from("raspberry")).unwrap();
let bookmark = ftparams_to_tup(client.get_bookmark(&String::from("raspberry")).unwrap());
assert_eq!(bookmark.0, String::from("192.168.1.31"));
assert_eq!(bookmark.1, 22);
assert_eq!(bookmark.2, FileTransferProtocol::Sftp);
@@ -574,15 +590,45 @@ mod tests {
BookmarksClient::new(cfg_path.as_path(), key_path.as_path(), 16).unwrap();
// Add bookmark
client.add_bookmark(
String::from(""),
String::from("192.168.1.31"),
22,
FileTransferProtocol::Sftp,
String::from("pi"),
Some(String::from("mypassword")),
"",
make_generic_ftparams(
FileTransferProtocol::Sftp,
"192.168.1.31",
22,
"pi",
Some("mypassword"),
),
true,
);
}
#[test]
fn save_bookmark_wno_password() {
let tmp_dir: tempfile::TempDir = TempDir::new().ok().unwrap();
let (cfg_path, key_path): (PathBuf, PathBuf) = get_paths(tmp_dir.path());
// Initialize a new bookmarks client
let mut client: BookmarksClient =
BookmarksClient::new(cfg_path.as_path(), key_path.as_path(), 16).unwrap();
// Add bookmark
client.add_bookmark(
"raspberry",
make_generic_ftparams(
FileTransferProtocol::Sftp,
"192.168.1.31",
22,
"pi",
Some("mypassword"),
),
false,
);
let bookmark = ftparams_to_tup(client.get_bookmark(&String::from("raspberry")).unwrap());
assert_eq!(bookmark.0, String::from("192.168.1.31"));
assert_eq!(bookmark.1, 22);
assert_eq!(bookmark.2, FileTransferProtocol::Sftp);
assert_eq!(bookmark.3, String::from("pi"));
assert_eq!(bookmark.4, None);
}
#[test]
fn test_system_bookmarks_manipulate_recents() {
@@ -592,22 +638,23 @@ mod tests {
let mut client: BookmarksClient =
BookmarksClient::new(cfg_path.as_path(), key_path.as_path(), 16).unwrap();
// Add bookmark
client.add_recent(
String::from("192.168.1.31"),
22,
client.add_recent(make_generic_ftparams(
FileTransferProtocol::Sftp,
String::from("pi"),
);
"192.168.1.31",
22,
"pi",
Some("mypassword"),
));
// Iter
assert_eq!(client.iter_recents().count(), 1);
let key: String = String::from(client.iter_recents().next().unwrap());
// Get bookmark
let bookmark: (String, u16, FileTransferProtocol, String) =
client.get_recent(&key).unwrap();
let bookmark = ftparams_to_tup(client.get_recent(&key).unwrap());
assert_eq!(bookmark.0, String::from("192.168.1.31"));
assert_eq!(bookmark.1, 22);
assert_eq!(bookmark.2, FileTransferProtocol::Sftp);
assert_eq!(bookmark.3, String::from("pi"));
assert_eq!(bookmark.4, None);
// Write bookmarks
assert!(client.write_bookmarks().is_ok());
// Delete bookmark
@@ -627,18 +674,20 @@ mod tests {
let mut client: BookmarksClient =
BookmarksClient::new(cfg_path.as_path(), key_path.as_path(), 16).unwrap();
// Add bookmark
client.add_recent(
String::from("192.168.1.31"),
22,
client.add_recent(make_generic_ftparams(
FileTransferProtocol::Sftp,
String::from("pi"),
);
client.add_recent(
String::from("192.168.1.31"),
"192.168.1.31",
22,
"pi",
Some("mypassword"),
));
client.add_recent(make_generic_ftparams(
FileTransferProtocol::Sftp,
String::from("pi"),
);
"192.168.1.31",
22,
"pi",
Some("mypassword"),
));
// There should be only one recent
assert_eq!(client.iter_recents().count(), 1);
}
@@ -653,39 +702,60 @@ mod tests {
BookmarksClient::new(cfg_path.as_path(), key_path.as_path(), 2).unwrap();
// Add recent, wait 1 second for each one (cause the name depends on time)
// 1
client.add_recent(
String::from("192.168.1.1"),
22,
client.add_recent(make_generic_ftparams(
FileTransferProtocol::Sftp,
String::from("pi"),
);
"192.168.1.1",
22,
"pi",
Some("mypassword"),
));
sleep(Duration::from_secs(1));
// 2
client.add_recent(
String::from("192.168.1.2"),
22,
client.add_recent(make_generic_ftparams(
FileTransferProtocol::Sftp,
String::from("pi"),
);
"192.168.1.2",
22,
"pi",
Some("mypassword"),
));
sleep(Duration::from_secs(1));
// 3
client.add_recent(
String::from("192.168.1.3"),
22,
client.add_recent(make_generic_ftparams(
FileTransferProtocol::Sftp,
String::from("pi"),
);
"192.168.1.3",
22,
"pi",
Some("mypassword"),
));
// Limit is 2
assert_eq!(client.iter_recents().count(), 2);
// Check that 192.168.1.1 has been removed
let key: String = client.iter_recents().nth(0).unwrap().to_string();
assert!(matches!(
client.hosts.recents.get(&key).unwrap().address.as_str(),
client
.hosts
.recents
.get(&key)
.unwrap()
.address
.as_ref()
.cloned()
.unwrap_or_default()
.as_str(),
"192.168.1.2" | "192.168.1.3"
));
let key: String = client.iter_recents().nth(1).unwrap().to_string();
assert!(matches!(
client.hosts.recents.get(&key).unwrap().address.as_str(),
client
.hosts
.recents
.get(&key)
.unwrap()
.address
.as_ref()
.cloned()
.unwrap_or_default()
.as_str(),
"192.168.1.2" | "192.168.1.3"
));
}
@@ -700,17 +770,33 @@ mod tests {
BookmarksClient::new(cfg_path.as_path(), key_path.as_path(), 16).unwrap();
// Add bookmark
client.add_bookmark(
String::from(""),
String::from("192.168.1.31"),
22,
FileTransferProtocol::Sftp,
String::from("pi"),
Some(String::from("mypassword")),
"",
make_generic_ftparams(
FileTransferProtocol::Sftp,
"192.168.1.31",
22,
"pi",
Some("mypassword"),
),
true,
);
}
/// ### get_paths
///
#[test]
fn test_system_bookmarks_decrypt_str() {
let tmp_dir: tempfile::TempDir = TempDir::new().ok().unwrap();
let (cfg_path, key_path): (PathBuf, PathBuf) = get_paths(tmp_dir.path());
// Initialize a new bookmarks client
let mut client: BookmarksClient =
BookmarksClient::new(cfg_path.as_path(), key_path.as_path(), 16).unwrap();
client.key = "MYSUPERSECRETKEY".to_string();
assert_eq!(
client.decrypt_str("z4Z6LpcpYqBW4+bkIok+5A==").ok().unwrap(),
"Hello world!"
);
assert!(client.decrypt_str("bidoof").is_err());
}
/// Get paths for configuration and key for bookmarks
fn get_paths(dir: &Path) -> (PathBuf, PathBuf) {
let k: PathBuf = PathBuf::from(dir);
@@ -718,4 +804,50 @@ mod tests {
c.push("bookmarks.toml");
(c, k)
}
fn make_generic_ftparams(
protocol: FileTransferProtocol,
address: &str,
port: u16,
username: &str,
password: Option<&str>,
) -> FileTransferParams {
let params = ProtocolParams::Generic(
GenericProtocolParams::default()
.address(address)
.port(port)
.username(Some(username))
.password(password),
);
FileTransferParams::new(protocol, params)
}
fn make_s3_ftparams() -> FileTransferParams {
FileTransferParams::new(
FileTransferProtocol::AwsS3,
ProtocolParams::AwsS3(
AwsS3Params::new("omar", Some("eu-west-1"), Some("test"))
.endpoint(Some("http://localhost:9000"))
.new_path_style(false)
.access_key(Some("pippo"))
.secret_access_key(Some("pluto"))
.security_token(Some("omar"))
.session_token(Some("gerry-scotti")),
),
)
}
fn ftparams_to_tup(
params: FileTransferParams,
) -> (String, u16, FileTransferProtocol, String, Option<String>) {
let protocol = params.protocol;
let p = params.params.generic_params().unwrap();
(
p.address.to_string(),
p.port,
protocol,
p.username.as_ref().cloned().unwrap_or_default(),
p.password.as_ref().cloned(),
)
}
}

View File

@@ -2,36 +2,13 @@
//!
//! `config_client` is the module which provides an API between the Config module and the system
/**
* MIT License
*
* termscp - Copyright (c) 2021 Christian Visintin
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// Deps
extern crate rand;
// Locals
use crate::config::serializer::ConfigSerializer;
use crate::config::{SerializerError, SerializerErrorKind, UserConfig};
use crate::config::{
params::{UserConfig, DEFAULT_NOTIFICATION_TRANSFER_THRESHOLD},
serialization::{deserialize, serialize, SerializerError, SerializerErrorKind},
};
use crate::explorer::GroupDirs;
use crate::filetransfer::FileTransferProtocol;
use crate::fs::explorer::GroupDirs;
// Ext
use std::fs::{create_dir, remove_file, File, OpenOptions};
use std::io::Write;
@@ -42,20 +19,17 @@ use std::string::ToString;
// Types
pub type SshHost = (String, String, PathBuf); // 0: host, 1: username, 2: RSA key path
/// ## ConfigClient
///
/// ConfigClient provides a high level API to communicate with the termscp configuration
pub struct ConfigClient {
config: UserConfig, // Configuration loaded
config_path: PathBuf, // Configuration TOML Path
ssh_key_dir: PathBuf, // SSH Key storage directory
degraded: bool, // Indicates the `ConfigClient` is working in degraded mode
}
impl ConfigClient {
/// ### new
///
/// Instantiate a new `ConfigClient` with provided path
pub fn new(config_path: &Path, ssh_key_dir: &Path) -> Result<ConfigClient, SerializerError> {
pub fn new(config_path: &Path, ssh_key_dir: &Path) -> Result<Self, SerializerError> {
// Initialize a default configuration
let default_config: UserConfig = UserConfig::default();
info!(
@@ -68,13 +42,14 @@ impl ConfigClient {
config: default_config,
config_path: PathBuf::from(config_path),
ssh_key_dir: PathBuf::from(ssh_key_dir),
degraded: false,
};
// If ssh key directory doesn't exist, create it
if !ssh_key_dir.exists() {
if let Err(err) = create_dir(ssh_key_dir) {
error!("Failed to create SSH key dir: {}", err);
return Err(SerializerError::new_ex(
SerializerErrorKind::IoError,
SerializerErrorKind::Io,
format!(
"Could not create SSH key directory \"{}\": {}",
ssh_key_dir.display(),
@@ -102,17 +77,25 @@ impl ConfigClient {
Ok(client)
}
/// Instantiate a ConfigClient in degraded mode.
/// When in degraded mode, the configuration in use will be the default configuration
/// and the IO operation on configuration won't be available
pub fn degraded() -> Self {
Self {
config: UserConfig::default(),
config_path: PathBuf::default(),
ssh_key_dir: PathBuf::default(),
degraded: true,
}
}
// Text editor
/// ### get_text_editor
///
/// Get text editor from configuration
pub fn get_text_editor(&self) -> PathBuf {
self.config.user_interface.text_editor.clone()
}
/// ### set_text_editor
///
/// Set text editor path
pub fn set_text_editor(&mut self, path: PathBuf) {
self.config.user_interface.text_editor = path;
@@ -120,8 +103,6 @@ impl ConfigClient {
// Default protocol
/// ### get_default_protocol
///
/// Get default protocol from configuration
pub fn get_default_protocol(&self) -> FileTransferProtocol {
match FileTransferProtocol::from_str(self.config.user_interface.default_protocol.as_str()) {
@@ -130,43 +111,44 @@ impl ConfigClient {
}
}
/// ### set_default_protocol
///
/// Set default protocol to configuration
pub fn set_default_protocol(&mut self, proto: FileTransferProtocol) {
self.config.user_interface.default_protocol = proto.to_string();
}
/// ### get_show_hidden_files
///
/// Get value of `show_hidden_files`
pub fn get_show_hidden_files(&self) -> bool {
self.config.user_interface.show_hidden_files
}
/// ### set_show_hidden_files
///
/// Set new value for `show_hidden_files`
pub fn set_show_hidden_files(&mut self, value: bool) {
self.config.user_interface.show_hidden_files = value;
}
/// ### get_check_for_updates
///
/// Get value of `check_for_updates`
pub fn get_check_for_updates(&self) -> bool {
self.config.user_interface.check_for_updates.unwrap_or(true)
}
/// ### set_check_for_updates
///
/// Set new value for `check_for_updates`
pub fn set_check_for_updates(&mut self, value: bool) {
self.config.user_interface.check_for_updates = Some(value);
}
/// ### get_group_dirs
///
/// Get value of `prompt_on_file_replace`
pub fn get_prompt_on_file_replace(&self) -> bool {
self.config
.user_interface
.prompt_on_file_replace
.unwrap_or(true)
}
/// Set new value for `prompt_on_file_replace`
pub fn set_prompt_on_file_replace(&mut self, value: bool) {
self.config.user_interface.prompt_on_file_replace = Some(value);
}
/// Get GroupDirs value from configuration (will be converted from string)
pub fn get_group_dirs(&self) -> Option<GroupDirs> {
// Convert string to `GroupDirs`
@@ -179,23 +161,17 @@ impl ConfigClient {
}
}
/// ### set_group_dirs
///
/// Set value for group_dir in configuration.
/// Provided value, if `Some` will be converted to `GroupDirs`
pub fn set_group_dirs(&mut self, val: Option<GroupDirs>) {
self.config.user_interface.group_dirs = val.map(|val| val.to_string());
}
/// ### get_local_file_fmt
///
/// Get current file fmt for local host
pub fn get_local_file_fmt(&self) -> Option<String> {
self.config.user_interface.file_fmt.clone()
}
/// ### set_local_file_fmt
///
/// Set file fmt parameter for local host
pub fn set_local_file_fmt(&mut self, s: String) {
self.config.user_interface.file_fmt = match s.is_empty() {
@@ -204,15 +180,11 @@ impl ConfigClient {
};
}
/// ### get_remote_file_fmt
///
/// Get current file fmt for remote host
pub fn get_remote_file_fmt(&self) -> Option<String> {
self.config.user_interface.remote_file_fmt.clone()
}
/// ### set_remote_file_fmt
///
/// Set file fmt parameter for remote host
pub fn set_remote_file_fmt(&mut self, s: String) {
self.config.user_interface.remote_file_fmt = match s.is_empty() {
@@ -221,10 +193,43 @@ impl ConfigClient {
};
}
/// Get value of `notifications`
pub fn get_notifications(&self) -> bool {
self.config.user_interface.notifications.unwrap_or(true)
}
/// Set new value for `notifications`
pub fn set_notifications(&mut self, value: bool) {
self.config.user_interface.notifications = Some(value);
}
/// Get value of `notification_threshold`
pub fn get_notification_threshold(&self) -> u64 {
self.config
.user_interface
.notification_threshold
.unwrap_or(DEFAULT_NOTIFICATION_TRANSFER_THRESHOLD)
}
/// Set new value for `notification_threshold`
pub fn set_notification_threshold(&mut self, value: u64) {
self.config.user_interface.notification_threshold = Some(value);
}
// Remote params
/// Get ssh config path
pub fn get_ssh_config(&self) -> Option<&str> {
self.config.remote.ssh_config.as_deref()
}
/// Set ssh config path
pub fn set_ssh_config(&mut self, p: Option<String>) {
self.config.remote.ssh_config = p;
}
// SSH Keys
/// ### save_ssh_key
///
/// Save a SSH key into configuration.
/// This operation also creates the key file in `ssh_key_dir`
/// and also commits changes to configuration, to prevent incoerent data
@@ -234,6 +239,12 @@ impl ConfigClient {
username: &str,
ssh_key: &str,
) -> Result<(), SerializerError> {
if self.degraded {
return Err(SerializerError::new_ex(
SerializerErrorKind::Generic,
String::from("Configuration won't be saved, since in degraded mode"),
));
}
let host_name: String = Self::make_ssh_host_key(host, username);
// Get key path
let ssh_key_path: PathBuf = {
@@ -261,12 +272,16 @@ impl ConfigClient {
self.write_config()
}
/// ### del_ssh_key
///
/// Delete a ssh key from configuration, using host as key.
/// This operation also unlinks the key file in `ssh_key_dir`
/// and also commits changes to configuration, to prevent incoerent data
pub fn del_ssh_key(&mut self, host: &str, username: &str) -> Result<(), SerializerError> {
if self.degraded {
return Err(SerializerError::new_ex(
SerializerErrorKind::Generic,
String::from("Configuration won't be saved, since in degraded mode"),
));
}
// Remove key from configuration and get key path
info!("Removing key for {}@{}", host, username);
let key_path: PathBuf = match self
@@ -287,12 +302,13 @@ impl ConfigClient {
self.write_config()
}
/// ### get_ssh_key
///
/// Get ssh key from host.
/// None is returned if key doesn't exist
/// `std::io::Error` is returned in case it was not possible to read the key file
pub fn get_ssh_key(&self, mkey: &str) -> std::io::Result<Option<SshHost>> {
if self.degraded {
return Ok(None);
}
// Check if Key exists
match self.config.remote.ssh_keys.get(mkey) {
None => Ok(None),
@@ -305,8 +321,6 @@ impl ConfigClient {
}
}
/// ### iter_ssh_keys
///
/// Get an iterator through hosts in the ssh key storage
pub fn iter_ssh_keys(&self) -> impl Iterator<Item = &String> + '_ {
Box::new(self.config.remote.ssh_keys.keys())
@@ -314,10 +328,14 @@ impl ConfigClient {
// I/O
/// ### write_config
///
/// Write configuration to file
pub fn write_config(&self) -> Result<(), SerializerError> {
if self.degraded {
return Err(SerializerError::new_ex(
SerializerErrorKind::Generic,
String::from("Configuration won't be saved, since in degraded mode"),
));
}
// Open file
match OpenOptions::new()
.create(true)
@@ -325,24 +343,25 @@ impl ConfigClient {
.truncate(true)
.open(self.config_path.as_path())
{
Ok(writer) => {
let serializer: ConfigSerializer = ConfigSerializer {};
serializer.serialize(Box::new(writer), &self.config)
}
Ok(writer) => serialize(&self.config, Box::new(writer)),
Err(err) => {
error!("Failed to write configuration file: {}", err);
Err(SerializerError::new_ex(
SerializerErrorKind::IoError,
SerializerErrorKind::Io,
err.to_string(),
))
}
}
}
/// ### read_config
///
/// Read configuration from file (or reload it if already read)
pub fn read_config(&mut self) -> Result<(), SerializerError> {
if self.degraded {
return Err(SerializerError::new_ex(
SerializerErrorKind::Generic,
String::from("Configuration won't be loaded, since in degraded mode"),
));
}
// Open bookmarks file for read
match OpenOptions::new()
.read(true)
@@ -350,8 +369,7 @@ impl ConfigClient {
{
Ok(reader) => {
// Deserialize
let deserializer: ConfigSerializer = ConfigSerializer {};
match deserializer.deserialize(Box::new(reader)) {
match deserialize(Box::new(reader)) {
Ok(config) => {
self.config = config;
Ok(())
@@ -362,38 +380,32 @@ impl ConfigClient {
Err(err) => {
error!("Failed to read configuration: {}", err);
Err(SerializerError::new_ex(
SerializerErrorKind::IoError,
SerializerErrorKind::Io,
err.to_string(),
))
}
}
}
/// ### make_ssh_host_key
///
/// Hosts are saved as `username@host` into configuration.
/// This method creates the key name, starting from host and username
fn make_ssh_host_key(host: &str, username: &str) -> String {
format!("{}@{}", username, host)
}
/// ### get_ssh_tokens
///
/// Get ssh tokens starting from ssh host key
/// Panics if key has invalid syntax
/// Returns: (host, username)
fn get_ssh_tokens(host_key: &str) -> (String, String) {
let tokens: Vec<&str> = host_key.split('@').collect();
assert_eq!(tokens.len(), 2);
assert!(tokens.len() >= 2);
(String::from(tokens[1]), String::from(tokens[0]))
}
/// ### make_io_err
///
/// Make serializer error from `std::io::Error`
fn make_io_err(err: std::io::Error) -> Result<(), SerializerError> {
Err(SerializerError::new_ex(
SerializerErrorKind::IoError,
SerializerErrorKind::Io,
err.to_string(),
))
}
@@ -419,6 +431,7 @@ mod tests {
.unwrap();
// Verify parameters
let default_config: UserConfig = UserConfig::default();
assert_eq!(client.degraded, false);
assert_eq!(client.config.remote.ssh_keys.len(), 0);
assert_eq!(
client.config.user_interface.default_protocol,
@@ -432,6 +445,20 @@ mod tests {
assert_eq!(client.ssh_key_dir, ssh_keys_path);
}
#[test]
fn test_system_config_degraded() {
let mut client: ConfigClient = ConfigClient::degraded();
assert_eq!(client.degraded, true);
assert_eq!(client.config_path, PathBuf::default());
assert_eq!(client.ssh_key_dir, PathBuf::default());
// I/O
assert!(client.add_ssh_key("Omar", "omar", "omar").is_err());
assert!(client.del_ssh_key("omar", "omar").is_err());
assert!(client.get_ssh_key("omar").ok().unwrap().is_none());
assert!(client.write_config().is_err());
assert!(client.read_config().is_err());
}
#[test]
fn test_system_config_new_err() {
assert!(
@@ -526,6 +553,20 @@ mod tests {
assert_eq!(client.get_check_for_updates(), false);
}
#[test]
fn test_system_config_prompt_on_file_replace() {
let tmp_dir: TempDir = TempDir::new().ok().unwrap();
let (cfg_path, key_path): (PathBuf, PathBuf) = get_paths(tmp_dir.path());
let mut client: ConfigClient = ConfigClient::new(cfg_path.as_path(), key_path.as_path())
.ok()
.unwrap();
assert_eq!(client.get_prompt_on_file_replace(), true); // Null ?
client.set_prompt_on_file_replace(true);
assert_eq!(client.get_prompt_on_file_replace(), true);
client.set_prompt_on_file_replace(false);
assert_eq!(client.get_prompt_on_file_replace(), false);
}
#[test]
fn test_system_config_group_dirs() {
let tmp_dir: TempDir = TempDir::new().ok().unwrap();
@@ -572,6 +613,51 @@ mod tests {
assert_eq!(client.get_remote_file_fmt(), None);
}
#[test]
fn test_system_config_notifications() {
let tmp_dir: TempDir = TempDir::new().ok().unwrap();
let (cfg_path, key_path): (PathBuf, PathBuf) = get_paths(tmp_dir.path());
let mut client: ConfigClient = ConfigClient::new(cfg_path.as_path(), key_path.as_path())
.ok()
.unwrap();
assert_eq!(client.get_notifications(), true); // Null ?
client.set_notifications(true);
assert_eq!(client.get_notifications(), true);
client.set_notifications(false);
assert_eq!(client.get_notifications(), false);
}
#[test]
fn test_system_config_remote_notification_threshold() {
let tmp_dir: TempDir = TempDir::new().ok().unwrap();
let (cfg_path, key_path): (PathBuf, PathBuf) = get_paths(tmp_dir.path());
let mut client: ConfigClient = ConfigClient::new(cfg_path.as_path(), key_path.as_path())
.ok()
.unwrap();
assert_eq!(
client.get_notification_threshold(),
DEFAULT_NOTIFICATION_TRANSFER_THRESHOLD
); // Null ?
client.set_notification_threshold(1024);
assert_eq!(client.get_notification_threshold(), 1024);
client.set_notification_threshold(64);
assert_eq!(client.get_notification_threshold(), 64);
}
#[test]
fn test_system_config_remote_ssh_config() {
let tmp_dir: TempDir = TempDir::new().ok().unwrap();
let (cfg_path, key_path): (PathBuf, PathBuf) = get_paths(tmp_dir.path());
let mut client: ConfigClient = ConfigClient::new(cfg_path.as_path(), key_path.as_path())
.ok()
.unwrap();
assert_eq!(client.get_ssh_config(), None); // Null ?
client.set_ssh_config(Some(String::from("/tmp/ssh_config")));
assert_eq!(client.get_ssh_config(), Some("/tmp/ssh_config"));
client.set_ssh_config(None);
assert_eq!(client.get_ssh_config(), None);
}
#[test]
fn test_system_config_ssh_keys() {
let tmp_dir: TempDir = TempDir::new().ok().unwrap();
@@ -627,8 +713,6 @@ mod tests {
assert_eq!(err.to_string(), "IO error (permission denied)");
}
/// ### get_paths
///
/// Get paths for configuration and keys directory
fn get_paths(dir: &Path) -> (PathBuf, PathBuf) {
let mut k: PathBuf = PathBuf::from(dir);

View File

@@ -2,32 +2,6 @@
//!
//! `environment` is the module which provides Path and values for the system environment
/**
* MIT License
*
* termscp - Copyright (c) 2021 Christian Visintin
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// Deps
extern crate dirs;
// Ext
use std::path::{Path, PathBuf};
@@ -96,16 +70,29 @@ pub fn get_log_paths(config_dir: &Path) -> PathBuf {
log_file
}
/// ### get_theme_path
///
/// Get paths for theme provider
/// Returns: path of theme.toml
pub fn get_theme_path(config_dir: &Path) -> PathBuf {
// Prepare paths
let mut theme_file: PathBuf = PathBuf::from(config_dir);
theme_file.push("theme.toml");
theme_file
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
use serial_test::serial;
use std::fs::{File, OpenOptions};
use std::io::Write;
#[test]
#[serial]
fn test_system_environment_get_config_dir() {
// Create and get conf_dir
let conf_dir: PathBuf = init_config_dir().ok().unwrap().unwrap();
@@ -114,6 +101,7 @@ mod tests {
}
#[test]
#[serial]
fn test_system_environment_get_config_dir_err() {
let mut conf_dir: PathBuf = std::env::temp_dir();
conf_dir.push("termscp");
@@ -135,6 +123,7 @@ mod tests {
}
#[test]
#[serial]
fn test_system_environment_get_bookmarks_paths() {
assert_eq!(
get_bookmarks_paths(&Path::new("/home/omar/.config/termscp/")),
@@ -143,6 +132,7 @@ mod tests {
}
#[test]
#[serial]
fn test_system_environment_get_config_paths() {
assert_eq!(
get_config_paths(&Path::new("/home/omar/.config/termscp/")),
@@ -154,10 +144,20 @@ mod tests {
}
#[test]
#[serial]
fn test_system_environment_get_log_paths() {
assert_eq!(
get_log_paths(&Path::new("/home/omar/.config/termscp/")),
PathBuf::from("/home/omar/.config/termscp/termscp.log"),
);
}
#[test]
#[serial]
fn test_system_environment_get_theme_path() {
assert_eq!(
get_theme_path(&Path::new("/home/omar/.config/termscp/")),
PathBuf::from("/home/omar/.config/termscp/theme.toml"),
);
}
}

View File

@@ -2,29 +2,6 @@
//!
//! `filestorage` provides an implementation of the `KeyStorage` trait using a file
/**
* MIT License
*
* termscp - Copyright (c) 2021 Christian Visintin
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// Local
use super::{KeyStorage, KeyStorageError};
// Ext
@@ -32,16 +9,12 @@ use std::fs::{OpenOptions, Permissions};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
/// ## FileStorage
///
/// File storage is an implementation o the `KeyStorage` which uses a file to store the key
pub struct FileStorage {
dir_path: PathBuf,
}
impl FileStorage {
/// ### new
///
/// Instantiates a new `FileStorage`
pub fn new(dir_path: &Path) -> Self {
FileStorage {
@@ -49,8 +22,6 @@ impl FileStorage {
}
}
/// ### make_file_path
///
/// Make file path for key file from `dir_path` and the application id
fn make_file_path(&self, storage_id: &str) -> PathBuf {
let mut p: PathBuf = self.dir_path.clone();
@@ -61,8 +32,6 @@ impl FileStorage {
}
impl KeyStorage for FileStorage {
/// ### get_key
///
/// Retrieve key from the key storage.
/// The key might be acccess through an identifier, which identifies
/// the key in the storage
@@ -85,8 +54,6 @@ impl KeyStorage for FileStorage {
}
}
/// ### set_key
///
/// Set the key into the key storage
fn set_key(&self, storage_id: &str, key: &str) -> Result<(), KeyStorageError> {
let key_file: PathBuf = self.make_file_path(storage_id);

View File

@@ -2,47 +2,17 @@
//!
//! `keyringstorage` provides an implementation of the `KeyStorage` trait using the OS keyring
/**
* MIT License
*
* termscp - Copyright (c) 2021 Christian Visintin
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// Deps
extern crate keyring;
// Local
use super::{KeyStorage, KeyStorageError};
// Ext
use keyring::{Keyring, KeyringError};
use keyring::{Entry as Keyring, Error as KeyringError};
/// ## KeyringStorage
///
/// provides a `KeyStorage` implementation using the keyring crate
pub struct KeyringStorage {
username: String,
}
#[cfg(not(tarpaulin_include))]
impl KeyringStorage {
/// ### new
///
/// Instantiates a new KeyringStorage
pub fn new(username: &str) -> Self {
KeyringStorage {
@@ -51,10 +21,7 @@ impl KeyringStorage {
}
}
#[cfg(not(tarpaulin_include))]
impl KeyStorage for KeyringStorage {
/// ### get_key
///
/// Retrieve key from the key storage.
/// The key might be acccess through an identifier, which identifies
/// the key in the storage
@@ -63,18 +30,17 @@ impl KeyStorage for KeyringStorage {
match storage.get_password() {
Ok(s) => Ok(s),
Err(e) => match e {
KeyringError::NoPasswordFound => Err(KeyStorageError::NoSuchKey),
#[cfg(target_os = "windows")]
KeyringError::WindowsVaultError => Err(KeyStorageError::NoSuchKey),
#[cfg(target_os = "macos")]
KeyringError::MacOsKeychainError(_) => Err(KeyStorageError::NoSuchKey),
_ => panic!("{}", e),
KeyringError::NoEntry => Err(KeyStorageError::NoSuchKey),
KeyringError::PlatformFailure(_)
| KeyringError::NoStorageAccess(_)
| KeyringError::WrongCredentialPlatform => Err(KeyStorageError::ProviderError),
KeyringError::BadEncoding(_) | KeyringError::TooLong(_, _) => {
Err(KeyStorageError::BadSytax)
}
},
}
}
/// ### set_key
///
/// Set the key into the key storage
fn set_key(&self, storage_id: &str, key: &str) -> Result<(), KeyStorageError> {
let storage: Keyring = Keyring::new(storage_id, self.username.as_str());
@@ -93,15 +59,14 @@ impl KeyStorage for KeyringStorage {
// Check what kind of error is returned
match storage.get_password() {
Ok(_) => true,
Err(err) => !matches!(err, KeyringError::NoBackendFound),
Err(KeyringError::NoStorageAccess(_) | KeyringError::PlatformFailure(_)) => false,
Err(_) => true,
}
}
}
#[cfg(test)]
mod tests {
extern crate whoami;
use super::*;
use pretty_assertions::assert_eq;

View File

@@ -2,68 +2,32 @@
//!
//! `keystorage` provides the trait to manipulate to a KeyStorage
/**
* MIT License
*
* termscp - Copyright (c) 2021 Christian Visintin
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// Storages
pub mod filestorage;
#[cfg(any(target_os = "windows", target_os = "macos"))]
#[cfg(feature = "with-keyring")]
pub mod keyringstorage;
// ext
use thiserror::Error;
/// ## KeyStorageError
///
/// defines the error type for the `KeyStorage`
#[derive(PartialEq, std::fmt::Debug)]
#[derive(Debug, Error, PartialEq)]
pub enum KeyStorageError {
//BadKey,
#[cfg(feature = "with-keyring")]
#[error("Key has a bad syntax")]
BadSytax,
#[error("Provider service error")]
ProviderError,
#[error("No such key")]
NoSuchKey,
}
impl std::fmt::Display for KeyStorageError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let err: String = String::from(match &self {
//KeyStorageError::BadKey => "Bad key syntax",
KeyStorageError::ProviderError => "Provider service error",
KeyStorageError::NoSuchKey => "No such key",
});
write!(f, "{}", err)
}
}
/// ## KeyStorage
///
/// this traits provides the methods to communicate and interact with the key storage.
pub trait KeyStorage {
/// ### get_key
///
/// Retrieve key from the key storage.
/// The key might be acccess through an identifier, which identifies
/// the key in the storage
fn get_key(&self, storage_id: &str) -> Result<String, KeyStorageError>;
/// ### set_key
///
/// Set the key into the key storage
fn set_key(&self, storage_id: &str, key: &str) -> Result<(), KeyStorageError>;
@@ -82,12 +46,17 @@ mod tests {
#[test]
fn test_system_keys_mod_errors() {
#[cfg(feature = "with-keyring")]
assert_eq!(
format!("{}", KeyStorageError::ProviderError),
KeyStorageError::BadSytax.to_string(),
String::from("Key has a bad syntax")
);
assert_eq!(
KeyStorageError::ProviderError.to_string(),
String::from("Provider service error")
);
assert_eq!(
format!("{}", KeyStorageError::NoSuchKey),
KeyStorageError::NoSuchKey.to_string(),
String::from("No such key")
);
}

View File

@@ -2,41 +2,19 @@
//!
//! `logging` is the module which initializes the logging system for termscp
/**
* MIT License
*
* termscp - Copyright (c) 2021 Christian Visintin
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// locals
use crate::system::environment::{get_log_paths, init_config_dir};
use crate::utils::file::open_file;
// ext
use simplelog::{ConfigBuilder, LevelFilter, WriteLogger};
pub use simplelog::LevelFilter as LogLevel;
use simplelog::{ConfigBuilder, WriteLogger};
use std::fs::File;
use std::path::PathBuf;
/// ### init
///
/// Initialize logger
pub fn init() -> Result<(), String> {
pub fn init(level: LogLevel) -> Result<(), String> {
// Init config dir
let config_dir: PathBuf = match init_config_dir() {
Ok(Some(p)) => p,
@@ -52,11 +30,9 @@ pub fn init() -> Result<(), String> {
let file: File = open_file(log_file_path.as_path(), true, true, false)
.map_err(|e| format!("Failed to open file {}: {}", log_file_path.display(), e))?;
// Prepare log config
let config = ConfigBuilder::new()
.set_time_format_str("%Y-%m-%dT%H:%M:%S%z")
.build();
let config = ConfigBuilder::new().set_time_format_rfc3339().build();
// Make logger
WriteLogger::init(LevelFilter::Trace, config, file)
WriteLogger::init(level, config, file)
.map_err(|e| format!("Failed to initialize logger: {}", e))
}
@@ -67,6 +43,6 @@ mod test {
#[test]
fn test_system_logging_setup() {
assert!(init().is_ok());
assert!(init(LogLevel::Trace).is_ok());
}
}

View File

@@ -2,33 +2,14 @@
//!
//! `system` is the module which contains functions and data types related to current system
/**
* MIT License
*
* termscp - Copyright (c) 2021 Christian Visintin
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// modules
pub mod auto_update;
pub mod bookmarks_client;
pub mod config_client;
pub mod environment;
pub(crate) mod keys;
pub(self) mod keys;
pub mod logging;
pub mod notifications;
pub mod sshkey_storage;
pub mod theme_provider;
pub mod watcher;

View File

@@ -0,0 +1,68 @@
//! # Notifications
//!
//! This module exposes the function to send notifications to the guest OS
#[cfg(all(unix, not(target_os = "macos")))]
use notify_rust::Hint;
use notify_rust::{Notification as OsNotification, Timeout};
/// A notification helper which provides all the functions to send the available notifications for termscp
pub struct Notification;
impl Notification {
/// Notify a transfer has been completed with success
pub fn transfer_completed<S: AsRef<str>>(body: S) {
Self::notify(
"Transfer completed ✅",
body.as_ref(),
Some("transfer.complete"),
);
}
/// Notify a transfer has failed
pub fn transfer_error<S: AsRef<str>>(body: S) {
Self::notify("Transfer failed ❌", body.as_ref(), Some("transfer.error"));
}
/// Notify a new version of termscp is available for download
pub fn update_available<S: AsRef<str>>(version: S) {
Self::notify(
"New version available ⬇️",
format!("termscp {} is now available for download", version.as_ref()).as_str(),
None,
);
}
/// Notify the update has been correctly installed
pub fn update_installed<S: AsRef<str>>(version: S) {
Self::notify(
"Update installed 🎉",
format!("termscp {} has been installed! Restart termscp to enjoy the latest version of termscp 🙂", version.as_ref()).as_str(),
None,
);
}
/// Notify the update installation has failed
pub fn update_failed<S: AsRef<str>>(err: S) {
Self::notify("Update installation failed ❌", err.as_ref(), None);
}
/// Notify guest OS with provided Summary, body and optional category
/// e.g. Category is supported on FreeBSD/Linux only
#[allow(unused_variables)]
fn notify(summary: &str, body: &str, category: Option<&str>) {
let mut notification = OsNotification::new();
// Set common params
notification
.appname(env!("CARGO_PKG_NAME"))
.summary(summary)
.body(body)
.timeout(Timeout::Milliseconds(10000));
// Set category if any
#[cfg(all(unix, not(target_os = "macos")))]
if let Some(category) = category {
notification.hint(Hint::Category(category.to_string()));
}
let _ = notification.show();
}
}

Some files were not shown because too many files have changed in this diff Show More