aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorTrygve Aaberge <trygveaa@gmail.com>2022-11-19 23:05:11 +0100
committerTrygve Aaberge <trygveaa@gmail.com>2024-02-18 11:32:53 +0100
commit734e76aea266632643f4c5df49b8ab34ffc403d0 (patch)
tree83c1e8c3288a52875ad32e025781f856003c6b86
parent1358241a612980781bc7f80dec67bc8de74a3903 (diff)
downloadwee-slack-734e76aea266632643f4c5df49b8ab34ffc403d0.tar.gz
Add command to list workspaces
-rw-r--r--slack/api.py2
-rw-r--r--slack/commands.py82
-rw-r--r--slack/config.py6
-rw-r--r--slack/util.py6
-rw-r--r--tests/test_commands.py28
5 files changed, 113 insertions, 11 deletions
diff --git a/slack/api.py b/slack/api.py
index 19cfb11..52479ae 100644
--- a/slack/api.py
+++ b/slack/api.py
@@ -53,6 +53,8 @@ class SlackWorkspace:
self.name = name
self.config = shared.config.create_workspace_config(self.name)
self.api = SlackApi(self)
+ self.connected = False
+ self.nick = "TODO"
class SlackChannelCommonNew:
diff --git a/slack/commands.py b/slack/commands.py
index 547ac59..39e5c67 100644
--- a/slack/commands.py
+++ b/slack/commands.py
@@ -3,14 +3,15 @@ from __future__ import annotations
import re
from dataclasses import dataclass
from functools import wraps
-from typing import Callable, Dict, List
+from typing import Any, Callable, Dict, List, Optional
import weechat
from slack.api import SlackWorkspace
+from slack.config import WeeChatOption
from slack.log import print_error
from slack.shared import shared
-from slack.util import get_callback_name
+from slack.util import get_callback_name, with_color
commands: Dict[str, Command] = {}
@@ -22,6 +23,15 @@ commands: Dict[str, Command] = {}
# return cmd_line[0], args, doc[1].strip()
+def parse_options(args: str):
+ regex = re.compile(" +-([^ =]+)(?:=([^ ]+))?")
+ pos_args = regex.sub("", args)
+ options: Dict[str, Optional[str]] = {
+ match.group(1): match.group(2) for match in regex.finditer(args)
+ }
+ return pos_args, options
+
+
@dataclass
class Command:
cmd: str
@@ -34,19 +44,20 @@ class Command:
def weechat_command(min_args: int = 0, slack_buffer_required: bool = False):
- def decorator(f: Callable[[str, List[str]], None]):
+ def decorator(f: Callable[[str, List[str], Dict[str, Optional[str]]], None]):
cmd = f.__name__.removeprefix("command_").replace("_", " ")
top_level = " " not in cmd
@wraps(f)
def wrapper(buffer: str, args: str):
- split_args = args.split(" ", min_args)
- if min_args and not args or len(split_args) < min_args:
+ pos_args, options = parse_options(args)
+ split_args = pos_args.split(" ", min_args)
+ if min_args and not pos_args or len(split_args) < min_args:
print_error(
f'Too few arguments for command "/{cmd}" (help on command: /help {cmd})'
)
return
- return f(buffer, split_args)
+ return f(buffer, split_args, options)
commands[cmd] = Command(cmd, top_level, "", "", "", "", wrapper)
@@ -55,8 +66,31 @@ def weechat_command(min_args: int = 0, slack_buffer_required: bool = False):
return decorator
+def list_workspaces(workspace_name: Optional[str] = None, detailed_list: bool = False):
+ weechat.prnt("", "")
+ weechat.prnt("", "All workspaces:")
+ for workspace in shared.workspaces.values():
+ display_workspace(workspace, detailed_list)
+
+
+def display_workspace(workspace: SlackWorkspace, detailed_list: bool):
+ if workspace.connected:
+ weechat.prnt(
+ "",
+ f" * "
+ f"{with_color('chat_server', workspace.name)} "
+ f"{with_color('chat_delimiters', '[')}"
+ f"connected"
+ f"{with_color('chat_delimiters', ']')}"
+ f", nick: {workspace.nick}"
+ f", 0 channel(s), 0 pv",
+ )
+ else:
+ weechat.prnt("", f" {with_color('chat_server', workspace.name)}")
+
+
@weechat_command()
-def command_slack(buffer: str, args: List[str]):
+def command_slack(buffer: str, args: List[str], options: Dict[str, Optional[str]]):
"""
slack command
"""
@@ -64,17 +98,45 @@ def command_slack(buffer: str, args: List[str]):
@weechat_command()
-def command_slack_workspace(buffer: str, args: List[str]):
- print("ran workspace")
+def command_slack_workspace(
+ buffer: str, args: List[str], options: Dict[str, Optional[str]]
+):
+ list_workspaces()
+
+
+@weechat_command()
+def command_slack_workspace_list(
+ buffer: str, args: List[str], options: Dict[str, Optional[str]]
+):
+ list_workspaces()
+
+
+@weechat_command()
+def command_slack_workspace_listfull(
+ buffer: str, args: List[str], options: Dict[str, Optional[str]]
+):
+ list_workspaces(detailed_list=True)
@weechat_command(min_args=1)
-def command_slack_workspace_add(buffer: str, args: List[str]):
+def command_slack_workspace_add(
+ buffer: str, args: List[str], options: Dict[str, Optional[str]]
+):
name = args[0]
if name in shared.workspaces:
print_error(f'workspace "{name}" already exists, can\'t add it!')
return
+
shared.workspaces[name] = SlackWorkspace(name)
+
+ for option_name, option_value in options.items():
+ if hasattr(shared.workspaces[name].config, option_name):
+ config_option: WeeChatOption[Any] = getattr(
+ shared.workspaces[name].config, option_name
+ )
+ value = "on" if option_value is None else option_value
+ config_option.value_set_as_str(value)
+
weechat.prnt(
"",
f"{shared.SCRIPT_NAME}: workspace added: {weechat.color('chat_server')}{name}{weechat.color('reset')}",
diff --git a/slack/config.py b/slack/config.py
index 5351569..e9be0ba 100644
--- a/slack/config.py
+++ b/slack/config.py
@@ -190,6 +190,12 @@ class SlackConfigSectionWorkspace:
"",
)
+ self.autoconnect = self._create_option(
+ "autoconnect",
+ "automatically connect to workspace when WeeChat is starting",
+ False,
+ )
+
self.slack_timeout = self._create_option(
"slack_timeout",
"timeout (in seconds) for network requests",
diff --git a/slack/util.py b/slack/util.py
index 507978d..c6cb57d 100644
--- a/slack/util.py
+++ b/slack/util.py
@@ -1,8 +1,14 @@
from typing import Any, Callable
+import weechat
+
from slack.shared import shared
def get_callback_name(callback: Callable[..., Any]) -> str:
shared.weechat_callbacks[callback.__name__] = callback
return callback.__name__
+
+
+def with_color(color: str, string: str):
+ return f"{weechat.color(color)}{string}{weechat.color('reset')}"
diff --git a/tests/test_commands.py b/tests/test_commands.py
index c9dbcaa..fe3e917 100644
--- a/tests/test_commands.py
+++ b/tests/test_commands.py
@@ -1,9 +1,9 @@
-# Test parsing options
# Test calling the correct function
from itertools import accumulate
import slack.commands
+from slack.commands import parse_options
def test_all_parent_commands_exist():
@@ -11,3 +11,29 @@ def test_all_parent_commands_exist():
parents = accumulate(command.split(" "), lambda x, y: f"{x} {y}")
for parent in parents:
assert parent in slack.commands.commands
+
+
+def test_parse_options_without_options():
+ pos_args, options = parse_options("workspace add wee-slack-test")
+ assert pos_args == "workspace add wee-slack-test"
+ assert options == {}
+
+
+def test_parse_options_with_option():
+ pos_args, options = parse_options("workspace add wee-slack-test -autoconnect")
+ assert pos_args == "workspace add wee-slack-test"
+ assert options == {"autoconnect": None}
+
+
+def test_parse_options_option_in_middle():
+ pos_args, options = parse_options("workspace add -autoconnect wee-slack-test")
+ assert pos_args == "workspace add wee-slack-test"
+ assert options == {"autoconnect": None}
+
+
+def test_parse_options_option_with_value():
+ pos_args, options = parse_options(
+ "workspace add wee-slack-test -autoconnect -api_token=xoxp-1"
+ )
+ assert pos_args == "workspace add wee-slack-test"
+ assert options == {"autoconnect": None, "api_token": "xoxp-1"}