Skip to content

Instantly share code, notes, and snippets.

@raek raek/message.clj
Created Sep 8, 2010

Embed
What would you like to do?
(ns se.raek.quirclj.message
(:refer-clojure :exclude [format])
(:use [clojure.contrib.def :only [defvar-]]))
(declare parse-params)
(defvar- message-regex
#"^(?::([^ ]+) +)?([^ ]+)(?: +(.+))?$")
(defn parse [s]
(when-let [[_ prefix command param-str] (re-find message-regex s)]
(let [params (parse-params param-str)]
{:source prefix
:command command
:params params})))
(defvar- param-regex
#"(?:(?<!:)[^ :][^ ]*|(?<=:).*)")
(defn- parse-params [param-str]
(when param-str
(re-seq param-regex param-str)))
(ns se.raek.quirclj.test-message
(:use clojure.test)
(:require [se.raek.quirclj.message :as msg]))
(deftest test-parse
(testing "command only"
(let [{:keys [source command params]}
(msg/parse "FOO")]
(is (= source nil))
(is (= command "FOO"))
(is (= params nil))))
(testing "prefix and command"
(let [{:keys [source command params]}
(msg/parse ":tortoise BAR")]
(is (= source "tortoise"))
(is (= command "BAR"))
(is (= params nil))))
(testing "single parameter"
(let [{:keys [source command params]}
(msg/parse "BAZ param")]
(is (= source nil))
(is (= command "BAZ"))
(is (= params ["param"]))))
(testing "prefix, command and single parameter"
(let [{:keys [source command params]}
(msg/parse ":achilles QUUX param")]
(is (= source "achilles"))
(is (= command "QUUX"))
(is (= params ["param"]))))
(testing "three parameters"
(let [{:keys [source command params]}
(msg/parse "COMMAND one two three")]
(is (= source nil))
(is (= command "COMMAND"))
(is (= params ["one" "two" "three"]))))
(testing "rest parameter"
(let [{:keys [source command params]}
(msg/parse "COMMAND :rest")]
(is (= source nil))
(is (= command "COMMAND"))
(is (= params ["rest"]))))
(testing "empty rest parameter"
(let [{:keys [source command params]}
(msg/parse "COMMAND :")]
(is (= source nil))
(is (= command "COMMAND"))
(is (= params [""]))))
(testing "rest parameter with spaces"
(let [{:keys [source command params]}
(msg/parse "COMMAND :one two three")]
(is (= source nil))
(is (= command "COMMAND"))
(is (= params ["one two three"]))))
(testing "normal parameters and rest parameter"
(let [{:keys [source command params]}
(msg/parse "COMMAND one two :three three three")]
(is (= source nil))
(is (= command "COMMAND"))
(is (= params ["one" "two" "three three three"])))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.