SlideShare a Scribd company logo
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

Meetup 23 - 03 - Application Delivery on K8S with GitOps
Meetup 23 - 03 - Application Delivery on K8S with GitOpsMeetup 23 - 03 - Application Delivery on K8S with GitOps
Meetup 23 - 03 - Application Delivery on K8S with GitOps
Vietnam Open Infrastructure User Group
 
Ansible
AnsibleAnsible
Ansible
Rahul Bajaj
 
Understand your system like never before with OpenTelemetry, Grafana, and Pro...
Understand your system like never before with OpenTelemetry, Grafana, and Pro...Understand your system like never before with OpenTelemetry, Grafana, and Pro...
Understand your system like never before with OpenTelemetry, Grafana, and Pro...
LibbySchulze
 
Designing a complete ci cd pipeline using argo events, workflow and cd products
Designing a complete ci cd pipeline using argo events, workflow and cd productsDesigning a complete ci cd pipeline using argo events, workflow and cd products
Designing a complete ci cd pipeline using argo events, workflow and cd products
Julian Mazzitelli
 
Get started with gitops and flux
Get started with gitops and fluxGet started with gitops and flux
Get started with gitops and flux
LibbySchulze1
 
Kubernetes extensibility: crd & operators
Kubernetes extensibility: crd & operators Kubernetes extensibility: crd & operators
Kubernetes extensibility: crd & operators
Giacomo Tirabassi
 
Infrastructure-as-Code with Pulumi - Better than all the others (like Ansible)?
Infrastructure-as-Code with Pulumi- Better than all the others (like Ansible)?Infrastructure-as-Code with Pulumi- Better than all the others (like Ansible)?
Infrastructure-as-Code with Pulumi - Better than all the others (like Ansible)?
Jonas Hecht
 
Terraform vs Pulumi
Terraform vs PulumiTerraform vs Pulumi
Terraform vs Pulumi
HoaiNam307
 
The Power of GitOps with Flux & GitOps Toolkit
The Power of GitOps with Flux & GitOps ToolkitThe Power of GitOps with Flux & GitOps Toolkit
The Power of GitOps with Flux & GitOps Toolkit
Weaveworks
 
Introduction to GitHub Actions
Introduction to GitHub ActionsIntroduction to GitHub Actions
Introduction to GitHub Actions
Knoldus Inc.
 
Introduction to Google Cloud Platform and APIs
Introduction to Google Cloud Platform and APIsIntroduction to Google Cloud Platform and APIs
Introduction to Google Cloud Platform and APIs
GDSCSoton
 
Gitops: the kubernetes way
Gitops: the kubernetes wayGitops: the kubernetes way
Gitops: the kubernetes way
sparkfabrik
 
Kubernetes extensibility: CRDs & Operators
Kubernetes extensibility: CRDs & OperatorsKubernetes extensibility: CRDs & Operators
Kubernetes extensibility: CRDs & Operators
SIGHUP
 
A Hands-on Introduction on Terraform Best Concepts and Best Practices
A Hands-on Introduction on Terraform Best Concepts and Best Practices A Hands-on Introduction on Terraform Best Concepts and Best Practices
A Hands-on Introduction on Terraform Best Concepts and Best Practices
Nebulaworks
 
Gitlab CI/CD
Gitlab CI/CDGitlab CI/CD
Gitlab CI/CD
JEMLI Fathi
 
Effective terraform
Effective terraformEffective terraform
Effective terraform
Calvin French-Owen
 
Grafana.pptx
Grafana.pptxGrafana.pptx
Grafana.pptx
Bhushan Rane
 
GitOps w/argocd
GitOps w/argocdGitOps w/argocd
GitOps w/argocd
Jean-Philippe Bélanger
 
infrastructure as code
infrastructure as codeinfrastructure as code
infrastructure as code
Amazon Web Services
 
GitOps with ArgoCD
GitOps with ArgoCDGitOps with ArgoCD
GitOps with ArgoCD
CloudOps2005
 

What's hot (20)

Meetup 23 - 03 - Application Delivery on K8S with GitOps
Meetup 23 - 03 - Application Delivery on K8S with GitOpsMeetup 23 - 03 - Application Delivery on K8S with GitOps
Meetup 23 - 03 - Application Delivery on K8S with GitOps
 
