首页 > 解决方案 > Haskell Twitch(高级文件观察 DSL)执行 2 次

问题描述

我想使用 Twitch 包将“中央”目录中的任何 javascript 文件复制到“后”和“前”目录。这是代码:

{-# LANGUAGE OverloadedStrings #-}


module Main where

import Data.List
  ( isPrefixOf
  , tails
  , findIndex
  )
import System.Directory 
  ( createDirectoryIfMissing
  , removeDirectoryRecursive
  , copyFile
  )
import System.Directory.Recursive 
  ( getSubdirsRecursive
  , getFilesRecursive
  )
import Twitch
  ( defaultMain
  , (|>)
  )


main :: IO ()
main = do

  putStrLn "Haskell works <(^u^)>"

  -- Copy central folder to back and front, and setup recopy when central changes
  copyCentral
  defaultMain $ do 
    "./central/**/*.js" |> copyFileToBackAndFront




copyCentral :: IO ()
copyCentral = do

  createDirectoryIfMissing False "./back/src/central/" 
  removeDirectoryRecursive "./back/src/central"
  createDirectoryIfMissing False "./front/src/central/" 
  removeDirectoryRecursive "./front/src/central"

  centralFiles <- getFilesRecursive "./central/"
  centralDirs  <- getSubdirsRecursive "./central/"

  mapM_ (\d -> createDirectoryIfMissing True $ "./back/src" ++ tail d) centralDirs
  mapM_ (\d -> createDirectoryIfMissing True $ "./front/src" ++ tail d) centralDirs
  mapM_ (\f -> copyFile f $ "./back/src" ++ tail f) centralFiles
  mapM_ (\f -> copyFile f $ "./front/src" ++ tail f) centralFiles


copyFileToBackAndFront :: FilePath -> IO ()
copyFileToBackAndFront absolutePath = 
    maybe 
      (putStrLn "Error in the file path")
      getRelativePathAndCopy
      (findIndex (isPrefixOf "central") (tails absolutePath))
  where
    getRelativePathAndCopy n = do
      let relativePath = drop n absolutePath
      copyFile relativePath $ "./back/src/"  ++ relativePath
      copyFile relativePath $ "./front/src/" ++ relativePath
      putStrLn $ "Copied file " ++ relativePath ++ " to back and front"

令人惊讶的是它有效!但我得到 putStrLn 输出 2 次:

Copied file central\models\Board\Board.js to back and front
Copied file central\models\Board\Board.js to back and front

而且我怀疑这可能是因为程序在 2 个线程中运行,因为有时我会得到交错输出:

CCooppiieedd  ffiillee  cceennttrraall\\mmooddeellss\\BBooaarrdd\\BBooaarrdd..jjss  ttoo  bbaacckk  aanndd  ffrroonntt

CopiCeodp ifeidl ef icleen tcreanlt\rmaold\emlosd\eBlosa\rBdo\aBroda\rBdo.ajrsd .tjos  btaoc kb aacnkd  afnrdo nftr
ont

当我跑步时也会发生这种情况cabal v2-repl,我只是尝试过cabal v2-run myprogram &,但它根本不起作用:(

请问这两个问题有什么帮助吗?

标签: haskellconcurrencycorefile-watcher

解决方案


推荐阅读