From df49ab92f3f4d30eb7578cdef3f929e95dfff098 Mon Sep 17 00:00:00 2001 From: joe Date: Thu, 31 Jul 2014 00:45:19 -0400 Subject: Hosts.hs tweaks --- Hosts.hs | 46 +++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 43 insertions(+), 3 deletions(-) diff --git a/Hosts.hs b/Hosts.hs index 5b117c7..29e54be 100644 --- a/Hosts.hs +++ b/Hosts.hs @@ -130,7 +130,7 @@ scrubName f line = line' (a,ws') = splitAt 2 ws ws'' = f ws' line' = if null ws'' - then if length a==2 then "# " <> L.concat a <> ign + then if length a==2 then "" -- "# " <> L.concat a <> ign else line else if length a==2 then L.concat (a ++ ws'') <> ign @@ -147,6 +147,36 @@ scrubName f line = line' assignName :: SockAddr -> L.ByteString -> Hosts -> Hosts assignName addr name hosts = assignName0 False addr name hosts +chaddr :: Int -> SockAddr -> Hosts -> Hosts +chaddr n addr hosts = + hosts { addrnum = Map.insert addr n (addrnum hosts) + , numline = Map.adjust re n (numline hosts) } + where + re line = if length a==2 + then L.pack (inet_ntop addr) <> " " <> L.concat ws' <> ign + else line + where (x,ign) = L.break (=='#') line + ws = L.groupBy ( (==EQ) `oo` comparing isSpace) x + where oo = (.) . (.) + (a,ws') = splitAt 2 ws + +isLonerName line = length ws' <= 2 + where (x,_) = L.break (=='#') line + ws = L.groupBy ( (==EQ) `oo` comparing isSpace) x + where oo = (.) . (.) + (_,ws') = splitAt 2 ws + +scrubTrailingEmpties :: Hosts -> Hosts +scrubTrailingEmpties hosts = + hosts { lineCount = cnt' + , numline = foldl' (flip Map.delete) (numline hosts) es + } + where + cnt = lineCount hosts + es = takeWhile (\n -> Map.lookup n (numline hosts) == Just "") + $ [cnt,cnt-1..] + cnt' = cnt - length es + assignName0 :: Bool -> SockAddr -> L.ByteString -> Hosts -> Hosts assignName0 iscannon addr name hosts = hosts' where @@ -157,9 +187,19 @@ assignName0 iscannon addr name hosts = hosts' then hosts -- address already has name, nothing to do else let hosts0 = -- remove name if it's present - maybe hosts (removeName hosts) ns + scrubTrailingEmpties $ maybe hosts (removeName hosts) ns + ns' = fmap (filter $ + isLonerName + . fromJust + . (\n -> Map.lookup n (numline hosts))) + ns + >>= listToMaybe hosts1 = -- insert name, or add new line - maybe (newLine hosts0) (appendName iscannon name hosts0) a + maybe (maybe (newLine hosts0) + (\n -> chaddr n addr $ appendName iscannon name hosts0 n) + ns') + (appendName iscannon name hosts0) + a in hosts1 removeName hosts nums = hosts { namenum = Map.delete name (namenum hosts) -- cgit v1.2.3