Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
Василий Толстов 2023-09-23 21:16:26 +03:00
parent eb4daf33f1
commit cfb7cb0f26
61 changed files with 130034 additions and 1053 deletions

4
.gitignore vendored
View File

@ -26,5 +26,7 @@ bin/
.env
tmp/
/pkgdash
cmd/pkgdash/pkgdash
cmd/pkgdashctl/pkgdashctl
*.sqlite
*.db

View File

@ -1,284 +0,0 @@
@angular/animations
MIT
@angular/common
MIT
@angular/core
MIT
@angular/material
MIT
The MIT License
Copyright (c) 2021 Google LLC.
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.
@angular/platform-browser
MIT
@angular/router
MIT
rxjs
Apache-2.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 (c) 2015-2018 Google, Inc., Netflix, Inc., Microsoft Corp. and contributors
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.
tslib
0BSD
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
zone.js
MIT
The MIT License
Copyright (c) 2010-2022 Google LLC. https://angular.io/license
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.

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@ -1 +0,0 @@
(()=>{"use strict";var e,_={},i={};function n(e){var a=i[e];if(void 0!==a)return a.exports;var r=i[e]={exports:{}};return _[e](r,r.exports,n),r.exports}n.m=_,e=[],n.O=(a,r,t,u)=>{if(!r){var o=1/0;for(f=0;f<e.length;f++){for(var[r,t,u]=e[f],s=!0,l=0;l<r.length;l++)(!1&u||o>=u)&&Object.keys(n.O).every(h=>n.O[h](r[l]))?r.splice(l--,1):(s=!1,u<o&&(o=u));if(s){e.splice(f--,1);var c=t();void 0!==c&&(a=c)}}return a}u=u||0;for(var f=e.length;f>0&&e[f-1][2]>u;f--)e[f]=e[f-1];e[f]=[r,t,u]},n.n=e=>{var a=e&&e.__esModule?()=>e.default:()=>e;return n.d(a,{a}),a},n.d=(e,a)=>{for(var r in a)n.o(a,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:a[r]})},n.o=(e,a)=>Object.prototype.hasOwnProperty.call(e,a),(()=>{var e={666:0};n.O.j=t=>0===e[t];var a=(t,u)=>{var l,c,[f,o,s]=u,v=0;if(f.some(d=>0!==e[d])){for(l in o)n.o(o,l)&&(n.m[l]=o[l]);if(s)var b=s(n)}for(t&&t(u);v<f.length;v++)n.o(e,c=f[v])&&e[c]&&e[c][0](),e[c]=0;return n.O(b)},r=self.webpackChunkui=self.webpackChunkui||[];r.forEach(a.bind(null,0)),r.push=a.bind(null,r.push.bind(r))})()})();

View File

