diff --git a/commands/root.go b/commands/root.go index a748e9ee2..3e1426f56 100644 --- a/commands/root.go +++ b/commands/root.go @@ -162,6 +162,7 @@ func initConfig() { func addCommands() { rootCmd.AddCommand(VersionCmd()) rootCmd.AddCommand(LoginCmd()) + rootCmd.AddCommand(InteractiveShellCmd()) // V6 Resources Commands rootCmd.AddCommand(cloudapiv6.LocationCmd()) rootCmd.AddCommand(cloudapiv6.DatacenterCmd()) diff --git a/commands/shell.go b/commands/shell.go new file mode 100644 index 000000000..0aafe3190 --- /dev/null +++ b/commands/shell.go @@ -0,0 +1,36 @@ +package commands + +import ( + "context" + "fmt" + "github.com/ionos-cloud/ionosctl/v6/pkg/core" + "github.com/stromland/cobra-prompt" +) + +var simplePrompt = &cobraprompt.CobraPrompt{ + RootCmd: GetRootCmd().Command, + AddDefaultExitCommand: true, + DisableCompletionCommand: true, + OnErrorFunc: func(err error) { + fmt.Printf(err.Error()) + }, +} + +func InteractiveShellCmd() *core.Command { + cmd := core.NewCommand(context.Background(), nil, core.CommandBuilder{ + Namespace: "shell", + Resource: "shell", + Verb: "shell", + ShortDesc: "Use ionosctl interactively", + Example: "ionosctl shell", + PreCmdRun: core.NoPreRun, + CmdRun: func(commandConfig *core.CommandConfig) error { + fmt.Printf("Use `exit` to leave the shell.\n") + simplePrompt.Run() + return nil + }, + InitClient: false, + }) + + return cmd +} diff --git a/go.mod b/go.mod index 106c5c336..9a29d5cf2 100644 --- a/go.mod +++ b/go.mod @@ -33,7 +33,16 @@ require ( github.com/ionos-cloud/sdk-go-container-registry v1.0.0 ) -require github.com/ionos-cloud/sdk-go-dataplatform v1.0.0 +require ( + github.com/ionos-cloud/sdk-go-dataplatform v1.0.0 + github.com/stromland/cobra-prompt v0.5.0 +) + +require ( + github.com/c-bata/go-prompt v0.2.6 // indirect + github.com/mattn/go-tty v0.0.3 // indirect + github.com/pkg/term v1.2.0-beta.2 // indirect +) require ( github.com/VividCortex/ewma v1.2.0 // indirect diff --git a/go.sum b/go.sum index 52a28cd61..db9f6b508 100644 --- a/go.sum +++ b/go.sum @@ -63,6 +63,8 @@ github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24 github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= +github.com/c-bata/go-prompt v0.2.6 h1:POP+nrHE+DfLYx370bedwNhsqmpCUynWPxuHi0C5vZI= +github.com/c-bata/go-prompt v0.2.6/go.mod h1:/LMAke8wD2FsNu9EXNdHxNLbd9MedkPnCdfpU9wwHfY= github.com/casbin/casbin/v2 v2.1.2/go.mod h1:YcPU1XXisHhLzuxH9coDNf2FbKpjGlbCg3n9yuLkIJQ= github.com/cenkalti/backoff v2.2.1+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= @@ -168,8 +170,6 @@ github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= -github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= -github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= @@ -255,8 +255,6 @@ github.com/ionos-cloud/sdk-go-dataplatform v1.0.0 h1:seX3oHtMmmlmwSCYUUF91Jrx4B/ github.com/ionos-cloud/sdk-go-dataplatform v1.0.0/go.mod h1:YitNqq01IAbzMr1GpXIDW1+pvhiY9eUs7/+rB9UitXE= github.com/ionos-cloud/sdk-go-dbaas-mongo v1.2.2 h1:ulRbidG3UQ6Htb7DMIewkr67FbNlqHuv1MYqIs3XOas= github.com/ionos-cloud/sdk-go-dbaas-mongo v1.2.2/go.mod h1:XxUpRByvuEnYSTCMeJGt1Ia7JID7+gFo8tTGw1BfbNE= -github.com/ionos-cloud/sdk-go-dbaas-mongo v1.2.2 h1:ulRbidG3UQ6Htb7DMIewkr67FbNlqHuv1MYqIs3XOas= -github.com/ionos-cloud/sdk-go-dbaas-mongo v1.2.2/go.mod h1:XxUpRByvuEnYSTCMeJGt1Ia7JID7+gFo8tTGw1BfbNE= github.com/ionos-cloud/sdk-go-dbaas-postgres v1.1.1 h1:ce/ViK3ZTyJXHDDMP4LHxtRXXgHcIvxJn/talGT0Zn0= github.com/ionos-cloud/sdk-go-dbaas-postgres v1.1.1/go.mod h1:hW3TPdwzS0iYjfY0gO6NJ7x+85wFW2rrZMxiwBhQmko= github.com/ionos-cloud/sdk-go/v6 v6.1.4 h1:BJHhFA8Q1SZC7VOXqKKr2BV2ysQ2/4hlk1e4hZte7GY= @@ -292,21 +290,27 @@ github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0V github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= +github.com/mattn/go-colorable v0.1.7/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= +github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84= github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng= github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= +github.com/mattn/go-runewidth v0.0.6/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= +github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk= github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU= github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= +github.com/mattn/go-tty v0.0.3 h1:5OfyWorkyO7xP52Mq7tB36ajHDG5OHrmBGIS/DtakQI= +github.com/mattn/go-tty v0.0.3/go.mod h1:ihxohKRERHTVzN+aSVRwACLCeqIoZAWpoICkkvrWyR0= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= @@ -364,6 +368,8 @@ github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/profile v1.2.1/go.mod h1:hJw3o1OdXxsrSjjVksARp5W95eeEaEfptyVZyv6JUPA= github.com/pkg/sftp v1.13.1/go.mod h1:3HaPG6Dq1ILlpPZRO0HVMrsydcdLt6HRDccSgb87qRg= +github.com/pkg/term v1.2.0-beta.2 h1:L3y/h2jkuBVFdWiJvNfYfKmzcCnILw7mJWm2JQuMppw= +github.com/pkg/term v1.2.0-beta.2/go.mod h1:E25nymQcrSllhX42Ok8MRm1+hyBdHY0dCeiKZ9jpNGw= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= @@ -435,6 +441,8 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stromland/cobra-prompt v0.5.0 h1:KsJF8KIVbKzRfCbFXrkEoRPNB7BaQjXuic3zXOY98Jg= +github.com/stromland/cobra-prompt v0.5.0/go.mod h1:YEPyw5mBSti7yvvcpscvOq0lQ6Fvke2FaHve2p3g4dk= github.com/subosito/gotenv v1.4.2 h1:X1TuBLAMDFbaTAChgCBLu3DU3UPyELpnF2jjJ2cz/S8= github.com/subosito/gotenv v1.4.2/go.mod h1:ayKnFf/c6rvx/2iiLrJUk1e6plDbT3edrFNGqEflhK0= github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= @@ -601,7 +609,9 @@ golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190826190057-c7b8b68b1456/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191220142924-d4481acd189f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -620,6 +630,8 @@ golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200803210538-64077c9b5642/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200909081042-eff7692f9009/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200918174421-af09f7315aff/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201201145000-ef89a241ccb3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= diff --git a/vendor/github.com/c-bata/go-prompt/.gitignore b/vendor/github.com/c-bata/go-prompt/.gitignore new file mode 100644 index 000000000..eba2b56ab --- /dev/null +++ b/vendor/github.com/c-bata/go-prompt/.gitignore @@ -0,0 +1,26 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so +bin/ + +# Folders +pkg/ +_obj +_test + +# Architecture specific extensions/prefixes +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof + +# Glide +vendor/ diff --git a/vendor/github.com/c-bata/go-prompt/CHANGELOG.md b/vendor/github.com/c-bata/go-prompt/CHANGELOG.md new file mode 100644 index 000000000..b9e21f1ef --- /dev/null +++ b/vendor/github.com/c-bata/go-prompt/CHANGELOG.md @@ -0,0 +1,79 @@ +# Change Log + +## v0.3.0 (2018/??/??) + +next release. + +## v0.2.3 (2018/10/25) + +### What's new? + +* Add `prompt.FuzzyFilter` for fuzzy matching at [#92](https://github.com/c-bata/go-prompt/pull/92). +* Add `OptionShowCompletionAtStart` to show completion at start at [#100](https://github.com/c-bata/go-prompt/pull/100). +* Add `prompt.NewStderrWriter` at [#102](https://github.com/c-bata/go-prompt/pull/102). + +### Fixed + +* Fix resetting display attributes (please see [pull #104](https://github.com/c-bata/go-prompt/pull/104) for more details). +* Fix error handling of Flush function in ConsoleWriter (please see [pull #97](https://github.com/c-bata/go-prompt/pull/97) for more details). +* Fix panic problem when reading from stdin before starting the prompt (please see [issue #88](https://github.com/c-bata/go-prompt/issues/88) for more details). + +### Removed or Deprecated + +* `prompt.NewStandardOutputWriter` is deprecated. Please use `prompt.NewStdoutWriter`. + +## v0.2.2 (2018/06/28) + +### What's new? + +* Support CJK(Chinese, Japanese and Korean) and Cyrillic characters. +* Add OptionCompletionWordSeparator(x string) to customize insertion points for completions. + * To support this, text query functions by arbitrary word separator are added in Document (please see [here](https://github.com/c-bata/go-prompt/pull/79) for more details). +* Add FilePathCompleter to complete file path on your system. +* Add option to customize ascii code key bindings. +* Add GetWordAfterCursor method in Document. + +### Removed or Deprecated + +* prompt.Choose shortcut function is deprecated. + +## v0.2.1 (2018/02/14) + +### What's New? + +* ~~It seems that windows support is almost perfect.~~ + * A critical bug is found :( When you change a terminal window size, the layout will be broken because current implementation cannot catch signal for updating window size on Windows. + +### Fixed + +* Fix a Shift+Tab handling on Windows. +* Fix 4-dimension arrow keys handling on Windows. + +## v0.2.0 (2018/02/13) + +### What's New? + +* Supports scrollbar when there are too many matched suggestions +* Windows support (but please caution because this is still not perfect). +* Add OptionLivePrefix to update the prefix dynamically +* Implement clear screen by `Ctrl+L`. + +### Fixed + +* Fix the behavior of `Ctrl+W` keybind. +* Fix the panic because when running on a docker container (please see [here](https://github.com/c-bata/go-prompt/pull/32) for details). +* Fix panic when making terminal window small size after input 2 lines of texts. See [here](https://github.com/c-bata/go-prompt/issues/37) for details). +* And also fixed many bugs that layout is broken when using Terminal.app, GNU Terminal and a Goland(IntelliJ). + +### News + +New core developers are joined (alphabetical order). + +* Nao Yonashiro (Github @orisano) +* Ryoma Abe (Github @Allajah) +* Yusuke Nakamura (Github @unasuke) + + +## v0.1.0 (2017/08/15) + +Initial Release diff --git a/vendor/github.com/c-bata/go-prompt/LICENSE b/vendor/github.com/c-bata/go-prompt/LICENSE new file mode 100644 index 000000000..a86acaa7a --- /dev/null +++ b/vendor/github.com/c-bata/go-prompt/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Masashi SHIBATA + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/c-bata/go-prompt/Makefile b/vendor/github.com/c-bata/go-prompt/Makefile new file mode 100644 index 000000000..505817c36 --- /dev/null +++ b/vendor/github.com/c-bata/go-prompt/Makefile @@ -0,0 +1,46 @@ +.DEFAULT_GOAL := help + +SOURCES := $(shell find . -prune -o -name "*.go" -not -name '*_test.go' -print) + +GOIMPORTS ?= goimports +GOCILINT ?= golangci-lint + +.PHONY: setup +setup: ## Setup for required tools. + go get -u golang.org/x/tools/cmd/goimports + go get -u github.com/golangci/golangci-lint/cmd/golangci-lint + go get -u golang.org/x/tools/cmd/stringer + +.PHONY: fmt +fmt: $(SOURCES) ## Formatting source codes. + @$(GOIMPORTS) -w $^ + +.PHONY: lint +lint: ## Run golangci-lint. + @$(GOCILINT) run --no-config --disable-all --enable=goimports --enable=misspell ./... + +.PHONY: test +test: ## Run tests with race condition checking. + @go test -race ./... + +.PHONY: bench +bench: ## Run benchmarks. + @go test -bench=. -run=- -benchmem ./... + +.PHONY: coverage +cover: ## Run the tests. + @go test -coverprofile=coverage.o + @go tool cover -func=coverage.o + +.PHONY: generate +generate: ## Run go generate + @go generate ./... + +.PHONY: build +build: ## Build example command lines. + ./_example/build.sh + +.PHONY: help +help: ## Show help text + @echo "Commands:" + @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " \033[36m%-10s\033[0m %s\n", $$1, $$2}' diff --git a/vendor/github.com/c-bata/go-prompt/README.md b/vendor/github.com/c-bata/go-prompt/README.md new file mode 100644 index 000000000..cfcd7a399 --- /dev/null +++ b/vendor/github.com/c-bata/go-prompt/README.md @@ -0,0 +1,125 @@ +# go-prompt + +[![Go Report Card](https://goreportcard.com/badge/github.com/c-bata/go-prompt)](https://goreportcard.com/report/github.com/c-bata/go-prompt) +![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square) +[![GoDoc](https://godoc.org/github.com/c-bata/go-prompt?status.svg)](https://godoc.org/github.com/c-bata/go-prompt) +![tests](https://github.com/c-bata/go-prompt/workflows/tests/badge.svg) + +A library for building powerful interactive prompts inspired by [python-prompt-toolkit](https://github.com/jonathanslenders/python-prompt-toolkit), +making it easier to build cross-platform command line tools using Go. + +```go +package main + +import ( + "fmt" + "github.com/c-bata/go-prompt" +) + +func completer(d prompt.Document) []prompt.Suggest { + s := []prompt.Suggest{ + {Text: "users", Description: "Store the username and age"}, + {Text: "articles", Description: "Store the article text posted by user"}, + {Text: "comments", Description: "Store the text commented to articles"}, + } + return prompt.FilterHasPrefix(s, d.GetWordBeforeCursor(), true) +} + +func main() { + fmt.Println("Please select table.") + t := prompt.Input("> ", completer) + fmt.Println("You selected " + t) +} +``` + +#### Projects using go-prompt + +* [c-bata/kube-prompt : An interactive kubernetes client featuring auto-complete written in Go.](https://github.com/c-bata/kube-prompt) +* [rancher/cli : The Rancher Command Line Interface (CLI)is a unified tool to manage your Rancher server](https://github.com/rancher/cli) +* [kubicorn/kubicorn : Simple, cloud native infrastructure for Kubernetes.](https://github.com/kubicorn/kubicorn) +* [cch123/asm-cli : Interactive shell of assembly language(X86/X64) based on unicorn and rasm2](https://github.com/cch123/asm-cli) +* [ktr0731/evans : more expressive universal gRPC client](https://github.com/ktr0731/evans) +* [CrushedPixel/moshpit: A Command-line tool for datamoshing.](https://github.com/CrushedPixel/moshpit) +* [last-ent/testy-go: Testy Go: A tool for easy testing!](https://github.com/last-ent/testy-go) +* [tiagorlampert/CHAOS: a PoC that allow generate payloads and control remote operating systems.](https://github.com/tiagorlampert/CHAOS) +* [abs-lang/abs: ABS is a scripting language that works best on terminal. It tries to combine the elegance of languages such as Python, or Ruby, to the convenience of Bash.](https://github.com/abs-lang/abs) +* [takashabe/btcli: btcli is a CLI client for the Bigtable. Has many read options and auto-completion.](https://github.com/takashabe/btcli) +* [ysn2233/kafka-prompt: An interactive kafka-prompt(kafka-shell) built on existing kafka command client](https://github.com/ysn2233/kafka-prompt) +* [fishi0x01/vsh: HashiCorp Vault interactive shell](https://github.com/fishi0x01/vsh) +* [mstrYoda/docker-shell: A simple interactive prompt for docker](https://github.com/mstrYoda/docker-shell) +* [c-bata/gh-prompt: An interactive GitHub CLI featuring auto-complete.](https://github.com/c-bata/gh-prompt) +* [docker-slim/docker-slim: Don't change anything in your Docker container image and minify it by up to 30x (and for compiled languages even more) making it secure too! (free and open source)](https://github.com/docker-slim/docker-slim) +* [rueyaa332266/ezcron: Ezcron is a CLI tool, helping you deal with cron expression easier.](https://github.com/rueyaa332266/ezcron) +* [qingstor/qsctl: Advanced command line tool for QingStor Object Storage.](https://github.com/qingstor/qsctl) +* [segmentio/topicctl: Tool for declarative management of Kafka topics](https://github.com/segmentio/topicctl) +* [chriswalz/bit: Bit is a modern Git CLI](https://github.com/chriswalz/bit) +* (If you create a CLI utility using go-prompt and want your own project to be listed here, please submit a GitHub issue.) + +## Features + +### Powerful auto-completion + +[![demo](https://github.com/c-bata/assets/raw/master/go-prompt/kube-prompt.gif)](https://github.com/c-bata/kube-prompt) + +(This is a GIF animation of kube-prompt.) + +### Flexible options + +go-prompt provides many options. Please check [option section of GoDoc](https://godoc.org/github.com/c-bata/go-prompt#Option) for more details. + +[![options](https://github.com/c-bata/assets/raw/master/go-prompt/prompt-options.png)](#flexible-options) + +### Keyboard Shortcuts + +Emacs-like keyboard shortcuts are available by default (these also are the default shortcuts in Bash shell). +You can customize and expand these shortcuts. + +[![keyboard shortcuts](https://github.com/c-bata/assets/raw/master/go-prompt/keyboard-shortcuts.gif)](#keyboard-shortcuts) + +Key Binding | Description +---------------------|--------------------------------------------------------- +Ctrl + A | Go to the beginning of the line (Home) +Ctrl + E | Go to the end of the line (End) +Ctrl + P | Previous command (Up arrow) +Ctrl + N | Next command (Down arrow) +Ctrl + F | Forward one character +Ctrl + B | Backward one character +Ctrl + D | Delete character under the cursor +Ctrl + H | Delete character before the cursor (Backspace) +Ctrl + W | Cut the word before the cursor to the clipboard +Ctrl + K | Cut the line after the cursor to the clipboard +Ctrl + U | Cut the line before the cursor to the clipboard +Ctrl + L | Clear the screen + +### History + +You can use Up arrow and Down arrow to walk through the history of commands executed. + +[![History](https://github.com/c-bata/assets/raw/master/go-prompt/history.gif)](#history) + +### Multiple platform support + +We have confirmed go-prompt works fine in the following terminals: + +* iTerm2 (macOS) +* Terminal.app (macOS) +* Command Prompt (Windows) +* gnome-terminal (Ubuntu) + +## Links + +* [Change Log](./CHANGELOG.md) +* [GoDoc](http://godoc.org/github.com/c-bata/go-prompt) +* [gocover.io](https://gocover.io/github.com/c-bata/go-prompt) + +## Author + +Masashi Shibata + +* Twitter: [@c\_bata\_](https://twitter.com/c_bata_/) +* Github: [@c-bata](https://github.com/c-bata/) + +## License + +This software is licensed under the MIT license, see [LICENSE](./LICENSE) for more information. + diff --git a/vendor/github.com/c-bata/go-prompt/buffer.go b/vendor/github.com/c-bata/go-prompt/buffer.go new file mode 100644 index 000000000..46efbbba8 --- /dev/null +++ b/vendor/github.com/c-bata/go-prompt/buffer.go @@ -0,0 +1,191 @@ +package prompt + +import ( + "strings" + + "github.com/c-bata/go-prompt/internal/debug" +) + +// Buffer emulates the console buffer. +type Buffer struct { + workingLines []string // The working lines. Similar to history + workingIndex int + cursorPosition int + cacheDocument *Document + preferredColumn int // Remember the original column for the next up/down movement. + lastKeyStroke Key +} + +// Text returns string of the current line. +func (b *Buffer) Text() string { + return b.workingLines[b.workingIndex] +} + +// Document method to return document instance from the current text and cursor position. +func (b *Buffer) Document() (d *Document) { + if b.cacheDocument == nil || + b.cacheDocument.Text != b.Text() || + b.cacheDocument.cursorPosition != b.cursorPosition { + b.cacheDocument = &Document{ + Text: b.Text(), + cursorPosition: b.cursorPosition, + } + } + b.cacheDocument.lastKey = b.lastKeyStroke + return b.cacheDocument +} + +// DisplayCursorPosition returns the cursor position on rendered text on terminal emulators. +// So if Document is "日本(cursor)語", DisplayedCursorPosition returns 4 because '日' and '本' are double width characters. +func (b *Buffer) DisplayCursorPosition() int { + return b.Document().DisplayCursorPosition() +} + +// InsertText insert string from current line. +func (b *Buffer) InsertText(v string, overwrite bool, moveCursor bool) { + or := []rune(b.Text()) + oc := b.cursorPosition + + if overwrite { + overwritten := string(or[oc : oc+len(v)]) + if strings.Contains(overwritten, "\n") { + i := strings.IndexAny(overwritten, "\n") + overwritten = overwritten[:i] + } + b.setText(string(or[:oc]) + v + string(or[oc+len(overwritten):])) + } else { + b.setText(string(or[:oc]) + v + string(or[oc:])) + } + + if moveCursor { + b.cursorPosition += len([]rune(v)) + } +} + +// SetText method to set text and update cursorPosition. +// (When doing this, make sure that the cursor_position is valid for this text. +// text/cursor_position should be consistent at any time, otherwise set a Document instead.) +func (b *Buffer) setText(v string) { + debug.Assert(b.cursorPosition <= len([]rune(v)), "length of input should be shorter than cursor position") + b.workingLines[b.workingIndex] = v +} + +// Set cursor position. Return whether it changed. +func (b *Buffer) setCursorPosition(p int) { + if p > 0 { + b.cursorPosition = p + } else { + b.cursorPosition = 0 + } +} + +func (b *Buffer) setDocument(d *Document) { + b.cacheDocument = d + b.setCursorPosition(d.cursorPosition) // Call before setText because setText check the relation between cursorPosition and line length. + b.setText(d.Text) +} + +// CursorLeft move to left on the current line. +func (b *Buffer) CursorLeft(count int) { + l := b.Document().GetCursorLeftPosition(count) + b.cursorPosition += l +} + +// CursorRight move to right on the current line. +func (b *Buffer) CursorRight(count int) { + l := b.Document().GetCursorRightPosition(count) + b.cursorPosition += l +} + +// CursorUp move cursor to the previous line. +// (for multi-line edit). +func (b *Buffer) CursorUp(count int) { + orig := b.preferredColumn + if b.preferredColumn == -1 { // -1 means nil + orig = b.Document().CursorPositionCol() + } + b.cursorPosition += b.Document().GetCursorUpPosition(count, orig) + + // Remember the original column for the next up/down movement. + b.preferredColumn = orig +} + +// CursorDown move cursor to the next line. +// (for multi-line edit). +func (b *Buffer) CursorDown(count int) { + orig := b.preferredColumn + if b.preferredColumn == -1 { // -1 means nil + orig = b.Document().CursorPositionCol() + } + b.cursorPosition += b.Document().GetCursorDownPosition(count, orig) + + // Remember the original column for the next up/down movement. + b.preferredColumn = orig +} + +// DeleteBeforeCursor delete specified number of characters before cursor and return the deleted text. +func (b *Buffer) DeleteBeforeCursor(count int) (deleted string) { + debug.Assert(count >= 0, "count should be positive") + r := []rune(b.Text()) + + if b.cursorPosition > 0 { + start := b.cursorPosition - count + if start < 0 { + start = 0 + } + deleted = string(r[start:b.cursorPosition]) + b.setDocument(&Document{ + Text: string(r[:start]) + string(r[b.cursorPosition:]), + cursorPosition: b.cursorPosition - len([]rune(deleted)), + }) + } + return +} + +// NewLine means CR. +func (b *Buffer) NewLine(copyMargin bool) { + if copyMargin { + b.InsertText("\n"+b.Document().leadingWhitespaceInCurrentLine(), false, true) + } else { + b.InsertText("\n", false, true) + } +} + +// Delete specified number of characters and Return the deleted text. +func (b *Buffer) Delete(count int) (deleted string) { + r := []rune(b.Text()) + if b.cursorPosition < len(r) { + deleted = b.Document().TextAfterCursor()[:count] + b.setText(string(r[:b.cursorPosition]) + string(r[b.cursorPosition+len(deleted):])) + } + return +} + +// JoinNextLine joins the next line to the current one by deleting the line ending after the current line. +func (b *Buffer) JoinNextLine(separator string) { + if !b.Document().OnLastLine() { + b.cursorPosition += b.Document().GetEndOfLinePosition() + b.Delete(1) + // Remove spaces + b.setText(b.Document().TextBeforeCursor() + separator + strings.TrimLeft(b.Document().TextAfterCursor(), " ")) + } +} + +// SwapCharactersBeforeCursor swaps the last two characters before the cursor. +func (b *Buffer) SwapCharactersBeforeCursor() { + if b.cursorPosition >= 2 { + x := b.Text()[b.cursorPosition-2 : b.cursorPosition-1] + y := b.Text()[b.cursorPosition-1 : b.cursorPosition] + b.setText(b.Text()[:b.cursorPosition-2] + y + x + b.Text()[b.cursorPosition:]) + } +} + +// NewBuffer is constructor of Buffer struct. +func NewBuffer() (b *Buffer) { + b = &Buffer{ + workingLines: []string{""}, + workingIndex: 0, + preferredColumn: -1, // -1 means nil + } + return +} diff --git a/vendor/github.com/c-bata/go-prompt/completion.go b/vendor/github.com/c-bata/go-prompt/completion.go new file mode 100644 index 000000000..57e82eefc --- /dev/null +++ b/vendor/github.com/c-bata/go-prompt/completion.go @@ -0,0 +1,190 @@ +package prompt + +import ( + "strings" + + "github.com/c-bata/go-prompt/internal/debug" + runewidth "github.com/mattn/go-runewidth" +) + +const ( + shortenSuffix = "..." + leftPrefix = " " + leftSuffix = " " + rightPrefix = " " + rightSuffix = " " +) + +var ( + leftMargin = runewidth.StringWidth(leftPrefix + leftSuffix) + rightMargin = runewidth.StringWidth(rightPrefix + rightSuffix) + completionMargin = leftMargin + rightMargin +) + +// Suggest is printed when completing. +type Suggest struct { + Text string + Description string +} + +// CompletionManager manages which suggestion is now selected. +type CompletionManager struct { + selected int // -1 means nothing one is selected. + tmp []Suggest + max uint16 + completer Completer + + verticalScroll int + wordSeparator string + showAtStart bool +} + +// GetSelectedSuggestion returns the selected item. +func (c *CompletionManager) GetSelectedSuggestion() (s Suggest, ok bool) { + if c.selected == -1 { + return Suggest{}, false + } else if c.selected < -1 { + debug.Assert(false, "must not reach here") + c.selected = -1 + return Suggest{}, false + } + return c.tmp[c.selected], true +} + +// GetSuggestions returns the list of suggestion. +func (c *CompletionManager) GetSuggestions() []Suggest { + return c.tmp +} + +// Reset to select nothing. +func (c *CompletionManager) Reset() { + c.selected = -1 + c.verticalScroll = 0 + c.Update(*NewDocument()) +} + +// Update to update the suggestions. +func (c *CompletionManager) Update(in Document) { + c.tmp = c.completer(in) +} + +// Previous to select the previous suggestion item. +func (c *CompletionManager) Previous() { + if c.verticalScroll == c.selected && c.selected > 0 { + c.verticalScroll-- + } + c.selected-- + c.update() +} + +// Next to select the next suggestion item. +func (c *CompletionManager) Next() { + if c.verticalScroll+int(c.max)-1 == c.selected { + c.verticalScroll++ + } + c.selected++ + c.update() +} + +// Completing returns whether the CompletionManager selects something one. +func (c *CompletionManager) Completing() bool { + return c.selected != -1 +} + +func (c *CompletionManager) update() { + max := int(c.max) + if len(c.tmp) < max { + max = len(c.tmp) + } + + if c.selected >= len(c.tmp) { + c.Reset() + } else if c.selected < -1 { + c.selected = len(c.tmp) - 1 + c.verticalScroll = len(c.tmp) - max + } +} + +func deleteBreakLineCharacters(s string) string { + s = strings.Replace(s, "\n", "", -1) + s = strings.Replace(s, "\r", "", -1) + return s +} + +func formatTexts(o []string, max int, prefix, suffix string) (new []string, width int) { + l := len(o) + n := make([]string, l) + + lenPrefix := runewidth.StringWidth(prefix) + lenSuffix := runewidth.StringWidth(suffix) + lenShorten := runewidth.StringWidth(shortenSuffix) + min := lenPrefix + lenSuffix + lenShorten + for i := 0; i < l; i++ { + o[i] = deleteBreakLineCharacters(o[i]) + + w := runewidth.StringWidth(o[i]) + if width < w { + width = w + } + } + + if width == 0 { + return n, 0 + } + if min >= max { + return n, 0 + } + if lenPrefix+width+lenSuffix > max { + width = max - lenPrefix - lenSuffix + } + + for i := 0; i < l; i++ { + x := runewidth.StringWidth(o[i]) + if x <= width { + spaces := strings.Repeat(" ", width-x) + n[i] = prefix + o[i] + spaces + suffix + } else if x > width { + x := runewidth.Truncate(o[i], width, shortenSuffix) + // When calling runewidth.Truncate("您好xxx您好xxx", 11, "...") returns "您好xxx..." + // But the length of this result is 10. So we need fill right using runewidth.FillRight. + n[i] = prefix + runewidth.FillRight(x, width) + suffix + } + } + return n, lenPrefix + width + lenSuffix +} + +func formatSuggestions(suggests []Suggest, max int) (new []Suggest, width int) { + num := len(suggests) + new = make([]Suggest, num) + + left := make([]string, num) + for i := 0; i < num; i++ { + left[i] = suggests[i].Text + } + right := make([]string, num) + for i := 0; i < num; i++ { + right[i] = suggests[i].Description + } + + left, leftWidth := formatTexts(left, max, leftPrefix, leftSuffix) + if leftWidth == 0 { + return []Suggest{}, 0 + } + right, rightWidth := formatTexts(right, max-leftWidth, rightPrefix, rightSuffix) + + for i := 0; i < num; i++ { + new[i] = Suggest{Text: left[i], Description: right[i]} + } + return new, leftWidth + rightWidth +} + +// NewCompletionManager returns initialized CompletionManager object. +func NewCompletionManager(completer Completer, max uint16) *CompletionManager { + return &CompletionManager{ + selected: -1, + max: max, + completer: completer, + + verticalScroll: 0, + } +} diff --git a/vendor/github.com/c-bata/go-prompt/document.go b/vendor/github.com/c-bata/go-prompt/document.go new file mode 100644 index 000000000..2a47f52bb --- /dev/null +++ b/vendor/github.com/c-bata/go-prompt/document.go @@ -0,0 +1,441 @@ +package prompt + +import ( + "strings" + "unicode/utf8" + + "github.com/c-bata/go-prompt/internal/bisect" + istrings "github.com/c-bata/go-prompt/internal/strings" + runewidth "github.com/mattn/go-runewidth" +) + +// Document has text displayed in terminal and cursor position. +type Document struct { + Text string + // This represents a index in a rune array of Document.Text. + // So if Document is "日本(cursor)語", cursorPosition is 2. + // But DisplayedCursorPosition returns 4 because '日' and '本' are double width characters. + cursorPosition int + lastKey Key +} + +// NewDocument return the new empty document. +func NewDocument() *Document { + return &Document{ + Text: "", + cursorPosition: 0, + } +} + +// LastKeyStroke return the last key pressed in this document. +func (d *Document) LastKeyStroke() Key { + return d.lastKey +} + +// DisplayCursorPosition returns the cursor position on rendered text on terminal emulators. +// So if Document is "日本(cursor)語", DisplayedCursorPosition returns 4 because '日' and '本' are double width characters. +func (d *Document) DisplayCursorPosition() int { + var position int + runes := []rune(d.Text)[:d.cursorPosition] + for i := range runes { + position += runewidth.RuneWidth(runes[i]) + } + return position +} + +// GetCharRelativeToCursor return character relative to cursor position, or empty string +func (d *Document) GetCharRelativeToCursor(offset int) (r rune) { + s := d.Text + cnt := 0 + + for len(s) > 0 { + cnt++ + r, size := utf8.DecodeRuneInString(s) + if cnt == d.cursorPosition+offset { + return r + } + s = s[size:] + } + return 0 +} + +// TextBeforeCursor returns the text before the cursor. +func (d *Document) TextBeforeCursor() string { + r := []rune(d.Text) + return string(r[:d.cursorPosition]) +} + +// TextAfterCursor returns the text after the cursor. +func (d *Document) TextAfterCursor() string { + r := []rune(d.Text) + return string(r[d.cursorPosition:]) +} + +// GetWordBeforeCursor returns the word before the cursor. +// If we have whitespace before the cursor this returns an empty string. +func (d *Document) GetWordBeforeCursor() string { + x := d.TextBeforeCursor() + return x[d.FindStartOfPreviousWord():] +} + +// GetWordAfterCursor returns the word after the cursor. +// If we have whitespace after the cursor this returns an empty string. +func (d *Document) GetWordAfterCursor() string { + x := d.TextAfterCursor() + return x[:d.FindEndOfCurrentWord()] +} + +// GetWordBeforeCursorWithSpace returns the word before the cursor. +// Unlike GetWordBeforeCursor, it returns string containing space +func (d *Document) GetWordBeforeCursorWithSpace() string { + x := d.TextBeforeCursor() + return x[d.FindStartOfPreviousWordWithSpace():] +} + +// GetWordAfterCursorWithSpace returns the word after the cursor. +// Unlike GetWordAfterCursor, it returns string containing space +func (d *Document) GetWordAfterCursorWithSpace() string { + x := d.TextAfterCursor() + return x[:d.FindEndOfCurrentWordWithSpace()] +} + +// GetWordBeforeCursorUntilSeparator returns the text before the cursor until next separator. +func (d *Document) GetWordBeforeCursorUntilSeparator(sep string) string { + x := d.TextBeforeCursor() + return x[d.FindStartOfPreviousWordUntilSeparator(sep):] +} + +// GetWordAfterCursorUntilSeparator returns the text after the cursor until next separator. +func (d *Document) GetWordAfterCursorUntilSeparator(sep string) string { + x := d.TextAfterCursor() + return x[:d.FindEndOfCurrentWordUntilSeparator(sep)] +} + +// GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor returns the word before the cursor. +// Unlike GetWordBeforeCursor, it returns string containing space +func (d *Document) GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(sep string) string { + x := d.TextBeforeCursor() + return x[d.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(sep):] +} + +// GetWordAfterCursorUntilSeparatorIgnoreNextToCursor returns the word after the cursor. +// Unlike GetWordAfterCursor, it returns string containing space +func (d *Document) GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(sep string) string { + x := d.TextAfterCursor() + return x[:d.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(sep)] +} + +// FindStartOfPreviousWord returns an index relative to the cursor position +// pointing to the start of the previous word. Return 0 if nothing was found. +func (d *Document) FindStartOfPreviousWord() int { + x := d.TextBeforeCursor() + i := strings.LastIndexByte(x, ' ') + if i != -1 { + return i + 1 + } + return 0 +} + +// FindStartOfPreviousWordWithSpace is almost the same as FindStartOfPreviousWord. +// The only difference is to ignore contiguous spaces. +func (d *Document) FindStartOfPreviousWordWithSpace() int { + x := d.TextBeforeCursor() + end := istrings.LastIndexNotByte(x, ' ') + if end == -1 { + return 0 + } + + start := strings.LastIndexByte(x[:end], ' ') + if start == -1 { + return 0 + } + return start + 1 +} + +// FindStartOfPreviousWordUntilSeparator is almost the same as FindStartOfPreviousWord. +// But this can specify Separator. Return 0 if nothing was found. +func (d *Document) FindStartOfPreviousWordUntilSeparator(sep string) int { + if sep == "" { + return d.FindStartOfPreviousWord() + } + + x := d.TextBeforeCursor() + i := strings.LastIndexAny(x, sep) + if i != -1 { + return i + 1 + } + return 0 +} + +// FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor is almost the same as FindStartOfPreviousWordWithSpace. +// But this can specify Separator. Return 0 if nothing was found. +func (d *Document) FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(sep string) int { + if sep == "" { + return d.FindStartOfPreviousWordWithSpace() + } + + x := d.TextBeforeCursor() + end := istrings.LastIndexNotAny(x, sep) + if end == -1 { + return 0 + } + start := strings.LastIndexAny(x[:end], sep) + if start == -1 { + return 0 + } + return start + 1 +} + +// FindEndOfCurrentWord returns an index relative to the cursor position. +// pointing to the end of the current word. Return 0 if nothing was found. +func (d *Document) FindEndOfCurrentWord() int { + x := d.TextAfterCursor() + i := strings.IndexByte(x, ' ') + if i != -1 { + return i + } + return len(x) +} + +// FindEndOfCurrentWordWithSpace is almost the same as FindEndOfCurrentWord. +// The only difference is to ignore contiguous spaces. +func (d *Document) FindEndOfCurrentWordWithSpace() int { + x := d.TextAfterCursor() + + start := istrings.IndexNotByte(x, ' ') + if start == -1 { + return len(x) + } + + end := strings.IndexByte(x[start:], ' ') + if end == -1 { + return len(x) + } + + return start + end +} + +// FindEndOfCurrentWordUntilSeparator is almost the same as FindEndOfCurrentWord. +// But this can specify Separator. Return 0 if nothing was found. +func (d *Document) FindEndOfCurrentWordUntilSeparator(sep string) int { + if sep == "" { + return d.FindEndOfCurrentWord() + } + + x := d.TextAfterCursor() + i := strings.IndexAny(x, sep) + if i != -1 { + return i + } + return len(x) +} + +// FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor is almost the same as FindEndOfCurrentWordWithSpace. +// But this can specify Separator. Return 0 if nothing was found. +func (d *Document) FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(sep string) int { + if sep == "" { + return d.FindEndOfCurrentWordWithSpace() + } + + x := d.TextAfterCursor() + + start := istrings.IndexNotAny(x, sep) + if start == -1 { + return len(x) + } + + end := strings.IndexAny(x[start:], sep) + if end == -1 { + return len(x) + } + + return start + end +} + +// CurrentLineBeforeCursor returns the text from the start of the line until the cursor. +func (d *Document) CurrentLineBeforeCursor() string { + s := strings.Split(d.TextBeforeCursor(), "\n") + return s[len(s)-1] +} + +// CurrentLineAfterCursor returns the text from the cursor until the end of the line. +func (d *Document) CurrentLineAfterCursor() string { + return strings.Split(d.TextAfterCursor(), "\n")[0] +} + +// CurrentLine return the text on the line where the cursor is. (when the input +// consists of just one line, it equals `text`. +func (d *Document) CurrentLine() string { + return d.CurrentLineBeforeCursor() + d.CurrentLineAfterCursor() +} + +// Array pointing to the start indexes of all the lines. +func (d *Document) lineStartIndexes() []int { + // TODO: Cache, because this is often reused. + // (If it is used, it's often used many times. + // And this has to be fast for editing big documents!) + lc := d.LineCount() + lengths := make([]int, lc) + for i, l := range d.Lines() { + lengths[i] = len(l) + } + + // Calculate cumulative sums. + indexes := make([]int, lc+1) + indexes[0] = 0 // https://github.com/jonathanslenders/python-prompt-toolkit/blob/master/prompt_toolkit/document.py#L189 + pos := 0 + for i, l := range lengths { + pos += l + 1 + indexes[i+1] = pos + } + if lc > 1 { + // Pop the last item. (This is not a new line.) + indexes = indexes[:lc] + } + return indexes +} + +// For the index of a character at a certain line, calculate the index of +// the first character on that line. +func (d *Document) findLineStartIndex(index int) (pos int, lineStartIndex int) { + indexes := d.lineStartIndexes() + pos = bisect.Right(indexes, index) - 1 + lineStartIndex = indexes[pos] + return +} + +// CursorPositionRow returns the current row. (0-based.) +func (d *Document) CursorPositionRow() (row int) { + row, _ = d.findLineStartIndex(d.cursorPosition) + return +} + +// CursorPositionCol returns the current column. (0-based.) +func (d *Document) CursorPositionCol() (col int) { + // Don't use self.text_before_cursor to calculate this. Creating substrings + // and splitting is too expensive for getting the cursor position. + _, index := d.findLineStartIndex(d.cursorPosition) + col = d.cursorPosition - index + return +} + +// GetCursorLeftPosition returns the relative position for cursor left. +func (d *Document) GetCursorLeftPosition(count int) int { + if count < 0 { + return d.GetCursorRightPosition(-count) + } + if d.CursorPositionCol() > count { + return -count + } + return -d.CursorPositionCol() +} + +// GetCursorRightPosition returns relative position for cursor right. +func (d *Document) GetCursorRightPosition(count int) int { + if count < 0 { + return d.GetCursorLeftPosition(-count) + } + if len(d.CurrentLineAfterCursor()) > count { + return count + } + return len(d.CurrentLineAfterCursor()) +} + +// GetCursorUpPosition return the relative cursor position (character index) where we would be +// if the user pressed the arrow-up button. +func (d *Document) GetCursorUpPosition(count int, preferredColumn int) int { + var col int + if preferredColumn == -1 { // -1 means nil + col = d.CursorPositionCol() + } else { + col = preferredColumn + } + + row := d.CursorPositionRow() - count + if row < 0 { + row = 0 + } + return d.TranslateRowColToIndex(row, col) - d.cursorPosition +} + +// GetCursorDownPosition return the relative cursor position (character index) where we would be if the +// user pressed the arrow-down button. +func (d *Document) GetCursorDownPosition(count int, preferredColumn int) int { + var col int + if preferredColumn == -1 { // -1 means nil + col = d.CursorPositionCol() + } else { + col = preferredColumn + } + row := d.CursorPositionRow() + count + return d.TranslateRowColToIndex(row, col) - d.cursorPosition +} + +// Lines returns the array of all the lines. +func (d *Document) Lines() []string { + // TODO: Cache, because this one is reused very often. + return strings.Split(d.Text, "\n") +} + +// LineCount return the number of lines in this document. If the document ends +// with a trailing \n, that counts as the beginning of a new line. +func (d *Document) LineCount() int { + return len(d.Lines()) +} + +// TranslateIndexToPosition given an index for the text, return the corresponding (row, col) tuple. +// (0-based. Returns (0, 0) for index=0.) +func (d *Document) TranslateIndexToPosition(index int) (row int, col int) { + row, rowIndex := d.findLineStartIndex(index) + col = index - rowIndex + return +} + +// TranslateRowColToIndex given a (row, col), return the corresponding index. +// (Row and col params are 0-based.) +func (d *Document) TranslateRowColToIndex(row int, column int) (index int) { + indexes := d.lineStartIndexes() + if row < 0 { + row = 0 + } else if row > len(indexes) { + row = len(indexes) - 1 + } + index = indexes[row] + line := d.Lines()[row] + + // python) result += max(0, min(col, len(line))) + if column > 0 || len(line) > 0 { + if column > len(line) { + index += len(line) + } else { + index += column + } + } + + // Keep in range. (len(self.text) is included, because the cursor can be + // right after the end of the text as well.) + // python) result = max(0, min(result, len(self.text))) + if index > len(d.Text) { + index = len(d.Text) + } + if index < 0 { + index = 0 + } + return index +} + +// OnLastLine returns true when we are at the last line. +func (d *Document) OnLastLine() bool { + return d.CursorPositionRow() == (d.LineCount() - 1) +} + +// GetEndOfLinePosition returns relative position for the end of this line. +func (d *Document) GetEndOfLinePosition() int { + return len([]rune(d.CurrentLineAfterCursor())) +} + +func (d *Document) leadingWhitespaceInCurrentLine() (margin string) { + trimmed := strings.TrimSpace(d.CurrentLine()) + margin = d.CurrentLine()[:len(d.CurrentLine())-len(trimmed)] + return +} diff --git a/vendor/github.com/c-bata/go-prompt/emacs.go b/vendor/github.com/c-bata/go-prompt/emacs.go new file mode 100644 index 000000000..632f96321 --- /dev/null +++ b/vendor/github.com/c-bata/go-prompt/emacs.go @@ -0,0 +1,120 @@ +package prompt + +import "github.com/c-bata/go-prompt/internal/debug" + +/* + +======== +PROGRESS +======== + +Moving the cursor +----------------- + +* [x] Ctrl + a Go to the beginning of the line (Home) +* [x] Ctrl + e Go to the End of the line (End) +* [x] Ctrl + p Previous command (Up arrow) +* [x] Ctrl + n Next command (Down arrow) +* [x] Ctrl + f Forward one character +* [x] Ctrl + b Backward one character +* [x] Ctrl + xx Toggle between the start of line and current cursor position + +Editing +------- + +* [x] Ctrl + L Clear the Screen, similar to the clear command +* [x] Ctrl + d Delete character under the cursor +* [x] Ctrl + h Delete character before the cursor (Backspace) + +* [x] Ctrl + w Cut the Word before the cursor to the clipboard. +* [x] Ctrl + k Cut the Line after the cursor to the clipboard. +* [x] Ctrl + u Cut/delete the Line before the cursor to the clipboard. + +* [ ] Ctrl + t Swap the last two characters before the cursor (typo). +* [ ] Esc + t Swap the last two words before the cursor. + +* [ ] ctrl + y Paste the last thing to be cut (yank) +* [ ] ctrl + _ Undo + +*/ + +var emacsKeyBindings = []KeyBind{ + // Go to the End of the line + { + Key: ControlE, + Fn: func(buf *Buffer) { + x := []rune(buf.Document().TextAfterCursor()) + buf.CursorRight(len(x)) + }, + }, + // Go to the beginning of the line + { + Key: ControlA, + Fn: func(buf *Buffer) { + x := []rune(buf.Document().TextBeforeCursor()) + buf.CursorLeft(len(x)) + }, + }, + // Cut the Line after the cursor + { + Key: ControlK, + Fn: func(buf *Buffer) { + x := []rune(buf.Document().TextAfterCursor()) + buf.Delete(len(x)) + }, + }, + // Cut/delete the Line before the cursor + { + Key: ControlU, + Fn: func(buf *Buffer) { + x := []rune(buf.Document().TextBeforeCursor()) + buf.DeleteBeforeCursor(len(x)) + }, + }, + // Delete character under the cursor + { + Key: ControlD, + Fn: func(buf *Buffer) { + if buf.Text() != "" { + buf.Delete(1) + } + }, + }, + // Backspace + { + Key: ControlH, + Fn: func(buf *Buffer) { + buf.DeleteBeforeCursor(1) + }, + }, + // Right allow: Forward one character + { + Key: ControlF, + Fn: func(buf *Buffer) { + buf.CursorRight(1) + }, + }, + // Left allow: Backward one character + { + Key: ControlB, + Fn: func(buf *Buffer) { + buf.CursorLeft(1) + }, + }, + // Cut the Word before the cursor. + { + Key: ControlW, + Fn: func(buf *Buffer) { + buf.DeleteBeforeCursor(len([]rune(buf.Document().GetWordBeforeCursorWithSpace()))) + }, + }, + // Clear the Screen, similar to the clear command + { + Key: ControlL, + Fn: func(buf *Buffer) { + consoleWriter.EraseScreen() + consoleWriter.CursorGoTo(0, 0) + debug.AssertNoError(consoleWriter.Flush()) + }, + }, +} diff --git a/vendor/github.com/c-bata/go-prompt/filter.go b/vendor/github.com/c-bata/go-prompt/filter.go new file mode 100644 index 000000000..61c17ed7f --- /dev/null +++ b/vendor/github.com/c-bata/go-prompt/filter.go @@ -0,0 +1,71 @@ +package prompt + +import "strings" + +// Filter is the type to filter the prompt.Suggestion array. +type Filter func([]Suggest, string, bool) []Suggest + +// FilterHasPrefix checks whether the string completions.Text begins with sub. +func FilterHasPrefix(completions []Suggest, sub string, ignoreCase bool) []Suggest { + return filterSuggestions(completions, sub, ignoreCase, strings.HasPrefix) +} + +// FilterHasSuffix checks whether the completion.Text ends with sub. +func FilterHasSuffix(completions []Suggest, sub string, ignoreCase bool) []Suggest { + return filterSuggestions(completions, sub, ignoreCase, strings.HasSuffix) +} + +// FilterContains checks whether the completion.Text contains sub. +func FilterContains(completions []Suggest, sub string, ignoreCase bool) []Suggest { + return filterSuggestions(completions, sub, ignoreCase, strings.Contains) +} + +// FilterFuzzy checks whether the completion.Text fuzzy matches sub. +// Fuzzy searching for "dog" is equivalent to "*d*o*g*". This search term +// would match, for example, "Good food is gone" +// ^ ^ ^ +func FilterFuzzy(completions []Suggest, sub string, ignoreCase bool) []Suggest { + return filterSuggestions(completions, sub, ignoreCase, fuzzyMatch) +} + +func fuzzyMatch(s, sub string) bool { + sChars := []rune(s) + sIdx := 0 + + // https://staticcheck.io/docs/checks#S1029 + for _, c := range sub { + found := false + for ; sIdx < len(sChars); sIdx++ { + if sChars[sIdx] == c { + found = true + sIdx++ + break + } + } + if !found { + return false + } + } + return true +} + +func filterSuggestions(suggestions []Suggest, sub string, ignoreCase bool, function func(string, string) bool) []Suggest { + if sub == "" { + return suggestions + } + if ignoreCase { + sub = strings.ToUpper(sub) + } + + ret := make([]Suggest, 0, len(suggestions)) + for i := range suggestions { + c := suggestions[i].Text + if ignoreCase { + c = strings.ToUpper(c) + } + if function(c, sub) { + ret = append(ret, suggestions[i]) + } + } + return ret +} diff --git a/vendor/github.com/c-bata/go-prompt/history.go b/vendor/github.com/c-bata/go-prompt/history.go new file mode 100644 index 000000000..e75c64592 --- /dev/null +++ b/vendor/github.com/c-bata/go-prompt/history.go @@ -0,0 +1,61 @@ +package prompt + +// History stores the texts that are entered. +type History struct { + histories []string + tmp []string + selected int +} + +// Add to add text in history. +func (h *History) Add(input string) { + h.histories = append(h.histories, input) + h.Clear() +} + +// Clear to clear the history. +func (h *History) Clear() { + h.tmp = make([]string, len(h.histories)) + for i := range h.histories { + h.tmp[i] = h.histories[i] + } + h.tmp = append(h.tmp, "") + h.selected = len(h.tmp) - 1 +} + +// Older saves a buffer of current line and get a buffer of previous line by up-arrow. +// The changes of line buffers are stored until new history is created. +func (h *History) Older(buf *Buffer) (new *Buffer, changed bool) { + if len(h.tmp) == 1 || h.selected == 0 { + return buf, false + } + h.tmp[h.selected] = buf.Text() + + h.selected-- + new = NewBuffer() + new.InsertText(h.tmp[h.selected], false, true) + return new, true +} + +// Newer saves a buffer of current line and get a buffer of next line by up-arrow. +// The changes of line buffers are stored until new history is created. +func (h *History) Newer(buf *Buffer) (new *Buffer, changed bool) { + if h.selected >= len(h.tmp)-1 { + return buf, false + } + h.tmp[h.selected] = buf.Text() + + h.selected++ + new = NewBuffer() + new.InsertText(h.tmp[h.selected], false, true) + return new, true +} + +// NewHistory returns new history object. +func NewHistory() *History { + return &History{ + histories: []string{}, + tmp: []string{""}, + selected: 0, + } +} diff --git a/vendor/github.com/c-bata/go-prompt/input.go b/vendor/github.com/c-bata/go-prompt/input.go new file mode 100644 index 000000000..307e74719 --- /dev/null +++ b/vendor/github.com/c-bata/go-prompt/input.go @@ -0,0 +1,169 @@ +package prompt + +import "bytes" + +// WinSize represents the width and height of terminal. +type WinSize struct { + Row uint16 + Col uint16 +} + +// ConsoleParser is an interface to abstract input layer. +type ConsoleParser interface { + // Setup should be called before starting input + Setup() error + // TearDown should be called after stopping input + TearDown() error + // GetWinSize returns WinSize object to represent width and height of terminal. + GetWinSize() *WinSize + // Read returns byte array. + Read() ([]byte, error) +} + +// GetKey returns Key correspond to input byte codes. +func GetKey(b []byte) Key { + for _, k := range ASCIISequences { + if bytes.Equal(k.ASCIICode, b) { + return k.Key + } + } + return NotDefined +} + +// ASCIISequences holds mappings of the key and byte array. +var ASCIISequences = []*ASCIICode{ + {Key: Escape, ASCIICode: []byte{0x1b}}, + + {Key: ControlSpace, ASCIICode: []byte{0x00}}, + {Key: ControlA, ASCIICode: []byte{0x1}}, + {Key: ControlB, ASCIICode: []byte{0x2}}, + {Key: ControlC, ASCIICode: []byte{0x3}}, + {Key: ControlD, ASCIICode: []byte{0x4}}, + {Key: ControlE, ASCIICode: []byte{0x5}}, + {Key: ControlF, ASCIICode: []byte{0x6}}, + {Key: ControlG, ASCIICode: []byte{0x7}}, + {Key: ControlH, ASCIICode: []byte{0x8}}, + //{Key: ControlI, ASCIICode: []byte{0x9}}, + //{Key: ControlJ, ASCIICode: []byte{0xa}}, + {Key: ControlK, ASCIICode: []byte{0xb}}, + {Key: ControlL, ASCIICode: []byte{0xc}}, + {Key: ControlM, ASCIICode: []byte{0xd}}, + {Key: ControlN, ASCIICode: []byte{0xe}}, + {Key: ControlO, ASCIICode: []byte{0xf}}, + {Key: ControlP, ASCIICode: []byte{0x10}}, + {Key: ControlQ, ASCIICode: []byte{0x11}}, + {Key: ControlR, ASCIICode: []byte{0x12}}, + {Key: ControlS, ASCIICode: []byte{0x13}}, + {Key: ControlT, ASCIICode: []byte{0x14}}, + {Key: ControlU, ASCIICode: []byte{0x15}}, + {Key: ControlV, ASCIICode: []byte{0x16}}, + {Key: ControlW, ASCIICode: []byte{0x17}}, + {Key: ControlX, ASCIICode: []byte{0x18}}, + {Key: ControlY, ASCIICode: []byte{0x19}}, + {Key: ControlZ, ASCIICode: []byte{0x1a}}, + + {Key: ControlBackslash, ASCIICode: []byte{0x1c}}, + {Key: ControlSquareClose, ASCIICode: []byte{0x1d}}, + {Key: ControlCircumflex, ASCIICode: []byte{0x1e}}, + {Key: ControlUnderscore, ASCIICode: []byte{0x1f}}, + {Key: Backspace, ASCIICode: []byte{0x7f}}, + + {Key: Up, ASCIICode: []byte{0x1b, 0x5b, 0x41}}, + {Key: Down, ASCIICode: []byte{0x1b, 0x5b, 0x42}}, + {Key: Right, ASCIICode: []byte{0x1b, 0x5b, 0x43}}, + {Key: Left, ASCIICode: []byte{0x1b, 0x5b, 0x44}}, + {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x48}}, + {Key: Home, ASCIICode: []byte{0x1b, 0x30, 0x48}}, + {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x46}}, + {Key: End, ASCIICode: []byte{0x1b, 0x30, 0x46}}, + + {Key: Enter, ASCIICode: []byte{0xa}}, + {Key: Delete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x7e}}, + {Key: ShiftDelete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x3b, 0x32, 0x7e}}, + {Key: ControlDelete, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x3b, 0x35, 0x7e}}, + {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x7e}}, + {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x34, 0x7e}}, + {Key: PageUp, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x7e}}, + {Key: PageDown, ASCIICode: []byte{0x1b, 0x5b, 0x36, 0x7e}}, + {Key: Home, ASCIICode: []byte{0x1b, 0x5b, 0x37, 0x7e}}, + {Key: End, ASCIICode: []byte{0x1b, 0x5b, 0x38, 0x7e}}, + {Key: Tab, ASCIICode: []byte{0x9}}, + {Key: BackTab, ASCIICode: []byte{0x1b, 0x5b, 0x5a}}, + {Key: Insert, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x7e}}, + + {Key: F1, ASCIICode: []byte{0x1b, 0x4f, 0x50}}, + {Key: F2, ASCIICode: []byte{0x1b, 0x4f, 0x51}}, + {Key: F3, ASCIICode: []byte{0x1b, 0x4f, 0x52}}, + {Key: F4, ASCIICode: []byte{0x1b, 0x4f, 0x53}}, + + {Key: F1, ASCIICode: []byte{0x1b, 0x4f, 0x50, 0x41}}, // Linux console + {Key: F2, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x42}}, // Linux console + {Key: F3, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x43}}, // Linux console + {Key: F4, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x44}}, // Linux console + {Key: F5, ASCIICode: []byte{0x1b, 0x5b, 0x5b, 0x45}}, // Linux console + + {Key: F1, ASCIICode: []byte{0x1b, 0x5b, 0x11, 0x7e}}, // rxvt-unicode + {Key: F2, ASCIICode: []byte{0x1b, 0x5b, 0x12, 0x7e}}, // rxvt-unicode + {Key: F3, ASCIICode: []byte{0x1b, 0x5b, 0x13, 0x7e}}, // rxvt-unicode + {Key: F4, ASCIICode: []byte{0x1b, 0x5b, 0x14, 0x7e}}, // rxvt-unicode + + {Key: F5, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x35, 0x7e}}, + {Key: F6, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x37, 0x7e}}, + {Key: F7, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x38, 0x7e}}, + {Key: F8, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x39, 0x7e}}, + {Key: F9, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x30, 0x7e}}, + {Key: F10, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x31, 0x7e}}, + {Key: F11, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x32, 0x7e}}, + {Key: F12, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x34, 0x7e, 0x8}}, + {Key: F13, ASCIICode: []byte{0x1b, 0x5b, 0x25, 0x7e}}, + {Key: F14, ASCIICode: []byte{0x1b, 0x5b, 0x26, 0x7e}}, + {Key: F15, ASCIICode: []byte{0x1b, 0x5b, 0x28, 0x7e}}, + {Key: F16, ASCIICode: []byte{0x1b, 0x5b, 0x29, 0x7e}}, + {Key: F17, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x7e}}, + {Key: F18, ASCIICode: []byte{0x1b, 0x5b, 0x32, 0x7e}}, + {Key: F19, ASCIICode: []byte{0x1b, 0x5b, 0x33, 0x7e}}, + {Key: F20, ASCIICode: []byte{0x1b, 0x5b, 0x34, 0x7e}}, + + // Xterm + {Key: F13, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x50}}, + {Key: F14, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x51}}, + // &ASCIICode{Key: F15, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x52}}, // Conflicts with CPR response + {Key: F16, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x52}}, + {Key: F17, ASCIICode: []byte{0x1b, 0x5b, 0x15, 0x3b, 0x32, 0x7e}}, + {Key: F18, ASCIICode: []byte{0x1b, 0x5b, 0x17, 0x3b, 0x32, 0x7e}}, + {Key: F19, ASCIICode: []byte{0x1b, 0x5b, 0x18, 0x3b, 0x32, 0x7e}}, + {Key: F20, ASCIICode: []byte{0x1b, 0x5b, 0x19, 0x3b, 0x32, 0x7e}}, + {Key: F21, ASCIICode: []byte{0x1b, 0x5b, 0x20, 0x3b, 0x32, 0x7e}}, + {Key: F22, ASCIICode: []byte{0x1b, 0x5b, 0x21, 0x3b, 0x32, 0x7e}}, + {Key: F23, ASCIICode: []byte{0x1b, 0x5b, 0x23, 0x3b, 0x32, 0x7e}}, + {Key: F24, ASCIICode: []byte{0x1b, 0x5b, 0x24, 0x3b, 0x32, 0x7e}}, + + {Key: ControlUp, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x41}}, + {Key: ControlDown, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x42}}, + {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x43}}, + {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x35, 0x44}}, + + {Key: ShiftUp, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x41}}, + {Key: ShiftDown, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x42}}, + {Key: ShiftRight, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x43}}, + {Key: ShiftLeft, ASCIICode: []byte{0x1b, 0x5b, 0x31, 0x3b, 0x32, 0x44}}, + + // Tmux sends following keystrokes when control+arrow is pressed, but for + // Emacs ansi-term sends the same sequences for normal arrow keys. Consider + // it a normal arrow press, because that's more important. + {Key: Up, ASCIICode: []byte{0x1b, 0x4f, 0x41}}, + {Key: Down, ASCIICode: []byte{0x1b, 0x4f, 0x42}}, + {Key: Right, ASCIICode: []byte{0x1b, 0x4f, 0x43}}, + {Key: Left, ASCIICode: []byte{0x1b, 0x4f, 0x44}}, + + {Key: ControlUp, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x41}}, + {Key: ControlDown, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x42}}, + {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x43}}, + {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x35, 0x44}}, + + {Key: ControlRight, ASCIICode: []byte{0x1b, 0x5b, 0x4f, 0x63}}, // rxvt + {Key: ControlLeft, ASCIICode: []byte{0x1b, 0x5b, 0x4f, 0x64}}, // rxvt + + {Key: Ignore, ASCIICode: []byte{0x1b, 0x5b, 0x45}}, // Xterm + {Key: Ignore, ASCIICode: []byte{0x1b, 0x5b, 0x46}}, // Linux console +} diff --git a/vendor/github.com/c-bata/go-prompt/input_posix.go b/vendor/github.com/c-bata/go-prompt/input_posix.go new file mode 100644 index 000000000..f10430318 --- /dev/null +++ b/vendor/github.com/c-bata/go-prompt/input_posix.go @@ -0,0 +1,77 @@ +// +build !windows + +package prompt + +import ( + "syscall" + + "github.com/c-bata/go-prompt/internal/term" + "golang.org/x/sys/unix" +) + +const maxReadBytes = 1024 + +// PosixParser is a ConsoleParser implementation for POSIX environment. +type PosixParser struct { + fd int + origTermios syscall.Termios +} + +// Setup should be called before starting input +func (t *PosixParser) Setup() error { + // Set NonBlocking mode because if syscall.Read block this goroutine, it cannot receive data from stopCh. + if err := syscall.SetNonblock(t.fd, true); err != nil { + return err + } + if err := term.SetRaw(t.fd); err != nil { + return err + } + return nil +} + +// TearDown should be called after stopping input +func (t *PosixParser) TearDown() error { + if err := syscall.SetNonblock(t.fd, false); err != nil { + return err + } + if err := term.Restore(); err != nil { + return err + } + return nil +} + +// Read returns byte array. +func (t *PosixParser) Read() ([]byte, error) { + buf := make([]byte, maxReadBytes) + n, err := syscall.Read(t.fd, buf) + if err != nil { + return []byte{}, err + } + return buf[:n], nil +} + +// GetWinSize returns WinSize object to represent width and height of terminal. +func (t *PosixParser) GetWinSize() *WinSize { + ws, err := unix.IoctlGetWinsize(t.fd, unix.TIOCGWINSZ) + if err != nil { + panic(err) + } + return &WinSize{ + Row: ws.Row, + Col: ws.Col, + } +} + +var _ ConsoleParser = &PosixParser{} + +// NewStandardInputParser returns ConsoleParser object to read from stdin. +func NewStandardInputParser() *PosixParser { + in, err := syscall.Open("/dev/tty", syscall.O_RDONLY, 0) + if err != nil { + panic(err) + } + + return &PosixParser{ + fd: in, + } +} diff --git a/vendor/github.com/c-bata/go-prompt/input_windows.go b/vendor/github.com/c-bata/go-prompt/input_windows.go new file mode 100644 index 000000000..11b7679d4 --- /dev/null +++ b/vendor/github.com/c-bata/go-prompt/input_windows.go @@ -0,0 +1,83 @@ +// +build windows + +package prompt + +import ( + "errors" + "syscall" + "unicode/utf8" + "unsafe" + + tty "github.com/mattn/go-tty" +) + +const maxReadBytes = 1024 + +var kernel32 = syscall.NewLazyDLL("kernel32.dll") + +var procGetNumberOfConsoleInputEvents = kernel32.NewProc("GetNumberOfConsoleInputEvents") + +// WindowsParser is a ConsoleParser implementation for Win32 console. +type WindowsParser struct { + tty *tty.TTY +} + +// Setup should be called before starting input +func (p *WindowsParser) Setup() error { + t, err := tty.Open() + if err != nil { + return err + } + p.tty = t + return nil +} + +// TearDown should be called after stopping input +func (p *WindowsParser) TearDown() error { + return p.tty.Close() +} + +// Read returns byte array. +func (p *WindowsParser) Read() ([]byte, error) { + var ev uint32 + r0, _, err := procGetNumberOfConsoleInputEvents.Call(p.tty.Input().Fd(), uintptr(unsafe.Pointer(&ev))) + if r0 == 0 { + return nil, err + } + if ev == 0 { + return nil, errors.New("EAGAIN") + } + + r, err := p.tty.ReadRune() + if err != nil { + return nil, err + } + + buf := make([]byte, maxReadBytes) + n := utf8.EncodeRune(buf[:], r) + for p.tty.Buffered() && n < maxReadBytes { + r, err := p.tty.ReadRune() + if err != nil { + break + } + n += utf8.EncodeRune(buf[n:], r) + } + return buf[:n], nil +} + +// GetWinSize returns WinSize object to represent width and height of terminal. +func (p *WindowsParser) GetWinSize() *WinSize { + w, h, err := p.tty.Size() + if err != nil { + panic(err) + } + return &WinSize{ + Row: uint16(h), + Col: uint16(w), + } +} + +// NewStandardInputParser returns ConsoleParser object to read from stdin. +func NewStandardInputParser() *WindowsParser { + return &WindowsParser{} +} diff --git a/vendor/github.com/c-bata/go-prompt/internal/bisect/bisect.go b/vendor/github.com/c-bata/go-prompt/internal/bisect/bisect.go new file mode 100644 index 000000000..efe162fa8 --- /dev/null +++ b/vendor/github.com/c-bata/go-prompt/internal/bisect/bisect.go @@ -0,0 +1,15 @@ +package bisect + +import "sort" + +// Right to locate the insertion point for v in a to maintain sorted order. +func Right(a []int, v int) int { + return bisectRightRange(a, v, 0, len(a)) +} + +func bisectRightRange(a []int, v int, lo, hi int) int { + s := a[lo:hi] + return sort.Search(len(s), func(i int) bool { + return s[i] > v + }) +} diff --git a/vendor/github.com/c-bata/go-prompt/internal/debug/assert.go b/vendor/github.com/c-bata/go-prompt/internal/debug/assert.go new file mode 100644 index 000000000..56f648ac9 --- /dev/null +++ b/vendor/github.com/c-bata/go-prompt/internal/debug/assert.go @@ -0,0 +1,55 @@ +package debug + +import ( + "fmt" + "os" +) + +const ( + envAssertPanic = "GO_PROMPT_ENABLE_ASSERT" +) + +var ( + enableAssert bool +) + +func init() { + if e := os.Getenv(envAssertPanic); e == "true" || e == "1" { + enableAssert = true + } +} + +// Assert ensures expected condition. +func Assert(cond bool, msg interface{}) { + if cond { + return + } + if enableAssert { + panic(msg) + } + writeWithSync(2, "[ASSERT] "+toString(msg)) +} + +func toString(v interface{}) string { + switch a := v.(type) { + case func() string: + return a() + case string: + return a + case fmt.Stringer: + return a.String() + default: + return fmt.Sprintf("unexpected type, %t", v) + } +} + +// AssertNoError ensures err is nil. +func AssertNoError(err error) { + if err == nil { + return + } + if enableAssert { + panic(err) + } + writeWithSync(2, "[ASSERT] "+err.Error()) +} diff --git a/vendor/github.com/c-bata/go-prompt/internal/debug/log.go b/vendor/github.com/c-bata/go-prompt/internal/debug/log.go new file mode 100644 index 000000000..516378627 --- /dev/null +++ b/vendor/github.com/c-bata/go-prompt/internal/debug/log.go @@ -0,0 +1,52 @@ +package debug + +import ( + "io/ioutil" + "log" + "os" +) + +const ( + envEnableLog = "GO_PROMPT_ENABLE_LOG" + logFileName = "go-prompt.log" +) + +var ( + logfile *os.File + logger *log.Logger +) + +func init() { + if e := os.Getenv(envEnableLog); e == "true" || e == "1" { + var err error + logfile, err = os.OpenFile(logFileName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666) + if err == nil { + logger = log.New(logfile, "", log.Llongfile) + return + } + } + logger = log.New(ioutil.Discard, "", log.Llongfile) +} + +// Teardown to close logfile +func Teardown() { + if logfile == nil { + return + } + _ = logfile.Close() +} + +func writeWithSync(calldepth int, msg string) { + calldepth++ + if logfile == nil { + return + } + _ = logger.Output(calldepth, msg) + _ = logfile.Sync() // immediately write msg +} + +// Log to output message +func Log(msg string) { + calldepth := 2 + writeWithSync(calldepth, msg) +} diff --git a/vendor/github.com/c-bata/go-prompt/internal/strings/strings.go b/vendor/github.com/c-bata/go-prompt/internal/strings/strings.go new file mode 100644 index 000000000..f7d1886ae --- /dev/null +++ b/vendor/github.com/c-bata/go-prompt/internal/strings/strings.go @@ -0,0 +1,102 @@ +package strings + +import "unicode/utf8" + +// IndexNotByte is similar with strings.IndexByte but showing the opposite behavior. +func IndexNotByte(s string, c byte) int { + n := len(s) + for i := 0; i < n; i++ { + if s[i] != c { + return i + } + } + return -1 +} + +// LastIndexNotByte is similar with strings.LastIndexByte but showing the opposite behavior. +func LastIndexNotByte(s string, c byte) int { + for i := len(s) - 1; i >= 0; i-- { + if s[i] != c { + return i + } + } + return -1 +} + +type asciiSet [8]uint32 + +func (as *asciiSet) notContains(c byte) bool { + return (as[c>>5] & (1 << uint(c&31))) == 0 +} + +func makeASCIISet(chars string) (as asciiSet, ok bool) { + for i := 0; i < len(chars); i++ { + c := chars[i] + if c >= utf8.RuneSelf { + return as, false + } + as[c>>5] |= 1 << uint(c&31) + } + return as, true +} + +// IndexNotAny is similar with strings.IndexAny but showing the opposite behavior. +func IndexNotAny(s, chars string) int { + if len(chars) > 0 { + if len(s) > 8 { + if as, isASCII := makeASCIISet(chars); isASCII { + for i := 0; i < len(s); i++ { + if as.notContains(s[i]) { + return i + } + } + return -1 + } + } + + LabelFirstLoop: + for i, c := range s { + for j, m := range chars { + if c != m && j == len(chars)-1 { + return i + } else if c != m { + continue + } else { + continue LabelFirstLoop + } + } + } + } + return -1 +} + +// LastIndexNotAny is similar with strings.LastIndexAny but showing the opposite behavior. +func LastIndexNotAny(s, chars string) int { + if len(chars) > 0 { + if len(s) > 8 { + if as, isASCII := makeASCIISet(chars); isASCII { + for i := len(s) - 1; i >= 0; i-- { + if as.notContains(s[i]) { + return i + } + } + return -1 + } + } + LabelFirstLoop: + for i := len(s); i > 0; { + r, size := utf8.DecodeLastRuneInString(s[:i]) + i -= size + for j, m := range chars { + if r != m && j == len(chars)-1 { + return i + } else if r != m { + continue + } else { + continue LabelFirstLoop + } + } + } + } + return -1 +} diff --git a/vendor/github.com/c-bata/go-prompt/internal/term/raw.go b/vendor/github.com/c-bata/go-prompt/internal/term/raw.go new file mode 100644 index 000000000..7aa3ed8d0 --- /dev/null +++ b/vendor/github.com/c-bata/go-prompt/internal/term/raw.go @@ -0,0 +1,29 @@ +// +build !windows + +package term + +import ( + "syscall" + + "github.com/pkg/term/termios" + "golang.org/x/sys/unix" +) + +// SetRaw put terminal into a raw mode +func SetRaw(fd int) error { + n, err := getOriginalTermios(fd) + if err != nil { + return err + } + + n.Iflag &^= syscall.IGNBRK | syscall.BRKINT | syscall.PARMRK | + syscall.ISTRIP | syscall.INLCR | syscall.IGNCR | + syscall.ICRNL | syscall.IXON + n.Lflag &^= syscall.ECHO | syscall.ICANON | syscall.IEXTEN | syscall.ISIG | syscall.ECHONL + n.Cflag &^= syscall.CSIZE | syscall.PARENB + n.Cflag |= syscall.CS8 // Set to 8-bit wide. Typical value for displaying characters. + n.Cc[syscall.VMIN] = 1 + n.Cc[syscall.VTIME] = 0 + + return termios.Tcsetattr(uintptr(fd), termios.TCSANOW, (*unix.Termios)(n)) +} diff --git a/vendor/github.com/c-bata/go-prompt/internal/term/term.go b/vendor/github.com/c-bata/go-prompt/internal/term/term.go new file mode 100644 index 000000000..3f3a53c05 --- /dev/null +++ b/vendor/github.com/c-bata/go-prompt/internal/term/term.go @@ -0,0 +1,34 @@ +// +build !windows + +package term + +import ( + "sync" + + "github.com/pkg/term/termios" + "golang.org/x/sys/unix" +) + +var ( + saveTermios *unix.Termios + saveTermiosFD int + saveTermiosOnce sync.Once +) + +func getOriginalTermios(fd int) (*unix.Termios, error) { + var err error + saveTermiosOnce.Do(func() { + saveTermiosFD = fd + saveTermios, err = termios.Tcgetattr(uintptr(fd)) + }) + return saveTermios, err +} + +// Restore terminal's mode. +func Restore() error { + o, err := getOriginalTermios(saveTermiosFD) + if err != nil { + return err + } + return termios.Tcsetattr(uintptr(saveTermiosFD), termios.TCSANOW, o) +} diff --git a/vendor/github.com/c-bata/go-prompt/key.go b/vendor/github.com/c-bata/go-prompt/key.go new file mode 100644 index 000000000..7ba569c2d --- /dev/null +++ b/vendor/github.com/c-bata/go-prompt/key.go @@ -0,0 +1,128 @@ +// Code generated by hand; DO NOT EDIT. +// This is a little bit stupid, but there are many public constants which is no value for writing godoc comment. + +package prompt + +// Key is the type express the key inserted from user. +//go:generate stringer -type=Key +type Key int + +// ASCIICode is the type contains Key and it's ascii byte array. +type ASCIICode struct { + Key Key + ASCIICode []byte +} + +const ( + Escape Key = iota + + ControlA + ControlB + ControlC + ControlD + ControlE + ControlF + ControlG + ControlH + ControlI + ControlJ + ControlK + ControlL + ControlM + ControlN + ControlO + ControlP + ControlQ + ControlR + ControlS + ControlT + ControlU + ControlV + ControlW + ControlX + ControlY + ControlZ + + ControlSpace + ControlBackslash + ControlSquareClose + ControlCircumflex + ControlUnderscore + ControlLeft + ControlRight + ControlUp + ControlDown + + Up + Down + Right + Left + + ShiftLeft + ShiftUp + ShiftDown + ShiftRight + + Home + End + Delete + ShiftDelete + ControlDelete + PageUp + PageDown + BackTab + Insert + Backspace + + // Aliases. + Tab + Enter + // Actually Enter equals ControlM, not ControlJ, + // However, in prompt_toolkit, we made the mistake of translating + // \r into \n during the input, so everyone is now handling the + // enter key by binding ControlJ. + + // From now on, it's better to bind `ASCII_SEQUENCES.Enter` everywhere, + // because that's future compatible, and will still work when we + // stop replacing \r by \n. + + F1 + F2 + F3 + F4 + F5 + F6 + F7 + F8 + F9 + F10 + F11 + F12 + F13 + F14 + F15 + F16 + F17 + F18 + F19 + F20 + F21 + F22 + F23 + F24 + + // Matches any key. + Any + + // Special + CPRResponse + Vt100MouseEvent + WindowsMouseEvent + BracketedPaste + + // Key which is ignored. (The key binding for this key should not do anything.) + Ignore + + // Key is not defined + NotDefined +) diff --git a/vendor/github.com/c-bata/go-prompt/key_bind.go b/vendor/github.com/c-bata/go-prompt/key_bind.go new file mode 100644 index 000000000..42669e7f9 --- /dev/null +++ b/vendor/github.com/c-bata/go-prompt/key_bind.go @@ -0,0 +1,59 @@ +package prompt + +// KeyBindFunc receives buffer and processed it. +type KeyBindFunc func(*Buffer) + +// KeyBind represents which key should do what operation. +type KeyBind struct { + Key Key + Fn KeyBindFunc +} + +// ASCIICodeBind represents which []byte should do what operation +type ASCIICodeBind struct { + ASCIICode []byte + Fn KeyBindFunc +} + +// KeyBindMode to switch a key binding flexibly. +type KeyBindMode string + +const ( + // CommonKeyBind is a mode without any keyboard shortcut + CommonKeyBind KeyBindMode = "common" + // EmacsKeyBind is a mode to use emacs-like keyboard shortcut + EmacsKeyBind KeyBindMode = "emacs" +) + +var commonKeyBindings = []KeyBind{ + // Go to the End of the line + { + Key: End, + Fn: GoLineEnd, + }, + // Go to the beginning of the line + { + Key: Home, + Fn: GoLineBeginning, + }, + // Delete character under the cursor + { + Key: Delete, + Fn: DeleteChar, + }, + // Backspace + { + Key: Backspace, + Fn: DeleteBeforeChar, + }, + // Right allow: Forward one character + { + Key: Right, + Fn: GoRightChar, + }, + // Left allow: Backward one character + { + Key: Left, + Fn: GoLeftChar, + }, +} diff --git a/vendor/github.com/c-bata/go-prompt/key_bind_func.go b/vendor/github.com/c-bata/go-prompt/key_bind_func.go new file mode 100644 index 000000000..7b2ecdf63 --- /dev/null +++ b/vendor/github.com/c-bata/go-prompt/key_bind_func.go @@ -0,0 +1,48 @@ +package prompt + +// GoLineEnd Go to the End of the line +func GoLineEnd(buf *Buffer) { + x := []rune(buf.Document().TextAfterCursor()) + buf.CursorRight(len(x)) +} + +// GoLineBeginning Go to the beginning of the line +func GoLineBeginning(buf *Buffer) { + x := []rune(buf.Document().TextBeforeCursor()) + buf.CursorLeft(len(x)) +} + +// DeleteChar Delete character under the cursor +func DeleteChar(buf *Buffer) { + buf.Delete(1) +} + +// DeleteWord Delete word before the cursor +func DeleteWord(buf *Buffer) { + buf.DeleteBeforeCursor(len([]rune(buf.Document().TextBeforeCursor())) - buf.Document().FindStartOfPreviousWordWithSpace()) +} + +// DeleteBeforeChar Go to Backspace +func DeleteBeforeChar(buf *Buffer) { + buf.DeleteBeforeCursor(1) +} + +// GoRightChar Forward one character +func GoRightChar(buf *Buffer) { + buf.CursorRight(1) +} + +// GoLeftChar Backward one character +func GoLeftChar(buf *Buffer) { + buf.CursorLeft(1) +} + +// GoRightWord Forward one word +func GoRightWord(buf *Buffer) { + buf.CursorRight(buf.Document().FindEndOfCurrentWordWithSpace()) +} + +// GoLeftWord Backward one word +func GoLeftWord(buf *Buffer) { + buf.CursorLeft(len([]rune(buf.Document().TextBeforeCursor())) - buf.Document().FindStartOfPreviousWordWithSpace()) +} diff --git a/vendor/github.com/c-bata/go-prompt/key_string.go b/vendor/github.com/c-bata/go-prompt/key_string.go new file mode 100644 index 000000000..fce6ea31c --- /dev/null +++ b/vendor/github.com/c-bata/go-prompt/key_string.go @@ -0,0 +1,16 @@ +// Code generated by "stringer -type=Key"; DO NOT EDIT. + +package prompt + +import "strconv" + +const _Key_name = "EscapeControlAControlBControlCControlDControlEControlFControlGControlHControlIControlJControlKControlLControlMControlNControlOControlPControlQControlRControlSControlTControlUControlVControlWControlXControlYControlZControlSpaceControlBackslashControlSquareCloseControlCircumflexControlUnderscoreControlLeftControlRightControlUpControlDownUpDownRightLeftShiftLeftShiftUpShiftDownShiftRightHomeEndDeleteShiftDeleteControlDeletePageUpPageDownBackTabInsertBackspaceTabEnterF1F2F3F4F5F6F7F8F9F10F11F12F13F14F15F16F17F18F19F20F21F22F23F24AnyCPRResponseVt100MouseEventWindowsMouseEventBracketedPasteIgnoreNotDefined" + +var _Key_index = [...]uint16{0, 6, 14, 22, 30, 38, 46, 54, 62, 70, 78, 86, 94, 102, 110, 118, 126, 134, 142, 150, 158, 166, 174, 182, 190, 198, 206, 214, 226, 242, 260, 277, 294, 305, 317, 326, 337, 339, 343, 348, 352, 361, 368, 377, 387, 391, 394, 400, 411, 424, 430, 438, 445, 451, 460, 463, 468, 470, 472, 474, 476, 478, 480, 482, 484, 486, 489, 492, 495, 498, 501, 504, 507, 510, 513, 516, 519, 522, 525, 528, 531, 534, 545, 560, 577, 591, 597, 607} + +func (i Key) String() string { + if i < 0 || i >= Key(len(_Key_index)-1) { + return "Key(" + strconv.FormatInt(int64(i), 10) + ")" + } + return _Key_name[_Key_index[i]:_Key_index[i+1]] +} diff --git a/vendor/github.com/c-bata/go-prompt/option.go b/vendor/github.com/c-bata/go-prompt/option.go new file mode 100644 index 000000000..9fbd6806c --- /dev/null +++ b/vendor/github.com/c-bata/go-prompt/option.go @@ -0,0 +1,310 @@ +package prompt + +// Option is the type to replace default parameters. +// prompt.New accepts any number of options (this is functional option pattern). +type Option func(prompt *Prompt) error + +// OptionParser to set a custom ConsoleParser object. An argument should implement ConsoleParser interface. +func OptionParser(x ConsoleParser) Option { + return func(p *Prompt) error { + p.in = x + return nil + } +} + +// OptionWriter to set a custom ConsoleWriter object. An argument should implement ConsoleWriter interface. +func OptionWriter(x ConsoleWriter) Option { + return func(p *Prompt) error { + registerConsoleWriter(x) + p.renderer.out = x + return nil + } +} + +// OptionTitle to set title displayed at the header bar of terminal. +func OptionTitle(x string) Option { + return func(p *Prompt) error { + p.renderer.title = x + return nil + } +} + +// OptionPrefix to set prefix string. +func OptionPrefix(x string) Option { + return func(p *Prompt) error { + p.renderer.prefix = x + return nil + } +} + +// OptionInitialBufferText to set the initial buffer text +func OptionInitialBufferText(x string) Option { + return func(p *Prompt) error { + p.buf.InsertText(x, false, true) + return nil + } +} + +// OptionCompletionWordSeparator to set word separators. Enable only ' ' if empty. +func OptionCompletionWordSeparator(x string) Option { + return func(p *Prompt) error { + p.completion.wordSeparator = x + return nil + } +} + +// OptionLivePrefix to change the prefix dynamically by callback function +func OptionLivePrefix(f func() (prefix string, useLivePrefix bool)) Option { + return func(p *Prompt) error { + p.renderer.livePrefixCallback = f + return nil + } +} + +// OptionPrefixTextColor change a text color of prefix string +func OptionPrefixTextColor(x Color) Option { + return func(p *Prompt) error { + p.renderer.prefixTextColor = x + return nil + } +} + +// OptionPrefixBackgroundColor to change a background color of prefix string +func OptionPrefixBackgroundColor(x Color) Option { + return func(p *Prompt) error { + p.renderer.prefixBGColor = x + return nil + } +} + +// OptionInputTextColor to change a color of text which is input by user +func OptionInputTextColor(x Color) Option { + return func(p *Prompt) error { + p.renderer.inputTextColor = x + return nil + } +} + +// OptionInputBGColor to change a color of background which is input by user +func OptionInputBGColor(x Color) Option { + return func(p *Prompt) error { + p.renderer.inputBGColor = x + return nil + } +} + +// OptionPreviewSuggestionTextColor to change a text color which is completed +func OptionPreviewSuggestionTextColor(x Color) Option { + return func(p *Prompt) error { + p.renderer.previewSuggestionTextColor = x + return nil + } +} + +// OptionPreviewSuggestionBGColor to change a background color which is completed +func OptionPreviewSuggestionBGColor(x Color) Option { + return func(p *Prompt) error { + p.renderer.previewSuggestionBGColor = x + return nil + } +} + +// OptionSuggestionTextColor to change a text color in drop down suggestions. +func OptionSuggestionTextColor(x Color) Option { + return func(p *Prompt) error { + p.renderer.suggestionTextColor = x + return nil + } +} + +// OptionSuggestionBGColor change a background color in drop down suggestions. +func OptionSuggestionBGColor(x Color) Option { + return func(p *Prompt) error { + p.renderer.suggestionBGColor = x + return nil + } +} + +// OptionSelectedSuggestionTextColor to change a text color for completed text which is selected inside suggestions drop down box. +func OptionSelectedSuggestionTextColor(x Color) Option { + return func(p *Prompt) error { + p.renderer.selectedSuggestionTextColor = x + return nil + } +} + +// OptionSelectedSuggestionBGColor to change a background color for completed text which is selected inside suggestions drop down box. +func OptionSelectedSuggestionBGColor(x Color) Option { + return func(p *Prompt) error { + p.renderer.selectedSuggestionBGColor = x + return nil + } +} + +// OptionDescriptionTextColor to change a background color of description text in drop down suggestions. +func OptionDescriptionTextColor(x Color) Option { + return func(p *Prompt) error { + p.renderer.descriptionTextColor = x + return nil + } +} + +// OptionDescriptionBGColor to change a background color of description text in drop down suggestions. +func OptionDescriptionBGColor(x Color) Option { + return func(p *Prompt) error { + p.renderer.descriptionBGColor = x + return nil + } +} + +// OptionSelectedDescriptionTextColor to change a text color of description which is selected inside suggestions drop down box. +func OptionSelectedDescriptionTextColor(x Color) Option { + return func(p *Prompt) error { + p.renderer.selectedDescriptionTextColor = x + return nil + } +} + +// OptionSelectedDescriptionBGColor to change a background color of description which is selected inside suggestions drop down box. +func OptionSelectedDescriptionBGColor(x Color) Option { + return func(p *Prompt) error { + p.renderer.selectedDescriptionBGColor = x + return nil + } +} + +// OptionScrollbarThumbColor to change a thumb color on scrollbar. +func OptionScrollbarThumbColor(x Color) Option { + return func(p *Prompt) error { + p.renderer.scrollbarThumbColor = x + return nil + } +} + +// OptionScrollbarBGColor to change a background color of scrollbar. +func OptionScrollbarBGColor(x Color) Option { + return func(p *Prompt) error { + p.renderer.scrollbarBGColor = x + return nil + } +} + +// OptionMaxSuggestion specify the max number of displayed suggestions. +func OptionMaxSuggestion(x uint16) Option { + return func(p *Prompt) error { + p.completion.max = x + return nil + } +} + +// OptionHistory to set history expressed by string array. +func OptionHistory(x []string) Option { + return func(p *Prompt) error { + p.history.histories = x + p.history.Clear() + return nil + } +} + +// OptionSwitchKeyBindMode set a key bind mode. +func OptionSwitchKeyBindMode(m KeyBindMode) Option { + return func(p *Prompt) error { + p.keyBindMode = m + return nil + } +} + +// OptionCompletionOnDown allows for Down arrow key to trigger completion. +func OptionCompletionOnDown() Option { + return func(p *Prompt) error { + p.completionOnDown = true + return nil + } +} + +// SwitchKeyBindMode to set a key bind mode. +// Deprecated: Please use OptionSwitchKeyBindMode. +var SwitchKeyBindMode = OptionSwitchKeyBindMode + +// OptionAddKeyBind to set a custom key bind. +func OptionAddKeyBind(b ...KeyBind) Option { + return func(p *Prompt) error { + p.keyBindings = append(p.keyBindings, b...) + return nil + } +} + +// OptionAddASCIICodeBind to set a custom key bind. +func OptionAddASCIICodeBind(b ...ASCIICodeBind) Option { + return func(p *Prompt) error { + p.ASCIICodeBindings = append(p.ASCIICodeBindings, b...) + return nil + } +} + +// OptionShowCompletionAtStart to set completion window is open at start. +func OptionShowCompletionAtStart() Option { + return func(p *Prompt) error { + p.completion.showAtStart = true + return nil + } +} + +// OptionBreakLineCallback to run a callback at every break line +func OptionBreakLineCallback(fn func(*Document)) Option { + return func(p *Prompt) error { + p.renderer.breakLineCallback = fn + return nil + } +} + +// OptionSetExitCheckerOnInput set an exit function which checks if go-prompt exits its Run loop +func OptionSetExitCheckerOnInput(fn ExitChecker) Option { + return func(p *Prompt) error { + p.exitChecker = fn + return nil + } +} + +// New returns a Prompt with powerful auto-completion. +func New(executor Executor, completer Completer, opts ...Option) *Prompt { + defaultWriter := NewStdoutWriter() + registerConsoleWriter(defaultWriter) + + pt := &Prompt{ + in: NewStandardInputParser(), + renderer: &Render{ + prefix: "> ", + out: defaultWriter, + livePrefixCallback: func() (string, bool) { return "", false }, + prefixTextColor: Blue, + prefixBGColor: DefaultColor, + inputTextColor: DefaultColor, + inputBGColor: DefaultColor, + previewSuggestionTextColor: Green, + previewSuggestionBGColor: DefaultColor, + suggestionTextColor: White, + suggestionBGColor: Cyan, + selectedSuggestionTextColor: Black, + selectedSuggestionBGColor: Turquoise, + descriptionTextColor: Black, + descriptionBGColor: Turquoise, + selectedDescriptionTextColor: White, + selectedDescriptionBGColor: Cyan, + scrollbarThumbColor: DarkGray, + scrollbarBGColor: Cyan, + }, + buf: NewBuffer(), + executor: executor, + history: NewHistory(), + completion: NewCompletionManager(completer, 6), + keyBindMode: EmacsKeyBind, // All the above assume that bash is running in the default Emacs setting + } + + for _, opt := range opts { + if err := opt(pt); err != nil { + panic(err) + } + } + return pt +} diff --git a/vendor/github.com/c-bata/go-prompt/output.go b/vendor/github.com/c-bata/go-prompt/output.go new file mode 100644 index 000000000..42531b412 --- /dev/null +++ b/vendor/github.com/c-bata/go-prompt/output.go @@ -0,0 +1,161 @@ +package prompt + +import "sync" + +var ( + consoleWriterMu sync.Mutex + consoleWriter ConsoleWriter +) + +func registerConsoleWriter(f ConsoleWriter) { + consoleWriterMu.Lock() + defer consoleWriterMu.Unlock() + consoleWriter = f +} + +// DisplayAttribute represents display attributes like Blinking, Bold, Italic and so on. +type DisplayAttribute int + +const ( + // DisplayReset reset all display attributes. + DisplayReset DisplayAttribute = iota + // DisplayBold set bold or increases intensity. + DisplayBold + // DisplayLowIntensity decreases intensity. Not widely supported. + DisplayLowIntensity + // DisplayItalic set italic. Not widely supported. + DisplayItalic + // DisplayUnderline set underline + DisplayUnderline + // DisplayBlink set blink (less than 150 per minute). + DisplayBlink + // DisplayRapidBlink set blink (more than 150 per minute). Not widely supported. + DisplayRapidBlink + // DisplayReverse swap foreground and background colors. + DisplayReverse + // DisplayInvisible set invisible. Not widely supported. + DisplayInvisible + // DisplayCrossedOut set characters legible, but marked for deletion. Not widely supported. + DisplayCrossedOut + // DisplayDefaultFont set primary(default) font + DisplayDefaultFont +) + +// Color represents color on terminal. +type Color int + +const ( + // DefaultColor represents a default color. + DefaultColor Color = iota + + // Low intensity + + // Black represents a black. + Black + // DarkRed represents a dark red. + DarkRed + // DarkGreen represents a dark green. + DarkGreen + // Brown represents a brown. + Brown + // DarkBlue represents a dark blue. + DarkBlue + // Purple represents a purple. + Purple + // Cyan represents a cyan. + Cyan + // LightGray represents a light gray. + LightGray + + // High intensity + + // DarkGray represents a dark gray. + DarkGray + // Red represents a red. + Red + // Green represents a green. + Green + // Yellow represents a yellow. + Yellow + // Blue represents a blue. + Blue + // Fuchsia represents a fuchsia. + Fuchsia + // Turquoise represents a turquoise. + Turquoise + // White represents a white. + White +) + +// ConsoleWriter is an interface to abstract output layer. +type ConsoleWriter interface { + /* Write */ + + // WriteRaw to write raw byte array. + WriteRaw(data []byte) + // Write to write safety byte array by removing control sequences. + Write(data []byte) + // WriteStr to write raw string. + WriteRawStr(data string) + // WriteStr to write safety string by removing control sequences. + WriteStr(data string) + // Flush to flush buffer. + Flush() error + + /* Erasing */ + + // EraseScreen erases the screen with the background colour and moves the cursor to home. + EraseScreen() + // EraseUp erases the screen from the current line up to the top of the screen. + EraseUp() + // EraseDown erases the screen from the current line down to the bottom of the screen. + EraseDown() + // EraseStartOfLine erases from the current cursor position to the start of the current line. + EraseStartOfLine() + // EraseEndOfLine erases from the current cursor position to the end of the current line. + EraseEndOfLine() + // EraseLine erases the entire current line. + EraseLine() + + /* Cursor */ + + // ShowCursor stops blinking cursor and show. + ShowCursor() + // HideCursor hides cursor. + HideCursor() + // CursorGoTo sets the cursor position where subsequent text will begin. + CursorGoTo(row, col int) + // CursorUp moves the cursor up by 'n' rows; the default count is 1. + CursorUp(n int) + // CursorDown moves the cursor down by 'n' rows; the default count is 1. + CursorDown(n int) + // CursorForward moves the cursor forward by 'n' columns; the default count is 1. + CursorForward(n int) + // CursorBackward moves the cursor backward by 'n' columns; the default count is 1. + CursorBackward(n int) + // AskForCPR asks for a cursor position report (CPR). + AskForCPR() + // SaveCursor saves current cursor position. + SaveCursor() + // UnSaveCursor restores cursor position after a Save Cursor. + UnSaveCursor() + + /* Scrolling */ + + // ScrollDown scrolls display down one line. + ScrollDown() + // ScrollUp scroll display up one line. + ScrollUp() + + /* Title */ + + // SetTitle sets a title of terminal window. + SetTitle(title string) + // ClearTitle clears a title of terminal window. + ClearTitle() + + /* Font */ + + // SetColor sets text and background colors. and specify whether text is bold. + SetColor(fg, bg Color, bold bool) +} diff --git a/vendor/github.com/c-bata/go-prompt/output_posix.go b/vendor/github.com/c-bata/go-prompt/output_posix.go new file mode 100644 index 000000000..26c770cc1 --- /dev/null +++ b/vendor/github.com/c-bata/go-prompt/output_posix.go @@ -0,0 +1,67 @@ +// +build !windows + +package prompt + +import ( + "syscall" +) + +const flushMaxRetryCount = 3 + +// PosixWriter is a ConsoleWriter implementation for POSIX environment. +// To control terminal emulator, this outputs VT100 escape sequences. +type PosixWriter struct { + VT100Writer + fd int +} + +// Flush to flush buffer +func (w *PosixWriter) Flush() error { + l := len(w.buffer) + offset := 0 + retry := 0 + for { + n, err := syscall.Write(w.fd, w.buffer[offset:]) + if err != nil { + if retry < flushMaxRetryCount { + retry++ + continue + } + return err + } + offset += n + if offset == l { + break + } + } + w.buffer = []byte{} + return nil +} + +var _ ConsoleWriter = &PosixWriter{} + +var ( + // NewStandardOutputWriter returns ConsoleWriter object to write to stdout. + // This generates VT100 escape sequences because almost terminal emulators + // in POSIX OS built on top of a VT100 specification. + // Deprecated: Please use NewStdoutWriter + NewStandardOutputWriter = NewStdoutWriter +) + +// NewStdoutWriter returns ConsoleWriter object to write to stdout. +// This generates VT100 escape sequences because almost terminal emulators +// in POSIX OS built on top of a VT100 specification. +func NewStdoutWriter() ConsoleWriter { + return &PosixWriter{ + fd: syscall.Stdout, + } +} + +// NewStderrWriter returns ConsoleWriter object to write to stderr. +// This generates VT100 escape sequences because almost terminal emulators +// in POSIX OS built on top of a VT100 specification. +func NewStderrWriter() ConsoleWriter { + return &PosixWriter{ + fd: syscall.Stderr, + } +} diff --git a/vendor/github.com/c-bata/go-prompt/output_vt100.go b/vendor/github.com/c-bata/go-prompt/output_vt100.go new file mode 100644 index 000000000..20850fead --- /dev/null +++ b/vendor/github.com/c-bata/go-prompt/output_vt100.go @@ -0,0 +1,310 @@ +package prompt + +import ( + "bytes" + "strconv" +) + +// VT100Writer generates VT100 escape sequences. +type VT100Writer struct { + buffer []byte +} + +// WriteRaw to write raw byte array +func (w *VT100Writer) WriteRaw(data []byte) { + w.buffer = append(w.buffer, data...) +} + +// Write to write safety byte array by removing control sequences. +func (w *VT100Writer) Write(data []byte) { + w.WriteRaw(bytes.Replace(data, []byte{0x1b}, []byte{'?'}, -1)) +} + +// WriteRawStr to write raw string +func (w *VT100Writer) WriteRawStr(data string) { + w.WriteRaw([]byte(data)) +} + +// WriteStr to write safety string by removing control sequences. +func (w *VT100Writer) WriteStr(data string) { + w.Write([]byte(data)) +} + +/* Erase */ + +// EraseScreen erases the screen with the background colour and moves the cursor to home. +func (w *VT100Writer) EraseScreen() { + w.WriteRaw([]byte{0x1b, '[', '2', 'J'}) +} + +// EraseUp erases the screen from the current line up to the top of the screen. +func (w *VT100Writer) EraseUp() { + w.WriteRaw([]byte{0x1b, '[', '1', 'J'}) +} + +// EraseDown erases the screen from the current line down to the bottom of the screen. +func (w *VT100Writer) EraseDown() { + w.WriteRaw([]byte{0x1b, '[', 'J'}) +} + +// EraseStartOfLine erases from the current cursor position to the start of the current line. +func (w *VT100Writer) EraseStartOfLine() { + w.WriteRaw([]byte{0x1b, '[', '1', 'K'}) +} + +// EraseEndOfLine erases from the current cursor position to the end of the current line. +func (w *VT100Writer) EraseEndOfLine() { + w.WriteRaw([]byte{0x1b, '[', 'K'}) +} + +// EraseLine erases the entire current line. +func (w *VT100Writer) EraseLine() { + w.WriteRaw([]byte{0x1b, '[', '2', 'K'}) +} + +/* Cursor */ + +// ShowCursor stops blinking cursor and show. +func (w *VT100Writer) ShowCursor() { + w.WriteRaw([]byte{0x1b, '[', '?', '1', '2', 'l', 0x1b, '[', '?', '2', '5', 'h'}) +} + +// HideCursor hides cursor. +func (w *VT100Writer) HideCursor() { + w.WriteRaw([]byte{0x1b, '[', '?', '2', '5', 'l'}) +} + +// CursorGoTo sets the cursor position where subsequent text will begin. +func (w *VT100Writer) CursorGoTo(row, col int) { + if row == 0 && col == 0 { + // If no row/column parameters are provided (ie. [H), the cursor will move to the home position. + w.WriteRaw([]byte{0x1b, '[', 'H'}) + return + } + r := strconv.Itoa(row) + c := strconv.Itoa(col) + w.WriteRaw([]byte{0x1b, '['}) + w.WriteRaw([]byte(r)) + w.WriteRaw([]byte{';'}) + w.WriteRaw([]byte(c)) + w.WriteRaw([]byte{'H'}) +} + +// CursorUp moves the cursor up by 'n' rows; the default count is 1. +func (w *VT100Writer) CursorUp(n int) { + if n == 0 { + return + } else if n < 0 { + w.CursorDown(-n) + return + } + s := strconv.Itoa(n) + w.WriteRaw([]byte{0x1b, '['}) + w.WriteRaw([]byte(s)) + w.WriteRaw([]byte{'A'}) +} + +// CursorDown moves the cursor down by 'n' rows; the default count is 1. +func (w *VT100Writer) CursorDown(n int) { + if n == 0 { + return + } else if n < 0 { + w.CursorUp(-n) + return + } + s := strconv.Itoa(n) + w.WriteRaw([]byte{0x1b, '['}) + w.WriteRaw([]byte(s)) + w.WriteRaw([]byte{'B'}) +} + +// CursorForward moves the cursor forward by 'n' columns; the default count is 1. +func (w *VT100Writer) CursorForward(n int) { + if n == 0 { + return + } else if n < 0 { + w.CursorBackward(-n) + return + } + s := strconv.Itoa(n) + w.WriteRaw([]byte{0x1b, '['}) + w.WriteRaw([]byte(s)) + w.WriteRaw([]byte{'C'}) +} + +// CursorBackward moves the cursor backward by 'n' columns; the default count is 1. +func (w *VT100Writer) CursorBackward(n int) { + if n == 0 { + return + } else if n < 0 { + w.CursorForward(-n) + return + } + s := strconv.Itoa(n) + w.WriteRaw([]byte{0x1b, '['}) + w.WriteRaw([]byte(s)) + w.WriteRaw([]byte{'D'}) +} + +// AskForCPR asks for a cursor position report (CPR). +func (w *VT100Writer) AskForCPR() { + // CPR: Cursor Position Request. + w.WriteRaw([]byte{0x1b, '[', '6', 'n'}) +} + +// SaveCursor saves current cursor position. +func (w *VT100Writer) SaveCursor() { + w.WriteRaw([]byte{0x1b, '[', 's'}) +} + +// UnSaveCursor restores cursor position after a Save Cursor. +func (w *VT100Writer) UnSaveCursor() { + w.WriteRaw([]byte{0x1b, '[', 'u'}) +} + +/* Scrolling */ + +// ScrollDown scrolls display down one line. +func (w *VT100Writer) ScrollDown() { + w.WriteRaw([]byte{0x1b, 'D'}) +} + +// ScrollUp scroll display up one line. +func (w *VT100Writer) ScrollUp() { + w.WriteRaw([]byte{0x1b, 'M'}) +} + +/* Title */ + +// SetTitle sets a title of terminal window. +func (w *VT100Writer) SetTitle(title string) { + titleBytes := []byte(title) + patterns := []struct { + from []byte + to []byte + }{ + { + from: []byte{0x13}, + to: []byte{}, + }, + { + from: []byte{0x07}, + to: []byte{}, + }, + } + for i := range patterns { + titleBytes = bytes.Replace(titleBytes, patterns[i].from, patterns[i].to, -1) + } + + w.WriteRaw([]byte{0x1b, ']', '2', ';'}) + w.WriteRaw(titleBytes) + w.WriteRaw([]byte{0x07}) +} + +// ClearTitle clears a title of terminal window. +func (w *VT100Writer) ClearTitle() { + w.WriteRaw([]byte{0x1b, ']', '2', ';', 0x07}) +} + +/* Font */ + +// SetColor sets text and background colors. and specify whether text is bold. +func (w *VT100Writer) SetColor(fg, bg Color, bold bool) { + if bold { + w.SetDisplayAttributes(fg, bg, DisplayBold) + } else { + // If using `DisplayDefualt`, it will be broken in some environment. + // Details are https://github.com/c-bata/go-prompt/pull/85 + w.SetDisplayAttributes(fg, bg, DisplayReset) + } +} + +// SetDisplayAttributes to set VT100 display attributes. +func (w *VT100Writer) SetDisplayAttributes(fg, bg Color, attrs ...DisplayAttribute) { + w.WriteRaw([]byte{0x1b, '['}) // control sequence introducer + defer w.WriteRaw([]byte{'m'}) // final character + + var separator byte = ';' + for i := range attrs { + p, ok := displayAttributeParameters[attrs[i]] + if !ok { + continue + } + w.WriteRaw(p) + w.WriteRaw([]byte{separator}) + } + + f, ok := foregroundANSIColors[fg] + if !ok { + f = foregroundANSIColors[DefaultColor] + } + w.WriteRaw(f) + w.WriteRaw([]byte{separator}) + b, ok := backgroundANSIColors[bg] + if !ok { + b = backgroundANSIColors[DefaultColor] + } + w.WriteRaw(b) +} + +var displayAttributeParameters = map[DisplayAttribute][]byte{ + DisplayReset: {'0'}, + DisplayBold: {'1'}, + DisplayLowIntensity: {'2'}, + DisplayItalic: {'3'}, + DisplayUnderline: {'4'}, + DisplayBlink: {'5'}, + DisplayRapidBlink: {'6'}, + DisplayReverse: {'7'}, + DisplayInvisible: {'8'}, + DisplayCrossedOut: {'9'}, + DisplayDefaultFont: {'1', '0'}, +} + +var foregroundANSIColors = map[Color][]byte{ + DefaultColor: {'3', '9'}, + + // Low intensity. + Black: {'3', '0'}, + DarkRed: {'3', '1'}, + DarkGreen: {'3', '2'}, + Brown: {'3', '3'}, + DarkBlue: {'3', '4'}, + Purple: {'3', '5'}, + Cyan: {'3', '6'}, + LightGray: {'3', '7'}, + + // High intensity. + DarkGray: {'9', '0'}, + Red: {'9', '1'}, + Green: {'9', '2'}, + Yellow: {'9', '3'}, + Blue: {'9', '4'}, + Fuchsia: {'9', '5'}, + Turquoise: {'9', '6'}, + White: {'9', '7'}, +} + +var backgroundANSIColors = map[Color][]byte{ + DefaultColor: {'4', '9'}, + + // Low intensity. + Black: {'4', '0'}, + DarkRed: {'4', '1'}, + DarkGreen: {'4', '2'}, + Brown: {'4', '3'}, + DarkBlue: {'4', '4'}, + Purple: {'4', '5'}, + Cyan: {'4', '6'}, + LightGray: {'4', '7'}, + + // High intensity + DarkGray: {'1', '0', '0'}, + Red: {'1', '0', '1'}, + Green: {'1', '0', '2'}, + Yellow: {'1', '0', '3'}, + Blue: {'1', '0', '4'}, + Fuchsia: {'1', '0', '5'}, + Turquoise: {'1', '0', '6'}, + White: {'1', '0', '7'}, +} diff --git a/vendor/github.com/c-bata/go-prompt/output_windows.go b/vendor/github.com/c-bata/go-prompt/output_windows.go new file mode 100644 index 000000000..3b9c2769f --- /dev/null +++ b/vendor/github.com/c-bata/go-prompt/output_windows.go @@ -0,0 +1,49 @@ +// +build windows + +package prompt + +import ( + "io" + + colorable "github.com/mattn/go-colorable" +) + +// WindowsWriter is a ConsoleWriter implementation for Win32 console. +// Output is converted from VT100 escape sequences by mattn/go-colorable. +type WindowsWriter struct { + VT100Writer + out io.Writer +} + +// Flush to flush buffer +func (w *WindowsWriter) Flush() error { + _, err := w.out.Write(w.buffer) + if err != nil { + return err + } + w.buffer = []byte{} + return nil +} + +var _ ConsoleWriter = &WindowsWriter{} + +var ( + // NewStandardOutputWriter is Deprecated: Please use NewStdoutWriter + NewStandardOutputWriter = NewStdoutWriter +) + +// NewStdoutWriter returns ConsoleWriter object to write to stdout. +// This generates win32 control sequences. +func NewStdoutWriter() ConsoleWriter { + return &WindowsWriter{ + out: colorable.NewColorableStdout(), + } +} + +// NewStderrWriter returns ConsoleWriter object to write to stderr. +// This generates win32 control sequences. +func NewStderrWriter() ConsoleWriter { + return &WindowsWriter{ + out: colorable.NewColorableStderr(), + } +} diff --git a/vendor/github.com/c-bata/go-prompt/prompt.go b/vendor/github.com/c-bata/go-prompt/prompt.go new file mode 100644 index 000000000..173cd517c --- /dev/null +++ b/vendor/github.com/c-bata/go-prompt/prompt.go @@ -0,0 +1,296 @@ +package prompt + +import ( + "bytes" + "os" + "time" + + "github.com/c-bata/go-prompt/internal/debug" +) + +// Executor is called when user input something text. +type Executor func(string) + +// ExitChecker is called after user input to check if prompt must stop and exit go-prompt Run loop. +// User input means: selecting/typing an entry, then, if said entry content matches the ExitChecker function criteria: +// - immediate exit (if breakline is false) without executor called +// - exit after typing (meaning breakline is true), and the executor is called first, before exit. +// Exit means exit go-prompt (not the overall Go program) +type ExitChecker func(in string, breakline bool) bool + +// Completer should return the suggest item from Document. +type Completer func(Document) []Suggest + +// Prompt is core struct of go-prompt. +type Prompt struct { + in ConsoleParser + buf *Buffer + renderer *Render + executor Executor + history *History + completion *CompletionManager + keyBindings []KeyBind + ASCIICodeBindings []ASCIICodeBind + keyBindMode KeyBindMode + completionOnDown bool + exitChecker ExitChecker + skipTearDown bool +} + +// Exec is the struct contains user input context. +type Exec struct { + input string +} + +// Run starts prompt. +func (p *Prompt) Run() { + p.skipTearDown = false + defer debug.Teardown() + debug.Log("start prompt") + p.setUp() + defer p.tearDown() + + if p.completion.showAtStart { + p.completion.Update(*p.buf.Document()) + } + + p.renderer.Render(p.buf, p.completion) + + bufCh := make(chan []byte, 128) + stopReadBufCh := make(chan struct{}) + go p.readBuffer(bufCh, stopReadBufCh) + + exitCh := make(chan int) + winSizeCh := make(chan *WinSize) + stopHandleSignalCh := make(chan struct{}) + go p.handleSignals(exitCh, winSizeCh, stopHandleSignalCh) + + for { + select { + case b := <-bufCh: + if shouldExit, e := p.feed(b); shouldExit { + p.renderer.BreakLine(p.buf) + stopReadBufCh <- struct{}{} + stopHandleSignalCh <- struct{}{} + return + } else if e != nil { + // Stop goroutine to run readBuffer function + stopReadBufCh <- struct{}{} + stopHandleSignalCh <- struct{}{} + + // Unset raw mode + // Reset to Blocking mode because returned EAGAIN when still set non-blocking mode. + debug.AssertNoError(p.in.TearDown()) + p.executor(e.input) + + p.completion.Update(*p.buf.Document()) + + p.renderer.Render(p.buf, p.completion) + + if p.exitChecker != nil && p.exitChecker(e.input, true) { + p.skipTearDown = true + return + } + // Set raw mode + debug.AssertNoError(p.in.Setup()) + go p.readBuffer(bufCh, stopReadBufCh) + go p.handleSignals(exitCh, winSizeCh, stopHandleSignalCh) + } else { + p.completion.Update(*p.buf.Document()) + p.renderer.Render(p.buf, p.completion) + } + case w := <-winSizeCh: + p.renderer.UpdateWinSize(w) + p.renderer.Render(p.buf, p.completion) + case code := <-exitCh: + p.renderer.BreakLine(p.buf) + p.tearDown() + os.Exit(code) + default: + time.Sleep(10 * time.Millisecond) + } + } +} + +func (p *Prompt) feed(b []byte) (shouldExit bool, exec *Exec) { + key := GetKey(b) + p.buf.lastKeyStroke = key + // completion + completing := p.completion.Completing() + p.handleCompletionKeyBinding(key, completing) + + switch key { + case Enter, ControlJ, ControlM: + p.renderer.BreakLine(p.buf) + + exec = &Exec{input: p.buf.Text()} + p.buf = NewBuffer() + if exec.input != "" { + p.history.Add(exec.input) + } + case ControlC: + p.renderer.BreakLine(p.buf) + p.buf = NewBuffer() + p.history.Clear() + case Up, ControlP: + if !completing { // Don't use p.completion.Completing() because it takes double operation when switch to selected=-1. + if newBuf, changed := p.history.Older(p.buf); changed { + p.buf = newBuf + } + } + case Down, ControlN: + if !completing { // Don't use p.completion.Completing() because it takes double operation when switch to selected=-1. + if newBuf, changed := p.history.Newer(p.buf); changed { + p.buf = newBuf + } + return + } + case ControlD: + if p.buf.Text() == "" { + shouldExit = true + return + } + case NotDefined: + if p.handleASCIICodeBinding(b) { + return + } + p.buf.InsertText(string(b), false, true) + } + + shouldExit = p.handleKeyBinding(key) + return +} + +func (p *Prompt) handleCompletionKeyBinding(key Key, completing bool) { + switch key { + case Down: + if completing || p.completionOnDown { + p.completion.Next() + } + case Tab, ControlI: + p.completion.Next() + case Up: + if completing { + p.completion.Previous() + } + case BackTab: + p.completion.Previous() + default: + if s, ok := p.completion.GetSelectedSuggestion(); ok { + w := p.buf.Document().GetWordBeforeCursorUntilSeparator(p.completion.wordSeparator) + if w != "" { + p.buf.DeleteBeforeCursor(len([]rune(w))) + } + p.buf.InsertText(s.Text, false, true) + } + p.completion.Reset() + } +} + +func (p *Prompt) handleKeyBinding(key Key) bool { + shouldExit := false + for i := range commonKeyBindings { + kb := commonKeyBindings[i] + if kb.Key == key { + kb.Fn(p.buf) + } + } + + if p.keyBindMode == EmacsKeyBind { + for i := range emacsKeyBindings { + kb := emacsKeyBindings[i] + if kb.Key == key { + kb.Fn(p.buf) + } + } + } + + // Custom key bindings + for i := range p.keyBindings { + kb := p.keyBindings[i] + if kb.Key == key { + kb.Fn(p.buf) + } + } + if p.exitChecker != nil && p.exitChecker(p.buf.Text(), false) { + shouldExit = true + } + return shouldExit +} + +func (p *Prompt) handleASCIICodeBinding(b []byte) bool { + checked := false + for _, kb := range p.ASCIICodeBindings { + if bytes.Equal(kb.ASCIICode, b) { + kb.Fn(p.buf) + checked = true + } + } + return checked +} + +// Input just returns user input text. +func (p *Prompt) Input() string { + defer debug.Teardown() + debug.Log("start prompt") + p.setUp() + defer p.tearDown() + + if p.completion.showAtStart { + p.completion.Update(*p.buf.Document()) + } + + p.renderer.Render(p.buf, p.completion) + bufCh := make(chan []byte, 128) + stopReadBufCh := make(chan struct{}) + go p.readBuffer(bufCh, stopReadBufCh) + + for { + select { + case b := <-bufCh: + if shouldExit, e := p.feed(b); shouldExit { + p.renderer.BreakLine(p.buf) + stopReadBufCh <- struct{}{} + return "" + } else if e != nil { + // Stop goroutine to run readBuffer function + stopReadBufCh <- struct{}{} + return e.input + } else { + p.completion.Update(*p.buf.Document()) + p.renderer.Render(p.buf, p.completion) + } + default: + time.Sleep(10 * time.Millisecond) + } + } +} + +func (p *Prompt) readBuffer(bufCh chan []byte, stopCh chan struct{}) { + debug.Log("start reading buffer") + for { + select { + case <-stopCh: + debug.Log("stop reading buffer") + return + default: + if b, err := p.in.Read(); err == nil && !(len(b) == 1 && b[0] == 0) { + bufCh <- b + } + } + time.Sleep(10 * time.Millisecond) + } +} + +func (p *Prompt) setUp() { + debug.AssertNoError(p.in.Setup()) + p.renderer.Setup() + p.renderer.UpdateWinSize(p.in.GetWinSize()) +} + +func (p *Prompt) tearDown() { + if !p.skipTearDown { + debug.AssertNoError(p.in.TearDown()) + } + p.renderer.TearDown() +} diff --git a/vendor/github.com/c-bata/go-prompt/render.go b/vendor/github.com/c-bata/go-prompt/render.go new file mode 100644 index 000000000..299ac48b6 --- /dev/null +++ b/vendor/github.com/c-bata/go-prompt/render.go @@ -0,0 +1,287 @@ +package prompt + +import ( + "runtime" + + "github.com/c-bata/go-prompt/internal/debug" + runewidth "github.com/mattn/go-runewidth" +) + +// Render to render prompt information from state of Buffer. +type Render struct { + out ConsoleWriter + prefix string + livePrefixCallback func() (prefix string, useLivePrefix bool) + breakLineCallback func(*Document) + title string + row uint16 + col uint16 + + previousCursor int + + // colors, + prefixTextColor Color + prefixBGColor Color + inputTextColor Color + inputBGColor Color + previewSuggestionTextColor Color + previewSuggestionBGColor Color + suggestionTextColor Color + suggestionBGColor Color + selectedSuggestionTextColor Color + selectedSuggestionBGColor Color + descriptionTextColor Color + descriptionBGColor Color + selectedDescriptionTextColor Color + selectedDescriptionBGColor Color + scrollbarThumbColor Color + scrollbarBGColor Color +} + +// Setup to initialize console output. +func (r *Render) Setup() { + if r.title != "" { + r.out.SetTitle(r.title) + debug.AssertNoError(r.out.Flush()) + } +} + +// getCurrentPrefix to get current prefix. +// If live-prefix is enabled, return live-prefix. +func (r *Render) getCurrentPrefix() string { + if prefix, ok := r.livePrefixCallback(); ok { + return prefix + } + return r.prefix +} + +func (r *Render) renderPrefix() { + r.out.SetColor(r.prefixTextColor, r.prefixBGColor, false) + r.out.WriteStr(r.getCurrentPrefix()) + r.out.SetColor(DefaultColor, DefaultColor, false) +} + +// TearDown to clear title and erasing. +func (r *Render) TearDown() { + r.out.ClearTitle() + r.out.EraseDown() + debug.AssertNoError(r.out.Flush()) +} + +func (r *Render) prepareArea(lines int) { + for i := 0; i < lines; i++ { + r.out.ScrollDown() + } + for i := 0; i < lines; i++ { + r.out.ScrollUp() + } +} + +// UpdateWinSize called when window size is changed. +func (r *Render) UpdateWinSize(ws *WinSize) { + r.row = ws.Row + r.col = ws.Col +} + +func (r *Render) renderWindowTooSmall() { + r.out.CursorGoTo(0, 0) + r.out.EraseScreen() + r.out.SetColor(DarkRed, White, false) + r.out.WriteStr("Your console window is too small...") +} + +func (r *Render) renderCompletion(buf *Buffer, completions *CompletionManager) { + suggestions := completions.GetSuggestions() + if len(completions.GetSuggestions()) == 0 { + return + } + prefix := r.getCurrentPrefix() + formatted, width := formatSuggestions( + suggestions, + int(r.col)-runewidth.StringWidth(prefix)-1, // -1 means a width of scrollbar + ) + // +1 means a width of scrollbar. + width++ + + windowHeight := len(formatted) + if windowHeight > int(completions.max) { + windowHeight = int(completions.max) + } + formatted = formatted[completions.verticalScroll : completions.verticalScroll+windowHeight] + r.prepareArea(windowHeight) + + cursor := runewidth.StringWidth(prefix) + runewidth.StringWidth(buf.Document().TextBeforeCursor()) + x, _ := r.toPos(cursor) + if x+width >= int(r.col) { + cursor = r.backward(cursor, x+width-int(r.col)) + } + + contentHeight := len(completions.tmp) + + fractionVisible := float64(windowHeight) / float64(contentHeight) + fractionAbove := float64(completions.verticalScroll) / float64(contentHeight) + + scrollbarHeight := int(clamp(float64(windowHeight), 1, float64(windowHeight)*fractionVisible)) + scrollbarTop := int(float64(windowHeight) * fractionAbove) + + isScrollThumb := func(row int) bool { + return scrollbarTop <= row && row <= scrollbarTop+scrollbarHeight + } + + selected := completions.selected - completions.verticalScroll + r.out.SetColor(White, Cyan, false) + for i := 0; i < windowHeight; i++ { + r.out.CursorDown(1) + if i == selected { + r.out.SetColor(r.selectedSuggestionTextColor, r.selectedSuggestionBGColor, true) + } else { + r.out.SetColor(r.suggestionTextColor, r.suggestionBGColor, false) + } + r.out.WriteStr(formatted[i].Text) + + if i == selected { + r.out.SetColor(r.selectedDescriptionTextColor, r.selectedDescriptionBGColor, false) + } else { + r.out.SetColor(r.descriptionTextColor, r.descriptionBGColor, false) + } + r.out.WriteStr(formatted[i].Description) + + if isScrollThumb(i) { + r.out.SetColor(DefaultColor, r.scrollbarThumbColor, false) + } else { + r.out.SetColor(DefaultColor, r.scrollbarBGColor, false) + } + r.out.WriteStr(" ") + r.out.SetColor(DefaultColor, DefaultColor, false) + + r.lineWrap(cursor + width) + r.backward(cursor+width, width) + } + + if x+width >= int(r.col) { + r.out.CursorForward(x + width - int(r.col)) + } + + r.out.CursorUp(windowHeight) + r.out.SetColor(DefaultColor, DefaultColor, false) +} + +// Render renders to the console. +func (r *Render) Render(buffer *Buffer, completion *CompletionManager) { + // In situations where a pseudo tty is allocated (e.g. within a docker container), + // window size via TIOCGWINSZ is not immediately available and will result in 0,0 dimensions. + if r.col == 0 { + return + } + defer func() { debug.AssertNoError(r.out.Flush()) }() + r.move(r.previousCursor, 0) + + line := buffer.Text() + prefix := r.getCurrentPrefix() + cursor := runewidth.StringWidth(prefix) + runewidth.StringWidth(line) + + // prepare area + _, y := r.toPos(cursor) + + h := y + 1 + int(completion.max) + if h > int(r.row) || completionMargin > int(r.col) { + r.renderWindowTooSmall() + return + } + + // Rendering + r.out.HideCursor() + defer r.out.ShowCursor() + + r.renderPrefix() + r.out.SetColor(r.inputTextColor, r.inputBGColor, false) + r.out.WriteStr(line) + r.out.SetColor(DefaultColor, DefaultColor, false) + r.lineWrap(cursor) + + r.out.EraseDown() + + cursor = r.backward(cursor, runewidth.StringWidth(line)-buffer.DisplayCursorPosition()) + + r.renderCompletion(buffer, completion) + if suggest, ok := completion.GetSelectedSuggestion(); ok { + cursor = r.backward(cursor, runewidth.StringWidth(buffer.Document().GetWordBeforeCursorUntilSeparator(completion.wordSeparator))) + + r.out.SetColor(r.previewSuggestionTextColor, r.previewSuggestionBGColor, false) + r.out.WriteStr(suggest.Text) + r.out.SetColor(DefaultColor, DefaultColor, false) + cursor += runewidth.StringWidth(suggest.Text) + + rest := buffer.Document().TextAfterCursor() + r.out.WriteStr(rest) + cursor += runewidth.StringWidth(rest) + r.lineWrap(cursor) + + cursor = r.backward(cursor, runewidth.StringWidth(rest)) + } + r.previousCursor = cursor +} + +// BreakLine to break line. +func (r *Render) BreakLine(buffer *Buffer) { + // Erasing and Render + cursor := runewidth.StringWidth(buffer.Document().TextBeforeCursor()) + runewidth.StringWidth(r.getCurrentPrefix()) + r.clear(cursor) + r.renderPrefix() + r.out.SetColor(r.inputTextColor, r.inputBGColor, false) + r.out.WriteStr(buffer.Document().Text + "\n") + r.out.SetColor(DefaultColor, DefaultColor, false) + debug.AssertNoError(r.out.Flush()) + if r.breakLineCallback != nil { + r.breakLineCallback(buffer.Document()) + } + + r.previousCursor = 0 +} + +// clear erases the screen from a beginning of input +// even if there is line break which means input length exceeds a window's width. +func (r *Render) clear(cursor int) { + r.move(cursor, 0) + r.out.EraseDown() +} + +// backward moves cursor to backward from a current cursor position +// regardless there is a line break. +func (r *Render) backward(from, n int) int { + return r.move(from, from-n) +} + +// move moves cursor to specified position from the beginning of input +// even if there is a line break. +func (r *Render) move(from, to int) int { + fromX, fromY := r.toPos(from) + toX, toY := r.toPos(to) + + r.out.CursorUp(fromY - toY) + r.out.CursorBackward(fromX - toX) + return to +} + +// toPos returns the relative position from the beginning of the string. +func (r *Render) toPos(cursor int) (x, y int) { + col := int(r.col) + return cursor % col, cursor / col +} + +func (r *Render) lineWrap(cursor int) { + if runtime.GOOS != "windows" && cursor > 0 && cursor%int(r.col) == 0 { + r.out.WriteRaw([]byte{'\n'}) + } +} + +func clamp(high, low, x float64) float64 { + switch { + case high < x: + return high + case x < low: + return low + default: + return x + } +} diff --git a/vendor/github.com/c-bata/go-prompt/shortcut.go b/vendor/github.com/c-bata/go-prompt/shortcut.go new file mode 100644 index 000000000..be8d42827 --- /dev/null +++ b/vendor/github.com/c-bata/go-prompt/shortcut.go @@ -0,0 +1,43 @@ +package prompt + +func dummyExecutor(in string) {} + +// Input get the input data from the user and return it. +func Input(prefix string, completer Completer, opts ...Option) string { + pt := New(dummyExecutor, completer) + pt.renderer.prefixTextColor = DefaultColor + pt.renderer.prefix = prefix + + for _, opt := range opts { + if err := opt(pt); err != nil { + panic(err) + } + } + return pt.Input() +} + +// Choose to the shortcut of input function to select from string array. +// Deprecated: Maybe anyone want to use this. +func Choose(prefix string, choices []string, opts ...Option) string { + completer := newChoiceCompleter(choices, FilterHasPrefix) + pt := New(dummyExecutor, completer) + pt.renderer.prefixTextColor = DefaultColor + pt.renderer.prefix = prefix + + for _, opt := range opts { + if err := opt(pt); err != nil { + panic(err) + } + } + return pt.Input() +} + +func newChoiceCompleter(choices []string, filter Filter) Completer { + s := make([]Suggest, len(choices)) + for i := range choices { + s[i] = Suggest{Text: choices[i]} + } + return func(x Document) []Suggest { + return filter(s, x.GetWordBeforeCursor(), true) + } +} diff --git a/vendor/github.com/c-bata/go-prompt/signal_posix.go b/vendor/github.com/c-bata/go-prompt/signal_posix.go new file mode 100644 index 000000000..f3150df5d --- /dev/null +++ b/vendor/github.com/c-bata/go-prompt/signal_posix.go @@ -0,0 +1,49 @@ +// +build !windows + +package prompt + +import ( + "os" + "os/signal" + "syscall" + + "github.com/c-bata/go-prompt/internal/debug" +) + +func (p *Prompt) handleSignals(exitCh chan int, winSizeCh chan *WinSize, stop chan struct{}) { + in := p.in + sigCh := make(chan os.Signal, 1) + signal.Notify( + sigCh, + syscall.SIGINT, + syscall.SIGTERM, + syscall.SIGQUIT, + syscall.SIGWINCH, + ) + + for { + select { + case <-stop: + debug.Log("stop handleSignals") + return + case s := <-sigCh: + switch s { + case syscall.SIGINT: // kill -SIGINT XXXX or Ctrl+c + debug.Log("Catch SIGINT") + exitCh <- 0 + + case syscall.SIGTERM: // kill -SIGTERM XXXX + debug.Log("Catch SIGTERM") + exitCh <- 1 + + case syscall.SIGQUIT: // kill -SIGQUIT XXXX + debug.Log("Catch SIGQUIT") + exitCh <- 0 + + case syscall.SIGWINCH: + debug.Log("Catch SIGWINCH") + winSizeCh <- in.GetWinSize() + } + } + } +} diff --git a/vendor/github.com/c-bata/go-prompt/signal_windows.go b/vendor/github.com/c-bata/go-prompt/signal_windows.go new file mode 100644 index 000000000..3a427c79e --- /dev/null +++ b/vendor/github.com/c-bata/go-prompt/signal_windows.go @@ -0,0 +1,44 @@ +// +build windows + +package prompt + +import ( + "os" + "os/signal" + "syscall" + + "github.com/c-bata/go-prompt/internal/debug" +) + +func (p *Prompt) handleSignals(exitCh chan int, winSizeCh chan *WinSize, stop chan struct{}) { + sigCh := make(chan os.Signal, 1) + signal.Notify( + sigCh, + syscall.SIGINT, + syscall.SIGTERM, + syscall.SIGQUIT, + ) + + for { + select { + case <-stop: + debug.Log("stop handleSignals") + return + case s := <-sigCh: + switch s { + + case syscall.SIGINT: // kill -SIGINT XXXX or Ctrl+c + debug.Log("Catch SIGINT") + exitCh <- 0 + + case syscall.SIGTERM: // kill -SIGTERM XXXX + debug.Log("Catch SIGTERM") + exitCh <- 1 + + case syscall.SIGQUIT: // kill -SIGQUIT XXXX + debug.Log("Catch SIGQUIT") + exitCh <- 0 + } + } + } +} diff --git a/vendor/github.com/mattn/go-tty/.travis.yml b/vendor/github.com/mattn/go-tty/.travis.yml new file mode 100644 index 000000000..63b9f7084 --- /dev/null +++ b/vendor/github.com/mattn/go-tty/.travis.yml @@ -0,0 +1,4 @@ +language: go +sudo: false +go: + - tip diff --git a/vendor/github.com/mattn/go-tty/LICENSE b/vendor/github.com/mattn/go-tty/LICENSE new file mode 100644 index 000000000..e364750d2 --- /dev/null +++ b/vendor/github.com/mattn/go-tty/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2018 Yasuhiro Matsumoto + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/mattn/go-tty/README.md b/vendor/github.com/mattn/go-tty/README.md new file mode 100644 index 000000000..6712eb49d --- /dev/null +++ b/vendor/github.com/mattn/go-tty/README.md @@ -0,0 +1,49 @@ +# go-tty + +Simple tty utility + +## Usage + +```go +tty, err := tty.Open() +if err != nil { + log.Fatal(err) +} +defer tty.Close() + +for { + r, err := tty.ReadRune() + if err != nil { + log.Fatal(err) + } + // handle key event +} +``` + +if you are on windows and want to display ANSI colors, use go-colorable. + +```go +tty, err := tty.Open() +if err != nil { + log.Fatal(err) +} +defer tty.Close() + +out := colorable.NewColorable(tty.Output()) + +fmt.Fprintln(out, "\x1b[2J") +``` + +## Installation + +``` +$ go get github.com/mattn/go-tty +``` + +## License + +MIT + +## Author + +Yasuhiro Matsumoto (a.k.a mattn) diff --git a/vendor/github.com/mattn/go-tty/tty.go b/vendor/github.com/mattn/go-tty/tty.go new file mode 100644 index 000000000..13cb206a2 --- /dev/null +++ b/vendor/github.com/mattn/go-tty/tty.go @@ -0,0 +1,128 @@ +package tty + +import ( + "os" + "strings" + "unicode" +) + +func Open() (*TTY, error) { + return open("/dev/tty") +} + +func OpenDevice(path string) (*TTY, error) { + return open(path) +} + +func (tty *TTY) Raw() (func() error, error) { + return tty.raw() +} + +func (tty *TTY) MustRaw() func() error { + f, err := tty.raw() + if err != nil { + panic(err.Error()) + } + return f +} + +func (tty *TTY) Buffered() bool { + return tty.buffered() +} + +func (tty *TTY) ReadRune() (rune, error) { + return tty.readRune() +} + +func (tty *TTY) Close() error { + return tty.close() +} + +func (tty *TTY) Size() (int, int, error) { + return tty.size() +} + +func (tty *TTY) SizePixel() (int, int, int, int, error) { + return tty.sizePixel() +} + +func (tty *TTY) Input() *os.File { + return tty.input() +} + +func (tty *TTY) Output() *os.File { + return tty.output() +} + +// Display types. +const ( + displayNone = iota + displayRune + displayMask +) + +func (tty *TTY) readString(displayType int) (string, error) { + rs := []rune{} +loop: + for { + r, err := tty.readRune() + if err != nil { + return "", err + } + switch r { + case 13: + break loop + case 8, 127: + if len(rs) > 0 { + rs = rs[:len(rs)-1] + if displayType != displayNone { + tty.Output().WriteString("\b \b") + } + } + default: + if unicode.IsPrint(r) { + rs = append(rs, r) + switch displayType { + case displayRune: + tty.Output().WriteString(string(r)) + case displayMask: + tty.Output().WriteString("*") + } + } + } + } + return string(rs), nil +} + +func (tty *TTY) ReadString() (string, error) { + defer tty.Output().WriteString("\n") + return tty.readString(displayRune) +} + +func (tty *TTY) ReadPassword() (string, error) { + defer tty.Output().WriteString("\n") + return tty.readString(displayMask) +} + +func (tty *TTY) ReadPasswordNoEcho() (string, error) { + defer tty.Output().WriteString("\n") + return tty.readString(displayNone) +} + +func (tty *TTY) ReadPasswordClear() (string, error) { + s, err := tty.readString(displayMask) + tty.Output().WriteString( + strings.Repeat("\b", len(s)) + + strings.Repeat(" ", len(s)) + + strings.Repeat("\b", len(s))) + return s, err +} + +type WINSIZE struct { + W int + H int +} + +func (tty *TTY) SIGWINCH() <-chan WINSIZE { + return tty.sigwinch() +} diff --git a/vendor/github.com/mattn/go-tty/tty_bsd.go b/vendor/github.com/mattn/go-tty/tty_bsd.go new file mode 100644 index 000000000..e0a51fc0d --- /dev/null +++ b/vendor/github.com/mattn/go-tty/tty_bsd.go @@ -0,0 +1,12 @@ +// +build darwin dragonfly freebsd netbsd openbsd + +package tty + +import ( + "syscall" +) + +const ( + ioctlReadTermios = syscall.TIOCGETA + ioctlWriteTermios = syscall.TIOCSETA +) diff --git a/vendor/github.com/mattn/go-tty/tty_linux.go b/vendor/github.com/mattn/go-tty/tty_linux.go new file mode 100644 index 000000000..1b9e8cef6 --- /dev/null +++ b/vendor/github.com/mattn/go-tty/tty_linux.go @@ -0,0 +1,8 @@ +// +build linux + +package tty + +const ( + ioctlReadTermios = 0x5401 // syscall.TCGETS + ioctlWriteTermios = 0x5402 // syscall.TCSETS +) diff --git a/vendor/github.com/mattn/go-tty/tty_plan9.go b/vendor/github.com/mattn/go-tty/tty_plan9.go new file mode 100644 index 000000000..782895356 --- /dev/null +++ b/vendor/github.com/mattn/go-tty/tty_plan9.go @@ -0,0 +1,69 @@ +package tty + +import ( + "bufio" + "errors" + "os" + "syscall" +) + +type TTY struct { + in *os.File + bin *bufio.Reader + out *os.File +} + +func open(path string) (*TTY, error) { + tty := new(TTY) + + in, err := os.Open("/dev/cons") + if err != nil { + return nil, err + } + tty.in = in + tty.bin = bufio.NewReader(in) + + out, err := os.OpenFile("/dev/cons", syscall.O_WRONLY, 0) + if err != nil { + return nil, err + } + tty.out = out + + return tty, nil +} + +func (tty *TTY) buffered() bool { + return tty.bin.Buffered() > 0 +} + +func (tty *TTY) readRune() (rune, error) { + r, _, err := tty.bin.ReadRune() + return r, err +} + +func (tty *TTY) close() (err error) { + if err2 := tty.in.Close(); err2 != nil { + err = err2 + } + if err2 := tty.out.Close(); err2 != nil { + err = err2 + } + return +} + +func (tty *TTY) size() (int, int, error) { + return 80, 24, nil +} + +func (tty *TTY) sizePixel() (int, int, int, int, error) { + x, y, _ := tty.size() + return x, y, -1, -1, errors.New("no implemented method for querying size in pixels on Plan 9") +} + +func (tty *TTY) input() *os.File { + return tty.in +} + +func (tty *TTY) output() *os.File { + return tty.out +} diff --git a/vendor/github.com/mattn/go-tty/tty_sys5.go b/vendor/github.com/mattn/go-tty/tty_sys5.go new file mode 100644 index 000000000..7dc30eda8 --- /dev/null +++ b/vendor/github.com/mattn/go-tty/tty_sys5.go @@ -0,0 +1,12 @@ +// +build solaris + +package tty + +import ( + "golang.org/x/sys/unix" +) + +const ( + ioctlReadTermios = unix.TCGETA + ioctlWriteTermios = unix.TCSETA +) diff --git a/vendor/github.com/mattn/go-tty/tty_unix.go b/vendor/github.com/mattn/go-tty/tty_unix.go new file mode 100644 index 000000000..3cb945057 --- /dev/null +++ b/vendor/github.com/mattn/go-tty/tty_unix.go @@ -0,0 +1,142 @@ +// +build !windows +// +build !plan9 + +package tty + +import ( + "bufio" + "os" + "os/signal" + "syscall" + "unsafe" + + "golang.org/x/sys/unix" +) + +type TTY struct { + in *os.File + bin *bufio.Reader + out *os.File + termios syscall.Termios + ss chan os.Signal +} + +func open(path string) (*TTY, error) { + tty := new(TTY) + + in, err := os.Open(path) + if err != nil { + return nil, err + } + tty.in = in + tty.bin = bufio.NewReader(in) + + out, err := os.OpenFile(path, syscall.O_WRONLY, 0) + if err != nil { + return nil, err + } + tty.out = out + + if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(tty.in.Fd()), ioctlReadTermios, uintptr(unsafe.Pointer(&tty.termios))); err != 0 { + return nil, err + } + newios := tty.termios + newios.Iflag &^= syscall.ISTRIP | syscall.INLCR | syscall.ICRNL | syscall.IGNCR | syscall.IXOFF + newios.Lflag &^= syscall.ECHO | syscall.ICANON /*| syscall.ISIG*/ + if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(tty.in.Fd()), ioctlWriteTermios, uintptr(unsafe.Pointer(&newios))); err != 0 { + return nil, err + } + + tty.ss = make(chan os.Signal, 1) + + return tty, nil +} + +func (tty *TTY) buffered() bool { + return tty.bin.Buffered() > 0 +} + +func (tty *TTY) readRune() (rune, error) { + r, _, err := tty.bin.ReadRune() + return r, err +} + +func (tty *TTY) close() error { + signal.Stop(tty.ss) + close(tty.ss) + _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(tty.in.Fd()), ioctlWriteTermios, uintptr(unsafe.Pointer(&tty.termios))) + return err +} + +func (tty *TTY) size() (int, int, error) { + x, y, _, _, err := tty.sizePixel() + return x, y, err +} + +func (tty *TTY) sizePixel() (int, int, int, int, error) { + var dim [4]uint16 + if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(tty.out.Fd()), uintptr(syscall.TIOCGWINSZ), uintptr(unsafe.Pointer(&dim))); err != 0 { + return -1, -1, -1, -1, err + } + return int(dim[1]), int(dim[0]), int(dim[2]), int(dim[3]), nil +} + +func (tty *TTY) input() *os.File { + return tty.in +} + +func (tty *TTY) output() *os.File { + return tty.out +} + +func (tty *TTY) raw() (func() error, error) { + termios, err := unix.IoctlGetTermios(int(tty.in.Fd()), ioctlReadTermios) + if err != nil { + return nil, err + } + backup := *termios + + termios.Iflag &^= unix.IGNBRK | unix.BRKINT | unix.PARMRK | unix.ISTRIP | unix.INLCR | unix.IGNCR | unix.ICRNL | unix.IXON + termios.Oflag &^= unix.OPOST + termios.Lflag &^= unix.ECHO | unix.ECHONL | unix.ICANON | unix.ISIG | unix.IEXTEN + termios.Cflag &^= unix.CSIZE | unix.PARENB + termios.Cflag |= unix.CS8 + termios.Cc[unix.VMIN] = 1 + termios.Cc[unix.VTIME] = 0 + if err := unix.IoctlSetTermios(int(tty.in.Fd()), ioctlWriteTermios, termios); err != nil { + return nil, err + } + + return func() error { + if err := unix.IoctlSetTermios(int(tty.in.Fd()), ioctlWriteTermios, &backup); err != nil { + return err + } + return nil + }, nil +} + +func (tty *TTY) sigwinch() <-chan WINSIZE { + signal.Notify(tty.ss, syscall.SIGWINCH) + + ws := make(chan WINSIZE) + go func() { + defer close(ws) + for sig := range tty.ss { + if sig != syscall.SIGWINCH { + continue + } + + w, h, err := tty.size() + if err != nil { + continue + } + // send but do not block for it + select { + case ws <- WINSIZE{W: w, H: h}: + default: + } + + } + }() + return ws +} diff --git a/vendor/github.com/mattn/go-tty/tty_windows.go b/vendor/github.com/mattn/go-tty/tty_windows.go new file mode 100644 index 000000000..73ba6c783 --- /dev/null +++ b/vendor/github.com/mattn/go-tty/tty_windows.go @@ -0,0 +1,383 @@ +// +build windows + +package tty + +import ( + "context" + "errors" + "os" + "syscall" + "unsafe" + + "github.com/mattn/go-isatty" +) + +const ( + rightAltPressed = 1 + leftAltPressed = 2 + rightCtrlPressed = 4 + leftCtrlPressed = 8 + shiftPressed = 0x0010 + ctrlPressed = rightCtrlPressed | leftCtrlPressed + altPressed = rightAltPressed | leftAltPressed +) + +const ( + enableProcessedInput = 0x1 + enableLineInput = 0x2 + enableEchoInput = 0x4 + enableWindowInput = 0x8 + enableMouseInput = 0x10 + enableInsertMode = 0x20 + enableQuickEditMode = 0x40 + enableExtendedFlag = 0x80 + + enableProcessedOutput = 1 + enableWrapAtEolOutput = 2 + + keyEvent = 0x1 + mouseEvent = 0x2 + windowBufferSizeEvent = 0x4 +) + +var kernel32 = syscall.NewLazyDLL("kernel32.dll") + +var ( + procAllocConsole = kernel32.NewProc("AllocConsole") + procSetStdHandle = kernel32.NewProc("SetStdHandle") + procGetStdHandle = kernel32.NewProc("GetStdHandle") + procSetConsoleScreenBufferSize = kernel32.NewProc("SetConsoleScreenBufferSize") + procCreateConsoleScreenBuffer = kernel32.NewProc("CreateConsoleScreenBuffer") + procGetConsoleScreenBufferInfo = kernel32.NewProc("GetConsoleScreenBufferInfo") + procWriteConsoleOutputCharacter = kernel32.NewProc("WriteConsoleOutputCharacterW") + procWriteConsoleOutputAttribute = kernel32.NewProc("WriteConsoleOutputAttribute") + procGetConsoleCursorInfo = kernel32.NewProc("GetConsoleCursorInfo") + procSetConsoleCursorInfo = kernel32.NewProc("SetConsoleCursorInfo") + procSetConsoleCursorPosition = kernel32.NewProc("SetConsoleCursorPosition") + procReadConsoleInput = kernel32.NewProc("ReadConsoleInputW") + procGetConsoleMode = kernel32.NewProc("GetConsoleMode") + procSetConsoleMode = kernel32.NewProc("SetConsoleMode") + procFillConsoleOutputCharacter = kernel32.NewProc("FillConsoleOutputCharacterW") + procFillConsoleOutputAttribute = kernel32.NewProc("FillConsoleOutputAttribute") + procScrollConsoleScreenBuffer = kernel32.NewProc("ScrollConsoleScreenBufferW") +) + +type wchar uint16 +type short int16 +type dword uint32 +type word uint16 + +type coord struct { + x short + y short +} + +type smallRect struct { + left short + top short + right short + bottom short +} + +type consoleScreenBufferInfo struct { + size coord + cursorPosition coord + attributes word + window smallRect + maximumWindowSize coord +} + +type consoleCursorInfo struct { + size dword + visible int32 +} + +type inputRecord struct { + eventType word + _ [2]byte + event [16]byte +} + +type keyEventRecord struct { + keyDown int32 + repeatCount word + virtualKeyCode word + virtualScanCode word + unicodeChar wchar + controlKeyState dword +} + +type windowBufferSizeRecord struct { + size coord +} + +type mouseEventRecord struct { + mousePos coord + buttonState dword + controlKeyState dword + eventFlags dword +} + +type charInfo struct { + unicodeChar wchar + attributes word +} + +type TTY struct { + in *os.File + out *os.File + st uint32 + rs []rune + ws chan WINSIZE + sigwinchCtx context.Context + sigwinchCtxCancel context.CancelFunc +} + +func readConsoleInput(fd uintptr, record *inputRecord) (err error) { + var w uint32 + r1, _, err := procReadConsoleInput.Call(fd, uintptr(unsafe.Pointer(record)), 1, uintptr(unsafe.Pointer(&w))) + if r1 == 0 { + return err + } + return nil +} + +func open(path string) (*TTY, error) { + tty := new(TTY) + if false && isatty.IsTerminal(os.Stdin.Fd()) { + tty.in = os.Stdin + } else { + in, err := syscall.Open("CONIN$", syscall.O_RDWR, 0) + if err != nil { + return nil, err + } + + tty.in = os.NewFile(uintptr(in), "/dev/tty") + } + + if isatty.IsTerminal(os.Stdout.Fd()) { + tty.out = os.Stdout + } else { + procAllocConsole.Call() + out, err := syscall.Open("CONOUT$", syscall.O_RDWR, 0) + if err != nil { + return nil, err + } + + tty.out = os.NewFile(uintptr(out), "/dev/tty") + } + + h := tty.in.Fd() + var st uint32 + r1, _, err := procGetConsoleMode.Call(h, uintptr(unsafe.Pointer(&st))) + if r1 == 0 { + return nil, err + } + tty.st = st + + st &^= enableEchoInput + st &^= enableInsertMode + st &^= enableLineInput + st &^= enableMouseInput + st &^= enableWindowInput + st &^= enableExtendedFlag + st &^= enableQuickEditMode + + // ignore error + procSetConsoleMode.Call(h, uintptr(st)) + + tty.ws = make(chan WINSIZE) + tty.sigwinchCtx, tty.sigwinchCtxCancel = context.WithCancel(context.Background()) + + return tty, nil +} + +func (tty *TTY) buffered() bool { + return len(tty.rs) > 0 +} + +func (tty *TTY) readRune() (rune, error) { + if len(tty.rs) > 0 { + r := tty.rs[0] + tty.rs = tty.rs[1:] + return r, nil + } + var ir inputRecord + err := readConsoleInput(tty.in.Fd(), &ir) + if err != nil { + return 0, err + } + + switch ir.eventType { + case windowBufferSizeEvent: + wr := (*windowBufferSizeRecord)(unsafe.Pointer(&ir.event)) + ws := WINSIZE{ + W: int(wr.size.x), + H: int(wr.size.y), + } + + if err := tty.sigwinchCtx.Err(); err != nil { + // closing + // the following select might panic without this guard close + return 0, err + } + + select { + case tty.ws <- ws: + case <-tty.sigwinchCtx.Done(): + return 0, tty.sigwinchCtx.Err() + default: + return 0, nil // no one is currently trying to read + } + case keyEvent: + kr := (*keyEventRecord)(unsafe.Pointer(&ir.event)) + if kr.keyDown != 0 { + if kr.controlKeyState&altPressed != 0 && kr.unicodeChar > 0 { + tty.rs = []rune{rune(kr.unicodeChar)} + return rune(0x1b), nil + } + if kr.unicodeChar > 0 { + if kr.controlKeyState&shiftPressed != 0 { + switch kr.unicodeChar { + case 0x09: + tty.rs = []rune{0x5b, 0x5a} + return rune(0x1b), nil + } + } + return rune(kr.unicodeChar), nil + } + vk := kr.virtualKeyCode + if kr.controlKeyState&ctrlPressed != 0 { + switch vk { + case 0x21: // ctrl-page-up + tty.rs = []rune{0x5b, 0x35, 0x3B, 0x35, 0x7e} + return rune(0x1b), nil + case 0x22: // ctrl-page-down + tty.rs = []rune{0x5b, 0x36, 0x3B, 0x35, 0x7e} + return rune(0x1b), nil + case 0x23: // ctrl-end + tty.rs = []rune{0x5b, 0x31, 0x3B, 0x35, 0x46} + return rune(0x1b), nil + case 0x24: // ctrl-home + tty.rs = []rune{0x5b, 0x31, 0x3B, 0x35, 0x48} + return rune(0x1b), nil + case 0x25: // ctrl-left + tty.rs = []rune{0x5b, 0x31, 0x3B, 0x35, 0x44} + return rune(0x1b), nil + case 0x26: // ctrl-up + tty.rs = []rune{0x5b, 0x31, 0x3B, 0x35, 0x41} + return rune(0x1b), nil + case 0x27: // ctrl-right + tty.rs = []rune{0x5b, 0x31, 0x3B, 0x35, 0x43} + return rune(0x1b), nil + case 0x28: // ctrl-down + tty.rs = []rune{0x5b, 0x31, 0x3B, 0x35, 0x42} + return rune(0x1b), nil + case 0x2e: // ctrl-delete + tty.rs = []rune{0x5b, 0x33, 0x3B, 0x35, 0x7e} + return rune(0x1b), nil + } + } + switch vk { + case 0x21: // page-up + tty.rs = []rune{0x5b, 0x35, 0x7e} + return rune(0x1b), nil + case 0x22: // page-down + tty.rs = []rune{0x5b, 0x36, 0x7e} + return rune(0x1b), nil + case 0x23: // end + tty.rs = []rune{0x5b, 0x46} + return rune(0x1b), nil + case 0x24: // home + tty.rs = []rune{0x5b, 0x48} + return rune(0x1b), nil + case 0x25: // left + tty.rs = []rune{0x5b, 0x44} + return rune(0x1b), nil + case 0x26: // up + tty.rs = []rune{0x5b, 0x41} + return rune(0x1b), nil + case 0x27: // right + tty.rs = []rune{0x5b, 0x43} + return rune(0x1b), nil + case 0x28: // down + tty.rs = []rune{0x5b, 0x42} + return rune(0x1b), nil + case 0x2e: // delete + tty.rs = []rune{0x5b, 0x33, 0x7e} + return rune(0x1b), nil + case 0x70, 0x71, 0x72, 0x73: // F1,F2,F3,F4 + tty.rs = []rune{0x5b, 0x4f, rune(vk) - 0x20} + return rune(0x1b), nil + case 0x074, 0x75, 0x76, 0x77: // F5,F6,F7,F8 + tty.rs = []rune{0x5b, 0x31, rune(vk) - 0x3f, 0x7e} + return rune(0x1b), nil + case 0x78, 0x79: // F9,F10 + tty.rs = []rune{0x5b, 0x32, rune(vk) - 0x48, 0x7e} + return rune(0x1b), nil + case 0x7a, 0x7b: // F11,F12 + tty.rs = []rune{0x5b, 0x32, rune(vk) - 0x47, 0x7e} + return rune(0x1b), nil + } + return 0, nil + } + } + return 0, nil +} + +func (tty *TTY) close() error { + procSetConsoleMode.Call(tty.in.Fd(), uintptr(tty.st)) + tty.sigwinchCtxCancel() + close(tty.ws) + return nil +} + +func (tty *TTY) size() (int, int, error) { + var csbi consoleScreenBufferInfo + r1, _, err := procGetConsoleScreenBufferInfo.Call(tty.out.Fd(), uintptr(unsafe.Pointer(&csbi))) + if r1 == 0 { + return 0, 0, err + } + return int(csbi.window.right - csbi.window.left + 1), int(csbi.window.bottom - csbi.window.top + 1), nil +} + +func (tty *TTY) sizePixel() (int, int, int, int, error) { + x, y, err := tty.size() + if err != nil { + x = -1 + y = -1 + } + return x, y, -1, -1, errors.New("no implemented method for querying size in pixels on Windows") +} + +func (tty *TTY) input() *os.File { + return tty.in +} + +func (tty *TTY) output() *os.File { + return tty.out +} + +func (tty *TTY) raw() (func() error, error) { + var st uint32 + r1, _, err := procGetConsoleMode.Call(tty.in.Fd(), uintptr(unsafe.Pointer(&st))) + if r1 == 0 { + return nil, err + } + mode := st &^ (enableEchoInput | enableProcessedInput | enableLineInput | enableProcessedOutput) + r1, _, err = procSetConsoleMode.Call(tty.in.Fd(), uintptr(mode)) + if r1 == 0 { + return nil, err + } + return func() error { + r1, _, err := procSetConsoleMode.Call(tty.in.Fd(), uintptr(st)) + if r1 == 0 { + return err + } + return nil + }, nil +} + +func (tty *TTY) sigwinch() <-chan WINSIZE { + return tty.ws +} diff --git a/vendor/github.com/pkg/term/LICENSE b/vendor/github.com/pkg/term/LICENSE new file mode 100644 index 000000000..8b9d1574f --- /dev/null +++ b/vendor/github.com/pkg/term/LICENSE @@ -0,0 +1,10 @@ +Copyright (c) 2014, David Cheney +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/pkg/term/termios/doc.go b/vendor/github.com/pkg/term/termios/doc.go new file mode 100644 index 000000000..7b178c2df --- /dev/null +++ b/vendor/github.com/pkg/term/termios/doc.go @@ -0,0 +1,4 @@ +// Package termios implements the low level termios(3) terminal line discipline facilities. +// +// For a higher level interface please use the github.com/pkg/term package. +package termios diff --git a/vendor/github.com/pkg/term/termios/ioctl.go b/vendor/github.com/pkg/term/termios/ioctl.go new file mode 100644 index 000000000..10aa2b138 --- /dev/null +++ b/vendor/github.com/pkg/term/termios/ioctl.go @@ -0,0 +1,9 @@ +// +build !windows + +package termios + +import "golang.org/x/sys/unix" + +func ioctl(fd, request, argp uintptr) error { + return unix.IoctlSetInt(int(fd), uint(request), int(argp)) +} diff --git a/vendor/github.com/pkg/term/termios/pty.go b/vendor/github.com/pkg/term/termios/pty.go new file mode 100644 index 000000000..2f88d0252 --- /dev/null +++ b/vendor/github.com/pkg/term/termios/pty.go @@ -0,0 +1,48 @@ +// +build !windows + +package termios + +import ( + "fmt" + "os" + + "golang.org/x/sys/unix" +) + +func open_device(path string) (uintptr, error) { + fd, err := unix.Open(path, unix.O_NOCTTY|unix.O_RDWR|unix.O_CLOEXEC, 0666) + if err != nil { + return 0, fmt.Errorf("unable to open %q: %v", path, err) + } + return uintptr(fd), nil +} + +// Pty returns a UNIX 98 pseudoterminal device. +// Pty returns a pair of fds representing the master and slave pair. +func Pty() (*os.File, *os.File, error) { + ptm, err := open_pty_master() + if err != nil { + return nil, nil, err + } + + sname, err := Ptsname(ptm) + if err != nil { + return nil, nil, err + } + + err = grantpt(ptm) + if err != nil { + return nil, nil, err + } + + err = unlockpt(ptm) + if err != nil { + return nil, nil, err + } + + pts, err := open_device(sname) + if err != nil { + return nil, nil, err + } + return os.NewFile(uintptr(ptm), "ptm"), os.NewFile(uintptr(pts), sname), nil +} diff --git a/vendor/github.com/pkg/term/termios/pty_cgo.go b/vendor/github.com/pkg/term/termios/pty_cgo.go new file mode 100644 index 000000000..568f9cf5a --- /dev/null +++ b/vendor/github.com/pkg/term/termios/pty_cgo.go @@ -0,0 +1,37 @@ +// +build dragonfly openbsd solaris + +package termios + +// #include +import "C" + +import "syscall" + +func open_pty_master() (uintptr, error) { + rc := C.posix_openpt(syscall.O_NOCTTY | syscall.O_RDWR) + if rc < 0 { + return 0, syscall.Errno(rc) + } + return uintptr(rc), nil +} + +func Ptsname(fd uintptr) (string, error) { + slavename := C.GoString(C.ptsname(C.int(fd))) + return slavename, nil +} + +func grantpt(fd uintptr) error { + rc := C.grantpt(C.int(fd)) + if rc == 0 { + return nil + } + return syscall.Errno(rc) +} + +func unlockpt(fd uintptr) error { + rc := C.unlockpt(C.int(fd)) + if rc == 0 { + return nil + } + return syscall.Errno(rc) +} diff --git a/vendor/github.com/pkg/term/termios/pty_darwin.go b/vendor/github.com/pkg/term/termios/pty_darwin.go new file mode 100644 index 000000000..a57357a94 --- /dev/null +++ b/vendor/github.com/pkg/term/termios/pty_darwin.go @@ -0,0 +1,45 @@ +package termios + +import ( + "errors" + "unsafe" + + "golang.org/x/sys/unix" +) + +func open_pty_master() (uintptr, error) { + return open_device("/dev/ptmx") +} + +const ( + _IOC_PARAM_SHIFT = 13 + _IOC_PARAM_MASK = (1 << _IOC_PARAM_SHIFT) - 1 +) + +func _IOC_PARM_LEN(ioctl uintptr) uintptr { + return (ioctl >> 16) & _IOC_PARAM_MASK +} + +func Ptsname(fd uintptr) (string, error) { + n := make([]byte, _IOC_PARM_LEN(unix.TIOCPTYGNAME)) + + err := ioctl(fd, unix.TIOCPTYGNAME, uintptr(unsafe.Pointer(&n[0]))) + if err != nil { + return "", err + } + + for i, c := range n { + if c == 0 { + return string(n[:i]), nil + } + } + return "", errors.New("TIOCPTYGNAME string not NUL-terminated") +} + +func grantpt(fd uintptr) error { + return unix.IoctlSetInt(int(fd), unix.TIOCPTYGRANT, 0) +} + +func unlockpt(fd uintptr) error { + return unix.IoctlSetInt(int(fd), unix.TIOCPTYUNLK, 0) +} diff --git a/vendor/github.com/pkg/term/termios/pty_freebsd.go b/vendor/github.com/pkg/term/termios/pty_freebsd.go new file mode 100644 index 000000000..f7bf882b8 --- /dev/null +++ b/vendor/github.com/pkg/term/termios/pty_freebsd.go @@ -0,0 +1,34 @@ +package termios + +import ( + "fmt" + + "golang.org/x/sys/unix" +) + +func posix_openpt(oflag int) (fd uintptr, err error) { + // Copied from debian-golang-pty/pty_freebsd.go. + r0, _, e1 := unix.Syscall(unix.SYS_POSIX_OPENPT, uintptr(oflag), 0, 0) + fd = uintptr(r0) + if e1 != 0 { + err = e1 + } + return +} + +func open_pty_master() (uintptr, error) { + return posix_openpt(unix.O_NOCTTY | unix.O_RDWR | unix.O_CLOEXEC) +} + +func Ptsname(fd uintptr) (string, error) { + n, err := unix.IoctlGetInt(int(fd), unix.TIOCGPTN) + return fmt.Sprintf("/dev/pts/%d", n), err +} + +func grantpt(fd uintptr) error { + return unix.IoctlSetInt(int(fd), unix.TIOCGPTN, 0) +} + +func unlockpt(fd uintptr) error { + return nil +} diff --git a/vendor/github.com/pkg/term/termios/pty_linux.go b/vendor/github.com/pkg/term/termios/pty_linux.go new file mode 100644 index 000000000..018511c1e --- /dev/null +++ b/vendor/github.com/pkg/term/termios/pty_linux.go @@ -0,0 +1,27 @@ +package termios + +import ( + "fmt" + "unsafe" + + "golang.org/x/sys/unix" +) + +func open_pty_master() (uintptr, error) { + return open_device("/dev/ptmx") +} + +func Ptsname(fd uintptr) (string, error) { + n, err := unix.IoctlGetInt(int(fd), unix.TIOCGPTN) + return fmt.Sprintf("/dev/pts/%d", n), err +} + +func grantpt(fd uintptr) error { + var n uintptr + return ioctl(fd, unix.TIOCGPTN, uintptr(unsafe.Pointer(&n))) +} + +func unlockpt(fd uintptr) error { + var n uintptr + return ioctl(fd, unix.TIOCSPTLCK, uintptr(unsafe.Pointer(&n))) +} diff --git a/vendor/github.com/pkg/term/termios/pty_netbsd.go b/vendor/github.com/pkg/term/termios/pty_netbsd.go new file mode 100644 index 000000000..c921017b6 --- /dev/null +++ b/vendor/github.com/pkg/term/termios/pty_netbsd.go @@ -0,0 +1,27 @@ +package termios + +import ( + "bytes" + + "golang.org/x/sys/unix" +) + +func open_pty_master() (uintptr, error) { + return open_device("/dev/ptmx") +} + +func Ptsname(fd uintptr) (string, error) { + ptm, err := unix.IoctlGetPtmget(int(fd), unix.TIOCPTSNAME) + if err != nil { + return "", err + } + return string(ptm.Sn[:bytes.IndexByte(ptm.Sn[:], 0)]), nil +} + +func grantpt(fd uintptr) error { + return unix.IoctlSetInt(int(fd), unix.TIOCGRANTPT, 0) +} + +func unlockpt(fd uintptr) error { + return nil +} diff --git a/vendor/github.com/pkg/term/termios/termios.go b/vendor/github.com/pkg/term/termios/termios.go new file mode 100644 index 000000000..8ef8ea2c8 --- /dev/null +++ b/vendor/github.com/pkg/term/termios/termios.go @@ -0,0 +1,50 @@ +// +build !windows + +package termios + +import ( + "golang.org/x/sys/unix" +) + +// Tiocmget returns the state of the MODEM bits. +func Tiocmget(fd uintptr) (int, error) { + return unix.IoctlGetInt(int(fd), unix.TIOCMGET) +} + +// Tiocmset sets the state of the MODEM bits. +func Tiocmset(fd uintptr, status int) error { + return unix.IoctlSetInt(int(fd), unix.TIOCMSET, status) +} + +// Tiocmbis sets the indicated modem bits. +func Tiocmbis(fd uintptr, status int) error { + return unix.IoctlSetPointerInt(int(fd), unix.TIOCMBIS, status) +} + +// Tiocmbic clears the indicated modem bits. +func Tiocmbic(fd uintptr, status int) error { + return unix.IoctlSetPointerInt(int(fd), unix.TIOCMBIC, status) +} + +// Tiocoutq return the number of bytes in the output buffer. +func Tiocoutq(fd uintptr) (int, error) { + return unix.IoctlGetInt(int(fd), unix.TIOCOUTQ) +} + +// Cfmakecbreak modifies attr for cbreak mode. +func Cfmakecbreak(attr *unix.Termios) { + attr.Lflag &^= unix.ECHO | unix.ICANON + attr.Cc[unix.VMIN] = 1 + attr.Cc[unix.VTIME] = 0 +} + +// Cfmakeraw modifies attr for raw mode. +func Cfmakeraw(attr *unix.Termios) { + attr.Iflag &^= unix.BRKINT | unix.ICRNL | unix.INPCK | unix.ISTRIP | unix.IXON + attr.Oflag &^= unix.OPOST + attr.Cflag &^= unix.CSIZE | unix.PARENB + attr.Cflag |= unix.CS8 + attr.Lflag &^= unix.ECHO | unix.ICANON | unix.IEXTEN | unix.ISIG + attr.Cc[unix.VMIN] = 1 + attr.Cc[unix.VTIME] = 0 +} diff --git a/vendor/github.com/pkg/term/termios/termios_bsd.go b/vendor/github.com/pkg/term/termios/termios_bsd.go new file mode 100644 index 000000000..86221c204 --- /dev/null +++ b/vendor/github.com/pkg/term/termios/termios_bsd.go @@ -0,0 +1,70 @@ +// +build darwin freebsd openbsd netbsd dragonfly + +package termios + +import ( + "time" + + "golang.org/x/sys/unix" +) + +const ( + IXON = 0x00000200 + IXOFF = 0x00000400 + IXANY = 0x00000800 + CCTS_OFLOW = 0x00010000 + CRTS_IFLOW = 0x00020000 + CRTSCTS = CCTS_OFLOW | CRTS_IFLOW +) + +// Tcgetattr gets the current serial port settings. +func Tcgetattr(fd uintptr) (*unix.Termios, error) { + return unix.IoctlGetTermios(int(fd), unix.TIOCGETA) +} + +// Tcsetattr sets the current serial port settings. +func Tcsetattr(fd, opt uintptr, argp *unix.Termios) error { + switch opt { + case TCSANOW: + opt = unix.TIOCSETA + case TCSADRAIN: + opt = unix.TIOCSETAW + case TCSAFLUSH: + opt = unix.TIOCSETAF + default: + return unix.EINVAL + } + return unix.IoctlSetTermios(int(fd), uint(opt), argp) +} + +// Tcsendbreak function transmits a continuous stream of zero-valued bits for +// four-tenths of a second to the terminal referenced by fildes. The duration +// parameter is ignored in this implementation. +func Tcsendbreak(fd uintptr, duration int) error { + if err := unix.IoctlSetInt(int(fd), unix.TIOCSBRK, 0); err != nil { + return err + } + time.Sleep(4 / 10 * time.Second) + return unix.IoctlSetInt(int(fd), unix.TIOCCBRK, 0) +} + +// Tcdrain waits until all output written to the terminal referenced by fd has been transmitted to the terminal. +func Tcdrain(fd uintptr) error { + return unix.IoctlSetInt(int(fd), unix.TIOCDRAIN, 0) +} + +// Tcflush discards data written to the object referred to by fd but not transmitted, or data received but not read, depending on the value of which. +func Tcflush(fd, which uintptr) error { + return unix.IoctlSetPointerInt(int(fd), unix.TIOCFLUSH, int(which)) +} + +// Cfgetispeed returns the input baud rate stored in the termios structure. +func Cfgetispeed(attr *unix.Termios) uint32 { return uint32(attr.Ispeed) } + +// Cfgetospeed returns the output baud rate stored in the termios structure. +func Cfgetospeed(attr *unix.Termios) uint32 { return uint32(attr.Ospeed) } + +// Tiocinq returns the number of bytes in the input buffer. +func Tiocinq(fd uintptr) (int, error) { + return 0, nil +} diff --git a/vendor/github.com/pkg/term/termios/termios_const.go b/vendor/github.com/pkg/term/termios/termios_const.go new file mode 100644 index 000000000..7e319bc85 --- /dev/null +++ b/vendor/github.com/pkg/term/termios/termios_const.go @@ -0,0 +1,13 @@ +// +build !windows,!solaris + +package termios + +const ( + TCIFLUSH = 0 + TCOFLUSH = 1 + TCIOFLUSH = 2 + + TCSANOW = 0 + TCSADRAIN = 1 + TCSAFLUSH = 2 +) diff --git a/vendor/github.com/pkg/term/termios/termios_const_solaris.go b/vendor/github.com/pkg/term/termios/termios_const_solaris.go new file mode 100644 index 000000000..cd0f08266 --- /dev/null +++ b/vendor/github.com/pkg/term/termios/termios_const_solaris.go @@ -0,0 +1,14 @@ +package termios + +// #include +import "C" + +const ( + TCIFLUSH = C.TCIFLUSH + TCOFLUSH = C.TCOFLUSH + TCIOFLUSH = C.TCIOFLUSH + + TCSANOW = C.TCSANOW + TCSADRAIN = C.TCSADRAIN + TCSAFLUSH = C.TCSAFLUSH +) diff --git a/vendor/github.com/pkg/term/termios/termios_linux.go b/vendor/github.com/pkg/term/termios/termios_linux.go new file mode 100644 index 000000000..131a64b72 --- /dev/null +++ b/vendor/github.com/pkg/term/termios/termios_linux.go @@ -0,0 +1,68 @@ +package termios + +import ( + "golang.org/x/sys/unix" +) + +const ( + IXON = 0x00000400 + IXANY = 0x00000800 + IXOFF = 0x00001000 + CRTSCTS = 0x80000000 +) + +// Tcgetattr gets the current serial port settings. +func Tcgetattr(fd uintptr) (*unix.Termios, error) { + return unix.IoctlGetTermios(int(fd), unix.TCGETS) +} + +// Tcsetattr sets the current serial port settings. +func Tcsetattr(fd, action uintptr, argp *unix.Termios) error { + var request uintptr + switch action { + case TCSANOW: + request = unix.TCSETS + case TCSADRAIN: + request = unix.TCSETSW + case TCSAFLUSH: + request = unix.TCSETSF + default: + return unix.EINVAL + } + return unix.IoctlSetTermios(int(fd), uint(request), argp) +} + +// Tcsendbreak transmits a continuous stream of zero-valued bits for a specific +// duration, if the terminal is using asynchronous serial data transmission. If +// duration is zero, it transmits zero-valued bits for at least 0.25 seconds, and not more that 0.5 seconds. +// If duration is not zero, it sends zero-valued bits for some +// implementation-defined length of time. +func Tcsendbreak(fd uintptr, duration int) error { + return unix.IoctlSetInt(int(fd), unix.TCSBRKP, duration) +} + +// Tcdrain waits until all output written to the object referred to by fd has been transmitted. +func Tcdrain(fd uintptr) error { + // simulate drain with TCSADRAIN + attr, err := Tcgetattr(fd) + if err != nil { + return err + } + return Tcsetattr(fd, TCSADRAIN, attr) +} + +// Tcflush discards data written to the object referred to by fd but not transmitted, or data received but not read, depending on the value of selector. +func Tcflush(fd, selector uintptr) error { + return unix.IoctlSetInt(int(fd), unix.TCFLSH, int(selector)) +} + +// Tiocinq returns the number of bytes in the input buffer. +func Tiocinq(fd uintptr) (int, error) { + return unix.IoctlGetInt(int(fd), unix.TIOCINQ) +} + +// Cfgetispeed returns the input baud rate stored in the termios structure. +func Cfgetispeed(attr *unix.Termios) uint32 { return attr.Ispeed } + +// Cfgetospeed returns the output baud rate stored in the termios structure. +func Cfgetospeed(attr *unix.Termios) uint32 { return attr.Ospeed } diff --git a/vendor/github.com/pkg/term/termios/termios_solaris.go b/vendor/github.com/pkg/term/termios/termios_solaris.go new file mode 100644 index 000000000..959ceb383 --- /dev/null +++ b/vendor/github.com/pkg/term/termios/termios_solaris.go @@ -0,0 +1,112 @@ +package termios + +// #include +// typedef struct termios termios_t; +import "C" + +import ( + "golang.org/x/sys/unix" + "unsafe" +) + +const ( + TCSETS = 0x5402 + TCSETSW = 0x5403 + TCSETSF = 0x5404 + TCSBRK = 0x5409 + TCSBRKP = 0x5425 + + IXON = 0x00000400 + IXANY = 0x00000800 + IXOFF = 0x00001000 + CRTSCTS = 0x80000000 +) + +// Tcgetattr gets the current serial port settings. +func Tcgetattr(fd uintptr) (*unix.Termios, error) { + return unix.IoctlGetTermios(int(fd), unix.TCGETS) +} + +// Tcsetattr sets the current serial port settings. +func Tcsetattr(fd, action uintptr, argp *unix.Termios) error { + return unix.IoctlSetTermios(int(fd), uint(action), tiosToUnix(argp)) +} + +// Tcsendbreak transmits a continuous stream of zero-valued bits for a specific +// duration, if the terminal is using asynchronous serial data transmission. If +// duration is zero, it transmits zero-valued bits for at least 0.25 seconds, and not more that 0.5 seconds. +// If duration is not zero, it sends zero-valued bits for some +// implementation-defined length of time. +func Tcsendbreak(fd uintptr, duration int) error { + return ioctl(fd, TCSBRKP, uintptr(duration)) +} + +// Tcdrain waits until all output written to the object referred to by fd has been transmitted. +func Tcdrain(fd uintptr) error { + // simulate drain with TCSADRAIN + var attr unix.Termios + if err := Tcgetattr(fd, &attr); err != nil { + return err + } + return Tcsetattr(fd, TCSADRAIN, &attr) +} + +// Tcflush discards data written to the object referred to by fd but not transmitted, or data received but not read, depending on the value of selector. +func Tcflush(fd, selector uintptr) error { + return ioctl(fd, unix.TCFLSH, selector) +} + +// Tiocinq returns the number of bytes in the input buffer. +func Tiocinq(fd uintptr) (int, error) { + return unix.IoctlGetInt(int(fd), unix.FIORDCHK) +} + +// Cfgetispeed returns the input baud rate stored in the termios structure. +func Cfgetispeed(attr *unix.Termios) uint32 { + solTermios := tiosToUnix(attr) + return uint32(C.cfgetispeed((*C.termios_t)(unsafe.Pointer(solTermios)))) +} + +// Cfsetispeed sets the input baud rate stored in the termios structure. +func Cfsetispeed(attr *unix.Termios, speed uintptr) error { + solTermios := tiosToUnix(attr) + _, err := C.cfsetispeed((*C.termios_t)(unsafe.Pointer(solTermios)), C.speed_t(speed)) + return err +} + +// Cfgetospeed returns the output baud rate stored in the termios structure. +func Cfgetospeed(attr *unix.Termios) uint32 { + solTermios := tiosToUnix(attr) + return uint32(C.cfgetospeed((*C.termios_t)(unsafe.Pointer(solTermios)))) +} + +// Cfsetospeed sets the output baud rate stored in the termios structure. +func Cfsetospeed(attr *unix.Termios, speed uintptr) error { + solTermios := tiosToUnix(attr) + _, err := C.cfsetospeed((*C.termios_t)(unsafe.Pointer(solTermios)), C.speed_t(speed)) + return err +} + +// tiosToUnix copies a unix.Termios to a x/sys/unix.Termios. +// This is needed since type conversions between the two fail due to +// more recent x/sys/unix.Termios renaming the padding field. +func tiosToUnix(st *unix.Termios) *unix.Termios { + return &unix.Termios{ + Iflag: st.Iflag, + Oflag: st.Oflag, + Cflag: st.Cflag, + Lflag: st.Lflag, + Cc: st.Cc, + } +} + +// tiosTounix copies a x/sys/unix.Termios to a unix.Termios. +func tiosTounix(ut *unix.Termios) *unix.Termios { + return &unix.Termios{ + Iflag: ut.Iflag, + Oflag: ut.Oflag, + Cflag: ut.Cflag, + Lflag: ut.Lflag, + Cc: ut.Cc, + } +} diff --git a/vendor/github.com/stromland/cobra-prompt/.gitignore b/vendor/github.com/stromland/cobra-prompt/.gitignore new file mode 100644 index 000000000..273a39ce2 --- /dev/null +++ b/vendor/github.com/stromland/cobra-prompt/.gitignore @@ -0,0 +1,22 @@ +# Binaries for programs and plugins +*.exe +*.dll +*.so +*.dylib + +# Test binary, build with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +# Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 +.glide/ + +# Intellij +.idea/ + +vendor/ + +_example/cobra-prompt +_example/_example \ No newline at end of file diff --git a/vendor/github.com/stromland/cobra-prompt/CHANGELOG.md b/vendor/github.com/stromland/cobra-prompt/CHANGELOG.md new file mode 100644 index 000000000..a002c090e --- /dev/null +++ b/vendor/github.com/stromland/cobra-prompt/CHANGELOG.md @@ -0,0 +1,24 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [0.5.0] - 2023-01-28 + +### Added + +- `RunContext` - option to pass context into nested command execututions. ([#9](https://github.com/stromland/cobra-prompt/pull/9) by [@klowdo](https://github.com/klowdo)) + +## [0.4.0] - 2022-10-04 + +### Added + +- `SuggestionFilter` to `CobraPrompt`. Function to decide which suggestions that should be presentet to the user. Overrides the current filter from go-prompt. ([#8](https://github.com/stromland/cobra-prompt/pull/8) by [@klowdo](https://github.com/klowdo)) + +## [0.3.0] - 2022-04-25 + +### Added + +- `InArgsParser` to `CobraPrompt`. This makes it possible to decide how arguments should be structured before passing them to Cobra. ([#7](https://github.com/stromland/cobra-prompt/pull/7) by [@klowdo](https://github.com/klowdo)) diff --git a/vendor/github.com/stromland/cobra-prompt/LICENSE b/vendor/github.com/stromland/cobra-prompt/LICENSE new file mode 100644 index 000000000..e2219e0d2 --- /dev/null +++ b/vendor/github.com/stromland/cobra-prompt/LICENSE @@ -0,0 +1,9 @@ +The MIT License (MIT) + +Copyright 2018 Espen Strømland + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/vendor/github.com/stromland/cobra-prompt/README.md b/vendor/github.com/stromland/cobra-prompt/README.md new file mode 100644 index 000000000..f2ce7ef81 --- /dev/null +++ b/vendor/github.com/stromland/cobra-prompt/README.md @@ -0,0 +1,28 @@ +# Cobra-Prompt + +Cobra-prompt makes every Cobra command and flag available for go-prompt. +- https://github.com/spf13/cobra +- https://github.com/c-bata/go-prompt + + +## Features + +- Traverse cobra command tree. Every command and flag will be available. +- Persist flag values. +- Add custom functions for dynamic suggestions. + +## Getting started + +Get the module: + +``` +go get github.com/stromland/cobra-prompt +``` + +## Explore the example + +``` +cd _example +go build -o cobra-prompt +./cobra-prompt +``` diff --git a/vendor/github.com/stromland/cobra-prompt/cobra-prompt.go b/vendor/github.com/stromland/cobra-prompt/cobra-prompt.go new file mode 100644 index 000000000..406f29479 --- /dev/null +++ b/vendor/github.com/stromland/cobra-prompt/cobra-prompt.go @@ -0,0 +1,179 @@ +package cobraprompt + +import ( + "context" + "os" + "strings" + + "github.com/c-bata/go-prompt" + "github.com/spf13/cobra" + "github.com/spf13/pflag" +) + +// DynamicSuggestionsAnnotation for dynamic suggestions. +const DynamicSuggestionsAnnotation = "cobra-prompt-dynamic-suggestions" + +// PersistFlagValuesFlag the flag that will be avaiailable when PersistFlagValues is true +const PersistFlagValuesFlag = "persist-flag-values" + +// CobraPrompt given a Cobra command it will make every flag and sub commands available as suggestions. +// Command.Short will be used as description for the suggestion. +type CobraPrompt struct { + // RootCmd is the start point, all its sub commands and flags will be available as suggestions + RootCmd *cobra.Command + + // GoPromptOptions is for customize go-prompt + // see https://github.com/c-bata/go-prompt/blob/master/option.go + GoPromptOptions []prompt.Option + + // DynamicSuggestionsFunc will be executed if an command has CallbackAnnotation as an annotation. If it's included + // the value will be provided to the DynamicSuggestionsFunc function. + DynamicSuggestionsFunc func(annotationValue string, document *prompt.Document) []prompt.Suggest + + // PersistFlagValues will persist flags. For example have verbose turned on every command. + PersistFlagValues bool + + // ShowHelpCommandAndFlags will make help command and flag for every command available. + ShowHelpCommandAndFlags bool + + // DisableCompletionCommand will disable the default completion command for cobra + DisableCompletionCommand bool + + // ShowHiddenCommands makes hidden commands available + ShowHiddenCommands bool + + // ShowHiddenFlags makes hidden flags available + ShowHiddenFlags bool + + // AddDefaultExitCommand adds a command for exiting prompt loop + AddDefaultExitCommand bool + + // OnErrorFunc handle error for command.Execute, if not set print error and exit + OnErrorFunc func(err error) + + // InArgsParser adds a custom parser for the command line arguments (default: strings.Fields) + InArgsParser func(args string) []string + + // SuggestionFilter will be uses when filtering suggestions as typing + SuggestionFilter func(suggestions []prompt.Suggest, document *prompt.Document) []prompt.Suggest +} + +// Run will automatically generate suggestions for all cobra commands and flags defined by RootCmd +// and execute the selected commands. Run will also reset all given flags by default, see PersistFlagValues +func (co CobraPrompt) Run() { + co.RunContext(nil) +} + +// RunContext same as Run but with context +func (co CobraPrompt) RunContext(ctx context.Context) { + if co.RootCmd == nil { + panic("RootCmd is not set. Please set RootCmd") + } + + co.prepare() + + p := prompt.New( + func(in string) { + promptArgs := co.parseArgs(in) + os.Args = append([]string{os.Args[0]}, promptArgs...) + if err := co.RootCmd.ExecuteContext(ctx); err != nil { + if co.OnErrorFunc != nil { + co.OnErrorFunc(err) + } else { + co.RootCmd.PrintErrln(err) + os.Exit(1) + } + } + }, + func(d prompt.Document) []prompt.Suggest { + return findSuggestions(&co, &d) + }, + co.GoPromptOptions..., + ) + + p.Run() +} + +func (co CobraPrompt) parseArgs(in string) []string { + if co.InArgsParser != nil { + return co.InArgsParser(in) + } + + return strings.Fields(in) +} + +func (co CobraPrompt) prepare() { + if co.ShowHelpCommandAndFlags { + // TODO: Add suggestions for help command + co.RootCmd.InitDefaultHelpCmd() + } + + if co.DisableCompletionCommand { + co.RootCmd.CompletionOptions.DisableDefaultCmd = true + } + + if co.AddDefaultExitCommand { + co.RootCmd.AddCommand(&cobra.Command{ + Use: "exit", + Short: "Exit prompt", + Run: func(cmd *cobra.Command, args []string) { + os.Exit(0) + }, + }) + } + + if co.PersistFlagValues { + co.RootCmd.PersistentFlags().BoolP(PersistFlagValuesFlag, "", + false, "Persist last given value for flags") + } +} + +func findSuggestions(co *CobraPrompt, d *prompt.Document) []prompt.Suggest { + command := co.RootCmd + args := strings.Fields(d.CurrentLine()) + + if found, _, err := command.Find(args); err == nil { + command = found + } + + var suggestions []prompt.Suggest + persistFlagValues, _ := command.Flags().GetBool(PersistFlagValuesFlag) + addFlags := func(flag *pflag.Flag) { + if flag.Changed && !persistFlagValues { + flag.Value.Set(flag.DefValue) + } + if flag.Hidden && !co.ShowHiddenFlags { + return + } + if strings.HasPrefix(d.GetWordBeforeCursor(), "--") { + suggestions = append(suggestions, prompt.Suggest{Text: "--" + flag.Name, Description: flag.Usage}) + } else if strings.HasPrefix(d.GetWordBeforeCursor(), "-") && flag.Shorthand != "" { + suggestions = append(suggestions, prompt.Suggest{Text: "-" + flag.Shorthand, Description: flag.Usage}) + } + } + + command.LocalFlags().VisitAll(addFlags) + command.InheritedFlags().VisitAll(addFlags) + + if command.HasAvailableSubCommands() { + for _, c := range command.Commands() { + if !c.Hidden && !co.ShowHiddenCommands { + suggestions = append(suggestions, prompt.Suggest{Text: c.Name(), Description: c.Short}) + } + if co.ShowHelpCommandAndFlags { + c.InitDefaultHelpFlag() + } + } + } + + annotation := command.Annotations[DynamicSuggestionsAnnotation] + if co.DynamicSuggestionsFunc != nil && annotation != "" { + suggestions = append(suggestions, co.DynamicSuggestionsFunc(annotation, d)...) + } + + if co.SuggestionFilter != nil { + return co.SuggestionFilter(suggestions, d) + } + + return prompt.FilterHasPrefix(suggestions, d.GetWordBeforeCursor(), true) +} diff --git a/vendor/modules.txt b/vendor/modules.txt index c12640dde..0df284719 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1,6 +1,13 @@ # github.com/VividCortex/ewma v1.2.0 ## explicit; go 1.12 github.com/VividCortex/ewma +# github.com/c-bata/go-prompt v0.2.6 +## explicit; go 1.14 +github.com/c-bata/go-prompt +github.com/c-bata/go-prompt/internal/bisect +github.com/c-bata/go-prompt/internal/debug +github.com/c-bata/go-prompt/internal/strings +github.com/c-bata/go-prompt/internal/term # github.com/cheggaaa/pb/v3 v3.1.0 ## explicit; go 1.12 github.com/cheggaaa/pb/v3 @@ -53,12 +60,12 @@ github.com/ionos-cloud/sdk-go-auth # github.com/ionos-cloud/sdk-go-cert-manager v1.0.0 ## explicit; go 1.17 github.com/ionos-cloud/sdk-go-cert-manager -# github.com/ionos-cloud/sdk-go-dataplatform v1.0.0 -## explicit; go 1.18 -github.com/ionos-cloud/sdk-go-dataplatform # github.com/ionos-cloud/sdk-go-container-registry v1.0.0 ## explicit; go 1.18 github.com/ionos-cloud/sdk-go-container-registry +# github.com/ionos-cloud/sdk-go-dataplatform v1.0.0 +## explicit; go 1.18 +github.com/ionos-cloud/sdk-go-dataplatform # github.com/ionos-cloud/sdk-go-dbaas-mongo v1.2.2 ## explicit; go 1.18 github.com/ionos-cloud/sdk-go-dbaas-mongo @@ -86,6 +93,9 @@ github.com/mattn/go-isatty # github.com/mattn/go-runewidth v0.0.14 ## explicit; go 1.9 github.com/mattn/go-runewidth +# github.com/mattn/go-tty v0.0.3 +## explicit; go 1.14 +github.com/mattn/go-tty # github.com/mitchellh/go-homedir v1.1.0 ## explicit github.com/mitchellh/go-homedir @@ -102,6 +112,9 @@ github.com/pelletier/go-toml/v2/internal/characters github.com/pelletier/go-toml/v2/internal/danger github.com/pelletier/go-toml/v2/internal/tracker github.com/pelletier/go-toml/v2/unstable +# github.com/pkg/term v1.2.0-beta.2 +## explicit; go 1.14 +github.com/pkg/term/termios # github.com/pmezard/go-difflib v1.0.0 ## explicit github.com/pmezard/go-difflib/difflib @@ -139,6 +152,9 @@ github.com/spf13/viper/internal/encoding/yaml # github.com/stretchr/testify v1.8.1 ## explicit; go 1.13 github.com/stretchr/testify/assert +# github.com/stromland/cobra-prompt v0.5.0 +## explicit; go 1.17 +github.com/stromland/cobra-prompt # github.com/subosito/gotenv v1.4.2 ## explicit; go 1.18 github.com/subosito/gotenv