diff options
Diffstat (limited to 'accounts/gkleen@sif/xmonad/lib')
| -rw-r--r-- | accounts/gkleen@sif/xmonad/lib/XMonad/Mpv.hs | 127 | ||||
| -rw-r--r-- | accounts/gkleen@sif/xmonad/lib/XMonad/Prompt/MyPass.hs | 94 | ||||
| -rw-r--r-- | accounts/gkleen@sif/xmonad/lib/XMonad/Prompt/MyShell.hs | 105 | ||||
| -rw-r--r-- | accounts/gkleen@sif/xmonad/lib/XMonad/Prompt/MySsh.hs | 246 |
4 files changed, 572 insertions, 0 deletions
diff --git a/accounts/gkleen@sif/xmonad/lib/XMonad/Mpv.hs b/accounts/gkleen@sif/xmonad/lib/XMonad/Mpv.hs new file mode 100644 index 00000000..e6accdcc --- /dev/null +++ b/accounts/gkleen@sif/xmonad/lib/XMonad/Mpv.hs | |||
| @@ -0,0 +1,127 @@ | |||
| 1 | {-# LANGUAGE DeriveGeneric, OverloadedLists, OverloadedStrings, ViewPatterns, ExistentialQuantification, MultiWayIf #-} | ||
| 2 | |||
| 3 | module XMonad.Mpv | ||
| 4 | ( MpvCommand(..), MpvResponse(..), MpvException(..) | ||
| 5 | , mpv | ||
| 6 | , mpvDir | ||
| 7 | , mpvAll, mpvOne | ||
| 8 | , mpvResponse | ||
| 9 | ) where | ||
| 10 | |||
| 11 | import Data.Aeson | ||
| 12 | |||
| 13 | import Data.Monoid | ||
| 14 | |||
| 15 | import Network.Socket hiding (recv) | ||
| 16 | import Network.Socket.ByteString | ||
| 17 | |||
| 18 | import qualified Data.ByteString as BS | ||
| 19 | import qualified Data.ByteString.Char8 as CBS | ||
| 20 | import qualified Data.ByteString.Lazy as LBS | ||
| 21 | |||
| 22 | import GHC.Generics (Generic) | ||
| 23 | import Data.Typeable (Typeable) | ||
| 24 | import Data.String (IsString(..)) | ||
| 25 | |||
| 26 | import Control.Exception | ||
| 27 | |||
| 28 | import System.IO.Temp (getCanonicalTemporaryDirectory) | ||
| 29 | |||
| 30 | import Control.Monad | ||
| 31 | import Control.Exception (bracket) | ||
| 32 | import Control.Monad.IO.Class (MonadIO(..)) | ||
| 33 | |||
| 34 | import System.FilePath | ||
| 35 | import System.Directory (getDirectoryContents) | ||
| 36 | |||
| 37 | import Data.List | ||
| 38 | import Data.Either | ||
| 39 | import Data.Maybe | ||
| 40 | |||
| 41 | import Debug.Trace | ||
| 42 | |||
| 43 | |||
| 44 | data MpvCommand | ||
| 45 | = forall a. ToJSON a => MpvSetProperty String a | ||
| 46 | | MpvGetProperty String | ||
| 47 | data MpvResponse | ||
| 48 | = MpvError String | ||
| 49 | | MpvSuccess (Maybe Value) | ||
| 50 | deriving (Read, Show, Generic, Eq) | ||
| 51 | data MpvException = MpvException String | ||
| 52 | | MpvNoValue | ||
| 53 | | MpvNoParse String | ||
| 54 | deriving (Generic, Typeable, Read, Show) | ||
| 55 | instance Exception MpvException | ||
| 56 | |||
| 57 | |||
| 58 | instance ToJSON MpvCommand where | ||
| 59 | toJSON (MpvSetProperty name val) = Array ["set_property", fromString name, toJSON val] | ||
| 60 | toJSON (MpvGetProperty name) = Array ["get_property", fromString name] | ||
| 61 | |||
| 62 | instance FromJSON MpvResponse where | ||
| 63 | parseJSON = withObject "response object" $ \obj -> do | ||
| 64 | mval <- obj .:? "data" | ||
| 65 | err <- obj .: "error" | ||
| 66 | |||
| 67 | let ret | ||
| 68 | | err == "success" = MpvSuccess mval | ||
| 69 | | otherwise = MpvError err | ||
| 70 | |||
| 71 | return ret | ||
| 72 | |||
| 73 | mpvSocket :: FilePath -> (Socket -> IO a) -> IO a | ||
| 74 | mpvSocket sockPath = withSocketsDo . bracket mkSock close | ||
| 75 | where | ||
| 76 | mkSock = do | ||
| 77 | sock <- socket AF_UNIX Stream defaultProtocol | ||
| 78 | connect sock $ SockAddrUnix (traceId sockPath) | ||
| 79 | return sock | ||
| 80 | |||
| 81 | mpvResponse :: FromJSON v => MpvResponse -> IO v | ||
| 82 | mpvResponse (MpvError str) = throwIO $ MpvException str | ||
| 83 | mpvResponse (MpvSuccess Nothing) = throwIO MpvNoValue | ||
| 84 | mpvResponse (MpvSuccess (Just v)) = case fromJSON v of | ||
| 85 | Success v' -> return v' | ||
| 86 | Error str -> throwIO $ MpvNoParse str | ||
| 87 | |||
| 88 | mpv :: FilePath -> MpvCommand -> IO MpvResponse | ||
| 89 | mpv sockPath cmd = mpvSocket sockPath $ \sock -> do | ||
| 90 | let message = (`BS.append` "\n") . LBS.toStrict . encode $ Object [("command", toJSON cmd)] | ||
| 91 | traceIO $ show message | ||
| 92 | sendAll sock message | ||
| 93 | let recvAll = do | ||
| 94 | prefix <- recv sock 4096 | ||
| 95 | if | ||
| 96 | | (prefix', rest) <- CBS.break (== '\n') prefix | ||
| 97 | , not (BS.null rest) -> return prefix' | ||
| 98 | | BS.null prefix -> return prefix | ||
| 99 | | otherwise -> BS.append prefix <$> recvAll | ||
| 100 | response <- recvAll | ||
| 101 | traceIO $ show response | ||
| 102 | either (ioError . userError) return . traceShowId $ eitherDecodeStrict' response | ||
| 103 | |||
| 104 | mpvDir :: Exception e => FilePath -> (FilePath -> [(FilePath, Either e MpvResponse)] -> Maybe MpvCommand) -> IO [(FilePath, Either e MpvResponse)] | ||
| 105 | mpvDir dir step = do | ||
| 106 | socks <- filter (".sock" `isSuffixOf`) <$> getDirectoryContents dir | ||
| 107 | go [] socks | ||
| 108 | where | ||
| 109 | go acc [] = return acc | ||
| 110 | go acc (sock:socks) | ||
| 111 | | Just cmd <- step sock acc = do | ||
| 112 | res <- try $ mpv (dir </> sock) cmd | ||
| 113 | go ((sock, res) : acc) socks | ||
| 114 | | otherwise = | ||
| 115 | go acc socks | ||
| 116 | |||
| 117 | mpvAll :: FilePath -> MpvCommand -> IO [MpvResponse] | ||
| 118 | mpvAll dir cmd = do | ||
| 119 | results <- map snd <$> (mpvDir dir (\_ _ -> Just cmd) :: IO [(FilePath, Either SomeException MpvResponse)]) | ||
| 120 | mapM (either throwIO return) results | ||
| 121 | |||
| 122 | mpvOne :: FilePath -> MpvCommand -> IO (Maybe MpvResponse) | ||
| 123 | mpvOne dir cmd = listToMaybe . snd . partitionEithers . map snd <$> (mpvDir dir step :: IO [(FilePath, Either SomeException MpvResponse)]) | ||
| 124 | where | ||
| 125 | step _ results | ||
| 126 | | any (isRight . snd) results = Nothing | ||
| 127 | | otherwise = Just cmd | ||
diff --git a/accounts/gkleen@sif/xmonad/lib/XMonad/Prompt/MyPass.hs b/accounts/gkleen@sif/xmonad/lib/XMonad/Prompt/MyPass.hs new file mode 100644 index 00000000..1caefae5 --- /dev/null +++ b/accounts/gkleen@sif/xmonad/lib/XMonad/Prompt/MyPass.hs | |||
| @@ -0,0 +1,94 @@ | |||
| 1 | module XMonad.Prompt.MyPass | ||
| 2 | ( | ||
| 3 | -- * Usages | ||
| 4 | -- $usages | ||
| 5 | mkPassPrompt | ||
| 6 | ) where | ||
| 7 | |||
| 8 | import Control.Monad (liftM) | ||
| 9 | import XMonad.Core | ||
| 10 | import XMonad.Prompt ( XPrompt | ||
| 11 | , showXPrompt | ||
| 12 | , commandToComplete | ||
| 13 | , nextCompletion | ||
| 14 | , getNextCompletion | ||
| 15 | , XPConfig | ||
| 16 | , mkXPrompt | ||
| 17 | , searchPredicate) | ||
| 18 | import System.Directory (getHomeDirectory) | ||
| 19 | import System.FilePath (takeExtension, dropExtension, combine) | ||
| 20 | import System.Posix.Env (getEnv) | ||
| 21 | import XMonad.Util.Run (runProcessWithInput) | ||
| 22 | |||
| 23 | -- $usages | ||
| 24 | -- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@: | ||
| 25 | -- | ||
| 26 | -- > import XMonad.Prompt.Pass | ||
| 27 | -- | ||
| 28 | -- Then add a keybinding for 'passPrompt', 'passGeneratePrompt' or 'passRemovePrompt': | ||
| 29 | -- | ||
| 30 | -- > , ((modMask x , xK_p) , passPrompt xpconfig) | ||
| 31 | -- > , ((modMask x .|. controlMask, xK_p) , passGeneratePrompt xpconfig) | ||
| 32 | -- > , ((modMask x .|. controlMask .|. shiftMask, xK_p), passRemovePrompt xpconfig) | ||
| 33 | -- | ||
| 34 | -- For detailed instructions on: | ||
| 35 | -- | ||
| 36 | -- - editing your key bindings, see "XMonad.Doc.Extending#Editing_key_bindings". | ||
| 37 | -- | ||
| 38 | -- - how to setup the password storage, see <http://git.zx2c4.com/password-store/about/> | ||
| 39 | -- | ||
| 40 | |||
| 41 | type Predicate = String -> String -> Bool | ||
| 42 | |||
| 43 | getPassCompl :: [String] -> Predicate -> String -> IO [String] | ||
| 44 | getPassCompl compls p s | ||
| 45 | | length s <= minL | ||
| 46 | , all ((> minL) . length) compls = return [] | ||
| 47 | | otherwise = do return $ filter (p s) compls | ||
| 48 | where | ||
| 49 | minL = 3 | ||
| 50 | |||
| 51 | type PromptLabel = String | ||
| 52 | |||
| 53 | data Pass = Pass PromptLabel | ||
| 54 | |||
| 55 | instance XPrompt Pass where | ||
| 56 | showXPrompt (Pass prompt) = prompt ++ ": " | ||
| 57 | commandToComplete _ c = c | ||
| 58 | nextCompletion _ = getNextCompletion | ||
| 59 | |||
| 60 | -- | Default password store folder in $HOME/.password-store | ||
| 61 | -- | ||
| 62 | passwordStoreFolderDefault :: String -> String | ||
| 63 | passwordStoreFolderDefault home = combine home ".password-store" | ||
| 64 | |||
| 65 | -- | Compute the password store's location. | ||
| 66 | -- Use the PASSWORD_STORE_DIR environment variable to set the password store. | ||
| 67 | -- If empty, return the password store located in user's home. | ||
| 68 | -- | ||
| 69 | passwordStoreFolder :: IO String | ||
| 70 | passwordStoreFolder = | ||
| 71 | getEnv "PASSWORD_STORE_DIR" >>= computePasswordStoreDir | ||
| 72 | where computePasswordStoreDir Nothing = liftM passwordStoreFolderDefault getHomeDirectory | ||
| 73 | computePasswordStoreDir (Just storeDir) = return storeDir | ||
| 74 | |||
| 75 | -- | A pass prompt factory | ||
| 76 | -- | ||
| 77 | mkPassPrompt :: PromptLabel -> (String -> X ()) -> XPConfig -> X () | ||
| 78 | mkPassPrompt promptLabel passwordFunction xpconfig = do | ||
| 79 | passwords <- io (passwordStoreFolder >>= getPasswords) | ||
| 80 | mkXPrompt (Pass promptLabel) xpconfig (getPassCompl passwords $ searchPredicate xpconfig) passwordFunction | ||
| 81 | |||
| 82 | -- | Retrieve the list of passwords from the password storage 'passwordStoreDir | ||
| 83 | getPasswords :: FilePath -> IO [String] | ||
| 84 | getPasswords passwordStoreDir = do | ||
| 85 | files <- runProcessWithInput "find" [ | ||
| 86 | passwordStoreDir, | ||
| 87 | "-type", "f", | ||
| 88 | "-name", "*.gpg", | ||
| 89 | "-printf", "%P\n"] [] | ||
| 90 | return $ map removeGpgExtension $ lines files | ||
| 91 | |||
| 92 | removeGpgExtension :: String -> String | ||
| 93 | removeGpgExtension file | takeExtension file == ".gpg" = dropExtension file | ||
| 94 | | otherwise = file | ||
diff --git a/accounts/gkleen@sif/xmonad/lib/XMonad/Prompt/MyShell.hs b/accounts/gkleen@sif/xmonad/lib/XMonad/Prompt/MyShell.hs new file mode 100644 index 00000000..c268f87d --- /dev/null +++ b/accounts/gkleen@sif/xmonad/lib/XMonad/Prompt/MyShell.hs | |||
| @@ -0,0 +1,105 @@ | |||
| 1 | module XMonad.Prompt.MyShell | ||
| 2 | ( Shell (..) | ||
| 3 | , shellPrompt | ||
| 4 | , prompt | ||
| 5 | , safePrompt | ||
| 6 | , unsafePrompt | ||
| 7 | , getCommands | ||
| 8 | , getShellCompl | ||
| 9 | , split | ||
| 10 | ) where | ||
| 11 | |||
| 12 | import Codec.Binary.UTF8.String (encodeString) | ||
| 13 | import Control.Exception as E | ||
| 14 | import Control.Monad (forM) | ||
| 15 | import Data.List (isPrefixOf) | ||
| 16 | import System.Directory (doesDirectoryExist, getDirectoryContents) | ||
| 17 | import System.Environment (getEnv) | ||
| 18 | import System.Posix.Files (getFileStatus, isDirectory) | ||
| 19 | |||
| 20 | import XMonad hiding (config) | ||
| 21 | import XMonad.Prompt | ||
| 22 | import XMonad.Util.Run | ||
| 23 | |||
| 24 | econst :: Monad m => a -> IOException -> m a | ||
| 25 | econst = const . return | ||
| 26 | |||
| 27 | data Shell = Shell String | ||
| 28 | |||
| 29 | instance XPrompt Shell where | ||
| 30 | showXPrompt (Shell q) = q | ||
| 31 | completionToCommand _ = escape | ||
| 32 | |||
| 33 | shellPrompt :: String -> XPConfig -> X () | ||
| 34 | shellPrompt q c = do | ||
| 35 | cmds <- io getCommands | ||
| 36 | mkXPrompt (Shell q) c (getShellCompl cmds) spawn | ||
| 37 | |||
| 38 | {- $spawns | ||
| 39 | See safe and unsafeSpawn in "XMonad.Util.Run". | ||
| 40 | prompt is an alias for safePrompt; | ||
| 41 | safePrompt and unsafePrompt work on the same principles, but will use | ||
| 42 | XPrompt to interactively query the user for input; the appearance is | ||
| 43 | set by passing an XPConfig as the second argument. The first argument | ||
| 44 | is the program to be run with the interactive input. | ||
| 45 | You would use these like this: | ||
| 46 | |||
| 47 | > , ((modm, xK_b), safePrompt "firefox" greenXPConfig) | ||
| 48 | > , ((modm .|. shiftMask, xK_c), prompt ("xterm" ++ " -e") greenXPConfig) | ||
| 49 | |||
| 50 | Note that you want to use safePrompt for Firefox input, as Firefox | ||
| 51 | wants URLs, and unsafePrompt for the XTerm example because this allows | ||
| 52 | you to easily start a terminal executing an arbitrary command, like | ||
| 53 | 'top'. -} | ||
| 54 | |||
| 55 | prompt, unsafePrompt, safePrompt :: String -> FilePath -> XPConfig -> X () | ||
| 56 | prompt = unsafePrompt | ||
| 57 | safePrompt q c config = mkXPrompt (Shell q) config (getShellCompl [c]) run | ||
| 58 | where run = safeSpawn c . return | ||
| 59 | unsafePrompt q c config = mkXPrompt (Shell q) config (getShellCompl [c]) run | ||
| 60 | where run a = unsafeSpawn $ c ++ " " ++ a | ||
| 61 | |||
| 62 | getShellCompl :: [String] -> String -> IO [String] | ||
| 63 | getShellCompl cmds s | s == "" || last s == ' ' = return [] | ||
| 64 | | otherwise = do | ||
| 65 | f <- fmap lines $ runProcessWithInput "bash" [] ("compgen -A file -- " | ||
| 66 | ++ s ++ "\n") | ||
| 67 | files <- case f of | ||
| 68 | [x] -> do fs <- getFileStatus (encodeString x) | ||
| 69 | if isDirectory fs then return [x ++ "/"] | ||
| 70 | else return [x] | ||
| 71 | _ -> return f | ||
| 72 | return . uniqSort $ files ++ commandCompletionFunction cmds s | ||
| 73 | |||
| 74 | commandCompletionFunction :: [String] -> String -> [String] | ||
| 75 | commandCompletionFunction cmds str | '/' `elem` str = [] | ||
| 76 | | otherwise = filter (isPrefixOf str) cmds | ||
| 77 | |||
| 78 | getCommands :: IO [String] | ||
| 79 | getCommands = do | ||
| 80 | p <- getEnv "PATH" `E.catch` econst [] | ||
| 81 | let ds = filter (/= "") $ split ':' p | ||
| 82 | es <- forM ds $ \d -> do | ||
| 83 | exists <- doesDirectoryExist d | ||
| 84 | if exists | ||
| 85 | then getDirectoryContents d | ||
| 86 | else return [] | ||
| 87 | return . uniqSort . filter ((/= '.') . head) . concat $ es | ||
| 88 | |||
| 89 | split :: Eq a => a -> [a] -> [[a]] | ||
| 90 | split _ [] = [] | ||
| 91 | split e l = | ||
| 92 | f : split e (rest ls) | ||
| 93 | where | ||
| 94 | (f,ls) = span (/=e) l | ||
| 95 | rest s | s == [] = [] | ||
| 96 | | otherwise = tail s | ||
| 97 | |||
| 98 | escape :: String -> String | ||
| 99 | escape [] = "" | ||
| 100 | escape (x:xs) | ||
| 101 | | isSpecialChar x = '\\' : x : escape xs | ||
| 102 | | otherwise = x : escape xs | ||
| 103 | |||
| 104 | isSpecialChar :: Char -> Bool | ||
| 105 | isSpecialChar = flip elem " &\\@\"'#?$*()[]{};" | ||
diff --git a/accounts/gkleen@sif/xmonad/lib/XMonad/Prompt/MySsh.hs b/accounts/gkleen@sif/xmonad/lib/XMonad/Prompt/MySsh.hs new file mode 100644 index 00000000..729941aa --- /dev/null +++ b/accounts/gkleen@sif/xmonad/lib/XMonad/Prompt/MySsh.hs | |||
| @@ -0,0 +1,246 @@ | |||
| 1 | module XMonad.Prompt.MySsh | ||
| 2 | ( -- * Usage | ||
| 3 | -- $usage | ||
| 4 | sshPrompt, | ||
| 5 | Ssh, | ||
| 6 | Override (..), | ||
| 7 | mkOverride, | ||
| 8 | Conn (..), | ||
| 9 | moshCmd, | ||
| 10 | moshCmd', | ||
| 11 | sshCmd, | ||
| 12 | inTmux, | ||
| 13 | withEnv | ||
| 14 | ) where | ||
| 15 | |||
| 16 | import XMonad | ||
| 17 | import XMonad.Util.Run | ||
| 18 | import XMonad.Prompt | ||
| 19 | |||
| 20 | import System.Directory | ||
| 21 | import System.Environment | ||
| 22 | import qualified Control.Exception as E | ||
| 23 | |||
| 24 | import Control.Monad | ||
| 25 | import Data.Maybe | ||
| 26 | |||
| 27 | import Text.Parsec.String | ||
| 28 | import Text.Parsec | ||
| 29 | import Data.Char (isSpace) | ||
| 30 | |||
| 31 | econst :: Monad m => a -> E.IOException -> m a | ||
| 32 | econst = const . return | ||
| 33 | |||
| 34 | -- $usage | ||
| 35 | -- 1. In your @~\/.xmonad\/xmonad.hs@: | ||
| 36 | -- | ||
| 37 | -- > import XMonad.Prompt | ||
| 38 | -- > import XMonad.Prompt.Ssh | ||
| 39 | -- | ||
| 40 | -- 2. In your keybindings add something like: | ||
| 41 | -- | ||
| 42 | -- > , ((modm .|. controlMask, xK_s), sshPrompt defaultXPConfig) | ||
| 43 | -- | ||
| 44 | -- Keep in mind, that if you want to use the completion you have to | ||
| 45 | -- disable the "HashKnownHosts" option in your ssh_config | ||
| 46 | -- | ||
| 47 | -- For detailed instruction on editing the key binding see | ||
| 48 | -- "XMonad.Doc.Extending#Editing_key_bindings". | ||
| 49 | |||
| 50 | data Override = Override | ||
| 51 | { oUser :: Maybe String | ||
| 52 | , oHost :: String | ||
| 53 | , oPort :: Maybe Int | ||
| 54 | , oCommand :: Conn -> String | ||
| 55 | } | ||
| 56 | |||
| 57 | mkOverride = Override { oUser = Nothing, oHost = "", oPort = Nothing, oCommand = sshCmd } | ||
| 58 | sshCmd c = concat | ||
| 59 | [ "ssh -t " | ||
| 60 | , if isJust $ cUser c then (fromJust $ cUser c) ++ "@" else "" | ||
| 61 | , cHost c | ||
| 62 | , if isJust $ cPort c then " -p " ++ (show $ fromJust $ cPort c) else "" | ||
| 63 | , " -- " | ||
| 64 | , cCommand c | ||
| 65 | ] | ||
| 66 | moshCmd c = concat | ||
| 67 | [ "mosh " | ||
| 68 | , if isJust $ cUser c then (fromJust $ cUser c) ++ "@" else "" | ||
| 69 | , cHost c | ||
| 70 | , if isJust $ cPort c then " --ssh=\"ssh -p " ++ (show $ fromJust $ cPort c) ++ "\"" else "" | ||
| 71 | , " -- " | ||
| 72 | , cCommand c | ||
| 73 | ] | ||
| 74 | moshCmd' p c = concat | ||
| 75 | [ "mosh " | ||
| 76 | , "--server=" ++ p ++ " " | ||
| 77 | , if isJust $ cUser c then (fromJust $ cUser c) ++ "@" else "" | ||
| 78 | , cHost c | ||
| 79 | , if isJust $ cPort c then " --ssh=\"ssh -p " ++ (show $ fromJust $ cPort c) ++ "\"" else "" | ||
| 80 | , " -- " | ||
| 81 | , cCommand c | ||
| 82 | ] | ||
| 83 | inTmux Nothing c | ||
| 84 | | null $ cCommand c = c { cCommand = "tmux new-session" } | ||
| 85 | | otherwise = c { cCommand = "tmux new-session \"" ++ (cCommand c) ++ "\"" } | ||
| 86 | inTmux (Just h) c | ||
| 87 | | null $ cCommand c = c { cCommand = "tmux new-session -As " <> h } | ||
| 88 | | otherwise = c { cCommand = "tmux new-session \"" ++ (cCommand c) ++ "\"" } | ||
| 89 | withEnv :: [(String, String)] -> Conn -> Conn | ||
| 90 | withEnv envs c = c { cCommand = "env" ++ (concat $ map (\(n, v) -> ' ' : (n ++ "=" ++ v)) envs) ++ " " ++ (cCommand c) } | ||
| 91 | |||
| 92 | data Conn = Conn | ||
| 93 | { cUser :: Maybe String | ||
| 94 | , cHost :: String | ||
| 95 | , cPort :: Maybe Int | ||
| 96 | , cCommand :: String | ||
| 97 | } deriving (Eq, Show, Read) | ||
| 98 | |||
| 99 | data Ssh = Ssh | ||
| 100 | |||
| 101 | instance XPrompt Ssh where | ||
| 102 | showXPrompt Ssh = "SSH to: " | ||
| 103 | commandToComplete _ c = c | ||
| 104 | nextCompletion _ = getNextCompletion | ||
| 105 | |||
| 106 | toConn :: String -> Maybe Conn | ||
| 107 | toConn = toConn' . parse connParser "(unknown)" | ||
| 108 | toConn' :: Either ParseError Conn -> Maybe Conn | ||
| 109 | toConn' (Left _) = Nothing | ||
| 110 | toConn' (Right a) = Just a | ||
| 111 | |||
| 112 | connParser :: Parser Conn | ||
| 113 | connParser = do | ||
| 114 | spaces | ||
| 115 | user' <- optionMaybe $ try $ do | ||
| 116 | str <- many1 $ satisfy (\c -> (not $ isSpace c) && (c /= '@')) | ||
| 117 | char '@' | ||
| 118 | return str | ||
| 119 | host' <- many1 $ satisfy (not . isSpace) | ||
| 120 | port' <- optionMaybe $ try $ do | ||
| 121 | space | ||
| 122 | string "-p" | ||
| 123 | spaces | ||
| 124 | int <- many1 digit | ||
| 125 | (space >> return ()) <|> eof | ||
| 126 | return $ (read int :: Int) | ||
| 127 | spaces | ||
| 128 | command' <- many anyChar | ||
| 129 | eof | ||
| 130 | return $ Conn | ||
| 131 | { cHost = host' | ||
| 132 | , cUser = user' | ||
| 133 | , cPort = port' | ||
| 134 | , cCommand = command' | ||
| 135 | } | ||
| 136 | |||
| 137 | sshPrompt :: [Override] -> XPConfig -> X () | ||
| 138 | sshPrompt o c = do | ||
| 139 | sc <- io sshComplList | ||
| 140 | mkXPrompt Ssh c (mkComplFunFromList sc) $ ssh o | ||
| 141 | |||
| 142 | ssh :: [Override] -> String -> X () | ||
| 143 | ssh overrides str = do | ||
| 144 | let cmd = applyOverrides overrides str | ||
| 145 | liftIO $ putStr "SSH Command: " | ||
| 146 | liftIO $ putStrLn cmd | ||
| 147 | runInTerm "" cmd | ||
| 148 | |||
| 149 | applyOverrides :: [Override] -> String -> String | ||
| 150 | applyOverrides [] str = "ssh " ++ str | ||
| 151 | applyOverrides (o:os) str = case (applyOverride o str) of | ||
| 152 | Just str -> str | ||
| 153 | Nothing -> applyOverrides os str | ||
| 154 | |||
| 155 | applyOverride :: Override -> String -> Maybe String | ||
| 156 | applyOverride o str = let | ||
| 157 | conn = toConn str | ||
| 158 | in | ||
| 159 | if isNothing conn then Nothing else | ||
| 160 | case (fromJust conn) `matches` o of | ||
| 161 | True -> Just $ (oCommand o) (fromJust conn) | ||
| 162 | False -> Nothing | ||
| 163 | |||
| 164 | matches :: Conn -> Override -> Bool | ||
| 165 | a `matches` b = and | ||
| 166 | [ justBool (cUser a) (oUser b) (==) | ||
| 167 | , (cHost a) == (oHost b) | ||
| 168 | , justBool (cPort a) (oPort b) (==) | ||
| 169 | ] | ||
| 170 | |||
| 171 | justBool :: Eq a => Maybe a -> Maybe a -> (a -> a -> Bool) -> Bool | ||
| 172 | justBool Nothing _ _ = True | ||
| 173 | justBool _ Nothing _ = True | ||
| 174 | justBool (Just a) (Just b) match = a `match` b | ||
| 175 | |||
| 176 | sshComplList :: IO [String] | ||
| 177 | sshComplList = uniqSort `fmap` liftM2 (++) sshComplListLocal sshComplListGlobal | ||
| 178 | |||
| 179 | sshComplListLocal :: IO [String] | ||
| 180 | sshComplListLocal = do | ||
| 181 | h <- getEnv "HOME" | ||
| 182 | s1 <- sshComplListFile $ h ++ "/.ssh/known_hosts" | ||
| 183 | s2 <- sshComplListConf $ h ++ "/.ssh/config" | ||
| 184 | return $ s1 ++ s2 | ||
| 185 | |||
| 186 | sshComplListGlobal :: IO [String] | ||
| 187 | sshComplListGlobal = do | ||
| 188 | env <- getEnv "SSH_KNOWN_HOSTS" `E.catch` econst "/nonexistent" | ||
| 189 | fs <- mapM fileExists [ env | ||
| 190 | , "/usr/local/etc/ssh/ssh_known_hosts" | ||
| 191 | , "/usr/local/etc/ssh_known_hosts" | ||
| 192 | , "/etc/ssh/ssh_known_hosts" | ||
| 193 | , "/etc/ssh_known_hosts" | ||
| 194 | ] | ||
| 195 | case catMaybes fs of | ||
| 196 | [] -> return [] | ||
| 197 | (f:_) -> sshComplListFile' f | ||
| 198 | |||
| 199 | sshComplListFile :: String -> IO [String] | ||
| 200 | sshComplListFile kh = do | ||
| 201 | f <- doesFileExist kh | ||
| 202 | if f then sshComplListFile' kh | ||
| 203 | else return [] | ||
| 204 | |||
| 205 | sshComplListFile' :: String -> IO [String] | ||
| 206 | sshComplListFile' kh = do | ||
| 207 | l <- readFile kh | ||
| 208 | return $ map (getWithPort . takeWhile (/= ',') . concat . take 1 . words) | ||
| 209 | $ filter nonComment | ||
| 210 | $ lines l | ||
| 211 | |||
| 212 | sshComplListConf :: String -> IO [String] | ||
| 213 | sshComplListConf kh = do | ||
| 214 | f <- doesFileExist kh | ||
| 215 | if f then sshComplListConf' kh | ||
| 216 | else return [] | ||
| 217 | |||
| 218 | sshComplListConf' :: String -> IO [String] | ||
| 219 | sshComplListConf' kh = do | ||
| 220 | l <- readFile kh | ||
| 221 | return $ map (!!1) | ||
| 222 | $ filter isHost | ||
| 223 | $ map words | ||
| 224 | $ lines l | ||
| 225 | where | ||
| 226 | isHost ws = take 1 ws == ["Host"] && length ws > 1 | ||
| 227 | |||
| 228 | fileExists :: String -> IO (Maybe String) | ||
| 229 | fileExists kh = do | ||
| 230 | f <- doesFileExist kh | ||
| 231 | if f then return $ Just kh | ||
| 232 | else return Nothing | ||
| 233 | |||
| 234 | nonComment :: String -> Bool | ||
| 235 | nonComment [] = False | ||
| 236 | nonComment ('#':_) = False | ||
| 237 | nonComment ('|':_) = False -- hashed, undecodeable | ||
| 238 | nonComment _ = True | ||
| 239 | |||
| 240 | getWithPort :: String -> String | ||
| 241 | getWithPort ('[':str) = host ++ " -p " ++ port | ||
| 242 | where (host,p) = break (==']') str | ||
| 243 | port = case p of | ||
| 244 | ']':':':x -> x | ||
| 245 | _ -> "22" | ||
| 246 | getWithPort str = str | ||
