golang cli
With the capability to build lightweight yet efficient system, Golang has been getting a lot of attention from software engineers who use it to build backend services, microservices etc as well as DevOps engineers who use it as scripting language. FYI, Kubernetes is written in Go as well.
具有构建轻便高效系统的功能,Golang受到了使用它构建后端服务,微服务等的软件工程师以及将其用作脚本语言的DevOps工程师的广泛关注。 仅供参考,Kubernetes也是用Go编写的。
In this article, we will be looking at how to build a CLI-based tool to rename files in batch using spf13/cobra. While there are other libraries that can be used to build CLI application, Cobra offers the usage of flags, arguments validation, auto-generated help command, suggestion when there is typo and many more.
在本文中,我们将研究如何构建基于CLI的工具,以使用spf13 / cobra批量重命名文件。 虽然还有其他库可用于构建CLI应用程序,但Cobra会提供标志的用法,参数验证,自动生成的帮助命令,出现错别字时的建议等。
Let’s get start on building our file renaming tool. Before diving into the code, let’s lay out the requirements:
让我们开始构建文件重命名工具。 在深入研究代码之前,让我们对需求进行布局:
- Ability to specify the target folder 能够指定目标文件夹
- Ability to scan all files in subfolders能够扫描子文件夹中的所有文件
- Ability to include or exclude files based on name or extension能够根据名称或扩展名包含或排除文件
根命令(Root command)
First, we start by defining a root command which will be called in the main.go
. Also, we can create a folder called cmd
where we can store all the command files.
首先,我们先定义一个root命令,该命令将在main.go
。 另外,我们可以创建一个名为cmd
的文件夹,在其中可以存储所有命令文件。
To execute the root command from main.go, we can add the following line in the main()
function:
要从main.go执行root命令,我们可以在main()
函数中添加以下行: