Browse Source

Merge pull request #25 from Rudi9719/dev

Updating from dev
pull/27/head
Gregory Rudolph 5 years ago committed by GitHub
parent
commit
5557c17ad4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 1
      .gitignore
  2. 13
      .travis.yml
  3. 8
      README.md
  4. 26
      cmdDownload.go
  5. 29
      cmdEdit.go
  6. 2
      cmdHelp.go
  7. 2
      cmdJoin.go
  8. 12
      cmdReact.go
  9. 14
      cmdReply.go
  10. 66
      cmdSet.go
  11. 2
      cmdStream.go
  12. 17
      cmdUploadFile.go
  13. 2
      cmdWall.go
  14. 2
      cmdWallet.go
  15. 3
      emojiList.go
  16. 30
      kbtui.tml
  17. 73
      mage.go
  18. 662
      main.go
  19. 213
      tabComplete.go
  20. 2
      userConfigs.go

1
.gitignore vendored

@ -1,4 +1,5 @@ @@ -1,4 +1,5 @@
kbtui
emojiList.go
*~
.\#*
\#*\#

13
.travis.yml

@ -0,0 +1,13 @@ @@ -0,0 +1,13 @@
language: go
go:
- tip
- 1.13.x
install: true
script:
- go get -u github.com/magefile/mage/mage
- go run build.go buildBeta
- go vet ./...
- go fmt ./...

8
README.md

