SlideShare une entreprise Scribd logo
1  sur  46
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

Kubernetes Application Deployment with Helm - A beginner Guide!
Kubernetes Application Deployment with Helm - A beginner Guide!Kubernetes Application Deployment with Helm - A beginner Guide!
Kubernetes Application Deployment with Helm - A beginner Guide!Krishna-Kumar
 
Running Kubernetes in Production: A Million Ways to Crash Your Cluster - DevO...
Running Kubernetes in Production: A Million Ways to Crash Your Cluster - DevO...Running Kubernetes in Production: A Million Ways to Crash Your Cluster - DevO...
Running Kubernetes in Production: A Million Ways to Crash Your Cluster - DevO...Henning Jacobs
 
Invoke-Obfuscation DerbyCon 2016
Invoke-Obfuscation DerbyCon 2016Invoke-Obfuscation DerbyCon 2016
Invoke-Obfuscation DerbyCon 2016Daniel Bohannon
 
Gitlab CI : Integration et Déploiement Continue
Gitlab CI : Integration et Déploiement ContinueGitlab CI : Integration et Déploiement Continue
Gitlab CI : Integration et Déploiement ContinueVincent Composieux
 
Flink on Kubernetes operator
Flink on Kubernetes operatorFlink on Kubernetes operator
Flink on Kubernetes operatorEui Heo
 
Journée DevOps : La boite à outil d'une équipe DevOps
Journée DevOps : La boite à outil d'une équipe DevOpsJournée DevOps : La boite à outil d'une équipe DevOps
Journée DevOps : La boite à outil d'une équipe DevOpsPublicis Sapient Engineering
 
GitLab과 Kubernetes를 통한 CI/CD 구축
GitLab과 Kubernetes를 통한 CI/CD 구축GitLab과 Kubernetes를 통한 CI/CD 구축
GitLab과 Kubernetes를 통한 CI/CD 구축철구 김
 
Azure DevOps & GitHub... Better Together!
Azure DevOps & GitHub... Better Together!Azure DevOps & GitHub... Better Together!
Azure DevOps & GitHub... Better Together!Lorenzo Barbieri
 
System Hardening Using Ansible
System Hardening Using AnsibleSystem Hardening Using Ansible
System Hardening Using AnsibleSonatype
 
Introduction to Kubernetes RBAC
Introduction to Kubernetes RBACIntroduction to Kubernetes RBAC
Introduction to Kubernetes RBACKublr
 
GitOps for Helm Users by Scott Rigby
GitOps for Helm Users by Scott RigbyGitOps for Helm Users by Scott Rigby
GitOps for Helm Users by Scott RigbyWeaveworks
 
Devops Devops Devops
Devops Devops DevopsDevops Devops Devops
Devops Devops DevopsKris Buytaert
 
DevOps vs Agile | DevOps Tutorial For Beginners | DevOps Training | Edureka
DevOps vs Agile | DevOps Tutorial For Beginners | DevOps Training | EdurekaDevOps vs Agile | DevOps Tutorial For Beginners | DevOps Training | Edureka
DevOps vs Agile | DevOps Tutorial For Beginners | DevOps Training | EdurekaEdureka!
 
Gitlab ci e kubernetes, build test and deploy your projects like a pro
Gitlab ci e kubernetes, build test and deploy your projects like a proGitlab ci e kubernetes, build test and deploy your projects like a pro
Gitlab ci e kubernetes, build test and deploy your projects like a prosparkfabrik
 
Dapr - A 10x Developer Framework for Any Language
Dapr - A 10x Developer Framework for Any LanguageDapr - A 10x Developer Framework for Any Language
Dapr - A 10x Developer Framework for Any LanguageBilgin Ibryam
 

Tendances (20)

Gitops Hands On
Gitops Hands OnGitops Hands On
Gitops Hands On
 
Kubernetes Application Deployment with Helm - A beginner Guide!
Kubernetes Application Deployment with Helm - A beginner Guide!Kubernetes Application Deployment with Helm - A beginner Guide!
Kubernetes Application Deployment with Helm - A beginner Guide!
 
Devops architecture
Devops architectureDevops architecture
Devops architecture
 
Running Kubernetes in Production: A Million Ways to Crash Your Cluster - DevO...
Running Kubernetes in Production: A Million Ways to Crash Your Cluster - DevO...Running Kubernetes in Production: A Million Ways to Crash Your Cluster - DevO...
Running Kubernetes in Production: A Million Ways to Crash Your Cluster - DevO...
 
Invoke-Obfuscation DerbyCon 2016
Invoke-Obfuscation DerbyCon 2016Invoke-Obfuscation DerbyCon 2016
Invoke-Obfuscation DerbyCon 2016
 
Gitlab CI : Integration et Déploiement Continue
Gitlab CI : Integration et Déploiement ContinueGitlab CI : Integration et Déploiement Continue
Gitlab CI : Integration et Déploiement Continue
 
Flink on Kubernetes operator
Flink on Kubernetes operatorFlink on Kubernetes operator
Flink on Kubernetes operator
 
Journée DevOps : La boite à outil d'une équipe DevOps
Journée DevOps : La boite à outil d'une équipe DevOpsJournée DevOps : La boite à outil d'une équipe DevOps
Journée DevOps : La boite à outil d'une équipe DevOps
 
GitLab과 Kubernetes를 통한 CI/CD 구축
GitLab과 Kubernetes를 통한 CI/CD 구축GitLab과 Kubernetes를 통한 CI/CD 구축
GitLab과 Kubernetes를 통한 CI/CD 구축
 
