SlideShare a Scribd company logo
1 of 46
Download to read offline
Building robust and
friendly CLI apps
rclone
delve
cat
heroku
helm
Disclaimer:
No configs today
$ wc -l shakespeare.txt
124456 shakespeare.txt
os.Args - []string
Usage: docker [OPTIONS] COMMAND
A self-sufficient runtime for containers
Options:
--config string Location of client config files (default "/Users/andrii/.docker")
-D, --debug Enable debug mode
-H, --host list Daemon socket(s) to connect to
...
--tlsverify Use TLS and verify the remote
-v, --version Print version information and quit
Management Commands:
checkpoint Manage checkpoints
config Manage Docker configs
container Manage containers
image Manage images
network Manage networks
...
system Manage Docker
trust Manage trust on Docker images
volume Manage volumes
Commands:
attach Attach local standard input, output, and error streams to a running container
build Build an image from a Dockerfile
commit Create a new image from a container's changes
cp Copy files/folders between a container and the local filesystem
create Create a new container
deploy Deploy a new stack or update an existing stack
diff Inspect changes to files or directories on a container's filesystem
events Get real time events from the server
...
inspect Return low-level information on Docker objects
kill Kill one or more running containers
$ ls -la
User interface
Flags in linux/BSD
$ ls -ltrah
Long form flags:
$ ls 
--color
Go flag system based on
Plan 9
$ ls -la
la
func main() {
var la = flag.String("la", "1 flag", "1 flag in golang.")
flag.Parse()
fmt.Println(*la)
}
➜ golang_for_two ./ls -la
flag needs an argument: -la
Usage of ./ls:
  -la string
        1 flag in golang. (default "1 flag")
GNU flags??
GNU flags??
GNU/UNIX-style
command-line arguments
- fork of flag pkg
- Docker has sub-package
- launchpad.net/gnuflag
- go-flags
GNU flags??launchpad.net/gnuflag
Supports:
✓ -l short flag
✓ -la for group of flags
✓ --color for long name
✓ Etc.

git add,
git commit
git push
$ app [global opts] cmd [cmd opts] args
Command-line
frameworks
✓ https://github.com/urfave/cli
(drone, cloudfoundry)
✓ https://github.com/spf13/cobra

