fbrnch (empty) → 0.7.1
raw patch · 62 files changed
+9873/−0 lines, 62 filesdep +aesondep +asyncdep +base
Dependencies added: aeson, async, base, bugzilla-redhat, bytestring, config-ini, directory, email-validate, extra, fbrnch, filepath, haxr, http-conduit, http-directory, http-query, lens, lens-aeson, mtl, network-uri, optparse-applicative, pretty-terminal, process, rpmbuild-order, semigroups, simple-cmd, simple-cmd-args, text, time, typed-process, unordered-containers, utf8-string, xdg-basedir
Files
- CHANGELOG.md +288/−0
- LICENSE +339/−0
- README.md +238/−0
- fbrnch.cabal +280/−0
- libs/bodhi-hs/LICENSE +21/−0
- libs/bodhi-hs/src/Fedora/Bodhi.hs +185/−0
- libs/copr-hs/LICENSE +674/−0
- libs/copr-hs/src/Web/Fedora/Copr.hs +35/−0
- libs/copr-hs/src/Web/Fedora/Copr/API.hs +190/−0
- libs/fedora-dists/LICENSE +674/−0
- libs/fedora-dists/src/Distribution/Fedora.hs +216/−0
- libs/fedora-dists/src/Distribution/Fedora/Branch.hs +180/−0
- libs/fedora-dists/src/Distribution/Fedora/Products.hs +52/−0
- libs/fedora-dists/src/Distribution/Fedora/ReadProducts.hs +34/−0
- libs/koji-hs/LICENSE +339/−0
- libs/koji-hs/src/Fedora/Koji.hs +308/−0
- libs/koji-hs/src/Fedora/Koji/Internal.hs +824/−0
- libs/pagure-hs/LICENSE +339/−0
- libs/pagure-hs/src/Fedora/Pagure.hs +236/−0
- libs/pdc-hs/LICENSE +21/−0
- libs/pdc-hs/src/Fedora/PDC.hs +209/−0
- src/Bodhi.hs +70/−0
- src/Branches.hs +163/−0
- src/Bugzilla.hs +410/−0
- src/Cmd/Bugs.hs +21/−0
- src/Cmd/Build.hs +202/−0
- src/Cmd/Bump.hs +48/−0
- src/Cmd/Clone.hs +25/−0
- src/Cmd/Commit.hs +48/−0
- src/Cmd/Copr.hs +156/−0
- src/Cmd/Diff.hs +85/−0
- src/Cmd/Import.hs +93/−0
- src/Cmd/ListBranches.hs +61/−0
- src/Cmd/ListPackages.hs +61/−0
- src/Cmd/Local.hs +143/−0
- src/Cmd/Log.hs +33/−0
- src/Cmd/Merge.hs +69/−0
- src/Cmd/Mock.hs +59/−0
- src/Cmd/Override.hs +33/−0
- src/Cmd/Parallel.hs +241/−0
- src/Cmd/PkgReview.hs +123/−0
- src/Cmd/Pull.hs +15/−0
- src/Cmd/RequestBranch.hs +89/−0
- src/Cmd/RequestRepo.hs +87/−0
- src/Cmd/Reviews.hs +21/−0
- src/Cmd/Scratch.hs +59/−0
- src/Cmd/SideTags.hs +16/−0
- src/Cmd/Status.hs +120/−0
- src/Cmd/Switch.hs +12/−0
- src/Cmd/Update.hs +96/−0
- src/Common.hs +18/−0
- src/Common/System.hs +50/−0
- src/Common/Text.hs +7/−0
- src/Git.hs +172/−0
- src/InterleaveOutput.hs +11/−0
- src/Koji.hs +211/−0
- src/Krb.hs +26/−0
- src/ListReviews.hs +90/−0
- src/Main.hs +265/−0
- src/Package.hs +623/−0
- src/Pagure.hs +28/−0
- src/Prompt.hs +31/−0
+ CHANGELOG.md view
@@ -0,0 +1,288 @@+# Changelog++## 0.7.1 (2021-02-09)+- fix package review urls and also run rpmlint on .spec+- 'master-rename' improvements+- workaround spectool src download bug introduced with 0.7.0.1+- Fedora web service API libraries are now internal libraries++## 0.7.0.1 (2021-02-05)+- Srpm generation: error if spectool fails to download source tarball++## 0.7.0 (2021-02-05)+- reworked branch/pkg arg processing+ which allows `branches --remote` to work without a repo+- 'local'/'install': --with/--without bcond options+- Koji: exit if aborting incomplete build (prevents premature bugzilla comment)+- Bugzilla: updateBug result is Array not Object+- 'build': for a new package use rpm Summary & Url for Bodhi note+- 'build': offer to create a Bodhi update for an already built candidate nvr+- new 'update' command: highly experimental package version updating+- 'diff' now works for a different branch+- 'request-branches' now posts pagure urls to package review too+- 'import' prompts for branching after build+- 'build': --no-prompt replaces --merge+- Git: more readable shortlogs+- 'parallel': only use --background if >5 packages in layer (#17)+- Master branches are now Rawhide+- new 'master-rename' command: renames package master branches to rawhide++## 0.6.9 (2021-01-17)+- PkgReview: use fasid for ssh (#16)+- Bugzilla: separate commentBug from updateBug++## 0.6.8 (2021-01-16)+- build: check bodhi client new update success more carefully+- Bugzilla: correctly check that bug update succeeded+- new 'list' command to list packages from pagure+- branches: add --remote option+- update to latest lts-16.29++## 0.6.7 (2020-12-23)+- Bugzilla: don't conflate POST comment with PUT update+- build/install: allow no branch arg for current directory+- request-repos: prompt for reviewer thanks+- request-repos: added --all-states for Modified+- copr: only output buildargs when build fails++## 0.6.6 (2020-12-17)+- Bugzilla: use POST again for comments...+- copr: print chroots when building++## 0.6.5 (2020-12-03)+- support git worktrees (experimental)+- branches: fix --missing output for given branch and --skip-dead+- git fetching now outputs new branches+- build: only wait-repo if overriding or autoupdate+- koji: improve uploading message+- mock and scratch: --dryrun+- add --all-fedora and --all-epel branch options (#15)++## 0.6.4 (2020-11-12)+- Bugzilla: fix updating of bugs and check for error+- import: offer to request-branches after build+- branches: can now take branch args and --missing option+- request-repo: thank reviewer by first name++## 0.6.3 (2020-10-21)+- new 'branches' command lists package's branches+- copr: fix running in a package dir+- copr: revert restarting failed watch+- mock: fix running in a package dir+- mock: --network option+- improve errors for commands that only take zero or one branches++## 0.6.2 (2020-10-20)+- build: fix bodhi update options error+- merging to latest epel now works (from oldest active fedora branch)+- status: fixed error on new branch+- request-repo: thank reviewer by name+- copr: watch now restarts on a net failure++## 0.6.1 (2020-10-17)+- build, parallel: request testing state for bodhi updates+- bugs: --summary to filter by a phrase+- reviews: --user to list reviews from another user+- reviews: --assigned-to to list bugs by reviewer+- reviews: filter out "Rename Request" and "Re-Review Request" prefixes+- copr: remove trailing / from project name++## Below are pre-release changes from the copr package rpm:++* Fri Oct 9 2020 Jens Petersen <petersen@redhat.com> - 0.6-1 (34223fd)+- accept spec filepaths as package args (#12)+- native Koji wait-repo (#14)+- parallel: now requires --sidetag or --target unless development branch+ - offers bodhi update from side-tag+ - lists koji sidetags natively+ - checks not in pkg dir when multiple packages+- mock: chain multiple package builds+ - Add --no-clean and --no-clean-after+- new 'log' command for comparing branch logs+- new 'override' command+- new 'sidetags' command lists user's sidetags per branch+- Bugzilla: fix body comments not getting posted with PUT (#13)+- status: --no-fetch option+- bump: only if not latest in koji+- merge: assert still in branch after prompt input+- Git short log: use reference format+- copr: detect non-existent project+- Bodhi overrides now display url++* Sun Sep 20 2020 Jens Petersen <petersen@redhat.com> - 0.5-3 (e32fac9)+- new 'bump' command to bump package release+- 'parallel': new --side-tag option to use user's current branch side-tag+- 'build': print nvr and git push as late as possible only if nvr new+- 'bugs' command can now take multiple packages+- wait-repo first without nvr to avoid "nvr not latest" warning+- remove single "- " prefix from changelog for commit+- fix merge prompt text++* Fri Sep 11 2020 Jens Petersen <petersen@redhat.com> - 0.5-2 (1d44bd3)+- copr: error if no chroots+- build,parallel: improve review post/autoupdate and override logic+- reviews: add --branched filter, --short, and --all-status+- scratch: experimental --dry-run and output message before srpm upload+- scratch: add --exclude-arch+- commit: improve checking for changelog+- build: --no-update option+- fetching and switch output pkgdir name+- fix Bugzilla utf8 encoding corruption (when posting reviews, etc)+- new 'command' for running an arbitrary shell command across packages+- diff: --spec-only and --with-branch (use origin if branch not local)+- improve branch error message if package paths/dir wrong+- fix error when detecting autoupdate for master++* Tue Sep 1 2020 Jens Petersen <petersen@redhat.com> - 0.5-1 (41ed229)+- major change: branches are now args preceding package args+- new 'nvr' command+- 'build' doesn't override for Bodhi create_automatic_updates branches+- 'switch'ing to a new branch should work now without explicit pulling+- disallow Fedora branch newer than latest branched release+- 'commit' without -m will try to use rpm changelog+- 'commit' also works in a pkg dir now+- 'create-review' and 'request-branches' can now handle multiple packages++* Fri Aug 21 2020 Jens Petersen <petersen@redhat.com> - 0.4-3 (39edd49)+- check active branches after option parsing (#10)+- `reviews --approved` now limits to NEW, ASSIGNED and POST+- `status -B` now displays new branches+- latest fedora-dists lib uses ~/.fedora/product-versions-2.json++* Sun Aug 16 2020 Jens Petersen <petersen@redhat.com> - 0.4-2 (3d8a9e5)+- rebuild with correct updated cabal.project git deps++* Fri Aug 14 2020 Jens Petersen <petersen@redhat.com> - 0.4-1 (45a590b)+- local commands now work for non-release branches (eg module branches)+- scratch: build by default for branch target+- Koji: check taskstate even if koji watch-task appears to succeed (#9)+- parallel: parallel branch building in a package dir (#6)+- diff: don't git fetch every time+- Koji: abort waiting (do not loop) if task canceled+- fedora-dists: avoid caching PDC error instead of product list+- status: recognize epel testing tags+- Package: warn rather than error if spec filename differs from pkg/dir+- build: don't push Bodhi update for create_automatic_updates releases+- be more careful with creating and comparing NVRs+ - fixing handling for bootstrap bcond (#5)+- parallel: also experimental --dryrun++* Sun Aug 9 2020 Jens Petersen <petersen@redhat.com> - 0.3-5 (98370b7)+- fix handling of failed bugzilla login+- uses http-query for fedora web api libs and bugzilla responses++* Fri Aug 7 2020 Jens Petersen <petersen@redhat.com> - 0.3-4+- strip executable++* Fri Aug 7 2020 Jens Petersen <petersen@redhat.com> - 0.3-3 (a07a33b)+- add 'install-deps' (builddep) command+- experimental --exclude-branch option++* Fri Aug 7 2020 Jens Petersen <petersen@redhat.com> - 0.3-2 (5a44f81)+- local/prep: revert back from using "." for rpmbuild macros dir options++* Thu Aug 6 2020 Jens Petersen <petersen@redhat.com> - 0.3-1 (acb05de)+- install: don't build if existing rpm files newer than spec+ and add --rebuild and --short-circuit options+- use absolute paths for sudo and dnf everywhere+- add 'copr' build command (ported from juhp/cobrnch)++* Wed Aug 5 2020 Jens Petersen <petersen@redhat.com> - 0.2-9 (7499a63)+- improve mock results dir paths like fedpkg++* Wed Aug 5 2020 Jens Petersen <petersen@redhat.com> - 0.2-8 (9462af2)+- support .git file repos also for prepping and building++* Wed Aug 5 2020 Jens Petersen <petersen@redhat.com> - 0.2-7 (d65baee)+- fix srpm generation when _sourcedir is user undefined++* Tue Aug 4 2020 Jens Petersen <petersen@redhat.com> - 0.2-6 (70e945c)+- local: print uninstalled deps+- sort: --with/--without options (rpmbuild-order-0.4.2) (#5)+- support absorbed git submodules (#8)+- build: experimental --dry-run option+- build: Bodhi --update-type option (#7)++* Tue Aug 4 2020 Jens Petersen <petersen@redhat.com> - 0.2-5 (4784a63)+- build now does git fetch and merge of origin+- clone: output package names to show progress+- wait-repo's now show datestamp+- build: maybe override and waitrepo when build already complete+- sort/parallel: update to rpmbuild-order-0.4.1 which also shows any subcycles++* Wed Jul 29 2020 Jens Petersen <petersen@redhat.com> - 0.2-4 (f7a009d)+- parallel: only override when no target or not stable+- parallel: fixed to switch to branch+- update to rpmbuild-0.4.0 release with bugfixes:+ (Provide Name and parse package name dirs with a dot)++* Wed Jul 29 2020 Jens Petersen <petersen@redhat.com> - 0.2-3 (570d531)+- parallel: do override for built package if not tagged (#3)+ - reported by QuLogic+- fix pull command and check for clean working dir+- latest rpmbuild-order fixes a recent regression+- be more lenient when package is in a old branch+- generate a basic manpage with help2man++* Thu Jul 23 2020 Jens Petersen <petersen@redhat.com> - 0.2-2 (9b8982d)+- further simply the option/arg parsing for better error messages++* Wed Jul 22 2020 Jens Petersen <petersen@redhat.com> - 0.2-1 (d8c9a66)+- build/merge/status by default now only act on the current branch+ and require a branch option when more than one package+- use -B or --all-branches to act on all branches like before+- read Koji for correct buildtag for wait-repo+- ignore sources file when not dist-git++* Wed Jul 22 2020 Jens Petersen <petersen@redhat.com> - 0.1-12+- bash completions++* Tue Jul 21 2020 Jens Petersen <petersen@redhat.com> - 0.1-11 (5d9e3af)+- mock: add --root option (takes a branch)++* Tue Jul 21 2020 Jens Petersen <petersen@redhat.com> - 0.1-10 (3a2c181)+- build/parallel: check no existing koji task which is not yet building+- parallel: rpmbuild-order now preserves dir paths to packages+- scratch: allow multiple --arch options++* Sun Jul 19 2020 Jens Petersen <petersen@redhat.com> - 0.1-9 (8492abd)+- 'build' now does wait-repo between packages+- 'build' always checks sources file up to date+- 'build' can now rejoin started builds+- new 'parallel' build command for building packages in dependency layers+- new 'diff' command for checking changes across many packages+- new 'commit' command for committing changes across many packages+- prep now prints nvr+- 'install' handles reinstalls correctly (when only some subpackages installed)+- ignore remote branches other than origin++* Wed Jul 15 2020 Jens Petersen <petersen@redhat.com> - 0.1-8 (e5dd3f3)+- local --short-circuit+- interleaved output for prep and local errors++* Fri Jul 10 2020 Jens Petersen <petersen@redhat.com> - 0.1-7 (981285c)+- build: allow pushing/building before current HEAD+- scratch: add --rebuild-srpm option (default is --no-rebuild-srpm)+- status: allow dirty working dir++* Sat Jul 4 2020 Jens Petersen <petersen@redhat.com> - 0.1-6 (254130a)+- scratch: --arch option and don't get sources too early+- build: drop --scratch+- srpm and mock commands++* Fri Jul 3 2020 Jens Petersen <petersen@redhat.com> - 0.1-5 (7d0e70d)+- 'scratch' build command+- 'build' options --override and --no-fail-fast++* Thu Jul 2 2020 Jens Petersen <petersen@redhat.com> - 0.1-4 (cdeaffb)+- create-review/updatereview: now run rpmlint and optionally mock++* Thu Jul 2 2020 Jens Petersen <petersen@redhat.com> - 0.1-3 (6fd8b0a)+- local, install: install deps++* Wed Jul 1 2020 Jens Petersen <petersen@redhat.com> - 0.1-2 (4612be2)+- prep, local, install: pull down sources now+- add Requires for client tools++* Wed Jul 1 2020 Jens Petersen <petersen@redhat.com> - 0.1-1 (4fe8239)+- initial package
+ LICENSE view
@@ -0,0 +1,339 @@+ GNU GENERAL PUBLIC LICENSE+ Version 2, June 1991++ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA+ Everyone is permitted to copy and distribute verbatim copies+ of this license document, but changing it is not allowed.++ Preamble++ The licenses for most software are designed to take away your+freedom to share and change it. By contrast, the GNU General Public+License is intended to guarantee your freedom to share and change free+software--to make sure the software is free for all its users. This+General Public License applies to most of the Free Software+Foundation's software and to any other program whose authors commit to+using it. (Some other Free Software Foundation software is covered by+the GNU Lesser General Public License instead.) You can apply it to+your programs, too.++ When we speak of free software, we are referring to freedom, not+price. Our General Public Licenses are designed to make sure that you+have the freedom to distribute copies of free software (and charge for+this service if you wish), that you receive source code or can get it+if you want it, that you can change the software or use pieces of it+in new free programs; and that you know you can do these things.++ To protect your rights, we need to make restrictions that forbid+anyone to deny you these rights or to ask you to surrender the rights.+These restrictions translate to certain responsibilities for you if you+distribute copies of the software, or if you modify it.++ For example, if you distribute copies of such a program, whether+gratis or for a fee, you must give the recipients all the rights that+you have. You must make sure that they, too, receive or can get the+source code. And you must show them these terms so they know their+rights.++ We protect your rights with two steps: (1) copyright the software, and+(2) offer you this license which gives you legal permission to copy,+distribute and/or modify the software.++ Also, for each author's protection and ours, we want to make certain+that everyone understands that there is no warranty for this free+software. If the software is modified by someone else and passed on, we+want its recipients to know that what they have is not the original, so+that any problems introduced by others will not reflect on the original+authors' reputations.++ Finally, any free program is threatened constantly by software+patents. We wish to avoid the danger that redistributors of a free+program will individually obtain patent licenses, in effect making the+program proprietary. To prevent this, we have made it clear that any+patent must be licensed for everyone's free use or not licensed at all.++ The precise terms and conditions for copying, distribution and+modification follow.++ GNU GENERAL PUBLIC LICENSE+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION++ 0. This License applies to any program or other work which contains+a notice placed by the copyright holder saying it may be distributed+under the terms of this General Public License. The "Program", below,+refers to any such program or work, and a "work based on the Program"+means either the Program or any derivative work under copyright law:+that is to say, a work containing the Program or a portion of it,+either verbatim or with modifications and/or translated into another+language. (Hereinafter, translation is included without limitation in+the term "modification".) Each licensee is addressed as "you".++Activities other than copying, distribution and modification are not+covered by this License; they are outside its scope. The act of+running the Program is not restricted, and the output from the Program+is covered only if its contents constitute a work based on the+Program (independent of having been made by running the Program).+Whether that is true depends on what the Program does.++ 1. You may copy and distribute verbatim copies of the Program's+source code as you receive it, in any medium, provided that you+conspicuously and appropriately publish on each copy an appropriate+copyright notice and disclaimer of warranty; keep intact all the+notices that refer to this License and to the absence of any warranty;+and give any other recipients of the Program a copy of this License+along with the Program.++You may charge a fee for the physical act of transferring a copy, and+you may at your option offer warranty protection in exchange for a fee.++ 2. You may modify your copy or copies of the Program or any portion+of it, thus forming a work based on the Program, and copy and+distribute such modifications or work under the terms of Section 1+above, provided that you also meet all of these conditions:++ a) You must cause the modified files to carry prominent notices+ stating that you changed the files and the date of any change.++ b) You must cause any work that you distribute or publish, that in+ whole or in part contains or is derived from the Program or any+ part thereof, to be licensed as a whole at no charge to all third+ parties under the terms of this License.++ c) If the modified program normally reads commands interactively+ when run, you must cause it, when started running for such+ interactive use in the most ordinary way, to print or display an+ announcement including an appropriate copyright notice and a+ notice that there is no warranty (or else, saying that you provide+ a warranty) and that users may redistribute the program under+ these conditions, and telling the user how to view a copy of this+ License. (Exception: if the Program itself is interactive but+ does not normally print such an announcement, your work based on+ the Program is not required to print an announcement.)++These requirements apply to the modified work as a whole. If+identifiable sections of that work are not derived from the Program,+and can be reasonably considered independent and separate works in+themselves, then this License, and its terms, do not apply to those+sections when you distribute them as separate works. But when you+distribute the same sections as part of a whole which is a work based+on the Program, the distribution of the whole must be on the terms of+this License, whose permissions for other licensees extend to the+entire whole, and thus to each and every part regardless of who wrote it.++Thus, it is not the intent of this section to claim rights or contest+your rights to work written entirely by you; rather, the intent is to+exercise the right to control the distribution of derivative or+collective works based on the Program.++In addition, mere aggregation of another work not based on the Program+with the Program (or with a work based on the Program) on a volume of+a storage or distribution medium does not bring the other work under+the scope of this License.++ 3. You may copy and distribute the Program (or a work based on it,+under Section 2) in object code or executable form under the terms of+Sections 1 and 2 above provided that you also do one of the following:++ a) Accompany it with the complete corresponding machine-readable+ source code, which must be distributed under the terms of Sections+ 1 and 2 above on a medium customarily used for software interchange; or,++ b) Accompany it with a written offer, valid for at least three+ years, to give any third party, for a charge no more than your+ cost of physically performing source distribution, a complete+ machine-readable copy of the corresponding source code, to be+ distributed under the terms of Sections 1 and 2 above on a medium+ customarily used for software interchange; or,++ c) Accompany it with the information you received as to the offer+ to distribute corresponding source code. (This alternative is+ allowed only for noncommercial distribution and only if you+ received the program in object code or executable form with such+ an offer, in accord with Subsection b above.)++The source code for a work means the preferred form of the work for+making modifications to it. For an executable work, complete source+code means all the source code for all modules it contains, plus any+associated interface definition files, plus the scripts used to+control compilation and installation of the executable. However, as a+special exception, the source code distributed need not include+anything that is normally distributed (in either source or binary+form) with the major components (compiler, kernel, and so on) of the+operating system on which the executable runs, unless that component+itself accompanies the executable.++If distribution of executable or object code is made by offering+access to copy from a designated place, then offering equivalent+access to copy the source code from the same place counts as+distribution of the source code, even though third parties are not+compelled to copy the source along with the object code.++ 4. You may not copy, modify, sublicense, or distribute the Program+except as expressly provided under this License. Any attempt+otherwise to copy, modify, sublicense or distribute the Program is+void, and will automatically terminate your rights under this License.+However, parties who have received copies, or rights, from you under+this License will not have their licenses terminated so long as such+parties remain in full compliance.++ 5. You are not required to accept this License, since you have not+signed it. However, nothing else grants you permission to modify or+distribute the Program or its derivative works. These actions are+prohibited by law if you do not accept this License. Therefore, by+modifying or distributing the Program (or any work based on the+Program), you indicate your acceptance of this License to do so, and+all its terms and conditions for copying, distributing or modifying+the Program or works based on it.++ 6. Each time you redistribute the Program (or any work based on the+Program), the recipient automatically receives a license from the+original licensor to copy, distribute or modify the Program subject to+these terms and conditions. You may not impose any further+restrictions on the recipients' exercise of the rights granted herein.+You are not responsible for enforcing compliance by third parties to+this License.++ 7. If, as a consequence of a court judgment or allegation of patent+infringement or for any other reason (not limited to patent issues),+conditions are imposed on you (whether by court order, agreement or+otherwise) that contradict the conditions of this License, they do not+excuse you from the conditions of this License. If you cannot+distribute so as to satisfy simultaneously your obligations under this+License and any other pertinent obligations, then as a consequence you+may not distribute the Program at all. For example, if a patent+license would not permit royalty-free redistribution of the Program by+all those who receive copies directly or indirectly through you, then+the only way you could satisfy both it and this License would be to+refrain entirely from distribution of the Program.++If any portion of this section is held invalid or unenforceable under+any particular circumstance, the balance of the section is intended to+apply and the section as a whole is intended to apply in other+circumstances.++It is not the purpose of this section to induce you to infringe any+patents or other property right claims or to contest validity of any+such claims; this section has the sole purpose of protecting the+integrity of the free software distribution system, which is+implemented by public license practices. Many people have made+generous contributions to the wide range of software distributed+through that system in reliance on consistent application of that+system; it is up to the author/donor to decide if he or she is willing+to distribute software through any other system and a licensee cannot+impose that choice.++This section is intended to make thoroughly clear what is believed to+be a consequence of the rest of this License.++ 8. If the distribution and/or use of the Program is restricted in+certain countries either by patents or by copyrighted interfaces, the+original copyright holder who places the Program under this License+may add an explicit geographical distribution limitation excluding+those countries, so that distribution is permitted only in or among+countries not thus excluded. In such case, this License incorporates+the limitation as if written in the body of this License.++ 9. The Free Software Foundation may publish revised and/or new versions+of the General Public License from time to time. Such new versions will+be similar in spirit to the present version, but may differ in detail to+address new problems or concerns.++Each version is given a distinguishing version number. If the Program+specifies a version number of this License which applies to it and "any+later version", you have the option of following the terms and conditions+either of that version or of any later version published by the Free+Software Foundation. If the Program does not specify a version number of+this License, you may choose any version ever published by the Free Software+Foundation.++ 10. If you wish to incorporate parts of the Program into other free+programs whose distribution conditions are different, write to the author+to ask for permission. For software which is copyrighted by the Free+Software Foundation, write to the Free Software Foundation; we sometimes+make exceptions for this. Our decision will be guided by the two goals+of preserving the free status of all derivatives of our free software and+of promoting the sharing and reuse of software generally.++ NO WARRANTY++ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,+REPAIR OR CORRECTION.++ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE+POSSIBILITY OF SUCH DAMAGES.++ END OF TERMS AND CONDITIONS++ How to Apply These Terms to Your New Programs++ If you develop a new program, and you want it to be of the greatest+possible use to the public, the best way to achieve this is to make it+free software which everyone can redistribute and change under these terms.++ To do so, attach the following notices to the program. It is safest+to attach them to the start of each source file to most effectively+convey the exclusion of warranty; and each file should have at least+the "copyright" line and a pointer to where the full notice is found.++ <one line to give the program's name and a brief idea of what it does.>+ Copyright (C) <year> <name of author>++ This program is free software; you can redistribute it and/or modify+ it under the terms of the GNU General Public License as published by+ the Free Software Foundation; either version 2 of the License, or+ (at your option) any later version.++ This program is distributed in the hope that it will be useful,+ but WITHOUT ANY WARRANTY; without even the implied warranty of+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ GNU General Public License for more details.++ You should have received a copy of the GNU General Public License along+ with this program; if not, write to the Free Software Foundation, Inc.,+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.++Also add information on how to contact you by electronic and paper mail.++If the program is interactive, make it output a short notice like this+when it starts in an interactive mode:++ Gnomovision version 69, Copyright (C) year name of author+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.+ This is free software, and you are welcome to redistribute it+ under certain conditions; type `show c' for details.++The hypothetical commands `show w' and `show c' should show the appropriate+parts of the General Public License. Of course, the commands you use may+be called something other than `show w' and `show c'; they could even be+mouse-clicks or menu items--whatever suits your program.++You should also get your employer (if you work as a programmer) or your+school, if any, to sign a "copyright disclaimer" for the program, if+necessary. Here is a sample; alter the names:++ Yoyodyne, Inc., hereby disclaims all copyright interest in the program+ `Gnomovision' (which makes passes at compilers) written by James Hacker.++ <signature of Ty Coon>, 1 April 1989+ Ty Coon, President of Vice++This General Public License does not permit incorporating your program into+proprietary programs. If your program is a subroutine library, you may+consider it more useful to permit linking proprietary applications with the+library. If this is what you want to do, use the GNU Lesser General+Public License instead of this License.
+ README.md view
@@ -0,0 +1,238 @@+# fbrnch - "Fed Brunch"++[](LICENSE)+[](https://github.com/juhp/fbrnch/actions)+[](https://hackage.haskell.org/package/fbrnch)++A tool to help Fedora Packagers build package branches and add new packages.++Fedora developers use a lot of time building packages across releases+and workflow for adding new packages, etc. The motivation for fbrnch is+to help to (semi-)automate common workflows to save time and effort.++fbrnch is distributed under the GPL license version 2 or later.++## Description+`fbrnch` is a Fedora Packager client which tries to automate some common tasks+like:++- merging and building a package across release branches+- automatic parallel builds of sets of packages in dependency order+- creating, updating and listing package reviews+- requesting new repos and branches+- importing new packages+- progressive copr builds+- rename master branches to rawhide++and more.++## Usage++### Creating new packages/branches++#### Creating a new package+```+$ fbrnch create-review [my-new-package]+```+This will create (or update) an srpm, run rpmlint,+then upload it to fedorapeople, perform a scratch build,+and open a Review Request in Bugzilla (similar to fedora-create-review).++#### Update a package review+```+$ fbrnch update-review [my-new-package]+```+Similar to create-review: uploads to fedorapeople and posts+updated package links to the open package review.++#### List open package reviews+```+$ fbrnch reviews+```+This lists one's open package reviews.+Various options like `--approved` or `--created` allow filtering by status.++One can also search for reviews with:+```+$ fbrnch find-review package-name+```++#### Request repos+Once a review has been approved+```+$ fbrnch request-repos+```+will request repos for approved package(s).++#### Import a new package+With fbrnch this can be done in one step - no need to clone first.+```+$ fbrnch import [my-new-package]+```+will offer to import the srpm from the approved review+(similar to `fedpkg import`).+Without any arguments it will offer to import any approved package reviews+one by one.+The imported package is then built in Koji Rawhide,+and the package review updated.++#### Request branches+Finally you can request branches with+```+$ fbrnch request-branches+```+which will confirm which branches you want, unless given.++Optionally a mock build can be done first.+++### Building+#### Cloning and switching branch+```+$ fbrnch clone [package] ...+```+(one can also clone all one's packages or another user's packages).++```+$ fbrnch switch f33 [package] ...+```++You can also git pull:+```+$ fbrnch pull [package] ...+```+#### Package status+```+$ fbrnch status -B [package]+```+outputs information about the status of each branch.+The status command can also be used with `--reviews`+to check the build status of new packages.++List package bugs:+```+$ fbrnch bugs [package]+```++#### Commit, Merging and Building in Koji+You can commit to the current branch:+```+$ fbrnch commit+```+uses any rpm changelog, or you can pass `-m "..."` or amend with `-a`.++You can merge branches with:+```+$ fbrnch merge f32 package+```+which will offer to merge f33 (or some of it) into f32.++Merging can also be done together with building:+```+$ fbrnch build f33 package+```+will offer to merge newer commits from the newer branch.+If the branch NVR is also ready pushed and built it will be skipped.+Branch builds are pushed to Bodhi.++You can also build all branches:+```+$ fbrnch build -B package+```++Scratch builds can also be done:+```+$ fbrnch scratch rawhide+```+optionally a different koji target can be given.++You can sort packages by build dependency order:+```+$ fbrnch sort rawhide package1 package2 package3 package4 ...+```++### Local commands+```+$ fbrnch prep rawhide package+```++Build locally:+```+$ fbrnch local+```+this works in the current package dir like other commands+and one can also specify package.++Locally build and install:+```+$ fbrnch install package1 package2 package3 ...+```++### Parallel building+fbrnch can automatically sort packages and build them in parallel+in Koji in dependency layers (using low-priority background builds+to avoid grabbing too many Koji resources).++```+$ fbrnch parallel --sidetag rawhide pkg-x pkg-y pkg-z pkg-xy pkg-xyz+```+builds a list of packages in parallel ordered by build dependencies.++Note it requires a sidetag in general, so you need to manage and select them+if using more than one per branch with `--target`.++### Other commands+There are more commands like `nvr`, `install-deps`, `copr`.++See `fbrnch --help` for details and the full list.++## Known issues+- parallel builds will push local package commits without asking+- currently only checks if already built by NVR not githash+- authentication is not implemented yet natively for Koji, Bodhi, Pagure+ (and source upload)+ - so python clients are used for "writing"+ (specifically koji, bodhi-client, fedpkg),+ but all queries are done directly by Web RPC for speed and control.++## Motivation and history+This project started off (as "fedbrnch") basically as a simple tool to+build a package across branches (ie for current releases). Then bugzilla+and Bodhi integration was added, and gradually more features, including+some generic commands across packages which had already been done before+in fedora-haskell-tools.++## Installation+On Fedora the easiest way to install is using my [copr repo](https://copr.fedorainfracloud.org/coprs/petersen/fbrnch/).++## Build from source+1. Install openssl-devel++2. Clone the git repo and in the source dir, setup the git submodules:++`git submodule update --init`++3. Then either:++a) using stack >= 2.1: `stack install`++or++b) with cabal-install (probably 2.4 or later) and cabal-rpm:++```+$ cabal-rpm builddep+$ cabal new-install --installdir=~/bin+```++## Contributing+Bug reports, feedback, and fixes are welcome.++See the TODO list and also the many FIXME comments scattered across the source.+It is better to ask before embarking on large changes.++## Usual disclaimer+This is still in active development.+While it is generally works well for me,+if it should breaks things for you, you get to keep the pieces. :)+But please do report unsupported or unintuitive workflows.
+ fbrnch.cabal view
@@ -0,0 +1,280 @@+cabal-version: 2.0+name: fbrnch+version: 0.7.1+synopsis: Build and create Fedora package repos and branches+description:+ fbrnch is a convenient packaging tool for Fedora Packagers,+ with integration for Bugzilla, Koji, and Bodhi.+ .+ Features include:+ .+ - merging and building a package across release branches+ .+ - automatic parallel builds of sets of packages in dependency order+ .+ - creating, updating and listing one's package reviews+ .+ - requesting repos for new approved packages and branch requests+ .+ - import srpms from package reviews+ .+ - progressive copr builds+ .+ - and many more commands.+homepage: https://github.com/juhp/fbrnch+bug-reports: https://github.com/juhp/fbrnch/issues+license: GPL-2+license-file: LICENSE+author: Jens Petersen+maintainer: petersen@fedoraproject.org+copyright: 2019-2021 Jens Petersen+category: Utility+build-type: Simple+extra-doc-files: CHANGELOG.md+ README.md+ libs/bodhi-hs/LICENSE+ libs/copr-hs/LICENSE+ libs/fedora-dists/LICENSE+ libs/koji-hs/LICENSE+ libs/pagure-hs/LICENSE+ libs/pdc-hs/LICENSE+tested-with: GHC == 7.10.3, GHC == 8.0.2, GHC == 8.2.2, GHC == 8.4.4,+ GHC == 8.6.5, GHC == 8.8.4, GHC == 8.10.3++source-repository head+ type: git+ location: https://github.com/juhp/fbrnch.git++executable fbrnch+ main-is: Main.hs+ autogen-modules: Paths_fbrnch+ other-modules: Bodhi+ Branches+ Bugzilla+ Cmd.Bugs+ Cmd.Build+ Cmd.Bump+ Cmd.Clone+ Cmd.Commit+ Cmd.Copr+ Cmd.Diff+ Cmd.Import+ Cmd.ListBranches+ Cmd.ListPackages+ Cmd.Local+ Cmd.Log+ Cmd.Merge+ Cmd.Mock+ Cmd.Override+ Cmd.Parallel+ Cmd.PkgReview+ Cmd.Pull+ Cmd.RequestBranch+ Cmd.RequestRepo+ Cmd.Reviews+ Cmd.Scratch+ Cmd.SideTags+ Cmd.Status+ Cmd.Switch+ Cmd.Update+ Common+ Common.System+ Common.Text+ Git+ InterleaveOutput+ Koji+ Krb+ ListReviews+ Package+ Pagure+ Paths_fbrnch+ Prompt+ hs-source-dirs: src+ default-language: Haskell2010++ build-depends: aeson+ , async+ , base < 5+ , bodhi-internal+ , bugzilla-redhat >= 0.3+ , bytestring+ , config-ini+ , copr-internal+ , directory >= 1.2.3+ , email-validate+ , extra+ , fedora-dists-internal+ -- > 2.0+ , filepath+ , http-conduit+ , http-directory >= 0.1.5+ , http-query+ , koji-internal+ , network-uri+ , optparse-applicative+ , pagure-internal+ , pretty-terminal+ , process+ , rpmbuild-order >= 0.4.2+ , simple-cmd >= 0.2.0+ , simple-cmd-args >= 0.1.6+ , text+ , time+ , typed-process >= 0.2.4.0+ , utf8-string+ , xdg-basedir+ if impl(ghc<8.0)+ build-depends: semigroups++ ghc-options: -threaded+ -Wall+ -Wcompat+ -Widentities+ -Wincomplete-uni-patterns+ -Wincomplete-record-updates+ if impl(ghc >= 8.0)+ ghc-options: -Wredundant-constraints+ if impl(ghc >= 8.2)+ ghc-options: -fhide-source-paths+ if impl(ghc >= 8.4)+ ghc-options: -Wmissing-export-lists+ -Wpartial-fields+ if impl(ghc >= 8.10)+ ghc-options: -Wunused-packages+++library bodhi-internal+ build-depends: aeson+ , base >= 4 && < 5+ , http-query+ , text+ , time+ , lens, lens-aeson+ default-language: Haskell2010+ default-extensions: OverloadedStrings+ hs-source-dirs: libs/bodhi-hs/src+ exposed-modules: Fedora.Bodhi+ ghc-options: -Wall+ if impl(ghc >= 8.0)+ ghc-options: -Wcompat+ -Widentities+ -Wincomplete-uni-patterns+ -Wincomplete-record-updates+ -Wredundant-constraints+ if impl(ghc >= 8.2)+ ghc-options: -fhide-source-paths+ if impl(ghc >= 8.4)+ ghc-options: -Wmissing-export-lists+ -Wpartial-fields++library copr-internal+ default-language: Haskell2010+ exposed-modules: Web.Fedora.Copr+ Web.Fedora.Copr.API+ hs-source-dirs: libs/copr-hs/src+ build-depends:+ base >= 4.7 && <5+ , aeson+ , bytestring+ , directory+ , http-query+ , text+ , unordered-containers+ ghc-options: -Wall+ if impl(ghc >= 8.0)+ ghc-options: -Wcompat+ -Widentities+ -Wincomplete-uni-patterns+ -Wincomplete-record-updates+ -Wredundant-constraints+ if impl(ghc >= 8.2)+ ghc-options: -fhide-source-paths+ if impl(ghc >= 8.4)+ ghc-options: -Wmissing-export-lists+ -Wpartial-fields++library fedora-dists-internal+ exposed-modules: Distribution.Fedora+ Distribution.Fedora.Branch+ other-modules: Distribution.Fedora.Products+ Distribution.Fedora.ReadProducts+ hs-source-dirs: libs/fedora-dists/src+ build-depends: base >= 4.6 && < 5+ , aeson+ , bytestring+ , directory+ , filepath+ , pdc-internal+ , text+ , time+ default-language: Haskell2010+ ghc-options: -Wall+ if impl(ghc >= 8.0)+ ghc-options: -Wcompat+ -Widentities+ -Wincomplete-uni-patterns+ -Wincomplete-record-updates+ -Wredundant-constraints+ if impl(ghc >= 8.2)+ ghc-options: -fhide-source-paths+ if impl(ghc >= 8.4)+ ghc-options: -Wmissing-export-lists+ -Wpartial-fields+++library koji-internal+ hs-source-dirs: libs/koji-hs/src+ exposed-modules: Fedora.Koji+ Fedora.Koji.Internal++ build-depends: base >= 4 && < 5+ , haxr >= 3000.11.4+ , mtl+ default-language: Haskell2010+ default-extensions: OverloadedStrings+ ghc-options: -Wall++library pagure-internal+ build-depends: aeson+ , base >= 4 && < 5+ , http-query+ , text+ , lens, lens-aeson+ default-language: Haskell2010+ default-extensions: OverloadedStrings+ hs-source-dirs: libs/pagure-hs/src+ exposed-modules: Fedora.Pagure+ ghc-options: -Wall+ if impl(ghc >= 8.0)+ ghc-options: -Wcompat+ -Widentities+ -Wincomplete-uni-patterns+ -Wincomplete-record-updates+ -Wredundant-constraints+ if impl(ghc >= 8.2)+ ghc-options: -fhide-source-paths+ if impl(ghc >= 8.4)+ ghc-options: -Wmissing-export-lists+ -Wpartial-fields++library pdc-internal+ build-depends: aeson+ , base >= 4 && < 5+ , http-query+ , text+ , time+ default-language: Haskell2010+ exposed-modules: Fedora.PDC+ hs-source-dirs: libs/pdc-hs/src+ ghc-options: -Wall+ if impl(ghc >= 8.0)+ ghc-options: -Wcompat+ -Widentities+ -Wincomplete-uni-patterns+ -Wincomplete-record-updates+ -Wredundant-constraints+ if impl(ghc >= 8.2)+ ghc-options: -fhide-source-paths+ if impl(ghc >= 8.4)+ ghc-options: -Wmissing-export-lists+ -Wpartial-fields
+ libs/bodhi-hs/LICENSE view
@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2020 Jens Petersen++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.
+ libs/bodhi-hs/src/Fedora/Bodhi.hs view
@@ -0,0 +1,185 @@+{-# LANGUAGE CPP #-}++{- |+Copyright: (c) 2020 Jens Petersen+SPDX-License-Identifier: MIT+Maintainer: Jens Petersen <juhpetersen@gmail.com>++Fedora Bodhi REST client library+-}++module Fedora.Bodhi+ ( bodhiBuild+ , bodhiBuilds+ , bodhiComment+ , bodhiComments+ , bodhiCSRF+ , bodhiOverride+ , bodhiOverrides+ , bodhiOverrideDates+ , bodhiPackages+ , bodhiRelease+ , bodhiReleases+ , bodhiUpdate+ , bodhiUpdates+ , bodhiUser+ , bodhiUsers+ , lookupKey+ , lookupKey'+ , queryBodhi+ , makeKey+ , makeItem+ , maybeKey+ , Query+ , QueryItem+ ) where++#if (defined(VERSION_lens_aeson))+import Control.Lens+import Data.Aeson.Lens+#else+import Lens.Micro+import Lens.Micro.Aeson+#endif+import Data.Aeson.Types+import Data.Text (Text)+import Data.Time.LocalTime+import Network.HTTP.Query++server :: String+server = "bodhi.fedoraproject.org"++-- | Returns build JSON for NVR+--+-- https://bodhi.fedoraproject.org/docs/server_api/rest/builds.html#service-0+bodhiBuild :: String -> IO Object+bodhiBuild nvr = do+ res <- queryBodhi [] $ "builds" +/+ nvr+ return $ res ^. _Object++-- | returns JSON list of builds+--+-- https://bodhi.fedoraproject.org/docs/server_api/rest/builds.html#service-1+bodhiBuilds :: Query -> IO [Object]+bodhiBuilds params = do+ res <- queryBodhi params "builds/"+ return $ res ^.. key "builds" . values . _Object++-- | Returns comment JSON for id+--+-- https://bodhi.fedoraproject.org/docs/server_api/rest/comments.html#service-0+bodhiComment :: String -> IO Object+bodhiComment cid = do+ res <- queryBodhi [] $ "comments" +/+ cid+ return $ res ^. _Object++-- | returns JSON list of comments+--+-- https://bodhi.fedoraproject.org/docs/server_api/rest/comments.html#service-1+bodhiComments :: Query -> IO [Object]+bodhiComments params = do+ res <- queryBodhi params "comments/"+ return $ res ^.. key "comments" . values . _Object++-- | Get CSRF token+--+-- https://bodhi.fedoraproject.org/docs/server_api/rest/csrf.html+bodhiCSRF :: IO (Maybe Text)+bodhiCSRF = do+ res <- queryBodhi [] "csrf"+ return $ res ^? key "csrf_token" . _String++-- | Returns override JSON for NVR+--+-- https://bodhi.fedoraproject.org/docs/server_api/rest/overrides.html#service-0+bodhiOverride :: String -> IO (Maybe Object)+bodhiOverride nvr = do+ res <- queryBodhi [] $ "overrides" +/+ nvr+ return $ res ^? key "override" . _Object++-- | Returns override expiration and submission dates for NVR+bodhiOverrideDates :: String -> IO (Maybe (LocalTime,LocalTime))+bodhiOverrideDates nvr = do+ mobj <- bodhiOverride nvr+ case mobj of+ Nothing -> do+ putStrLn $ "Override for " ++ nvr ++ " not found"+ return Nothing+ Just obj -> return $ readDates obj+ where+ readDates :: Object -> Maybe (LocalTime,LocalTime)+ readDates =+ parseMaybe $ \obj -> do+ expire <- obj .: "expiration_date"+ submit <- obj .: "submission_date"+ return (expire,submit)++-- | returns JSON list of overrides+--+-- https://bodhi.fedoraproject.org/docs/server_api/rest/overrides.html#service-1+bodhiOverrides :: Query -> IO [Object]+bodhiOverrides params = do+ res <- queryBodhi params "overrides/"+ return $ res ^.. key "overrides" . values . _Object++-- | Packages query+--+-- https://bodhi.fedoraproject.org/docs/server_api/rest/packages.html#service-0+bodhiPackages :: Query -> IO [Object]+bodhiPackages params = do+ res <- queryBodhi params "packages/"+ return $ res ^.. key "packages" . values . _Object++-- | read releases metadata from Bodhi+--+-- https://bodhi.fedoraproject.org/docs/server_api/rest/releases.html#service-0+bodhiRelease :: String -> IO Object+bodhiRelease rel = do+ res <- queryBodhi [] $ "releases" +/+ rel+ return $ res ^. _Object++-- | read releases metadata from Bodhi+--+-- https://bodhi.fedoraproject.org/docs/server_api/rest/releases.html#service-1+bodhiReleases :: Query -> IO [Object]+bodhiReleases params = do+ res <- queryBodhi params "releases/"+ return $ res ^.. key "releases" . values . _Object++-- | read an update from Bodhi+--+-- https://bodhi.fedoraproject.org/docs/server_api/rest/updates.html#service-0+bodhiUpdate :: String -> IO (Maybe Object)+bodhiUpdate update = do+ res <- queryBodhi [] $ "updates" +/+ update+ return $ res ^? key "update" . _Object++-- | search for updates on Bodhi+--+-- https://bodhi.fedoraproject.org/docs/server_api/rest/updates.html#service-2+bodhiUpdates :: Query -> IO [Object]+bodhiUpdates params = do+ res <- queryBodhi params "updates/"+ return $ res ^.. key "updates" . values . _Object++-- | user info from Bodhi+--+-- https://bodhi.fedoraproject.org/docs/server_api/rest/users.html#service-0+bodhiUser :: String -> IO Object+bodhiUser user = do+ res <- queryBodhi [] $ "users" +/+ user+ return $ res ^. _Object++-- | list users from Bodhi+--+-- https://bodhi.fedoraproject.org/docs/server_api/rest/users.html#service-1+bodhiUsers :: Query -> IO [Object]+bodhiUsers params = do+ res <- queryBodhi params "users/"+ return $ res ^.. key "users" . values . _Object++-- | low-level query+queryBodhi :: Query -> String -> IO Value+queryBodhi params path =+ let url = "https://" ++ server +/+ path+ in webAPIQuery url params
+ libs/copr-hs/LICENSE view
@@ -0,0 +1,674 @@+ GNU GENERAL PUBLIC LICENSE+ Version 3, 29 June 2007++ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>+ Everyone is permitted to copy and distribute verbatim copies+ of this license document, but changing it is not allowed.++ Preamble++ The GNU General Public License is a free, copyleft license for+software and other kinds of works.++ The licenses for most software and other practical works are designed+to take away your freedom to share and change the works. By contrast,+the GNU General Public License is intended to guarantee your freedom to+share and change all versions of a program--to make sure it remains free+software for all its users. We, the Free Software Foundation, use the+GNU General Public License for most of our software; it applies also to+any other work released this way by its authors. You can apply it to+your programs, too.++ When we speak of free software, we are referring to freedom, not+price. Our General Public Licenses are designed to make sure that you+have the freedom to distribute copies of free software (and charge for+them if you wish), that you receive source code or can get it if you+want it, that you can change the software or use pieces of it in new+free programs, and that you know you can do these things.++ To protect your rights, we need to prevent others from denying you+these rights or asking you to surrender the rights. Therefore, you have+certain responsibilities if you distribute copies of the software, or if+you modify it: responsibilities to respect the freedom of others.++ For example, if you distribute copies of such a program, whether+gratis or for a fee, you must pass on to the recipients the same+freedoms that you received. You must make sure that they, too, receive+or can get the source code. And you must show them these terms so they+know their rights.++ Developers that use the GNU GPL protect your rights with two steps:+(1) assert copyright on the software, and (2) offer you this License+giving you legal permission to copy, distribute and/or modify it.++ For the developers' and authors' protection, the GPL clearly explains+that there is no warranty for this free software. For both users' and+authors' sake, the GPL requires that modified versions be marked as+changed, so that their problems will not be attributed erroneously to+authors of previous versions.++ Some devices are designed to deny users access to install or run+modified versions of the software inside them, although the manufacturer+can do so. This is fundamentally incompatible with the aim of+protecting users' freedom to change the software. The systematic+pattern of such abuse occurs in the area of products for individuals to+use, which is precisely where it is most unacceptable. Therefore, we+have designed this version of the GPL to prohibit the practice for those+products. If such problems arise substantially in other domains, we+stand ready to extend this provision to those domains in future versions+of the GPL, as needed to protect the freedom of users.++ Finally, every program is threatened constantly by software patents.+States should not allow patents to restrict development and use of+software on general-purpose computers, but in those that do, we wish to+avoid the special danger that patents applied to a free program could+make it effectively proprietary. To prevent this, the GPL assures that+patents cannot be used to render the program non-free.++ The precise terms and conditions for copying, distribution and+modification follow.++ TERMS AND CONDITIONS++ 0. Definitions.++ "This License" refers to version 3 of the GNU General Public License.++ "Copyright" also means copyright-like laws that apply to other kinds of+works, such as semiconductor masks.++ "The Program" refers to any copyrightable work licensed under this+License. Each licensee is addressed as "you". "Licensees" and+"recipients" may be individuals or organizations.++ To "modify" a work means to copy from or adapt all or part of the work+in a fashion requiring copyright permission, other than the making of an+exact copy. The resulting work is called a "modified version" of the+earlier work or a work "based on" the earlier work.++ A "covered work" means either the unmodified Program or a work based+on the Program.++ To "propagate" a work means to do anything with it that, without+permission, would make you directly or secondarily liable for+infringement under applicable copyright law, except executing it on a+computer or modifying a private copy. Propagation includes copying,+distribution (with or without modification), making available to the+public, and in some countries other activities as well.++ To "convey" a work means any kind of propagation that enables other+parties to make or receive copies. Mere interaction with a user through+a computer network, with no transfer of a copy, is not conveying.++ An interactive user interface displays "Appropriate Legal Notices"+to the extent that it includes a convenient and prominently visible+feature that (1) displays an appropriate copyright notice, and (2)+tells the user that there is no warranty for the work (except to the+extent that warranties are provided), that licensees may convey the+work under this License, and how to view a copy of this License. If+the interface presents a list of user commands or options, such as a+menu, a prominent item in the list meets this criterion.++ 1. Source Code.++ The "source code" for a work means the preferred form of the work+for making modifications to it. "Object code" means any non-source+form of a work.++ A "Standard Interface" means an interface that either is an official+standard defined by a recognized standards body, or, in the case of+interfaces specified for a particular programming language, one that+is widely used among developers working in that language.++ The "System Libraries" of an executable work include anything, other+than the work as a whole, that (a) is included in the normal form of+packaging a Major Component, but which is not part of that Major+Component, and (b) serves only to enable use of the work with that+Major Component, or to implement a Standard Interface for which an+implementation is available to the public in source code form. A+"Major Component", in this context, means a major essential component+(kernel, window system, and so on) of the specific operating system+(if any) on which the executable work runs, or a compiler used to+produce the work, or an object code interpreter used to run it.++ The "Corresponding Source" for a work in object code form means all+the source code needed to generate, install, and (for an executable+work) run the object code and to modify the work, including scripts to+control those activities. However, it does not include the work's+System Libraries, or general-purpose tools or generally available free+programs which are used unmodified in performing those activities but+which are not part of the work. For example, Corresponding Source+includes interface definition files associated with source files for+the work, and the source code for shared libraries and dynamically+linked subprograms that the work is specifically designed to require,+such as by intimate data communication or control flow between those+subprograms and other parts of the work.++ The Corresponding Source need not include anything that users+can regenerate automatically from other parts of the Corresponding+Source.++ The Corresponding Source for a work in source code form is that+same work.++ 2. Basic Permissions.++ All rights granted under this License are granted for the term of+copyright on the Program, and are irrevocable provided the stated+conditions are met. This License explicitly affirms your unlimited+permission to run the unmodified Program. The output from running a+covered work is covered by this License only if the output, given its+content, constitutes a covered work. This License acknowledges your+rights of fair use or other equivalent, as provided by copyright law.++ You may make, run and propagate covered works that you do not+convey, without conditions so long as your license otherwise remains+in force. You may convey covered works to others for the sole purpose+of having them make modifications exclusively for you, or provide you+with facilities for running those works, provided that you comply with+the terms of this License in conveying all material for which you do+not control copyright. Those thus making or running the covered works+for you must do so exclusively on your behalf, under your direction+and control, on terms that prohibit them from making any copies of+your copyrighted material outside their relationship with you.++ Conveying under any other circumstances is permitted solely under+the conditions stated below. Sublicensing is not allowed; section 10+makes it unnecessary.++ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.++ No covered work shall be deemed part of an effective technological+measure under any applicable law fulfilling obligations under article+11 of the WIPO copyright treaty adopted on 20 December 1996, or+similar laws prohibiting or restricting circumvention of such+measures.++ When you convey a covered work, you waive any legal power to forbid+circumvention of technological measures to the extent such circumvention+is effected by exercising rights under this License with respect to+the covered work, and you disclaim any intention to limit operation or+modification of the work as a means of enforcing, against the work's+users, your or third parties' legal rights to forbid circumvention of+technological measures.++ 4. Conveying Verbatim Copies.++ You may convey verbatim copies of the Program's source code as you+receive it, in any medium, provided that you conspicuously and+appropriately publish on each copy an appropriate copyright notice;+keep intact all notices stating that this License and any+non-permissive terms added in accord with section 7 apply to the code;+keep intact all notices of the absence of any warranty; and give all+recipients a copy of this License along with the Program.++ You may charge any price or no price for each copy that you convey,+and you may offer support or warranty protection for a fee.++ 5. Conveying Modified Source Versions.++ You may convey a work based on the Program, or the modifications to+produce it from the Program, in the form of source code under the+terms of section 4, provided that you also meet all of these conditions:++ a) The work must carry prominent notices stating that you modified+ it, and giving a relevant date.++ b) The work must carry prominent notices stating that it is+ released under this License and any conditions added under section+ 7. This requirement modifies the requirement in section 4 to+ "keep intact all notices".++ c) You must license the entire work, as a whole, under this+ License to anyone who comes into possession of a copy. This+ License will therefore apply, along with any applicable section 7+ additional terms, to the whole of the work, and all its parts,+ regardless of how they are packaged. This License gives no+ permission to license the work in any other way, but it does not+ invalidate such permission if you have separately received it.++ d) If the work has interactive user interfaces, each must display+ Appropriate Legal Notices; however, if the Program has interactive+ interfaces that do not display Appropriate Legal Notices, your+ work need not make them do so.++ A compilation of a covered work with other separate and independent+works, which are not by their nature extensions of the covered work,+and which are not combined with it such as to form a larger program,+in or on a volume of a storage or distribution medium, is called an+"aggregate" if the compilation and its resulting copyright are not+used to limit the access or legal rights of the compilation's users+beyond what the individual works permit. Inclusion of a covered work+in an aggregate does not cause this License to apply to the other+parts of the aggregate.++ 6. Conveying Non-Source Forms.++ You may convey a covered work in object code form under the terms+of sections 4 and 5, provided that you also convey the+machine-readable Corresponding Source under the terms of this License,+in one of these ways:++ a) Convey the object code in, or embodied in, a physical product+ (including a physical distribution medium), accompanied by the+ Corresponding Source fixed on a durable physical medium+ customarily used for software interchange.++ b) Convey the object code in, or embodied in, a physical product+ (including a physical distribution medium), accompanied by a+ written offer, valid for at least three years and valid for as+ long as you offer spare parts or customer support for that product+ model, to give anyone who possesses the object code either (1) a+ copy of the Corresponding Source for all the software in the+ product that is covered by this License, on a durable physical+ medium customarily used for software interchange, for a price no+ more than your reasonable cost of physically performing this+ conveying of source, or (2) access to copy the+ Corresponding Source from a network server at no charge.++ c) Convey individual copies of the object code with a copy of the+ written offer to provide the Corresponding Source. This+ alternative is allowed only occasionally and noncommercially, and+ only if you received the object code with such an offer, in accord+ with subsection 6b.++ d) Convey the object code by offering access from a designated+ place (gratis or for a charge), and offer equivalent access to the+ Corresponding Source in the same way through the same place at no+ further charge. You need not require recipients to copy the+ Corresponding Source along with the object code. If the place to+ copy the object code is a network server, the Corresponding Source+ may be on a different server (operated by you or a third party)+ that supports equivalent copying facilities, provided you maintain+ clear directions next to the object code saying where to find the+ Corresponding Source. Regardless of what server hosts the+ Corresponding Source, you remain obligated to ensure that it is+ available for as long as needed to satisfy these requirements.++ e) Convey the object code using peer-to-peer transmission, provided+ you inform other peers where the object code and Corresponding+ Source of the work are being offered to the general public at no+ charge under subsection 6d.++ A separable portion of the object code, whose source code is excluded+from the Corresponding Source as a System Library, need not be+included in conveying the object code work.++ A "User Product" is either (1) a "consumer product", which means any+tangible personal property which is normally used for personal, family,+or household purposes, or (2) anything designed or sold for incorporation+into a dwelling. In determining whether a product is a consumer product,+doubtful cases shall be resolved in favor of coverage. For a particular+product received by a particular user, "normally used" refers to a+typical or common use of that class of product, regardless of the status+of the particular user or of the way in which the particular user+actually uses, or expects or is expected to use, the product. A product+is a consumer product regardless of whether the product has substantial+commercial, industrial or non-consumer uses, unless such uses represent+the only significant mode of use of the product.++ "Installation Information" for a User Product means any methods,+procedures, authorization keys, or other information required to install+and execute modified versions of a covered work in that User Product from+a modified version of its Corresponding Source. The information must+suffice to ensure that the continued functioning of the modified object+code is in no case prevented or interfered with solely because+modification has been made.++ If you convey an object code work under this section in, or with, or+specifically for use in, a User Product, and the conveying occurs as+part of a transaction in which the right of possession and use of the+User Product is transferred to the recipient in perpetuity or for a+fixed term (regardless of how the transaction is characterized), the+Corresponding Source conveyed under this section must be accompanied+by the Installation Information. But this requirement does not apply+if neither you nor any third party retains the ability to install+modified object code on the User Product (for example, the work has+been installed in ROM).++ The requirement to provide Installation Information does not include a+requirement to continue to provide support service, warranty, or updates+for a work that has been modified or installed by the recipient, or for+the User Product in which it has been modified or installed. Access to a+network may be denied when the modification itself materially and+adversely affects the operation of the network or violates the rules and+protocols for communication across the network.++ Corresponding Source conveyed, and Installation Information provided,+in accord with this section must be in a format that is publicly+documented (and with an implementation available to the public in+source code form), and must require no special password or key for+unpacking, reading or copying.++ 7. Additional Terms.++ "Additional permissions" are terms that supplement the terms of this+License by making exceptions from one or more of its conditions.+Additional permissions that are applicable to the entire Program shall+be treated as though they were included in this License, to the extent+that they are valid under applicable law. If additional permissions+apply only to part of the Program, that part may be used separately+under those permissions, but the entire Program remains governed by+this License without regard to the additional permissions.++ When you convey a copy of a covered work, you may at your option+remove any additional permissions from that copy, or from any part of+it. (Additional permissions may be written to require their own+removal in certain cases when you modify the work.) You may place+additional permissions on material, added by you to a covered work,+for which you have or can give appropriate copyright permission.++ Notwithstanding any other provision of this License, for material you+add to a covered work, you may (if authorized by the copyright holders of+that material) supplement the terms of this License with terms:++ a) Disclaiming warranty or limiting liability differently from the+ terms of sections 15 and 16 of this License; or++ b) Requiring preservation of specified reasonable legal notices or+ author attributions in that material or in the Appropriate Legal+ Notices displayed by works containing it; or++ c) Prohibiting misrepresentation of the origin of that material, or+ requiring that modified versions of such material be marked in+ reasonable ways as different from the original version; or++ d) Limiting the use for publicity purposes of names of licensors or+ authors of the material; or++ e) Declining to grant rights under trademark law for use of some+ trade names, trademarks, or service marks; or++ f) Requiring indemnification of licensors and authors of that+ material by anyone who conveys the material (or modified versions of+ it) with contractual assumptions of liability to the recipient, for+ any liability that these contractual assumptions directly impose on+ those licensors and authors.++ All other non-permissive additional terms are considered "further+restrictions" within the meaning of section 10. If the Program as you+received it, or any part of it, contains a notice stating that it is+governed by this License along with a term that is a further+restriction, you may remove that term. If a license document contains+a further restriction but permits relicensing or conveying under this+License, you may add to a covered work material governed by the terms+of that license document, provided that the further restriction does+not survive such relicensing or conveying.++ If you add terms to a covered work in accord with this section, you+must place, in the relevant source files, a statement of the+additional terms that apply to those files, or a notice indicating+where to find the applicable terms.++ Additional terms, permissive or non-permissive, may be stated in the+form of a separately written license, or stated as exceptions;+the above requirements apply either way.++ 8. Termination.++ You may not propagate or modify a covered work except as expressly+provided under this License. Any attempt otherwise to propagate or+modify it is void, and will automatically terminate your rights under+this License (including any patent licenses granted under the third+paragraph of section 11).++ However, if you cease all violation of this License, then your+license from a particular copyright holder is reinstated (a)+provisionally, unless and until the copyright holder explicitly and+finally terminates your license, and (b) permanently, if the copyright+holder fails to notify you of the violation by some reasonable means+prior to 60 days after the cessation.++ Moreover, your license from a particular copyright holder is+reinstated permanently if the copyright holder notifies you of the+violation by some reasonable means, this is the first time you have+received notice of violation of this License (for any work) from that+copyright holder, and you cure the violation prior to 30 days after+your receipt of the notice.++ Termination of your rights under this section does not terminate the+licenses of parties who have received copies or rights from you under+this License. If your rights have been terminated and not permanently+reinstated, you do not qualify to receive new licenses for the same+material under section 10.++ 9. Acceptance Not Required for Having Copies.++ You are not required to accept this License in order to receive or+run a copy of the Program. Ancillary propagation of a covered work+occurring solely as a consequence of using peer-to-peer transmission+to receive a copy likewise does not require acceptance. However,+nothing other than this License grants you permission to propagate or+modify any covered work. These actions infringe copyright if you do+not accept this License. Therefore, by modifying or propagating a+covered work, you indicate your acceptance of this License to do so.++ 10. Automatic Licensing of Downstream Recipients.++ Each time you convey a covered work, the recipient automatically+receives a license from the original licensors, to run, modify and+propagate that work, subject to this License. You are not responsible+for enforcing compliance by third parties with this License.++ An "entity transaction" is a transaction transferring control of an+organization, or substantially all assets of one, or subdividing an+organization, or merging organizations. If propagation of a covered+work results from an entity transaction, each party to that+transaction who receives a copy of the work also receives whatever+licenses to the work the party's predecessor in interest had or could+give under the previous paragraph, plus a right to possession of the+Corresponding Source of the work from the predecessor in interest, if+the predecessor has it or can get it with reasonable efforts.++ You may not impose any further restrictions on the exercise of the+rights granted or affirmed under this License. For example, you may+not impose a license fee, royalty, or other charge for exercise of+rights granted under this License, and you may not initiate litigation+(including a cross-claim or counterclaim in a lawsuit) alleging that+any patent claim is infringed by making, using, selling, offering for+sale, or importing the Program or any portion of it.++ 11. Patents.++ A "contributor" is a copyright holder who authorizes use under this+License of the Program or a work on which the Program is based. The+work thus licensed is called the contributor's "contributor version".++ A contributor's "essential patent claims" are all patent claims+owned or controlled by the contributor, whether already acquired or+hereafter acquired, that would be infringed by some manner, permitted+by this License, of making, using, or selling its contributor version,+but do not include claims that would be infringed only as a+consequence of further modification of the contributor version. For+purposes of this definition, "control" includes the right to grant+patent sublicenses in a manner consistent with the requirements of+this License.++ Each contributor grants you a non-exclusive, worldwide, royalty-free+patent license under the contributor's essential patent claims, to+make, use, sell, offer for sale, import and otherwise run, modify and+propagate the contents of its contributor version.++ In the following three paragraphs, a "patent license" is any express+agreement or commitment, however denominated, not to enforce a patent+(such as an express permission to practice a patent or covenant not to+sue for patent infringement). To "grant" such a patent license to a+party means to make such an agreement or commitment not to enforce a+patent against the party.++ If you convey a covered work, knowingly relying on a patent license,+and the Corresponding Source of the work is not available for anyone+to copy, free of charge and under the terms of this License, through a+publicly available network server or other readily accessible means,+then you must either (1) cause the Corresponding Source to be so+available, or (2) arrange to deprive yourself of the benefit of the+patent license for this particular work, or (3) arrange, in a manner+consistent with the requirements of this License, to extend the patent+license to downstream recipients. "Knowingly relying" means you have+actual knowledge that, but for the patent license, your conveying the+covered work in a country, or your recipient's use of the covered work+in a country, would infringe one or more identifiable patents in that+country that you have reason to believe are valid.++ If, pursuant to or in connection with a single transaction or+arrangement, you convey, or propagate by procuring conveyance of, a+covered work, and grant a patent license to some of the parties+receiving the covered work authorizing them to use, propagate, modify+or convey a specific copy of the covered work, then the patent license+you grant is automatically extended to all recipients of the covered+work and works based on it.++ A patent license is "discriminatory" if it does not include within+the scope of its coverage, prohibits the exercise of, or is+conditioned on the non-exercise of one or more of the rights that are+specifically granted under this License. You may not convey a covered+work if you are a party to an arrangement with a third party that is+in the business of distributing software, under which you make payment+to the third party based on the extent of your activity of conveying+the work, and under which the third party grants, to any of the+parties who would receive the covered work from you, a discriminatory+patent license (a) in connection with copies of the covered work+conveyed by you (or copies made from those copies), or (b) primarily+for and in connection with specific products or compilations that+contain the covered work, unless you entered into that arrangement,+or that patent license was granted, prior to 28 March 2007.++ Nothing in this License shall be construed as excluding or limiting+any implied license or other defenses to infringement that may+otherwise be available to you under applicable patent law.++ 12. No Surrender of Others' Freedom.++ If conditions are imposed on you (whether by court order, agreement or+otherwise) that contradict the conditions of this License, they do not+excuse you from the conditions of this License. If you cannot convey a+covered work so as to satisfy simultaneously your obligations under this+License and any other pertinent obligations, then as a consequence you may+not convey it at all. For example, if you agree to terms that obligate you+to collect a royalty for further conveying from those to whom you convey+the Program, the only way you could satisfy both those terms and this+License would be to refrain entirely from conveying the Program.++ 13. Use with the GNU Affero General Public License.++ Notwithstanding any other provision of this License, you have+permission to link or combine any covered work with a work licensed+under version 3 of the GNU Affero General Public License into a single+combined work, and to convey the resulting work. The terms of this+License will continue to apply to the part which is the covered work,+but the special requirements of the GNU Affero General Public License,+section 13, concerning interaction through a network will apply to the+combination as such.++ 14. Revised Versions of this License.++ The Free Software Foundation may publish revised and/or new versions of+the GNU General Public License from time to time. Such new versions will+be similar in spirit to the present version, but may differ in detail to+address new problems or concerns.++ Each version is given a distinguishing version number. If the+Program specifies that a certain numbered version of the GNU General+Public License "or any later version" applies to it, you have the+option of following the terms and conditions either of that numbered+version or of any later version published by the Free Software+Foundation. If the Program does not specify a version number of the+GNU General Public License, you may choose any version ever published+by the Free Software Foundation.++ If the Program specifies that a proxy can decide which future+versions of the GNU General Public License can be used, that proxy's+public statement of acceptance of a version permanently authorizes you+to choose that version for the Program.++ Later license versions may give you additional or different+permissions. However, no additional obligations are imposed on any+author or copyright holder as a result of your choosing to follow a+later version.++ 15. Disclaimer of Warranty.++ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.++ 16. Limitation of Liability.++ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF+SUCH DAMAGES.++ 17. Interpretation of Sections 15 and 16.++ If the disclaimer of warranty and limitation of liability provided+above cannot be given local legal effect according to their terms,+reviewing courts shall apply local law that most closely approximates+an absolute waiver of all civil liability in connection with the+Program, unless a warranty or assumption of liability accompanies a+copy of the Program in return for a fee.++ END OF TERMS AND CONDITIONS++ How to Apply These Terms to Your New Programs++ If you develop a new program, and you want it to be of the greatest+possible use to the public, the best way to achieve this is to make it+free software which everyone can redistribute and change under these terms.++ To do so, attach the following notices to the program. It is safest+to attach them to the start of each source file to most effectively+state the exclusion of warranty; and each file should have at least+the "copyright" line and a pointer to where the full notice is found.++ <one line to give the program's name and a brief idea of what it does.>+ Copyright (C) <year> <name of author>++ This program is free software: you can redistribute it and/or modify+ it under the terms of the GNU General Public License as published by+ the Free Software Foundation, either version 3 of the License, or+ (at your option) any later version.++ This program is distributed in the hope that it will be useful,+ but WITHOUT ANY WARRANTY; without even the implied warranty of+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ GNU General Public License for more details.++ You should have received a copy of the GNU General Public License+ along with this program. If not, see <https://www.gnu.org/licenses/>.++Also add information on how to contact you by electronic and paper mail.++ If the program does terminal interaction, make it output a short+notice like this when it starts in an interactive mode:++ <program> Copyright (C) <year> <name of author>+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.+ This is free software, and you are welcome to redistribute it+ under certain conditions; type `show c' for details.++The hypothetical commands `show w' and `show c' should show the appropriate+parts of the General Public License. Of course, your program's commands+might be different; for a GUI interface, you would use an "about box".++ You should also get your employer (if you work as a programmer) or school,+if any, to sign a "copyright disclaimer" for the program, if necessary.+For more information on this, and how to apply and follow the GNU GPL, see+<https://www.gnu.org/licenses/>.++ The GNU General Public License does not permit incorporating your program+into proprietary programs. If your program is a subroutine library, you+may consider it more useful to permit linking proprietary applications with+the library. If this is what you want to do, use the GNU Lesser General+Public License instead of this License. But first, please read+<https://www.gnu.org/licenses/why-not-lgpl.html>.
+ libs/copr-hs/src/Web/Fedora/Copr.hs view
@@ -0,0 +1,35 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE OverloadedStrings #-}++{- |+Copyright: (c) 2020 Jens Petersen+SPDX-License-Identifier: GPL-2.0-only+Maintainer: Jens Petersen <petersen@redhat.com>++Copr REST client library+-}++module Web.Fedora.Copr+ (coprChroots,+ fedoraCopr)+where++import Data.Aeson.Types (Object)+import qualified Data.HashMap.Lazy as H+import Data.List (sort)+import Data.Text (Text)++import Web.Fedora.Copr.API++coprChroots :: String -> String -> String -> IO [Text]+coprChroots server owner project = do+ proj <- coprGetProject server owner project+ case lookupKey "chroot_repos" proj :: Maybe Object of+ Nothing ->+ case lookupKey "error" proj of+ Just err -> error err+ Nothing -> return []+ Just obj -> return $ (reverse . sort . H.keys) obj++fedoraCopr :: String+fedoraCopr = "copr.fedorainfracloud.org"
+ libs/copr-hs/src/Web/Fedora/Copr/API.hs view
@@ -0,0 +1,190 @@+{-# LANGUAGE CPP #-}++{- |+Copyright: (c) 2020 Jens Petersen+SPDX-License-Identifier: GPL-2.0-only+Maintainer: Jens Petersen <petersen@redhat.com>++Copr REST client library+-}++module Web.Fedora.Copr.API+ ( coprGetProject+ , coprGetProjectsList+ , coprSearchProjects+ , coprGetBuild+ , coprGetBuildSourceChroot+ , coprGetBuildSourceConfig+ , coprGetBuildPackageList+ , coprGetBuildChroot+ , coprGetBuildChrootList+ , coprGetBuildChrootConfig+ , coprMockChrootList+ , coprGetPackage+ , coprGetPackageList+ , coprGetProjectChroot+ , coprGetProjectChrootBuildConfig+ , queryCopr+ , maybeKey+ , makeKey+ , makeItem+ , lookupKey+ , lookupKey'+ )+where++import Data.Aeson.Types+import Network.HTTP.Query++-- # Projects++-- | List project details+--+-- https://pagure.io/copr/copr/blob/master/f/python/copr/v3/proxies/project.py#_9+coprGetProject :: String -> String -> String -> IO Object+coprGetProject server owner project = do+ let path = "project"+ params = [makeItem "ownername" owner, makeItem "projectname" project]+ queryCopr server path params++-- | List projects of owner+--+-- https://pagure.io/copr/copr/blob/master/f/python/copr/v3/proxies/project.py#_26+coprGetProjectsList :: String -> String -> IO Value+-- FIXME limit=int or maybe pagination?+coprGetProjectsList server owner = do+ let path = "project/list"+ params = makeKey "ownername" owner+ queryCopr server path params++-- | search projects by query string+--+-- https://pagure.io/copr/copr/blob/master/f/python/copr/v3/proxies/project.py#_43+coprSearchProjects :: String -> String -> IO Value+coprSearchProjects server query = do+ let path = "project/search"+ params = makeKey "query" query+ queryCopr server path params++-- # Builds++-- | get build+--+-- https://pagure.io/copr/copr/blob/master/f/python/copr/v3/proxies/build.py#_10+coprGetBuild :: String -> Int -> IO Value+coprGetBuild server bid = do+ let path = "build" +/+ show bid+ queryCopr server path []++-- | get srpm build+--+-- https://pagure.io/copr/copr/blob/master/f/python/copr/v3/proxies/build.py#_22+coprGetBuildSourceChroot :: String -> Int -> IO Value+coprGetBuildSourceChroot server bid = do+ let path = "build/source-chroot" +/+ show bid+ queryCopr server path []++-- | get build source config+--+-- https://pagure.io/copr/copr/blob/master/f/python/copr/v3/proxies/build.py#_34+coprGetBuildSourceConfig :: String -> Int -> IO Value+coprGetBuildSourceConfig server bid = do+ let path = "build/source-build-config" +/+ show bid+ queryCopr server path []++-- | get list of packages+--+-- https://pagure.io/copr/copr/blob/master/f/python/copr/v3/proxies/build.py#_46+coprGetBuildPackageList :: String -> Query -> IO Value+coprGetBuildPackageList server params = do+ let path = "build/list"+ queryCopr server path params++-- # Build chroot++-- | get build chroot+--+-- https://pagure.io/copr/copr/blob/master/f/python/copr/v3/proxies/build_chroot.py#_8+coprGetBuildChroot :: String -> Int -> String -> IO Value+coprGetBuildChroot server bid chroot = do+ let path = "build-chroot" +/+ show bid +/+ chroot+ queryCopr server path []++-- | list of build chroots+--+-- https://pagure.io/copr/copr/blob/master/f/python/copr/v3/proxies/build_chroot.py#_25+coprGetBuildChrootList :: String -> Int -> IO Value+coprGetBuildChrootList server bid = do+ let path = "build-chroot/list" +/+ show bid+ queryCopr server path []++-- | get build config for chroot+--+-- https://pagure.io/copr/copr/blob/master/f/python/copr/v3/proxies/build_chroot.py#_44+coprGetBuildChrootConfig :: String -> Int -> String -> IO Value+coprGetBuildChrootConfig server bid chroot = do+ let path = "build-chroot/build-config" +/+ show bid +/+ chroot+ queryCopr server path []++-- # Mock chroot++-- | list of all available mock chroots+--+-- https://pagure.io/copr/copr/blob/master/f/python/copr/v3/proxies/mock_chroot.py+coprMockChrootList :: String -> IO Value+coprMockChrootList server = do+ let path = "mock-chroots/list"+ queryCopr server path []++-- # Package++-- | Get project package details+--+-- https://pagure.io/copr/copr/blob/master/f/python/copr/v3/proxies/package.py#_9+coprGetPackage :: String -> String -> String -> String -> IO Value+coprGetPackage server owner project package = do+ let path = "package"+ params = [makeItem "ownername" owner,+ makeItem "projectname" project,+ makeItem "packagename" package]+ queryCopr server path params++-- | List project packages+--+-- https://pagure.io/copr/copr/blob/master/f/python/copr/v3/proxies/package.py#_28+coprGetPackageList :: String -> String -> String -> IO Value+coprGetPackageList server owner project = do+ let path = "package/list"+ params = [makeItem "ownername" owner, makeItem "projectname" project]+ queryCopr server path params++-- # Project chroot++-- | get build chroot+--+-- https://pagure.io/copr/copr/blob/master/f/python/copr/v3/proxies/project_chroot.py#_10+coprGetProjectChroot :: String -> String -> String -> String -> IO Value+coprGetProjectChroot server owner project chroot = do+ let path = "project-chroot"+ params = [makeItem "ownername" owner,+ makeItem "projectname" project,+ makeItem "chrootname" chroot]+ queryCopr server path params++-- | list of build chroots+--+-- https://pagure.io/copr/copr/blob/master/f/python/copr/v3/proxies/project_chroot.py#_29+coprGetProjectChrootBuildConfig :: String -> String -> String -> String -> IO Value+coprGetProjectChrootBuildConfig server owner project chroot = do+ let path = "project-chroot/build-config"+ params = [makeItem "ownername" owner,+ makeItem "projectname" project,+ makeItem "chrootname" chroot]+ queryCopr server path params+++-- | low-level query+queryCopr :: FromJSON a => String -> String -> Query -> IO a+queryCopr server path params =+ let url = "https://" ++ server +/+ "api_3" +/+ path+ in webAPIQuery url params
+ libs/fedora-dists/LICENSE view
@@ -0,0 +1,674 @@+ GNU GENERAL PUBLIC LICENSE+ Version 3, 29 June 2007++ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>+ Everyone is permitted to copy and distribute verbatim copies+ of this license document, but changing it is not allowed.++ Preamble++ The GNU General Public License is a free, copyleft license for+software and other kinds of works.++ The licenses for most software and other practical works are designed+to take away your freedom to share and change the works. By contrast,+the GNU General Public License is intended to guarantee your freedom to+share and change all versions of a program--to make sure it remains free+software for all its users. We, the Free Software Foundation, use the+GNU General Public License for most of our software; it applies also to+any other work released this way by its authors. You can apply it to+your programs, too.++ When we speak of free software, we are referring to freedom, not+price. Our General Public Licenses are designed to make sure that you+have the freedom to distribute copies of free software (and charge for+them if you wish), that you receive source code or can get it if you+want it, that you can change the software or use pieces of it in new+free programs, and that you know you can do these things.++ To protect your rights, we need to prevent others from denying you+these rights or asking you to surrender the rights. Therefore, you have+certain responsibilities if you distribute copies of the software, or if+you modify it: responsibilities to respect the freedom of others.++ For example, if you distribute copies of such a program, whether+gratis or for a fee, you must pass on to the recipients the same+freedoms that you received. You must make sure that they, too, receive+or can get the source code. And you must show them these terms so they+know their rights.++ Developers that use the GNU GPL protect your rights with two steps:+(1) assert copyright on the software, and (2) offer you this License+giving you legal permission to copy, distribute and/or modify it.++ For the developers' and authors' protection, the GPL clearly explains+that there is no warranty for this free software. For both users' and+authors' sake, the GPL requires that modified versions be marked as+changed, so that their problems will not be attributed erroneously to+authors of previous versions.++ Some devices are designed to deny users access to install or run+modified versions of the software inside them, although the manufacturer+can do so. This is fundamentally incompatible with the aim of+protecting users' freedom to change the software. The systematic+pattern of such abuse occurs in the area of products for individuals to+use, which is precisely where it is most unacceptable. Therefore, we+have designed this version of the GPL to prohibit the practice for those+products. If such problems arise substantially in other domains, we+stand ready to extend this provision to those domains in future versions+of the GPL, as needed to protect the freedom of users.++ Finally, every program is threatened constantly by software patents.+States should not allow patents to restrict development and use of+software on general-purpose computers, but in those that do, we wish to+avoid the special danger that patents applied to a free program could+make it effectively proprietary. To prevent this, the GPL assures that+patents cannot be used to render the program non-free.++ The precise terms and conditions for copying, distribution and+modification follow.++ TERMS AND CONDITIONS++ 0. Definitions.++ "This License" refers to version 3 of the GNU General Public License.++ "Copyright" also means copyright-like laws that apply to other kinds of+works, such as semiconductor masks.++ "The Program" refers to any copyrightable work licensed under this+License. Each licensee is addressed as "you". "Licensees" and+"recipients" may be individuals or organizations.++ To "modify" a work means to copy from or adapt all or part of the work+in a fashion requiring copyright permission, other than the making of an+exact copy. The resulting work is called a "modified version" of the+earlier work or a work "based on" the earlier work.++ A "covered work" means either the unmodified Program or a work based+on the Program.++ To "propagate" a work means to do anything with it that, without+permission, would make you directly or secondarily liable for+infringement under applicable copyright law, except executing it on a+computer or modifying a private copy. Propagation includes copying,+distribution (with or without modification), making available to the+public, and in some countries other activities as well.++ To "convey" a work means any kind of propagation that enables other+parties to make or receive copies. Mere interaction with a user through+a computer network, with no transfer of a copy, is not conveying.++ An interactive user interface displays "Appropriate Legal Notices"+to the extent that it includes a convenient and prominently visible+feature that (1) displays an appropriate copyright notice, and (2)+tells the user that there is no warranty for the work (except to the+extent that warranties are provided), that licensees may convey the+work under this License, and how to view a copy of this License. If+the interface presents a list of user commands or options, such as a+menu, a prominent item in the list meets this criterion.++ 1. Source Code.++ The "source code" for a work means the preferred form of the work+for making modifications to it. "Object code" means any non-source+form of a work.++ A "Standard Interface" means an interface that either is an official+standard defined by a recognized standards body, or, in the case of+interfaces specified for a particular programming language, one that+is widely used among developers working in that language.++ The "System Libraries" of an executable work include anything, other+than the work as a whole, that (a) is included in the normal form of+packaging a Major Component, but which is not part of that Major+Component, and (b) serves only to enable use of the work with that+Major Component, or to implement a Standard Interface for which an+implementation is available to the public in source code form. A+"Major Component", in this context, means a major essential component+(kernel, window system, and so on) of the specific operating system+(if any) on which the executable work runs, or a compiler used to+produce the work, or an object code interpreter used to run it.++ The "Corresponding Source" for a work in object code form means all+the source code needed to generate, install, and (for an executable+work) run the object code and to modify the work, including scripts to+control those activities. However, it does not include the work's+System Libraries, or general-purpose tools or generally available free+programs which are used unmodified in performing those activities but+which are not part of the work. For example, Corresponding Source+includes interface definition files associated with source files for+the work, and the source code for shared libraries and dynamically+linked subprograms that the work is specifically designed to require,+such as by intimate data communication or control flow between those+subprograms and other parts of the work.++ The Corresponding Source need not include anything that users+can regenerate automatically from other parts of the Corresponding+Source.++ The Corresponding Source for a work in source code form is that+same work.++ 2. Basic Permissions.++ All rights granted under this License are granted for the term of+copyright on the Program, and are irrevocable provided the stated+conditions are met. This License explicitly affirms your unlimited+permission to run the unmodified Program. The output from running a+covered work is covered by this License only if the output, given its+content, constitutes a covered work. This License acknowledges your+rights of fair use or other equivalent, as provided by copyright law.++ You may make, run and propagate covered works that you do not+convey, without conditions so long as your license otherwise remains+in force. You may convey covered works to others for the sole purpose+of having them make modifications exclusively for you, or provide you+with facilities for running those works, provided that you comply with+the terms of this License in conveying all material for which you do+not control copyright. Those thus making or running the covered works+for you must do so exclusively on your behalf, under your direction+and control, on terms that prohibit them from making any copies of+your copyrighted material outside their relationship with you.++ Conveying under any other circumstances is permitted solely under+the conditions stated below. Sublicensing is not allowed; section 10+makes it unnecessary.++ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.++ No covered work shall be deemed part of an effective technological+measure under any applicable law fulfilling obligations under article+11 of the WIPO copyright treaty adopted on 20 December 1996, or+similar laws prohibiting or restricting circumvention of such+measures.++ When you convey a covered work, you waive any legal power to forbid+circumvention of technological measures to the extent such circumvention+is effected by exercising rights under this License with respect to+the covered work, and you disclaim any intention to limit operation or+modification of the work as a means of enforcing, against the work's+users, your or third parties' legal rights to forbid circumvention of+technological measures.++ 4. Conveying Verbatim Copies.++ You may convey verbatim copies of the Program's source code as you+receive it, in any medium, provided that you conspicuously and+appropriately publish on each copy an appropriate copyright notice;+keep intact all notices stating that this License and any+non-permissive terms added in accord with section 7 apply to the code;+keep intact all notices of the absence of any warranty; and give all+recipients a copy of this License along with the Program.++ You may charge any price or no price for each copy that you convey,+and you may offer support or warranty protection for a fee.++ 5. Conveying Modified Source Versions.++ You may convey a work based on the Program, or the modifications to+produce it from the Program, in the form of source code under the+terms of section 4, provided that you also meet all of these conditions:++ a) The work must carry prominent notices stating that you modified+ it, and giving a relevant date.++ b) The work must carry prominent notices stating that it is+ released under this License and any conditions added under section+ 7. This requirement modifies the requirement in section 4 to+ "keep intact all notices".++ c) You must license the entire work, as a whole, under this+ License to anyone who comes into possession of a copy. This+ License will therefore apply, along with any applicable section 7+ additional terms, to the whole of the work, and all its parts,+ regardless of how they are packaged. This License gives no+ permission to license the work in any other way, but it does not+ invalidate such permission if you have separately received it.++ d) If the work has interactive user interfaces, each must display+ Appropriate Legal Notices; however, if the Program has interactive+ interfaces that do not display Appropriate Legal Notices, your+ work need not make them do so.++ A compilation of a covered work with other separate and independent+works, which are not by their nature extensions of the covered work,+and which are not combined with it such as to form a larger program,+in or on a volume of a storage or distribution medium, is called an+"aggregate" if the compilation and its resulting copyright are not+used to limit the access or legal rights of the compilation's users+beyond what the individual works permit. Inclusion of a covered work+in an aggregate does not cause this License to apply to the other+parts of the aggregate.++ 6. Conveying Non-Source Forms.++ You may convey a covered work in object code form under the terms+of sections 4 and 5, provided that you also convey the+machine-readable Corresponding Source under the terms of this License,+in one of these ways:++ a) Convey the object code in, or embodied in, a physical product+ (including a physical distribution medium), accompanied by the+ Corresponding Source fixed on a durable physical medium+ customarily used for software interchange.++ b) Convey the object code in, or embodied in, a physical product+ (including a physical distribution medium), accompanied by a+ written offer, valid for at least three years and valid for as+ long as you offer spare parts or customer support for that product+ model, to give anyone who possesses the object code either (1) a+ copy of the Corresponding Source for all the software in the+ product that is covered by this License, on a durable physical+ medium customarily used for software interchange, for a price no+ more than your reasonable cost of physically performing this+ conveying of source, or (2) access to copy the+ Corresponding Source from a network server at no charge.++ c) Convey individual copies of the object code with a copy of the+ written offer to provide the Corresponding Source. This+ alternative is allowed only occasionally and noncommercially, and+ only if you received the object code with such an offer, in accord+ with subsection 6b.++ d) Convey the object code by offering access from a designated+ place (gratis or for a charge), and offer equivalent access to the+ Corresponding Source in the same way through the same place at no+ further charge. You need not require recipients to copy the+ Corresponding Source along with the object code. If the place to+ copy the object code is a network server, the Corresponding Source+ may be on a different server (operated by you or a third party)+ that supports equivalent copying facilities, provided you maintain+ clear directions next to the object code saying where to find the+ Corresponding Source. Regardless of what server hosts the+ Corresponding Source, you remain obligated to ensure that it is+ available for as long as needed to satisfy these requirements.++ e) Convey the object code using peer-to-peer transmission, provided+ you inform other peers where the object code and Corresponding+ Source of the work are being offered to the general public at no+ charge under subsection 6d.++ A separable portion of the object code, whose source code is excluded+from the Corresponding Source as a System Library, need not be+included in conveying the object code work.++ A "User Product" is either (1) a "consumer product", which means any+tangible personal property which is normally used for personal, family,+or household purposes, or (2) anything designed or sold for incorporation+into a dwelling. In determining whether a product is a consumer product,+doubtful cases shall be resolved in favor of coverage. For a particular+product received by a particular user, "normally used" refers to a+typical or common use of that class of product, regardless of the status+of the particular user or of the way in which the particular user+actually uses, or expects or is expected to use, the product. A product+is a consumer product regardless of whether the product has substantial+commercial, industrial or non-consumer uses, unless such uses represent+the only significant mode of use of the product.++ "Installation Information" for a User Product means any methods,+procedures, authorization keys, or other information required to install+and execute modified versions of a covered work in that User Product from+a modified version of its Corresponding Source. The information must+suffice to ensure that the continued functioning of the modified object+code is in no case prevented or interfered with solely because+modification has been made.++ If you convey an object code work under this section in, or with, or+specifically for use in, a User Product, and the conveying occurs as+part of a transaction in which the right of possession and use of the+User Product is transferred to the recipient in perpetuity or for a+fixed term (regardless of how the transaction is characterized), the+Corresponding Source conveyed under this section must be accompanied+by the Installation Information. But this requirement does not apply+if neither you nor any third party retains the ability to install+modified object code on the User Product (for example, the work has+been installed in ROM).++ The requirement to provide Installation Information does not include a+requirement to continue to provide support service, warranty, or updates+for a work that has been modified or installed by the recipient, or for+the User Product in which it has been modified or installed. Access to a+network may be denied when the modification itself materially and+adversely affects the operation of the network or violates the rules and+protocols for communication across the network.++ Corresponding Source conveyed, and Installation Information provided,+in accord with this section must be in a format that is publicly+documented (and with an implementation available to the public in+source code form), and must require no special password or key for+unpacking, reading or copying.++ 7. Additional Terms.++ "Additional permissions" are terms that supplement the terms of this+License by making exceptions from one or more of its conditions.+Additional permissions that are applicable to the entire Program shall+be treated as though they were included in this License, to the extent+that they are valid under applicable law. If additional permissions+apply only to part of the Program, that part may be used separately+under those permissions, but the entire Program remains governed by+this License without regard to the additional permissions.++ When you convey a copy of a covered work, you may at your option+remove any additional permissions from that copy, or from any part of+it. (Additional permissions may be written to require their own+removal in certain cases when you modify the work.) You may place+additional permissions on material, added by you to a covered work,+for which you have or can give appropriate copyright permission.++ Notwithstanding any other provision of this License, for material you+add to a covered work, you may (if authorized by the copyright holders of+that material) supplement the terms of this License with terms:++ a) Disclaiming warranty or limiting liability differently from the+ terms of sections 15 and 16 of this License; or++ b) Requiring preservation of specified reasonable legal notices or+ author attributions in that material or in the Appropriate Legal+ Notices displayed by works containing it; or++ c) Prohibiting misrepresentation of the origin of that material, or+ requiring that modified versions of such material be marked in+ reasonable ways as different from the original version; or++ d) Limiting the use for publicity purposes of names of licensors or+ authors of the material; or++ e) Declining to grant rights under trademark law for use of some+ trade names, trademarks, or service marks; or++ f) Requiring indemnification of licensors and authors of that+ material by anyone who conveys the material (or modified versions of+ it) with contractual assumptions of liability to the recipient, for+ any liability that these contractual assumptions directly impose on+ those licensors and authors.++ All other non-permissive additional terms are considered "further+restrictions" within the meaning of section 10. If the Program as you+received it, or any part of it, contains a notice stating that it is+governed by this License along with a term that is a further+restriction, you may remove that term. If a license document contains+a further restriction but permits relicensing or conveying under this+License, you may add to a covered work material governed by the terms+of that license document, provided that the further restriction does+not survive such relicensing or conveying.++ If you add terms to a covered work in accord with this section, you+must place, in the relevant source files, a statement of the+additional terms that apply to those files, or a notice indicating+where to find the applicable terms.++ Additional terms, permissive or non-permissive, may be stated in the+form of a separately written license, or stated as exceptions;+the above requirements apply either way.++ 8. Termination.++ You may not propagate or modify a covered work except as expressly+provided under this License. Any attempt otherwise to propagate or+modify it is void, and will automatically terminate your rights under+this License (including any patent licenses granted under the third+paragraph of section 11).++ However, if you cease all violation of this License, then your+license from a particular copyright holder is reinstated (a)+provisionally, unless and until the copyright holder explicitly and+finally terminates your license, and (b) permanently, if the copyright+holder fails to notify you of the violation by some reasonable means+prior to 60 days after the cessation.++ Moreover, your license from a particular copyright holder is+reinstated permanently if the copyright holder notifies you of the+violation by some reasonable means, this is the first time you have+received notice of violation of this License (for any work) from that+copyright holder, and you cure the violation prior to 30 days after+your receipt of the notice.++ Termination of your rights under this section does not terminate the+licenses of parties who have received copies or rights from you under+this License. If your rights have been terminated and not permanently+reinstated, you do not qualify to receive new licenses for the same+material under section 10.++ 9. Acceptance Not Required for Having Copies.++ You are not required to accept this License in order to receive or+run a copy of the Program. Ancillary propagation of a covered work+occurring solely as a consequence of using peer-to-peer transmission+to receive a copy likewise does not require acceptance. However,+nothing other than this License grants you permission to propagate or+modify any covered work. These actions infringe copyright if you do+not accept this License. Therefore, by modifying or propagating a+covered work, you indicate your acceptance of this License to do so.++ 10. Automatic Licensing of Downstream Recipients.++ Each time you convey a covered work, the recipient automatically+receives a license from the original licensors, to run, modify and+propagate that work, subject to this License. You are not responsible+for enforcing compliance by third parties with this License.++ An "entity transaction" is a transaction transferring control of an+organization, or substantially all assets of one, or subdividing an+organization, or merging organizations. If propagation of a covered+work results from an entity transaction, each party to that+transaction who receives a copy of the work also receives whatever+licenses to the work the party's predecessor in interest had or could+give under the previous paragraph, plus a right to possession of the+Corresponding Source of the work from the predecessor in interest, if+the predecessor has it or can get it with reasonable efforts.++ You may not impose any further restrictions on the exercise of the+rights granted or affirmed under this License. For example, you may+not impose a license fee, royalty, or other charge for exercise of+rights granted under this License, and you may not initiate litigation+(including a cross-claim or counterclaim in a lawsuit) alleging that+any patent claim is infringed by making, using, selling, offering for+sale, or importing the Program or any portion of it.++ 11. Patents.++ A "contributor" is a copyright holder who authorizes use under this+License of the Program or a work on which the Program is based. The+work thus licensed is called the contributor's "contributor version".++ A contributor's "essential patent claims" are all patent claims+owned or controlled by the contributor, whether already acquired or+hereafter acquired, that would be infringed by some manner, permitted+by this License, of making, using, or selling its contributor version,+but do not include claims that would be infringed only as a+consequence of further modification of the contributor version. For+purposes of this definition, "control" includes the right to grant+patent sublicenses in a manner consistent with the requirements of+this License.++ Each contributor grants you a non-exclusive, worldwide, royalty-free+patent license under the contributor's essential patent claims, to+make, use, sell, offer for sale, import and otherwise run, modify and+propagate the contents of its contributor version.++ In the following three paragraphs, a "patent license" is any express+agreement or commitment, however denominated, not to enforce a patent+(such as an express permission to practice a patent or covenant not to+sue for patent infringement). To "grant" such a patent license to a+party means to make such an agreement or commitment not to enforce a+patent against the party.++ If you convey a covered work, knowingly relying on a patent license,+and the Corresponding Source of the work is not available for anyone+to copy, free of charge and under the terms of this License, through a+publicly available network server or other readily accessible means,+then you must either (1) cause the Corresponding Source to be so+available, or (2) arrange to deprive yourself of the benefit of the+patent license for this particular work, or (3) arrange, in a manner+consistent with the requirements of this License, to extend the patent+license to downstream recipients. "Knowingly relying" means you have+actual knowledge that, but for the patent license, your conveying the+covered work in a country, or your recipient's use of the covered work+in a country, would infringe one or more identifiable patents in that+country that you have reason to believe are valid.++ If, pursuant to or in connection with a single transaction or+arrangement, you convey, or propagate by procuring conveyance of, a+covered work, and grant a patent license to some of the parties+receiving the covered work authorizing them to use, propagate, modify+or convey a specific copy of the covered work, then the patent license+you grant is automatically extended to all recipients of the covered+work and works based on it.++ A patent license is "discriminatory" if it does not include within+the scope of its coverage, prohibits the exercise of, or is+conditioned on the non-exercise of one or more of the rights that are+specifically granted under this License. You may not convey a covered+work if you are a party to an arrangement with a third party that is+in the business of distributing software, under which you make payment+to the third party based on the extent of your activity of conveying+the work, and under which the third party grants, to any of the+parties who would receive the covered work from you, a discriminatory+patent license (a) in connection with copies of the covered work+conveyed by you (or copies made from those copies), or (b) primarily+for and in connection with specific products or compilations that+contain the covered work, unless you entered into that arrangement,+or that patent license was granted, prior to 28 March 2007.++ Nothing in this License shall be construed as excluding or limiting+any implied license or other defenses to infringement that may+otherwise be available to you under applicable patent law.++ 12. No Surrender of Others' Freedom.++ If conditions are imposed on you (whether by court order, agreement or+otherwise) that contradict the conditions of this License, they do not+excuse you from the conditions of this License. If you cannot convey a+covered work so as to satisfy simultaneously your obligations under this+License and any other pertinent obligations, then as a consequence you may+not convey it at all. For example, if you agree to terms that obligate you+to collect a royalty for further conveying from those to whom you convey+the Program, the only way you could satisfy both those terms and this+License would be to refrain entirely from conveying the Program.++ 13. Use with the GNU Affero General Public License.++ Notwithstanding any other provision of this License, you have+permission to link or combine any covered work with a work licensed+under version 3 of the GNU Affero General Public License into a single+combined work, and to convey the resulting work. The terms of this+License will continue to apply to the part which is the covered work,+but the special requirements of the GNU Affero General Public License,+section 13, concerning interaction through a network will apply to the+combination as such.++ 14. Revised Versions of this License.++ The Free Software Foundation may publish revised and/or new versions of+the GNU General Public License from time to time. Such new versions will+be similar in spirit to the present version, but may differ in detail to+address new problems or concerns.++ Each version is given a distinguishing version number. If the+Program specifies that a certain numbered version of the GNU General+Public License "or any later version" applies to it, you have the+option of following the terms and conditions either of that numbered+version or of any later version published by the Free Software+Foundation. If the Program does not specify a version number of the+GNU General Public License, you may choose any version ever published+by the Free Software Foundation.++ If the Program specifies that a proxy can decide which future+versions of the GNU General Public License can be used, that proxy's+public statement of acceptance of a version permanently authorizes you+to choose that version for the Program.++ Later license versions may give you additional or different+permissions. However, no additional obligations are imposed on any+author or copyright holder as a result of your choosing to follow a+later version.++ 15. Disclaimer of Warranty.++ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.++ 16. Limitation of Liability.++ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF+SUCH DAMAGES.++ 17. Interpretation of Sections 15 and 16.++ If the disclaimer of warranty and limitation of liability provided+above cannot be given local legal effect according to their terms,+reviewing courts shall apply local law that most closely approximates+an absolute waiver of all civil liability in connection with the+Program, unless a warranty or assumption of liability accompanies a+copy of the Program in return for a fee.++ END OF TERMS AND CONDITIONS++ How to Apply These Terms to Your New Programs++ If you develop a new program, and you want it to be of the greatest+possible use to the public, the best way to achieve this is to make it+free software which everyone can redistribute and change under these terms.++ To do so, attach the following notices to the program. It is safest+to attach them to the start of each source file to most effectively+state the exclusion of warranty; and each file should have at least+the "copyright" line and a pointer to where the full notice is found.++ <one line to give the program's name and a brief idea of what it does.>+ Copyright (C) <year> <name of author>++ This program is free software: you can redistribute it and/or modify+ it under the terms of the GNU General Public License as published by+ the Free Software Foundation, either version 3 of the License, or+ (at your option) any later version.++ This program is distributed in the hope that it will be useful,+ but WITHOUT ANY WARRANTY; without even the implied warranty of+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ GNU General Public License for more details.++ You should have received a copy of the GNU General Public License+ along with this program. If not, see <https://www.gnu.org/licenses/>.++Also add information on how to contact you by electronic and paper mail.++ If the program does terminal interaction, make it output a short+notice like this when it starts in an interactive mode:++ <program> Copyright (C) <year> <name of author>+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.+ This is free software, and you are welcome to redistribute it+ under certain conditions; type `show c' for details.++The hypothetical commands `show w' and `show c' should show the appropriate+parts of the General Public License. Of course, your program's commands+might be different; for a GUI interface, you would use an "about box".++ You should also get your employer (if you work as a programmer) or school,+if any, to sign a "copyright disclaimer" for the program, if necessary.+For more information on this, and how to apply and follow the GNU GPL, see+<https://www.gnu.org/licenses/>.++ The GNU General Public License does not permit incorporating your program+into proprietary programs. If your program is a subroutine library, you+may consider it more useful to permit linking proprietary applications with+the library. If this is what you want to do, use the GNU Lesser General+Public License instead of this License. But first, please read+<https://www.gnu.org/licenses/why-not-lgpl.html>.
+ libs/fedora-dists/src/Distribution/Fedora.hs view
@@ -0,0 +1,216 @@+{-# LANGUAGE CPP #-}++-- |+-- Module : Distribution.Fedora+-- Copyright : (C) 2014-2020 Jens Petersen+--+-- Maintainer : Jens Petersen <petersen@fedoraproject.org>+--+-- Explanation: Fedora Dist type and functions++-- This program is free software: you can redistribute it and/or modify+-- it under the terms of the GNU General Public License as published by+-- the Free Software Foundation, either version 3 of the License, or+-- (at your option) any later version.++module Distribution.Fedora+ (Dist(..),+ getReleaseIds,+ getFedoraReleaseIds,+ getFedoraDists,+ getEPELReleaseIds,+ getRawhideDist,+ getLatestFedoraDist,+ getLatestEPELDist,+ rawhideVersionId,+ distBranch,+ distRepo,+ distUpdates,+ distOverride,+ mockConfig,+ distVersion,+ kojicmd,+ rpkg,+ rpmDistTag) where++import qualified Data.Text as T+import Data.Text (Text)+import Data.Version+import Text.Read+import Text.ParserCombinators.ReadP (char, eof, string)++#if !MIN_VERSION_base(4,8,0)+import Control.Applicative ((<$>), (*>))+import Data.Traversable (traverse)+#endif++import Distribution.Fedora.ReadProducts+import Distribution.Fedora.Products++-- | The `Dist` datatype specifies the target OS and version.+-- (roughly corresponds to a git branch)+data Dist = RHEL Version -- ^ RHEL version+ | EPEL Int -- ^ EPEL release+ | Fedora Int -- ^ Fedora release+ deriving (Eq, Ord)++instance Show Dist where+ show (Fedora n) = "f" ++ show n+ show (EPEL n) = (if n <= 6 then "el" else "epel") ++ show n+ show (RHEL v) = "rhel-" ++ showVersion v++-- | Read from eg "f29", "epel7"+instance Read Dist where+ readPrec = choice [pFedora, pEPEL, pRHEL] where+ pFedora = Fedora <$> (lift (char 'f') *> readPrec)+ pEPEL = EPEL <$> (lift (string "epel") *> readPrec)+ pRHEL = RHEL <$> lift (do+ v <- string "rhel-" >> parseVersion+ eof+ return v)++getReleases :: IO [Release]+getReleases = do+ file <- getProductsFile+ reverse <$> parseReleases file++-- | gets list of current releases (Fedora and EPEL)+--+-- The data is stored in ~/.fedora/product-versions.json+-- and refreshed from Fedora PDC if older than 5.5 hours+getReleaseIds :: IO [Text]+getReleaseIds = map releaseProductVersionId <$> getReleases++getProductReleases :: Text -> IO [Release]+getProductReleases name =+ filter (\p -> releaseProduct p == name) <$> getReleases++-- getRelease :: Text -> IO (Maybe Release)+-- getRelease pv =+-- find (\p -> releaseProductVersionId p == pv) <$> getReleases++getFedoraReleases :: IO [Release]+getFedoraReleases =+ getProductReleases (T.pack "fedora")++-- | gets current Fedora releases+getFedoraReleaseIds :: IO [Text]+getFedoraReleaseIds =+ map releaseProductVersionId <$> getFedoraReleases++getEPELReleases :: IO [Release]+getEPELReleases =+ getProductReleases (T.pack "epel")++-- | gets current EPEL releases+getEPELReleaseIds :: IO [Text]+getEPELReleaseIds =+ map releaseProductVersionId <$> getEPELReleases++-- | Rawhide version id+rawhideVersionId :: Text+rawhideVersionId = T.pack "fedora-rawhide"++-- fails on rawhide - only use on other releases+releaseMajorVersion :: Release -> Int+releaseMajorVersion = read . T.unpack . releaseVersion++releaseDist :: Release -> Dist+releaseDist = Fedora . releaseMajorVersion++releaseDists :: [Release] -> [Dist]+releaseDists rels =+ map mkDist rels+ where+ mkDist :: Release -> Dist+ mkDist r | releaseProductVersionId r == rawhideVersionId = newerDist latestbranch+ | otherwise = releaseDist r++ latestbranch = maximum $ filter (\p -> releaseProductVersionId p /= rawhideVersionId) rels++ newerDist = Fedora . (+ 1) . releaseMajorVersion++-- | get list of current Fedora Dist's+getFedoraDists :: IO [Dist]+getFedoraDists = releaseDists <$> getFedoraReleases++-- | get current Dist for Fedora Rawhide+getRawhideDist :: IO Dist+getRawhideDist =+ head . releaseDists <$> getFedoraReleases++-- | get newest Fedora branch+getLatestFedoraDist :: IO Dist+getLatestFedoraDist =+ releaseDist . maximum . filter (\p -> releaseProductVersionId p /= rawhideVersionId) <$> getFedoraReleases++-- | get newest EPEL release+getLatestEPELDist :: IO Dist+getLatestEPELDist =+ EPEL . releaseMajorVersion . maximum <$> getEPELReleases++-- activeRelease :: Text -> IO Bool+-- activeRelease pv = do+-- res <- filter (\p -> releaseProductVersionId p == pv) <$> getReleases+-- return $ not (null res)++-- | Maps `Dist` to package dist-git branch name, relative to latest branch+--+-- > distBranch (Fedora 32) (Fedora 33) == "rawhide"+-- > distBranch (Fedora 32) (Fedora 31) == "f31"+distBranch :: Dist -- ^ latest branch+ -> Dist -> String+distBranch branch (Fedora n) | Fedora n > branch = "rawhide"+distBranch _ d = show d++-- | Map `Dist` to DNF/YUM repo name, relative to latest branch+distRepo :: Dist -> Dist -> String+distRepo branched (Fedora n) | Fedora n > branched = "rawhide"+ | otherwise = "fedora"+distRepo _ (EPEL _) = "epel"+distRepo _ (RHEL _) = "rhel"++-- | Map `Dist` to Maybe the DNF/YUM updates repo name, relative to latest branch+distUpdates :: Dist -> Dist -> Maybe String+distUpdates branched (Fedora n) | Fedora n > branched = Nothing+distUpdates _ (Fedora _) = Just "updates"+distUpdates _ _ = Nothing++-- | Whether dist has overrides in Bodhi, relative to latest branch+distOverride :: Dist -> Dist -> Bool+distOverride branch (Fedora n) = Fedora n <= branch+distOverride _ (EPEL n) = n < 9+distOverride _ _ = False++-- | OS release major version for `Dist`, relative to latest branch+distVersion :: Dist -> Dist -> String+distVersion branch (Fedora n) | Fedora n > branch = "rawhide"+distVersion _ (Fedora n) = show n+distVersion _ (EPEL n) = show n+distVersion _ (RHEL n) = show n++-- | Mock configuration for `Dist` and arch, relative to latest branch+mockConfig :: Dist -> Dist -> String -> String+mockConfig branch dist arch =+ let prefix =+ case dist of+ Fedora _ -> "fedora"+ _ -> distRepo branch dist+ in+ prefix ++ "-" ++ distVersion branch dist ++ "-" ++ arch++-- | `Dist` tag (appended to rpm package release field)+rpmDistTag :: Dist -> String+rpmDistTag (Fedora n) = ".fc" ++ show n+rpmDistTag (EPEL n) = ".el" ++ show n+rpmDistTag (RHEL v) = ".el" ++ (show . head . versionBranch) v++-- | Command line tool for `Dist` (eg "koji")+kojicmd :: Dist -> String+kojicmd (RHEL _) = "brew"+kojicmd _ = "koji"++-- | rpkg command for `Dist` (eg "fedpkg")+rpkg :: Dist -> String+rpkg (RHEL _) = "rhpkg"+rpkg _ = "fedpkg"
+ libs/fedora-dists/src/Distribution/Fedora/Branch.hs view
@@ -0,0 +1,180 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE CPP #-}++-- |+-- Module : Distribution.Fedora.Branch+-- Copyright : (C) 2020 Jens Petersen+--+-- Maintainer : Jens Petersen <petersen@fedoraproject.org>+--+-- Explanation: Fedora Branch type and functions++-- This program is free software: you can redistribute it and/or modify+-- it under the terms of the GNU General Public License as published by+-- the Free Software Foundation, either version 3 of the License, or+-- (at your option) any later version.++module Distribution.Fedora.Branch+ ( Branch(..)+ , readBranch+ , readBranch'+ , eitherBranch+ , eitherBranch'+ , readActiveBranch+ , readActiveBranch'+ , eitherActiveBranch+ , newerBranch+ , releaseBranch+ , getFedoraBranches+ , getFedoraBranched+ , branchDestTag+ , branchDist+ , branchTarget+ )+where++#if (defined(MIN_VERSION_base) && MIN_VERSION_base(4,8,0))+#else+import Control.Applicative ((<$>))+#endif++import Data.Char (isDigit)+import qualified Data.Text as T++import qualified Distribution.Fedora as Dist++-- | Branch datatype+--+-- Branch can be rawhide, or a fedora or epel branch+data Branch = EPEL Int | Fedora Int | Rawhide+ deriving (Eq, Ord)++-- | Read a Fedora Branch name, otherwise return branch string+eitherBranch :: String -> Either String Branch+eitherBranch "rawhide" = Right Rawhide+eitherBranch ('f':ns) | all isDigit ns = let br = Fedora (read ns) in Right br+eitherBranch ('e':'p':'e':'l':n) | all isDigit n = let br = EPEL (read n) in Right br+eitherBranch cs = Left cs++-- | Read a Fedora Branch name, otherwise return an error message+eitherBranch' :: String -> Either String Branch+eitherBranch' cs = case eitherBranch cs of+ Right br -> Right br+ Left xs -> Left $ xs ++ " is not a known Fedora/EPEL branch"++-- | Read a Fedora Branch name+readBranch :: String -> Maybe Branch+readBranch bs =+ case eitherBranch bs of+ Left _ -> Nothing+ Right br -> Just br++-- | Unsafely read a Fedora Branch name: errors for unknown branches+readBranch' :: String -> Branch+readBranch' bs =+ case eitherBranch bs of+ Left e -> error' $ "unknown Fedora branch: " ++ e+ Right br -> br++-- | Read a Branch name (one of the list of active branches)+--+-- Provides error strings for inactive or unknown branches.+eitherActiveBranch :: [Branch] -> String -> Either String Branch+eitherActiveBranch active bs =+ case eitherBranch bs of+ Left e -> Left e+ Right br -> if br `elem` active+ then Right br+ else Left bs++-- | Read a Branch name (one of the list of active branches)+--+-- Similar to eitherActiceBranch but ignores any error string+readActiveBranch :: [Branch] -> String -> Maybe Branch+readActiveBranch active cs =+ case eitherActiveBranch active cs of+ Left _ -> Nothing+ Right br -> Just br++-- | Read a Branch name (one of the list of active branches)+--+-- Like readActiveBranch, but errors for inactive or unknown branches.+readActiveBranch' :: [Branch] -> String -> Branch+readActiveBranch' active cs =+ case eitherActiveBranch active cs of+ Left e -> error' $ "inactive Fedora branch: " ++ e+ Right br -> br++instance Show Branch where+ show Rawhide = "rawhide"+ show (Fedora n) = "f" ++ show n+ show (EPEL n) = (if n <= 6 then "el" else "epel") ++ show n++-- | Map Branch to Koji destination tag+branchDestTag :: Branch -> String+branchDestTag Rawhide = "rawhide"+branchDestTag (Fedora n) = show (Fedora n) ++ "-updates-candidate"+branchDestTag (EPEL n) = show (EPEL n) ++ "-testing-candidate"++-- | Default build target associated with a branch+branchTarget :: Branch -> String+branchTarget (Fedora n) = show (Fedora n)+branchTarget (EPEL n) = show (EPEL n)+branchTarget Rawhide = "rawhide"++--getLatestBranch :: IO Branch++-- | Returns newer branch than given one from supplied active branches.+--+-- Branches should be in descending order, eg from getFedoraBranches+newerBranch :: Branch -> [Branch] -> Branch+newerBranch Rawhide _ = Rawhide+newerBranch (Fedora n) branches =+ if Fedora n `elem` branches+ then if Fedora (n+1) `elem` branches+ then Fedora (n+1)+ else Rawhide+ else error' $ "Unsupported branch: " ++ show (Fedora n)+newerBranch (EPEL n) branches =+ if EPEL n `elem` branches+ then if EPEL (n+1) `elem` branches+ then EPEL (n+1)+ else EPEL n+ else error' $ "Unsupported branch: " ++ show (EPEL n)++--olderBranch :: Branch -> Branch+--olderBranch Rawhide = latestBranch+--olderBranch (Fedora n) = Fedora (n-1)++-- | Returns list of active Fedora branches, including rawhide and EPEL+getFedoraBranches :: IO [Branch]+getFedoraBranches = map releaseBranch <$> Dist.getReleaseIds++-- | Maps release-id to Branch+releaseBranch :: T.Text -> Branch+releaseBranch "fedora-rawhide" = Rawhide+releaseBranch rel | "fedora-" `T.isPrefixOf` rel =+ let (_,ver) = T.breakOnEnd "-" rel in+ Fedora $ read . T.unpack $ ver+ | "epel-" `T.isPrefixOf` rel =+ let (_,ver) = T.breakOnEnd "-" rel in+ EPEL $ read . T.unpack $ ver+ | otherwise = error' $ "Unsupport release: " ++ T.unpack rel++-- | Returns list of active Fedora branches, excluding rawhide+getFedoraBranched :: IO [Branch]+getFedoraBranched = filter (/= Rawhide) <$> getFedoraBranches++-- from simple-cmd+error' :: String -> a+#if (defined(MIN_VERSION_base) && MIN_VERSION_base(4,9,0))+error' = errorWithoutStackTrace+#else+error' = error+#endif++-- | Convert a Branch to a Dist+branchDist :: Branch -> IO Dist.Dist+branchDist (Fedora n) = return $ Dist.Fedora n+branchDist (EPEL n) = return $ Dist.EPEL n+branchDist Rawhide = Dist.getRawhideDist
+ libs/fedora-dists/src/Distribution/Fedora/Products.hs view
@@ -0,0 +1,52 @@+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE CPP #-}++module Distribution.Fedora.Products+ ( Release(releaseProductVersionId,releaseVersion,releaseProduct)+ , parseReleases+ )+where++import qualified Data.ByteString.Lazy.Char8 as BL+import Control.Monad (mzero)+import Data.Aeson(eitherDecode, Value(..), FromJSON(..), ToJSON(..),+ pairs,+ (.:), (.=), object)+#if !MIN_VERSION_base(4,13,0)+import Data.Monoid((<>))+#endif+import Data.Text (Text)+#if !MIN_VERSION_base(4,8,0)+import Control.Applicative ((<$>), (<*>))+#endif++data Release = Release {+ releaseProductVersionId :: Text,+ releaseReleases :: [Text],+ releaseAllowedPushTargets :: [[Maybe Value]],+ releaseActive :: Bool,+ releaseName :: Text,+ releaseVersion :: Text,+ releaseShort :: Text,+ releaseProduct :: Text+ } deriving (Show,Eq)++instance Ord Release where+ compare r1 r2 =+ compare (releaseProductVersionId r1) (releaseProductVersionId r2)++instance FromJSON Release where+ parseJSON (Object v) = Release <$> v .: "product_version_id" <*> v .: "releases" <*> v .: "allowed_push_targets" <*> v .: "active" <*> v .: "name" <*> v .: "version" <*> v .: "short" <*> v .: "product"+ parseJSON _ = mzero++instance ToJSON Release where+ toJSON Release {..} = object ["product_version_id" .= releaseProductVersionId, "releases" .= releaseReleases, "allowed_push_targets" .= releaseAllowedPushTargets, "active" .= releaseActive, "name" .= releaseName, "version" .= releaseVersion, "short" .= releaseShort, "product" .= releaseProduct]+ toEncoding Release {..} = pairs ("product_version_id" .= releaseProductVersionId<>"releases" .= releaseReleases<>"allowed_push_targets" .= releaseAllowedPushTargets<>"active" .= releaseActive<>"name" .= releaseName<>"version" .= releaseVersion<>"short" .= releaseShort<>"product" .= releaseProduct)++parseReleases :: FilePath -> IO [Release]+parseReleases filename = do+ input <- BL.readFile filename+ case eitherDecode input of+ Left err -> error $ "Invalid JSON file: " ++ filename ++ "\n" ++ err+ Right r -> return r
+ libs/fedora-dists/src/Distribution/Fedora/ReadProducts.hs view
@@ -0,0 +1,34 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE CPP #-}++module Distribution.Fedora.ReadProducts+ (getProductsFile)+where++import Control.Monad+import Data.Aeson(encode)+import qualified Data.ByteString.Lazy.Char8 as BL+import Data.Time.Clock (diffUTCTime, getCurrentTime)+import Fedora.PDC (makeKey, pdcProductVersions)+import System.Directory+import System.FilePath ((</>))++getProductsFile :: IO FilePath+getProductsFile = do+ home <- getHomeDirectory+ let dir = home </> ".fedora"+ dirExists <- doesDirectoryExist dir+ unless dirExists $ createDirectory dir+ let file = dir </> "product-versions-2.json"+ recent <- do+ have <- doesFileExist file+ if have then do+ ts <- getModificationTime file+ t <- getCurrentTime+ -- about 5.5 hours+ return $ diffUTCTime t ts < 20000+ else return False+ unless recent $+ pdcProductVersions "pdc.fedoraproject.org" (makeKey "active" "true") >>=+ BL.writeFile file . encode+ return file
+ libs/koji-hs/LICENSE view
@@ -0,0 +1,339 @@+ GNU GENERAL PUBLIC LICENSE+ Version 2, June 1991++ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA+ Everyone is permitted to copy and distribute verbatim copies+ of this license document, but changing it is not allowed.++ Preamble++ The licenses for most software are designed to take away your+freedom to share and change it. By contrast, the GNU General Public+License is intended to guarantee your freedom to share and change free+software--to make sure the software is free for all its users. This+General Public License applies to most of the Free Software+Foundation's software and to any other program whose authors commit to+using it. (Some other Free Software Foundation software is covered by+the GNU Lesser General Public License instead.) You can apply it to+your programs, too.++ When we speak of free software, we are referring to freedom, not+price. Our General Public Licenses are designed to make sure that you+have the freedom to distribute copies of free software (and charge for+this service if you wish), that you receive source code or can get it+if you want it, that you can change the software or use pieces of it+in new free programs; and that you know you can do these things.++ To protect your rights, we need to make restrictions that forbid+anyone to deny you these rights or to ask you to surrender the rights.+These restrictions translate to certain responsibilities for you if you+distribute copies of the software, or if you modify it.++ For example, if you distribute copies of such a program, whether+gratis or for a fee, you must give the recipients all the rights that+you have. You must make sure that they, too, receive or can get the+source code. And you must show them these terms so they know their+rights.++ We protect your rights with two steps: (1) copyright the software, and+(2) offer you this license which gives you legal permission to copy,+distribute and/or modify the software.++ Also, for each author's protection and ours, we want to make certain+that everyone understands that there is no warranty for this free+software. If the software is modified by someone else and passed on, we+want its recipients to know that what they have is not the original, so+that any problems introduced by others will not reflect on the original+authors' reputations.++ Finally, any free program is threatened constantly by software+patents. We wish to avoid the danger that redistributors of a free+program will individually obtain patent licenses, in effect making the+program proprietary. To prevent this, we have made it clear that any+patent must be licensed for everyone's free use or not licensed at all.++ The precise terms and conditions for copying, distribution and+modification follow.++ GNU GENERAL PUBLIC LICENSE+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION++ 0. This License applies to any program or other work which contains+a notice placed by the copyright holder saying it may be distributed+under the terms of this General Public License. The "Program", below,+refers to any such program or work, and a "work based on the Program"+means either the Program or any derivative work under copyright law:+that is to say, a work containing the Program or a portion of it,+either verbatim or with modifications and/or translated into another+language. (Hereinafter, translation is included without limitation in+the term "modification".) Each licensee is addressed as "you".++Activities other than copying, distribution and modification are not+covered by this License; they are outside its scope. The act of+running the Program is not restricted, and the output from the Program+is covered only if its contents constitute a work based on the+Program (independent of having been made by running the Program).+Whether that is true depends on what the Program does.++ 1. You may copy and distribute verbatim copies of the Program's+source code as you receive it, in any medium, provided that you+conspicuously and appropriately publish on each copy an appropriate+copyright notice and disclaimer of warranty; keep intact all the+notices that refer to this License and to the absence of any warranty;+and give any other recipients of the Program a copy of this License+along with the Program.++You may charge a fee for the physical act of transferring a copy, and+you may at your option offer warranty protection in exchange for a fee.++ 2. You may modify your copy or copies of the Program or any portion+of it, thus forming a work based on the Program, and copy and+distribute such modifications or work under the terms of Section 1+above, provided that you also meet all of these conditions:++ a) You must cause the modified files to carry prominent notices+ stating that you changed the files and the date of any change.++ b) You must cause any work that you distribute or publish, that in+ whole or in part contains or is derived from the Program or any+ part thereof, to be licensed as a whole at no charge to all third+ parties under the terms of this License.++ c) If the modified program normally reads commands interactively+ when run, you must cause it, when started running for such+ interactive use in the most ordinary way, to print or display an+ announcement including an appropriate copyright notice and a+ notice that there is no warranty (or else, saying that you provide+ a warranty) and that users may redistribute the program under+ these conditions, and telling the user how to view a copy of this+ License. (Exception: if the Program itself is interactive but+ does not normally print such an announcement, your work based on+ the Program is not required to print an announcement.)++These requirements apply to the modified work as a whole. If+identifiable sections of that work are not derived from the Program,+and can be reasonably considered independent and separate works in+themselves, then this License, and its terms, do not apply to those+sections when you distribute them as separate works. But when you+distribute the same sections as part of a whole which is a work based+on the Program, the distribution of the whole must be on the terms of+this License, whose permissions for other licensees extend to the+entire whole, and thus to each and every part regardless of who wrote it.++Thus, it is not the intent of this section to claim rights or contest+your rights to work written entirely by you; rather, the intent is to+exercise the right to control the distribution of derivative or+collective works based on the Program.++In addition, mere aggregation of another work not based on the Program+with the Program (or with a work based on the Program) on a volume of+a storage or distribution medium does not bring the other work under+the scope of this License.++ 3. You may copy and distribute the Program (or a work based on it,+under Section 2) in object code or executable form under the terms of+Sections 1 and 2 above provided that you also do one of the following:++ a) Accompany it with the complete corresponding machine-readable+ source code, which must be distributed under the terms of Sections+ 1 and 2 above on a medium customarily used for software interchange; or,++ b) Accompany it with a written offer, valid for at least three+ years, to give any third party, for a charge no more than your+ cost of physically performing source distribution, a complete+ machine-readable copy of the corresponding source code, to be+ distributed under the terms of Sections 1 and 2 above on a medium+ customarily used for software interchange; or,++ c) Accompany it with the information you received as to the offer+ to distribute corresponding source code. (This alternative is+ allowed only for noncommercial distribution and only if you+ received the program in object code or executable form with such+ an offer, in accord with Subsection b above.)++The source code for a work means the preferred form of the work for+making modifications to it. For an executable work, complete source+code means all the source code for all modules it contains, plus any+associated interface definition files, plus the scripts used to+control compilation and installation of the executable. However, as a+special exception, the source code distributed need not include+anything that is normally distributed (in either source or binary+form) with the major components (compiler, kernel, and so on) of the+operating system on which the executable runs, unless that component+itself accompanies the executable.++If distribution of executable or object code is made by offering+access to copy from a designated place, then offering equivalent+access to copy the source code from the same place counts as+distribution of the source code, even though third parties are not+compelled to copy the source along with the object code.++ 4. You may not copy, modify, sublicense, or distribute the Program+except as expressly provided under this License. Any attempt+otherwise to copy, modify, sublicense or distribute the Program is+void, and will automatically terminate your rights under this License.+However, parties who have received copies, or rights, from you under+this License will not have their licenses terminated so long as such+parties remain in full compliance.++ 5. You are not required to accept this License, since you have not+signed it. However, nothing else grants you permission to modify or+distribute the Program or its derivative works. These actions are+prohibited by law if you do not accept this License. Therefore, by+modifying or distributing the Program (or any work based on the+Program), you indicate your acceptance of this License to do so, and+all its terms and conditions for copying, distributing or modifying+the Program or works based on it.++ 6. Each time you redistribute the Program (or any work based on the+Program), the recipient automatically receives a license from the+original licensor to copy, distribute or modify the Program subject to+these terms and conditions. You may not impose any further+restrictions on the recipients' exercise of the rights granted herein.+You are not responsible for enforcing compliance by third parties to+this License.++ 7. If, as a consequence of a court judgment or allegation of patent+infringement or for any other reason (not limited to patent issues),+conditions are imposed on you (whether by court order, agreement or+otherwise) that contradict the conditions of this License, they do not+excuse you from the conditions of this License. If you cannot+distribute so as to satisfy simultaneously your obligations under this+License and any other pertinent obligations, then as a consequence you+may not distribute the Program at all. For example, if a patent+license would not permit royalty-free redistribution of the Program by+all those who receive copies directly or indirectly through you, then+the only way you could satisfy both it and this License would be to+refrain entirely from distribution of the Program.++If any portion of this section is held invalid or unenforceable under+any particular circumstance, the balance of the section is intended to+apply and the section as a whole is intended to apply in other+circumstances.++It is not the purpose of this section to induce you to infringe any+patents or other property right claims or to contest validity of any+such claims; this section has the sole purpose of protecting the+integrity of the free software distribution system, which is+implemented by public license practices. Many people have made+generous contributions to the wide range of software distributed+through that system in reliance on consistent application of that+system; it is up to the author/donor to decide if he or she is willing+to distribute software through any other system and a licensee cannot+impose that choice.++This section is intended to make thoroughly clear what is believed to+be a consequence of the rest of this License.++ 8. If the distribution and/or use of the Program is restricted in+certain countries either by patents or by copyrighted interfaces, the+original copyright holder who places the Program under this License+may add an explicit geographical distribution limitation excluding+those countries, so that distribution is permitted only in or among+countries not thus excluded. In such case, this License incorporates+the limitation as if written in the body of this License.++ 9. The Free Software Foundation may publish revised and/or new versions+of the General Public License from time to time. Such new versions will+be similar in spirit to the present version, but may differ in detail to+address new problems or concerns.++Each version is given a distinguishing version number. If the Program+specifies a version number of this License which applies to it and "any+later version", you have the option of following the terms and conditions+either of that version or of any later version published by the Free+Software Foundation. If the Program does not specify a version number of+this License, you may choose any version ever published by the Free Software+Foundation.++ 10. If you wish to incorporate parts of the Program into other free+programs whose distribution conditions are different, write to the author+to ask for permission. For software which is copyrighted by the Free+Software Foundation, write to the Free Software Foundation; we sometimes+make exceptions for this. Our decision will be guided by the two goals+of preserving the free status of all derivatives of our free software and+of promoting the sharing and reuse of software generally.++ NO WARRANTY++ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,+REPAIR OR CORRECTION.++ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE+POSSIBILITY OF SUCH DAMAGES.++ END OF TERMS AND CONDITIONS++ How to Apply These Terms to Your New Programs++ If you develop a new program, and you want it to be of the greatest+possible use to the public, the best way to achieve this is to make it+free software which everyone can redistribute and change under these terms.++ To do so, attach the following notices to the program. It is safest+to attach them to the start of each source file to most effectively+convey the exclusion of warranty; and each file should have at least+the "copyright" line and a pointer to where the full notice is found.++ <one line to give the program's name and a brief idea of what it does.>+ Copyright (C) <year> <name of author>++ This program is free software; you can redistribute it and/or modify+ it under the terms of the GNU General Public License as published by+ the Free Software Foundation; either version 2 of the License, or+ (at your option) any later version.++ This program is distributed in the hope that it will be useful,+ but WITHOUT ANY WARRANTY; without even the implied warranty of+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ GNU General Public License for more details.++ You should have received a copy of the GNU General Public License along+ with this program; if not, write to the Free Software Foundation, Inc.,+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.++Also add information on how to contact you by electronic and paper mail.++If the program is interactive, make it output a short notice like this+when it starts in an interactive mode:++ Gnomovision version 69, Copyright (C) year name of author+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.+ This is free software, and you are welcome to redistribute it+ under certain conditions; type `show c' for details.++The hypothetical commands `show w' and `show c' should show the appropriate+parts of the General Public License. Of course, the commands you use may+be called something other than `show w' and `show c'; they could even be+mouse-clicks or menu items--whatever suits your program.++You should also get your employer (if you work as a programmer) or your+school, if any, to sign a "copyright disclaimer" for the program, if+necessary. Here is a sample; alter the names:++ Yoyodyne, Inc., hereby disclaims all copyright interest in the program+ `Gnomovision' (which makes passes at compilers) written by James Hacker.++ <signature of Ty Coon>, 1 April 1989+ Ty Coon, President of Vice++This General Public License does not permit incorporating your program into+proprietary programs. If your program is a subroutine library, you may+consider it more useful to permit linking proprietary applications with the+library. If this is what you want to do, use the GNU Lesser General+Public License instead of this License.
+ libs/koji-hs/src/Fedora/Koji.hs view
@@ -0,0 +1,308 @@+module Fedora.Koji+ ( BuildID(..)+ , BuildInfo(..)+ , buildIDInfo+ , fedoraKojiHub+ , centosKojiHub+ , kojiBuildTags+ , kojiBuildTarget+ , kojiGetBuildID+ , kojiGetBuildState+ , kojiGetBuildTaskID+ , kojiGetCurrentRepo+ , kojiGetRepo+ , kojiGetTaskInfo+ , kojiGetTaskChildren+ , kojiGetTaskState+ , kojiGetUserID+ , kojiLatestBuild+ , kojiLatestBuildRepo+ , kojiListSideTags+ , kojiListTaskIDs+ , kojiUserBuildTasks+ , KojiBuild(..)+ , kojiListTaggedBuilds+ , PackageID(..)+ , TagID(..)+ , TaskID(..)+ , UserID(..)+ , displayID+ , getID+ , readID+ , readID'+ , TaskState(..)+ , getTaskState+ , openTaskStates+ , openTaskValues+ , readTaskState+ , BuildState(..)+ , readBuildState+ , Struct+ , lookupStruct+ , Value (..)+ , getInt+ , getString+ , maybeVal+ , RepoState(..)+ , readRepoState+ )+where++import Data.List+import Data.Maybe+import Network.XmlRpc.Internals++import Fedora.Koji.Internal++class ID a where+ getID :: a -> Int+ mkID :: Int -> a++displayID :: ID a => a -> String+displayID = show . getID++-- FIXME rename to structID ?+readID :: ID a => Struct -> Maybe a+readID st = lookup "id" st >>= fmap mkID . getInt++readID' :: Struct -> Maybe Int+readID' st = lookup "id" st >>= getInt++-- FIXME rename to valueInt ?+getInt :: Value -> Maybe Int+getInt (ValueInt i) = Just i+getInt _ = Nothing++getString :: Value -> Maybe String+getString (ValueString i) = Just i+getString _ = Nothing++newtype TaskID = TaskId Int+ deriving Show++instance ID TaskID where+ getID (TaskId i) = i+ mkID = TaskId++newtype TagID = TagId Int+ deriving Show++instance ID TagID where+ getID (TagId i) = i+ mkID = TagId++newtype UserID = UserId Int+ deriving Show++instance ID UserID where+ getID (UserId i) = i+ mkID = UserId++newtype BuildID = BuildId Int++instance ID BuildID where+ getID (BuildId i) = i+ mkID = BuildId++newtype PackageID = PackageId Int++instance ID PackageID where+ getID (PackageId i) = i+ mkID = PackageId++newtype BuildrootID = BuildrootId Int++instance ID BuildrootID where+ getID (BuildrootId i) = i+ mkID = BuildrootId++data BuildInfo = BuildInfoID Int | BuildInfoNVR String++buildInfo :: BuildInfo -> Info+buildInfo (BuildInfoID bid) = InfoID bid+buildInfo (BuildInfoNVR nvr) = InfoString nvr++buildIDInfo :: BuildID -> BuildInfo+buildIDInfo (BuildId bid) = BuildInfoID bid++fedoraKojiHub :: String+fedoraKojiHub = "https://koji.fedoraproject.org/kojihub"++centosKojiHub :: String+centosKojiHub = "https://koji.mbox.centos.org/kojihub"++kojiGetBuildID :: String -- ^ hub url+ -> String -- ^ NVR+ -> IO (Maybe BuildID)+kojiGetBuildID hubUrl nvr =+ ((fmap BuildId . lookupStruct "id") =<<) <$> getBuild hubUrl (InfoString nvr)++kojiGetBuildTaskID :: String -- ^ hub url+ -> String -- ^ NVR+ -> IO (Maybe TaskID)+kojiGetBuildTaskID hubUrl nvr =+ ((fmap TaskId . lookupStruct "task_id") =<<) <$> getBuild hubUrl (InfoString nvr)++kojiListTaskIDs :: String+ -> Struct -- ^ opts+ -> Struct -- ^ qopts+ -> IO [TaskID]+kojiListTaskIDs hubUrl opts qopts =+ mapMaybe readID <$> listTasks hubUrl opts qopts++kojiUserBuildTasks :: String -> UserID -> Maybe String -> Maybe String -> IO [TaskID]+kojiUserBuildTasks hubUrl userid msource mtarget = do+ tasks <- listTasks hubUrl [("owner",ValueInt (getID userid)),("method",ValueString "build"),("state",openTaskValues)] []+ return $ map TaskId . mapMaybe (lookupStruct "id") $ filter isTheBuild tasks+ where+ isTheBuild :: Struct -> Bool+ isTheBuild st =+ let mreq = lookupStruct "request" st in+ case mreq of+ Nothing -> False+ Just req ->+ maybe True (`isInfixOf` req) msource &&+ maybe True (\ target -> ("<value><string>" ++ target ++ "</string></value>") `isInfixOf` req) mtarget++-- getTagID :: String -- ^ tag+-- -> IO TagID+-- getTagID tag =+-- TagId <$> koji "getTagID" tag++kojiGetUserID :: String -> String -> IO (Maybe UserID)+kojiGetUserID hubUrl name = do+ res <- getUser hubUrl (InfoString name) False+ return $ readID =<< res++kojiBuildTags :: String -> BuildInfo -> IO [String]+kojiBuildTags hubUrl buildinfo = do+ lst <- listTags hubUrl (Just (buildInfo buildinfo)) Nothing False+ return $ mapMaybe (lookupStruct "name") lst++data BuildState = BuildBuilding | BuildComplete | BuildDeleted | BuildFailed | BuildCanceled+ deriving (Eq, Enum, Show)++readBuildState :: Value -> BuildState+readBuildState (ValueInt i) | i `elem` map fromEnum (enumFrom BuildBuilding) = toEnum i+readBuildState _ = error "invalid build state"++kojiGetBuildState :: String -> BuildInfo -> IO (Maybe BuildState)+kojiGetBuildState hubUrl buildinfo =+ ((fmap readBuildState . lookupStruct "state") =<<) <$>+ getBuild hubUrl (buildInfo buildinfo)++data TaskState = TaskFree | TaskOpen | TaskClosed | TaskCanceled | TaskAssigned | TaskFailed+ deriving (Eq, Enum, Show)++openTaskStates :: [TaskState]+openTaskStates = [TaskFree, TaskOpen, TaskAssigned]++openTaskValues :: Value+openTaskValues = ValueArray $ map taskStateToValue openTaskStates+ where+ taskStateToValue :: TaskState -> Value+ taskStateToValue = ValueInt . fromEnum++readTaskState :: Value -> TaskState+readTaskState (ValueInt i) | i `elem` map fromEnum (enumFrom TaskFree) = toEnum i+readTaskState _ = error "invalid task state"++getTaskState :: Struct -> Maybe TaskState+getTaskState st = readTaskState <$> lookup "state" st++kojiGetTaskState :: String -> TaskID -> IO (Maybe TaskState)+kojiGetTaskState hubUrl tid = do+ mti <- getTaskInfo hubUrl (getID tid) False+ return $ case mti of+ Nothing -> Nothing+ Just ti -> readTaskState <$> lookupStruct "state" ti++kojiGetTaskInfo :: String+ -> TaskID+ -> IO (Maybe Struct)+kojiGetTaskInfo hubUrl tid = getTaskInfo hubUrl (getID tid) True+ -- res <- kojiCall "getTaskInfo" [show taskid]+ -- let state = res ^? key "state" % _Integer <&> (toEnum . fromInteger)+ -- arch = res ^? key "arch" % _String+ -- return $ TaskInfo arch state++kojiGetTaskChildren :: String -> TaskID -> Bool -> IO [Struct]+kojiGetTaskChildren hubUrl tid =+ getTaskChildren hubUrl (getID tid)++kojiLatestBuild :: String -- ^ hub+ -> String -- ^ tag+ -> String -- ^ pkg+ -> IO (Maybe Struct)+kojiLatestBuild hubUrl tag pkg =+ listToMaybe <$> getLatestBuilds hubUrl (InfoString tag) Nothing (Just pkg) Nothing++kojiLatestBuildRepo :: String -- ^ hub+ -> String -- ^ tag+ -> Int -- ^ event+ -> String -- ^ pkg+ -> IO (Maybe Struct)+kojiLatestBuildRepo hubUrl tag event pkg =+ listToMaybe <$> getLatestBuilds hubUrl (InfoString tag) (Just event) (Just pkg) Nothing++data KojiBuild+ = KojiBuild+ { kbBuildId :: Int+ , kbPackageId :: Int+ , kbOwnerName :: String+ , kbNvr :: String+ }+ deriving (Show)++kojiListTaggedBuilds :: String -> Bool -> String -> IO [KojiBuild]+kojiListTaggedBuilds hubUrl latest tag =+ mapMaybe readKojiBuild <$> listTagged hubUrl tag Nothing False Nothing latest Nothing Nothing Nothing+ where+ readKojiBuild :: Struct -> Maybe KojiBuild+ readKojiBuild values = do+ buildId <- lookupStruct "build_id" values+ packageId <- lookupStruct "package_id" values+ owner <- lookupStruct "owner_name" values+ nvr <- lookupStruct "nvr" values+ return $ KojiBuild buildId packageId owner nvr++kojiBuildTarget :: String -- ^ hubUrl+ -> String -- ^ target+ -> IO (Maybe (String, String)) -- ^ (build-tag,dest-tag)+kojiBuildTarget hub target = do+ mres <- maybeStruct <$> getBuildTarget hub target+ case mres of+ Nothing -> return Nothing+ Just res -> return $ readTarget res+ where+ readTarget res = do+ buildtag <- lookupStruct "build_tag_name" res+ desttag <- lookupStruct "dest_tag_name" res+ return (buildtag, desttag)++-- | List sidetags (preferably for user and/or basetag)+kojiListSideTags :: String -- ^ hubUrl+ -> Maybe String -- ^ basetag+ -> Maybe String -- ^ user+ -> IO [String] -- ^ list of sidetags+kojiListSideTags hub mbasetag muser =+ mapMaybe (lookupStruct "name") . structArray <$> listSideTags hub (InfoString <$> mbasetag) (InfoString <$> muser)++data RepoState = RepoInit | RepoReady | RepoExpired | RepoDeleted | RepoProblem+ deriving (Eq, Enum, Show)++readRepoState :: Value -> RepoState+readRepoState (ValueInt i) | i `elem` map fromEnum (enumFrom RepoInit) = toEnum i+readRepoState _ = error "invalid repo state"++-- getRepoState :: Struct -> Maybe RepoState+-- getRepoState st = readRepoState <$> lookup "state" st++kojiGetRepo :: String -> String -> Maybe RepoState -> Maybe Int+ -> IO (Maybe Struct)+kojiGetRepo hub tag mstate mevent =+ maybeStruct <$> getRepo hub tag (fromEnum <$> mstate) mevent False++kojiGetCurrentRepo :: String -> String -> IO (Maybe Struct)+kojiGetCurrentRepo hub tag =+ maybeStruct <$> getRepo hub tag Nothing Nothing False
+ libs/koji-hs/src/Fedora/Koji/Internal.hs view
@@ -0,0 +1,824 @@+-- Note: much of this module is untested and experimental:+-- particularly the functions just returning a Value++module Fedora.Koji.Internal+ ( Info(..)+ , koji+ , hello+ , checkTagAccess+ , checkTagPackage+ , getAPIVersion+ , getActiveRepos+ , getAllArches+ , getAllPerms+ , getArchive+ , getArchiveFile+ , getArchiveType+ , getArchiveTypes+ , getAverageBuildDuration+ , getBuild+ , getBuildConfig+ , getBuildLogs+ , getBuildTarget+ , getBuildTargets+ , getBuildType+ , getBuildroot+ , getBuildrootListing+ , getChangelogEntries+ , getChannel+ , getEvent+ , getExternalRepo+ , getExternalRepoList+ , getFullInheritance+ , getGlobalInheritance+ , getGroupMembers+ , getHost+ , getImageArchive+ , getImageBuild+ , getInheritanceData+ , getLastEvent+ , getLastHostUpdate+ , getLatestBuilds+ , getLatestMavenArchives+ , getLatestRPMS+ , getMavenArchive+ , getMavenBuild+ , getNextRelease+ , getPackage+ , getPackageConfig+ , getPackageID+ , getRPM+ , getRPMDeps+ , getRPMFile+ , getRPMHeaders+ , getRepo+ , getTag+ , getTagExternalRepos+ , getTagGroups+ , getTagID+ , getTaskChildren+ , getTaskDescendents+ , getTaskInfo+ , getTaskRequest+ , getTaskResult+ , getUser+ , getUserPerms+ , getVolume+ , getWinArchive+ , getWinBuild++ , listArchiveFiles+ , listArchives+ , listBTypes+ , listBuildRPMs+ , listBuildroots+ , listBuilds+ , listCGs+ , listChannels+ , listExternalRepos+ , listHosts+ , listPackages+ , listPackagesSimple+ , listRPMFiles+ , listRPMs+ , listSideTags+ , listTagged+ , listTaggedArchives+ , listTaggedRPMS+ , listTags+ , listTaskOutput+ , listTasks+ , listUsers+ , listVolumes++ , repoInfo+ , resubmitTask+ , tagChangedSinceEvent+ , tagHistory+ , taskFinished+ , taskReport++ , Value(..)+ , Struct+ , lookupStruct+-- , readStructString+-- , readStructArray+-- , readMethodParams+ , maybeVal+ , maybeStruct+ , structArray+ , getValue+ )+where++import Data.Maybe+--import Control.Monad.Fail (MonadFail)+--import qualified Data.ByteString.Lazy.Char8 as B+import Network.XmlRpc.Client+import Network.XmlRpc.Internals+--import Network.HTTP.Simple+--import Network.HTTP.Client.Conduit+import Control.Monad.Except (runExceptT)++koji :: Remote a+ => String -- ^ kojihub url+ -> String -- ^ command+ -> a+koji = remote++-- xmlrpc :: String -> String -> [Value] -> IO Value+-- xmlrpc url m args = do+-- initreq <- parseRequest url+-- let reqbody = renderCall (MethodCall m args)+-- request = setRequestBody (RequestBodyLBS reqbody) $ setRequestMethod "POST" initreq+-- resp <- httpLBS request+-- let respbody = getResponseBody resp+-- handleError fail $ (parseResponse (B.unpack respbody) >>= handleResponse)+-- where+-- -- | Gets the return value from a method response.+-- -- Throws an exception if the response was a fault.+-- handleResponse :: MonadFail m => MethodResponse -> m Value+-- handleResponse (Return v) = return v+-- handleResponse (Fault code str) = error ("Error " ++ show code ++ ": " ++ str)++-- FIXME rename to newtype KojiStruct+type Struct = [(String,Value)]++maybeString :: Maybe String -> Value+maybeString = maybe ValueNil ValueString++maybeInt :: Maybe Int -> Value+maybeInt = maybe ValueNil ValueInt++maybeValue :: Maybe Value -> Value+maybeValue = fromMaybe ValueNil++data Info = InfoID Int | InfoString String++infoValue :: Info -> Value+infoValue (InfoID i) = ValueInt i+infoValue (InfoString s) = ValueString s++maybeInfo :: Maybe Info -> Value+maybeInfo = maybe ValueNil infoValue++maybeStruct :: Value -> Maybe Struct+maybeStruct (ValueStruct st) = Just st+maybeStruct _ = Nothing++structArray :: Value -> [Struct]+structArray (ValueArray v) = mapMaybe maybeStruct v+structArray _ = []++-- https://koji.fedoraproject.org/koji/api++-- CG*++-- _listapi()++-- add*++-- applyVolumePolicy(build, strict=False)++-- assignTask(task_id, host, force=False)++-- build(src, target, opts=None, priority=None, channel=None)++-- buildContainer(src, target, opts=None, priority=None, channel='container')++-- buildImage(name, version, arch, target, ksfile, img_type, opts=None, priority=None)++-- buildImageIndirection(opts=None, priority=None)++-- buildImageOz(name, version, arches, target, inst_tree, opts=None, priority=None)++-- buildReferences(build, limit=None, lazy=False)++-- cancelBuild(buildID)++-- cancelTask(task_id, recurse=True)++-- cancelTaskChildren(task_id)++-- cancelTaskFull(task_id, strict=True)++-- chainBuild(srcs, target, opts=None, priority=None, channel=None)++-- chainMaven(builds, target, opts=None, priority=None, channel='maven')++-- changeBuildVolume(build, volume, strict=True)++-- | checkTagAccess(tag_id, user_id=None)+checkTagAccess :: String -> Int -> Int -> IO Value+checkTagAccess hubUrl = koji hubUrl "checkTagAccess"++-- | checkTagPackage(tag, pkg)+checkTagPackage :: String -> Info -> Info -> IO Bool+checkTagPackage hubUrl taginfo pkginfo = koji hubUrl "checkTagPackage" (infoValue taginfo) (infoValue pkginfo)++-- count*++-- create*++-- debugFunction(name, *args, **kwargs)++-- delete*++-- disable*++-- distRepo(tag, keys, **task_opts)++-- downloadTaskOutput(taskID, fileName, offset=0, size=-1, volume=None)++-- dropGroupMember(group, user)++-- echo(*args)++-- edit*++-- enable*++-- error++-- filterResults(methodName, *args, **kw)++-- findBuildID(X, strict=False)++-- freeTask(task_id)++-- | getAPIVersion()+getAPIVersion :: String -> IO String+getAPIVersion hubUrl = koji hubUrl "getAPIVersion"++-- | getActiveRepos()+getActiveRepos :: String -> IO Value+getActiveRepos hubUrl = koji hubUrl "getActiveRepos"++-- | getAllArches+getAllArches :: String -> IO Value+getAllArches hubUrl = koji hubUrl "getAllArches"++-- | getAllPerms+getAllPerms :: String -> IO [Struct]+getAllPerms hubUrl = koji hubUrl "getAllPerms"++-- | getArchive(archive_id, strict=False)+getArchive :: String -> Int -> IO (Maybe Struct)+getArchive hubUrl = fmap maybeStruct . koji hubUrl "getArchive"++-- | getArchiveFile(archive_id, filename, strict=False)+getArchiveFile :: String -> Int -> FilePath -> IO (Maybe Struct)+getArchiveFile hubUrl archiveID file = maybeStruct <$> koji hubUrl "getArchiveFile" archiveID file++-- | getArchiveType(filename=None, type_name=None, type_id=None, strict=False)+getArchiveType :: String -> Maybe FilePath -> Maybe String -> Maybe Int -> IO Value+getArchiveType hubUrl filename type_name type_id =+ koji hubUrl "getArchiveType" (maybeString filename) (maybeString type_name) (maybeInt type_id)++-- | getArchiveTypes()+getArchiveTypes :: String -> IO Value+getArchiveTypes hubUrl = koji hubUrl "getArchiveTypes"++-- | getAverageBuildDuration pkginfo+getAverageBuildDuration :: String -> Info -> IO Value+getAverageBuildDuration hubUrl = koji hubUrl "getAverageBuildDuration" . infoValue++-- | getBuild(buildInfo, strict=False)+getBuild :: String+ -> Info -- ^ buildID+ -> IO (Maybe Struct)+getBuild hubUrl = fmap maybeStruct . koji hubUrl "getBuild" . infoValue++-- | getBuildConfig tag+getBuildConfig :: String -> String -> IO Value+getBuildConfig hubUrl = koji hubUrl "getBuildConfig"++-- | getBuildLogs build+getBuildLogs :: String -> Info -- ^ buildinfo+ -> IO Value+getBuildLogs hubUrl = koji hubUrl "getBuildLogs" . infoValue++-- | getBuildTarget info+getBuildTarget :: String -> String -> IO Value+getBuildTarget hubUrl = koji hubUrl "getBuildTarget"++-- | getBuildTargets info event buildTagID destTagID+getBuildTargets :: String -> Maybe Info -> Maybe Int -> Maybe Int -> Maybe Int -> IO Value+getBuildTargets hubUrl info event buildTagId destTagId =+ koji hubUrl "getBuildTargets" (maybeInfo info) (maybeInt event) (maybeInt buildTagId) (maybeInt destTagId)++-- | getBuildType buildinfo+getBuildType :: String -> Info -- ^ buildinfo+ -> IO Value+getBuildType hubUrl = koji hubUrl "getBuildType" . infoValue++-- | getBuildroot buildrootId+getBuildroot :: String -> Int -> IO Value+getBuildroot hubUrl = koji hubUrl "getBuildroot"++-- | getBuildrootListing buildrootId+getBuildrootListing :: String -> Int -> IO Value+getBuildrootListing hubUrl = koji hubUrl "getBuildrootListing"++-- | getChangelogEntries(buildID=None, taskID=None, filepath=None, author=None, before=None, after=None, queryOpts=None)+getChangelogEntries :: String+ -> Maybe Int -- ^ buildID+ -> Maybe Int -- ^ taskID+ -> Maybe FilePath+ -> Maybe String -- ^ author+ -> Maybe String -- ^ before+ -> Maybe String -- ^ after+ -> IO [Struct]+getChangelogEntries hubUrl buildID taskID filepath author before after =+ koji hubUrl "getChangelogEntries" (maybeInt buildID) (maybeInt taskID) (maybeString filepath) (maybeString author) (maybeString before) (maybeString after)++-- | getChannel channelinfo+getChannel :: String -> Info -> IO Value+getChannel hubUrl = koji hubUrl "getChannel" . infoValue++-- | getEvent eventid+getEvent :: String -> Int -> IO Struct+getEvent hubUrl = koji hubUrl "getEvent"++-- | getExternalRepo info+getExternalRepo :: String -> Info -> Maybe Int -> IO Struct+getExternalRepo hubUrl info event =+ koji hubUrl "getExternalRepo" (infoValue info) () (maybeInt event)++-- | getExternalRepoList(tag_info, event=None)+getExternalRepoList :: String -> Info -> Maybe Int -> IO [Struct]+getExternalRepoList hubUrl info event =+ koji hubUrl "getExternalRepoList" (infoValue info) (maybeInt event)++-- | getFullInheritance(tag, event=None, reverse=False, stops=None, jumps=None)+getFullInheritance :: String -> String -> Maybe Int -> Bool -> IO Value+getFullInheritance hubUrl tag event =+ koji hubUrl "getFullInheritance" tag (maybeInt event)++-- | getGlobalInheritance(event=None)+getGlobalInheritance :: String -> Maybe Int -> IO Value+getGlobalInheritance hubUrl = koji hubUrl "getGlobalInheritance" . maybeInt++-- | getGroupMembers(group)+getGroupMembers :: String -> String -> IO Value+getGroupMembers hubUrl = koji hubUrl "getGroupMembers"++-- | getHost(hostInfo, strict=False, event=None)+getHost :: String -> Info -> Maybe Int -> IO Struct+getHost hubUrl info = koji hubUrl "getHost" (infoValue info) () . maybeInt++-- | getImageArchive(archive_id, strict=False)+getImageArchive :: String -> Int -> IO Struct+getImageArchive hubUrl = koji hubUrl "getImageArchive"++-- | getImageBuild(buildInfo, strict=False)+getImageBuild :: String -> Info -> IO Struct+getImageBuild hubUrl info = koji hubUrl "getImageBuild" (infoValue info)++-- | getInheritanceData(tag, event=None)+getInheritanceData :: String -> String -> Maybe Int -> IO Value+getInheritanceData hubUrl tag event =+ koji hubUrl "getInheritanceData" tag (maybeInt event)+++-- | getLastEvent(before=None)+getLastEvent :: String -> Maybe Int -> IO Value+getLastEvent hubUrl = koji hubUrl "getLastEvent" . maybeInt++-- | getLastHostUpdate(hostID)+getLastHostUpdate :: String -> Int -> IO Value+getLastHostUpdate hubUrl = koji hubUrl "getLastHostUpdate"++-- | getLatestBuilds(tag, event=None, package=None, type=None)+--+-- List latest builds for tag (inheritance enabled)+getLatestBuilds :: String+ -> Info -- ^ tag+ -> Maybe Int -- ^ event+ -> Maybe String -- ^ pkg+ -> Maybe String -- ^ type+ -> IO [Struct]+getLatestBuilds hubUrl tag event pkg type_ =+ koji hubUrl "getLatestBuilds" (infoValue tag) (maybeInt event) (maybeString pkg) (maybeString type_)++-- | getLatestMavenArchives(tag, event=None, inherit=True)+getLatestMavenArchives :: String -> String -> Maybe Int -> Bool -> IO Value+getLatestMavenArchives hubUrl tag event =+ koji hubUrl "getLatestMavenArchives" tag (maybeInt event)++-- | getLatestRPMS(tag, package=None, arch=None, event=None, rpmsigs=False, type=None)+getLatestRPMS :: String -> String -> Maybe String -> Maybe String -> Maybe Int -> Bool -> Maybe String -> IO Value+getLatestRPMS hubUrl tag pkg arch event rpmsigs type_ =+ koji hubUrl "getLatestRPMS" tag (maybeString pkg) (maybeString arch) (maybeInt event) rpmsigs (maybeString type_)++-- getLoggedInUser()++-- | getMavenArchive(archive_id, strict=False)+getMavenArchive :: String -> Int -> IO Struct+getMavenArchive hubUrl = koji hubUrl "getMavenArchive"++-- | getMavenBuild(buildInfo, strict=False)+getMavenBuild :: String -> Info -> IO Struct+getMavenBuild hubUrl info = koji hubUrl "getMavenBuild" (infoValue info)++-- | getNextRelease(build_info)+--+-- find the last successful or deleted build of this N-V.+-- If building is specified, skip also builds in progress+getNextRelease :: String -> Info -> IO Value+getNextRelease hubUrl info = koji hubUrl "getNextRelease" (infoValue info)++-- | getPackage(info, strict=False, create=False)+--+-- Get the id,name for package+getPackage :: String -> Info -> IO Value+getPackage hubUrl info = koji hubUrl "getPackage" (infoValue info)++-- | getPackageConfig(tag, pkg, event=None)+--+-- Get config for package in tag+getPackageConfig :: String -> String -> String -> Maybe Int -> IO Value+getPackageConfig hubUrl tag pkg event =+ koji hubUrl "getPackageConfig" tag pkg (maybeInt event)++-- | getPackageID(name, strict=False)+--+-- Get package ID by name.+getPackageID :: String -> String -> IO (Maybe Int)+getPackageID hubUrl pkg = do+ res <- koji hubUrl "getPackageID" pkg+ case res of+ ValueInt i -> return $ Just i+ _ -> return Nothing++-- | getRPM(rpminfo, strict=False, multi=False)+getRPM :: String -> Info -> IO Struct+getRPM hubUrl = koji hubUrl "getRPM" . infoValue++-- | getRPMDeps(rpmID, depType=None, queryOpts=None, strict=False)+getRPMDeps :: String -> Int -> Maybe String -> IO [Struct]+getRPMDeps hubUrl rpmid deptype =+ koji hubUrl "getRPMDeps" rpmid (maybeString deptype)++-- | getRPMFile(rpmID, filename, strict=False)+getRPMFile :: String -> Int -> FilePath -> IO Struct+getRPMFile hubUrl = koji hubUrl "getRPMFile"++-- | getRPMHeaders(rpmID=None, taskID=None, filepath=None, headers=None)+getRPMHeaders :: String -> Maybe Int -> Maybe Int -> Maybe FilePath -> Maybe Value -> IO Struct+getRPMHeaders hubUrl rpmid taskid file headers =+ koji hubUrl "getRPMHeaders" (maybeInt rpmid) (maybeInt taskid) (maybeString file) (fromMaybe ValueNil headers)++-- | getRepo(tag, state=None, event=None, dist=False)+getRepo :: String -> String -> Maybe Int -> Maybe Int -> Bool -> IO Value+getRepo hubUrl tag state event =+ koji hubUrl "getRepo" tag (maybeInt state) (maybeInt event)++-- getSessionInfo()++-- | getTag(tagInfo, strict=False, event=None)+getTag :: String -> Info -> Maybe Int -> IO Struct+getTag hubUrl info = koji hubUrl "getTag" (infoValue info) () . maybeInt++-- | getTagExternalRepos(tag_info=None, repo_info=None, event=None)+getTagExternalRepos :: String -> Maybe Info -> Maybe Info -> Maybe Int -> IO Struct+getTagExternalRepos hubUrl taginfo repoinfo event =+ koji hubUrl "getTagExternalRepos" (maybeInfo taginfo) (maybeInfo repoinfo) (maybeInt event)++-- | getTagGroups(tag, event=None, inherit=True, incl_pkgs=True, incl_reqs=True, incl_blocked=False)+getTagGroups :: String -> String -> Maybe Int -> Bool -> Bool -> Bool -> Bool -> IO Value+getTagGroups hubUrl tag event =+ koji hubUrl "getTagGroups" tag (maybeInt event)++-- | getTagID(info, strict=False, create=False)+getTagID :: String -> Info -> IO Value+getTagID hubUrl = koji hubUrl "getTagID" . infoValue++-- | getTaskChildren(task_id, request=False, strict=False)+getTaskChildren :: String -> Int -> Bool -> IO [Struct]+getTaskChildren hubUrl = koji hubUrl "getTaskChildren"++-- | getTaskDescendents(task_id, request=False)+getTaskDescendents :: String -> Int -> Bool -> IO Struct+getTaskDescendents hubUrl = koji hubUrl "getTaskDescendents"++-- | getTaskInfo(task_id, request=False, strict=False)+getTaskInfo :: String+ -> Int+ -> Bool -- ^ include request details+ -> IO (Maybe Struct)+getTaskInfo hubUrl tid request = maybeStruct <$> koji hubUrl "getTaskInfo" tid request+ -- res <- kojiCall "getTaskInfo" [show taskid]+ -- let state = res ^? key "state" % _Integer <&> (toEnum . fromInteger)+ -- arch = res ^? key "arch" % _String+ -- return $ TaskInfo arch state++-- | getTaskRequest(taskId)+getTaskRequest :: String -> Int -> IO Value+getTaskRequest hubUrl = koji hubUrl "getTaskRequest"++-- | getTaskResult(taskId, raise_fault=True)+getTaskResult :: String -> Int -> IO Value+getTaskResult hubUrl = koji hubUrl "getTaskResult"++-- | getUser(userInfo=None, strict=False, krb_princs=True)+getUser :: String -> Info -> Bool -> IO (Maybe Struct)+getUser hubUrl info krbprncpl =+ maybeStruct <$> koji hubUrl "getUser" (infoValue info) () krbprncpl++-- | getUserPerms(userID=None)+getUserPerms :: String -> Maybe Info -> IO Value+getUserPerms hubUrl = koji hubUrl "getUserPerms" . maybeInfo++-- | getVolume(volume, strict=False)+getVolume :: String -> Info -> IO Value+getVolume hubUrl = koji hubUrl "getVolume" . infoValue++-- | getWinArchive(archive_id, strict=False)+getWinArchive :: String -> Int -> IO Struct+getWinArchive hubUrl = koji hubUrl "getWinArchive"++-- | getWinBuild(buildInfo, strict=False)+getWinBuild :: String -> Info -> IO (Maybe Struct)+getWinBuild hubUrl = fmap maybeStruct . koji hubUrl "getWinBuild" . infoValue++-- grantCGAccess(user, cg, create=False)++-- grantPermission(userinfo, permission, create=False)++-- groupListAdd(taginfo, grpinfo, block=False, force=False, **opts)++-- groupListBlock(taginfo, grpinfo)++-- groupListRemove(taginfo, grpinfo, force=False)++-- groupListUnblock(taginfo, grpinfo)++-- groupPackageListAdd(taginfo, grpinfo, pkg_name, block=False, force=False, **opts)++-- groupPackageListBlock(taginfo, grpinfo, pkg_name)++-- groupPackageListRemove(taginfo, grpinfo, pkg_name, force=False)++-- groupReqListUnblock(taginfo, grpinfo, reqinfo)++-- hasPerm(perm, strict=False)++hello :: String -> IO String+hello hubUrl = koji hubUrl "hello"++-- host.* [skipped]++-- importArchive(filepath, buildinfo, type, typeInfo)++-- importRPM(path, basename)++-- krbLogin(*args, **opts)++-- | listArchiveFiles(archive_id, queryOpts=None, strict=False)+listArchiveFiles :: String -> Int -> IO [Struct]+listArchiveFiles hubUrl = koji hubUrl "listArchiveFiles"++-- | listArchives(buildID=None, buildrootID=None, componentBuildrootID=None, hostID=None, type=None, filename=None, size=None, checksum=None, typeInfo=None, queryOpts=None, imageID=None, archiveID=None, strict=False)+listArchives :: String -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe String -> Maybe FilePath -> Maybe Int -> Maybe String -> Maybe Info -> Maybe Int -> Maybe Int -> IO [Struct]+listArchives hubUrl buildID buildrootID componentBuildrootID hostID type_ file size checksum typeInfo imageID archiveID =+ koji hubUrl "listArchives" (maybeInt buildID) (maybeInt buildrootID) (maybeInt componentBuildrootID) (maybeInt hostID) (maybeString type_) (maybeString file) (maybeInt size) (maybeString checksum) (maybeInfo typeInfo) () (maybeInt imageID) (maybeInt archiveID)++-- | listBTypes(query=None, queryOpts=None)+listBTypes :: String -> Value -> IO Value+listBTypes hubUrl = koji hubUrl "listBTypes"++-- | listBuildRPMs(build)+listBuildRPMs :: String -> Int -> IO [Struct]+listBuildRPMs hubUrl = koji hubUrl "listBuildRPMs"++-- | listBuildroots(hostID=None, tagID=None, state=None, rpmID=None, archiveID=None, taskID=None, buildrootID=None, queryOpts=None)+listBuildroots :: String -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> IO Value+listBuildroots hubUrl hostID tagID state rpmID archiveID taskID buildrootID =+ koji hubUrl "listBuildroots" (maybeInt hostID) (maybeInt tagID) (maybeInt state) (maybeInt rpmID) (maybeInt archiveID) (maybeInt taskID) (maybeInt buildrootID)++-- | listBuilds (packageID=None, userID=None, taskID=None, prefix=None, state=None, volumeID=None, source=None, createdBefore=None, createdAfter=None, completeBefore=None, completeAfter=None, type=None, typeInfo=None, queryOpts=None)+listBuilds :: String -> Struct -> IO [Struct]+listBuilds hubUrl args =+ let maybeArg fld = maybeValue (lookupStruct fld args) in+ koji hubUrl "listBuilds" (maybeArg "packageID") (maybeArg "userID") (maybeArg "taskID") (maybeArg "prefix") (maybeArg "state") (maybeArg "volumeID") (maybeArg "source") (maybeArg "createdBefore") (maybeArg "createdAfter") (maybeArg "completeBefore") (maybeArg "completeAfter") (maybeArg "type") (maybeArg "typeInfo") (maybeArg "queryOpts")++-- | listCGs()+listCGs :: String -> IO Struct+listCGs hubUrl = koji hubUrl "listCGs"++-- | listChannels(hostID=None, event=None)+listChannels :: String -> Maybe Int -> Maybe Int -> IO Value+listChannels hubUrl hostID event =+ koji hubUrl "listChannels" (maybeInt hostID) (maybeInt event)++-- | listExternalRepos(info=None, url=None, event=None, queryOpts=None)+listExternalRepos :: String -> Maybe Info -> Maybe String -> Maybe Int -> IO Value+listExternalRepos hubUrl info url event =+ koji hubUrl "listExternalRepos" (maybeInfo info) (maybeString url) (maybeInt event)++-- | listHosts(arches=None, channelID=None, ready=None, enabled=None, userID=None, queryOpts=None)+listHosts :: String -> Maybe Value -> Maybe Int -> Bool -> Bool -> Maybe Int -> IO Value+listHosts hubUrl arches channelID ready enabled userID =+ koji hubUrl "listHosts" (maybeValue arches) (maybeInt channelID) ready enabled (maybeInt userID)++-- | listPackages(tagID=None, userID=None, pkgID=None, prefix=None, inherited=False, with_dups=False, event=None, queryOpts=None)+listPackages :: String -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe String -> Bool -> Bool -> Maybe Int -> IO [Struct]+listPackages hubUrl tagID userID pkgID prefix inherited with_dups event =+ koji hubUrl "listPackages" (maybeInt tagID) (maybeInt userID) (maybeInt pkgID) (maybeString prefix) inherited with_dups (maybeInt event)++-- | listPackagesSimple prefix+listPackagesSimple :: String -> String -- ^ package name search prefix+ -> IO [Struct]+listPackagesSimple hubUrl = koji hubUrl "listPackagesSimple"++-- | listRPMFiles(rpmID, queryOpts=None)+listRPMFiles :: String -> Int -> IO [Struct]+listRPMFiles hubUrl = koji hubUrl "listRPMFiles"++-- | listRPMs(buildID=None, buildrootID=None, imageID=None, componentBuildrootID=None, hostID=None, arches=None, queryOpts=None)+listRPMs :: String -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Value -> IO [Struct]+listRPMs hubUrl buildID buildrootID imageID componentBuildrootID hostID arches =+ koji hubUrl "listRPMs" (maybeInt buildID) (maybeInt buildrootID) (maybeInt imageID) (maybeInt componentBuildrootID) (maybeInt hostID) (maybeValue arches)++-- | listSideTags(basetag=None, user=None, queryOpts=None)+listSideTags :: String -> Maybe Info -> Maybe Info -> IO Value+listSideTags hubUrl basetag user = do+ koji hubUrl "listSideTags" (maybeInfo basetag) (maybeInfo user)++-- | listTagged(tag, event=None, inherit=False, prefix=None, latest=False, package=None, owner=None, type=None)+listTagged :: String -> String -> Maybe Int -> Bool -> Maybe String -> Bool -> Maybe String -> Maybe String -> Maybe String -> IO [Struct]+listTagged hubUrl tag event inherit prefix latest package owner type_ =+ koji hubUrl "listTagged" tag (maybeInt event) inherit (maybeString prefix) latest (maybeString package) (maybeString owner) (maybeString type_)++-- | listTaggedArchives(tag, event=None, inherit=False, latest=False, package=None, type=None)+listTaggedArchives :: String -> String -> Maybe Int -> Bool -> Bool -> Maybe String -> Maybe String -> IO Value+listTaggedArchives hubUrl tag event inherit latest package type_ =+ koji hubUrl "listTaggedArchives" tag (maybeInt event) inherit latest (maybeString package) (maybeString type_)++-- | listTaggedRPMS(tag, event=None, inherit=False, latest=False, package=None, arch=None, rpmsigs=False, owner=None, type=None)+listTaggedRPMS :: String -> String -> Maybe Int -> Bool -> Bool -> Maybe String -> Maybe String -> Bool -> Maybe String -> Maybe String -> IO Value+listTaggedRPMS hubUrl tag event inherit latest package arch rpmsigs owner type_ =+ koji hubUrl "listTaggedRPMS" tag (maybeInt event) inherit latest (maybeString package) (maybeString arch) rpmsigs (maybeString owner) (maybeString type_)++-- | listTags(build=None, package=None, perms=True, queryOpts=None)+listTags :: String -> Maybe Info -> Maybe Info -> Bool -> IO [Struct]+listTags hubUrl build package =+ koji hubUrl "listTags" (maybeInfo build) (maybeInfo package)++-- | listTaskOutput(taskID, stat=False, all_volumes=False, strict=False)+listTaskOutput :: String -> Int -> Bool -> Bool -> Bool -> IO Struct+listTaskOutput hubUrl = koji hubUrl "listTaskOutput"++-- | listTasks(opts=None, queryOpts=None)+listTasks :: String -> Struct -- ^ opts+ -> Struct -- ^ qopts+ -> IO [Struct]+listTasks hubUrl = koji hubUrl "listTasks"++-- | listUsers(userType=0, prefix=None, queryOpts=None)+listUsers :: String -> Maybe Int -> Maybe String -> IO [Struct]+listUsers hubUrl userType prefix =+ koji hubUrl "listUsers" (maybeInt userType) (maybeString prefix)++-- | listVolumes()+listVolumes :: String -> IO Value+listVolumes hubUrl = koji hubUrl "listVolumes"++-- login(*args, **opts)++-- logout()++-- logoutChild(session_id)++-- makeTask(*args, **opts)++-- mavenBuild(url, target, opts=None, priority=None, channel='maven')++-- mavenEnabled()++-- mergeScratch(task_id)++-- moveAllBuilds(tag1, tag2, package, force=False)++-- moveBuild(tag1, tag2, build, force=False)++-- newGroup(name)++-- newRepo(tag, event=None, src=False, debuginfo=False, separate_src=False)++-- packageListAdd(taginfo, pkginfo, owner=None, block=None, extra_arches=None, force=False, update=False)++-- packageListBlock(taginfo, pkginfo, force=False)++-- packageListRemove(taginfo, pkginfo, force=False)++-- packageListSetArches(taginfo, pkginfo, arches, force=False)++-- packageListSetOwner(taginfo, pkginfo, owner, force=False)++-- packageListUnblock(taginfo, pkginfo, force=False)++-- queryHistory(tables=None, **kwargs)++-- queryRPMSigs(rpm_id=None, sigkey=None, queryOpts=None)++-- remove*++-- repo*++-- | repoInfo(repo_id, strict=False)+repoInfo :: String -> Int -> IO Value+repoInfo hubUrl = koji hubUrl "repoInfo"++-- resetBuild(build)++-- restartHosts(priority=5, options=None)++-- | resubmitTask(taskID)+resubmitTask :: String -> Int -> IO Value+resubmitTask hubUrl = koji hubUrl "resubmitTask"++-- revoke*++-- runroot(tagInfo, arch, command, channel=None, **opts)++-- search(terms, type, matchType, queryOpts=None)++-- set*++-- sharedSession()++-- showOpts()++-- showSession()++-- sslLogin(*args, **opts)++-- subsession()++-- system.*++-- tagBuild(tag, build, force=False, fromtag=None)++-- tagBuildBypass(tag, build, force=False, notify=True)++-- | tagChangedSinceEvent(event, taglist)+tagChangedSinceEvent :: String -> Int -> Value -> IO Bool+tagChangedSinceEvent hubUrl = koji hubUrl "tagChangedSinceEvent"++-- | tagHistory(build=None, tag=None, package=None, active=None, queryOpts=None)+tagHistory :: String -> Maybe Info -> Maybe Info -> Maybe Info -> Bool -> IO Value+tagHistory hubUrl build tag package =+ koji hubUrl "tagHistory" (maybeInfo build) (maybeInfo tag) (maybeInfo package)++-- | taskFinished(taskId)+taskFinished :: String -> Int -> IO Bool+taskFinished hubUrl = koji hubUrl "taskFinished"++-- | taskReport(owner=None)+taskReport :: String -> Maybe String -> IO Value+taskReport hubUrl = koji hubUrl "taskReport" . maybeString++-- untag*++-- updateNotification(id, package_id, tag_id, success_only)++-- uploadFile(path, name, size, md5sum, offset, data, volume=None)++-- winBuild(vm, url, target, opts=None, priority=None, channel='vm')++-- winEnabled()++-- wrapperRPM(build, url, target, priority=None, channel='maven', opts=None)++-- writeSignedRPM(an_rpm, sigkey, force=False)+++-- readStructString :: String -> Struct -> String+-- readStructString key str =+-- case lookup key str of+-- Just (ValueString s) -> s+-- _ -> error $ "No String for " ++ key++-- readStructArray :: String -> Struct -> Maybe [Value]+-- readStructArray key struct =+-- either error id <$> runExceptT (getField key struct)+-- -- Just (ValueArray s) -> s+-- -- _ -> error $ "No Array for " ++ key++-- readMethodParams :: String -> Maybe [Value]+-- readMethodParams s =+-- either error params <$> runExceptT (parseCall s)+-- where+-- params (MethodCall _m str) = str++lookupStruct :: XmlRpcType a => String -> Struct -> Maybe a+lookupStruct key struct =+ either error id <$> runExceptT (getField key struct)++maybeVal :: String -> Maybe a -> a+maybeVal err = fromMaybe (error err)++getValue :: XmlRpcType a => Value -> Maybe a+getValue = fmap (either error id) . runExceptT . fromValue
+ libs/pagure-hs/LICENSE view
@@ -0,0 +1,339 @@+ GNU GENERAL PUBLIC LICENSE+ Version 2, June 1991++ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA+ Everyone is permitted to copy and distribute verbatim copies+ of this license document, but changing it is not allowed.++ Preamble++ The licenses for most software are designed to take away your+freedom to share and change it. By contrast, the GNU General Public+License is intended to guarantee your freedom to share and change free+software--to make sure the software is free for all its users. This+General Public License applies to most of the Free Software+Foundation's software and to any other program whose authors commit to+using it. (Some other Free Software Foundation software is covered by+the GNU Lesser General Public License instead.) You can apply it to+your programs, too.++ When we speak of free software, we are referring to freedom, not+price. Our General Public Licenses are designed to make sure that you+have the freedom to distribute copies of free software (and charge for+this service if you wish), that you receive source code or can get it+if you want it, that you can change the software or use pieces of it+in new free programs; and that you know you can do these things.++ To protect your rights, we need to make restrictions that forbid+anyone to deny you these rights or to ask you to surrender the rights.+These restrictions translate to certain responsibilities for you if you+distribute copies of the software, or if you modify it.++ For example, if you distribute copies of such a program, whether+gratis or for a fee, you must give the recipients all the rights that+you have. You must make sure that they, too, receive or can get the+source code. And you must show them these terms so they know their+rights.++ We protect your rights with two steps: (1) copyright the software, and+(2) offer you this license which gives you legal permission to copy,+distribute and/or modify the software.++ Also, for each author's protection and ours, we want to make certain+that everyone understands that there is no warranty for this free+software. If the software is modified by someone else and passed on, we+want its recipients to know that what they have is not the original, so+that any problems introduced by others will not reflect on the original+authors' reputations.++ Finally, any free program is threatened constantly by software+patents. We wish to avoid the danger that redistributors of a free+program will individually obtain patent licenses, in effect making the+program proprietary. To prevent this, we have made it clear that any+patent must be licensed for everyone's free use or not licensed at all.++ The precise terms and conditions for copying, distribution and+modification follow.++ GNU GENERAL PUBLIC LICENSE+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION++ 0. This License applies to any program or other work which contains+a notice placed by the copyright holder saying it may be distributed+under the terms of this General Public License. The "Program", below,+refers to any such program or work, and a "work based on the Program"+means either the Program or any derivative work under copyright law:+that is to say, a work containing the Program or a portion of it,+either verbatim or with modifications and/or translated into another+language. (Hereinafter, translation is included without limitation in+the term "modification".) Each licensee is addressed as "you".++Activities other than copying, distribution and modification are not+covered by this License; they are outside its scope. The act of+running the Program is not restricted, and the output from the Program+is covered only if its contents constitute a work based on the+Program (independent of having been made by running the Program).+Whether that is true depends on what the Program does.++ 1. You may copy and distribute verbatim copies of the Program's+source code as you receive it, in any medium, provided that you+conspicuously and appropriately publish on each copy an appropriate+copyright notice and disclaimer of warranty; keep intact all the+notices that refer to this License and to the absence of any warranty;+and give any other recipients of the Program a copy of this License+along with the Program.++You may charge a fee for the physical act of transferring a copy, and+you may at your option offer warranty protection in exchange for a fee.++ 2. You may modify your copy or copies of the Program or any portion+of it, thus forming a work based on the Program, and copy and+distribute such modifications or work under the terms of Section 1+above, provided that you also meet all of these conditions:++ a) You must cause the modified files to carry prominent notices+ stating that you changed the files and the date of any change.++ b) You must cause any work that you distribute or publish, that in+ whole or in part contains or is derived from the Program or any+ part thereof, to be licensed as a whole at no charge to all third+ parties under the terms of this License.++ c) If the modified program normally reads commands interactively+ when run, you must cause it, when started running for such+ interactive use in the most ordinary way, to print or display an+ announcement including an appropriate copyright notice and a+ notice that there is no warranty (or else, saying that you provide+ a warranty) and that users may redistribute the program under+ these conditions, and telling the user how to view a copy of this+ License. (Exception: if the Program itself is interactive but+ does not normally print such an announcement, your work based on+ the Program is not required to print an announcement.)++These requirements apply to the modified work as a whole. If+identifiable sections of that work are not derived from the Program,+and can be reasonably considered independent and separate works in+themselves, then this License, and its terms, do not apply to those+sections when you distribute them as separate works. But when you+distribute the same sections as part of a whole which is a work based+on the Program, the distribution of the whole must be on the terms of+this License, whose permissions for other licensees extend to the+entire whole, and thus to each and every part regardless of who wrote it.++Thus, it is not the intent of this section to claim rights or contest+your rights to work written entirely by you; rather, the intent is to+exercise the right to control the distribution of derivative or+collective works based on the Program.++In addition, mere aggregation of another work not based on the Program+with the Program (or with a work based on the Program) on a volume of+a storage or distribution medium does not bring the other work under+the scope of this License.++ 3. You may copy and distribute the Program (or a work based on it,+under Section 2) in object code or executable form under the terms of+Sections 1 and 2 above provided that you also do one of the following:++ a) Accompany it with the complete corresponding machine-readable+ source code, which must be distributed under the terms of Sections+ 1 and 2 above on a medium customarily used for software interchange; or,++ b) Accompany it with a written offer, valid for at least three+ years, to give any third party, for a charge no more than your+ cost of physically performing source distribution, a complete+ machine-readable copy of the corresponding source code, to be+ distributed under the terms of Sections 1 and 2 above on a medium+ customarily used for software interchange; or,++ c) Accompany it with the information you received as to the offer+ to distribute corresponding source code. (This alternative is+ allowed only for noncommercial distribution and only if you+ received the program in object code or executable form with such+ an offer, in accord with Subsection b above.)++The source code for a work means the preferred form of the work for+making modifications to it. For an executable work, complete source+code means all the source code for all modules it contains, plus any+associated interface definition files, plus the scripts used to+control compilation and installation of the executable. However, as a+special exception, the source code distributed need not include+anything that is normally distributed (in either source or binary+form) with the major components (compiler, kernel, and so on) of the+operating system on which the executable runs, unless that component+itself accompanies the executable.++If distribution of executable or object code is made by offering+access to copy from a designated place, then offering equivalent+access to copy the source code from the same place counts as+distribution of the source code, even though third parties are not+compelled to copy the source along with the object code.++ 4. You may not copy, modify, sublicense, or distribute the Program+except as expressly provided under this License. Any attempt+otherwise to copy, modify, sublicense or distribute the Program is+void, and will automatically terminate your rights under this License.+However, parties who have received copies, or rights, from you under+this License will not have their licenses terminated so long as such+parties remain in full compliance.++ 5. You are not required to accept this License, since you have not+signed it. However, nothing else grants you permission to modify or+distribute the Program or its derivative works. These actions are+prohibited by law if you do not accept this License. Therefore, by+modifying or distributing the Program (or any work based on the+Program), you indicate your acceptance of this License to do so, and+all its terms and conditions for copying, distributing or modifying+the Program or works based on it.++ 6. Each time you redistribute the Program (or any work based on the+Program), the recipient automatically receives a license from the+original licensor to copy, distribute or modify the Program subject to+these terms and conditions. You may not impose any further+restrictions on the recipients' exercise of the rights granted herein.+You are not responsible for enforcing compliance by third parties to+this License.++ 7. If, as a consequence of a court judgment or allegation of patent+infringement or for any other reason (not limited to patent issues),+conditions are imposed on you (whether by court order, agreement or+otherwise) that contradict the conditions of this License, they do not+excuse you from the conditions of this License. If you cannot+distribute so as to satisfy simultaneously your obligations under this+License and any other pertinent obligations, then as a consequence you+may not distribute the Program at all. For example, if a patent+license would not permit royalty-free redistribution of the Program by+all those who receive copies directly or indirectly through you, then+the only way you could satisfy both it and this License would be to+refrain entirely from distribution of the Program.++If any portion of this section is held invalid or unenforceable under+any particular circumstance, the balance of the section is intended to+apply and the section as a whole is intended to apply in other+circumstances.++It is not the purpose of this section to induce you to infringe any+patents or other property right claims or to contest validity of any+such claims; this section has the sole purpose of protecting the+integrity of the free software distribution system, which is+implemented by public license practices. Many people have made+generous contributions to the wide range of software distributed+through that system in reliance on consistent application of that+system; it is up to the author/donor to decide if he or she is willing+to distribute software through any other system and a licensee cannot+impose that choice.++This section is intended to make thoroughly clear what is believed to+be a consequence of the rest of this License.++ 8. If the distribution and/or use of the Program is restricted in+certain countries either by patents or by copyrighted interfaces, the+original copyright holder who places the Program under this License+may add an explicit geographical distribution limitation excluding+those countries, so that distribution is permitted only in or among+countries not thus excluded. In such case, this License incorporates+the limitation as if written in the body of this License.++ 9. The Free Software Foundation may publish revised and/or new versions+of the General Public License from time to time. Such new versions will+be similar in spirit to the present version, but may differ in detail to+address new problems or concerns.++Each version is given a distinguishing version number. If the Program+specifies a version number of this License which applies to it and "any+later version", you have the option of following the terms and conditions+either of that version or of any later version published by the Free+Software Foundation. If the Program does not specify a version number of+this License, you may choose any version ever published by the Free Software+Foundation.++ 10. If you wish to incorporate parts of the Program into other free+programs whose distribution conditions are different, write to the author+to ask for permission. For software which is copyrighted by the Free+Software Foundation, write to the Free Software Foundation; we sometimes+make exceptions for this. Our decision will be guided by the two goals+of preserving the free status of all derivatives of our free software and+of promoting the sharing and reuse of software generally.++ NO WARRANTY++ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,+REPAIR OR CORRECTION.++ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE+POSSIBILITY OF SUCH DAMAGES.++ END OF TERMS AND CONDITIONS++ How to Apply These Terms to Your New Programs++ If you develop a new program, and you want it to be of the greatest+possible use to the public, the best way to achieve this is to make it+free software which everyone can redistribute and change under these terms.++ To do so, attach the following notices to the program. It is safest+to attach them to the start of each source file to most effectively+convey the exclusion of warranty; and each file should have at least+the "copyright" line and a pointer to where the full notice is found.++ <one line to give the program's name and a brief idea of what it does.>+ Copyright (C) <year> <name of author>++ This program is free software; you can redistribute it and/or modify+ it under the terms of the GNU General Public License as published by+ the Free Software Foundation; either version 2 of the License, or+ (at your option) any later version.++ This program is distributed in the hope that it will be useful,+ but WITHOUT ANY WARRANTY; without even the implied warranty of+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ GNU General Public License for more details.++ You should have received a copy of the GNU General Public License along+ with this program; if not, write to the Free Software Foundation, Inc.,+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.++Also add information on how to contact you by electronic and paper mail.++If the program is interactive, make it output a short notice like this+when it starts in an interactive mode:++ Gnomovision version 69, Copyright (C) year name of author+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.+ This is free software, and you are welcome to redistribute it+ under certain conditions; type `show c' for details.++The hypothetical commands `show w' and `show c' should show the appropriate+parts of the General Public License. Of course, the commands you use may+be called something other than `show w' and `show c'; they could even be+mouse-clicks or menu items--whatever suits your program.++You should also get your employer (if you work as a programmer) or your+school, if any, to sign a "copyright disclaimer" for the program, if+necessary. Here is a sample; alter the names:++ Yoyodyne, Inc., hereby disclaims all copyright interest in the program+ `Gnomovision' (which makes passes at compilers) written by James Hacker.++ <signature of Ty Coon>, 1 April 1989+ Ty Coon, President of Vice++This General Public License does not permit incorporating your program into+proprietary programs. If your program is a subroutine library, you may+consider it more useful to permit linking proprietary applications with the+library. If this is what you want to do, use the GNU Lesser General+Public License instead of this License.
+ libs/pagure-hs/src/Fedora/Pagure.hs view
@@ -0,0 +1,236 @@+{-# LANGUAGE CPP #-}++{- |+Copyright: (c) 2020 Jens Petersen+SPDX-License-Identifier: GPL-2.0-only+Maintainer: Jens Petersen <petersen@redhat.com>++Pagure REST client library+-}++module Fedora.Pagure+ ( pagureProjectInfo+ , pagureListProjects+ , pagureListProjectIssues+ , IssueTitleStatus(..)+ , pagureListProjectIssueTitlesStatus+ , pagureProjectIssueInfo+ , pagureListGitBranches+ , pagureListGitBranchesWithCommits+ , pagureListUsers+ , pagureUserForks+ , pagureUserInfo+ , pagureUserRepos+ , pagureListGroups+ , pagureProjectGitURLs+ , queryPagure+ , queryPagureSingle+ , queryPagurePaged+ , queryPagureCount+ , makeKey+ , makeItem+ , maybeKey+ , Query+ , QueryItem+ , lookupKey+ , lookupKey'+ ) where++import Control.Monad+#if (defined(VERSION_lens_aeson))+import Control.Lens+import Data.Aeson.Lens+#else+import Lens.Micro+import Lens.Micro.Aeson+#endif+import Data.Aeson.Types+import Data.Maybe+import Data.Text (Text)+import qualified Data.Text as T+import Network.HTTP.Query+import System.IO (hPutStrLn, stderr)++-- | Project info+--+-- `pagureProjectInfo server "<repo>"`+-- `pagureProjectInfo server "<namespace>/<repo>"`+--+-- https://pagure.io/api/0/#projects-tab+pagureProjectInfo :: String -> String -> IO (Either String Value)+pagureProjectInfo server project = do+ let path = project+ queryPagureSingle server path []++-- | List projects+--+-- https://pagure.io/api/0/#projects-tab+pagureListProjects :: String -> Query -> IO Value+pagureListProjects server params = do+ let path = "projects"+ queryPagure server path params++-- | List project issues+--+-- https://pagure.io/api/0/#issues-tab+pagureListProjectIssues :: String -> String -> Query -> IO (Either String Value)+pagureListProjectIssues server repo params = do+ let path = repo +/+ "issues"+ queryPagureSingle server path params++data IssueTitleStatus =+ IssueTitleStatus { pagureIssueId :: Integer+ , pagureIssueTitle :: String+ , pagureIssueStatus :: T.Text+ , pagureIssueCloseStatus :: Maybe T.Text+ }++-- | List project issue titles+--+-- https://pagure.io/api/0/#issues-tab+pagureListProjectIssueTitlesStatus :: String -> String -> Query+ -> IO (Either String [IssueTitleStatus])+pagureListProjectIssueTitlesStatus server repo params = do+ let path = repo +/+ "issues"+ res <- queryPagureSingle server path params+ return $ case res of+ Left e -> Left e+ Right v -> Right $ v ^.. key (T.pack "issues") . values . _Object & mapMaybe parseIssue+ where+ parseIssue :: Object -> Maybe IssueTitleStatus+ parseIssue =+ parseMaybe $ \obj -> do+ id' <- obj .: "id"+ title <- obj .: "title"+ status <- obj .: "status"+ mcloseStatus <- obj .:? "close_status"+ return $ IssueTitleStatus id' (T.unpack title) status mcloseStatus++-- | Issue information+--+-- https://pagure.io/api/0/#issues-tab+pagureProjectIssueInfo :: String -> String -> Int -> IO (Either String Object)+pagureProjectIssueInfo server repo issue = do+ let path = repo +/+ "issue" +/+ show issue+ res <- queryPagureSingle server path []+ return $ case res of+ Left e -> Left e+ Right v -> Right $ v ^. _Object++-- | List repo branches+--+-- https://pagure.io/api/0/#projects-tab+pagureListGitBranches :: String -> String -> IO (Either String [String])+pagureListGitBranches server repo = do+ let path = repo +/+ "git/branches"+ res <- queryPagureSingle server path []+ return $ case res of+ Left e -> Left e+ Right v -> Right $ v ^.. key (T.pack "branches") . values . _String & map T.unpack++-- | List repo branches with commits+--+-- https://pagure.io/api/0/#projects-tab+pagureListGitBranchesWithCommits :: String -> String -> IO (Either String Object)+pagureListGitBranchesWithCommits server repo = do+ let path = repo +/+ "git/branches"+ params = makeKey "with_commits" "1"+ res <- queryPagureSingle server path params+ return $ case res of+ Left e -> Left e+ Right v -> Right $ v ^. key (T.pack "branches") . _Object++-- | List users+--+-- https://pagure.io/api/0/#users-tab+pagureListUsers :: String -> String -> IO Value+pagureListUsers server pat = do+ let path = "users"+ params = makeKey "pattern" pat+ queryPagure server path params++-- | User information+--+-- https://pagure.io/api/0/#users-tab+pagureUserInfo :: String -> String -> Query -> IO (Either String Value)+pagureUserInfo server user params = do+ let path = "user" +/+ user+ queryPagureSingle server path params++-- | List groups+--+-- https://pagure.io/api/0/#groups-tab+pagureListGroups :: String -> Maybe String -> Query -> IO Value+pagureListGroups server mpat paging = do+ let path = "groups"+ params = maybeKey "pattern" mpat ++ paging+ queryPagure server path params++-- | Project Git URLs+--+-- https://pagure.io/api/0/#projects-tab+pagureProjectGitURLs :: String -> String -> IO (Either String Value)+pagureProjectGitURLs server repo = do+ let path = repo +/+ "git/urls"+ queryPagureSingle server path []+++-- | low-level query+queryPagure :: String -> String -> Query -> IO Value+queryPagure server path params =+ let url = "https://" ++ server +/+ "api/0" +/+ path+ in webAPIQuery url params++-- | single query+queryPagureSingle :: String -> String -> Query -> IO (Either String Value)+queryPagureSingle server path params = do+ res <- queryPagure server path params+ if isJust (res ^? key "error") then+ return $ Left (res ^. key "error" . _String & T.unpack)+ else+ return $ Right res++-- | count total number of hits+queryPagureCount :: String -> String -> Query -> String -> IO (Maybe Integer)+queryPagureCount server path params pagination = do+ res <- queryPagure server path (params ++ makeKey "per_page" "1")+ return $ res ^? key (T.pack pagination) . key "pages" . _Integer++-- | get all pages of results+--+-- Note this can potentially download very large amount of data.+-- For potentially large queries, it is a good idea to queryPagureCount first.+queryPagurePaged :: String -> String -> Query -> (String,String) -> IO [Value]+queryPagurePaged server path params (pagination,paging) = do+ -- FIXME allow overriding per_page+ let maxPerPage = "100"+ res1 <- queryPagure server path (params ++ makeKey "per_page" maxPerPage)+ let mpages = res1 ^? key (T.pack pagination) . key "pages" . _Integer+ case mpages of+ Nothing -> return []+ Just pages -> do+ when (pages > 1) $+ hPutStrLn stderr $ "receiving " ++ show pages ++ " pages × " ++ maxPerPage ++ " results..."+ rest <- mapM nextPage [2..pages]+ return $ res1 : rest+ where+ nextPage p =+ queryPagure server path (params ++ makeKey "per_page" "100" ++ makeKey paging (show p))++-- | list user's repos+pagureUserRepos :: String -> String -> IO [Text]+pagureUserRepos server user = do+ let path = "user" +/+ user+ pages <- queryPagurePaged server path [] ("repos_pagination", "repopage")+ return $ concatMap (getRepos "repos") pages++getRepos :: Text -> Value -> [Text]+getRepos field result =+ result ^.. key field . values . key "fullname" . _String++-- | list user's forks+pagureUserForks :: String -> String -> IO [Text]+pagureUserForks server user = do+ let path = "user" +/+ user+ pages <- queryPagurePaged server path [] ("forks_pagination", "forkpage")+ return $ concatMap (getRepos "forks") pages
+ libs/pdc-hs/LICENSE view
@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2020 Jens Petersen++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.
+ libs/pdc-hs/src/Fedora/PDC.hs view
@@ -0,0 +1,209 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE OverloadedStrings #-}++{- |+Copyright: (c) 2020 Jens Petersen+SPDX-License-Identifier: MIT+Maintainer: Jens Petersen <juhpetersen@gmail.com>++Fedora PDC web api client library+-}++module Fedora.PDC+ ( fedoraPDC+ , pdcArches+ , pdcChangesets+ , pdcComponentBranches+ , pdcComponentBranchSLAs+ , pdcComponentRelationshipTypes+ , pdcComponentSLATypes+ , pdcComposes+ , pdcComposeImages+ , pdcComposeImageRttTests+ , pdcComposeRpms+ , pdcComposeTreeRttTests+ , pdcContentDeliveryContentFormats+ , pdcGlobalComponents+ , pdcImages+ , pdcModules+ , pdcProductVersions+ , pdcProducts+ , pdcReleases+ , pdcWhereToFileBugs+ , pdcRpms+ , queryPDC+ , lookupKey+ , lookupKey'+ , makeKey+ , makeItem+ , maybeKey+ , Query+ , QueryItem+ , getResultsList+ )+where++import Data.Aeson.Types+import Network.HTTP.Query++fedoraPDC :: String+fedoraPDC = "pdc.fedoraproject.org"++-- | Arch List+--+-- https://pdc.fedoraproject.org/rest_api/v1/arches/+pdcArches :: String -> IO [Object]+pdcArches server =+ lookupKey' "results" <$> queryPDC server "arches" []++-- https://pdc.fedoraproject.org/rest_api/v1/auth/ *++-- https://pdc.fedoraproject.org/rest_api/v1/base-products/ no-op?++-- https://pdc.fedoraproject.org/rest_api/v1/bugzilla-components/ no-op?++-- | Changeset List+--+-- https://pdc.fedoraproject.org/rest_api/v1/changesets/+pdcChangesets :: String -> Query -> IO Object+pdcChangesets server =+ queryPDC server "changesets"++-- | Sla To Component Branch List+--+-- https://pdc.fedoraproject.org/rest_api/v1/component-branch-slas/+pdcComponentBranchSLAs :: String -> Query -> IO Object+pdcComponentBranchSLAs server =+ queryPDC server "component-branch-slas"++-- | Component Branch List+--+-- https://pdc.fedoraproject.org/rest_api/v1/component-branches/+pdcComponentBranches :: String -> Query -> IO Object+pdcComponentBranches server =+ queryPDC server "component-branches"++-- | Release Component Relationship Type List+--+-- https://pdc.fedoraproject.org/rest_api/v1/component-relationship-types/+pdcComponentRelationshipTypes :: String -> IO [Object]+pdcComponentRelationshipTypes server =+ lookupKey' "results" <$> queryPDC server "component-relationship-types" []++-- | Sla List+--+-- https://pdc.fedoraproject.org/rest_api/v1/component-sla-types/+pdcComponentSLATypes :: String -> Query -> IO [Object]+pdcComponentSLATypes server params =+ lookupKey' "results" <$> queryPDC server "component-sla-types" params++-- | Compose Image Rtt Test List+--+-- https://pdc.fedoraproject.org/rest_api/v1/compose-image-rtt-tests/ (all untested?)+pdcComposeImageRttTests :: String -> Query -> IO Object+pdcComposeImageRttTests server =+ queryPDC server "compose-image-rtt-tests"++-- | Compose Image Instance+--+-- https://pdc.fedoraproject.org/rest_api/v1/compose-images/ {compose_id}/+pdcComposeImages :: String -> String -> IO Object+pdcComposeImages server compose =+ queryPDC server ("compose-images" +/+ compose ++ "/") []++-- | Compose Rpm List (seems heavy)+--+-- https://pdc.fedoraproject.org/rest_api/v1/compose-rpms/ {compose_id}/+pdcComposeRpms :: String -> String -> IO Object+pdcComposeRpms server compose =+ queryPDC server ("compose-rpms" +/+ compose ++ "/") []++-- | Compose Tree Rtt Test List+--+-- https://pdc.fedoraproject.org/rest_api/v1/compose-tree-rtt-tests/+pdcComposeTreeRttTests :: String -> Query -> IO Object+pdcComposeTreeRttTests server =+ queryPDC server "compose-tree-rtt-tests"++-- | Compose List+--+-- https://pdc.fedoraproject.org/rest_api/v1/composes/+pdcComposes :: String -> Maybe String -> Query -> IO Object+pdcComposes server mcompose params = do+ let path = "composes" +/+ maybe "" (++ "/") mcompose+ queryPDC server path params++-- https://pdc.fedoraproject.org/rest_api/v1/composes/%7Bcompose_id%7D/rpm-mapping/%7Bpackage%7D/++-- | Content Format List+--+-- https://pdc.fedoraproject.org/rest_api/v1/content-delivery-content-formats/+pdcContentDeliveryContentFormats :: String -> Query -> IO [Object]+pdcContentDeliveryContentFormats server params =+ lookupKey' "results" <$> queryPDC server "content-delivery-content-formats" params++-- | Global Component List+--+-- https://pdc.fedoraproject.org/rest_api/v1/global-components/+pdcGlobalComponents :: String -> Query -> IO Object+pdcGlobalComponents server =+ queryPDC server "global-components"++-- | Image List+--+-- https://pdc.fedoraproject.org/rest_api/v1/images/+pdcImages :: String -> Query -> IO Object+pdcImages server =+ queryPDC server "images"++-- | Module List+--+-- https://pdc.fedoraproject.org/rest_api/v1/modules/+pdcModules :: String -> Query -> IO Object+pdcModules server =+ queryPDC server "modules"++-- | Product Version List+--+-- https://pdc.fedoraproject.org/rest_api/v1/product-versions/+pdcProductVersions :: String -> Query -> IO [Object]+pdcProductVersions server params =+ lookupKey' "results" <$> queryPDC server "product-versions" params++-- | Product List+--+-- https://pdc.fedoraproject.org/rest_api/v1/products/+pdcProducts :: String -> Query -> IO [Object]+pdcProducts server params =+ lookupKey' "results" <$> queryPDC server "products" params++-- | Release List+--+-- https://pdc.fedoraproject.org/rest_api/v1/releases/+pdcReleases :: String -> Query -> IO Object+pdcReleases server =+ queryPDC server "releases"++-- | Filter Bugzilla Products And Components List+--+-- https://pdc.fedoraproject.org/rest_api/v1/rpc/where-to-file-bugs/+pdcWhereToFileBugs :: String -> Query -> IO Object+pdcWhereToFileBugs server =+ queryPDC server "rpc/where-to-file-bugs"++-- | Rpm List+--+-- https://pdc.fedoraproject.org/rest_api/v1/rpms/+pdcRpms :: String -> Query -> IO Object+pdcRpms server =+ queryPDC server "rpms"++-- | low-level query+queryPDC :: String -> String -> Query -> IO Object+queryPDC server path params =+ let url = "https://" ++ server +/+ "rest_api/v1" +/+ path+ in webAPIQuery url params++-- | Get results key from a response object+getResultsList :: Object -> [Object]+getResultsList = lookupKey' "results"
+ src/Bodhi.hs view
@@ -0,0 +1,70 @@+{-# LANGUAGE OverloadedStrings #-}++module Bodhi (+ bodhiCreateOverride,+ checkAutoBodhiUpdate,+ UpdateType(..)+ )+where++import Data.Aeson.Types (Object, (.:), parseEither)+import Data.Char (toLower)+import Fedora.Bodhi hiding (bodhiUpdate)+import Text.Read+import qualified Text.ParserCombinators.ReadP as R+import qualified Text.ParserCombinators.ReadPrec as RP+++import Branches+import Common.System+import qualified Common.Text as T+import Prompt++checkAutoBodhiUpdate :: Branch -> IO Bool+checkAutoBodhiUpdate Rawhide = return True+-- epel7 returns 'create_automatic_updates: null' !+checkAutoBodhiUpdate (EPEL 7) = return False+checkAutoBodhiUpdate br =+ lookupKey'' "create_automatic_updates" <$> bodhiRelease (show br)+ where+ -- Error in $: key "create_automatic_updates" not found+ lookupKey'' :: T.Text -> Object -> Bool+ lookupKey'' k obj =+ let errMsg e = error $ e ++ " " ++ show obj in+ -- bodhi-hs has lookupKeyEither+ either errMsg id $ parseEither (.: k) obj++-- FIXME should determine 3 days for branched devel release+bodhiCreateOverride :: String -> IO ()+bodhiCreateOverride nvr = do+ putStrLn $ "Creating Bodhi Override for " ++ nvr ++ ":"+ ok <- cmdBool "bodhi" ["overrides", "save", "--notes", "chain building with fbrnch", "--duration", "7", nvr]+ if ok+ then putStrLn $ "https://bodhi.fedoraproject.org/overrides/" ++ nvr+ else do+ moverride <- bodhiOverride nvr+ case moverride of+ Nothing -> do+ putStrLn "bodhi override failed"+ prompt_ "Press Enter to retry"+ bodhiCreateOverride nvr+ Just obj -> print obj++data UpdateType =+ SecurityUpdate | BugfixUpdate | EnhancementUpdate | NewPackageUpdate++instance Show UpdateType where+ show SecurityUpdate = "security"+ show BugfixUpdate = "bugfix"+ show EnhancementUpdate = "enhancement"+ show NewPackageUpdate = "newpackage"++instance Read UpdateType where+ readPrec = do+ s <- look+ case map toLower s of+ "security" -> RP.lift (R.string s) >> return SecurityUpdate+ "bugfix" -> RP.lift (R.string s) >> return BugfixUpdate+ "enhancement" -> RP.lift (R.string s) >> return EnhancementUpdate+ "newpackage" -> RP.lift (R.string s) >> return NewPackageUpdate+ _ -> error' "unknown bodhi update type" >> RP.pfail
+ src/Branches.hs view
@@ -0,0 +1,163 @@+module Branches (+ activeBranches,+ fedoraBranches,+ fedoraBranchesNoMaster,+ isFedoraBranch,+ isEPELBranch,+ localBranches,+ pagurePkgBranches,+ mockConfig,+ module Distribution.Fedora.Branch,+ AnyBranch(..),+ anyBranch,+ isRelBranch,+ onlyRelBranch,+ BranchOpts(..),+ listOfBranches,+ gitCurrentBranch,+ systemBranch,+ getReleaseBranch+) where++import Common++import Distribution.Fedora.Branch+import SimpleCmd+import SimpleCmd.Git++import Pagure++data AnyBranch = RelBranch Branch | OtherBranch String+ deriving Eq++anyBranch :: String -> AnyBranch+anyBranch = either OtherBranch RelBranch . eitherBranch++-- allRelBranches :: [AnyBranch] -> Bool+-- allRelBranches = all isRelBranch++isRelBranch :: AnyBranch -> Bool+isRelBranch (RelBranch _) = True+isRelBranch _ = False++instance Show AnyBranch where+ show (RelBranch br) = show br+ show (OtherBranch obr) = obr++activeBranches :: [Branch] -> [String] -> [Branch]+activeBranches active =+ -- newest branch first+ reverse . sort . mapMaybe (readActiveBranch active)++fedoraBranches :: IO [String] -> IO [Branch]+fedoraBranches mthd = do+ active <- getFedoraBranches+ activeBranches active <$> mthd++fedoraBranchesNoMaster :: IO [String] -> IO [Branch]+fedoraBranchesNoMaster mthd = do+ active <- getFedoraBranched+ activeBranches active <$> mthd++isFedoraBranch :: Branch -> Bool+isFedoraBranch (Fedora _) = True+isFedoraBranch Rawhide = True+isFedoraBranch _ = False++isEPELBranch :: Branch -> Bool+isEPELBranch (EPEL _) = True+isEPELBranch _ = False++-- FIXME misnamed+localBranches :: IO [String]+localBranches = do+ origins <- filter ("origin/" `isPrefixOf`) <$> cmdLines "git" ["branch", "--remote", "--list", "--format=%(refname:lstrip=-2)"]+ return $ map (removePrefix "origin/") origins \\ ["HEAD", "master"]++pagurePkgBranches :: String -> IO [String]+pagurePkgBranches pkg = do+ let project = "rpms/" ++ pkg+ res <- pagureListGitBranches srcfpo project+ return $ either (error' . include project) id res+ where+ include p e = e ++ ": " ++ p++mockConfig :: Branch -> String+mockConfig Rawhide = "fedora-rawhide-x86_64"+mockConfig (Fedora n) = "fedora-" ++ show n ++ "-x86_64"+mockConfig (EPEL n) = "epel-" ++ show n ++ "-x86_64"++------++data BranchOpts = AllBranches | AllFedora | AllEPEL | ExcludeBranches [Branch]+ deriving Eq++onlyRelBranch :: AnyBranch -> Branch+onlyRelBranch (RelBranch br) = br+onlyRelBranch (OtherBranch br) = error' $ "Non-release branch not allowed: " ++ br++systemBranch :: IO Branch+systemBranch =+ readBranch' . init . removePrefix "PLATFORM_ID=\"platform:" <$> cmd "grep" ["PLATFORM_ID=", "/etc/os-release"]++listOfBranches :: Bool -> Bool -> Maybe BranchOpts -> [AnyBranch] -> IO [AnyBranch]+listOfBranches _ _active (Just AllBranches) (_:_) =+ error' "cannot specify branches with --all-branches"+listOfBranches distgit _active (Just AllBranches) [] =+ if distgit+ then map RelBranch <$> fedoraBranches localBranches+ else error' "--all-branches only allowed for dist-git packages"+listOfBranches _ _active (Just AllFedora) (_:_) =+ error' "cannot specify branches with --all-fedora"+listOfBranches distgit _active (Just AllFedora) [] =+ if distgit+ then map RelBranch . filter isFedoraBranch <$> fedoraBranches localBranches+ else error' "--all-fedora only allowed for dist-git packages"+listOfBranches _ _active (Just AllEPEL) (_:_) =+ error' "cannot specify branches with --all-epel"+listOfBranches distgit _active (Just AllEPEL) [] =+ if distgit+ then map RelBranch . filter isEPELBranch <$> fedoraBranches localBranches+ else error' "--all-epel only allowed for dist-git packages"+listOfBranches distgit active Nothing brs =+ if null brs+ then+ pure <$> if distgit+ then gitCurrentBranch+ else RelBranch <$> systemBranch+ else do+ activeBrs <- getFedoraBranches+ forM_ brs $ \ br ->+ case br of+ RelBranch rbr -> do+ if active+ then when (rbr `notElem` activeBrs) $+ error' $ show br ++ " is not an active branch"+ else+ case rbr of+ Fedora _ -> do+ let latest = maximum (delete Rawhide activeBrs)+ when (rbr > latest) $+ error' $ show rbr ++ " is newer than latest branch"+ -- FIXME also check for too new EPEL+ _ -> return ()+ _ -> return ()+ return brs+listOfBranches _ _ (Just (ExcludeBranches _)) (_:_) =+ error' "cannot specify branches with exclude-branch"+listOfBranches distgit _ (Just (ExcludeBranches brs)) [] = do+ branches <- if distgit+ then fedoraBranches localBranches+ else getFedoraBranches+ return $ map RelBranch (branches \\ brs)++getReleaseBranch :: IO Branch+getReleaseBranch = do+ mcurrent <- gitCurrentBranch+ case mcurrent of+ RelBranch br -> return br+ _ -> systemBranch++gitCurrentBranch :: IO AnyBranch+gitCurrentBranch =+ anyBranch <$> git "rev-parse" ["--abbrev-ref", "HEAD"]
+ src/Bugzilla.hs view
@@ -0,0 +1,410 @@+{-# LANGUAGE OverloadedStrings #-}++module Bugzilla (+ Bug(..),+ User(..),+ BugId,+ -- session+ BugzillaSession,+ bugIdsSession,+ bugsSession,+ bzLoginSession,+ bzReviewSession,+ reviewBugIdSession,+ approvedReviewBugIdSession,+ approvedReviewBugSession,+ pkgBugs,+ pkgReviews,+ listBzUsers,+ emailIsValid,+-- testBZlogin,+ -- search+ searchBugs,+ (.&&.),+ not',+ packageReview,+ assigneeIs,+ reporterIs,+ reviewApproved,+ statusNewPost,+ statusNewModified,+ statusOpen,+ summaryContains,+ -- comments+ Comment,+ checkForComment,+ checkRepoCreatedComment,+ createBug,+ commentBug,+ updateBug,+ putBugBuild,+ showComment,+ commentText,+ getComments,+ --+ reviewBugToPackage,+ sortBugsByProduct,+ sortBugsByStatus,+ -- output+ putBug,+ putBugVer,+ putReviewBug,+ putBugId,+ -- request+ newBzRequest,+ intAsText,+ makeTextItem+ ) where++import Common+import Common.System+import qualified Common.Text as T+import Prompt++import Control.Exception (finally)+import Data.Aeson.Types (Array, Object)+import qualified Data.ByteString.Char8 as B+import Data.ByteString.UTF8+import Data.Ini.Config+import Network.HTTP.Conduit+import Network.HTTP.Query+import Network.HTTP.Simple+import System.Environment+import System.Environment.XDG.BaseDir+import System.IO (hSetEcho, stdin)+import qualified Text.Email.Validate as Email+import Web.Bugzilla.RedHat+import Web.Bugzilla.RedHat.Search++createBug :: BugzillaSession -> [(String,String)] -> IO Int+createBug session params = do+ let req = -- posting url encoded utf8 to bugzilla only seems to work in body+ urlEncodedBody (encodeParams params) $+ setRequestCheckStatus $+ newBzRequest session ["bug"] []+ lookupKey' "id" . getResponseBody <$> httpJSON req++commentBug :: BugzillaSession -> BugId -> String -> IO ()+commentBug session bid comment = do+ let req = setRequestMethod "POST" $+ -- earlier posting url encoded utf8 only seemed to work in body+ urlEncodedBody (encodeParams [("comment", comment)]) $+ setRequestCheckStatus $+ newBzRequest session (map T.pack ["bug",show bid,"comment"]) []+ res <- getResponseBody <$> httpJSON req+ -- [("id",Number 1.4682731e7)]+ when (isNothing (lookupKey "id" res :: Maybe Int)) $ do+ -- eg [("error",Bool True),("documentation",String "https://bugzilla.redhat.com/docs/en/html/api/index.html"),("code",Number 32614.0),("message",String "A REST API resource was not found for 'POST /bug/1880903'.")]+ case lookupKey "message" res of+ Nothing -> print res+ Just msg -> T.putStrLn msg+ error' $ "failed to update bug " ++ show bid+ putStrLn "Comment added:"+ putStrLn comment++updateBug :: BugzillaSession -> BugId -> [(String,String)] -> IO ()+updateBug session bid params = do+ let req = setRequestMethod "PUT" $+ -- earlier posting url encoded utf8 only seemed to work in body+ urlEncodedBody (encodeParams params) $+ setRequestCheckStatus $+ newBzRequest session (map T.pack ["bug",show bid]) []+ res <- getResponseBody <$> httpJSON req+ -- [("bugs",Array [Object (fromList [("changes",Object (fromList [])),("alias",Array []),("id",Number 1897441.0),("last_change_time",String "2021-01-24T08:20:18Z")])])]+ when (isNothing (lookupKey "bugs" res :: Maybe Array)) $ do+ -- eg [("error",Bool True),("documentation",String "https://bugzilla.redhat.com/docs/en/html/api/index.html"),("code",Number 32614.0),("message",String "A REST API resource was not found for 'POST /bug/1880903'.")]+ case lookupKey "message" res of+ Nothing -> print res+ Just msg -> T.putStrLn msg+ error' $ "failed to update bug " ++ show bid++encodeParams :: [(String, String)] -> [(ByteString, ByteString)]+encodeParams [] = []+encodeParams ((k,v):ps) =+ (B.pack k, fromString v) : encodeParams ps++putBugBuild :: BugzillaSession -> BugId -> String -> IO ()+putBugBuild session bid nvr = do+ void $ updateBug session bid+ [("cf_fixed_in", nvr), ("status", "MODIFIED")]+ putStrLn $ "build posted to review bug " ++ show bid++brc :: T.Text+brc = "bugzilla.redhat.com"++bzReviewSession :: IO (Maybe BugId,BugzillaSession)+bzReviewSession = do+ pkg <- getDirectoryName+ (bids,session) <- bugIdsSession $+ pkgReviews pkg .&&. statusOpen .&&. reviewApproved+ case bids of+ [bid] -> return (Just bid, session)+ _ -> return (Nothing, session)++newtype BzUserRC = BzUserRC {rcUserEmail :: UserEmail}+ deriving (Eq, Show)++emailIsValid :: String -> Bool+emailIsValid = Email.isValid . B.pack++-- FIXME support bugzilla API key+bzLoginSession :: IO (BugzillaSession, UserEmail)+bzLoginSession = do+ user <- getBzUser+ ctx <- newBugzillaContext brc+ session <- getBzLoginSession ctx user+ return (session,user)+ where+ getBzUser :: IO UserEmail+ getBzUser = do+ home <- getEnv "HOME"+ let rc = home </> ".bugzillarc"+ -- FIXME assumption if file exists then it has b.r.c user+ ifM (doesFileExist rc)+ (readIniConfig rc rcParser rcUserEmail) $+ do+ -- FIXME: option to override email+ email <- prompt "Bugzilla Username"+ when (emailIsValid email) $ do+ T.writeFile rc $ "[" <> brc <> "]\nuser = " <> T.pack email <> "\n"+ putStrLn $ "Saved in " ++ rc+ getBzUser+ where+ rcParser :: IniParser BzUserRC+ rcParser =+ section brc $+ BzUserRC <$> fieldOf "user" string++ getBzLoginSession :: BugzillaContext -> UserEmail -> IO BugzillaSession+ getBzLoginSession ctx user = do+ cache <- getUserCacheFile "python-bugzilla" "bugzillatoken"+ let cacheDir = takeDirectory cache+ cacheDirExists <- doesDirectoryExist cacheDir+ unless cacheDirExists $ createDirectory cacheDir+ tokenstatus <- ifM (notM (doesFileExist cache)) (return NoToken) $+ do+ token <- readIniConfig cache rcParser bzToken+ let session = LoginSession ctx $ BugzillaToken token+ let validreq = setRequestCheckStatus $+ newBzRequest session ["valid_login"] [("login",Just user)]+ valid <- lookupKey' "result" . getResponseBody <$> httpJSON validreq+ return $ if valid then ValidToken session else InvalidToken token+ case tokenstatus of+ ValidToken session -> return session+ InvalidToken oldtoken -> do+ token <- bzLogin+ cmd_ "sed" ["-i", "s/" ++ T.unpack oldtoken ++ "/" ++ T.unpack token ++ "/", cache]+ return $ LoginSession ctx $ BugzillaToken token+ NoToken -> do+ token <- bzLogin+ T.writeFile cache $ "[" <> brc <> "]\ntoken = " <> token <> "\n"+ putStrLn $ "Saved in " ++ cache+ return $ LoginSession ctx $ BugzillaToken token+ where+ rcParser :: IniParser BzTokenConf+ rcParser =+ section brc $+ BzTokenConf <$> fieldOf "token" string++ bzLogin :: IO T.Text+ bzLogin = do+ putStrLn "No valid bugzilla login token, please login:"+ passwd <- withoutEcho $ prompt "Bugzilla Password"+ if null passwd then bzLogin+ else do+ let anonsession = AnonymousSession ctx+ tokenReq = setRequestCheckStatus $+ newBzRequest anonsession ["login"]+ [("login", Just user),+ makeTextItem "password" passwd]+ res <- getResponseBody <$> httpJSON tokenReq+ case lookupKey "token" res of+ Nothing -> T.putStrLn (lookupKey' "message" res) >> bzLogin+ Just token -> return token++ withoutEcho :: IO a -> IO a+ withoutEcho action =+ finally (hSetEcho stdin False >> action) (hSetEcho stdin True)++newtype BzTokenConf = BzTokenConf {bzToken :: T.Text}+ deriving (Eq, Show)++data BzTokenStatus = ValidToken BugzillaSession | InvalidToken T.Text | NoToken++reporterIs :: T.Text -> SearchExpression+reporterIs = (ReporterField .==.)++assigneeIs :: T.Text -> SearchExpression+assigneeIs = (AssignedToField .==.)++packageReview :: SearchExpression+packageReview =+ ComponentField .==. ["Package Review"]++statusOpen :: SearchExpression+statusOpen =+ StatusField ./=. "CLOSED"++statusNewPost :: SearchExpression+statusNewPost =+ StatusField `equalsAny` ["NEW", "ASSIGNED", "POST"]++statusNewModified :: SearchExpression+statusNewModified =+ StatusField `equalsAny` ["NEW", "ASSIGNED", "POST", "MODIFIED"]++reviewApproved :: SearchExpression+reviewApproved =+ FlagsField `contains` "fedora-review+"++pkgReviews :: String -> SearchExpression+pkgReviews pkg =+ SummaryField `contains` T.pack ("Review Request: " ++ pkg ++ " - ") .&&.+ packageReview++pkgBugs :: String -> SearchExpression+pkgBugs pkg =+ ComponentField .==. [T.pack pkg]++summaryContains :: String -> SearchExpression+summaryContains keywrd =+ SummaryField `contains` T.pack keywrd++bugIdsSession :: SearchExpression -> IO ([BugId],BugzillaSession)+bugIdsSession query = do+ (session,_) <- bzLoginSession+ bugs <- searchBugs' session query+ return (bugs, session)++bugsSession :: SearchExpression -> IO ([Bug],BugzillaSession)+bugsSession query = do+ (session,_) <- bzLoginSession+ bugs <- searchBugs session query+ return (bugs, session)++reviewBugIdSession :: String -> IO (BugId,BugzillaSession)+reviewBugIdSession pkg = do+ (bugs,session) <- bugIdsSession $ pkgReviews pkg .&&. statusOpen+ case bugs of+ [] -> error $ "No review bug found for " ++ pkg+ [bug] -> return (bug, session)+ _ -> error' "more than one review bug found!"++approvedReviewBugIdSession :: String -> IO (BugId,BugzillaSession)+approvedReviewBugIdSession pkg = do+ (bugs,session) <- bugIdsSession $+ pkgReviews pkg .&&. statusOpen .&&. reviewApproved+ case bugs of+ [] -> error $ "No review bug found for " ++ pkg+ [bug] -> return (bug, session)+ _ -> error' "more than one review bug found!"++approvedReviewBugSession :: String -> IO (Bug,BugzillaSession)+approvedReviewBugSession pkg = do+ (bugs,session) <- bugsSession $+ pkgReviews pkg .&&. statusOpen .&&. reviewApproved+ case bugs of+ [] -> error $ "No review bug found for " ++ pkg+ [bug] -> return (bug, session)+ _ -> error' "more than one review bug found!"++reviewBugToPackage :: Bug -> String+reviewBugToPackage =+ head . dropOne ["Request:"] . dropOne ["Review", "Re-Review", "Rename"] . words . T.unpack . bugSummary+ where+ dropOne _ [] = []+ dropOne ks as@(w:ws) = if w `elem` ks then ws else as++readIniConfig :: FilePath -> IniParser a -> (a -> b) -> IO b+readIniConfig inifile iniparser fn = do+ ini <- T.readFile inifile+ return $ either error fn $ parseIniFile ini iniparser++sortBugsByStatus :: [Bug] -> [Bug]+sortBugsByStatus = sortOn (bugStatusEnum . bugStatus)++sortBugsByProduct :: [Bug] -> [Bug]+sortBugsByProduct = sortOn bugProduct++-- FIXME make datatype+bugStatusEnum :: T.Text -> Int+bugStatusEnum st =+ case st of+ "NEW" -> 0+ "ASSIGNED" -> 1+ "POST" -> 2+ "MODIFIED" -> 3+ "ON_QA" -> 4+ "VERIFIED" -> 5+ "RELEASE_PENDING" -> 6+ "CLOSED" -> 7+ _ -> -1++showComment :: Comment -> IO ()+showComment cmt = do+ -- comment0 from fedora-create-review has leading newline+ T.putStrLn $ "(Comment " <> intAsText (commentCount cmt) <> ") <" <> commentCreator cmt <> "> " <> (T.pack . show) (commentCreationTime cmt) <> "\n"+ mapM_ (T.putStrLn . (" " <>)) $ dropDuplicates . removeLeadingNewline . T.lines $ commentText cmt+ putStrLn ""++checkRepoCreatedComment :: BugzillaSession -> BugId -> IO Bool+checkRepoCreatedComment session bid =+ checkForComment session bid+ "(fedscm-admin): The Pagure repository was created at"++checkForComment :: BugzillaSession -> BugId -> T.Text -> IO Bool+checkForComment session bid text = do+ comments <- map commentText <$> getComments session bid+ return $ any (text `T.isInfixOf`) $ reverse comments++putReviewBug :: Bool -> Bug -> IO ()+putReviewBug short bug = do+ if short then putStr $ reviewBugToPackage bug ++ " "+ else do+ putStrLn $ reviewBugToPackage bug ++ " (" ++ T.unpack (bugStatus bug) ++ ")"+ putBugId $ bugId bug+ putStrLn ""++putBug :: Bug -> IO ()+putBug bug = do+ T.putStrLn $ bugSummary bug <> " (" <> bugStatus bug <> ")"+ putBugId $ bugId bug+ putStrLn ""++putBugVer :: Bug -> IO ()+putBugVer bug = do+ T.putStr $ "[" <> prodVersion <> "] "+ putBug bug+ where+ prodVersion = T.unwords (bugVersion bug)++putBugId :: BugId -> IO ()+putBugId =+ T.putStrLn . (("https://" <> brc <> "/show_bug.cgi?id=") <>) . intAsText++-- uniq for lists+dropDuplicates :: Eq a => [a] -> [a]+dropDuplicates (x:xs) =+ let ys = dropDuplicates xs in+ case ys of+ (y:_) | x == y -> ys+ _ -> x:ys+dropDuplicates _ = []++removeLeadingNewline :: [T.Text] -> [T.Text]+removeLeadingNewline ("":ts) = ts+removeLeadingNewline ts = ts++-- testBZlogin :: IO ()+-- testBZlogin =+-- void bzLoginSession++-- | make a key-value+makeTextItem :: String -> String -> (T.Text, Maybe T.Text)+makeTextItem k val = (T.pack k, Just (T.pack val))++listBzUsers :: BugzillaSession -> String -> IO [Object]+listBzUsers session user = do+ let req = setRequestCheckStatus $+ newBzRequest session ["user"] [makeTextItem "match" user]+ lookupKey' "users" . getResponseBody <$> httpJSON req
+ src/Cmd/Bugs.hs view
@@ -0,0 +1,21 @@+module Cmd.Bugs (bugsCmd) where++import Bugzilla+import Package++bugsCmd :: Maybe String -> [String] -> IO ()+bugsCmd keyword pkgs = do+ if null pkgs+ then bugsPkg "."+ else mapM_ bugsPkg pkgs+ where+ bugsPkg :: String -> IO ()+ bugsPkg path = do+ pkg <- getPackageName path+ putPkgHdr pkg+ let query =+ case keyword of+ Nothing -> statusOpen+ Just key -> statusOpen .&&. summaryContains key+ (bugs, _) <- bugsSession $ pkgBugs (unPackage pkg) .&&. query+ mapM_ putBugVer $ sortBugsByProduct bugs
+ src/Cmd/Build.hs view
@@ -0,0 +1,202 @@+{-# LANGUAGE OverloadedStrings #-}++module Cmd.Build (+ buildCmd,+ BuildOpts(..),+ UpdateType(..),+ ) where++import Common+import Common.System++import Data.Char (isDigit)+import Fedora.Bodhi hiding (bodhiUpdate)++import Bodhi+import Bugzilla+import Branches+import Cmd.Merge+import Git+import Krb+import Koji+import Package+import Prompt++data BuildOpts = BuildOpts+ { buildoptNoPrompt :: Bool+ , buildoptNoFailFast :: Bool+ , buildoptTarget :: Maybe String+ , buildoptOverride :: Bool+ , buildoptDryrun :: Bool+ , buildoptUpdateType :: Maybe UpdateType+ }++-- FIXME --add-to-update nvr+-- FIXME vertical vs horizontal builds (ie by package or branch)+-- FIXME --rpmlint (only run for master?)+-- FIXME support --wait-build=NVR+-- FIXME provide direct link to failed task/build.log+-- FIXME default behaviour for build in pkg dir: all branches or current?+buildCmd :: BuildOpts -> Maybe BranchOpts -> [String] -> IO ()+buildCmd opts mbrnchopts args = do+ let singleBrnch = if isJust (buildoptTarget opts)+ then ZeroOrOne+ else AnyNumber+ (brs,pkgs) <- splitBranchesPkgs True mbrnchopts True args+ let morethan1 = length pkgs > 1+ withPackageByBranches' (Just False) cleanGitFetchActive mbrnchopts singleBrnch (buildBranch morethan1 opts) (brs,pkgs)++-- FIXME what if untracked files+buildBranch :: Bool -> BuildOpts -> Package -> AnyBranch -> IO ()+buildBranch _ _ _ (OtherBranch _) =+ error' "build only defined for release branches"+buildBranch morethan1 opts pkg rbr@(RelBranch br) = do+ putPkgAnyBrnchHdr pkg rbr+ gitSwitchBranch rbr+ gitMergeOrigin rbr+ newrepo <- initialPkgRepo+ tty <- isTty+ unmerged <- mergeable br+ -- FIXME if already built or failed, also offer merge+ merged <-+ if notNull unmerged && (buildoptNoPrompt opts || newrepo || tty)+ then mergeBranch True (buildoptNoPrompt opts) unmerged br >> return True+ else return False+ let spec = packageSpec pkg+ checkForSpecFile spec+ checkSourcesMatch spec+ nvr <- pkgNameVerRel' br spec+ unpushed <- gitShortLog $ "origin/" ++ show br ++ "..HEAD"+ unless (null unpushed) $+ putStrLn $ "\n" ++ nvr ++ "\n"+ when (not merged || br == Rawhide) $+ unless (null unpushed) $ do+ putStrLn "Local commits:"+ mapM_ (putStrLn . simplifyCommitLog) unpushed+ mpush <-+ if null unpushed then return Nothing+ else+ -- see mergeBranch for: unmerged == 1 (774b5890)+ if tty && (not merged || (newrepo && length unmerged == 1))+ then refPrompt unpushed $ "Press Enter to push and build" ++ (if length unpushed > 1 then "; or give a ref to push" else "") ++ (if not newrepo then "; or 'no' to skip pushing" else "")+ else return $ Just Nothing+ let dryrun = buildoptDryrun opts+ buildstatus <- kojiBuildStatus nvr+ let mtarget = buildoptTarget opts+ target = fromMaybe (branchTarget br) mtarget+ case buildstatus of+ Just BuildComplete -> do+ putStrLn $ nvr ++ " is already built"+ when (isJust mpush) $+ error' "Please bump the spec file"+ when (br /= Rawhide && isNothing mtarget) $ do+ mtags <- kojiNVRTags nvr+ case mtags of+ Nothing -> error' $ nvr ++ " is untagged"+ Just tags ->+ unless dryrun $+ unlessM (checkAutoBodhiUpdate br) $ do+ unless (any (`elem` tags) [show br, show br ++ "-updates", show br ++ "-updates-pending", show br ++ "-updates-testing", show br ++ "-updates-testing-pending"]) $ do+ mBugSess <- do+ (mbid, session) <- bzReviewSession+ return $ case mbid of+ Just bid -> Just (bid,session)+ Nothing -> Nothing+ bodhiUpdate (fmap fst mBugSess) spec nvr+ unless (any (`elem` tags) [show br, show br ++ "-updates", show br ++ "-override"]) $+ when (buildoptOverride opts) $+ bodhiCreateOverride nvr+ when morethan1 $ do+ autoupdate <- checkAutoBodhiUpdate br+ when (buildoptOverride opts || autoupdate) $+ kojiWaitRepo target nvr+ Just BuildBuilding -> do+ putStrLn $ nvr ++ " is already building"+ when (isJust mpush) $+ error' "Please bump the spec file"+ whenJustM (kojiGetBuildTaskID fedoraHub nvr) kojiWatchTask+ -- FIXME do override+ _ -> do+ mbuildref <- case mpush of+ Nothing -> Just <$> git "show-ref" ["--hash", "origin" </> show br]+ _ -> return $ join mpush+ opentasks <- kojiOpenTasks pkg mbuildref target+ case opentasks of+ [task] -> do+ putStrLn $ nvr ++ " task " ++ displayID task ++ " is already open"+ when (isJust mpush) $+ error' "Please bump the spec file"+ kojiWatchTask task+ (_:_) -> error' $ show (length opentasks) ++ " open " ++ unPackage pkg ++ " tasks already!"+ [] -> do+ let tag = fromMaybe (branchDestTag br) mtarget+ mlatest <- kojiLatestNVR tag $ unPackage pkg+ if equivNVR nvr (fromMaybe "" mlatest)+ then error' $ nvr ++ " is already latest" ++ if Just nvr /= mlatest then " (modulo disttag)" else ""+ else do+ unless dryrun krbTicket+ whenJust mpush $ \ mref ->+ unless dryrun $+ gitPushSilent $ fmap (++ ":" ++ show br) mref+ unlessM (null <$> gitShortLog ("origin" </> show br ++ "..HEAD")) $+ when (mpush == Just Nothing) $+ error' "Unpushed changes remain"+ unlessM isGitDirClean $+ error' "local changes remain (dirty)"+ -- FIXME parse build output+ unless dryrun $ do+ kojiBuildBranch target pkg mbuildref ["--fail-fast"]+ mBugSess <-+ if isNothing mlatest+ then do+ (mbid, session) <- bzReviewSession+ return $ case mbid of+ Just bid -> Just (bid,session)+ Nothing -> Nothing+ else return Nothing+ autoupdate <- checkAutoBodhiUpdate br+ if autoupdate+ then whenJust mBugSess $+ \ (bid,session) -> putBugBuild session bid nvr+ else do+ when (isNothing mtarget) $ do+ -- FIXME diff previous changelog?+ bodhiUpdate (fmap fst mBugSess) spec nvr+ -- FIXME prompt for override note+ when (buildoptOverride opts) $+ bodhiCreateOverride nvr+ when morethan1 $+ when (buildoptOverride opts || autoupdate) $+ kojiWaitRepo target nvr+ where+ bodhiUpdate :: Maybe BugId -> FilePath -> String -> IO ()+ bodhiUpdate mreview spec nvr = do+ changelog <- if isJust mreview+ then getSummaryURL spec+ else getChangeLog spec+ let cbugs = mapMaybe extractBugReference $ lines changelog+ bugs = let bids = [show rev | Just rev <- [mreview]] ++ cbugs in+ if null bids then [] else ["--bugs", intercalate "," bids]+ -- FIXME also query for open existing bugs+ case buildoptUpdateType opts of+ Nothing -> return ()+ Just updateType -> do+ putStrLn $ "Creating Bodhi Update for " ++ nvr ++ ":"+ cmd_ "bodhi" (["updates", "new", "--type", if isJust mreview then "newpackage" else show updateType, "--request", "testing", "--notes", changelog, "--autokarma", "--autotime", "--close-bugs"] ++ bugs ++ [nvr])+ updatequery <- bodhiUpdates [makeItem "display_user" "0", makeItem "builds" nvr]+ case updatequery of+ [] -> do+ putStrLn "bodhi submission failed"+ prompt_ "Press Enter to resubmit to Bodhi"+ bodhiUpdate mreview spec nvr+ [update] -> case lookupKey "url" update of+ Nothing -> error' "Update created but no url"+ Just uri -> putStrLn uri+ _ -> error' $ "impossible happened: more than one update found for " ++ nvr++ extractBugReference :: String -> Maybe String+ extractBugReference clog =+ let rest = dropWhile (/= '#') clog in+ if null rest then Nothing+ else let bid = takeWhile isDigit $ tail rest in+ if null bid then Nothing else Just bid
+ src/Cmd/Bump.hs view
@@ -0,0 +1,48 @@+module Cmd.Bump+ ( bumpPkgs,+ )+where++import Branches+import Common+import Common.System+import Git+import Koji+import Package++bumpPkgs :: Maybe CommitOpt -> Maybe BranchOpts -> [String] -> IO ()+bumpPkgs mopt mbrnchopts =+ withPackageByBranches (Just True) cleanGitFetchActive mbrnchopts True AnyNumber bumpPkg+ where+ bumpPkg :: Package -> AnyBranch -> IO ()+ bumpPkg pkg br = do+ -- FIXME or check for unpushed bump+ mlatest <-+ case br of+ RelBranch rbr ->+ let tag = branchDestTag rbr in+ kojiLatestNVR tag $ unPackage pkg+ _ -> return Nothing+ spec <- localBranchSpecFile pkg br+ rbr <-+ case br of+ RelBranch rbr -> return rbr+ OtherBranch _ -> systemBranch+ nvr <- pkgNameVerRel' rbr spec+ if equivNVR nvr (fromMaybe "" mlatest) then do+ git_ "log" ["origin..HEAD", "--pretty=oneline"]+ let clmsg =+ case mopt of+ Just (CommitMsg msg) -> msg+ _ -> "rebuild"+ cmd_ "rpmdev-bumpspec" ["-c", clmsg, spec]+ let copts =+ case mopt of+ Nothing -> ["-m", "bump release"]+ Just opt ->+ case opt of+ CommitMsg msg -> ["-m", msg]+ -- FIXME reject amend if already pushed+ CommitAmend -> ["--amend", "--no-edit"]+ git_ "commit" $ "-a" : copts+ else putStrLn "already bumped"
+ src/Cmd/Clone.hs view
@@ -0,0 +1,25 @@+module Cmd.Clone (cloneCmd, CloneRequest(..)) where++import Common.System+import qualified Common.Text as T++import Branches+import Krb+import Package+import Pagure++data CloneRequest = CloneUser (Maybe String) | ClonePkgs [String]++-- FIXME allow pagure repo wildcard+-- FIXME --anonymous (detect commit rights? or a ssh key?)+cloneCmd :: Maybe Branch -> CloneRequest -> IO ()+cloneCmd mbr request = do+ pkgs <- case request of+ CloneUser mid -> do+ userid <- maybe fasIdFromKrb return mid+ map (takeFileName . T.unpack) <$> pagureUserRepos srcfpo userid+ -- FIXME detect/prevent "path/dir"+ ClonePkgs ps -> return ps+ putStr "Cloning: "+ mapM_ (clonePkg False mbr) pkgs+ putStrLn ""
+ src/Cmd/Commit.hs view
@@ -0,0 +1,48 @@+module Cmd.Commit+ ( commitPkgs,+ )+where++import Common+import Common.System+import Git+import Package+import Prompt++-- FIXME use branches after all?+commitPkgs :: Maybe CommitOpt -> [String] -> IO ()+commitPkgs mopt args =+ if null args+ then commitPkg "."+ else mapM_ commitPkg args+ where+ commitPkg :: FilePath -> IO ()+ commitPkg path =+ withExistingDirectory path $+ unlessM isGitDirClean $ do+ getPackageName path >>= putPkgHdr+ opts <- case mopt of+ Just opt -> return $+ case opt of+ CommitMsg msg -> ["-m", msg]+ -- FIXME reject amend if already pushed+ CommitAmend -> ["--amend", "--no-edit"]+ Nothing -> do+ changelog <- do+ spec <- findSpecfile+ clog <- cleanChangelog <$> cmd "rpmspec" ["-q", "--srpm", "--qf", "%{changelogtext}", spec]+ when (length (lines clog) > 1) $+ putStrLn clog+ diff <- git "diff" ["-U0", "HEAD"]+ if ("+- " ++ clog) `elem` lines diff+ then putStrLn clog >> return clog+ else putStrLn diff >> readCommitMsg+ return ["-m", changelog]+ git_ "commit" $ "-a" : opts++readCommitMsg :: IO String+readCommitMsg = do+ clog <- prompt "\nPlease input the commit message"+ if null clog+ then readCommitMsg+ else return clog
+ src/Cmd/Copr.hs view
@@ -0,0 +1,156 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE OverloadedStrings #-}++module Cmd.Copr (+ BuildBy(..),+ coprCmd+ )+where++import Branches+import Common+import Common.System+import qualified Common.Text as T+import Package++import Data.Ini.Config+import System.Environment.XDG.BaseDir (getUserConfigDir)+import Web.Fedora.Copr (coprChroots)++data BuildBy = SingleBuild | ValidateByRelease | ValidateByArch | BuildByRelease+ deriving (Eq)++coprServer :: String+coprServer = "copr.fedorainfracloud.org"++-- FIXME make project optional (if same as pkg??) or configurable ?+-- FIXME repo config with a setup command?+-- FIXME interact with copr dist-git+-- FIXME parallel copr builds+coprCmd ::+ Bool -> BuildBy -> [String] -> String -> Maybe BranchOpts -> [String] -> IO ()+coprCmd dryrun buildBy archs project mbrnchopts args = do+ (brs,pkgs) <- splitBranchesPkgs True mbrnchopts True args+ chroots <- coprGetChroots brs+ if null pkgs then+ getPackageName "." >>= coprBuildPkg chroots+ else+ mapM_ (\ p -> withExistingDirectory p $ coprBuildPkg chroots (Package p)) pkgs+ where+ coprGetChroots brs = do+ username <- getUsername+ chroots <- map T.unpack <$> coprChroots coprServer username project+ when (null chroots) $+ error' $ "No chroots found for " ++ username ++ "/" ++ project+ branches <-+ if isNothing mbrnchopts && null brs+ then return $ (map (releaseBranch . T.pack) . nub . map removeArch) chroots+ else do+ brs' <- listOfBranches False False mbrnchopts brs+ forM brs' $ \ case+ OtherBranch obr -> error' $ "unknown copr target: " ++ obr+ RelBranch rbr -> return rbr+ let buildroots =+ reverseSort $+ if null archs+ then [chroot | chroot <- chroots, removeArch chroot `elem` map branchRelease branches]+ else [chroot | arch <- archs, br <- branches, let chroot = branchRelease br ++ "-" ++ arch, chroot `elem` chroots]+ if null buildroots+ then error' "No chroots chosen"+ else return buildroots++ coprBuildPkg buildroots pkg = do+ -- FIXME check is pkg.spec+ spec <- localBranchSpecFile pkg (RelBranch Rawhide)+ -- pkg <- takeFileName <$> getCurrentDirectory+ -- hack to avoid generating srpm for dryrun+ srpm <- if not dryrun+ then generateSrpm Nothing spec -- FIXME: let distopt = ["--undefine", "dist"]+ else return spec+ case buildBy of+ SingleBuild -> coprBuild dryrun project srpm buildroots+ -- FIXME or default to secondary parallel to previous primary+ ValidateByRelease -> do+ let initialChroots =+ let primaryArch = releaseArch $ head buildroots+ in map pure $ filter (isArch primaryArch) buildroots+ remainingChroots = buildroots \\ concat initialChroots+ staggerBuilds srpm initialChroots remainingChroots+ ValidateByArch -> do+ let initialChroots =+ let newestRelease = removeArch $ head buildroots+ in map pure $ filter (newestRelease `isPrefixOf`) buildroots+ remainingChroots = buildroots \\ concat initialChroots+ staggerBuilds srpm initialChroots remainingChroots+ BuildByRelease -> do+ let initialChroots = groupBy sameRelease buildroots+ remainingChroots = buildroots \\ concat initialChroots+ staggerBuilds srpm initialChroots remainingChroots++ removeArch relarch = init $ dropWhileEnd (/= '-') relarch++ staggerBuilds srpm initialChroots remainingChroots = do+ mapM_ (coprBuild dryrun project srpm) initialChroots+ unless (null remainingChroots) $+ coprBuild dryrun project srpm remainingChroots++ releaseArch relarch = takeWhileEnd (/= '-') relarch++ isArch arch release = releaseArch release == arch++ sameRelease r1 r2 = removeArch r1 == removeArch r2++ reverseSort = reverse . sort++branchRelease :: Branch -> String+branchRelease Rawhide = "fedora-rawhide"+branchRelease (Fedora n) = "fedora-" ++ show n+branchRelease (EPEL n) = "epel-" ++ show n++--data Chroot = Chroot Release Arch++getUsername :: IO String+getUsername = do+ rc <- getUserConfigDir "copr"+ readIniConfig rc rcParser id+ where+ rcParser :: IniParser String+ rcParser =+ section "copr-cli" $+ fieldOf "username" string++-- changed from Bugzilla.hs+readIniConfig :: FilePath -> IniParser a -> (a -> b) -> IO b+readIniConfig inifile iniparser record = do+ havefile <- doesFileExist inifile+ if not havefile+ then error' $ inifile ++ " not found: try https://" ++ coprServer ++ "/api"+ else do+ ini <- T.readFile inifile+ let config = parseIniFile ini iniparser+ return $ either error' record config++coprBuild :: Bool -> String -> FilePath -> [String] -> IO ()+coprBuild _ _ _ [] = error' "No chroots chosen"+coprBuild dryrun project srpm buildroots = do+ let chrootargs = mconcat [["-r", bldrt] | bldrt <- buildroots]+ buildargs = ["build", "--nowait"] ++ chrootargs ++ [project, srpm]+ putStrLn ""+ putStrLn $ unwords buildroots+ unless dryrun $ do+ output <- cmd "copr" buildargs+ putStrLn output+ let bid = last $ words $ last $ lines output+ ok <- cmdBool "copr" ["watch-build", bid]+ unless ok $+ cmdN "Failed: copr" buildargs++#if !MIN_VERSION_simple_cmd(0,1,4)+error' :: String -> a+#if MIN_VERSION_base(4,9,0)+error' = errorWithoutStackTrace+#else+error' = error+#endif+#endif
+ src/Cmd/Diff.hs view
@@ -0,0 +1,85 @@+module Cmd.Diff (+ diffCmd,+ DiffFormat(..),+ DiffWork(..)+ ) where++import Branches+import Common+import Common.System+import Git+import Package++data DiffFormat =+ DiffDefault | DiffQuiet | DiffContext Int | DiffMinimal | DiffStats+ deriving (Eq)++data DiffWork =+ DiffWorkAll | DiffWorkUnstage | DiffWorkStaged+ deriving (Eq)++-- FIXME diff other branches without switching+-- FIXME --older/--newer branch+diffCmd :: Bool -> DiffWork -> DiffFormat -> Maybe AnyBranch -> [String]+ -> IO ()+diffCmd speconly work fmt mwbr =+ withPackageByBranches Nothing dirtyGit Nothing True ZeroOrOne diffPkg+ where+ diffPkg :: Package -> AnyBranch -> IO ()+ diffPkg pkg br = do+ gitSwitchBranch br+ let contxt = case fmt of+ DiffContext n -> ["--unified=" ++ show n]+ DiffMinimal -> ["--unified=0"]+ -- FIXME hide "files changed" and "insertions" summary+ DiffStats -> ["--compact-summary"]+ _ -> []+ (workOpts,workArgs) =+ case work of+ DiffWorkAll -> ([],["HEAD" | isNothing mwbr])+ DiffWorkUnstage -> ([],[])+ DiffWorkStaged -> (["--cached"],[])+ file = [packageSpec pkg | speconly]+ withBranch <-+ case mwbr of+ Nothing -> return []+ Just wbr ->+ let brn = show wbr in+ if '/' `elem` brn+ then return [brn]+ else do+ localbrs <- gitLines "branch" ["--format=%(refname:short)"]+ if brn `elem` localbrs+ then return [brn]+ else return ["origin/" ++ brn]+ let revdiff = case mwbr of+ Nothing -> []+ Just wbr -> case (wbr,br) of+ (RelBranch rwbr, RelBranch rbr) -> ["-R" | rwbr > rbr]+ _ -> []+ diff <- git "diff" $ contxt ++ workOpts ++ revdiff ++ withBranch ++ workArgs ++ file+ unless (null diff) $+ case fmt of+ DiffQuiet -> putStrLn $ unPackage pkg+ DiffMinimal -> do+ putPkgAnyBrnchHdr pkg br+ putStr $ minifyDiff diff+ _ -> do+ putPkgAnyBrnchHdr pkg br+ putStrLn diff+ where+ minifyDiff =+ unlines . maybeRemoveDiffGit . filterCommon . lines+ where+ filterCommon =+ -- flist is from swish+ let flist fs a = map ($ a) fs in+ filter (not . or . flist (map isPrefixOf ["--- a/", "+++ b/", "index ", "@@ -"]))++ maybeRemoveDiffGit ls =+ let spec = unPackage pkg <.> "spec"+ specDiffGit = "diff --git a/" ++ spec ++ " b/" ++ spec+ gitDiffs = filter ("diff --git a/" `isPrefixOf`) ls in+ if gitDiffs == [specDiffGit]+ then delete specDiffGit ls+ else ls
+ src/Cmd/Import.hs view
@@ -0,0 +1,93 @@+{-# LANGUAGE OverloadedStrings #-}++module Cmd.Import (importCmd) where++import Common+import Common.System+import qualified Common.Text as T++import Network.URI++import Branches+import Bugzilla+import Cmd.RequestBranch (requestPkgBranches)+import Git+import Koji+import Krb+import ListReviews+import Package+import Prompt++-- FIXME separate pre-checked listReviews and direct pkg call, which needs checks+importCmd :: [String] -> IO ()+importCmd ps = do+ pkgs <- if null ps+ then map reviewBugToPackage <$> listReviews ReviewRepoCreated+ else return ps+ mapM_ importPkg pkgs++-- FIXME check not in a different git dir+importPkg :: String -> IO ()+importPkg pkg = do+ putPkgHdr (Package pkg)+ dir <- getCurrentDirectory+ when (pkg /= takeFileName dir) $ do+ -- FIXME check git repo exists+ clonePkg True Nothing pkg+ putStrLn ""+ setCurrentDirectory pkg+ -- FIXME: check branch is master+ unlessM isGitRepo $ error' "Not a git repo"+ newrepo <- initialPkgRepo+ if not newrepo+ then putStrLn "Skipping: already imported"+ else do+ checkWorkingDirClean+ -- FIXME get session from importPkgs+ (bid,session) <- approvedReviewBugIdSession pkg+ comments <- getComments session bid+ putBugId bid+ putStrLn ""+ mapM_ showComment comments+ putStrLn ""+ putStr "Review bug: "+ putBugId bid+ putStrLn ""+ prompt_ "Press Enter to continue"+ let srpms = map (T.replace "/reviews//" "/reviews/") $ concatMap findSRPMs comments+ when (null srpms) $ error "No srpm urls found!"+ mapM_ T.putStrLn srpms+ let srpm = (head . filter isURI . filter (".src.rpm" `isSuffixOf`) . words . T.unpack . last) srpms+ let srpmfile = takeFileName srpm+ -- FIXME if havesrpm then print local filename+ prompt_ $ "Press Enter to import " ++ srpmfile+ havesrpm <- doesFileExist srpmfile+ unless havesrpm $+ cmd_ "curl" ["--silent", "--show-error", "--remote-name", srpm]+ krbTicket+ fedpkg_ "import" [srpmfile]+ git_ "commit" ["--message", "import #" ++ show bid]+ nvr <- pkgNameVerRel' Rawhide (pkg <.> "spec")+ prompt_ $ "Press Enter to push and build " ++ nvr+ gitPushSilent Nothing+ kojiBuildBranch "rawhide" (Package pkg) Nothing ["--fail-fast"]+ putBugBuild session bid nvr+ brs <- branchingPrompt+ requestPkgBranches False Nothing brs (Package pkg)+ when (pkg /= takeFileName dir) $+ setCurrentDirectory dir+ where+ findSRPMs :: Comment -> [T.Text]+ findSRPMs =+ filter (\ l -> "https://" `T.isInfixOf` l && any (`T.isPrefixOf` T.toLower l) ["srpm url:", "srpm:", "new srpm:", "updated srpm:"] && ".src.rpm" `T.isSuffixOf` l) . T.lines . commentText++ branchingPrompt :: IO [Branch]+ branchingPrompt = do+ inp <- prompt "Enter required branches [default: latest 2]"+ if null inp+ then return []+ else+ let brs = map anyBranch $ words inp+ in if all isRelBranch brs+ then return $ map onlyRelBranch brs+ else branchingPrompt
+ src/Cmd/ListBranches.hs view
@@ -0,0 +1,61 @@+module Cmd.ListBranches (+ branchesCmd+ )+where++import Common+import Common.System++import Branches+import Git+import Package++-- FIXME remote/pagures branch and --remote or --no-remote+-- FIXME --local for existing local branches+branchesCmd :: Bool -> Bool -> Bool -> Bool -> [String] -> IO ()+branchesCmd skipdead allbrs missing remote args = do+ (brs,pkgs) <- splitBranchesPkgs False Nothing (not remote) args+ when allbrs $ do+ unless (null brs) $+ error' "cannot combine --all and branches"+ when missing $+ error' "cannot combine --all and --missing"+ if null pkgs+ then branchesPkg brs "."+ else mapM_ (branchesPkg brs) pkgs+ where+ branchesPkg :: [AnyBranch] -> FilePath -> IO ()+ branchesPkg branches path = do+ if remote then doBranchesPkg+ else+ withExistingDirectory path $+ if skipdead then+ ifM (doesFileExist "dead.package")+ (return ())+ doBranchesPkg+ else doBranchesPkg+ where+ doBranchesPkg :: IO ()+ doBranchesPkg = do+ unlessM isPkgGitRepo $+ unless remote $+ error' "not dist-git"+ pkg <- getPackageName path+ brs <- if remote+ then pagurePkgBranches (unPackage pkg)+ else localBranches+ if allbrs then do+ putStrLn $ unPackage pkg ++ ": " ++ unwords brs+ else do+ if null branches then do+ -- FIXME better to filter inactive instead+ active <- getFedoraBranches+ let result = if missing then active \\ mapMaybe readBranch brs else activeBranches active brs+ putStr $ unPackage pkg ++ ": "+ putStrLn $ (unwords . map show) result+ else do+ let havebrs = filter (`elem` branches) (map anyBranch brs)+ result = if missing then branches \\ havebrs else havebrs+ unless (null result) $ do+ putStr $ unPackage pkg ++ ": "+ putStrLn $ (unwords . map show) result
+ src/Cmd/ListPackages.hs view
@@ -0,0 +1,61 @@+{-# LANGUAGE OverloadedStrings #-}++module Cmd.ListPackages (+ listCmd,+ Packager(..)+ )+where++import Data.Aeson+import Fedora.Pagure++import Common+import Common.System+import qualified Common.Text as T+import Pagure++data Packager = Owner String | Committer String++-- FIXME remote/pagures branch and --remote or --no-remote+listCmd :: Bool -> Maybe Packager -> [String] -> IO ()+listCmd count mpackager pkgs = do+ unless (count || isJust mpackager || not (null pkgs)) $+ error' "Please give a package pattern, --count, or --owner/--username"+ if null pkgs then listPackage Nothing+ else mapM_ (listPackage . Just) pkgs+ where+ listPackage :: Maybe String -> IO ()+ listPackage mpattern = do+ let path = "projects"+ params = makeKey "short" "1" ++ fork ++ packager ++ makeKey "namespace" "rpms" ++ maybeKey "pattern" mpattern+ pages <- queryPaged srcfpo count path params ("pagination", "page")+ mapM_ (printPage . toObject) pages+ where+ packager =+ case mpackager of+ Nothing -> makeKey "owner" "!orphan"+ Just (Owner o) -> makeKey "owner" o+ Just (Committer c) -> makeKey "username" c++ fork = makeKey "fork" "0"++ printPage :: Object -> IO ()+ printPage result =+ let projects = lookupKey' "projects" result :: [Object]+ in+ mapM_ (T.putStrLn . lookupKey' "name") projects++ toObject :: Value -> Object+ toObject (Object obj) = obj+ toObject v = error $ "not object: " ++ show v++-- FIXME limit max number of pages (10?) or --pages+queryPaged :: String -> Bool -> String -> Query -> (String,String) -> IO [Value]+queryPaged server count path params (pagination,paging) =+ if count+ then do+ mnum <- queryPagureCount server path params pagination+ print $ fromMaybe (error' "pages not found") mnum+ return []+ else+ queryPagurePaged server path params (pagination,paging)
+ src/Cmd/Local.hs view
@@ -0,0 +1,143 @@+module Cmd.Local (+ commandCmd,+ installCmd,+ installDepsCmd,+ localCmd,+ nvrCmd,+ prepCmd,+ sortCmd,+ RpmWith(..),+ srpmCmd,+ masterRenameCmd+ ) where++import Distribution.RPM.Build.Order (dependencySortRpmOpts)+import qualified System.Process as P+import System.Environment++import Branches+import Common+import Common.System+import Git+import Package++-- FIXME package countdown+-- FIXME --ignore-uninstalled subpackages+-- FIXME --recursive+installCmd :: Maybe ForceShort -> [BCond] -> Bool -> [String] -> IO ()+installCmd mforceshort bconds reinstall =+ withPackageByBranches Nothing Nothing Nothing True ZeroOrOne installPkg+ where+ installPkg :: Package -> AnyBranch -> IO ()+ installPkg pkg br = do+ spec <- localBranchSpecFile pkg br+ rpms <- builtRpms br spec+ -- removing arch+ let packages = map takeNVRName rpms+ installed <- filterM pkgInstalled packages+ if isJust mforceshort || null installed || reinstall+ then doInstallPkg spec rpms installed+ else putStrLn $ unwords installed ++ " already installed!\n"+ where+ doInstallPkg spec rpms installed = do+ putStrLn $ takeBaseName (head rpms) ++ "\n"+ buildRPMs True mforceshort bconds rpms br spec+ putStrLn ""+ unless (mforceshort == Just ShortCircuit) $+ if reinstall then do+ let reinstalls = filter (\ f -> takeNVRName f `elem` installed) rpms+ unless (null reinstalls) $+ sudo_ "/usr/bin/dnf" $ "reinstall" : "-q" : "-y" : reinstalls+ let remaining = filterDebug $ rpms \\ reinstalls+ unless (null remaining) $+ sudo_ "/usr/bin/dnf" $ "install" : "-q" : "-y" : remaining+ else sudo_ "/usr/bin/dnf" $ "install" : "-q" : "-y" : filterDebug rpms++ filterDebug = filter (\p -> not (any (`isInfixOf` p) ["-debuginfo-", "-debugsource-"]))++localCmd :: Maybe ForceShort -> [BCond] -> [String] -> IO ()+localCmd mforceshort bconds =+ withPackageByBranches Nothing Nothing Nothing True ZeroOrOne localBuildPkg+ where+ localBuildPkg :: Package -> AnyBranch -> IO ()+ localBuildPkg pkg br = do+ spec <- localBranchSpecFile pkg br+ rpms <- builtRpms br spec+ buildRPMs False mforceshort bconds rpms br spec++-- FIXME single branch+installDepsCmd :: [String] -> IO ()+installDepsCmd =+ withPackageByBranches Nothing Nothing Nothing True ZeroOrOne installDepsPkg+ where+ installDepsPkg :: Package -> AnyBranch -> IO ()+ installDepsPkg pkg br =+ localBranchSpecFile pkg br >>= installDeps++-- FIXME single branch+srpmCmd :: [String] -> IO ()+srpmCmd =+ withPackageByBranches Nothing Nothing Nothing True ZeroOrOne srpmBuildPkg+ where+ srpmBuildPkg :: Package -> AnyBranch -> IO ()+ srpmBuildPkg pkg br = do+ spec <- localBranchSpecFile pkg br+ void $ generateSrpm (Just br) spec++data RpmWith = RpmWith String | RpmWithout String++sortCmd :: Maybe RpmWith -> [String] -> IO ()+sortCmd _ [] = return ()+sortCmd mrpmwith args = do+ (brs,pkgs) <- splitBranchesPkgs False Nothing True args+ withPackageByBranches' Nothing Nothing Nothing ExactlyOne dummy (brs,pkgs)+ let rpmopts = maybe [] toRpmOption mrpmwith+ packages <- dependencySortRpmOpts rpmopts $ reverse pkgs+ putStrLn $ unwords packages+ where+ dummy _ br = gitSwitchBranch br++ toRpmOption :: RpmWith -> [String]+ toRpmOption (RpmWith opt) = ["--with=" ++ opt]+ toRpmOption (RpmWithout opt) = ["--without=" ++ opt]++prepCmd :: [String] -> IO ()+prepCmd =+ withPackageByBranches Nothing Nothing Nothing True ZeroOrOne prepPackage++nvrCmd :: Maybe BranchOpts -> [String] -> IO ()+nvrCmd mbrnchopts =+ withPackageByBranches Nothing Nothing mbrnchopts True AnyNumber nvrBranch+ where+ nvrBranch :: Package -> AnyBranch -> IO ()+ nvrBranch pkg br = do+ spec <- localBranchSpecFile pkg br+ case br of+ RelBranch rbr ->+ pkgNameVerRel' rbr spec+ OtherBranch _obr -> do+ sbr <- systemBranch+ pkgNameVerRel' sbr spec+ >>= putStrLn++commandCmd :: String -> Maybe BranchOpts -> [String] -> IO ()+commandCmd cs mbrnchopts =+ withPackageByBranches (Just True) Nothing mbrnchopts True AnyNumber cmdBranch+ where+ cmdBranch :: Package -> AnyBranch -> IO ()+ cmdBranch pkg _br = do+ curEnv <- getEnvironment+ let p = (P.shell cs) { P.env = Just (("p",unPackage pkg):curEnv) }+ (_,_,_,h) <- P.createProcess p+ void $ P.waitForProcess h++masterRenameCmd :: [String] -> IO ()+masterRenameCmd =+ withPackageByBranches Nothing dirtyGit Nothing True ZeroOrOne masterRenameBranch+ where+ masterRenameBranch :: Package -> AnyBranch -> IO ()+ masterRenameBranch _pkg _br = do+ git_ "fetch" ["--prune"]+ git_ "branch" ["-m", "master", "rawhide"]+ git_ "remote" ["set-head", "origin", "rawhide"]+ git_ "branch" ["-u", "origin/rawhide", "rawhide"]
+ src/Cmd/Log.hs view
@@ -0,0 +1,33 @@+module Cmd.Log (+ logCmd)+where++import Branches+import Common+import Common.System+import Git+import Package++logCmd :: Bool -> AnyBranch -> AnyBranch -> [String] -> IO ()+logCmd long br1 br2 pkgs = do+ if null pkgs+ then do+ unlessM isPkgGitRepo $+ error' "Please specify at least one package"+ else do+ whenM isPkgGitRepo $+ error' "Cannot specify multiple packages inside a package dir"+ let packages = if null pkgs then ["."] else pkgs+ mapM_ logPkg packages+ where+ logPkg :: String -> IO ()+ logPkg pkgdir =+ withExistingDirectory pkgdir $ do+ unless (null pkgs) $+ getPackageName pkgdir >>= putPkgHdr+ let (br1',br2') =+ case (br1, br2) of+ (RelBranch b1, RelBranch b2) | b2 < b1 -> (br2,br1)+ _ -> (br1,br2)+ in+ git_ "log" $ ["--format=reference" | not long] ++ [show br1' ++ ".." ++ show br2']
+ src/Cmd/Merge.hs view
@@ -0,0 +1,69 @@+module Cmd.Merge (mergeCmd, mergeable, mergeBranch) where++import Common+import Common.System++import Branches+import Git+import Package+import Prompt++-- FIXME add --no-prompt+-- add BranchOpts?+mergeCmd :: [String] -> IO ()+mergeCmd =+ withPackageByBranches (Just False) cleanGitFetchActive Nothing True AnyNumber runMergeBranch+ where+ runMergeBranch :: Package -> AnyBranch -> IO ()+ runMergeBranch _ (OtherBranch _) =+ error' "merge only defined for release branches"+ runMergeBranch pkg rbr@(RelBranch br) = do+ putPkgBrnchHdr pkg br+ gitSwitchBranch rbr+ gitMergeOrigin rbr+ unmerged <- mergeable br+ mergeBranch False False unmerged br++getNewerBranch :: Branch -> IO Branch+getNewerBranch Rawhide = return Rawhide+getNewerBranch br = do+ branches <- fedoraBranches localBranches+ let newer = newerBranch br branches+ return $ if newer > br then newer+ -- FIXME this can be dropped with next fedora-dists+ else case elemIndex br branches of+ Just i -> branches !! (i - 1)+ Nothing -> error' $ show br ++ ": branch not found"++-- FIXME newer branch might not exist (eg epel8):+ -- restrict to local branches+mergeable :: Branch -> IO [String]+mergeable br = do+ newerBr <- getNewerBranch br+ gitMergeable $ show newerBr++-- FIXME return merged ref+mergeBranch :: Bool -> Bool -> [String] -> Branch -> IO ()+mergeBranch _ _ _ Rawhide = return ()+mergeBranch _ _ [] _ = return ()+mergeBranch build noprompt unmerged br = do+ newerBr <- getNewerBranch br+ newrepo <- initialPkgRepo+ unless (null unmerged) $ do+ putStrLn $ (if newrepo || noprompt then "Merging from" else "New commits in") ++ " " ++ show newerBr ++ ":"+ mapM_ (putStrLn . simplifyCommitLog) unmerged+ unpushed <- gitShortLog $ "origin/" ++ show br ++ "..HEAD"+ unless (null unpushed) $ do+ putStrLn "Local commits:"+ mapM_ (putStrLn . simplifyCommitLog) unpushed+ -- FIXME avoid Mass_Rebuild bumps+ mmerge <-+ if newrepo && length unmerged == 1 || noprompt then return $ Just Nothing+ else refPrompt unmerged $ "Press Enter to merge " ++ show newerBr ++ (if build then " and build" else "") ++ (if length unmerged > 1 then "; or give a ref to merge" else "") ++ "; or 'no' to skip merge"+ -- ensure still on same branch!+ gitSwitchBranch (RelBranch br)+ whenJust mmerge $ \ mhash -> do+ let ref = case mhash of+ Nothing -> show newerBr+ Just hash -> hash+ git_ "merge" ["--quiet", ref]
+ src/Cmd/Mock.hs view
@@ -0,0 +1,59 @@+module Cmd.Mock+ ( mockCmd+ )+where++import Branches+import Common+import Common.System+import Git+import Package++mockCmd :: Bool -> Bool -> Bool -> Bool -> Maybe Branch -> [String] -> IO ()+mockCmd dryrun noclean network noCleanAfter mroot args = do+ (brs, pkgs) <- splitBranchesPkgs True Nothing True args+ unless (null pkgs) $+ whenM isPkgGitRepo $+ error' "Cannot build multiple packages inside a package dir"+ when (null brs && length pkgs > 1 && isNothing mroot) $+ error' "Must specific branch or --root chroot"+ branches <-+ if null brs+ then+ if null pkgs+ then pure <$> getReleaseBranch+ else pure <$> systemBranch+ else map onlyRelBranch <$> listOfBranches False False Nothing brs+ let packages = if null pkgs then ["."] else pkgs+ mapM_ (mockBuildPkgs (null brs) packages) branches+ where+ mockBuildPkgs :: Bool -> [String] -> Branch -> IO ()+ mockBuildPkgs noswitch pkgs br = do+ srpms <- mapM (prepSrpm (RelBranch br)) pkgs+ putStrLn ""+ rootBr <- maybe getReleaseBranch return mroot+ let resultdir =+ case pkgs of+ [] -> error' "cannot build zero packages"+ [_] ->+ let verrel = joinPath $ takeEnd 2 $ splitOn "-" $ takeNVRName (head srpms)+ in ["--resultdir=results" </> verrel]+ _ -> []+ let command = if length pkgs > 1 then "--chain" else "--rebuild"+ (if dryrun then cmdN else cmd_) "mock" $ [command, "--root", mockConfig rootBr] ++ ["--no-clean" | noclean] ++ ["--no-clean-after" | noCleanAfter] ++ ["--config-opts=cleanup_on_failure=False" | not noCleanAfter] ++ ["--enable-network" | network] ++ resultdir ++ srpms+ where+ prepSrpm :: AnyBranch -> FilePath -> IO FilePath+ prepSrpm rbr pkgdir =+ withExistingDirectory pkgdir $ do+ pkg <- getPackageName pkgdir+ putPkgHdr pkg+ actualBr <-+ ifM+ (notM isPkgGitRepo)+ (return rbr)+ ( if noswitch+ then gitCurrentBranch+ else gitSwitchBranch rbr >> return rbr+ )+ spec <- findSpecfile+ (pkgdir </>) . takeFileName <$> generateSrpm (Just actualBr) spec
+ src/Cmd/Override.hs view
@@ -0,0 +1,33 @@+module Cmd.Override (overrideCmd)+where++import Common+import Common.System++import Bodhi+import Branches+import Git+import Koji+import Package++overrideCmd :: [String] -> IO ()+overrideCmd =+ withPackageByBranches (Just False) cleanGitFetchActive Nothing True AnyNumber overrideBranch+ where+ overrideBranch :: Package -> AnyBranch -> IO ()+ overrideBranch _ (OtherBranch _) =+ error' "override only defined for release branches"+ overrideBranch pkg rbr@(RelBranch br) = do+ putPkgBrnchHdr pkg br+ gitSwitchBranch rbr+ let spec = packageSpec pkg+ nvr <- pkgNameVerRel' br spec+ putStrLn nvr+ mtags <- kojiNVRTags nvr+ case mtags of+ Nothing -> error' $ nvr ++ " is untagged"+ Just tags ->+ unless (any (`elem` tags) [show br, show br ++ "-updates", show br ++ "-override"]) $+ unlessM (checkAutoBodhiUpdate br) $ do+ bodhiCreateOverride nvr+ kojiWaitRepo (branchTarget br) nvr
+ src/Cmd/Parallel.hs view
@@ -0,0 +1,241 @@+{-# LANGUAGE OverloadedStrings #-}++module Cmd.Parallel (+ parallelBuildCmd,+ SideTagTarget(..)+ ) where++import Common+import Common.System++import Control.Concurrent.Async+import Distribution.RPM.Build.Order (dependencyLayers)+import System.Console.Pretty+import System.Time.Extra (sleep)++import Bodhi+import Bugzilla+import Branches+import Git+import Krb+import Koji+import Package+import Prompt++data SideTagTarget = SideTag | Target String++maybeTarget :: Maybe SideTagTarget -> Maybe String+maybeTarget (Just (Target t)) = Just t+maybeTarget _ = Nothing++-- (pkg, (sidetag, nvr))+type Job = (String, Async (String, String))++-- FIXME only override if more packages to build+-- FIXME option to build multiple packages over branches in parallel+-- FIXME use --wait-build=NVR+-- FIXME check sources asap+parallelBuildCmd :: Bool -> Maybe SideTagTarget -> Maybe UpdateType -> Maybe BranchOpts -> [String]+ -> IO ()+parallelBuildCmd dryrun msidetagTarget mupdatetype mbrnchopts args = do+ (brs,pkgs) <- splitBranchesPkgs True mbrnchopts True args+ when (null brs && isNothing mbrnchopts) $+ error' "Please specify at least one branch"+ branches <- listOfBranches True True mbrnchopts brs+ let mtarget = maybeTarget msidetagTarget+ when (isJust mtarget && length branches > 1) $+ error' "You can only specify target with one branch"+ if null pkgs+ then do+ unlessM isPkgGitRepo $+ error' "Please specify at least one package"+ parallelBranches $ map onlyRelBranch branches+ else do+ whenM isPkgGitRepo $+ error' "Cannot build multiple packages inside a package dir"+ forM_ branches $ \ br -> do+ case br of+ (RelBranch rbr) -> do+ layers <- dependencyLayers pkgs+ when (isNothing msidetagTarget && length layers > 1) $ do+ unlessM (checkAutoBodhiUpdate rbr) $+ error' "You must use --target/--sidetag to build package layers for this branch"+ when (length branches > 1) $+ putStrLn $ "# " ++ show rbr+ targets <- mapM (parallelBuild rbr) layers+ when (isJust msidetagTarget && null targets) $+ error' "No target was returned from jobs!"+ unless (isNothing msidetagTarget || null targets) $ do+ let target = head targets+ when (target /= branchTarget rbr) $ do+ notes <- prompt $ "Enter notes to submit Bodhi update for " ++ target+ bodhiSidetagUpdate target notes+ (OtherBranch _) ->+ error' "parallel builds only defined for release branches"+ where+ parallelBranches :: [Branch] -> IO ()+ parallelBranches brs = do+ krbTicket+ putStrLn $ "Building parallel " ++ show (length brs) ++ " branches:"+ putStrLn $ unwords $ map show brs+ jobs <- mapM setupBranch brs+ (failures,_mtarget) <- watchJobs Nothing [] jobs+ unless (null failures) $+ error' $ "Build failures: " ++ unwords failures+ where+ setupBranch :: Branch -> IO Job+ setupBranch br = do+ job <- startBuild False br "." >>= async+ sleep 5+ return (show br,job)++ parallelBuild :: Branch -> [String] -> IO String+ parallelBuild br layer = do+ krbTicket+ when (nopkgs > 1) $ do+ putStrLn $ "\nBuilding parallel layer of " ++ show nopkgs ++ " packages:"+ putStrLn $ unwords layer+ jobs <- mapM setupBuild layer+ (failures,mtarget) <- watchJobs Nothing [] jobs+ unless (null failures) $+ error' $ "Build failures: " ++ unwords failures+ when (null jobs) $+ error' "No jobs run"+ return $ fromMaybe (error' "No target determined") mtarget+ where+ nopkgs = length layer++ setupBuild :: String -> IO Job+ setupBuild pkg = do+ job <- startBuild (nopkgs > 5) br pkg >>= async+ sleep 5+ return (pkg,job)++ watchJobs :: Maybe String -> [String] -> [Job] -> IO ([String],Maybe String)+ watchJobs mtarget fails [] = return (fails,mtarget)+ watchJobs mtarget fails (job:jobs) = do+ sleep 1+ status <- poll (snd job)+ case status of+ Nothing -> watchJobs mtarget fails (jobs ++ [job])+ Just (Right (target,nvr)) -> do+ putStrLn $ nvr ++ " job " ++ color Yellow "completed" ++ " (" ++ show (length jobs) ++ " jobs left)"+ watchJobs (Just target) fails jobs+ Just (Left except) -> do+ print except+ let pkg = fst job+ putStrLn $ "** " ++ pkg ++ " job " ++ color Magenta "failed" ++ " ** (" ++ show (length jobs) ++ " jobs left)"+ watchJobs mtarget (pkg : fails) jobs++ -- FIXME prefix output with package name+ startBuild :: Bool -> Branch -> String -> IO (IO (String,String))+ startBuild background br pkgdir =+ withExistingDirectory pkgdir $ do+ gitSwitchBranch (RelBranch br)+ pkg <- getPackageName pkgdir+ putPkgBrnchHdr pkg br+ unpushed <- gitShortLog $ "origin/" ++ show br ++ "..HEAD"+ unless (null unpushed) $+ mapM_ (putStrLn . simplifyCommitLog) unpushed+ let spec = packageSpec pkg+ checkForSpecFile spec+ unless (null unpushed) $ do+ checkSourcesMatch spec+ unless dryrun $+ gitPushSilent Nothing+ nvr <- pkgNameVerRel' br spec+ target <- case msidetagTarget of+ Nothing -> return $ branchTarget br+ Just (Target t) -> return t+ Just SideTag -> do+ tags <- map (head . words) <$> kojiUserSideTags br+ case tags of+ [] -> do+ out <- head . lines <$> fedpkg "request-side-tag" []+ if "Side tag '" `isPrefixOf` out then+ return $ init . dropWhileEnd (/= '\'') $ dropPrefix "Side tag '" out+ else error' "'fedpkg request-side-tag' failed"+ [tag] -> return tag+ _ -> error' $ "More than one user side-tag found for " ++ show br+ putStrLn $ nvr ++ " (" ++ target ++ ")\n"+ -- FIXME should compare git refs+ -- FIXME check for target+ buildstatus <- kojiBuildStatus nvr+ let tag = if target == branchTarget br then branchDestTag br else target+ mlatest <- kojiLatestNVR tag $ unPackage pkg+ case buildstatus of+ Just BuildComplete -> do+ putStrLn $ nvr ++ " is " ++ color Green "already built"+ when (br /= Rawhide && target == branchTarget br) $ do+ mtags <- kojiNVRTags nvr+ case mtags of+ Nothing -> error' $ nvr ++ " is untagged"+ Just tags ->+ unless (dryrun || any (`elem` tags) [show br, show br ++ "-updates", show br ++ "-override"]) $+ unlessM (checkAutoBodhiUpdate br) $+ bodhiCreateOverride nvr+ return $ do+ unless dryrun $+ kojiWaitRepo target nvr+ return (target,nvr)+ Just BuildBuilding -> do+ putStrLn $ nvr ++ " is already building"+ return $+ kojiGetBuildTaskID fedoraHub nvr >>=+ maybe (error' $ "Task for " ++ nvr ++ " not found")+ (kojiWaitTaskAndRepo (isNothing mlatest) nvr target)+ _ -> do+ buildref <- git "show-ref" ["--hash", "origin" </> show br]+ opentasks <- kojiOpenTasks pkg (Just buildref) target+ case opentasks of+ [task] -> do+ putStrLn $ nvr ++ " task is already open"+ return $ kojiWaitTaskAndRepo (isNothing mlatest) nvr target task+ (_:_) -> error' $ show (length opentasks) ++ " open " ++ unPackage pkg ++ " tasks already"+ [] -> do+ if equivNVR nvr (fromMaybe "" mlatest)+ then return $ error' $ color Red $ nvr ++ " is already latest (modulo disttag)"+ else do+ -- FIXME parse build output+ if dryrun+ then return (return (target,nvr))+ else do+ task <- kojiBuildBranchNoWait target pkg Nothing $ "--fail-fast" : ["--background" | background]+ return $ kojiWaitTaskAndRepo (isNothing mlatest) nvr target task+ where+ kojiWaitTaskAndRepo :: Bool -> String -> String -> TaskID -> IO (String,String)+ kojiWaitTaskAndRepo newpkg nvr target task = do+ finish <- kojiWatchTaskQuiet task+ if finish+ then putStrLn $ color Green $ nvr ++ " build success"+ else error' $ color Red $ nvr ++ " build failed"+ unless dryrun $ do+ autoupdate <- checkAutoBodhiUpdate br+ if autoupdate then+ when newpkg $ do+ mBugSess <- do+ (mbid, session) <- bzReviewSession+ return $ case mbid of+ Just bid -> Just (bid,session)+ Nothing -> Nothing+ whenJust mBugSess $+ \ (bid,session) -> putBugBuild session bid nvr+ else do+ when (target == branchTarget br) $+ -- -- FIXME: avoid prompt in+ -- changelog <- getChangeLog spec+ -- bodhiUpdate (fmap fst mBugSess) changelog nvr+ bodhiCreateOverride nvr+ kojiWaitRepo target nvr+ return (target,nvr)++ bodhiSidetagUpdate :: String -> String -> IO ()+ bodhiSidetagUpdate sidetag notes = do+ case mupdatetype of+ Nothing -> return ()+ Just updateType -> do+ putStrLn $ "Creating Bodhi Update for " ++ sidetag+ ok <- cmdBool "bodhi" ["updates", "new", "--type", show updateType , "--notes", "--request", "testing", if null notes then "to be written" else notes, "--autokarma", "--autotime", "--close-bugs", "--from-tag", sidetag]+ when ok $ do+ prompt_ "After editing update, press Enter to remove sidetag"+ fedpkg_ "remove-side-tag" [sidetag]
+ src/Cmd/PkgReview.hs view
@@ -0,0 +1,123 @@+{-# LANGUAGE OverloadedStrings #-}++module Cmd.PkgReview (+ createReview,+ updateReview+ ) where++import Common+import Common.System+import qualified Common.Text as T++import Data.Char+import Network.HTTP.Directory++import Branches+import Bugzilla+import Koji+import Krb+import Package+import Prompt++-- FIXME add --dependent pkgreview+-- FIXME reference existing/previous scratch build+createReview :: Bool -> Bool -> [FilePath] -> IO ()+createReview noscratch mock pkgs =+ withPackageByBranches (Just True) Nothing Nothing True AnyNumber createPkgReview ("master":pkgs)+ where+ createPkgReview :: Package -> AnyBranch -> IO ()+ createPkgReview package _br = do+ let spec = packageSpec package+ pkg = unPackage package+ unless (all isAscii pkg) $+ putStrLn "Warning: package name is not ASCII!"+ putStrLn "checking for existing reviews..."+ (bugs,session) <- bugsSession $ pkgReviews pkg+ unless (null bugs) $ do+ putStrLn "Existing review(s):"+ mapM_ putBug bugs+ -- FIXME abort if open review (unless --force?)+ prompt_ "Press Enter to continue"+ srpm <- generateSrpm Nothing spec+ mockRpmLint mock noscratch pkg spec srpm+ (mkojiurl,specSrpmUrls) <- buildAndUpload noscratch srpm pkg spec+ bugid <- postReviewReq session spec specSrpmUrls mkojiurl pkg+ putStrLn "Review request posted:"+ putBugId bugid+ where+ postReviewReq :: BugzillaSession -> FilePath -> String -> Maybe String -> String -> IO BugId+ postReviewReq session spec specSrpmUrls mkojiurl pkg = do+ summary <- cmd "rpmspec" ["-q", "--srpm", "--qf", "%{summary}", spec]+ description <- cmd "rpmspec" ["-q", "--srpm", "--qf", "%{description}", spec]+ createBug session+ [ ("product", "Fedora")+ , ("component", "Package Review")+ , ("version", "rawhide")+ , ("summary", "Review Request: " <> pkg <> " - " <> summary)+ , ("description", specSrpmUrls <> "\n\nDescription:\n" <> description <> maybe "" ("\n\n\nKoji scratch build: " <>) mkojiurl)]++buildAndUpload :: Bool -> String -> String -> FilePath+ -> IO (Maybe String, String)+buildAndUpload noscratch srpm pkg spec = do+ mkojiurl <- if noscratch then return Nothing+ else Just <$> kojiScratchBuild "rawhide" [] srpm+ specSrpmUrls <- uploadPkgFiles pkg spec srpm+ return (mkojiurl, specSrpmUrls)++updateReview :: Bool -> Bool -> Maybe FilePath -> IO ()+updateReview noscratch mock mspec = do+ spec <- maybe findSpecfile checkLocalFile mspec+ pkg <- cmd "rpmspec" ["-q", "--srpm", "--qf", "%{name}", spec]+ (bid,session) <- reviewBugIdSession pkg+ putBugId bid+ srpm <- generateSrpm Nothing spec+ submitted <- checkForComment session bid (T.pack srpm)+ when submitted $+ error' "This NVR was already posted on the review bug: please bump"+ mockRpmLint mock noscratch pkg spec srpm+ (mkojiurl,specSrpmUrls) <- buildAndUpload noscratch srpm pkg spec+ changelog <- getChangeLog spec+ commentBug session bid (specSrpmUrls <> (if null changelog then "" else "\n\n" <> changelog) <> maybe "" ("\n\nKoji scratch build: " <>) mkojiurl)+ -- putStrLn "Review bug updated"+ where+ checkLocalFile :: FilePath -> IO FilePath+ checkLocalFile f =+ if takeFileName f == f then return f+ else error' "Please run in the directory of the spec file"++uploadPkgFiles :: String -> FilePath -> FilePath -> IO String+uploadPkgFiles pkg spec srpm = do+ fasid <- fasIdFromKrb+ -- read ~/.config/fedora-create-review+ let sshhost = "fedorapeople.org"+ sshpath = "public_html/reviews/" ++ pkg+ cmd_ "ssh" [fasid ++ "@" ++ sshhost, "mkdir", "-p", sshpath]+ cmd_ "scp" [spec, srpm, sshhost ++ ":" ++ sshpath]+ getCheckedFileUrls $ "https://" <> fasid <> ".fedorapeople.org" </> removePrefix "public_html/" sshpath+ where+ getCheckedFileUrls :: String -> IO String+ getCheckedFileUrls uploadurl = do+ let specUrl = uploadurl </> takeFileName spec+ srpmUrl = uploadurl </> takeFileName srpm+ mgr <- httpManager+ checkUrlOk mgr specUrl+ checkUrlOk mgr srpmUrl+ return $ "Spec URL: " <> specUrl <> "\nSRPM URL: " <> srpmUrl+ where+ checkUrlOk mgr url = do+ okay <- httpExists mgr url+ unless okay $ error' $ "Could not access: " ++ url++mockRpmLint :: Bool -> Bool -> String -> FilePath -> FilePath -> IO ()+mockRpmLint mock noscratch pkg spec srpm = do+ rpms <-+ if mock then do+ -- FIXME check that mock is installed+ let resultsdir = "results_" ++ pkg+ cmd_ "mock" ["--root", mockConfig Rawhide, "--resultdir=" ++ resultsdir, srpm]+ map (resultsdir </>) . filter ((== ".rpm") . takeExtension) <$> listDirectory resultsdir+ else+ builtRpms (RelBranch Rawhide) spec >>= filterM doesFileExist+ -- FIXME parse # of errors/warnings+ void $ cmdBool "rpmlint" $ spec:srpm:rpms+ prompt_ $ "Press Enter to " ++ if noscratch then "upload" else "submit"
+ src/Cmd/Pull.hs view
@@ -0,0 +1,15 @@+module Cmd.Pull (pullPkgs) where++import Branches+import Git+import Package++-- FIXME pulling more than one branch+-- FIXME print nvr after pulling or old -> new+pullPkgs :: [String] -> IO ()+pullPkgs =+ withPackageByBranches (Just False) cleanGitFetch Nothing True AnyNumber pullPkg+ where+ pullPkg :: Package -> AnyBranch -> IO ()+ pullPkg _pkg _br =+ gitCurrentBranch >>= gitMergeOrigin
+ src/Cmd/RequestBranch.hs view
@@ -0,0 +1,89 @@+module Cmd.RequestBranch (+ requestBranches,+ requestPkgBranches+ ) where++import Common+import Common.System++import Branches+import Bugzilla+import Git+import Krb+import ListReviews+import Package+import Pagure+import Prompt++requestBranches :: Bool -> Maybe BranchOpts -> [String] -> IO ()+requestBranches mock mbrnchopts args = do+ (abrs,ps) <- splitBranchesPkgs True mbrnchopts True args+ let brs = map onlyRelBranch abrs+ if null ps then+ ifM isPkgGitRepo+ (getDirectoryName >>= requestPkgBranches mock mbrnchopts brs . Package) $+ do pkgs <- map reviewBugToPackage <$> listReviews ReviewUnbranched+ mapM_ (\ p -> withExistingDirectory p $ requestPkgBranches mock mbrnchopts brs (Package p)) pkgs+ else+ mapM_ (\ p -> withExistingDirectory p $ requestPkgBranches mock mbrnchopts brs (Package p)) ps++-- FIXME add --yes, or skip prompt when args given+requestPkgBranches :: Bool -> Maybe BranchOpts -> [Branch] -> Package -> IO ()+requestPkgBranches mock mbrnchopts brs pkg = do+ putPkgHdr pkg+ git_ "fetch" []+ active <- getFedoraBranched+ branches <- case mbrnchopts of+ Nothing -> if null brs+ then return $ take 2 active+ else return brs+ Just request -> do+ let requested = case request of+ AllBranches -> active+ AllFedora -> filter isFedoraBranch active+ AllEPEL -> filter isEPELBranch active+ ExcludeBranches xbrs -> active \\ xbrs+ inp <- prompt $ "Confirm branches [" ++ unwords (map show requested) ++ "]"+ return $ if null inp+ then requested+ else map (readActiveBranch' active) $ words inp+ newbranches <- filterExistingBranchRequests branches+ unless (null newbranches) $ do+ (bug,session) <- approvedReviewBugSession (unPackage pkg)+ let bid = bugId bug+ urls <- forM newbranches $ \ br -> do+ when mock $ fedpkg_ "mockbuild" ["--root", mockConfig br]+ fedpkg "request-branch" [show br]+ commentBug session bid $ unlines urls+ where+ filterExistingBranchRequests :: [Branch] -> IO [Branch]+ filterExistingBranchRequests branches = do+ existing <- fedoraBranchesNoMaster localBranches+ forM_ branches $ \ br ->+ when (br `elem` existing) $+ putStrLn $ show br ++ " branch already exists"+ let brs' = branches \\ existing+ if null brs' then return []+ else do+ current <- fedoraBranchesNoMaster $ pagurePkgBranches (unPackage pkg)+ forM_ brs' $ \ br ->+ when (br `elem` current) $+ putStrLn $ show br ++ " remote branch already exists"+ let newbranches = brs' \\ current+ if null newbranches then return []+ else do+ fasid <- fasIdFromKrb+ erecent <- pagureListProjectIssueTitlesStatus "pagure.io" "releng/fedora-scm-requests"+ [makeItem "author" fasid, makeItem "status" "all"]+ case erecent of+ Left err -> error' err+ Right recent -> filterM (notExistingRequest recent) newbranches++ -- FIXME handle close_status Invalid+ notExistingRequest :: [IssueTitleStatus] -> Branch -> IO Bool+ notExistingRequest requests br = do+ let pending = filter ((("New Branch \"" ++ show br ++ "\" for \"rpms/" ++ unPackage pkg ++ "\"") ==) . pagureIssueTitle) requests+ unless (null pending) $ do+ putStrLn $ "Branch request already open for " ++ unPackage pkg ++ ":" ++ show br+ mapM_ printScmIssue pending+ return $ null pending
+ src/Cmd/RequestRepo.hs view
@@ -0,0 +1,87 @@+{-# LANGUAGE OverloadedStrings #-}++module Cmd.RequestRepo (requestRepos) where++import Common+import qualified Common.Text as T++import Network.HTTP.Directory (httpExists, httpManager)+import Network.HTTP.Query ((+/+))+import SimpleCmd++import Bugzilla+import Krb+import ListReviews+import Package+import Pagure+import Prompt++-- FIXME separate pre-checked listReviews and direct pkg call, which needs checks+requestRepos :: Bool -> Bool -> [String] -> IO ()+requestRepos allstates retry ps = do+ when (retry && length ps /= 1) $+ error' "--retry only for a single package"+ pkgs <- if null ps+ then map reviewBugToPackage <$> listReviewsAll allstates ReviewWithoutRepoReq+ else return ps+ mapM_ (requestRepo retry) pkgs++-- FIXME also accept bugid instead+requestRepo :: Bool -> String -> IO ()+requestRepo retry pkg = do+ putStrLn pkg+ (bug,session) <- approvedReviewBugSession pkg+ putBug bug+ let bid = bugId bug+ if bugAssignedTo bug == "nobody@fedoraproject.org" then+ putStrLn "Review bug needs to be assigned to reviewer first"+ else do+ created <- checkRepoCreatedComment session bid+ if created+ then putStrLn "scm repo was already created"+ else do+ -- show comments?+ requests <- existingRepoRequests+ unless (null requests) $ do+ putStrLn "Request exists:"+ mapM_ printScmIssue requests+ when (retry && pagureIssueCloseStatus (head requests) == Just "Processed") $+ error' "The last repo request was already successfully Processed"+ when (null requests || retry) $ do+ checkNoPagureRepo+ url <- fedpkg "request-repo" [pkg, show bid]+ putStrLn $ url ++ "\n"+ let assignee = userRealName (bugAssignedToDetail bug)+ let draft = "Thank you for the review" ++ maybe "" ((", " ++) . T.unpack) (getFirstname assignee)+ putStrLn "```"+ putStrLn draft+ putStrLn "```"+ input <- prompt "Press Enter to post above comment, or input now"+ let comment = (if null input then draft else input) ++ "\n\n" <> url+ commentBug session bid comment+ putStrLn ""+ where+ existingRepoRequests :: IO [IssueTitleStatus]+ existingRepoRequests = do+ fasid <- fasIdFromKrb+ erecent <- pagureListProjectIssueTitlesStatus pagureio "releng/fedora-scm-requests" [makeItem "author" fasid, makeItem "status" "all"]+ case erecent of+ Left err -> error' err+ Right recent ->+ -- don't mention "New Repo" here, since Branch requests also imply repo already exists+ return $ filter (((" for \"rpms/" ++ pkg ++ "\"") `isSuffixOf`) . pagureIssueTitle) recent++ checkNoPagureRepo :: IO ()+ checkNoPagureRepo = do+ mgr <- httpManager+ exists <- httpExists mgr $ "https://" ++ srcfpo +/+ "rpms" +/+ pkg+ when exists $+ error' $ "Repo for " ++ pkg ++ " already exists"++ -- FIXME handle "email name"+ getFirstname :: T.Text -> Maybe T.Text+ getFirstname t =+ let first = head (T.words t) in+ if "@" `T.isInfixOf` first+ then Nothing+ else Just first
+ src/Cmd/Reviews.hs view
@@ -0,0 +1,21 @@+module Cmd.Reviews (+ reviewsCmd,+ findReview)+where++import Bugzilla+import Common+import ListReviews++-- FIXME add --state or --new, --modified, etc+-- FIXME display time of last update+reviewsCmd :: Bool -> Bool -> Bool -> Maybe String -> ReviewStatus -> IO ()+reviewsCmd short allstates assignee muser status = do+ listReviewsFull assignee muser allstates status >>=+ mapM_ (putReviewBug short) . sortBugsByStatus+ when short $ putStrLn ""++findReview :: String -> IO ()+findReview pkg = do+ (bugs, _) <- bugIdsSession $ pkgReviews pkg+ mapM_ putBugId bugs
+ src/Cmd/Scratch.hs view
@@ -0,0 +1,59 @@+{-# LANGUAGE OverloadedStrings #-}++module Cmd.Scratch (+ scratchCmd,+ Archs(..),+ ) where++import Branches+import Common+import Git+import Koji+import Package++data Archs = Archs [String] | ExcludedArchs [String]++-- FIXME default to rawhide/master?+-- FIXME build from a specific git ref+-- FIXME print message about uploading srpm+scratchCmd :: Bool -> Bool -> Bool -> Maybe Archs -> Maybe String -> [String]+ -> IO ()+scratchCmd dryrun rebuildSrpm nofailfast marchopts mtarget =+ withPackageByBranches (Just False) Nothing Nothing True AnyNumber scratchBuild+ where+ scratchBuild :: Package -> AnyBranch -> IO ()+ scratchBuild pkg br = do+ spec <- localBranchSpecFile pkg br+ let target = fromMaybe (anyTarget br) mtarget+ archs <- case marchopts of+ Nothing -> return []+ Just archopts -> case archopts of+ Archs as -> return as+ ExcludedArchs as -> do+ Just (buildtag,_desttag) <- kojiBuildTarget fedoraHub target+ tagArchs <- kojiTagArchs buildtag+ return $ tagArchs \\ as+ let kojiargs = ["--arch-override=" ++ intercalate "," archs | notNull archs] ++ ["--fail-fast" | not nofailfast] ++ ["--no-rebuild-srpm" | not rebuildSrpm]+ pkggit <- isPkgGitRepo+ if pkggit+ then do+ gitSwitchBranch br+ pushed <- do+ clean <- isGitDirClean+ if clean then+ null <$> gitShortLog ("origin/" ++ show br ++ "..HEAD")+ else return False+ putStrLn $ "koji scratch " ++ (if pushed then "" else "srpm ") ++ "build for " ++ target+ unless dryrun $ do+ if pushed then do+ void $ getSources spec+ kojiBuildBranch target pkg Nothing $ "--scratch" : kojiargs+ else srpmBuild target kojiargs spec+ else srpmBuild target kojiargs spec+ where+ srpmBuild :: FilePath -> [String] -> String -> IO ()+ srpmBuild target kojiargs spec =+ void $ generateSrpm (Just br) spec >>= kojiScratchBuild target kojiargs++ anyTarget (RelBranch b) = branchTarget b+ anyTarget _ = "rawhide"
+ src/Cmd/SideTags.hs view
@@ -0,0 +1,16 @@+module Cmd.SideTags (sideTagsCmd) where++import Branches+import Koji++sideTagsCmd :: [Branch] -> IO ()+sideTagsCmd brs = do+ branches <-+ if null brs+ then getFedoraBranches+ else return brs+ mapM_ sideTagsBranch branches+ where+ sideTagsBranch :: Branch -> IO ()+ sideTagsBranch br =+ kojiUserSideTags br >>= mapM_ putStrLn
+ src/Cmd/Status.hs view
@@ -0,0 +1,120 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE OverloadedStrings #-}++module Cmd.Status (statusCmd) where++import Common+import Common.System++import Data.Fixed+import Data.Time.Clock+import Data.Time.LocalTime+import Fedora.Bodhi++import Bugzilla+import Branches+import Git+import Koji+import ListReviews+import Package++-- FIXME instead --pull?+-- FIXME --pending+-- FIXME handle not cloned (remote only)+-- FIXME silence fetching of new branches? (for --reviews etc)+statusCmd :: Bool -> Bool -> Maybe BranchOpts -> [String] -> IO ()+statusCmd nofetch reviews mbrnchopts args = do+ reviewpkgs <- if reviews then+ map reviewBugToPackage <$> listReviewsAll True ReviewRepoCreated+ else return []+ -- FIXME dirty not okay for multiple branches?+ withPackageByBranches (Just False) (if nofetch then dirtyGit else dirtyGitFetch) mbrnchopts True AnyNumber statusBranch+ (args ++ reviewpkgs)++-- FIXME note dirty when local changes+statusBranch :: Package -> AnyBranch -> IO ()+statusBranch _ (OtherBranch _) =+ error' "status currently only defined for release branches"+statusBranch pkg rbr@(RelBranch br) = do+ gitSwitchBranch rbr+ let spec = packageSpec pkg+ ifM (notM (doesFileExist spec))+ (ifM initialPkgRepo+ (putStrLn $ show br ++ ": initial repo")+ (putStrLn $ "missing " ++ spec)) $+ do+ mnvr <- pkgNameVerRel br spec+ case mnvr of+ Nothing -> do+ putStrLn "undefined NVR!\n"+ putStr "HEAD "+ gitShortLog1 Nothing >>= putStrLn . simplifyCommitLog+ Just nvr -> do+ -- unless (br == Master) $ do+ -- newerBr <- newerBranch br <$> getFedoraBranches+ -- ancestor <- gitBool "merge-base" ["--is-ancestor", "HEAD", show newerBr]+ -- when ancestor $ do+ -- unmerged <- gitShortLog $ "HEAD.." ++ show newerBr+ -- unless (null unmerged) $ do+ -- putStrLn $ "Newer commits in " ++ show newerBr ++ ":"+ -- mapM_ (putStrLn . simplifyCommitLog) unmerged+ unpushed <- gitShortLog1 $ Just $ "origin/" ++ show br ++ "..HEAD"+ if null unpushed then do+ mbuild <- kojiGetBuildID fedoraHub nvr+ case mbuild of+ Nothing -> do+ mlatest <- kojiLatestNVR (branchDestTag br) (unPackage pkg)+ case mlatest of+ Nothing -> putStrLn $ "new " ++ nvr+ Just latest ->+ putStrLn $ if equivNVR nvr latest then latest ++ " is latest modulo disttag" else (if null latest then "new " else (head . words) latest ++ " ->\n") ++ nvr+ Just buildid -> do+ tags <- kojiBuildTags fedoraHub (buildIDInfo buildid)+ if null tags then do+ mstatus <- kojiBuildStatus nvr+ -- FIXME show pending archs building+ whenJust mstatus $ \ status ->+ -- FIXME better Show BuildStatus+ putStr $ nvr ++ " (" ++ show status ++ ")"+ else do+ -- FIXME hide testing if ga/stable+ putStr $ nvr ++ " (" ++ unwords tags ++ ")"+ unless (isStable tags) $ do+ updates <- bodhiUpdates+ [makeItem "display_user" "0",+ makeItem "builds" nvr]+ case updates of+ [] -> putStrLn "No update found"+ [update] -> do+ -- FIXME could show minus time left using stable_days?+ let msince = lookupKey "date_testing" update :: Maybe LocalTime+ case msince of+ Nothing -> return ()+ Just date -> do+ let since = localTimeToUTC utc date+ current <- getCurrentTime+ let diff = diffUTCTime current since+ putAge diff+ _ -> putStrLn "More than one update found!"+ putStrLn ""+ else putStrLn $ show br ++ ": " ++ simplifyCommitLog unpushed+ where+ isStable :: [String] -> Bool+ isStable = not . all ("-testing" `isSuffixOf`)++ putAge :: NominalDiffTime -> IO ()+ putAge diff = do+ -- FIXME time-1.10 has formatTime of NominalDiffTime+ let (days,nomRest) = diff `divMod'` nominalDay :: (Int,NominalDiffTime)+ nominalHour = 3600 :: NominalDiffTime+ hours = nomRest `div'` nominalHour :: Int+ putStr $ " " ++ showUnits days "day" +-+ showUnits hours "hour"++ showUnits :: Int -> String -> String+ showUnits i uni = show i ++ " " ++ uni +++ if i == 1 then "" else "s"++#if MIN_VERSION_time(1,8,0)+#else+ nominalDay = 3600 * 24 :: NominalDiffTime+#endif
+ src/Cmd/Switch.hs view
@@ -0,0 +1,12 @@+module Cmd.Switch (switchCmd) where++--import Branches+import Git+import Package++switchCmd :: [String] -> IO ()+switchCmd =+ -- FIXME use withBranchByPackages ?+ withPackageByBranches Nothing cleanGit Nothing True ExactlyOne dummy+ where+ dummy _ br = gitSwitchBranch br
+ src/Cmd/Update.hs view
@@ -0,0 +1,96 @@+module Cmd.Update+ ( updateCmd+ )+where++import SimpleCmd++import Branches+import Common+import Common.System+import Git+import Krb+import Package++-- FIXME branch arg?+updateCmd :: [String] -> IO ()+updateCmd args = do+ pkgGit <- isPkgGitRepo+ let (mver,pkgs) =+ if pkgGit+ then (listToMaybe args, if length args > 1 then error' "cannot specify packages in a dist-git repo" else [])+ else (Nothing, args)+ withPackageByBranches (Just False) dirtyGitFetch Nothing True ZeroOrOne (updatePkg mver) pkgs+ where+ updatePkg :: Maybe String -> Package -> AnyBranch -> IO ()+ updatePkg mver pkg br = do+ spec <- localBranchSpecFile pkg br+ (curver,_) <- pkgVerRel spec+ vdiff <- filter ("Version:" `isInfixOf`) . filter (not . ("@@ " `isPrefixOf`)) <$> gitLines "diff" ["-U0", "HEAD", spec]+ when (isNothing mver) $ do+ when (null vdiff) $+ error' "please specify version or edit in spec file"+ unless (length vdiff == 2) $+ error' $ "diff contains complex version change:\n" ++ unlines vdiff+ if Just curver == mver+ then putStrLn $ "already new version " ++ curver+ else do+ --FIXME: compare rpm versions+ -- if newver < oldver+ -- then putStrLn $ "current" +-+ display oldver +-+ "is newer!"+ -- else do+ pkgGit <- isPkgGitRepo+ let (oldver,newver) =+ case mver of+ Just nver -> (curver,nver)+ Nothing ->+ case map (last . words) vdiff of+ [old,new] -> (old,new)+ _ -> error' "complex version change"+ putStrLn $ oldver ++ " ->\n" ++ newver+ when (curver /= newver) $ do+ editSpecField "Version" newver spec+ editSpecField "Release" "0%{?dist}" spec+ cmd_ "rpmdev-bumpspec" ["-c", "update to " ++ newver, spec]+ when pkgGit $ do+ sources <- map sourceFieldFile <$> cmdLines "spectool" ["-S", spec]+ cmd_ "sed" ["-i", "/" ++ unPackage pkg ++ "-" ++ oldver ++ "./d", "sources"]+ allExist <- and <$> mapM doesFileExist sources+ unless allExist $ do+ cmd_ "fedpkg" ["sources"]+ cmd_ "spectool" ["-g", "-S", spec]+ krbTicket+ copyFile "sources" "sources.fbrnch"+ cmd_ "fedpkg" $ "new-sources" : filter (".tar." `isInfixOf`) sources+ shell_ $ "cat sources.fbrnch >>" +-+ "sources"+ removeFile "sources.fbrnch"+ prepPackage pkg br+ cmd_ "git" ["commit", "-a", "-m", "update to " ++ newver]++ sourceFieldFile :: String -> FilePath+ sourceFieldFile field =+ if null field then+ -- should be impossible+ error "empty source field!"+ else (takeFileName . last . words) field++pkgVerRel :: FilePath -> IO (String,String)+pkgVerRel spec = do+ --dist <- branchDist br+ -- workaround dist with bootstrap+ --hostdist <- cmd "rpm" ["--eval", "%{dist}"]+ mvr <- cmdMaybe "rpmspec" ["-q", "--srpm", "--qf", "%{version}-%{release}", spec]+ case mvr of+ Nothing -> error' $ "Failed to read package ver-rel: " ++ spec+ Just vr -> return $ splitBy "-" vr++splitBy :: String -> String -> (String,String)+splitBy sep xs =+ let ws = splitOn sep xs in+ case ws of+ [f,v] -> (f,v)+ _ -> error $ "inconsistent field: " ++ xs++editSpecField :: String -> String -> FilePath -> IO ()+editSpecField field new spec =+ cmd_ "sed" ["-i", "-e s/^\\(" ++ field ++ ":\\s\\+\\).*/\\1" ++ new ++ "/", spec]
+ src/Common.hs view
@@ -0,0 +1,18 @@+{-# LANGUAGE CPP #-}++module Common (+ module Control.Monad.Extra,+ module Data.List.Extra,+ module Data.Maybe,+#if !MIN_VERSION_base(4,11,0)+ (<>)+#endif+ ) where++import Control.Monad.Extra+import Data.List.Extra+import Data.Maybe++#if !MIN_VERSION_base(4,11,0)+import Data.Semigroup ((<>))+#endif
+ src/Common/System.hs view
@@ -0,0 +1,50 @@+{-# LANGUAGE CPP #-}++module Common.System (+ module SimpleCmd,+ module System.Directory,+ module System.FilePath,+ getDirectoryName,+ isTty,+ setNoBuffering,+#if !MIN_VERSION_simple_cmd(0,2,3)+ cmdFull+#endif+ ) where++import SimpleCmd+#if MIN_VERSION_simple_cmd(0,2,1)+ hiding (ifM,whenM)+#endif+#if !MIN_VERSION_simple_cmd(0,2,3)+import System.Exit+import System.Process+#endif+import System.Directory+import System.FilePath+import System.IO++isTty :: IO Bool+isTty = hIsTerminalDevice stdin++setNoBuffering :: IO ()+setNoBuffering =+ hSetBuffering stdout NoBuffering++getDirectoryName :: IO String+getDirectoryName =+ takeFileName <$> getCurrentDirectory++#if !MIN_VERSION_simple_cmd(0,2,3)+cmdFull :: String -> [String] -> String -> IO (Bool, String, String)+cmdFull c args input = do+ (ret, out, err) <- readProcessWithExitCode c args input+ return (ret == ExitSuccess, removeTrailingNewline out, removeTrailingNewline err)+ where+ removeTrailingNewline :: String -> String+ removeTrailingNewline "" = ""+ removeTrailingNewline str =+ if last str == '\n'+ then init str+ else str+#endif
+ src/Common/Text.hs view
@@ -0,0 +1,7 @@+module Common.Text (+ module Data.Text,+ module Data.Text.IO+ ) where++import Data.Text+import Data.Text.IO
+ src/Git.hs view
@@ -0,0 +1,172 @@+{-# LANGUAGE CPP #-}++module Git (+#if !MIN_VERSION_simple_cmd(0,2,2)+ gitBool,+#endif+ gitLines,+ gitMergeable,+ gitMergeOrigin,+ gitFetchSilent,+ gitPushSilent,+ gitShortLog,+ gitShortLogN,+ gitShortLog1,+ gitSwitchBranch,+ simplifyCommitLog,+-- checkIsPkgGitDir,+ isGitRepo,+ isPkgGitRepo,+ checkWorkingDirClean,+ isGitDirClean,+ CommitOpt (..),+ module SimpleCmd.Git+ ) where++import Common+import Common.System++import SimpleCmd.Git++import Branches++#if !MIN_VERSION_simple_cmd(0,2,2)+-- | 'gitBool c args' runs git command and return result+gitBool :: String -- ^ git command+ -> [String] -- ^ arguments+ -> IO Bool -- ^ result+gitBool c args =+ cmdBool "git" (c:args)+#endif++gitMergeable :: String -> IO [String]+gitMergeable ref = do+ ancestor <- gitBool "merge-base" ["--is-ancestor", "HEAD", ref]+ if ancestor then gitShortLog $ "HEAD.." ++ ref+ else return []++gitMergeOrigin :: AnyBranch -> IO ()+gitMergeOrigin br = do+ commits <- gitMergeable $ "origin" </> show br+ unless (null commits) $ do+ rebase <- git "rebase" []+ unless ("Already up to date." `isPrefixOf` rebase) $+ putStr rebase++gitShortLog :: String -> IO [String]+gitShortLog range =+ gitLines "log" ["--pretty=reference", range]++gitShortLogN :: Int -> Maybe String -> IO [String]+gitShortLogN num mrange =+ gitLines "log" (["--max-count=" ++ show num, "--pretty=reference"] ++ maybeToList mrange)++gitShortLog1 :: Maybe String -> IO String+gitShortLog1 mrange =+ git "log" (["--max-count=1", "--pretty=reference"] ++ maybeToList mrange)++-- FIXME currently no-op with --format=reference+simplifyCommitLog :: String -> String+simplifyCommitLog = unwords . shortenHash . words+ where+ shortenHash :: [String] -> [String]+ shortenHash [] = []+ shortenHash (h:cs) = take 8 h : simplifyLog cs++ simplifyLog [] = []+ -- remove leading '('+ simplifyLog (w:ws) =+ case ws of+ [] -> error "malformed changelog"+ [_] -> init (tail w) : map ('(' :) ws+ _ ->+ let (mid,end) = splitAt (length ws - 2) ws+ in tail w : mid ++ [init (head end),'(' : last end]++gitPushSilent :: Maybe String -> IO ()+gitPushSilent mref = do+ putStr "git pushing... "+ out <- cmdQuiet "git" $ ["push", "--quiet", "origin"] ++ maybeToList mref+ putStrLn $ if null out then "done\n" else "\n" ++ out++-- FIXME flag for really silent?+gitFetchSilent :: IO ()+gitFetchSilent = do+ name <- getDirectoryName+ putStr $ "git fetching " ++ name ++ "... "+ (ok, out, err) <- cmdFull "git" ["fetch"] ""+ unless (null out) $ putStrLn out+ unless ok $ error' err+ let filtered = case lines err of+ [] -> []+ (hd:tl) -> filter (/= "Already up to date.") $+ if "From " `isPrefixOf` hd then tl else hd:tl+ putStrLn $ if null filtered then "done" else "\n" ++ intercalate "\n" filtered++checkWorkingDirClean :: IO ()+checkWorkingDirClean = do+ clean <- isGitDirClean+ unless clean $ do+ dir <- getCurrentDirectory+ error' $ "Working dir is not clean: " ++ dir++isGitDirClean :: IO Bool+isGitDirClean =+ gitBool "diff" ["--quiet", "--exit-code", "HEAD"]++-- checkIsPkgGitDir :: IO ()+-- checkIsPkgGitDir = do+-- pkgGit <- isPkgGitRepo+-- unless pkgGit $ error' "Not a pkg git dir"++isGitRepo :: IO Bool+isGitRepo = isGitDir "." ||^ doesFileExist ".git"++isPkgGitRepo :: IO Bool+isPkgGitRepo = grepGitConfig' "@\\(pkgs\\|src\\)\\."+ where+ -- adapted from SimpleCmd.Git+ grepGitConfig' :: String -> IO Bool+ grepGitConfig' key =+ ifM (isGitDir ".")+ (egrep_ key ".git/config") $+ -- could be a worktree or absorbed submodule (#8)+ ifM (not <$> doesFileExist ".git")+ (return False) $ do+ gitdir <- last . words <$> readFile ".git"+ if "/worktrees/" `isInfixOf` gitdir+ then egrep_ key (takeDirectory (takeDirectory gitdir) </> "config")+ else+ -- absorbed submodule: "gitdir: ../.git/modules/R-bit"+ if "/modules/" `isInfixOf` gitdir then+ egrep_ key $ gitdir </> "config"+ else return False++gitLines :: String -> [String] -> IO [String]+gitLines c args = lines <$> git c args++gitSwitchBranch :: AnyBranch -> IO ()+gitSwitchBranch br = do+ localbranches <- gitLines "branch" ["--format=%(refname:short)"]+ if show br `elem` localbranches then do+ current <- git "rev-parse" ["--abbrev-ref", "HEAD"]+ when (current /= show br) $+ -- cmdSilent+ git_ "checkout" ["-q", show br]+ else do+ -- check remote branch exists+ remotebranch <-+ ifM checkIfRemoteBranchExists+ (return True) $+ gitFetchSilent >> checkIfRemoteBranchExists+ if not remotebranch+ then do+ name <- getDirectoryName+ error' $ name ++ " " ++ show br ++ " branch does not exist!"+ else+ git_ "checkout" ["-q", "-b", show br, "--track", "origin" </> show br]+ where+ checkIfRemoteBranchExists =+ gitBool "show-ref" ["--verify", "--quiet", "refs/remotes/origin/" ++ show br]++data CommitOpt = CommitMsg String | CommitAmend
+ src/InterleaveOutput.hs view
@@ -0,0 +1,11 @@+{-# LANGUAGE CPP #-}++module InterleaveOutput (cmdSilent_) where++import System.Process.Typed (proc, readProcessInterleaved_)++import Common++cmdSilent_ :: String -> [String] -> IO ()+cmdSilent_ c args =+ void $ readProcessInterleaved_ $ proc c args
+ src/Koji.hs view
@@ -0,0 +1,211 @@+module Koji (+ kojiNVRTags,+ kojiBuildStatus,+ kojiBuildTags,+ kojiGetBuildID,+ kojiGetBuildTaskID,+ kojiLatestNVR,+ kojiOpenTasks,+ kojiScratchBuild,+ kojiUserSideTags,+ buildIDInfo,+ BuildState(..),+ kojiBuildBranch,+ kojiBuildBranchNoWait,+ kojiSource,+ kojiBuildTarget,+ kojiTagArchs,+ kojiWaitRepo,+ kojiWatchTask,+ kojiWatchTaskQuiet,+ TaskID,+ displayID,+ fedoraHub+ ) where++import Data.Char (isDigit)++import Control.Concurrent (threadDelay)+import Fedora.Koji+import qualified Fedora.Koji.Internal as Koji++import Branches+import Common+import Common.System+import Git+import Krb+import Package+import Pagure++fedoraHub :: String+fedoraHub = fedoraKojiHub++kojiNVRTags :: String -> IO (Maybe [String])+kojiNVRTags nvr = do+ mbldid <- kojiGetBuildID fedoraHub nvr+ case mbldid of+ Nothing -> return Nothing+ Just bldid -> Just <$> kojiBuildTags fedoraHub (buildIDInfo bldid)++kojiBuildStatus :: String -> IO (Maybe BuildState)+kojiBuildStatus nvr =+ kojiGetBuildState fedoraHub (BuildInfoNVR nvr)++kojiLatestNVR :: String -> String -> IO (Maybe String)+kojiLatestNVR tag pkg = do+ mbld <- kojiLatestBuild fedoraHub tag pkg+ return $ case mbld of+ Nothing -> Nothing+ Just bld -> lookupStruct "nvr" bld++kojiLatestNVRRepo :: String -> Int -> String -> IO (Maybe String)+kojiLatestNVRRepo tag event pkg = do+ mbld <- kojiLatestBuildRepo fedoraHub tag event pkg+ return $ case mbld of+ Nothing -> Nothing+ Just bld -> lookupStruct "nvr" bld++kojiOpenTasks :: Package -> Maybe String -> String -> IO [TaskID]+kojiOpenTasks pkg mref target = do+ user <- fasIdFromKrb+ muserid <- kojiGetUserID fedoraHub 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 fedoraHub userid (Just source) (Just target)++-- * Koji building++kojiScratchBuild :: String -> [String] -> FilePath -> IO String+kojiScratchBuild target args srpm = do+ Right url <- kojiBuild' True target $ args ++ ["--scratch", "--no-rebuild-srpm", srpm]+ return url++type KojiBuildTask = Either TaskID String++-- FIXME can fail like:+-- [ERROR] koji: AuthError: unable to obtain a session+-- readCreateProcess: koji "build" "--nowait" "f33-build-side-25385" "--fail-fast" "--background" ... (exit 1): failed+kojiBuild' :: Bool -> String -> [String] -> IO KojiBuildTask+kojiBuild' wait target args = do+ krbTicket+ cmd_ "date" []+ let srpm = if null args+ then error' "no args passed to koji build"+ else ".src.rpm" `isSuffixOf` last args+ -- FIXME use tee functionality+ when srpm $ putStrLn "koji srpm build uploading..."+ -- FIXME setTermTitle nvr+ out <- cmd "koji" $ ["build", "--nowait", target] ++ args+ putStrLn $ if srpm+ -- drop uploading line until doing tee+ then (unlines . tail . lines) out+ else out+ let kojiurl = last $ words out+ task = (TaskId . read) $ takeWhileEnd isDigit kojiurl+ when wait $ do+ kojiWatchTask task+ cmd_ "date" []+ return $ if wait then Right kojiurl else Left task++-- kojiBuild :: String -> [String] -> IO String+-- kojiBuild target args = do+-- Right url <- kojiBuild' True target args+-- return url++-- FIXME filter/simplify output+kojiWatchTask :: TaskID -> IO ()+kojiWatchTask task = do+ -- FIXME can error:+ -- eg1 [ERROR] koji: HTTPError: 503 Server Error: Service Unavailable for url: https://koji.fedoraproject.org/kojihub+ -- eg2 [ERROR] koji: ServerOffline: database outage: - user error (Error 1014: database outage)+ -- eg3 [ERROR] koji: ReadTimeout: HTTPSConnectionPool(host='koji.fedoraproject.org', port=443): Read timed out. (read timeout=43200)+ -- This might error with exit 0 occasionally so we check the taskstate always+ void $ cmdBool "koji" ["watch-task", displayID task]+ mst <- kojiGetTaskState fedoraHub task+ case mst of+ Just TaskClosed -> return ()+ Just TaskFailed -> error "Task failed!"+ Just TaskCanceled -> return ()+ _ -> kojiWatchTask task++kojiWatchTaskQuiet :: TaskID -> IO Bool+kojiWatchTaskQuiet task =+ ifM (cmdBool "koji" ["watch-task", "--quiet", displayID task])+ (return True) $+ do+ -- FIXME can error:+ -- eg1 [ERROR] koji: HTTPError: 503 Server Error: Service Unavailable for url: https://koji.fedoraproject.org/kojihub+ -- eg2 [ERROR] koji: ServerOffline: database outage: - user error (Error 1014: database outage)+ mst <- kojiGetTaskState fedoraHub task+ case mst of+ Just TaskClosed -> return True+ Just TaskFailed -> return False+ _ -> kojiWatchTaskQuiet task++kojiSource :: Package -> String -> String+kojiSource pkg ref =+ "git+https://" ++ srcfpo ++ "/rpms" </> unPackage pkg ++ ".git#" ++ ref++kojiBuildBranch' :: Bool -> String -> Package -> Maybe String -> [String]+ -> IO KojiBuildTask+kojiBuildBranch' wait target pkg mref args = do+ commit <- maybe (git "rev-parse" ["HEAD"]) return mref+ kojiBuild' wait target $ args ++ [kojiSource pkg commit]++kojiBuildBranch :: String -> Package -> Maybe String -> [String] -> IO ()+kojiBuildBranch target pkg mref args =+ checkResult <$> kojiBuildBranch' True target pkg mref args+ where+ checkResult = either (\ task -> error' (displayID task ++ " not completed")) (const ())++kojiBuildBranchNoWait ::String -> Package -> Maybe String -> [String] -> IO TaskID+kojiBuildBranchNoWait target pkg mref args = do+ Left task <- kojiBuildBranch' False target pkg mref args+ return task++kojiWaitRepo :: String -> String -> IO ()+kojiWaitRepo target nvr = do+ Just (buildtag,_desttag) <- kojiBuildTarget fedoraHub target+ waitRepo buildtag Nothing+ where+ waitRepo :: String -> Maybe Struct -> IO ()+ waitRepo buildtag moldrepo = do+ when (isJust moldrepo) $ do+ threadDelay (50 * 1000 * 1000) -- 50s+ putChar '.'+ mrepo <- kojiGetRepo fedoraHub buildtag Nothing Nothing+ case mrepo of+ Nothing -> error' $ "failed to find koji repo for " ++ buildtag+ Just repo ->+ if moldrepo == mrepo+ then waitRepo buildtag mrepo+ else do+ let mevent = lookupStruct "create_event" repo+ case mevent of+ Nothing -> error "create_event not found"+ Just event -> do+ latest <- kojiLatestNVRRepo buildtag event (nameOfNVR nvr)+ if latest == Just nvr+ then if isNothing moldrepo+ then putStrLn $ nvr ++ " is in " ++ buildtag+ else putStrLn "done"+ else do+ when (isNothing moldrepo) $ do+ cmd_ "date" []+ putStrLn $ "Waiting for " ++ buildtag ++ " to have " ++ nvr+ waitRepo buildtag mrepo++kojiTagArchs :: String -> IO [String]+kojiTagArchs tag = do+ st <- Koji.getTag fedoraHub (Koji.InfoString tag) Nothing+ return $ maybe [] words $ lookupStruct "arches" st++kojiUserSideTags :: Branch -> IO [String]+kojiUserSideTags br = do+ mtags <- kojiBuildTarget fedoraHub (branchTarget br)+ case mtags of+ Nothing -> return []+ Just (buildtag,_desttag) -> do+ user <- fasIdFromKrb+ kojiListSideTags fedoraKojiHub (Just buildtag) (Just user)
+ src/Krb.hs view
@@ -0,0 +1,26 @@+module Krb (+ fasIdFromKrb,+ krbTicket+ ) where++import Common++import SimpleCmd++krbTicket :: IO ()+krbTicket = do+ krb <- words . fromMaybe "" . find ("@FEDORAPROJECT.ORG" `isInfixOf`) . lines <$> cmd "klist" ["-l"]+ if null krb+ then error' "No krb5 ticket found for FEDORAPROJECT.ORG"+ else+ when (last krb == "(Expired)") $ do+ putStrLn $ unwords krb+ cmd_ "kinit" [head krb]+ putStrLn ""++fasIdFromKrb :: IO String+fasIdFromKrb = do+ mfasid <- (removeSuffix "@FEDORAPROJECT.ORG" <$>) . find ("@FEDORAPROJECT.ORG" `isSuffixOf`) . words <$> cmd "klist" ["-l"]+ case mfasid of+ Nothing -> error' "Could not determine fasid from klist"+ Just fasid -> return fasid
+ src/ListReviews.hs view
@@ -0,0 +1,90 @@+{-# LANGUAGE OverloadedStrings #-}++module ListReviews (+ ReviewStatus(..),+ listReviews,+ listReviewsAll,+ listReviewsFull+ ) where++import Common+import Common.System+import qualified Common.Text as T+import Network.HTTP.Query++import Branches+import Bugzilla++data ReviewStatus = ReviewAllOpen+ | ReviewUnApproved+ | ReviewApproved+ | ReviewWithoutRepoReq+ | ReviewRepoRequested+ | ReviewRepoCreated+ | ReviewUnbranched+ | ReviewBranched++listReviews :: ReviewStatus -> IO [Bug]+listReviews = listReviewsAll False++listReviewsAll :: Bool -> ReviewStatus -> IO [Bug]+listReviewsAll = listReviewsFull False Nothing++listReviewsFull :: Bool -> Maybe String -> Bool -> ReviewStatus-> IO [Bug]+listReviewsFull assignee muser allopen status = do+ (session,user) <- bzLoginSession+ accountid <- do+ case muser of+ Nothing -> return user+ Just userid ->+ if emailIsValid userid then return $ T.pack userid+ else do+ users <- listBzUsers session userid+ case users of+ [] -> error' $ "No user found for " ++ userid+ [obj] -> return $ T.pack $ lookupKey' "email" obj+ objs -> error' $ "Found multiple user matches: " +++ unwords (map (lookupKey' "email") objs)+ let reviews = (if assignee then assigneeIs else reporterIs) accountid .&&. packageReview+ open = if allopen+ then statusOpen else+ case status of+ ReviewAllOpen -> statusOpen+ ReviewUnApproved -> statusOpen+ ReviewApproved -> statusNewPost+ ReviewRepoCreated -> statusNewPost+ ReviewUnbranched -> statusNewModified+ ReviewBranched -> statusNewModified+ _ -> statusNewPost+ query = case status of+ ReviewAllOpen -> reviews+ ReviewUnApproved -> reviews .&&. not' reviewApproved+ _ -> reviews .&&. reviewApproved+ -- FIXME sort by status, bid (default?) / pkg?+ bugs <- searchBugs session (query .&&. open)+ case status of+ ReviewWithoutRepoReq ->+ filterM (fmap not . checkRepoRequestedComment session . bugId) bugs+ ReviewRepoRequested ->+ filterM (checkRepoRequestedComment session . bugId) bugs >>=+ filterM (fmap not . checkRepoCreatedComment session . bugId)+ ReviewRepoCreated ->+ filterM (checkRepoCreatedComment session . bugId) bugs+ ReviewUnbranched ->+ filterM (checkRepoCreatedComment session . bugId) bugs >>=+ filterM (notBranched . reviewBugToPackage)+ ReviewBranched ->+ filterM (checkRepoCreatedComment session . bugId) bugs >>=+ filterM (branched . reviewBugToPackage)+ _ -> return bugs+ where+ checkRepoRequestedComment :: BugzillaSession -> BugId -> IO Bool+ checkRepoRequestedComment session bid =+ checkForComment session bid+ "https://pagure.io/releng/fedora-scm-requests/issue/"++ branched :: String -> IO Bool+ branched pkg = not <$> notBranched pkg++ notBranched :: String -> IO Bool+ notBranched pkg = null <$> fedoraBranchesNoMaster (pagurePkgBranches pkg)
+ src/Main.hs view
@@ -0,0 +1,265 @@+module Main (main) where++import Distribution.Fedora.Branch+import Options.Applicative (eitherReader, ReadM)+import SimpleCmdArgs++-- commands+import Cmd.Bugs+import Cmd.Build+import Cmd.Bump+import Cmd.Clone+import Cmd.Commit+import Cmd.Copr+import Cmd.Diff+import Cmd.Import+import Cmd.ListBranches+import Cmd.ListPackages+import Cmd.Local+import Cmd.Log+import Cmd.Merge+import Cmd.Mock+import Cmd.Override+import Cmd.Parallel+import Cmd.PkgReview+import Cmd.Pull+import Cmd.RequestBranch+import Cmd.RequestRepo+import Cmd.Reviews+import Cmd.Scratch+import Cmd.SideTags+import Cmd.Status+import Cmd.Switch+import Cmd.Update++import Branches+import Common.System+import Git (CommitOpt(..))+import ListReviews+import Package (ForceShort(..), BCond(..))+import Paths_fbrnch (version)++main :: IO ()+main = do+ setNoBuffering+ simpleCmdArgs (Just version) "Fedora package branch building tool"+ "This tool helps with updating and building package branches" $+ subcommands+ [ Subcommand "clone" "clone packages" $+ cloneCmd <$> optional branchOpt <*> cloneRequest+ , Subcommand "switch" "Switch branch" $+ switchCmd <$> branchesPackages+ , Subcommand "nvr" "Print name-version-release" $+ nvrCmd <$> branchesOpt <*> branchesPackages+ , Subcommand "status" "Status package/branch status" $+ statusCmd <$> switchWith 'n' "no-fetch" "Do not git fetch to save time" <*> switchWith 'r' "reviews" "Status of reviewed packages" <*> branchesOpt <*> branchesPackages+ , Subcommand "merge" "Merge from newer branch" $+ mergeCmd <$> branchesPackages+ , Subcommand "build" "Build package(s) in Koji" $+ buildCmd <$> buildOpts <*> branchesOpt <*> branchesPackages+ , Subcommand "list" "List packages in pagure" $+ listCmd <$> switchWith 'c' "count" "Print number of packages" <*> optional packagerOpt <*> many (pkgArg "PKGPAT...")+ , Subcommand "branches" "List package branches" $+ branchesCmd <$> switchWith 'd' "skip-dead" "Skip if dead.package exists" <*> switchWith 'a' "all" "List all branches" <*> switchWith 'm' "missing" "Show missing branches" <*> switchWith 'r' "remote" "List remote branches" <*> many (pkgArg "PACKAGE...")+ , Subcommand "parallel" "Parallel build packages in Koji" $+ parallelBuildCmd <$> dryrunOpt <*> optional sidetagTargetOpt <*> updatetypeOpt <*> branchesOpt <*> branchesPackages+ , Subcommand "sidetags" "List user's side-tags" $+ sideTagsCmd <$> many branchArg+ , Subcommand "override" "Tag builds into buildroot override in Koji" $+ overrideCmd <$> branchesPackages+ , Subcommand "scratch" "Scratch build package in Koji" $+ scratchCmd <$> dryrunOpt <*> rebuildSrpmOpt <*> noFailFastOpt <*> optional archesOpt <*> mtargetOpt <*> branchesPackages+ , Subcommand "update" "Update package to newer version" $+ updateCmd <$> many (pkgArg "[VERSION] [PKG...]")+ , Subcommand "sort" "Sort packages in build dependency order" $+ sortCmd <$> optional rpmWithOpt <*> branchesPackages+ , Subcommand "prep" "Prep sources" $+ prepCmd <$> branchesPackages+ , Subcommand "local" "Build locally" $+ localCmd <$> optional forceshortOpt <*> many bcondOpt <*> branchesPackages+ , Subcommand "srpm" "Build srpm" $+ srpmCmd <$> branchesPackages+ , Subcommand "diff" "Diff local changes" $+ diffCmd <$> diffSpecOnly <*> diffWorkOpt <*> diffFormatOpt <*> diffBranchOpt <*> branchesPackages+ , Subcommand "log" "Show commits between branches" $+ logCmd <$> switchWith 'l' "long" "show full commit log" <*> anyBranchArg <*> anyBranchArg <*> many (pkgArg "PACKAGE...")+ , Subcommand "mock" "Local mock build" $+ mockCmd <$> switchWith 'd' "dry-run" "Do not build (but creates srpm)" <*> switchWith 'n' "no-clean" "Do not clean chroot before building a package" <*> switchWith 'w' "network" "Use network during build" <*> switchWith 'N' "no-clean-after" "Don't clean chroot after building a package" <*> optional (optionWith branchM 'r' "root" "BRANCH" "Mock config to use") <*> branchesPackages+ , Subcommand "install-deps" "Install package build dependencies" $+ installDepsCmd <$> branchesPackages+ , Subcommand "install" "Build locally and install package(s)" $+ -- FIXME drop --shortcircuit from install?+ installCmd <$> optional forceshortOpt <*> many bcondOpt <*> switchWith 'r' "reinstall" "reinstall rpms" <*> branchesPackages+ , Subcommand "bugs" "List package bugs" $+ bugsCmd <$> optional (strOptionWith 's' "summary" "KEY" "Search for bugs containing keyword") <*> many (pkgArg "PACKAGE...")+ , Subcommand "bump" "Bump release for package" $+ bumpPkgs <$> optional commitOpts <*> branchesOpt <*> branchesPackages+ , Subcommand "commit" "Git commit packages" $+ commitPkgs <$> optional commitOpts <*> many (pkgArg "PACKAGE...")+ , Subcommand "pull" "Git pull packages" $+ pullPkgs <$> branchesPackages+ , Subcommand "create-review" "Create a Package Review request" $+ createReview <$> noScratchBuild <*> mockOpt <*> many (pkgArg "PACKAGE...")+ , Subcommand "update-review" "Update a Package Review" $+ updateReview <$> noScratchBuild <*> mockOpt <*> optional (strArg "SPECFILE")+ , Subcommand "reviews" "List package reviews" $+ reviewsCmd <$> reviewShortOpt <*> reviewAllStatusOpt <*> switchWith 'T' "assigned-to" "List reviews assigned to user" <*> optional (strOptionWith 'U' "user" "USER" "Bugzilla user email") <*> reviewStatusOpt+ , Subcommand "request-repos" "Request dist git repo for new approved packages" $+ requestRepos <$> reviewAllStatusOpt <*> switchWith 'r' "retry" "Re-request repo" <*> many (pkgArg "NEWPACKAGE...")+ , Subcommand "import" "Import new approved created packages from bugzilla review" $+ importCmd <$> many (pkgArg "NEWPACKAGE...")+ , Subcommand "request-branches" "Request branches for approved created packages" $+ requestBranches <$> mockOpt <*> optional branchesRequestOpt <*> branchesPackages+ , Subcommand "find-review" "Find package review bug" $+ findReview <$> pkgArg "PACKAGE"+-- , Subcommand "test-bz-token" "Check bugzilla login status" $+-- pure testBZlogin+ , Subcommand "command" "Run shell command in package dirs ($p)" $+ commandCmd <$> commandOpt <*> branchesOpt <*> branchesPackages+ , Subcommand "copr" "Build package(s) in Fedora Copr" $+ coprCmd <$> dryrunOpt <*> buildByOpt <*> many archOpt <*> pkgArg "PROJECT" <*> branchesOpt <*> branchesPackages+ , Subcommand "master-rename" "Rename local master branch to rawhide" $+ masterRenameCmd <$> many (pkgArg "[PACKAGE]...")+ ]+ where+ cloneRequest :: Parser CloneRequest+ cloneRequest = flagWith' (CloneUser Nothing) 'M' "mine" "Your packages" <|> CloneUser . Just <$> strOptionWith 'u' "user" "USER" "Packages of FAS user" <|> ClonePkgs <$> some (pkgArg "PACKAGE...")++ noScratchBuild = switchWith 'S' "no-scratch-build" "Skip Koji scratch build"++ reviewShortOpt :: Parser Bool+ reviewShortOpt = switchWith 's' "short" "Only output the package name"++ reviewAllStatusOpt :: Parser Bool+ reviewAllStatusOpt = switchWith 'A' "all-status" "all open reviews"++ reviewStatusOpt :: Parser ReviewStatus+ reviewStatusOpt =+ flagWith' ReviewUnApproved 'u' "unapproved" "Package reviews not yet approved" <|>+ flagWith' ReviewApproved 'a' "approved" "All open approved package reviews" <|>+ flagWith' ReviewWithoutRepoReq 'w' "without-request" "Approved package reviews without a repo request" <|>+ flagWith' ReviewRepoRequested 'r' "requested" "Approved package reviews with a pending repo request" <|>+ flagWith' ReviewRepoCreated 'c' "created" "Approved package reviews with a created repo" <|>+ flagWith' ReviewUnbranched 'B' "unbranched" "Approved created package reviews not yet branched" <|>+ flagWith ReviewAllOpen ReviewBranched 'b' "branched" "Approved created package reviews already branched"++ branchOpt :: Parser Branch+ branchOpt = optionWith branchM 'b' "branch" "BRANCH" "branch"++ branchArg :: Parser Branch+ branchArg = argumentWith branchM "BRANCH"++ anyBranchArg :: Parser AnyBranch+ anyBranchArg = argumentWith anyBranchM "BRANCH"++ branchM :: ReadM Branch+ branchM = eitherReader eitherBranch'++ anyBranchM :: ReadM AnyBranch+ anyBranchM = anyBranch <$> str++ pkgArg :: String -> Parser String+ pkgArg lbl = removeSuffix "/" <$> strArg lbl++ branchesOpt :: Parser (Maybe BranchOpts)+ branchesOpt =+ optional (flagWith' AllBranches 'B' "all-branches" "All active release branches" <|>+ flagWith' AllFedora 'F' "all-fedora" "All active Fedora branches" <|>+ flagWith' AllEPEL 'E' "all-epel" "All active EPEL branches" <|>+ ExcludeBranches <$> some excludeBranchOpt)++ excludeBranchOpt :: Parser Branch+ excludeBranchOpt = optionWith branchM 'x' "exclude-branch" "BRANCH" "branch"++ branchesPackages :: Parser [String]+ branchesPackages = many (pkgArg "[BRANCH]... [PACKAGE]...")++ branchesRequestOpt :: Parser BranchOpts+ branchesRequestOpt =+ flagWith' AllBranches 'B' "all-branches" "Request branches for all current releases [default latest 2]" <|>+ ExcludeBranches <$> some excludeBranchOpt++ rpmWithOpt :: Parser RpmWith+ rpmWithOpt =+ RpmWith <$> strOptionWith 'w' "with" "BCOND" "rpmspec --with option" <|>+ RpmWithout <$> strOptionWith 'W' "without" "BCOND" "rpmspec --without option"++ mockOpt = switchWith 'm' "mock" "Do mock build to test"++ archOpt :: Parser String+ archOpt = strOptionWith 'a' "arch" "ARCH[,ARCH].." "build for arch(s)"++ rebuildSrpmOpt = switchWith 's' "rebuild-srpm" "rebuild srpm in Koji"++ buildOpts = BuildOpts <$> nopromptOpt <*> noFailFastOpt <*> mtargetOpt <*> overrideOpt <*> dryrunOpt <*> updatetypeOpt++-- yesOpt = switchWith 'y' "yes" "Assume yes for questions"++ nopromptOpt = switchWith 'm' "no-prompt" "Merge without prompt"++ noFailFastOpt = switchWith 'f' "no-fast-fail" "Do not --fast-fail"++ excludeArch :: Parser String+ excludeArch = strOptionWith 'X' "exclude-arch" "ARCH[,ARCH].." "build without arch(s)"++ archesOpt :: Parser Archs+ archesOpt = Archs <$> some archOpt <|> ExcludedArchs <$> some excludeArch++ mtargetOpt :: Parser (Maybe String)+ mtargetOpt = optional targetOpt++ targetOpt :: Parser String+ targetOpt =+ checkNotMaster <$> strOptionWith 't' "target" "TARGET" "Koji target"+ where+ checkNotMaster "master" = error' "'master' is not a valid target!"+ checkNotMaster t = t++ overrideOpt = switchWith 'o' "override" "Create a buildroot override and wait-repo"++ dryrunOpt = switchWith 'n' "dry-run" "Do not write (push, build, post, override)"++ updatetypeOpt = flagWith' Nothing 'U' "no-update" "Do not generate a Bodhi update" <|> Just <$> optionalWith auto 'u' "update-type" "TYPE" "security, bugfix, enhancement (default), or newpackage" EnhancementUpdate++ forceshortOpt =+ flagWith' ForceBuild 'f' "rebuild" "Rebuild even if already built" <|>+ flagWith' ShortCircuit 's' "short-circuit" "Do --short-circuit rpmbuild"++ diffFormatOpt :: Parser DiffFormat+ diffFormatOpt =+ DiffContext <$> optionWith auto 'u' "unified" "CONTEXT" "Lines of context" <|>+ flagWith' DiffMinimal 'm' "minimal" "Minimize diff noise" <|>+ flagWith' DiffStats 's' "stats" "Minimize diff noise" <|>+ flagWith DiffDefault DiffQuiet 'q' "quiet" "Just output package name"++ diffSpecOnly :: Parser Bool+ diffSpecOnly = switchWith 'o' "spec-only" "Only diff spec file"++ diffWorkOpt :: Parser DiffWork+ diffWorkOpt =+ flagWith' DiffWorkStaged 'S' "staged" "Diff staged changes (git diff --cached)" <|>+ flagWith DiffWorkAll DiffWorkUnstage 'U' "unstaged" "Diff unstaged changes (git diff) [default is 'git diff HEAD']"++ diffBranchOpt :: Parser (Maybe AnyBranch)+ diffBranchOpt = optional (optionWith anyBranchM 'w' "with-branch" "BRANCH" "branch")++ commitOpts :: Parser CommitOpt+ commitOpts =+ CommitMsg <$> strOptionWith 'm' "message" "COMMITMSG" "commit message" <|>+ flagWith' CommitAmend 'a' "amend" "Amend commit"++ buildByOpt = flagWith' SingleBuild 'S' "single" "Non-progressive normal single build" <|> flagWith' BuildByRelease 'R' "by-release" "Builds by release" <|> flagWith ValidateByRelease ValidateByArch 'A' "by-arch" "Build across latest release archs first (default is across releases for primary arch)"++ commandOpt = strOptionWith 'c' "cmd" "COMMAND" "Shell command to run in $p"++ sidetagTargetOpt :: Parser SideTagTarget+ sidetagTargetOpt =+ Target <$> targetOpt <|>+ flagWith' SideTag 's' "sidetag" "Use existing branch side-tag for building: create with 'fedpkg request-side-tag --base-tag'"++ packagerOpt = Owner <$> ownerOpt <|> Committer <$> usernameOpt+ usernameOpt = strOptionWith 'u' "username" "USERNAME" "Packages user can commit to"+ ownerOpt = strOptionWith 'o' "owner" "OWNER" "Package owner"++ bcondOpt = BuildWith <$> strOptionWith 'w' "with" "FEATURE" "Turn on package FEATURE for build" <|>+ BuildWithout <$> strOptionWith 'W' "without" "FEATURE" "Turn off package FEATURE for build"
+ src/Package.hs view
@@ -0,0 +1,623 @@+{-# LANGUAGE CPP #-}++module Package (+ builtRpms,+ clonePkg,+ fedpkg,+ fedpkg_,+ checkForSpecFile,+ cleanChangelog,+ getChangeLog,+ getDirectoryName,+ getPackageName,+ getSummaryURL,+ findSpecfile,+ localBranchSpecFile,+ generateSrpm,+ BCond(..),+ ForceShort(..),+ buildRPMs,+ installDeps,+ prepPackage,+ checkSourcesMatch,+ getSources,+ putPkgHdr,+ putPkgBrnchHdr,+ putPkgAnyBrnchHdr,+ withExistingDirectory,+ initialPkgRepo,+ splitBranchesPkgs,+-- withBranchByPackages,+ withPackageByBranches,+ withPackageByBranches',+ LimitBranches(..),+ cleanGit,+ cleanGitFetch,+ cleanGitFetchActive,+ dirtyGit,+ dirtyGitFetch,+ Package(..),+ packageSpec,+ pkgNameVerRel,+ pkgNameVerRel',+ buildRequires,+ notInstalled,+ pkgInstalled,+ systemBranch,+ equivNVR,+ takeNVRName,+ nameOfNVR+ ) where++import Common+import Common.System++import Distribution.Fedora+import SimpleCmd.Rpm+import System.Console.Pretty++import Branches+import Git+import InterleaveOutput+import Krb+import Prompt++fedpkg :: String -> [String] -> IO String+fedpkg c args =+ cmd "fedpkg" (c:args)++fedpkg_ :: String -> [String] -> IO ()+fedpkg_ c args =+ cmd_ "fedpkg" (c:args)++checkForSpecFile :: String -> IO ()+checkForSpecFile spec = do+ have <- doesFileExist spec+ unless have $ error' $ spec ++ " not found"++getChangeLog :: FilePath -> IO String+getChangeLog spec = do+ clog <- cleanChangelog <$> cmd "rpmspec" ["-q", "--srpm", "--qf", "%{changelogtext}", spec]+ putStrLn ""+ putStrLn "```"+ putStrLn clog+ putStrLn "```"+ ifM (not <$> isTty)+ (return clog) $+ do+ userlog <- prompt "Press Enter to use above or input change summary now"+ return $ if null userlog then clog else userlog++cleanChangelog :: String -> String+cleanChangelog [] = error' "empty changelog" -- should not happen+cleanChangelog cs =+ let ls = lines cs+ no = length $ filter ("- " `isPrefixOf`) ls+ in if no == 1 then removePrefix "- " cs else cs++getSummaryURL :: FilePath -> IO String+getSummaryURL spec = do+ notes <- cmd "rpmspec" ["-q", "--srpm", "--qf", "%{summary}\n\n- %{url}", spec]+ putStrLn ""+ putStrLn "```"+ putStrLn notes+ putStrLn "```"+ ifM (not <$> isTty)+ (return notes) $+ do+ usernote <- prompt "Press Enter to use above or input notes"+ return $ if null usernote then notes else usernote++-- FIXME maybe check spec filename/%name more carefully+getPackageName :: FilePath -> IO Package+getPackageName pkgdir =+ if pkgdir == "."+ then Package <$> getDirectoryName+ else return $ Package $ takeFileName pkgdir++findSpecfile :: IO FilePath+findSpecfile = do+ mspec <- maybeFindSpecfile+ case mspec of+ Just spec -> return spec+ Nothing -> error' "No spec file found"++maybeFindSpecfile :: IO (Maybe FilePath)+maybeFindSpecfile = fileWithExtension ".spec"+ where+ -- looks in dir for a unique file with given extension+ fileWithExtension :: String -> IO (Maybe FilePath)+ fileWithExtension ext = do+ files <- filter ((== ext) . takeExtension) <$> listDirectory "."+ case files of+ [] -> return Nothing+ [spec] -> return $ Just spec+ _ -> error' $ "No unique " ++ ext ++ " file found"++localBranchSpecFile :: Package -> AnyBranch -> IO FilePath+localBranchSpecFile pkg br = do+ gitdir <- isPkgGitRepo+ when gitdir $ do+ putPkgAnyBrnchHdr pkg br+ gitSwitchBranch br+ if gitdir+ then do+ let spec = packageSpec pkg+ ifM (doesFileExist spec)+ (return spec) $+ do+ mspec <- maybeFindSpecfile+ case mspec of+ Just spc -> do+ putStrLn $ "Warning: directory name differs from " ++ spc ++ "\n"+ return spc+ Nothing -> error' "No spec file"+ else findSpecfile++rpmEval :: String -> IO (Maybe String)+rpmEval s = do+ res <- cmd "rpm" ["--eval", s]+ return $ if null res || res == s then Nothing else Just res++generateSrpm :: Maybe AnyBranch -> FilePath -> IO FilePath+generateSrpm mbr spec = do+ getSources spec+ distopt <- case mbr of+ Nothing -> return []+ Just br -> do+ dist <- getBranchDist br+ return ["--define", "dist " ++ rpmDistTag dist]+ srpmfile <- cmd "rpmspec" $ ["-q", "--srpm"] ++ distopt ++ ["--qf", "%{name}-%{version}-%{release}.src.rpm", spec]+ srcrpmdir <-+ ifM isPkgGitRepo+ (return ".") $+ rpmEval "%{_srcrpmdir}" >>= maybe (error' "%_srcrpmdir undefined!") return+ let srpm = srcrpmdir </> srpmfile+ srpmdiropt = if null srcrpmdir then []+ else ["--define", "_srcrpmdir " ++ srcrpmdir]+ sourcedir <-+ ifM isPkgGitRepo+ (return ".") $+ rpmEval "%{_sourcedir}" >>= maybe (error' "%_sourcedir undefined!") return+ let sourcediropt = if null sourcedir then []+ else ["--define", "_sourcedir " ++ sourcedir]+ ifM (notM $ doesFileExist srpm)+ (buildSrpm (distopt ++ srpmdiropt ++ sourcediropt)) $+ do+ specTime <- getModificationTime spec+ srpmTime <- getModificationTime srpm+ if srpmTime > specTime+ then do+ -- pretty print with ~/+ putStrLn $ srpm ++ " is up to date"+ return srpm+ else buildSrpm (distopt ++ srpmdiropt ++ sourcediropt)+ where+ buildSrpm opts = do+ srpm <- last . words <$> cmd "rpmbuild" (opts ++ ["-bs", spec])+ putStrLn $ "Created " ++ takeFileName srpm+ return srpm++data ForceShort = ForceBuild | ShortCircuit+ deriving Eq++data BCond = BuildWith String | BuildWithout String++instance Show BCond where+ show (BuildWith s) = "--with=" ++ s+ show (BuildWithout s) = "--without=" ++ s++-- FIXME create build.log+-- Note does not check if bcond changed+buildRPMs :: Bool -> Maybe ForceShort -> [BCond] -> [FilePath] -> AnyBranch+ -> FilePath -> IO ()+buildRPMs quiet mforceshort bconds rpms br spec = do+ needBuild <-+ if isJust mforceshort+ then return True+ else+ ifM (not . and <$> mapM doesFileExist rpms)+ (return True) $+ do specTime <- getModificationTime spec+ rpmTimes <- sort <$> mapM getModificationTime rpms+ return $ specTime > head rpmTimes+ if not needBuild then+ putStrLn "Existing rpms are newer than spec file (use --force to rebuild)"+ else do+ installDeps spec+ void $ getSources spec+ dist <- getBranchDist br+ cwd <- getCurrentDirectory+ gitDir <- isGitRepo+ let shortcircuit = mforceshort == Just ShortCircuit+ let buildopt = if shortcircuit then ["-bi", "--short-circuit"] else ["-bb"]+ rpmdirs =+ [ "--define="++ mcr +-+ cwd | gitDir,+ mcr <- ["_builddir", "_rpmdir", "_srcrpmdir", "_sourcedir"]]+ args = rpmdirs ++ ["--define", "dist " ++ rpmDistTag dist] ++ buildopt ++ map show bconds ++ [spec]+ if not quiet || shortcircuit then+ cmd_ "rpmbuild" args+ else do+ putStr "Building locally: "+ cmdSilent_ "rpmbuild" args+ putStrLn "done"++installDeps :: FilePath -> IO ()+installDeps spec = do+ missingdeps <- nub <$> (buildRequires spec >>= filterM notInstalled)+ unless (null missingdeps) $ do+ putStrLn $ "Need: " ++ unwords missingdeps+ putStr "Running dnf builddep... "+ cmdSilent "/usr/bin/sudo" $ "/usr/bin/dnf":["builddep", "--assumeyes", spec]+ putStrLn "done"++prepPackage :: Package -> AnyBranch -> IO ()+prepPackage pkg br =+ ifM (doesFileExist "dead.package")+ (putStrLn "dead.package") $+ do+ spec <- localBranchSpecFile pkg br+ unlessM (doesFileExist spec) $+ error' $ spec ++ " not found"+ cwd <- getCurrentDirectory+ getSources spec+ gitDir <- isGitRepo+ let rpmdirs =+ [ "--define="++ mcr +-+ cwd | gitDir,+ mcr <- ["_builddir", "_sourcedir"]]+ args = rpmdirs ++ ["-bp", spec]+ case br of+ RelBranch rbr -> do+ nvr <- pkgNameVerRel' rbr spec+ putStr $ "Prepping " ++ nvr ++ ": "+ _ -> return ()+ cmdSilent_ "rpmbuild" args+ putStrLn "done"++checkSourcesMatch :: FilePath -> IO ()+checkSourcesMatch spec = do+ -- "^[Ss]ource[0-9]*:"+ sourcefiles <- map (takeFileName . last . words) <$> cmdLines "spectool" [spec]+ sources <- lines <$> readFile "sources"+ gitfiles <- gitLines "ls-files" []+ forM_ sourcefiles $ \ src ->+ unless (isJust (find (src `isInfixOf`) sources) || src `elem` gitfiles) $ do+ prompt_ $ color Red $ src ++ " not in sources, please fix"+ checkSourcesMatch spec++getSources :: FilePath -> IO ()+getSources spec = do+ gitDir <- isGitRepo+ srcdir <- getSourceDir gitDir+ srcs <- mapMaybe sourceFieldFile <$> cmdLines "spectool" ["-S", spec]+ unless gitDir $+ unlessM (doesDirectoryExist srcdir) $+ createDirectoryIfMissing True srcdir+ forM_ srcs $ \ src ->+ unlessM (doesFileExist (srcdir </> src)) $ do+ uploaded <-+ if gitDir then do+ have_sources <- doesFileExist "sources"+ if have_sources then+ grep_ src "sources"+ else return False+ else return False+ if uploaded+ then cmd_ "fedpkg" ["sources"]+ else do+ cmd_ "spectool" ["-g", "-S", "-C", srcdir, spec]+ unlessM (doesFileExist (srcdir </> src)) $+ error' $ "download failed: " ++ src+ where+ sourceFieldFile :: String -> Maybe FilePath+ sourceFieldFile field =+ case words field of+ [f,v] ->+ -- workaround rpmdevtools 9.3 (spectool -S lists patches)+ if "source" `isPrefixOf` lower f+ then Just $ takeFileName v+ else Nothing+ _ -> error $ "bad source field!: " ++ field++ getSourceDir :: Bool -> IO FilePath+ getSourceDir gitDir =+ if gitDir+ then getCurrentDirectory+ else fromJust <$> rpmEval "%{_sourcedir}"++withExistingDirectory :: FilePath -> IO a -> IO a+withExistingDirectory dir act =+ ifM (doesDirectoryExist dir)+ (withCurrentDirectory dir act)+ (error' $ "No such directory: " ++ dir)++-- newly created Fedora repos/branches have just one README commit+initialPkgRepo :: IO Bool+initialPkgRepo = do+ commits <- length <$> gitShortLogN 2 Nothing+ return $ commits <= 1++newtype Package = Package {unPackage :: String}++putPkgHdr :: Package -> IO ()+putPkgHdr pkg =+ putStrLn $ "\n= " ++ unPackage pkg ++ " ="++putPkgBrnchHdr :: Package -> Branch -> IO ()+putPkgBrnchHdr pkg br =+ putStrLn $ "\n== " ++ unPackage pkg ++ " " ++ show br ++ " =="++putPkgAnyBrnchHdr :: Package -> AnyBranch -> IO ()+putPkgAnyBrnchHdr pkg br =+ putStrLn $ "\n== " ++ unPackage pkg ++ " " ++ show br ++ " =="++packageSpec :: Package -> FilePath+packageSpec pkg = unPackage pkg <.> "spec"++data BrPkg = IsBr AnyBranch | Unknown String | IsPkg String+ deriving Show++splitBranchesPkgs :: Bool -> Maybe BranchOpts -> Bool -> [String]+ -> IO ([AnyBranch], [String])+splitBranchesPkgs release mbrnchopts exists args = do+ pkggit <- isPkgGitRepo+ brPkgs <- mapM (toBrPkg pkggit) args+ let (brs,pkgs) = brPkgsToBranchesPkgs brPkgs+ return $ case mbrnchopts of+ Just _ | brs /= [] -> error' "cannot specify branches with branch options"+ _ -> (brs,pkgs)+ where+ toBrPkg :: Bool -> String -> IO BrPkg+ toBrPkg gitdir str =+ case anyBranch str of+ rbr@(RelBranch _) -> return (IsBr rbr)+ abr@(OtherBranch p) -> if release then return (IsPkg p)+ else+ ifM (isPath str)+ (return $ IsPkg str) $+ if gitdir+ then return (IsBr abr)+ else return $ if exists+ then IsBr abr+ else IsPkg str+ where+ isPath :: FilePath -> IO Bool+ isPath fp =+ if ".spec" `isExtensionOf` fp+ then do+ exists' <- doesFileExist fp+ unless exists' $ error' $ fp ++ " file not found"+ return True+ else do+ exists' <- doesDirectoryExist fp+ let ispath = '/' `elem` fp+ when (not exists' && ispath) $+ error' $ fp ++ " directory not found"+ return exists'++ brPkgsToBranchesPkgs :: [BrPkg] -> ([AnyBranch], [String])+ brPkgsToBranchesPkgs brpkgs =+ let (pbrs,ppkgs) = span isBranch brpkgs+ in (map toBranch pbrs, map toPackage ppkgs)+ where+ isBranch :: BrPkg -> Bool+ isBranch (IsBr _) = True+ isBranch (Unknown _) = True+ isBranch (IsPkg _) = False++ toBranch :: BrPkg -> AnyBranch+ toBranch (IsBr br) = br+ toBranch (Unknown br) = OtherBranch br+ toBranch (IsPkg p) = error' $ "can't map package to branch: " ++ p++ toPackage :: BrPkg -> String+ toPackage (IsPkg p) = p+ toPackage (Unknown p) = p+ toPackage (IsBr b) = error' $ "can't map branch to package: " ++ show b++data GitOpts =+ GitOpts+ { gitOptClean :: Bool+ , gitOptFetch :: Bool+ , gitOptActive :: Bool+ }++cleanGit, cleanGitFetch, cleanGitFetchActive, dirtyGit, dirtyGitFetch :: Maybe GitOpts+-- clean fetch active+cleanGit = Just $ GitOpts True False False+cleanGitFetch = Just $ GitOpts True True False+cleanGitFetchActive = Just $ GitOpts True True True+dirtyGit = Just $ GitOpts False False False+dirtyGitFetch = Just $ GitOpts False True False++data LimitBranches = AnyNumber | ZeroOrOne | ExactlyOne+ deriving Eq++-- do package over branches+withPackageByBranches :: Maybe Bool+ -> Maybe GitOpts+ -> Maybe BranchOpts+ -> Bool+ -> LimitBranches+ -> (Package -> AnyBranch -> IO ())+ -> [String]+ -> IO ()+withPackageByBranches mheader mgitopts mbrnchopts exists limitBranches action args = do+ (brs,pkgs) <- splitBranchesPkgs (have gitOptActive) mbrnchopts exists args+ let mheader' =+ case mheader of+ Nothing -> Nothing+ Just _ | length pkgs < 2 && length brs < 2 -> Nothing+ _ -> mheader+ withPackageByBranches' mheader' mgitopts mbrnchopts limitBranches action (brs,pkgs)+ where+ have :: (GitOpts -> Bool) -> Bool+ have opt = maybe False opt mgitopts++withPackageByBranches' :: Maybe Bool+ -> Maybe GitOpts+ -> Maybe BranchOpts+ -> LimitBranches+ -> (Package -> AnyBranch -> IO ())+ -> ([AnyBranch], [String])+ -> IO ()+withPackageByBranches' mheader mgitopts mbrnchopts limitBranches action (brs,pkgs) = do+ case mbrnchopts of+ Just _ ->+ unless (null brs) $+ error' "cannot specify branches and branch option together"+ Nothing ->+ case limitBranches of+ ZeroOrOne | length brs > 1 ->+ error' "more than one branch given"+ ExactlyOne | null brs ->+ error' "please specify one branch"+ ExactlyOne | length brs > 1 ->+ error' "please only specify one branch"+ _ -> return ()+ if null pkgs+ then do+ withPackageDir "."+ else do+ when (length pkgs > 1 && null brs) $+ error' "At least one branch must be specified when there are multiple packages"+ mapM_ withPackageDir pkgs+ where+ -- FIXME support arbitrary (module) branches+ withPackageDir :: FilePath -> IO ()+ withPackageDir path = do+ let dir =+ if ".spec" `isExtensionOf` path+ then takeDirectory path+ else path+ withExistingDirectory dir $ do+ mspec <- if ".spec" `isExtensionOf` path+ then return $ Just $ takeFileName path+ else maybeFindSpecfile+ pkg <- Package <$>+ case mspec of+ -- FIXME fails if spec file can't be parsed+ Just spec -> cmd "rpmspec" ["-q", "--srpm", "--qf", "%{name}", spec]+ Nothing -> getDirectoryName+ unless (isNothing mspec || mspec == Just (unPackage pkg <.> "spec")) $+ putStrLn "Warning: package name and spec filename differ!"+ haveGit <- isPkgGitRepo+ when (isJust mgitopts && not haveGit) $+ error' $ "Not a pkg git dir: " ++ unPackage pkg+ mcurrentbranch <- if haveGit then Just <$> gitCurrentBranch+ else return Nothing+ let fetch = have gitOptFetch+ when ((mheader == Just True || isJust mheader && max (length brs) (length pkgs) > 1 || fetch) && dir /= ".") $+ putPkgHdr pkg+ when haveGit $+ when (have gitOptClean) checkWorkingDirClean+ when fetch gitFetchSilent+ branches <- listOfBranches haveGit (have gitOptActive) mbrnchopts brs+ when (mbrnchopts == Just AllBranches) $+ putStrLn $ "Branches: " ++ unwords (map show branches) ++ "\n"+ mapM_ (action pkg) branches+ when (length branches /= 1) $+ whenJust mcurrentbranch gitSwitchBranch++ have :: (GitOpts -> Bool) -> Bool+ have opt = maybe False opt mgitopts++-- -- do branch over packages+-- withBranchByPackages :: (Branch -> [String] -> IO ()) -> (Branches,[String]) -> IO ()+-- withBranchByPackages action (brs,pkgs) = do+-- when (null brs) $+-- error' "Please specify at least one branch"+-- when (null pkgs) $+-- error' "Please give at least one package"+-- forM_ brs $ \ br ->+-- -- forM_ (map packagePath pkgs) $ \ (dir,pkg) ->+-- -- withExistingDirectory dir $ do+-- -- void $ setupGit False pkg True+-- action br pkgs++clonePkg :: Bool -> Maybe Branch -> String -> IO ()+clonePkg quiet mbr pkg =+ ifM (doesDirectoryExist pkg)+ {-then-} (putStrLn $ pkg ++ "/ already exists") $+ {-else-} do+ let mbranch = case mbr of+ Nothing -> []+ Just br -> ["--branch", show br]+ fasid <- fasIdFromKrb+ unless quiet $+ putStr $ pkg ++ " "+ git_ "clone" $ ["--quiet"] ++ mbranch ++ ["ssh://" ++ fasid ++ "@pkgs.fedoraproject.org/rpms/" ++ pkg]++pkgNameVerRel :: Branch -> FilePath -> IO (Maybe String)+pkgNameVerRel br spec = do+ dist <- branchDist br+ -- workaround dist with bootstrap+ hostdist <- cmd "rpm" ["--eval", "%{dist}"]+ fmap (replace hostdist (rpmDistTag dist)) . listToMaybe <$> rpmspec ["--srpm"] (Just "%{name}-%{version}-%{release}") spec++pkgNameVerRel' :: Branch -> FilePath -> IO String+pkgNameVerRel' br spec = do+ mnvr <- pkgNameVerRel br spec+ case mnvr of+ Nothing -> error' $ "rpmspec failed to parse " ++ spec+ Just nvr -> return nvr++builtRpms :: AnyBranch -> FilePath -> IO [FilePath]+builtRpms br spec = do+ dist <- getBranchDist br+ rpms <- rpmspec ["--builtrpms", "--define", "dist " ++ rpmDistTag dist] (Just "%{arch}/%{name}-%{version}-%{release}.%{arch}.rpm") spec+ if null rpms+ then error' $ spec ++ " does not seem to create any rpms"+ else return rpms++getBranchDist :: AnyBranch -> IO Dist+getBranchDist (RelBranch br) = branchDist br+getBranchDist (OtherBranch _) = systemBranch >>= branchDist++-- from fedora-haskell-tools+buildRequires :: FilePath -> IO [String]+buildRequires spec =+ -- FIXME should resolve meta+ map (head . words) <$> rpmspec ["--buildrequires"] Nothing spec++notInstalled :: String -> IO Bool+notInstalled pkg =+ not <$> cmdBool "rpm" ["--quiet", "-q", "--whatprovides", pkg]++pkgInstalled :: String -> IO Bool+pkgInstalled pkg =+ cmdBool "rpm" ["--quiet", "-q", pkg]+++-- FIXME could be more strict about dist tag (eg .fcNN only)+equivNVR :: String -> String -> Bool+equivNVR nvr1 nvr2+ | nvr1 == nvr2 = True+ | length nvr1 /= length nvr2 = False+ | otherwise =+ -- (name-ver-rel,.dist)+ let (nvr, r) = splitExtension nvr1+ (nvr', r') = splitExtension nvr2+ in nvr == nvr' &&+ -- (dist,.more)+ let (r1,r1') = splitExtension $ tail r+ (r2,r2') = splitExtension $ tail r'+ -- allow differing dist+ in length r1 == length r2 && r1' == r2'++-- FIXME?+-- n-v-r.src.rpm -> n-v-r+takeNVRName :: FilePath -> String+takeNVRName = takeBaseName . takeBaseName++-- n-v-r -> n+nameOfNVR :: String -> String+nameOfNVR = removeSeg . removeSeg+ where+ removeSeg = init . dropWhileEnd (/= '-')++#if !MIN_VERSION_filepath(1,4,2)+isExtensionOf :: String -> FilePath -> Bool+isExtensionOf ext@('.':_) = isSuffixOf ext . takeExtensions+isExtensionOf ext = isSuffixOf ('.':ext) . takeExtensions+#endif
+ src/Pagure.hs view
@@ -0,0 +1,28 @@+module Pagure (+ srcfpo,+ pagureio,+ pagureProjectInfo,+ pagureListGitBranches,+ pagureListProjectIssueTitlesStatus,+ IssueTitleStatus(..),+ pagureUserRepos,+ makeItem,+ printScmIssue+ ) where++import qualified Common.Text as T++import Fedora.Pagure+import System.FilePath++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
+ src/Prompt.hs view
@@ -0,0 +1,31 @@+module Prompt (+ prompt,+ prompt_,+ refPrompt+ ) where++import Common++import Data.Char++-- FIXME promptNonEmpty+prompt :: String -> IO String+prompt s = do+ putStr $ s ++ ": "+ inp <- getLine+ putStrLn ""+ return inp++prompt_ :: String -> IO ()+prompt_ = void <$> prompt++-- FIXME select ref by number+refPrompt :: [String] -> String -> IO (Maybe (Maybe String))+refPrompt commits txt = do+ let commitrefs = tail $ map (head . words) commits+ inp <- prompt txt+ if null inp then return (Just Nothing) else+ if map toLower inp == "no" then return Nothing+ else case find (inp `isPrefixOf`) commitrefs of+ Just ref -> return $ Just (Just ref)+ Nothing -> refPrompt commits txt