@ -0,0 +1,163 @@
/******/ (() => { // webpackBootstrap
/******/ "use strict";
/******/ var __webpack_modules__ = ({});
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = __webpack_modules__;
/******/
/************************************************************************/
/******/ /* webpack/runtime/chunk loaded */
/******/ (() => {
/******/ var deferred = [];
/******/ __webpack_require__.O = (result, chunkIds, fn, priority) => {
/******/ if(chunkIds) {
/******/ priority = priority || 0;
/******/ for(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];
/******/ deferred[i] = [chunkIds, fn, priority];
/******/ return;
/******/ }
/******/ var notFulfilled = Infinity;
/******/ for (var i = 0; i < deferred.length; i++) {
/******/ var [chunkIds, fn, priority] = deferred[i];
/******/ var fulfilled = true;
/******/ for (var j = 0; j < chunkIds.length; j++) {
/******/ if ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every((key) => (__webpack_require__.O[key](chunkIds[j])))) {
/******/ chunkIds.splice(j--, 1);
/******/ } else {
/******/ fulfilled = false;
/******/ if(priority < notFulfilled) notFulfilled = priority;
/******/ }
/******/ }
/******/ if(fulfilled) {
/******/ deferred.splice(i--, 1)
/******/ var r = fn();
/******/ if (r !== undefined) result = r;
/******/ }
/******/ }
/******/ return result;
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/compat get default export */
/******/ (() => {
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = (module) => {
/******/ var getter = module && module.__esModule ?
/******/ () => (module['default']) :
/******/ () => (module);
/******/ __webpack_require__.d(getter, { a: getter });
/******/ return getter;
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/define property getters */
/******/ (() => {
/******/ // define getter functions for harmony exports
/******/ __webpack_require__.d = (exports, definition) => {
/******/ for(var key in definition) {
/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ }
/******/ }
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/ (() => {
/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ })();
/******/
/******/ /* webpack/runtime/make namespace object */
/******/ (() => {
/******/ // define __esModule on exports
/******/ __webpack_require__.r = (exports) => {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/jsonp chunk loading */
/******/ (() => {
/******/ // no baseURI
/******/
/******/ // object to store loaded and loading chunks
/******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched
/******/ // [resolve, reject, Promise] = chunk loading, 0 = chunk loaded
/******/ var installedChunks = {
/******/ "runtime": 0
/******/ };
/******/
/******/ // no chunk on demand loading
/******/
/******/ // no prefetching
/******/
/******/ // no preloaded
/******/
/******/ // no HMR
/******/
/******/ // no HMR manifest
/******/
/******/ __webpack_require__.O.j = (chunkId) => (installedChunks[chunkId] === 0);
/******/
/******/ // install a JSONP callback for chunk loading
/******/ var webpackJsonpCallback = (parentChunkLoadingFunction, data) => {
/******/ var [chunkIds, moreModules, runtime] = data;
/******/ // add "moreModules" to the modules object,
/******/ // then flag all "chunkIds" as loaded and fire callback
/******/ var moduleId, chunkId, i = 0;
/******/ if(chunkIds.some((id) => (installedChunks[id] !== 0))) {
/******/ for(moduleId in moreModules) {
/******/ if(__webpack_require__.o(moreModules, moduleId)) {
/******/ __webpack_require__.m[moduleId] = moreModules[moduleId];
/******/ }
/******/ }
/******/ if(runtime) var result = runtime(__webpack_require__);
/******/ }
/******/ if(parentChunkLoadingFunction) parentChunkLoadingFunction(data);
/******/ for(;i < chunkIds.length; i++) {
/******/ chunkId = chunkIds[i];
/******/ if(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {
/******/ installedChunks[chunkId][0]();
/******/ }
/******/ installedChunks[chunkId] = 0;
/******/ }
/******/ return __webpack_require__.O(result);
/******/ }
/******/
/******/ var chunkLoadingGlobal = self["webpackChunkui"] = self["webpackChunkui"] || [];
/******/ chunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));
/******/ chunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));
/******/ })();
/******/
/************************************************************************/
/******/
/******/
/******/ })()
;
//# sourceMappingURL=runtime.js.map

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

121153
cmd/pkgdash/assets/ui/vendor.js Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

177
cmd/pkgdashctl/main.go Normal file
View File

@ -0,0 +1,177 @@
package main
import (
"bytes"
"context"
"fmt"
"os"
"path/filepath"
"text/template"
"git.unistack.org/unistack-org/pkgdash/internal/modules"
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/options"
"golang.org/x/mod/modfile"
"golang.org/x/mod/module"
)
// https://docs.github.com/ru/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
var (
DefaultPullRequestTitle = `Bump {{.Name}} from {{.VersionOld}} to {{.VersionNew}}`
DefaultPullRequestBody = `Bumps {{.Name}} from {{.VersionOld}} to {{.VersionNew}}.`
)
type Config struct {
PullRequestTitle string `json:"pull_request_title" yaml:"pull_request_title"`
PullRequestBody string `json:"pull_request_body" yaml:"pull_request_body"`
}
var (
configFiles = []string{
"dependabot.yml",
"pkgdash.yml",
"pkgdash.yaml",
}
configDirs = []string{
".gitea",
".github",
".gitlab",
}
repoMgmt = map[string]string{
".gitea": "gitea",
".gogs": "gogs",
".github": "github",
".gitlab": "gitlab",
}
)
type Data struct {
Modules []module.Version
}
func main() {
var err error
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cfg := &Config{}
if err = config.Load(ctx,
[]config.Config{
config.NewConfig(
config.Struct(cfg),
),
envconfig.NewConfig(
config.Struct(cfg),
),
},
config.LoadOverride(true),
); err != nil {
logger.Fatalf(ctx, "failed to load config: %v", err)
}
for _, configDir := range configDirs {
for _, configFile := range configFiles {
c := fileconfig.NewConfig(
config.AllowFail(true),
config.Struct(cfg),
options.Codec(yamlcodec.NewCodec()),
fileconfig.Path(filepath.Join(configDir, configFile)),
)
if err = c.Load(ctx, config.LoadOverride(true)); err != nil {
logger.Fatalf(ctx, "failed to load config: %v", err)
}
}
}
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: false,
Major: false,
Cached: true,
OnUpdate: func(u modules.Update) {
if u.Err != nil {
logger.Errorf(ctx, "%s: failed: %v", u.Module.Path, u.Err)
return
}
mvs[u.Module.Path] = u
},
}
for _, req := range mfile.Require {
updateOptions.Modules = append(updateOptions.Modules, req.Mod)
}
modules.Updates(updateOptions)
data := &Data{Modules: updateOptions.Modules}
tplTitle, err := template.New("pull_request_title").Parse(cfg.PullRequestTitle)
if err != nil {
logger.Fatalf(ctx, "failed to parse template: %v", err)
}
wTitle := bytes.NewBuffer(nil)
if err = tplTitle.Execute(wTitle, data); err != nil {
logger.Fatalf(ctx, "failed to execute template: %v", err)
}
tplBody, err := template.New("pull_request_title").Parse(cfg.PullRequestTitle)
if err != nil {
logger.Fatalf(ctx, "failed to parse template: %v", err)
}
wBody := bytes.NewBuffer(nil)
if err = tplBody.Execute(wBody, data); err != nil {
logger.Fatalf(ctx, "failed to execute template: %v", err)
}
for path, u := range mvs {
fmt.Printf("%s from %s to %s\n", path, u.Module.Version, u.Version)
}
}
func getRepoMgmt() string {
for _, configDir := range configDirs {
_, err := os.Stat(configDir)
if err != nil {
continue
}
if name, ok := repoMgmt[configDir]; ok {
return name
}
}
return "unknown"
}
func giteaPullRequest(mods []module.Version) {
}

Binary file not shown.

View File

@ -1,4 +1,5 @@
drop table if exists packages;
drop table if exists modules;
drop table if exists issues;
drop table if exists comments;
drop table if exists comments;
drop table if exists handlers;

View File

@ -15,11 +15,18 @@ create table if not exists issues (
updated timestamp not null default current_timestamp
);
create table if not exists handlers (
id integer primary key autoincrement not null,
package integer not null,
name varchar,
coverage number default 0
);
create table if not exists packages (
id integer primary key autoincrement not null,
name varchar not null,
url varchar not null,
desc varchar,
description varchar,
modules integer default 0,
issues integer default 0,
comments integer default 0,

View File

@ -0,0 +1,28 @@
package handler
import (
"context"
"net/http"
"git.unistack.org/unistack-org/pkgdash/internal/models"
pb "git.unistack.org/unistack-org/pkgdash/proto"
httpsrv "go.unistack.org/micro-server-http/v4"
"go.unistack.org/micro/v4/logger"
)
func (h *Handler) HandlerList(ctx context.Context, req *pb.HandlerListReq, rsp *pb.HandlerListRsp) error {
logger.Debug(ctx, "HandlerList handler start")
packages, err := h.store.HandlerList(ctx, req)
if err != nil {
logger.Errorf(ctx, "error db response: %v", err)
httpsrv.SetRspCode(ctx, http.StatusInternalServerError)
return httpsrv.SetError(NewInternalError(err))
}
for _, hdlr := range packages {
rsp.Handlers = append(rsp.Handlers, models.NewHandler(hdlr))
}
logger.Debug(ctx, "HandlerList handler stop")
return nil
}

View File

@ -8,20 +8,48 @@ import (
"google.golang.org/protobuf/types/known/timestamppb"
)
type Handler struct {
ID uint64 `db:"id"`
Package uint64 `db:"package"`
Name string `db:"name"`
Coverage sql.NullFloat64 `db:"coverage"`
}
func NewHandler(hdlr *Handler) *pb.Handler {
if hdlr == nil {
return nil
}
rsp := &pb.Handler{
Id: hdlr.ID,
Package: hdlr.Package,
Name: hdlr.Name,
}
if hdlr.Coverage.Valid {
rsp.Coverage = hdlr.Coverage.Float64
}
return rsp
}
type Package struct {
LastCheck sql.NullTime `db:"last_check"`
Created time.Time `db:"created"`
Updated time.Time `db:"updated"`
Name string `db:"name"`
URL string `db:"url"`
Modules uint64 `db:"modules"`
Issues uint64 `db:"issues"`
Comments uint64 `db:"comments"`
ID uint64 `db:"id"`
Status uint64 `db:"status"`
Created time.Time `db:"created"`
Updated time.Time `db:"updated"`
LastCheck sql.NullTime `db:"last_check"`
Type string `db:"type"`
Name string `db:"name"`
URL string `db:"url"`
Description sql.NullString `db:"description"`
Coverage sql.NullFloat64 `db:"coverage"`
Modules uint64 `db:"modules"`
ID uint64 `db:"id"`
Status uint64 `db:"status"`
Comments uint64 `db:"comments"`
Issues uint64 `db:"issues"`
}
func NewPackage(pkg *Package) *pb.Package {
if pkg == nil {
return nil
}
rsp := &pb.Package{
Name: pkg.Name,
Url: pkg.URL,
@ -31,10 +59,20 @@ func NewPackage(pkg *Package) *pb.Package {
Id: pkg.ID,
Created: timestamppb.New(pkg.Created),
Updated: timestamppb.New(pkg.Updated),
Type: pkg.Type,
}
if rsp.Type == "" {
rsp.Type = "package"
}
if pkg.Description.Valid {
rsp.Description = pkg.Description.String
}
if pkg.LastCheck.Valid {
rsp.LastCheck = timestamppb.New(pkg.LastCheck.Time)
}
if pkg.Coverage.Valid {
rsp.Coverage = pkg.Coverage.Float64
}
return rsp
}
@ -46,6 +84,9 @@ type Module struct {
}
func NewModule(mod *Module) *pb.Module {
if mod == nil {
return nil
}
rsp := &pb.Module{
Name: mod.Name,
Version: mod.Version,
@ -73,6 +114,9 @@ type Comment struct {
}
func NewComment(com *Comment) *pb.Comment {
if com == nil {
return nil
}
return &pb.Comment{
Id: com.ID,
Comment: com.Comment,

View File

@ -1,6 +1,7 @@
package sqlite
const (
queryPackageModulesCount = `update packages set modules = $2 where id = $1;`
queryPackagesModulesCreate = `insert into packages_modules as pm (package, module) values ($1, $2) on conflict (package,module) do nothing;`
queryPackagesUpdateLastCheck = `update packages set last_check = CURRENT_TIMESTAMP where id = $1;`
queryPackagesModules = `select modules.id, modules.name, modules.version from modules left join packages_modules on modules.id = packages_modules.module left join packages on packages.id = packages_modules.package where packages_modules.package = $1;`
@ -13,5 +14,6 @@ const (
queryPackagesCreate = `insert into packages as p (name, url) values ($1, $2) on conflict (url) do update set name = p.name returning *;`
queryModulesList = `select id, name, version from modules;`
queryModulesCreate = `insert into modules as m (name, version) values ($1, $2) on conflict (name,version) do update set last_check = CURRENT_TIMESTAMP returning *;`
queryCommentsList = `select id, text, created, updated from comments;`
queryCommentsList = `select id, text, created, updated from comments where package = $1;`
queryHandlersList = `select id, name, coverage from handlers where package = $1;`
)

View File

@ -2,6 +2,7 @@ package sqlite
import (
"context"
"database/sql"
"fmt"
"time"
@ -48,6 +49,12 @@ func (s *Sqlite) PackageModulesCreate(ctx context.Context, pkg *models.Package,
}
_, err = tx.ExecContext(ctx, queryPackageModulesCount, pkg.ID, len(modules))
if err != nil {
_ = tx.Rollback()
return err
}
if err = tx.Commit(); err != nil {
_ = tx.Rollback()
return err
@ -69,6 +76,9 @@ func (s *Sqlite) PackageLookup(ctx context.Context, req *pb.PackageLookupReq) (*
err := s.db.GetContext(ctx, pkg, queryPackagesLookup, req.Id)
if err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
return nil, err
}
@ -80,6 +90,9 @@ func (s *Sqlite) PackageList(ctx context.Context, req *pb.PackageListReq) ([]*mo
err := s.db.SelectContext(ctx, &packages, queryPackagesList)
if err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
return nil, err
}
@ -91,6 +104,9 @@ func (s *Sqlite) PackageModules(ctx context.Context, req *pb.PackageModulesReq)
err := s.db.SelectContext(ctx, &modules, queryPackagesModules, req.Package)
if err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
return nil, err
}
@ -201,6 +217,9 @@ func (s *Sqlite) ModuleList(ctx context.Context, req *pb.ModuleListReq) ([]*mode
err := s.db.SelectContext(ctx, &modules, queryModulesList)
if err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
return nil, err
}
@ -210,10 +229,27 @@ func (s *Sqlite) ModuleList(ctx context.Context, req *pb.ModuleListReq) ([]*mode
func (s *Sqlite) CommentList(ctx context.Context, req *pb.CommentListReq) ([]*models.Comment, error) {
var comments []*models.Comment
err := s.db.SelectContext(ctx, &comments, queryCommentsList, req.PackageId)
err := s.db.SelectContext(ctx, &comments, queryCommentsList, req.Package)
if err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
return nil, err
}
return comments, nil
}
func (s *Sqlite) HandlerList(ctx context.Context, req *pb.HandlerListReq) ([]*models.Handler, error) {
var handlers []*models.Handler
err := s.db.SelectContext(ctx, &handlers, queryHandlersList, req.Package)
if err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
return nil, err
}
return handlers, nil
}

View File

@ -23,6 +23,7 @@ type Storage interface {
ModulesProcess(ctx context.Context, td time.Duration) ([]*models.Module, error)
PackagesProcess(ctx context.Context, td time.Duration) ([]*models.Package, error)
PackageCreate(ctx context.Context, req *pb.PackageCreateReq) (*models.Package, error)
HandlerList(ctx context.Context, req *pb.HandlerListReq) ([]*models.Handler, error)
PackageList(ctx context.Context, req *pb.PackageListReq) ([]*models.Package, error)
PackageLookup(ctx context.Context, req *pb.PackageLookupReq) (*models.Package, error)
PackageUpdate(ctx context.Context, req *pb.PackageUpdateReq) (*models.Package, error)

View File

@ -5,7 +5,7 @@ info:
title: Pkgdash API
version: 0.0.1
paths:
/v1/comments/{id}/comments:
/v1/comments/{id}:
get:
tags:
- Pkgdash
@ -17,7 +17,7 @@ paths:
schema:
type: integer
format: uint64
- name: package_id
- name: package
in: query
schema:
type: integer
@ -40,6 +40,12 @@ paths:
tags:
- Pkgdash
operationId: ModuleList
parameters:
- name: package
in: query
schema:
type: integer
format: uint64
responses:
default:
description: Default
@ -213,10 +219,6 @@ paths:
- name: package
in: path
required: true
schema:
type: string
- name: package_id
in: query
schema:
type: integer
format: uint64
@ -262,6 +264,31 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/CommentCreateRsp'
/v1/packages/{package}/handlers:
get:
tags:
- Pkgdash
operationId: HandlerList
parameters:
- name: package
in: path
required: true
schema:
type: integer
format: uint64
responses:
default:
description: Default
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorRsp'
"200":
description: OK
content:
application/json:
schema:
$ref: '#/components/schemas/HandlerListRsp'
/v1/packages/{package}/modules:
get:
tags:
@ -345,6 +372,27 @@ components:
type: string
details:
type: string
Handler:
type: object
properties:
id:
type: integer
format: uint64
package:
type: integer
format: uint64
name:
type: string
coverage:
type: number
format: double
HandlerListRsp:
type: object
properties:
handlers:
type: array
items:
$ref: '#/components/schemas/Handler'
Module:
type: object
properties:
@ -386,6 +434,9 @@ components:
comments:
type: integer
format: uint64
handlers:
type: integer
format: uint64
created:
type: string
format: RFC3339
@ -395,6 +446,11 @@ components:
last_check:
type: string
format: RFC3339
type:
type: string
coverage:
type: number
format: double
PackageCreateReq:
type: object
properties:
@ -402,11 +458,8 @@ components:
type: string
url:
type: string
modules:
type: array
items:
type: integer
format: uint64
description:
type: string
PackageCreateRsp:
type: object
properties:
@ -454,6 +507,9 @@ components:
items:
type: integer
format: uint64
coverprofile:
type: string
format: bytes
PackageUpdateRsp:
type: object
properties:

File diff suppressed because it is too large Load Diff

View File

@ -35,6 +35,240 @@ var (
_ = sort.Sort
)
// Validate checks the field values on HandlerListReq with the rules defined in
// the proto definition for this message. If any rules are violated, the first
// error encountered is returned, or nil if there are no violations.
func (m *HandlerListReq) Validate() error {
return m.validate(false)
}
// ValidateAll checks the field values on HandlerListReq with the rules defined
// in the proto definition for this message. If any rules are violated, the
// result is a list of violation errors wrapped in HandlerListReqMultiError,
// or nil if none found.
func (m *HandlerListReq) ValidateAll() error {
return m.validate(true)
}
func (m *HandlerListReq) validate(all bool) error {
if m == nil {
return nil
}
var errors []error
// no validation rules for Package
if len(errors) > 0 {
return HandlerListReqMultiError(errors)
}
return nil
}
// HandlerListReqMultiError is an error wrapping multiple validation errors
// returned by HandlerListReq.ValidateAll() if the designated constraints
// aren't met.
type HandlerListReqMultiError []error
// Error returns a concatenation of all the error messages it wraps.
func (m HandlerListReqMultiError) Error() string {
var msgs []string
for _, err := range m {
msgs = append(msgs, err.Error())
}
return strings.Join(msgs, "; ")
}
// AllErrors returns a list of validation violation errors.
func (m HandlerListReqMultiError) AllErrors() []error { return m }
// HandlerListReqValidationError is the validation error returned by
// HandlerListReq.Validate if the designated constraints aren't met.
type HandlerListReqValidationError struct {
field string
reason string
cause error
key bool
}
// Field function returns field value.
func (e HandlerListReqValidationError) Field() string { return e.field }
// Reason function returns reason value.
func (e HandlerListReqValidationError) Reason() string { return e.reason }
// Cause function returns cause value.
func (e HandlerListReqValidationError) Cause() error { return e.cause }
// Key function returns key value.
func (e HandlerListReqValidationError) Key() bool { return e.key }
// ErrorName returns error name.
func (e HandlerListReqValidationError) ErrorName() string { return "HandlerListReqValidationError" }
// Error satisfies the builtin error interface
func (e HandlerListReqValidationError) Error() string {
cause := ""
if e.cause != nil {
cause = fmt.Sprintf(" | caused by: %v", e.cause)
}
key := ""
if e.key {
key = "key for "
}
return fmt.Sprintf(
"invalid %sHandlerListReq.%s: %s%s",
key,
e.field,
e.reason,
cause)
}
var _ error = HandlerListReqValidationError{}
var _ interface {
Field() string
Reason() string
Key() bool
Cause() error
ErrorName() string
} = HandlerListReqValidationError{}
// Validate checks the field values on HandlerListRsp with the rules defined in
// the proto definition for this message. If any rules are violated, the first
// error encountered is returned, or nil if there are no violations.
func (m *HandlerListRsp) Validate() error {
return m.validate(false)
}
// ValidateAll checks the field values on HandlerListRsp with the rules defined
// in the proto definition for this message. If any rules are violated, the
// result is a list of violation errors wrapped in HandlerListRspMultiError,
// or nil if none found.
func (m *HandlerListRsp) ValidateAll() error {
return m.validate(true)
}
func (m *HandlerListRsp) validate(all bool) error {
if m == nil {
return nil
}
var errors []error
for idx, item := range m.GetHandlers() {
_, _ = idx, item
if all {
switch v := interface{}(item).(type) {
case interface{ ValidateAll() error }:
if err := v.ValidateAll(); err != nil {
errors = append(errors, HandlerListRspValidationError{
field: fmt.Sprintf("Handlers[%v]", idx),
reason: "embedded message failed validation",
cause: err,
})
}
case interface{ Validate() error }:
if err := v.Validate(); err != nil {
errors = append(errors, HandlerListRspValidationError{
field: fmt.Sprintf("Handlers[%v]", idx),
reason: "embedded message failed validation",
cause: err,
})
}
}
} else if v, ok := interface{}(item).(interface{ Validate() error }); ok {
if err := v.Validate(); err != nil {
return HandlerListRspValidationError{
field: fmt.Sprintf("Handlers[%v]", idx),
reason: "embedded message failed validation",
cause: err,
}
}
}
}
if len(errors) > 0 {
return HandlerListRspMultiError(errors)
}
return nil
}
// HandlerListRspMultiError is an error wrapping multiple validation errors
// returned by HandlerListRsp.ValidateAll() if the designated constraints
// aren't met.
type HandlerListRspMultiError []error
// Error returns a concatenation of all the error messages it wraps.
func (m HandlerListRspMultiError) Error() string {
var msgs []string
for _, err := range m {
msgs = append(msgs, err.Error())
}
return strings.Join(msgs, "; ")
}
// AllErrors returns a list of validation violation errors.
func (m HandlerListRspMultiError) AllErrors() []error { return m }
// HandlerListRspValidationError is the validation error returned by
// HandlerListRsp.Validate if the designated constraints aren't met.
type HandlerListRspValidationError struct {
field string
reason string
cause error
key bool
}
// Field function returns field value.
func (e HandlerListRspValidationError) Field() string { return e.field }
// Reason function returns reason value.
func (e HandlerListRspValidationError) Reason() string { return e.reason }
// Cause function returns cause value.
func (e HandlerListRspValidationError) Cause() error { return e.cause }
// Key function returns key value.
func (e HandlerListRspValidationError) Key() bool { return e.key }
// ErrorName returns error name.
func (e HandlerListRspValidationError) ErrorName() string { return "HandlerListRspValidationError" }
// Error satisfies the builtin error interface
func (e HandlerListRspValidationError) Error() string {
cause := ""
if e.cause != nil {
cause = fmt.Sprintf(" | caused by: %v", e.cause)
}
key := ""
if e.key {
key = "key for "
}
return fmt.Sprintf(
"invalid %sHandlerListRsp.%s: %s%s",
key,
e.field,
e.reason,
cause)
}
var _ error = HandlerListRspValidationError{}
var _ interface {
Field() string
Reason() string
Key() bool
Cause() error
ErrorName() string
} = HandlerListRspValidationError{}
// Validate checks the field values on PackageModulesReq with the rules defined
// in the proto definition for this message. If any rules are violated, the
// first error encountered is returned, or nil if there are no violations.
@ -679,6 +913,8 @@ func (m *Package) validate(all bool) error {
// no validation rules for Comments
// no validation rules for Handlers
if all {
switch v := interface{}(m.GetCreated()).(type) {
case interface{ ValidateAll() error }:
@ -766,6 +1002,10 @@ func (m *Package) validate(all bool) error {
}
}
// no validation rules for Type
// no validation rules for Coverage
if len(errors) > 0 {
return PackageMultiError(errors)
}
@ -842,6 +1082,138 @@ var _ interface {
ErrorName() string
} = PackageValidationError{}
// Validate checks the field values on Handler with the rules defined in the
// proto definition for this message. If any rules are violated, the first
// error encountered is returned, or nil if there are no violations.
func (m *Handler) Validate() error {
return m.validate(false)
}
// ValidateAll checks the field values on Handler with the rules defined in the
// proto definition for this message. If any rules are violated, the result is
// a list of violation errors wrapped in HandlerMultiError, or nil if none found.
func (m *Handler) ValidateAll() error {
return m.validate(true)
}
func (m *Handler) validate(all bool) error {
if m == nil {
return nil
}
var errors []error
if m.GetId() <= 0 {
err := HandlerValidationError{
field: "Id",
reason: "value must be greater than 0",
}
if !all {
return err
}
errors = append(errors, err)
}
if m.GetPackage() <= 0 {
err := HandlerValidationError{
field: "Package",
reason: "value must be greater than 0",
}
if !all {
return err
}
errors = append(errors, err)
}
if utf8.RuneCountInString(m.GetName()) < 1 {
err := HandlerValidationError{
field: "Name",
reason: "value length must be at least 1 runes",
}
if !all {
return err
}
errors = append(errors, err)
}
// no validation rules for Coverage
if len(errors) > 0 {
return HandlerMultiError(errors)
}
return nil
}
// HandlerMultiError is an error wrapping multiple validation errors returned
// by Handler.ValidateAll() if the designated constraints aren't met.
type HandlerMultiError []error
// Error returns a concatenation of all the error messages it wraps.
func (m HandlerMultiError) Error() string {
var msgs []string
for _, err := range m {
msgs = append(msgs, err.Error())
}
return strings.Join(msgs, "; ")
}
// AllErrors returns a list of validation violation errors.
func (m HandlerMultiError) AllErrors() []error { return m }
// HandlerValidationError is the validation error returned by Handler.Validate
// if the designated constraints aren't met.
type HandlerValidationError struct {
field string
reason string
cause error
key bool
}
// Field function returns field value.
func (e HandlerValidationError) Field() string { return e.field }
// Reason function returns reason value.
func (e HandlerValidationError) Reason() string { return e.reason }
// Cause function returns cause value.
func (e HandlerValidationError) Cause() error { return e.cause }
// Key function returns key value.
func (e HandlerValidationError) Key() bool { return e.key }
// ErrorName returns error name.
func (e HandlerValidationError) ErrorName() string { return "HandlerValidationError" }
// Error satisfies the builtin error interface
func (e HandlerValidationError) Error() string {
cause := ""
if e.cause != nil {
cause = fmt.Sprintf(" | caused by: %v", e.cause)
}
key := ""
if e.key {
key = "key for "
}
return fmt.Sprintf(
"invalid %sHandler.%s: %s%s",
key,
e.field,
e.reason,
cause)
}
var _ error = HandlerValidationError{}
var _ interface {
Field() string
Reason() string
Key() bool
Cause() error
ErrorName() string
} = HandlerValidationError{}
// Validate checks the field values on Module with the rules defined in the
// proto definition for this message. If any rules are violated, the first
// error encountered is returned, or nil if there are no violations.
@ -2068,6 +2440,8 @@ func (m *PackageUpdateReq) validate(all bool) error {
errors = append(errors, err)
}
// no validation rules for Coverprofile
if len(errors) > 0 {
return PackageUpdateReqMultiError(errors)
}
@ -2557,6 +2931,8 @@ func (m *PackageCreateReq) validate(all bool) error {
errors = append(errors, err)
}
// no validation rules for Description
if len(errors) > 0 {
return PackageCreateReqMultiError(errors)
}
@ -2784,6 +3160,8 @@ func (m *ModuleListReq) validate(all bool) error {
var errors []error
// no validation rules for Package
if len(errors) > 0 {
return ModuleListReqMultiError(errors)
}
@ -3016,7 +3394,7 @@ func (m *CommentListReq) validate(all bool) error {
var errors []error
// no validation rules for PackageId
// no validation rules for Package
if len(errors) > 0 {
return CommentListReqMultiError(errors)
@ -3252,7 +3630,7 @@ func (m *CommentLookupReq) validate(all bool) error {
// no validation rules for Id
// no validation rules for PackageId
// no validation rules for Package
if len(errors) > 0 {
return CommentLookupReqMultiError(errors)

View File

@ -19,9 +19,7 @@ service Pkgdash {
};
};
};
option (micro.api.http) = {
get: "/v1/packages/{id}";
};
option (micro.api.http) = {get: "/v1/packages/{id}"};
}
rpc PackageCreate(PackageCreateReq) returns (PackageCreateRsp) {
option (micro.openapiv3.openapiv3_operation) = {
@ -59,6 +57,17 @@ service Pkgdash {
};
option (micro.api.http) = {get: "/v1/packages"};
}
rpc HandlerList(HandlerListReq) returns (HandlerListRsp) {
option (micro.openapiv3.openapiv3_operation) = {
operation_id: "HandlerList";
responses: {
default: {
reference: {_ref: ".pkgdash.ErrorRsp"};
};
};
};
option (micro.api.http) = {get: "/v1/packages/{package}/handlers"};
}
rpc PackageModules(PackageModulesReq) returns (PackageModulesRsp) {
option (micro.openapiv3.openapiv3_operation) = {
operation_id: "PackageModules";
@ -108,7 +117,7 @@ service Pkgdash {
};
};
option (micro.api.http) = {
get: "/v1/comments/{id}/comments";
get: "/v1/comments/{id}";
additional_bindings {get: "/v1/comments/{package}/comments/{id}"};
};
}
@ -150,6 +159,14 @@ service Pkgdash {
}
}
message HandlerListReq {
uint64 package = 1;
}
message HandlerListRsp {
repeated Handler handlers = 1;
}
message PackageModulesReq {
uint64 package = 1 [json_name = "package"];
}
@ -181,9 +198,19 @@ message Package {
uint64 modules = 5;
uint64 issues = 6;
uint64 comments = 7;
google.protobuf.Timestamp created = 8;
google.protobuf.Timestamp updated = 9;
google.protobuf.Timestamp last_check = 10;
uint64 handlers = 8;
google.protobuf.Timestamp created = 9;
google.protobuf.Timestamp updated = 10;
google.protobuf.Timestamp last_check = 11;
string type = 12;
double coverage = 13;
}
message Handler {
uint64 id = 1 [(validate.rules).uint64.gt = 0];
uint64 package = 2 [(validate.rules).uint64.gt = 0];
string name = 3 [(validate.rules).string.min_len = 1];
double coverage = 4;
}
message Module {
@ -236,6 +263,7 @@ message PackageUpdateReq {
string url = 3 [(validate.rules).string.min_len = 1];
repeated uint64 modules = 4;
repeated uint64 issues = 5;
bytes coverprofile = 6;
}
message PackageUpdateRsp {
@ -257,21 +285,23 @@ message CommentCreateRsp {
message PackageCreateReq {
string name = 1 [(validate.rules).string.min_len = 1];
string url = 2 [(validate.rules).string.min_len = 1];
repeated uint64 modules = 3;
string description = 3;
}
message PackageCreateRsp {
Package package = 1 [json_name="package"];
Package package = 1 [json_name = "package"];
}
message ModuleListReq {}
message ModuleListReq {
uint64 package = 1 [json_name = "package"];
}
message ModuleListRsp {
repeated Module modules = 1 [json_name="modules"];
repeated Module modules = 1 [json_name = "modules"];
}
message CommentListReq {
uint64 package_id = 1 [json_name = "package_id"];
uint64 package = 1 [json_name = "package"];
}
message CommentListRsp {
@ -280,7 +310,7 @@ message CommentListRsp {
message CommentLookupReq {
uint64 id = 1 [json_name = "id"];
uint64 package_id = 2 [json_name = "package_id"];
uint64 package = 2 [json_name = "package"];
}
message CommentLookupRsp {

View File

@ -1,7 +1,7 @@
// Code generated by protoc-gen-go-micro. DO NOT EDIT.
// versions:
// - protoc-gen-go-micro v4.0.2
// - protoc v4.23.4
// - protoc v4.24.3
// source: pkgdash.proto
package pkgdashpb
@ -21,6 +21,7 @@ type PkgdashServiceClient interface {
PackageCreate(ctx context.Context, req *PackageCreateReq, opts ...options.Option) (*PackageCreateRsp, error)
PackageDelete(ctx context.Context, req *PackageDeleteReq, opts ...options.Option) (*PackageDeleteRsp, error)
PackageList(ctx context.Context, req *PackageListReq, opts ...options.Option) (*PackageListRsp, error)
HandlerList(ctx context.Context, req *HandlerListReq, opts ...options.Option) (*HandlerListRsp, error)
PackageModules(ctx context.Context, req *PackageModulesReq, opts ...options.Option) (*PackageModulesRsp, error)
PackageUpdate(ctx context.Context, req *PackageUpdateReq, opts ...options.Option) (*PackageUpdateRsp, error)
CommentCreate(ctx context.Context, req *CommentCreateReq, opts ...options.Option) (*CommentCreateRsp, error)
@ -35,6 +36,7 @@ type PkgdashServiceServer interface {
PackageCreate(ctx context.Context, req *PackageCreateReq, rsp *PackageCreateRsp) error
PackageDelete(ctx context.Context, req *PackageDeleteReq, rsp *PackageDeleteRsp) error
PackageList(ctx context.Context, req *PackageListReq, rsp *PackageListRsp) error
HandlerList(ctx context.Context, req *HandlerListReq, rsp *HandlerListRsp) error
PackageModules(ctx context.Context, req *PackageModulesReq, rsp *PackageModulesRsp) error
PackageUpdate(ctx context.Context, req *PackageUpdateReq, rsp *PackageUpdateRsp) error
CommentCreate(ctx context.Context, req *CommentCreateReq, rsp *CommentCreateRsp) error

View File

@ -44,6 +44,13 @@ var (
Body: "",
Stream: false,
},
{
Name: "PkgdashService.HandlerList",
Path: "/v1/packages/{package}/handlers",
Method: "GET",
Body: "",
Stream: false,
},
{
Name: "PkgdashService.PackageModules",
Path: "/v1/packages/{package}/modules",
@ -67,7 +74,7 @@ var (
},
{
Name: "PkgdashService.CommentLookup",
Path: "/v1/comments/{id}/comments",
Path: "/v1/comments/{id}",
Method: "GET",
Body: "",
Stream: false,
@ -192,6 +199,24 @@ func (c *pkgdashServiceClient) PackageList(ctx context.Context, req *PackageList
return rsp, nil
}
func (c *pkgdashServiceClient) HandlerList(ctx context.Context, req *HandlerListReq, opts ...options.Option) (*HandlerListRsp, error) {
errmap := make(map[string]interface{}, 1)
errmap["default"] = &ErrorRsp{}
opts = append(opts,
v41.ErrorMap(errmap),
)
opts = append(opts,
v41.Method(http.MethodGet),
v41.Path("/v1/packages/{package}/handlers"),
)
rsp := &HandlerListRsp{}
err := c.c.Call(ctx, c.c.NewRequest(c.name, "PkgdashService.HandlerList", req), rsp, opts...)
if err != nil {
return nil, err
}
return rsp, nil
}
func (c *pkgdashServiceClient) PackageModules(ctx context.Context, req *PackageModulesReq, opts ...options.Option) (*PackageModulesRsp, error) {
errmap := make(map[string]interface{}, 1)
errmap["default"] = &ErrorRsp{}
@ -256,7 +281,7 @@ func (c *pkgdashServiceClient) CommentLookup(ctx context.Context, req *CommentLo
)
opts = append(opts,
v41.Method(http.MethodGet),
v41.Path("/v1/comments/{id}/comments"),
v41.Path("/v1/comments/{id}"),
)
rsp := &CommentLookupRsp{}
err := c.c.Call(ctx, c.c.NewRequest(c.name, "PkgdashService.CommentLookup", req), rsp, opts...)
@ -340,6 +365,10 @@ func (h *pkgdashServiceServer) PackageList(ctx context.Context, req *PackageList
return h.PkgdashServiceServer.PackageList(ctx, req, rsp)
}
func (h *pkgdashServiceServer) HandlerList(ctx context.Context, req *HandlerListReq, rsp *HandlerListRsp) error {
return h.PkgdashServiceServer.HandlerList(ctx, req, rsp)
}
func (h *pkgdashServiceServer) PackageModules(ctx context.Context, req *PackageModulesReq, rsp *PackageModulesRsp) error {
return h.PkgdashServiceServer.PackageModules(ctx, req, rsp)
}
@ -374,6 +403,7 @@ func RegisterPkgdashServiceServer(s server.Server, sh PkgdashServiceServer, opts
PackageCreate(ctx context.Context, req *PackageCreateReq, rsp *PackageCreateRsp) error
PackageDelete(ctx context.Context, req *PackageDeleteReq, rsp *PackageDeleteRsp) error
PackageList(ctx context.Context, req *PackageListReq, rsp *PackageListRsp) error
HandlerList(ctx context.Context, req *HandlerListReq, rsp *HandlerListRsp) error
PackageModules(ctx context.Context, req *PackageModulesReq, rsp *PackageModulesRsp) error
PackageUpdate(ctx context.Context, req *PackageUpdateReq, rsp *PackageUpdateRsp) error
CommentCreate(ctx context.Context, req *CommentCreateReq, rsp *CommentCreateRsp) error

View File

@ -5,6 +5,7 @@
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"devbuild": "ng build --configuration development",
"watch": "ng build --watch --configuration development",
"test": "ng test"
},

View File

@ -7,6 +7,8 @@ export { CommentDeleteRsp } from './models/comment-delete-rsp';
export { CommentListRsp } from './models/comment-list-rsp';
export { CommentLookupRsp } from './models/comment-lookup-rsp';
export { ErrorRsp } from './models/error-rsp';
export { Handler } from './models/handler';
export { HandlerListRsp } from './models/handler-list-rsp';
export { Module } from './models/module';
export { ModuleListRsp } from './models/module-list-rsp';
export { Package } from './models/package';

View File

@ -0,0 +1,6 @@
/* tslint:disable */
/* eslint-disable */
import { Handler } from './handler';
export interface HandlerListRsp {
handlers?: Array<Handler>;
}

View File

@ -0,0 +1,8 @@
/* tslint:disable */
/* eslint-disable */
export interface Handler {
coverage?: number;
id?: number;
name?: string;
package?: number;
}

View File

@ -1,7 +1,7 @@
/* tslint:disable */
/* eslint-disable */
export interface PackageCreateReq {
modules?: Array<number>;
description?: string;
name?: string;
url?: string;
}

View File

@ -1,6 +1,7 @@
/* tslint:disable */
/* eslint-disable */
export interface PackageUpdateReq {
coverprofile?: string;
id?: number;
issues?: Array<number>;
modules?: Array<number>;

View File

@ -2,13 +2,16 @@
/* eslint-disable */
export interface Package {
comments?: number;
coverage?: number;
created?: string;
description?: string;
handlers?: number;
id?: number;
issues?: number;
last_check?: string;
modules?: number;
name?: string;
type?: string;
updated?: string;
url?: string;
}

View File

@ -15,6 +15,7 @@ import { CommentCreateRsp } from '../models/comment-create-rsp';
import { CommentDeleteRsp } from '../models/comment-delete-rsp';
import { CommentListRsp } from '../models/comment-list-rsp';
import { CommentLookupRsp } from '../models/comment-lookup-rsp';
import { HandlerListRsp } from '../models/handler-list-rsp';
import { ModuleListRsp } from '../models/module-list-rsp';
import { PackageCreateReq } from '../models/package-create-req';
import { PackageCreateRsp } from '../models/package-create-rsp';
@ -32,7 +33,7 @@ export class PkgdashService extends BaseService {
}
/** Path part for operation `commentLookup()` */
static readonly CommentLookupPath = '/v1/comments/{id}/comments';
static readonly CommentLookupPath = '/v1/comments/{id}';
/**
* This method provides access to the full `HttpResponse`, allowing access to response headers.
@ -43,14 +44,14 @@ export class PkgdashService extends BaseService {
commentLookup$Response(
params: {
id: number;
package_id?: number;
package?: number;
},
context?: HttpContext
): Observable<StrictHttpResponse<CommentLookupRsp>> {
const rb = new RequestBuilder(this.rootUrl, PkgdashService.CommentLookupPath, 'get');
if (params) {
rb.path('id', params.id, {});
rb.query('package_id', params.package_id, {});
rb.query('package', params.package, {});
}
return this.http.request(
@ -72,7 +73,7 @@ export class PkgdashService extends BaseService {
commentLookup(
params: {
id: number;
package_id?: number;
package?: number;
},
context?: HttpContext
): Observable<CommentLookupRsp> {
@ -92,11 +93,13 @@ export class PkgdashService extends BaseService {
*/
moduleList$Response(
params?: {
package?: number;
},
context?: HttpContext
): Observable<StrictHttpResponse<ModuleListRsp>> {
const rb = new RequestBuilder(this.rootUrl, PkgdashService.ModuleListPath, 'get');
if (params) {
rb.query('package', params.package, {});
}
return this.http.request(
@ -117,6 +120,7 @@ export class PkgdashService extends BaseService {
*/
moduleList(
params?: {
package?: number;
},
context?: HttpContext
): Observable<ModuleListRsp> {
@ -421,15 +425,13 @@ export class PkgdashService extends BaseService {
*/
commentList$Response(
params: {
package: string;
package_id?: number;
package: number;
},
context?: HttpContext
): Observable<StrictHttpResponse<CommentListRsp>> {
const rb = new RequestBuilder(this.rootUrl, PkgdashService.CommentListPath, 'get');
if (params) {
rb.path('package', params.package, {});
rb.query('package_id', params.package_id, {});
}
return this.http.request(
@ -450,8 +452,7 @@ export class PkgdashService extends BaseService {
*/
commentList(
params: {
package: string;
package_id?: number;
package: number;
},
context?: HttpContext
): Observable<CommentListRsp> {
@ -510,6 +511,53 @@ export class PkgdashService extends BaseService {
);
}
/** Path part for operation `handlerList()` */
static readonly HandlerListPath = '/v1/packages/{package}/handlers';
/**
* This method provides access to the full `HttpResponse`, allowing access to response headers.
* To access only the response body, use `handlerList()` instead.
*
* This method doesn't expect any request body.
*/
handlerList$Response(
params: {
package: number;
},
context?: HttpContext
): Observable<StrictHttpResponse<HandlerListRsp>> {
const rb = new RequestBuilder(this.rootUrl, PkgdashService.HandlerListPath, 'get');
if (params) {
rb.path('package', params.package, {});
}
return this.http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<HandlerListRsp>;
})
);
}
/**
* This method provides access only to the response body.
* To access the full response (for headers, for example), `handlerList$Response()` instead.
*
* This method doesn't expect any request body.
*/
handlerList(
params: {
package: number;
},
context?: HttpContext
): Observable<HandlerListRsp> {
return this.handlerList$Response(params, context).pipe(
map((r: StrictHttpResponse<HandlerListRsp>): HandlerListRsp => r.body)
);
}
/** Path part for operation `packageModules()` */
static readonly PackageModulesPath = '/v1/packages/{package}/modules';

View File

@ -1,10 +1,30 @@
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { PackageListComponent } from './components/package-list/package-list.component';
import { PackageComponent } from './components/package/package.component';
import { PackageResolver } from './resolvers/package/package.resolver';
const routes: Routes = [
{ path: '', component: PackageComponent },
{ path: '**', component: PackageComponent },
{
path: 'packages',
component: PackageListComponent
},
{
path: 'packages/:id',
component: PackageComponent,
resolve: {
package: PackageResolver,
},
},
{
path: '',
pathMatch: 'full',
redirectTo: 'packages',
},
{
path: '**',
redirectTo: 'packages',
},
];
@NgModule({

View File

@ -26,17 +26,19 @@ import { ConfirmDialogComponent } from './components/confirm-dialog/confirm-dial
import { MatSelectModule } from '@angular/material/select';
import { MessageService } from './services/message/message.service';
import { ConfirmService } from './services/confirm/confirm.service';
import { PackageComponent } from './components/package/package.component';
import { PackageListComponent } from './components/package-list/package-list.component';
import { PackagesService } from './services/packages/packages.service';
import { PkgdashService } from './api/services';
import { AppConstants } from './app.constants';
import { PackageComponent } from './components/package/package.component';
@NgModule({
declarations: [
AppComponent,
PackageComponent,
PackageListComponent,
PackageDialogComponent,
ConfirmDialogComponent,
PackageComponent,
],
imports: [
BrowserModule,

View File

@ -17,18 +17,18 @@ export class ConfirmDialogComponent implements OnInit {
private mdDialogRef: MatDialogRef<ConfirmDialogComponent>,
) { }
ngOnInit(): void {}
ngOnInit(): void { }
public cancel() {
this.mdDialogRef.close();
}
public submit(value: any) {
this.mdDialogRef.close(value);
}
@HostListener("keydown.esc")
@HostListener("keydown.esc")
public onEsc() {
this.cancel();
}

View File

@ -19,8 +19,8 @@
</p>
<p>
<mat-form-field appearance="standard">
<mat-label>Url</mat-label>
<input matInput placeholder="http://example:port" formControlName="endpoint" required>
<mat-label>URL</mat-label>
<input matInput placeholder="http://example:port" formControlName="url" required>
<!-- <mat-icon matSuffix>sentiment_very_satisfied</mat-icon>-->
<!-- <mat-hint>service name</mat-hint> -->
</mat-form-field>

View File

@ -10,7 +10,7 @@ import { Package } from 'src/app/api/models/package';
styleUrls: ['./package-dialog.component.scss']
})
export class PackageDialogComponent implements OnInit {
packageForm: UntypedFormGroup = new UntypedFormGroup({});
constructor(@Inject(MAT_DIALOG_DATA) public data: {
@ -26,14 +26,14 @@ export class PackageDialogComponent implements OnInit {
url: '',
}
}
}
}
ngOnInit(): void {
this.packageForm = this.formBuilder.group({
name: [{ value: this.data.pkg.name, disabled: false },
Validators.required,
Validators.required,
],
url: [{ value:this.data.pkg.url, disabled: false },
url: [{ value: this.data.pkg.url, disabled: false },
Validators.compose([
Validators.required,
Validators.pattern("(^(http[s]?:\/\/(.*)$))?"),
@ -48,16 +48,15 @@ export class PackageDialogComponent implements OnInit {
});
}
public cancel() {
this.mdDialogRef.close();
}
public submit(value: any) {
this.mdDialogRef.close(value);
}
@HostListener("keydown.esc")
@HostListener("keydown.esc")
public onEsc() {
this.cancel();
}

View File

@ -0,0 +1,82 @@
<button mat-fab color="primary" (click)="createPackageDialog()">
<mat-icon>create</mat-icon>
</button>
<div class="mat-elevation-z8 mat-app-background" [hidden]="dataSource.loading$ | async">
<mat-form-field>
<input matInput type="search" placeholder="Search by name/path" #input>
</mat-form-field>
<div class="spinner-container" *ngIf="dataSource.loading$ | async">
<mat-progress-spinner [mode]="'indeterminate'"></mat-progress-spinner>
</div>
<table #packagesTable mat-table
matSort [matSortActive]="sortField" [matSortDirection]="sortOrder"
(matSortChange)="sortPackages($event)" matSortDisableClear
[dataSource]="dataSource" class="mat-elevation-z8 packages-table">
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef mat-sort-header="Name">Name</th>
<td mat-cell *matCellDef="let package">{{package.name}}<br/>{{package.description}}</td>
</ng-container>
<ng-container matColumnDef="url">
<th mat-header-cell *matHeaderCellDef mat-sort-header="URL">URL</th>
<td mat-cell *matCellDef="let package">{{package.url}}</td>
</ng-container>
<ng-container matColumnDef="issues">
<th mat-header-cell *matHeaderCellDef mat-sort-header="Issues">Issues</th>
<td mat-cell *matCellDef="let package">{{package.issues ? package.issues : 0}}</td>
</ng-container>
<ng-container matColumnDef="modules">
<th mat-header-cell *matHeaderCellDef mat-sort-header="Modules">Modules</th>
<td mat-cell *matCellDef="let package">{{package.modules ? package.modules : 0}}</td>
</ng-container>
<ng-container matColumnDef="comments">
<th mat-header-cell *matHeaderCellDef mat-sort-header="Comments">Comments</th>
<td mat-cell *matCellDef="let package">{{package.comments ? package.comments : 0}}</td>
</ng-container>
<ng-container matColumnDef="coverage">
<th mat-header-cell *matHeaderCellDef mat-sort-header="Coverage">Coverage</th>
<td mat-cell *matCellDef="let package">{{package.coverage ? package.coverage : 0}}</td>
</ng-container>
<ng-container matColumnDef="handlers">
<th mat-header-cell *matHeaderCellDef mat-sort-header="Handlers">Handlers</th>
<td mat-cell *matCellDef="let package">{{package.handlers ? package.handlers : 0}}</td>
</ng-container>
<ng-container matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef>Actions</th>
<td mat-cell *matCellDef="let package">
<button mat-icon-button [matMenuTriggerFor]="menu">
<mat-icon>more_vert</mat-icon>
</button>
<mat-menu #menu="matMenu">
<button mat-menu-item (click)="deletePackageDialog(package);">
<mat-icon>delete</mat-icon>
<span>Delete</span>
</button>
<button mat-menu-item (click)="updatePackageDialog(package)">
<mat-icon>edit</mat-icon>
<span>Edit</span>
</button>
</mat-menu>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let package; columns: displayedColumns;" routerLink="/packages/{{package.id}}"></tr>
</table>
<mat-paginator #paginator [length]="10" [pageSize]="itemsCount" [pageSizeOptions]="[10, 20, 30, 50]" showFirstLastButtons>
</mat-paginator>
</div>

View File

@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { PackageListComponent } from './package-list.component';
describe('PackagesComponent', () => {
let component: PackageListComponent;
let fixture: ComponentFixture<PackageListComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ PackageListComponent ]
})
.compileComponents();
fixture = TestBed.createComponent(PackageListComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,194 @@
import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { Package } from '../../api/models/package';
import { PkgdashService } from '../../api/services/pkgdash.service';
import { debounceTime, distinctUntilChanged, fromEvent, merge, Observable, of, tap } from 'rxjs';
import { MatPaginator } from '@angular/material/paginator';
import { PackagesService } from '../../services/packages/packages.service';
import { PackagesDataSource } from '../../datasources/packages';
import { MatSort, Sort, SortDirection } from '@angular/material/sort';
import { Router } from '@angular/router';
import { ConfirmService } from 'src/app/services/confirm/confirm.service';
import { AppConstants } from 'src/app/app.constants';
import { MessageService } from 'src/app/services/message/message.service';
import { ErrorRsp, PackageCreateRsp, PackageDeleteRsp, PackageUpdateRsp } from 'src/app/api/models';
@Component({
selector: 'app-packages',
templateUrl: './package-list.component.html',
styleUrls: ['./package-list.component.scss'],
providers: [PkgdashService, MessageService]
})
export class PackageListComponent implements OnInit, AfterViewInit {
@ViewChild(MatPaginator) paginator!: MatPaginator;
@ViewChild(MatSort) sort!: MatSort;
@ViewChild('input') input!: ElementRef;
selectedPackage?: Package;
dataSource: PackagesDataSource;
selectedRowIndex: any;
packages$!: Observable<any>;
public itemsCount = 20;
sortField = 'name';
sortOrder: SortDirection = 'asc';
displayedColumns: string[] = ['name', 'modules', 'issues', 'comments', 'coverage', 'handlers', 'actions'];
constructor(
private router: Router,
private packageDialog: PackagesService,
private pkgdashService: PkgdashService,
private confirmDialog: ConfirmService,
private messageService: MessageService,
) {
this.dataSource = new PackagesDataSource(this.pkgdashService);
}
createPackageDialog(): void {
this.packageDialog.open({
height: '400px',
width: '600px',
autoFocus: true,
disableClose: false,
backdropClass: "package-dialog",
data: {
title: 'Create package'
}
});
this.packageDialog.confirmed().subscribe((data: any) => {
if (data) {
this.pkgdashService.packageCreate(data)
.subscribe({
next: (rsp: PackageCreateRsp) => {
this.loadPackages();
this.reloadComponent();
this.messageService.showMessage("package " + rsp.package!.name + " created")
},
error: (err: ErrorRsp) => {
this.messageService.showMessage("package " + data.name + " not created, error " + err.details)
}
});
}
});
}
updatePackageDialog(pkg: Package): void {
this.packageDialog.open({
height: '400px',
width: '600px',
autoFocus: true,
disableClose: false,
backdropClass: "package-dialog",
data: {
pkg: pkg,
title: 'Update package ' + pkg.name,
}
});
this.packageDialog.confirmed().subscribe((data: any) => {
if (data) {
this.pkgdashService.packageUpdate({
id: pkg.id!,
body: data,
}).subscribe({
next: (rsp: PackageUpdateRsp) => {
this.loadPackages();
this.reloadComponent();
this.messageService.showMessage("package " + data.name + " updated")
},
error: (err: ErrorRsp) => {
this.messageService.showMessage("package " + data.name + " not updated, error " + err.details)
}
})
}
});
}
deletePackageDialog(pkg: Package): void {
this.confirmDialog.open({
height: '200px',
width: '300px',
autoFocus: true,
disableClose: false,
backdropClass: "package-dialog",
data: {
title: 'Delete package ' + pkg.name,
message: 'Are you sure?',
}
});
this.confirmDialog.confirmed().subscribe((data: any) => {
if (data) {
this.pkgdashService.packageDelete({
id: pkg.id!,
}).subscribe({
next: (rsp: PackageDeleteRsp) => {
this.loadPackages();
this.reloadComponent();
this.messageService.showMessage("package " + data.name + " deleted")
},
error: (err: ErrorRsp) => {
this.messageService.showMessage("package " + data.name + " not deleted, error " + err.details)
}
})
}
})
}
selectPackage(pkg: Package): void {
this.selectedPackage = pkg;
}
ngAfterViewInit() {
fromEvent(this.input.nativeElement, 'keyup')
.pipe(
debounceTime(AppConstants.SEARCH_DEBOUNCE),
distinctUntilChanged(),
tap(() => {
this.paginator.pageIndex = 0;
this.loadPackages();
})
)
.subscribe();
this.sort.sortChange.subscribe(() => this.paginator.pageIndex = 0);
merge(this.sort.sortChange, this.paginator.page)
.pipe(
tap(() => this.loadPackages())
)
.subscribe();
}
public sortPackages(event: Sort): void {
this.loadPackages()
this.reloadComponent()
}
private reloadComponent(): void {
let currentUrl = this.router.url;
this.router.routeReuseStrategy.shouldReuseRoute = () => false;
this.router.onSameUrlNavigation = 'reload';
this.router.navigate([currentUrl]);
}
private loadPackages(): void {
this.dataSource.list(
this.input.nativeElement.value,
this.sort.active,
this.sort.direction,
this.paginator.pageIndex,
this.paginator.pageSize);
}
ngOnInit(): void {
this.dataSource.list('', this.sortField, this.sortOrder, 0, this.itemsCount);
this.packages$ = this.dataSource.connect();
}
}

View File

@ -1,53 +1,58 @@
<button mat-fab color="primary" (click)="createPackageDialog()">
<mat-icon>create</mat-icon>
</button>
<p>modules</p>
<div class="mat-elevation-z8 mat-app-background" [hidden]="dataSource.loading$ | async">
<div>
<mat-form-field>
<input matInput type="search" placeholder="Search by name/path" #input>
</mat-form-field>
<div class="spinner-container" *ngIf="dataSource.loading$ | async">
<mat-progress-spinner [mode]="'indeterminate'"></mat-progress-spinner>
</div>
<table #packagesTable mat-table
<table #handlersTable mat-table
matSort [matSortActive]="sortField" [matSortDirection]="sortOrder"
(matSortChange)="sortPackages($event)" matSortDisableClear
(matSortChange)="sortHandlers($event)" matSortDisableClear
[dataSource]="dataSource" class="mat-elevation-z8 packages-table">
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef mat-sort-header="Name">Name</th>
<td mat-cell *matCellDef="let package">{{package.name}}</td>
<td mat-cell *matCellDef="let handler">{{handler.name}}</td>
</ng-container>
<ng-container matColumnDef="coverage">
<th mat-header-cell *matHeaderCellDef mat-sort-header="coverage">Coverage</th>
<td mat-cell *matCellDef="let package">{{package.coverage}}</td>
</ng-container>
<ng-container matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef>Actions</th>
<td mat-cell *matCellDef="let operation">
<button mat-icon-button [matMenuTriggerFor]="menu">
<mat-icon>more_vert</mat-icon>
</button>
<mat-menu #menu="matMenu">
<button mat-menu-item (click)="deletePackageDialog(package);">
<mat-icon>delete</mat-icon>
<span>Delete</span>
</button>
<button mat-menu-item (click)="updatePackageDialog(package)">
<mat-icon>edit</mat-icon>
<span>Edit</span>
</button>
</mat-menu>
</td>
<th mat-header-cell *matHeaderCellDef mat-sort-header="Coverage">Coverage</th>
<td mat-cell *matCellDef="let handler">{{handler.coverage}}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;" (click)="highlight(row)" [ngClass]="{'highlightTableColor': selectedRowIndex == row.id}"></tr>
<tr mat-row *matRowDef="let handler; columns: displayedColumns;" routerLink="/packages/{{package.id}}/handlers/{{handler.id}}"></tr>
</table>
</div>
<mat-paginator #paginator [length]="10" [pageSize]="itemsCount" [pageSizeOptions]="[10, 20, 30, 50]" showFirstLastButtons>
</mat-paginator>
</div>
<p>modules</p>
<div>
<table #modulesTable mat-table
matSort [matSortActive]="sortField" [matSortDirection]="sortOrder"
(matSortChange)="sortModules($event)" matSortDisableClear
[dataSource]="dataSource" class="mat-elevation-z8 packages-table">
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef mat-sort-header="Name">Name</th>
<td mat-cell *matCellDef="let handler">{{handler.name}}</td>
</ng-container>
<ng-container matColumnDef="version">
<th mat-header-cell *matHeaderCellDef mat-sort-header="Version">Version</th>
<td mat-cell *matCellDef="let module">{{module.version}}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let module; columns: displayedColumns;"></tr>
</table>
<mat-paginator #paginator [length]="10" [pageSize]="itemsCount" [pageSizeOptions]="[10, 20, 30, 50]" showFirstLastButtons>
</mat-paginator>
</div>

View File

@ -1,18 +1,18 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { PackagesComponent } from './package.component';
import { PackageComponent } from './package.component';
describe('PackagesComponent', () => {
let component: PackagesComponent;
let fixture: ComponentFixture<PackagesComponent>;
describe('PackageComponent', () => {
let component: PackageComponent;
let fixture: ComponentFixture<PackageComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ PackagesComponent ]
declarations: [ PackageComponent ]
})
.compileComponents();
fixture = TestBed.createComponent(PackagesComponent);
fixture = TestBed.createComponent(PackageComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});

View File

@ -1,171 +1,92 @@
import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { Package } from '../../api/models/package';
import { PkgdashService } from '../../api/services/pkgdash.service';
import { debounceTime, distinctUntilChanged, fromEvent, merge, Observable, of, tap } from 'rxjs';
import { MatDialogConfig } from '@angular/material/dialog';
import { MatIcon } from '@angular/material/icon';
import { Component, OnInit, ViewChild, AfterViewInit, ElementRef } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { tap, merge, debounceTime, distinctUntilChanged, fromEvent } from 'rxjs';
//import { Location } from '@angular/common';
import { MatPaginator } from '@angular/material/paginator';
import { PackagesService } from '../../services/packages/packages.service';
import { PackagesDataSource } from '../../datasources/packages';
import { MatSort, Sort, SortDirection } from '@angular/material/sort';
import { ActivatedRoute, Router } from '@angular/router';
import { ConfirmService } from 'src/app/services/confirm/confirm.service';
import { AppConstants } from 'src/app/app.constants';
import { MessageService } from 'src/app/services/message/message.service';
import { ErrorRsp, PackagesCreateRsp, PackagesDeleteRsp, PackagesUpdateRsp } from 'src/app/api/models';
import { ErrorRsp, Handler, Package } from 'src/app/api/models';
import { PkgdashService } from 'src/app/api/services';
import { HandlersDataSource } from 'src/app/datasources/handlers';
@Component({
selector: 'app-packages',
selector: 'app-package',
templateUrl: './package.component.html',
styleUrls: ['./package.component.scss'],
providers: [PkgdashService, MessageService]
providers: [PkgdashService],
})
export class PackageComponent implements OnInit {
export class PackageComponent implements OnInit, AfterViewInit {
@ViewChild(MatPaginator) paginator!: MatPaginator;
@ViewChild(MatSort) sort!: MatSort;
@ViewChild('input') input!: ElementRef;
selectedPackage?: Package;
dataSource: PackagesDataSource;
package!: Package;
packages$!: Observable<any>;
public itemsCount = 20;
public itemsCount = 10;
sortField = 'name';
sortOrder: SortDirection = 'asc';
displayedColumns: string[] = ['name', 'coverage'];
dataSource: HandlersDataSource;
selectedRowIndex: any;
constructor(
private router: Router,
private packageDialog: PackagesService,
private route: ActivatedRoute,
//private location: Location,
private pkgdashService: PkgdashService,
private confirmDialog: ConfirmService,
private messageService: MessageService,
) {
this.dataSource = new PackagesDataSource(this.pkgdashService);
) {
this.dataSource = new HandlersDataSource(this.pkgdashService);
}
createPackageDialog(): void {
this.packageDialog.open({
height: '400px',
width: '600px',
autoFocus: true,
disableClose: false,
backdropClass: "package-dialog",
data: {
title: 'Create package'
}
});
this.packageDialog.confirmed().subscribe((data: any) => {
if (data) {
this.pkgdashService.packagesCreate(data)
.subscribe({
next: (rsp: PackagesCreateRsp) => {
this.loadPackages();
this.reloadComponent();
this.messageService.showMessage("package "+rsp.package!.name+" created")
},
error: (err: ErrorRsp) => {
this.messageService.showMessage("package "+data.name+" not created, error "+ err.details)
}
});
}
});
}
updatePackageDialog(pkg: Package): void {
this.packageDialog.open({
height: '400px',
width: '600px',
autoFocus: true,
disableClose: false,
backdropClass: "package-dialog",
data: {
service: pkg,
title: 'Update package '+pkg.name,
}
});
this.packageDialog.confirmed().subscribe((data: any) => {
if (data) {
this.pkgdashService.packagesUpdate({
id: pkg.id!,
body: data,
}).subscribe({
next: (rsp: PackagesUpdateRsp) => {
this.loadPackages();
this.reloadComponent();
this.messageService.showMessage("package "+rsp.package!.name+" updated")
},
error: (err: ErrorRsp) => {
this.messageService.showMessage("package "+data.name+" not updated, error "+ err.details)
}
})
}
});
}
deletePackageDialog(pkg: Package): void {
this.confirmDialog.open({
height: '200px',
width: '300px',
autoFocus: true,
disableClose: false,
backdropClass: "package-dialog",
data: {
title: 'Delete package '+pkg.name,
message: 'Are you sure?',
}
});
this.confirmDialog.confirmed().subscribe((data: any) => {
if (data) {
this.pkgdashService.packagesDelete({
id: pkg.id!,
}).subscribe({
next: (rsp: PackagesDeleteRsp) => {
this.loadPackages();
this.reloadComponent();
this.messageService.showMessage("package "+data.name+" deleted")
},
error: (err: ErrorRsp) => {
this.messageService.showMessage("package "+data.name+" not deleted, error "+ err.details)
}
})
}
})
}
selectPackage(pkg: Package): void {
this.selectedPackage = pkg;
highlight(row: Handler) {
this.selectedRowIndex = row.id;
}
ngAfterViewInit() {
fromEvent(this.input.nativeElement, 'keyup')
.pipe(
debounceTime(AppConstants.SEARCH_DEBOUNCE),
distinctUntilChanged(),
tap(() => {
this.paginator.pageIndex = 0;
this.loadHandlers();
})
)
.subscribe();
this.sort.sortChange.subscribe(() => this.paginator.pageIndex = 0);
merge(this.sort.sortChange, this.paginator.page)
.pipe(
tap(() => this.loadHandlers())
)
.subscribe();
}
public sortPackages(event: Sort): void {
this.loadPackages()
this.reloadComponent()
public sortHandlers(event: Sort): void {
this.loadHandlers()
}
private reloadComponent(): void {
let currentUrl = this.router.url;
this.router.routeReuseStrategy.shouldReuseRoute = () => false;
this.router.onSameUrlNavigation = 'reload';
this.router.navigate([currentUrl]);
private loadHandlers(): void {
this.dataSource.list(
this.package.id!,
'',
this.sort.active,
this.sort.direction,
this.paginator.pageIndex,
this.paginator.pageSize);
}
private loadPackages(): void {
this.dataSource.list();
}
ngOnInit(): void {
this.dataSource.list('', this.sortField, this.sortOrder, 0, this.itemsCount);
this.packages$ = this.dataSource.connect();
this.package = this.route.snapshot.data['package'];
this.dataSource.list(this.package.id!, '', this.sortField, this.sortOrder, 0, this.itemsCount);
this.selectedRowIndex = 1;
}
}

View File

@ -0,0 +1,53 @@
import { DataSource } from "@angular/cdk/collections";
import { Handler } from "../api/models/handler"
import { BehaviorSubject, Observable, retry, map, catchError, of, finalize } from "rxjs";
import { PkgdashService } from "../api/services";
export class HandlersDataSource extends DataSource<Handler> {
private handlerSubject = new BehaviorSubject<Handler[]>([]);
private loadingSubject = new BehaviorSubject<boolean>(false);
public loading$ = this.loadingSubject.asObservable();
constructor(
private pkgdashService: PkgdashService
) {
super();
}
connect(): Observable<Handler[]> {
return this.handlerSubject.asObservable();
}
disconnect(): void {
this.handlerSubject.complete();
this.loadingSubject.complete();
}
list(id = 0, filter = '', sortField = 'name', sortOrder = 'asc', page = 0, limit = 20) {
this.loadingSubject.next(true);
this.pkgdashService.handlerList({package: id}).pipe(
retry(2),
map(rsp => rsp.handlers || []),
catchError(this.handleError('list', [])),
finalize(() => this.loadingSubject.next(false))
).subscribe(handlers => this.handlerSubject.next(handlers));
}
lookup(id: number, filter: string,
sortDirection: string, pageIndex: number, pageSize: number) {
}
private handleError<T>(operation = '', result?: T) {
return (error: any): Observable<T> => {
// TODO: send the error to remote logging infrastructure
console.error(error); // log to console instead
// Let the app keep running by returning an empty result.
return of(result as T);
};
};
}

View File

@ -1,53 +1,52 @@
import { CollectionViewer, DataSource } from "@angular/cdk/collections";
import { DataSource } from "@angular/cdk/collections";
import { Package } from "../api/models/package"
import { BehaviorSubject, Observable, retry, map, catchError, of, finalize } from "rxjs";
import { PkgdashService } from "../api/services";
export class PackagesDataSource extends DataSource<Package> {
private packageSubject = new BehaviorSubject<Package[]>([]);
private loadingSubject = new BehaviorSubject<boolean>(false);
private packageSubject = new BehaviorSubject<Package[]>([]);
private loadingSubject = new BehaviorSubject<boolean>(false);
public loading$ = this.loadingSubject.asObservable();
public loading$ = this.loadingSubject.asObservable();
constructor(
private pkgdashService: PkgdashService
) {
super();
}
constructor(
private pkgdashService: PkgdashService
) {
super();
}
connect(): Observable<Package[]> {
return this.packageSubject.asObservable();
}
connect(): Observable<Package[]> {
return this.packageSubject.asObservable();
}
disconnect(): void {
this.packageSubject.complete();
this.loadingSubject.complete();
}
disconnect(): void {
this.packageSubject.complete();
this.loadingSubject.complete();
}
list(filter = '', sortField = 'name', sortOrder = 'asc', page = 0, limit = 20) {
this.loadingSubject.next(true);
this.pkgdashService.packagesList().pipe(
retry(2),
map(rsp => rsp.packages || []),
catchError(this.handleError('getPackages', [])),
finalize(() => this.loadingSubject.next(false))
).subscribe(packages => this.packageSubject.next(packages));
}
lookup(id: string, filter: string,
sortDirection: string, pageIndex: number, pageSize: number) {
}
list(filter = '', sortField = 'name', sortOrder = 'asc', page = 0, limit = 20) {
this.loadingSubject.next(true);
this.pkgdashService.packageList().pipe(
retry(2),
map(rsp => rsp.packages || []),
catchError(this.handleError('list', [])),
finalize(() => this.loadingSubject.next(false))
).subscribe(packages => this.packageSubject.next(packages));
}
private handleError<T>(operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
// TODO: send the error to remote logging infrastructure
console.error(error); // log to console instead
// Let the app keep running by returning an empty result.
return of(result as T);
};
lookup(id: number, filter: string,
sortDirection: string, pageIndex: number, pageSize: number) {
}
private handleError<T>(operation = '', result?: T) {
return (error: any): Observable<T> => {
// TODO: send the error to remote logging infrastructure
console.error(error); // log to console instead
// Let the app keep running by returning an empty result.
return of(result as T);
};
};
}

View File

@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { PackageResolver } from './package.resolver';
describe('PackageResolver', () => {
let resolver: PackageResolver;
beforeEach(() => {
TestBed.configureTestingModule({});
resolver = TestBed.inject(PackageResolver);
});
it('should be created', () => {
expect(resolver).toBeTruthy();
});
});

View File

@ -0,0 +1,28 @@
import { Injectable } from '@angular/core';
import {
Router, Resolve,
RouterStateSnapshot,
ActivatedRouteSnapshot
} from '@angular/router';
import { Package } from "../../api/models/package";
import { map, Observable, of } from "rxjs";
import { PkgdashService } from '../../api/services/pkgdash.service';
@Injectable({
providedIn: 'root'
})
export class PackageResolver implements Resolve<Package> {
constructor(private pkgdashService: PkgdashService) { }
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Package> {
console.log("resolver with "+ route.paramMap.get('id'));
let id = Number(route.paramMap.get('id'));
return this.pkgdashService.packageLookup({ id: id }).pipe(
map(rsp => rsp.package!)
);
}
}

View File

@ -13,16 +13,15 @@ export class ConfirmService {
constructor(
private dialog: MatDialog
) { }
public open(options: MatDialogConfig) {
this.dialogRef = this.dialog.open(ConfirmDialogComponent, options);
}
public confirmed(): Observable<any> {
return this.dialogRef.afterClosed().pipe(take(1), map(res => {
return res;
}
return res;
}
));
}
}

View File

@ -9,7 +9,7 @@ export class MessageService {
constructor(
private snackbar: MatSnackBar,
) {
) {
}
showMessage(message: string, action?: string, config?: MatSnackBarConfig) {

View File

@ -13,16 +13,15 @@ export class PackagesService {
constructor(
private dialog: MatDialog
) { }
public open(options: MatDialogConfig) {
this.dialogRef = this.dialog.open(PackageDialogComponent, options);
}
public confirmed(): Observable<any> {
return this.dialogRef.afterClosed().pipe(take(1), map(res => {
return res;
}
return res;
}
));
}
}

View File

@ -13,4 +13,4 @@ export const environment = {
* This import should be commented out in production mode because it will have a negative impact
* on performance if an error is thrown.
*/
// import 'zone.js/plugins/zone-error'; // Included with Angular CLI.
import 'zone.js/plugins/zone-error'; // Included with Angular CLI.

View File

@ -1,4 +1,40 @@
/* You can add global styles to this file, and also import other style files */
@import '~@angular/material/prebuilt-themes/deeppurple-amber.css';
html, body { height: 100%; }
body { margin: 0; font-family: Roboto, "Helvetica Neue", sans-serif; }
.mat-table {
overflow-x: scroll;
display: table;
width: 100%;
}
.mat-cell,
.mat-header-cell {
word-wrap: initial;
display: table-cell;
padding: 0px 4px 4px 4px;
line-break: unset;
width: auto;
white-space: nowrap;
overflow: hidden;
vertical-align: middle;
}
.mat-row,
.mat-header-row {
display: table-row;
}
.mat-mdc-row .mat-mdc-cell {
border-bottom: 1px solid transparent;
border-top: 1px solid transparent;
cursor: pointer;
}
.mat-mdc-row:hover .mat-mdc-cell {
border-color: currentColor;
}
.demo-row-is-clicked {
font-weight: bold;
}