From a70db09a95ef041e9894d69fdfe21272353dce56 Mon Sep 17 00:00:00 2001 From: "J. Konrad Tegtmeier-Rottach" <jktr@0x16.de> Date: Wed, 3 May 2023 00:06:58 +0200 Subject: [PATCH] Apply minor linter suggestions --- qbar/src/QBar/BlockHelper.hs | 2 +- qbar/src/QBar/Blocks/Battery.hs | 2 +- qbar/src/QBar/Blocks/DiskUsage.hs | 4 ++-- qbar/src/QBar/Blocks/Pipe.hs | 2 +- qbar/src/QBar/Blocks/Qubes.hs | 2 +- qbar/src/QBar/Blocks/Script.hs | 4 ++-- qbar/src/QBar/Cli.hs | 3 +-- qbar/src/QBar/Color.hs | 12 ++++++----- qbar/src/QBar/Core.hs | 10 ++++----- qbar/src/QBar/Host.hs | 4 ++-- qbar/src/QBar/Qubes/AdminAPI.hs | 36 +++++++++++++++++-------------- qbar/src/QBar/Server.hs | 2 +- qbar/src/QBar/TagParser.hs | 4 ++-- qbar/src/QBar/Theme.hs | 2 +- qbar/src/QBar/Time.hs | 6 +++--- 15 files changed, 50 insertions(+), 45 deletions(-) diff --git a/qbar/src/QBar/BlockHelper.hs b/qbar/src/QBar/BlockHelper.hs index 0a3ff06..6366bf8 100644 --- a/qbar/src/QBar/BlockHelper.hs +++ b/qbar/src/QBar/BlockHelper.hs @@ -127,7 +127,7 @@ runSignalBlockConfiguration SignalBlockConfiguration{aquire, release, signalThre liftIO $ Event.wait renderEvent liftIO $ Event.clear renderEvent - currentState <- liftIO . atomically $ readTVar renderStateVar + currentState <- liftIO (readTVarIO renderStateVar) renderer' currentState where renderer' :: (Maybe BlockUpdate, Bool) -> Block diff --git a/qbar/src/QBar/Blocks/Battery.hs b/qbar/src/QBar/Blocks/Battery.hs index b9d32f9..302fe40 100644 --- a/qbar/src/QBar/Blocks/Battery.hs +++ b/qbar/src/QBar/Blocks/Battery.hs @@ -97,7 +97,7 @@ batteryBlock = runPollBlock $ forever $ do updateBatteryBlock :: Bool -> [BatteryState] -> PollBlock' () updateBatteryBlock _ [] = yieldEmptyBlockUpdate -updateBatteryBlock isPlugged bs = yieldBlockUpdate $ (shortText.~shortText') $ mkBlockOutput fullText' +updateBatteryBlock isPlugged bs = yieldBlockUpdate $ (shortText .~ shortText') $ mkBlockOutput fullText' where fullText' :: BlockText fullText' = overallPercentage <> optionalEachBattery <> optionalOverallEstimate diff --git a/qbar/src/QBar/Blocks/DiskUsage.hs b/qbar/src/QBar/Blocks/DiskUsage.hs index ebdf1c7..c624778 100644 --- a/qbar/src/QBar/Blocks/DiskUsage.hs +++ b/qbar/src/QBar/Blocks/DiskUsage.hs @@ -29,6 +29,6 @@ diskUsageBlock path = runPollBlock $ forever $ do (ExitFailure nr) -> mkErrorOutput $ "exit code " <> T.pack (show nr) <> "" createBlockOutput :: C8.ByteString -> BlockOutput createBlockOutput output = case map T.decodeUtf8 (C8.lines output) of - [] -> mkErrorOutput $ "no output" - [_header] -> mkErrorOutput $ "invalid output" + [] -> mkErrorOutput "no output" + [_header] -> mkErrorOutput "invalid output" (_header:values) -> mkBlockOutput $ normalText $ T.intercalate " " $ map T.strip values diff --git a/qbar/src/QBar/Blocks/Pipe.hs b/qbar/src/QBar/Blocks/Pipe.hs index 57183a9..9643d25 100644 --- a/qbar/src/QBar/Blocks/Pipe.hs +++ b/qbar/src/QBar/Blocks/Pipe.hs @@ -23,7 +23,7 @@ runPipeClient enableEvents mainOptions = do inputTask <- async $ runEffect $ PP.stdinLn >-> toOutput output void $ waitEitherCancel hostTask inputTask where - -- |Special block that reads the processes stdin line-by-line and shows the latest line in the block. Must never be used in a 'server' process or when stdin/stdout is used in another way. + -- Special block that reads the processes stdin line-by-line and shows the latest line in the block. Must never be used in a 'server' process or when stdin/stdout is used in another way. pipeBlock :: Producer String BarIO () -> Block pipeBlock source = ExitBlock <$ source >-> pack where diff --git a/qbar/src/QBar/Blocks/Qubes.hs b/qbar/src/QBar/Blocks/Qubes.hs index 52b4c33..f0e0ede 100644 --- a/qbar/src/QBar/Blocks/Qubes.hs +++ b/qbar/src/QBar/Blocks/Qubes.hs @@ -43,7 +43,7 @@ diskUsageQubesBlock = runPollBlock $ forever $ do ("k", 1024), (" bytes", 1) ] - formatSize size = case filter ((<size) . snd) sizeUnits of + formatSize size = case filter ((< size) . snd) sizeUnits of ((unit, factor) : _) -> T.pack (show $ size `div` factor) <> unit _ -> T.pack (show size) <> " bytes" diff --git a/qbar/src/QBar/Blocks/Script.hs b/qbar/src/QBar/Blocks/Script.hs index 0f3bae9..352a964 100644 --- a/qbar/src/QBar/Blocks/Script.hs +++ b/qbar/src/QBar/Blocks/Script.hs @@ -65,11 +65,11 @@ scriptBlock clickEvents path = startScriptProcess (True, Nothing) -> -- This will happen if we hit the race condition (see below) -- or the process closes its stdout without exiting. - Left $ "exit code unavailable" + Left "exit code unavailable" _ -> Left $ T.pack (show exc) ignoreIOException :: a -> IO a -> IO a ignoreIOException errValue = handle $ \(_ :: IOException) -> return errValue - handleErrorWithProcess :: (Process i o e) -> IOException -> Block + handleErrorWithProcess :: Process i o e -> IOException -> Block handleErrorWithProcess process exc = do -- We want to know whether the process has already exited or we are -- killing it because of some other error. stopProcess determines diff --git a/qbar/src/QBar/Cli.hs b/qbar/src/QBar/Cli.hs index d4e6d64..900eabf 100644 --- a/qbar/src/QBar/Cli.hs +++ b/qbar/src/QBar/Cli.hs @@ -1,4 +1,3 @@ -{-# LANGUAGE ApplicativeDo #-} {-# LANGUAGE TemplateHaskell #-} module QBar.Cli ( @@ -122,7 +121,7 @@ scriptBlockParser = helper <*> do -- HACK optparse-applicative does not support options of style --poll[=INTERVAL], -- so we add a second option to specify the interval explicitly instead -- https://github.com/pcapriotti/optparse-applicative/issues/243 - pollInterval <- fromMaybe defaultInterval <$> (optional $ IntervalSeconds <$> option auto ( + pollInterval <- fromMaybe defaultInterval <$> optional (IntervalSeconds <$> option auto ( long "interval" <> short 'i' <> metavar "SECONDS" <> diff --git a/qbar/src/QBar/Color.hs b/qbar/src/QBar/Color.hs index b39faf5..be259fe 100644 --- a/qbar/src/QBar/Color.hs +++ b/qbar/src/QBar/Color.hs @@ -52,14 +52,16 @@ colorParser = do doubleFromHex2 :: Parser Double doubleFromHex2 = (/ 256) . fromIntegral <$> hexadecimal'' 2 - -- |Variant of 'Data.Attoparsec.Text.hexadecimal' that parses a fixed amount of digits. - hexadecimal'' :: Int -> Parser Int + -- Variant of 'Data.Attoparsec.Text.hexadecimal' that parses a fixed amount of digits. + hexadecimal'' :: Int -> A.Parser Int hexadecimal'' digits = foldl step 0 <$> count digits (satisfy isHexDigit) where isHexDigit c = (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') - step a c | w >= 48 && w <= 57 = (a `shiftL` 4) .|. fromIntegral (w - 48) - | w >= 97 = (a `shiftL` 4) .|. fromIntegral (w - 87) - | otherwise = (a `shiftL` 4) .|. fromIntegral (w - 55) + + step :: Int -> Char -> Int + step a c | w >= 48 && w <= 57 = (a `shiftL` 4) .|. (w - 48) + | w >= 97 = (a `shiftL` 4) .|. (w - 87) + | otherwise = (a `shiftL` 4) .|. (w - 55) where w = ord c diff --git a/qbar/src/QBar/Core.hs b/qbar/src/QBar/Core.hs index 6e35ca8..ef9ad38 100644 --- a/qbar/src/QBar/Core.hs +++ b/qbar/src/QBar/Core.hs @@ -246,7 +246,7 @@ newCache'' = do -- |Creates a cache from a block. cacheBlock :: Block -> BlockCache -- 'Block's 'yield' an update whenever they want to update the cache. -cacheBlock pushBlock = newCache $ () <$ (pushBlock >-> updateBarP >-> addBlockName >-> PP.map (\a -> [a])) +cacheBlock pushBlock = newCache $ void $ pushBlock >-> updateBarP >-> addBlockName >-> PP.map (: []) where updateBarP :: Pipe BlockUpdate BlockState BarIO r updateBarP = forever $ do @@ -254,7 +254,7 @@ cacheBlock pushBlock = newCache $ () <$ (pushBlock >-> updateBarP >-> addBlockNa yield state updateBar reason - -- |Sets 'blockName' to a random (but static) identifier if an event handler is set but the 'blockName' is not set. + -- Sets 'blockName' to a random (but static) identifier if an event handler is set but the 'blockName' is not set. addBlockName :: Pipe BlockState BlockState BarIO r addBlockName = do defaultBlockName <- randomIdentifier @@ -274,9 +274,9 @@ autoPadding = autoPadding' 0 0 maybeBlock <- await case maybeBlock of (Just (block, eventHandler), reason) -> do - let fullLength' = max fullLength . printedLength $ block^.fullText - let shortLength' = max shortLength . printedLength $ block^.shortText._Just - yield $ (Just (padFullText fullLength' . padShortText shortLength' $ block, eventHandler), reason) + let fullLength' = max fullLength . printedLength $ block ^. fullText + let shortLength' = max shortLength . printedLength $ block ^. shortText._Just + yield (Just (padFullText fullLength' . padShortText shortLength' $ block, eventHandler), reason) autoPadding' fullLength' shortLength' (Nothing, reason) -> do yield (Nothing, reason) diff --git a/qbar/src/QBar/Host.hs b/qbar/src/QBar/Host.hs index 1696562..50e2aee 100644 --- a/qbar/src/QBar/Host.hs +++ b/qbar/src/QBar/Host.hs @@ -123,13 +123,13 @@ runBlocks bar HostHandle{barUpdateEvent, barUpdatedEvent, followupEventWaitTimeM writeIORef eventHandlerListIORef eventHandlerList where eventHandlerList :: [(T.Text, BlockEventHandler)] - eventHandlerList = mapMaybe getEventHandler $ blockStates + eventHandlerList = mapMaybe getEventHandler blockStates getEventHandler :: BlockState -> Maybe (T.Text, BlockEventHandler) getEventHandler Nothing = Nothing getEventHandler (Just (_, Nothing)) = Nothing getEventHandler (Just (blockOutput, Just eventHandler)) = do - blockName' <- blockOutput^.blockName + blockName' <- blockOutput ^. blockName return (blockName', eventHandler) diff --git a/qbar/src/QBar/Qubes/AdminAPI.hs b/qbar/src/QBar/Qubes/AdminAPI.hs index fe6866c..73a7146 100644 --- a/qbar/src/QBar/Qubes/AdminAPI.hs +++ b/qbar/src/QBar/Qubes/AdminAPI.hs @@ -86,7 +86,7 @@ instance Binary QubesAdminReturn where qubesAdminConnect :: BL.ByteString -> [BL.ByteString] -> IO (Process () Handle ()) qubesAdminConnect serviceName args = do hostname <- getHostName - let concatArgs sep = mconcat (map (sep<>) args) + let concatArgs sep = mconcat (map (sep <>) args) let cmd = if hostname == "dom0" then "qubesd-query dom0 " <> serviceName <> " dom0" <> concatArgs " " else "qrexec-client-vm dom0 " <> serviceName <> concatArgs "+" @@ -114,7 +114,7 @@ qubesAdminCall serviceName args = qubesTryAdminCall serviceName args >>= extract extract x@Exception {} = fail $ "service has returned an exception: " <> show x extract Event {} = fail "service has returned events instead of a reply" -qubesAdminCallP :: forall m. (P.MonadSafe m, MonadIO m, MonadFail m) +qubesAdminCallP :: forall m. (P.MonadSafe m, MonadFail m) => BL.ByteString -> [BL.ByteString] -> Producer QubesAdminReturn m () qubesAdminCallP serviceName args = do process <- liftIO $ qubesAdminConnect serviceName args @@ -137,7 +137,7 @@ qubesAdminCallP serviceName args = do go (runGetIncremental get) `P.finally` stopProcess process -qubesAdminEvents :: forall m. (P.MonadSafe m, MonadIO m, MonadFail m) +qubesAdminEvents :: forall m. (P.MonadSafe m, MonadFail m) => BL.ByteString -> [BL.ByteString] -> Producer QubesAdminReturn m () qubesAdminEvents serviceName args = qubesAdminCallP serviceName args >-> onlyEvents where @@ -147,14 +147,14 @@ qubesAdminEvents serviceName args = qubesAdminCallP serviceName args >-> onlyEve Exception {} -> fail $ "service has returned an exception: " ++ show reply Event {} -> yield reply -qubesVMStatsRaw :: forall m. (P.MonadSafe m, MonadIO m, MonadFail m) +qubesVMStatsRaw :: forall m. (P.MonadSafe m, MonadFail m) => Producer QubesAdminReturn m () qubesVMStatsRaw = qubesAdminEvents "admin.vm.Stats" [] data QubesVMStats = QubesVMStats { statsVMName :: BL.ByteString, memoryKB :: Int, cpuTime :: Int, cpuUsageRaw :: Int, cpuUsage :: Int } deriving (Eq, Ord, Show, Read) -qubesVMStats :: forall m. (P.MonadSafe m, MonadIO m, MonadFail m) +qubesVMStats :: forall m. (P.MonadSafe m, MonadFail m) => Producer QubesVMStats m () qubesVMStats = qubesVMStatsRaw >-> P.mapFoldable parse where parse :: QubesAdminReturn -> Maybe QubesVMStats @@ -188,11 +188,11 @@ data QubesEvent | PropertyDel { domainName :: BL.ByteString, changedProperty :: BL.ByteString, oldValue :: BL.ByteString } -- reset to default value deriving (Eq, Ord, Show, Read) -qubesEventsRaw :: forall m. (P.MonadSafe m, MonadIO m, MonadFail m) +qubesEventsRaw :: forall m. (P.MonadSafe m, MonadFail m) => Producer QubesAdminReturn m () qubesEventsRaw = qubesAdminEvents "admin.Events" [] -qubesEvents :: forall m. (P.MonadSafe m, MonadIO m, MonadFail m) +qubesEvents :: forall m. (P.MonadSafe m, MonadFail m) => Producer QubesEvent m () qubesEvents = qubesEventsRaw >-> P.mapFoldable parse where parse :: QubesAdminReturn -> Maybe QubesEvent @@ -208,7 +208,7 @@ qubesEvents = qubesEventsRaw >-> P.mapFoldable parse where DomainUpdatesAvailable evSubject (boolPropViaInt "value") (boolPropViaInt "oldvalue") "domain-start-failed" -> DomainStartFailed evSubject (fromMaybe "" $ getProp "reason") - _ -> case BLC.break (==':') evEvent of + _ -> case BLC.break (== ':') evEvent of ("property-set", _) -> PropertySet evSubject (fromMaybe "" $ getProp "name") (fromMaybe "" $ getProp "newvalue") (fromMaybe "" $ getProp "oldvalue") ("property-del", _) -> @@ -224,11 +224,11 @@ qubesEvents = qubesEventsRaw >-> P.mapFoldable parse where boolProp :: BL.ByteString -> Maybe Bool boolProp = readProp boolPropViaInt :: BL.ByteString -> Bool - boolPropViaInt = fromMaybe False . fmap (/=0) . intProp + boolPropViaInt = maybe False (/= 0) . intProp parse _ = Nothing -- shouldn't happen -> report error? printEvents :: Show a => Producer a (P.SafeT IO) () -> IO () -printEvents prod = P.runSafeT $ runEffect $ prod >-> (forever $ await >>= liftIO . print) +printEvents prod = P.runSafeT $ runEffect $ prod >-> forever (await >>= liftIO . print) data QubesVMState = VMRunning | VMHalted | UnknownState deriving (Eq, Ord, Enum) @@ -254,19 +254,23 @@ instance Read QubesVMState where qubesAdminCallLines :: BL.ByteString -> [BL.ByteString] -> IO [BL.ByteString] qubesAdminCallLines serviceName args = qubesAdminCall serviceName args >>= parse where + parse :: BLC.ByteString -> IO [BLC.ByteString] parse reply = BLC.split '\n' reply - & filter (/="") + & filter (/= "") & return qubesListVMs :: IO (Map.Map BL.ByteString QubesVMInfo) qubesListVMs = parse <$> qubesAdminCallLines "admin.vm.List" [] where + parse :: [BLC.ByteString] -> Map.Map BLC.ByteString QubesVMInfo parse = Map.fromList . map parseLine + + parseLine :: BLC.ByteString -> (BLC.ByteString, QubesVMInfo) parseLine line = (vmName, QubesVMInfo (readPropEmpty "state") (tryReadProp "class" & fromMaybe UnknownClass)) where (vmName : propsRaw) = BLC.split ' ' line - props = map (fmap BLC.tail . BLC.break (=='=')) propsRaw + props = map (fmap BLC.tail . BLC.break (== '=')) propsRaw getProp :: BL.ByteString -> Maybe BL.ByteString getProp name = lookup name props readPropEmpty :: Read a => BL.ByteString -> a @@ -274,7 +278,7 @@ qubesListVMs = parse <$> qubesAdminCallLines "admin.vm.List" [] tryReadProp :: Read a => BL.ByteString -> Maybe a tryReadProp name = readMaybe . BLC.unpack =<< getProp name -qubesListVMsP :: forall m. (P.MonadSafe m, MonadIO m, MonadFail m) +qubesListVMsP :: forall m. (P.MonadSafe m, MonadFail m) => Producer (Map.Map BL.ByteString QubesVMInfo) m () qubesListVMsP = liftIO qubesListVMs >>= yield >> qubesEvents >-> P.mapM (const $ liftIO qubesListVMs) @@ -286,7 +290,7 @@ qubesGetProperty name = parse <$> qubesAdminCall "admin.property.Get" [name] where parse reply = QubesPropertyInfo (isDefault == "default=True") (BL.drop 5 typeStr) value where - splitOn ch = fmap BLC.tail . BLC.break (==ch) + splitOn ch = fmap BLC.tail . BLC.break (== ch) (isDefault, (typeStr, value)) = splitOn ' ' reply & fmap (splitOn ' ') qubesListPropertyNames :: IO [BL.ByteString] @@ -304,7 +308,7 @@ qubesGetDefaultPool = propValue <$> qubesGetProperty "default_pool" qubesGetPoolInfo :: BL.ByteString -> IO [(BL.ByteString, BL.ByteString)] qubesGetPoolInfo name = map parseLine <$> qubesAdminCallLines "admin.pool.Info" [name] where - parseLine = fmap BLC.tail . BLC.break (=='=') + parseLine = fmap BLC.tail . BLC.break (== '=') qubesUsageOfDefaultPool :: IO (Maybe Int, Maybe Int) qubesUsageOfDefaultPool = qubesGetDefaultPool >>= qubesGetPoolInfo >>= extract @@ -340,7 +344,7 @@ qubesListLabels = qubesListLabelNames >>= mapM (toSndM qubesGetLabelColor) toSndM :: Applicative m => (a -> m b) -> a -> m (a, b) toSndM f x = sequenceA (x, f x) -qubesMonitorProperty :: forall m. (P.MonadSafe m, MonadIO m, MonadFail m) +qubesMonitorProperty :: forall m. MonadIO m => Producer QubesEvent m () -> BL.ByteString -> Producer QubesPropertyInfo m () qubesMonitorProperty events name = events >-> P.filter isRelevant >-> fetchValue where diff --git a/qbar/src/QBar/Server.hs b/qbar/src/QBar/Server.hs index d31a7d3..3737c9c 100644 --- a/qbar/src/QBar/Server.hs +++ b/qbar/src/QBar/Server.hs @@ -112,7 +112,7 @@ swayBarOutput options@MainOptions{indicator} = do hPut stderr "\n" hFlush stderr encodeOutput :: [ThemedBlockOutput] -> BS.ByteString - encodeOutput blocks = encode $ map renderPangoBlock $ blocks + encodeOutput blocks = encode $ map renderPangoBlock blocks renderPangoBlock :: ThemedBlockOutput -> PangoBlock renderPangoBlock ThemedBlockOutput{_fullText, _shortText, _blockName} = PangoBlock { pangoBlockFullText = renderPango _fullText, diff --git a/qbar/src/QBar/TagParser.hs b/qbar/src/QBar/TagParser.hs index 1eb6051..0ec71d3 100644 --- a/qbar/src/QBar/TagParser.hs +++ b/qbar/src/QBar/TagParser.hs @@ -60,7 +60,7 @@ tagParser = parser (False, normalImportant) spanParser :: Parser BlockText spanParser = do void $ string "<span" - (colors, backgrounds) <- unzip <$> (many' $ colorAttribute <|> backgroundAttribute) + (colors, backgrounds) <- unzip <$> many' (colorAttribute <|> backgroundAttribute) let color = listToMaybe . catMaybes $ colors let background = listToMaybe . catMaybes $ backgrounds void $ char '>' @@ -90,7 +90,7 @@ tagParser = parser (False, normalImportant) parseTags :: T.Text -> Either String BlockText -parseTags text = parseOnly (tagParser <* endOfInput) (T.toStrict text) +parseTags = parseOnly (tagParser <* endOfInput) parseTags' :: T.Text -> BlockOutput parseTags' = either (mkErrorOutput . T.pack) mkBlockOutput . parseTags diff --git a/qbar/src/QBar/Theme.hs b/qbar/src/QBar/Theme.hs index feb9ef5..3c92f85 100644 --- a/qbar/src/QBar/Theme.hs +++ b/qbar/src/QBar/Theme.hs @@ -159,7 +159,7 @@ rainbowTheme = AnimatedTheme rainbowThemePipe let text = rawText $ block ^. fullText let chars = T.unpack . T.reverse $ text coloredChars <- mapM rainbowChar chars - let rainbowText = reverse $ coloredChars + let rainbowText = reverse coloredChars return $ ThemedBlockOutput { _blockName, _fullText = ThemedBlockText rainbowText, diff --git a/qbar/src/QBar/Time.hs b/qbar/src/QBar/Time.hs index b205165..15a2121 100644 --- a/qbar/src/QBar/Time.hs +++ b/qbar/src/QBar/Time.hs @@ -63,7 +63,7 @@ class HasSleepScheduler m where createSleepScheduler :: MonadIO m => m SleepScheduler createSleepScheduler = liftIO $ do scheduler <- SleepScheduler <$> newMVar ([], []) <*> Event.new - link =<< (async $ schedulerThread scheduler) + link =<< async (schedulerThread scheduler) return scheduler where schedulerThread :: SleepScheduler -> IO () @@ -87,7 +87,7 @@ createSleepScheduler = liftIO $ do schedulerThread' start - -- |Waits for the next event, with a timeout. A return value of 'False' indicates a timeout occured. + -- Waits for the next event, with a timeout. A return value of 'False' indicates a timeout occured. waitForEvent :: UTCTime -> IO Bool waitForEvent eventTime = do now <- getCurrentTime @@ -109,7 +109,7 @@ createSleepScheduler = liftIO $ do Event.clear trigger return (futureEvents, []) - -- |Predicate to check if an event should be fired. + -- Predicate to check if an event should be fired. checkEvent :: UTCTime -> ScheduledEvent -> Bool checkEvent now ScheduledEvent{time} = now >= time -- GitLab