Beispiel #1
0
    def action(self, args=None):
        config = Config.get()

        if args.set:
            workspace = args.set
            if workspace == config.active_workspace():
                self.logger.warning("Workspace already active!")
                return
            elif workspace not in config.workspaces():
                self.logger.warning(
                    "Unknown workspace: '{}'".format(workspace))
                return

            config.set_active_workspace(workspace)
            config.save()

        elif args.create:
            (workspace, token) = workspace_token_prompt()
            config.add_workspace(workspace, token)
            config.save()

        elif args.remove:
            workspace = args.remove
            config.remove_workspace(workspace)
            config.save()

        self.logger.info("Workspaces:")
        for workspace in config.workspaces():
            active = " (active)" if (config.active_workspace()
                                     == workspace) else ""
            self.logger.info("  {}{}".format(workspace, active))
Beispiel #2
0
 def make_parser(self):
     parser = ArgumentParser(prog=self.name(),
                             description=self.description())
     parser.add_argument("-ws",
                         "--workspace",
                         choices=Config.get().workspaces(),
                         help="Check auth for specified workspace.")
     return parser
Beispiel #3
0
  def __init__(self, token=None, command=None, requires_token=False, is_destructive=True):
    config = Config.get()
    self.__logger = Logger(__name__).get()

    if token:
      self.__token = token
    else:
      self.__token = config.active_workspace_token()

    self.__requires_token = requires_token if not command else command.requires_token()
    self.__is_destructive = is_destructive if not command else command.is_destructive()
Beispiel #4
0
    def action(self, args=None):
        if args.level:
            level = Logger.level_from_name(args.level)
            self.logger.debug("Set log level to: {}".format(args.level))

            config = Config.get()
            config.set_log_level(level)
            config.save()

        else:
            level = logging.getLevelName(self.logger.getEffectiveLevel())
            self.logger.info("Log level: {}".format(level))
Beispiel #5
0
def readline(completer, history):
  """ Set prompt and read input """
  try:
    config = Config.get()
    txt = "{}{}".format(config.active_workspace(), config.repl_prefix())
    if config.read_only():
      txt = "(read-only) {}".format(txt)
    return prompt(txt, completer=completer, history=history)

  # Handle EOF/^D nicely.
  except BaseException:
    return None
Beispiel #6
0
    def __check_read_only_abort(self, method):
        """Returns exception to avoid sending requests to Slack API.

    If the command is marked as destructive or the REPL is in read-only mode
    requests to Slack API will not be sent.

    Arguments:
      method {str} -- Slack API method name

    Raises:
      SlackAPIException
    """
        if self.__is_destructive and Config.get().read_only():
            raise SlackAPIException(
                "Not executing '{}' due to read-only mode!".format(method))
Beispiel #7
0
def readline(completer, history):
    """ Set prompt and read input """
    try:
        config = Config.get()
        read_only = ""
        if config.read_only():
            read_only = config.read_only_str()
        tmpl_fill = dict(w=config.active_workspace(), ro=read_only)
        s = Template(config.repl_prompt())
        txt = s.safe_substitute(tmpl_fill)
        return prompt(txt, completer=completer, history=history)

    # Handle EOF/^D nicely.
    except BaseException:
        return None
Beispiel #8
0
def workspace_token_prompt(msg="Input workspace token: "):
  logger = Logger(__name__).get()
  config = Config.get()
  workspace = ""
  token = ""
  while True:
    token = prompt(msg, is_password=True).strip()
    if len(token) == 0:
      continue
    data = verify_token(token)
    if not data:
      continue
    workspace = data["team"]
    if workspace in config.workspaces():
      logger.warning("Workspace of token already exists: {}".format(workspace))
      continue
    return (workspace, token)
Beispiel #9
0
  def action(self, args=None):
    config = Config.get()

    if args.read_only is not None:
      config.set_read_only(args.read_only)
      config.save()

    elif args.reset:
      if config.read_only():
        self.logger.warning("Cannot reset config in read-only mode!")
        return
      if confirm("Resetting will close slacker and requires --init again.\n"
                 "Are you sure you want to reset the config? "):
        config.reset()
        config.save()
        sys.exit(0)
      return

    self.logger.info("Current config state of '{}'".format(config.file_path()))
    self.logger.info(json.dumps(config.safe_dict(), indent=2))
Beispiel #10
0
    def action(self, args=None):
        config = Config.get()
        if args and args.workspace:
            ws = args.workspace
            token = config.workspace_token(ws)
        else:
            ws = config.active_workspace()
            token = config.active_workspace_token()

        self.logger.debug("Checking auth for '{}'...".format(ws))

        data = verify_token(token)
        if not data:
            return False

        self.logger.info("Auth successful.")
        self.logger.debug("URL: {}".format(data["url"]))
        self.logger.debug("Workspace: {}".format(data["team"]))
        self.logger.debug("Workspace ID: {}".format(data["team_id"]))
        self.logger.debug("User: {}".format(data["user"]))
        self.logger.debug("User ID: {}".format(data["user_id"]))
        return True
Beispiel #11
0
def start_slacker():
    signal.signal(signal.SIGINT, signal_handler)
    (args, cmd_args) = parse_args()

    session = Session.get()
    session.set_quiet_mode(args.quiet)

    global config
    config = Config.get()
    session.set_log_level(config.log_level())

    global slacker_logger
    slacker_logger = Logger(__name__).get()
    slacker_logger.debug("Starting Slacker...")

    if args.verbose:
        session.set_log_level(logging.DEBUG)
        Logger.set_level(logging.DEBUG)
        slacker_logger.debug("Verbose mode setting debug session log level.")

    if args.check:
        check()
        return

    if args.init:
        init()

    if not config.active_workspace():
        slacker_logger.error("No workspace active!")
        slacker_logger.error(
            "Run slacker with --init to interactively create a workspace and config "
            "file.")
        return

    reg = Registrar()
    for cmd in Command.find_all():
        reg.register(cmd())

    if reg.count() == 0:
        slacker_logger.error("No commands found!")
        sys.exit(-1)

    try:
        if not args.no_tests:
            reg.action("api.test")
            reg.action("auth.test")
    except Exception as ex:
        slacker_logger.error(str(ex))
        slacker_logger.warning(
            "Make sure you have internet access and verify your tokens!")
        sys.exit(-1)

    if cmd_args:
        # The arguments are already parsed into a list so pass it on!
        process(cmd_args, reg)
        return

    completer = build_prompt_completer(reg)
    in_memory_history = InMemoryHistory()

    while True:
        line = readline(completer, in_memory_history)
        if line is None:
            break
        elif not line:
            continue
        process(line, reg)
Beispiel #12
0
 def __check_read_only_abort(self, method):
   if self.__is_destructive and Config.get().read_only():
     raise SlackAPIException("Not executing '{}' due to read-only mode!".format(method))