2016-10-27 00:59:27 +03:00
{- # LANGUAGE LambdaCase, GADTs, DataKinds # -}
2016-10-06 02:17:46 +03:00
module Main where
import Arguments
import Control.Exception
import Data.Aeson
import Data.Aeson.Encode.Pretty
import Data.Map.Strict as Map
import qualified Data.ByteString.Lazy as DL
import qualified Data.ByteString.Char8 as DC
import Data.String
import qualified Data.Text as DT
import JSONTestCase
import qualified Prelude
import Prologue
import SemanticDiff ( fetchDiffs )
import System.FilePath.Glob
import System.Process
import qualified Data.String.Utils as DSUtils
import Options.Applicative hiding ( ( <> ) )
import qualified Options.Applicative as O
import qualified Renderer as R
2016-10-27 00:59:13 +03:00
import Control.Monad.Effect
import Control.Monad.Effect.Internal
2016-10-06 02:17:46 +03:00
2016-10-27 00:55:08 +03:00
data GenerateFormat =
GenerateSummaries
| GenerateJSON
deriving ( Show )
data GeneratorArgs = GeneratorArgs { generateFormat :: GenerateFormat } deriving ( Show )
2016-10-06 02:17:46 +03:00
generatorArgs :: Parser GeneratorArgs
2016-10-27 00:55:08 +03:00
generatorArgs = GeneratorArgs
2016-11-01 18:01:28 +03:00
<$> ( flag' GenerateSummaries ( long " generate-summaries " O .<> short 's' O .<> help " Generates summary results for new JSON test cases " )
<|> flag' GenerateJSON ( long " generate-json " O .<> short 'j' O .<> help " Generate JSON output for new JSON test cases " ) )
2016-10-06 02:17:46 +03:00
options :: ParserInfo GeneratorArgs
options = info ( helper <*> generatorArgs ) ( fullDesc O .<> progDesc " Auto-generate JSON test cases " O .<> header " JSON Test Case Generator " )
main :: IO ()
main = do
opts <- execParser options
generatorFilePaths <- runFetchGeneratorFiles
2016-11-01 17:53:28 +03:00
metaRepos <- traverse DL . readFile generatorFilePaths
for_ ( decodeMetaRepos metaRepos ) ( handle opts generatorFilePaths )
where decodeMetaRepos :: [ DL . ByteString ] -> [ Either String [ JSONMetaRepo ] ]
decodeMetaRepos metaRepos = eitherDecode <$> metaRepos
handle :: GeneratorArgs -> [ FilePath ] -> Either String [ JSONMetaRepo ] -> IO ()
handle opts generatorFilePaths decodedMetaRepos =
case decodedMetaRepos of
2016-10-06 02:17:46 +03:00
Left err -> Prelude . putStrLn $ " An error occurred: " <> err
2016-11-01 17:53:28 +03:00
Right metaRepos -> do
traverse_ ( runGenerator opts ) metaRepos
2016-10-06 02:17:46 +03:00
traverse_ runMoveGeneratorFile generatorFilePaths
-- | Finds all JSON files within the generators directory.
runFetchGeneratorFiles :: IO [ FilePath ]
2016-10-06 03:16:59 +03:00
runFetchGeneratorFiles = globDir1 ( compile " *.json " ) " test/corpus/generators "
2016-10-06 02:17:46 +03:00
-- | First initialize the git submodule repository where commits will be made for the given metaRepo and its syntaxes.
-- | Second generate the commits for each syntax and generate the associated JSONTestCase objects.
-- | Finally push the generated commits to the submodule's remote repository.
runGenerator :: GeneratorArgs -> JSONMetaRepo -> IO ()
runGenerator opts metaRepo @ JSONMetaRepo { .. } = do
2016-11-01 17:53:28 +03:00
runSetupGitRepo repoUrl $ repoPath language
2016-10-06 02:17:46 +03:00
runCommitsAndTestCasesGeneration opts metaRepo
2016-11-01 17:53:28 +03:00
runPullGitRemote repoUrl $ repoPath language
runPushGitRemote $ repoPath language
-- | Defines the repoPath based on the convention that a repository is based on its language name for a defaut location.
repoPath :: String -> FilePath
repoPath language = " test/corpus/repos/ " <> language
2016-10-06 02:17:46 +03:00
-- | Upon successful test case generation for a generator file, move the file to the generated directory.
-- | This prevents subsequence runs of the test generator from duplicating test cases and adding extraneous
-- | commits to the git submodule.
runMoveGeneratorFile :: FilePath -> IO ()
runMoveGeneratorFile filePath = do
let updatedPath = DT . unpack $ DT . replace ( DT . pack " generators " ) ( DT . pack " generated " ) ( DT . pack filePath )
Prelude . putStrLn updatedPath
_ <- readCreateProcess ( shell $ " mv " <> filePath <> " " <> updatedPath ) " "
return ()
-- | Initializes a new git repository and adds it as a submodule to the semantic-diff git index.
-- | This repository contains the commits associated with the given JSONMetaRepo's syntax examples.
2016-11-01 17:53:28 +03:00
runSetupGitRepo :: String -> FilePath -> IO ()
runSetupGitRepo repoUrl repoPath = do
2016-10-06 02:17:46 +03:00
runInitializeRepo repoUrl repoPath
runAddSubmodule repoUrl repoPath
-- | Performs the system calls for initializing the git repository.
-- | If the git repository already exists, the operation will result in an error,
-- | but will not prevent successful completion of the test case generation.
runInitializeRepo :: String -> FilePath -> IO ()
runInitializeRepo repoUrl repoPath = do
result <- try $ readCreateProcess ( shell $ mkDirCommand repoPath ) " "
case ( result :: Either Prelude . IOError String ) of
Left error -> Prelude . putStrLn $ " Creating the repository directory at " <> repoPath <> " failed with: " <> show error <> " . " <> " Possible reason: repository already initialized. \ n Proceeding to the next step. "
Right _ -> do
_ <- executeCommand repoPath ( initializeRepoCommand repoUrl )
Prelude . putStrLn $ " Repository directory successfully initialized for " <> repoPath <> " . "
-- | Git repositories generated as a side-effect of generating tests cases are
-- | added to semantic-diff's git index as submodules. If the submodule initialization
-- | fails (usually because the submodule was already initialized), operations will
-- | continue.
runAddSubmodule :: String -> FilePath -> IO ()
runAddSubmodule repoUrl repoPath = do
result <- try $ readCreateProcess ( shell $ addSubmoduleCommand repoUrl repoPath ) " "
case ( result :: Either Prelude . IOError String ) of
Left error -> Prelude . putStrLn $ " Initializing the submodule repository at " <> repoPath <> " failed with: " <> show error <> " . " <> " Possible reason: submodule already initialized. \ n Proceeding to the next step. "
_ -> Prelude . putStrLn $ " Submodule successfully initialized for " <> repoPath <> " . "
-- | Performs the system calls for generating the commits and test cases.
-- | Also appends the JSONTestCases generated to the test case file defined by
-- | the syntaxes.
runCommitsAndTestCasesGeneration :: GeneratorArgs -> JSONMetaRepo -> IO ()
2016-10-28 04:42:46 +03:00
runCommitsAndTestCasesGeneration opts metaRepo @ JSONMetaRepo { .. } =
2016-10-06 02:17:46 +03:00
for_ syntaxes generate
2016-10-28 04:42:46 +03:00
where
generate :: JSONMetaSyntax -> IO ()
generate metaSyntax = do
_ <- runInitialCommitForSyntax metaRepo metaSyntax
2016-11-01 17:53:28 +03:00
runSetupTestCaseFile $ testCaseFilePath language opts metaSyntax
runCommitAndTestCaseGeneration opts metaRepo metaSyntax ( testCaseFilePath language opts metaSyntax )
runCloseTestCaseFile $ testCaseFilePath language opts metaSyntax
testCaseFilePath :: String -> GeneratorArgs -> JSONMetaSyntax -> FilePath
testCaseFilePath language GeneratorArgs { .. } JSONMetaSyntax { .. } = case generateFormat of
GenerateSummaries -> " test/corpus/diff-summaries/ " <> language <> " / " <> syntax <> " .json "
GenerateJSON -> " test/corpus/json/ " <> language <> " / " <> syntax <> " .json "
2016-10-06 02:17:46 +03:00
-- | For a syntax, we want the initial commit to be an empty file.
-- | This function performs a touch and commits the empty file.
2016-10-28 04:42:46 +03:00
runInitialCommitForSyntax :: JSONMetaRepo -> JSONMetaSyntax -> IO ()
runInitialCommitForSyntax JSONMetaRepo { .. } JSONMetaSyntax { .. } = do
2016-10-06 02:17:46 +03:00
Prelude . putStrLn $ " Generating initial commit for " <> syntax <> " syntax. "
2016-11-01 17:53:28 +03:00
result <- try . executeCommand ( repoPath language ) $ touchCommand ( syntax <> fileExt ) <> commitCommand syntax " Initial commit "
2016-10-06 02:17:46 +03:00
case ( result :: Either Prelude . IOError String ) of
2016-10-28 04:42:46 +03:00
Left error -> Prelude . putStrLn $ " Initializing the " <> syntax <> fileExt <> " failed with: " <> show error <> " . " <> " Possible reason: file already initialized. \ n Proceeding to the next step. "
2016-10-06 02:17:46 +03:00
Right _ -> pure ()
-- | Initializes the test case file where JSONTestCase examples are written to.
-- | This manually inserts a "[" to open a JSON array.
2016-10-28 04:42:46 +03:00
runSetupTestCaseFile :: FilePath -> IO ()
runSetupTestCaseFile testCaseFilePath = do
Prelude . putStrLn $ " Opening " <> testCaseFilePath
DL . writeFile testCaseFilePath " [ "
2016-10-06 02:17:46 +03:00
-- | For each command constructed for a given metaSyntax, execute the system commands.
2016-10-28 04:42:46 +03:00
runCommitAndTestCaseGeneration :: GeneratorArgs -> JSONMetaRepo -> JSONMetaSyntax -> FilePath -> IO ()
runCommitAndTestCaseGeneration opts metaRepo metaSyntax testCaseFilePath =
traverse_ ( runGenerateCommitAndTestCase opts metaRepo testCaseFilePath ) ( commands metaRepo metaSyntax )
2016-10-06 02:17:46 +03:00
2016-10-28 04:42:46 +03:00
-- | Converts a list of Output to a list of Renderer.Summary Map values
2016-10-07 18:28:57 +03:00
maybeMapSummary :: [ R . Output ] -> [ Maybe ( Map Text ( Map Text [ Value ] ) ) ]
2016-10-06 02:17:46 +03:00
maybeMapSummary = fmap $ \ case
R . SummaryOutput output -> Just output
_ -> Nothing
2016-10-28 04:42:46 +03:00
-- | Converst a list of Output to a list of Renderer.JSON values
2016-10-27 00:59:13 +03:00
maybeMapJSON :: [ R . Output ] -> [ Maybe ( Map Text Value ) ]
maybeMapJSON = fmap $ \ case
R . JSONOutput output -> Just output
_ -> Nothing
2016-10-06 02:17:46 +03:00
-- | This function represents the heart of the test case generation. It keeps track of
-- | the git shas prior to running a command, fetches the git sha after a command, so that
-- | JSONTestCase objects can be created. Finally, it appends the created JSONTestCase
-- | object to the test case file.
2016-10-28 04:42:46 +03:00
runGenerateCommitAndTestCase :: GeneratorArgs -> JSONMetaRepo -> FilePath -> ( JSONMetaSyntax , String , String , String ) -> IO ()
runGenerateCommitAndTestCase opts JSONMetaRepo { .. } testCaseFilePath ( JSONMetaSyntax { .. } , description , seperator , command ) = do
2016-10-06 02:17:46 +03:00
Prelude . putStrLn $ " Executing " <> syntax <> " " <> description <> " commit. "
2016-10-27 00:59:13 +03:00
2016-11-01 17:53:28 +03:00
beforeSha <- executeCommand ( repoPath language ) getLastCommitShaCommand
_ <- executeCommand ( repoPath language ) command
afterSha <- executeCommand ( repoPath language ) getLastCommitShaCommand
2016-10-06 02:17:46 +03:00
2016-11-01 17:53:28 +03:00
expectedResult' <- runExpectedResult ( repoPath language ) beforeSha afterSha ( syntax <> fileExt ) opts
2016-10-06 02:17:46 +03:00
let jsonTestCase = encodePretty JSONTestCase {
2016-11-01 17:53:28 +03:00
gitDir = extractGitDir ( repoPath language ) ,
2016-10-06 02:17:46 +03:00
testCaseDescription = language <> " - " <> syntax <> " - " <> description <> " - " <> " test " ,
2016-10-28 04:42:46 +03:00
filePaths = [ syntax <> fileExt ] ,
2016-10-06 02:17:46 +03:00
sha1 = beforeSha ,
sha2 = afterSha ,
2016-10-27 00:59:13 +03:00
expectedResult = expectedResult'
2016-10-06 02:17:46 +03:00
}
Prelude . putStrLn $ " Generating test case for " <> language <> " : " <> syntax <> " " <> description <> " . "
DL . appendFile testCaseFilePath $ jsonTestCase <> DL . fromStrict ( DC . pack seperator )
where extractGitDir :: String -> String
extractGitDir fullRepoPath = DC . unpack $ snd $ DC . breakSubstring ( DC . pack " test " ) ( DC . pack fullRepoPath )
2016-10-31 23:03:12 +03:00
-- | This constructs an Eff and runs it to return the appropriate IO ExpectedResult.
runExpectedResult :: FilePath -> String -> String -> FilePath -> GeneratorArgs -> IO ExpectedResult
runExpectedResult repoPath beforeSha afterSha repoFilePath GeneratorArgs { .. } =
case generateFormat of
GenerateSummaries -> Main . run $ constructSummariesEff repoPath beforeSha afterSha repoFilePath
GenerateJSON -> Main . run $ constructJSONEff repoPath beforeSha afterSha repoFilePath
2016-10-27 00:59:13 +03:00
data GenerateEff a where
GenerateSummaries' :: Arguments -> GenerateEff ExpectedResult
GenerateJSON' :: Arguments -> GenerateEff ExpectedResult
2016-10-31 23:03:12 +03:00
-- | Construct an Eff whose queue includes only GenerateEff effects.
constructSummariesEff :: FilePath -> String -> String -> FilePath -> Eff '[GenerateEff] ExpectedResult
constructSummariesEff repoPath beforeSha afterSha repoFilePath = send $ GenerateSummaries' ( args repoPath beforeSha afterSha [ repoFilePath ] R . Summary )
2016-10-27 00:59:13 +03:00
2016-10-31 23:03:12 +03:00
-- | Construct an Eff whose queue includes only GenerateEff effects.
constructJSONEff :: FilePath -> String -> String -> FilePath -> Eff '[GenerateEff] ExpectedResult
constructJSONEff repoPath beforeSha afterSha repoFilePath = send $ GenerateJSON' ( args repoPath beforeSha afterSha [ repoFilePath ] R . JSON )
2016-10-27 00:59:13 +03:00
2016-10-31 23:03:12 +03:00
-- | Evaluate the Effs and return the IO ExpectedResult.
2016-10-27 00:59:13 +03:00
run :: Eff '[GenerateEff] ExpectedResult -> IO ExpectedResult
run ( Val x ) = pure x
run ( E u queue ) = case decompose u of
2016-10-28 04:42:46 +03:00
( Right ( GenerateSummaries' args ) ) -> generateSummaries args >>= \ s -> Main . run ( apply queue s )
( Right ( GenerateJSON' args ) ) -> generateJSON args >>= \ s -> Main . run ( apply queue s )
2016-11-01 18:18:41 +03:00
( Left _ ) -> pure $ SummaryResult ( Map . fromList [ ( " changes " , Map . singleton mempty mempty ) , ( " errors " , Map . singleton mempty mempty ) ] )
2016-10-27 00:59:13 +03:00
2016-10-31 23:03:12 +03:00
-- | Produces DiffSummary results for the given Arguments.
generateSummaries :: Arguments -> IO ExpectedResult
2016-10-27 00:59:13 +03:00
generateSummaries args @ Arguments { .. } = do
diffs <- fetchDiffs args
let headResult = Prelude . head $ maybeMapSummary diffs
let changes = fromMaybe ( fromList [ ( " changes " , mempty ) ] ) headResult ! " changes "
let errors = fromMaybe ( fromList [ ( " errors " , mempty ) ] ) headResult ! " errors "
pure $ SummaryResult ( Map . fromList [ ( " changes " , changes ) , ( " errors " , errors ) ] )
2016-10-31 23:03:12 +03:00
-- | Produces JSON output for the given Arguments.
generateJSON :: Arguments -> IO ExpectedResult
2016-10-27 00:59:13 +03:00
generateJSON args = do
diffs <- fetchDiffs args
let headResult = Prelude . head $ maybeMapJSON diffs
let oids = fromMaybe ( fromList [ ( " oids " , " " ) ] ) headResult ! " oids "
let paths = fromMaybe ( fromList [ ( " output " , " " ) ] ) headResult ! " paths "
let rows = fromMaybe ( fromList [ ( " rows " , " " ) ] ) headResult ! " rows "
pure $ JSONResult ( Map . fromList [ ( " oids " , oids ) , ( " paths " , paths ) , ( " rows " , rows ) ] )
2016-10-06 02:17:46 +03:00
-- | Commands represent the various combination of patches (insert, delete, replacement)
-- | for a given syntax.
2016-10-28 04:42:46 +03:00
commands :: JSONMetaRepo -> JSONMetaSyntax -> [ ( JSONMetaSyntax , String , String , String ) ]
commands JSONMetaRepo { .. } metaSyntax @ JSONMetaSyntax { .. } =
2016-11-03 21:07:10 +03:00
[ ( metaSyntax , " insert " , commaSeperator , insertCommands )
, ( metaSyntax , " replacement-insert " , commaSeperator , replaceInsertCommands )
, ( metaSyntax , " delete-insert " , commaSeperator , deleteInsertCommands )
, ( metaSyntax , " replacement " , commaSeperator , replacementCommands )
, ( metaSyntax , " delete-replacement " , commaSeperator , deleteReplacementCommands )
, ( metaSyntax , " delete " , commaSeperator , deleteCommands )
, ( metaSyntax , " delete-rest " , spaceSeperator , deleteRestCommands )
2016-10-06 02:17:46 +03:00
]
where commaSeperator = " \ n , "
spaceSeperator = " "
2016-10-28 04:42:46 +03:00
repoFilePath = syntax <> fileExt
2016-11-03 21:07:10 +03:00
withTemplate = contentsWithTemplate template
insertCommands
= fileWriteCommand repoFilePath ( withTemplate " " )
<> commitCommand syntax " setup "
<> fileWriteCommand repoFilePath ( withTemplate insert )
<> commitCommand syntax " insert "
replaceInsertCommands
= fileWriteCommand repoFilePath ( withTemplate ( Prologue . intercalate " \ n " [ replacement , insert , insert ] ) )
<> commitCommand syntax " replacement + insert + insert "
deleteInsertCommands
= fileWriteCommand repoFilePath ( withTemplate ( Prologue . intercalate " \ n " [ insert , insert , insert ] ) )
<> commitCommand syntax " delete + insert "
replacementCommands
= fileWriteCommand repoFilePath ( withTemplate ( Prologue . intercalate " \ n " [ replacement , insert , insert ] ) )
<> commitCommand syntax " replacement "
deleteReplacementCommands
= fileWriteCommand repoFilePath ( withTemplate ( Prologue . intercalate " \ n " [ insert , replacement ] ) )
<> commitCommand syntax " delete + replacement "
deleteCommands
= fileWriteCommand repoFilePath ( withTemplate replacement )
<> commitCommand syntax " delete "
deleteRestCommands
= removeCommand repoFilePath
<> touchCommand repoFilePath
<> commitCommand syntax " delete rest "
contentsWithTemplate :: Maybe String -> String -> String
contentsWithTemplate ( Just template ) contents = DT . unpack $ DT . replace " {0} " ( toS contents ) ( toS template )
contentsWithTemplate Nothing contents = contents
2016-10-06 02:17:46 +03:00
2016-10-10 20:38:28 +03:00
-- | Attempts to pull from the git repository's remote repository.
2016-10-11 19:55:28 +03:00
-- | If the pull fails, the exception is caught and continues to the next step.
2016-10-10 20:38:28 +03:00
runPullGitRemote :: String -> FilePath -> IO ()
runPullGitRemote repoUrl repoPath = do
Prelude . putStrLn " Attempting to fetch from the remote repository. "
2016-10-11 19:07:51 +03:00
_ <- executeCommand repoPath checkoutMasterCommand
2016-10-10 20:38:28 +03:00
result <- attempt
2016-10-11 19:55:28 +03:00
handle result next errorMessage
2016-10-10 20:38:28 +03:00
where attempt :: IO ( Either Prelude . IOError String )
attempt = try $ executeCommand repoPath pullFromRemoteCommand
handle :: Either Prelude . IOError String -> IO () -> ( Prelude . IOError -> IO () ) -> IO ()
handle result success err = case ( result :: Either Prelude . IOError String ) of
Left error -> err error
Right _ -> success
next :: IO ()
next = Prelude . putStrLn " Remote repository successfully fetched. \ n "
errorMessage :: Prelude . IOError -> IO ()
2016-10-11 19:55:28 +03:00
errorMessage err = Prelude . putStrLn $ " Pulling from the remote repository at " <> repoUrl <> " failed with: " <> show err <> " . Proceeding to the next step. \ n "
2016-10-10 20:38:28 +03:00
2016-10-06 02:17:46 +03:00
-- | Pushes git commits to the submodule repository's remote.
2016-10-10 20:38:46 +03:00
runPushGitRemote :: FilePath -> IO ()
runPushGitRemote repoPath = do
2016-10-06 02:17:46 +03:00
Prelude . putStrLn " Updating git remote. "
2016-10-11 18:03:48 +03:00
result <- try $ executeCommand repoPath pushToGitRemoteCommand
case ( result :: Either Prelude . IOError String ) of
Left err -> die $ " Failed to push to remote repository: " <> show err
Right _ -> Prelude . putStrLn " Successfully updated git remote. "
2016-10-06 02:17:46 +03:00
-- | Closes the JSON array and closes the test case file.
2016-10-28 04:42:46 +03:00
runCloseTestCaseFile :: FilePath -> IO ()
runCloseTestCaseFile testCaseFilePath = do
Prelude . putStrLn $ " Closing " <> testCaseFilePath
DL . appendFile testCaseFilePath " ] \ n "
2016-10-06 02:17:46 +03:00
initializeRepoCommand :: String -> String
initializeRepoCommand repoUrl = " rm -rf *; rm -rf .git; git init .; git remote add origin " <> repoUrl <> " ; "
addSubmoduleCommand :: String -> FilePath -> String
addSubmoduleCommand repoUrl repoPath = " git submodule add " <> repoUrl <> " " <> " ./ " <> repoPath <> " ; "
getLastCommitShaCommand :: String
getLastCommitShaCommand = " git log --pretty=format: \ " %H \ " -n 1; "
2016-10-11 19:07:51 +03:00
checkoutMasterCommand :: String
checkoutMasterCommand = " git checkout master; "
2016-10-10 20:38:28 +03:00
pullFromRemoteCommand :: String
pullFromRemoteCommand = " git pull origin master; "
2016-10-06 02:17:46 +03:00
touchCommand :: FilePath -> String
touchCommand repoFilePath = " touch " <> repoFilePath <> " ; "
-- | In order to correctly record syntax examples that include backticks (like JavaScript template strings)
-- | we must first escape them for bash (due to the use of the `echo` system command). Additionally,
-- | we must also escape the escape character `\` in Haskell, hence the double `\\`.
fileWriteCommand :: FilePath -> String -> String
fileWriteCommand repoFilePath contents = " echo \ " " <> ( escapeBackticks . escapeDoubleQuotes ) contents <> " \ " > " <> repoFilePath <> " ; "
where
escapeBackticks = DSUtils . replace " ` " " \ \ ` "
escapeDoubleQuotes = DSUtils . replace " \ " " " \ \ \ " "
commitCommand :: String -> String -> String
commitCommand syntax commitMessage = " git add .; git commit -m \ " " <> syntax <> " : " <> commitMessage <> " \ " " <> " ; "
removeCommand :: FilePath -> String
removeCommand repoFilePath = " rm " <> repoFilePath <> " ; "
pushToGitRemoteCommand :: String
pushToGitRemoteCommand = " git push origin HEAD; "
mkDirCommand :: FilePath -> String
mkDirCommand repoPath = " mkdir " <> repoPath <> " ; "
executeCommand :: FilePath -> String -> IO String
executeCommand repoPath command = readCreateProcess ( shell command ) { cwd = Just repoPath } " "