From 90fcbf6a212ebc0750f1150d16629917f206e6bb Mon Sep 17 00:00:00 2001 From: Gorbunov Kirill Andreevich Date: Sat, 23 Mar 2024 18:52:13 +0300 Subject: [PATCH] #8 add cli, need fix parse yaml. --- LICENSE | 73 ------------------- Makefile | 4 + README.md | 45 ++++++++++++ cmd/pkgdashcli/main.go | 32 +++----- cmd/pkgdashcli/pkgdashcli.go | 7 ++ go.mod | 11 ++- go.sum | 10 ++- internal/cli/checkupdate.go | 94 ++++++++++++++++++++++++ internal/cli/delete.go | 75 +++++++++++++++++++ internal/cli/init.go | 121 +++++++++++++++++++++++++++++++ internal/cli/list.go | 73 +++++++++++++++++++ internal/cli/root.go | 42 +++++++++++ internal/cli/update.go | 97 +++++++++++++++++++++++++ internal/source/gitea/gitea.go | 26 ++++++- internal/source/github/github.go | 3 + internal/source/gitlab/gitlab.go | 3 + internal/source/gogs/gogs.go | 3 + internal/source/source.go | 1 + 18 files changed, 615 insertions(+), 105 deletions(-) create mode 100644 cmd/pkgdashcli/pkgdashcli.go create mode 100644 internal/cli/checkupdate.go create mode 100644 internal/cli/delete.go create mode 100644 internal/cli/init.go create mode 100644 internal/cli/list.go create mode 100644 internal/cli/root.go create mode 100644 internal/cli/update.go diff --git a/LICENSE b/LICENSE index 79b4205..e69de29 100644 --- a/LICENSE +++ b/LICENSE @@ -1,73 +0,0 @@ -Apache License -Version 2.0, January 2004 -http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - -"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. - -"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. - -"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. - -"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. - -"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. - -"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. - -"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). - -"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. - -"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." - -"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: - - (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. - - You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work. - -To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. - -Copyright 2023 unistack-org - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/Makefile b/Makefile index fec0650..8789ad8 100644 --- a/Makefile +++ b/Makefile @@ -6,6 +6,10 @@ build: buildcli: CGO_ENABLED=0 go build -o bin/app -mod=readonly git.unistack.org/unistack-org/pkgdash/cmd/pkgdashcli +.PHONY: cli +cli: + go install git.unistack.org/unistack-org/pkgdash/cmd/pkgdashcli + .PHONY: test test: go test -v ./... -race -cover diff --git a/README.md b/README.md index 53874ec..63d0fb0 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,47 @@ # pkgdash +# pkgdashcli + +## Installation + +Use any of the following for a pain-free installation: + +* If you have [`go`](https://go.dev/doc/install) installed, you can run: + ```shell + go install git.unistack.org/unistack-org/pkgdash/cmd/pkgdashcli@latest + ``` + +## Config + + Before starting, you should fill out the configuration file. +The file must be located in the .gitea, .gitlab, .github directory +according to the git type you are using. + +- branches - array of main branches +- source - information about the version control system +- source.type - type of version control system +- source.apiurl - path to the version control system api +- source.repository - repository name +- source.owner - username of the repository owner +- update_opt - dependency update options +- update_opt.pre - update to pre-release versions +- update_opt.major - compare only major versions in modules +- update_opt.up_major - raise the version according to major +- update_opt.cached - caching + +### Config.Example + +```yaml +# .gitea/pkgdashcli.yaml +branches: [master] +source: + type: gitea + apiurl: https://git.unistack.org/api/v1 + repository: pkgdash + owner: unistack +update_opt: + pre: false + major: false + up_major: false + cached: true +``` \ No newline at end of file diff --git a/cmd/pkgdashcli/main.go b/cmd/pkgdashcli/main.go index 6c31d7a..674ac7e 100644 --- a/cmd/pkgdashcli/main.go +++ b/cmd/pkgdashcli/main.go @@ -32,7 +32,6 @@ import ( "go.unistack.org/micro/v4/options" "golang.org/x/mod/modfile" "golang.org/x/mod/semver" - "gopkg.in/yaml.v2" ) // https://docs.github.com/ru/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file @@ -66,7 +65,6 @@ type Data struct { } func main() { - fmt.Println("Start...") var err error ctx, cancel := context.WithCancel(context.Background()) @@ -96,30 +94,24 @@ func main() { for _, configDir := range configDirs { for _, configFile := range configFiles { + logger.Info(ctx, fmt.Sprintf("path: %s", filepath.Join(configDir, configFile))) c := fileconfig.NewConfig( - config.AllowFail(true), + config.AllowFail(false), config.Struct(cfg), options.Codec(yamlcodec.NewCodec()), - fileconfig.Path(filepath.Join(configDir, configFile)), + fileconfig.Path(".gitea/pkgdashcli.yaml"), ) + err = c.Init(options.Context(ctx)) + if err != nil { + logger.Error(ctx, fmt.Sprintf("failed to init config: %v", err)) + } if err = c.Load(ctx, config.LoadOverride(true)); err != nil { - logger.Fatal(ctx, fmt.Sprintf("failed to load config: %v", err)) + logger.Error(ctx, fmt.Sprintf("failed to load config: %v", err)) } } } - file, err := os.Open(".gitea/pkgdashcli.yaml") - if err != nil { - logger.Fatal(ctx, fmt.Sprintf("file open: %s", err)) - } - defer file.Close() - - d := yaml.NewDecoder(file) - if err = d.Decode(&cfg); err != nil { - logger.Fatal(ctx, fmt.Sprintf("Decode err: %s", d)) - } - - logger.Info(ctx, fmt.Sprintf("Load config... %s", cfg)) + logger.Info(ctx, fmt.Sprintf("Load config... %s", cfg.Source.Repository)) if cfg.PullRequestBody == "" { cfg.PullRequestBody = DefaultPullRequestBody @@ -218,12 +210,6 @@ func main() { logger.Debugf(ctx, fmt.Sprintf("Start update %s from %s to %s", pathMod, mod.Module.Version, mod.Version)) err = gitSource.RequestOpen(ctx, branch, pathMod, mod) if err != nil { - if err.Error() == "pull request exists" { - err = gitSource.RequestUpdate(ctx, branch, pathMod, mod) - if err != nil { - logger.Error(ctx, fmt.Sprintf("Update PR error: %s", err)) - } - } logger.Error(ctx, fmt.Sprintf("failed to create pr: %v", err)) } logger.Debugf(ctx, fmt.Sprintf("Update successful for %s", pathMod)) diff --git a/cmd/pkgdashcli/pkgdashcli.go b/cmd/pkgdashcli/pkgdashcli.go new file mode 100644 index 0000000..e080b7c --- /dev/null +++ b/cmd/pkgdashcli/pkgdashcli.go @@ -0,0 +1,7 @@ +package main + +import "git.unistack.org/unistack-org/pkgdash/internal/cli" + +func main() { + cli.Execute() +} diff --git a/go.mod b/go.mod index 82e2882..9cfffe8 100644 --- a/go.mod +++ b/go.mod @@ -2,6 +2,11 @@ module git.unistack.org/unistack-org/pkgdash go 1.20 +replace ( + go.unistack.org/micro-config-file/v4 v4.0.3 => /Users/kgorbunov/GolandProjects/src/micro-config-file + go.unistack.org/micro/v4 v4.0.18 => /Users/kgorbunov/GolandProjects/src/micro +) + require ( github.com/envoyproxy/protoc-gen-validate v1.0.4 github.com/go-git/go-git/v5 v5.8.1 @@ -25,15 +30,17 @@ require ( golang.org/x/mod v0.14.0 golang.org/x/sync v0.6.0 google.golang.org/protobuf v1.33.0 - gopkg.in/yaml.v2 v2.4.0 modernc.org/sqlite v1.21.0 ) require ( github.com/google/go-cmp v0.6.0 // indirect + github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/silas/dag v0.0.0-20220518035006-a7e85ada93c5 // indirect + github.com/spf13/cobra v1.8.0 // indirect + github.com/spf13/pflag v1.0.5 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20240311132316-a219d84964c2 // indirect - google.golang.org/grpc v1.62.1 // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect ) require ( diff --git a/go.sum b/go.sum index 590fc6c..9b8c237 100644 --- a/go.sum +++ b/go.sum @@ -298,6 +298,7 @@ github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfc github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= +github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/creack/pty v1.1.11/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= @@ -619,6 +620,8 @@ github.com/imdario/mergo v0.3.12/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH github.com/imdario/mergo v0.3.16 h1:wwQJbIsHYGMUyLSPrEq1CT16AhnhNJQ51+4fdHUnCl4= github.com/imdario/mergo v0.3.16/go.mod h1:WBLT9ZmE3lPoWsEzCh9LPo3TiwVN+ZKEjmz+hD27ysY= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/j-keck/arping v0.0.0-20160618110441-2cf9dc699c56/go.mod h1:ymszkNOg6tORTn+6F6j+Jc8TOr5osrynvN6ivFWZ2GA= github.com/jackc/chunkreader v1.0.0/go.mod h1:RT6O25fNZIuasFJRyZ4R/Y2BbhasbmZXF9QQ7T3kePo= github.com/jackc/chunkreader/v2 v2.0.0/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk= @@ -936,6 +939,7 @@ github.com/rs/zerolog v1.15.0/go.mod h1:xYTKnLHcpfU2225ny5qZjxnj9NvkumZYjJHlAThC github.com/rs/zerolog v1.30.0 h1:SymVODrcRsaRaSInD9yQtKbtWqwsfoPcRff/oRXLj4c= github.com/rs/zerolog v1.30.0/go.mod h1:/tk+P47gFdPXq4QYjvCmT5/Gsug2nagsFWBWhAiSi1w= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ruudk/golang-pdf417 v0.0.0-20181029194003-1af4ab5afa58/go.mod h1:6lfFZQK844Gfx8o5WFuvpxWRwnSoipWe/p622j1v06w= github.com/ryanuber/columnize v2.1.0+incompatible/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/ryanuber/go-glob v1.0.0 h1:iQh3xXAumdQ+4Ufa5b25cRpC5TYKlno6hsv6Cb3pkBk= @@ -977,11 +981,14 @@ github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkU github.com/spf13/cobra v0.0.2-0.20171109065643-2da4a54c5cee/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= github.com/spf13/cobra v1.0.0/go.mod h1:/6GTrnGXV9HjY+aR4k0oJ5tcvakLuG6EuKReYlHNrgE= +github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0= +github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/pflag v0.0.0-20170130214245-9ff6c6923cff/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.1-0.20171106142849-4c012f6dcd95/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.1/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.4.0/go.mod h1:PTJ7Z/lr49W6bUbkmS1V3by4uWynFiR9p7+dSq/yZzE= github.com/stefanberger/go-pkcs11uri v0.0.0-20201008174630-78d3cae3a980/go.mod h1:AO3tvPzVZ/ayst6UlUKUv6rcPQInYe3IknH3jYhAKu8= @@ -1094,8 +1101,6 @@ go.unistack.org/micro-proto/v4 v4.0.1 h1:2RKHgtCOOcAFgKsnngGK5bqM/6MWXOjVCdw03db go.unistack.org/micro-proto/v4 v4.0.1/go.mod h1:ArmK7o+uFvxSY3dbJhKBBX4Pm1rhWdLEFf3LxBrMtec= go.unistack.org/micro-server-http/v4 v4.0.13 h1:/EUEE32ddsNH9qbBilg2cdnnMWXPOyL6TfG++Las4E4= go.unistack.org/micro-server-http/v4 v4.0.13/go.mod h1:mQ18qN/1PxeTCKMNslh5qgswV582DP9QnsaI/ohFo/k= -go.unistack.org/micro/v4 v4.0.17 h1:mF7uM+J4ILdG+1fcwzKYCwDlxhdbF/e1WnGzKKLnIXc= -go.unistack.org/micro/v4 v4.0.17/go.mod h1:ZDgU9931vm2l7X6RN/6UuwRIVp24GRdmQ7dKmegArk4= go.unistack.org/micro/v4 v4.0.18 h1:b7WFwem8Nz1xBrRg5FeLnm9CE5gJseHyf9j0BhkiXW0= go.unistack.org/micro/v4 v4.0.18/go.mod h1:5+da5r835gP0WnNZbYUJDCvWpJ9Xc3IEGyp62e8o8R4= go.unistack.org/protoc-gen-go-micro/v4 v4.0.7 h1:c3CeBvjWV9MBrGGPaQCcHZrnuLY9sVJHv7vACI/dvuM= @@ -1628,7 +1633,6 @@ google.golang.org/grpc v1.39.0/go.mod h1:PImNr+rS9TWYb2O4/emRugxiyHZ5JyHW5F+RPnD google.golang.org/grpc v1.40.0/go.mod h1:ogyxbiOoUXAkP+4+xa6PZSE9DZgIHtSpzjDTB9KAK34= google.golang.org/grpc v1.41.0/go.mod h1:U3l9uK9J0sini8mHphKoXyaqDA/8VyGnDee1zzIUK6k= google.golang.org/grpc v1.62.1 h1:B4n+nfKzOICUXMgyrNd19h/I9oH0L1pizfk1d4zSgTk= -google.golang.org/grpc v1.62.1/go.mod h1:IWTG0VlJLCh1SkC58F7np9ka9mx/WNkjl4PGJaiq+QE= google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.1.0/go.mod h1:6Kw0yEErY5E/yWrBtf03jp27GLLJujG4z/JK95pnjjw= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= diff --git a/internal/cli/checkupdate.go b/internal/cli/checkupdate.go new file mode 100644 index 0000000..1fe8e2a --- /dev/null +++ b/internal/cli/checkupdate.go @@ -0,0 +1,94 @@ +/* +Copyright © 2024 NAME HERE +*/ +package cli + +import ( + "context" + "fmt" + "os" + "strings" + + "git.unistack.org/unistack-org/pkgdash/internal/modules" + "github.com/spf13/cobra" + "go.unistack.org/micro/v4/logger" + "golang.org/x/mod/modfile" + "golang.org/x/mod/semver" +) + +// checkupdateCmd represents the checkupdate command +var checkupdateCmd = NewCheckUpdateCommand() + +var mvs = make(map[string]modules.Update) + +func init() { + rootCmd.AddCommand(checkupdateCmd) +} + +func NewCheckUpdateCommand() *cobra.Command { + ctx := context.Background() + + cmd := &cobra.Command{ + Use: "checkupdate", + Short: "CheckUpdate collects a list of dependencies with the latest updates.", + Long: `CheckUpdate collects a list of dependencies with the latest updates.`, + RunE: func(cmd *cobra.Command, args []string) error { + fmt.Println("checkupdate called") + path := "." + if len(os.Args) > 1 { + path = os.Args[1] + } + + name, err := modules.FindModFile(path) + if err != nil { + panic(err) + } + buf, err := os.ReadFile(name) + if err != nil { + panic(err) + } + mfile, err := modfile.Parse(name, buf, nil) + if err != nil { + panic(err) + } + + mvs = make(map[string]modules.Update) + + updateOptions := modules.UpdateOptions{ + Pre: cfg.UpdateOpt.Pre, + Major: cfg.UpdateOpt.Major, + UpMajor: cfg.UpdateOpt.UpMajor, + Cached: cfg.UpdateOpt.Cached, + OnUpdate: func(u modules.Update) { + var modpath string // new mod path with major + if u.Err != nil { + logger.Error(ctx, fmt.Sprintf("%s: failed: %v", u.Module.Path, u.Err)) + return + } + modpath = u.Module.Path + v := semver.Major(u.Version) + p := modules.ModPrefix(modpath) + if !strings.HasPrefix(u.Module.Version, v) && v != "v1" && v != "v0" { + switch strings.HasPrefix(u.Module.Path, "gopkg.in") { + case true: + modpath = p + "." + v + case false: + modpath = p + "/" + v + } + } + mvs[modpath] = u + }, + } + + for _, req := range mfile.Require { + updateOptions.Modules = append(updateOptions.Modules, req.Mod) + } + + modules.Updates(updateOptions) + logger.Info(ctx, fmt.Sprintf("Modules get update: /n %s", mvs)) + return nil + }, + } + + return cmd +} diff --git a/internal/cli/delete.go b/internal/cli/delete.go new file mode 100644 index 0000000..b152c83 --- /dev/null +++ b/internal/cli/delete.go @@ -0,0 +1,75 @@ +/* +Copyright © 2024 NAME HERE +*/ +package cli + +import ( + "context" + "fmt" + + "github.com/spf13/cobra" +) + +// deleteCmd represents the delete command +var deleteCmd = NewDeleteCommand() + +type DeleteFlags struct { + all bool + mod string +} + +func init() { + rootCmd.AddCommand(deleteCmd) +} + +func NewDeleteCommand() *cobra.Command { + var flags UpdateFlags + + ctx := context.Background() + + cmd := &cobra.Command{ + Use: "delete", + Short: "Delete closes the merge requests created with a dependency update.", + Long: `Delete closes the merge requests created with a dependency update.`, + RunE: func(cmd *cobra.Command, args []string) error { + fmt.Println("delete called") + var err error + + if gitsource == nil { + return errSourceNil + } + + if len(prList) == 0 { + return errPRNotExist + } + + if flags.all { + for _, branch := range cfg.Branches { + rMap := prList[branch] + for path, _ := range rMap { + err = gitsource.RequestClose(ctx, branch, path) + if err != nil { + return err + } + } + } + } + + if flags.mod != "" { + for _, branch := range cfg.Branches { + err = gitsource.RequestClose(ctx, branch, flags.mod) + if err != nil { + return err + } + } + } + + return errFlagsNotExist + }, + } + + deleteCmd.Flags().BoolVarP(&flags.all, "all", "a", false, "Deletes everything depending") + deleteCmd.Flags().StringVarP(&flags.mod, "mod", "m", "", "Deletes one dependency") + + return cmd +} diff --git a/internal/cli/init.go b/internal/cli/init.go new file mode 100644 index 0000000..0a6af9d --- /dev/null +++ b/internal/cli/init.go @@ -0,0 +1,121 @@ +/* +Copyright © 2024 NAME HERE +*/ +package cli + +import ( + "context" + "fmt" + "path/filepath" + + "git.unistack.org/unistack-org/pkgdash/internal/configcli" + "git.unistack.org/unistack-org/pkgdash/internal/source" + "github.com/spf13/cobra" + yamlcodec "go.unistack.org/micro-codec-yaml/v4" + envconfig "go.unistack.org/micro-config-env/v4" + fileconfig "go.unistack.org/micro-config-file/v4" + "go.unistack.org/micro/v4/config" + "go.unistack.org/micro/v4/logger" + "go.unistack.org/micro/v4/logger/slog" + "go.unistack.org/micro/v4/options" +) + +// initCmd represents the init command +var initCmd = NewInitCommand() + +var gitsource = source.SourceControl(nil) + +var cfg = configcli.NewConfig() + +var ( + DefaultPullRequestTitle = `Bump {{.Name}} from {{.VersionOld}} to {{.VersionNew}}` + DefaultPullRequestBody = `Bumps {{.Name}} from {{.VersionOld}} to {{.VersionNew}}` +) + +var ( + configFiles = []string{ + "dependabot.yml", + "pkgdashcli.yml", + "pkgdashcli.yaml", + } + configDirs = []string{ + ".gitea", + ".github", + ".gitlab", + } +) + +func init() { + rootCmd.AddCommand(initCmd) +} + +func NewInitCommand() *cobra.Command { + ctx := context.Background() + + logger.DefaultLogger = slog.NewLogger() + + if err := logger.DefaultLogger.Init(logger.WithCallerSkipCount(3), logger.WithLevel(logger.DebugLevel)); err != nil { + logger.Error(ctx, fmt.Sprintf("logger init error: %v", err)) + } + + cmd := &cobra.Command{ + Use: "init", + Short: "Init fills the config with data from the configuration file.", + Long: `Init fills the config with data from the configuration file.`, + RunE: func(cmd *cobra.Command, args []string) error { + fmt.Println("init called") + var err error + + if err = config.Load(ctx, + []config.Config{ + config.NewConfig( + config.Struct(cfg), + ), + envconfig.NewConfig( + config.Struct(cfg), + ), + }, + config.LoadOverride(true), + ); err != nil { + logger.Fatal(ctx, fmt.Sprintf("failed to load config: %v", err)) + } + + for _, configDir := range configDirs { + for _, configFile := range configFiles { + logger.Info(ctx, fmt.Sprintf("path: %s", filepath.Join(configDir, configFile))) + c := fileconfig.NewConfig( + config.AllowFail(false), + config.Struct(cfg), + options.Codec(yamlcodec.NewCodec()), + fileconfig.Path(".gitea/pkgdashcli.yaml"), + ) + err = c.Init(options.Context(ctx)) + if err != nil { + logger.Error(ctx, fmt.Sprintf("failed to init config: %v", err)) + return err + } + if err = c.Load(ctx, config.LoadOverride(true)); err != nil { + logger.Error(ctx, fmt.Sprintf("failed to load config: %v", err)) + return err + } + } + } + + logger.Info(ctx, fmt.Sprintf("Load config... %s", cfg.Source.Repository)) + + if cfg.PullRequestBody == "" { + cfg.PullRequestBody = DefaultPullRequestBody + } + + if cfg.PullRequestTitle == "" { + cfg.PullRequestTitle = DefaultPullRequestTitle + } + + gitsource = source.NewSourceControl(*cfg) + + return nil + }, + } + + return cmd +} diff --git a/internal/cli/list.go b/internal/cli/list.go new file mode 100644 index 0000000..a440079 --- /dev/null +++ b/internal/cli/list.go @@ -0,0 +1,73 @@ +/* +Copyright © 2024 NAME HERE +*/ +package cli + +import ( + "context" + "fmt" + + "github.com/spf13/cobra" + "go.unistack.org/micro/v4/logger" +) + +// updateCmd represents the update command +var listCmd = NewListCommand() + +var prList = map[string]map[string]string{} + +/* [ + "master": + [ + "go.unistack.org/micro/v4" : "Bump go.unistack.org/micro/v4 from v4.0.0 to v4.0.1", + "go.unistack.org/micro-client-http/v4":"Bump go.unistack.org/micro-client-http/v4 from v4.0.0 to v4.0.2", + ], + "v3": + [ + "go.unistack.org/micro/v3" : "Bump go.unistack.org/micro/v4 from v3.0.0 to v3.0.1", + ], +] */ + +func init() { + rootCmd.AddCommand(listCmd) +} + +func NewListCommand() *cobra.Command { + ctx := context.Background() + + logger.Info(ctx, "RequestList start") + + cmd := &cobra.Command{ + Use: "list", + Short: "Update allows you to start the process of creating a PR in the repository", + Long: ` +Update allows you to start the process of creating a PR in the repository. +Use the -a flag to update all dependencies or -m flag a specific module. +`, + RunE: func(cmd *cobra.Command, args []string) error { + if gitsource == nil { + return errSourceNil + } + + if cfg == nil { + return errCfgNil + } + + prList = make(map[string]map[string]string) + + for _, branch := range cfg.Branches { + rMap, err := gitsource.RequestList(ctx, branch) + if err != nil { + return err + } + prList[branch] = rMap + + logger.Info(ctx, fmt.Sprintf("for %s:\n%s", branch, rMap)) + } + + return nil + }, + } + + return cmd +} diff --git a/internal/cli/root.go b/internal/cli/root.go new file mode 100644 index 0000000..b700289 --- /dev/null +++ b/internal/cli/root.go @@ -0,0 +1,42 @@ +/* +Copyright © 2024 NAME HERE +*/ +package cli + +import ( + "fmt" + "os" + + "github.com/spf13/cobra" +) + +var ( + errUpdateNotExist = fmt.Errorf("mod not in list of update. Call init") + errFlagsNotExist = fmt.Errorf("empty flags") + errSourceNil = fmt.Errorf("source nil. Call init") + errCfgNil = fmt.Errorf("cfg nil. Call init") + errPRNotExist = fmt.Errorf("pr not exist. Call list") +) + +// rootCmd represents the base command when called without any subcommands +var rootCmd = &cobra.Command{ + Use: "pkgdash [flags]", + Short: "Pkgdash application to update dependencies.", + Long: `Pkgdash allows you to define a version update for a dependency and start merge requests in version control systems.`, + // Uncomment the following line if your bare application + // has an action associated with it: + // Run: func(cmd *cobra.Command, args []string) { }, +} + +// Execute adds all child commands to the root command and sets flags appropriately. +// This is called by main.main(). It only needs to happen once to the rootCmd. +func Execute() { + err := rootCmd.Execute() + if err != nil { + os.Exit(1) + } +} + +func init() { + +} diff --git a/internal/cli/update.go b/internal/cli/update.go new file mode 100644 index 0000000..279db50 --- /dev/null +++ b/internal/cli/update.go @@ -0,0 +1,97 @@ +/* +Copyright © 2024 NAME HERE +*/ +package cli + +import ( + "context" + "fmt" + + "github.com/spf13/cobra" + "go.unistack.org/micro/v4/logger" +) + +// updateCmd represents the update command +var updateCmd = NewUpdateCommand() + +type UpdateFlags struct { + all bool + mod string +} + +func init() { + rootCmd.AddCommand(updateCmd) +} + +func NewUpdateCommand() *cobra.Command { + var flags UpdateFlags + + ctx := context.Background() + + logger.Info(ctx, "update start") + cmd := &cobra.Command{ + Use: "update", + Short: "Update allows you to start the process of creating a PR in the repository", + Long: ` +Update allows you to start the process of creating a PR in the repository. +Use the -a flag to update all dependencies or -m flag a specific module. +`, + RunE: func(cmd *cobra.Command, args []string) error { + var err error + + if gitsource == nil { + return errSourceNil + } + if len(mvs) == 0 { + return errUpdateNotExist + } + + if flags.all { + logger.Info(ctx, "update all") + for pathMod, m := range mvs { + for _, branch := range cfg.Branches { + logger.Info(ctx, fmt.Sprintf("update mod: %s", m)) + + if err = gitsource.RequestOpen(ctx, branch, pathMod, m); err != nil { + logger.Error(ctx, fmt.Sprintf("PR open error: %s, base branch: %s", pathMod, branch)) + return err + } + + logger.Info(ctx, fmt.Sprintf("Successful update mod: %s", pathMod)) + } + + delete(mvs, pathMod) // todo возможно чисть не стоит и нужно просто пропускать + } + return nil + } + + if flags.mod != "" { + for _, branch := range cfg.Branches { + logger.Info(ctx, fmt.Sprintf("update mod: %s", flags.mod)) + + if _, ok := mvs[flags.mod]; !ok { + return errUpdateNotExist + } + + if err = gitsource.RequestOpen(ctx, branch, flags.mod, mvs[flags.mod]); err != nil { + logger.Error(ctx, fmt.Sprintf("PR open error: %s, base branch: %s", flags.mod, branch)) + return err + } + + logger.Info(ctx, fmt.Sprintf("Successful update mod: %s", flags.mod)) + } + + delete(mvs, flags.mod) + + return nil + } + + return errFlagsNotExist + }, + } + + updateCmd.Flags().BoolVarP(&flags.all, "all", "a", false, "Updates everything depending") + updateCmd.Flags().StringVarP(&flags.mod, "mod", "m", "", "Update one dependency") + + return cmd +} diff --git a/internal/source/gitea/gitea.go b/internal/source/gitea/gitea.go index c527081..e5950d3 100644 --- a/internal/source/gitea/gitea.go +++ b/internal/source/gitea/gitea.go @@ -26,7 +26,6 @@ import ( ) var ( - ErrPRExist = errors.New("pull request exists") ErrPRNotExist = errors.New("pull request does not exist") ) @@ -145,10 +144,10 @@ func (g *Gitea) RequestOpen(ctx context.Context, branch string, path string, mod } for _, pull := range pulls { - logger.Info(ctx, fmt.Sprintf("PULL title - %s | ref - %s", pull.Title, pull.Base.Ref)) + logger.Debugf(ctx, fmt.Sprintf("PULL title - %s | ref - %s", pull.Title, pull.Base.Ref)) if strings.Contains(pull.Title, path) && strings.Contains(pull.Base.Ref, branch) { - logger.Info(ctx, fmt.Sprintf("skip %s as pr already exists %s", path, pull.URL)) - return ErrPRExist + logger.Info(ctx, fmt.Sprintf("PR for %s exists %s, call RequestUpdate", path, pull.URL)) + return g.RequestUpdate(ctx, branch, path, mod) } // хотим проверить есть ли пулл реквест для этой ветки, если есть то выходим } @@ -362,6 +361,25 @@ func (g *Gitea) RequestUpdate(ctx context.Context, branch string, path string, m return g.RequestOpen(ctx, branch, path, mod) } +func (g *Gitea) RequestList(ctx context.Context, branch string) (map[string]string, error) { + logger.Debugf(ctx, fmt.Sprintf("RequestList for %s", branch)) + + gPulls, err := GetPulls(ctx, g.URL, g.Owner, g.Repository, g.Token) + if err != nil { + return nil, err + } + + var path string + rMap := make(map[string]string) + + for _, pull := range gPulls { + path = strings.Split(pull.Title, " ")[1] //todo Работет только для дефолтного шаблона + rMap[path] = pull.Title + } + + return rMap, nil +} + func getVersions(s string) string { re := regexp.MustCompile("[vV][0-9]+\\.[0-9]+\\.[0-9]+") diff --git a/internal/source/github/github.go b/internal/source/github/github.go index 9156bb3..6449e20 100644 --- a/internal/source/github/github.go +++ b/internal/source/github/github.go @@ -26,3 +26,6 @@ func (g *Github) RequestClose(ctx context.Context, branch string, path string) e func (g *Github) RequestUpdate(ctx context.Context, branch string, path string, mod modules.Update) error { return nil } +func (g *Github) RequestList(ctx context.Context, branch string) (map[string]string, error) { + return nil, nil +} diff --git a/internal/source/gitlab/gitlab.go b/internal/source/gitlab/gitlab.go index dbc0af2..0167c65 100644 --- a/internal/source/gitlab/gitlab.go +++ b/internal/source/gitlab/gitlab.go @@ -26,3 +26,6 @@ func (g *Gitlab) RequestClose(ctx context.Context, branch string, path string) e func (g *Gitlab) RequestUpdate(ctx context.Context, branch string, path string, mod modules.Update) error { return nil } +func (g *Gitlab) RequestList(ctx context.Context, branch string) (map[string]string, error) { + return nil, nil +} diff --git a/internal/source/gogs/gogs.go b/internal/source/gogs/gogs.go index d7b8fdc..8a8479f 100644 --- a/internal/source/gogs/gogs.go +++ b/internal/source/gogs/gogs.go @@ -26,3 +26,6 @@ func (g *Gogs) RequestClose(ctx context.Context, branch string, path string) err func (g *Gogs) RequestUpdate(ctx context.Context, branch string, path string, mod modules.Update) error { return nil } +func (g *Gogs) RequestList(ctx context.Context, branch string) (map[string]string, error) { + return nil, nil +} diff --git a/internal/source/source.go b/internal/source/source.go index fb6686c..3c3dc65 100644 --- a/internal/source/source.go +++ b/internal/source/source.go @@ -15,6 +15,7 @@ type SourceControl interface { RequestOpen(ctx context.Context, branch string, path string, mod modules.Update) error RequestClose(ctx context.Context, branch string, path string) error RequestUpdate(ctx context.Context, branch string, path string, mod modules.Update) error + RequestList(ctx context.Context, branch string) (map[string]string, error) } func NewSourceControl(cfg configcli.Config) SourceControl {