Ansible
AnsibleAnsible
Ansible
 
Understand your system like never before with OpenTelemetry, Grafana, and Pro...
Understand your system like never before with OpenTelemetry, Grafana, and Pro...Understand your system like never before with OpenTelemetry, Grafana, and Pro...
Understand your system like never before with OpenTelemetry, Grafana, and Pro...
 
Designing a complete ci cd pipeline using argo events, workflow and cd products
Designing a complete ci cd pipeline using argo events, workflow and cd productsDesigning a complete ci cd pipeline using argo events, workflow and cd products
Designing a complete ci cd pipeline using argo events, workflow and cd products
 
Get started with gitops and flux
Get started with gitops and fluxGet started with gitops and flux
Get started with gitops and flux
 
Kubernetes extensibility: crd & operators
Kubernetes extensibility: crd & operators Kubernetes extensibility: crd & operators
Kubernetes extensibility: crd & operators
 
Infrastructure-as-Code with Pulumi - Better than all the others (like Ansible)?
Infrastructure-as-Code with Pulumi- Better than all the others (like Ansible)?Infrastructure-as-Code with Pulumi- Better than all the others (like Ansible)?
Infrastructure-as-Code with Pulumi - Better than all the others (like Ansible)?
 
Terraform vs Pulumi
Terraform vs PulumiTerraform vs Pulumi
Terraform vs Pulumi
 
The Power of GitOps with Flux & GitOps Toolkit
The Power of GitOps with Flux & GitOps ToolkitThe Power of GitOps with Flux & GitOps Toolkit
The Power of GitOps with Flux & GitOps Toolkit
 
Introduction to GitHub Actions
Introduction to GitHub ActionsIntroduction to GitHub Actions
Introduction to GitHub Actions
 
Introduction to Google Cloud Platform and APIs
Introduction to Google Cloud Platform and APIsIntroduction to Google Cloud Platform and APIs
Introduction to Google Cloud Platform and APIs
 
Gitops: the kubernetes way
Gitops: the kubernetes wayGitops: the kubernetes way
Gitops: the kubernetes way
 
Kubernetes extensibility: CRDs & Operators
Kubernetes extensibility: CRDs & OperatorsKubernetes extensibility: CRDs & Operators
Kubernetes extensibility: CRDs & Operators
 
A Hands-on Introduction on Terraform Best Concepts and Best Practices
A Hands-on Introduction on Terraform Best Concepts and Best Practices A Hands-on Introduction on Terraform Best Concepts and Best Practices
A Hands-on Introduction on Terraform Best Concepts and Best Practices
 
Gitlab CI/CD
Gitlab CI/CDGitlab CI/CD
Gitlab CI/CD
 
Effective terraform
Effective terraformEffective terraform
Effective terraform
 
Grafana.pptx
Grafana.pptxGrafana.pptx
Grafana.pptx
 
GitOps w/argocd
GitOps w/argocdGitOps w/argocd
GitOps w/argocd
 
infrastructure as code
infrastructure as codeinfrastructure as code
infrastructure as code
 
GitOps with ArgoCD
GitOps with ArgoCDGitOps with ArgoCD
GitOps with ArgoCD
 

Similar to Building robust and friendly command line applications in go

Linux
LinuxLinux
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
LGS, GBHS&IC, University Of South-Asia, TARA-Technologies
 
NYPHP March 2009 Presentation
NYPHP March 2009 PresentationNYPHP March 2009 Presentation
NYPHP March 2009 Presentation
brian_dailey
 
CMake Tutorial
CMake TutorialCMake Tutorial
CMake Tutorial
Fu 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 configuration
lutter
 
Ansible best practices
Ansible best practicesAnsible best practices
Ansible best practices
StephaneFlotat1
 
Top 10 Random Linux/Ubuntu Commands
Top 10 Random Linux/Ubuntu CommandsTop 10 Random Linux/Ubuntu Commands
Top 10 Random Linux/Ubuntu Commands
Yusuf 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.pdf
Thninh2
 
