Rust: Filesystems and Command-Line Tools

Rust has found a significant niche in the world of command-line tools.

Rust已经在命令行工具的世界中找到了一个重要的位置。

As a modern, safe, and fast systems programming language, it gives programmers a toolbox they can use to assemble slick command-line interfaces that replicate or extend the functionality of existing tools.

作为一种现代、安全和快速的系统编程语言,它为程序员提供了一个工具箱,他们可以使用它来组装精美的命令行界面,这些界面可以复制或扩展现有工具的功能。

For instance, the bat command provides a syntax- highlighting-aware cat alternative with built-in support for paging tools, and hyperfine can automatically benchmark anything that can be run with a command or pipeline.

例如,bat命令提供了一个支持语法高亮显示的cat替代方案,它内置了对分页工具的支持,而且hyperfine可以自动对任何可以通过命令或管道运行的东西进行基准测试。

rust 复制代码
cargo new quickreplace
	Created binary (application) `quickreplace` package
cd quickreplace

For our program, we'll need two other crates: text- colorizer for creating colorful output in the terminal and regex for the actual search-and-replace functionality.

对于我们的程序,我们还需要另外两个crate:用于在终端中创建彩色输出的text- colorizer和用于实际搜索和替换功能的regex。

rust 复制代码
[package]
 name = "quickreplace"
 version = "0.1.0"
 authors = ["You <you@example.com>"]
 edition = "2024"
 # See more keys and their definitions at
 # https://doc.rust-lang.org/cargo/reference/manifest.html
 [dependencies]
 text-colorizer = "1"
 regex = "1"

The Command-Line Interface

It takes four arguments: a string (or regular expression) to search for, a string (or regular expression) to replace it with, the name of an input file, and the name of an output file.

We'll start off our main.rs file with a struct containing these arguments:

rust 复制代码
#[derive(Debug)]
struct Arguments { target: String,
      replacement: String,
      filename: String,
      output: String,
}

The #[derive(Debug)] attribute tells the compiler to generate some extra code that allows us to format the Arguments struct with {:?} in println!.

#[派生(调试)]属性告诉编译器生成一些额外的代码,这些代码允许我们在println!中使用{:?}!

rust 复制代码
use text_colorizer::*;
fn print_usage() {
	eprintln!("{} - change occurrences of one string into another","quickreplace".green());
    eprintln!("Usage: quickreplace <target> <replacement> <INPUT> <OUTPUT>");
  }

Now we can collect and process the program's arguments:

现在我们可以收集和处理程序的参数了:

rust 复制代码
use std::env;
fn parse_args() -> Arguments {
	let args: Vec<String> = env::args().skip(1).collect();
	if args.len() != 4 { print_usage();
	          eprintln!("{} wrong number of arguments: expected 4, got
	  {}.",
	              "Error:".red().bold(), args.len());
	          std::process::exit(1);
	}
	Arguments {
	target: args[0].clone(), replacement: args[1].clone(), filename: args[2].clone(), output: args[3].clone()
} }

.skip(1) skips the iterator's first value (the name of the program being run) so that the result has only the command-line arguments.

.skip(1)跳过迭代器的第一个值(正在运行的程序的名称),因此结果只有命令行参数。

The collect() method produces a Vec of arguments.

collect()方法产生一个参数集合。

We again colorize part of the message and use .bold() to make the text heavier, as well.

我们再次为部分消息上色,并使用.bold()使文本变粗。

If the right number of arguments is present, we putt them in an Arguments struct, and return it.

如果存在正确数量的参数,则将它们放入arguments结构体中,并返回它。

rust 复制代码
fn main() {
	let args = parse_args(); println!("{:?}", args);
}
rust 复制代码
cargo run
Updating crates.io index
  Compiling libc v0.2.82
  Compiling lazy_static v1.4.0
  Compiling memchr v2.3.4
  Compiling regex-syntax v0.6.22
  Compiling thread_local v1.1.0
  Compiling aho-corasick v0.7.15
  Compiling atty v0.2.14
  Compiling text-colorizer v1.0.0
  Compiling regex v1.4.3
  Compiling quickreplace v0.1.0 (/home/jimb/quickreplace)
  Finished dev [unoptimized + debuginfo] target(s) in 6.98s
  Running `target/debug/quickreplace`
  quickreplace - change occurrences of one string into another
  Usage: quickreplace <target> <replacement> <INPUT> <OUTPUT>
  Error: wrong number of arguments: expected 4, got 0

If you give the program some arguments, it will instead print out a representation of the Arguments struct:

如果你给程序一些参数,它会打印出arguments结构体的表示形式:

rust 复制代码
cargo run "find" "replace" file output
Finished dev [unoptimized + debuginfo] target(s) in 0.01s
       Running `target/debug/quickreplace find replace file output`
  Arguments { target: "find", replacement: "replace", filename:
  "file", output: "output" }
相关推荐
架构精进之路9 分钟前
多智能体系统不是银弹
后端·架构·aigc
枯萎穿心攻击24 分钟前
从 Unity UGUI 到 Unreal UMG 的交互与高效实践:UI 事件、坐标系适配与性能优化
开发语言·ui·unity·性能优化·ue5·游戏引擎·虚幻引擎
WALL-EC32 分钟前
Qt工具栏中图标槽函数没有响应的问题分析
开发语言·qt·osgearth
涡能增压发动积1 小时前
MySQL数据库为何逐渐黯淡,PostgreSQL为何能新王登基
人工智能·后端
架构精进之路1 小时前
多智能体系统架构解析
后端·架构·ai编程
Java中文社群1 小时前
重磅!Ollama发布UI界面,告别命令窗口!
java·人工智能·后端
熙客1 小时前
Java:HashMap的使用
java·开发语言
程序员清风1 小时前
程序员代码有Bug别怕,人生亦是如此!
java·后端·面试
咸甜适中2 小时前
rust语言 (1.88) egui (0.32.1) 学习笔记(逐行注释)(十五)网格布局
笔记·学习·rust·egui
就是帅我不改2 小时前
告别996!高可用低耦合架构揭秘:SpringBoot + RabbitMQ 让订单系统不再崩
java·后端·面试