fbrnch 1.8.3 → 1.8.4
raw patch · 39 files changed
+836/−432 lines, 39 filesdep +boxesdep +forgejodep +pagure-clidep ~fedora-krbdep ~pagure
Dependencies added: boxes, forgejo, pagure-cli, terminal-size
Dependency ranges changed: fedora-krb, pagure
Files
- CHANGELOG.md +37/−9
- README.md +2/−1
- fbrnch.cabal +9/−3
- src/Bodhi.hs +27/−24
- src/Branches.hs +2/−2
- src/Bugzilla.hs +8/−9
- src/Cmd/BranchLogs.hs +1/−1
- src/Cmd/Build.hs +5/−3
- src/Cmd/Bump.hs +1/−0
- src/Cmd/CompareTarballs.hs +121/−27
- src/Cmd/Copr.hs +41/−30
- src/Cmd/CreateReview.hs +2/−1
- src/Cmd/FTBFS.hs +1/−1
- src/Cmd/Fetch.hs +2/−2
- src/Cmd/Import.hs +22/−25
- src/Cmd/Install.hs +8/−6
- src/Cmd/ListPackages.hs +3/−3
- src/Cmd/Local.hs +7/−7
- src/Cmd/Mock.hs +11/−10
- src/Cmd/PRs.hs +22/−0
- src/Cmd/Parallel.hs +3/−1
- src/Cmd/Prep.hs +4/−4
- src/Cmd/Pull.hs +1/−1
- src/Cmd/RequestBranch.hs +74/−49
- src/Cmd/RequestRepo.hs +46/−11
- src/Cmd/ReviewPackage.hs +65/−43
- src/Cmd/SideTags.hs +2/−1
- src/Cmd/Sort.hs +13/−11
- src/Cmd/Update.hs +21/−21
- src/Cmd/UpdateReview.hs +2/−2
- src/Common/System.hs +17/−2
- src/Forgejo.hs +39/−0
- src/Git.hs +8/−1
- src/Koji.hs +16/−13
- src/ListReviews.hs +1/−2
- src/Main.hs +104/−39
- src/Package.hs +23/−23
- src/Pagure.hs +7/−13
- src/RpmBuild.hs +58/−31
CHANGELOG.md view
@@ -1,5 +1,33 @@ # Changelog +## 1.8.4 (2026-11-23)+- 'build','parallel': list open PRs before proceeding to building+- 'compare-tarballs','update-sources': improved source name/version logic+- 'compare-tarballs': download (older) tarball if missing+- 'copr': improved state wait logic+- 'import': don't ask for branches again if coming from request-repos+- 'mock': add --no-bootstrap and use it by default inside a container+- 'parallel': better pseudo sidetag for --dryrun+- 'prs': new command to list open PRs for a package+- 'request-branches': add --skip-request-check+- 'request-branches': intercept expired token to allow creating a new one+- 'request-branches': rename --skip-check to --skip-koji-check+- 'request-repos': intercept expired token to allow creating a new one inline+- 'request-repos','request-branches': now use forgejo to check Fedora Forge+- 'review-package': prefix prep timing output+- 'review-package': specify files to rpmlint+- 'review-package': highlight differing source with red+- 'sort','graph': add --deps (closes #74)+- add `--dryrun` option to many more commands+- Bodhi: retry without re-asking for notes when update creation failed+- RpmBuild getSources: be pedantic about spectool result (#74)+- RpmBuild: use "script -e" to exit with error code+- improve header/fetch output handling+- introduce new monadic `error'`+- main: output list of subcommands in vertical columns when no args+- add --list-commands hidden option+- use fedora-krb-0.1.1+ ## 1.8.3 (2026-06-03) - 'compare-tarballs': order tarballs by removal and addition @@ -19,13 +47,16 @@ - 'copr': retry coprGetBuild when watching a build - 'install': take %_rpmdir into account - 'local','install': rename --rebuild to --force-build-- 'parallel: for single package do full kojiWaitTask-- 'parallel: notify-send for failure or --must-push failure-- 'parallel: use reverse text to highlight problem prompts-- 'pull: use retry-- 'request-branches: include branches in comment-- 'update-sources: for "sources" diff also compare-tarballs+- 'parallel': for single package do full kojiWaitTask+- 'parallel': notify-send for failure or --must-push failure+- 'parallel': use reverse text to highlight problem prompts+- 'pull': use retry+- 'request-branches': include branches in comment+- 'update-sources': for "sources" diff also compare-tarballs - 'waitrepo': rename --no-nvr to --no-package+- 'watchtask': displays build hosts initially+- 'watchtask': can watch ongoing package branch build; --progress+- 'watchtask': improve formatting with arch padding and list hosts host - Koji getChildrenTasks: use maybeTimeout to avoid crash - Koji: introduce kojiGetTaskState' for DRY - Koji: kojiBuild output profile if uploading srpm@@ -38,9 +69,6 @@ - kojiWatchBuildTask loopWatch: check parent state not number of buildArchs - kojiWatchBuildTask: track display of NVR (in Cyan) - stack: lts-24.28 has crypton-x509-system-1.6.8-- 'watchtask': displays build hosts initially-- 'watchtask': can watch ongoing package branch build; --progress-- 'watchtask': improve formatting with arch padding and list hosts host ## 1.8 (2026-01-02) - 'branch-log': new command to check local and remote branches
README.md view
@@ -270,7 +270,7 @@ `$ fbrnch --version` ```-1.8.3+1.8.4 ``` `$ fbrnch --help`@@ -324,6 +324,7 @@ not-installed Packages not installed locally uninstall Remove installed package(s) bugs List package bugs+ prs List package PRs bump Bump release for package commit Git commit packages pull Git pull packages
fbrnch.cabal view
@@ -1,6 +1,6 @@ cabal-version: 2.2 name: fbrnch-version: 1.8.3+version: 1.8.4 synopsis: Fedora packager tool to build package branches description: fbrnch (fedora branch or "f-branch" for short) is@@ -71,6 +71,7 @@ Cmd.Mock Cmd.Override Cmd.Owner+ Cmd.PRs Cmd.Parallel Cmd.Prep Cmd.Pull@@ -94,6 +95,7 @@ Common Common.System Common.Text+ Forgejo Git InterleaveOutput Koji@@ -114,6 +116,7 @@ async, base >= 4.9 && < 5, bodhi,+ boxes, bugzilla-redhat >= 1.0.1, bytestring, config-ini,@@ -123,15 +126,17 @@ either, email-validate, extra,- fedora-krb,+ fedora-krb >= 0.1.1, fedora-releases >= 0.3, filepath,+ forgejo, http-conduit, http-directory >= 0.1.9, http-query, koji, network-uri,- pagure >= 0.2.1,+ pagure >= 0.2.2,+ pagure-cli >= 0.3, pretty-terminal, process, -- regex-tdfa,@@ -143,6 +148,7 @@ simple-cmd >= 0.2.7, simple-cmd-args >= 0.1.8, simple-prompt >= 0.2.3,+ terminal-size, text, time, typed-process >= 0.2.4.0,
src/Bodhi.hs view
@@ -12,6 +12,7 @@ ) where +import Control.Exception.Extra (retry) import Data.Aeson.Types (Object) import Data.Char (isDigit) import Data.RPM.NVR (NVR)@@ -76,7 +77,7 @@ "enhancement" -> RP.lift (R.string s) >> return EnhancementUpdate "newpackage" -> RP.lift (R.string s) >> return NewPackageUpdate "template" -> RP.lift (R.string s) >> return TemplateUpdate- _ -> error' "unknown bodhi update type" >> RP.pfail+ _ -> error "unknown bodhi update type" >> RP.pfail data UpdateSeverity = SeverityLow | SeverityMedium | SeverityHigh | SeverityUrgent |@@ -98,7 +99,7 @@ "medium" -> RP.lift (R.string s) >> return SeverityMedium "high" -> RP.lift (R.string s) >> return SeverityHigh "urgent" -> RP.lift (R.string s) >> return SeverityUrgent- _ -> error' "unknown bodhi update severity" >> RP.pfail+ _ -> error "unknown bodhi update severity" >> RP.pfail bodhiTestingRepoTag :: Branch -> IO (Maybe String) bodhiTestingRepoTag Rawhide = return Nothing@@ -112,39 +113,41 @@ -- FIXME support --no-close-bugs -- push comma separated list of builds for a package to bodhi-bodhiUpdate :: Bool -> (Maybe UpdateType, UpdateSeverity) -> Maybe BugId- -> Maybe UpdateNotes -> Maybe Branch -> FilePath -> String -> IO ()-bodhiUpdate _ _ _ _ _ _ [] = putStrLn "no package to push"-bodhiUpdate dryrun (mupdate,severity) mreview mnotes mrbr spec nvrs = do+bodhiUpdate :: Bool -> Bool -> (Maybe UpdateType, UpdateSeverity)+ -> Maybe BugId -> Maybe UpdateNotes -> Maybe Branch -> FilePath+ -> String -> IO ()+bodhiUpdate _ _ _ _ _ _ _ [] = putStrLn "no package to push"+bodhiUpdate dryrun reattempt (mupdate,severity) mreview mnotes mrbr spec nvrs = do case mupdate of Nothing -> return () Just updateType -> unless dryrun $ do- updateDone <- do+ (updateDone,mnotes') <- do mtemplate <- maybeTemplate updateType case mtemplate of Just file -> do -- FIXME use cmdLog_ to debug, but notes are not quoted -- FIXME does not fail cmd_ "bodhi" ["updates", "new", "--file", file, nvrs]- return True+ return (True,mnotes) Nothing -> do whenJust mrbr $ gitSwitchBranch . RelBranch -- FIXME also query for open existing bugs- changelog <- if isJust mreview- then getSummaryURL spec- else- case mnotes of- Just NotesChangelog ->- -- FIXME all changes since last update!- cleanChangelog True spec- Just (NotesText notes) ->- return notes- Nothing ->- -- FIXME list open bugs- changeLogPrompt ChangeBodhi spec+ changelog <-+ if isJust mreview && not reattempt+ then getSummaryURL spec+ else+ case mnotes of+ Just NotesChangelog ->+ -- FIXME all changes since last update!+ cleanChangelog True spec+ Just (NotesText notes) ->+ return notes+ Nothing ->+ -- FIXME list open bugs+ changeLogPrompt ChangeBodhi spec if trim (lower changelog) `elem` ["no","n"]- then return False+ then return (False, mnotes) else do when (length changelog > 10000) $ putStrLn "Bodhi only accepts up to 10000 chars: will be truncated"@@ -162,8 +165,8 @@ -- FIXME returns json error string if it exists: -- {"status": "error", "errors": [{"location": "body", "name": "builds", "description": "Update for ghc9.2-9.2.5-14.fc36 already exists"}]} -- ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))- cmd_ "bodhi" $ ["updates", "new", "--type", if isJust mreview then "newpackage" else show updateType, "--severity", show severity, "--request", "testing", "--notes", take 10000 changelog, "--autokarma", "--autotime", "--close-bugs"] ++ bugs ++ [nvrs]- return True+ retry 3 $ cmd_ "bodhi" $ ["updates", "new", "--type", if isJust mreview then "newpackage" else show updateType, "--severity", show severity, "--request", "testing", "--notes", take 10000 changelog, "--autokarma", "--autotime", "--close-bugs"] ++ bugs ++ [nvrs]+ return (True, Just $ NotesText changelog) when updateDone $ do -- FIXME avoid this if we know the update URLs (split update does not seem to return URLs) eupdates <- bodhiUpdatesEither [makeItem "display_user" "0", makeItem "builds" nvrs]@@ -174,7 +177,7 @@ then do putStrLn $ "bodhi submission failed for" +-+ nvrs promptEnter "Press Enter to resubmit to Bodhi"- bodhiUpdate dryrun (mupdate,severity) mreview mnotes mrbr spec nvrs+ bodhiUpdate dryrun True (mupdate,severity) mreview mnotes' mrbr spec nvrs else forM_ updates $ \update -> case lookupKey "url" update of
src/Branches.hs view
@@ -124,7 +124,7 @@ pagurePkgBranches pkg = do let project = "rpms/" ++ pkg res <- pagureListGitBranches srcfpo project- return $ either (error' . include project) id res+ either (error' . include project) return res where include p e = e ++ ":" +-+ p @@ -158,7 +158,7 @@ onlyRelBranch :: AnyBranch -> Branch onlyRelBranch (RelBranch br) = br-onlyRelBranch (OtherBranch br) = error' $ "Non-release branch not allowed:" +-+ br+onlyRelBranch (OtherBranch br) = error $ "Non-release branch not allowed:" +-+ br systemBranch :: IO Branch systemBranch = do
src/Bugzilla.hs view
@@ -149,10 +149,10 @@ bzBugMaybe :: BugzillaSession -> SearchExpression -> IO (Maybe Bug) bzBugMaybe session query = do bugs <- searchBugs session query- return $ case bugs of- [] -> Nothing- [bug] -> Just bug- _ -> error' "more that one bug found"+ case bugs of+ [] -> return Nothing+ [bug] -> return $ Just bug+ _ -> error' "more that one bug found" bzReviewAnon :: IO (Maybe BugId) bzReviewAnon = do@@ -364,7 +364,7 @@ reviewBugToPackage :: Bug -> String reviewBugToPackage bug = case (dropOne ["Request:"] . dropOne ["Review", "Re-Review", "Rename"] . words . T.unpack . bugSummary) bug of- [] -> error' $ "failed to determine review package for" +-+ show (bugId bug)+ [] -> error $ "failed to determine review package for" +-+ show (bugId bug) (p:_) -> p where dropOne _ [] = []@@ -373,10 +373,9 @@ readIniConfig :: FilePath -> IniParser a -> (a -> b) -> IO b readIniConfig inifile iniparser fn = do ini <- T.readFile inifile- return $- case parseIniFile ini iniparser of- Left err -> error' $ err ++ "\nin" +-+ inifile- Right res -> fn res+ case parseIniFile ini iniparser of+ Left err -> error' $ err ++ "\nin" +-+ inifile+ Right res -> return $ fn res sortBugsByID :: [Bug] -> [Bug] sortBugsByID = sortOn bugId
src/Cmd/BranchLogs.hs view
@@ -142,7 +142,7 @@ case mbrs of Nothing -> Nothing Just brs -> Just $ LogCommit h (NE.sort brs) s t- _ -> error' $ "malformed log line:" +-+ cs+ _ -> error $ "malformed log line:" +-+ cs hasBranch :: BranchRemote -> Branch -> Bool hasBranch (BR _ b1) b2 = b1 == b2
src/Cmd/Build.hs view
@@ -19,6 +19,7 @@ import Git import Koji import Package+import Pagure (pagurePRs) import RpmBuild (checkSourcesMatch) import Types @@ -107,6 +108,7 @@ checkForSpecFile spec checkSourcesMatch pkg (RelBranch br) spec -- FIXME: check for %macros in %changelog+ pagurePRs $ unPackage pkg unpushed <- gitOneLineLog $ "origin/" ++ showBranch br ++ "..HEAD" putNewLn let msidetagTarget = buildoptSidetagTarget opts@@ -141,7 +143,7 @@ if b == Fedora rawhide then Rawhide else b- Nothing -> error' $ "unknown branch for target" +-+ target+ Nothing -> error $ "unknown branch for target" +-+ target buildRun spec nvr merged mpush unpushed target msidetagTarget moverride = do let mwaitrepo = buildoptWaitrepo opts@@ -161,7 +163,7 @@ then putStrLn "update exists" else do mbug <- bzReviewAnon- bodhiUpdate dryrun (buildoptUpdate opts) mbug (buildoptNotes opts) (Just br) spec $ showNVR nvr+ bodhiUpdate dryrun False (buildoptUpdate opts) mbug (buildoptNotes opts) (Just br) spec $ showNVR nvr whenJust moverride $ \days -> do tags <- maybeTimeout 30 $ kojiNVRTags nvr unless (any (`elem` tags) [showBranch br, showBranch br ++ "-updates", showBranch br ++ "-override"]) $@@ -257,7 +259,7 @@ whenJust (fmap fst mBugSess) $ \bid -> putStr "review bug: " >> putBugId bid -- FIXME diff previous changelog?- bodhiUpdate dryrun (buildoptUpdate opts) (fmap fst mBugSess) (buildoptNotes opts) (Just br) spec $ showNVR nvr+ bodhiUpdate dryrun False (buildoptUpdate opts) (fmap fst mBugSess) (buildoptNotes opts) (Just br) spec $ showNVR nvr -- FIXME prompt for override note whenJust moverride $ \days -> bodhiCreateOverride dryrun (Just days) nvr
src/Cmd/Bump.hs view
@@ -97,6 +97,7 @@ then putStrLn $ color Green "already bumped" else do git_ "log" ["origin..HEAD", "--pretty=oneline"]+ -- FIXME improve default behavior to not worry about clog vs cmsg let clog = case mclog of Just cl -> cl
src/Cmd/CompareTarballs.hs view
@@ -1,48 +1,101 @@ module Cmd.CompareTarballs (- compareTarballsCmd+ compareTarballsCmd,+ Src(..),+ readSrc ) where -import Safe (tailSafe)-import SimpleCmd+import Data.Char (isDigit)+import Safe (headMay, tailSafe) import SimpleCmd.Git import System.Console.Pretty (supportsPretty) import System.IO.Extra (withTempDir) import Common import Common.System-import Package (findSpecfile, pkgVersion)+import Package (findSpecfile, isArchiveFile, pkgVersion, sourceFieldFile) import Patch (simplifyMinimalDiff) -compareTarballsCmd :: Maybe Natural -> Maybe String -> Maybe String -> IO ()-compareTarballsCmd mmaxlen (Just nv1) (Just nv2) = diffTarballs mmaxlen nv1 nv2-compareTarballsCmd mmaxlen (Just nv) Nothing = do+data Src = SrcVer String | SrcNameVer String | SrcArchive String++readSrc :: String -> Src+readSrc s =+ if isArchiveFile s+ then SrcArchive s+ else+ case headMay s of+ Just h | isDigit h -> SrcVer s+ _ -> SrcNameVer s++srcToArchive :: FilePath -> Src -> IO FilePath+srcToArchive spec src =+ case src of+ SrcArchive f -> return f+ SrcNameVer nv -> do+ let (n,v) = breakEnd (== '-') $ takeFileName nv+ cur <- pkgVersion spec+ sources <- filter isArchiveFile . map sourceFieldFile <$>+ cmdLines "spectool" ["-S", spec]+ case filter (n `isPrefixOf`) $ map takeFileName sources of+ [] -> error' $ "unknown source" +-+ n+ [f] -> return $ replace cur v f+ _ -> do+ let f = nv <.> "tar.gz"+ putStrLn $ "trying with" +-+ f+ return f+ SrcVer v -> do+ sources <- filter isArchiveFile . map sourceFieldFile <$>+ cmdLines "spectool" ["-S", spec]+ case sources of+ [] -> error' $ "unknown source for" +-+ v+ [f] -> do+ cur <- pkgVersion spec+ return $ replace cur v $ takeFileName f+ _ -> do+ warning "multiple source files"+ pkg <- getDirectoryName+ putStrLn $ "trying with" +-+ pkg+ return $ pkg ++ '-' : v <.> "tar.gz"++compareTarballsCmd :: Maybe Natural -> Maybe Src -> Maybe Src -> IO ()+compareTarballsCmd mmaxlen (Just src1) (Just src2) = do spec <- findSpecfile+ nv1 <- srcToArchive spec src1+ nv2 <- srcToArchive spec src2+ diffTarballs spec mmaxlen nv1 nv2+compareTarballsCmd mmaxlen (Just src) Nothing = do+ spec <- findSpecfile+ nv <- srcToArchive spec src cur <- pkgVersion spec- if nv == cur- then error' "same source version!"- else diffTarballs mmaxlen nv cur+ nv' <- srcToArchive spec $ SrcVer cur+ if nv == nv'+ then error' "same source/version!"+ else diffTarballs spec mmaxlen nv nv' compareTarballsCmd _ Nothing (Just _) = error' "impossible happened: only second arg" compareTarballsCmd mmaxlen Nothing Nothing = do+ spec <- findSpecfile let sourcesfile = "sources" havesrc <- doesFileExist sourcesfile if havesrc then do -- was "origin"- diff <- git "diff" ["-U0", "--cached", sourcesfile]+ diff <- do+ ds <- git "diff" ["-U0", "--cached", sourcesfile]+ if null ds+ then git "diff" ["-U0", "HEAD^!", sourcesfile]+ else return ds case lines diff of [] -> error' $ "no uncommitted version changes in" +-+ show sourcesfile ls -> -- FIXME cannot handle majorversion macros etc (eg lean4) case simplifyMinimalDiff ls of- [s1,s2] -> diffTarballs mmaxlen (sourcesFilename s1) (sourcesFilename s2)+ [s1@('-':_),s2@('+':_)] -> diffTarballs spec mmaxlen (sourcesFilename s1) (sourcesFilename s2) ss -> do putNewLn error' $ unlines $ ("More than one source archive changed in" +-+ show sourcesfile ++ ":") : map sourcesFilename ss ++ ["", "Run: fbrnch compare-tarballs <source1> <source2>"] else do- spec <- findSpecfile diff <- git "diff" ["-U0", spec] case lines diff of [] -> error' $ "no uncommitted version changes in" +-+ show spec@@ -53,27 +106,28 @@ let newtar = name ++ '-' : specVersion v2 <.> "tar.gz" exists <- doesFileExist newtar unless exists $ cmd_ "spectool" ["-g", "-S", spec]- diffTarballs mmaxlen (name ++ '-' : specVersion v1 <.> "tar.gz") newtar+ diffTarballs spec mmaxlen (name ++ '-' : specVersion v1 <.> "tar.gz") newtar _ -> error' $ "could not determine changed versions in" +-+ show sourcesfile where sourcesFilename s = -- "+SHA512 (filestore-0.6.5.1.tar.gz) = 9eec4d23737bcdfc3d0ded..." case words s of (_:"SHA512") : ('(':fp) : "=" : _hash -> init fp- _ -> error' $ "Failed to parse:" +-+ s+ _ -> error $ "Failed to parse:" +-+ s specVersion s = -- "-Version: 0.1.50.1" case words s of (_:"Version:") : [ver] -> ver- _ -> error' $ "Failed to parse:" +-+ s+ _ -> error $ "Failed to parse:" +-+ s -- FIXME --reverse diff-diffTarballs :: Maybe Natural -> String -> String -> IO ()-diffTarballs mmaxlen src1 src2 = do+diffTarballs :: FilePath -> Maybe Natural -> String -> String -> IO ()+diffTarballs spec mmaxlen src1 src2 = do cwd <- getCurrentDirectory withTempDir $ \tmp -> withCurrentDirectory tmp $ do+ -- print (src1,src2) adir <- getDirTop "a" cwd src1 bdir <- getDirTop "b" cwd src2 -- createDirectory "b"@@ -84,18 +138,58 @@ pipe_ -- FIXME add option to filter out certain files ("diff", ["--color=always" | color] ++ ["-u", "-r", "-w", "a" </> adir, "b" </> bdir])+ -- filter out very long lines (often machine generated/formatted) ("grep", ["-v", ".\\{" ++ maybe "200" show mmaxlen ++ ",\\}"]) where getDirTop :: FilePath -> FilePath -> FilePath -> IO FilePath getDirTop subdir topdir src = do createDirectory subdir withCurrentDirectory subdir $ do- exists <- doesFileExist $ topdir </> src- if exists- then do- cmd_ "tar" ["xf", topdir </> src]- ls <- listDirectory "."- case ls of- [n] -> return n- _ -> error' $ "more than one top-level dir in" +-+ src- else error' $ src +-+ "not found"+ let archive = topdir </> src+ unlessM (doesFileExist archive) $ do+ downloadMissingArchive topdir spec archive src+ unlessM (doesFileExist archive) $+ error' $ src +-+ "not found (Source URL may not use %{version})"+ cmd_ "tar" ["xf", archive]+ ls <- listDirectory "."+ case ls of+ [n] -> return n+ _ -> error' $ "more than one top-level dir in" +-+ src++-- Derive version from archive name (Name-Version.tar.gz) or bare version arg+versionFromSrc :: FilePath -> FilePath -> String+versionFromSrc spec src =+ let name = takeBaseName spec+ base = dropArchiveExt $ takeFileName src+ prefix = name ++ "-"+ in if prefix `isPrefixOf` base+ then drop (length prefix) base+ else src++dropArchiveExt :: FilePath -> FilePath+dropArchiveExt f+ | ".tar." `isInfixOf` f = dropExtension $ dropExtension f+ -- note also checks .tar. and .gpg+ | isArchiveFile f = dropExtension f+ | otherwise = f++-- spectool --define version is ignored (Version: wins), so rewrite the+-- expanded Source URL by substituting the current version with the needed one.+downloadMissingArchive :: FilePath -> FilePath -> FilePath -> FilePath -> IO ()+downloadMissingArchive topdir spec archive src = do+ let ver = versionFromSrc spec src+ curver <- pkgVersion $ topdir </> spec+ if ver == curver+ then cmd_ "spectool" ["-g", "-S", "-C", topdir, topdir </> spec]+ else do+ fields <- cmdLines "spectool" ["-S", topdir </> spec]+ let urls = map (last . words) fields+ currentName = replace ver curver $ takeFileName src+ case filter ((== currentName) . takeFileName) urls of+ [] ->+ error' $ "could not find Source URL for" +-+ currentName+ (url:_) ->+ let oldurl = replace curver ver url+ in cmd_ "curl"+ ["--fail", "--show-error", "--location",+ "--output", archive, oldurl]
src/Cmd/Copr.hs view
@@ -27,7 +27,7 @@ import Distribution.Fedora.Branch (getActiveBranches, getActiveBranched) import Network.HTTP.Query (lookupKey, lookupKey') import Network.HTTP.Simple as HTTP-import Safe (headDef, lastMay)+import Safe (lastMay) import System.Environment.XDG.BaseDir (getUserConfigDir) import System.Time.Extra (sleep) import Web.Fedora.Copr (coprChroots, fedoraCopr)@@ -56,13 +56,13 @@ case dropPrefix "fedora-" release of "rawhide" -> Rawhide n | all isDigit n -> Fedora (read n)- | otherwise -> error' $ "unknown fedora release:" +-+ release+ | otherwise -> error $ "unknown fedora release:" +-+ release | "epel-" `isPrefixOf` release = let next = "-next" `isSuffixOf` release in case dropSuffix "-next" (dropPrefix "epel-" release) of n | all isDigit n -> (if next then EPELNext else EPEL) $ read n- | otherwise -> error' $ "unknown epel release:" +-+ release- | otherwise = error' $ "unknown release:" +-+ release+ | otherwise -> error $ "unknown epel release:" +-+ release+ | otherwise = error $ "unknown release:" +-+ release branchToRelease :: Branch -> String branchToRelease Rawhide = "fedora-rawhide"@@ -79,7 +79,7 @@ readChroot :: String -> Chroot readChroot ch = case stripInfixEnd "-" ch of- Nothing -> error' $ "invalid chroot:" +-+ ch+ Nothing -> error $ "invalid chroot:" +-+ ch Just (b,a) -> Chroot (releaseToBranch b) (readArch a) showChroot :: Chroot -> String@@ -100,7 +100,7 @@ readArch "aarch64" = AARCH64 readArch "ppc64le" = PPC64LE readArch "s390x" = S390X-readArch a = error' $ "unknown arch:" +-+ a+readArch a = error $ "unknown arch:" +-+ a showArch :: Arch -> String showArch X86_64 = "x86_64"@@ -115,6 +115,7 @@ | CoprNew | CoprFailures (Maybe String) +-- FIXME directory config to exclude "branch", e.g. epel9? -- FIXME fbrnch: unknown release: centos-stream-9 -- FIXME take ExclusiveArch/ExcludeArch into account -- FIXME -1 for only first unbuilt chroot@@ -125,16 +126,17 @@ -- FIXME interact with copr dist-git -- FIXME parallel copr builds -- FIXME time builds?-coprCmd :: Bool -> CoprMode -> Bool -> Maybe BuildBy -> Maybe Archs -> String- -> (BranchesReq,[String]) -> IO ()-coprCmd dryrun mode force mbuildBy marchs copr (breq, pkgs) = do+-- FIXME --by-release does not work for multiple packages+coprCmd :: Bool -> Bool -> CoprMode -> Bool -> Maybe BuildBy -> Maybe Archs+ -> String -> (BranchesReq,[String]) -> IO ()+coprCmd dryrun debug mode force mbuildBy marchs copr (breq, pkgs) = do -- FIXME disallow user/project for build/new? (user,project) <- coprUserProject copr let buildBy = fromMaybe ValidateByRelease mbuildBy case mode of ListChroots -> coprGetChroots user project >>= mapM_ (putStrLn . showChroot) CoprMonitor mneedle nameonly -> coprMonitorPackages user project >>= mapM_ (printPkgRes mneedle nameonly)- CoprNew -> coprNewProject dryrun project marchs breq pkgs+ CoprNew -> coprNewProject dryrun debug project marchs breq pkgs CoprFailures mgrep -> coprMonitorPackages user project >>= mapM_ (printFailures user project mgrep) CoprBuild -> do chroots <- coprGetChroots user project@@ -184,7 +186,8 @@ else return spec -- hack to avoid generating srpm for dryrun verrel <- showVerRel . nvrVerRel <$> pkgNameVerRelNodist spec actualpkg <- cmd "rpmspec" ["-q", "--srpm", "--qf", "%{name}", spec]- builtChroots <- existingChrootBuilds dryrun user project (Package actualpkg) verrel chroots+ builtChroots <- existingChrootBuilds dryrun debug user project (Package actualpkg) verrel chroots+ when debug $ mapM_ (putStrLn . renderCoprTask) builtChroots let finalChroots = chroots \\ if force then [] else map taskChroot builtChroots case finalChroots of [] -> putStrLn $ actualpkg ++ '-' : verrel +-+ "built"@@ -254,7 +257,7 @@ else do ini <- T.readFile inifile let config = parseIniFile ini iniparser- return $ either error' record config+ either error' (return . record) config -- from copr/frontend/coprs_frontend/coprs/logic/builds_logic.py -- FIXME after adding to copr-api@@ -266,15 +269,19 @@ -- coprEndedStates = -- ["canceled", "failed", "skipped", "succeeded"] +coprNotOkStates :: [String]+coprNotOkStates = ["canceled", "failed", "skipped"]+ -- FIXME restrict to requested chroots?-existingChrootBuilds :: Bool -> String -> String -> Package -> String+existingChrootBuilds :: Bool -> Bool -> String -> String -> Package -> String -> [Chroot] -> IO [CoprTask]-existingChrootBuilds dryrun user project actualpkg verrel chroots = do+existingChrootBuilds dryrun debug user project actualpkg verrel chroots = do monitorPkgs <- coprMonitorPackages user project let pkgmonitor = fromMaybe [] $ lookup actualpkg monitorPkgs let buildingChroots = filterTasks verrel (`elem` coprProcessingStates) pkgmonitor builds = filterTasks verrel (`notElem` ["failed","skipped","canceled"]) pkgmonitor+ when debug $ mapM_ (putStrLn . renderCoprTask) buildingChroots if null buildingChroots then return builds else do@@ -293,7 +300,7 @@ coprBuild :: Bool -> String -> String -> FilePath -> FilePath -> [Chroot] -> IO () coprBuild _ _ _ _ _ [] = error' "No chroots chosen"-coprBuild dryrun user project srpm spec chroots = do+coprBuild dryrun user project srpm spec chroots@(c:_) = do let chrootargs = mconcat [["-r", showChroot bldrt] | bldrt <- chroots] buildargs = ["build", "--nowait"] ++ chrootargs ++ [project, srpm] putNewLn@@ -311,7 +318,7 @@ actualpkg <- cmd "rpmspec" ["-q", "--srpm", "--qf", "%{name}", spec] -- FIXME which chroot? -- FIXME print buildlog size- error' $ "https://download.copr.fedorainfracloud.org/results" +/+ user +/+ project +/+ showChroot (headDef (error' " nochroot!") chroots) +/+ zeroBuildId bid ++ "-" ++ actualpkg +/+ "builder-live.log.gz"+ error' $ "https://download.copr.fedorainfracloud.org/results" +/+ user +/+ project +/+ showChroot c +/+ zeroBuildId bid ++ "-" ++ actualpkg +/+ "builder-live.log.gz" zeroBuildId :: Int -> String zeroBuildId bid =@@ -323,7 +330,7 @@ coprWatchBuild :: Maybe String -> Either CoprTask Int -> IO Bool coprWatchBuild mstate ebuild = do let bid = either taskBuild id ebuild- res <- retry 2 $ coprGetBuild fedoraCopr bid+ res <- retry 3 $ coprGetBuild fedoraCopr bid case lookupKey "state" res of Just state -> if mstate == Just state@@ -420,8 +427,8 @@ $ filterResults cs renderCoprTask :: CoprTask -> String-renderCoprTask (CoprTask chr build status version) =- version +-+ status +-+ "on" +-+ showChroot chr +-+ show build+renderCoprTask (CoprTask chr build status verrel) =+ verrel +-+ status +-+ "on" +-+ showChroot chr +-+ show build printCoprTask :: CoprTask -> IO () printCoprTask =@@ -469,7 +476,7 @@ putStrLn $ '\n' : logurl ++ "\n" where match :: String -> String -> Bool- match "" _ = error' "empty grep string not allowed"+ match "" _ = error "empty grep string not allowed" match _ "" = False match ('^':needle) ls = if lastMay needle == Just '$'@@ -485,12 +492,16 @@ coprWaitPackage build = do case buildResult of Nothing -> error' "unknown source_package"- Just (_, "failed", _) -> return ()- Just (_, _, Just _pkg) -> return ()- Just (bid, _, Nothing) -> do- sleep 5- print bid- coprGetBuild fedoraCopr bid >>= coprWaitPackage+ Just (bid, state, mpkg) ->+ if state `elem` coprNotOkStates+ then return ()+ else+ case mpkg of+ Just _ -> return ()+ Nothing -> do+ print bid+ sleep 10+ coprGetBuild fedoraCopr bid >>= coprWaitPackage where buildResult = do bid <- lookupKey "id" build@@ -499,9 +510,9 @@ let mname = lookupKey "name" source return (bid :: Int, state :: String, mname :: Maybe String) -coprNewProject :: Bool -> String -> Maybe Archs -> BranchesReq -> [String]- -> IO ()-coprNewProject dryrun project marchs breq pkgs = do+coprNewProject :: Bool -> Bool -> String -> Maybe Archs -> BranchesReq+ -> [String] -> IO ()+coprNewProject dryrun debug project marchs breq pkgs = do branches <- listOfBranches False False breq let archs = case marchs of@@ -511,4 +522,4 @@ let chroots = [ Chroot b a | b <- branches, a <- archs] (if dryrun then cmdN else cmd_) "copr" $ "create" : concatMap (\ch -> ["--chroot", showChroot ch]) chroots ++ [project] unless (null pkgs) $- coprCmd False CoprBuild False Nothing Nothing project (breq, pkgs)+ coprCmd False debug CoprBuild False Nothing Nothing project (breq, pkgs)
src/Cmd/CreateReview.hs view
@@ -5,13 +5,14 @@ import Data.Char (isAscii) import Fedora.Krb (maybeFasIdFromKrb)-import SimpleCmd (cmd, error')+import SimpleCmd (cmd) import SimplePrompt (promptEnter) import System.Directory (doesFileExist) import Branches import Bugzilla import Common+import Common.System (error') import Package import PkgReview import RpmBuild
src/Cmd/FTBFS.hs view
@@ -44,7 +44,7 @@ bugComponents bug = case bugComponent bug of [component] -> T.unpack component- _ -> error' $ "multiple components!\n" ++ show bug+ _ -> error $ "multiple components!\n" ++ show bug query = ftbfsFedoraBugs .&&.
src/Cmd/Fetch.hs view
@@ -4,7 +4,7 @@ where import Branches-import Common ((+-+))+import Common (when, (+-+)) import Common.System (error') import Git import Package@@ -23,7 +23,7 @@ fetchPkgLenient pkg _br = do haveGit <- isPkgGitRepo if haveGit- then gitFetchSilent False+ then when lenient $ gitFetchSilent False else if lenient then putStrLn $ "ignoring" +-+ unPackage pkg else error' "not a dist-git dir"
src/Cmd/Import.hs view
@@ -7,10 +7,7 @@ ) where -import Common-import Common.System-import qualified Common.Text as T-+import Control.Exception.Extra (retry) import Fedora.Krb (krbTicket) import Network.URI import SimplePrompt (promptEnter)@@ -18,7 +15,10 @@ import Branches import Bugzilla-import Cmd.RequestBranch (requestPkgBranches, waitForKojiPkgBranch)+import Cmd.RequestBranch (requestPkgBranches, waitForKojiPkgBranches)+import Common+import Common.System+import qualified Common.Text as T import Git import Koji import ListReviews@@ -53,7 +53,7 @@ -- FIXME get session from importPkgs (bid,session) <- approvedReviewBugIdSession pkg putBugId bid- srpmfile <- downloadReviewSRPM showbug False True pkg bid session+ srpmfile <- downloadReviewSRPM showbug False True False pkg bid session putNewLn promptEnter $ "Press Enter to import" +-+ srpmfile krbTicket@@ -69,11 +69,12 @@ kojiBuildBranch "rawhide" (Package pkg) Nothing ["--fail-fast"] putBugBuild False session bid nvr existing <- fedoraBranchesNoRawhide (localBranches False)- when (null existing) $ do- brs <- getRequestedBranches [] breq- unless (reporequest || null brs) $- requestPkgBranches False False mock (Branches brs) (Package pkg) >>=- mapM_ (waitForKojiPkgBranch False (Package pkg))+ when (null existing) $+ unless reporequest $ do+ brs <- getRequestedBranches [] breq+ unless (null brs) $+ requestPkgBranches False False False mock (Branches brs) (Package pkg) >>=+ waitForKojiPkgBranches False (Package pkg) when (pkg /= takeFileName dir) $ setCurrentDirectory dir @@ -92,9 +93,9 @@ "no" -> Just (Just False) _ -> Nothing -downloadReviewSRPM :: Bool -> Bool -> Bool -> String -> Int -> BugzillaSession- -> IO FilePath-downloadReviewSRPM showbug getspec prompt pkg bid session = do+downloadReviewSRPM :: Bool -> Bool -> Bool -> Bool -> String -> Int+ -> BugzillaSession -> IO FilePath+downloadReviewSRPM showbug getspec prompt update pkg bid session = do comments <- getComments session bid when showbug $ do putNewLn@@ -136,19 +137,18 @@ let srpmfile = takeFileName srpmurl -- FIXME if havesrpm then print local filename havesrpm <- doesFileExist srpmfile- if havesrpm- then putStrLn $ srpmfile +-+ "already exists"- else+ when havesrpm $+ putStrLn $ srpmfile +-+ "already exists"+ when (not havesrpm || update) $ -- was "--silent"- cmd_ "curl" ["--show-error", "--remote-name", srpmurl]+ retry 3 $ cmd_ "curl" ["--show-error", "--remote-name", srpmurl] return srpmfile srpmurls -> error' $ "multiple srpm urls:" +-+ unwords srpmurls downloadSpec :: [Comment] -> IO () downloadSpec comments = do- let specs = map (T.replace "/reviews//" "/reviews/") $ concatMap findSpecs comments+ let specs = map (T.replace "/reviews//" "/reviews/") . nub $ concatMap findSpecs comments mapM_ T.putStrLn specs- unless (null specs) putNewLn case (filter ((pkg <.> "spec") `isSuffixOf`) . words . T.unpack . last) specs of [] -> error' "no spec filename found" specfiles ->@@ -156,12 +156,9 @@ [] -> error "no valid spec urls found" [specurl] -> do let specfile = upstreamDir </> takeFileName specurl- havespec <- doesFileExist specfile- if havespec- then putStrLn $ specfile +-+ "already exists"- else- cmd_ "curl" ["--silent", "--show-error", "--create-dirs", "--output", specfile, specurl]+ retry 3 $ cmd_ "curl" ["--silent", "--show-error", "--create-dirs", "--output", specfile, specurl] specurls -> error' $ "multiple spec urls:" +-+ unwords specurls+ unless (null specs) putNewLn upstreamDir :: FilePath upstreamDir = "UPSTREAM"
src/Cmd/Install.hs view
@@ -30,15 +30,17 @@ -- FIXME add --debug or respect --verbose for dnf commands -- FIXME handle subpackage renames (eg ghc-rpm-macros-no-prof to ghc-rpm-macros-quick) -- FIXME allow building an srpm-installCmd :: Bool -> Bool -> Maybe Branch -> Maybe Natural+installCmd :: Bool -> Bool -> Bool -> Maybe Branch -> Maybe Natural -> Maybe ForceShort -> [BCond] -> Maybe PkgMgr -> Bool -> Bool -> Bool -> Bool -> Yes -> Select -> Maybe ExistingStrategy -> (Maybe Branch,[String]) -> IO ()-installCmd quiet recurse mfrom mjobs mforceshort bconds mmgr reinstall allowerasing nobuild nobuilddeps yes select mexisting (mbr, pkgs) = do+installCmd dryrun quiet recurse mfrom mjobs mforceshort bconds mmgr reinstall allowerasing nobuild nobuilddeps yes select mexisting (mbr, pkgs) = do when (recurse && isShortCircuit mforceshort) $ error' "cannot use --recurse and --shortcircuit" withPackagesMaybeBranch (boolHeader (recurse || length pkgs > 1)) True Nothing installPkg (mbr, filter (/= ":") pkgs) where+ yesDry = if dryrun then No else yes+ installPkg :: Package -> AnyBranch -> IO () installPkg pkg br = do whenJust mbr $ gitSwitchBranch . RelBranch@@ -79,15 +81,15 @@ mpkgdir <- lookForPkgDir rbr ".." dep case mpkgdir of Nothing -> putStrLn $ dep +-+ "not known"- Just pkgdir -> installCmd quiet recurse mfrom mjobs mforceshort bconds mmgr reinstall allowerasing nobuild nobuilddeps yes select mexisting (mbr, [pkgdir]) >> putNewLn+ Just pkgdir -> installCmd dryrun quiet recurse mfrom mjobs mforceshort bconds mmgr reinstall allowerasing nobuild nobuilddeps yesDry select mexisting (mbr, [pkgdir]) >> putNewLn -- FIXME option to enable/disable installing missing deps -- FIXME --skip-missing-deps or prompt- else installDeps True spec+ else installDeps dryrun True spec -- FIXME unused _wasbuilt <- if nobuild then return True- else buildRPMs quiet False False mjobs mforceshort bconds rpms br spec+ else buildRPMs dryrun quiet False False mjobs mforceshort bconds rpms br spec unless (isShortCircuit mforceshort) $ do -- paths lost here let nvras = rpmsToNVRAs rpms@@ -99,7 +101,7 @@ -- FIXME dryrun and debug -- FIXME return Bool? withCurrentDirectory rpmdir $- installRPMsAllowErasing False False mmgr allowerasing yes $ groupOnArch "" decided+ installRPMsAllowErasing False False mmgr allowerasing yesDry $ groupOnArch "" decided lookForPkgDir :: Branch -> FilePath -> String -> IO (Maybe FilePath) lookForPkgDir rbr topdir p = do
src/Cmd/ListPackages.hs view
@@ -73,7 +73,7 @@ else return True if ok then do- pages <- queryPagureCountPaged srcfpo False path (mkParams mpattern) ("pagination", "page")+ pages <- queryPagurePaged srcfpo path (mkParams mpattern) ("pagination", "page") return $ concatMap (map (lookupKey' "name")) $ mapMaybe (lookupKey "projects") pages@@ -95,5 +95,5 @@ listPackages :: Bool -> Maybe Packager -> [String] -> IO [String] listPackages force mpackager pkgs =- either (error' "impossible happened") id <$>- countListPackages force False mpackager pkgs+ countListPackages force False mpackager pkgs >>=+ either (const $ error' "impossible happened") return
src/Cmd/Local.hs view
@@ -26,9 +26,9 @@ import Package import RpmBuild -localCmd :: Bool -> Bool -> Bool -> Maybe Natural -> Maybe ForceShort+localCmd :: Bool -> Bool -> Bool -> Bool -> Maybe Natural -> Maybe ForceShort -> [BCond] -> (BranchesReq, [String]) -> IO ()-localCmd quiet debug allowhead mjobs mforceshort bconds (breq,pkgs) =+localCmd dryrun quiet debug allowhead mjobs mforceshort bconds (breq,pkgs) = if allowhead then if breq == Branches [] then withPackagesMaybeBranch HeaderNone False dirtyGitHEAD localBuildPkgNoBranch (Nothing, pkgs)@@ -43,21 +43,21 @@ then return [] else builtRpms br spec -- FIXME backup BUILD tree to .prev- void $ buildRPMs quiet debug True mjobs mforceshort bconds rpms br spec+ void $ buildRPMs dryrun quiet debug True mjobs mforceshort bconds rpms br spec -- FIXME mark BUILD dir complete localBuildPkgNoBranch :: Package -> AnyBranch -> IO () localBuildPkgNoBranch _pkg _ = do spec <- findSpecfile- void $ buildRPMsNoBranch quiet debug True mjobs mforceshort bconds spec+ void $ buildRPMsNoBranch dryrun quiet debug True mjobs mforceshort bconds spec -installDepsCmd :: (Maybe Branch,[String]) -> IO ()-installDepsCmd =+installDepsCmd :: Bool -> (Maybe Branch,[String]) -> IO ()+installDepsCmd dryrun = withPackagesMaybeBranch HeaderNone False Nothing installDepsPkg where installDepsPkg :: Package -> AnyBranch -> IO () installDepsPkg pkg br =- localBranchSpecFile pkg br >>= installDeps False+ localBranchSpecFile pkg br >>= installDeps dryrun False srpmCmd :: Bool -> (Maybe Branch,[String]) -> IO () srpmCmd force =
src/Cmd/Mock.hs view
@@ -31,10 +31,10 @@ -- FIXME add repo/copr for build -- FIXME handle non-release branches (on-branch works) -- FIXME option for --shell without rebuild-mockCmd :: Bool -> Maybe NoClean -> Bool -> Maybe String -> Bool -> Bool+mockCmd :: Bool -> Bool -> Maybe NoClean -> Bool -> Maybe String -> Bool -> Bool -> Maybe MockMode -> Maybe Branch -> Maybe String -> (BranchesReq, [String]) -> IO ()-mockCmd dryrun mnoclean noPull mconfigOptions network reinstall mockmode mroot march (breq, ps) = do+mockCmd dryrun nobootstrap mnoclean noPull mconfigOptions network reinstall mockmode mroot march (breq, ps) = do pkggit <- isPkgGitRepo branches <- case breq of@@ -55,13 +55,14 @@ putNewLn -- FIXME? is it better just to fail asking for target branch? rootBr <- maybe (if pkggit then getReleaseBranch else return br) return mroot- let resultdir =- case srpms of- [] -> error' "cannot build zero packages"- [srpm] ->- let verrel = showPkgVerRel . readNVRA $ srpm- in ["--resultdir=results" </> verrel]- _ -> []+ resultdir <-+ case srpms of+ [] -> error' "cannot build zero packages"+ [srpm] ->+ let verrel = showPkgVerRel . readNVRA $ srpm+ in return ["--resultdir=results" </> verrel]+ _ -> return []+ incontainer <- doesFileExist "/run/.containerenv" let command = if length pkgs > 1 then "--chain" else "--rebuild" noclean = case mnoclean of Nothing -> []@@ -69,7 +70,7 @@ Just NoCleanAfter -> ["--no-cleanup-after"] Just NoCleanAll -> ["--no-clean", "--no-cleanup-after"] Just MockShortCircuit -> ["--short-circuit", "install"]- mockopts_common c = [c, "--root", mockRoot rootBr march] ++ noclean ++ ["--enable-network" | network]+ mockopts_common c = [c, "--root", mockRoot rootBr march] ++ noclean ++ ["--enable-network" | network] ++ ["--no-bootstrap-chroot" | nobootstrap || incontainer] config_opts = ["cleanup_on_failure=False" | mnoclean `elem` [Nothing, Just NoCleanBefore]] ++ ["buildroot_image_skip_pull=True" | noPull] ++ maybe [] words mconfigOptions mockbuild_opts = mockopts_common command ++ ["--config-opts=" ++ unwords config_opts | not (null config_opts)] ++ resultdir ++ srpms mockshell_opts = mockopts_common "--shell" ++ ["--no-clean" | "--no-clean" `notElem` noclean]
+ src/Cmd/PRs.hs view
@@ -0,0 +1,22 @@+{-# LANGUAGE CPP #-}++module Cmd.PRs (+ prsCmd+ )+where++#if MIN_VERSION_base(4,15,0)+import Common (singleton)+#endif+import Common.System (getDirectoryName)+import Pagure (pagurePRs)++prsCmd :: [String] -> IO ()+prsCmd pkgs = do+ packages <-+ if null pkgs then singleton <$> getDirectoryName else return pkgs+ mapM_ pagurePRs packages+#if !MIN_VERSION_base(4,15,0)+ where+ singleton x = [x]+#endif
src/Cmd/Parallel.hs view
@@ -27,6 +27,7 @@ import Git import Koji import Package+import Pagure (pagurePRs) import RpmBuild (checkSourcesMatch, distRpmOptions, getDynSourcesMacros) import Types @@ -140,7 +141,7 @@ unless okay $ error' "Quitting" when (isNothing msidetagTarget) $ do let spec = packageSpec pkg- bodhiUpdate dryrun mupdate Nothing Nothing Nothing spec $+ bodhiUpdate dryrun False mupdate Nothing Nothing Nothing spec $ intercalate "," . map (showNVR . jobNvr) $ filter ((/= Rawhide) . jobBranch) nvrclogs where@@ -283,6 +284,7 @@ -- FIXME make sure branch is up-to-date (otherwise autorelease may be wrong!) nvr <- pkgNameVerRel' br spec putStrLn $ showNVR nvr +-+ "(" ++ target ++ ")" +-+ morepkgs+ pagurePRs $ unPackage pkg putNewLn unpushed <- gitOneLineLog $ "origin/" ++ showBranch br ++ "..HEAD" if null unpushed
src/Cmd/Prep.hs view
@@ -17,9 +17,9 @@ -- FIXME prompt for cloning -- FIXME to skip prep or deps (eg in broken toolbox when deps can't install;)-prepCmd :: Maybe PrepPre -> Bool -> Bool -> Bool -> (Maybe Branch,[String])- -> IO ()-prepCmd mpre verbose deps allowhead (mbr,pkgs) = do+prepCmd :: Bool -> Maybe PrepPre -> Bool -> Bool -> Bool+ -> (Maybe Branch,[String]) -> IO ()+prepCmd dryrun mpre verbose deps allowhead (mbr,pkgs) = do when (mpre == Just PrepClone) $ cloneCmd False mbr (ClonePkgs pkgs) withPackagesMaybeBranch HeaderNone False (if allowhead then dirtyGitHEAD else Nothing) prepPackage (mbr,pkgs)@@ -40,7 +40,7 @@ error' $ spec +-+ "not found" getSourcesMacros spec when deps $- installDeps False spec+ installDeps dryrun False spec whenM isPkgGitRepo $ case br of RelBranch rbr -> do
src/Cmd/Pull.hs view
@@ -47,7 +47,7 @@ current <- getReleaseBranchWarn unless (breq == Branches [] || RelBranch current == br) $ gitSwitchBranch br- retry 2 $+ retry 3 $ if pullopt == Just PullRebase then git_ "pull" ["origin"] else gitMergeOrigin current
src/Cmd/RequestBranch.hs view
@@ -3,12 +3,17 @@ module Cmd.RequestBranch ( requestBranchesCmd, requestPkgBranches,- waitForKojiPkgBranch+ waitForKojiPkgBranches ) where import Fedora.Krb (fasIdFromKrb)+import Gitea.Forgejo (fedoraForge, listRepoIssues, RepoIssueOptions(..)) import Network.HTTP.Query (lookupKey') import SimplePrompt (promptEnter)+import qualified System.Process.Typed as P+#if !MIN_VERSION_base(4,14,0)+import qualified System.Exit as P+#endif import System.Time.Extra (sleep) import Common@@ -17,24 +22,17 @@ import Branches import Bugzilla import Cmd.SrcDeps (srcDeps)+import Forgejo import Git import Koji (fedoraHub, kojiBuildTarget') import ListReviews import Package-import Pagure---- FIXME try to catch expired token (maybe record date when key updated?)--- request-branch and request-repo require pagure.io API key in ~/.config/rpkg/fedpkg.conf for opening releng-scm issue: following is error for expired key---- "Could not execute request_branch: The following error occurred while creating a new issue in Pagure: Invalid or expired token. Please visit https://pagure.io/settings#nav-api-tab to get or renew your API token.--- For invalid or expired tokens please set a new token in your user configuration by running:--- fedpkg set-pagure-token--- The command is interactive; enter the new token when prompted."+import Pagure (pagureGroupInfo, pagureProjectInfo, srcfpo) -- FIXME option to do koji scratch build instead of mock-requestBranchesCmd :: Bool -> Bool -> Bool -> Maybe Branch -> Bool+requestBranchesCmd :: Bool -> Bool -> Bool -> Bool -> Maybe Branch -> Bool -> (BranchesReq,[String]) -> IO ()-requestBranchesCmd quiet reviews skipcheck mrecursebr mock (breq, ps) = do+requestBranchesCmd quiet reviews skipreqchk skipkojicheck mrecursebr mock (breq, ps) = do if null ps then do when (isJust mrecursebr) $@@ -45,13 +43,13 @@ pkgs <- map reviewBugToPackage <$> listReviews ReviewUnbranched when isPkgGit $ promptEnter "Press Enter to continue inside this dist-git dir!"- mapM_ (\ p -> withExistingDirectory p $ requestPkgBranches quiet (length pkgs > 1) mock breq (Package $ takeFileName p)) pkgs+ mapM_ (\ p -> withExistingDirectory p $ requestPkgBranches quiet (length pkgs > 1) skipreqchk mock breq (Package $ takeFileName p)) pkgs else if isPkgGit then do pkg <- Package <$> getDirectoryName- requestPkgBranches quiet False mock breq pkg >>=- mapM_ (waitForKojiPkgBranch skipcheck pkg)+ requestPkgBranches quiet False skipreqchk mock breq pkg >>=+ waitForKojiPkgBranches skipkojicheck pkg else error' "not a dist-git dir: specify package(s)" else do pkgs <-@@ -70,14 +68,14 @@ forM pkgs $ \ p -> withExistingDirectory p $ do pkg <- Package <$> getDirectoryName- requestPkgBranches quiet (length pkgs > 1) mock breq pkg+ requestPkgBranches quiet (length pkgs > 1) skipreqchk mock breq pkg putNewLn forM_ (zip pkgs newPkgBranches) $ \(pkg,newbrs) ->- forM_ newbrs $ waitForKojiPkgBranch skipcheck (Package $ takeFileName pkg)+ waitForKojiPkgBranches skipkojicheck (Package $ takeFileName pkg) newbrs -requestPkgBranches :: Bool -> Bool -> Bool -> BranchesReq -> Package+requestPkgBranches :: Bool -> Bool -> Bool -> Bool -> BranchesReq -> Package -> IO [Branch]-requestPkgBranches quiet multiple mock breq pkg = do+requestPkgBranches quiet multiple skipreqchk mock breq pkg = do when (multiple && not quiet) $ putPkgHdr pkg brs <- localBranches False@@ -114,27 +112,44 @@ urls <- forM newbranches $ \ br -> do when mock $ fedpkg_ "mockbuild" ["--root", mockRoot br Nothing] when (length branches > 1) $ putStr $ showBranch br ++ " "- -- 1. Can timeout like this:- -- Could not execute request_branch: HTTPSConnectionPool(host='pagure.io', port=443): Read timed out. (read timeout=60)- -- fbrnch: readCreateProcess: fedpkg "request-branch" "epel9" (exit 1): failed- -- &- -- 2. Can fail like this:- -- Could not execute request_branch: The following error occurred while trying to get the active release branches in PDC: <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">- -- <title>500 Internal Server Error</title>- -- <p>The server encountered an internal error or- -- misconfiguration and was unable to complete- -- your request.</p> [...]- -- fbrnch: readCreateProcess: fedpkg "request-branch" "epel9" (exit 1): failed- u <- fedpkg "request-branch" [showBranch br]- putStrLn u- return u+ url <- doRequestBr br+ putStrLn url+ return url whenJust mbidsession $ \(bid,session) -> commentBug session bid $ unlines $ zipWith (\u b -> u +-+ showBranch b) urls newbranches return newbranches where- -- doRequestBr :: Bool -> Branch -> IO String- -- doRequestBr multibr br = do+-- 1. Can timeout like this:+-- Could not execute request_branch: HTTPSConnectionPool(host='pagure.io', port=443): Read timed out. (read timeout=60)+-- fbrnch: readCreateProcess: fedpkg "request-branch" "epel9" (exit 1): failed+-- &+-- 2. Can fail like this:+-- Could not execute request_branch: The following error occurred while trying to get the active release branches in PDC: <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">+-- <title>500 Internal Server Error</title>+-- <p>The server encountered an internal error or+-- misconfiguration and was unable to complete+-- your request.</p> [...]+-- fbrnch: readCreateProcess: fedpkg "request-branch" "epel9" (exit 1): failed+ doRequestBr :: Branch -> IO String+ doRequestBr br = do+ (ok, u, err) <- cmdFull "fedpkg" ["request-branch", showBranch br] ""+ if ok+ then return u+ else do+ -- "Could not execute request_branch: The following error occurred while creating a new issue in Pagure: Invalid or expired token. Please visit https://pagure.io/settings#nav-api-tab to get or renew your API token.+ -- For invalid or expired tokens please set a new token in your user configuration by running:+ -- fedpkg set-pagure-token+ -- The command is interactive; enter the new token when prompted."+ if "Invalid or expired token." `isInfixOf` err+ then do+ putStrLn "pagure.io token expired"+ putStrLn "Refresh token at https://pagure.io/settings#nav-api-tab and paste here directly into 'fedpkg set-pagure-token' now"+ ret <- P.runProcess $ P.proc "fedpkg" ["set-pagure-token"]+ if ret == P.ExitSuccess+ then doRequestBr br+ else error' "Failed to set token"+ else error' err -- when mock $ fedpkg_ "mockbuild" ["--root", mockRoot br] -- when multiple $ putStr (unPackage pkg ++ " ") -- when multibr $ putStr (show br)@@ -163,16 +178,20 @@ let newbranches = brs' \\ current if null newbranches then return []+ else+ if skipreqchk+ then return newbranches else do fasid <- fasIdFromKrb -- FIXME retry on HttpExceptionRequest ... ConnectionTimeout- erecent <- pagureListProjectIssueTitlesStatus "pagure.io"- "releng/fedora-scm-requests"- [makeItem "author" fasid, makeItem "status" "all",- makeItem "per_page" "100"]- case erecent of+ eissues <-+ listRepoIssues fedoraForge "releng" "fedora-scm-requests" $+ RepoIssueOptions (Just fasid) (Just "all")+ case eissues of Left err -> error' err- Right recent -> filterM (notExistingRequest recent) newbranches+ Right issues -> do+ let its = mapMaybe readIssue issues+ filterM (notExistingRequest its) newbranches -- FIXME print invalid requests? notExistingRequest :: [IssueTitleStatus] -> Branch -> IO Bool@@ -184,9 +203,9 @@ return $ null processed where processedIssueFilter issue =- pagureIssueTitle issue == ("New Branch \"" ++ showBranch br ++ "\" for \"rpms/" ++ unPackage pkg ++ "\"")+ forgeIssueTitle issue == ("New Branch \"" ++ showBranch br ++ "\" for \"rpms/" ++ unPackage pkg ++ "\"") &&- pagureIssueCloseStatus issue == Just "Processed"+ hasIssueLabel "Processed" issue havePkgAccess :: Package -> IO Bool havePkgAccess pkg = do@@ -227,16 +246,22 @@ commits = lookupKey' "commit" access in (admins, commits ++ collabs) -waitForKojiPkgBranch :: Bool -- skipcheck- -> Package -> Branch -> IO ()-waitForKojiPkgBranch skipcheck pkg br =- unless skipcheck $ do+waitForKojiPkgBranches :: Bool -> Package -> [Branch] -> IO ()+waitForKojiPkgBranches skipkojicheck pkg brs =+ unless (null brs) $ do+ sleep 30 -- wait first to avoid "(undefined package)"+ mapM_ (waitForKojiPkgBranch skipkojicheck pkg) brs++waitForKojiPkgBranch :: Bool -> Package -> Branch -> IO ()+waitForKojiPkgBranch skipkojicheck pkg br =+ unless skipkojicheck $ do putStrLn $ "waiting for" +-+ unPackage pkg +-+ "to be added to" +-+ showBranch br ++ "-build" (buildtag,_desttag) <- kojiBuildTarget' fedoraHub (showBranch br) waitBuildTag buildtag where waitBuildTag :: String -> IO () waitBuildTag buildtag = do- sleep 30 -- wait first to avoid "(undefined package)" ok <- cmdBool "koji" ["list-pkgs", "--quiet", "--package=" ++ unPackage pkg, "--tag=" ++ buildtag]- unless ok $ waitBuildTag buildtag+ unless ok $ do+ sleep 30+ waitBuildTag buildtag
src/Cmd/RequestRepo.hs view
@@ -1,12 +1,21 @@+{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} module Cmd.RequestRepo (requestRepos) where import Control.Exception.Extra (retry)+import qualified Data.ByteString.Lazy.Char8 as B import Fedora.Krb (fasIdFromKrb)+import Gitea.Forgejo (fedoraForge, listRepoIssues, RepoIssueOptions(..)) import Network.HTTP.Directory (httpExists') import Safe (headMay) import SimplePrompt (promptEnter, promptInitial, yesNo)+import System.Directory (doesFileExist)+import System.Environment.XDG.BaseDir (getUserConfigFile)+import qualified System.Process.Typed as P+#if !MIN_VERSION_base(4,14,0)+import qualified System.Exit as P+#endif import System.Time.Extra (sleep) import Branches@@ -15,9 +24,10 @@ import Common import Common.System (error') import qualified Common.Text as T+import Forgejo import ListReviews import Package-import Pagure+import Pagure (pagureListGitBranches, srcfpo) -- FIXME separate pre-checked listReviews and direct pkg call, which needs checks requestRepos :: Bool -> Bool -> Bool -> Bool -> (BranchesReq, [String])@@ -52,7 +62,7 @@ putStrLn "Request exists:" mapM_ printScmIssue requests -- don't resubmit if succeeded- when (resubmit && pagureIssueCloseStatus request == Just "Processed") $+ when (resubmit && hasIssueLabel "Processed" request) $ error' "The last repo request was already successfully Processed" when (null requests || resubmit) $ do checkNoPagureRepo@@ -64,7 +74,7 @@ putNewLn promptEnter "Press Enter to continue" -- FIXME check api key is still valid or open pagure ticket directly- fedpkg_ "request-repo" [pkg, show bid]+ doRequestRepo pkg bid putNewLn let draft = "Thank you for the review" ++ maybe "" ("," +-+) (assigneeFirstname $ bugAssignedToDetail bug) input <- promptInitial "Enter comment" draft@@ -85,17 +95,16 @@ existingRepoRequests :: IO [IssueTitleStatus] existingRepoRequests = do fasid <- fasIdFromKrb- erecent <-+ eissues <- retry 2 $- pagureListProjectIssueTitlesStatus pagureio- "releng/fedora-scm-requests"- [makeItem "author" fasid, makeItem "status" "all",- makeItem "per_page" "100"]- case erecent of+ listRepoIssues fedoraForge "releng" "fedora-scm-requests" $+ RepoIssueOptions (Just fasid) (Just "all")+ case eissues of Left err -> error' err- Right recent ->+ Right issues -> do+ let its = mapMaybe readIssue issues -- don't mention "New Repo" here, since Branch requests also imply repo already exists- return $ filter (((" for \"rpms/" ++ pkg ++ "\"") `isSuffixOf`) . pagureIssueTitle) recent+ return $ filter (((" for \"rpms/" ++ pkg ++ "\"") `isSuffixOf`) . forgeIssueTitle) its checkNoPagureRepo :: IO () checkNoPagureRepo = do@@ -124,3 +133,29 @@ Right brs -> when (null brs) $ error' $ "no branches in dist-git for" +-+ pkg++doRequestRepo :: String -> Int -> IO ()+doRequestRepo pkg bid = do+ file <- getUserConfigFile "rpkg" "fedpkg.conf"+ cfg <- doesFileExist file+ if cfg+ then do+ (exit, err) <- P.readProcessStderr $ P.proc "fedpkg" ["request-repo", pkg, show bid]+ let errstr = B.unpack err+ unless (exit == P.ExitSuccess) $ do+ if "Invalid or expired token." `isInfixOf` errstr+ then do+ putStrLn "pagure.io token expired or invalid"+ putStrLn "Refresh token at https://pagure.io/settings#nav-api-tab and paste here directly into 'fedpkg set-pagure-token' now"+ setPagureToken+ else error' errstr+ else do+ putStrLn "Missing pagure.io token"+ putStrLn "Please create a token for issue creation at https://pagure.io/settings#nav-api-tab and paste here into 'fedpkg set-pagure-token' now"+ setPagureToken+ where+ setPagureToken = do+ ret <- P.runProcess $ P.proc "fedpkg" ["set-forgejo-token"]+ if ret == P.ExitSuccess+ then doRequestRepo pkg bid+ else error' "Failed to set token"
src/Cmd/ReviewPackage.hs view
@@ -10,9 +10,10 @@ import Data.Char import Data.Either (isRight) import Data.Tuple.Extra (second)-import Safe (headDef, headMay, tailSafe)+import Safe (headDef, headMay, lastMay, tailSafe) import SelectRPMs (selectDefault, Yes(No)) import SimplePrompt (promptEnter, yesNoDefault)+import System.Console.Pretty (color, Color(Red)) import Branches import Bugzilla@@ -20,22 +21,25 @@ import Cmd.Install (installCmd) import Cmd.Local (localCmd) import Cmd.Prep (prepCmd)-import Git (isGitRepo, git_, gitBool)+import Git (isGitDirClean, isGitRepo, git_, gitBool) import Package import RpmBuild -- FIXME does not work with pkg dir/spec: 'fbrnch: No spec file found' -- FIXME --user to download all user's review requests-reviewPackage :: Bool -> Maybe String -> IO ()-reviewPackage full Nothing = do+reviewPackage :: Bool -> Bool -> Bool -> Maybe String -> IO ()+reviewPackage dryrun full update Nothing = do -- FIXME catch no spec file spec <- findSpecfile srpm <- generateSrpm Nothing spec if not full- then doInteractiveReview False (Just spec) srpm+ then+ if update+ then reviewPackage dryrun full update (Just $ takeBaseName spec)+ else doInteractiveReview dryrun update (Just spec) srpm else do cmd_ "fedora-review" ["-rn", srpm]-reviewPackage full (Just pkgbug) = do+reviewPackage dryrun full update (Just pkgbug) = do let epkgbid = if all isDigit pkgbug then Right $ read pkgbug@@ -54,7 +58,7 @@ let bid = bugId bug pkg = reviewBugToPackage bug if not full- then reviewPackageInteractive bid pkg session bug+ then reviewPackageInteractive dryrun update bid pkg session bug else do promptEnter "Press Enter to run fedora-review" -- FIXME support copr build@@ -63,36 +67,45 @@ [] -> error' $ "No package review found for" +-+ pkgbug _ -> error' $ "More than one review bug found for" +-+ pkgbug -reviewPackageInteractive :: Int -> String -> BugzillaSession -> Bug -> IO ()-reviewPackageInteractive bid pkg session bug = do+reviewPackageInteractive :: Bool -> Bool -> Int -> String+ -> BugzillaSession -> Bug -> IO ()+reviewPackageInteractive dryrun update bid pkg session bug = do let dir = show bid ++ '-' : pkg -- FIXME check if current directory exists <- doesDirectoryExist dir- unless exists $- createDirectory dir- setCurrentDirectory dir- srpm <- downloadReviewSRPM True True False pkg bid session+ unless update $ do+ unless exists $+ createDirectory dir+ setCurrentDirectory dir+ srpm <- downloadReviewSRPM True True False update pkg bid session importsrpm <-- if exists- then do- putStrLn $ "in" +-+ dir </> ":\n"- cmd_ "ls" ["-F"]- putNewLn- -- FIXME default to no if nvr unchanged?- yesNoDefault True "Press Enter to install/prep srpm"- else return True+ if update+ then return True+ else+ if exists+ then do+ putStrLn $ "in" +-+ dir </> ":\n"+ cmd_ "ls" ["-F"]+ putNewLn+ -- FIXME default to no if nvr unchanged?+ yesNoDefault True "Press Enter to install/prep srpm"+ else return True -- review and package name may be different (eg ramalama)- doInteractiveReview importsrpm Nothing srpm+ doInteractiveReview dryrun importsrpm Nothing srpm putNewLn putReviewBug False bug putNewLn putStrLn $ "Review dir is" +-+ dir -doInteractiveReview :: Bool -> Maybe FilePath -> FilePath -> IO ()-doInteractiveReview importsrpm mspec srpm = do+doInteractiveReview :: Bool -> Bool -> Maybe FilePath -> FilePath -> IO ()+doInteractiveReview dryrun importsrpm mspec srpm = do when importsrpm $ do isgit <- isGitRepo- unless isgit $ git_ "init" []+ if isgit+ then+ unlessM isGitDirClean $+ promptEnter "git dir not clean: commit and Press Enter"+ else git_ "init" [] -- FIXME override %_sourcedir so it doesn't put elsewhere? sourcediropt <- sourceDirCwdOpt putStrLn "installing srpm:"@@ -111,7 +124,12 @@ let filterdiff = filter (\d -> not (any (`isSuffixOf` d) ["SPEC","SRPMS","RPMS","BUILD","BUILDROOT","src.rpm",".log", ".git", upstreamDir])) diff if null filterdiff then putStrLn $ "no difference with" +-+ upstreamDir ++ "/"- else mapM_ putStrLn filterdiff+ else do+ let colorDiffer cs =+ case lastMay $ words cs of+ Just l | l == "differ" -> color Red cs+ _ -> cs+ mapM_ (putStrLn . colorDiffer) filterdiff unlessM (gitBool "diff" ["--quiet", "--cached"]) $ git_ "commit" ["-m", srpm] putNewLn@@ -119,14 +137,18 @@ -- FIXME or download rpms build <- yesNoDefault importsrpm "Build package locally" if build- then localCmd False False False Nothing Nothing [] (Branches [],[])- else prepCmd Nothing False False False (Nothing,[])+ then localCmd dryrun False False False Nothing Nothing [] (Branches [],[])+ else do+ putStr "prep "+ prepCmd dryrun Nothing False False False (Nothing,[]) putNewLn putStrLn "# RpmLint"- void $ cmdBool "rpmlint" ["."] -- FIXME $ spec:srpm:rpms spec <- maybe findSpecfile return mspec+ br <- systemBranch+ built <- builtRpms (RelBranch br) spec+ void $ cmdBool "rpmlint" $ spec : srpm : built whenM (yesNoDefault importsrpm "Install packages locally") $ do- installCmd False False Nothing Nothing Nothing [] Nothing False False True True No selectDefault Nothing (Nothing,[])+ installCmd dryrun False False Nothing Nothing Nothing [] Nothing False False True True No selectDefault Nothing (Nothing,[]) rpms <- cmdLines "rpmspec" ["-q", "--rpms", "--qf", "%{name}\n", spec] whenM (yesNoDefault importsrpm "Rpmlint installed packages") $ do (_ok, out, err) <- cmdFull "rpmlint" ("-i" : rpms) ""@@ -147,19 +169,19 @@ putStrLn "# Licensing" whenM (yesNoDefault True "Run licensecheck") $ do buildls <- listDirectory "BUILD"- let builddir =- case sort buildls of- [] -> error' "empty BUILD/"- [d] -> "BUILD" </> d- -- FIXME not good enough! use nvr- ds -> "BUILD" </> last ds- builddirls <- listDirectory builddir- let builddir2 =- case sort $ builddirls \\ ["BUILDROOT","SPECPARTS"] of- [] -> error' $ "empty" +-+ "BUILD" </> builddir- [d] -> builddir </> d- -- FIXME? some projects might have more than one topdir- ds -> error' $ "more than one dir:" +-+ unwords ds+ builddir <-+ case sort buildls of+ [] -> error' "empty BUILD/"+ [d] -> return $ "BUILD" </> d+ -- FIXME not good enough! use nvr+ ds -> return $ "BUILD" </> last ds+ builddirls <- listDirectory builddir >>= filterM (doesDirectoryExist . (builddir +/+))+ builddir2 <-+ case sort $ builddirls \\ ["BUILDROOT","SPECPARTS",".pyproject-builddir","pyproject-wheeldir"] of+ [] -> error' $ "empty" +-+ "BUILD" </> builddir+ [d] -> return $ builddir </> d+ -- FIXME? some projects might have more than one topdir+ ds -> error' $ "more than one dir:" +-+ unwords ds let args = ["--shortname-scheme", "spdx", "-r", builddir2] cmdN "licensecheck" args cmdLines "licensecheck" args >>=
src/Cmd/SideTags.hs view
@@ -5,11 +5,12 @@ where import Fedora.Krb (krbTicket)-import SimpleCmd (cmd_, cmdN, error')+import SimpleCmd (cmd_, cmdN) import SimplePrompt (yesNo) import Branches import Common+import Common.System (error') import Git (gitSwitchBranchVerbose, isPkgGitRepo) import Koji import Package (cleanGit, dirtyGit, findSpecfile, pkgNameVerRel',
src/Cmd/Sort.hs view
@@ -17,17 +17,17 @@ import Branches import Git import Package-import RpmBuild (distRpmOptions, getDynSourcesMacros)+import RpmBuild (distRpmOptions, getDynSourcesMacros, installDeps) data RpmWith = RpmWith String | RpmWithout String data SortDisplay = SortParallel | SortChain | SortLayers | SortPlain -- FIXME ghc-attempt f37 branch does not exist! (coming from f29)-sortCmd :: SortDisplay -> Maybe RpmWith -> (Branch,[String]) -> IO ()-sortCmd _ _ (_,[]) = return ()-sortCmd displaymode mrpmwith (br, pkgs) = do- withPackagesBranch HeaderNone False Nothing setupPkg (br, pkgs)+sortCmd :: SortDisplay -> Bool -> Maybe RpmWith -> (Branch,[String]) -> IO ()+sortCmd _ _ _ (_,[]) = return ()+sortCmd displaymode deps mrpmwith (br, pkgs) = do+ withPackagesBranch HeaderNone False Nothing (setupPkg deps) (br, pkgs) distopts <- distRpmOptions br let rpmopts = maybe [] toRpmOption mrpmwith ++ distopts case displaymode of@@ -43,19 +43,21 @@ SortPlain -> dependencySortRpmOpts rpmopts (reverse pkgs) >>= putStrLn . unwords -setupPkg :: Package -> AnyBranch -> IO ()-setupPkg pkg br = do+setupPkg :: Bool -> Package -> AnyBranch -> IO ()+setupPkg deps pkg br = do whenM isPkgGitRepo $ gitSwitchBranch br- unlessM (doesFileExist "dead.package") $+ unlessM (doesFileExist "dead.package") $ do getDynSourcesMacros $ packageSpec pkg+ when deps $+ localBranchSpecFile pkg br >>= installDeps False False toRpmOption :: RpmWith -> [String] toRpmOption (RpmWith opt) = ["--with=" ++ opt] toRpmOption (RpmWithout opt) = ["--without=" ++ opt] -graphCmd :: Bool -> Maybe RpmWith -> (Maybe Branch,[FilePath]) -> IO ()-graphCmd dot mrpmwith (mbr, pkgs) = do- withPackagesMaybeBranchNoHeadergit setupPkg (mbr, pkgs)+graphCmd :: Bool -> Bool -> Maybe RpmWith -> (Maybe Branch,[FilePath]) -> IO ()+graphCmd dot deps mrpmwith (mbr, pkgs) = do+ withPackagesMaybeBranchNoHeadergit (setupPkg deps) (mbr, pkgs) let rpmopts = maybe [] toRpmOption mrpmwith createGraph4 False [] rpmopts False False True Nothing pkgs >>= if dot then printGraph else renderGraph
src/Cmd/Update.hs view
@@ -58,7 +58,7 @@ then findSpecfile else localBranchSpecFile pkg br curver <- pkgVersion spec- rawdiff <- filter (not . ("@@ " `isPrefixOf`)) <$> gitLines "diff" ["-U0", "HEAD", spec]+ rawdiff <- filter (not . ("@@ " `isPrefixOf`)) <$> gitDiffHEAD spec let vdiff = filter (\v -> any (`isPrefixOf` v) ["-Version:","+Version:"]) rawdiff mnewrel = find ("+Release:" `isPrefixOf`) rawdiff when (length vdiff > 2) $@@ -78,10 +78,7 @@ case map extractFieldValue vdiff of [old,new] -> Just (old,new) _ -> Nothing- when (isJust mver) $- when (isJust moldnewver) $ do- let (oldver,newver) =- fromMaybe (error' "complex version change") moldnewver+ whenJust moldnewver $ \(oldver,newver) -> do -- FIXME take epoch into account when (rpmVerCompare oldver newver == GT) $ putStrLn $ "current" +-+ oldver +-+ "is newer!"@@ -95,17 +92,17 @@ error' "Please edit complex 'Version' fields with macro(s) by hand" _ -> error' "Please edit package with multiple versions by hand" editSpecField "Version" newver spec- autorelease <- isAutoRelease spec- if autorelease- then do- autoreset <- autoReleaseReset spec- when autoreset $- editSpecField "Release" "%autorelease" spec- -- FIXME if multiple versions need to bump release- else editSpecField "Release" "0%{?dist}" spec+ autorelease <- isAutoRelease spec+ if autorelease+ then do+ autoreset <- autoReleaseReset spec+ when autoreset $+ editSpecField "Release" "%autorelease" spec+ -- FIXME if multiple versions need to bump release+ else editSpecField "Release" "0%{?dist}" spec -- FIXME should be sure sources exists for distgit- whenM (doesFileExist "sources") $- cmd_ "sed" ["-i", "/" ++ unPackage pkg ++ "-" ++ oldver ++ "./d", "sources"]+ whenM (doesFileExist "sources") $+ cmd_ "sed" ["-i", "/" ++ unPackage pkg ++ "-" ++ oldver ++ "./d", "sources"] when distgit $ do -- FIXME forM_ sources <- map sourceFieldFile <$> cmdLines "spectool" ["-S", spec]@@ -125,19 +122,21 @@ forM_ archives removeFile cmd_ "spectool" ["-g", "-S", spec] krbTicket+ -- FIXME ideally we could diff first, but new-sources sets up sources for diff fedpkg_ "new-sources" archives unless (null textsources) $ git_ "add" textsources case moldnewver of- Just (_old,newver) -> do+ Just (old,newver) -> do whenM (yesNoDefault False "Do you want to diff the sources") $- compareTarballsCmd Nothing Nothing Nothing+ compareTarballsCmd Nothing (Just $ SrcVer old) (Just $ SrcVer newver) versions <- changelogVersions spec let missing = case versions of [] -> True (h:_) -> not $ (newver ++ "-") `isPrefixOf` h- when missing $ do+ if missing+ then do -- FIXME newver may contain macros! newversion <- pkgVersion spec cmd_ "rpmdev-bumpspec" ["-c", "Update to" +-+ newversion, spec]@@ -147,10 +146,11 @@ editSpecField "Release" newrel spec cmd_ "sed" ["-i", "s/> -" +-+ newversion ++ '-' : newrelease ++ "/> -" +-+ newversion ++ '-' : replace "%{?dist}" "" newrel ++ "/" , spec] git_ "commit" ["-a", "-m", "Update to" +-+ newversion]+ else warning $ "Changelog for" +-+ newver +-+ "already exists" Nothing -> do- rawsdiff <- filter (not . ("@@ " `isPrefixOf`)) <$> gitLines "diff" ["-U0", "HEAD", "sources"]+ rawsdiff <- filter (not . ("@@ " `isPrefixOf`)) <$> gitDiffHEAD "sources" unless (null rawsdiff) $- whenM (yesNoDefault False "Do you want to diff the sources") $+ whenM (yesNoDefault False "Do you want to try to diff the sources") $ compareTarballsCmd Nothing Nothing Nothing putStr "Prepping in temp dir... " sourcediropt <- sourceDirCwdOpt@@ -171,4 +171,4 @@ extractFieldValue vs = case headMay . tailSafe . words $ vs of Just h -> h- Nothing -> error' $ "no field value:" +-+ vs+ Nothing -> error $ "no field value:" +-+ vs
src/Cmd/UpdateReview.hs view
@@ -4,11 +4,11 @@ where import Control.Monad (when)-import SimpleCmd (cmd, error')+import SimpleCmd (cmd) import System.FilePath (takeFileName) import Bugzilla---import Common+import Common.System (error') import qualified Common.Text as T import Package import PkgReview
src/Common/System.hs view
@@ -13,20 +13,25 @@ #if !MIN_VERSION_simple_cmd(0,2,8) cmdFull, #endif+ error', #if !MIN_VERSION_simple_cmd(0,2,5) timeIO, #endif timeIODesc ) where +import Control.Monad.IO.Class #if !MIN_VERSION_filepath(1,4,2) import Data.List #endif-#if MIN_VERSION_time(1,9,0)+#if MIN_VERSION_time(1,9,0) && !MIN_VERSION_simple_cmd(0,2,8) import Data.Time.Format (formatTime, defaultTimeLocale) #endif+#if !MIN_VERSION_simple_cmd(0,2,8) import Safe+#endif import SimpleCmd hiding (+ error', #if !MIN_VERSION_simple_cmd(0,2,8) cmdFull, #endif@@ -34,16 +39,18 @@ ifM,whenM #endif )-#if !MIN_VERSION_simple_cmd(0,2,8) import System.Exit+#if !MIN_VERSION_simple_cmd(0,2,8) import System.Process #endif import System.Directory import System.FilePath import System.IO +#if !MIN_VERSION_simple_cmd(0,2,8) import Control.Exception (bracket) import Data.Time.Clock+#endif #if !MIN_VERSION_simple_cmd(0,2,5) timeIO :: IO a -> IO a@@ -53,6 +60,7 @@ timeIODesc :: String -> IO a -> IO a timeIODesc thing = timeIOHelper (thing +-+ "took") +#if !MIN_VERSION_simple_cmd(0,2,8) timeIOHelper :: String -> IO a -> IO a timeIOHelper msg action = do bracket@@ -74,6 +82,7 @@ #else renderDuration = show #endif+#endif isTty :: IO Bool isTty = hIsTerminalDevice stdin@@ -106,3 +115,9 @@ isExtensionOf ext@('.':_) = isSuffixOf ext . takeExtensions isExtensionOf ext = isSuffixOf ('.':ext) . takeExtensions #endif++error':: MonadIO m => String -> m a+error' err = do+ liftIO $ do+ putStrLn err+ exitFailure
+ src/Forgejo.hs view
@@ -0,0 +1,39 @@+module Forgejo (+ readIssue,+ IssueTitleStatus(..),+ printScmIssue,+ hasIssueLabel+ )+where++import Data.Maybe (mapMaybe)+import qualified Data.Text as T+import Gitea.Forgejo+import Common ((+/+), (+-+))++data IssueTitleStatus =+ IssueTitleStatus { forgeIssueId :: Integer+ , forgeIssueTitle :: String+ , forgeIssueStatus :: T.Text+ , forgeIssueLabels :: Maybe [T.Text]+ }++readIssue :: Issue -> Maybe IssueTitleStatus+readIssue issue = do+ number <- issueNumber issue+ title <- T.unpack <$> issueTitle issue+ state <- issueState issue+ let labels = mapMaybe labelName <$> issueLabels issue+ return $ IssueTitleStatus number title state labels++printScmIssue :: IssueTitleStatus -> IO ()+printScmIssue issue =+ putStrLn $ "https://forge.fedproject.org" +/+ "releng/fedora-scm-requests" +/+ "issue" +/+ show (forgeIssueId issue) +-+ "(" ++ T.unpack (forgeIssueStatus issue) ++ labels ++ "):" +-+ forgeIssueTitle issue+ where+ labels = maybe "" show $ forgeIssueLabels issue++hasIssueLabel :: String -> IssueTitleStatus -> Bool+hasIssueLabel label issue =+ case forgeIssueLabels issue of+ Just labels -> T.pack label `elem` labels+ Nothing -> False
src/Git.hs view
@@ -16,6 +16,7 @@ showCommit, displayCommits, displayHdrCommits,+ gitDiffHEAD, gitOneLineLog, gitShortLogN, gitShortLog1,@@ -181,7 +182,7 @@ mkCommit :: String -> Commit mkCommit cs = case word1 cs of- ("",_) -> error' "empty commit log line!"+ ("",_) -> error "empty commit log line!" (hash,rest) -> case breakEnd isSpace rest of -- "(msg txt, date)"@@ -293,6 +294,7 @@ if not exists then return False else do+ -- FIXME should ideally check for "gitdir: ..." gitdir <- last . words <$> readFile ".git" if "/worktrees/" `isInfixOf` gitdir then egrep_ key (takeDirectory (takeDirectory gitdir) </> "config")@@ -408,3 +410,8 @@ if lower ref == "head" then return $ Just c else conflictPrompt commits txt++gitDiffHEAD :: FilePath -> IO [String]+gitDiffHEAD file = do+ haveHEAD <- isJust <$> cmdMaybe "git" ("rev-parse" : ["--verify", "--quiet", "HEAD"])+ gitLines "diff" $ ["-U0"] ++ ["HEAD" | haveHEAD] ++ ["--", file]
src/Koji.hs view
@@ -124,10 +124,12 @@ hub <- getKojiProfileHub user <- fasIdFromKrb muserid <- kojiGetUserID hub user- let userid = fromMaybe (error' $ "Koji failed to return userid for '" ++ user ++ "'") muserid- commit <- maybe (git "rev-parse" ["HEAD"]) return mref- let source = kojiSource pkg commit- kojiUserBuildTasks hub userid (Just source) (Just target)+ case muserid of+ Nothing -> error' $ "Koji failed to return userid for '" ++ user ++ "'"+ Just userid -> do+ commit <- maybe (git "rev-parse" ["HEAD"]) return mref+ let source = kojiSource pkg commit+ kojiUserBuildTasks hub userid (Just source) (Just target) -- * Koji building @@ -142,12 +144,13 @@ kojiBuild' :: Bool -> String -> [String] -> IO KojiBuildTask kojiBuild' wait target args = do krbTicket- let srpm = if null args- then error' "no args passed to koji build"- else ".src.rpm" `isSuffixOf` last args+ issrpm <-+ if null args+ then error "no args passed to koji build"+ else return $ ".src.rpm" `isSuffixOf` last args -- FIXME use tee functionality mprofile <- getKojiProfile- when srpm $ putStrLn $ "koji srpm build: uploading..." +-+ maybe "" ("to" +-+) mprofile+ when issrpm $ putStrLn $ "koji srpm build: uploading..." +-+ maybe "" ("to" +-+) mprofile -- can fail like: -- [ERROR] koji: Request error: POST::https://koji.fedoraproject.org/kojihub/ssllogin::<PreparedRequest [POST]> -- [ERROR] koji: AuthError: unable to obtain a session@@ -390,9 +393,9 @@ kojiBuildBranch :: String -> Package -> Maybe String -> [String] -> IO () kojiBuildBranch target pkg mref args =- checkResult <$> kojiBuildBranch' True target pkg mref args+ kojiBuildBranch' True target pkg mref args >>= checkResult where- checkResult = either (\ task -> error' (displayID task +-+ "not completed")) (const ())+ checkResult = either (\ task -> error' (displayID task +-+ "not completed")) (const $ return ()) kojiBuildBranchNoWait ::String -> Package -> Maybe String -> [String] -> IO TaskID kojiBuildBranchNoWait target pkg mref args = do@@ -473,11 +476,11 @@ createKojiSidetag :: Bool -> Branch -> IO String createKojiSidetag dryrun br = do hub <- getKojiProfileHub- (buildtag,_desttag) <- kojiBuildTarget' hub (showBranch br) out <- if dryrun- then return $ "Side tag '" ++ buildtag ++ "'"+ then return $ "Side tag '" ++ showBranch br ++ "'" else do+ buildtag <- fst <$> kojiBuildTarget' hub (showBranch br) krbTicket ls <- lines <$> fedpkg "request-side-tag" ["--base-tag", buildtag] case ls of@@ -575,7 +578,7 @@ (if "fedora-ci_" `isPrefixOf` base then takeWhileEnd (/= ':') $ dropPrefix ";" $ dropWhile (/= ';') base else base) +-+ fromMaybe "" mtag- _ -> error' "could not determine package from build request"+ _ -> error "could not determine package from build request" where showValue :: Value -> String showValue (ValueString cs) = cs
src/ListReviews.hs view
@@ -7,9 +7,8 @@ listReviewsFull ) where -import SimpleCmd (error')- import Common+import Common.System (error') import Branches import Bugzilla
src/Main.hs view
@@ -2,7 +2,7 @@ module Main (main) where -import Data.List.Extra (dropSuffix)+import Data.List.Extra (chunksOf, dropSuffix, sort) import Data.Maybe (fromMaybe) import Distribution.Fedora.Branch (partitionBranches, readBranch) #if !MIN_VERSION_simple_cmd_args(0,1,7)@@ -11,6 +11,9 @@ import SelectRPMs (existingStrategyOption, pkgMgrOpt, selectRpmsOptions, Yes(..)) import SimpleCmdArgs+import System.Environment (getArgs)+import System.Console.Terminal.Size (size, Window(..))+import qualified Text.PrettyPrint.Boxes as B -- commands import Cmd.Autospec@@ -36,6 +39,7 @@ import Cmd.Mock import Cmd.Override import Cmd.Owner+import Cmd.PRs import Cmd.Parallel import Cmd.Prep import Cmd.Pull@@ -67,15 +71,61 @@ import Paths_fbrnch (version) import Types (SideTagTarget(..)) +getTerminalWidth :: IO Int+getTerminalWidth = do+ mSize <- size+ case mSize of+ Just s -> return (width s)+ Nothing -> return 80++renderVertGridWithBoxes :: Int -> [String] -> String+renderVertGridWithBoxes termWidth items =+ let matrix = commandMatrix+ boxMatrix = map (map B.text) matrix+ columns = map (B.vcat B.left) boxMatrix+ finalBox = B.hsep 4 B.left columns+ in B.render finalBox+ where+ commandMatrix :: [[String]]+ commandMatrix =+ if null items+ then []+ else+ let numCols = max 1 $ min 6 (termWidth `div` 20)+ in toVerticalGrid numCols++ toVerticalGrid :: Int -> [[String]]+ toVerticalGrid numCols =+ let numItems = length items+ numRows = (numItems + numCols - 1) `div` numCols+ -- Pad with empty strings to make a perfect rectangle+ padded = items ++ replicate (numRows * numCols - numItems) ""+ in chunksOf numRows padded+ main :: IO () main = do- setNoBuffering- simpleCmdArgs (Just version) "Fedora branch building tool"- "A tool to help with updating and building package branches https://github.com/juhp/fbrnch#readme" $- subcommands+ args <- getArgs+ case args of+ [] -> do+ putStrLn "Usage: 'fbrnch <command>' where <command> is one of:\n"+ w <- getTerminalWidth+ putStrLn $ renderVertGridWithBoxes w . sort $ map cmdName progCommands+ putStrLn "Use -h (--help) for details"+ ["--list-commands"] ->+ mapM_ putStrLn $ sort $ map cmdName progCommands+ _ -> do+ setNoBuffering+ simpleCmdArgs (Just version) "Fedora branch building tool"+ "A tool to help with updating and building package branches https://github.com/juhp/fbrnch#readme" $+ subcommands progCommands+ where+ cmdName (Subcommand name _ _) = name++progCommands :: [Subcommand]+progCommands = [ Subcommand "clone" "Clone packages" $ cloneCmd- <$> dryrunOpt "Dry run"+ <$> dryrunOpt <*> optional (optionWith branchM 'b' "branch" "BRANCH" "branch") <*> cloneRequest , Subcommand "switch" "Switch branch" $@@ -103,7 +153,7 @@ <*> branchesPackages , Subcommand "merge" "Merge from newer branch" $ mergeCmd- <$> dryrunOpt "Dry run (do not merge)"+ <$> dryrunOptDesc "Dry run (do not merge)" <*> switchLongWith "no-fetch" "Skip git fetch" <*> nopromptOpt <*> optional (optionWith auto 's' "skip-bumps" "NUM" "Max num of rebuild commits to ignore [default 0]")@@ -139,7 +189,7 @@ <*> branchesPackages , Subcommand "parallel" "Parallel build packages in Koji" $ parallelBuildCmd- <$> dryrunOpt "Dry run: do not build anything"+ <$> dryrunOptDesc "Dry run: do not build anything" <*> mergeOpt <*> optional (optionWith branchM 'f' "from" "BRANCH" "Branch to merge from [default newer]") <*> optionalWith auto 'l' "skip-to-layer" "LAYERNO" "Skip the first N layers [default 0]" 0@@ -150,21 +200,21 @@ <*> branchesPackagesDesc "BRANCH... PKG1... [:] PKG2..." , Subcommand "sidetags" "List user's side-tags" $ sideTagsCmd- <$> dryrunOpt "Dry-run: no sidetag actions"+ <$> dryrunOptDesc "Dry-run: no sidetag actions" <*> optional (flagLongWith' SidetagTagged "tagged" "List tagged builds in sidetag(s)" <|> flagLongWith' SidetagAdd "create" "Create one or more sidetags" <|> flagLongWith' SidetagRemove "remove" "Remove one or more sidetags") <*> many branchArg , Subcommand "override" "Tag builds into buildroot override in Koji" $ overrideCmd- <$> dryrunOpt "Dry run: do not override"+ <$> dryrunOptDesc "Dry run: do not override" <*> overrideModeOpt <*> optional (optionWith auto 'd' "duration" "DAYS" "Number of days until expiry [default 4]") <*> switchWith 'w' "no-wait" "Skip waitrepo step" <*> branchesPackages , Subcommand "waitrepo" "Wait for build to appear in Koji buildroot" $ waitrepoCmd- <$> dryrunOpt "Dry run: do not wait"+ <$> dryrunOptDesc "Dry run: do not wait" <*> switchLongWith "no-package" "Generic wait-repo without a build NVR" <*> waitfetchOpt <*> optional (sidetagTargetOpt Nothing)@@ -175,7 +225,7 @@ <*> optional (argumentWith auto "TASKID") , Subcommand "scratch" "Scratch build package in Koji" $ scratchCmd- <$> dryrunOpt "Dry run: do not build"+ <$> dryrunOptDesc "Dry run: do not build" <*> switchLongWith "stagger" "Stagger archs" <*> rebuildSrpmOpt <*> noFailFastOpt@@ -186,7 +236,7 @@ <*> branchesPackages , Subcommand "scratch-aarch64" "Koji aarch64 scratch build of package" $ scratchCmdAarch64- <$> dryrunOpt "Dry run: do not build"+ <$> dryrunOptDesc "Dry run: do not build" <*> rebuildSrpmOpt <*> allowHeadOpt <*> switchWith 'X' "exclude-arch" "Exclude aarch64"@@ -195,7 +245,7 @@ <*> branchesPackages , Subcommand "scratch-x86_64" "Koji x86_64 scratch build of package" $ scratchCmdX86_64- <$> dryrunOpt "Dry run: do not build"+ <$> dryrunOptDesc "Dry run: do not build" <*> rebuildSrpmOpt <*> allowHeadOpt <*> switchWith 'X' "exclude-arch" "Exclude x86_64"@@ -210,18 +260,21 @@ , Subcommand "sort" "Sort packages in build dependency order (default format: chain-build)" $ sortCmd <$> sortDisplayOpt+ <*> switchWith 'd' "deps" "require deps to be installed" <*> optional rpmWithOpt <*> branchPackages , Subcommand "prep" "Prep sources" $ prepCmd- <$> optional prepPreOpts+ <$> dryrunOpt+ <*> optional prepPreOpts <*> verboseOpt "show rpmbuild output" <*> switchWith 'd' "deps" "require deps to be installed" <*> allowHeadOpt <*> maybeBranchPackages False , Subcommand "local" "Build locally" $ localCmd- <$> quietOpt "Hide the build.log until it errors"+ <$> dryrunOpt+ <*> quietOpt "Hide the build.log until it errors" <*> debugOpt "show the rpmbuild command" <*> allowHeadOpt <*> jobsOpt@@ -256,8 +309,8 @@ , Subcommand "compare-tarballs" "Diff source tarballs" $ compareTarballsCmd <$> optional (optionLongWith auto "max-line-length" "LENGTH" "Skip diff files longer than this [default 200]")- <*> optional (strArg "[NAME-]VERSION1[.tar.gz]")- <*> optional (strArg "[NAME-]VERSION2[.tar.gz]")+ <*> optional (readSrc <$> strArg "[NAME-]VERSION1[.tar.gz]")+ <*> optional (readSrc <$> strArg "[NAME-]VERSION2[.tar.gz]") , Subcommand "src-deps" "List source package dependencies" $ srcDepsCmd <$> switchWith 'r' "reverse" "Reverse dependencies"@@ -265,7 +318,8 @@ <*> branchPackages , Subcommand "mock" "Local mock build" $ mockCmd- <$> dryrunOpt "Do not build (but creates srpm)"+ <$> dryrunOptDesc "Do not build (but creates srpm)"+ <*> switchLongWith "no-bootstrap" "Use --no-bootstrap-chroot to avoid podman" <*> optional nocleanOpt <*> switchLongWith "no-pull" "Do not pull latest buildroot image" <*> optional (strOptionLongWith "config-options" "'OPTION=VALUE ..'" "Set mock config_opts")@@ -280,11 +334,13 @@ -- was install-deps , Subcommand "builddeps" "Install package build dependencies" $ installDepsCmd- <$> maybeBranchPackages False+ <$> dryrunOpt+ <*> maybeBranchPackages False , Subcommand "install" "Build locally and install package(s)" $ -- FIXME drop --shortcircuit from install? installCmd- <$> quietOpt "Quiet rpmbuild output"+ <$> dryrunOpt+ <*> quietOpt "Quiet rpmbuild output" <*> switchWith 'R' "recurse" "build and install missing deps packages" <*> optional (optionLongWith branchM "from" "BRANCH" "Merge branch first") <*> jobsOpt@@ -310,9 +366,12 @@ bugsCmd <$> optional (strOptionWith 's' "summary" "KEY" "Search for bugs containing keyword") <*> manyPackages+ , Subcommand "prs" "List package PRs" $+ prsCmd+ <$> manyPackages , Subcommand "bump" "Bump release for package" $ bumpCmd- <$> dryrunOpt "Dry run: do not bump"+ <$> dryrunOptDesc "Dry run: do not bump" <*> switchLongWith "strict" "Check koji if NVR was built" <*> optional (strOptionWith 'm' "message" "COMMITMSG" "Specify commit message")@@ -321,7 +380,7 @@ <*> branchesPackages , Subcommand "commit" "Git commit packages" $ commitCmd- <$> dryrunOpt "Dry run: do not commit"+ <$> dryrunOptDesc "Dry run: do not commit" <*> switchWith 'b' "branched" "Commit to branched dist-git" <*> optional commitOpts <*> switchWith '1' "first-line" "use first line of changelog"@@ -337,7 +396,7 @@ <*> manyPackages , Subcommand "push" "Git push packages" $ pushPkgs- <$> dryrunOpt "Dry run: do not push"+ <$> dryrunOptDesc "Dry run: do not push" <*> switchLongWith "no-fetch" "Skip git fetch" <*> optional (strOptionWith 'r' "ref" "COMMITHASH" "git commit to push") <*> branchesPackages@@ -360,7 +419,9 @@ <*> optional (strArg "SPECFILE") , Subcommand "review-package" "Run fedora-review on a package Review Request bug" $ reviewPackage- <$> switchWith 'f' "full" "Download and check package review with fedora-review mock build"+ <$> dryrunOpt+ <*> switchWith 'f' "full" "Download and check package review with fedora-review mock build"+ <*> switchWith 'u' "update" "Retrieve latest packaging from review" <*> optional (pkgArg "PACKAGE/BZID") , Subcommand "reviews" "List package reviews" $ reviewsCmd@@ -390,7 +451,8 @@ requestBranchesCmd <$> quietOpt "Quieter output" <*> switchWith 'r' "reviews" "Request branches for package reviews"- <*> switchLongWith "skip-check" "Skip koji check for branch package"+ <*> switchLongWith "skip-request-check" "Skip check for package branch ticket"+ <*> switchLongWith "skip-koji-check" "Skip koji check for branch package" <*> optional (optionWith branchM 'R' "recurse-from" "BRANCH" "Add neighboring dependencies from branch") <*> mockOpt False <*> branchesPackages@@ -408,7 +470,8 @@ <*> branchesPackages , Subcommand "copr" "Build package(s) in Fedora Copr" $ coprCmd- <$> dryrunOpt "Dry run: do not build"+ <$> dryrunOptDesc "Dry run: do not build"+ <*> debugOpt "Debug output" <*> (flagWith' ListChroots 'l' "list-chroots" "Show project chroots" <|> flagLongWith' CoprNew "new" "Create new copr repo" <|> -- FIXME: NonEmpty String@@ -430,13 +493,14 @@ , Subcommand "graph" "Output dependency graph" $ graphCmd <$> switchWith 'o' "output" "Output graph in gv/dot format"+ <*> switchWith 'd' "deps" "require deps to be installed" <*> optional rpmWithOpt <*> maybeBranchPackages True , Subcommand "repoquery" "Repoquery branches (put repoquery options after '--')" $ repoqueryCmd <$> branchesPackages , Subcommand "ftbfs" "Check FTBFS bug status" $ ftbfsCmd- <$> dryrunOpt "dry run"+ <$> dryrunOptDesc "dry run" <*> switchWith 'l' "short" "Only list packages" <*> optional (flagWith' (FtbfsUser Nothing) 'M' "mine" "Your packages" <|>@@ -457,7 +521,7 @@ <*> manyPackages , Subcommand "tag-build-to-sidetag" "Tag NVR for current branch to sidetag" $ tagBuildToSidetagCmd- <$> dryrunOpt "Dry run"+ <$> dryrunOptDesc "Dry run" <*> switchWith 'k' "allow-dirty" "Allow unclean git repo" <*> optionWith branchM 't' "to" "BRANCH" "Target branch of sidetag" <*> maybeBranchPackages False@@ -533,9 +597,9 @@ branchPkgs args = let (brs,pkgs) = partitionBranches args in case brs of- [] -> error' "specify one branch"+ [] -> error "specify one branch" [br] -> (br,pkgs)- _ -> error' $ "cannot have more than one branch:" +-+ unwords (map showBranch brs)+ _ -> error $ "cannot have more than one branch:" +-+ unwords (map showBranch brs) maybeBranchPackages :: Bool -> Parser (Maybe Branch,[String]) maybeBranchPackages = maybeBranchPackages' Nothing@@ -554,7 +618,7 @@ in case brs of [] -> (Nothing, pkgs) [br] -> (Just br,pkgs)- _ -> error' $ "cannot have more than one branch:" +-+ unwords (map showBranch brs)+ _ -> error $ "cannot have more than one branch:" +-+ unwords (map showBranch brs) extraargdesc = fromMaybe "" mextraarg @@ -572,7 +636,7 @@ in case mbrnchopts of Nothing -> (Branches brs, pkgs) Just req | null brs -> (BranchOpt req, pkgs)- | otherwise -> error' "cannot have branch option and branch list"+ | otherwise -> error "cannot have branch option and branch list" prepPreOpts :: Parser PrepPre prepPreOpts =@@ -603,7 +667,7 @@ <*> optional (sidetagTargetOpt Nothing) <*> overrideOpt <*> waitrepoOpt- <*> dryrunOpt "Dry run: do not merge/push/build"+ <*> dryrunOptDesc "Dry run: do not merge/push/build" <*> skipFetchOpt <*> gitrefOpt <*> updateOpt@@ -634,8 +698,9 @@ archesOpt :: Parser Archs archesOpt = Archs <$> some archOpt <|> ExcludedArchs <$> some excludeArch - dryrunOpt desc = switchWith 'n' "dry-run" desc <|>- switchLongWith "dryrun" "alias for --dry-run"+ dryrunOpt = switchLongWith "dryrun" "Dry run"+ dryrunOptDesc desc = switchWith 'n' "dry-run" desc <|>+ switchLongWith "dryrun" "alias for --dry-run" debugOpt = switchWith 'd' "debug" @@ -654,11 +719,11 @@ updatePair :: Maybe UpdateType -> UpdateSeverity -> (Maybe UpdateType, UpdateSeverity) updatePair (Just SecurityUpdate) SeverityUnspecified =- error' "Security update requires specifying Severity"+ error "Security update requires specifying Severity" updatePair Nothing sev | sev /= SeverityUnspecified =- error' "cannot have --severity with --no-update"+ error "cannot have --severity with --no-update" updatePair (Just TemplateUpdate) sev | sev /= SeverityUnspecified =- error' "Template update cannot have --severity"+ error "Template update cannot have --severity" updatePair ty sv = (ty,sv) forceshortOpt =
src/Package.hs view
@@ -300,12 +300,14 @@ let fetch = have gitOptFetch -- quiet to avoid output before header -- fetch first to include any new branches- when fetch $ gitFetchSilent True+ when fetch $ do+ when (header /= HeaderNone) $ putPkgHdr pkg+ gitFetchSilent True brs <- listOfAnyBranches (haveGit && not (have gitOptHEAD)) (have gitOptActive) breq- when ((header /= HeaderNone || fetch) && dir /= ".") $+ when (header /= HeaderNone && not fetch && dir /= ".") $ case brs of- [br] -> when (fetch || header == HeaderMust) $ putPkgAnyBrnchHdr pkg br- _ -> when (fetch || header /= HeaderNone) $ putPkgHdr pkg+ [br] -> when (header == HeaderMust) $ putPkgAnyBrnchHdr pkg br+ _ -> when (header /= HeaderNone) $ putPkgHdr pkg case limitBranches of ZeroOrOne | length brs > 1 -> -- FIXME: could be handled better (testcase: run long list of packages in wrong directory)@@ -390,14 +392,14 @@ autoReleaseReset :: FilePath -> IO Bool autoReleaseReset spec = do matches <- filter ("Release:" `isPrefixOf`) <$> grep "%autorelease" spec- return $- case matches of- [] -> False- [release] ->- case words release of- ("Release:":"%autorelease":"-b":_) -> True- _ -> False- _ -> error' $ "multiple autorelease fields in" +-+ spec+ case matches of+ [] -> return False+ [release] ->+ return $+ case words release of+ ("Release:":"%autorelease":"-b":_) -> True+ _ -> False+ _ -> error' $ "multiple autorelease fields in" +-+ spec calculateRelease :: FilePath -> IO String calculateRelease spec = do@@ -414,11 +416,10 @@ pkgNameVerRelDist :: Bool -> Maybe Branch -> FilePath -> IO (Maybe NVR) pkgNameVerRelDist _strict Nothing spec = do nvrs <- rpmspec ["--srpm", "--undefine=dist"] (Just "%{name}-%{version}-%{release}") spec- return $- case nvrs of- [] -> Nothing- [nvr] -> maybeNVR nvr- _ -> error' "could not determine unique nvr"+ case nvrs of+ [] -> return Nothing+ [nvr] -> return $ maybeNVR nvr+ _ -> error' "could not determine unique nvr" pkgNameVerRelDist strict (Just br) spec = do disttag <- branchDistTag br -- workaround dist with bootstrap@@ -433,7 +434,7 @@ mfedpkg <- findExecutable "fedpkg" when (isNothing mfedpkg) $ error' "requires fedpkg.."- maybeNVR <$> cmd "fedpkg" ["verrel"]+ maybeNVR <$> fedpkg "verrel" [] else if strict then error' "cannot determine NVR accurately for autorelease outside dist-git"@@ -442,11 +443,10 @@ seq disttag $ do nvrs <- rpmspec ["--srpm"] (Just "%{name}-%{version}-%{release}") spec- return $- case nvrs of- [] -> Nothing- [nvr] -> maybeNVR (replace hostdist disttag nvr)- _ -> error' "could not determine unique nvr"+ case nvrs of+ [] -> return Nothing+ [nvr] -> return $ maybeNVR (replace hostdist disttag nvr)+ _ -> error' "could not determine unique nvr" pkgNameVerRel' :: Branch -> FilePath -> IO NVR pkgNameVerRel' br spec = do
src/Pagure.hs view
@@ -1,30 +1,24 @@ module Pagure ( srcfpo,- pagureio, pagureGroupInfo, pagureGroupRepos, pagureListGitBranches, pagureListProjectIssueTitlesStatus,- IssueTitleStatus(..), pagureProjectInfo, pagureUserRepos, makeItem,- printScmIssue+ pagurePRs ) where -import Common ((+/+), (+-+))-import qualified Common.Text as T+import Common ((+/+)) import Fedora.Pagure+import Fedora.Pagure.Client (projectPRs, OutputFormat(FormatDefault)) srcfpo :: String srcfpo = "src.fedoraproject.org" -pagureio :: String-pagureio = "pagure.io"--printScmIssue :: IssueTitleStatus -> IO ()-printScmIssue issue =- putStrLn $ "https://" ++ pagureio +/+ "releng/fedora-scm-requests" +/+ "issue" +/+ show (pagureIssueId issue) +-+ "(" ++ T.unpack (pagureIssueStatus issue) ++ mclosed ++ "):" +-+ pagureIssueTitle issue- where- mclosed = maybe "" (\s-> ":" ++ T.unpack s) $ pagureIssueCloseStatus issue+-- Package makes circular dep+pagurePRs :: String -> IO ()+pagurePRs pkg =+ projectPRs srcfpo False False FormatDefault False Nothing Nothing Nothing ("rpms" +/+ pkg)
src/RpmBuild.hs view
@@ -113,8 +113,26 @@ then return msourcedir else return Nothing isPkgGit <- isPkgGitRepo- (patches,srcs) <- partitionEithers . map sourcePatchFile- <$> cmdLines "spectool" ["-a", spec]+ (patches,srcs) <- partitionEithers . map sourcePatchFile <$>+ do+ -- can fail in pathological case: eg dl_poly (#74)+ (ok, out, err) <- cmdFull "spectool" ["-a", spec] ""+ if ok+ then return $ lines out+ else do+ warning err+ if isPkgGit then do+ warning "running fedpkg sources first"+ have_sources <- doesFileExist "sources"+ if not have_sources+ then error' "spectool failed to parse sources"+ else do+ fedpkg_ "sources" []+ (ok', out', err') <- cmdFull "spectool" ["-a", spec] ""+ if ok'+ then return $ lines out'+ else error' err'+ else error' "spectool failed to parse sources" forM_ srcs $ \ src -> do exists <- checkCompression src inSrcdir <- doesSourceDirFileExist msrcdir src@@ -131,7 +149,7 @@ else return False mfedpkg <- findExecutable "fedpkg" if uploaded && isJust mfedpkg- then cmd_ "fedpkg" ["sources"]+ then fedpkg_ "sources" [] else do cmd_ "spectool" ["-g", "-S", spec] unlessM (doesFileExist src) $@@ -159,7 +177,7 @@ (case lower (dropWhileEnd isDigit (init f)) of "source" -> Right "patch" -> Left- _ -> error' $! "illegal field:" +-+ f)+ _ -> error $! "illegal field:" +-+ f) -- either url or local file (cannot really have subdir/file) $ takeFileName v @@ -244,7 +262,7 @@ -- prevent Ctrl-c from truncating srpm to corrupted file fmap words . uninterruptibleMask_ $ if autospec- then cmd "fedpkg" $ "srpm" : opts+ then fedpkg "srpm" opts else cmd "rpmbuild" (opts ++ ["-bs", spec]) case filter ("src.rpm" `isExtensionOf`) outs of [srpm] -> do@@ -307,14 +325,14 @@ -- Note does not check if bcond changed -- FIXME check tarball timestamp -- FIXME handle prep (-bp) too?-buildRPMs :: Bool -> Bool -> Bool -> Maybe Natural -> Maybe ForceShort+buildRPMs :: Bool -> Bool -> Bool -> Bool -> Maybe Natural -> Maybe ForceShort -> [BCond] -> [FilePath] -> AnyBranch -> FilePath -> IO Bool-buildRPMs quiet debug noclean mjobs mforceshort bconds rpms br spec = do+buildRPMs dryrun quiet debug noclean mjobs mforceshort bconds rpms br spec = do needBuild <- needToBuildRPMS False mforceshort rpms spec if not needBuild then- putStrLn "Existing rpms are newer than spec file (use --force to rebuild)"+ putStrLn "Existing rpms are newer than spec file (use -f to rebuild)" else do- installDeps True spec+ installDeps dryrun True spec void $ getSources spec distopt <- distOptAny br autoreleaseOpt <- getAutoReleaseOptions spec@@ -355,11 +373,15 @@ putNewLn -- FIXME would like to have pipeOutErr let buildcmd = "rpmbuild" : map quoteArg args- when debug $ putStrLn $ unwords buildcmd- cmdBool "script" ["-c", unwords buildcmd, buildlog]+ when (debug || dryrun) $ putStrLn $ unwords buildcmd+ when dryrun $+ error' "stopped due to dryrun"+ cmdBool "script" ["-e", "-c", unwords buildcmd, buildlog] else do let buildcmd = unwords $ "rpmbuild" : map quoteArg args ++ [">&", buildlog]- when debug $ putStrLn buildcmd+ when (debug || dryrun) $ putStrLn buildcmd+ when dryrun $+ error' "stopped due to dryrun" res <- shellBool buildcmd if res then putStrLn "done"@@ -373,10 +395,10 @@ quoteArg cs = if ' ' `elem` cs then '\'' : cs ++ "'" else cs -buildRPMsNoBranch :: Bool -> Bool -> Bool -> Maybe Natural -> Maybe ForceShort- -> [BCond] -> FilePath -> IO Bool-buildRPMsNoBranch quiet debug noclean mjobs mforceshort bconds spec = do- installDeps True spec+buildRPMsNoBranch :: Bool -> Bool -> Bool -> Bool -> Maybe Natural+ -> Maybe ForceShort -> [BCond] -> FilePath -> IO Bool+buildRPMsNoBranch dryrun quiet debug noclean mjobs mforceshort bconds spec = do+ installDeps dryrun True spec void $ getSources spec sourcediropt <- sourceDirCwdOpt let distopt = ["--define", "dist" +-+ "%{?distprefix}"]@@ -410,11 +432,15 @@ putNewLn -- FIXME would like to have pipeOutErr let buildcmd = "rpmbuild" : map quoteArg args- when debug $ putStrLn $ unwords buildcmd- cmdBool "script" ["-c", unwords buildcmd, buildlog]+ when (debug || dryrun) $ putStrLn $ unwords buildcmd+ when dryrun $+ error' "stopped due to dryrun"+ cmdBool "script" ["-e", "-c", unwords buildcmd, buildlog] else do let buildcmd = unwords $ "rpmbuild" : map quoteArg args ++ [">&", buildlog]- when debug $ putStrLn buildcmd+ when (debug || dryrun) $ putStrLn buildcmd+ when dryrun $+ error' "stopped due to dryrun" res <- shellBool buildcmd if res then putStrLn "done"@@ -425,12 +451,13 @@ return True -- FIXME print unavailable deps-installDeps :: Bool -> FilePath -> IO ()-installDeps strict spec = do+installDeps :: Bool -> Bool -> FilePath -> IO ()+installDeps dryrun strict spec = do missingdeps <- nub <$> (buildRequires spec >>= filterM notInstalled) unless (null missingdeps) $ do putStrLn $ "Running 'dnf install'" +-+ unwords missingdeps- cmd_ "/usr/bin/sudo" $ "/usr/bin/dnf":"install": ["--skip-broken" | not strict] ++ ["--assumeyes"] ++ missingdeps+ unless dryrun $+ cmd_ "/usr/bin/sudo" $ "/usr/bin/dnf":"install": ["--skip-broken" | not strict] ++ ["--assumeyes"] ++ missingdeps installMissingMacros :: FilePath -> IO () installMissingMacros spec = do@@ -484,7 +511,7 @@ where primary dep = case words dep of- [] -> error' "empty dep" -- corner case+ [] -> error "empty dep" -- corner case (('(':h):_) -> Just h (d:_) -> if "rpmlib(" `isPrefixOf` d then Nothing@@ -527,14 +554,14 @@ checkLookasideCache :: String -> IO () checkLookasideCache source = do let lookaside = "https://src.fedoraproject.org/lookaside/pkgs" +/+ unPackage pkg- (file,url) =- case words source of- ("SHA512":('(':fileparen):"=":[hash]) ->- let file' = dropSuffix ")" fileparen- in (file', lookaside +/+ file' +/+ "sha512" +/+ hash +/+ file')- [hash,file'] ->- (file', lookaside +/+ file' +/+ "md5" +/+ hash +/+ file')- _ -> error' $ "invalid/unknown source:\n" ++ source+ (file,url) <-+ case words source of+ ("SHA512":('(':fileparen):"=":[hash]) ->+ let file' = dropSuffix ")" fileparen+ in return (file', lookaside +/+ file' +/+ "sha512" +/+ hash +/+ file')+ [hash,file'] ->+ return (file', lookaside +/+ file' +/+ "md5" +/+ hash +/+ file')+ _ -> error' $ "invalid/unknown source:\n" ++ source unlessM (httpExists' url) $ do putStrLn $ url +-+ "not found" putStrLn $ "uploading" +-+ file +-+ "to lookaside source repo"