Examples -partII
Examples -partIIExamples -partII
Examples -partII
Kedar Bhandari
 
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
CloudHero
 
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 You
Dalibor Gogic
 
RHCSA EX200 - Summary
RHCSA EX200 - SummaryRHCSA EX200 - Summary
RHCSA EX200 - Summary
Nugroho Gito
 
Crafting Beautiful CLI Applications in Ruby
Crafting Beautiful CLI Applications in RubyCrafting Beautiful CLI Applications in Ruby
Crafting Beautiful CLI Applications in Ruby
Nikhil Mungel
 
Docker Security workshop slides
Docker Security workshop slidesDocker Security workshop slides
Docker Security workshop slides
Docker, Inc.
 
From Arm to Z: Building, Shipping, and Running a Multi-platform Docker Swarm ...
From Arm to Z: Building, Shipping, and Running a Multi-platform Docker Swarm ...From Arm to Z: Building, Shipping, and Running a Multi-platform Docker Swarm ...
From Arm to Z: Building, Shipping, and Running a Multi-platform Docker Swarm ...
Docker, Inc.
 

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
 
From Arm to Z: Building, Shipping, and Running a Multi-platform Docker Swarm ...
From Arm to Z: Building, Shipping, and Running a Multi-platform Docker Swarm ...From Arm to Z: Building, Shipping, and Running a Multi-platform Docker Swarm ...
From Arm to Z: Building, Shipping, and Running a Multi-platform Docker Swarm ...
 

More from Andrii Soldatenko

Debugging concurrency programs in go
Debugging concurrency programs in goDebugging concurrency programs in go
Debugging concurrency programs in go
Andrii Soldatenko
 
Advanced debugging  techniques in different environments
Advanced debugging  techniques in different environmentsAdvanced debugging  techniques in different environments
Advanced debugging  techniques in different environments
Andrii Soldatenko
 
Origins of Serverless
Origins of ServerlessOrigins of Serverless
Origins of Serverless
Andrii Soldatenko
 
Building serverless-applications
Building serverless-applicationsBuilding serverless-applications
Building serverless-applications
Andrii Soldatenko
 
Building Serverless applications with Python
Building Serverless applications with PythonBuilding Serverless applications with Python
Building Serverless applications with Python
Andrii 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 Python
Andrii 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 process
Andrii Soldatenko
 
Kyiv.py #16 october 2015
Kyiv.py #16 october 2015Kyiv.py #16 october 2015
Kyiv.py #16 october 2015
Andrii 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 Soldatenko
Andrii Soldatenko
 
PyCon Ukraine 2014
PyCon Ukraine 2014PyCon Ukraine 2014
PyCon Ukraine 2014
Andrii Soldatenko
 
SeleniumCamp 2015 Andrii Soldatenko
SeleniumCamp 2015 Andrii SoldatenkoSeleniumCamp 2015 Andrii Soldatenko
SeleniumCamp 2015 Andrii Soldatenko
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

Democratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek AryaDemocratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek Arya
abh.arya
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
JoytuBarua2
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
Jayaprasanna4
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
Event Management System Vb Net Project Report.pdf
Event Management System Vb Net  Project Report.pdfEvent Management System Vb Net  Project Report.pdf
Event Management System Vb Net Project Report.pdf
Kamal Acharya
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
 
Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.
PrashantGoswami42
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
Divya Somashekar
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
Intella Parts
 
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSE
TECHNICAL TRAINING MANUAL   GENERAL FAMILIARIZATION COURSETECHNICAL TRAINING MANUAL   GENERAL FAMILIARIZATION COURSE
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSE
DuvanRamosGarzon1
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Dr.Costas Sachpazis
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
ViniHema
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
R&R Consult
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 

Recently uploaded (20)

Democratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek AryaDemocratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek Arya
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
 
Event Management System Vb Net Project Report.pdf
Event Management System Vb Net  Project Report.pdfEvent Management System Vb Net  Project Report.pdf
Event Management System Vb Net Project Report.pdf
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
 
Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
 
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSE
TECHNICAL TRAINING MANUAL   GENERAL FAMILIARIZATION COURSETECHNICAL TRAINING MANUAL   GENERAL FAMILIARIZATION COURSE
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSE
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 

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.