Helm 3
Helm 3Helm 3
Helm 3
 
Azure DevOps & GitHub... Better Together!
Azure DevOps & GitHub... Better Together!Azure DevOps & GitHub... Better Together!
Azure DevOps & GitHub... Better Together!
 
System Hardening Using Ansible
System Hardening Using AnsibleSystem Hardening Using Ansible
System Hardening Using Ansible
 
Introduction to Kubernetes RBAC
Introduction to Kubernetes RBACIntroduction to Kubernetes RBAC
Introduction to Kubernetes RBAC
 
GitOps for Helm Users by Scott Rigby
GitOps for Helm Users by Scott RigbyGitOps for Helm Users by Scott Rigby
GitOps for Helm Users by Scott Rigby
 
Devops Devops Devops
Devops Devops DevopsDevops Devops Devops
Devops Devops Devops
 
DevOps vs Agile | DevOps Tutorial For Beginners | DevOps Training | Edureka
DevOps vs Agile | DevOps Tutorial For Beginners | DevOps Training | EdurekaDevOps vs Agile | DevOps Tutorial For Beginners | DevOps Training | Edureka
DevOps vs Agile | DevOps Tutorial For Beginners | DevOps Training | Edureka
 
"DevOps > CI+CD "
"DevOps > CI+CD ""DevOps > CI+CD "
"DevOps > CI+CD "
 
Gitlab, GitOps & ArgoCD
Gitlab, GitOps & ArgoCDGitlab, GitOps & ArgoCD
Gitlab, GitOps & ArgoCD
 
Gitlab ci e kubernetes, build test and deploy your projects like a pro
Gitlab ci e kubernetes, build test and deploy your projects like a proGitlab ci e kubernetes, build test and deploy your projects like a pro
Gitlab ci e kubernetes, build test and deploy your projects like a pro
 
Dapr - A 10x Developer Framework for Any Language
Dapr - A 10x Developer Framework for Any LanguageDapr - A 10x Developer Framework for Any Language
Dapr - A 10x Developer Framework for Any Language
 

Similaire à Building robust and friendly command line applications in go

NYPHP March 2009 Presentation
NYPHP March 2009 PresentationNYPHP March 2009 Presentation
NYPHP March 2009 Presentationbrian_dailey
 
CMake Tutorial
CMake TutorialCMake Tutorial
CMake TutorialFu Haiping
 
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...Puppet
 
Challenges of container configuration
Challenges of container configurationChallenges of container configuration
Challenges of container configurationlutter
 
Top 10 Random Linux/Ubuntu Commands
Top 10 Random Linux/Ubuntu CommandsTop 10 Random Linux/Ubuntu Commands
Top 10 Random Linux/Ubuntu CommandsYusuf Felly
 
Course 102: Lecture 8: Composite Commands
Course 102: Lecture 8: Composite Commands Course 102: Lecture 8: Composite Commands
Course 102: Lecture 8: Composite Commands Ahmed El-Arabawy
 
LOSS_C11- Programming Linux 20221006.pdf
LOSS_C11- Programming Linux 20221006.pdfLOSS_C11- Programming Linux 20221006.pdf
LOSS_C11- Programming Linux 20221006.pdfThninh2
 
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 2020CloudHero
 
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...Jim Birch
 
May The Nodejs Be With You
May The Nodejs Be With YouMay The Nodejs Be With You
May The Nodejs Be With YouDalibor Gogic
 
RHCSA EX200 - Summary
RHCSA EX200 - SummaryRHCSA EX200 - Summary
RHCSA EX200 - SummaryNugroho Gito
 
Crafting Beautiful CLI Applications in Ruby
Crafting Beautiful CLI Applications in RubyCrafting Beautiful CLI Applications in Ruby
Crafting Beautiful CLI Applications in RubyNikhil Mungel
 
Docker Security workshop slides
Docker Security workshop slidesDocker Security workshop slides
Docker Security workshop slidesDocker, Inc.
 
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...Christy Norman
 

Similaire à 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...
 

Plus de Andrii Soldatenko

Debugging concurrency programs in go
Debugging concurrency programs in goDebugging concurrency programs in go
Debugging concurrency programs in goAndrii Soldatenko
 
Advanced debugging  techniques in different environments
Advanced debugging  techniques in different environmentsAdvanced debugging  techniques in different environments
Advanced debugging  techniques in different environmentsAndrii Soldatenko
 
Building serverless-applications
Building serverless-applicationsBuilding serverless-applications
Building serverless-applicationsAndrii Soldatenko
 
Building Serverless applications with Python
Building Serverless applications with PythonBuilding Serverless applications with Python
Building Serverless applications with PythonAndrii Soldatenko
 
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 PythonAndrii Soldatenko
 
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?Andrii Soldatenko
 
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 processAndrii Soldatenko
 
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.Andrii Soldatenko
 
PyCon 2015 Belarus Andrii Soldatenko
PyCon 2015 Belarus Andrii SoldatenkoPyCon 2015 Belarus Andrii Soldatenko
PyCon 2015 Belarus Andrii SoldatenkoAndrii Soldatenko
 
SeleniumCamp 2015 Andrii Soldatenko
SeleniumCamp 2015 Andrii SoldatenkoSeleniumCamp 2015 Andrii Soldatenko
SeleniumCamp 2015 Andrii SoldatenkoAndrii Soldatenko
 

Plus de 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
 

Dernier

main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxhumanexperienceaaa
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 

Dernier (20)

main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 

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.