Skip to content

Commit bc49a71

Browse files
authored
[#cli-package] Added docs for cli package. (#14)
1 parent 6e05fb1 commit bc49a71

File tree

8 files changed

+889
-0
lines changed

8 files changed

+889
-0
lines changed

content/_index.md

+1
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ layout: hextra-home
6969

7070
title="Cli"
7171
subtitle="CLI offers an intuitive API for creating command-line applications, enabling the development of complex command structures with ease. It includes robust argument parsing and validation to ensure accurate and user-friendly command execution."
72+
link="docs/cli"
7273
>}}
7374

7475
{{< hextra/feature-card

content/docs/_index.md

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
---
2+
title: Golly
3+
draft: false
4+
prev: /docs
5+
next: /docs/cli
6+
---
7+
8+
Welcome to **Golly**, a robust collection of enterprise-grade, open-source libraries written in Go (Golang). This project is designed to simplify and enhance the development of modern software systems by providing developers with highly reusable, well-documented utilities tailored to meet enterprise needs. Whether you are building scalable microservices, crafting middleware, or handling complex messaging systems, Golly offers solutions to common programming challenges while adhering to Go’s philosophy of simplicity and performance.
9+
10+
## Background and Motivation
11+
12+
In today's fast-paced development landscape, building scalable and maintainable software requires efficient tools and libraries. Golly was born out of the need for reusable components that tackle common programming tasks with minimal external dependencies, ensuring developers can focus on their core applications without compromising on performance or flexibility.
13+
14+
The project aims to be a **self-contained toolkit**, minimizing the need for additional external libraries while maintaining modularity and flexibility. This approach makes it easier for developers to integrate the libraries into various systems, regardless of their scale or complexity, while ensuring that they can handle high-demand, production-level environments.
15+
16+
## Why Golly?
17+
18+
- **Modular and Lightweight**: Golly is designed with a modular architecture, allowing developers to integrate only the components they need, without unnecessary bloat.
19+
- **Enterprise-Focused**: The libraries in Golly are built with enterprise use cases in mind, ensuring reliability, scalability, and maintainability.
20+
- **Minimal Dependencies**: A key focus of Golly is reducing external dependencies, making it easier to integrate and maintain, while minimizing potential conflicts and complexities during updates or changes.
21+
22+
## Available Packages
23+
24+
Golly contains a rich set of libraries to handle various aspects of development. Here's a breakdown of some core packages available in the Golly repository:
25+
26+
1. **Clients**: A flexible package to manage different types of clients. This module supports various client types like REST and messaging clients, simplifying the integration of external services into your application.
27+
2. **CLI (Command-Line Interface)**: This package provides easy-to-use APIs for building complex command-line applications. It supports argument parsing, validation, and command structuring, making it ideal for automation tasks or command-line tools.
28+
29+
3. **Codec**: A unified interface for encoding and decoding structured data formats such as JSON, XML, and YAML. It simplifies data handling and ensures compatibility with various formats out of the box.
30+
31+
4. **L3 (Logging)**: A lightweight, level-based logging library. L3 supports various logging levels (OFF, ERROR, INFO, DEBUG, TRACE) and allows configuration through files, environment variables, or runtime values. It also provides asynchronous logging support and the ability to specify log levels per package.
32+
33+
5. **Messaging**: A general interface for producing and consuming messages across different messaging platforms, making it ideal for event-driven applications. It supports both local and remote messaging systems.
34+
35+
6. **REST**: A comprehensive HTTP client package, supporting common HTTP methods (GET, POST, PUT, DELETE), query parameters, headers, SSL, TLS, and error handling. This makes it an excellent choice for interacting with APIs or building RESTful services.
36+
37+
7. **SemVer**: A simple API for working with [Semantic Versioning 2.0.0](https://semver.org), providing utilities to parse, compare, and generate semantic versions, supporting pre-releases and build metadata.
38+
39+
8. **Testing/Assertion**: A flexible and extensible assertion library designed to facilitate consistent testing practices in Go projects. It provides a unified interface for asserting conditions in tests.
40+
41+
Each of these packages comes with extensive documentation and usage examples, making it easy for developers to get started and integrate them into their existing projects.
42+
43+
## How to Get Started
44+
45+
To install Golly, you can use the following command:
46+
47+
```bash
48+
go get oss.nandlabs.io/golly
49+
```

content/docs/cli/_index.md

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
---
2+
title: CLI (Commad-Line Interface)
3+
draft: false
4+
weight: 2
5+
prev: /docs
6+
next: /docs/cli/basic
7+
---
8+
9+
### Introduction
10+
11+
Command-Line Interfaces (CLIs) are a critical tool for automating tasks, configuring software, and managing systems. They provide developers and users with quick and efficient ways to interact with applications from the command line. In Go, creating such interfaces is simplified with the help of libraries like Golly’s cli package.
12+
13+
### Why Golly’s cli Package?
14+
15+
- Modular and Scalable: It supports multiple commands, subcommands, flags, and argument parsing, making it easy to build both small utilities and complex, multi-level CLI applications.
16+
- Auto-Generated Help: Automatically provides help text based on your defined commands and flags, improving usability without extra effort.
17+
- Extensibility: Custom hooks, error handling make the cli package highly extensible.
18+
19+
### Setting Up Golly’s cli Package
20+
21+
To begin building a CLI application with Golly, you first need to install the package in your Go environment:
22+
23+
```bash
24+
go get oss.nandlabs.io/golly/cli
25+
```
26+
27+
Once installed, create a new Go file for your CLI tool.
28+
In the next chapter let’s set up a basic application that prints a greeting message.

content/docs/cli/arguments.md

+253
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,253 @@
1+
---
2+
title: Arguments
3+
draft: false
4+
weight: 4
5+
prev: /docs/cli/flags
6+
next: /docs/cli/help
7+
---
8+
9+
# Comprehensive Guide to Argument Handling in Golly's CLI Package
10+
11+
In command-line interfaces (CLIs), **arguments** are essential for passing inputs to commands. These inputs, which are distinct from flags, typically consist of filenames, paths, or other necessary data required by the command to perform its task. The Golly `cli` package provides robust support for handling arguments, making it simple to manage both required and optional arguments in your Go applications.
12+
13+
Lets explore how to handle arguments using the Golly `cli` package, covering everything from simple argument retrieval to advanced use cases. We will provide detailed examples to illustrate how you can leverage arguments effectively in your CLI application.
14+
15+
## What Are Arguments in CLI?
16+
17+
Arguments in a CLI application refer to positional parameters passed to a command when it is invoked. Unlike flags, which are prefixed by an identifier (e.g., `--flag`), arguments do not require a prefix and are typically listed after the command in the terminal. For example:
18+
19+
```bash
20+
$ myapp greet John
21+
```
22+
23+
In this example, greet is the command, and John is an argument.
24+
25+
Arguments are often required, though they can also be optional depending on the design of the CLI. The Golly cli package provides flexible handling of both required and optional arguments.
26+
27+
### Basic Argument Handling
28+
29+
To demonstrate basic argument handling, let’s create a simple CLI application that accepts a name as an argument and greets the user.
30+
31+
#### Example: Greeting Command with One Argument
32+
33+
```go
34+
package main
35+
36+
import (
37+
"fmt"
38+
"log"
39+
"os"
40+
"oss.nandlabs.io/golly/cli"
41+
)
42+
43+
func main() {
44+
app := cli.NewApp()
45+
app.Name = "Greeter"
46+
app.Usage = "A simple CLI to greet users"
47+
48+
// Define the action of the app
49+
app.Action = func(ctx *cli.Context) error {
50+
if ctx.Args().Len() > 0 {
51+
name := ctx.Args().Get(0) // Get the first argument
52+
fmt.Printf("Hello, %s!\n", name)
53+
} else {
54+
fmt.Println("Hello, World!")
55+
}
56+
return nil
57+
}
58+
59+
if err := app.Execute(os.Args); err != nil {
60+
log.Fatal(err)
61+
}
62+
}
63+
```
64+
65+
In this Example:
66+
67+
- We define a single argument (the user’s name) which is passed to the greet command.
68+
- We retrieve the argument using ctx.Args().Get(0), which gets the first positional argument.
69+
- If no arguments are provided, a default message (“Hello, World!”) is displayed.
70+
71+
#### Running the Application
72+
73+
$ go run main.go John
74+
Hello, John!
75+
76+
$ go run main.go
77+
Hello, World!
78+
79+
In the first command, John is passed as an argument, and the application greets John. In the second command, no arguments are passed, so the default greeting is shown.
80+
81+
### Handling Multiple Arguments
82+
83+
The Golly cli package supports multiple arguments. Let’s extend the previous example to handle two arguments: the user’s first name and last name.
84+
85+
#### Example: Greeting with Multiple Arguments
86+
87+
```go
88+
package main
89+
90+
import (
91+
"fmt"
92+
"log"
93+
"os"
94+
"oss.nandlabs.io/golly/cli"
95+
)
96+
97+
func main() {
98+
app := cli.NewApp()
99+
app.Name = "Greeter"
100+
app.Usage = "A simple CLI to greet users with full name"
101+
102+
// Define the action of the app
103+
app.Action = func(ctx *cli.Context) error {
104+
if ctx.Args().Len() >= 2 {
105+
firstName := ctx.Args().Get(0) // First argument
106+
lastName := ctx.Args().Get(1) // Second argument
107+
fmt.Printf("Hello, %s %s!\n", firstName, lastName)
108+
} else {
109+
fmt.Println("Please provide both first and last name")
110+
}
111+
return nil
112+
}
113+
114+
if err := app.Execute(os.Args); err != nil {
115+
log.Fatal(err)
116+
}
117+
}
118+
```
119+
120+
In this example:
121+
122+
- The application expects two arguments: the first name and the last name.
123+
- If two arguments are provided, the application prints the full name.
124+
- If fewer than two arguments are provided, an error message is shown.
125+
126+
#### Running the Application
127+
128+
```bash
129+
$ go run main.go John Doe
130+
Hello, John Doe!
131+
132+
$ go run main.go John
133+
Please provide both first and last name
134+
```
135+
136+
### Argument Validation
137+
138+
The Golly cli package allows you to validate arguments before proceeding with command execution. You can check for the presence, length, or format of arguments. Let’s modify the previous example to validate that only alphabetic characters are allowed in the arguments.
139+
140+
#### Example: Validating Arguments
141+
142+
```go
143+
package main
144+
145+
import (
146+
"fmt"
147+
"log"
148+
"os"
149+
"regexp"
150+
"oss.nandlabs.io/golly/cli"
151+
)
152+
153+
func isValidName(name string) bool {
154+
regex := regexp.MustCompile(`^[a-zA-Z]+$`)
155+
return regex.MatchString(name)
156+
}
157+
158+
func main() {
159+
app := cli.NewApp()
160+
app.Name = "Greeter"
161+
app.Usage = "A simple CLI to greet users with validated names"
162+
163+
app.Action = func(ctx *cli.Context) error {
164+
if ctx.Args().Len() >= 2 {
165+
firstName := ctx.Args().Get(0)
166+
lastName := ctx.Args().Get(1)
167+
168+
if !isValidName(firstName) || !isValidName(lastName) {
169+
fmt.Println("Invalid name: Only alphabetic characters are allowed.")
170+
return nil
171+
}
172+
173+
fmt.Printf("Hello, %s %s!\n", firstName, lastName)
174+
} else {
175+
fmt.Println("Please provide both first and last name")
176+
}
177+
return nil
178+
}
179+
180+
if err := app.Execute(os.Args); err != nil {
181+
log.Fatal(err)
182+
}
183+
}
184+
```
185+
186+
In this example, the isValidName function checks if the provided arguments are valid alphabetic names. If an invalid name is provided, the application displays an error message.
187+
188+
### Handling Optional Arguments
189+
190+
Sometimes, arguments are optional. You can define default behaviors when certain arguments are not provided. Let’s modify our application to allow for an optional title (e.g., Mr., Mrs., Dr.) before the name.
191+
192+
#### Example: Handling Optional Arguments
193+
194+
```go
195+
package main
196+
197+
import (
198+
"fmt"
199+
"log"
200+
"os"
201+
"oss.nandlabs.io/golly/cli"
202+
)
203+
204+
func main() {
205+
app := cli.NewApp()
206+
app.Name = "Greeter"
207+
app.Usage = "A simple CLI to greet users with optional title"
208+
209+
app.Action = func(ctx *cli.Context) error {
210+
var title, firstName, lastName string
211+
212+
if ctx.Args().Len() == 3 {
213+
title = ctx.Args().Get(0)
214+
firstName = ctx.Args().Get(1)
215+
lastName = ctx.Args().Get(2)
216+
fmt.Printf("Hello, %s %s %s!\n", title, firstName, lastName)
217+
} else if ctx.Args().Len() == 2 {
218+
firstName = ctx.Args().Get(0)
219+
lastName = ctx.Args().Get(1)
220+
fmt.Printf("Hello, %s %s!\n", firstName, lastName)
221+
} else {
222+
fmt.Println("Please provide at least a first and last name")
223+
}
224+
return nil
225+
}
226+
227+
if err := app.Execute(os.Args); err != nil {
228+
log.Fatal(err)
229+
}
230+
}
231+
```
232+
233+
In this example:
234+
235+
- The application checks if a title is provided by counting the number of arguments.
236+
- If three arguments are provided, it assumes the first argument is the title and prints the full name with the title.
237+
- If two arguments are provided, it only prints the first and last name.
238+
239+
#### Running the Application
240+
241+
```go
242+
$ go run main.go Dr. John Doe
243+
Hello, Dr. John Doe!
244+
245+
$ go run main.go John Doe
246+
Hello, John Doe!
247+
```
248+
249+
The Golly cli package provides comprehensive and flexible argument handling, enabling developers to build powerful and user-friendly command-line tools. Whether you’re dealing with simple, required arguments or more complex, optional inputs, the cli package makes argument management easy and intuitive.
250+
251+
From basic retrieval to validation and optional argument handling, the package offers a range of tools to suit your application’s needs. Start building your CLI applications with confidence using Golly’s cli package and take advantage of its robust argument handling capabilities.
252+
253+
For more information, check out the official [Golly CLI package documentation](https://pkg.go.dev/oss.nandlabs.io/golly/cli).

content/docs/cli/basic.md

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
---
2+
title: Basic Usage
3+
draft: false
4+
weight: 1
5+
prev: /docs/cli
6+
next: /docs/cli/multiple-commands
7+
---
8+
9+
Here’s a simple example of a CLI tool with a single greet command:
10+
11+
```go
12+
package main
13+
14+
import (
15+
"fmt"
16+
"oss.nandlabs.io/golly/cli"
17+
"os"
18+
)
19+
20+
func main() {
21+
app := cli.NewApp()
22+
app.Name = "greetcli"
23+
app.Usage = "A simple CLI to greet people"
24+
25+
app.Commands = []*cli.Command{
26+
{
27+
Name: "greet",
28+
Usage: "Prints a greeting message",
29+
Action: func(c *cli.Context) error {
30+
fmt.Println("Hello, world!")
31+
return nil
32+
},
33+
},
34+
}
35+
36+
err := app.Run(os.Args)
37+
if err != nil {
38+
fmt.Println("Error running app:", err)
39+
}
40+
41+
}
42+
```
43+
44+
Running the command greetcli greet will print “Hello, world!” to the console.
45+
Let’s break down what’s happening:
46+
47+
- app.Name: Sets the CLI tool’s name.
48+
- app.Usage: Describes what the tool does, which is used in the help message.
49+
- app.Commands: Defines the list of commands that your CLI will support.
50+
- Action: This is the function that executes when the command is run.

0 commit comments

Comments
 (0)