Hello!
I am on my first day with rust, coming from things as far back as Commodore BASIC, but mostly C#.
I wrote something that I think is very handy for Windows and WSL. I wrote a blog post about it here, but the code changes often and I don't update the blog.
I could ask several specific questions, but I was hoping that someone familiar with rust could look at this from a higher level and see what patterns I'm missing, what conventions I'm not following, what I'm misunderstanding, what I'm doing wrong, and so forth, and then afterwards I could ask the specific questions.
Is this a good place for such a discussion? If anyone is interested, thanks in advance! Please be brutal; if I should not be programming in rust, then I should not be programming in rust.
use std::env;
use std::process::Command;
//TODO: command line parameters: don't show command, show but don't invoke, etc.
fn main()
{
// command line arguments
let args: Vec<String> = env::args().collect();
match env::var("WSL_DISTRO_NAME") {
Ok(_e) => {},
Err(_e) => {
if cfg!(target_os = "windows") {} else {
println!("");
println!("{0} : ", args[0]);
println!("Define WSL_DISTRO_NAME environment variable to override.");
println!("");
help("Runs only under Windows and Windows Subsystem for Linux (WSL). Define WSL_DISTRO_NAME environment variable to override.", args);
std::process::exit(0);
}
},
}
// first command line argument
let mut first = String::from("");
if args.len() > 1
{
first += &args[1].to_lowercase();
}
if first == ""
|| first == "help"
|| first == "-help"
|| first == "-h"
|| first == "--h"
|| first == "/h"
|| first == "-?"
|| first == "--?"
|| first == "/?" {
help("Help requested or no command specified", args);
std::process::exit(0);
}
// WINDOWS command line to invoke - start in background
let mut cmd = String::from("").to_owned();
// first command line argument indicates command to invoke; copy its characters
let compare: &str = &first[..first.len()];
// switch on that first command line argument
//TODO: configuration file
match compare {
// for testing an error condition
"fail" => cmd += "donotwork",
"raw" => cmd += "start /b",
// common windows applications
"exp" => cmd += "explorer.exe", // file system explorer and general launcher
"rd" => cmd += "mstsc.exe", // remote desktop client
"edge" => cmd += "C:/progra~2/Microsoft/Edge/Application/msedge.exe --inprivate --ash-force-desktop --disable-background-mode --disable-preconnect --new-window --dns-prefetch-disable --no-pings --process-per-tab --no-referrers --start-maximized",
"trackme" => cmd += "C:/progra~2/Microsoft/Edge/Application/msedge.exe --ash-force-desktop --disable-background-mode --disable-preconnect --new-window --dns-prefetch-disable --no-pings --process-per-tab --no-referrers --start-maximized",
"mp" => cmd += "C:/progra~2/window~4/wmplayer.exe /prefetch:1",
//TODO: acess environment variables for paths??
// progra~2 is not consistent, but Program Files (x86) causes problems due to parenthesis
"vs" => cmd += "c:/PROGRA~2/Microsoft Visual Studio/2019/Community/Common7/IDEdevenv.exe",
// just type code in cmd.exe or bash.exe, not wince code.
"code" => cmd += "C:/Users/ms/AppData/Local/Programs/Microsoft VS Code/Code.exe",
"rider" => cmd += "C:/Program Files/JetBrains/JetBrains Rider 2021.1.2/bin/rider64.exe",
"flp" => cmd += "C:/Program Files/Mythicsoft/FileLocator Pro/FileLocatorPro.exe",
"winmerge" => cmd += "C:/Progra~2/WinMerge/WinMergeU.exe",
"tb" => cmd += "C:/Progra~2/Mozilla Thunderbird/thunderbird.exe",
"excel" => cmd += "C:/Program Files/Microsoft Office/root/Office16/EXCEL.EXE",
"winword" => cmd += "C:/Program Files/Microsoft Office/root/Office16/WINWORD.EXE",
"outlook" => cmd += "C:/Program Files/Microsoft Office/root/Office16/OUTLOOK.EXE",
"ppt" => cmd += "C:/Program Files/Microsoft Office/root/Office16/POWERPNT.EXE",
"sub" => cmd += "C:/progra~1/Sublime Text 3/sublime_text.exe",
// https://live.sysinternals.com/ https://docs.microsoft.com/en-us/sysinternals/
"bginfo" => cmd += "start /b \\\\live.sysinternals.com\\tools\\bginfo64.exe -accepteula",
"handle" => cmd += "\\\\live.sysinternals.com\\tools\\handle64.exe -accepteula",
"whoson" => cmd += "\\\\live.sysinternals.com\\tools\\PsLoggedon64.exe -accepteula",
"listdlls" => cmd += "\\\\live.sysinternals.com\\tools\\listdlls64.exe -accepteula",
"procexp" => cmd += "\\\\live.sysinternals.com\\tools\\procexp64.exe -accepteula",
"pslist" => cmd += "\\\\live.sysinternals.com\\tools\\pslist64.exe -accepteula",
"pskill" => cmd += "\\\\live.sysinternals.com\\tools\\pskill64.exe -accepteula",
"procmon" => cmd += "\\\\live.sysinternals.com\\tools\\procmon64.exe -accepteula",
"autoruns" => cmd += "\\\\live.sysinternals.com\\tools\\autoruns64.exe -accepteula",
"diskview" => cmd += "\\\\live.sysinternals.com\\tools\\diskview64.exe -accepteula",
"du" => cmd += "\\\\live.sysinternals.com\\tools\\du64.exe -accepteula",
// WSL commands
"path" => cmd += "wslpath.exe -w", // convert WSL path to windows path
// shutdown commands
"hyb" => cmd += "shutdown.exe /h", // hybernate in 30 seconds unless shutdown.exe /a
"down" => cmd += "shutdown.exe /s", // shut down in 30 seconds unless shutdown.exe /a
"boot" => cmd += "shutdown.exe /g", //reboot in 30 seconds unless shutdown.exe /a
"logoff" => cmd += "shutdown.exe /l", // logoff in 30 seconds unless shutdown.exe /a
"firmware" => cmd += "shutdown.exe /r /fw", // reboot to formware in 30 seconds unless shutdown.exe /a
"bootopt" => cmd += "shutdown.exe /r /o", // reboot to boot options in 30 seconds unless shutdown.exe /a
// third-party commands
"stb" => cmd += "nircmd.exe win show class Shell_TrayWnd", // show taskbar (requries nircmd)
"htb" => cmd += "nircmd.exe win hide class Shell_TrayWnd", // hide taskbar (requries nircmd)
// Windows control panels
// https://wslguy.net/2021/01/21/launch-windows-features-from-wsl-shells/
"devman" => cmd += "cmd.exe /c hdwwiz.cpl", // device manager
"inet" => cmd += "cmd.exe /c inetcpl.cpl",
"joy" => cmd += "cmd.exe /c joy.cpl", // game controllers
"sound" => cmd += "cmd.exe /c mmsys.cpl",
"power" => cmd += "cmd.exe /c powercfg.cpl",
"netcon" => cmd += "cmd.exe /c ncpa.cpl", // explorer.exe shell:::{7007ACC7-3202-11D1-AAD2-00805FC1270E}
"sysprop" => cmd += "cmd.exe /c sysdm.cpl",
"loc" => cmd += "cmd.exe /c telephon.cpl",
"dt" => cmd += "cmd.exe /c timedate.cpl",
"secman" => cmd += "cmd.exe /c wscui.cpl", // security and maintenance
"programs" => cmd += "cmd.exe /c appwiz.cpl", //"explorer.exe shell:::{7b81be6a-ce2b-4676-a29e-eb907a5126c5}", // change/remove programs
"firewall" => cmd += "cmd.exe /c firewall.cpl", //"explorer.exe shell:::{4026492F-2F69-46B8-B9BF-5654FC07E423}",
"mouse" => cmd += "cmd.exe /c main.cpl",
// Windows features known by name
// https://www.linkedin.com/pulse/wsl-script-access-windows-functions-code-john-west/
"volume" => cmd += "start /b ms-settings:apps-volume", // volume
"display" => cmd += "start /b ms-settings:display", // desk.cpl
"mouseset" => cmd += "start /b ms-settings:mousetouchpad",
"personal" => cmd += "start /b ms-settings:personalization", //TODO: same as person?
"background" => cmd += "start /b ms-settings:personalization-background",
"colors" => cmd += "start /b ms-settings:personalization-colors",
"lock" => cmd += "start /b ms-settings:lockscreen",
"start" => cmd += "start /b ms-settings:personalization-start", // start menu settings
"startfol" => cmd += "start /b ms-settings:personalization-start-places", // folders on start menu
"taskbar" => cmd += "start /b ms-settings:taskbar",
"allstart" => cmd += "start /b shell:common startup", // all users startup folder
"startup" => cmd += "start /b shell:startup", // current user startup folder
"datetime" => cmd += "start /b ms-settings:dateandtime",
"region" => cmd += "start /b ms-settings:regionformatting", // intl.cpl
"gamebar" => cmd += "start /b ms-settings:gaming-gamebaar",
"pointer" => cmd += "start /b ms-settings:easeofaccess-MousePointer",
"update" => cmd += "start /b ms-settings:windowsupdate-action",
"dev" => cmd += "start /b ms-settings:developers",
"privacy" => cmd += "start /b ms-settings:privacy",
"settings" => cmd += "start /b ms-settings:",
"desktop" => cmd += "start /b shell:Desktop", // shell:::{00021400-0000-0000-C000-000000000046}", // error?
"apps" => cmd += "start /b shell:AppsFolder", // {4234d49b-0245-4df3-b780-3893943456e1}", // all applications
"recyc" => cmd += "start /b shell:RecycleBinFolder",
// Windows features known only by GUID
"admin" => cmd += "start /b shell:::{D20EA4E1-3957-11d2-A40B-0C5020524153}",
"control" => cmd += "start /b shell:::{21EC2020-3AEA-1069-A2DD-08002B30309D}", // control panel small icons
"tasks" => cmd += "start /b shell:::{5ED4F38C-D3FF-4D61-B506-6820320AEBFE}",
"cpcats" => cmd += "start /b shell:::{26EE0668-A00A-44D7-9371-BEB064C98683}", // control panel categories
"defaults" => cmd += "start /b shell:::{17cd9488-1228-4b2f-88ce-4298e93e0966}", // default programs
"printers" => cmd += "start /b shell:::{A8A91A66-3A7D-4424-8D24-04E180695C7A}",
"disp" => cmd += "start /b shell:::{C555438B-3C23-4769-A71F-B6D3D9B6053A}", // error
"email" => cmd += "start /b shell:::{2559a1f5-21d7-11d4-bdaf-00c04f60b9f0}",
"fileopt" => cmd += "start /b shell:::{6DFD7C5C-2451-11d3-A299-00C04F8EF6AF}", // file system explorer options
"onedrive" => cmd += "start /b shell:::{018D5C66-4533-4307-9B53-224DE2ED1FE6}",
"person" => cmd += "start /b shell:::{ED834ED6-4B5A-4bfe-8F11-A626DCB6A921}", // personalization
"remove" => cmd += "start /b shell:::{a6482830-08eb-41e2-84c1-73920c2badb9}", // removable storage devices
"system" => cmd += "start /b shell:::{BB06C0E4-D293-4f75-8A90-CB05B6477EEE}", // system info
"pc" => cmd += "start /b shell:::{20D04FE0-3AEA-1069-A2D8-08002B30309D}", // file explorer exe "This Computer"
"trouble" => cmd += "start /b shell:::{C58C4893-3BE0-4B45-ABB5-A63E4B8C8651}", // Windows troubleshooting Windows? hahahahaha...
"users" => cmd += "start /b shell:::{60632754-c523-4b62-b45c-4172da012619}", // users
"user" => cmd += "start /b shell:::{60632754-c523-4b62-b45c-4172da012619}", // current user
"features" => cmd += "start /b shell:::{67718415-c450-4f3c-bf8a-b487642dc39b}", // Windows features
"mobility" => cmd += "start /b shell:::{5ea4f148-308c-46d7-98a9-49041b1dd468}",
// no match
_ => {
help(&format!("invalid command: {0}", compare), args);
std::process::exit(0);
},
}
if args.len() > 1 {
// append a space before subsequent parameters
for n in 2..args.len() {
cmd += " \"";
cmd += &args[n].to_string();
cmd += "\"";
}
}
run(&cmd);
std::process::exit(0);
}
fn run(command: &str) {
let line = command;//str::replace(command, "'", "\"");
println!("{}", line);
let _output = Command::new("cmd.exe")
.args(&["/c", &line]).spawn();
}
fn help(msg: &str, args: Vec<String>)
{
let text: &'static str =
"fail Test Error devman Device Manager
exp Windows Explorer inet Internet Options
rd Remote Desktop joy Game Controllers
vs Visual Studio sound Sound Options
code Visual Studio Code power Power Options
edge Edge Browser (InPrivate) netcon Network Connections
trackme Edge Browser privacy Privacy Settings
mp Media Player sysprop System Properties
bginfo Background Info loc Localization Options
handle File Handles dt Date & Time Options
whoson Who's Logged On secman Security & Maintenance
listdlls List Assemblies programs Change/Remove Programs
procexp Process Explorer firewall Windows Firewall
pslist Process List mouse Mouse Options
pskill Kill Process volume Volume
procmon Monitor Processes display Display
autoruns Startup Processes mousesset Mouse Settings
diskview Disk Space Viewer personal Personalization
du Disk Usage background Desktop Backgrond
path wslpath -w colors Windows Colors
hyb Hybernate lock Lock Screen Settings
down Shutdown start Start Menu Settings
boot Reboot startfol Start Folders
logoff Log Off taskbar Taskbar Settings
firmware Reboot to Firmware allstart Startup Folder (All)
bootopt Reboot to Options startup Startup Folder (User)
stb Show taskbar start Start Menu Settings
htb Hide taskbar datetime Date/Time
region Region features Add/Remove Windows Features
gamebar Game Bar printers Printers
pointer Mouse Pointer disp Display
update Windows Update email Email Accounts
dev Developer Settings fileopt File Explorer Options
apps All Applications onedrive OneDrive
admin Administrative Tools system System
settings Settings pc This Computer
control Control Panel trouble Troubleshoot Windows
cpcats (Categories) user User Settings
defaults Default Programs users Windows Users
mobility Windows Mobility Center desktop Desktop Folder
recyc Recycle Bin Folder rider JetBrains Rider
flp File Locator Pro winmerge WinMerge
tb Thunderbird excel Microsoft Excel
winword Microsoft Word ppt Microsoft PowerPoint
outlook Microsoft Outlook sub Sublime Text Editor
tasks";
println!("");
println!("{0} : access Windows features : {1}", args[0], msg);
println!("");
println!("{0} : usage :", args[0]);
println!("");
println!("{0} help", args[0]);
println!("{0} <code>", args[0]);
println!("{0} raw <command>", args[0]);
println!("");
println!("{0}", text);
println!("");
}