@ -31,16 +31,16 @@ go get -u github.com/rudi9719/kbtui @@ -31,16 +31,16 @@ go get -u github.com/rudi9719/kbtui
```
Or you can do the following:
```
go get ./
go get ./...
go run build.go
go run build.go {build, buildBeta... etc}
./kbtui
```
You may see an error with `go get ./` about PATHs, that may be safely ignored.
You may see an error with `go get ./...` about PATHs, that may be safely ignored.
If you see an error about a missing dependancy during a build, you'll want to resolve that.
Occasionally when @dxb updates his API it will be necessary to run
`go get -u ./`
Occasionally when [@dxb](https://keybase.io/dxb) updates his API it will be necessary to run
`go get -u ./...` or `go get -u samhofi.us/x/keybase`

26
cmdDownload.go

@ -19,16 +19,34 @@ func init() { @@ -19,16 +19,34 @@ func init() {
}
func cmdDownloadFile(cmd []string) {
messageID, _ := strconv.Atoi(cmd[1])
if len(cmd) < 2 {
printToView("Feed", fmt.Sprintf("%s%s $messageId $fileName - Download a file to user's downloadpath", cmdPrefix, cmd[0]))
return
}
messageID, err := strconv.Atoi(cmd[1])
if err != nil {
printToView("Feed", "There was an error converting your messageID to an int")
return
}
chat := k.NewChat(channel)
api, err := chat.ReadMessage(messageID)
if err != nil {
printToView("Feed", fmt.Sprintf("There was an error pulling message %d", messageID))
return
}
if api.Result.Messages[0].Msg.Content.Type != "attachment" {
printToView("Feed", "No attachment detected")
return
}
var fileName string
if len(cmd) == 3 {
fileName = cmd[2]
} else {
fileName = ""
fileName = api.Result.Messages[0].Msg.Content.Attachment.Object.Filename
}
chat := k.NewChat(channel)
_, err := chat.Download(messageID, fmt.Sprintf("%s/%s", downloadPath, fileName))
_, err = chat.Download(messageID, fmt.Sprintf("%s/%s", downloadPath, fileName))
if err != nil {
printToView("Feed", fmt.Sprintf("There was an error downloading %s from %s", fileName, channel.Name))
} else {

29
cmdEdit.go

@ -11,7 +11,7 @@ import ( @@ -11,7 +11,7 @@ import (
func init() {
command := Command{
Cmd: []string{"edit", "e"},
Description: "$messageId - Edit a message (messageID is optional)",
Description: "$messageID - Edit a message (messageID is optional)",
Help: "",
Exec: cmdEdit,
}
@ -20,16 +20,22 @@ func init() { @@ -20,16 +20,22 @@ func init() {
}
func cmdEdit(cmd []string) {
var messageId int
var messageID int
chat := k.NewChat(channel)
if len(cmd) == 2 || len(cmd) == 1 {
if len(cmd) == 2 {
messageId, _ = strconv.Atoi(cmd[1])
messageID, _ = strconv.Atoi(cmd[1])
} else if lastMessage.ID != 0 {
if lastMessage.Type != "text" {
printToView("Feed", "Last message isn't editable (is it an edit?)")
return
}
messageID = lastMessage.ID
} else {
messageId = lastMessage.ID
printToView("Feed", "No message to edit")
return
}
origMessage, _ := chat.ReadMessage(messageId)
origMessage, _ := chat.ReadMessage(messageID)
if origMessage.Result.Messages[0].Msg.Content.Type != "text" {
printToView("Feed", fmt.Sprintf("%+v", origMessage))
return
@ -41,19 +47,20 @@ func cmdEdit(cmd []string) { @@ -41,19 +47,20 @@ func cmdEdit(cmd []string) {
editString := origMessage.Result.Messages[0].Msg.Content.Text.Body
clearView("Edit")
popupView("Edit")
printToView("Edit", fmt.Sprintf("/e %d %s", messageId, editString))
viewTitle("Edit", fmt.Sprintf(" Editing message %d ", messageId))
printToView("Edit", fmt.Sprintf("/e %d %s", messageID, editString))
setViewTitle("Edit", fmt.Sprintf(" Editing message %d ", messageID))
moveCursorToEnd("Edit")
return
}
if len(cmd) < 3 {
printToView("Feed", "Not enough options for Edit")
return
}
messageId, _ = strconv.Atoi(cmd[1])
messageID, _ = strconv.Atoi(cmd[1])
newMessage := strings.Join(cmd[2:], " ")
_, err := chat.Edit(messageId, newMessage)
_, err := chat.Edit(messageID, newMessage)
if err != nil {
printToView("Feed", fmt.Sprintf("Error editing message %d, %+v", messageId, err))
printToView("Feed", fmt.Sprintf("Error editing message %d, %+v", messageID, err))
}
}

2
cmdHelp.go

@ -28,7 +28,7 @@ func cmdHelp(cmd []string) { @@ -28,7 +28,7 @@ func cmdHelp(cmd []string) {
helpText = fmt.Sprintf("%s%s%s\t\t%s\n", helpText, cmdPrefix, c, commands[c].Description)
}
if len(typeCommands) > 0 {
for c, _ := range typeCommands {
for c := range typeCommands {
tCommands = append(tCommands, typeCommands[c].Name)
}
sort.Strings(tCommands)

2
cmdJoin.go

@ -43,7 +43,7 @@ func cmdJoin(cmd []string) { @@ -43,7 +43,7 @@ func cmdJoin(cmd []string) {
}
printToView("Feed", fmt.Sprintf("You are joining: %s", joinedName))
clearView("Chat")
viewTitle("Input", fmt.Sprintf(" %s ", joinedName))
setViewTitle("Input", fmt.Sprintf(" %s ", joinedName))
go populateChat()
default:
printToView("Feed", fmt.Sprintf("To join a team use %sjoin <team> <channel>", cmdPrefix))

12
cmdReact.go

@ -10,7 +10,7 @@ import ( @@ -10,7 +10,7 @@ import (
func init() {
command := Command{
Cmd: []string{"react", "r", "+"},
Description: "$messageId $reaction - React to a message (messageID is optional)",
Description: "$messageID $reaction - React to a message (messageID is optional)",
Help: "",
Exec: cmdReact,
}
@ -20,7 +20,7 @@ func init() { @@ -20,7 +20,7 @@ func init() {
func cmdReact(cmd []string) {
if len(cmd) > 2 {
reactToMessageId(cmd[1], strings.Join(cmd[2:], " "))
reactToMessageID(cmd[1], strings.Join(cmd[2:], " "))
} else if len(cmd) == 2 {
reactToMessage(cmd[1])
}
@ -30,13 +30,13 @@ func cmdReact(cmd []string) { @@ -30,13 +30,13 @@ func cmdReact(cmd []string) {
func reactToMessage(reaction string) {
doReact(lastMessage.ID, reaction)
}
func reactToMessageId(messageId string, reaction string) {
ID, _ := strconv.Atoi(messageId)
func reactToMessageID(messageID string, reaction string) {
ID, _ := strconv.Atoi(messageID)
doReact(ID, reaction)
}
func doReact(messageId int, reaction string) {
func doReact(messageID int, reaction string) {
chat := k.NewChat(channel)
_, err := chat.React(messageId, reaction)
_, err := chat.React(messageID, reaction)
if err != nil {
printToView("Feed", "There was an error reacting to the message.")
}

14
cmdReply.go

@ -3,6 +3,7 @@ @@ -3,6 +3,7 @@
package main
import (
"fmt"
"strconv"
"strings"
)
@ -20,10 +21,19 @@ func init() { @@ -20,10 +21,19 @@ func init() {
func cmdReply(cmd []string) {
chat := k.NewChat(channel)
messageId, err := strconv.Atoi(cmd[1])
_, err = chat.Reply(messageId, strings.Join(cmd[2:], " "))
if len(cmd) < 2 {
printToView("Feed", fmt.Sprintf("%s%s $ID - Reply to message $ID", cmdPrefix, cmd[0]))
return
}
messageID, err := strconv.Atoi(cmd[1])
if err != nil {
printToView("Feed", fmt.Sprintf("There was an error determining message ID %s", cmd[1]))
return
}
_, err = chat.Reply(messageID, strings.Join(cmd[2:], " "))
if err != nil {
printToView("Feed", "There was an error with your reply.")
return
}
return
}

66
cmdSet.go

@ -5,6 +5,8 @@ package main @@ -5,6 +5,8 @@ package main
import (
"fmt"
"strings"
"github.com/pelletier/go-toml"
)
func init() {
@ -17,31 +19,34 @@ func init() { @@ -17,31 +19,34 @@ func init() {
RegisterCommand(command)
}
func printSetting(cmd []string) {
switch cmd[1] {
case "load":
loadFromToml()
printToView("Feed", fmt.Sprintf("Loading config from toml"))
case "downloadPath":
printToView("Feed", fmt.Sprintf("Setting for %s -> %s", cmd[1], downloadPath))
case "outputFormat":
printToView("Feed", fmt.Sprintf("Setting for %s -> %s", cmd[1], outputFormat))
case "dateFormat":
printToView("Feed", fmt.Sprintf("Setting for %s -> %s", cmd[1], dateFormat))
case "timeFormat":
printToView("Feed", fmt.Sprintf("Setting for %s -> %s", cmd[1], timeFormat))
case "cmdPrefix":
printToView("Feed", fmt.Sprintf("Setting for %s -> %s", cmd[1], cmdPrefix))
default:
printToView("Feed", fmt.Sprintf("Unknown config value %s", cmd[1]))
}
return
}
func cmdSet(cmd []string) {
if len(cmd) < 2 {
printToView("Feed", "No config value specified")
return
}
if len(cmd) < 3 {
switch cmd[1] {
case "load":
printToView("Feed", "Load values from file?")
case "downloadPath":
printToView("Feed", fmt.Sprintf("Setting for %s -> %s", cmd[1], downloadPath))
case "outputFormat":
printToView("Feed", fmt.Sprintf("Setting for %s -> %s", cmd[1], outputFormat))
case "dateFormat":
printToView("Feed", fmt.Sprintf("Setting for %s -> %s", cmd[1], dateFormat))
case "timeFormat":
printToView("Feed", fmt.Sprintf("Setting for %s -> %s", cmd[1], timeFormat))
case "cmdPrefix":
printToView("Feed", fmt.Sprintf("Setting for %s -> %s", cmd[1], cmdPrefix))
default:
printToView("Feed", fmt.Sprintf("Unknown config value %s", cmd[1]))
}
return
printSetting(cmd)
}
switch cmd[1] {
case "downloadPath":
@ -62,3 +67,28 @@ func cmdSet(cmd []string) { @@ -62,3 +67,28 @@ func cmdSet(cmd []string) {
}
}
func loadFromToml() {
config, err := toml.LoadFile("kbtui.tml")
if err != nil {
printToView("Feed", fmt.Sprintf("Could not read config file: %+v", err))
return
}
if config.Has("Basics.colorless") {
colorless = config.Get("Basics.colorless").(bool)
}
if config.Has("Basics.downloadPath") {
downloadPath = config.Get("Basics.downloadPath").(string)
}
if config.Has("Basics.cmdPrefix") {
cmdPrefix = config.Get("Basics.cmdPrefix").(string)
}
if config.Has("Formatting.outputFormat") {
outputFormat = config.Get("Formatting.outputFormat").(string)
}
if config.Has("Formatting.dateFormat") {
dateFormat = config.Get("Formatting.dateFormat").(string)
}
if config.Has("Formatting.timeFormat") {
timeFormat = config.Get("Formatting.timeFormat").(string)
}
}

2
cmdStream.go

@ -18,6 +18,6 @@ func cmdStream(cmd []string) { @@ -18,6 +18,6 @@ func cmdStream(cmd []string) {
channel.Name = ""
printToView("Feed", "You are now viewing the formatted stream")
viewTitle("Input", " Stream - Not in a chat /j to join ")
setViewTitle("Input", " Stream - Not in a chat /j to join ")
clearView("Chat")
}

17
cmdUploadFile.go

@ -4,12 +4,14 @@ package main @@ -4,12 +4,14 @@ package main
import (
"fmt"
"os"
"strings"
)
func init() {
command := Command{
Cmd: []string{"upload", "u"},
Description: "$filePath $fileName - Upload file with optional name",
Description: "$filePath $fileName - Upload file from absolute path with optional name",
Help: "",
Exec: cmdUploadFile,
}
@ -18,7 +20,18 @@ func init() { @@ -18,7 +20,18 @@ func init() {
}
func cmdUploadFile(cmd []string) {
if len(cmd) < 2 {
printToView("Feed", fmt.Sprintf("%s%s $filePath $fileName - Upload file from absolute path with optional name", cmdPrefix, cmd[0]))
return
}
filePath := cmd[1]
if !strings.HasPrefix(filePath, "/") {
dir, err := os.Getwd()
if err != nil {
printToView("Feed", fmt.Sprintf("There was an error determining path %+v", err))
}
filePath = fmt.Sprintf("%s/%s", dir, filePath)
}
var fileName string
if len(cmd) == 3 {
fileName = cmd[2]
@ -28,7 +41,7 @@ func cmdUploadFile(cmd []string) { @@ -28,7 +41,7 @@ func cmdUploadFile(cmd []string) {
chat := k.NewChat(channel)
_, err := chat.Upload(fileName, filePath)
if err != nil {
printToView("Feed", fmt.Sprintf("There was an error uploading %s to %s", filePath, channel.Name))
printToView("Feed", fmt.Sprintf("There was an error uploading %s to %s\n%+v", filePath, channel.Name, err))
} else {
printToView("Feed", fmt.Sprintf("Uploaded %s to %s", filePath, channel.Name))
}

2
cmdWall.go

@ -15,7 +15,7 @@ import ( @@ -15,7 +15,7 @@ import (
func init() {
command := Command{
Cmd: []string{"wall", "w"},
Description: "- Show public messages for a user",
Description: "$user / !all - Show public messages for a user or all users you follow",
Help: "",
Exec: cmdWall,
}

2
cmdWallet.go

@ -34,7 +34,7 @@ func cmdWallet(cmd []string) { @@ -34,7 +34,7 @@ func cmdWallet(cmd []string) {
chars := []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"abcdefghijklmnopqrstuvwxyz" +
"0123456789")
length := 5
length := 8
var b strings.Builder
for i := 0; i < length; i++ {
b.WriteRune(chars[rand.Intn(len(chars))])

3
emojiList.go

File diff suppressed because one or more lines are too long

30
kbtui.tml

@ -0,0 +1,30 @@ @@ -0,0 +1,30 @@
[Basics]
downloadPath = "/tmp/"
colorless = false
# The prefix before evaluating a command
cmdPrefix = "/"
[Formatting]
# BASH-like PS1 variable equivalent
outputFormat = "┌──[$USER@$DEVICE] [$ID] [$DATE - $TIME]\n└╼ $MSG"
# 02 = Day, Jan = Month, 06 = Year
dateFormat = "02Jan06"
# 15 = hours, 04 = minutes, 05 = seconds
timeFormat = "15:04"
[Colors]
channelsColor = 8
channelsHeaderColor = 6
noColor = -1
mentionColor = 3
messageHeaderColor = 8
messageIdColor = 7
messageTimeColor = 6
messageSenderDefaultColor = 8
messageSenderDeviceColor = 8
messageBodyColor = -1
messageAttachmentColor = 2
messageLinkColor = 4

73
mage.go

@ -5,12 +5,13 @@ package main @@ -5,12 +5,13 @@ package main
import (
"encoding/json"
"fmt"
"github.com/magefile/mage/mg"
"github.com/magefile/mage/sh"
"io/ioutil"
"net/http"
"os"
"strings"
"github.com/magefile/mage/mg"
"github.com/magefile/mage/sh"
)
// emoji related constants
@ -61,8 +62,34 @@ func createEmojiSlice() ([]string, error) { @@ -61,8 +62,34 @@ func createEmojiSlice() ([]string, error) {
return emojiSlice, nil
}
func getRemotePackages() error {
var packages = []string{
"samhofi.us/x/keybase",
"github.com/awesome-gocui/gocui",
"github.com/magefile/mage/mage",
"github.com/magefile/mage/mg",
"github.com/magefile/mage/sh",
"github.com/pelletier/go-toml",
}
for _, p := range packages {
if err := sh.Run("go", "get", "-u", p); err != nil {
return err
}
}
return nil
}
// proper error reporting and exit code
func exit(err error) {
if err != nil {
fmt.Fprintf(os.Stderr, "%+v\n", err)
os.Exit(1)
}
}
// Build kbtui with emoji lookup support
func BuildEmoji() error {
mg.Deps(getRemotePackages)
emojis, err := createEmojiSlice()
if err != nil {
return err
@ -84,14 +111,24 @@ func BuildEmoji() error { @@ -84,14 +111,24 @@ func BuildEmoji() error {
// Build kbtui with just the basic commands.
func Build() {
sh.Run("go", "build")
mg.Deps(getRemotePackages)
if err := sh.Run("go", "build"); err != nil {
defer func() {
exit(err)
}()
}
}
// Build kbtui with the basic commands, and the ShowReactions "TypeCommand".
// The ShowReactions TypeCommand will print a message in the feed window when
// a reaction is received in the current conversation.
func BuildShowReactions() {
sh.Run("go", "build", "-tags", "showreactionscmd")
mg.Deps(getRemotePackages)
if err := sh.Run("go", "build", "-tags", "showreactionscmd"); err != nil {
defer func() {
exit(err)
}()
}
}
// Build kbtui with the basec commands, and the AutoReact "TypeCommand".
@ -99,21 +136,41 @@ func BuildShowReactions() { @@ -99,21 +136,41 @@ func BuildShowReactions() {
// received in the current conversation. This gets pretty annoying, and
// is not recommended.
func BuildAutoReact() {
sh.Run("go", "build", "-tags", "autoreactcmd")
mg.Deps(getRemotePackages)
if err := sh.Run("go", "build", "-tags", "autoreactcmd"); err != nil {
defer func() {
exit(err)
}()
}
}
// Build kbtui with all commands and TypeCommands disabled.
func BuildAllCommands() {
sh.Run("go", "build", "-tags", "allcommands")
mg.Deps(getRemotePackages)
if err := sh.Run("go", "build", "-tags", "allcommands"); err != nil {
defer func() {
exit(err)
}()
}
}
// Build kbtui with all Commands and TypeCommands enabled.
func BuildAllCommandsT() {
sh.Run("go", "build", "-tags", "type_commands,allcommands")
mg.Deps(getRemotePackages)
if err := sh.Run("go", "build", "-tags", "type_commands,allcommands"); err != nil {
defer func() {
exit(err)
}()
}
}
// Build kbtui with beta functionality
func BuildBeta() {
mg.Deps(getRemotePackages)
mg.Deps(BuildEmoji)
sh.Run("go", "build", "-tags", "allcommands,showreactionscmd,emojiList")
if err := sh.Run("go", "build", "-tags", "allcommands,showreactionscmd,emojiList,tabcompletion"); err != nil {
defer func() {
exit(err)
}()
}
}

662
main.go

@ -4,7 +4,6 @@ import ( @@ -4,7 +4,6 @@ import (
"fmt"
"log"
"os"
"regexp"
"strings"
"time"
@ -12,17 +11,19 @@ import ( @@ -12,17 +11,19 @@ import (
"samhofi.us/x/keybase"
)
var typeCommands = make(map[string]TypeCommand)
var commands = make(map[string]Command)
var baseCommands = make([]string, 0)
var dev = false
var k = keybase.NewKeybase()
var channel keybase.Channel
var channels []keybase.Channel
var stream = false
var lastMessage keybase.ChatAPI
var g *gocui.Gui
var (
typeCommands = make(map[string]TypeCommand)
commands = make(map[string]Command)
baseCommands = make([]string, 0)
dev = false
k = keybase.NewKeybase()
channel keybase.Channel
channels []keybase.Channel
stream = false
lastMessage keybase.ChatAPI
g *gocui.Gui
)
func main() {
if !k.LoggedIn {
@ -50,31 +51,137 @@ func main() { @@ -50,31 +51,137 @@ func main() {
if err := g.MainLoop(); err != nil && !gocui.IsQuit(err) {
fmt.Printf("%+v", err)
}
go generateChannelTabCompletionSlice()
}
func viewTitle(viewName string, title string) {
// Gocui basic setup
func layout(g *gocui.Gui) error {
maxX, maxY := g.Size()
if editView, err := g.SetView("Edit", maxX/2-maxX/3+1, maxY/2, maxX-2, maxY/2+10, 0); err != nil {
if !gocui.IsUnknownView(err) {
return err
}
editView.Editable = true
editView.Wrap = true
fmt.Fprintln(editView, "Edit window. Should disappear")
}
if feedView, err := g.SetView("Feed", maxX/2-maxX/3, 0, maxX-1, maxY/5, 0); err != nil {
if !gocui.IsUnknownView(err) {
return err
}
feedView.Autoscroll = true
feedView.Wrap = true
feedView.Title = "Feed Window"
fmt.Fprintln(feedView, "Feed Window - If you are mentioned or receive a PM it will show here")
}
if chatView, err2 := g.SetView("Chat", maxX/2-maxX/3, maxY/5+1, maxX-1, maxY-5, 0); err2 != nil {
if !gocui.IsUnknownView(err2) {
return err2
}
chatView.Autoscroll = true
chatView.Wrap = true
fmt.Fprintf(chatView, "Welcome %s!\n\nYour chats will appear here.\nSupported commands are as follows:\n\n", k.Username)
RunCommand("help")
}
if inputView, err3 := g.SetView("Input", maxX/2-maxX/3, maxY-4, maxX-1, maxY-1, 0); err3 != nil {
if !gocui.IsUnknownView(err3) {
return err3
}
if _, err := g.SetCurrentView("Input"); err != nil {
return err
}
inputView.Editable = true
inputView.Wrap = true
inputView.Title = fmt.Sprintf(" Not in a chat - write `%sj` to join", cmdPrefix)
g.Cursor = true
}
if listView, err4 := g.SetView("List", 0, 0, maxX/2-maxX/3-1, maxY-1, 0); err4 != nil {
if !gocui.IsUnknownView(err4) {
return err4
}
listView.Title = "Channels"
fmt.Fprintf(listView, "Lists\nWindow\nTo view\n activity")
}
return nil
}
func initKeybindings() error {
if err := g.SetKeybinding("", gocui.KeyCtrlC, gocui.ModNone,
func(g *gocui.Gui, v *gocui.View) error {
input, err := getInputString("Input")
if err != nil {
return err
}
if input != "" {
clearView("Input")
return nil
}
return gocui.ErrQuit
}); err != nil {
return err
}
if err := g.SetKeybinding("Edit", gocui.KeyCtrlC, gocui.ModNone,
func(g *gocui.Gui, v *gocui.View) error {
popupView("Chat")
popupView("Input")
clearView("Edit")
return nil
}); err != nil {
return err
}
if err := g.SetKeybinding("Input", gocui.KeyEnter, gocui.ModNone,
func(g *gocui.Gui, v *gocui.View) error {
return handleInput("Input")
}); err != nil {
return err
}
if err := g.SetKeybinding("Input", gocui.KeyTab, gocui.ModNone,
func(g *gocui.Gui, v *gocui.View) error {
return handleTab("Input")
}); err != nil {
return err
}
if err := g.SetKeybinding("Edit", gocui.KeyEnter, gocui.ModNone,
func(g *gocui.Gui, v *gocui.View) error {
popupView("Chat")
popupView("Input")
return handleInput("Edit")
}); err != nil {
return err
}
if err := g.SetKeybinding("Input", gocui.KeyArrowUp, gocui.ModNone,
func(g *gocui.Gui, v *gocui.View) error {
RunCommand("edit")
return nil
}); err != nil {
return err
}
return nil
}
// End gocui basic setup
// Gocui helper funcs
func setViewTitle(viewName string, title string) {
g.Update(func(g *gocui.Gui) error {
updatingView, err := g.View(viewName)
if err != nil {
return err
} else {
updatingView.Title = title
}
updatingView.Title = title
return nil
})
}
func getViewTitle(viewName string) string {
view, err := g.View(viewName)
if err != nil {
// in case there is active tab completion, filter that to just the view title and not the completion options.
writeToView("Feed", fmt.Sprintf("Error getting view title: %s", err))
printToView("Feed", fmt.Sprintf("Error getting view title: %s", err))
return ""
} else {
return strings.Split(view.Title, "||")[0]
}
}
return strings.Split(view.Title, "||")[0]
}
func popupView(viewName string) {
_, err := g.SetCurrentView(viewName)
if err != nil {
@ -88,15 +195,83 @@ func popupView(viewName string) { @@ -88,15 +195,83 @@ func popupView(viewName string) {
updatingView, err := g.View(viewName)
if err != nil {
return err
} else {
viewX, viewY := updatingView.Size()
updatingView.MoveCursor(viewX, viewY, true)
}
updatingView.MoveCursor(0, 0, true)
return nil
})
}
func moveCursorToEnd(viewName string) {
g.Update(func(g *gocui.Gui) error {
inputView, err := g.View(viewName)
if err != nil {
return err
}
inputString, _ := getInputString(viewName)
stringLen := len(inputString)
maxX, _ := inputView.Size()
x := stringLen % maxX
y := stringLen / maxX
inputView.SetCursor(0, 0)
inputView.SetOrigin(0, 0)
inputView.MoveCursor(x, y, true)
return nil
})
}
func clearView(viewName string) {
g.Update(func(g *gocui.Gui) error {
inputView, err := g.View(viewName)
if err != nil {
return err
}
inputView.Clear()
inputView.SetCursor(0, 0)
inputView.SetOrigin(0, 0)
return nil
})
}
func writeToView(viewName string, message string) {
g.Update(func(g *gocui.Gui) error {
updatingView, err := g.View(viewName)
if err != nil {
return err
}
for _, c := range message {
updatingView.EditWrite(c)
}
return nil
})
}
func printToView(viewName string, message string) {
g.Update(func(g *gocui.Gui) error {
updatingView, err := g.View(viewName)
if err != nil {
return err
}
fmt.Fprintf(updatingView, "%s\n", message)
return nil
})
}
// End gocui helper funcs
// Update/Populate views automatically
func updateChatWindow() {
runOpts := keybase.RunOptions{
Dev: dev,
}
k.Run(func(api keybase.ChatAPI) {
handleMessage(api)
},
runOpts)
}
func populateChat() {
lastMessage.ID = 0
chat := k.NewChat(channel)
@ -114,10 +289,11 @@ func populateChat() { @@ -114,10 +289,11 @@ func populateChat() {
if err2 != nil {
printToView("Feed", fmt.Sprintf("%+v", err))
return
} else {
go populateChat()
return
}
go populateChat()
go generateChannelTabCompletionSlice()
return
}
var printMe []string
var actuallyPrintMe string
@ -144,47 +320,6 @@ func populateChat() { @@ -144,47 +320,6 @@ func populateChat() {
printToView("Chat", actuallyPrintMe)
}
func sendChat(message string) {
chat := k.NewChat(channel)
_, err := chat.Send(message)
if err != nil {
printToView("Feed", fmt.Sprintf("There was an error %+v", err))
}
}
func formatOutput(api keybase.ChatAPI) string {
ret := ""
msgType := api.Msg.Content.Type
switch msgType {
case "text", "attachment":
var c = messageHeaderColor
ret = colorText(outputFormat, c, noColor)
tm := time.Unix(int64(api.Msg.SentAt), 0)
var msg = api.Msg.Content.Text.Body
// mention teams or users
msg = colorRegex(msg, `(@\w*(\.\w+)*)`, messageLinkColor, messageBodyColor)
// mention URL
msg = colorRegex(msg, `(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*))`, messageLinkColor, messageBodyColor)
msg = colorText(colorReplaceMentionMe(msg, messageBodyColor), messageBodyColor, c)
if msgType == "attachment" {
msg = fmt.Sprintf("%s\n%s", msg, colorText("[Attachment]", messageAttachmentColor, c))
}
user := colorUsername(api.Msg.Sender.Username, c)
device := colorText(api.Msg.Sender.DeviceName, messageSenderDeviceColor, c)
msgId := colorText(fmt.Sprintf("%d", api.Msg.ID), messageIdColor, c)
ts := colorText(fmt.Sprintf("%s", tm.Format(timeFormat)), messageTimeColor, c)
ret = strings.Replace(ret, "$MSG", msg, 1)
ret = strings.Replace(ret, "$USER", user, 1)
ret = strings.Replace(ret, "$DEVICE", device, 1)
ret = strings.Replace(ret, "$ID", msgId, 1)
ret = strings.Replace(ret, "$TIME", ts, 1)
ret = strings.Replace(ret, "$DATE", fmt.Sprintf("%s", tm.Format(dateFormat)), 1)
ret = strings.Replace(ret, "```", fmt.Sprintf("\n<code>\n"), -1)
}
return ret
}
func populateList() {
_, maxY := g.Size()
if testVar, err := k.ChatList(); err != nil {
@ -218,336 +353,52 @@ func populateList() { @@ -218,336 +353,52 @@ func populateList() {
}
time.Sleep(1 * time.Millisecond)
printToView("List", fmt.Sprintf("%s%s%s%s", channelsColor, recentPMs, recentChannels, noColor))
go generateRecentTabCompletionSlice()
}
}
func getCurrentChannelMembership() []string {
var rs []string
if channel.Name != "" {
t := k.NewTeam(channel.Name)
if testVar, err := t.MemberList(); err != nil {
return rs // then this isn't a team, its a PM or there was an error in the API call
} else {
for _, m := range testVar.Result.Members.Owners {
rs = append(rs, fmt.Sprintf("%+v", m.Username))
}
for _, m := range testVar.Result.Members.Admins {
rs = append(rs, fmt.Sprintf("%+v", m.Username))
}
for _, m := range testVar.Result.Members.Writers {
rs = append(rs, fmt.Sprintf("%+v", m.Username))
}
for _, m := range testVar.Result.Members.Readers {
rs = append(rs, fmt.Sprintf("%+v", m.Username))
}
}
}
return rs
}
func filterStringSlice(ss []string, fv string) []string {
var rs []string
for _, s := range ss {
if strings.HasPrefix(s, fv) {
rs = append(rs, s)
}
}
return rs
}
func longestCommonPrefix(ss []string) string {
// cover the case where the slice has no or one members
switch len(ss) {
case 0:
return ""
case 1:
return ss[0]
}
// all strings are compared by bytes here forward (TBD unicode normalization?)
// establish min, max lenth members of the slice by iterating over the members
min, max := ss[0], ss[0]
for _, s := range ss[1:] {
switch {
case s < min:
min = s
case s > max:
max = s
}
}
// then iterate over the characters from min to max, as soon as chars don't match return
for i := 0; i < len(min) && i < len(max); i++ {
if min[i] != max[i] {
return min[:i]
}
}
// to cover the case where all members are equal, just return one
return min
}
func stringRemainder(aStr, bStr string) string {
var long, short string
//figure out which string is longer
switch {
case len(aStr) < len(bStr):
short = aStr
long = bStr
default:
short = bStr
long = aStr
}
// iterate over the strings using an external iterator so we don't lose the value
i := 0
for i < len(short) && i < len(long) {
if short[i] != long[i] {
// the strings aren't equal so don't return anything
return ""
}
i++
}
// return whatever's left of the longer string
return long[i:]
}
func appendIfNotInSlice(ss []string, s string) []string {
for _, element := range ss {
if element == s {
return ss
}
}
return append(ss, s)
}
func generateChannelTabCompletionSlice(inputWord string) []string {
// create a slice to hold the values
var firstSlice []string
// iterate over all the conversation results
for _, s := range channels {
if s.MembersType == keybase.TEAM {
// its a team so add the topic name as a possible tab completion
firstSlice = appendIfNotInSlice(firstSlice, s.TopicName)
firstSlice = appendIfNotInSlice(firstSlice, s.Name)
} else {
// its a user, so clean the name and append the users name as a possible tab completion
firstSlice = appendIfNotInSlice(firstSlice, cleanChannelName(s.Name))
}
}
// next fetch all members of the current channel and add them to the slice
secondSlice := getCurrentChannelMembership()
for _, m := range secondSlice {
firstSlice = appendIfNotInSlice(firstSlice, m)
}
// now return the resultSlice which contains all that are prefixed with inputWord
resultSlice := filterStringSlice(firstSlice, inputWord)
return resultSlice
}
func generateEmojiTabCompletionSlice(inputWord string) []string {
// use the emojiSlice from emojiList.go and filter it for the input word
resultSlice := filterStringSlice(emojiSlice, inputWord)
return resultSlice
}
func handleTab() error {
inputString, err := getInputString("Input")
if err != nil {
return err
} else {
// if you successfully get an input string, grab the last word from the string
ss := regexp.MustCompile(`[ #]`).Split(inputString, -1)
s := ss[len(ss)-1]
// create a variable in which to store the result
var resultSlice []string
// if the word starts with a : its an emoji lookup
if strings.HasPrefix(s, ":") {
resultSlice = generateEmojiTabCompletionSlice(s)
} else {
// now in case the word (s) is a mention @something, lets remove it to normalize
if strings.HasPrefix(s, "@") {
s = strings.Replace(s, "@", "", 1)
}
// now call get the list of all possible cantidates that have that as a prefix
resultSlice = generateChannelTabCompletionSlice(s)
}
rLen := len(resultSlice)
lcp := longestCommonPrefix(resultSlice)
if lcp != "" {
originalViewTitle := getViewTitle("Input")
newViewTitle := ""
if rLen >= 1 && originalViewTitle != "" {
if rLen == 1 {
newViewTitle = originalViewTitle
} else if rLen <= 5 {
newViewTitle = fmt.Sprintf("%s|| %s", originalViewTitle, strings.Join(resultSlice, " "))
} else if rLen > 5 {
newViewTitle = fmt.Sprintf("%s|| %s +%d more", originalViewTitle, strings.Join(resultSlice[:6], " "), rLen-5)
}
viewTitle("Input", newViewTitle)
remainder := stringRemainder(s, lcp)
writeToView("Input", remainder)
}
}
}
return nil
}
// End update/populate views automatically
func clearView(viewName string) {
g.Update(func(g *gocui.Gui) error {
inputView, err := g.View(viewName)
if err != nil {
return err
} else {
inputView.Clear()
inputView.SetCursor(0, 0)
inputView.SetOrigin(0, 0)
}
return nil
})
}
func writeToView(viewName string, message string) {
g.Update(func(g *gocui.Gui) error {
updatingView, err := g.View(viewName)
if err != nil {
return err
} else {
for _, c := range message {
updatingView.EditWrite(c)
}
}
return nil
})
}
func printToView(viewName string, message string) {
g.Update(func(g *gocui.Gui) error {
updatingView, err := g.View(viewName)
if err != nil {
return err
} else {
fmt.Fprintf(updatingView, "%s\n", message)
}
return nil
})
// Formatting
func cleanChannelName(c string) string {
newChannelName := strings.Replace(c, fmt.Sprintf("%s,", k.Username), "", 1)
return strings.Replace(newChannelName, fmt.Sprintf(",%s", k.Username), "", 1)
}
func layout(g *gocui.Gui) error {
maxX, maxY := g.Size()
if editView, err := g.SetView("Edit", maxX/2-maxX/3+1, maxY/2, maxX-2, maxY/2+10, 0); err != nil {
if !gocui.IsUnknownView(err) {
return err
}
editView.Editable = true
editView.Wrap = true
fmt.Fprintln(editView, "Edit window. Should disappear")
}
if feedView, err := g.SetView("Feed", maxX/2-maxX/3, 0, maxX-1, maxY/5, 0); err != nil {
if !gocui.IsUnknownView(err) {
return err
}
feedView.Autoscroll = true
feedView.Wrap = true
feedView.Title = "Feed Window"
fmt.Fprintln(feedView, "Feed Window - If you are mentioned or receive a PM it will show here")
}
if chatView, err2 := g.SetView("Chat", maxX/2-maxX/3, maxY/5+1, maxX-1, maxY-5, 0); err2 != nil {
if !gocui.IsUnknownView(err2) {
return err2
}
chatView.Autoscroll = true
chatView.Wrap = true
fmt.Fprintf(chatView, "Welcome %s!\n\nYour chats will appear here.\nSupported commands are as follows:\n\n", k.Username)
RunCommand("help")
}
if inputView, err3 := g.SetView("Input", maxX/2-maxX/3, maxY-4, maxX-1, maxY-1, 0); err3 != nil {
if !gocui.IsUnknownView(err3) {
return err3
}
if _, err := g.SetCurrentView("Input"); err != nil {
return err
}
inputView.Editable = true
inputView.Wrap = true
inputView.Title = fmt.Sprintf(" Not in a chat - write `%sj` to join", cmdPrefix)
g.Cursor = true
}
if listView, err4 := g.SetView("List", 0, 0, maxX/2-maxX/3-1, maxY-1, 0); err4 != nil {
if !gocui.IsUnknownView(err4) {
return err4
func formatOutput(api keybase.ChatAPI) string {
ret := ""
msgType := api.Msg.Content.Type
switch msgType {
case "text", "attachment":
var c = messageHeaderColor
ret = colorText(outputFormat, c, noColor)
tm := time.Unix(int64(api.Msg.SentAt), 0)
var msg = api.Msg.Content.Text.Body
// mention teams or users
msg = colorRegex(msg, `(@\w*(\.\w+)*)`, messageLinkColor, messageBodyColor)
// mention URL
msg = colorRegex(msg, `(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*))`, messageLinkColor, messageBodyColor)
msg = colorText(colorReplaceMentionMe(msg, messageBodyColor), messageBodyColor, c)
if msgType == "attachment" {
msg = fmt.Sprintf("%s\n%s", api.Msg.Content.Attachment.Object.Title, colorText(fmt.Sprintf("[Attachment: %s]", api.Msg.Content.Attachment.Object.Filename), messageAttachmentColor, c))
}
listView.Title = "Channels"
fmt.Fprintf(listView, "Lists\nWindow\nTo view\n activity")
}
return nil
}
func getInputString(viewName string) (string, error) {
inputView, err := g.View(viewName)
if err != nil {
return "", err
}
retString := inputView.Buffer()
retString = strings.Replace(retString, "\n", "", 800)
return retString, err
}
func initKeybindings() error {
if err := g.SetKeybinding("", gocui.KeyCtrlC, gocui.ModNone,
func(g *gocui.Gui, v *gocui.View) error {
input, err := getInputString("Input")
if err != nil {
return err
}
if input != "" {
clearView("Input")
return nil
} else {
return gocui.ErrQuit
}
}); err != nil {
return err
}
if err := g.SetKeybinding("Input", gocui.KeyEnter, gocui.ModNone,
func(g *gocui.Gui, v *gocui.View) error {
return handleInput("Input")
}); err != nil {
return err
}
if err := g.SetKeybinding("Input", gocui.KeyTab, gocui.ModNone,
func(g *gocui.Gui, v *gocui.View) error {
return handleTab()
}); err != nil {
return err
}
if err := g.SetKeybinding("Edit", gocui.KeyEnter, gocui.ModNone,
func(g *gocui.Gui, v *gocui.View) error {
popupView("Chat")
popupView("Input")
return handleInput("Edit")
}); err != nil {
return err
user := colorUsername(api.Msg.Sender.Username, c)
device := colorText(api.Msg.Sender.DeviceName, messageSenderDeviceColor, c)
msgID := colorText(fmt.Sprintf("%d", api.Msg.ID), messageIdColor, c)
ts := colorText(tm.Format(timeFormat), messageTimeColor, c)
ret = strings.Replace(ret, "$MSG", msg, 1)
ret = strings.Replace(ret, "$USER", user, 1)
ret = strings.Replace(ret, "$DEVICE", device, 1)
ret = strings.Replace(ret, "$ID", msgID, 1)
ret = strings.Replace(ret, "$TIME", ts, 1)
ret = strings.Replace(ret, "$DATE", colorText(tm.Format(dateFormat), messageTimeColor, c), 1)
ret = strings.Replace(ret, "```", fmt.Sprintf("\n<code>\n"), -1)
}
return nil
return ret
}
func updateChatWindow() {
runOpts := keybase.RunOptions{
Dev: dev,
}
k.Run(func(api keybase.ChatAPI) {
handleMessage(api)
},
runOpts)
}
func cleanChannelName(c string) string {
newChannelName := strings.Replace(c, fmt.Sprintf("%s,", k.Username), "", 1)
return strings.Replace(newChannelName, fmt.Sprintf(",%s", k.Username), "", 1)
}
// End formatting
// Input handling
func handleMessage(api keybase.ChatAPI) {
if _, ok := typeCommands[api.Msg.Content.Type]; ok {
if api.Msg.Channel.MembersType == channel.MembersType && cleanChannelName(api.Msg.Channel.Name) == channel.Name {
@ -586,16 +437,12 @@ func handleMessage(api keybase.ChatAPI) { @@ -586,16 +437,12 @@ func handleMessage(api keybase.ChatAPI) {
}
}
if api.Msg.Channel.MembersType == channel.MembersType && cleanChannelName(api.Msg.Channel.Name) == channel.Name {
if channel.MembersType == keybase.TEAM && channel.TopicName != api.Msg.Channel.TopicName {
// Do nothing, wrong channel
} else {
if channel.MembersType == keybase.USER || channel.MembersType == keybase.TEAM && channel.TopicName == api.Msg.Channel.TopicName {
printToView("Chat", formatOutput(api))
chat := k.NewChat(channel)
lastMessage.ID = api.Msg.ID
chat.Read(api.Msg.ID)
}
}
} else {
if api.Msg.Channel.MembersType == keybase.TEAM {
@ -612,9 +459,16 @@ func handleMessage(api keybase.ChatAPI) { @@ -612,9 +459,16 @@ func handleMessage(api keybase.ChatAPI) {
}
}
}
// It seems that golang doesn't have filter and other high order functions :'(
func delete_empty(s []string) []string {
func getInputString(viewName string) (string, error) {
inputView, err := g.View(viewName)
if err != nil {
return "", err
}
retString := inputView.Buffer()
retString = strings.Replace(retString, "\n", "", 800)
return retString, err
}
func deleteEmpty(s []string) []string {
var r []string
for _, str := range s {
if str != "" {
@ -623,7 +477,6 @@ func delete_empty(s []string) []string { @@ -623,7 +477,6 @@ func delete_empty(s []string) []string {
}
return r
}
func handleInput(viewName string) error {
clearView(viewName)
inputString, _ := getInputString(viewName)
@ -631,7 +484,10 @@ func handleInput(viewName string) error { @@ -631,7 +484,10 @@ func handleInput(viewName string) error {
return nil
}
if strings.HasPrefix(inputString, cmdPrefix) {
cmd := delete_empty(strings.Split(inputString[len(cmdPrefix):], " "))
cmd := deleteEmpty(strings.Split(inputString[len(cmdPrefix):], " "))
if len(cmd) < 1 {
return nil
}
if c, ok := commands[cmd[0]]; ok {
c.Exec(cmd)
return nil
@ -644,18 +500,28 @@ func handleInput(viewName string) error { @@ -644,18 +500,28 @@ func handleInput(viewName string) error {
}
if inputString[:1] == "+" || inputString[:1] == "-" {
cmd := strings.Split(inputString, " ")
cmd[0] = inputString[:1]
RunCommand(cmd...)
} else {
go sendChat(inputString)
}
// restore any tab completion view titles on input commit
if newViewTitle := getViewTitle(viewName); newViewTitle != "" {
viewTitle(viewName, newViewTitle)
setViewTitle(viewName, newViewTitle)
}
go populateList()
return nil
}
func sendChat(message string) {
chat := k.NewChat(channel)
_, err := chat.Send(message)
if err != nil {
printToView("Feed", fmt.Sprintf("There was an error %+v", err))
}
}
// End input handling
func quit(g *gocui.Gui, v *gocui.View) error {
return gocui.ErrQuit

213
tabComplete.go

@ -0,0 +1,213 @@ @@ -0,0 +1,213 @@
// +build !rm_basic_commands allcommands tabcompletion
package main
import (
"fmt"
"regexp"
"strings"
"samhofi.us/x/keybase"
)
var (
tabSlice []string
commandSlice []string
)
// This defines the handleTab function thats called by key bindind tab for the input control.
func handleTab(viewName string) error {
inputString, err := getInputString(viewName)
if err != nil {
return err
}
// if you successfully get an input string, grab the last word from the string
ss := regexp.MustCompile(`[ #]`).Split(inputString, -1)
s := ss[len(ss)-1]
// create a variable in which to store the result
var resultSlice []string
// if the word starts with a : its an emoji lookup
if strings.HasPrefix(s, ":") {
resultSlice = getEmojiTabCompletionSlice(s)
} else if strings.HasPrefix(s, "/") {
generateCommandTabCompletionSlice()
s = strings.Replace(s, "/", "", 1)
resultSlice = getCommandTabCompletionSlice(s)
} else {
if strings.HasPrefix(s, "@") {
// now in case the word (s) is a mention @something, lets remove it to normalize
s = strings.Replace(s, "@", "", 1)
}
// now call get the list of all possible cantidates that have that as a prefix
resultSlice = getChannelTabCompletionSlice(s)
}
rLen := len(resultSlice)
lcp := longestCommonPrefix(resultSlice)
if lcp != "" {
originalViewTitle := getViewTitle("Input")
newViewTitle := ""
if rLen >= 1 && originalViewTitle != "" {
if rLen == 1 {
newViewTitle = originalViewTitle
} else if rLen <= 5 {
newViewTitle = fmt.Sprintf("%s|| %s", originalViewTitle, strings.Join(resultSlice, " "))
} else if rLen > 5 {
newViewTitle = fmt.Sprintf("%s|| %s +%d more", originalViewTitle, strings.Join(resultSlice[:6], " "), rLen-5)
}
setViewTitle(viewName, newViewTitle)
remainder := stringRemainder(s, lcp)
writeToView(viewName, remainder)
}
}
return nil
}
// Main tab completion functions
func getEmojiTabCompletionSlice(inputWord string) []string {
// use the emojiSlice from emojiList.go and filter it for the input word
resultSlice := filterStringSlice(emojiSlice, inputWord)
return resultSlice
}
func getChannelTabCompletionSlice(inputWord string) []string {
// use the tabSlice from above and filter it for the input word
resultSlice := filterStringSlice(tabSlice, inputWord)
return resultSlice
}
func getCommandTabCompletionSlice(inputWord string) []string {
// use the commandSlice from above and filter it for the input word
resultSlice := filterStringSlice(commandSlice, inputWord)
return resultSlice
}
//Generator Functions (should be called externally when chat/list/join changes
func generateChannelTabCompletionSlice() {
// fetch all members of the current channel and add them to the slice
channelSlice := getCurrentChannelMembership()
for _, m := range channelSlice {
tabSlice = appendIfNotInSlice(tabSlice, m)
}
}
func generateCommandTabCompletionSlice() {
// get the maps of all built commands - this should only need to be done on startup
// removing typeCommands for now, since they aren't actually commands you can type - contrary to the naming
/*for commandString1 := range typeCommands {
commandSlice = appendIfNotInSlice(commandSlice, commandString1)
}*/
for commandString2 := range commands {
commandSlice = appendIfNotInSlice(commandSlice, commandString2)
}
for _, commandString3 := range baseCommands {
commandSlice = appendIfNotInSlice(commandSlice, commandString3)
}
}
func generateRecentTabCompletionSlice() {
var recentSlice []string
for _, s := range channels {
if s.MembersType == keybase.TEAM {
// its a team so add the topic name and channel name
recentSlice = appendIfNotInSlice(recentSlice, s.TopicName)
recentSlice = appendIfNotInSlice(recentSlice, s.Name)
} else {
//its a user, so clean the name and append
recentSlice = appendIfNotInSlice(recentSlice, cleanChannelName(s.Name))
}
}
for _, s := range recentSlice {
tabSlice = appendIfNotInSlice(tabSlice, s)
}
}
// Helper functions
func getCurrentChannelMembership() []string {
var rs []string
if channel.Name != "" {
t := k.NewTeam(channel.Name)
testVar, err := t.MemberList()
if err != nil {
return rs // then this isn't a team, its a PM or there was an error in the API call
}
for _, m := range testVar.Result.Members.Owners {
rs = append(rs, fmt.Sprintf("%+v", m.Username))
}
for _, m := range testVar.Result.Members.Admins {
rs = append(rs, fmt.Sprintf("%+v", m.Username))
}
for _, m := range testVar.Result.Members.Writers {
rs = append(rs, fmt.Sprintf("%+v", m.Username))
}
for _, m := range testVar.Result.Members.Readers {
rs = append(rs, fmt.Sprintf("%+v", m.Username))
}
}
return rs
}
func filterStringSlice(ss []string, fv string) []string {
var rs []string
for _, s := range ss {
if strings.HasPrefix(s, fv) {
rs = append(rs, s)
}
}
return rs
}
func longestCommonPrefix(ss []string) string {
// cover the case where the slice has no or one members
switch len(ss) {
case 0:
return ""
case 1:
return ss[0]
}
// all strings are compared by bytes here forward (TBD unicode normalization?)
// establish min, max lenth members of the slice by iterating over the members
min, max := ss[0], ss[0]
for _, s := range ss[1:] {
switch {
case s < min:
min = s
case s > max:
max = s
}
}
// then iterate over the characters from min to max, as soon as chars don't match return
for i := 0; i < len(min) && i < len(max); i++ {
if min[i] != max[i] {
return min[:i]
}
}
// to cover the case where all members are equal, just return one
return min
}
func stringRemainder(aStr, bStr string) string {
var long, short string
//figure out which string is longer
switch {
case len(aStr) < len(bStr):
short = aStr
long = bStr
default:
short = bStr
long = aStr
}
// iterate over the strings using an external iterator so we don't lose the value
i := 0
for i < len(short) && i < len(long) {
if short[i] != long[i] {
// the strings aren't equal so don't return anything
return ""
}
i++
}
// return whatever's left of the longer string
return long[i:]
}
func appendIfNotInSlice(ss []string, s string) []string {
for _, element := range ss {
if element == s {
return ss
}
}
return append(ss, s)
}

2
userConfigs.go

@ -17,7 +17,7 @@ var messageBodyColor = noColor @@ -17,7 +17,7 @@ var messageBodyColor = noColor
var messageAttachmentColor = color(2)
var messageLinkColor = color(4)
// BASH-like PS1 variable equivalent (without colours)
// BASH-like PS1 variable equivalent
var outputFormat = "┌──[$USER@$DEVICE] [$ID] [$DATE - $TIME]\n└╼ $MSG"
// 02 = Day, Jan = Month, 06 = Year

Loading…
Cancel
Save