summaryrefslogtreecommitdiff
path: root/src/Main.hs
blob: 24f52c6f11fffb0559d13f6b7122bc33000b9093 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
{- This Source Code Form is subject to the terms of the Mozilla Public License,
   v. 2.0. If a copy of the MPL was not distributed with this file, You can
   obtain one at https://mozilla.org/MPL/2.0/. -}

module Main
    ( main
    ) where

import Data.Char (isNumber)
import Control.Applicative (Applicative(liftA2))
import Data.List.NonEmpty (NonEmpty(..))
import qualified Data.List.NonEmpty as NonEmpty
import Control.Monad.Catch (MonadThrow(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Maybe (fromJust)
import qualified Data.Map as Map
import Options.Applicative (execParser)
import SlackBuilder.CommandLine
import SlackBuilder.Config
import SlackBuilder.Trans
import SlackBuilder.LatestVersionCheck
import qualified Toml
import qualified Data.ByteString as ByteString
import Data.Text (Text)
import qualified Data.Text as Text
import qualified Data.Text.IO as Text.IO
import Control.Monad.Trans.Reader (ReaderT(..), asks)
import SlackBuilder.Download
import SlackBuilder.Package (Package(..))
import qualified SlackBuilder.Package as Package
import Text.URI (URI(..), mkURI)
import Text.URI.QQ (uri)
import Data.Foldable (Foldable(..), for_, find)
import qualified Text.URI as URI
import System.FilePath ((</>), (<.>), dropExtension, takeBaseName, makeRelative, splitFileName, takeDirectory, takeFileName)
import SlackBuilder.Info
import Text.Megaparsec (parse, errorBundlePretty)
import GHC.Records (HasField(..))
import System.Process
    ( CmdSpec(..)
    , CreateProcess(..)
    , StdStream(..)
    , callProcess
    , withCreateProcess
    , waitForProcess
    )
import System.Console.ANSI
    ( setSGR
    , SGR(..)
    , ColorIntensity(..)
    , Color(..)
    , ConsoleLayer(..)
    )
import System.Directory (listDirectory, doesDirectoryExist, withCurrentDirectory, removeDirectoryRecursive)
import Control.Monad (filterM)
import Data.List (isPrefixOf, isSuffixOf, partition)
import Conduit (runConduitRes, (.|), sourceFile)

autoUpdatable :: [Package]
autoUpdatable =
    [ Package
        { latest =
            let ghArguments = PackageOwner{ owner = "universal-ctags", name = "ctags" }
                templateTail =
                    [ Package.VersionPlaceholder
                    , Package.StaticPlaceholder "/ctags-"
                    , Package.VersionPlaceholder
                    , Package.StaticPlaceholder ".tar.gz"
                    ]
                template = Package.DownloadTemplate
                    $ Package.StaticPlaceholder "https://github.com/universal-ctags/ctags/archive/"
                    :| templateTail
             in Package.Updater
                { detectLatest = latestGitHub ghArguments stableTagTransform
                , getVersion = reuploadWithTemplate template []
                , is64 = False
                }
        , category = "development"
        , name = "universal-ctags"
        , downloaders = mempty
        }
    , Package
        { latest =
            let packagistArguments = PackageOwner{ owner = "composer", name = "composer" }
                template = Package.DownloadTemplate
                    $ Package.StaticPlaceholder "https://getcomposer.org/download/"
                    :| [Package.VersionPlaceholder, Package.StaticPlaceholder "/composer.phar"]
             in Package.Updater
                { detectLatest = latestPackagist packagistArguments
                , getVersion = downloadWithTemplate template
                , is64 = False
                }
        , category = "development"
        , name = "composer"
        , downloaders = mempty
        }
    , Package
        { latest =
            let ghArguments = PackageOwner
                    { owner = "jitsi"
                    , name = "jitsi-meet-electron"
                    }
                template = Package.DownloadTemplate
                    $ Package.StaticPlaceholder "https://github.com/jitsi/jitsi-meet-electron/releases/download/v"
                    :| Package.VersionPlaceholder
                    : [Package.StaticPlaceholder "/jitsi-meet-x86_64.AppImage"]
             in Package.Updater
                { detectLatest = latestGitHub ghArguments $ Text.stripPrefix "v"
                , getVersion = downloadWithTemplate template
                , is64 = True
                }
        , category = "network"
        , name = "jitsi-meet-desktop"
        , downloaders = mempty
        }
    , Package
        { latest =
            let ghArguments = PackageOwner
                    { owner = "php"
                    , name = "php-src"
                    }
                checkVersion x
                    | not $ Text.isInfixOf "RC" x
                    , Text.isPrefixOf "php-8.2." x = Text.stripPrefix "php-" x
                    | otherwise = Nothing
                template = Package.DownloadTemplate
                    $ Package.StaticPlaceholder "https://www.php.net/distributions/php-"
                    :| Package.VersionPlaceholder
                    : [Package.StaticPlaceholder ".tar.xz"]
             in Package.Updater
                { detectLatest = latestGitHub ghArguments checkVersion
                , getVersion = downloadWithTemplate template
                , is64 = False
                }
        , category = "development"
        , name = "php82"
        , downloaders = mempty
        }
    , Package
        { latest =
            let ghArguments = PackageOwner
                    { owner = "kovidgoyal"
                    , name = "kitty"
                    }
                templateTail =
                    [ Package.StaticPlaceholder "/kitty-"
                    , Package.VersionPlaceholder
                    , Package.StaticPlaceholder ".tar.xz"
                    ]
                template = Package.DownloadTemplate
                    $ Package.StaticPlaceholder "https://github.com/kovidgoyal/kitty/releases/download/v"
                    :| Package.VersionPlaceholder
                    : templateTail
             in Package.Updater
                { detectLatest = latestGitHub ghArguments stableTagTransform
                , getVersion = reuploadWithTemplate template [RawCommand "go" ["mod", "vendor"]]
                , is64 = False
                }
        , category = "system"
        , name = "kitty"
        , downloaders = mempty
        }
    , Package
        { latest =
            let ghArguments = PackageOwner
                    { owner = "rdiff-backup"
                    , name = "rdiff-backup"
                    }
                template = Package.DownloadTemplate
                    $ Package.StaticPlaceholder "https://github.com/rdiff-backup/rdiff-backup/releases/download/v"
                    :| Package.VersionPlaceholder
                    : Package.StaticPlaceholder "/rdiff-backup-"
                    : Package.VersionPlaceholder
                    : [Package.StaticPlaceholder ".tar.gz"]
             in Package.Updater
                { detectLatest = latestGitHub ghArguments $ Text.stripPrefix "v"
                , getVersion = reuploadWithTemplate template []
                , is64 = False
                }
        , category = "system"
        , name = "rdiff-backup"
        , downloaders = mempty
        }
    , Package
        { latest =
            let needle = "Linux—"
                textArguments = TextArguments
                    { textURL = "https://help.webex.com/en-us/article/mqkve8/Webex-App-%7C-Release-notes"
                    , versionPicker = Text.takeWhile (liftA2 (||) (== '.') isNumber)
                        . Text.drop (Text.length needle)
                        . snd
                        . Text.breakOn needle
                    }
                template = Package.DownloadTemplate $ pure
                    $ Package.StaticPlaceholder
                        "https://binaries.webex.com/WebexDesktop-Ubuntu-Official-Package/Webex.deb"
             in Package.Updater
                { detectLatest = latestText textArguments
                , getVersion = downloadWithTemplate template
                , is64 = True
                }
        , category = "network"
        , name = "webex"
        , downloaders = mempty
        }
    , Package
        { latest =
            let ghArguments = PackageOwner
                    { owner = "librsync"
                    , name = "librsync"
                    }
                template = Package.DownloadTemplate
                    $ Package.StaticPlaceholder "https://github.com/librsync/librsync/archive/v"
                    :| Package.VersionPlaceholder
                    : Package.StaticPlaceholder "/librsync-"
                    : Package.VersionPlaceholder
                    : [Package.StaticPlaceholder ".tar.gz"]
             in Package.Updater
                { detectLatest = latestGitHub ghArguments $ Text.stripPrefix "v"
                , getVersion = reuploadWithTemplate template []
                , is64 = True
                }
        , category = "libraries"
        , name = "librsync"
        , downloaders = mempty
        }
    , Package
        { latest =
            let textArguments = TextArguments
                    { textURL = "https://downloads.dlang.org/releases/LATEST"
                    , versionPicker = Text.strip
                    }
                template = Package.DownloadTemplate
                    $ Package.StaticPlaceholder "https://downloads.dlang.org/releases/2.x/"
                    :| Package.VersionPlaceholder
                    : Package.StaticPlaceholder "/dmd."
                    : Package.VersionPlaceholder
                    : [Package.StaticPlaceholder ".linux.tar.xz"]
             in Package.Updater
                { detectLatest = latestText textArguments
                , getVersion = downloadWithTemplate template
                , is64 = False
                }
        , category = "development"
        , name = "dmd"
        , downloaders = mempty
        }
    , Package
        { latest =
            let textArguments = TextArguments
                    { textURL = "https://downloads.dlang.org/releases/LATEST"
                    , versionPicker = Text.strip
                    }
                template = Package.DownloadTemplate
                    $ Package.StaticPlaceholder "https://codeload.github.com/dlang/tools/tar.gz/v"
                    :| [Package.VersionPlaceholder]
             in Package.Updater
                { detectLatest = latestText textArguments
                , getVersion = reuploadWithTemplate template []
                , is64 = False
                }
        , category = "development"
        , name = "d-tools"
        , downloaders =
            let dubArguments = PackageOwner{ owner = "dlang", name = "dub" }
                dscannerArguments = PackageOwner{ owner = "dlang-community", name = "D-Scanner" }
                dcdArguments = PackageOwner{ owner = "dlang-community", name = "DCD" }
                latestDub = Package.Updater
                    { detectLatest = latestGitHub dubArguments stableTagTransform
                    , getVersion = downloadWithTemplate dubTemplate
                    , is64 = False
                    }
                latestDscanner = Package.Updater
                    { detectLatest = latestGitHub dscannerArguments stableTagTransform
                    , getVersion = cloneFromGit dscannerURI "v"
                    , is64 = False
                    }
                dcdURI = [uri|https://github.com/dlang-community/DCD.git|]
                latestDcd = Package.Updater
                    { detectLatest = latestGitHub dcdArguments stableTagTransform
                    , getVersion = cloneFromGit dcdURI "v"
                    , is64 = False
                    }
                dubTemplate = Package.DownloadTemplate
                    $ Package.StaticPlaceholder "https://codeload.github.com/dlang/dub/tar.gz/v"
                    :| [Package.VersionPlaceholder]
                dscannerURI = [uri|https://github.com/dlang-community/D-Scanner.git|]
             in Map.fromList
                [ ("DUB", latestDub)
                , ("DSCANNER", latestDscanner) 
                , ("DCD", latestDcd)
                ]
        }
    ]

up2Date :: Maybe Text -> SlackBuilderT ()
up2Date = \case
    Nothing -> for_ autoUpdatable go
    Just packageName
        | Just foundPackage <- find ((packageName ==) . getField @"name") autoUpdatable ->
            go foundPackage
        | otherwise -> throwM $ UpdaterNotFound packageName
  where
    go package = getAndLogLatest package
        >>= mapM_ (updatePackageIfRequired package)
        >> liftIO (putStrLn "")

check :: SlackBuilderT ()
check = for_ autoUpdatable go
  where
    go package = getAndLogLatest package
        >>= mapM_ (checkUpdateAvailability package)
        >> liftIO (putStrLn "")

getAndLogLatest :: Package -> SlackBuilderT (Maybe Text)
getAndLogLatest Package{ latest = Package.Updater{ detectLatest }, name }
    = liftIO (putStrLn $ Text.unpack name <> ": Retreiving the latest version.")
    >> detectLatest

checkUpdateAvailability :: Package -> Text -> SlackBuilderT (Maybe PackageInfo)
checkUpdateAvailability Package{..} version = do
    let packagePath = Text.unpack category </> Text.unpack name </> (Text.unpack name <.> "info")
    repository' <- SlackBuilderT $ asks repository
    infoContents <- liftIO $ ByteString.readFile $ repository' </> packagePath

    case parse parseInfoFile packagePath infoContents of
        Right parsedInfoFile
            | version == getField @"version" parsedInfoFile ->
                liftIO $ do
                    setSGR [SetColor Foreground Dull Green]
                    Text.IO.putStrLn
                        $ name <> " is up to date (Version " <> version <> ")."
                    setSGR [Reset]
                    pure Nothing
            | otherwise ->
                liftIO $ do
                    setSGR [SetColor Foreground Dull Yellow]
                    Text.IO.putStr
                        $ "A new version of "
                        <> name <> " " <> getField @"version" parsedInfoFile
                        <> " is available (" <> version <> ")."
                    setSGR [Reset]
                    putStrLn ""
                    pure $ Just parsedInfoFile
        Left errorBundle -> liftIO (putStr $ errorBundlePretty errorBundle)
            >> pure Nothing

updatePackageIfRequired :: Package -> Text -> SlackBuilderT ()
updatePackageIfRequired package version
    = checkUpdateAvailability package version
    >>= mapM_ (updatePackage package version)

data DownloadUpdated = DownloadUpdated
    { result :: Package.Download
    , version :: Text
    , is64 :: Bool
    } deriving (Eq, Show)

updateDownload :: Text -> Package.Updater -> SlackBuilderT DownloadUpdated
updateDownload packagePath Package.Updater{..} = do
    latestDownloadVersion <- fromJust <$> detectLatest
    result <- getVersion packagePath latestDownloadVersion
    pure $ DownloadUpdated
        { result = result
        , version = latestDownloadVersion
        , is64 = is64
        }

cloneFromGit :: URI -> Text -> Text -> Text -> SlackBuilderT Package.Download
cloneFromGit repo tagPrefix packagePath version = do
    let downloadFileName = URI.unRText
            $ NonEmpty.last $ snd $ fromJust $ URI.uriPath repo
        relativeTarball = Text.unpack packagePath
            </> (dropExtension (Text.unpack downloadFileName) <> "-" <> Text.unpack version)
    (uri', checksum) <- fromJust <$> cloneAndUpload (URI.render repo) relativeTarball tagPrefix
    pure $ Package.Download
        { md5sum = checksum
        , download = uri'
        }

downloadWithTemplate :: Package.DownloadTemplate -> Text -> Text -> SlackBuilderT Package.Download
downloadWithTemplate downloadTemplate packagePath version = do
    repository' <- SlackBuilderT $ asks repository
    uri' <- liftIO $ Package.renderDownloadWithVersion downloadTemplate version
    let downloadFileName = URI.unRText
            $ NonEmpty.last $ snd $ fromJust $ URI.uriPath uri'
        relativeTarball = packagePath <> "/" <> downloadFileName
        tarball = repository' </> Text.unpack relativeTarball
    checksum <- fromJust <$> download uri' tarball
    pure $ Package.Download uri' checksum

reuploadWithTemplate :: Package.DownloadTemplate -> [CmdSpec] -> Text -> Text -> SlackBuilderT Package.Download
reuploadWithTemplate downloadTemplate commands packagePath version = do
    repository' <- SlackBuilderT $ asks repository
    uri' <- liftIO $ Package.renderDownloadWithVersion downloadTemplate version
    let downloadFileName = URI.unRText
            $ NonEmpty.last $ snd $ fromJust $ URI.uriPath uri'
        relativeTarball = Text.unpack $ packagePath <> "/" <> downloadFileName
        tarball = repository' </> relativeTarball

    extractRemote uri' packagePath
    download' <- handleReupload relativeTarball downloadFileName
    checksum <- liftIO $ runConduitRes $ sourceFile tarball .| sinkHash

    pure $ Package.Download download' checksum
  where
    name' = Text.pack $ takeBaseName $ Text.unpack packagePath
    handleReupload relativeTarball downloadFileName = do
        repository' <- SlackBuilderT $ asks repository
        downloadURL' <- SlackBuilderT $ asks downloadURL

        liftIO $ putStrLn $ "Upload the source tarball " <> relativeTarball
        case commands of
            [] -> uploadCommand relativeTarball ("/" <> name')
            _ ->
                let tarballPath = repository' </> relativeTarball
                    packedDirectory = dropExtension $ dropExtension tarballPath
                 in liftIO (traverse (defaultCreateProcess packedDirectory) commands)
                >> liftIO
                    ( withCurrentDirectory (takeDirectory tarballPath)
                    $ callProcess "tar" ["Jcvf", takeFileName tarballPath, takeFileName packedDirectory]
                    )
                >> liftIO (removeDirectoryRecursive packedDirectory)
                >> uploadCommand relativeTarball ("/" <> name')
        liftIO $ mkURI $ downloadURL' <> "/" <> name' <> "/" <> downloadFileName
    defaultCreateProcess cwd' cmdSpec
        = flip withCreateProcess (const . const . const waitForProcess)
        $ CreateProcess
            { use_process_jobs = False
            , std_out = Inherit
            , std_in = NoStream
            , std_err = Inherit
            , new_session = False
            , env = Nothing
            , detach_console = False
            , delegate_ctlc = False
            , cwd = Just cwd'
            , create_new_console = False
            , create_group = False
            , cmdspec = cmdSpec
            , close_fds = True
            , child_user = Nothing
            , child_group = Nothing
            }

updatePackage :: Package -> Text -> PackageInfo -> SlackBuilderT ()
updatePackage Package{..} version info = do
    let packagePath = category <> "/" <> name

    repository' <- SlackBuilderT $ asks repository
    mainDownload <- (, getField @"is64" latest)
        <$> getField @"getVersion" latest packagePath version
    moreDownloads <- traverse (updateDownload packagePath) downloaders
    let (downloads64, allDownloads) = partition snd
            $ mainDownload
            : (liftA2 (,) (getField @"result") (getField @"is64") <$> toList moreDownloads)
    let infoFilePath = repository' </> Text.unpack packagePath
            </> (Text.unpack name <.> "info")
        package' = info
            { version = version
            , downloads = getField @"download" . fst <$> allDownloads
            , checksums = getField @"md5sum" . fst <$> allDownloads
            , downloadX64 = getField @"download" . fst <$> downloads64
            , checksumX64 = getField @"md5sum" . fst <$> downloads64
            }
    liftIO $ Text.IO.writeFile infoFilePath $ generate package'
    updateSlackBuildVersion packagePath version
        $ getField @"version" <$> moreDownloads

    commit packagePath version

findCategory :: FilePath -> IO [FilePath]
findCategory currentDirectory = do
    contents <- liftIO $ listDirectory currentDirectory
    case find (isSuffixOf ".info") contents of
        Just _ -> pure [currentDirectory]
        Nothing -> do
            let contents' = (currentDirectory </>) <$> filter (not . isPrefixOf ".") contents
            directories <- filterM doesDirectoryExist contents'
            subCategories <- traverse findCategory directories
            pure $ concat subCategories

main :: IO ()
main = do
    programCommand <- execParser slackBuilderParser
    settings <- Toml.decodeFile settingsCodec "config/config.toml"
    latestVersion <- flip runReaderT settings
        $ runSlackBuilderT
        $ executeCommand programCommand

    maybe (pure ()) Text.IO.putStrLn latestVersion
  where
    executeCommand = \case
        CategoryCommand -> do
            repository' <- SlackBuilderT $ asks repository
            categories <- liftIO $ findCategory repository'
            liftIO $ print $ splitFileName . makeRelative repository' <$> categories
            pure Nothing
        CheckCommand -> check >> pure Nothing
        Up2DateCommand packageName -> up2Date packageName >> pure Nothing