{-# LANGUAGE TemplateHaskell #-}

-- | Primary interface for looking up the programming language of a file or
-- interacting with languages known to linguist
-- (https://github.com/github/linguist).
module Data.Languages
  ( languagesForPath,
    languages,
    languagesByExtension,
    languagesByFileName,
    LanguageKey,
    Language (..),
    languageName
  )
where

import Control.Applicative
import Data.Languages.Templates
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Text (Text)
import qualified Data.Text as Text
import System.FilePath.Posix

$(Map String [String]
Map String Language
languagesByFileName :: Map String [String]
languagesByExtension :: Map String [String]
languages :: Map String Language
generateLanguageMap)

-- | Find the set of possible languages for a given file path.
--
-- Multiple results will be returned for ambiguous files; for example, @.md@ files can be Markdown or GCC machine descriptions, and @.php@ files can be PHP or Hack source files.
languagesForPath :: FilePath -> [Language]
languagesForPath :: String -> [Language]
languagesForPath String
path = [Language]
languageForFileName [Language] -> [Language] -> [Language]
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> [Language]
languageForExtension
  where
    languageForFileName :: [Language]
languageForFileName = String -> Map String [String] -> [Language]
languageFor (String -> String
takeFileName String
path) Map String [String]
languagesByFileName
    languageForExtension :: [Language]
languageForExtension = String -> Map String [String] -> [Language]
languageFor (String -> String
takeExtension String
path) Map String [String]
languagesByExtension
    languageFor :: String -> Map.Map String [LanguageKey] -> [Language]
    languageFor :: String -> Map String [String] -> [Language]
languageFor String
k =
      (String -> [Language]) -> [String] -> [Language]
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (Maybe Language -> [Language]
forall a. Maybe a -> [a]
maybeToList (Maybe Language -> [Language])
-> (String -> Maybe Language) -> String -> [Language]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (String -> Map String Language -> Maybe Language)
-> Map String Language -> String -> Maybe Language
forall a b c. (a -> b -> c) -> b -> a -> c
flip String -> Map String Language -> Maybe Language
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup Map String Language
languages)
        ([String] -> [Language])
-> (Map String [String] -> [String])
-> Map String [String]
-> [Language]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [String] -> Maybe [String] -> [String]
forall a. a -> Maybe a -> a
fromMaybe []
        (Maybe [String] -> [String])
-> (Map String [String] -> Maybe [String])
-> Map String [String]
-> [String]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> Map String [String] -> Maybe [String]
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup String
k