(kubectl, hugo, rkt, docker,
helm, delve)
Part 2
ytop
Top 10 докладов
по кол-ву
просмотров и
лайков :)
ytop.sh v1
$ tree -L 3
.
!"" client_secret.json
!"" cmd
#   $"" ytop
#   !"" completion.go
#   !"" list.go
#   !"" root.go
#   !"" root_test.go
#   $"" ytop.go
!"" go.mod
!"" go.sum
!"" pkg
#   !"" action
#   #   $"" list.go
4 directories, 11 files
Project layout
Task oriented
$ ytop list <playlist-id>
Task oriented in practise:
helm3 example of purge default flags
`helm delete --purge` is used
more often than not, so I suggest we
should make it the default convention for
Helm 3.
helm/helm/pull/5283
🔀
Task oriented:
helm3 example of purge default flags
helm/helm/pull/5283
🔀
Add tests:📝
func executeCommand(args ...string) (output string, err error)
{
buf := new(bytes.Buffer)
rootCmd := newRootCmd(buf, []string{})
rootCmd.SetOut(buf)
rootCmd.SetArgs(args)
_, err = rootCmd.ExecuteC()
return buf.String(), err
}
func TestListRootCommand(t *testing.T) {
output, err := executeCommand("list")
assert.NoError(t, err)
assert.Contains(t, output, "ytop list", output)
}
Actions pattern:
func newListCmd(out io.Writer) *cobra.Command {
cmd := &cobra.Command{
Use: "list",
Short: "list top youtube videos.",
Long: "list top youtube videos.",
Example: listExample,
RunE: func(cmd *cobra.Command, args []string) error {
return action.List()
},
}
return cmd
}
autocompletion:
func newCompletionCmd(out io.Writer) *cobra.Command {
var shells []string
for s := range completionShells {
shells = append(shells, s)
}
cmd := &cobra.Command{
Use: "completion SHELL",
Short: "Generate autocompletions script for the specified
shell (bash or zsh)",
Long: completionLong,
RunE: func(cmd *cobra.Command, args []string) error {
return runCompletion(out, cmd, args)
},
Args: cobra.ExactValidArgs(1),
ValidArgs: shells,
}
return cmd
}
autocompletion:
func runCompletionBash(w io.Writer, cmd *cobra.Command)
error {
err := cmd.Root().GenBashCompletion(w)
if err != nil {
return fmt.Errorf("error while generating bash
completion: %v", err)
}
return nil
}
Examples:
var listExample = `
List of youtube videos you would like to print:
$ youtube list <playlist-id>
`
func newListCmd(out io.Writer) *cobra.Command {
cmd := &cobra.Command{
Use: "list",
Short: "list top youtube videos.",
Long: "list top youtube videos.",
Example: listExample ,
}
return cmd
}
$ ./ytop list -h
list top youtube videos.
Usage:
ytop list [flags]
Examples:
# List of youtube videos you would like to
print:
$ youtube list <playlist-id>
Flags:
-h, --help help for list
Ship your CLI tool to
multiply OS:
🐳
https://raw.githubusercontent.com/YOU/YOURAPP/master/godownloader.sh
🏗
Aliases:
Aliases tl;dr:
type Command struct {

	 // Use is the one-line usage message.

	 Use string

	 // Aliases is an array of aliases that can be used instead of the first word in Use.
	 Aliases []string

$ ytop list --help

Usage:

ytop list [flags]

Aliases:

list, ls, l
Default to human output:
VIDEO ID LIKE COUNT TITLE
g8BD-0rIRN4 1232 Ricardo Jimenez - Quicksilver How Cloudflare …

op14_lAifQ4 597 Joan López de la Franca Beltran - From Chaos to …

KEUmOomnEqc 435 Roberto Clapis - Tackling Contention: The Monsters…

KUC5WtbBdFA 97 Johan Brandhorst - Writing REST Services for the ..
Friendly for both people
and scripts
Avoid sed/awk
$ ./ytop list <id> 
| awk -F '|' '{print NR ". " $3}'
$ ./ytop list —output json
{“videoId”: 124, “likeCount”: 1000}
CLI Best Practices
https://bestpractices.coreinfrastructure.org/en/projects/3131#changecontrol
References:
📹 justforfunc #5: Defining a Color Flag in Go
📹 justforfunc #32: CLI tools with Cobra
📹 GopherCon 2019: Carolyn Van Slyck - Design
Command-Line Tools People Love
📖 The Go Programming Language by Alan A. A.
Donovan, Brian W. Kernighan
📖 Go in Practice by Matt Butcher, Matt Farina
Go на двоих
https://t.me/golang_for_two
Questions
? @a_soldatenkot.me/golang_for_two

More Related Content

What's hot

What's hot (20)

CI/CD with Github Actions
CI/CD with Github ActionsCI/CD with Github Actions
CI/CD with Github Actions
 
Ansible
AnsibleAnsible
Ansible
 
DevSecOps 101
DevSecOps 101DevSecOps 101
DevSecOps 101
 
Introduction to Ansible
Introduction to AnsibleIntroduction to Ansible
Introduction to Ansible
 
CI/CD Overview
CI/CD OverviewCI/CD Overview
CI/CD Overview
 
Free GitOps Workshop + Intro to Kubernetes & GitOps
Free GitOps Workshop + Intro to Kubernetes & GitOpsFree GitOps Workshop + Intro to Kubernetes & GitOps
Free GitOps Workshop + Intro to Kubernetes & GitOps
 
Terraform introduction
Terraform introductionTerraform introduction
Terraform introduction
 
Let's talk about Failures with Kubernetes - Hamburg Meetup
Let's talk about Failures with Kubernetes - Hamburg MeetupLet's talk about Failures with Kubernetes - Hamburg Meetup
Let's talk about Failures with Kubernetes - Hamburg Meetup
 
Advanced Container Security
Advanced Container Security Advanced Container Security
Advanced Container Security
 
Kubernetes Security
Kubernetes SecurityKubernetes Security
Kubernetes Security
 
HashiCorp's Vault - The Examples
HashiCorp's Vault - The ExamplesHashiCorp's Vault - The Examples
HashiCorp's Vault - The Examples
 
Ansible presentation
Ansible presentationAnsible presentation
Ansible presentation
 
Docker 101 - Nov 2016
Docker 101 - Nov 2016Docker 101 - Nov 2016
Docker 101 - Nov 2016
 
GitHub Actions in action
GitHub Actions in actionGitHub Actions in action
GitHub Actions in action
 
Kubernetes Introduction
Kubernetes IntroductionKubernetes Introduction
Kubernetes Introduction
 
Automation CICD
Automation CICDAutomation CICD
Automation CICD
 
Containers Anywhere with OpenShift by Red Hat
Containers Anywhere with OpenShift by Red HatContainers Anywhere with OpenShift by Red Hat
Containers Anywhere with OpenShift by Red Hat
 
Automation with ansible
Automation with ansibleAutomation with ansible
Automation with ansible
 
FOSDEM 2017: GitLab CI
FOSDEM 2017:  GitLab CIFOSDEM 2017:  GitLab CI
FOSDEM 2017: GitLab CI
 
DevOps & SRE at Google Scale
DevOps & SRE at Google ScaleDevOps & SRE at Google Scale
DevOps & SRE at Google Scale
 

Similar to Building robust and friendly command line applications in go

LOSS_C11- Programming Linux 20221006.pdf
LOSS_C11- Programming Linux 20221006.pdfLOSS_C11- Programming Linux 20221006.pdf
LOSS_C11- Programming Linux 20221006.pdf
Thninh2
 

Similar to Building robust and friendly command line applications in go (20)

Linux
LinuxLinux
Linux
 
50 Most Frequently Used UNIX Linux Commands -hmftj
50 Most Frequently Used UNIX  Linux Commands -hmftj50 Most Frequently Used UNIX  Linux Commands -hmftj
50 Most Frequently Used UNIX Linux Commands -hmftj
 
NYPHP March 2009 Presentation
NYPHP March 2009 PresentationNYPHP March 2009 Presentation
NYPHP March 2009 Presentation
 
CMake Tutorial
CMake TutorialCMake Tutorial
CMake Tutorial
 
PuppetConf 2016: The Challenges with Container Configuration – David Lutterko...
PuppetConf 2016: The Challenges with Container Configuration – David Lutterko...PuppetConf 2016: The Challenges with Container Configuration – David Lutterko...
PuppetConf 2016: The Challenges with Container Configuration – David Lutterko...
 
Challenges of container configuration
Challenges of container configurationChallenges of container configuration
Challenges of container configuration
 
50 most frequently used unix
50 most frequently used unix50 most frequently used unix
50 most frequently used unix
 
50 most frequently used unix
50 most frequently used unix50 most frequently used unix
50 most frequently used unix
 
Ansible best practices
Ansible best practicesAnsible best practices
Ansible best practices
 
Top 10 Random Linux/Ubuntu Commands
Top 10 Random Linux/Ubuntu CommandsTop 10 Random Linux/Ubuntu Commands
Top 10 Random Linux/Ubuntu Commands
 
Course 102: Lecture 8: Composite Commands
Course 102: Lecture 8: Composite Commands Course 102: Lecture 8: Composite Commands
Course 102: Lecture 8: Composite Commands
 
LOSS_C11- Programming Linux 20221006.pdf
LOSS_C11- Programming Linux 20221006.pdfLOSS_C11- Programming Linux 20221006.pdf
LOSS_C11- Programming Linux 20221006.pdf
 
Examples -partII
Examples -partIIExamples -partII
Examples -partII
 
Docker Essentials Workshop— Innovation Labs July 2020
Docker Essentials Workshop— Innovation Labs July 2020Docker Essentials Workshop— Innovation Labs July 2020
Docker Essentials Workshop— Innovation Labs July 2020
 
Command line for the beginner - Using the command line in developing for the...
Command line for the beginner -  Using the command line in developing for the...Command line for the beginner -  Using the command line in developing for the...
Command line for the beginner - Using the command line in developing for the...
 
May The Nodejs Be With You
May The Nodejs Be With YouMay The Nodejs Be With You
May The Nodejs Be With You
 
RHCSA EX200 - Summary
RHCSA EX200 - SummaryRHCSA EX200 - Summary
RHCSA EX200 - Summary
 
Crafting Beautiful CLI Applications in Ruby
Crafting Beautiful CLI Applications in RubyCrafting Beautiful CLI Applications in Ruby
Crafting Beautiful CLI Applications in Ruby
 
Docker Security workshop slides
Docker Security workshop slidesDocker Security workshop slides
Docker Security workshop slides
 
A to Z of a Multi-platform Docker Swarm: Building, Shipping, and Running Mult...
A to Z of a Multi-platform Docker Swarm: Building, Shipping, and Running Mult...A to Z of a Multi-platform Docker Swarm: Building, Shipping, and Running Mult...
A to Z of a Multi-platform Docker Swarm: Building, Shipping, and Running Mult...
 

More from Andrii Soldatenko

More from Andrii Soldatenko (13)

Debugging concurrency programs in go
Debugging concurrency programs in goDebugging concurrency programs in go
Debugging concurrency programs in go
 
Advanced debugging  techniques in different environments
Advanced debugging  techniques in different environmentsAdvanced debugging  techniques in different environments
Advanced debugging  techniques in different environments
 
Origins of Serverless
Origins of ServerlessOrigins of Serverless
Origins of Serverless
 
Building serverless-applications
Building serverless-applicationsBuilding serverless-applications
Building serverless-applications
 
Building Serverless applications with Python
Building Serverless applications with PythonBuilding Serverless applications with Python
Building Serverless applications with Python
 
Building social network with Neo4j and Python
Building social network with Neo4j and PythonBuilding social network with Neo4j and Python
Building social network with Neo4j and Python
 
What is the best full text search engine for Python?
What is the best full text search engine for Python?What is the best full text search engine for Python?
What is the best full text search engine for Python?
 
Practical continuous quality gates for development process
Practical continuous quality gates for development processPractical continuous quality gates for development process
Practical continuous quality gates for development process
 
Kyiv.py #16 october 2015
Kyiv.py #16 october 2015Kyiv.py #16 october 2015
Kyiv.py #16 october 2015
 
PyCon Russian 2015 - Dive into full text search with python.
PyCon Russian 2015 - Dive into full text search with python.PyCon Russian 2015 - Dive into full text search with python.
PyCon Russian 2015 - Dive into full text search with python.
 
PyCon 2015 Belarus Andrii Soldatenko
PyCon 2015 Belarus Andrii SoldatenkoPyCon 2015 Belarus Andrii Soldatenko
PyCon 2015 Belarus Andrii Soldatenko
 
PyCon Ukraine 2014
PyCon Ukraine 2014PyCon Ukraine 2014
PyCon Ukraine 2014
 
SeleniumCamp 2015 Andrii Soldatenko
SeleniumCamp 2015 Andrii SoldatenkoSeleniumCamp 2015 Andrii Soldatenko
SeleniumCamp 2015 Andrii Soldatenko
 

Recently uploaded

Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
amitlee9823
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
dollysharma2066
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Kandungan 087776558899
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
dharasingh5698
 

Recently uploaded (20)

Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
 
Intro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdfIntro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdf
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
 

Building robust and friendly command line applications in go

  • 2.
  • 5. $ wc -l shakespeare.txt 124456 shakespeare.txt
  • 7.
  • 8.
  • 9. Usage: docker [OPTIONS] COMMAND A self-sufficient runtime for containers Options: --config string Location of client config files (default "/Users/andrii/.docker") -D, --debug Enable debug mode -H, --host list Daemon socket(s) to connect to ... --tlsverify Use TLS and verify the remote -v, --version Print version information and quit Management Commands: checkpoint Manage checkpoints config Manage Docker configs container Manage containers image Manage images network Manage networks ... system Manage Docker trust Manage trust on Docker images volume Manage volumes Commands: attach Attach local standard input, output, and error streams to a running container build Build an image from a Dockerfile commit Create a new image from a container's changes cp Copy files/folders between a container and the local filesystem create Create a new container deploy Deploy a new stack or update an existing stack diff Inspect changes to files or directories on a container's filesystem events Get real time events from the server ... inspect Return low-level information on Docker objects kill Kill one or more running containers
  • 10.
  • 11. $ ls -la User interface
  • 12. Flags in linux/BSD $ ls -ltrah
  • 13. Long form flags: $ ls --color
  • 14. Go flag system based on Plan 9
  • 16. func main() { var la = flag.String("la", "1 flag", "1 flag in golang.") flag.Parse() fmt.Println(*la) } ➜ golang_for_two ./ls -la flag needs an argument: -la Usage of ./ls:   -la string         1 flag in golang. (default "1 flag")
  • 18. GNU flags?? GNU/UNIX-style command-line arguments - fork of flag pkg - Docker has sub-package - launchpad.net/gnuflag - go-flags
  • 19. GNU flags??launchpad.net/gnuflag Supports: ✓ -l short flag ✓ -la for group of flags ✓ --color for long name ✓ Etc.

  • 20. git add, git commit git push $ app [global opts] cmd [cmd opts] args
  • 21. Command-line frameworks ✓ https://github.com/urfave/cli (drone, cloudfoundry) ✓ https://github.com/spf13/cobra
 (kubectl, hugo, rkt, docker, helm, delve)
  • 23.
  • 24. ytop Top 10 докладов по кол-ву просмотров и лайков :)
  • 26. $ tree -L 3 . !"" client_secret.json !"" cmd #   $"" ytop #   !"" completion.go #   !"" list.go #   !"" root.go #   !"" root_test.go #   $"" ytop.go !"" go.mod !"" go.sum !"" pkg #   !"" action #   #   $"" list.go 4 directories, 11 files Project layout
  • 27. Task oriented $ ytop list <playlist-id>
  • 28. Task oriented in practise: helm3 example of purge default flags `helm delete --purge` is used more often than not, so I suggest we should make it the default convention for Helm 3. helm/helm/pull/5283 🔀
  • 29. Task oriented: helm3 example of purge default flags helm/helm/pull/5283 🔀
  • 30. Add tests:📝 func executeCommand(args ...string) (output string, err error) { buf := new(bytes.Buffer) rootCmd := newRootCmd(buf, []string{}) rootCmd.SetOut(buf) rootCmd.SetArgs(args) _, err = rootCmd.ExecuteC() return buf.String(), err } func TestListRootCommand(t *testing.T) { output, err := executeCommand("list") assert.NoError(t, err) assert.Contains(t, output, "ytop list", output) }
  • 31. Actions pattern: func newListCmd(out io.Writer) *cobra.Command { cmd := &cobra.Command{ Use: "list", Short: "list top youtube videos.", Long: "list top youtube videos.", Example: listExample, RunE: func(cmd *cobra.Command, args []string) error { return action.List() }, } return cmd }
  • 32. autocompletion: func newCompletionCmd(out io.Writer) *cobra.Command { var shells []string for s := range completionShells { shells = append(shells, s) } cmd := &cobra.Command{ Use: "completion SHELL", Short: "Generate autocompletions script for the specified shell (bash or zsh)", Long: completionLong, RunE: func(cmd *cobra.Command, args []string) error { return runCompletion(out, cmd, args) }, Args: cobra.ExactValidArgs(1), ValidArgs: shells, } return cmd }
  • 33. autocompletion: func runCompletionBash(w io.Writer, cmd *cobra.Command) error { err := cmd.Root().GenBashCompletion(w) if err != nil { return fmt.Errorf("error while generating bash completion: %v", err) } return nil }
  • 34. Examples: var listExample = ` List of youtube videos you would like to print: $ youtube list <playlist-id> ` func newListCmd(out io.Writer) *cobra.Command { cmd := &cobra.Command{ Use: "list", Short: "list top youtube videos.", Long: "list top youtube videos.", Example: listExample , } return cmd }
  • 35. $ ./ytop list -h list top youtube videos. Usage: ytop list [flags] Examples: # List of youtube videos you would like to print: $ youtube list <playlist-id> Flags: -h, --help help for list
  • 36. Ship your CLI tool to multiply OS: 🐳 https://raw.githubusercontent.com/YOU/YOURAPP/master/godownloader.sh 🏗
  • 38. Aliases tl;dr: type Command struct { // Use is the one-line usage message. Use string // Aliases is an array of aliases that can be used instead of the first word in Use. Aliases []string $ ytop list --help Usage: ytop list [flags] Aliases: list, ls, l
  • 39. Default to human output: VIDEO ID LIKE COUNT TITLE g8BD-0rIRN4 1232 Ricardo Jimenez - Quicksilver How Cloudflare … op14_lAifQ4 597 Joan López de la Franca Beltran - From Chaos to … KEUmOomnEqc 435 Roberto Clapis - Tackling Contention: The Monsters… KUC5WtbBdFA 97 Johan Brandhorst - Writing REST Services for the ..
  • 40. Friendly for both people and scripts
  • 41. Avoid sed/awk $ ./ytop list <id> | awk -F '|' '{print NR ". " $3}' $ ./ytop list —output json {“videoId”: 124, “likeCount”: 1000}
  • 43. References: 📹 justforfunc #5: Defining a Color Flag in Go 📹 justforfunc #32: CLI tools with Cobra 📹 GopherCon 2019: Carolyn Van Slyck - Design Command-Line Tools People Love 📖 The Go Programming Language by Alan A. A. Donovan, Brian W. Kernighan 📖 Go in Practice by Matt Butcher, Matt Farina
  • 44.