Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add --filename flag for overriding the filename when using stdioTarget #264

Merged
merged 1 commit into from
Nov 22, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 13 additions & 6 deletions main/Main.hs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import Data.ByteString.Char8 (unpack)
import Data.Either (lefts)
import Data.FileEmbed
import Data.List (isSuffixOf)
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import qualified Data.Text.IO as TextIO (getContents, hPutStr, putStr)
import Data.Version (showVersion)
Expand Down Expand Up @@ -49,7 +50,8 @@ data Nixfmt = Nixfmt
quiet :: Bool,
strict :: Bool,
verify :: Bool,
ast :: Bool
ast :: Bool,
filename :: Maybe FilePath
}
deriving (Show, Data, Typeable)

Expand All @@ -76,7 +78,12 @@ options =
ast =
False
&= help
"Pretty print the internal AST, only for debugging"
"Pretty print the internal AST, only for debugging",
filename =
Nothing
&= help
"The filename to display when the file input is given through stdin.\n\
\Useful for tools like editors and autoformatters that wish to use Nixfmt without providing it direct file access, while still providing context to where the file is."
}
&= summary ("nixfmt " ++ versionFromFile)
&= help "Format Nix source code"
Expand Down Expand Up @@ -132,8 +139,8 @@ checkTarget format Target{tDoRead, tPath} = do
| formatted == contents -> Right ()
| otherwise -> Left $ tPath ++ ": not formatted"

stdioTarget :: Target
stdioTarget = Target TextIO.getContents "<stdin>" (const TextIO.putStr)
stdioTarget :: Maybe FilePath -> Target
stdioTarget filename = Target TextIO.getContents (fromMaybe "<stdin>" filename) (const TextIO.putStr)

fileTarget :: FilePath -> Target
fileTarget path = Target (readFileUtf8 path) path atomicWriteFile
Expand All @@ -148,8 +155,8 @@ checkFileTarget :: FilePath -> Target
checkFileTarget path = Target (readFileUtf8 path) path (const $ const $ pure ())

toTargets :: Nixfmt -> IO [Target]
toTargets Nixfmt{files = []} = pure [stdioTarget]
toTargets Nixfmt{files = ["-"]} = pure [stdioTarget]
toTargets Nixfmt{files = [], filename} = pure [stdioTarget filename]
toTargets Nixfmt{files = ["-"], filename} = pure [stdioTarget filename]
toTargets Nixfmt{check = False, files = paths} = map fileTarget <$> collectAllNixFiles paths
toTargets Nixfmt{check = True, files = paths} = map checkFileTarget <$> collectAllNixFiles paths

Expand Down