From 406e274759b325b9987634e5f9e1536760b87c8f Mon Sep 17 00:00:00 2001 From: Sam Truzjan Date: Sat, 15 Feb 2014 07:20:00 +0400 Subject: Add command line arguments to tiny client --- examples/Client.hs | 69 ++++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 54 insertions(+), 15 deletions(-) diff --git a/examples/Client.hs b/examples/Client.hs index 320b4269..abf62657 100644 --- a/examples/Client.hs +++ b/examples/Client.hs @@ -1,26 +1,65 @@ +{-# LANGUAGE RankNTypes #-} +{-# LANGUAGE ExistentialQuantification #-} +{-# LANGUAGE RecordWildCards #-} module Main (main) where import Control.Concurrent import Control.Monad.Trans +import Options.Applicative import System.Environment import System.Exit import System.IO +import Text.Read + import Network.BitTorrent -parseArgs :: IO FilePath -parseArgs = do - args <- getArgs - case args of - [path] -> return path - _ -> do - hPutStrLn stderr "Usage: client file.torrent" - exitFailure +{----------------------------------------------------------------------- +-- Command line arguments +-----------------------------------------------------------------------} + +data TorrentBox = forall s. TorrentSource s => TorrentBox { unTorrentBox :: s } + +data Args = Args + { topic :: TorrentBox + , contentDir :: FilePath + } + +argsParser :: Parser Args +argsParser = Args <$> (TorrentBox <$> infohashP <|> TorrentBox <$> torrentP) + <*> destDirP + where + infohashP :: Parser InfoHash + infohashP = argument readMaybe + (metavar "SHA1" <> help "infohash of torrent file") + + torrentP :: Parser FilePath + torrentP = argument Just + ( metavar "FILE" + <> help "A .torrent file" + ) + + destDirP :: Parser FilePath + destDirP = argument Just + ( metavar "DIR" + <> help "Directory to put content" + ) + +argsInfo :: ParserInfo Args +argsInfo = info (helper <*> argsParser) + ( fullDesc + <> progDesc "A simple CLI bittorrent client" + <> header "foo" + ) + +{----------------------------------------------------------------------- +-- Client +-----------------------------------------------------------------------} + +run :: Args -> BitTorrent () +run (Args (TorrentBox t) dir) = do + h <- openHandle dir t + start h + liftIO $ threadDelay 10000000000 main :: IO () -main = do - path <- parseArgs - torrent <- fromFile path - simpleClient $ do - h <- openTorrent "data" torrent - start h - liftIO $ threadDelay 10000000000 +main = execParser argsInfo >>= simpleClient . run -- cgit v1.2.3