init
This commit is contained in:
commit
c0f618a9db
133 files changed
+55621
No files matched your search
@@ -0,0 +1,2 @@
|
||||
server/manifest.go linguist-generated=true
|
||||
webapp/src/manifest.js linguist-generated=true
|
||||
@@ -0,0 +1 @@
|
||||
root: ./docs/
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
bin/
|
||||
dist/
|
||||
webapp/src/manifest.ts
|
||||
server/manifest.go
|
||||
|
||||
# Mac
|
||||
.DS_Store
|
||||
|
||||
# Jetbrains
|
||||
.idea/
|
||||
|
||||
# VS Code
|
||||
.vscode
|
||||
@@ -0,0 +1 @@
|
||||
mainConfiguration: https://github.com/mattermost/mattermost-gitpod-config
|
||||
@@ -0,0 +1,56 @@
|
||||
run:
|
||||
timeout: 5m
|
||||
modules-download-mode: readonly
|
||||
|
||||
linters-settings:
|
||||
gofmt:
|
||||
simplify: true
|
||||
goimports:
|
||||
local-prefixes: github.com/mattermost/mattermost-plugin-gitlab
|
||||
golint:
|
||||
min-confidence: 0
|
||||
govet:
|
||||
check-shadowing: true
|
||||
enable-all: true
|
||||
disable:
|
||||
- fieldalignment
|
||||
misspell:
|
||||
locale: US
|
||||
ignore-words:
|
||||
- noteable
|
||||
|
||||
linters:
|
||||
disable-all: true
|
||||
enable:
|
||||
- bodyclose
|
||||
- deadcode
|
||||
- errcheck
|
||||
- gocritic
|
||||
- gofmt
|
||||
- goimports
|
||||
- golint
|
||||
- gosec
|
||||
- gosimple
|
||||
- govet
|
||||
- ineffassign
|
||||
- misspell
|
||||
- nakedret
|
||||
- staticcheck
|
||||
- structcheck
|
||||
- stylecheck
|
||||
- typecheck
|
||||
- unconvert
|
||||
- unused
|
||||
- varcheck
|
||||
- whitespace
|
||||
|
||||
issues:
|
||||
exclude-rules:
|
||||
- path: server/configuration.go
|
||||
linters:
|
||||
- unused
|
||||
- path: _test\.go
|
||||
linters:
|
||||
- bodyclose
|
||||
- goconst
|
||||
- scopelint # https://github.com/kyoh86/scopelint/issues/4
|
||||
@@ -0,0 +1,39 @@
|
||||
# Changelog
|
||||
|
||||
ALl releases can be found at https://github.com/mattermost/mattermost-plugin-gitlab/releases.
|
||||
|
||||
## 0.3.0 - 2019-06-05
|
||||
|
||||
- Give feedback to user when subscription has unknown feature [#47](https://github.com/manland/mattermost-plugin-gitlab/pull/47)
|
||||
- Implement `OnConfigurationChange` to have configuration changes without reload [#22](https://github.com/manland/mattermost-plugin-gitlab/issues/22)
|
||||
- Give feedback to user when deleting an unknown subscription [#48](https://github.com/manland/mattermost-plugin-gitlab/pull/48)
|
||||
- **Fix** Reject private group subscription when `Enable Private repository` is `False` [#52](https://github.com/manland/mattermost-plugin-gitlab/pull/52)
|
||||
- **Fix** `settings.notifications=off` was not implemented [#50](https://github.com/manland/mattermost-plugin-gitlab/pull/50)
|
||||
- `/gitlab help` is accessible before user is logged [#49](https://github.com/manland/mattermost-plugin-gitlab/pull/49)
|
||||
- Clean configuration for plugin [#51](https://github.com/manland/mattermost-plugin-gitlab/pull/51)
|
||||
- **Breaking** Configuration `EnterpriseBaseURL` become `GitlabURL` with `https://gitlab.com` as de fault value [#34](https://github.com/manland/mattermost-plugin-gitlab/pull/34)
|
||||
- Use a bot account [#9](https://github.com/manland/mattermost-plugin-gitlab/pull/9)
|
||||
- Rewrite all `pull request` to `merge request`
|
||||
- Display coverage with [codecov](https://codecov.io) [#37](https://github.com/manland/mattermost-plugin-gitlab/issues/37)
|
||||
- Add screenshot in [README.md](https://github.com/manland/mattermost-plugin-gitlab/blob/master/README.md) [#26](https://github.com/manland/mattermost-plugin-gitlab/issues/26)
|
||||
- Backport [mattermost-plugin-sample](https://github.com/mattermost/mattermost-plugin-sample/) infra code : use go mod, rework makefile to use sub-module, repair coverage [#27](https://github.com/manland/mattermost-plugin-gitlab/issues/27)
|
||||
- From `Gitlab` to `GitLab` [#31](https://github.com/manland/mattermost-plugin-gitlab/issues/31)
|
||||
|
||||
## 0.2.0 - 2019-05-06
|
||||
|
||||
- Send refresh to webapp of the author of events received by webhook [#25](https://github.com/manland/mattermost-plugin-gitlab/pull/25)
|
||||
- Add all webhook events for pipeline (run, fail, success) [#24](https://github.com/manland/mattermost-plugin-gitlab/pull/24)
|
||||
- Finish group restriction [#21](https://github.com/manland/mattermost-plugin-gitlab/pull/21)
|
||||
- Finish private repositories on/off [#18](https://github.com/manland/mattermost-plugin-gitlab/pull/18)
|
||||
- Finish all webhook implementation [#16](https://github.com/manland/mattermost-plugin-gitlab/pull/16):
|
||||
- MergeEvent
|
||||
- IssueEvent
|
||||
- IssueCommentEvent
|
||||
- MergeCommentEvent
|
||||
- PushEvent
|
||||
- PipelineEvent
|
||||
- TagEvent
|
||||
|
||||
## 0.1.0 - 2019-04-17
|
||||
|
||||
- Get all code from [mattermost-plugin-github](https://github.com/mattermost/mattermost-plugin-github/) and adapt it for gitlab
|
||||
@@ -0,0 +1 @@
|
||||
* @mickmister @spirosoik
|
||||
@@ -0,0 +1,201 @@
|
||||
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 [yyyy] [name of copyright owner]
|
||||
|
||||
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.
|
||||
@@ -0,0 +1,291 @@
|
||||
GO ?= $(shell command -v go 2> /dev/null)
|
||||
NPM ?= $(shell command -v npm 2> /dev/null)
|
||||
CURL ?= $(shell command -v curl 2> /dev/null)
|
||||
MM_DEBUG ?=
|
||||
GOPATH ?= $(shell go env GOPATH)
|
||||
GO_TEST_FLAGS ?= -race
|
||||
GO_BUILD_FLAGS ?=
|
||||
MM_UTILITIES_DIR ?= ../mattermost-utilities
|
||||
DLV_DEBUG_PORT := 2346
|
||||
DEFAULT_GOOS := $(shell go env GOOS)
|
||||
DEFAULT_GOARCH := $(shell go env GOARCH)
|
||||
|
||||
export GO111MODULE=on
|
||||
|
||||
# We need to export GOBIN to allow it to be set
|
||||
# for processes spawned from the Makefile
|
||||
export GOBIN ?= $(PWD)/bin
|
||||
|
||||
# You can include assets this directory into the bundle. This can be e.g. used to include profile pictures.
|
||||
ASSETS_DIR ?= assets
|
||||
|
||||
## Define the default target (make all)
|
||||
.PHONY: default
|
||||
default: all
|
||||
|
||||
# Verify environment, and define PLUGIN_ID, PLUGIN_VERSION, HAS_SERVER and HAS_WEBAPP as needed.
|
||||
include build/setup.mk
|
||||
|
||||
BUNDLE_NAME ?= $(PLUGIN_ID)-$(PLUGIN_VERSION).tar.gz
|
||||
|
||||
# Include custom makefile, if present
|
||||
ifneq ($(wildcard build/custom.mk),)
|
||||
include build/custom.mk
|
||||
endif
|
||||
|
||||
ifneq ($(MM_DEBUG),)
|
||||
GO_BUILD_GCFLAGS = -gcflags "all=-N -l"
|
||||
else
|
||||
GO_BUILD_GCFLAGS =
|
||||
endif
|
||||
|
||||
## Checks the code style, tests, builds and bundles the plugin.
|
||||
.PHONY: all
|
||||
all: check-style test dist
|
||||
|
||||
## Propagates plugin manifest information into the server/ and webapp/ folders.
|
||||
.PHONY: apply
|
||||
apply:
|
||||
./build/bin/manifest apply
|
||||
|
||||
## Install go tools
|
||||
install-go-tools:
|
||||
@echo Installing go tools
|
||||
$(GO) install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.51.1
|
||||
$(GO) install gotest.tools/gotestsum@v1.7.0
|
||||
|
||||
## Runs eslint and golangci-lint
|
||||
.PHONY: check-style
|
||||
check-style: apply webapp/node_modules install-go-tools
|
||||
@echo Checking for style guide compliance
|
||||
|
||||
ifneq ($(HAS_WEBAPP),)
|
||||
cd webapp && npm run lint
|
||||
cd webapp && npm run check-types
|
||||
endif
|
||||
|
||||
# It's highly recommended to run go-vet first
|
||||
# to find potential compile errors that could introduce
|
||||
# weird reports at golangci-lint step
|
||||
ifneq ($(HAS_SERVER),)
|
||||
@echo Running golangci-lint
|
||||
$(GO) vet ./...
|
||||
$(GOBIN)/golangci-lint run ./...
|
||||
endif
|
||||
|
||||
## Builds the server, if it exists, for all supported architectures, unless MM_SERVICESETTINGS_ENABLEDEVELOPER is set
|
||||
.PHONY: server
|
||||
server:
|
||||
ifneq ($(HAS_SERVER),)
|
||||
ifneq ($(MM_DEBUG),)
|
||||
$(info DEBUG mode is on; to disable, unset MM_DEBUG)
|
||||
endif
|
||||
mkdir -p server/dist;
|
||||
ifneq ($(MM_SERVICESETTINGS_ENABLEDEVELOPER),)
|
||||
@echo Building plugin only for $(DEFAULT_GOOS)-$(DEFAULT_GOARCH) because MM_SERVICESETTINGS_ENABLEDEVELOPER is enabled
|
||||
cd server && env CGO_ENABLED=0 $(GO) build $(GO_BUILD_FLAGS) $(GO_BUILD_GCFLAGS) -trimpath -o dist/plugin-$(DEFAULT_GOOS)-$(DEFAULT_GOARCH);
|
||||
else
|
||||
cd server && env CGO_ENABLED=0 GOOS=linux GOARCH=amd64 $(GO) build $(GO_BUILD_FLAGS) $(GO_BUILD_GCFLAGS) -trimpath -o dist/plugin-linux-amd64;
|
||||
cd server && env CGO_ENABLED=0 GOOS=linux GOARCH=arm64 $(GO) build $(GO_BUILD_FLAGS) $(GO_BUILD_GCFLAGS) -trimpath -o dist/plugin-linux-arm64;
|
||||
cd server && env CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 $(GO) build $(GO_BUILD_FLAGS) $(GO_BUILD_GCFLAGS) -trimpath -o dist/plugin-darwin-amd64;
|
||||
cd server && env CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 $(GO) build $(GO_BUILD_FLAGS) $(GO_BUILD_GCFLAGS) -trimpath -o dist/plugin-darwin-arm64;
|
||||
cd server && env CGO_ENABLED=0 GOOS=windows GOARCH=amd64 $(GO) build $(GO_BUILD_FLAGS) $(GO_BUILD_GCFLAGS) -trimpath -o dist/plugin-windows-amd64.exe;
|
||||
endif
|
||||
endif
|
||||
|
||||
## Ensures NPM dependencies are installed without having to run this all the time.
|
||||
webapp/node_modules: $(wildcard webapp/package.json)
|
||||
ifneq ($(HAS_WEBAPP),)
|
||||
cd webapp && $(NPM) install --verbose
|
||||
touch $@
|
||||
endif
|
||||
|
||||
## Builds the webapp, if it exists.
|
||||
.PHONY: webapp
|
||||
webapp: webapp/node_modules
|
||||
ifneq ($(HAS_WEBAPP),)
|
||||
ifeq ($(MM_DEBUG),)
|
||||
cd webapp && $(NPM) run build;
|
||||
else
|
||||
cd webapp && $(NPM) run debug;
|
||||
endif
|
||||
endif
|
||||
|
||||
## Generates a tar bundle of the plugin for install.
|
||||
.PHONY: bundle
|
||||
bundle:
|
||||
rm -rf dist/
|
||||
mkdir -p dist/$(PLUGIN_ID)
|
||||
./build/bin/manifest dist
|
||||
ifneq ($(wildcard $(ASSETS_DIR)/.),)
|
||||
cp -r $(ASSETS_DIR) dist/$(PLUGIN_ID)/
|
||||
endif
|
||||
ifneq ($(HAS_PUBLIC),)
|
||||
cp -r public dist/$(PLUGIN_ID)/
|
||||
endif
|
||||
ifneq ($(HAS_SERVER),)
|
||||
mkdir -p dist/$(PLUGIN_ID)/server
|
||||
cp -r server/dist dist/$(PLUGIN_ID)/server/
|
||||
endif
|
||||
ifneq ($(HAS_WEBAPP),)
|
||||
mkdir -p dist/$(PLUGIN_ID)/webapp
|
||||
cp -r webapp/dist dist/$(PLUGIN_ID)/webapp/
|
||||
endif
|
||||
cd dist && tar -cvzf $(BUNDLE_NAME) $(PLUGIN_ID)
|
||||
|
||||
@echo plugin built at: dist/$(BUNDLE_NAME)
|
||||
|
||||
## Builds and bundles the plugin.
|
||||
.PHONY: dist
|
||||
dist: apply server webapp bundle
|
||||
|
||||
## Builds and installs the plugin to a server.
|
||||
.PHONY: deploy
|
||||
deploy: dist
|
||||
./build/bin/pluginctl deploy $(PLUGIN_ID) dist/$(BUNDLE_NAME)
|
||||
|
||||
## Builds and installs the plugin to a server, updating the webapp automatically when changed.
|
||||
.PHONY: watch
|
||||
watch: apply server bundle
|
||||
ifeq ($(MM_DEBUG),)
|
||||
cd webapp && $(NPM) run build:watch
|
||||
else
|
||||
cd webapp && $(NPM) run debug:watch
|
||||
endif
|
||||
|
||||
## Installs a previous built plugin with updated webpack assets to a server.
|
||||
.PHONY: deploy-from-watch
|
||||
deploy-from-watch: bundle
|
||||
./build/bin/pluginctl deploy $(PLUGIN_ID) dist/$(BUNDLE_NAME)
|
||||
|
||||
## Setup dlv for attaching, identifying the plugin PID for other targets.
|
||||
.PHONY: setup-attach
|
||||
setup-attach:
|
||||
$(eval PLUGIN_PID := $(shell ps aux | grep "plugins/${PLUGIN_ID}" | grep -v "grep" | awk -F " " '{print $$2}'))
|
||||
$(eval NUM_PID := $(shell echo -n ${PLUGIN_PID} | wc -w))
|
||||
|
||||
@if [ ${NUM_PID} -gt 2 ]; then \
|
||||
echo "** There is more than 1 plugin process running. Run 'make kill reset' to restart just one."; \
|
||||
exit 1; \
|
||||
fi
|
||||
|
||||
## Check if setup-attach succeeded.
|
||||
.PHONY: check-attach
|
||||
check-attach:
|
||||
@if [ -z ${PLUGIN_PID} ]; then \
|
||||
echo "Could not find plugin PID; the plugin is not running. Exiting."; \
|
||||
exit 1; \
|
||||
else \
|
||||
echo "Located Plugin running with PID: ${PLUGIN_PID}"; \
|
||||
fi
|
||||
|
||||
## Attach dlv to an existing plugin instance.
|
||||
.PHONY: attach
|
||||
attach: setup-attach check-attach
|
||||
dlv attach ${PLUGIN_PID}
|
||||
|
||||
## Attach dlv to an existing plugin instance, exposing a headless instance on $DLV_DEBUG_PORT.
|
||||
.PHONY: attach-headless
|
||||
attach-headless: setup-attach check-attach
|
||||
dlv attach ${PLUGIN_PID} --listen :$(DLV_DEBUG_PORT) --headless=true --api-version=2 --accept-multiclient
|
||||
|
||||
## Detach dlv from an existing plugin instance, if previously attached.
|
||||
.PHONY: detach
|
||||
detach: setup-attach
|
||||
@DELVE_PID=$(shell ps aux | grep "dlv attach ${PLUGIN_PID}" | grep -v "grep" | awk -F " " '{print $$2}') && \
|
||||
if [ "$$DELVE_PID" -gt 0 ] > /dev/null 2>&1 ; then \
|
||||
echo "Located existing delve process running with PID: $$DELVE_PID. Killing." ; \
|
||||
kill -9 $$DELVE_PID ; \
|
||||
fi
|
||||
|
||||
## Runs any lints and unit tests defined for the server and webapp, if they exist.
|
||||
.PHONY: test
|
||||
test: apply webapp/node_modules install-go-tools
|
||||
ifneq ($(HAS_SERVER),)
|
||||
$(GOBIN)/gotestsum -- -v ./...
|
||||
endif
|
||||
ifneq ($(HAS_WEBAPP),)
|
||||
cd webapp && $(NPM) run test;
|
||||
endif
|
||||
|
||||
## Runs any lints and unit tests defined for the server and webapp, if they exist, optimized
|
||||
## for a CI environment.
|
||||
.PHONY: test-ci
|
||||
test-ci: apply webapp/node_modules install-go-tools
|
||||
ifneq ($(HAS_SERVER),)
|
||||
$(GOBIN)/gotestsum --format standard-verbose --junitfile report.xml -- ./...
|
||||
endif
|
||||
ifneq ($(HAS_WEBAPP),)
|
||||
cd webapp && $(NPM) run test;
|
||||
endif
|
||||
|
||||
## Creates a coverage report for the server code.
|
||||
.PHONY: coverage
|
||||
coverage: apply webapp/node_modules
|
||||
ifneq ($(HAS_SERVER),)
|
||||
$(GO) test $(GO_TEST_FLAGS) -coverprofile=server/coverage.txt ./server/...
|
||||
$(GO) tool cover -html=server/coverage.txt
|
||||
endif
|
||||
|
||||
## Extract strings for translation from the source code.
|
||||
.PHONY: i18n-extract
|
||||
i18n-extract:
|
||||
ifneq ($(HAS_WEBAPP),)
|
||||
ifeq ($(HAS_MM_UTILITIES),)
|
||||
@echo "You must clone github.com/mattermost/mattermost-utilities repo in .. to use this command"
|
||||
else
|
||||
cd $(MM_UTILITIES_DIR) && npm install && npm run babel && node mmjstool/build/index.js i18n extract-webapp --webapp-dir $(PWD)/webapp
|
||||
endif
|
||||
endif
|
||||
|
||||
## Disable the plugin.
|
||||
.PHONY: disable
|
||||
disable: detach
|
||||
./build/bin/pluginctl disable $(PLUGIN_ID)
|
||||
|
||||
## Enable the plugin.
|
||||
.PHONY: enable
|
||||
enable:
|
||||
./build/bin/pluginctl enable $(PLUGIN_ID)
|
||||
|
||||
## Reset the plugin, effectively disabling and re-enabling it on the server.
|
||||
.PHONY: reset
|
||||
reset: detach
|
||||
./build/bin/pluginctl reset $(PLUGIN_ID)
|
||||
|
||||
## Kill all instances of the plugin, detaching any existing dlv instance.
|
||||
.PHONY: kill
|
||||
kill: detach
|
||||
$(eval PLUGIN_PID := $(shell ps aux | grep "plugins/${PLUGIN_ID}" | grep -v "grep" | awk -F " " '{print $$2}'))
|
||||
|
||||
@for PID in ${PLUGIN_PID}; do \
|
||||
echo "Killing plugin pid $$PID"; \
|
||||
kill -9 $$PID; \
|
||||
done; \
|
||||
|
||||
## Clean removes all build artifacts.
|
||||
.PHONY: clean
|
||||
clean:
|
||||
rm -fr dist/
|
||||
ifneq ($(HAS_SERVER),)
|
||||
rm -fr server/coverage.txt
|
||||
rm -fr server/dist
|
||||
endif
|
||||
ifneq ($(HAS_WEBAPP),)
|
||||
rm -fr webapp/junit.xml
|
||||
rm -fr webapp/dist
|
||||
rm -fr webapp/node_modules
|
||||
endif
|
||||
rm -fr build/bin/
|
||||
|
||||
.PHONY: logs
|
||||
logs:
|
||||
./build/bin/pluginctl logs $(PLUGIN_ID)
|
||||
|
||||
.PHONY: logs-watch
|
||||
logs-watch:
|
||||
./build/bin/pluginctl logs-watch $(PLUGIN_ID)
|
||||
|
||||
# Help documentation à la https://marmelab.com/blog/2016/02/29/auto-documented-makefile.html
|
||||
help:
|
||||
@cat Makefile build/*.mk | grep -v '\.PHONY' | grep -v '\help:' | grep -B1 -E '^[a-zA-Z0-9_.-]+:.*' | sed -e "s/:.*//" | sed -e "s/^## //" | grep -v '\-\-' | sed '1!G;h;$$!d' | awk 'NR%2{printf "\033[36m%-30s\033[0m",$$0;next;}1' | sort
|
||||
@@ -0,0 +1,191 @@
|
||||
# Mattermost GitLab Plugin
|
||||
|
||||
[](https://circleci.com/gh/mattermost/mattermost-plugin-gitlab)
|
||||
[](https://codecov.io/gh/mattermost/mattermost-plugin-gitlab)
|
||||
[](https://github.com/mattermost/mattermost-plugin-gitlab/releases/latest)
|
||||
[](https://github.com/mattermost/mattermost-plugin-gitlab/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3A%22Up+For+Grabs%22+label%3A%22Help+Wanted%22)
|
||||
|
||||
A GitLab plugin for Mattermost. This plugin supports a two-way integration between Mattermost and GitLab. This plugin supports Software-as-a-Service (SaaS) or on-premises versions of GitLab.
|
||||
|
||||

|
||||
|
||||
Originally developed by [Romain Maneschi](https://github.com/manland). This project is a fork of the [mattermost-plugin-github](https://github.com/mattermost/mattermost-plugin-github). Thanks to all contributors of it.
|
||||
|
||||
**Maintainer:** [@mickmister](https://github.com/mickmister)
|
||||
|
||||
**Co-Maintainer:** [@hanzei](https://github.com/hanzei)
|
||||
|
||||
## Feature summary of GitLab to Mattermost notifications
|
||||
|
||||
### Channel subscriptions
|
||||
|
||||
Notify your team of the latest updates by sending notifications from your GitLab group or repository to Mattermost channels. When team members log in the first time to Mattermost each day, they can get a post letting them know what issues and merge requests need their attention. They can also get a refresh of new events by selecting **Refresh** from every webhook configured in GitLab.
|
||||
|
||||
You can specify which events trigger a notification. They can see:
|
||||
|
||||
- issues - includes new and closed issues
|
||||
- merges - includes new and closed merge requests
|
||||
- pushes - includes pushes
|
||||
- issue_comments - includes new issue comments
|
||||
- merge_request_comments - include new merge-request comments
|
||||
- pipeline - include pipeline
|
||||
- tag - include tag creation
|
||||
- pull_reviews - includes merge request reviews
|
||||
- label:"<labelname>" - must include "merges" or "issues" in feature list when using a label
|
||||
- Defaults to "merges,issues,tag"
|
||||
|
||||
### Personal notifications: GitLab bot
|
||||
|
||||
Each user in Mattermost is connected with their own personal GitLab account. Users can get a direct message in Mattermost when someone mentions them, requests their review, comments on, or modifies one of their merge requests/issues, or assigns them on GitLab.
|
||||
|
||||
### Sidebar buttons
|
||||
|
||||
Team members can stay up-to-date with how many reviews, todos, assigned issues, and assigned merge requests they have by using buttons in the Mattermost sidebar.
|
||||
|
||||
## Admin guide
|
||||
|
||||
Get started by installing the GitLab plugin from the Marketplace.
|
||||
|
||||
### Prerequisites
|
||||
|
||||
* The GitLab plugin is included in the Plugin Marketplace in Mattermost v5.16 and above.
|
||||
* For Mattermost v5.13 and earlier, a manual install is necessary.
|
||||
|
||||
## Installation
|
||||
|
||||
### Marketplace installation
|
||||
|
||||
1. Go to **Main Menu > Plugin Marketplace** in Mattermost.
|
||||
2. Search for "gitlab" or manually find the plugin from the list and select **Install**.
|
||||
3. After the plugin has downloaded and been installed, select the **Configure** button.
|
||||
|
||||
### Manual installation
|
||||
|
||||
If your server doesn't have access to the internet, you can download the latest [plugin binary release](https://github.com/mattermost/mattermost-plugin-gitlab/releases) and upload it to your server via **System Console > Plugins > Plugin Management**. The releases on this page are the same used by the Marketplace.
|
||||
|
||||
See the [GitLab plugin release page](https://github.com/mattermost/mattermost-plugin-gitlab/releases) for compatibility considerations.
|
||||
|
||||
## Configuration
|
||||
|
||||
### Step 1: Register an OAuth application in GitLab
|
||||
|
||||
1. Go to https://gitlab.com/-/profile/applications or https://gitlab.yourdomain.com/-/profile/applications to register an OAuth app.
|
||||
1. Set the following values:
|
||||
- **Name**: `Mattermost GitLab Plugin - <your company name>`
|
||||
- **Redirect URI**: `https://your-mattermost-url.com/plugins/com.github.manland.mattermost-plugin-gitlab/oauth/complete`, replacing `https://your-mattermost-url.com` with your Mattermost URL
|
||||
1. Select `api` and `read_user` in **Scopes**.
|
||||
1. Save the application. Copy the **Application ID** and **Secret** fields in the resulting screen.
|
||||
1. In Mattermost, go to **Plugins Marketplace > GitLab > Configure**, and enter the **GitLab URL**, **GitLab OAuth Client ID**, and **GitLab OAuth Client Secret**.
|
||||
|
||||
### Step 2: Configure the plugin in Mattermost
|
||||
|
||||
1. Go to **System Console > Plugins > GitLab** and do the following:
|
||||
- Generate a new value for **Webhook Secret**.
|
||||
- Generate a new value for **At Rest Encryption Key**.
|
||||
- (Optional) **GitLab Group**: Lock the plugin to a single GitLab group by setting this field to the name of your GitLab group.
|
||||
- (Optional) **Enable Private Repositories**: Allow the plugin to receive notifications from private repositories by setting this value to `true`. When enabled, existing users must reconnect their accounts to gain access to private project. Affected users will be notified by the plugin once private repositories are enabled.
|
||||
1. Select **Save**.
|
||||
1. Go to **Plugins Marketplace > GitLab > Configure > Enable Plugin** and select **Enable** to enable the GitLab plugin.
|
||||
|
||||
### Step 3: Connect your GitLab accounts
|
||||
|
||||
Run the `/gitlab connect` slash command to connect your Mattermost account with GitLab.
|
||||
|
||||
### Step 4: Subscribe to projects and groups
|
||||
|
||||
For each project you want to receive notifications for or subscribe to, you must create a webhook. Run the subscribe slash command to watch events sent from GitLab.
|
||||
|
||||
``/gitlab subscriptions add group[/project]``
|
||||
|
||||
Run the webhook slash command to have GitLab send events to Mattermost.
|
||||
|
||||
``/gitlab webhook add group[/project]``
|
||||
|
||||
For versions prior to 1.2:
|
||||
|
||||
1. In GitLab, go to the project you want to subscribe to, select **Settings > Integrations** in the sidebar.
|
||||
2. Set the following values:
|
||||
- **URL**: `https://your-mattermost-url.com/plugins/com.github.manland.mattermost-plugin-gitlab/webhook`, replacing `https://your-mattermost-url.com` with your Mattermost URL. Ensure that you add `/plugins/com.github.manland.mattermost-plugin-gitlab/webhook` to the URL or the webhook won't work.
|
||||
- **Secret Token**: The webhook secret you copied previously.
|
||||
3. Select all the events in **Triggers**.
|
||||
4. Add the webhook.
|
||||
|
||||
### Compatibility
|
||||
|
||||
| Mattermost-Plugin-Gitlab| Mattermost | GitLab |
|
||||
|:-----------------------:|:----------:|:------:|
|
||||
| 0.3.0 | 5.10+ | 11.2+ |
|
||||
| 0.2.0 | 5.8+ | 11.2+ |
|
||||
| 0.1.0 | 5.8+ | 11.2+ |
|
||||
|
||||
### Update the plugin
|
||||
|
||||
When a new version of the plugin is released to the **Plugin Marketplace**, the system will display a prompt asking you to update your current version of the GitLab plugin to the newest one. There may be a warning shown if there is a major version change that **may** affect the installation. Generally, updates are seamless and don't interrupt the user experience in Mattermost.
|
||||
|
||||
## Mattermost commands user guide
|
||||
|
||||
Interact with the GitLab plugin using the `/gitlab` slash command.
|
||||
|
||||
### Subscribe to/unsubscribe from a repository
|
||||
|
||||
Use `/gitlab subscriptions add owner[/repo] [features]` to subscribe a Mattermost channel to receive posts for new merge requests and/or issues, or other features (as listed above), from a GitLab repository. Ensure that the webhook is configured, otherwise this will not work properly.
|
||||
|
||||
Use `/gitlab subscriptions delete owner/repo` to unsubscribe from it.
|
||||
|
||||
`/gitlab subscriptions list` lists what you have subscribed to.
|
||||
|
||||
### Connect to/disconnect from GitLab
|
||||
|
||||
Connect your Mattermost account to your GitLab account using `/gitlab connect` and disconnect it using`/gitlab disconnect`.
|
||||
|
||||
`/gitlab me` displays the connected GitLab account.
|
||||
|
||||
### Get "To Do" items
|
||||
|
||||
Use `/gitlab todo` to get a list of todos, assigned issues, assigned merge requests and merge requests awaiting your review.
|
||||
|
||||
### Update settings
|
||||
|
||||
Use `/gitlab settings [setting] [value]` to update your settings for the plugin. There are two settings:
|
||||
|
||||
- To turn **personal notifications** `on` or `off`.
|
||||
- To turn **reminders** `on` or `off` for when you connect for the first time each day.
|
||||
|
||||
### And more...
|
||||
|
||||
Run `/gitlab help` to see what else the slash command can do.
|
||||
|
||||
**Tip**: Don't forget to add a webhook in GitLab!
|
||||
|
||||
## Development
|
||||
|
||||
This plugin contains both a server and web app portion. Read our documentation about the [Developer Workflow](https://developers.mattermost.com/integrate/plugins/developer-workflow/) and [Developer Setup](https://developers.mattermost.com/integrate/plugins/developer-setup/) for more information about developing and extending plugins.
|
||||
|
||||
## Help wanted!
|
||||
|
||||
If you're interested in joining our community of developers who contribute to Mattermost - check out the current set of issues [that are being requested](https://github.com/mattermost/mattermost-plugin-gitlab/issues?q=is%3Aissue+is%3Aopen+label%3AEnhancement).
|
||||
|
||||
You can also find issues labeled ["Help Wanted"](https://github.com/mattermost/mattermost-plugin-gitlab/issues?q=is%3Aissue+is%3Aopen+label%3A%22Help+Wanted%22) in the GitLab plugin repository that we have laid out the primary requirements for and could use some coding help from the community.
|
||||
|
||||
## Help and support
|
||||
|
||||
For Mattermost customers - please open a [support case](https://mattermost.zendesk.com/hc/en-us/requests/new) to ensure your issue is tracked properly.
|
||||
|
||||
For Questions, suggestions, and help - please find us on our forum at [https://forum.mattermost.org/c/plugins](https://forum.mattermost.org/c/plugins).
|
||||
|
||||
Alternatively, join our public Mattermost server and join the [Integrations and Apps channel](https://community.mattermost.com/core/channels/integrations).
|
||||
|
||||
## Feedback and feature requests
|
||||
|
||||
Feel free to create a GitHub issue or [join the GitLab Plugin channel on our community Mattermost instance](https://community.mattermost.com/core/channels/plugin-gitlab) to discuss.
|
||||
|
||||
Share your thoughts in the [Plugin: GitLab Channel](https://community.mattermost.com/core/channels/gitlab-plugin) on our Mattermost community!
|
||||
|
||||
### Releasing new versions
|
||||
|
||||
The version of a plugin is determined at compile time, automatically populating a `version` field in the [plugin manifest](plugin.json):
|
||||
* If the current commit matches a tag, the version will match after stripping any leading `v`, e.g. `1.3.1`.
|
||||
* Otherwise, the version will combine the nearest tag with `git rev-parse --short HEAD`, e.g. `1.3.1+d06e53e1`.
|
||||
* If there is no version tag, an empty version will be combined with the short hash, e.g. `0.0.0+76081421`.
|
||||
|
||||
To disable this behaviour, manually populate and maintain the `version` field.
|
||||
@@ -0,0 +1,34 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg width="338px" height="311px" viewBox="0 0 338 311" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<!-- Generator: Sketch 57.1 (83088) - https://sketch.com -->
|
||||
<title>gitlab</title>
|
||||
<desc>Created with Sketch.</desc>
|
||||
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
|
||||
<g id="gitlab" fill-rule="nonzero">
|
||||
<g id="g44" fill="#FC6D26">
|
||||
<path d="M337.17,177.83 L318.26,119.71 L280.84,4.43 C279.956602,1.7925919 277.486423,0.0149148401 274.705,0.0149148401 C271.923577,0.0149148401 269.453398,1.7925919 268.57,4.43 L231.15,119.64 L106.82,119.64 L69.4,4.43 C68.5220965,1.78979642 66.0523353,0.00830812195 63.27,0.00830812195 C60.4876647,0.00830812195 58.0179035,1.78979642 57.14,4.43 L19.78,119.64 L0.87,177.83 C-0.853328917,183.12969 1.02714845,188.936572 5.53,192.22 L169,311 L332.44,192.22 C336.963325,188.951421 338.871954,183.144831 337.17,177.83" id="path46"></path>
|
||||
</g>
|
||||
<g id="g48" transform="translate(106.000000, 119.000000)" fill="#E24329">
|
||||
<polygon id="path50" points="63 191.91 63 191.91 125.16 0.63 0.87 0.63"></polygon>
|
||||
</g>
|
||||
<g id="g56" transform="translate(19.000000, 119.000000)" fill="#FC6D26">
|
||||
<polygon id="path58" points="150 191.91 87.82 0.63 0.82 0.63"></polygon>
|
||||
</g>
|
||||
<g id="g64" transform="translate(0.000000, 119.000000)" fill="#FCA326">
|
||||
<path d="M19.75,0.69 L19.75,0.69 L0.84,58.81 C-0.883328917,64.1096898 0.997148451,69.9165716 5.5,73.2 L169,192 L19.75,0.69 Z" id="path66"></path>
|
||||
</g>
|
||||
<g id="g72" transform="translate(19.000000, 0.000000)" fill="#E24329">
|
||||
<path d="M0.78,119.69 L87.89,119.69 L50.4,4.49 C49.5166016,1.8525919 47.046423,0.0749148401 44.265,0.0749148401 C41.483577,0.0749148401 39.0133984,1.8525919 38.13,4.49 L0.78,119.69 Z" id="path74"></path>
|
||||
</g>
|
||||
<g id="g76" transform="translate(169.000000, 119.000000)" fill="#FC6D26">
|
||||
<polygon id="path78" points="0 191.91 62.16 0.63 149.3 0.63"></polygon>
|
||||
</g>
|
||||
<g id="g80" transform="translate(169.000000, 119.000000)" fill="#FCA326">
|
||||
<path d="M149.24,0.69 L149.24,0.69 L168.15,58.81 C169.883261,64.1096795 168.000893,69.9224023 163.49,73.2 L0,191.91 L149.2,0.69 L149.24,0.69 Z" id="path82"></path>
|
||||
</g>
|
||||
<g id="g84" transform="translate(231.000000, 0.000000)" fill="#E24329">
|
||||
<path d="M87.28,119.69 L0.18,119.69 L37.6,4.49 C38.4779035,1.84979642 40.9476647,0.0683081219 43.73,0.0683081219 C46.5123353,0.0683081219 48.9820965,1.84979642 49.86,4.49 L87.28,119.69 Z" id="path86"></path>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.8 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 210 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 55 KiB |
@@ -0,0 +1 @@
|
||||
bin
|
||||
@@ -0,0 +1,18 @@
|
||||
# Include custom targets and environment variables here
|
||||
|
||||
# If there's no MM_RUDDER_PLUGINS_PROD, add DEV data
|
||||
RUDDER_WRITE_KEY = 1d5bMvdrfWClLxgK1FvV3s4U1tg
|
||||
ifdef MM_RUDDER_PLUGINS_PROD
|
||||
RUDDER_WRITE_KEY = $(MM_RUDDER_PLUGINS_PROD)
|
||||
endif
|
||||
GO_BUILD_FLAGS += -ldflags '-X "github.com/mattermost/mattermost/server/public/pluginapi/experimental/telemetry.rudderWriteKey=$(RUDDER_WRITE_KEY)"'
|
||||
|
||||
|
||||
## Generates mock golang interfaces for testing
|
||||
.PHONY: mock
|
||||
mock:
|
||||
ifneq ($(HAS_SERVER),)
|
||||
go install github.com/golang/mock/mockgen@v1.6.0
|
||||
mockgen -destination server/mocks/mock_gitlab.go github.com/mattermost/mattermost-plugin-gitlab/server/gitlab Gitlab
|
||||
mockgen -destination server/gitlab/mocks/mock_gitlab.go github.com/mattermost/mattermost-plugin-gitlab/server/gitlab Gitlab
|
||||
endif
|
||||
@@ -0,0 +1,211 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/mattermost/mattermost/server/public/model"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
const pluginIDGoFileTemplate = `// This file is automatically generated. Do not modify it manually.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
"github.com/mattermost/mattermost/server/public/model"
|
||||
)
|
||||
|
||||
var manifest *model.Manifest
|
||||
|
||||
const manifestStr = ` + "`" + `
|
||||
%s
|
||||
` + "`" + `
|
||||
|
||||
func init() {
|
||||
_ = json.NewDecoder(strings.NewReader(manifestStr)).Decode(&manifest)
|
||||
}
|
||||
`
|
||||
|
||||
const pluginIDJSFileTemplate = `// This file is automatically generated. Do not modify it manually.
|
||||
|
||||
const manifest = JSON.parse(` + "`" + `
|
||||
%s
|
||||
` + "`" + `);
|
||||
|
||||
export default manifest;
|
||||
`
|
||||
|
||||
// These build-time vars are read from shell commands and populated in ../setup.mk
|
||||
var (
|
||||
BuildHashShort string
|
||||
BuildTagLatest string
|
||||
BuildTagCurrent string
|
||||
)
|
||||
|
||||
func main() {
|
||||
if len(os.Args) <= 1 {
|
||||
panic("no cmd specified")
|
||||
}
|
||||
|
||||
manifest, err := findManifest()
|
||||
if err != nil {
|
||||
panic("failed to find manifest: " + err.Error())
|
||||
}
|
||||
|
||||
cmd := os.Args[1]
|
||||
switch cmd {
|
||||
case "id":
|
||||
dumpPluginID(manifest)
|
||||
|
||||
case "version":
|
||||
dumpPluginVersion(manifest)
|
||||
|
||||
case "has_server":
|
||||
if manifest.HasServer() {
|
||||
fmt.Printf("true")
|
||||
}
|
||||
|
||||
case "has_webapp":
|
||||
if manifest.HasWebapp() {
|
||||
fmt.Printf("true")
|
||||
}
|
||||
|
||||
case "apply":
|
||||
if err := applyManifest(manifest); err != nil {
|
||||
panic("failed to apply manifest: " + err.Error())
|
||||
}
|
||||
|
||||
case "dist":
|
||||
if err := distManifest(manifest); err != nil {
|
||||
panic("failed to write manifest to dist directory: " + err.Error())
|
||||
}
|
||||
|
||||
default:
|
||||
panic("unrecognized command: " + cmd)
|
||||
}
|
||||
}
|
||||
|
||||
func findManifest() (*model.Manifest, error) {
|
||||
_, manifestFilePath, err := model.FindManifest(".")
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "failed to find manifest in current working directory")
|
||||
}
|
||||
manifestFile, err := os.Open(manifestFilePath)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(err, "failed to open %s", manifestFilePath)
|
||||
}
|
||||
defer manifestFile.Close()
|
||||
|
||||
// Re-decode the manifest, disallowing unknown fields. When we write the manifest back out,
|
||||
// we don't want to accidentally clobber anything we won't preserve.
|
||||
var manifest model.Manifest
|
||||
decoder := json.NewDecoder(manifestFile)
|
||||
decoder.DisallowUnknownFields()
|
||||
if err = decoder.Decode(&manifest); err != nil {
|
||||
return nil, errors.Wrap(err, "failed to parse manifest")
|
||||
}
|
||||
|
||||
// If no version is listed in the manifest, generate one based on the state of the current
|
||||
// commit, and use the first version we find (to prevent causing errors)
|
||||
if manifest.Version == "" {
|
||||
var version string
|
||||
tags := strings.Fields(BuildTagCurrent)
|
||||
for _, t := range tags {
|
||||
if strings.HasPrefix(t, "v") {
|
||||
version = t
|
||||
break
|
||||
}
|
||||
}
|
||||
if version == "" {
|
||||
if BuildTagLatest != "" {
|
||||
version = BuildTagLatest + "+" + BuildHashShort
|
||||
} else {
|
||||
version = "v0.0.0+" + BuildHashShort
|
||||
}
|
||||
}
|
||||
manifest.Version = strings.TrimPrefix(version, "v")
|
||||
}
|
||||
|
||||
// If no release notes specified, generate one from the latest tag, if present.
|
||||
if manifest.ReleaseNotesURL == "" && BuildTagLatest != "" {
|
||||
manifest.ReleaseNotesURL = manifest.HomepageURL + "releases/tag/" + BuildTagLatest
|
||||
}
|
||||
|
||||
return &manifest, nil
|
||||
}
|
||||
|
||||
// dumpPluginId writes the plugin id from the given manifest to standard out
|
||||
func dumpPluginID(manifest *model.Manifest) {
|
||||
fmt.Printf("%s", manifest.Id)
|
||||
}
|
||||
|
||||
// dumpPluginVersion writes the plugin version from the given manifest to standard out
|
||||
func dumpPluginVersion(manifest *model.Manifest) {
|
||||
fmt.Printf("%s", manifest.Version)
|
||||
}
|
||||
|
||||
// applyManifest propagates the plugin_id into the server and webapp folders, as necessary
|
||||
func applyManifest(manifest *model.Manifest) error {
|
||||
if manifest.HasServer() {
|
||||
// generate JSON representation of Manifest.
|
||||
manifestBytes, err := json.MarshalIndent(manifest, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
manifestStr := string(manifestBytes)
|
||||
|
||||
// write generated code to file by using Go file template.
|
||||
if err := os.WriteFile(
|
||||
"server/manifest.go",
|
||||
[]byte(fmt.Sprintf(pluginIDGoFileTemplate, manifestStr)),
|
||||
0600,
|
||||
); err != nil {
|
||||
return errors.Wrap(err, "failed to write server/manifest.go")
|
||||
}
|
||||
}
|
||||
|
||||
if manifest.HasWebapp() {
|
||||
// generate JSON representation of Manifest.
|
||||
// JSON is very similar and compatible with JS's object literals. so, what we do here
|
||||
// is actually JS code generation.
|
||||
manifestBytes, err := json.MarshalIndent(manifest, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
manifestStr := string(manifestBytes)
|
||||
|
||||
// Escape newlines
|
||||
manifestStr = strings.ReplaceAll(manifestStr, `\n`, `\\n`)
|
||||
|
||||
// write generated code to file by using JS file template.
|
||||
if err := os.WriteFile(
|
||||
"webapp/src/manifest.ts",
|
||||
[]byte(fmt.Sprintf(pluginIDJSFileTemplate, manifestStr)),
|
||||
0600,
|
||||
); err != nil {
|
||||
return errors.Wrap(err, "failed to open webapp/src/manifest.ts")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// distManifest writes the manifest file to the dist directory
|
||||
func distManifest(manifest *model.Manifest) error {
|
||||
manifestBytes, err := json.MarshalIndent(manifest, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := os.WriteFile(fmt.Sprintf("dist/%s/plugin.json", manifest.Id), manifestBytes, 0600); err != nil {
|
||||
return errors.Wrap(err, "failed to write plugin.json")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/mattermost/mattermost/server/public/model"
|
||||
)
|
||||
|
||||
const (
|
||||
logsPerPage = 100 // logsPerPage is the number of log entries to fetch per API call
|
||||
timeStampFormat = "2006-01-02 15:04:05.000 Z07:00"
|
||||
)
|
||||
|
||||
// logs fetches the latest 500 log entries from Mattermost,
|
||||
// and prints only the ones related to the plugin to stdout.
|
||||
func logs(ctx context.Context, client *model.Client4, pluginID string) error {
|
||||
err := checkJSONLogsSetting(ctx, client)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logs, err := fetchLogs(ctx, client, 0, 500, pluginID, time.Unix(0, 0))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to fetch log entries: %w", err)
|
||||
}
|
||||
|
||||
err = printLogEntries(logs)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to print logs entries: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// watchLogs fetches log entries from Mattermost and print them to stdout.
|
||||
// It will return without an error when ctx is canceled.
|
||||
func watchLogs(ctx context.Context, client *model.Client4, pluginID string) error {
|
||||
err := checkJSONLogsSetting(ctx, client)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
var oldestEntry string
|
||||
|
||||
ticker := time.NewTicker(1 * time.Second)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
case <-ticker.C:
|
||||
var page int
|
||||
for {
|
||||
logs, err := fetchLogs(ctx, client, page, logsPerPage, pluginID, now)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to fetch log entries: %w", err)
|
||||
}
|
||||
|
||||
var allNew bool
|
||||
logs, oldestEntry, allNew = checkOldestEntry(logs, oldestEntry)
|
||||
|
||||
err = printLogEntries(logs)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to print logs entries: %w", err)
|
||||
}
|
||||
|
||||
if !allNew {
|
||||
// No more logs to fetch
|
||||
break
|
||||
}
|
||||
page++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// checkOldestEntry check a if logs contains new log entries.
|
||||
// It returns the filtered slice of log entries, the new oldest entry and whether or not all entries were new.
|
||||
func checkOldestEntry(logs []string, oldest string) ([]string, string, bool) {
|
||||
if len(logs) == 0 {
|
||||
return nil, oldest, false
|
||||
}
|
||||
|
||||
newOldestEntry := logs[(len(logs) - 1)]
|
||||
|
||||
i := slices.Index(logs, oldest)
|
||||
switch i {
|
||||
case -1:
|
||||
// Every log entry is new
|
||||
return logs, newOldestEntry, true
|
||||
case len(logs) - 1:
|
||||
// No new log entries
|
||||
return nil, oldest, false
|
||||
default:
|
||||
// Filter out oldest log entry
|
||||
return logs[i+1:], newOldestEntry, false
|
||||
}
|
||||
}
|
||||
|
||||
// fetchLogs fetches log entries from Mattermost
|
||||
// and filters them based on pluginID and timestamp.
|
||||
func fetchLogs(ctx context.Context, client *model.Client4, page, perPage int, pluginID string, since time.Time) ([]string, error) {
|
||||
logs, _, err := client.GetLogs(ctx, page, perPage)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get logs from Mattermost: %w", err)
|
||||
}
|
||||
|
||||
logs, err = filterLogEntries(logs, pluginID, since)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to filter log entries: %w", err)
|
||||
}
|
||||
|
||||
return logs, nil
|
||||
}
|
||||
|
||||
// filterLogEntries filters a given slice of log entries by pluginID.
|
||||
// It also filters out any entries which timestamps are older then since.
|
||||
func filterLogEntries(logs []string, pluginID string, since time.Time) ([]string, error) {
|
||||
type logEntry struct {
|
||||
PluginID string `json:"plugin_id"`
|
||||
Timestamp string `json:"timestamp"`
|
||||
}
|
||||
|
||||
var ret []string
|
||||
|
||||
for _, e := range logs {
|
||||
var le logEntry
|
||||
err := json.Unmarshal([]byte(e), &le)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal log entry into JSON: %w", err)
|
||||
}
|
||||
if le.PluginID != pluginID {
|
||||
continue
|
||||
}
|
||||
|
||||
let, err := time.Parse(timeStampFormat, le.Timestamp)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unknown timestamp format: %w", err)
|
||||
}
|
||||
if let.Before(since) {
|
||||
continue
|
||||
}
|
||||
|
||||
// Log entries returned by the API have a newline a prefix.
|
||||
// Remove that to make printing consistent.
|
||||
e = strings.TrimPrefix(e, "\n")
|
||||
|
||||
ret = append(ret, e)
|
||||
}
|
||||
|
||||
return ret, nil
|
||||
}
|
||||
|
||||
// printLogEntries prints a slice of log entries to stdout.
|
||||
func printLogEntries(entries []string) error {
|
||||
for _, e := range entries {
|
||||
_, err := io.WriteString(os.Stdout, e+"\n")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to write log entry to stdout: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func checkJSONLogsSetting(ctx context.Context, client *model.Client4) error {
|
||||
cfg, _, err := client.GetConfig(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to fetch config: %w", err)
|
||||
}
|
||||
if cfg.LogSettings.FileJson == nil || !*cfg.LogSettings.FileJson {
|
||||
return errors.New("JSON output for file logs are disabled. Please enable LogSettings.FileJson via the configration in Mattermost.") //nolint:all
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestCheckOldestEntry(t *testing.T) {
|
||||
for name, tc := range map[string]struct {
|
||||
logs []string
|
||||
oldest string
|
||||
expectedLogs []string
|
||||
expectedOldest string
|
||||
expectedAllNew bool
|
||||
}{
|
||||
"nil logs": {
|
||||
logs: nil,
|
||||
oldest: "oldest",
|
||||
expectedLogs: nil,
|
||||
expectedOldest: "oldest",
|
||||
expectedAllNew: false,
|
||||
},
|
||||
"empty logs": {
|
||||
logs: []string{},
|
||||
oldest: "oldest",
|
||||
expectedLogs: nil,
|
||||
expectedOldest: "oldest",
|
||||
expectedAllNew: false,
|
||||
},
|
||||
"no new entries, one old entry": {
|
||||
logs: []string{"old"},
|
||||
oldest: "old",
|
||||
expectedLogs: []string{},
|
||||
expectedOldest: "old",
|
||||
expectedAllNew: false,
|
||||
},
|
||||
"no new entries, multipile old entries": {
|
||||
logs: []string{"old1", "old2", "old3"},
|
||||
oldest: "old3",
|
||||
expectedLogs: []string{},
|
||||
expectedOldest: "old3",
|
||||
expectedAllNew: false,
|
||||
},
|
||||
"one new entry, no old entry": {
|
||||
logs: []string{"new"},
|
||||
oldest: "old",
|
||||
expectedLogs: []string{"new"},
|
||||
expectedOldest: "new",
|
||||
expectedAllNew: true,
|
||||
},
|
||||
"multipile new entries, no old entry": {
|
||||
logs: []string{"new1", "new2", "new3"},
|
||||
oldest: "old",
|
||||
expectedLogs: []string{"new1", "new2", "new3"},
|
||||
expectedOldest: "new3",
|
||||
expectedAllNew: true,
|
||||
},
|
||||
"one new entry, one old entry": {
|
||||
logs: []string{"old", "new"},
|
||||
oldest: "old",
|
||||
expectedLogs: []string{"new"},
|
||||
expectedOldest: "new",
|
||||
expectedAllNew: false,
|
||||
},
|
||||
"one new entry, multipile old entries": {
|
||||
logs: []string{"old1", "old2", "old3", "new"},
|
||||
oldest: "old3",
|
||||
expectedLogs: []string{"new"},
|
||||
expectedOldest: "new",
|
||||
expectedAllNew: false,
|
||||
},
|
||||
"multipile new entries, ultipile old entries": {
|
||||
logs: []string{"old1", "old2", "old3", "new1", "new2", "new3"},
|
||||
oldest: "old3",
|
||||
expectedLogs: []string{"new1", "new2", "new3"},
|
||||
expectedOldest: "new3",
|
||||
expectedAllNew: false,
|
||||
},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
logs, oldest, allNew := checkOldestEntry(tc.logs, tc.oldest)
|
||||
|
||||
if allNew != tc.expectedAllNew {
|
||||
t.Logf("expected allNew: %v, got %v", tc.expectedAllNew, allNew)
|
||||
t.Fail()
|
||||
}
|
||||
if oldest != tc.expectedOldest {
|
||||
t.Logf("expected oldest: %v, got %v", tc.expectedOldest, oldest)
|
||||
t.Fail()
|
||||
}
|
||||
|
||||
compareSlice(t, tc.expectedLogs, logs)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterLogEntries(t *testing.T) {
|
||||
now := time.Now()
|
||||
|
||||
for name, tc := range map[string]struct {
|
||||
logs []string
|
||||
pluginID string
|
||||
since time.Time
|
||||
expectedLogs []string
|
||||
expectedErr bool
|
||||
}{
|
||||
"nil slice": {
|
||||
logs: nil,
|
||||
expectedLogs: nil,
|
||||
expectedErr: false,
|
||||
},
|
||||
"empty slice": {
|
||||
logs: []string{},
|
||||
expectedLogs: nil,
|
||||
expectedErr: false,
|
||||
},
|
||||
"no JSON": {
|
||||
logs: []string{
|
||||
`{"foo"`,
|
||||
},
|
||||
expectedLogs: nil,
|
||||
expectedErr: true,
|
||||
},
|
||||
"unknown time format": {
|
||||
logs: []string{
|
||||
`{"message":"foo", "plugin_id": "some.plugin.id", "timestamp": "2023-12-18 10:58:53"}`,
|
||||
},
|
||||
pluginID: "some.plugin.id",
|
||||
expectedLogs: nil,
|
||||
expectedErr: true,
|
||||
},
|
||||
"one matching entry": {
|
||||
logs: []string{
|
||||
`{"message":"foo", "plugin_id": "some.plugin.id", "timestamp": "2023-12-18 10:58:53.091 +01:00"}`,
|
||||
},
|
||||
pluginID: "some.plugin.id",
|
||||
expectedLogs: []string{
|
||||
`{"message":"foo", "plugin_id": "some.plugin.id", "timestamp": "2023-12-18 10:58:53.091 +01:00"}`,
|
||||
},
|
||||
expectedErr: false,
|
||||
},
|
||||
"filter out non plugin entries": {
|
||||
logs: []string{
|
||||
`{"message":"bar1", "timestamp": "2023-12-18 10:58:52.091 +01:00"}`,
|
||||
`{"message":"foo", "plugin_id": "some.plugin.id", "timestamp": "2023-12-18 10:58:53.091 +01:00"}`,
|
||||
`{"message":"bar2", "timestamp": "2023-12-18 10:58:54.091 +01:00"}`,
|
||||
},
|
||||
pluginID: "some.plugin.id",
|
||||
expectedLogs: []string{
|
||||
`{"message":"foo", "plugin_id": "some.plugin.id", "timestamp": "2023-12-18 10:58:53.091 +01:00"}`,
|
||||
},
|
||||
expectedErr: false,
|
||||
},
|
||||
"filter out old entries": {
|
||||
logs: []string{
|
||||
fmt.Sprintf(`{"message":"old2", "plugin_id": "some.plugin.id", "timestamp": "%s"}`, now.Add(-2*time.Second).Format(timeStampFormat)),
|
||||
fmt.Sprintf(`{"message":"old1", "plugin_id": "some.plugin.id", "timestamp": "%s"}`, now.Add(-1*time.Second).Format(timeStampFormat)),
|
||||
fmt.Sprintf(`{"message":"now", "plugin_id": "some.plugin.id", "timestamp": "%s"}`, now.Format(timeStampFormat)),
|
||||
fmt.Sprintf(`{"message":"new1", "plugin_id": "some.plugin.id", "timestamp": "%s"}`, now.Add(1*time.Second).Format(timeStampFormat)),
|
||||
fmt.Sprintf(`{"message":"new2", "plugin_id": "some.plugin.id", "timestamp": "%s"}`, now.Add(2*time.Second).Format(timeStampFormat)),
|
||||
},
|
||||
pluginID: "some.plugin.id",
|
||||
since: now,
|
||||
expectedLogs: []string{
|
||||
fmt.Sprintf(`{"message":"new1", "plugin_id": "some.plugin.id", "timestamp": "%s"}`, now.Add(1*time.Second).Format(timeStampFormat)),
|
||||
fmt.Sprintf(`{"message":"new2", "plugin_id": "some.plugin.id", "timestamp": "%s"}`, now.Add(2*time.Second).Format(timeStampFormat)),
|
||||
},
|
||||
expectedErr: false,
|
||||
},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
logs, err := filterLogEntries(tc.logs, tc.pluginID, tc.since)
|
||||
if tc.expectedErr {
|
||||
if err == nil {
|
||||
t.Logf("expected error, got nil")
|
||||
t.Fail()
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
t.Logf("expected no error, got %v", err)
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
compareSlice(t, tc.expectedLogs, logs)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func compareSlice[S ~[]E, E comparable](t *testing.T, expected, got S) {
|
||||
if len(expected) != len(got) {
|
||||
t.Logf("expected len: %v, got %v", len(expected), len(got))
|
||||
t.FailNow()
|
||||
}
|
||||
|
||||
for i := 0; i < len(expected); i++ {
|
||||
if expected[i] != got[i] {
|
||||
t.Logf("expected [%d]: %v, got %v", i, expected[i], got[i])
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
// main handles deployment of the plugin to a development server using the Client4 API.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/mattermost/mattermost/server/public/model"
|
||||
)
|
||||
|
||||
const commandTimeout = 120 * time.Second
|
||||
|
||||
const helpText = `
|
||||
Usage:
|
||||
pluginctl deploy <plugin id> <bundle path>
|
||||
pluginctl disable <plugin id>
|
||||
pluginctl enable <plugin id>
|
||||
pluginctl reset <plugin id>
|
||||
`
|
||||
|
||||
func main() {
|
||||
err := pluginctl()
|
||||
if err != nil {
|
||||
fmt.Printf("Failed: %s\n", err.Error())
|
||||
fmt.Print(helpText)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func pluginctl() error {
|
||||
if len(os.Args) < 3 {
|
||||
return errors.New("invalid number of arguments")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), commandTimeout)
|
||||
defer cancel()
|
||||
|
||||
client, err := getClient(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
switch os.Args[1] {
|
||||
case "deploy":
|
||||
if len(os.Args) < 4 {
|
||||
return errors.New("invalid number of arguments")
|
||||
}
|
||||
return deploy(ctx, client, os.Args[2], os.Args[3])
|
||||
case "disable":
|
||||
return disablePlugin(ctx, client, os.Args[2])
|
||||
case "enable":
|
||||
return enablePlugin(ctx, client, os.Args[2])
|
||||
case "reset":
|
||||
return resetPlugin(ctx, client, os.Args[2])
|
||||
case "logs":
|
||||
return logs(ctx, client, os.Args[2])
|
||||
case "logs-watch":
|
||||
return watchLogs(context.WithoutCancel(ctx), client, os.Args[2]) // Keep watching forever
|
||||
default:
|
||||
return errors.New("invalid second argument")
|
||||
}
|
||||
}
|
||||
|
||||
func getClient(ctx context.Context) (*model.Client4, error) {
|
||||
socketPath := os.Getenv("MM_LOCALSOCKETPATH")
|
||||
if socketPath == "" {
|
||||
socketPath = model.LocalModeSocketPath
|
||||
}
|
||||
|
||||
client, connected := getUnixClient(socketPath)
|
||||
if connected {
|
||||
log.Printf("Connecting using local mode over %s", socketPath)
|
||||
return client, nil
|
||||
}
|
||||
|
||||
if os.Getenv("MM_LOCALSOCKETPATH") != "" {
|
||||
log.Printf("No socket found at %s for local mode deployment. Attempting to authenticate with credentials.", socketPath)
|
||||
}
|
||||
|
||||
siteURL := os.Getenv("MM_SERVICESETTINGS_SITEURL")
|
||||
adminToken := os.Getenv("MM_ADMIN_TOKEN")
|
||||
adminUsername := os.Getenv("MM_ADMIN_USERNAME")
|
||||
adminPassword := os.Getenv("MM_ADMIN_PASSWORD")
|
||||
|
||||
if siteURL == "" {
|
||||
return nil, errors.New("MM_SERVICESETTINGS_SITEURL is not set")
|
||||
}
|
||||
|
||||
client = model.NewAPIv4Client(siteURL)
|
||||
|
||||
if adminToken != "" {
|
||||
log.Printf("Authenticating using token against %s.", siteURL)
|
||||
client.SetToken(adminToken)
|
||||
return client, nil
|
||||
}
|
||||
|
||||
if adminUsername != "" && adminPassword != "" {
|
||||
client := model.NewAPIv4Client(siteURL)
|
||||
log.Printf("Authenticating as %s against %s.", adminUsername, siteURL)
|
||||
_, _, err := client.Login(ctx, adminUsername, adminPassword)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to login as %s: %w", adminUsername, err)
|
||||
}
|
||||
|
||||
return client, nil
|
||||
}
|
||||
|
||||
return nil, errors.New("one of MM_ADMIN_TOKEN or MM_ADMIN_USERNAME/MM_ADMIN_PASSWORD must be defined")
|
||||
}
|
||||
|
||||
func getUnixClient(socketPath string) (*model.Client4, bool) {
|
||||
_, err := net.Dial("unix", socketPath)
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
return model.NewAPIv4SocketClient(socketPath), true
|
||||
}
|
||||
|
||||
// deploy attempts to upload and enable a plugin via the Client4 API.
|
||||
// It will fail if plugin uploads are disabled.
|
||||
func deploy(ctx context.Context, client *model.Client4, pluginID, bundlePath string) error {
|
||||
pluginBundle, err := os.Open(bundlePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open %s: %w", bundlePath, err)
|
||||
}
|
||||
defer pluginBundle.Close()
|
||||
|
||||
log.Print("Uploading plugin via API.")
|
||||
_, _, err = client.UploadPluginForced(ctx, pluginBundle)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to upload plugin bundle: %s", err.Error())
|
||||
}
|
||||
|
||||
log.Print("Enabling plugin.")
|
||||
_, err = client.EnablePlugin(ctx, pluginID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to enable plugin: %s", err.Error())
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// disablePlugin attempts to disable the plugin via the Client4 API.
|
||||
func disablePlugin(ctx context.Context, client *model.Client4, pluginID string) error {
|
||||
log.Print("Disabling plugin.")
|
||||
_, err := client.DisablePlugin(ctx, pluginID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to disable plugin: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// enablePlugin attempts to enable the plugin via the Client4 API.
|
||||
func enablePlugin(ctx context.Context, client *model.Client4, pluginID string) error {
|
||||
log.Print("Enabling plugin.")
|
||||
_, err := client.EnablePlugin(ctx, pluginID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to enable plugin: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// resetPlugin attempts to reset the plugin via the Client4 API.
|
||||
func resetPlugin(ctx context.Context, client *model.Client4, pluginID string) error {
|
||||
err := disablePlugin(ctx, client, pluginID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = enablePlugin(ctx, client, pluginID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
# Ensure that go is installed. Note that this is independent of whether or not a server is being
|
||||
# built, since the build script itself uses go.
|
||||
ifeq ($(GO),)
|
||||
$(error "go is not available: see https://golang.org/doc/install")
|
||||
endif
|
||||
|
||||
# Gather build variables to inject into the manifest tool
|
||||
BUILD_HASH_SHORT = $(shell git rev-parse --short HEAD)
|
||||
BUILD_TAG_LATEST = $(shell git describe --tags --match 'v*' --abbrev=0 2>/dev/null)
|
||||
BUILD_TAG_CURRENT = $(shell git tag --points-at HEAD)
|
||||
|
||||
# Ensure that the build tools are compiled. Go's caching makes this quick.
|
||||
$(shell cd build/manifest && $(GO) build -ldflags '-X "main.BuildHashShort=$(BUILD_HASH_SHORT)" -X "main.BuildTagLatest=$(BUILD_TAG_LATEST)" -X "main.BuildTagCurrent=$(BUILD_TAG_CURRENT)"' -o ../bin/manifest)
|
||||
|
||||
# Ensure that the deployment tools are compiled. Go's caching makes this quick.
|
||||
$(shell cd build/pluginctl && $(GO) build -o ../bin/pluginctl)
|
||||
|
||||
# Extract the plugin id from the manifest.
|
||||
PLUGIN_ID ?= $(shell build/bin/manifest id)
|
||||
ifeq ($(PLUGIN_ID),)
|
||||
$(error "Cannot parse id from $(MANIFEST_FILE)")
|
||||
endif
|
||||
|
||||
# Extract the plugin version from the manifest.
|
||||
PLUGIN_VERSION ?= $(shell build/bin/manifest version)
|
||||
ifeq ($(PLUGIN_VERSION),)
|
||||
$(error "Cannot parse version from $(MANIFEST_FILE)")
|
||||
endif
|
||||
|
||||
# Determine if a server is defined in the manifest.
|
||||
HAS_SERVER ?= $(shell build/bin/manifest has_server)
|
||||
|
||||
# Determine if a webapp is defined in the manifest.
|
||||
HAS_WEBAPP ?= $(shell build/bin/manifest has_webapp)
|
||||
|
||||
# Determine if a /public folder is in use
|
||||
HAS_PUBLIC ?= $(wildcard public/.)
|
||||
|
||||
# Determine if the mattermost-utilities repo is present
|
||||
HAS_MM_UTILITIES ?= $(wildcard $(MM_UTILITIES_DIR)/.)
|
||||
|
||||
# Store the current path for later use
|
||||
PWD ?= $(shell pwd)
|
||||
|
||||
# Ensure that npm (and thus node) is installed.
|
||||
ifneq ($(HAS_WEBAPP),)
|
||||
ifeq ($(NPM),)
|
||||
$(error "npm is not available: see https://www.npmjs.com/get-npm")
|
||||
endif
|
||||
endif
|
||||
@@ -0,0 +1,74 @@
|
||||
module github.com/mattermost/mattermost-plugin-gitlab
|
||||
|
||||
go 1.21
|
||||
|
||||
require (
|
||||
github.com/golang/mock v1.6.0
|
||||
github.com/gorilla/mux v1.8.0
|
||||
github.com/mattermost/mattermost/server/public v0.0.9-0.20230830065520-5de1e306de52
|
||||
github.com/microcosm-cc/bluemonday v1.0.19
|
||||
github.com/pkg/errors v0.9.1
|
||||
github.com/stretchr/testify v1.8.4
|
||||
github.com/xanzy/go-gitlab v0.97.0
|
||||
golang.org/x/oauth2 v0.7.0
|
||||
golang.org/x/sync v0.1.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/aymerick/douceur v0.2.0 // indirect
|
||||
github.com/blang/semver/v4 v4.0.0 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/dyatlov/go-opengraph/opengraph v0.0.0-20220524092352-606d7b1e5f8a // indirect
|
||||
github.com/fatih/color v1.15.0 // indirect
|
||||
github.com/francoispqt/gojay v1.2.13 // indirect
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.4 // indirect
|
||||
github.com/go-sql-driver/mysql v1.7.1 // indirect
|
||||
github.com/golang/protobuf v1.5.3 // indirect
|
||||
github.com/google/go-querystring v1.1.0 // indirect
|
||||
github.com/google/uuid v1.3.0 // indirect
|
||||
github.com/gorilla/css v1.0.0 // indirect
|
||||
github.com/gorilla/websocket v1.5.0 // indirect
|
||||
github.com/graph-gophers/graphql-go v1.5.1-0.20230110080634-edea822f558a // indirect
|
||||
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
|
||||
github.com/hashicorp/go-hclog v1.5.0 // indirect
|
||||
github.com/hashicorp/go-plugin v1.4.10 // indirect
|
||||
github.com/hashicorp/go-retryablehttp v0.7.2 // indirect
|
||||
github.com/hashicorp/yamux v0.1.1 // indirect
|
||||
github.com/lib/pq v1.10.9 // indirect
|
||||
github.com/mattermost/go-i18n v1.11.1-0.20211013152124-5c415071e404 // indirect
|
||||
github.com/mattermost/ldap v0.0.0-20201202150706-ee0e6284187d // indirect
|
||||
github.com/mattermost/logr/v2 v2.0.16 // indirect
|
||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||
github.com/mattn/go-isatty v0.0.19 // indirect
|
||||
github.com/mitchellh/go-testing-interface v1.14.1 // indirect
|
||||
github.com/oklog/run v1.1.0 // indirect
|
||||
github.com/pborman/uuid v1.2.1 // indirect
|
||||
github.com/pelletier/go-toml v1.9.5 // indirect
|
||||
github.com/philhofer/fwd v1.1.2 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/rudderlabs/analytics-go v3.3.3+incompatible // indirect
|
||||
github.com/segmentio/backo-go v1.0.1 // indirect
|
||||
github.com/sirupsen/logrus v1.9.3 // indirect
|
||||
github.com/stretchr/objx v0.5.0 // indirect
|
||||
github.com/tidwall/gjson v1.14.3 // indirect
|
||||
github.com/tidwall/match v1.1.1 // indirect
|
||||
github.com/tidwall/pretty v1.2.0 // indirect
|
||||
github.com/tinylib/msgp v1.1.8 // indirect
|
||||
github.com/vmihailenco/msgpack/v5 v5.3.5 // indirect
|
||||
github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect
|
||||
github.com/wiggin77/merror v1.0.5 // indirect
|
||||
github.com/wiggin77/srslog v1.0.1 // indirect
|
||||
github.com/xtgo/uuid v0.0.0-20140804021211-a0b114877d4c // indirect
|
||||
golang.org/x/crypto v0.21.0 // indirect
|
||||
golang.org/x/net v0.23.0 // indirect
|
||||
golang.org/x/sys v0.18.0 // indirect
|
||||
golang.org/x/text v0.14.0 // indirect
|
||||
golang.org/x/time v0.3.0 // indirect
|
||||
google.golang.org/appengine v1.6.7 // indirect
|
||||
google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 // indirect
|
||||
google.golang.org/grpc v1.56.3 // indirect
|
||||
google.golang.org/protobuf v1.33.0 // indirect
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
@@ -0,0 +1,384 @@
|
||||
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
|
||||
cloud.google.com/go v0.31.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
|
||||
cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
|
||||
cloud.google.com/go v0.37.0/go.mod h1:TS1dMSSfndXH133OKGwekG838Om/cQT0BUHV3HcBgoo=
|
||||
dmitri.shuralyov.com/app/changes v0.0.0-20180602232624-0a106ad413e3/go.mod h1:Yl+fi1br7+Rr3LqpNJf1/uxUdtRUV+Tnj0o93V2B9MU=
|
||||
dmitri.shuralyov.com/html/belt v0.0.0-20180602232347-f7d459c86be0/go.mod h1:JLBrvjyP0v+ecvNYvCpyZgu5/xkfAUhi6wJj28eUfSU=
|
||||
dmitri.shuralyov.com/service/change v0.0.0-20181023043359-a85b471d5412/go.mod h1:a1inKt/atXimZ4Mv927x+r7UpyzRUf4emIoiiSC2TN4=
|
||||
dmitri.shuralyov.com/state v0.0.0-20180228185332-28bcc343414c/go.mod h1:0PRwlb0D6DFvNNtx+9ybjezNCa8XF0xaYcETyp6rHWU=
|
||||
git.apache.org/thrift.git v0.0.0-20180902110319-2566ecd5d999/go.mod h1:fPE2ZNJGynbRyZ4dJvy6G277gSllfV2HJqblrnkyeyg=
|
||||
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||
github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239/go.mod h1:2FmKhYUyUczH0OGQWaF5ceTx0UBShxjsH6f8oGKYe2c=
|
||||
github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk=
|
||||
github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4=
|
||||
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
|
||||
github.com/blang/semver/v4 v4.0.0 h1:1PFHFE6yCCTv8C1TeyNNarDzntLi7wMI5i/pzqYIsAM=
|
||||
github.com/blang/semver/v4 v4.0.0/go.mod h1:IbckMUScFkM3pff0VJDNKRiT6TG/YpiHIM2yvyW5YoQ=
|
||||
github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 h1:DDGfHa7BWjL4YnC6+E63dPcxHo2sUxDIu8g3QgEJdRY=
|
||||
github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869/go.mod h1:Ekp36dRnpXw/yCqJaO+ZrUyxD+3VXMFFr56k5XYrpB4=
|
||||
github.com/bradfitz/go-smtpd v0.0.0-20170404230938-deb6d6237625/go.mod h1:HYsPBTaaSFSlLx/70C2HPIMNZpVV8+vt/A+FMnYP11g=
|
||||
github.com/buger/jsonparser v0.0.0-20181115193947-bf1c66bbce23/go.mod h1:bbYlZJ7hK1yFx9hf58LP0zeX7UjIGs20ufpu3evjr+s=
|
||||
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
|
||||
github.com/coreos/go-systemd v0.0.0-20181012123002-c6f51f82210d/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
|
||||
github.com/dyatlov/go-opengraph/opengraph v0.0.0-20220524092352-606d7b1e5f8a h1:etIrTD8BQqzColk9nKRusM9um5+1q0iOEJLqfBMIK64=
|
||||
github.com/dyatlov/go-opengraph/opengraph v0.0.0-20220524092352-606d7b1e5f8a/go.mod h1:emQhSYTXqB0xxjLITTw4EaWZ+8IIQYw+kx9GqNUKdLg=
|
||||
github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk=
|
||||
github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs=
|
||||
github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw=
|
||||
github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc=
|
||||
github.com/francoispqt/gojay v1.2.13 h1:d2m3sFjloqoIUQU3TsHBgj6qg/BVGlTBeHDUmyJnXKk=
|
||||
github.com/francoispqt/gojay v1.2.13/go.mod h1:ehT5mTG4ua4581f1++1WLG0vPdaA9HaiDsoyrBGkyDY=
|
||||
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
|
||||
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
|
||||
github.com/gliderlabs/ssh v0.1.1/go.mod h1:U7qILu1NlMHj9FlMhZLlkCdDnU1DBEAqr0aevW3Awn0=
|
||||
github.com/go-asn1-ber/asn1-ber v1.3.2-0.20191121212151-29be175fc3a3/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.4 h1:vXT6d/FNDiELJnLb6hGNa309LMsrCoYFvpwHDF0+Y1A=
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.4/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
|
||||
github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q=
|
||||
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||
github.com/go-logr/logr v1.2.3/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/go-sql-driver/mysql v1.7.1 h1:lUIinVbN1DY0xBg0eMOzmmtGoHwWBbvnWubQUrtU8EI=
|
||||
github.com/go-sql-driver/mysql v1.7.1/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
|
||||
github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
|
||||
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
|
||||
github.com/golang/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:tluoj9z5200jBnyusfRPU2LqT6J+DAorxEvtC7LHB+E=
|
||||
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
|
||||
github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
|
||||
github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc=
|
||||
github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs=
|
||||
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||
github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg=
|
||||
github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
|
||||
github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
|
||||
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
|
||||
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE=
|
||||
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
|
||||
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/go-github v17.0.0+incompatible/go.mod h1:zLgOLi98H3fifZn+44m+umXrS52loVEgC2AApnigrVQ=
|
||||
github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck=
|
||||
github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8=
|
||||
github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU=
|
||||
github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=
|
||||
github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
|
||||
github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
|
||||
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/googleapis/gax-go v2.0.0+incompatible/go.mod h1:SFVmujtThgffbyetf+mdk2eWhX2bMyUtNHzFKcPA9HY=
|
||||
github.com/googleapis/gax-go/v2 v2.0.3/go.mod h1:LLvjysVCY1JZeum8Z6l8qUty8fiNwE08qbEPm1M08qg=
|
||||
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
|
||||
github.com/gorilla/css v1.0.0 h1:BQqNyPTi50JCFMTw/b67hByjMVXZRwGha6wxVGkeihY=
|
||||
github.com/gorilla/css v1.0.0/go.mod h1:Dn721qIggHpt4+EFCcTLTU/vk5ySda2ReITrtgBl60c=
|
||||
github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
|
||||
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
|
||||
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
|
||||
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/graph-gophers/graphql-go v1.5.1-0.20230110080634-edea822f558a h1:i0+Se9S+2zL5CBxJouqn2Ej6UQMwH1c57ZB6DVnqck4=
|
||||
github.com/graph-gophers/graphql-go v1.5.1-0.20230110080634-edea822f558a/go.mod h1:YtmJZDLbF1YYNrlNAuiO5zAStUWc3XZT07iGsVqe1Os=
|
||||
github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA=
|
||||
github.com/grpc-ecosystem/grpc-gateway v1.5.0/go.mod h1:RSKVYQBd5MCa4OVpNdGskqpgL2+G+NZTnrVHpWWfpdw=
|
||||
github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ=
|
||||
github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48=
|
||||
github.com/hashicorp/go-hclog v0.9.2/go.mod h1:5CU+agLiy3J7N7QjHK5d05KxGsuXiQLrjA0H7acj2lQ=
|
||||
github.com/hashicorp/go-hclog v1.5.0 h1:bI2ocEMgcVlz55Oj1xZNBsVi900c7II+fWDyV9o+13c=
|
||||
github.com/hashicorp/go-hclog v1.5.0/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M=
|
||||
github.com/hashicorp/go-plugin v1.4.10 h1:xUbmA4jC6Dq163/fWcp8P3JuHilrHHMLNRxzGQJ9hNk=
|
||||
github.com/hashicorp/go-plugin v1.4.10/go.mod h1:6/1TEzT0eQznvI/gV2CM29DLSkAK/e58mUWKVsPaph0=
|
||||
github.com/hashicorp/go-retryablehttp v0.7.2 h1:AcYqCvkpalPnPF2pn0KamgwamS42TqUDDYFRKq/RAd0=
|
||||
github.com/hashicorp/go-retryablehttp v0.7.2/go.mod h1:Jy/gPYAdjqffZ/yFGCFV2doI5wjtH1ewM9u8iYVjtX8=
|
||||
github.com/hashicorp/yamux v0.1.1 h1:yrQxtgseBDrq9Y652vSRDvsKCJKOUD+GzTS4Y0Y8pvE=
|
||||
github.com/hashicorp/yamux v0.1.1/go.mod h1:CtWFDAQgb7dxtzFs4tWbplKIe2jSi3+5vKbgIO0SLnQ=
|
||||
github.com/jellevandenhooff/dkim v0.0.0-20150330215556-f50fe3d243e1/go.mod h1:E0B/fFc00Y+Rasa88328GlI/XbtyysCtTHZS8h7IrBU=
|
||||
github.com/jhump/protoreflect v1.6.0 h1:h5jfMVslIg6l29nsMs0D8Wj17RDVdNYti0vDN/PZZoE=
|
||||
github.com/jhump/protoreflect v1.6.0/go.mod h1:eaTn3RZAmMBcV0fifFvlm6VHNz3wSkYyXYWUh7ymB74=
|
||||
github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
|
||||
github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU=
|
||||
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
|
||||
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/pty v1.1.3/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
||||
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||
github.com/lunixbochs/vtclean v1.0.0/go.mod h1:pHhQNgMf3btfWnGBVipUOjRYhoOsdGqdm/+2c2E2WMI=
|
||||
github.com/mailru/easyjson v0.0.0-20190312143242-1de009706dbe/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
|
||||
github.com/mattermost/go-i18n v1.11.1-0.20211013152124-5c415071e404 h1:Khvh6waxG1cHc4Cz5ef9n3XVCxRWpAKUtqg9PJl5+y8=
|
||||
github.com/mattermost/go-i18n v1.11.1-0.20211013152124-5c415071e404/go.mod h1:RyS7FDNQlzF1PsjbJWHRI35exqaKGSO9qD4iv8QjE34=
|
||||
github.com/mattermost/ldap v0.0.0-20201202150706-ee0e6284187d h1:/RJ/UV7M5c7L2TQ0KNm4yZxxFvC1nvRz/gY/Daa35aI=
|
||||
github.com/mattermost/ldap v0.0.0-20201202150706-ee0e6284187d/go.mod h1:HLbgMEI5K131jpxGazJ97AxfPDt31osq36YS1oxFQPQ=
|
||||
github.com/mattermost/logr/v2 v2.0.16 h1:jnePX4cPskC3WDFvUardh/xZfxNdsFXbEERJQ1kUEDE=
|
||||
github.com/mattermost/logr/v2 v2.0.16/go.mod h1:1dm/YhTpozsqANXxo5Pi5zYLBsal2xY0pX+JZNbzYJY=
|
||||
github.com/mattermost/mattermost/server/public v0.0.9-0.20230830065520-5de1e306de52 h1:MFPVn7arQrF/eioUT2LHf9ERSM9GuHkYjCSboAp3RlI=
|
||||
github.com/mattermost/mattermost/server/public v0.0.9-0.20230830065520-5de1e306de52/go.mod h1:sgXQrYzs+IJy51mB8E8OBljagk2u3YwQRoYlBH5goiw=
|
||||
github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
|
||||
github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=
|
||||
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
|
||||
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
||||
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
|
||||
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
|
||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
|
||||
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
|
||||
github.com/microcosm-cc/bluemonday v1.0.1/go.mod h1:hsXNsILzKxV+sX77C5b8FSuKF00vh2OMYv+xgHpAMF4=
|
||||
github.com/microcosm-cc/bluemonday v1.0.19 h1:OI7hoF5FY4pFz2VA//RN8TfM0YJ2dJcl4P4APrCWy6c=
|
||||
github.com/microcosm-cc/bluemonday v1.0.19/go.mod h1:QNzV2UbLK2/53oIIwTOyLUSABMkjZ4tqiyC1g/DyqxE=
|
||||
github.com/mitchellh/go-testing-interface v1.14.1 h1:jrgshOhYAUVNMAJiKbEu7EqAwgJJ2JqpQmpLJOu07cU=
|
||||
github.com/mitchellh/go-testing-interface v1.14.1/go.mod h1:gfgS7OtZj6MA4U1UrDRp04twqAjfvlZyCfX3sDjEym8=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
|
||||
github.com/neelance/astrewrite v0.0.0-20160511093645-99348263ae86/go.mod h1:kHJEU3ofeGjhHklVoIGuVj85JJwZ6kWPaJwCIxgnFmo=
|
||||
github.com/neelance/sourcemap v0.0.0-20151028013722-8c68805598ab/go.mod h1:Qr6/a/Q4r9LP1IltGz7tA7iOK1WonHEYhu1HRBA7ZiM=
|
||||
github.com/oklog/run v1.1.0 h1:GEenZ1cK0+q0+wsJew9qUg/DyD8k3JzYsZAi5gYi2mA=
|
||||
github.com/oklog/run v1.1.0/go.mod h1:sVPdnTZT1zYwAJeCMu2Th4T21pA3FPOQRfWjQlk7DVU=
|
||||
github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc=
|
||||
github.com/openzipkin/zipkin-go v0.1.1/go.mod h1:NtoC/o8u3JlF1lSlyPNswIbeQH9bJTmOf0Erfk+hxe8=
|
||||
github.com/pborman/uuid v1.2.1 h1:+ZZIw58t/ozdjRaXh/3awHfmWRbzYxJoAdNJxe/3pvw=
|
||||
github.com/pborman/uuid v1.2.1/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k=
|
||||
github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
|
||||
github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8=
|
||||
github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c=
|
||||
github.com/philhofer/fwd v1.1.2 h1:bnDivRJ1EWPjUIRXV5KfORO897HTbpFAQddBdE8t7Gw=
|
||||
github.com/philhofer/fwd v1.1.2/go.mod h1:qkPdfjR2SIEbspLqpe1tO4n5yICnr2DY7mqEx2tUTP0=
|
||||
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/prometheus/client_golang v0.8.0/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
|
||||
github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
|
||||
github.com/prometheus/common v0.0.0-20180801064454-c7de2306084e/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro=
|
||||
github.com/prometheus/procfs v0.0.0-20180725123919-05ee40e3a273/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
|
||||
github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8=
|
||||
github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE=
|
||||
github.com/rudderlabs/analytics-go v3.3.3+incompatible h1:OG0XlKoXfr539e2t1dXtTB+Gr89uFW+OUNQBVhHIIBY=
|
||||
github.com/rudderlabs/analytics-go v3.3.3+incompatible/go.mod h1:LF8/ty9kUX4PTY3l5c97K3nZZaX5Hwsvt+NBaRL/f30=
|
||||
github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g=
|
||||
github.com/segmentio/backo-go v1.0.1 h1:68RQccglxZeyURy93ASB/2kc9QudzgIDexJ927N++y4=
|
||||
github.com/segmentio/backo-go v1.0.1/go.mod h1:9/Rh6yILuLysoQnZ2oNooD2g7aBnvM7r/fNVxRNWfBc=
|
||||
github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=
|
||||
github.com/shurcooL/component v0.0.0-20170202220835-f88ec8f54cc4/go.mod h1:XhFIlyj5a1fBNx5aJTbKoIq0mNaPvOagO+HjB3EtxrY=
|
||||
github.com/shurcooL/events v0.0.0-20181021180414-410e4ca65f48/go.mod h1:5u70Mqkb5O5cxEA8nxTsgrgLehJeAw6Oc4Ab1c/P1HM=
|
||||
github.com/shurcooL/github_flavored_markdown v0.0.0-20181002035957-2122de532470/go.mod h1:2dOwnU2uBioM+SGy2aZoq1f/Sd1l9OkAeAUvjSyvgU0=
|
||||
github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk=
|
||||
github.com/shurcooL/go-goon v0.0.0-20170922171312-37c2f522c041/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ=
|
||||
github.com/shurcooL/gofontwoff v0.0.0-20180329035133-29b52fc0a18d/go.mod h1:05UtEgK5zq39gLST6uB0cf3NEHjETfB4Fgr3Gx5R9Vw=
|
||||
github.com/shurcooL/gopherjslib v0.0.0-20160914041154-feb6d3990c2c/go.mod h1:8d3azKNyqcHP1GaQE/c6dDgjkgSx2BZ4IoEi4F1reUI=
|
||||
github.com/shurcooL/highlight_diff v0.0.0-20170515013008-09bb4053de1b/go.mod h1:ZpfEhSmds4ytuByIcDnOLkTHGUI6KNqRNPDLHDk+mUU=
|
||||
github.com/shurcooL/highlight_go v0.0.0-20181028180052-98c3abbbae20/go.mod h1:UDKB5a1T23gOMUJrI+uSuH0VRDStOiUVSjBTRDVBVag=
|
||||
github.com/shurcooL/home v0.0.0-20181020052607-80b7ffcb30f9/go.mod h1:+rgNQw2P9ARFAs37qieuu7ohDNQ3gds9msbT2yn85sg=
|
||||
github.com/shurcooL/htmlg v0.0.0-20170918183704-d01228ac9e50/go.mod h1:zPn1wHpTIePGnXSHpsVPWEktKXHr6+SS6x/IKRb7cpw=
|
||||
github.com/shurcooL/httperror v0.0.0-20170206035902-86b7830d14cc/go.mod h1:aYMfkZ6DWSJPJ6c4Wwz3QtW22G7mf/PEgaB9k/ik5+Y=
|
||||
github.com/shurcooL/httpfs v0.0.0-20171119174359-809beceb2371/go.mod h1:ZY1cvUeJuFPAdZ/B6v7RHavJWZn2YPVFQ1OSXhCGOkg=
|
||||
github.com/shurcooL/httpgzip v0.0.0-20180522190206-b1c53ac65af9/go.mod h1:919LwcH0M7/W4fcZ0/jy0qGght1GIhqyS/EgWGH2j5Q=
|
||||
github.com/shurcooL/issues v0.0.0-20181008053335-6292fdc1e191/go.mod h1:e2qWDig5bLteJ4fwvDAc2NHzqFEthkqn7aOZAOpj+PQ=
|
||||
github.com/shurcooL/issuesapp v0.0.0-20180602232740-048589ce2241/go.mod h1:NPpHK2TI7iSaM0buivtFUc9offApnI0Alt/K8hcHy0I=
|
||||
github.com/shurcooL/notifications v0.0.0-20181007000457-627ab5aea122/go.mod h1:b5uSkrEVM1jQUspwbixRBhaIjIzL2xazXp6kntxYle0=
|
||||
github.com/shurcooL/octicon v0.0.0-20181028054416-fa4f57f9efb2/go.mod h1:eWdoE5JD4R5UVWDucdOPg1g2fqQRq78IQa9zlOV1vpQ=
|
||||
github.com/shurcooL/reactions v0.0.0-20181006231557-f2e0b4ca5b82/go.mod h1:TCR1lToEk4d2s07G3XGfz2QrgHXg4RJBvjrOozvoWfk=
|
||||
github.com/shurcooL/sanitized_anchor_name v0.0.0-20170918181015-86672fcb3f95/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
|
||||
github.com/shurcooL/users v0.0.0-20180125191416-49c67e49c537/go.mod h1:QJTqeLYEDaXHZDBsXlPCDqdhQuJkuw4NOtaxYe3xii4=
|
||||
github.com/shurcooL/webdavfs v0.0.0-20170829043945-18c3829fa133/go.mod h1:hKmq5kWdCj2z2KEozexVbfEZIWiTjhE0+UjmZgPqehw=
|
||||
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
|
||||
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
|
||||
github.com/sourcegraph/annotate v0.0.0-20160123013949-f4cad6c6324d/go.mod h1:UdhH50NIW0fCiwBSr0co2m7BnFLdv4fQTgdqdJTHFeE=
|
||||
github.com/sourcegraph/syntaxhighlight v0.0.0-20170531221838-bd320f5d308e/go.mod h1:HuIsMU8RRBOtsCgI77wP899iHVBQpCmg4ErYMZB+2IA=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0 h1:1zr/of2m5FGMsad5YfcqgdqdWrIhu+EBEJRhR1U7z/c=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07/go.mod h1:kDXzergiv9cbyO7IOYJZWg1U88JhDg3PB6klq9Hg2pA=
|
||||
github.com/tidwall/gjson v1.14.3 h1:9jvXn7olKEHU1S9vwoMGliaT8jq1vJ7IH/n9zD9Dnlw=
|
||||
github.com/tidwall/gjson v1.14.3/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
|
||||
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
|
||||
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
|
||||
github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs=
|
||||
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
|
||||
github.com/tinylib/msgp v1.1.8 h1:FCXC1xanKO4I8plpHGH2P7koL/RzZs12l/+r7vakfm0=
|
||||
github.com/tinylib/msgp v1.1.8/go.mod h1:qkpG+2ldGg4xRFmx+jfTvZPxfGFhi64BcnL9vkCm/Tw=
|
||||
github.com/viant/assertly v0.4.8/go.mod h1:aGifi++jvCrUaklKEKT0BU95igDNaqkvz+49uaYMPRU=
|
||||
github.com/viant/toolbox v0.24.0/go.mod h1:OxMCG57V0PXuIP2HNQrtJf2CjqdmbrOx5EkMILuUhzM=
|
||||
github.com/vmihailenco/msgpack/v5 v5.3.5 h1:5gO0H1iULLWGhs2H5tbAHIZTV8/cYafcFOr9znI5mJU=
|
||||
github.com/vmihailenco/msgpack/v5 v5.3.5/go.mod h1:7xyJ9e+0+9SaZT0Wt1RGleJXzli6Q/V5KbhBonMG9jc=
|
||||
github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g=
|
||||
github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds=
|
||||
github.com/wiggin77/merror v1.0.5 h1:P+lzicsn4vPMycAf2mFf7Zk6G9eco5N+jB1qJ2XW3ME=
|
||||
github.com/wiggin77/merror v1.0.5/go.mod h1:H2ETSu7/bPE0Ymf4bEwdUoo73OOEkdClnoRisfw0Nm0=
|
||||
github.com/wiggin77/srslog v1.0.1 h1:gA2XjSMy3DrRdX9UqLuDtuVAAshb8bE1NhX1YK0Qe+8=
|
||||
github.com/wiggin77/srslog v1.0.1/go.mod h1:fehkyYDq1QfuYn60TDPu9YdY2bB85VUW2mvN1WynEls=
|
||||
github.com/xanzy/go-gitlab v0.97.0 h1:StMqJ1Kvt00X43pYIBBjj52dFlghwSeBhRDRfzaZ7xY=
|
||||
github.com/xanzy/go-gitlab v0.97.0/go.mod h1:ETg8tcj4OhrB84UEgeE8dSuV/0h4BBL1uOV/qK0vlyI=
|
||||
github.com/xtgo/uuid v0.0.0-20140804021211-a0b114877d4c h1:3lbZUMbMiGUW/LMkfsEABsc5zNT9+b1CvsJx47JzJ8g=
|
||||
github.com/xtgo/uuid v0.0.0-20140804021211-a0b114877d4c/go.mod h1:UrdRz5enIKZ63MEE3IF9l2/ebyx59GyGgPi+tICQdmM=
|
||||
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
go.opencensus.io v0.18.0/go.mod h1:vKdFvxhtzZ9onBp9VKHK8z/sRpBMnKAsufL7wlDrCOA=
|
||||
go.opentelemetry.io/otel v1.6.3/go.mod h1:7BgNga5fNlF/iZjG06hM3yofffp0ofKCDwSXx1GC4dI=
|
||||
go.opentelemetry.io/otel/trace v1.6.3/go.mod h1:GNJQusJlUgZl9/TQBPKU/Y/ty+0iVB5fjhKeJGZPGFs=
|
||||
go4.org v0.0.0-20180809161055-417644f6feb5/go.mod h1:MkTOUMDaeVYJUOUsaDXIhWPZYa1yOyC1qaOBpL57BhE=
|
||||
golang.org/x/build v0.0.0-20190111050920-041ab4dc3f9d/go.mod h1:OWs+y06UdEOHN4y+MfF/py+xQ/tYqIWW03b70/CG9Rw=
|
||||
golang.org/x/crypto v0.0.0-20181030102418-4d3f4d9ffa16/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20190313024323-a1f597ede03a/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.21.0 h1:X31++rzVUdKhX5sWmSOFZxx8UW/ldWx55cbf08iNAMA=
|
||||
golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs=
|
||||
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
|
||||
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20181029044818-c44066c5c816/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20181106065722-10aee1819953/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20190313220215-9f648a60d977/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
|
||||
golang.org/x/net v0.0.0-20220520000938-2e3eb7b945c2/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/net v0.3.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE=
|
||||
golang.org/x/net v0.23.0 h1:7EYJ93RZ9vYSZAIb2x3lnuvqO5zneoD6IvWjuhfxjTs=
|
||||
golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
|
||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/oauth2 v0.0.0-20181017192945-9dcd33a902f4/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/oauth2 v0.0.0-20181203162652-d668ce993890/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
golang.org/x/oauth2 v0.7.0 h1:qe6s0zUXlPX80/dITx3440hWZ7GwMwgDDyrSGTPJG/g=
|
||||
golang.org/x/oauth2 v0.7.0/go.mod h1:hPLQkd9LyjfXTiRohC/41GhcFqxisoUQ99sCUOHO9x4=
|
||||
golang.org/x/perf v0.0.0-20180704124530-6e6d33e29852/go.mod h1:JLpeXjPJfIyPr5TlbXLkXWLhP8nz10XfvxElABhCtcw=
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
|
||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20181029174526-d69651ed3497/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190316082340-a2f829d7f35f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4=
|
||||
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4=
|
||||
golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20181030000716-a0a13e073c7b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/tools v0.4.0/go.mod h1:UE5sM2OK9E/d67R0ANs2xJizIymRP5gJU295PvKXxjQ=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/api v0.0.0-20180910000450-7ca32eb868bf/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0=
|
||||
google.golang.org/api v0.0.0-20181030000543-1d582fd0359e/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0=
|
||||
google.golang.org/api v0.1.0/go.mod h1:UGEZY7KEX120AnNLIHFMKIo4obdJhkp2tPbaPlQx13Y=
|
||||
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
|
||||
google.golang.org/appengine v1.2.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
|
||||
google.golang.org/appengine v1.3.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
|
||||
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
|
||||
google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c=
|
||||
google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
|
||||
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
|
||||
google.golang.org/genproto v0.0.0-20180831171423-11092d34479b/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
|
||||
google.golang.org/genproto v0.0.0-20181029155118-b69ba1387ce2/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
|
||||
google.golang.org/genproto v0.0.0-20181202183823-bd91e49a0898/go.mod h1:7Ep/1NZk928CDR8SjdVbjWNpdIf6nzjE3BTgJDr2Atg=
|
||||
google.golang.org/genproto v0.0.0-20190306203927-b5d61aea6440/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
|
||||
google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 h1:KpwkzHKEF7B9Zxg18WzOa7djJ+Ha5DzthMyZYQfEn2A=
|
||||
google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1/go.mod h1:nKE/iIaLqn2bQwXBg8f1g2Ylh6r5MN5CmZvuzZCgsCU=
|
||||
google.golang.org/grpc v1.14.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw=
|
||||
google.golang.org/grpc v1.16.0/go.mod h1:0JHn/cJsOMiMfNA9+DeHDlAU7KAAB5GDlYFpa9MZMio=
|
||||
google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs=
|
||||
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
|
||||
google.golang.org/grpc v1.56.3 h1:8I4C0Yq1EjstUzUJzpcRVbuYA2mODtEmpWiQoN/b2nc=
|
||||
google.golang.org/grpc v1.56.3/go.mod h1:I9bI3vqKfayGqPUAwGdOSu7kt6oIJLixfffKrpXqQ9s=
|
||||
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
|
||||
google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI=
|
||||
google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw=
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=
|
||||
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
grpc.go4.org v0.0.0-20170609214715-11d0a25b4919/go.mod h1:77eQGdRu53HpSqPFJFmuJdjuHRquDANNeA4x7B8WQ9o=
|
||||
honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
sourcegraph.com/sourcegraph/go-diff v0.5.0/go.mod h1:kuch7UrkMzY0X+p9CRK03kfuPQ2zzQcaEFbx8wA8rck=
|
||||
sourcegraph.com/sqs/pbtypes v0.0.0-20180604144634-d3ebe8f20ae4/go.mod h1:ketZ/q3QxT9HOBeFhu6RdvsftgpsbFHBF5Cas6cDKZ0=
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
{
|
||||
"id": "com.github.manland.mattermost-plugin-gitlab",
|
||||
"name": "GitLab",
|
||||
"description": "GitLab plugin for Mattermost.",
|
||||
"homepage_url": "https://github.com/mattermost/mattermost-plugin-gitlab",
|
||||
"support_url": "https://github.com/mattermost/mattermost-plugin-gitlab/issues",
|
||||
"icon_path": "assets/icon.svg",
|
||||
"min_server_version": "7.1.0",
|
||||
"server": {
|
||||
"executables": {
|
||||
"darwin-amd64": "server/dist/plugin-darwin-amd64",
|
||||
"darwin-arm64": "server/dist/plugin-darwin-arm64",
|
||||
"linux-amd64": "server/dist/plugin-linux-amd64",
|
||||
"linux-arm64": "server/dist/plugin-linux-arm64",
|
||||
"windows-amd64": "server/dist/plugin-windows-amd64.exe"
|
||||
},
|
||||
"executable": ""
|
||||
},
|
||||
"webapp": {
|
||||
"bundle_path": "webapp/dist/main.js"
|
||||
},
|
||||
"settings_schema": {
|
||||
"header": "To set up the GitLab plugin, you need to register a GitLab OAuth app here https://gitlab.com/-/profile/applications.",
|
||||
"footer": "To report an issue, make a suggestion, or submit a contribution, [check the repository](https://github.com/mattermost/mattermost-plugin-gitlab).",
|
||||
"settings": [
|
||||
{
|
||||
"key": "UsePreregisteredApplication",
|
||||
"display_name": "Use Preregistered OAuth Application:",
|
||||
"type": "bool",
|
||||
"help_text": "When true, instructs the plugin to use the preregistered GitLab OAuth application - application registration steps can be skipped. Requires [Chimera Proxy](https://github.com/mattermost/chimera) URL to be configured for the server. Can only be used with official gitlab.com. **This setting is intended to be used with Mattermost Cloud instances only.**",
|
||||
"placeholder": "",
|
||||
"default": false
|
||||
},
|
||||
{
|
||||
"key": "GitlabURL",
|
||||
"display_name": "GitLab URL:",
|
||||
"type": "text",
|
||||
"help_text": "The base URL for using the plugin with a GitLab installation. Examples: https://gitlab.com or https://gitlab.example.com.",
|
||||
"placeholder": "https://gitlab.com",
|
||||
"default": "https://gitlab.com"
|
||||
},
|
||||
{
|
||||
"key": "GitlabOAuthClientID",
|
||||
"display_name": "GitLab OAuth Client ID:",
|
||||
"type": "text",
|
||||
"help_text": "The client ID for the OAuth app registered with GitLab.",
|
||||
"placeholder": "",
|
||||
"default": null
|
||||
},
|
||||
{
|
||||
"key": "GitlabOAuthClientSecret",
|
||||
"display_name": "GitLab OAuth Client Secret:",
|
||||
"type": "text",
|
||||
"help_text": "The client secret for the OAuth app registered with GitLab.",
|
||||
"placeholder": "",
|
||||
"default": null
|
||||
},
|
||||
{
|
||||
"key": "WebhookSecret",
|
||||
"display_name": "Webhook Secret:",
|
||||
"type": "generated",
|
||||
"help_text": "The webhook secret set in GitLab.",
|
||||
"placeholder": "",
|
||||
"default": null
|
||||
},
|
||||
{
|
||||
"key": "EncryptionKey",
|
||||
"display_name": "At Rest Encryption Key:",
|
||||
"type": "generated",
|
||||
"help_text": "The AES encryption key used to encrypt stored access tokens.",
|
||||
"placeholder": "",
|
||||
"default": null
|
||||
},
|
||||
{
|
||||
"key": "GitlabGroup",
|
||||
"display_name": "GitLab Group:",
|
||||
"type": "text",
|
||||
"help_text": "(Optional) Set to lock the plugin to a single GitLab group.",
|
||||
"placeholder": "groupName",
|
||||
"default": null
|
||||
},
|
||||
{
|
||||
"key": "EnablePrivateRepo",
|
||||
"display_name": "Enable Private Repositories:",
|
||||
"type": "bool",
|
||||
"help_text": "(Optional) Allow the plugin to work with private repositories for subscriptions.",
|
||||
"placeholder": "",
|
||||
"default": null
|
||||
},
|
||||
{
|
||||
"key": "EnableChildPipelineNotifications",
|
||||
"display_name": "Enable Child Pipelines Notification:",
|
||||
"type": "bool",
|
||||
"help_text": "Allow the plugin to post notfication for child pipelines when the pipeline subscription is created in a channel.",
|
||||
"placeholder": "",
|
||||
"default": true
|
||||
},
|
||||
{
|
||||
"key": "EnableCodePreview",
|
||||
"display_name": "Enable Code Previews:",
|
||||
"type": "dropdown",
|
||||
"help_text": "Allow the plugin to expand permalinks to GitLab files with an actual preview of the linked file.",
|
||||
"default": "public",
|
||||
"options": [
|
||||
{
|
||||
"display_name": "Enable for public projects",
|
||||
"value": "public"
|
||||
},
|
||||
{
|
||||
"display_name": "Enable for public and private projects. This might leak confidential code into public channels",
|
||||
"value": "privateAndPublic"
|
||||
},
|
||||
{
|
||||
"display_name": "Disable",
|
||||
"value": "disable"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 12 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 132 KiB |
@@ -0,0 +1 @@
|
||||
coverage.txt
|
||||
+727
@@ -0,0 +1,727 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
"runtime/debug"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/pkg/errors"
|
||||
"golang.org/x/oauth2"
|
||||
|
||||
"github.com/mattermost/mattermost/server/public/model"
|
||||
"github.com/mattermost/mattermost/server/public/plugin"
|
||||
"github.com/mattermost/mattermost/server/public/pluginapi/experimental/bot/logger"
|
||||
"github.com/mattermost/mattermost/server/public/pluginapi/experimental/flow"
|
||||
|
||||
"github.com/mattermost/mattermost-plugin-gitlab/server/gitlab"
|
||||
"github.com/mattermost/mattermost-plugin-gitlab/server/subscription"
|
||||
)
|
||||
|
||||
const (
|
||||
APIErrorIDNotConnected = "not_connected"
|
||||
|
||||
requestTimeout = 30 * time.Second
|
||||
)
|
||||
|
||||
func (p *Plugin) ServeHTTP(c *plugin.Context, w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
p.router.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
func (p *Plugin) initializeAPI() {
|
||||
p.router = mux.NewRouter()
|
||||
p.router.Use(p.withRecovery)
|
||||
|
||||
oauthRouter := p.router.PathPrefix("/oauth").Subrouter()
|
||||
apiRouter := p.router.PathPrefix("/api/v1").Subrouter()
|
||||
apiRouter.Use(p.checkConfigured)
|
||||
|
||||
p.router.HandleFunc("/webhook", p.handleWebhook).Methods(http.MethodPost)
|
||||
|
||||
oauthRouter.HandleFunc("/connect", p.checkAuth(p.attachContext(p.connectUserToGitlab), ResponseTypePlain)).Methods(http.MethodGet)
|
||||
oauthRouter.HandleFunc("/complete", p.checkAuth(p.attachContext(p.completeConnectUserToGitlab), ResponseTypePlain)).Methods(http.MethodGet)
|
||||
|
||||
apiRouter.HandleFunc("/connected", p.attachContext(p.getConnected)).Methods(http.MethodGet)
|
||||
|
||||
apiRouter.HandleFunc("/user", p.checkAuth(p.attachContext(p.getGitlabUser), ResponseTypeJSON)).Methods(http.MethodPost)
|
||||
apiRouter.HandleFunc("/todo", p.checkAuth(p.attachUserContext(p.postToDo), ResponseTypeJSON)).Methods(http.MethodPost)
|
||||
apiRouter.HandleFunc("/lhs-data", p.checkAuth(p.attachUserContext(p.getLHSData), ResponseTypePlain)).Methods(http.MethodGet)
|
||||
apiRouter.HandleFunc("/prdetails", p.checkAuth(p.attachUserContext(p.getPrDetails), ResponseTypePlain)).Methods(http.MethodPost)
|
||||
apiRouter.HandleFunc("/issue", p.checkAuth(p.attachUserContext(p.getIssueByNumber), ResponseTypeJSON)).Methods(http.MethodGet)
|
||||
apiRouter.HandleFunc("/mergerequest", p.checkAuth(p.attachUserContext(p.getMergeRequestByNumber), ResponseTypeJSON)).Methods(http.MethodGet)
|
||||
apiRouter.HandleFunc("/settings", p.checkAuth(p.attachUserContext(p.updateSettings), ResponseTypePlain)).Methods(http.MethodPost)
|
||||
|
||||
apiRouter.HandleFunc("/channel/{channel_id:[A-Za-z0-9]+}/subscriptions", p.checkAuth(p.attachUserContext(p.getChannelSubscriptions), ResponseTypeJSON)).Methods(http.MethodGet)
|
||||
}
|
||||
|
||||
type Context struct {
|
||||
Ctx context.Context
|
||||
UserID string
|
||||
Log logger.Logger
|
||||
}
|
||||
|
||||
func (p *Plugin) createContext(_ http.ResponseWriter, r *http.Request) (*Context, context.CancelFunc) {
|
||||
userID := r.Header.Get("Mattermost-User-ID")
|
||||
|
||||
logger := logger.New(p.API).With(logger.LogContext{
|
||||
"userid": userID,
|
||||
})
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
|
||||
|
||||
context := &Context{
|
||||
Ctx: ctx,
|
||||
UserID: userID,
|
||||
Log: logger,
|
||||
}
|
||||
|
||||
return context, cancel
|
||||
}
|
||||
|
||||
// HTTPHandlerFuncWithContext is http.HandleFunc but with a Context attached
|
||||
type HTTPHandlerFuncWithContext func(c *Context, w http.ResponseWriter, r *http.Request)
|
||||
|
||||
func (p *Plugin) attachContext(handler HTTPHandlerFuncWithContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
context, cancel := p.createContext(w, r)
|
||||
defer cancel()
|
||||
|
||||
handler(context, w, r)
|
||||
}
|
||||
}
|
||||
|
||||
type UserContext struct {
|
||||
Context
|
||||
GitlabInfo *gitlab.UserInfo
|
||||
}
|
||||
|
||||
// HTTPHandlerFuncWithUserContext is http.HandleFunc but with a UserContext attached
|
||||
type HTTPHandlerFuncWithUserContext func(c *UserContext, w http.ResponseWriter, r *http.Request)
|
||||
|
||||
func (p *Plugin) attachUserContext(handler HTTPHandlerFuncWithUserContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
context, cancel := p.createContext(w, r)
|
||||
defer cancel()
|
||||
|
||||
info, apiErr := p.getGitlabUserInfoByMattermostID(context.UserID)
|
||||
if apiErr != nil {
|
||||
p.writeAPIError(w, apiErr)
|
||||
return
|
||||
}
|
||||
|
||||
context.Log = context.Log.With(logger.LogContext{
|
||||
"gitlab username": info.GitlabUsername,
|
||||
"gitlab userid": info.GitlabUserID,
|
||||
})
|
||||
|
||||
userContext := &UserContext{
|
||||
Context: *context,
|
||||
GitlabInfo: info,
|
||||
}
|
||||
|
||||
handler(userContext, w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Plugin) withRecovery(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
if x := recover(); x != nil {
|
||||
p.client.Log.Warn("Recovered from a panic",
|
||||
"url", r.URL.String(),
|
||||
"error", x,
|
||||
"stack", string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func (p *Plugin) checkConfigured(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
config := p.getConfiguration()
|
||||
|
||||
if err := config.IsValid(); err != nil {
|
||||
http.Error(w, "This plugin is not configured.", http.StatusNotImplemented)
|
||||
return
|
||||
}
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func (p *Plugin) checkAuth(handler http.HandlerFunc, responseType ResponseType) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
userID := r.Header.Get("Mattermost-User-ID")
|
||||
if userID == "" {
|
||||
switch responseType {
|
||||
case ResponseTypeJSON:
|
||||
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Not authorized.", StatusCode: http.StatusUnauthorized})
|
||||
case ResponseTypePlain:
|
||||
http.Error(w, "Not authorized", http.StatusUnauthorized)
|
||||
default:
|
||||
p.client.Log.Debug("Unknown ResponseType detected")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
handler(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
// ResponseType indicates type of response returned by api
|
||||
type ResponseType string
|
||||
|
||||
const (
|
||||
// ResponseTypeJSON indicates that response type is json
|
||||
ResponseTypeJSON ResponseType = "JSON_RESPONSE"
|
||||
// ResponseTypePlain indicates that response type is text plain
|
||||
ResponseTypePlain ResponseType = "TEXT_RESPONSE"
|
||||
)
|
||||
|
||||
type APIErrorResponse struct {
|
||||
ID string `json:"id"`
|
||||
Message string `json:"message"`
|
||||
StatusCode int `json:"status_code"`
|
||||
}
|
||||
|
||||
func (e *APIErrorResponse) Error() string {
|
||||
return e.Message
|
||||
}
|
||||
|
||||
func (p *Plugin) writeAPIError(w http.ResponseWriter, err *APIErrorResponse) {
|
||||
b, _ := json.Marshal(err)
|
||||
w.WriteHeader(err.StatusCode)
|
||||
if _, err := w.Write(b); err != nil {
|
||||
p.client.Log.Warn("can't write api error http response", "err", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Plugin) writeAPIResponse(w http.ResponseWriter, resp interface{}) {
|
||||
b, jsonErr := json.Marshal(resp)
|
||||
if jsonErr != nil {
|
||||
p.client.Log.Warn("Error encoding JSON response", "err", jsonErr.Error())
|
||||
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Encountered an unexpected error. Please try again.", StatusCode: http.StatusInternalServerError})
|
||||
}
|
||||
if _, err := w.Write(b); err != nil {
|
||||
p.client.Log.Warn("can't write response user to http", "err", err.Error())
|
||||
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Encountered an unexpected error. Please try again.", StatusCode: http.StatusInternalServerError})
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Plugin) connectUserToGitlab(c *Context, w http.ResponseWriter, r *http.Request) {
|
||||
userID := r.Header.Get("Mattermost-User-ID")
|
||||
if userID == "" {
|
||||
http.Error(w, "Not authorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
conf := p.getOAuthConfig()
|
||||
|
||||
state := fmt.Sprintf("%v_%v", model.NewId()[0:15], userID)
|
||||
|
||||
if _, err := p.client.KV.Set(state, []byte(state)); err != nil {
|
||||
c.Log.WithError(err).Warnf("Can't store state oauth2")
|
||||
http.Error(w, "can't store state oauth2", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
url := conf.AuthCodeURL(state, oauth2.AccessTypeOffline)
|
||||
|
||||
ch := p.oauthBroker.SubscribeOAuthComplete(userID)
|
||||
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
|
||||
defer cancel()
|
||||
|
||||
var errorMsg string
|
||||
select {
|
||||
case err := <-ch:
|
||||
if err != nil {
|
||||
errorMsg = err.Error()
|
||||
}
|
||||
case <-ctx.Done():
|
||||
errorMsg = "Timed out waiting for OAuth connection. Please check if the SiteURL is correct."
|
||||
}
|
||||
|
||||
if errorMsg != "" {
|
||||
_, err := p.poster.DMWithAttachments(userID, &model.SlackAttachment{
|
||||
Text: fmt.Sprintf("There was an error connecting to your GitLab: `%s` Please double check your configuration.", errorMsg),
|
||||
Color: string(flow.ColorDanger),
|
||||
})
|
||||
if err != nil {
|
||||
c.Log.WithError(err).Warnf("Failed to DM with cancel information")
|
||||
}
|
||||
}
|
||||
|
||||
p.oauthBroker.UnsubscribeOAuthComplete(userID, ch)
|
||||
}()
|
||||
|
||||
http.Redirect(w, r, url, http.StatusFound)
|
||||
}
|
||||
|
||||
func (p *Plugin) completeConnectUserToGitlab(c *Context, w http.ResponseWriter, r *http.Request) {
|
||||
authedUserID := r.Header.Get("Mattermost-User-ID")
|
||||
if authedUserID == "" {
|
||||
http.Error(w, "Not authorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
var rErr error
|
||||
defer func() {
|
||||
p.oauthBroker.publishOAuthComplete(authedUserID, rErr, false)
|
||||
}()
|
||||
|
||||
config := p.getConfiguration()
|
||||
|
||||
conf := p.getOAuthConfig()
|
||||
|
||||
code := r.URL.Query().Get("code")
|
||||
if len(code) == 0 {
|
||||
rErr = errors.New("missing authorization code")
|
||||
http.Error(w, rErr.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
state := r.URL.Query().Get("state")
|
||||
|
||||
var storedState []byte
|
||||
err := p.client.KV.Get(state, &storedState)
|
||||
if err != nil {
|
||||
c.Log.WithError(err).Warnf("Can't get state from store")
|
||||
|
||||
rErr = errors.Wrap(err, "missing stored state")
|
||||
http.Error(w, rErr.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
err = p.client.KV.Delete(state)
|
||||
if err != nil {
|
||||
c.Log.WithError(err).Warnf("Failed to delete state token")
|
||||
|
||||
rErr = errors.Wrap(err, "error deleting stored state")
|
||||
http.Error(w, rErr.Error(), http.StatusBadRequest)
|
||||
}
|
||||
|
||||
if string(storedState) != state {
|
||||
rErr = errors.New("invalid state token")
|
||||
http.Error(w, rErr.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
userID := strings.Split(state, "_")[1]
|
||||
|
||||
if userID != authedUserID {
|
||||
rErr = errors.New("not authorized, incorrect user")
|
||||
http.Error(w, rErr.Error(), http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
tok, err := conf.Exchange(c.Ctx, code)
|
||||
if err != nil {
|
||||
c.Log.WithError(err).Warnf("Can't exchange state")
|
||||
|
||||
rErr = errors.Wrap(err, "Failed to exchange oauth code into token")
|
||||
http.Error(w, rErr.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
userInfo, err := p.GitlabClient.GetCurrentUser(c.Ctx, userID, *tok)
|
||||
if err != nil {
|
||||
c.Log.WithError(err).Warnf("Can't retrieve user info from gitLab API")
|
||||
|
||||
rErr = errors.Wrap(err, "unable to connect user to GitLab")
|
||||
http.Error(w, rErr.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
if err = p.storeGitlabUserInfo(userInfo); err != nil {
|
||||
c.Log.WithError(err).Warnf("Can't store user info")
|
||||
|
||||
rErr = errors.Wrap(err, "Unable to connect user to GitLab")
|
||||
http.Error(w, rErr.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
if err = p.storeGitlabUserToken(userInfo.UserID, tok); err != nil {
|
||||
c.Log.WithError(err).Warnf("Can't store user token")
|
||||
|
||||
rErr = errors.Wrap(err, "Unable to connect user to GitLab")
|
||||
http.Error(w, rErr.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
if err = p.storeGitlabToUserIDMapping(userInfo.GitlabUsername, userID); err != nil {
|
||||
c.Log.WithError(err).Warnf("Can't store GitLab to user id mapping")
|
||||
}
|
||||
|
||||
if err = p.storeGitlabIDToUserIDMapping(userInfo.GitlabUsername, userInfo.GitlabUserID); err != nil {
|
||||
c.Log.WithError(err).Warnf("Can't store GitLab to GitLab id mapping")
|
||||
}
|
||||
|
||||
flow := p.flowManager.setupFlow.ForUser(authedUserID)
|
||||
|
||||
stepName, err := flow.GetCurrentStep()
|
||||
if err != nil {
|
||||
c.Log.WithError(err).Warnf("Failed to get current step")
|
||||
}
|
||||
|
||||
if stepName == stepOAuthConnect {
|
||||
err = flow.Go(stepWebhookQuestion)
|
||||
if err != nil {
|
||||
c.Log.WithError(err).Warnf("Failed go to next step")
|
||||
}
|
||||
} else {
|
||||
// Only post introduction message if no setup wizard is running
|
||||
// Post intro post
|
||||
message := fmt.Sprintf("#### Welcome to the Mattermost GitLab Plugin!\n"+
|
||||
"You've connected your Mattermost account to %s on GitLab. Read about the features of this plugin below:\n\n"+
|
||||
"##### Daily Reminders\n"+
|
||||
"The first time you log in each day, you will get a post right here letting you know what messages you need to read and what merge requests are awaiting your review.\n"+
|
||||
"Turn off reminders with `/gitlab settings reminders off`.\n\n"+
|
||||
"##### Notifications\n"+
|
||||
"When someone mentions you, requests your review, comments on or modifies one of your merge requests/issues, or assigns you, you'll get a post here about it.\n"+
|
||||
"Turn off notifications with `/gitlab settings notifications off`.\n\n"+
|
||||
"##### Sidebar Buttons\n"+
|
||||
"Check out the buttons in the left-hand sidebar of Mattermost.\n"+
|
||||
"* The first button tells you how many merge requests you are assigned to.\n"+
|
||||
"* The second shows the number of merge requests that are awaiting your review.\n"+
|
||||
"* The third shows the number of issues you are assigned to.\n"+
|
||||
"* The fourth tracks the number of todos you have.\n"+
|
||||
"* The fifth will refresh the numbers.\n\n"+
|
||||
"Click on them!\n\n"+
|
||||
"##### Slash Commands\n"+
|
||||
strings.ReplaceAll(commandHelp, "|", "`"), userInfo.GitlabUsername)
|
||||
|
||||
if err := p.CreateBotDMPost(userID, message, "custom_git_welcome"); err != nil {
|
||||
c.Log.WithError(err).Warnf("Can't send help message with bot dm")
|
||||
}
|
||||
}
|
||||
|
||||
p.TrackUserEvent("account_connected", userID, nil)
|
||||
|
||||
p.client.Frontend.PublishWebSocketEvent(
|
||||
WsEventConnect,
|
||||
map[string]interface{}{
|
||||
"connected": true,
|
||||
"gitlab_username": userInfo.GitlabUsername,
|
||||
"gitlab_client_id": config.GitlabOAuthClientID,
|
||||
"gitlab_url": config.GitlabURL,
|
||||
"organization": config.GitlabGroup,
|
||||
},
|
||||
&model.WebsocketBroadcast{UserId: userID},
|
||||
)
|
||||
|
||||
html := `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<script>
|
||||
window.close();
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<p>Completed connecting to GitLab. Please close this window.</p>
|
||||
</body>
|
||||
</html>
|
||||
`
|
||||
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
if _, err := w.Write([]byte(html)); err != nil {
|
||||
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: ">Completed connecting to GitLab. Please close this window.", StatusCode: http.StatusInternalServerError})
|
||||
}
|
||||
}
|
||||
|
||||
type ConnectedResponse struct {
|
||||
Connected bool `json:"connected"`
|
||||
GitlabUsername string `json:"gitlab_username"`
|
||||
GitlabClientID string `json:"gitlab_client_id"`
|
||||
GitlabURL string `json:"gitlab_url,omitempty"`
|
||||
Organization string `json:"organization"`
|
||||
Settings *gitlab.UserSettings `json:"settings"`
|
||||
}
|
||||
|
||||
type GitlabUserRequest struct {
|
||||
UserID string `json:"user_id"`
|
||||
}
|
||||
|
||||
type GitlabUserResponse struct {
|
||||
Username string `json:"username"`
|
||||
}
|
||||
|
||||
func (p *Plugin) getGitlabUser(c *Context, w http.ResponseWriter, r *http.Request) {
|
||||
req := &GitlabUserRequest{}
|
||||
dec := json.NewDecoder(r.Body)
|
||||
if err := dec.Decode(&req); err != nil || req.UserID == "" {
|
||||
if err != nil {
|
||||
c.Log.WithError(err).Warnf("Error decoding JSON body")
|
||||
}
|
||||
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Please provide a JSON object with a non-blank user_id field.", StatusCode: http.StatusBadRequest})
|
||||
return
|
||||
}
|
||||
|
||||
userInfo, apiErr := p.getGitlabUserInfoByMattermostID(req.UserID)
|
||||
if apiErr != nil {
|
||||
if apiErr.ID == APIErrorIDNotConnected {
|
||||
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "User is not connected to a GitLab account.", StatusCode: http.StatusNotFound})
|
||||
} else {
|
||||
p.writeAPIError(w, apiErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if userInfo == nil {
|
||||
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "User is not connected to a GitLab account.", StatusCode: http.StatusNotFound})
|
||||
return
|
||||
}
|
||||
|
||||
p.writeAPIResponse(w, &GitlabUserResponse{Username: userInfo.GitlabUsername})
|
||||
}
|
||||
|
||||
func (p *Plugin) getConnected(c *Context, w http.ResponseWriter, r *http.Request) {
|
||||
config := p.getConfiguration()
|
||||
|
||||
resp := &ConnectedResponse{
|
||||
Connected: false,
|
||||
GitlabURL: config.GitlabURL,
|
||||
Organization: config.GitlabGroup,
|
||||
}
|
||||
|
||||
info, _ := p.getGitlabUserInfoByMattermostID(c.UserID)
|
||||
if info != nil {
|
||||
resp.Connected = true
|
||||
resp.GitlabUsername = info.GitlabUsername
|
||||
resp.GitlabClientID = config.GitlabOAuthClientID
|
||||
resp.Settings = info.Settings
|
||||
|
||||
if info.Settings.DailyReminder && r.URL.Query().Get("reminder") == "true" {
|
||||
lastPostAt := info.LastToDoPostAt
|
||||
|
||||
var timezone *time.Location
|
||||
offset, _ := strconv.Atoi(r.Header.Get("X-Timezone-Offset"))
|
||||
timezone = time.FixedZone("local", -60*offset)
|
||||
|
||||
// Post to do message if it's the next day and been more than an hour since the last post
|
||||
now := model.GetMillis()
|
||||
nt := time.Unix(now/1000, 0).In(timezone)
|
||||
lt := time.Unix(lastPostAt/1000, 0).In(timezone)
|
||||
if nt.Sub(lt).Hours() >= 1 && (nt.Day() != lt.Day() || nt.Month() != lt.Month() || nt.Year() != lt.Year()) {
|
||||
p.PostToDo(c.Ctx, info)
|
||||
info.LastToDoPostAt = now
|
||||
if err := p.storeGitlabUserInfo(info); err != nil {
|
||||
c.Log.WithError(err).Warnf("Can't store user info")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
p.writeAPIResponse(w, resp)
|
||||
}
|
||||
|
||||
func (p *Plugin) getPrDetails(c *UserContext, w http.ResponseWriter, r *http.Request) {
|
||||
var prList []*gitlab.PRDetails
|
||||
if err := json.NewDecoder(r.Body).Decode(&prList); err != nil {
|
||||
c.Log.WithError(err).Warnf("Error decoding PRDetails JSON body")
|
||||
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: fmt.Sprintf("Error decoding PRDetails JSON body. Error: %s", err.Error()), StatusCode: http.StatusBadRequest})
|
||||
return
|
||||
}
|
||||
var result []*gitlab.PRDetails
|
||||
err := p.useGitlabClient(c.GitlabInfo, func(info *gitlab.UserInfo, token *oauth2.Token) error {
|
||||
resp, err := p.GitlabClient.GetYourPrDetails(c.Ctx, c.Log, info, token, prList)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result = resp
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
c.Log.WithError(err).Warnf("Can't list merge-request details in GitLab API")
|
||||
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: fmt.Sprintf("Can't list merge-request details in GitLab API. Error: %s", err.Error()), StatusCode: http.StatusInternalServerError})
|
||||
return
|
||||
}
|
||||
|
||||
p.writeAPIResponse(w, result)
|
||||
}
|
||||
|
||||
func (p *Plugin) getLHSData(c *UserContext, w http.ResponseWriter, r *http.Request) {
|
||||
var result *gitlab.LHSContent
|
||||
err := p.useGitlabClient(c.GitlabInfo, func(info *gitlab.UserInfo, token *oauth2.Token) error {
|
||||
resp, err := p.GitlabClient.GetLHSData(c.Ctx, info, token)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result = resp
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
c.Log.WithError(err).Warnf("Unable to list issue where assignee in GitLab API")
|
||||
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Unable to list issue in GitLab API.", StatusCode: http.StatusInternalServerError})
|
||||
return
|
||||
}
|
||||
|
||||
p.writeAPIResponse(w, result)
|
||||
}
|
||||
|
||||
func (p *Plugin) postToDo(c *UserContext, w http.ResponseWriter, r *http.Request) {
|
||||
_, text, err := p.GetToDo(c.Ctx, c.GitlabInfo)
|
||||
if err != nil {
|
||||
c.Log.WithError(err).Warnf("Can't get todo")
|
||||
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Encountered an error getting the to do items.", StatusCode: http.StatusUnauthorized})
|
||||
return
|
||||
}
|
||||
|
||||
if err := p.CreateBotDMPost(c.UserID, text, "custom_git_todo"); err != nil {
|
||||
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Encountered an error posting the to do items.", StatusCode: http.StatusUnauthorized})
|
||||
}
|
||||
|
||||
p.writeAPIResponse(w, struct{ status string }{status: "OK"})
|
||||
}
|
||||
|
||||
func (p *Plugin) updateSettings(c *UserContext, w http.ResponseWriter, r *http.Request) {
|
||||
var settings *gitlab.UserSettings
|
||||
err := json.NewDecoder(r.Body).Decode(&settings)
|
||||
if settings == nil || err != nil {
|
||||
http.Error(w, "Invalid request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
info, apiErr := p.getGitlabUserInfoByMattermostID(c.UserID)
|
||||
if apiErr != nil {
|
||||
p.writeAPIError(w, apiErr)
|
||||
return
|
||||
}
|
||||
|
||||
info.Settings = settings
|
||||
|
||||
if err := p.storeGitlabUserInfo(info); err != nil {
|
||||
c.Log.WithError(err).Errorf("can't store GitLab user info when update settings")
|
||||
http.Error(w, "Encountered error updating settings", http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
p.writeAPIResponse(w, info.Settings)
|
||||
}
|
||||
|
||||
func (p *Plugin) getIssueByNumber(c *UserContext, w http.ResponseWriter, r *http.Request) {
|
||||
owner := r.FormValue("owner")
|
||||
repo := r.FormValue("repo")
|
||||
issueID, err := strconv.Atoi(r.FormValue("number"))
|
||||
if err != nil {
|
||||
c.Log.WithError(err).Warnf("Unable to convert issueID into int")
|
||||
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Unable to convert issueID into int.", StatusCode: http.StatusInternalServerError})
|
||||
return
|
||||
}
|
||||
|
||||
var result *gitlab.Issue
|
||||
if cErr := p.useGitlabClient(c.GitlabInfo, func(info *gitlab.UserInfo, token *oauth2.Token) error {
|
||||
issue, err := p.GitlabClient.GetIssueByID(c.Ctx, c.GitlabInfo, owner, repo, issueID, token)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result = issue
|
||||
return nil
|
||||
}); cErr != nil {
|
||||
c.Log.WithError(cErr).Warnf("Unable to get issue in GitLab API")
|
||||
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Unable to get issue in GitLab API.", StatusCode: http.StatusInternalServerError})
|
||||
return
|
||||
}
|
||||
|
||||
p.writeAPIResponse(w, result)
|
||||
}
|
||||
|
||||
func (p *Plugin) getMergeRequestByNumber(c *UserContext, w http.ResponseWriter, r *http.Request) {
|
||||
owner := r.FormValue("owner")
|
||||
repo := r.FormValue("repo")
|
||||
mergeRequestID, err := strconv.Atoi(r.FormValue("number"))
|
||||
if err != nil {
|
||||
c.Log.WithError(err).Warnf("Unable to convert mergeRequestID into int")
|
||||
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Unable to convert mergeRequestID into int.", StatusCode: http.StatusInternalServerError})
|
||||
return
|
||||
}
|
||||
|
||||
var result *gitlab.MergeRequest
|
||||
if cErr := p.useGitlabClient(c.GitlabInfo, func(info *gitlab.UserInfo, token *oauth2.Token) error {
|
||||
mergeRequest, err := p.GitlabClient.GetMergeRequestByID(c.Ctx, c.GitlabInfo, owner, repo, mergeRequestID, token)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result = mergeRequest
|
||||
return nil
|
||||
}); cErr != nil {
|
||||
c.Log.WithError(cErr).Warnf("Unable to get merge request in GitLab API")
|
||||
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Unable to get merge request in GitLab API.", StatusCode: http.StatusInternalServerError})
|
||||
return
|
||||
}
|
||||
|
||||
p.writeAPIResponse(w, result)
|
||||
}
|
||||
|
||||
type SubscriptionResponse struct {
|
||||
RepositoryName string `json:"repository_name"`
|
||||
RepositoryURL string `json:"repository_url"`
|
||||
Features []string `json:"features"`
|
||||
CreatorID string `json:"creator_id"`
|
||||
}
|
||||
|
||||
func subscriptionsToResponse(config *configuration, subscriptions []*subscription.Subscription) []SubscriptionResponse {
|
||||
gitlabURL, _ := url.Parse(config.GitlabURL)
|
||||
|
||||
subscriptionResponses := make([]SubscriptionResponse, 0, len(subscriptions))
|
||||
|
||||
for _, subscription := range subscriptions {
|
||||
features := []string{}
|
||||
if len(subscription.Features) > 0 {
|
||||
features = strings.Split(subscription.Features, ",")
|
||||
}
|
||||
|
||||
repositoryURL := *gitlabURL
|
||||
repositoryURL.Path = path.Join(gitlabURL.EscapedPath(), subscription.Repository)
|
||||
|
||||
subscriptionResponses = append(subscriptionResponses, SubscriptionResponse{
|
||||
RepositoryName: subscription.Repository,
|
||||
RepositoryURL: repositoryURL.String(),
|
||||
Features: features,
|
||||
CreatorID: subscription.CreatorID,
|
||||
})
|
||||
}
|
||||
|
||||
return subscriptionResponses
|
||||
}
|
||||
|
||||
func (p *Plugin) getChannelSubscriptions(c *UserContext, w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
channelID := vars["channel_id"]
|
||||
|
||||
if !p.client.User.HasPermissionToChannel(c.UserID, channelID, model.PermissionReadChannel) {
|
||||
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Not authorized.", StatusCode: http.StatusUnauthorized})
|
||||
return
|
||||
}
|
||||
|
||||
config := p.getConfiguration()
|
||||
subscriptions, err := p.GetSubscriptionsByChannel(channelID)
|
||||
if err != nil {
|
||||
p.client.Log.Warn("unable to get subscriptions by channel", "err", err.Error())
|
||||
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Unable to get subscriptions by channel.", StatusCode: http.StatusInternalServerError})
|
||||
return
|
||||
}
|
||||
|
||||
resp := subscriptionsToResponse(config, subscriptions)
|
||||
|
||||
b, err := json.Marshal(resp)
|
||||
if err != nil {
|
||||
p.client.Log.Warn("failed to marshal channel subscriptions response", "err", err.Error())
|
||||
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Encountered an unexpected error. Please try again.", StatusCode: http.StatusInternalServerError})
|
||||
} else if _, err := w.Write(b); err != nil {
|
||||
p.client.Log.Warn("can't write api error http response", "err", err.Error())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/mattermost/mattermost/server/public/model"
|
||||
"github.com/mattermost/mattermost/server/public/plugin/plugintest"
|
||||
"github.com/mattermost/mattermost/server/public/pluginapi"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/mattermost/mattermost-plugin-gitlab/server/gitlab"
|
||||
)
|
||||
|
||||
func TestGetChannelSubscriptions(t *testing.T) {
|
||||
setupPlugin := func(t *testing.T) (*Plugin, *plugintest.API) {
|
||||
t.Helper()
|
||||
|
||||
config := configuration{
|
||||
GitlabURL: "https://example.com",
|
||||
GitlabOAuthClientID: "client_id",
|
||||
GitlabOAuthClientSecret: "secret",
|
||||
EncryptionKey: "aaaaaaaaaaaaaaaa",
|
||||
}
|
||||
|
||||
plugin := Plugin{configuration: &config}
|
||||
plugin.initializeAPI()
|
||||
|
||||
info := gitlab.UserInfo{
|
||||
UserID: "user_id",
|
||||
GitlabUsername: "gitlab_username",
|
||||
GitlabUserID: 0,
|
||||
}
|
||||
|
||||
jsonInfo, err := json.Marshal(info)
|
||||
require.NoError(t, err)
|
||||
|
||||
mock := &plugintest.API{}
|
||||
plugin.SetAPI(mock)
|
||||
plugin.client = pluginapi.NewClient(plugin.API, plugin.Driver)
|
||||
|
||||
mock.On("KVGet", "user_id_userinfo").Return(jsonInfo, nil).Once()
|
||||
|
||||
return &plugin, mock
|
||||
}
|
||||
|
||||
t.Run("no permission to channel", func(t *testing.T) {
|
||||
plugin, mock := setupPlugin(t)
|
||||
|
||||
mock.On("HasPermissionToChannel", "user_id", "id", model.PermissionReadChannel).Return(false, nil).Once()
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
r := httptest.NewRequest(http.MethodGet, "/api/v1/channel/id/subscriptions", nil)
|
||||
r.Header.Set("Mattermost-User-ID", "user_id")
|
||||
|
||||
plugin.ServeHTTP(nil, w, r)
|
||||
|
||||
result := w.Result()
|
||||
assert.NotNil(t, result)
|
||||
assert.Equal(t, http.StatusUnauthorized, result.StatusCode)
|
||||
})
|
||||
|
||||
t.Run("no subscriptions", func(t *testing.T) {
|
||||
plugin, mock := setupPlugin(t)
|
||||
|
||||
mock.On("HasPermissionToChannel", "user_id", "id", model.PermissionReadChannel).Return(true, nil).Once()
|
||||
mock.On("KVGet", SubscriptionsKey).Return([]byte(`{"Repositories":{"repo1":[]}}`), nil)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
r := httptest.NewRequest(http.MethodGet, "/api/v1/channel/id/subscriptions", nil)
|
||||
r.Header.Set("Mattermost-User-ID", "user_id")
|
||||
|
||||
plugin.ServeHTTP(nil, w, r)
|
||||
|
||||
result := w.Result()
|
||||
defer result.Body.Close()
|
||||
data, err := io.ReadAll(result.Body)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.NotNil(t, result)
|
||||
assert.Equal(t, http.StatusOK, result.StatusCode)
|
||||
assert.Equal(t, "[]", string(data))
|
||||
})
|
||||
|
||||
t.Run("no subscriptions for channel", func(t *testing.T) {
|
||||
plugin, mock := setupPlugin(t)
|
||||
|
||||
mock.On("HasPermissionToChannel", "user_id", "id", model.PermissionReadChannel).Return(true, nil).Once()
|
||||
mock.On("KVGet", SubscriptionsKey).Return([]byte(`{"Repositories":{"namespace":[{"ChannelID":"other","Repository":"repo1"}]}}`), nil)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
r := httptest.NewRequest(http.MethodGet, "/api/v1/channel/id/subscriptions", nil)
|
||||
r.Header.Set("Mattermost-User-ID", "user_id")
|
||||
|
||||
plugin.ServeHTTP(nil, w, r)
|
||||
|
||||
result := w.Result()
|
||||
defer result.Body.Close()
|
||||
data, err := io.ReadAll(result.Body)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.NotNil(t, result)
|
||||
assert.Equal(t, http.StatusOK, result.StatusCode)
|
||||
assert.Equal(t, "[]", string(data))
|
||||
})
|
||||
|
||||
t.Run("subscriptions for channel", func(t *testing.T) {
|
||||
plugin, mock := setupPlugin(t)
|
||||
|
||||
mock.On("HasPermissionToChannel", "user_id", "id", model.PermissionReadChannel).Return(true, nil).Once()
|
||||
mock.On("KVGet", SubscriptionsKey).Return([]byte(`{"Repositories":{"namespace":[{"ChannelID":"other","Repository":"repo1","Features":"feature1,feature2","CreatorID":"creator1"},{"ChannelID":"id","Repository":"repo2","Features":"feature3,feature4","CreatorID":"creator2"},{"ChannelID":"id", "Repository":"repo3","Features":"feature5","CreatorID":"creator3"},{"ChannelID":"id","Repository":"repo4-empty"}]}}`), nil)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
r := httptest.NewRequest(http.MethodGet, "/api/v1/channel/id/subscriptions", nil)
|
||||
r.Header.Set("Mattermost-User-ID", "user_id")
|
||||
|
||||
plugin.ServeHTTP(nil, w, r)
|
||||
|
||||
result := w.Result()
|
||||
defer result.Body.Close()
|
||||
data, err := io.ReadAll(result.Body)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.NotNil(t, result)
|
||||
assert.Equal(t, http.StatusOK, result.StatusCode)
|
||||
assert.Equal(t, `[{"repository_name":"repo2","repository_url":"https://example.com/repo2","features":["feature3","feature4"],"creator_id":"creator2"},{"repository_name":"repo3","repository_url":"https://example.com/repo3","features":["feature5"],"creator_id":"creator3"},{"repository_name":"repo4-empty","repository_url":"https://example.com/repo4-empty","features":[],"creator_id":""}]`, string(data))
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/mattermost/mattermost/server/public/model"
|
||||
)
|
||||
|
||||
const (
|
||||
oauthCompleteEventID = "oauth-complete"
|
||||
)
|
||||
|
||||
func (p *Plugin) sendOAuthCompleteEvent(event OAuthCompleteEvent) {
|
||||
p.sendMessageToCluster(oauthCompleteEventID, event)
|
||||
}
|
||||
|
||||
func (p *Plugin) sendMessageToCluster(id string, v interface{}) {
|
||||
b, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
p.client.Log.Warn("couldn't get JSON bytes from cluster message",
|
||||
"id", id,
|
||||
"error", err,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
event := model.PluginClusterEvent{Id: id, Data: b}
|
||||
opts := model.PluginClusterEventSendOptions{
|
||||
SendType: model.PluginClusterEventSendTypeReliable,
|
||||
}
|
||||
|
||||
if err := p.client.Cluster.PublishPluginEvent(event, opts); err != nil {
|
||||
p.client.Log.Warn("error publishing cluster event",
|
||||
"id", id,
|
||||
"error", err,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Plugin) HandleClusterEvent(ev model.PluginClusterEvent) {
|
||||
switch ev.Id {
|
||||
case oauthCompleteEventID:
|
||||
var event OAuthCompleteEvent
|
||||
if err := json.Unmarshal(ev.Data, &event); err != nil {
|
||||
p.client.Log.Warn("cannot unmarshal cluster event with OAuth complete event", "error", err)
|
||||
return
|
||||
}
|
||||
|
||||
p.oauthBroker.publishOAuthComplete(event.UserID, event.Err, true)
|
||||
default:
|
||||
p.client.Log.Warn("unknown cluster event", "id", ev.Id)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,885 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"runtime/debug"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/mattermost/mattermost/server/public/model"
|
||||
"github.com/mattermost/mattermost/server/public/plugin"
|
||||
"github.com/mattermost/mattermost/server/public/pluginapi/experimental/command"
|
||||
"github.com/pkg/errors"
|
||||
gitlabLib "github.com/xanzy/go-gitlab"
|
||||
"golang.org/x/oauth2"
|
||||
|
||||
"github.com/mattermost/mattermost-plugin-gitlab/server/gitlab"
|
||||
)
|
||||
|
||||
const commandHelp = `* |/gitlab connect| - Connect your Mattermost account to your GitLab account
|
||||
* |/gitlab disconnect| - Disconnect your Mattermost account from your GitLab account
|
||||
* |/gitlab todo| - Get a list of todos, assigned issues, assigned merge requests and merge requests awaiting your review
|
||||
* |/gitlab subscriptions list| - Will list the current channel subscriptions
|
||||
* |/gitlab subscriptions add owner[/repo] [features]| - Subscribe the current channel to receive notifications about opened merge requests and issues for a group or repository
|
||||
* |features| is a comma-delimited list of one or more the following:
|
||||
* issues - includes new and closed issues
|
||||
* confidential_issues - includes new and closed confidential issues
|
||||
* jobs - includes jobs status updates
|
||||
* merges - includes new and closed merge requests
|
||||
* pushes - includes pushes
|
||||
* issue_comments - includes new issue comments
|
||||
* merge_request_comments - include new merge-request comments
|
||||
* pipeline - includes pipeline runs
|
||||
* tag - include tag creation
|
||||
* pull_reviews - includes merge request reviews
|
||||
* label:"<labelname>" - must include "merges" or "issues" in feature list when using a label
|
||||
* Defaults to "merges,issues,tag"
|
||||
* |/gitlab subscriptions delete owner/repo| - Unsubscribe the current channel from a repository
|
||||
* |/gitlab pipelines run [owner]/repo [ref]| - Run a pipeline for specific repository and ref (branch/tag)
|
||||
* |/gitlab me| - Display the connected GitLab account
|
||||
* |/gitlab settings [setting] [value]| - Update your user settings
|
||||
* |setting| can be "notifications" or "reminders"
|
||||
* |value| can be "on" or "off"
|
||||
* |/gitlab webhook list [owner]/repo| - Will list associated group or project hooks.
|
||||
* |/gitlab webhook add owner[/repo] [options] [url] [token]|
|
||||
* |options| is a comma-delimited list of one or more the following:
|
||||
* |*| - or missing defaults to all with SSL verification enabled
|
||||
* *noSSL - all triggers with SSL verification not enabled.
|
||||
* PushEvents
|
||||
* TagPushEvents
|
||||
* Comments
|
||||
* ConfidentialComments
|
||||
* IssuesEvents
|
||||
* ConfidentialIssuesEvents
|
||||
* MergeRequestsEvents
|
||||
* JobEvents
|
||||
* PipelineEvents
|
||||
* WikiPageEvents
|
||||
* SSLverification
|
||||
* |url| is the URL that will be called when triggered. Defaults to this plugins URL
|
||||
* |token| Secret token. Defaults to secret token used in plugin's settings.
|
||||
* |/gitlab about| - Display build information about the plugin
|
||||
`
|
||||
const (
|
||||
webhookHowToURL = "https://github.com/mattermost/mattermost-plugin-gitlab#step-3-create-a-gitlab-webhook"
|
||||
inboundWebhookURL = "plugins/com.github.manland.mattermost-plugin-gitlab/webhook"
|
||||
specifyRepositoryMessage = "Please specify a repository."
|
||||
specifyRepositoryAndBranchMessage = "Please specify a repository and a branch."
|
||||
unknownActionMessage = "Unknown action, please use `/gitlab help` to see all actions available."
|
||||
newWebhookEmptySiteURLmessage = "Unable to create webhook. The Mattermot Site URL is not set. " +
|
||||
"Set it in the Admin Console or rerun /gitlab webhook add group/project URL including the desired URL."
|
||||
)
|
||||
|
||||
const (
|
||||
groupNotFoundError = "404 {message: 404 Group Not Found}"
|
||||
groupNotFoundMessage = "Unable to find GitLab group: "
|
||||
|
||||
projectNotFoundError = "404 {message: 404 Project Not Found}"
|
||||
projectNotFoundMessage = "Unable to find project with namespace: "
|
||||
|
||||
invalidSubscribeSubCommand = "Invalid subscribe command. Available commands are add, delete, and list"
|
||||
|
||||
invalidPipelinesSubCommand = "Invalid pipelines command. Available commands are run, list"
|
||||
)
|
||||
|
||||
const (
|
||||
commandAdd = "add"
|
||||
commandDelete = "delete"
|
||||
commandList = "list"
|
||||
|
||||
commandRun = "run"
|
||||
)
|
||||
|
||||
const (
|
||||
commandTimeout = 30 * time.Second
|
||||
)
|
||||
|
||||
func (p *Plugin) getCommand(config *configuration) (*model.Command, error) {
|
||||
iconData, err := command.GetIconData(&p.client.System, "assets/icon.svg")
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "failed to get icon data")
|
||||
}
|
||||
|
||||
return &model.Command{
|
||||
Trigger: "gitlab",
|
||||
AutoComplete: true,
|
||||
AutoCompleteDesc: "Available commands: connect, disconnect, todo, subscriptions, me, pipelines, settings, webhook, setup, help, about",
|
||||
AutoCompleteHint: "[command]",
|
||||
AutocompleteData: getAutocompleteData(config),
|
||||
AutocompleteIconData: iconData,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (p *Plugin) postCommandResponse(args *model.CommandArgs, text string) {
|
||||
post := &model.Post{
|
||||
UserId: p.BotUserID,
|
||||
ChannelId: args.ChannelId,
|
||||
RootId: args.RootId,
|
||||
Message: text,
|
||||
}
|
||||
p.client.Post.SendEphemeralPost(args.UserId, post)
|
||||
}
|
||||
|
||||
func (p *Plugin) getCommandResponse(args *model.CommandArgs, text string) *model.CommandResponse {
|
||||
p.postCommandResponse(args, text)
|
||||
return &model.CommandResponse{}
|
||||
}
|
||||
|
||||
// ExecuteCommand is the entrypoint for /gitlab commands. It returns a message to display to the user or an error.
|
||||
func (p *Plugin) ExecuteCommand(c *plugin.Context, args *model.CommandArgs) (res *model.CommandResponse, appErr *model.AppError) {
|
||||
var (
|
||||
split = strings.Fields(args.Command)
|
||||
cmd = split[0]
|
||||
action string
|
||||
parameters []string
|
||||
)
|
||||
if len(split) > 1 {
|
||||
action = split[1]
|
||||
}
|
||||
if len(split) > 2 {
|
||||
parameters = split[2:]
|
||||
}
|
||||
if cmd != "/gitlab" {
|
||||
return &model.CommandResponse{}, nil
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), commandTimeout)
|
||||
defer cancel()
|
||||
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
p.client.Log.Warn("Recovered from a panic",
|
||||
"Command", args.Command,
|
||||
"UserId", args.UserId,
|
||||
"error", r,
|
||||
"stack", string(debug.Stack()))
|
||||
res = &model.CommandResponse{}
|
||||
p.postCommandResponse(args, "An unexpected error occurred. Please try again later.")
|
||||
if *p.client.Configuration.GetConfig().ServiceSettings.EnableDeveloper {
|
||||
p.postCommandResponse(args, fmt.Sprintf("error: %v, \nstack:\n```\n%s\n```", r, string(debug.Stack())))
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
if action == "about" {
|
||||
text, err := command.BuildInfo(model.Manifest{
|
||||
Id: manifest.Id,
|
||||
Version: manifest.Version,
|
||||
Name: manifest.Name,
|
||||
})
|
||||
if err != nil {
|
||||
text = errors.Wrap(err, "failed to get build info").Error()
|
||||
}
|
||||
p.postCommandResponse(args, text)
|
||||
return &model.CommandResponse{}, nil
|
||||
}
|
||||
|
||||
if action == "setup" {
|
||||
message := p.handleSetup(c, args, parameters)
|
||||
if message != "" {
|
||||
p.postCommandResponse(args, message)
|
||||
}
|
||||
return &model.CommandResponse{}, nil
|
||||
}
|
||||
|
||||
config := p.getConfiguration()
|
||||
|
||||
if err := config.IsValid(); err != nil {
|
||||
isSysAdmin, err := p.isAuthorizedSysAdmin(args.UserId)
|
||||
var text string
|
||||
switch {
|
||||
case err != nil:
|
||||
text = "Error checking user's permissions"
|
||||
p.client.Log.Warn(text, "error", err.Error())
|
||||
case isSysAdmin:
|
||||
text = "Before using this plugin, you'll need to configure it by running `/gitlab setup`"
|
||||
default:
|
||||
text = "Please contact your system administrator to configure the GitLab plugin."
|
||||
}
|
||||
|
||||
p.postCommandResponse(args, text)
|
||||
return &model.CommandResponse{}, nil
|
||||
}
|
||||
|
||||
if action == "connect" {
|
||||
config := p.client.Configuration.GetConfig()
|
||||
if config.ServiceSettings.SiteURL == nil {
|
||||
return p.getCommandResponse(args, "Encountered an error connecting to GitLab."), nil
|
||||
}
|
||||
|
||||
resp := p.getCommandResponse(args, fmt.Sprintf("[Click here to link your GitLab account.](%s/plugins/%s/oauth/connect)", *config.ServiceSettings.SiteURL, manifest.Id))
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
if action == "help" || action == "" {
|
||||
text := "###### Mattermost GitLab Plugin - Slash Command Help\n" + strings.ReplaceAll(commandHelp, "|", "`")
|
||||
return p.getCommandResponse(args, text), nil
|
||||
}
|
||||
|
||||
info, apiErr := p.getGitlabUserInfoByMattermostID(args.UserId)
|
||||
if apiErr != nil {
|
||||
text := "Unknown error."
|
||||
if apiErr.ID == APIErrorIDNotConnected {
|
||||
text = "You must connect your account to GitLab first. Either click on the GitLab logo in the bottom left of the screen or enter `/gitlab connect`."
|
||||
}
|
||||
return p.getCommandResponse(args, text), nil
|
||||
}
|
||||
|
||||
switch action {
|
||||
case "subscriptions", "subscription", "subscribe":
|
||||
message := p.subscribeCommand(ctx, parameters, args.ChannelId, config, info)
|
||||
response := p.getCommandResponse(args, message)
|
||||
return response, nil
|
||||
case "unsubscribe":
|
||||
// subcommand subscriptions delete is preferred but unsubscribe remains to prevent breaking existing workflows
|
||||
var message string
|
||||
var err error
|
||||
|
||||
if len(parameters) == 0 {
|
||||
message = specifyRepositoryMessage
|
||||
} else {
|
||||
message, err = p.subscriptionDelete(info, config, parameters[0], args.ChannelId)
|
||||
if err != nil {
|
||||
message = err.Error()
|
||||
}
|
||||
}
|
||||
response := p.getCommandResponse(args, message)
|
||||
return response, nil
|
||||
case "disconnect":
|
||||
p.disconnectGitlabAccount(args.UserId)
|
||||
return p.getCommandResponse(args, "Disconnected your GitLab account."), nil
|
||||
case "todo":
|
||||
_, text, err := p.GetToDo(ctx, info)
|
||||
if err != nil {
|
||||
p.client.Log.Warn("can't get todo in command", "err", err.Error())
|
||||
return p.getCommandResponse(args, "Encountered an error getting your todo items."), nil
|
||||
}
|
||||
return p.getCommandResponse(args, text), nil
|
||||
case "me":
|
||||
var gitUser *gitlabLib.User
|
||||
err := p.useGitlabClient(info, func(info *gitlab.UserInfo, token *oauth2.Token) error {
|
||||
resp, err := p.GitlabClient.GetUserDetails(ctx, info, token)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
gitUser = resp
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return p.getCommandResponse(args, "Encountered an error getting your GitLab profile."), nil
|
||||
}
|
||||
|
||||
text := fmt.Sprintf("You are connected to GitLab as:\n# [](%s) [%s](%s)", gitUser.AvatarURL, gitUser.WebURL, gitUser.Username, gitUser.WebsiteURL)
|
||||
return p.getCommandResponse(args, text), nil
|
||||
case "settings":
|
||||
if len(parameters) < 2 {
|
||||
return p.getCommandResponse(args, "Please specify both a setting and value. Use `/gitlab help` for more usage information."), nil
|
||||
}
|
||||
|
||||
setting := parameters[0]
|
||||
strValue := parameters[1]
|
||||
value := false
|
||||
if strValue == SettingOn {
|
||||
value = true
|
||||
} else if strValue != SettingOff {
|
||||
return p.getCommandResponse(args, "Invalid value. Accepted values are: \"on\" or \"off\"."), nil
|
||||
}
|
||||
|
||||
switch setting {
|
||||
case SettingNotifications:
|
||||
if value {
|
||||
if err := p.storeGitlabToUserIDMapping(info.GitlabUsername, info.UserID); err != nil {
|
||||
p.client.Log.Warn("can't store GitLab to user id mapping", "err", err.Error())
|
||||
return p.getCommandResponse(args, "Unknown error please retry or ask to an administrator to look at logs"), nil
|
||||
}
|
||||
if err := p.storeGitlabIDToUserIDMapping(info.GitlabUsername, info.GitlabUserID); err != nil {
|
||||
p.client.Log.Warn("can't store GitLab to GitLab id mapping", "err", err.Error())
|
||||
return p.getCommandResponse(args, "Unknown error please retry or ask to an administrator to look at logs"), nil
|
||||
}
|
||||
} else if err := p.deleteGitlabToUserIDMapping(info.GitlabUsername); err != nil {
|
||||
p.client.Log.Warn("can't delete GitLab username in kvstore", "err", err.Error())
|
||||
return p.getCommandResponse(args, "Unknown error please retry or ask to an administrator to look at logs"), nil
|
||||
}
|
||||
info.Settings.Notifications = value
|
||||
case SettingReminders:
|
||||
info.Settings.DailyReminder = value
|
||||
default:
|
||||
return p.getCommandResponse(args, "Unknown setting."), nil
|
||||
}
|
||||
|
||||
if err := p.storeGitlabUserInfo(info); err != nil {
|
||||
p.client.Log.Warn("can't store user info after update by command", "err", err.Error())
|
||||
return p.getCommandResponse(args, "Unknown error please retry or ask to an administrator to look at logs"), nil
|
||||
}
|
||||
|
||||
return p.getCommandResponse(args, "Settings updated."), nil
|
||||
|
||||
case "webhook":
|
||||
message := p.webhookCommand(ctx, parameters, info, config.EnablePrivateRepo)
|
||||
response := p.getCommandResponse(args, message)
|
||||
return response, nil
|
||||
case "pipelines":
|
||||
message := p.pipelinesCommand(ctx, parameters, args.ChannelId, info)
|
||||
response := p.getCommandResponse(args, message)
|
||||
return response, nil
|
||||
default:
|
||||
return p.getCommandResponse(args, unknownActionMessage), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Plugin) handleSetup(c *plugin.Context, args *model.CommandArgs, parameters []string) string {
|
||||
userID := args.UserId
|
||||
isSysAdmin, err := p.isAuthorizedSysAdmin(userID)
|
||||
if err != nil {
|
||||
p.client.Log.Warn("Failed to check if user is System Admin", "error", err.Error())
|
||||
|
||||
return "Error checking user's permissions"
|
||||
}
|
||||
|
||||
if !isSysAdmin {
|
||||
return "Only System Admins are allowed to set up the plugin."
|
||||
}
|
||||
|
||||
if len(parameters) == 0 {
|
||||
err = p.flowManager.StartSetupWizard(userID, "")
|
||||
} else {
|
||||
command := parameters[0]
|
||||
|
||||
switch {
|
||||
case command == "oauth":
|
||||
err = p.flowManager.StartOauthWizard(userID)
|
||||
case command == "webhook":
|
||||
err = p.flowManager.StartWebhookWizard(userID)
|
||||
case command == "announcement":
|
||||
err = p.flowManager.StartAnnouncementWizard(userID)
|
||||
default:
|
||||
return fmt.Sprintf("Unknown subcommand %v", command)
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return err.Error()
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
// webhookCommand processes the /gitlab webhook commands
|
||||
func (p *Plugin) webhookCommand(ctx context.Context, parameters []string, info *gitlab.UserInfo, enablePrivateRepo bool) string {
|
||||
if len(parameters) < 1 {
|
||||
return unknownActionMessage
|
||||
}
|
||||
subCommand := parameters[0]
|
||||
|
||||
switch subCommand {
|
||||
case commandList:
|
||||
if len(parameters) != 2 {
|
||||
return unknownActionMessage
|
||||
}
|
||||
|
||||
namespace := parameters[1]
|
||||
var group, project string
|
||||
err := p.useGitlabClient(info, func(info *gitlab.UserInfo, token *oauth2.Token) error {
|
||||
respGroup, respProject, err := p.GitlabClient.ResolveNamespaceAndProject(ctx, info, token, namespace, enablePrivateRepo)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
group = respGroup
|
||||
project = respProject
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return err.Error()
|
||||
}
|
||||
|
||||
var webhookInfo []*gitlab.WebhookInfo
|
||||
if project != "" {
|
||||
err := p.useGitlabClient(info, func(info *gitlab.UserInfo, token *oauth2.Token) error {
|
||||
resp, err := p.GitlabClient.GetProjectHooks(ctx, info, token, group, project)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
webhookInfo = resp
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), projectNotFoundError) {
|
||||
return projectNotFoundMessage + namespace
|
||||
}
|
||||
return err.Error()
|
||||
}
|
||||
} else {
|
||||
err := p.useGitlabClient(info, func(info *gitlab.UserInfo, token *oauth2.Token) error {
|
||||
resp, err := p.GitlabClient.GetGroupHooks(ctx, info, token, group)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
webhookInfo = resp
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), groupNotFoundError) {
|
||||
return groupNotFoundMessage + group
|
||||
}
|
||||
return err.Error()
|
||||
}
|
||||
}
|
||||
if len(webhookInfo) == 0 {
|
||||
return fmt.Sprintf("No webhooks found in %s", namespace)
|
||||
}
|
||||
var formatedWebhooks string
|
||||
for _, hook := range webhookInfo {
|
||||
formatedWebhooks += hook.String()
|
||||
}
|
||||
return formatedWebhooks
|
||||
|
||||
case commandAdd:
|
||||
if len(parameters) < 2 {
|
||||
return unknownActionMessage
|
||||
}
|
||||
|
||||
siteURL := *p.client.Configuration.GetConfig().ServiceSettings.SiteURL
|
||||
if siteURL == "" {
|
||||
return newWebhookEmptySiteURLmessage
|
||||
}
|
||||
|
||||
urlPath := fmt.Sprintf("%v/%s", siteURL, inboundWebhookURL)
|
||||
if len(parameters) > 3 {
|
||||
urlPath = parameters[3]
|
||||
}
|
||||
|
||||
// default to all triggers unless specified
|
||||
hookOptions := parseTriggers("*")
|
||||
if len(parameters) > 2 {
|
||||
triggersCsv := parameters[2]
|
||||
hookOptions = parseTriggers(triggersCsv)
|
||||
}
|
||||
hookOptions.URL = urlPath
|
||||
|
||||
if len(parameters) > 4 {
|
||||
hookOptions.Token = parameters[4]
|
||||
} else {
|
||||
hookOptions.Token = p.getConfiguration().WebhookSecret
|
||||
}
|
||||
|
||||
namespace := parameters[1]
|
||||
var group, project string
|
||||
namespaceErr := p.useGitlabClient(info, func(info *gitlab.UserInfo, token *oauth2.Token) error {
|
||||
respGroup, respProject, err := p.GitlabClient.ResolveNamespaceAndProject(ctx, info, token, namespace, enablePrivateRepo)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
group = respGroup
|
||||
project = respProject
|
||||
return nil
|
||||
})
|
||||
if namespaceErr != nil {
|
||||
return namespaceErr.Error()
|
||||
}
|
||||
|
||||
newWebhook, err := p.createHook(ctx, p.GitlabClient, info, group, project, hookOptions)
|
||||
if err != nil {
|
||||
return err.Error()
|
||||
}
|
||||
return fmt.Sprintf("Webhook Created:\n%s", newWebhook.String())
|
||||
|
||||
default:
|
||||
return fmt.Sprintf("Unknown webhook command: %s", subCommand)
|
||||
}
|
||||
}
|
||||
|
||||
func parseTriggers(triggersCsv string) *gitlab.AddWebhookOptions {
|
||||
var sslVerification, pushEvents, tagPushEvents, issuesEvents, confidentialIssuesEvents, noteEvents bool
|
||||
var confidentialNoteEvents, mergeRequestsEvents, jobEvents, pipelineEvents, wikiPageEvents bool
|
||||
var all bool
|
||||
if triggersCsv == "*" {
|
||||
all = true
|
||||
sslVerification = true
|
||||
}
|
||||
if strings.EqualFold(triggersCsv, "*noSSL") {
|
||||
all = true
|
||||
sslVerification = false
|
||||
}
|
||||
triggers := strings.Split(triggersCsv, ",")
|
||||
for _, trigger := range triggers {
|
||||
if strings.EqualFold(trigger, "SSLverification") {
|
||||
sslVerification = true
|
||||
}
|
||||
if all || strings.EqualFold(trigger, "PushEvents") {
|
||||
pushEvents = true
|
||||
}
|
||||
if all || strings.EqualFold(trigger, "TagPushEvents") {
|
||||
tagPushEvents = true
|
||||
}
|
||||
if all || strings.EqualFold(trigger, "IssuesEvents") {
|
||||
issuesEvents = true
|
||||
}
|
||||
if all || strings.EqualFold(trigger, "ConfidentialIssuesEvents") {
|
||||
confidentialIssuesEvents = true
|
||||
}
|
||||
if all || strings.EqualFold(trigger, "Comments") {
|
||||
noteEvents = true
|
||||
}
|
||||
if all || strings.EqualFold(trigger, "ConfidentialComments") {
|
||||
confidentialNoteEvents = true
|
||||
}
|
||||
if all || strings.EqualFold(trigger, "MergeRequestsEvents") {
|
||||
mergeRequestsEvents = true
|
||||
}
|
||||
if all || strings.EqualFold(trigger, "JobEvents") {
|
||||
jobEvents = true
|
||||
}
|
||||
if all || strings.EqualFold(trigger, "PipelineEvents") {
|
||||
pipelineEvents = true
|
||||
}
|
||||
if all || strings.EqualFold(trigger, "WikiPageEvents") {
|
||||
wikiPageEvents = true
|
||||
}
|
||||
}
|
||||
|
||||
return &gitlab.AddWebhookOptions{
|
||||
EnableSSLVerification: sslVerification,
|
||||
ConfidentialNoteEvents: confidentialNoteEvents,
|
||||
PushEvents: pushEvents,
|
||||
IssuesEvents: issuesEvents,
|
||||
ConfidentialIssuesEvents: confidentialIssuesEvents,
|
||||
MergeRequestsEvents: mergeRequestsEvents,
|
||||
TagPushEvents: tagPushEvents,
|
||||
NoteEvents: noteEvents,
|
||||
JobEvents: jobEvents,
|
||||
PipelineEvents: pipelineEvents,
|
||||
WikiPageEvents: wikiPageEvents,
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Plugin) subscriptionDelete(info *gitlab.UserInfo, config *configuration, fullPath, channelID string) (string, error) {
|
||||
normalizedPath := normalizePath(fullPath, config.GitlabURL)
|
||||
deleted, updatedSubscriptions, err := p.Unsubscribe(channelID, normalizedPath)
|
||||
if err != nil {
|
||||
p.client.Log.Warn("can't unsubscribe channel in command", "err", err.Error())
|
||||
return "Encountered an error trying to unsubscribe. Please try again.", nil
|
||||
}
|
||||
|
||||
if !deleted {
|
||||
return "Subscription not found, please check repository name.", nil
|
||||
}
|
||||
|
||||
p.sendChannelSubscriptionsUpdated(updatedSubscriptions, channelID)
|
||||
|
||||
return fmt.Sprintf("Successfully deleted subscription for %s.", normalizedPath), nil
|
||||
}
|
||||
|
||||
// subscriptionsListCommand list GitLab subscriptions in a channel
|
||||
func (p *Plugin) subscriptionsListCommand(channelID string) string {
|
||||
var txt string
|
||||
subs, err := p.GetSubscriptionsByChannel(channelID)
|
||||
if err != nil {
|
||||
return err.Error()
|
||||
}
|
||||
|
||||
if len(subs) == 0 {
|
||||
txt = "Currently there are no subscriptions in this channel"
|
||||
} else {
|
||||
txt = "### Subscriptions in this channel\n"
|
||||
}
|
||||
for _, sub := range subs {
|
||||
txt += fmt.Sprintf("* `%s` - %s\n", strings.Trim(sub.Repository, "/"), sub.Features)
|
||||
}
|
||||
return txt
|
||||
}
|
||||
|
||||
// subscriptionsAddCommand subscripes to A GitLab Project
|
||||
func (p *Plugin) subscriptionsAddCommand(ctx context.Context, info *gitlab.UserInfo, config *configuration, fullPath, channelID, features string) string {
|
||||
var namespace, project string
|
||||
err := p.useGitlabClient(info, func(info *gitlab.UserInfo, token *oauth2.Token) error {
|
||||
respGroup, respProject, err := p.GitlabClient.ResolveNamespaceAndProject(ctx, info, token, fullPath, config.EnablePrivateRepo)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
namespace = respGroup
|
||||
project = respProject
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, gitlab.ErrNotFound) {
|
||||
return "Resource with such path is not found."
|
||||
} else if errors.Is(err, gitlab.ErrPrivateResource) {
|
||||
return "Requested resource is private."
|
||||
}
|
||||
p.client.Log.Warn(
|
||||
"unable to resolve subscription namespace and project name",
|
||||
"err", err.Error(),
|
||||
)
|
||||
return err.Error()
|
||||
}
|
||||
|
||||
if hasPermission := p.permissionToProject(ctx, info.UserID, namespace, project); !hasPermission {
|
||||
msg := "You don't have the permissions to create subscriptions for this project."
|
||||
p.client.Log.Warn(msg)
|
||||
return msg
|
||||
}
|
||||
|
||||
updatedSubscriptions, subscribeErr := p.Subscribe(info, namespace, project, channelID, features)
|
||||
if subscribeErr != nil {
|
||||
p.client.Log.Warn(
|
||||
"failed to subscribe",
|
||||
"namespace", namespace,
|
||||
"project", project,
|
||||
"err", subscribeErr.Error(),
|
||||
)
|
||||
return subscribeErr.Error()
|
||||
}
|
||||
var hasHook bool
|
||||
if project != "" {
|
||||
hasHook, err = p.HasProjectHook(ctx, info, namespace, project)
|
||||
if err != nil {
|
||||
return fmt.Sprintf(
|
||||
"Unable to determine status of Webhook. See [setup instructions](%s) to validate.",
|
||||
webhookHowToURL,
|
||||
)
|
||||
}
|
||||
} else {
|
||||
hasHook, err = p.HasGroupHook(ctx, info, namespace)
|
||||
if err != nil {
|
||||
return fmt.Sprintf(
|
||||
"Unable to determine status of Webhook. See [setup instructions](%s) to validate.",
|
||||
webhookHowToURL,
|
||||
)
|
||||
}
|
||||
}
|
||||
var hookStatusMessage string
|
||||
if !hasHook {
|
||||
// no web hook found
|
||||
hookStatusMessage = fmt.Sprintf(
|
||||
"\nA Webhook is needed, run ```/gitlab webhook add %s``` to create one now.",
|
||||
fullPath,
|
||||
)
|
||||
}
|
||||
|
||||
p.sendChannelSubscriptionsUpdated(updatedSubscriptions, channelID)
|
||||
|
||||
return fmt.Sprintf("Successfully subscribed to %s.%s", fullPath, hookStatusMessage)
|
||||
}
|
||||
|
||||
// subscribeCommand process the /gitlab subscribe command.
|
||||
// It returns a message and handles all errors my including helpful information in the message
|
||||
func (p *Plugin) subscribeCommand(ctx context.Context, parameters []string, channelID string, config *configuration, info *gitlab.UserInfo) string {
|
||||
if len(parameters) == 0 {
|
||||
return invalidSubscribeSubCommand
|
||||
}
|
||||
|
||||
subcommand := parameters[0]
|
||||
|
||||
switch subcommand {
|
||||
case commandList:
|
||||
return p.subscriptionsListCommand(channelID)
|
||||
case commandAdd:
|
||||
features := "merges,issues,tag"
|
||||
if len(parameters) > 2 {
|
||||
features = strings.Join(parameters[2:], " ")
|
||||
}
|
||||
// Resolve namespace and project name
|
||||
fullPath := normalizePath(parameters[1], config.GitlabURL)
|
||||
|
||||
return p.subscriptionsAddCommand(ctx, info, config, fullPath, channelID, features)
|
||||
case commandDelete:
|
||||
if len(parameters) < 2 {
|
||||
return specifyRepositoryMessage
|
||||
}
|
||||
|
||||
message, err := p.subscriptionDelete(info, config, parameters[1], channelID)
|
||||
if err != nil {
|
||||
return err.Error()
|
||||
}
|
||||
return message
|
||||
default:
|
||||
return invalidSubscribeSubCommand
|
||||
}
|
||||
}
|
||||
func (p *Plugin) pipelinesCommand(ctx context.Context, parameters []string, channelID string, info *gitlab.UserInfo) string {
|
||||
if len(parameters) == 0 {
|
||||
return invalidPipelinesSubCommand
|
||||
}
|
||||
subcommand := parameters[0]
|
||||
switch subcommand {
|
||||
case commandRun:
|
||||
if len(parameters) < 3 {
|
||||
return specifyRepositoryAndBranchMessage
|
||||
}
|
||||
namespace := parameters[1]
|
||||
ref := parameters[2]
|
||||
return p.pipelineRunCommand(ctx, namespace, ref, channelID, info)
|
||||
default:
|
||||
return unknownActionMessage
|
||||
}
|
||||
}
|
||||
|
||||
// pipelineRunCommand run a pipeline in a project
|
||||
func (p *Plugin) pipelineRunCommand(ctx context.Context, namespace, ref, channelID string, info *gitlab.UserInfo) string {
|
||||
var pipelineInfo *gitlab.PipelineInfo
|
||||
err := p.useGitlabClient(info, func(info *gitlab.UserInfo, token *oauth2.Token) error {
|
||||
groupName, projectName, err := p.GitlabClient.ResolveNamespaceAndProject(ctx, info, token, namespace, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
project, err := p.GitlabClient.GetProject(ctx, info, token, groupName, projectName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
projectID := fmt.Sprintf("%d", project.ID)
|
||||
pipelineInfo, err = p.GitlabClient.TriggerProjectPipeline(info, token, projectID, ref)
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "failed to run pipeline for Project: :%s", projectName)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return err.Error()
|
||||
}
|
||||
|
||||
var txt string
|
||||
if pipelineInfo == nil {
|
||||
txt = "Currently there is no pipeline info"
|
||||
return txt
|
||||
}
|
||||
txt = "### Pipeline info\n"
|
||||
txt += fmt.Sprintf("**Status**: %s\n", pipelineInfo.Status)
|
||||
txt += fmt.Sprintf("**SHA**: %s\n", pipelineInfo.SHA)
|
||||
txt += fmt.Sprintf("**Ref**: %s\n", pipelineInfo.Ref)
|
||||
txt += fmt.Sprintf("**Triggered By**: %s\n", pipelineInfo.User)
|
||||
txt += fmt.Sprintf("**Visit pipeline [here](%s)** \n\n", pipelineInfo.WebURL)
|
||||
|
||||
foundPipelineSubscription := false
|
||||
subs, err := p.GetSubscriptionsByChannel(channelID)
|
||||
if err != nil {
|
||||
p.client.Log.Warn("Failed to get subscriptions for the channel", "channel_id", channelID, "error", err.Error())
|
||||
return txt
|
||||
}
|
||||
|
||||
for _, sub := range subs {
|
||||
if sub.Repository == namespace && sub.Pipeline() {
|
||||
foundPipelineSubscription = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !foundPipelineSubscription {
|
||||
txt += fmt.Sprintf("\n\n**Note:** This channel is currently not subscribed to pipeline event for `%s`. Run the command below if would you like to create a subscription.\n\n`/gitlab subscriptions add %s pipeline`", namespace, namespace)
|
||||
}
|
||||
|
||||
return txt
|
||||
}
|
||||
|
||||
func (p *Plugin) isAuthorizedSysAdmin(userID string) (bool, error) {
|
||||
user, err := p.client.User.Get(userID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if !strings.Contains(user.Roles, "system_admin") {
|
||||
return false, nil
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func getAutocompleteData(config *configuration) *model.AutocompleteData {
|
||||
if !config.IsOAuthConfigured() {
|
||||
gitlab := model.NewAutocompleteData("gitlab", "[command]", "Available commands: setup, about")
|
||||
|
||||
setup := model.NewAutocompleteData("setup", "", "Set up the GitLab plugin")
|
||||
gitlab.AddCommand(setup)
|
||||
|
||||
about := command.BuildInfoAutocomplete("about")
|
||||
gitlab.AddCommand(about)
|
||||
|
||||
return gitlab
|
||||
}
|
||||
|
||||
gitlab := model.NewAutocompleteData("gitlab", "[command]", "Available commands: connect, disconnect, todo, subscriptions, me, pipelines, settings, webhook, setup, help, about")
|
||||
|
||||
connect := model.NewAutocompleteData("connect", "", "Connect your GitLab account")
|
||||
gitlab.AddCommand(connect)
|
||||
|
||||
disconnect := model.NewAutocompleteData("disconnect", "", "disconnect your GitLab account")
|
||||
gitlab.AddCommand(disconnect)
|
||||
|
||||
todo := model.NewAutocompleteData("todo", "", "Get a list of todos, assigned issues, assigned merge requests and merge requests awaiting your review")
|
||||
gitlab.AddCommand(todo)
|
||||
|
||||
subscriptions := model.NewAutocompleteData("subscriptions", "[command]", "Available commands: Add, List, Delete")
|
||||
|
||||
subscriptionsList := model.NewAutocompleteData(commandList, "", "List current channel subscriptions")
|
||||
subscriptions.AddCommand(subscriptionsList)
|
||||
|
||||
subscriptionsAdd := model.NewAutocompleteData(commandAdd, "owner[/repo] [features]", "Subscribe the current channel to receive notifications from a project")
|
||||
subscriptionsAdd.AddTextArgument("Project path: includes user or group name with optional slash project name", "owner[/repo]", "")
|
||||
subscriptionsAdd.AddTextArgument("comma-delimited list of features to subscribe to: issues, confidential_issues, merges, pushes, issue_comments, merge_request_comments, pipeline, tag, pull_reviews, label:<labelName>", "[features] (optional)", `/[^,-\s]+(,[^,-\s]+)*/`)
|
||||
subscriptions.AddCommand(subscriptionsAdd)
|
||||
|
||||
subscriptionsDelete := model.NewAutocompleteData(commandDelete, "owner[/repo]", "Unsubscribe the current channel from a repository")
|
||||
subscriptionsDelete.AddTextArgument("Project path: includes user or group name with optional slash project name", "owner[/repo]", "")
|
||||
subscriptions.AddCommand(subscriptionsDelete)
|
||||
|
||||
gitlab.AddCommand(subscriptions)
|
||||
|
||||
me := model.NewAutocompleteData("me", "", "Displays the connected GitLab account")
|
||||
gitlab.AddCommand(me)
|
||||
|
||||
pipelines := model.NewAutocompleteData("pipelines", "[command]", "Available commands: Run, Trigger")
|
||||
pipelineRun := model.NewAutocompleteData(commandRun, "owner[/repo] [ref]", "Run a pipeline for the provided project")
|
||||
pipelineRun.AddTextArgument("Project path: includes user or group name with optional slash project name", "", "owner[/repo] [ref]")
|
||||
pipelines.AddCommand(pipelineRun)
|
||||
|
||||
gitlab.AddCommand(pipelines)
|
||||
|
||||
settings := model.NewAutocompleteData("settings", "[setting]", "Update your user settings")
|
||||
settingOptions := []model.AutocompleteListItem{{
|
||||
HelpText: "Turn notifications on/off",
|
||||
Item: "notifications",
|
||||
}, {
|
||||
HelpText: "Turn reminders on/off",
|
||||
Item: "reminders",
|
||||
}}
|
||||
settings.AddStaticListArgument("Setting to update", true, settingOptions)
|
||||
|
||||
value := []model.AutocompleteListItem{{
|
||||
HelpText: "Turn setting on",
|
||||
Item: "on",
|
||||
}, {
|
||||
HelpText: "Turn setting off",
|
||||
Item: "off",
|
||||
}}
|
||||
settings.AddStaticListArgument("New value", true, value)
|
||||
gitlab.AddCommand(settings)
|
||||
|
||||
webhook := model.NewAutocompleteData("webhook", "[command]", "Available Commands: list, add")
|
||||
webhookList := model.NewAutocompleteData(commandList, "owner/[repo]", "List existing project or group webhooks")
|
||||
webhookList.AddTextArgument("Project path: includes user or group name with optional slash project name", "owner[/repo]", "")
|
||||
webhook.AddCommand(webhookList)
|
||||
|
||||
webhookAdd := model.NewAutocompleteData(commandAdd, "owner/[repo] [options] [url] [token]", "Add a project or group webhook")
|
||||
webhookAdd.AddTextArgument("Group or Project path: includes user or group name with optional slash project name", "owner[/repo]", "")
|
||||
webhookAdd.AddTextArgument("[Optional] options: comma-delimited list of actions to trigger a webhook, defaults to all with SSL verification", "[* or *noSSL] or [PushEvents,][TagPushEvents,][Comments,][ConfidentialComments,][IssuesEvents,][ConfidentialIssuesEvents,][MergeRequestsEvents,][JobEvents,][PipelineEvents,][WikiPageEvents,][SSLverification]", "")
|
||||
webhookAdd.AddTextArgument("[Optional] url: URL to be triggered triggered. Defaults to this plugins URL", "[url]", "")
|
||||
webhookAdd.AddTextArgument("[Optional] token: Secret for webhook. Defaults to token used in plugin's settings.", "[token]", "")
|
||||
webhook.AddCommand(webhookAdd)
|
||||
|
||||
gitlab.AddCommand(webhook)
|
||||
|
||||
setup := model.NewAutocompleteData("setup", "[command]", "Available commands: oauth, webhook, announcement")
|
||||
setup.RoleID = model.SystemAdminRoleId
|
||||
setup.AddCommand(model.NewAutocompleteData("oauth", "", "Set up the OAuth2 Application in GitLab"))
|
||||
setup.AddCommand(model.NewAutocompleteData("webhook", "", "Create a webhook from GitLab to Mattermost"))
|
||||
setup.AddCommand(model.NewAutocompleteData("announcement", "", "Announce to your team that they can use GitLab integration"))
|
||||
gitlab.AddCommand(setup)
|
||||
|
||||
help := model.NewAutocompleteData("help", "", "Display GiLab Plug Help.")
|
||||
gitlab.AddCommand(help)
|
||||
|
||||
about := command.BuildInfoAutocomplete("about")
|
||||
gitlab.AddCommand(about)
|
||||
|
||||
return gitlab
|
||||
}
|
||||
@@ -0,0 +1,463 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/golang/mock/gomock"
|
||||
"github.com/mattermost/mattermost/server/public/model"
|
||||
"github.com/mattermost/mattermost/server/public/plugin/plugintest"
|
||||
"github.com/mattermost/mattermost/server/public/pluginapi"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/require"
|
||||
gitLabAPI "github.com/xanzy/go-gitlab"
|
||||
|
||||
"github.com/mattermost/mattermost-plugin-gitlab/server/gitlab"
|
||||
mocks "github.com/mattermost/mattermost-plugin-gitlab/server/gitlab/mocks"
|
||||
)
|
||||
|
||||
type subscribeCommandTest struct {
|
||||
testName string
|
||||
parameters []string
|
||||
want string
|
||||
webhookInfo []*gitlab.WebhookInfo
|
||||
mattermostURL string
|
||||
noAccess bool
|
||||
projectHookErr error
|
||||
getProjectErr error
|
||||
mockGitlab bool
|
||||
}
|
||||
|
||||
const subscribeSuccessMessage = "Successfully subscribed to group/project.\nA Webhook is needed, run ```/gitlab webhook add group/project``` to create one now."
|
||||
const testGitlabToken = `{"access_token":"6328a1014b19f741489b48cdc4291d93aa2957b0cea67335a34dcdadaf212139","token_type":"Bearer","refresh_token":"e6453b621e8979214c9f8a1b0e1e39723df8af11cef5e0d613a2cb2e39bdfeb7","expiry":"3022-10-23T15:14:43.623638795-05:00"}`
|
||||
const testEncryptionKey = `shD-LC2DElnQzUO50cbvlOvjsNnzfEbk`
|
||||
|
||||
var subscribeCommandTests = []subscribeCommandTest{
|
||||
{
|
||||
testName: "No Subscriptions",
|
||||
parameters: []string{"list"},
|
||||
want: "Currently there are no subscriptions in this channel",
|
||||
},
|
||||
{
|
||||
testName: "No Repository permissions",
|
||||
parameters: []string{"add", "group/project"},
|
||||
mockGitlab: true,
|
||||
want: "You don't have the permissions to create subscriptions for this project.",
|
||||
webhookInfo: []*gitlab.WebhookInfo{{URL: "example.com/somewebhookURL"}},
|
||||
noAccess: true,
|
||||
mattermostURL: "example.com",
|
||||
getProjectErr: errors.New("unable to get project"),
|
||||
},
|
||||
{
|
||||
testName: "Guest permissions only",
|
||||
parameters: []string{"add", "group/project"},
|
||||
mockGitlab: true,
|
||||
want: "You don't have the permissions to create subscriptions for this project.",
|
||||
webhookInfo: []*gitlab.WebhookInfo{{URL: "example.com/somewebhookURL"}},
|
||||
noAccess: true,
|
||||
mattermostURL: "example.com",
|
||||
},
|
||||
{
|
||||
testName: "Hook Found",
|
||||
parameters: []string{"add", "group/project"},
|
||||
mockGitlab: true,
|
||||
want: "Successfully subscribed to group/project.",
|
||||
webhookInfo: []*gitlab.WebhookInfo{{URL: "example.com/somewebhookURL"}},
|
||||
mattermostURL: "example.com",
|
||||
},
|
||||
{
|
||||
testName: "No webhooks",
|
||||
parameters: []string{"add", "group/project"},
|
||||
mattermostURL: "example.com",
|
||||
webhookInfo: []*gitlab.WebhookInfo{{}},
|
||||
mockGitlab: true,
|
||||
want: subscribeSuccessMessage,
|
||||
},
|
||||
{
|
||||
testName: "Multiple un-matching hooks",
|
||||
parameters: []string{"add", "group/project"},
|
||||
mattermostURL: "example.com",
|
||||
mockGitlab: true,
|
||||
webhookInfo: []*gitlab.WebhookInfo{{URL: "www.anotherhook.io/wrong"}, {URL: "www.213210948239324.edu/notgood"}},
|
||||
want: subscribeSuccessMessage,
|
||||
},
|
||||
{
|
||||
testName: "Error getting webhooks",
|
||||
parameters: []string{"add", "group"},
|
||||
mattermostURL: "example.com",
|
||||
mockGitlab: true,
|
||||
webhookInfo: []*gitlab.WebhookInfo{{}},
|
||||
want: "Unable to determine status of Webhook. See [setup instructions](https://github.com/mattermost/mattermost-plugin-gitlab#step-3-create-a-gitlab-webhook) to validate.",
|
||||
projectHookErr: errors.New("unable to get project hooks"),
|
||||
},
|
||||
}
|
||||
|
||||
func TestSubscribeCommand(t *testing.T) {
|
||||
for _, test := range subscribeCommandTests {
|
||||
t.Run(test.testName, func(t *testing.T) {
|
||||
mockCtrl := gomock.NewController(t)
|
||||
|
||||
channelID := "12345"
|
||||
userInfo := &gitlab.UserInfo{
|
||||
UserID: "user_id",
|
||||
}
|
||||
|
||||
p := getTestPlugin(t, mockCtrl, test.webhookInfo, test.mattermostURL, test.projectHookErr, test.getProjectErr, test.mockGitlab, test.noAccess)
|
||||
subscribeMessage := p.subscribeCommand(context.Background(), test.parameters, channelID, &configuration{}, userInfo)
|
||||
|
||||
assert.Equal(t, test.want, subscribeMessage, "Subscribe command message should be the same.")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type webhookCommandTest struct {
|
||||
testName string
|
||||
parameters []string
|
||||
scope string
|
||||
webhookInfo []*gitlab.WebhookInfo
|
||||
want string
|
||||
siteURL string
|
||||
webhook *gitlab.WebhookInfo
|
||||
}
|
||||
|
||||
var listWebhookCommandTests = []webhookCommandTest{
|
||||
{
|
||||
testName: "List Project hooks",
|
||||
parameters: []string{"list", "group/project"},
|
||||
scope: "project",
|
||||
webhookInfo: []*gitlab.WebhookInfo{
|
||||
{
|
||||
URL: "http://yourURL/plugins/com.github.manland.mattermost-plugin-gitlab/webhook",
|
||||
PushEvents: true,
|
||||
IssuesEvents: true,
|
||||
ConfidentialIssuesEvents: true,
|
||||
MergeRequestsEvents: true,
|
||||
TagPushEvents: true,
|
||||
NoteEvents: true,
|
||||
JobEvents: false,
|
||||
PipelineEvents: false,
|
||||
WikiPageEvents: false,
|
||||
},
|
||||
},
|
||||
want: "\n\n`http://yourURL/plugins/com.github.manland.mattermost-plugin-gitlab/webhook`" + `
|
||||
Triggers:
|
||||
* Push Events
|
||||
* Tag Push Events
|
||||
* Comments
|
||||
* Issues Events
|
||||
* Confidential Issues Events
|
||||
* Merge Request Events
|
||||
`,
|
||||
},
|
||||
{
|
||||
testName: "List multiple project hooks",
|
||||
parameters: []string{"list", "group/project"},
|
||||
scope: "project",
|
||||
webhookInfo: []*gitlab.WebhookInfo{
|
||||
{
|
||||
URL: "http://yourURL/plugins/com.github.manland.mattermost-plugin-gitlab/webhook",
|
||||
PushEvents: true,
|
||||
},
|
||||
{
|
||||
URL: "http://anotherURL",
|
||||
PushEvents: true,
|
||||
},
|
||||
},
|
||||
want: "\n\n`http://yourURL/plugins/com.github.manland.mattermost-plugin-gitlab/webhook`" + `
|
||||
Triggers:
|
||||
* Push Events
|
||||
` + "\n\n`http://anotherURL`" + `
|
||||
Triggers:
|
||||
* Push Events
|
||||
`,
|
||||
},
|
||||
{
|
||||
testName: "List Group hooks",
|
||||
parameters: []string{"list", "group"},
|
||||
scope: "group",
|
||||
webhookInfo: []*gitlab.WebhookInfo{
|
||||
{
|
||||
URL: "http://yourURL/plugins/com.github.manland.mattermost-plugin-gitlab/webhook",
|
||||
PushEvents: true,
|
||||
IssuesEvents: true,
|
||||
ConfidentialIssuesEvents: true,
|
||||
MergeRequestsEvents: true,
|
||||
TagPushEvents: true,
|
||||
NoteEvents: true,
|
||||
JobEvents: false,
|
||||
PipelineEvents: false,
|
||||
WikiPageEvents: false,
|
||||
},
|
||||
},
|
||||
want: "\n\n`http://yourURL/plugins/com.github.manland.mattermost-plugin-gitlab/webhook`" + `
|
||||
Triggers:
|
||||
* Push Events
|
||||
* Tag Push Events
|
||||
* Comments
|
||||
* Issues Events
|
||||
* Confidential Issues Events
|
||||
* Merge Request Events
|
||||
`,
|
||||
},
|
||||
{
|
||||
testName: "Unrecognized sub command",
|
||||
parameters: []string{"invalid", "group"},
|
||||
want: "Unknown webhook command: invalid",
|
||||
},
|
||||
{
|
||||
testName: "List missing namespace",
|
||||
parameters: []string{"list"},
|
||||
want: "Unknown action, please use `/gitlab help` to see all actions available.",
|
||||
},
|
||||
}
|
||||
|
||||
func TestListWebhookCommand(t *testing.T) {
|
||||
for _, test := range listWebhookCommandTests {
|
||||
t.Run(test.testName, func(t *testing.T) {
|
||||
p := new(Plugin)
|
||||
|
||||
mockCtrl := gomock.NewController(t)
|
||||
mockedClient := mocks.NewMockGitlab(mockCtrl)
|
||||
|
||||
encryptedToken, _ := encrypt([]byte(testEncryptionKey), testGitlabToken)
|
||||
|
||||
p.configuration = &configuration{
|
||||
EncryptionKey: testEncryptionKey,
|
||||
}
|
||||
|
||||
api := &plugintest.API{}
|
||||
api.On("KVGet", "_usertoken").Return([]byte(encryptedToken), nil)
|
||||
p.SetAPI(api)
|
||||
p.client = pluginapi.NewClient(api, p.Driver)
|
||||
|
||||
if test.scope == "project" {
|
||||
mockedClient.EXPECT().GetProjectHooks(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(test.webhookInfo, nil)
|
||||
mockedClient.EXPECT().ResolveNamespaceAndProject(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), true).Return("group", "project", nil)
|
||||
p.GitlabClient = mockedClient
|
||||
} else if test.scope == "group" {
|
||||
mockedClient.EXPECT().GetGroupHooks(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(test.webhookInfo, nil)
|
||||
mockedClient.EXPECT().ResolveNamespaceAndProject(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), true).Return("group", "", nil)
|
||||
p.GitlabClient = mockedClient
|
||||
}
|
||||
|
||||
got := p.webhookCommand(context.Background(), test.parameters, &gitlab.UserInfo{}, true)
|
||||
assert.Equal(t, test.want, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func getTestPlugin(t *testing.T, mockCtrl *gomock.Controller, hooks []*gitlab.WebhookInfo, mattermostURL string, projectHookErr error, getProjectErr error, mockGitlab, noAccess bool) *Plugin {
|
||||
p := new(Plugin)
|
||||
|
||||
accessLevel := gitLabAPI.OwnerPermissions
|
||||
if noAccess {
|
||||
accessLevel = gitLabAPI.GuestPermissions
|
||||
}
|
||||
|
||||
mockedClient := mocks.NewMockGitlab(mockCtrl)
|
||||
if mockGitlab {
|
||||
mockedClient.EXPECT().ResolveNamespaceAndProject(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return("group", "project", nil)
|
||||
if getProjectErr != nil {
|
||||
mockedClient.EXPECT().GetProject(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, getProjectErr)
|
||||
} else {
|
||||
mockedClient.EXPECT().GetProject(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(&gitLabAPI.Project{
|
||||
Permissions: &gitLabAPI.Permissions{
|
||||
ProjectAccess: &gitLabAPI.ProjectAccess{
|
||||
AccessLevel: accessLevel,
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
}
|
||||
|
||||
if !noAccess {
|
||||
mockedClient.EXPECT().GetProjectHooks(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(hooks, projectHookErr)
|
||||
if projectHookErr == nil {
|
||||
mockedClient.EXPECT().GetGroupHooks(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(hooks, projectHookErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
p.GitlabClient = mockedClient
|
||||
|
||||
conf := &model.Config{}
|
||||
conf.ServiceSettings.SiteURL = &mattermostURL
|
||||
|
||||
encryptedToken, _ := encrypt([]byte(testEncryptionKey), testGitlabToken)
|
||||
|
||||
p.configuration = &configuration{
|
||||
EncryptionKey: testEncryptionKey,
|
||||
}
|
||||
|
||||
info := gitlab.UserInfo{
|
||||
UserID: "user_id",
|
||||
GitlabUsername: "gitlab_username",
|
||||
}
|
||||
|
||||
jsonInfo, err := json.Marshal(info)
|
||||
require.NoError(t, err)
|
||||
|
||||
var subVal []byte
|
||||
|
||||
api := &plugintest.API{}
|
||||
api.On("GetConfig", mock.Anything).Return(conf)
|
||||
api.On("KVGet", "user_id_usertoken").Return([]byte(encryptedToken), nil)
|
||||
api.On("KVGet", "user_id_userinfo").Return(subVal, nil).Once()
|
||||
api.On("KVGet", "user_id_gitlabtoken").Return(jsonInfo, nil).Once()
|
||||
api.On("KVGet", "subscriptions").Return(subVal, nil)
|
||||
|
||||
api.On("KVSet", mock.Anything, mock.Anything).Return(nil)
|
||||
api.On("KVSetWithOptions", mock.AnythingOfType("string"), mock.Anything, mock.AnythingOfType("model.PluginKVSetOptions")).Return(true, nil)
|
||||
api.On("PublishWebSocketEvent", mock.Anything, mock.Anything, mock.Anything).Return(nil)
|
||||
api.On("LogWarn",
|
||||
mock.AnythingOfTypeArgument("string"),
|
||||
mock.AnythingOfTypeArgument("string"),
|
||||
mock.AnythingOfTypeArgument("string"),
|
||||
mock.AnythingOfTypeArgument("string"),
|
||||
mock.AnythingOfTypeArgument("string"))
|
||||
|
||||
p.SetAPI(api)
|
||||
p.client = pluginapi.NewClient(api, p.Driver)
|
||||
|
||||
return p
|
||||
}
|
||||
|
||||
var exampleWebhookWithAlltriggers = &gitlab.WebhookInfo{
|
||||
URL: "https://example.com",
|
||||
PushEvents: true,
|
||||
TagPushEvents: true,
|
||||
NoteEvents: true,
|
||||
ConfidentialNoteEvents: true,
|
||||
IssuesEvents: true,
|
||||
ConfidentialIssuesEvents: true,
|
||||
MergeRequestsEvents: true,
|
||||
JobEvents: true,
|
||||
PipelineEvents: true,
|
||||
WikiPageEvents: true,
|
||||
EnableSSLVerification: true,
|
||||
}
|
||||
|
||||
const allTriggersFormated = `
|
||||
SSL Verification Enabled
|
||||
Triggers:
|
||||
* Push Events
|
||||
* Tag Push Events
|
||||
* Comments
|
||||
* Confidential Comments
|
||||
* Issues Events
|
||||
* Confidential Issues Events
|
||||
* Merge Request Events
|
||||
* Job Events
|
||||
* Pipeline Events
|
||||
* Wiki Page Events
|
||||
`
|
||||
|
||||
var addWebhookCommandTests = []webhookCommandTest{
|
||||
{
|
||||
testName: "Create project hook with defaults",
|
||||
parameters: []string{"add", "group/project"},
|
||||
want: "Webhook Created:\n\n\n`https://example.com`" + allTriggersFormated,
|
||||
siteURL: "https://example.com",
|
||||
webhook: exampleWebhookWithAlltriggers,
|
||||
},
|
||||
{
|
||||
testName: "Create project hook with all trigers",
|
||||
parameters: []string{"add", "group/project", "*"},
|
||||
want: "Webhook Created:\n\n\n`https://example.com`" + allTriggersFormated,
|
||||
siteURL: "https://example.com",
|
||||
webhook: exampleWebhookWithAlltriggers,
|
||||
},
|
||||
{
|
||||
testName: "Create project hook with explicit trigers",
|
||||
parameters: []string{"add", "group/project", "PushEvents,MergeRequestEvents"},
|
||||
want: "Webhook Created:\n\n\n`https://example.com`" + `
|
||||
Triggers:
|
||||
* Push Events
|
||||
* Merge Request Events
|
||||
`,
|
||||
siteURL: "https://example.com",
|
||||
webhook: &gitlab.WebhookInfo{
|
||||
URL: "https://example.com",
|
||||
PushEvents: true,
|
||||
MergeRequestsEvents: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
testName: "Create project hook with explicit URL",
|
||||
parameters: []string{"add", "group/project", "*", "https://anothersite.com"},
|
||||
want: "Webhook Created:\n\n\n`https://anothersite.com`" + allTriggersFormated,
|
||||
siteURL: "https://example.com",
|
||||
webhook: &gitlab.WebhookInfo{
|
||||
URL: "https://anothersite.com",
|
||||
EnableSSLVerification: true,
|
||||
PushEvents: true,
|
||||
TagPushEvents: true,
|
||||
NoteEvents: true,
|
||||
ConfidentialNoteEvents: true,
|
||||
IssuesEvents: true,
|
||||
ConfidentialIssuesEvents: true,
|
||||
MergeRequestsEvents: true,
|
||||
JobEvents: true,
|
||||
PipelineEvents: true,
|
||||
WikiPageEvents: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
testName: "Create project hook with explicit token",
|
||||
parameters: []string{"add", "group/project", "*", "https://example.com", "1234abcd"},
|
||||
want: "Webhook Created:\n\n\n`https://example.com`" + allTriggersFormated,
|
||||
siteURL: "https://example.com",
|
||||
webhook: exampleWebhookWithAlltriggers,
|
||||
},
|
||||
{
|
||||
testName: "Create Group hook with defaults",
|
||||
parameters: []string{"add", "group"},
|
||||
want: "Webhook Created:\n\n\n`https://example.com`" + allTriggersFormated,
|
||||
siteURL: "https://example.com",
|
||||
scope: "group",
|
||||
webhook: exampleWebhookWithAlltriggers,
|
||||
},
|
||||
}
|
||||
|
||||
func TestAddWebhookCommand(t *testing.T) {
|
||||
for _, test := range addWebhookCommandTests {
|
||||
t.Run(test.testName, func(t *testing.T) {
|
||||
p := new(Plugin)
|
||||
|
||||
mockCtrl := gomock.NewController(t)
|
||||
mockedClient := mocks.NewMockGitlab(mockCtrl)
|
||||
|
||||
if test.scope == "group" {
|
||||
mockedClient.EXPECT().NewGroupHook(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(test.webhook, nil)
|
||||
mockedClient.EXPECT().ResolveNamespaceAndProject(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), true).Return("group", "", nil)
|
||||
} else {
|
||||
project := &gitLabAPI.Project{ID: 4}
|
||||
mockedClient.EXPECT().ResolveNamespaceAndProject(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), true).Return("group", "project", nil)
|
||||
mockedClient.EXPECT().GetProject(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(project, nil)
|
||||
mockedClient.EXPECT().NewProjectHook(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(test.webhook, nil)
|
||||
}
|
||||
p.GitlabClient = mockedClient
|
||||
|
||||
conf := &model.Config{}
|
||||
conf.ServiceSettings.SiteURL = model.NewString(test.siteURL)
|
||||
|
||||
encryptedToken, _ := encrypt([]byte(testEncryptionKey), testGitlabToken)
|
||||
|
||||
p.configuration = &configuration{
|
||||
EncryptionKey: testEncryptionKey,
|
||||
}
|
||||
|
||||
api := &plugintest.API{}
|
||||
api.On("GetConfig", mock.Anything).Return(conf)
|
||||
api.On("KVGet", "_usertoken").Return([]byte(encryptedToken), nil)
|
||||
p.SetAPI(api)
|
||||
p.client = pluginapi.NewClient(api, p.Driver)
|
||||
|
||||
got := p.webhookCommand(context.Background(), test.parameters, &gitlab.UserInfo{}, true)
|
||||
|
||||
assert.Equal(t, test.want, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
"github.com/mattermost/mattermost/server/public/model"
|
||||
"github.com/mattermost/mattermost/server/public/pluginapi"
|
||||
"github.com/mattermost/mattermost/server/public/pluginapi/experimental/telemetry"
|
||||
"github.com/pkg/errors"
|
||||
|
||||
"github.com/mattermost/mattermost-plugin-gitlab/server/gitlab"
|
||||
)
|
||||
|
||||
// configuration captures the plugin's external configuration as exposed in the Mattermost server
|
||||
// configuration, as well as values computed from the configuration. Any public fields will be
|
||||
// deserialized from the Mattermost server configuration in OnConfigurationChange.
|
||||
//
|
||||
// As plugins are inherently concurrent (hooks being called asynchronously), and the plugin
|
||||
// configuration can change at any time, access to the configuration must be synchronized. The
|
||||
// strategy used in this plugin is to guard a pointer to the configuration, and clone the entire
|
||||
// struct whenever it changes. You may replace this with whatever strategy you choose.
|
||||
//
|
||||
// If you add non-reference types to your configuration struct, be sure to rewrite Clone as a deep
|
||||
// copy appropriate for your types.
|
||||
type configuration struct {
|
||||
GitlabURL string `json:"gitlaburl"`
|
||||
GitlabOAuthClientID string `json:"gitlaboauthclientid"`
|
||||
GitlabOAuthClientSecret string `json:"gitlaboauthclientsecret"`
|
||||
WebhookSecret string `json:"webhooksecret"`
|
||||
EncryptionKey string `json:"encryptionkey"`
|
||||
GitlabGroup string `json:"gitlabgroup"`
|
||||
EnablePrivateRepo bool `json:"enableprivaterepo"`
|
||||
EnableCodePreview string `json:"enablecodepreview"`
|
||||
UsePreregisteredApplication bool `json:"usepreregisteredapplication"`
|
||||
EnableChildPipelineNotifications bool `json:"enablechildpipelinenotifications"`
|
||||
}
|
||||
|
||||
// Clone shallow copies the configuration. Your implementation may require a deep copy if
|
||||
// your configuration has reference types.
|
||||
func (c *configuration) Clone() *configuration {
|
||||
var clone = *c
|
||||
return &clone
|
||||
}
|
||||
|
||||
func (c *configuration) ToMap() (map[string]interface{}, error) {
|
||||
var out map[string]interface{}
|
||||
data, err := json.Marshal(c)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = json.Unmarshal(data, &out)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *configuration) setDefaults(isCloud bool) (bool, error) {
|
||||
changed := false
|
||||
|
||||
if c.EncryptionKey == "" {
|
||||
secret, err := generateSecret()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
c.EncryptionKey = secret
|
||||
changed = true
|
||||
}
|
||||
|
||||
if c.WebhookSecret == "" {
|
||||
secret, err := generateSecret()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
c.WebhookSecret = secret
|
||||
changed = true
|
||||
}
|
||||
|
||||
if isCloud && !c.UsePreregisteredApplication && !c.IsOAuthConfigured() {
|
||||
c.UsePreregisteredApplication = true
|
||||
changed = true
|
||||
}
|
||||
|
||||
return changed, nil
|
||||
}
|
||||
|
||||
func (c *configuration) sanitize() {
|
||||
// Ensure GitlabURL ends with a slash
|
||||
c.GitlabURL = strings.TrimRight(c.GitlabURL, "/")
|
||||
|
||||
// Trim spaces around org and OAuth credentials
|
||||
c.GitlabGroup = strings.TrimSpace(c.GitlabGroup)
|
||||
c.GitlabOAuthClientID = strings.TrimSpace(c.GitlabOAuthClientID)
|
||||
c.GitlabOAuthClientSecret = strings.TrimSpace(c.GitlabOAuthClientSecret)
|
||||
}
|
||||
|
||||
func (c *configuration) IsOAuthConfigured() bool {
|
||||
return (c.GitlabOAuthClientID != "" && c.GitlabOAuthClientSecret != "") ||
|
||||
c.UsePreregisteredApplication
|
||||
}
|
||||
|
||||
// IsSASS return if SASS gitlab at https://gitlab.com is used
|
||||
func (c *configuration) IsSASS() bool {
|
||||
return c.GitlabURL == "https://gitlab.com"
|
||||
}
|
||||
|
||||
// IsValid checks if all needed fields are set.
|
||||
func (c *configuration) IsValid() error {
|
||||
if err := isValidURL(c.GitlabURL); err != nil {
|
||||
return errors.New("must have a valid GitLab URL")
|
||||
}
|
||||
|
||||
if !c.UsePreregisteredApplication {
|
||||
if c.GitlabOAuthClientID == "" {
|
||||
return errors.New("must have a GitLab oauth client id")
|
||||
}
|
||||
if c.GitlabOAuthClientSecret == "" {
|
||||
return errors.New("must have a GitLab oauth client secret")
|
||||
}
|
||||
}
|
||||
|
||||
if c.UsePreregisteredApplication && !c.IsSASS() {
|
||||
return errors.New("pre-registered application can only be used with official public GitLab")
|
||||
}
|
||||
|
||||
if c.EncryptionKey == "" {
|
||||
return errors.New("must have an encryption key")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// getConfiguration retrieves the active configuration under lock, making it safe to use
|
||||
// concurrently. The active configuration may change underneath the client of this method, but
|
||||
// the struct returned by this API call is considered immutable.
|
||||
func (p *Plugin) getConfiguration() *configuration {
|
||||
p.configurationLock.RLock()
|
||||
defer p.configurationLock.RUnlock()
|
||||
|
||||
if p.configuration == nil {
|
||||
return &configuration{}
|
||||
}
|
||||
|
||||
return p.configuration
|
||||
}
|
||||
|
||||
// setConfiguration replaces the active configuration under lock.
|
||||
//
|
||||
// Do not call setConfiguration while holding the configurationLock, as sync.Mutex is not
|
||||
// reentrant. In particular, avoid using the plugin API entirely, as this may in turn trigger a
|
||||
// hook back into the plugin. If that hook attempts to acquire this lock, a deadlock may occur.
|
||||
//
|
||||
// This method panics if setConfiguration is called with the existing configuration. This almost
|
||||
// certainly means that the configuration was modified without being cloned and may result in
|
||||
// an unsafe access.
|
||||
func (p *Plugin) setConfiguration(configuration *configuration, serverConfiguration *model.Config) {
|
||||
p.configurationLock.Lock()
|
||||
defer p.configurationLock.Unlock()
|
||||
|
||||
if configuration != nil && p.configuration == configuration {
|
||||
// Ignore assignment if the configuration struct is empty. Go will optimize the
|
||||
// allocation for same to point at the same memory address, breaking the check
|
||||
// above.
|
||||
if reflect.ValueOf(*configuration).NumField() == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
panic("setConfiguration called with the existing configuration")
|
||||
}
|
||||
|
||||
p.configuration = configuration
|
||||
}
|
||||
|
||||
// OnConfigurationChange is invoked when configuration changes may have been made.
|
||||
func (p *Plugin) OnConfigurationChange() error {
|
||||
if p.client == nil {
|
||||
p.client = pluginapi.NewClient(p.API, p.Driver)
|
||||
}
|
||||
|
||||
var configuration = new(configuration)
|
||||
|
||||
// Load the public configuration fields from the Mattermost server configuration.
|
||||
if err := p.client.Configuration.LoadPluginConfiguration(configuration); err != nil {
|
||||
return errors.Wrap(err, "failed to load plugin configuration")
|
||||
}
|
||||
|
||||
configuration.sanitize()
|
||||
|
||||
serverConfiguration := p.client.Configuration.GetConfig()
|
||||
|
||||
p.setConfiguration(configuration, serverConfiguration)
|
||||
|
||||
command, err := p.getCommand(configuration)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to get command")
|
||||
}
|
||||
|
||||
err = p.client.SlashCommand.Register(command)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to register command")
|
||||
}
|
||||
|
||||
if p.tracker != nil {
|
||||
p.tracker.ReloadConfig(telemetry.NewTrackerConfig(p.API.GetConfig()))
|
||||
}
|
||||
|
||||
p.GitlabClient = gitlab.New(configuration.GitlabURL, configuration.GitlabGroup, p.isNamespaceAllowed)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func generateSecret() (string, error) {
|
||||
b := make([]byte, 256)
|
||||
_, err := rand.Read(b)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
s := base64.RawStdEncoding.EncodeToString(b)
|
||||
|
||||
s = s[:32]
|
||||
|
||||
return s, nil
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestIsValid(t *testing.T) {
|
||||
for _, testCase := range []struct {
|
||||
description string
|
||||
config *configuration
|
||||
errMsg string
|
||||
}{
|
||||
{
|
||||
description: "valid configuration: pre-registered app",
|
||||
config: &configuration{
|
||||
GitlabURL: "https://gitlab.com",
|
||||
EncryptionKey: "abcd",
|
||||
UsePreregisteredApplication: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "valid configuration: custom OAuth app",
|
||||
config: &configuration{
|
||||
GitlabURL: "https://gitlab.com",
|
||||
GitlabOAuthClientID: "client-id",
|
||||
GitlabOAuthClientSecret: "client-secret",
|
||||
EncryptionKey: "abcd",
|
||||
UsePreregisteredApplication: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "invalid configuration: custom OAuth app without credentials",
|
||||
config: &configuration{
|
||||
GitlabURL: "https://gitlab.com",
|
||||
EncryptionKey: "abcd",
|
||||
UsePreregisteredApplication: false,
|
||||
},
|
||||
errMsg: "must have a GitLab oauth client id",
|
||||
},
|
||||
{
|
||||
description: "invalid configuration: custom GitLab URL with pre-registered app",
|
||||
config: &configuration{
|
||||
GitlabURL: "https://my-company.gitlab.com",
|
||||
UsePreregisteredApplication: true,
|
||||
EncryptionKey: "abcd",
|
||||
},
|
||||
errMsg: "pre-registered application can only be used with official public GitLab",
|
||||
},
|
||||
} {
|
||||
t.Run(testCase.description, func(t *testing.T) {
|
||||
err := testCase.config.IsValid()
|
||||
if testCase.errMsg != "" {
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), testCase.errMsg)
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetDefaults(t *testing.T) {
|
||||
for _, testCase := range []struct {
|
||||
description string
|
||||
isCloud bool
|
||||
config *configuration
|
||||
|
||||
shouldChange bool
|
||||
outputCheck func(*testing.T, *configuration)
|
||||
errMsg string
|
||||
}{
|
||||
{
|
||||
description: "noop",
|
||||
config: &configuration{
|
||||
EncryptionKey: "abcd",
|
||||
WebhookSecret: "efgh",
|
||||
},
|
||||
shouldChange: false,
|
||||
outputCheck: func(t *testing.T, c *configuration) {
|
||||
assert.Equal(t, "abcd", c.EncryptionKey)
|
||||
assert.Equal(t, "efgh", c.WebhookSecret)
|
||||
},
|
||||
}, {
|
||||
description: "set encryption key",
|
||||
config: &configuration{
|
||||
EncryptionKey: "",
|
||||
},
|
||||
shouldChange: true,
|
||||
outputCheck: func(t *testing.T, c *configuration) {
|
||||
assert.Len(t, c.EncryptionKey, 32)
|
||||
},
|
||||
}, {
|
||||
description: "set webhook key",
|
||||
config: &configuration{
|
||||
WebhookSecret: "",
|
||||
},
|
||||
shouldChange: true,
|
||||
outputCheck: func(t *testing.T, c *configuration) {
|
||||
assert.Len(t, c.WebhookSecret, 32)
|
||||
},
|
||||
}, {
|
||||
description: "set webhook and encryption key",
|
||||
config: &configuration{
|
||||
EncryptionKey: "",
|
||||
WebhookSecret: "",
|
||||
},
|
||||
shouldChange: true,
|
||||
outputCheck: func(t *testing.T, c *configuration) {
|
||||
assert.Len(t, c.EncryptionKey, 32)
|
||||
assert.Len(t, c.WebhookSecret, 32)
|
||||
},
|
||||
}, {
|
||||
description: "Should not set UsePreregisteredApplication in on-prem",
|
||||
isCloud: false,
|
||||
config: &configuration{
|
||||
EncryptionKey: "abcd",
|
||||
WebhookSecret: "efgh",
|
||||
UsePreregisteredApplication: false,
|
||||
},
|
||||
shouldChange: false,
|
||||
outputCheck: func(t *testing.T, c *configuration) {
|
||||
assert.Equal(t, "abcd", c.EncryptionKey)
|
||||
assert.Equal(t, "efgh", c.WebhookSecret)
|
||||
},
|
||||
}, {
|
||||
description: "Should set UsePreregisteredApplication in cloud if no OAuth secret is configured",
|
||||
isCloud: true,
|
||||
config: &configuration{
|
||||
EncryptionKey: "abcd",
|
||||
WebhookSecret: "efgh",
|
||||
UsePreregisteredApplication: false,
|
||||
},
|
||||
shouldChange: true,
|
||||
outputCheck: func(t *testing.T, c *configuration) {
|
||||
assert.Equal(t, "abcd", c.EncryptionKey)
|
||||
assert.Equal(t, "efgh", c.WebhookSecret)
|
||||
|
||||
assert.True(t, c.UsePreregisteredApplication)
|
||||
},
|
||||
}, {
|
||||
description: "Should set not UsePreregisteredApplication in cloud if OAuth secret is configured",
|
||||
isCloud: true,
|
||||
config: &configuration{
|
||||
EncryptionKey: "abcd",
|
||||
WebhookSecret: "efgh",
|
||||
UsePreregisteredApplication: false,
|
||||
GitlabOAuthClientID: "some id",
|
||||
GitlabOAuthClientSecret: "some secret",
|
||||
},
|
||||
shouldChange: false,
|
||||
outputCheck: func(t *testing.T, c *configuration) {
|
||||
assert.Equal(t, "abcd", c.EncryptionKey)
|
||||
assert.Equal(t, "efgh", c.WebhookSecret)
|
||||
|
||||
assert.False(t, c.UsePreregisteredApplication)
|
||||
},
|
||||
},
|
||||
} {
|
||||
t.Run(testCase.description, func(t *testing.T) {
|
||||
changed, err := testCase.config.setDefaults(testCase.isCloud)
|
||||
|
||||
assert.Equal(t, testCase.shouldChange, changed)
|
||||
testCase.outputCheck(t, testCase.config)
|
||||
|
||||
if testCase.errMsg != "" {
|
||||
require.Error(t, err)
|
||||
assert.Equal(t, testCase.errMsg, err.Error())
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+849
@@ -0,0 +1,849 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/mattermost/mattermost/server/public/model"
|
||||
"github.com/mattermost/mattermost/server/public/pluginapi"
|
||||
"github.com/mattermost/mattermost/server/public/pluginapi/experimental/flow"
|
||||
"github.com/pkg/errors"
|
||||
"golang.org/x/oauth2"
|
||||
|
||||
"github.com/mattermost/mattermost-plugin-gitlab/server/gitlab"
|
||||
)
|
||||
|
||||
type Tracker interface {
|
||||
TrackEvent(event string, properties map[string]interface{})
|
||||
TrackUserEvent(event, userID string, properties map[string]interface{})
|
||||
}
|
||||
|
||||
type FlowManager struct {
|
||||
client *pluginapi.Client
|
||||
pluginURL string
|
||||
botUserID string
|
||||
router *mux.Router
|
||||
getConfiguration func() *configuration
|
||||
getGitlabUserInfoByMattermostID func(userID string) (*gitlab.UserInfo, *APIErrorResponse)
|
||||
getGitlabClient func() gitlab.Gitlab
|
||||
useGitlabClient func(info *gitlab.UserInfo, toRun func(info *gitlab.UserInfo, token *oauth2.Token) error) error
|
||||
createHook func(ctx context.Context, gitlabClient gitlab.Gitlab, info *gitlab.UserInfo, group, project string, hookOptions *gitlab.AddWebhookOptions) (*gitlab.WebhookInfo, error)
|
||||
|
||||
tracker Tracker
|
||||
|
||||
setupFlow *flow.Flow
|
||||
oauthFlow *flow.Flow
|
||||
webhokFlow *flow.Flow
|
||||
announcementFlow *flow.Flow
|
||||
}
|
||||
|
||||
func (p *Plugin) NewFlowManager() *FlowManager {
|
||||
fm := &FlowManager{
|
||||
client: p.client,
|
||||
pluginURL: *p.client.Configuration.GetConfig().ServiceSettings.SiteURL + "/" + "plugins" + "/" + manifest.Id,
|
||||
botUserID: p.BotUserID,
|
||||
router: p.router,
|
||||
getConfiguration: p.getConfiguration,
|
||||
getGitlabUserInfoByMattermostID: p.getGitlabUserInfoByMattermostID,
|
||||
getGitlabClient: p.getGitlabClient,
|
||||
useGitlabClient: p.useGitlabClient,
|
||||
createHook: p.createHook,
|
||||
|
||||
tracker: p,
|
||||
}
|
||||
|
||||
fm.setupFlow = fm.newFlow("setup").WithSteps(
|
||||
fm.stepWelcome(),
|
||||
|
||||
fm.stepDelegateQuestion(),
|
||||
fm.stepDelegateConfirmation(),
|
||||
fm.stepDelegateComplete(),
|
||||
|
||||
fm.stepInstanceURL(),
|
||||
fm.stepOAuthInfo(),
|
||||
fm.stepOAuthInput(),
|
||||
fm.stepOAuthConnect(),
|
||||
|
||||
fm.stepWebhookQuestion(),
|
||||
fm.stepWebhookWarning(),
|
||||
fm.stepWebhookConfirmation(),
|
||||
|
||||
fm.stepAnnouncementQuestion(),
|
||||
fm.stepAnnouncementConfirmation(),
|
||||
|
||||
fm.doneStep(),
|
||||
|
||||
fm.stepCancel("setup"),
|
||||
)
|
||||
|
||||
fm.oauthFlow = fm.newFlow("oauth").WithSteps(
|
||||
fm.stepInstanceURL(),
|
||||
fm.stepOAuthInfo(),
|
||||
fm.stepOAuthInput(),
|
||||
fm.stepOAuthConnect().Terminal(),
|
||||
|
||||
fm.stepCancel("setup oauth"),
|
||||
)
|
||||
fm.webhokFlow = fm.newFlow("webhook").WithSteps(
|
||||
fm.stepWebhookQuestion(),
|
||||
flow.NewStep(stepWebhookConfirmation).
|
||||
WithText("Use `/gitlab subscriptions add` to subscribe any Mattermost channel to your GitLab repository. [Learn more](https://mattermost.gitbook.io/plugin-gitlab/feature-summary#subscribe-to-unsubscribe-from-a-repository)").
|
||||
Terminal(),
|
||||
|
||||
fm.stepCancel("setup webhook"),
|
||||
)
|
||||
fm.announcementFlow = fm.newFlow("announcement").WithSteps(
|
||||
fm.stepAnnouncementQuestion(),
|
||||
fm.stepAnnouncementConfirmation().Terminal(),
|
||||
|
||||
fm.stepCancel("setup announcement"),
|
||||
)
|
||||
|
||||
return fm
|
||||
}
|
||||
|
||||
func (fm *FlowManager) doneStep() flow.Step {
|
||||
return flow.NewStep(stepDone).
|
||||
WithText(":tada: You successfully installed GitLab.").
|
||||
OnRender(fm.onDone).Terminal()
|
||||
}
|
||||
|
||||
func (fm *FlowManager) onDone(f *flow.Flow) {
|
||||
fm.trackCompleteSetupWizard(f.UserID)
|
||||
|
||||
delegatedFrom := f.GetState().GetString(keyDelegatedFrom)
|
||||
if delegatedFrom != "" {
|
||||
err := fm.setupFlow.ForUser(delegatedFrom).Go(stepDelegateComplete)
|
||||
fm.client.Log.Warn("failed start configuration wizard for delegate", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (fm *FlowManager) newFlow(name flow.Name) *flow.Flow {
|
||||
flow := flow.NewFlow(
|
||||
name,
|
||||
fm.client,
|
||||
fm.pluginURL,
|
||||
fm.botUserID,
|
||||
)
|
||||
|
||||
flow.InitHTTP(fm.router)
|
||||
|
||||
return flow
|
||||
}
|
||||
|
||||
const (
|
||||
// Delegate Steps
|
||||
|
||||
stepDelegateQuestion flow.Name = "delegate-question"
|
||||
stepDelegateConfirmation flow.Name = "delegate-confirmation"
|
||||
stepDelegateComplete flow.Name = "delegate-complete"
|
||||
|
||||
// OAuth steps
|
||||
|
||||
stepGitlabURL flow.Name = "gitlab-url"
|
||||
stepOAuthInfo flow.Name = "oauth-info"
|
||||
stepOAuthInput flow.Name = "oauth-input"
|
||||
stepOAuthConnect flow.Name = "oauth-connect"
|
||||
|
||||
// Webhook steps
|
||||
|
||||
stepWebhookQuestion flow.Name = "webhook-question"
|
||||
stepWebhookWarning flow.Name = "webhook-warning"
|
||||
stepWebhookConfirmation flow.Name = "webhook-confirmation"
|
||||
|
||||
// Announcement steps
|
||||
|
||||
stepAnnouncementQuestion flow.Name = "announcement-question"
|
||||
stepAnnouncementConfirmation flow.Name = "announcement-confirmation"
|
||||
|
||||
// Miscellaneous Steps
|
||||
|
||||
stepWelcome flow.Name = "welcome"
|
||||
stepDone flow.Name = "done"
|
||||
stepCancel flow.Name = "cancel"
|
||||
|
||||
keyDelegatedFrom = "DelegatedFrom"
|
||||
keyDelegatedTo = "DelegatedTo"
|
||||
keyGitlabURL = "GitlabURL"
|
||||
keyUsePreregisteredApplication = "UsePreregisteredApplication"
|
||||
keyIsOAuthConfigured = "IsOAuthConfigured"
|
||||
)
|
||||
|
||||
func cancelButton() flow.Button {
|
||||
return flow.Button{
|
||||
Name: "Cancel setup",
|
||||
Color: flow.ColorDanger,
|
||||
OnClick: flow.Goto(stepCancel),
|
||||
}
|
||||
}
|
||||
|
||||
func (fm *FlowManager) stepCancel(command string) flow.Step {
|
||||
return flow.NewStep(stepCancel).
|
||||
Terminal().
|
||||
WithText(fmt.Sprintf("Gitlab integration setup has stopped. Restart setup later by running `/gitlab %s`. Learn more about the plugin [here](https://mattermost.gitbook.io/plugin-gitlab/).", command)).
|
||||
WithColor(flow.ColorDanger)
|
||||
}
|
||||
|
||||
func continueButtonF(f func(f *flow.Flow) (flow.Name, flow.State, error)) flow.Button {
|
||||
return flow.Button{
|
||||
Name: "Continue",
|
||||
Color: flow.ColorPrimary,
|
||||
OnClick: f,
|
||||
}
|
||||
}
|
||||
|
||||
func continueButton(next flow.Name) flow.Button {
|
||||
return continueButtonF(flow.Goto(next))
|
||||
}
|
||||
|
||||
func (fm *FlowManager) getBaseState() flow.State {
|
||||
config := fm.getConfiguration()
|
||||
isOAuthConfigured := config.GitlabOAuthClientID != "" || config.GitlabOAuthClientSecret != ""
|
||||
return flow.State{
|
||||
keyGitlabURL: config.GitlabURL,
|
||||
keyUsePreregisteredApplication: config.UsePreregisteredApplication,
|
||||
keyIsOAuthConfigured: isOAuthConfigured,
|
||||
}
|
||||
}
|
||||
|
||||
func (fm *FlowManager) StartSetupWizard(userID string, delegatedFrom string) error {
|
||||
state := fm.getBaseState()
|
||||
state[keyDelegatedFrom] = delegatedFrom
|
||||
|
||||
err := fm.setupFlow.ForUser(userID).Start(state)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fm.client.Log.Debug("Started setup wizard", "userID", userID, "delegatedFrom", delegatedFrom)
|
||||
|
||||
fm.trackStartSetupWizard(userID, delegatedFrom != "")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (fm *FlowManager) trackStartSetupWizard(userID string, fromInvite bool) {
|
||||
fm.tracker.TrackUserEvent("setup_wizard_start", userID, map[string]interface{}{
|
||||
"from_invite": fromInvite,
|
||||
"time": model.GetMillis(),
|
||||
})
|
||||
}
|
||||
|
||||
func (fm *FlowManager) trackCompleteSetupWizard(userID string) {
|
||||
fm.tracker.TrackUserEvent("setup_wizard_complete", userID, map[string]interface{}{
|
||||
"time": model.GetMillis(),
|
||||
})
|
||||
}
|
||||
|
||||
func (fm *FlowManager) StartOauthWizard(userID string) error {
|
||||
state := fm.getBaseState()
|
||||
|
||||
err := fm.oauthFlow.ForUser(userID).Start(state)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fm.trackStartOauthWizard(userID)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (fm *FlowManager) trackStartOauthWizard(userID string) {
|
||||
fm.tracker.TrackUserEvent("oauth_wizard_start", userID, map[string]interface{}{
|
||||
"time": model.GetMillis(),
|
||||
})
|
||||
}
|
||||
|
||||
func (fm *FlowManager) trackCompleteOauthWizard(userID string) {
|
||||
fm.tracker.TrackUserEvent("oauth_wizard_complete", userID, map[string]interface{}{
|
||||
"time": model.GetMillis(),
|
||||
})
|
||||
}
|
||||
|
||||
func (fm *FlowManager) stepWelcome() flow.Step {
|
||||
welcomePretext := ":wave: Welcome to your GitLab integration! [Learn more](https://mattermost.gitbook.io/plugin-gitlab/)"
|
||||
|
||||
welcomeText := `
|
||||
{{- if .UsePreregisteredApplication -}}
|
||||
Just a few configuration steps to go!
|
||||
- **Step 1:** Connect your GiLab account
|
||||
- **Step 2:** Create a webhook in GitLab
|
||||
{{- else -}}
|
||||
Just a few configuration steps to go!
|
||||
- **Step 1:** Register an OAuth application in GitLab and enter OAuth values.
|
||||
- **Step 2:** Connect your GitLab account
|
||||
- **Step 3:** Create a webhook in GitLab
|
||||
{{- end -}}`
|
||||
|
||||
return flow.NewStep(stepWelcome).
|
||||
WithText(welcomeText).
|
||||
WithPretext(welcomePretext).
|
||||
WithButton(continueButton(""))
|
||||
}
|
||||
|
||||
func (fm *FlowManager) stepDelegateQuestion() flow.Step {
|
||||
delegateQuestionText := "Are you setting this GitLab integration up, or is someone else?"
|
||||
return flow.NewStep(stepDelegateQuestion).
|
||||
WithText(delegateQuestionText).
|
||||
WithButton(flow.Button{
|
||||
Name: "I'll do it myself",
|
||||
Color: flow.ColorPrimary,
|
||||
OnClick: func(f *flow.Flow) (flow.Name, flow.State, error) {
|
||||
if f.GetState().GetBool(keyUsePreregisteredApplication) {
|
||||
return stepOAuthConnect, nil, nil
|
||||
}
|
||||
|
||||
return stepGitlabURL, nil, nil
|
||||
},
|
||||
}).
|
||||
WithButton(flow.Button{
|
||||
Name: "I need someone else",
|
||||
Color: flow.ColorDefault,
|
||||
Dialog: &model.Dialog{
|
||||
Title: "Send instructions",
|
||||
SubmitLabel: "Send",
|
||||
Elements: []model.DialogElement{
|
||||
{
|
||||
DisplayName: "To",
|
||||
Name: "delegate",
|
||||
Type: "select",
|
||||
DataSource: "users",
|
||||
Placeholder: "Search for people",
|
||||
},
|
||||
},
|
||||
},
|
||||
OnDialogSubmit: fm.submitDelegateSelection,
|
||||
})
|
||||
}
|
||||
|
||||
func (fm *FlowManager) submitDelegateSelection(f *flow.Flow, submitted map[string]interface{}) (flow.Name, flow.State, map[string]string, error) {
|
||||
delegateIDRaw, ok := submitted["delegate"]
|
||||
if !ok {
|
||||
return "", nil, nil, errors.New("delegate missing")
|
||||
}
|
||||
delegateID, ok := delegateIDRaw.(string)
|
||||
if !ok {
|
||||
return "", nil, nil, errors.New("delegate is not a string")
|
||||
}
|
||||
|
||||
delegate, err := fm.client.User.Get(delegateID)
|
||||
if err != nil {
|
||||
return "", nil, nil, errors.Wrap(err, "failed get user")
|
||||
}
|
||||
|
||||
err = fm.StartSetupWizard(delegate.Id, f.UserID)
|
||||
if err != nil {
|
||||
return "", nil, nil, errors.Wrap(err, "failed start configuration wizard")
|
||||
}
|
||||
|
||||
return stepDelegateConfirmation, flow.State{
|
||||
keyDelegatedTo: delegate.Username,
|
||||
}, nil, nil
|
||||
}
|
||||
|
||||
func (fm *FlowManager) stepDelegateConfirmation() flow.Step {
|
||||
return flow.NewStep(stepDelegateConfirmation).
|
||||
WithText("GitLab integration setup details have been sent to @{{ .DelegatedTo }}").
|
||||
WithButton(flow.Button{
|
||||
Name: "Waiting for @{{ .DelegatedTo }}...",
|
||||
Color: flow.ColorDefault,
|
||||
Disabled: true,
|
||||
}).
|
||||
WithButton(cancelButton())
|
||||
}
|
||||
|
||||
func (fm *FlowManager) stepDelegateComplete() flow.Step {
|
||||
return flow.NewStep(stepDelegateComplete).
|
||||
WithText("@{{ .DelegatedTo }} completed configuring the integration.").
|
||||
Next(stepDone)
|
||||
}
|
||||
|
||||
func (fm *FlowManager) stepInstanceURL() flow.Step {
|
||||
enterpriseText := "Are you using `gitlab.com`?"
|
||||
return flow.NewStep(stepGitlabURL).
|
||||
WithText(enterpriseText).
|
||||
WithButton(flow.Button{
|
||||
Name: "Yes",
|
||||
Color: flow.ColorDefault,
|
||||
OnClick: func(f *flow.Flow) (flow.Name, flow.State, error) {
|
||||
err := fm.setGitlabURL(gitlab.Gitlabdotcom)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
return stepOAuthInfo, nil, nil
|
||||
},
|
||||
}).
|
||||
WithButton(flow.Button{
|
||||
Name: "No",
|
||||
Color: flow.ColorPrimary,
|
||||
Dialog: &model.Dialog{
|
||||
Title: "GitLab URL",
|
||||
IntroductionText: "Enter the **GitLab URL** of your GitLab instance (Example: https://gitlab.example.com).",
|
||||
SubmitLabel: "Save & continue",
|
||||
Elements: []model.DialogElement{
|
||||
{
|
||||
|
||||
DisplayName: "GitLab URL",
|
||||
Name: "gitlab_url",
|
||||
Type: "text",
|
||||
SubType: "url",
|
||||
Placeholder: "Enter GitLab URL",
|
||||
},
|
||||
},
|
||||
},
|
||||
OnDialogSubmit: fm.submitGitlabURL,
|
||||
}).
|
||||
WithButton(cancelButton())
|
||||
}
|
||||
|
||||
func (fm *FlowManager) submitGitlabURL(f *flow.Flow, submitted map[string]interface{}) (flow.Name, flow.State, map[string]string, error) {
|
||||
errorList := map[string]string{}
|
||||
|
||||
gitlabURLRaw, ok := submitted["gitlab_url"]
|
||||
if !ok {
|
||||
return "", nil, nil, errors.New("gitlab_url missing")
|
||||
}
|
||||
gitlabURL, ok := gitlabURLRaw.(string)
|
||||
if !ok {
|
||||
return "", nil, nil, errors.New("gitlab_url is not a string")
|
||||
}
|
||||
|
||||
err := isValidURL(gitlabURL)
|
||||
if err != nil {
|
||||
errorList["gitlab_url"] = err.Error()
|
||||
}
|
||||
|
||||
if len(errorList) != 0 {
|
||||
return "", nil, errorList, nil
|
||||
}
|
||||
|
||||
config := fm.getConfiguration()
|
||||
config.GitlabURL = gitlabURL
|
||||
config.sanitize()
|
||||
|
||||
configMap, err := config.ToMap()
|
||||
if err != nil {
|
||||
return "", nil, nil, err
|
||||
}
|
||||
|
||||
err = fm.client.Configuration.SavePluginConfig(configMap)
|
||||
if err != nil {
|
||||
return "", nil, nil, errors.Wrap(err, "failed to save plugin config")
|
||||
}
|
||||
|
||||
return "", flow.State{
|
||||
keyGitlabURL: config.GitlabURL,
|
||||
}, nil, nil
|
||||
}
|
||||
|
||||
func (fm *FlowManager) stepOAuthInfo() flow.Step {
|
||||
oauthPretext := `
|
||||
##### :white_check_mark: Step 1: Register an OAuth Application in GitLab
|
||||
You must first register the Mattermost GitLab Plugin as an authorized OAuth app.`
|
||||
oauthMessage := fmt.Sprintf(""+
|
||||
"1. In a browser, go to {{ .GitlabURL }}/-/profile/applications.\n"+
|
||||
"2. Set the following values:\n"+
|
||||
" - Name: `Mattermost GitLab Plugin - <your company name>`\n"+
|
||||
" - Redirect URI: `%s/oauth/complete`\n"+
|
||||
"3. Unselect **Expire access tokens**.\n"+
|
||||
"4. Select `api` and `read_user` in Scopes.\n"+
|
||||
"5. Select **Save application**\n",
|
||||
fm.pluginURL,
|
||||
)
|
||||
|
||||
return flow.NewStep(stepOAuthInfo).
|
||||
WithPretext(oauthPretext).
|
||||
WithText(oauthMessage).
|
||||
WithImage("public/new-oauth-application.png").
|
||||
WithButton(continueButton("")).
|
||||
WithButton(cancelButton())
|
||||
}
|
||||
|
||||
func (fm *FlowManager) stepOAuthInput() flow.Step {
|
||||
return flow.NewStep(stepOAuthInput).
|
||||
WithText("Click the Continue button below to open a dialog to enter the **Application ID** and **Secret**.").
|
||||
WithButton(flow.Button{
|
||||
Name: "Continue",
|
||||
Color: flow.ColorPrimary,
|
||||
Dialog: &model.Dialog{
|
||||
Title: "GitLab OAuth values",
|
||||
IntroductionText: "Please enter the **Application ID** and **Secret** you copied in a previous step.{{ if .IsOAuthConfigured }}\n\n**Any existing OAuth configuration will be overwritten.**{{end}}",
|
||||
SubmitLabel: "Save & continue",
|
||||
Elements: []model.DialogElement{
|
||||
{
|
||||
DisplayName: "GitLab OAuth Application ID",
|
||||
Name: "client_id",
|
||||
Type: "text",
|
||||
SubType: "text",
|
||||
Placeholder: "Enter GitLab OAuth Application ID",
|
||||
},
|
||||
{
|
||||
DisplayName: "GitLab OAuth Secret",
|
||||
Name: "client_secret",
|
||||
Type: "text",
|
||||
SubType: "text",
|
||||
Placeholder: "Enter GitLab OAuth Secret",
|
||||
},
|
||||
},
|
||||
},
|
||||
OnDialogSubmit: fm.submitOAuthConfig,
|
||||
}).
|
||||
WithButton(cancelButton())
|
||||
}
|
||||
|
||||
func (fm *FlowManager) submitOAuthConfig(f *flow.Flow, submitted map[string]interface{}) (flow.Name, flow.State, map[string]string, error) {
|
||||
errorList := map[string]string{}
|
||||
|
||||
clientIDRaw, ok := submitted["client_id"]
|
||||
if !ok {
|
||||
return "", nil, nil, errors.New("client_id missing")
|
||||
}
|
||||
clientID, ok := clientIDRaw.(string)
|
||||
if !ok {
|
||||
return "", nil, nil, errors.New("client_id is not a string")
|
||||
}
|
||||
|
||||
clientID = strings.TrimSpace(clientID)
|
||||
|
||||
if len(clientID) < 64 {
|
||||
errorList["client_id"] = "Client ID should be at least 64 characters long"
|
||||
}
|
||||
|
||||
clientSecretRaw, ok := submitted["client_secret"]
|
||||
if !ok {
|
||||
return "", nil, nil, errors.New("client_secret missing")
|
||||
}
|
||||
clientSecret, ok := clientSecretRaw.(string)
|
||||
if !ok {
|
||||
return "", nil, nil, errors.New("client_secret is not a string")
|
||||
}
|
||||
|
||||
clientSecret = strings.TrimSpace(clientSecret)
|
||||
|
||||
if len(clientSecret) < 64 {
|
||||
errorList["client_secret"] = "Client Secret should be at least 64 characters long"
|
||||
}
|
||||
|
||||
if len(errorList) != 0 {
|
||||
return "", nil, errorList, nil
|
||||
}
|
||||
|
||||
config := fm.getConfiguration()
|
||||
config.GitlabOAuthClientID = clientID
|
||||
config.GitlabOAuthClientSecret = clientSecret
|
||||
|
||||
configMap, err := config.ToMap()
|
||||
if err != nil {
|
||||
return "", nil, nil, err
|
||||
}
|
||||
|
||||
err = fm.client.Configuration.SavePluginConfig(configMap)
|
||||
if err != nil {
|
||||
return "", nil, nil, errors.Wrap(err, "failed to save plugin config")
|
||||
}
|
||||
|
||||
return "", nil, nil, nil
|
||||
}
|
||||
|
||||
func (fm *FlowManager) stepOAuthConnect() flow.Step {
|
||||
connectPretext := "##### :white_check_mark: Step {{ if .UsePreregisteredApplication }}1{{ else }}2{{ end }}: Connect your GitLab account"
|
||||
connectURL := fmt.Sprintf("%s/oauth/connect", fm.pluginURL)
|
||||
connectText := fmt.Sprintf("Go [here](%s) to connect your account.", connectURL)
|
||||
return flow.NewStep(stepOAuthConnect).
|
||||
WithText(connectText).
|
||||
WithPretext(connectPretext).
|
||||
OnRender(func(f *flow.Flow) { fm.trackCompleteOauthWizard(f.UserID) })
|
||||
// The API handler will advance to the next step and complete the flow
|
||||
}
|
||||
|
||||
func (fm *FlowManager) StartWebhookWizard(userID string) error {
|
||||
state := fm.getBaseState()
|
||||
|
||||
err := fm.webhokFlow.ForUser(userID).Start(state)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fm.trackStartWebhookWizard(userID)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (fm *FlowManager) trackStartWebhookWizard(userID string) {
|
||||
fm.tracker.TrackUserEvent("webhook_wizard_start", userID, map[string]interface{}{
|
||||
"time": model.GetMillis(),
|
||||
})
|
||||
}
|
||||
|
||||
func (fm *FlowManager) trackCompleteWebhookWizard(userID string) {
|
||||
fm.tracker.TrackUserEvent("webhook_wizard_complete", userID, map[string]interface{}{
|
||||
"time": model.GetMillis(),
|
||||
})
|
||||
}
|
||||
|
||||
func (fm *FlowManager) stepWebhookQuestion() flow.Step {
|
||||
questionPretext := `##### :white_check_mark: Step {{ if .UsePreregisteredApplication }}2{{ else }}3{{ end }}: Create a Webhook in GitLab
|
||||
The final setup step requires a Mattermost System Admin to create a webhook for each GitLab group or project to receive notifications for, or want to subscribe to.`
|
||||
return flow.NewStep(stepWebhookQuestion).
|
||||
WithText("Do you want to create a webhook?").
|
||||
WithPretext(questionPretext).
|
||||
WithButton(flow.Button{
|
||||
Name: "Yes",
|
||||
Color: flow.ColorPrimary,
|
||||
Dialog: &model.Dialog{
|
||||
Title: "Create webhook",
|
||||
SubmitLabel: "Create",
|
||||
Elements: []model.DialogElement{
|
||||
{
|
||||
|
||||
DisplayName: "Gitlab project or group name",
|
||||
Name: "namespace",
|
||||
Type: "text",
|
||||
SubType: "text",
|
||||
Placeholder: "Enter GitLab project or group name",
|
||||
HelpText: "Specify the GitLab project or group to connect to Mattermost. For example, mattermost/mattermost-server.",
|
||||
},
|
||||
},
|
||||
},
|
||||
OnDialogSubmit: fm.submitWebhook,
|
||||
}).
|
||||
WithButton(flow.Button{
|
||||
Name: "No",
|
||||
Color: flow.ColorDefault,
|
||||
OnClick: flow.Goto(stepWebhookWarning),
|
||||
})
|
||||
}
|
||||
|
||||
func (fm *FlowManager) submitWebhook(f *flow.Flow, submitted map[string]interface{}) (flow.Name, flow.State, map[string]string, error) {
|
||||
namespaceRaw, ok := submitted["namespace"]
|
||||
if !ok {
|
||||
return "", nil, nil, errors.New("namespace missing")
|
||||
}
|
||||
namespace, ok := namespaceRaw.(string)
|
||||
if !ok {
|
||||
return "", nil, nil, errors.New("namespace is not a string")
|
||||
}
|
||||
|
||||
config := fm.getConfiguration()
|
||||
|
||||
info, apiErr := fm.getGitlabUserInfoByMattermostID(f.UserID)
|
||||
if apiErr != nil {
|
||||
return "", nil, nil, apiErr
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 28*time.Second) // HTTP request times out after 30 seconds
|
||||
defer cancel()
|
||||
|
||||
gitlabClient := fm.getGitlabClient()
|
||||
|
||||
var group, project string
|
||||
err := fm.useGitlabClient(info, func(info *gitlab.UserInfo, token *oauth2.Token) error {
|
||||
respGroup, respProject, err := gitlabClient.ResolveNamespaceAndProject(ctx, info, token, namespace, config.EnablePrivateRepo)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
group = respGroup
|
||||
project = respProject
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, gitlab.ErrNotFound) {
|
||||
return "", nil, nil, errors.New("project or group was not found")
|
||||
}
|
||||
|
||||
return "", nil, nil, gitlab.PrettyError(err)
|
||||
}
|
||||
|
||||
hookOptions := &gitlab.AddWebhookOptions{
|
||||
URL: fmt.Sprintf("%s/webhook", fm.pluginURL),
|
||||
ConfidentialNoteEvents: true,
|
||||
PushEvents: true,
|
||||
IssuesEvents: true,
|
||||
ConfidentialIssuesEvents: true,
|
||||
MergeRequestsEvents: true,
|
||||
TagPushEvents: true,
|
||||
NoteEvents: true,
|
||||
JobEvents: true,
|
||||
PipelineEvents: true,
|
||||
WikiPageEvents: true,
|
||||
EnableSSLVerification: true,
|
||||
Token: config.WebhookSecret,
|
||||
}
|
||||
|
||||
var fullName string
|
||||
var repoOrGroup string
|
||||
|
||||
if group == "" {
|
||||
fullName = group
|
||||
repoOrGroup = "group"
|
||||
} else {
|
||||
fullName = group + "/" + project
|
||||
repoOrGroup = "repository"
|
||||
}
|
||||
|
||||
_, err = fm.createHook(ctx, gitlabClient, info, group, project, hookOptions)
|
||||
if err != nil {
|
||||
if errors.Is(err, gitlab.ErrNotFound) {
|
||||
return "", nil, nil, errors.New("project or group was not found")
|
||||
}
|
||||
if errors.Is(err, gitlab.ErrForbidden) {
|
||||
err = errors.Errorf("It seems like you don't have privileges to create webhooks in %s. Ask an admin of that %s to run /gitlab setup webhook for you.", fullName, repoOrGroup)
|
||||
return "", nil, nil, err
|
||||
}
|
||||
|
||||
return "", nil, nil, errors.Wrap(gitlab.PrettyError(err), "failed to create hook")
|
||||
}
|
||||
|
||||
return stepWebhookConfirmation, nil, nil, nil
|
||||
}
|
||||
|
||||
func (fm *FlowManager) stepWebhookWarning() flow.Step {
|
||||
warnText := "The GitLab plugin uses a webhook to connect a GitLab account to Mattermost to listen for incoming GitLab events. " +
|
||||
"You can't subscribe a channel to a repository for notifications until webhooks are configured.\n" +
|
||||
"Restart setup later by running `/gitab setup webhook`"
|
||||
|
||||
return flow.NewStep(stepWebhookWarning).
|
||||
WithText(warnText).
|
||||
WithColor(flow.ColorDanger).
|
||||
Next("")
|
||||
}
|
||||
|
||||
func (fm *FlowManager) stepWebhookConfirmation() flow.Step {
|
||||
return flow.NewStep(stepWebhookConfirmation).
|
||||
WithTitle("Success! :tada: You've successfully set up your Mattermost GitLab integration! ").
|
||||
WithText("Use `/gitlab subscriptions add` to subscribe any Mattermost channel to your GitLab repository. [Learn more](https://mattermost.gitbook.io/plugin-gitlab/feature-summary#subscribe-to-unsubscribe-from-a-repository)").
|
||||
OnRender(func(f *flow.Flow) { fm.trackCompleteWebhookWizard(f.UserID) }).
|
||||
Next("")
|
||||
}
|
||||
|
||||
func (fm *FlowManager) StartAnnouncementWizard(userID string) error {
|
||||
state := fm.getBaseState()
|
||||
|
||||
err := fm.announcementFlow.ForUser(userID).Start(state)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fm.trackStartAnnouncementWizard(userID)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (fm *FlowManager) trackStartAnnouncementWizard(userID string) {
|
||||
fm.tracker.TrackUserEvent("announcement_wizard_start", userID, map[string]interface{}{
|
||||
"time": model.GetMillis(),
|
||||
})
|
||||
}
|
||||
|
||||
func (fm *FlowManager) trackCompletAnnouncementWizard(userID string) {
|
||||
fm.tracker.TrackUserEvent("announcement_wizard_complete", userID, map[string]interface{}{
|
||||
"time": model.GetMillis(),
|
||||
})
|
||||
}
|
||||
|
||||
func (fm *FlowManager) stepAnnouncementQuestion() flow.Step {
|
||||
defaultMessage := "Hi team,\n" +
|
||||
"\n" +
|
||||
"We've set up the Mattermost Gitlab plugin to enable notifications from Gitlab in Mattermost. To get started, run the `/gitlab connect` slash command from any channel within Mattermost to connect that channel with GitLab. See the [documentation](https://mattermost.gitbook.io/plugin-gitlab/) for details on using the GitLab plugin."
|
||||
|
||||
return flow.NewStep(stepAnnouncementQuestion).
|
||||
WithText("Want to let your team know?").
|
||||
WithButton(flow.Button{
|
||||
Name: "Send Message",
|
||||
Color: flow.ColorPrimary,
|
||||
Dialog: &model.Dialog{
|
||||
Title: "Notify your team",
|
||||
SubmitLabel: "Send message",
|
||||
Elements: []model.DialogElement{
|
||||
{
|
||||
DisplayName: "To",
|
||||
Name: "channel_id",
|
||||
Type: "select",
|
||||
Placeholder: "Select channel",
|
||||
DataSource: "channels",
|
||||
},
|
||||
{
|
||||
DisplayName: "Message",
|
||||
Name: "message",
|
||||
Type: "textarea",
|
||||
Default: defaultMessage,
|
||||
HelpText: "You can edit this message before sending it.",
|
||||
},
|
||||
},
|
||||
},
|
||||
OnDialogSubmit: fm.submitChannelAnnouncement,
|
||||
}).
|
||||
WithButton(flow.Button{
|
||||
Name: "Not now",
|
||||
Color: flow.ColorDefault,
|
||||
OnClick: flow.Goto(stepDone),
|
||||
})
|
||||
}
|
||||
|
||||
func (fm *FlowManager) stepAnnouncementConfirmation() flow.Step {
|
||||
return flow.NewStep(stepAnnouncementConfirmation).
|
||||
WithText("Message to ~{{ .ChannelName }} was sent.").
|
||||
Next("").
|
||||
OnRender(func(f *flow.Flow) { fm.trackCompletAnnouncementWizard(f.UserID) })
|
||||
}
|
||||
|
||||
func (fm *FlowManager) submitChannelAnnouncement(f *flow.Flow, submitted map[string]interface{}) (flow.Name, flow.State, map[string]string, error) {
|
||||
channelIDRaw, ok := submitted["channel_id"]
|
||||
if !ok {
|
||||
return "", nil, nil, errors.New("channel_id missing")
|
||||
}
|
||||
channelID, ok := channelIDRaw.(string)
|
||||
if !ok {
|
||||
return "", nil, nil, errors.New("channel_id is not a string")
|
||||
}
|
||||
|
||||
channel, err := fm.client.Channel.Get(channelID)
|
||||
if err != nil {
|
||||
return "", nil, nil, errors.Wrap(err, "failed to get channel")
|
||||
}
|
||||
|
||||
messageRaw, ok := submitted["message"]
|
||||
if !ok {
|
||||
return "", nil, nil, errors.New("message is not a string")
|
||||
}
|
||||
message, ok := messageRaw.(string)
|
||||
if !ok {
|
||||
return "", nil, nil, errors.New("message is not a string")
|
||||
}
|
||||
|
||||
post := &model.Post{
|
||||
UserId: f.UserID,
|
||||
ChannelId: channel.Id,
|
||||
Message: message,
|
||||
}
|
||||
err = fm.client.Post.CreatePost(post)
|
||||
if err != nil {
|
||||
return "", nil, nil, errors.Wrap(err, "failed to create announcement post")
|
||||
}
|
||||
|
||||
return stepAnnouncementConfirmation, flow.State{
|
||||
"ChannelName": channel.Name,
|
||||
}, nil, nil
|
||||
}
|
||||
|
||||
func (fm *FlowManager) setGitlabURL(gitlabURL string) error {
|
||||
config := fm.getConfiguration()
|
||||
config.GitlabURL = gitlabURL
|
||||
|
||||
configMap, err := config.ToMap()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = fm.client.Configuration.SavePluginConfig(configMap)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to save plugin config")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,812 @@
|
||||
package gitlab
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/mattermost/mattermost/server/public/pluginapi/experimental/bot/logger"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
internGitlab "github.com/xanzy/go-gitlab"
|
||||
"golang.org/x/oauth2"
|
||||
"golang.org/x/sync/errgroup"
|
||||
)
|
||||
|
||||
const (
|
||||
stateOpened = "opened"
|
||||
scopeAll = "all"
|
||||
|
||||
perPage = 20
|
||||
)
|
||||
|
||||
type PRDetails struct {
|
||||
IID int `json:"iid"`
|
||||
Status *internGitlab.BuildStateValue `json:"status"`
|
||||
SHA string `json:"sha"`
|
||||
NumApprovers int `json:"num_approvers"`
|
||||
ProjectID int `json:"project_id"`
|
||||
}
|
||||
|
||||
type MergeRequest struct {
|
||||
*internGitlab.MergeRequest
|
||||
LabelsWithDetails []*internGitlab.Label `json:"labels_with_details,omitempty"`
|
||||
}
|
||||
|
||||
type Issue struct {
|
||||
*internGitlab.Issue
|
||||
LabelsWithDetails []*internGitlab.Label `json:"labels_with_details,omitempty"`
|
||||
}
|
||||
|
||||
type LHSContent struct {
|
||||
AssignedPRs []*MergeRequest `json:"yourAssignedPrs"`
|
||||
Reviews []*MergeRequest `json:"reviews"`
|
||||
AssignedIssues []*Issue `json:"yourAssignedIssues"`
|
||||
Todos []*internGitlab.Todo `json:"todos"`
|
||||
}
|
||||
|
||||
// NewGroupHook creates a webhook associated with a GitLab group
|
||||
func (g *gitlab) NewGroupHook(ctx context.Context, user *UserInfo, token *oauth2.Token, groupName string, webhookOptions *AddWebhookOptions) (*WebhookInfo, error) {
|
||||
client, err := g.GitlabConnect(*token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
group, resp, err := client.Groups.GetGroup(groupName, nil, internGitlab.WithContext(ctx))
|
||||
if respErr := checkResponse(resp); respErr != nil {
|
||||
return nil, respErr
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
groupHookOptions := internGitlab.AddGroupHookOptions{
|
||||
URL: &webhookOptions.URL,
|
||||
ConfidentialNoteEvents: &webhookOptions.ConfidentialNoteEvents,
|
||||
PushEvents: &webhookOptions.PushEvents,
|
||||
IssuesEvents: &webhookOptions.IssuesEvents,
|
||||
ConfidentialIssuesEvents: &webhookOptions.ConfidentialIssuesEvents,
|
||||
MergeRequestsEvents: &webhookOptions.MergeRequestsEvents,
|
||||
TagPushEvents: &webhookOptions.TagPushEvents,
|
||||
NoteEvents: &webhookOptions.NoteEvents,
|
||||
JobEvents: &webhookOptions.JobEvents,
|
||||
PipelineEvents: &webhookOptions.PipelineEvents,
|
||||
WikiPageEvents: &webhookOptions.WikiPageEvents,
|
||||
EnableSSLVerification: &webhookOptions.EnableSSLVerification,
|
||||
Token: &webhookOptions.Token,
|
||||
}
|
||||
|
||||
groupHook, resp, err := client.Groups.AddGroupHook(group.ID, &groupHookOptions, internGitlab.WithContext(ctx))
|
||||
if err != nil {
|
||||
if resp.StatusCode == http.StatusForbidden {
|
||||
return nil, ErrForbidden
|
||||
}
|
||||
|
||||
return nil, err
|
||||
}
|
||||
|
||||
groupHookInfo := getGroupHookInfo(groupHook)
|
||||
|
||||
return groupHookInfo, nil
|
||||
}
|
||||
|
||||
// NewProjectHook creates a webhook associated with a GitLab project
|
||||
func (g *gitlab) NewProjectHook(ctx context.Context, user *UserInfo, token *oauth2.Token, projectID interface{}, webhookOptions *AddWebhookOptions) (*WebhookInfo, error) {
|
||||
client, err := g.GitlabConnect(*token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
projectHookOptions := internGitlab.AddProjectHookOptions{
|
||||
URL: &webhookOptions.URL,
|
||||
ConfidentialNoteEvents: &webhookOptions.ConfidentialNoteEvents,
|
||||
PushEvents: &webhookOptions.PushEvents,
|
||||
IssuesEvents: &webhookOptions.IssuesEvents,
|
||||
ConfidentialIssuesEvents: &webhookOptions.ConfidentialIssuesEvents,
|
||||
MergeRequestsEvents: &webhookOptions.MergeRequestsEvents,
|
||||
TagPushEvents: &webhookOptions.TagPushEvents,
|
||||
NoteEvents: &webhookOptions.NoteEvents,
|
||||
JobEvents: &webhookOptions.JobEvents,
|
||||
PipelineEvents: &webhookOptions.PipelineEvents,
|
||||
WikiPageEvents: &webhookOptions.WikiPageEvents,
|
||||
EnableSSLVerification: &webhookOptions.EnableSSLVerification,
|
||||
Token: &webhookOptions.Token,
|
||||
}
|
||||
|
||||
projectHook, resp, err := client.Projects.AddProjectHook(projectID, &projectHookOptions, internGitlab.WithContext(ctx))
|
||||
if respErr := checkResponse(resp); respErr != nil {
|
||||
return nil, respErr
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
projectHookInfo := getProjectHookInfo(projectHook)
|
||||
|
||||
return projectHookInfo, nil
|
||||
}
|
||||
|
||||
// GetGroupHooks gathers all the group level hooks for a GitLab group.
|
||||
func (g *gitlab) GetGroupHooks(ctx context.Context, user *UserInfo, token *oauth2.Token, owner string) ([]*WebhookInfo, error) {
|
||||
client, err := g.GitlabConnect(*token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
hooks, resp, err := client.Groups.ListGroupHooks(owner, nil, internGitlab.WithContext(ctx))
|
||||
if respErr := checkResponse(resp); respErr != nil {
|
||||
return nil, respErr
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var webhooks []*WebhookInfo
|
||||
for _, hook := range hooks {
|
||||
webhooks = append(webhooks, getGroupHookInfo(hook))
|
||||
}
|
||||
|
||||
return webhooks, nil
|
||||
}
|
||||
|
||||
// String produces a multiline bulleted string for displaying webhook information.
|
||||
func (w *WebhookInfo) String() string {
|
||||
var formatedTriggers string
|
||||
if w.EnableSSLVerification {
|
||||
formatedTriggers += "SSL Verification Enabled\n"
|
||||
}
|
||||
|
||||
formatedTriggers += "Triggers:\n"
|
||||
if w.PushEvents {
|
||||
formatedTriggers += "* Push Events\n"
|
||||
}
|
||||
if w.TagPushEvents {
|
||||
formatedTriggers += "* Tag Push Events\n"
|
||||
}
|
||||
if w.NoteEvents {
|
||||
formatedTriggers += "* Comments\n"
|
||||
}
|
||||
if w.ConfidentialNoteEvents {
|
||||
formatedTriggers += "* Confidential Comments\n"
|
||||
}
|
||||
if w.IssuesEvents {
|
||||
formatedTriggers += "* Issues Events\n"
|
||||
}
|
||||
if w.ConfidentialIssuesEvents {
|
||||
formatedTriggers += "* Confidential Issues Events\n"
|
||||
}
|
||||
if w.MergeRequestsEvents {
|
||||
formatedTriggers += "* Merge Request Events\n"
|
||||
}
|
||||
if w.JobEvents {
|
||||
formatedTriggers += "* Job Events\n"
|
||||
}
|
||||
if w.PipelineEvents {
|
||||
formatedTriggers += "* Pipeline Events\n"
|
||||
}
|
||||
if w.WikiPageEvents {
|
||||
formatedTriggers += "* Wiki Page Events\n"
|
||||
}
|
||||
|
||||
return "\n\n`" + w.URL + "`\n" + formatedTriggers
|
||||
}
|
||||
|
||||
func getProjectHookInfo(hook *internGitlab.ProjectHook) *WebhookInfo {
|
||||
webhook := &WebhookInfo{
|
||||
Scope: Project,
|
||||
URL: hook.URL,
|
||||
ID: hook.ID,
|
||||
ConfidentialNoteEvents: hook.ConfidentialNoteEvents,
|
||||
PushEvents: hook.PushEvents,
|
||||
IssuesEvents: hook.IssuesEvents,
|
||||
ConfidentialIssuesEvents: hook.ConfidentialIssuesEvents,
|
||||
MergeRequestsEvents: hook.MergeRequestsEvents,
|
||||
TagPushEvents: hook.TagPushEvents,
|
||||
NoteEvents: hook.NoteEvents,
|
||||
JobEvents: hook.JobEvents,
|
||||
PipelineEvents: hook.PipelineEvents,
|
||||
WikiPageEvents: hook.WikiPageEvents,
|
||||
EnableSSLVerification: hook.EnableSSLVerification,
|
||||
CreatedAt: hook.CreatedAt,
|
||||
}
|
||||
return webhook
|
||||
}
|
||||
|
||||
func getGroupHookInfo(hook *internGitlab.GroupHook) *WebhookInfo {
|
||||
webhook := &WebhookInfo{
|
||||
Scope: Project,
|
||||
URL: hook.URL,
|
||||
ID: hook.ID,
|
||||
ConfidentialNoteEvents: hook.ConfidentialNoteEvents,
|
||||
PushEvents: hook.PushEvents,
|
||||
IssuesEvents: hook.IssuesEvents,
|
||||
ConfidentialIssuesEvents: hook.ConfidentialIssuesEvents,
|
||||
MergeRequestsEvents: hook.MergeRequestsEvents,
|
||||
TagPushEvents: hook.TagPushEvents,
|
||||
NoteEvents: hook.NoteEvents,
|
||||
JobEvents: hook.JobEvents,
|
||||
PipelineEvents: hook.PipelineEvents,
|
||||
WikiPageEvents: hook.WikiPageEvents,
|
||||
EnableSSLVerification: hook.EnableSSLVerification,
|
||||
CreatedAt: hook.CreatedAt,
|
||||
}
|
||||
return webhook
|
||||
}
|
||||
|
||||
// GetProjectHooks gathers all the project level hooks from a single GitLab project.
|
||||
func (g *gitlab) GetProjectHooks(ctx context.Context, user *UserInfo, token *oauth2.Token, owner string, repo string) ([]*WebhookInfo, error) {
|
||||
client, err := g.GitlabConnect(*token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
opt := &internGitlab.ListProjectHooksOptions{
|
||||
PerPage: perPage,
|
||||
Page: 1,
|
||||
}
|
||||
|
||||
var projectHooks []*internGitlab.ProjectHook
|
||||
var hooks []*internGitlab.ProjectHook
|
||||
var resp *internGitlab.Response
|
||||
projectPath := fmt.Sprintf("%s/%s", owner, repo)
|
||||
for {
|
||||
hooks, resp, err = client.Projects.ListProjectHooks(projectPath, opt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
projectHooks = append(projectHooks, hooks...)
|
||||
if resp.NextPage == 0 {
|
||||
break
|
||||
}
|
||||
opt.Page = resp.NextPage
|
||||
}
|
||||
var webhooks []*WebhookInfo
|
||||
for _, hook := range projectHooks {
|
||||
webhooks = append(webhooks, getProjectHookInfo(hook))
|
||||
}
|
||||
return webhooks, nil
|
||||
}
|
||||
|
||||
func (g *gitlab) GetProject(ctx context.Context, user *UserInfo, token *oauth2.Token, owner, repo string) (*internGitlab.Project, error) {
|
||||
client, err := g.GitlabConnect(*token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
project, resp, err := client.Projects.GetProject(fmt.Sprintf("%s/%s", owner, repo),
|
||||
&internGitlab.GetProjectOptions{},
|
||||
internGitlab.WithContext(ctx),
|
||||
)
|
||||
if respErr := checkResponse(resp); respErr != nil {
|
||||
return nil, respErr
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return project, nil
|
||||
}
|
||||
|
||||
func (g *gitlab) GetLHSData(ctx context.Context, user *UserInfo, token *oauth2.Token) (*LHSContent, error) {
|
||||
client, err := g.GitlabConnect(*token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
grp, ctx := errgroup.WithContext(ctx)
|
||||
|
||||
var reviews []*MergeRequest
|
||||
grp.Go(func() error {
|
||||
reviews, err = g.GetReviews(ctx, user, client)
|
||||
return err
|
||||
})
|
||||
|
||||
var issues []*Issue
|
||||
grp.Go(func() error {
|
||||
issues, err = g.GetYourAssignedIssues(ctx, user, client)
|
||||
return err
|
||||
})
|
||||
|
||||
var mergeRequests []*MergeRequest
|
||||
grp.Go(func() error {
|
||||
mergeRequests, err = g.GetYourAssignedPrs(ctx, user, client)
|
||||
return err
|
||||
})
|
||||
|
||||
var todos []*internGitlab.Todo
|
||||
grp.Go(func() error {
|
||||
todos, err = g.GetToDoList(ctx, user, client)
|
||||
return err
|
||||
})
|
||||
|
||||
if err := grp.Wait(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &LHSContent{
|
||||
Reviews: reviews,
|
||||
AssignedPRs: mergeRequests,
|
||||
AssignedIssues: issues,
|
||||
Todos: todos,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (g *gitlab) GetReviews(ctx context.Context, user *UserInfo, client *internGitlab.Client) ([]*MergeRequest, error) {
|
||||
opened := stateOpened
|
||||
scope := scopeAll
|
||||
|
||||
var mrs []*internGitlab.MergeRequest
|
||||
if g.gitlabGroup == "" {
|
||||
opt := &internGitlab.ListMergeRequestsOptions{
|
||||
ReviewerID: internGitlab.ReviewerID(user.GitlabUserID),
|
||||
State: &opened,
|
||||
Scope: &scope,
|
||||
ListOptions: internGitlab.ListOptions{Page: 1, PerPage: perPage},
|
||||
}
|
||||
for {
|
||||
current, resp, err := client.MergeRequests.ListMergeRequests(opt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mrs = append(mrs, current...)
|
||||
if resp.NextPage == 0 {
|
||||
break
|
||||
}
|
||||
opt.Page = resp.NextPage
|
||||
}
|
||||
} else {
|
||||
opt := &internGitlab.ListGroupMergeRequestsOptions{
|
||||
ReviewerID: internGitlab.ReviewerID(user.GitlabUserID),
|
||||
State: &opened,
|
||||
Scope: &scope,
|
||||
ListOptions: internGitlab.ListOptions{Page: 1, PerPage: perPage},
|
||||
}
|
||||
for {
|
||||
current, resp, err := client.MergeRequests.ListGroupMergeRequests(g.gitlabGroup, opt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mrs = append(mrs, current...)
|
||||
if resp.NextPage == 0 {
|
||||
break
|
||||
}
|
||||
opt.Page = resp.NextPage
|
||||
}
|
||||
}
|
||||
|
||||
mergeRequests := []*MergeRequest{}
|
||||
for _, mr := range mrs {
|
||||
if mr.Labels != nil {
|
||||
labelsWithDetails, err := g.GetLabelDetails(client, mr.ProjectID, mr.Labels)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mergeRequest := &MergeRequest{
|
||||
MergeRequest: mr,
|
||||
LabelsWithDetails: labelsWithDetails,
|
||||
}
|
||||
mergeRequests = append(mergeRequests, mergeRequest)
|
||||
}
|
||||
}
|
||||
|
||||
return mergeRequests, nil
|
||||
}
|
||||
|
||||
func (g *gitlab) GetYourAssignedPrs(ctx context.Context, user *UserInfo, client *internGitlab.Client) ([]*MergeRequest, error) {
|
||||
opened := stateOpened
|
||||
scope := scopeAll
|
||||
var mrs []*internGitlab.MergeRequest
|
||||
if g.gitlabGroup == "" {
|
||||
opt := &internGitlab.ListMergeRequestsOptions{
|
||||
AssigneeID: internGitlab.AssigneeID(user.GitlabUserID),
|
||||
State: &opened,
|
||||
Scope: &scope,
|
||||
ListOptions: internGitlab.ListOptions{Page: 1, PerPage: perPage},
|
||||
}
|
||||
for {
|
||||
current, resp, err := client.MergeRequests.ListMergeRequests(opt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mrs = append(mrs, current...)
|
||||
if resp.NextPage == 0 {
|
||||
break
|
||||
}
|
||||
opt.Page = resp.NextPage
|
||||
}
|
||||
} else {
|
||||
opt := &internGitlab.ListGroupMergeRequestsOptions{
|
||||
AssigneeID: internGitlab.AssigneeID(user.GitlabUserID),
|
||||
State: &opened,
|
||||
Scope: &scope,
|
||||
ListOptions: internGitlab.ListOptions{Page: 1, PerPage: perPage},
|
||||
}
|
||||
for {
|
||||
current, resp, err := client.MergeRequests.ListGroupMergeRequests(g.gitlabGroup, opt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mrs = append(mrs, current...)
|
||||
if resp.NextPage == 0 {
|
||||
break
|
||||
}
|
||||
opt.Page = resp.NextPage
|
||||
}
|
||||
}
|
||||
|
||||
mergeRequests := []*MergeRequest{}
|
||||
for _, mr := range mrs {
|
||||
if mr.Labels != nil {
|
||||
labelsWithDetails, err := g.GetLabelDetails(client, mr.ProjectID, mr.Labels)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mergeRequest := &MergeRequest{
|
||||
MergeRequest: mr,
|
||||
LabelsWithDetails: labelsWithDetails,
|
||||
}
|
||||
mergeRequests = append(mergeRequests, mergeRequest)
|
||||
}
|
||||
}
|
||||
return mergeRequests, nil
|
||||
}
|
||||
|
||||
func (g *gitlab) GetLabelDetails(client *internGitlab.Client, pid int, labels internGitlab.Labels) ([]*internGitlab.Label, error) {
|
||||
// Get list of all labels.
|
||||
labelList, resp, err := client.Labels.ListLabels(pid, nil)
|
||||
if respErr := checkResponse(resp); respErr != nil {
|
||||
return nil, respErr
|
||||
}
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "can't get list of labels in GitLab")
|
||||
}
|
||||
|
||||
allLabels := map[string]*internGitlab.Label{}
|
||||
for _, label := range labelList {
|
||||
allLabels[label.Name] = label
|
||||
}
|
||||
|
||||
labelsWithDetails := []*internGitlab.Label{}
|
||||
for _, label := range labels {
|
||||
if allLabels[label] == nil {
|
||||
return nil, errors.Wrap(err, "can't get label in GitLab api")
|
||||
}
|
||||
labelsWithDetails = append(labelsWithDetails, allLabels[label])
|
||||
}
|
||||
|
||||
return labelsWithDetails, nil
|
||||
}
|
||||
|
||||
func (g *gitlab) GetYourPrDetails(ctx context.Context, log logger.Logger, user *UserInfo, token *oauth2.Token, prList []*PRDetails) ([]*PRDetails, error) {
|
||||
client, err := g.GitlabConnect(*token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var result []*PRDetails
|
||||
var wg sync.WaitGroup
|
||||
for _, pr := range prList {
|
||||
wg.Add(1)
|
||||
go func(pid, iid int, sha string) {
|
||||
defer wg.Done()
|
||||
res := g.fetchYourPrDetails(ctx, log, client, pid, iid, sha)
|
||||
if res != nil {
|
||||
result = append(result, res)
|
||||
}
|
||||
}(pr.ProjectID, pr.IID, pr.SHA)
|
||||
}
|
||||
wg.Wait()
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (g *gitlab) fetchYourPrDetails(c context.Context, log logger.Logger, client *internGitlab.Client, pid, iid int, sha string) *PRDetails {
|
||||
var commitDetails *internGitlab.Commit
|
||||
var approvalDetails *internGitlab.MergeRequestApprovals
|
||||
var err error
|
||||
var resp *internGitlab.Response
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
commitDetails, resp, err = client.Commits.GetCommit(pid, sha, internGitlab.WithContext(c))
|
||||
if respErr := checkResponse(resp); respErr != nil {
|
||||
log.WithError(respErr).Warnf("Failed to fetch commit details for PR with project_id %d", pid)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
log.WithError(err).Warnf("Failed to fetch commit details for PR with project_id %d", pid)
|
||||
return
|
||||
}
|
||||
}()
|
||||
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
approvalDetails, resp, err = client.MergeRequestApprovals.GetConfiguration(pid, iid, internGitlab.WithContext(c))
|
||||
if respErr := checkResponse(resp); respErr != nil {
|
||||
log.WithError(respErr).Warnf("Failed to fetch approval details for PR with project_id %d", pid)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
log.WithError(err).Warnf("Failed to fetch approval details for PR with project_id %d", pid)
|
||||
return
|
||||
}
|
||||
}()
|
||||
|
||||
wg.Wait()
|
||||
if commitDetails != nil && approvalDetails != nil {
|
||||
return &PRDetails{
|
||||
ProjectID: pid,
|
||||
SHA: sha,
|
||||
Status: commitDetails.Status,
|
||||
NumApprovers: len(approvalDetails.ApprovedBy),
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g *gitlab) GetYourAssignedIssues(ctx context.Context, user *UserInfo, client *internGitlab.Client) ([]*Issue, error) {
|
||||
opened := stateOpened
|
||||
scope := scopeAll
|
||||
var issues []*internGitlab.Issue
|
||||
|
||||
if g.gitlabGroup == "" {
|
||||
opt := &internGitlab.ListIssuesOptions{
|
||||
AssigneeID: internGitlab.AssigneeID(user.GitlabUserID),
|
||||
State: &opened,
|
||||
Scope: &scope,
|
||||
ListOptions: internGitlab.ListOptions{Page: 1, PerPage: perPage},
|
||||
}
|
||||
for {
|
||||
current, resp, err := client.Issues.ListIssues(opt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
issues = append(issues, current...)
|
||||
if resp.NextPage == 0 {
|
||||
break
|
||||
}
|
||||
opt.Page = resp.NextPage
|
||||
}
|
||||
} else {
|
||||
opt := &internGitlab.ListGroupIssuesOptions{
|
||||
AssigneeID: internGitlab.AssigneeID(user.GitlabUserID),
|
||||
State: &opened,
|
||||
Scope: &scope,
|
||||
ListOptions: internGitlab.ListOptions{Page: 1, PerPage: perPage},
|
||||
}
|
||||
for {
|
||||
current, resp, err := client.Issues.ListGroupIssues(g.gitlabGroup, opt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
issues = append(issues, current...)
|
||||
if resp.NextPage == 0 {
|
||||
break
|
||||
}
|
||||
opt.Page = resp.NextPage
|
||||
}
|
||||
}
|
||||
|
||||
var result []*Issue
|
||||
for _, issue := range issues {
|
||||
if issue.Labels != nil {
|
||||
labelsWithDetails, err := g.GetLabelDetails(client, issue.ProjectID, issue.Labels)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
issue := &Issue{
|
||||
Issue: issue,
|
||||
LabelsWithDetails: labelsWithDetails,
|
||||
}
|
||||
result = append(result, issue)
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (g *gitlab) GetToDoList(ctx context.Context, user *UserInfo, client *internGitlab.Client) ([]*internGitlab.Todo, error) {
|
||||
var todos []*internGitlab.Todo
|
||||
|
||||
opt := &internGitlab.ListTodosOptions{
|
||||
ListOptions: internGitlab.ListOptions{Page: 1, PerPage: perPage},
|
||||
}
|
||||
for {
|
||||
current, resp, err := client.Todos.ListTodos(opt)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "can't list todo in GitLab api")
|
||||
}
|
||||
todos = append(todos, current...)
|
||||
if resp.NextPage == 0 {
|
||||
break
|
||||
}
|
||||
opt.Page = resp.NextPage
|
||||
}
|
||||
|
||||
notifications := make([]*internGitlab.Todo, 0, len(todos))
|
||||
for _, todo := range todos {
|
||||
if todo == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
if todo.Project != nil && g.checkGroup(strings.TrimSuffix(todo.Project.PathWithNamespace, "/"+todo.Project.Path)) != nil {
|
||||
continue
|
||||
}
|
||||
notifications = append(notifications, todo)
|
||||
}
|
||||
|
||||
return notifications, nil
|
||||
}
|
||||
|
||||
func (g *gitlab) ResolveNamespaceAndProject(
|
||||
ctx context.Context,
|
||||
userInfo *UserInfo,
|
||||
token *oauth2.Token,
|
||||
fullPath string,
|
||||
allowPrivate bool,
|
||||
) (owner string, repo string, err error) {
|
||||
// Initialize client
|
||||
client, err := g.GitlabConnect(*token)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
fullPath = strings.TrimPrefix(fullPath, g.gitlabURL)
|
||||
fullPath = strings.Trim(fullPath, "/")
|
||||
|
||||
// Search for matching user, group and project concurrently
|
||||
//
|
||||
// Note: Calls to Users and Groups could be replaced with a single call to Namespaces.
|
||||
// However, Namespaces endpoint will not return Group visibility, so we will have to make additional call anyway.
|
||||
// Making this extra call here should reduce overall latency.
|
||||
var (
|
||||
user *internGitlab.User
|
||||
group *internGitlab.Group
|
||||
project *internGitlab.Project
|
||||
)
|
||||
|
||||
errGroup, ctx := errgroup.WithContext(ctx)
|
||||
if strings.Count(fullPath, "/") == 0 { // This request only makes sense for single path component
|
||||
errGroup.Go(func() error {
|
||||
users, resp, err := client.Users.ListUsers(&internGitlab.ListUsersOptions{
|
||||
Username: &fullPath,
|
||||
},
|
||||
internGitlab.WithContext(ctx),
|
||||
)
|
||||
if respErr := checkResponse(resp); respErr != nil {
|
||||
return respErr
|
||||
}
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to search users by username")
|
||||
}
|
||||
if len(users) == 1 {
|
||||
user = users[0]
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
errGroup.Go(func() error {
|
||||
gr, resp, err := client.Groups.GetGroup(fullPath, nil, internGitlab.WithContext(ctx))
|
||||
if err != nil && resp != nil && resp.StatusCode != http.StatusNotFound {
|
||||
return errors.Wrap(err, "failed to retrieve group by path")
|
||||
}
|
||||
group = gr
|
||||
return nil
|
||||
})
|
||||
errGroup.Go(func() error {
|
||||
p, resp, err := client.Projects.GetProject(fullPath, nil, internGitlab.WithContext(ctx))
|
||||
if err != nil && resp != nil && resp.StatusCode != http.StatusNotFound {
|
||||
return errors.Wrap(err, "failed to retrieve project by path")
|
||||
}
|
||||
project = p
|
||||
return nil
|
||||
})
|
||||
if err := errGroup.Wait(); err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
// Decide what to return
|
||||
if user != nil {
|
||||
return user.Username, "", nil
|
||||
}
|
||||
|
||||
if group != nil {
|
||||
if !allowPrivate && group.Visibility != internGitlab.PublicVisibility {
|
||||
return "", "", errors.Wrap(ErrPrivateResource,
|
||||
"You can't add a private group on this Mattermost instance. Please enable private repositories in the System Console.",
|
||||
)
|
||||
}
|
||||
return group.FullPath, "", nil
|
||||
}
|
||||
|
||||
if project != nil {
|
||||
if !allowPrivate && project.Visibility != internGitlab.PublicVisibility {
|
||||
return "", "", errors.Wrap(ErrPrivateResource,
|
||||
"You can't add a private group on this Mattermost instance. Please enable private repositories in the System Console.",
|
||||
)
|
||||
}
|
||||
return project.Namespace.FullPath, project.Path, nil
|
||||
}
|
||||
return "", "", ErrNotFound
|
||||
}
|
||||
|
||||
func (g *gitlab) GetIssueByID(ctx context.Context, user *UserInfo, owner, repo string, issueID int, token *oauth2.Token) (*Issue, error) {
|
||||
client, err := g.GitlabConnect(*token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
projectPath := fmt.Sprintf("%s/%s", owner, repo)
|
||||
issue, resp, err := client.Issues.GetIssue(projectPath, issueID)
|
||||
if respErr := checkResponse(resp); respErr != nil {
|
||||
return nil, respErr
|
||||
}
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "can't get issue in GitLab api")
|
||||
}
|
||||
|
||||
gitlabIssue := &Issue{
|
||||
Issue: issue,
|
||||
}
|
||||
if issue.Labels != nil {
|
||||
labelsWithDetails, err := g.GetLabelDetails(client, issue.ProjectID, issue.Labels)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
gitlabIssue.LabelsWithDetails = labelsWithDetails
|
||||
}
|
||||
|
||||
return gitlabIssue, nil
|
||||
}
|
||||
|
||||
func (g *gitlab) GetMergeRequestByID(ctx context.Context, user *UserInfo, owner, repo string, mergeRequestID int, token *oauth2.Token) (*MergeRequest, error) {
|
||||
client, err := g.GitlabConnect(*token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
projectPath := fmt.Sprintf("%s/%s", owner, repo)
|
||||
mergeRequest, resp, err := client.MergeRequests.GetMergeRequest(projectPath, mergeRequestID, nil)
|
||||
if respErr := checkResponse(resp); respErr != nil {
|
||||
return nil, respErr
|
||||
}
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "can't get merge request in GitLab api")
|
||||
}
|
||||
|
||||
gitlabMergeRequest := &MergeRequest{
|
||||
MergeRequest: mergeRequest,
|
||||
}
|
||||
if mergeRequest.Labels != nil {
|
||||
labelsWithDetails, err := g.GetLabelDetails(client, mergeRequest.ProjectID, mergeRequest.Labels)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
gitlabMergeRequest.LabelsWithDetails = labelsWithDetails
|
||||
}
|
||||
|
||||
return gitlabMergeRequest, nil
|
||||
}
|
||||
|
||||
// TriggerProjectPipeline runs a pipeline in a specific project
|
||||
func (g *gitlab) TriggerProjectPipeline(userInfo *UserInfo, token *oauth2.Token, projectID string, ref string) (*PipelineInfo, error) {
|
||||
client, err := g.GitlabConnect(*token)
|
||||
if err != nil {
|
||||
return &PipelineInfo{}, err
|
||||
}
|
||||
pipeline, _, err := client.Pipelines.CreatePipeline(projectID, &internGitlab.CreatePipelineOptions{
|
||||
Ref: &ref,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "failed to run the pipeline")
|
||||
}
|
||||
|
||||
return &PipelineInfo{
|
||||
PipelineID: pipeline.ID,
|
||||
Status: pipeline.Status,
|
||||
Ref: pipeline.Ref,
|
||||
WebURL: pipeline.WebURL,
|
||||
SHA: pipeline.SHA,
|
||||
User: pipeline.User.Name,
|
||||
}, err
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package gitlab
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/mattermost/mattermost/server/public/pluginapi/experimental/bot/logger"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
internGitlab "github.com/xanzy/go-gitlab"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
const Gitlabdotcom = "https://gitlab.com"
|
||||
|
||||
// Errors returned by this package.
|
||||
var (
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrForbidden = errors.New("access forbidden")
|
||||
ErrPrivateResource = errors.New("private resource")
|
||||
)
|
||||
|
||||
// Gitlab is a client to call GitLab api see New() to build one
|
||||
type Gitlab interface {
|
||||
GitlabConnect(token oauth2.Token) (*internGitlab.Client, error)
|
||||
GetCurrentUser(ctx context.Context, userID string, token oauth2.Token) (*UserInfo, error)
|
||||
GetIssueByID(ctx context.Context, user *UserInfo, owner, repo string, issueID int, token *oauth2.Token) (*Issue, error)
|
||||
GetMergeRequestByID(ctx context.Context, user *UserInfo, owner, repo string, mergeRequestID int, token *oauth2.Token) (*MergeRequest, error)
|
||||
GetUserDetails(ctx context.Context, user *UserInfo, token *oauth2.Token) (*internGitlab.User, error)
|
||||
GetProject(ctx context.Context, user *UserInfo, token *oauth2.Token, owner, repo string) (*internGitlab.Project, error)
|
||||
GetYourPrDetails(ctx context.Context, log logger.Logger, user *UserInfo, token *oauth2.Token, prList []*PRDetails) ([]*PRDetails, error)
|
||||
GetReviews(ctx context.Context, user *UserInfo, client *internGitlab.Client) ([]*MergeRequest, error)
|
||||
GetYourAssignedPrs(ctx context.Context, user *UserInfo, client *internGitlab.Client) ([]*MergeRequest, error)
|
||||
GetLHSData(ctx context.Context, user *UserInfo, token *oauth2.Token) (*LHSContent, error)
|
||||
GetYourAssignedIssues(ctx context.Context, user *UserInfo, client *internGitlab.Client) ([]*Issue, error)
|
||||
GetToDoList(ctx context.Context, user *UserInfo, client *internGitlab.Client) ([]*internGitlab.Todo, error)
|
||||
GetProjectHooks(ctx context.Context, user *UserInfo, token *oauth2.Token, owner string, repo string) ([]*WebhookInfo, error)
|
||||
GetGroupHooks(ctx context.Context, user *UserInfo, token *oauth2.Token, owner string) ([]*WebhookInfo, error)
|
||||
NewProjectHook(ctx context.Context, user *UserInfo, token *oauth2.Token, projectID interface{}, projectHookOptions *AddWebhookOptions) (*WebhookInfo, error)
|
||||
NewGroupHook(ctx context.Context, user *UserInfo, token *oauth2.Token, groupName string, groupHookOptions *AddWebhookOptions) (*WebhookInfo, error)
|
||||
TriggerProjectPipeline(userInfo *UserInfo, token *oauth2.Token, projectID string, ref string) (*PipelineInfo, error)
|
||||
// ResolveNamespaceAndProject accepts full path to User, Group or namespaced Project and returns corresponding
|
||||
// namespace and project name.
|
||||
//
|
||||
// ErrNotFound will be returned if no resource can be found.
|
||||
// If allowPrivate is set to false, and resolved group/project is private, ErrPrivateResource will be returned.
|
||||
ResolveNamespaceAndProject(
|
||||
ctx context.Context,
|
||||
userInfo *UserInfo,
|
||||
token *oauth2.Token,
|
||||
fullPath string,
|
||||
allowPrivate bool,
|
||||
) (namespace string, project string, err error)
|
||||
}
|
||||
|
||||
type gitlab struct {
|
||||
gitlabURL string
|
||||
gitlabGroup string
|
||||
checkGroup func(projectNameWithGroup string) error
|
||||
}
|
||||
|
||||
// Scope identifies the scope of a webhook
|
||||
type Scope int
|
||||
|
||||
const (
|
||||
// Group is a type for group hooks
|
||||
Group Scope = iota
|
||||
// Project is a type for project hooks
|
||||
Project
|
||||
)
|
||||
|
||||
func (s Scope) String() string {
|
||||
return [...]string{"group", "project"}[s]
|
||||
}
|
||||
|
||||
// New return a client to call GitLab API
|
||||
func New(gitlabURL string, gitlabGroup string, checkGroup func(projectNameWithGroup string) error) Gitlab {
|
||||
if gitlabURL == "" {
|
||||
gitlabURL = Gitlabdotcom
|
||||
}
|
||||
return &gitlab{gitlabURL: gitlabURL, gitlabGroup: gitlabGroup, checkGroup: checkGroup}
|
||||
}
|
||||
|
||||
func (g *gitlab) GitlabConnect(token oauth2.Token) (*internGitlab.Client, error) {
|
||||
if g.gitlabURL == "" || strings.EqualFold(g.gitlabURL, Gitlabdotcom) {
|
||||
return internGitlab.NewOAuthClient(token.AccessToken)
|
||||
}
|
||||
|
||||
return internGitlab.NewOAuthClient(token.AccessToken, internGitlab.WithBaseURL(g.gitlabURL))
|
||||
}
|
||||
|
||||
// checkResponse returns known errors based on the http status code.
|
||||
func checkResponse(resp *internGitlab.Response) error {
|
||||
if resp == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
switch resp.StatusCode {
|
||||
case http.StatusForbidden:
|
||||
return ErrForbidden
|
||||
case http.StatusNotFound:
|
||||
return ErrNotFound
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// PrettyError returns an err in a better readable way.
|
||||
func PrettyError(err error) error {
|
||||
var errResp *internGitlab.ErrorResponse
|
||||
if errors.As(err, &errResp) {
|
||||
return errors.New(errResp.Message)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
// Code generated by MockGen. DO NOT EDIT.
|
||||
// Source: github.com/mattermost/mattermost-plugin-gitlab/server/gitlab (interfaces: Gitlab)
|
||||
|
||||
// Package mock_gitlab is a generated GoMock package.
|
||||
package mock_gitlab
|
||||
|
||||
import (
|
||||
context "context"
|
||||
reflect "reflect"
|
||||
|
||||
gomock "github.com/golang/mock/gomock"
|
||||
gitlab "github.com/mattermost/mattermost-plugin-gitlab/server/gitlab"
|
||||
logger "github.com/mattermost/mattermost/server/public/pluginapi/experimental/bot/logger"
|
||||
gitlab0 "github.com/xanzy/go-gitlab"
|
||||
oauth2 "golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
// MockGitlab is a mock of Gitlab interface.
|
||||
type MockGitlab struct {
|
||||
ctrl *gomock.Controller
|
||||
recorder *MockGitlabMockRecorder
|
||||
}
|
||||
|
||||
// MockGitlabMockRecorder is the mock recorder for MockGitlab.
|
||||
type MockGitlabMockRecorder struct {
|
||||
mock *MockGitlab
|
||||
}
|
||||
|
||||
// NewMockGitlab creates a new mock instance.
|
||||
func NewMockGitlab(ctrl *gomock.Controller) *MockGitlab {
|
||||
mock := &MockGitlab{ctrl: ctrl}
|
||||
mock.recorder = &MockGitlabMockRecorder{mock}
|
||||
return mock
|
||||
}
|
||||
|
||||
// EXPECT returns an object that allows the caller to indicate expected use.
|
||||
func (m *MockGitlab) EXPECT() *MockGitlabMockRecorder {
|
||||
return m.recorder
|
||||
}
|
||||
|
||||
// GetCurrentUser mocks base method.
|
||||
func (m *MockGitlab) GetCurrentUser(arg0 context.Context, arg1 string, arg2 oauth2.Token) (*gitlab.UserInfo, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "GetCurrentUser", arg0, arg1, arg2)
|
||||
ret0, _ := ret[0].(*gitlab.UserInfo)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// GetCurrentUser indicates an expected call of GetCurrentUser.
|
||||
func (mr *MockGitlabMockRecorder) GetCurrentUser(arg0, arg1, arg2 interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentUser", reflect.TypeOf((*MockGitlab)(nil).GetCurrentUser), arg0, arg1, arg2)
|
||||
}
|
||||
|
||||
// GetGroupHooks mocks base method.
|
||||
func (m *MockGitlab) GetGroupHooks(arg0 context.Context, arg1 *gitlab.UserInfo, arg2 *oauth2.Token, arg3 string) ([]*gitlab.WebhookInfo, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "GetGroupHooks", arg0, arg1, arg2, arg3)
|
||||
ret0, _ := ret[0].([]*gitlab.WebhookInfo)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// GetGroupHooks indicates an expected call of GetGroupHooks.
|
||||
func (mr *MockGitlabMockRecorder) GetGroupHooks(arg0, arg1, arg2, arg3 interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetGroupHooks", reflect.TypeOf((*MockGitlab)(nil).GetGroupHooks), arg0, arg1, arg2, arg3)
|
||||
}
|
||||
|
||||
// GetIssueByID mocks base method.
|
||||
func (m *MockGitlab) GetIssueByID(arg0 context.Context, arg1 *gitlab.UserInfo, arg2, arg3 string, arg4 int, arg5 *oauth2.Token) (*gitlab.Issue, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "GetIssueByID", arg0, arg1, arg2, arg3, arg4, arg5)
|
||||
ret0, _ := ret[0].(*gitlab.Issue)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// GetIssueByID indicates an expected call of GetIssueByID.
|
||||
func (mr *MockGitlabMockRecorder) GetIssueByID(arg0, arg1, arg2, arg3, arg4, arg5 interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetIssueByID", reflect.TypeOf((*MockGitlab)(nil).GetIssueByID), arg0, arg1, arg2, arg3, arg4, arg5)
|
||||
}
|
||||
|
||||
// GetLHSData mocks base method.
|
||||
func (m *MockGitlab) GetLHSData(arg0 context.Context, arg1 *gitlab.UserInfo, arg2 *oauth2.Token) (*gitlab.LHSContent, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "GetLHSData", arg0, arg1, arg2)
|
||||
ret0, _ := ret[0].(*gitlab.LHSContent)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// GetLHSData indicates an expected call of GetLHSData.
|
||||
func (mr *MockGitlabMockRecorder) GetLHSData(arg0, arg1, arg2 interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetLHSData", reflect.TypeOf((*MockGitlab)(nil).GetLHSData), arg0, arg1, arg2)
|
||||
}
|
||||
|
||||
// GetMergeRequestByID mocks base method.
|
||||
func (m *MockGitlab) GetMergeRequestByID(arg0 context.Context, arg1 *gitlab.UserInfo, arg2, arg3 string, arg4 int, arg5 *oauth2.Token) (*gitlab.MergeRequest, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "GetMergeRequestByID", arg0, arg1, arg2, arg3, arg4, arg5)
|
||||
ret0, _ := ret[0].(*gitlab.MergeRequest)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// GetMergeRequestByID indicates an expected call of GetMergeRequestByID.
|
||||
func (mr *MockGitlabMockRecorder) GetMergeRequestByID(arg0, arg1, arg2, arg3, arg4, arg5 interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMergeRequestByID", reflect.TypeOf((*MockGitlab)(nil).GetMergeRequestByID), arg0, arg1, arg2, arg3, arg4, arg5)
|
||||
}
|
||||
|
||||
// GetProject mocks base method.
|
||||
func (m *MockGitlab) GetProject(arg0 context.Context, arg1 *gitlab.UserInfo, arg2 *oauth2.Token, arg3, arg4 string) (*gitlab0.Project, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "GetProject", arg0, arg1, arg2, arg3, arg4)
|
||||
ret0, _ := ret[0].(*gitlab0.Project)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// GetProject indicates an expected call of GetProject.
|
||||
func (mr *MockGitlabMockRecorder) GetProject(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetProject", reflect.TypeOf((*MockGitlab)(nil).GetProject), arg0, arg1, arg2, arg3, arg4)
|
||||
}
|
||||
|
||||
// GetProjectHooks mocks base method.
|
||||
func (m *MockGitlab) GetProjectHooks(arg0 context.Context, arg1 *gitlab.UserInfo, arg2 *oauth2.Token, arg3, arg4 string) ([]*gitlab.WebhookInfo, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "GetProjectHooks", arg0, arg1, arg2, arg3, arg4)
|
||||
ret0, _ := ret[0].([]*gitlab.WebhookInfo)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// GetProjectHooks indicates an expected call of GetProjectHooks.
|
||||
func (mr *MockGitlabMockRecorder) GetProjectHooks(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetProjectHooks", reflect.TypeOf((*MockGitlab)(nil).GetProjectHooks), arg0, arg1, arg2, arg3, arg4)
|
||||
}
|
||||
|
||||
// GetReviews mocks base method.
|
||||
func (m *MockGitlab) GetReviews(arg0 context.Context, arg1 *gitlab.UserInfo, arg2 *gitlab0.Client) ([]*gitlab.MergeRequest, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "GetReviews", arg0, arg1, arg2)
|
||||
ret0, _ := ret[0].([]*gitlab.MergeRequest)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// GetReviews indicates an expected call of GetReviews.
|
||||
func (mr *MockGitlabMockRecorder) GetReviews(arg0, arg1, arg2 interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetReviews", reflect.TypeOf((*MockGitlab)(nil).GetReviews), arg0, arg1, arg2)
|
||||
}
|
||||
|
||||
// GetToDoList mocks base method.
|
||||
func (m *MockGitlab) GetToDoList(arg0 context.Context, arg1 *gitlab.UserInfo, arg2 *gitlab0.Client) ([]*gitlab0.Todo, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "GetToDoList", arg0, arg1, arg2)
|
||||
ret0, _ := ret[0].([]*gitlab0.Todo)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// GetToDoList indicates an expected call of GetToDoList.
|
||||
func (mr *MockGitlabMockRecorder) GetToDoList(arg0, arg1, arg2 interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetToDoList", reflect.TypeOf((*MockGitlab)(nil).GetToDoList), arg0, arg1, arg2)
|
||||
}
|
||||
|
||||
// GetUserDetails mocks base method.
|
||||
func (m *MockGitlab) GetUserDetails(arg0 context.Context, arg1 *gitlab.UserInfo, arg2 *oauth2.Token) (*gitlab0.User, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "GetUserDetails", arg0, arg1, arg2)
|
||||
ret0, _ := ret[0].(*gitlab0.User)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// GetUserDetails indicates an expected call of GetUserDetails.
|
||||
func (mr *MockGitlabMockRecorder) GetUserDetails(arg0, arg1, arg2 interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUserDetails", reflect.TypeOf((*MockGitlab)(nil).GetUserDetails), arg0, arg1, arg2)
|
||||
}
|
||||
|
||||
// GetYourAssignedIssues mocks base method.
|
||||
func (m *MockGitlab) GetYourAssignedIssues(arg0 context.Context, arg1 *gitlab.UserInfo, arg2 *gitlab0.Client) ([]*gitlab.Issue, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "GetYourAssignedIssues", arg0, arg1, arg2)
|
||||
ret0, _ := ret[0].([]*gitlab.Issue)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// GetYourAssignedIssues indicates an expected call of GetYourAssignedIssues.
|
||||
func (mr *MockGitlabMockRecorder) GetYourAssignedIssues(arg0, arg1, arg2 interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetYourAssignedIssues", reflect.TypeOf((*MockGitlab)(nil).GetYourAssignedIssues), arg0, arg1, arg2)
|
||||
}
|
||||
|
||||
// GetYourAssignedPrs mocks base method.
|
||||
func (m *MockGitlab) GetYourAssignedPrs(arg0 context.Context, arg1 *gitlab.UserInfo, arg2 *gitlab0.Client) ([]*gitlab.MergeRequest, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "GetYourAssignedPrs", arg0, arg1, arg2)
|
||||
ret0, _ := ret[0].([]*gitlab.MergeRequest)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// GetYourAssignedPrs indicates an expected call of GetYourAssignedPrs.
|
||||
func (mr *MockGitlabMockRecorder) GetYourAssignedPrs(arg0, arg1, arg2 interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetYourAssignedPrs", reflect.TypeOf((*MockGitlab)(nil).GetYourAssignedPrs), arg0, arg1, arg2)
|
||||
}
|
||||
|
||||
// GetYourPrDetails mocks base method.
|
||||
func (m *MockGitlab) GetYourPrDetails(arg0 context.Context, arg1 logger.Logger, arg2 *gitlab.UserInfo, arg3 *oauth2.Token, arg4 []*gitlab.PRDetails) ([]*gitlab.PRDetails, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "GetYourPrDetails", arg0, arg1, arg2, arg3, arg4)
|
||||
ret0, _ := ret[0].([]*gitlab.PRDetails)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// GetYourPrDetails indicates an expected call of GetYourPrDetails.
|
||||
func (mr *MockGitlabMockRecorder) GetYourPrDetails(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetYourPrDetails", reflect.TypeOf((*MockGitlab)(nil).GetYourPrDetails), arg0, arg1, arg2, arg3, arg4)
|
||||
}
|
||||
|
||||
// GitlabConnect mocks base method.
|
||||
func (m *MockGitlab) GitlabConnect(arg0 oauth2.Token) (*gitlab0.Client, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "GitlabConnect", arg0)
|
||||
ret0, _ := ret[0].(*gitlab0.Client)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// GitlabConnect indicates an expected call of GitlabConnect.
|
||||
func (mr *MockGitlabMockRecorder) GitlabConnect(arg0 interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GitlabConnect", reflect.TypeOf((*MockGitlab)(nil).GitlabConnect), arg0)
|
||||
}
|
||||
|
||||
// NewGroupHook mocks base method.
|
||||
func (m *MockGitlab) NewGroupHook(arg0 context.Context, arg1 *gitlab.UserInfo, arg2 *oauth2.Token, arg3 string, arg4 *gitlab.AddWebhookOptions) (*gitlab.WebhookInfo, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "NewGroupHook", arg0, arg1, arg2, arg3, arg4)
|
||||
ret0, _ := ret[0].(*gitlab.WebhookInfo)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// NewGroupHook indicates an expected call of NewGroupHook.
|
||||
func (mr *MockGitlabMockRecorder) NewGroupHook(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NewGroupHook", reflect.TypeOf((*MockGitlab)(nil).NewGroupHook), arg0, arg1, arg2, arg3, arg4)
|
||||
}
|
||||
|
||||
// NewProjectHook mocks base method.
|
||||
func (m *MockGitlab) NewProjectHook(arg0 context.Context, arg1 *gitlab.UserInfo, arg2 *oauth2.Token, arg3 interface{}, arg4 *gitlab.AddWebhookOptions) (*gitlab.WebhookInfo, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "NewProjectHook", arg0, arg1, arg2, arg3, arg4)
|
||||
ret0, _ := ret[0].(*gitlab.WebhookInfo)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// NewProjectHook indicates an expected call of NewProjectHook.
|
||||
func (mr *MockGitlabMockRecorder) NewProjectHook(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NewProjectHook", reflect.TypeOf((*MockGitlab)(nil).NewProjectHook), arg0, arg1, arg2, arg3, arg4)
|
||||
}
|
||||
|
||||
// ResolveNamespaceAndProject mocks base method.
|
||||
func (m *MockGitlab) ResolveNamespaceAndProject(arg0 context.Context, arg1 *gitlab.UserInfo, arg2 *oauth2.Token, arg3 string, arg4 bool) (string, string, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "ResolveNamespaceAndProject", arg0, arg1, arg2, arg3, arg4)
|
||||
ret0, _ := ret[0].(string)
|
||||
ret1, _ := ret[1].(string)
|
||||
ret2, _ := ret[2].(error)
|
||||
return ret0, ret1, ret2
|
||||
}
|
||||
|
||||
// ResolveNamespaceAndProject indicates an expected call of ResolveNamespaceAndProject.
|
||||
func (mr *MockGitlabMockRecorder) ResolveNamespaceAndProject(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ResolveNamespaceAndProject", reflect.TypeOf((*MockGitlab)(nil).ResolveNamespaceAndProject), arg0, arg1, arg2, arg3, arg4)
|
||||
}
|
||||
|
||||
// TriggerProjectPipeline mocks base method.
|
||||
func (m *MockGitlab) TriggerProjectPipeline(arg0 *gitlab.UserInfo, arg1 *oauth2.Token, arg2, arg3 string) (*gitlab.PipelineInfo, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "TriggerProjectPipeline", arg0, arg1, arg2, arg3)
|
||||
ret0, _ := ret[0].(*gitlab.PipelineInfo)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// TriggerProjectPipeline indicates an expected call of TriggerProjectPipeline.
|
||||
func (mr *MockGitlabMockRecorder) TriggerProjectPipeline(arg0, arg1, arg2, arg3 interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TriggerProjectPipeline", reflect.TypeOf((*MockGitlab)(nil).TriggerProjectPipeline), arg0, arg1, arg2, arg3)
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package gitlab
|
||||
|
||||
// PipelineInfo is the struct describing the status of
|
||||
// a running pipeline.
|
||||
type PipelineInfo struct {
|
||||
PipelineID int
|
||||
Status string
|
||||
Ref string
|
||||
WebURL string
|
||||
SHA string
|
||||
User string
|
||||
}
|
||||
|
||||
// PipelineJobInfo is the struct describing the status of
|
||||
// a running Job which is part of a pipeline
|
||||
type PipelineJobInfo struct {
|
||||
JobID int
|
||||
Status string
|
||||
Ref string
|
||||
WebURL string
|
||||
User string
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package gitlab
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/mattermost/mattermost/server/public/model"
|
||||
internGitlab "github.com/xanzy/go-gitlab"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
const SettingButtonsTeam = "team"
|
||||
|
||||
type UserInfo struct {
|
||||
UserID string
|
||||
GitlabUsername string
|
||||
GitlabUserID int
|
||||
LastToDoPostAt int64
|
||||
Settings *UserSettings
|
||||
AllowedPrivateRepos bool
|
||||
}
|
||||
|
||||
type UserSettings struct {
|
||||
SidebarButtons string `json:"sidebar_buttons"`
|
||||
DailyReminder bool `json:"daily_reminder"`
|
||||
Notifications bool `json:"notifications"`
|
||||
}
|
||||
|
||||
func (g *gitlab) GetCurrentUser(ctx context.Context, userID string, token oauth2.Token) (*UserInfo, error) {
|
||||
client, err := g.GitlabConnect(token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
gitUser, resp, err := client.Users.CurrentUser(internGitlab.WithContext(ctx))
|
||||
if respErr := checkResponse(resp); respErr != nil {
|
||||
return nil, respErr
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &UserInfo{
|
||||
UserID: userID,
|
||||
GitlabUserID: gitUser.ID,
|
||||
GitlabUsername: gitUser.Username,
|
||||
LastToDoPostAt: model.GetMillis(),
|
||||
Settings: &UserSettings{
|
||||
SidebarButtons: SettingButtonsTeam,
|
||||
DailyReminder: true,
|
||||
Notifications: true,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (g *gitlab) GetUserDetails(ctx context.Context, user *UserInfo, token *oauth2.Token) (*internGitlab.User, error) {
|
||||
client, err := g.GitlabConnect(*token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
gitUser, resp, err := client.Users.CurrentUser(internGitlab.WithContext(ctx))
|
||||
if respErr := checkResponse(resp); respErr != nil {
|
||||
return nil, respErr
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return gitUser, nil
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package gitlab
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// WebhookInfo Provides information about group or project hooks.
|
||||
type WebhookInfo struct {
|
||||
ID int
|
||||
URL string
|
||||
ConfidentialNoteEvents bool
|
||||
PushEvents bool
|
||||
IssuesEvents bool
|
||||
ConfidentialIssuesEvents bool
|
||||
MergeRequestsEvents bool
|
||||
TagPushEvents bool
|
||||
NoteEvents bool
|
||||
JobEvents bool
|
||||
PipelineEvents bool
|
||||
WikiPageEvents bool
|
||||
EnableSSLVerification bool
|
||||
CreatedAt *time.Time
|
||||
Scope Scope
|
||||
}
|
||||
|
||||
// AddWebhookOptions is a paramater object with options for creating a project or group hook.
|
||||
type AddWebhookOptions struct {
|
||||
URL string
|
||||
ConfidentialNoteEvents bool
|
||||
PushEvents bool
|
||||
IssuesEvents bool
|
||||
ConfidentialIssuesEvents bool
|
||||
MergeRequestsEvents bool
|
||||
TagPushEvents bool
|
||||
NoteEvents bool
|
||||
JobEvents bool
|
||||
PipelineEvents bool
|
||||
WikiPageEvents bool
|
||||
EnableSSLVerification bool
|
||||
Token string
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/mattermost/mattermost/server/public/plugin"
|
||||
)
|
||||
|
||||
func main() {
|
||||
plugin.ClientMain(NewPlugin())
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
// Code generated by MockGen. DO NOT EDIT.
|
||||
// Source: github.com/mattermost/mattermost-plugin-gitlab/server/gitlab (interfaces: Gitlab)
|
||||
|
||||
// Package mock_gitlab is a generated GoMock package.
|
||||
package mock_gitlab
|
||||
|
||||
import (
|
||||
context "context"
|
||||
reflect "reflect"
|
||||
|
||||
gomock "github.com/golang/mock/gomock"
|
||||
gitlab "github.com/mattermost/mattermost-plugin-gitlab/server/gitlab"
|
||||
logger "github.com/mattermost/mattermost/server/public/pluginapi/experimental/bot/logger"
|
||||
gitlab0 "github.com/xanzy/go-gitlab"
|
||||
oauth2 "golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
// MockGitlab is a mock of Gitlab interface.
|
||||
type MockGitlab struct {
|
||||
ctrl *gomock.Controller
|
||||
recorder *MockGitlabMockRecorder
|
||||
}
|
||||
|
||||
// MockGitlabMockRecorder is the mock recorder for MockGitlab.
|
||||
type MockGitlabMockRecorder struct {
|
||||
mock *MockGitlab
|
||||
}
|
||||
|
||||
// NewMockGitlab creates a new mock instance.
|
||||
func NewMockGitlab(ctrl *gomock.Controller) *MockGitlab {
|
||||
mock := &MockGitlab{ctrl: ctrl}
|
||||
mock.recorder = &MockGitlabMockRecorder{mock}
|
||||
return mock
|
||||
}
|
||||
|
||||
// EXPECT returns an object that allows the caller to indicate expected use.
|
||||
func (m *MockGitlab) EXPECT() *MockGitlabMockRecorder {
|
||||
return m.recorder
|
||||
}
|
||||
|
||||
// GetCurrentUser mocks base method.
|
||||
func (m *MockGitlab) GetCurrentUser(arg0 context.Context, arg1 string, arg2 oauth2.Token) (*gitlab.UserInfo, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "GetCurrentUser", arg0, arg1, arg2)
|
||||
ret0, _ := ret[0].(*gitlab.UserInfo)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// GetCurrentUser indicates an expected call of GetCurrentUser.
|
||||
func (mr *MockGitlabMockRecorder) GetCurrentUser(arg0, arg1, arg2 interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentUser", reflect.TypeOf((*MockGitlab)(nil).GetCurrentUser), arg0, arg1, arg2)
|
||||
}
|
||||
|
||||
// GetGroupHooks mocks base method.
|
||||
func (m *MockGitlab) GetGroupHooks(arg0 context.Context, arg1 *gitlab.UserInfo, arg2 *oauth2.Token, arg3 string) ([]*gitlab.WebhookInfo, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "GetGroupHooks", arg0, arg1, arg2, arg3)
|
||||
ret0, _ := ret[0].([]*gitlab.WebhookInfo)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// GetGroupHooks indicates an expected call of GetGroupHooks.
|
||||
func (mr *MockGitlabMockRecorder) GetGroupHooks(arg0, arg1, arg2, arg3 interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetGroupHooks", reflect.TypeOf((*MockGitlab)(nil).GetGroupHooks), arg0, arg1, arg2, arg3)
|
||||
}
|
||||
|
||||
// GetIssueByID mocks base method.
|
||||
func (m *MockGitlab) GetIssueByID(arg0 context.Context, arg1 *gitlab.UserInfo, arg2, arg3 string, arg4 int, arg5 *oauth2.Token) (*gitlab.Issue, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "GetIssueByID", arg0, arg1, arg2, arg3, arg4, arg5)
|
||||
ret0, _ := ret[0].(*gitlab.Issue)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// GetIssueByID indicates an expected call of GetIssueByID.
|
||||
func (mr *MockGitlabMockRecorder) GetIssueByID(arg0, arg1, arg2, arg3, arg4, arg5 interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetIssueByID", reflect.TypeOf((*MockGitlab)(nil).GetIssueByID), arg0, arg1, arg2, arg3, arg4, arg5)
|
||||
}
|
||||
|
||||
// GetLHSData mocks base method.
|
||||
func (m *MockGitlab) GetLHSData(arg0 context.Context, arg1 *gitlab.UserInfo, arg2 *oauth2.Token) (*gitlab.LHSContent, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "GetLHSData", arg0, arg1, arg2)
|
||||
ret0, _ := ret[0].(*gitlab.LHSContent)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// GetLHSData indicates an expected call of GetLHSData.
|
||||
func (mr *MockGitlabMockRecorder) GetLHSData(arg0, arg1, arg2 interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetLHSData", reflect.TypeOf((*MockGitlab)(nil).GetLHSData), arg0, arg1, arg2)
|
||||
}
|
||||
|
||||
// GetMergeRequestByID mocks base method.
|
||||
func (m *MockGitlab) GetMergeRequestByID(arg0 context.Context, arg1 *gitlab.UserInfo, arg2, arg3 string, arg4 int, arg5 *oauth2.Token) (*gitlab.MergeRequest, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "GetMergeRequestByID", arg0, arg1, arg2, arg3, arg4, arg5)
|
||||
ret0, _ := ret[0].(*gitlab.MergeRequest)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// GetMergeRequestByID indicates an expected call of GetMergeRequestByID.
|
||||
func (mr *MockGitlabMockRecorder) GetMergeRequestByID(arg0, arg1, arg2, arg3, arg4, arg5 interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMergeRequestByID", reflect.TypeOf((*MockGitlab)(nil).GetMergeRequestByID), arg0, arg1, arg2, arg3, arg4, arg5)
|
||||
}
|
||||
|
||||
// GetProject mocks base method.
|
||||
func (m *MockGitlab) GetProject(arg0 context.Context, arg1 *gitlab.UserInfo, arg2 *oauth2.Token, arg3, arg4 string) (*gitlab0.Project, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "GetProject", arg0, arg1, arg2, arg3, arg4)
|
||||
ret0, _ := ret[0].(*gitlab0.Project)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// GetProject indicates an expected call of GetProject.
|
||||
func (mr *MockGitlabMockRecorder) GetProject(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetProject", reflect.TypeOf((*MockGitlab)(nil).GetProject), arg0, arg1, arg2, arg3, arg4)
|
||||
}
|
||||
|
||||
// GetProjectHooks mocks base method.
|
||||
func (m *MockGitlab) GetProjectHooks(arg0 context.Context, arg1 *gitlab.UserInfo, arg2 *oauth2.Token, arg3, arg4 string) ([]*gitlab.WebhookInfo, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "GetProjectHooks", arg0, arg1, arg2, arg3, arg4)
|
||||
ret0, _ := ret[0].([]*gitlab.WebhookInfo)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// GetProjectHooks indicates an expected call of GetProjectHooks.
|
||||
func (mr *MockGitlabMockRecorder) GetProjectHooks(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetProjectHooks", reflect.TypeOf((*MockGitlab)(nil).GetProjectHooks), arg0, arg1, arg2, arg3, arg4)
|
||||
}
|
||||
|
||||
// GetReviews mocks base method.
|
||||
func (m *MockGitlab) GetReviews(arg0 context.Context, arg1 *gitlab.UserInfo, arg2 *gitlab0.Client) ([]*gitlab.MergeRequest, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "GetReviews", arg0, arg1, arg2)
|
||||
ret0, _ := ret[0].([]*gitlab.MergeRequest)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// GetReviews indicates an expected call of GetReviews.
|
||||
func (mr *MockGitlabMockRecorder) GetReviews(arg0, arg1, arg2 interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetReviews", reflect.TypeOf((*MockGitlab)(nil).GetReviews), arg0, arg1, arg2)
|
||||
}
|
||||
|
||||
// GetToDoList mocks base method.
|
||||
func (m *MockGitlab) GetToDoList(arg0 context.Context, arg1 *gitlab.UserInfo, arg2 *gitlab0.Client) ([]*gitlab0.Todo, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "GetToDoList", arg0, arg1, arg2)
|
||||
ret0, _ := ret[0].([]*gitlab0.Todo)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// GetToDoList indicates an expected call of GetToDoList.
|
||||
func (mr *MockGitlabMockRecorder) GetToDoList(arg0, arg1, arg2 interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetToDoList", reflect.TypeOf((*MockGitlab)(nil).GetToDoList), arg0, arg1, arg2)
|
||||
}
|
||||
|
||||
// GetUserDetails mocks base method.
|
||||
func (m *MockGitlab) GetUserDetails(arg0 context.Context, arg1 *gitlab.UserInfo, arg2 *oauth2.Token) (*gitlab0.User, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "GetUserDetails", arg0, arg1, arg2)
|
||||
ret0, _ := ret[0].(*gitlab0.User)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// GetUserDetails indicates an expected call of GetUserDetails.
|
||||
func (mr *MockGitlabMockRecorder) GetUserDetails(arg0, arg1, arg2 interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUserDetails", reflect.TypeOf((*MockGitlab)(nil).GetUserDetails), arg0, arg1, arg2)
|
||||
}
|
||||
|
||||
// GetYourAssignedIssues mocks base method.
|
||||
func (m *MockGitlab) GetYourAssignedIssues(arg0 context.Context, arg1 *gitlab.UserInfo, arg2 *gitlab0.Client) ([]*gitlab.Issue, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "GetYourAssignedIssues", arg0, arg1, arg2)
|
||||
ret0, _ := ret[0].([]*gitlab.Issue)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// GetYourAssignedIssues indicates an expected call of GetYourAssignedIssues.
|
||||
func (mr *MockGitlabMockRecorder) GetYourAssignedIssues(arg0, arg1, arg2 interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetYourAssignedIssues", reflect.TypeOf((*MockGitlab)(nil).GetYourAssignedIssues), arg0, arg1, arg2)
|
||||
}
|
||||
|
||||
// GetYourAssignedPrs mocks base method.
|
||||
func (m *MockGitlab) GetYourAssignedPrs(arg0 context.Context, arg1 *gitlab.UserInfo, arg2 *gitlab0.Client) ([]*gitlab.MergeRequest, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "GetYourAssignedPrs", arg0, arg1, arg2)
|
||||
ret0, _ := ret[0].([]*gitlab.MergeRequest)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// GetYourAssignedPrs indicates an expected call of GetYourAssignedPrs.
|
||||
func (mr *MockGitlabMockRecorder) GetYourAssignedPrs(arg0, arg1, arg2 interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetYourAssignedPrs", reflect.TypeOf((*MockGitlab)(nil).GetYourAssignedPrs), arg0, arg1, arg2)
|
||||
}
|
||||
|
||||
// GetYourPrDetails mocks base method.
|
||||
func (m *MockGitlab) GetYourPrDetails(arg0 context.Context, arg1 logger.Logger, arg2 *gitlab.UserInfo, arg3 *oauth2.Token, arg4 []*gitlab.PRDetails) ([]*gitlab.PRDetails, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "GetYourPrDetails", arg0, arg1, arg2, arg3, arg4)
|
||||
ret0, _ := ret[0].([]*gitlab.PRDetails)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// GetYourPrDetails indicates an expected call of GetYourPrDetails.
|
||||
func (mr *MockGitlabMockRecorder) GetYourPrDetails(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetYourPrDetails", reflect.TypeOf((*MockGitlab)(nil).GetYourPrDetails), arg0, arg1, arg2, arg3, arg4)
|
||||
}
|
||||
|
||||
// GitlabConnect mocks base method.
|
||||
func (m *MockGitlab) GitlabConnect(arg0 oauth2.Token) (*gitlab0.Client, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "GitlabConnect", arg0)
|
||||
ret0, _ := ret[0].(*gitlab0.Client)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// GitlabConnect indicates an expected call of GitlabConnect.
|
||||
func (mr *MockGitlabMockRecorder) GitlabConnect(arg0 interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GitlabConnect", reflect.TypeOf((*MockGitlab)(nil).GitlabConnect), arg0)
|
||||
}
|
||||
|
||||
// NewGroupHook mocks base method.
|
||||
func (m *MockGitlab) NewGroupHook(arg0 context.Context, arg1 *gitlab.UserInfo, arg2 *oauth2.Token, arg3 string, arg4 *gitlab.AddWebhookOptions) (*gitlab.WebhookInfo, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "NewGroupHook", arg0, arg1, arg2, arg3, arg4)
|
||||
ret0, _ := ret[0].(*gitlab.WebhookInfo)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// NewGroupHook indicates an expected call of NewGroupHook.
|
||||
func (mr *MockGitlabMockRecorder) NewGroupHook(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NewGroupHook", reflect.TypeOf((*MockGitlab)(nil).NewGroupHook), arg0, arg1, arg2, arg3, arg4)
|
||||
}
|
||||
|
||||
// NewProjectHook mocks base method.
|
||||
func (m *MockGitlab) NewProjectHook(arg0 context.Context, arg1 *gitlab.UserInfo, arg2 *oauth2.Token, arg3 interface{}, arg4 *gitlab.AddWebhookOptions) (*gitlab.WebhookInfo, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "NewProjectHook", arg0, arg1, arg2, arg3, arg4)
|
||||
ret0, _ := ret[0].(*gitlab.WebhookInfo)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// NewProjectHook indicates an expected call of NewProjectHook.
|
||||
func (mr *MockGitlabMockRecorder) NewProjectHook(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NewProjectHook", reflect.TypeOf((*MockGitlab)(nil).NewProjectHook), arg0, arg1, arg2, arg3, arg4)
|
||||
}
|
||||
|
||||
// ResolveNamespaceAndProject mocks base method.
|
||||
func (m *MockGitlab) ResolveNamespaceAndProject(arg0 context.Context, arg1 *gitlab.UserInfo, arg2 *oauth2.Token, arg3 string, arg4 bool) (string, string, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "ResolveNamespaceAndProject", arg0, arg1, arg2, arg3, arg4)
|
||||
ret0, _ := ret[0].(string)
|
||||
ret1, _ := ret[1].(string)
|
||||
ret2, _ := ret[2].(error)
|
||||
return ret0, ret1, ret2
|
||||
}
|
||||
|
||||
// ResolveNamespaceAndProject indicates an expected call of ResolveNamespaceAndProject.
|
||||
func (mr *MockGitlabMockRecorder) ResolveNamespaceAndProject(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ResolveNamespaceAndProject", reflect.TypeOf((*MockGitlab)(nil).ResolveNamespaceAndProject), arg0, arg1, arg2, arg3, arg4)
|
||||
}
|
||||
|
||||
// TriggerProjectPipeline mocks base method.
|
||||
func (m *MockGitlab) TriggerProjectPipeline(arg0 *gitlab.UserInfo, arg1 *oauth2.Token, arg2, arg3 string) (*gitlab.PipelineInfo, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "TriggerProjectPipeline", arg0, arg1, arg2, arg3)
|
||||
ret0, _ := ret[0].(*gitlab.PipelineInfo)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// TriggerProjectPipeline indicates an expected call of TriggerProjectPipeline.
|
||||
func (mr *MockGitlabMockRecorder) TriggerProjectPipeline(arg0, arg1, arg2, arg3 interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TriggerProjectPipeline", reflect.TypeOf((*MockGitlab)(nil).TriggerProjectPipeline), arg0, arg1, arg2, arg3)
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"sync"
|
||||
)
|
||||
|
||||
type OAuthCompleteEvent struct {
|
||||
UserID string
|
||||
Err error
|
||||
}
|
||||
|
||||
type OAuthBroker struct {
|
||||
sendOAuthCompleteEvent func(event OAuthCompleteEvent)
|
||||
|
||||
lock sync.RWMutex // Protects closed and pingSubs
|
||||
closed bool
|
||||
oauthCompleteSubs map[string][]chan error
|
||||
mapCreate sync.Once
|
||||
}
|
||||
|
||||
func NewOAuthBroker(sendOAuthCompleteEvent func(event OAuthCompleteEvent)) *OAuthBroker {
|
||||
return &OAuthBroker{
|
||||
sendOAuthCompleteEvent: sendOAuthCompleteEvent,
|
||||
}
|
||||
}
|
||||
|
||||
func (ob *OAuthBroker) SubscribeOAuthComplete(userID string) <-chan error {
|
||||
ob.lock.Lock()
|
||||
defer ob.lock.Unlock()
|
||||
|
||||
ob.mapCreate.Do(func() {
|
||||
ob.oauthCompleteSubs = make(map[string][]chan error)
|
||||
})
|
||||
|
||||
ch := make(chan error, 1)
|
||||
ob.oauthCompleteSubs[userID] = append(ob.oauthCompleteSubs[userID], ch)
|
||||
|
||||
return ch
|
||||
}
|
||||
|
||||
func (ob *OAuthBroker) UnsubscribeOAuthComplete(userID string, ch <-chan error) {
|
||||
ob.lock.Lock()
|
||||
defer ob.lock.Unlock()
|
||||
|
||||
for i, sub := range ob.oauthCompleteSubs[userID] {
|
||||
if sub == ch {
|
||||
ob.oauthCompleteSubs[userID] = append(ob.oauthCompleteSubs[userID][:i], ob.oauthCompleteSubs[userID][i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (ob *OAuthBroker) publishOAuthComplete(userID string, err error, fromCluster bool) {
|
||||
ob.lock.Lock()
|
||||
defer ob.lock.Unlock()
|
||||
|
||||
if ob.closed {
|
||||
return
|
||||
}
|
||||
|
||||
for _, userSubs := range ob.oauthCompleteSubs[userID] {
|
||||
// non-blocking send
|
||||
select {
|
||||
case userSubs <- err:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
if !fromCluster {
|
||||
ob.sendOAuthCompleteEvent(OAuthCompleteEvent{UserID: userID, Err: err})
|
||||
}
|
||||
}
|
||||
|
||||
func (ob *OAuthBroker) Close() {
|
||||
ob.lock.Lock()
|
||||
defer ob.lock.Unlock()
|
||||
|
||||
if !ob.closed {
|
||||
ob.closed = true
|
||||
|
||||
for _, userSubs := range ob.oauthCompleteSubs {
|
||||
for _, sub := range userSubs {
|
||||
close(sub)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/xanzy/go-gitlab"
|
||||
)
|
||||
|
||||
// maxPermalinkReplacements sets the maximum limit to the number of
|
||||
// permalink replacements that can be performed on a single message.
|
||||
const maxPermalinkReplacements = 10
|
||||
|
||||
const permalinkReqTimeout = 5 * time.Second
|
||||
|
||||
// maxPreviewLines sets the maximum number of preview lines that will be shown
|
||||
// while replacing a permalink.
|
||||
const maxPreviewLines = 10
|
||||
|
||||
// permalinkLineContext shows the number of lines before and after to show
|
||||
// if the link points to a single line.
|
||||
const permalinkLineContext = 3
|
||||
|
||||
// replacement holds necessary info to replace GitLab permalinks
|
||||
// in messages with a code preview block.
|
||||
type replacement struct {
|
||||
index int // Index of the permalink in the string
|
||||
word string // The permalink
|
||||
permalinkData permalinkInfo
|
||||
}
|
||||
|
||||
type permalinkInfo struct { // Holds the necessary metadata of a permalink
|
||||
haswww string
|
||||
commit string
|
||||
user string
|
||||
repo string
|
||||
path string
|
||||
line string
|
||||
}
|
||||
|
||||
// getPermalinkReplacements returns the permalink replacements that need to be performed
|
||||
// on a message. The returned slice is sorted by the index in ascending order.
|
||||
func (p *Plugin) getPermalinkReplacements(msg string) []replacement {
|
||||
// Find the permalinks from the msg using a regex
|
||||
matches := gitlabPermalinkRegex.FindAllStringSubmatch(msg, -1)
|
||||
indices := gitlabPermalinkRegex.FindAllStringIndex(msg, -1)
|
||||
var replacements []replacement
|
||||
for i, m := range matches {
|
||||
// Have a limit on the number of replacements to do
|
||||
if i > maxPermalinkReplacements {
|
||||
break
|
||||
}
|
||||
word := m[0]
|
||||
index := indices[i][0]
|
||||
r := replacement{
|
||||
index: index,
|
||||
word: word,
|
||||
}
|
||||
// Ignore if the word is inside a link
|
||||
if isInsideLink(msg, index) {
|
||||
continue
|
||||
}
|
||||
// Populate the permalinkInfo with the extracted groups of the regex
|
||||
for j, name := range gitlabPermalinkRegex.SubexpNames() {
|
||||
if j == 0 {
|
||||
continue
|
||||
}
|
||||
switch name {
|
||||
case "haswww":
|
||||
r.permalinkData.haswww = m[j]
|
||||
case "user":
|
||||
r.permalinkData.user = m[j]
|
||||
case "repo":
|
||||
r.permalinkData.repo = m[j]
|
||||
case "commit":
|
||||
r.permalinkData.commit = m[j]
|
||||
case "path":
|
||||
r.permalinkData.path = m[j]
|
||||
case "line":
|
||||
r.permalinkData.line = m[j]
|
||||
}
|
||||
}
|
||||
replacements = append(replacements, r)
|
||||
}
|
||||
return replacements
|
||||
}
|
||||
|
||||
// processReplacement processes a single replacement and stores the resulting markdown at the given index of the given array. Multiple goroutines are executing this function but all the goroutines concurrently modify unique indices of the given array, and concurrently modifying unique slice elements is not racy.
|
||||
func (p *Plugin) processReplacement(r replacement, glClient *gitlab.Client, wg *sync.WaitGroup, markdownForPermalink []string, index int) {
|
||||
defer wg.Done()
|
||||
|
||||
// Get the file contents
|
||||
opts := gitlab.GetFileOptions{
|
||||
Ref: &r.permalinkData.commit,
|
||||
}
|
||||
projectPath := fmt.Sprintf("%s/%s", r.permalinkData.user, r.permalinkData.repo)
|
||||
|
||||
// Check if the project is public
|
||||
if p.getConfiguration().EnableCodePreview == "public" {
|
||||
repo, _, err := glClient.Projects.GetProject(projectPath, &gitlab.GetProjectOptions{})
|
||||
if err != nil {
|
||||
p.API.LogError("Error while fetching project information", "error", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
if repo.Visibility == gitlab.PrivateVisibility {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
_, cancel := context.WithTimeout(context.Background(), permalinkReqTimeout)
|
||||
file, _, err := glClient.RepositoryFiles.GetFile(projectPath, r.permalinkData.path, &opts)
|
||||
defer cancel()
|
||||
if err != nil {
|
||||
p.API.LogDebug("Error while fetching file contents", "error", err.Error(), "path", r.permalinkData.path)
|
||||
return
|
||||
}
|
||||
// If this is not a file, ignore.
|
||||
if file == nil {
|
||||
p.API.LogWarn("Permalink is not a file", "file", r.permalinkData.path)
|
||||
return
|
||||
}
|
||||
|
||||
decoded, err := base64.StdEncoding.DecodeString(file.Content)
|
||||
if err != nil {
|
||||
p.API.LogDebug("Error while decoding file contents", "error", err.Error(), "path", r.permalinkData.path)
|
||||
return
|
||||
}
|
||||
// Get the required lines.
|
||||
start, end := getLineNumbers(r.permalinkData.line)
|
||||
// Bad anchor tag, ignore.
|
||||
if start == -1 || end == -1 {
|
||||
return
|
||||
}
|
||||
|
||||
isTruncated := false
|
||||
if end-start > maxPreviewLines {
|
||||
end = start + maxPreviewLines
|
||||
isTruncated = true
|
||||
}
|
||||
|
||||
lines, err := filterLines(string(decoded), start, end)
|
||||
if err != nil {
|
||||
p.API.LogDebug("Error while filtering lines", "error", err.Error(), "path", r.permalinkData.path)
|
||||
}
|
||||
|
||||
if lines == "" {
|
||||
p.API.LogDebug("Line numbers out of range. Skipping.", "file", r.permalinkData.path, "start", start, "end", end)
|
||||
return
|
||||
}
|
||||
|
||||
markdownForPermalink[index] = getCodeMarkdown(r.permalinkData.user, r.permalinkData.repo, r.permalinkData.path, r.word, lines, isTruncated)
|
||||
}
|
||||
|
||||
// makeReplacements performs the given replacements on the msg and returns
|
||||
// the new msg. The replacements slice needs to be sorted by the index in ascending order.
|
||||
// Ref: mattermost plugin github (https://github.com/mattermost/mattermost-plugin-github/blob/fcc50523c17c2670cb595a8038864a8a7f7fd1e5/server/plugin/permalinks.go#L90)
|
||||
func (p *Plugin) makeReplacements(msg string, replacements []replacement, glClient *gitlab.Client) string {
|
||||
// Iterating the slice in reverse to preserve the replacement indices.
|
||||
wg := new(sync.WaitGroup)
|
||||
markdownForPermalink := make([]string, len(replacements))
|
||||
for i := len(replacements) - 1; i >= 0; i-- {
|
||||
wg.Add(1)
|
||||
go p.processReplacement(replacements[i], glClient, wg, markdownForPermalink, i)
|
||||
}
|
||||
wg.Wait()
|
||||
for i := len(replacements) - 1; i >= 0; i-- {
|
||||
r := replacements[i]
|
||||
if markdownForPermalink[i] != "" {
|
||||
// Replace word in msg starting from r.index only once.
|
||||
msg = msg[:r.index] + strings.Replace(msg[r.index:], r.word, markdownForPermalink[i], 1)
|
||||
}
|
||||
}
|
||||
return msg
|
||||
}
|
||||
@@ -0,0 +1,396 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"github.com/mattermost/mattermost/server/public/plugin/plugintest"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/xanzy/go-gitlab"
|
||||
)
|
||||
|
||||
func TestGetReplacements(t *testing.T) {
|
||||
p := NewPlugin()
|
||||
|
||||
tcs := []struct {
|
||||
name string
|
||||
input string
|
||||
numReplacements int
|
||||
replacements []replacement
|
||||
}{
|
||||
{
|
||||
name: "basic one link",
|
||||
input: "start https://gitlab.com/mattermost/mattermost-server/-/blob/cbb25838a61872b624ac512556d7bc932486a64c/app/authentication.go#L15-L22 lorem ipsum",
|
||||
numReplacements: 1,
|
||||
replacements: []replacement{
|
||||
{
|
||||
index: 6,
|
||||
word: "https://gitlab.com/mattermost/mattermost-server/-/blob/cbb25838a61872b624ac512556d7bc932486a64c/app/authentication.go#L15-L22",
|
||||
permalinkData: struct {
|
||||
haswww string
|
||||
commit string
|
||||
user string
|
||||
repo string
|
||||
path string
|
||||
line string
|
||||
}{
|
||||
haswww: "",
|
||||
commit: "cbb25838a61872b624ac512556d7bc932486a64c",
|
||||
line: "L15-L22",
|
||||
path: "app/authentication.go",
|
||||
user: "mattermost",
|
||||
repo: "mattermost-server",
|
||||
},
|
||||
},
|
||||
},
|
||||
}, {
|
||||
name: "duplicate expansions",
|
||||
input: "start https://gitlab.com/mattermost/mattermost-server/-/blob/cbb25838a61872b624ac512556d7bc932486a64c/app/authentication.go#L15-L22 lorem ipsum https://gitlab.com/mattermost/mattermost-server/-/blob/cbb25838a61872b624ac512556d7bc932486a64c/app/authentication.go#L15-L22 lorem ipsum",
|
||||
numReplacements: 2,
|
||||
replacements: []replacement{
|
||||
{
|
||||
index: 6,
|
||||
word: "https://gitlab.com/mattermost/mattermost-server/-/blob/cbb25838a61872b624ac512556d7bc932486a64c/app/authentication.go#L15-L22",
|
||||
permalinkData: struct {
|
||||
haswww string
|
||||
commit string
|
||||
user string
|
||||
repo string
|
||||
path string
|
||||
line string
|
||||
}{
|
||||
commit: "cbb25838a61872b624ac512556d7bc932486a64c",
|
||||
haswww: "",
|
||||
line: "L15-L22",
|
||||
path: "app/authentication.go",
|
||||
user: "mattermost",
|
||||
repo: "mattermost-server",
|
||||
},
|
||||
}, {
|
||||
index: 144,
|
||||
word: "https://gitlab.com/mattermost/mattermost-server/-/blob/cbb25838a61872b624ac512556d7bc932486a64c/app/authentication.go#L15-L22",
|
||||
permalinkData: struct {
|
||||
haswww string
|
||||
commit string
|
||||
user string
|
||||
repo string
|
||||
path string
|
||||
line string
|
||||
}{
|
||||
commit: "cbb25838a61872b624ac512556d7bc932486a64c",
|
||||
haswww: "",
|
||||
line: "L15-L22",
|
||||
path: "app/authentication.go",
|
||||
user: "mattermost",
|
||||
repo: "mattermost-server",
|
||||
},
|
||||
},
|
||||
},
|
||||
}, {
|
||||
name: "inside link",
|
||||
input: "should not expand [link](https://gitlab.com/mattermost/mattermost-server/-/blob/cbb25838a61872b624ac512556d7bc932486a64c/app/authentication.go#L15-L22) here",
|
||||
numReplacements: 0,
|
||||
replacements: []replacement{},
|
||||
}, {
|
||||
name: "one link, one expansion",
|
||||
input: "first should not expand [link](https://gitlab.com/mattermost/mattermost-server/-/blob/cbb25838a61872b624ac512556d7bc932486a64c/app/authentication.go#L15-L22) this should https://gitlab.com/mattermost/mattermost-server/-/blob/cbb25838a61872b624ac512556d7bc932486a64c/app/authentication.go#L15-L22 lorem ipsum",
|
||||
numReplacements: 1,
|
||||
replacements: []replacement{
|
||||
{
|
||||
index: 170,
|
||||
word: "https://gitlab.com/mattermost/mattermost-server/-/blob/cbb25838a61872b624ac512556d7bc932486a64c/app/authentication.go#L15-L22",
|
||||
permalinkData: struct {
|
||||
haswww string
|
||||
commit string
|
||||
user string
|
||||
repo string
|
||||
path string
|
||||
line string
|
||||
}{
|
||||
commit: "cbb25838a61872b624ac512556d7bc932486a64c",
|
||||
haswww: "",
|
||||
line: "L15-L22",
|
||||
path: "app/authentication.go",
|
||||
user: "mattermost",
|
||||
repo: "mattermost-server",
|
||||
},
|
||||
},
|
||||
},
|
||||
}, {
|
||||
name: "one expansion, one link",
|
||||
input: "first should expand https://gitlab.com/mattermost/mattermost-server/-/blob/cbb25838a61872b624ac512556d7bc932486a64c/app/authentication.go#L15-L22 lorem ipsum , this should not [link](https://gitlab.com/mattermost/mattermost-server/-/blob/cbb25838a61872b624ac512556d7bc932486a64c/app/authentication.go#L15-L22)",
|
||||
numReplacements: 1,
|
||||
replacements: []replacement{
|
||||
{
|
||||
index: 20,
|
||||
word: "https://gitlab.com/mattermost/mattermost-server/-/blob/cbb25838a61872b624ac512556d7bc932486a64c/app/authentication.go#L15-L22",
|
||||
permalinkData: struct {
|
||||
haswww string
|
||||
commit string
|
||||
user string
|
||||
repo string
|
||||
path string
|
||||
line string
|
||||
}{
|
||||
commit: "cbb25838a61872b624ac512556d7bc932486a64c",
|
||||
haswww: "",
|
||||
line: "L15-L22",
|
||||
path: "app/authentication.go",
|
||||
user: "mattermost",
|
||||
repo: "mattermost-server",
|
||||
},
|
||||
},
|
||||
},
|
||||
}, {
|
||||
name: "2 links",
|
||||
input: "both should not expand- [link](https://gitlab.com/mattermost/mattermost-server/-/blob/cbb25838a61872b624ac512556d7bc932486a64c/app/authentication.go#L15-L22) and [link](https://gitlab.com/mattermost/mattermost-server/-/blob/cbb25838a61872b624ac512556d7bc932486a64c/app/authentication.go#L15-L22)",
|
||||
numReplacements: 0,
|
||||
replacements: []replacement{},
|
||||
}, {
|
||||
name: "multiple expansions",
|
||||
input: "multiple - https://gitlab.com/golang/go/-/blob/27fc32ff01cc699e160890546816bd99d6c57823/src/debug/macho/macho.go#L13-L16 second https://gitlab.com/mattermost/mattermost-server/-/blob/cbb25838a61872b624ac512556d7bc932486a64c/app/authentication.go#L15-L22",
|
||||
numReplacements: 2,
|
||||
replacements: []replacement{
|
||||
{
|
||||
index: 11,
|
||||
word: "https://gitlab.com/golang/go/-/blob/27fc32ff01cc699e160890546816bd99d6c57823/src/debug/macho/macho.go#L13-L16",
|
||||
permalinkData: struct {
|
||||
haswww string
|
||||
commit string
|
||||
user string
|
||||
repo string
|
||||
path string
|
||||
line string
|
||||
}{
|
||||
commit: "27fc32ff01cc699e160890546816bd99d6c57823",
|
||||
haswww: "",
|
||||
line: "L13-L16",
|
||||
path: "src/debug/macho/macho.go",
|
||||
user: "golang",
|
||||
repo: "go",
|
||||
},
|
||||
}, {
|
||||
index: 128,
|
||||
word: "https://gitlab.com/mattermost/mattermost-server/-/blob/cbb25838a61872b624ac512556d7bc932486a64c/app/authentication.go#L15-L22",
|
||||
permalinkData: struct {
|
||||
haswww string
|
||||
commit string
|
||||
user string
|
||||
repo string
|
||||
path string
|
||||
line string
|
||||
}{
|
||||
commit: "cbb25838a61872b624ac512556d7bc932486a64c",
|
||||
haswww: "",
|
||||
line: "L15-L22",
|
||||
path: "app/authentication.go",
|
||||
user: "mattermost",
|
||||
repo: "mattermost-server",
|
||||
},
|
||||
},
|
||||
},
|
||||
}, {
|
||||
name: "single line",
|
||||
input: "this is a one line permalink https://gitlab.com/mattermost/mattermost-server/-/blob/4225977966cf0855c8a5e55f8a0fef702b19dc18/api4/bot.go#L16",
|
||||
numReplacements: 1,
|
||||
replacements: []replacement{
|
||||
{
|
||||
index: 29,
|
||||
word: "https://gitlab.com/mattermost/mattermost-server/-/blob/4225977966cf0855c8a5e55f8a0fef702b19dc18/api4/bot.go#L16",
|
||||
permalinkData: struct {
|
||||
haswww string
|
||||
commit string
|
||||
user string
|
||||
repo string
|
||||
path string
|
||||
line string
|
||||
}{
|
||||
commit: "4225977966cf0855c8a5e55f8a0fef702b19dc18",
|
||||
haswww: "",
|
||||
line: "L16",
|
||||
path: "api4/bot.go",
|
||||
user: "mattermost",
|
||||
repo: "mattermost-server",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tcs {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
replacements := p.getPermalinkReplacements(tc.input)
|
||||
require.Equalf(t, tc.numReplacements, len(replacements), "unexpected number of replacements for %s", tc.input)
|
||||
for i, r := range replacements {
|
||||
assert.Equalf(t, tc.replacements[i].index, r.index, "unexpected replacement index")
|
||||
assert.Equalf(t, tc.replacements[i].word, r.word, "unexpected replacement word")
|
||||
assert.Equalf(t, tc.replacements[i].permalinkData.commit, r.permalinkData.commit, "unexpected gitlab commit")
|
||||
assert.Equalf(t, tc.replacements[i].permalinkData.haswww, r.permalinkData.haswww, "unexpected gitlab www domain")
|
||||
assert.Equalf(t, tc.replacements[i].permalinkData.line, r.permalinkData.line, "unexpected line number")
|
||||
assert.Equalf(t, tc.replacements[i].permalinkData.path, r.permalinkData.path, "unexpected file path")
|
||||
assert.Equalf(t, tc.replacements[i].permalinkData.user, r.permalinkData.user, "unexpected gitlab user")
|
||||
assert.Equalf(t, tc.replacements[i].permalinkData.repo, r.permalinkData.repo, "unexpected gitlab repo")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMakeReplacements(t *testing.T) {
|
||||
p := NewPlugin()
|
||||
p.configuration = &configuration{
|
||||
EnableCodePreview: "privateAndPublic",
|
||||
}
|
||||
mockPluginAPI := &plugintest.API{}
|
||||
mockPluginAPI.On("LogDebug", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything)
|
||||
mockPluginAPI.On("LogWarn", mock.Anything, mock.Anything)
|
||||
p.SetAPI(mockPluginAPI)
|
||||
|
||||
tcs := []struct {
|
||||
name string
|
||||
input string
|
||||
output string
|
||||
replacements []replacement
|
||||
}{
|
||||
{
|
||||
name: "basic one link",
|
||||
input: "start https://gitlab.com/mattermost/mattermost-server/-/blob/cbb25838a61872b624ac512556d7bc932486a64c/app/authentication.go#L15-L22 lorem ipsum",
|
||||
output: "start \n[mattermost/mattermost-server/app/authentication.go](https://gitlab.com/mattermost/mattermost-server/-/blob/cbb25838a61872b624ac512556d7bc932486a64c/app/authentication.go#L15-L22)\n```go\ntype TokenLocation int\n\nconst (\n\tTokenLocationNotFound TokenLocation = iota\n\tTokenLocationHeader\n\tTokenLocationCookie\n\tTokenLocationQueryString\n)\n```\n lorem ipsum",
|
||||
replacements: []replacement{
|
||||
{
|
||||
index: 6,
|
||||
word: "https://gitlab.com/mattermost/mattermost-server/-/blob/cbb25838a61872b624ac512556d7bc932486a64c/app/authentication.go#L15-L22",
|
||||
permalinkData: struct {
|
||||
haswww string
|
||||
commit string
|
||||
user string
|
||||
repo string
|
||||
path string
|
||||
line string
|
||||
}{
|
||||
haswww: "",
|
||||
commit: "cbb25838a61872b624ac512556d7bc932486a64c",
|
||||
line: "L15-L22",
|
||||
path: "app/authentication.go",
|
||||
user: "mattermost",
|
||||
repo: "mattermost-server",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "duplicate expansions",
|
||||
input: "start https://gitlab.com/mattermost/mattermost-server/-/blob/cbb25838a61872b624ac512556d7bc932486a64c/app/authentication.go#L15-L22 lorem ipsum https://gitlab.com/mattermost/mattermost-server/-/blob/cbb25838a61872b624ac512556d7bc932486a64c/app/authentication.go#L15-L22 lorem ipsum",
|
||||
output: "start \n[mattermost/mattermost-server/app/authentication.go](https://gitlab.com/mattermost/mattermost-server/-/blob/cbb25838a61872b624ac512556d7bc932486a64c/app/authentication.go#L15-L22)\n```go\ntype TokenLocation int\n\nconst (\n\tTokenLocationNotFound TokenLocation = iota\n\tTokenLocationHeader\n\tTokenLocationCookie\n\tTokenLocationQueryString\n)\n```\n lorem ipsum \n[mattermost/mattermost-server/app/authentication.go](https://gitlab.com/mattermost/mattermost-server/-/blob/cbb25838a61872b624ac512556d7bc932486a64c/app/authentication.go#L15-L22)\n```go\ntype TokenLocation int\n\nconst (\n\tTokenLocationNotFound TokenLocation = iota\n\tTokenLocationHeader\n\tTokenLocationCookie\n\tTokenLocationQueryString\n)\n```\n lorem ipsum",
|
||||
replacements: []replacement{
|
||||
{
|
||||
index: 6,
|
||||
word: "https://gitlab.com/mattermost/mattermost-server/-/blob/cbb25838a61872b624ac512556d7bc932486a64c/app/authentication.go#L15-L22",
|
||||
permalinkData: struct {
|
||||
haswww string
|
||||
commit string
|
||||
user string
|
||||
repo string
|
||||
path string
|
||||
line string
|
||||
}{
|
||||
commit: "cbb25838a61872b624ac512556d7bc932486a64c",
|
||||
haswww: "",
|
||||
line: "L15-L22",
|
||||
path: "app/authentication.go",
|
||||
user: "mattermost",
|
||||
repo: "mattermost-server",
|
||||
},
|
||||
}, {
|
||||
index: 142,
|
||||
word: "https://gitlab.com/mattermost/mattermost-server/-/blob/cbb25838a61872b624ac512556d7bc932486a64c/app/authentication.go#L15-L22",
|
||||
permalinkData: struct {
|
||||
haswww string
|
||||
commit string
|
||||
user string
|
||||
repo string
|
||||
path string
|
||||
line string
|
||||
}{
|
||||
commit: "cbb25838a61872b624ac512556d7bc932486a64c",
|
||||
haswww: "",
|
||||
line: "L15-L22",
|
||||
path: "app/authentication.go",
|
||||
user: "mattermost",
|
||||
repo: "mattermost-server",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "bad line range",
|
||||
input: "start https://gitlab.com/mattermost/mattermost-server/-/blob/cbb25838a61872b624ac512556d7bc932486a64c/app/authentication.go#L22-L15 lorem ipsum",
|
||||
output: "start https://gitlab.com/mattermost/mattermost-server/-/blob/cbb25838a61872b624ac512556d7bc932486a64c/app/authentication.go#L22-L15 lorem ipsum",
|
||||
replacements: []replacement{
|
||||
{
|
||||
index: 6,
|
||||
word: "https://gitlab.com/mattermost/mattermost-server/-/blob/cbb25838a61872b624ac512556d7bc932486a64c/app/authentication.go#L22-L15",
|
||||
permalinkData: struct {
|
||||
haswww string
|
||||
commit string
|
||||
user string
|
||||
repo string
|
||||
path string
|
||||
line string
|
||||
}{
|
||||
haswww: "",
|
||||
commit: "cbb25838a61872b624ac512556d7bc932486a64c",
|
||||
line: "L22-L15",
|
||||
path: "app/authentication.go",
|
||||
user: "mattermost",
|
||||
repo: "mattermost-server",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
client, close := getClient()
|
||||
defer close()
|
||||
|
||||
for _, tc := range tcs {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
msg := p.makeReplacements(tc.input, tc.replacements, client)
|
||||
assert.Equalf(t, tc.output, msg, "mismatched output")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const (
|
||||
baseURLPath = "/api/v4"
|
||||
requestURLPath = "/api/v4/projects/mattermost/mattermost-server/repository/files/app/authentication.go"
|
||||
)
|
||||
|
||||
func getClient() (*gitlab.Client, func()) {
|
||||
apiHandler := http.NewServeMux()
|
||||
apiHandler.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
|
||||
if req.URL.Path == requestURLPath {
|
||||
fmt.Fprintln(w, `{
|
||||
"file_name": "authentication.go",
|
||||
"file_path": "app/authentication.go",
|
||||
"size": 7950,
|
||||
"encoding": "base64",
|
||||
"content": "Ly8gQ29weXJpZ2h0IChjKSAyMDE2LXByZXNlbnQgTWF0dGVybW9zdCwgSW5j\nLiBBbGwgUmlnaHRzIFJlc2VydmVkLgovLyBTZWUgTGljZW5zZS50eHQgZm9y\nIGxpY2Vuc2UgaW5mb3JtYXRpb24uCgpwYWNrYWdlIGFwcAoKaW1wb3J0ICgK\nCSJuZXQvaHR0cCIKCSJzdHJpbmdzIgoKCSJnaXRodWIuY29tL21hdHRlcm1v\nc3QvbWF0dGVybW9zdC1zZXJ2ZXIvbW9kZWwiCgkiZ2l0aHViLmNvbS9tYXR0\nZXJtb3N0L21hdHRlcm1vc3Qtc2VydmVyL3NlcnZpY2VzL21mYSIKCSJnaXRo\ndWIuY29tL21hdHRlcm1vc3QvbWF0dGVybW9zdC1zZXJ2ZXIvdXRpbHMiCikK\nCnR5cGUgVG9rZW5Mb2NhdGlvbiBpbnQKCmNvbnN0ICgKCVRva2VuTG9jYXRp\nb25Ob3RGb3VuZCBUb2tlbkxvY2F0aW9uID0gaW90YQoJVG9rZW5Mb2NhdGlv\nbkhlYWRlcgoJVG9rZW5Mb2NhdGlvbkNvb2tpZQoJVG9rZW5Mb2NhdGlvblF1\nZXJ5U3RyaW5nCikKCmZ1bmMgKHRsIFRva2VuTG9jYXRpb24pIFN0cmluZygp\nIHN0cmluZyB7Cglzd2l0Y2ggdGwgewoJY2FzZSBUb2tlbkxvY2F0aW9uTm90\nRm91bmQ6CgkJcmV0dXJuICJOb3QgRm91bmQiCgljYXNlIFRva2VuTG9jYXRp\nb25IZWFkZXI6CgkJcmV0dXJuICJIZWFkZXIiCgljYXNlIFRva2VuTG9jYXRp\nb25Db29raWU6CgkJcmV0dXJuICJDb29raWUiCgljYXNlIFRva2VuTG9jYXRp\nb25RdWVyeVN0cmluZzoKCQlyZXR1cm4gIlF1ZXJ5U3RyaW5nIgoJZGVmYXVs\ndDoKCQlyZXR1cm4gIlVua25vd24iCgl9Cn0KCmZ1bmMgKGEgKkFwcCkgSXNQ\nYXNzd29yZFZhbGlkKHBhc3N3b3JkIHN0cmluZykgKm1vZGVsLkFwcEVycm9y\nIHsKCglpZiAqYS5Db25maWcoKS5TZXJ2aWNlU2V0dGluZ3MuRW5hYmxlRGV2\nZWxvcGVyIHsKCQlyZXR1cm4gbmlsCgl9CgoJcmV0dXJuIHV0aWxzLklzUGFz\nc3dvcmRWYWxpZFdpdGhTZXR0aW5ncyhwYXNzd29yZCwgJmEuQ29uZmlnKCku\nUGFzc3dvcmRTZXR0aW5ncykKfQoKZnVuYyAoYSAqQXBwKSBDaGVja1Bhc3N3\nb3JkQW5kQWxsQ3JpdGVyaWEodXNlciAqbW9kZWwuVXNlciwgcGFzc3dvcmQg\nc3RyaW5nLCBtZmFUb2tlbiBzdHJpbmcpICptb2RlbC5BcHBFcnJvciB7Cglp\nZiBlcnIgOj0gYS5DaGVja1VzZXJQcmVmbGlnaHRBdXRoZW50aWNhdGlvbkNy\naXRlcmlhKHVzZXIsIG1mYVRva2VuKTsgZXJyICE9IG5pbCB7CgkJcmV0dXJu\nIGVycgoJfQoKCWlmIGVyciA6PSBhLmNoZWNrVXNlclBhc3N3b3JkKHVzZXIs\nIHBhc3N3b3JkKTsgZXJyICE9IG5pbCB7CgkJaWYgcGFzc0VyciA6PSBhLlNy\ndi5TdG9yZS5Vc2VyKCkuVXBkYXRlRmFpbGVkUGFzc3dvcmRBdHRlbXB0cyh1\nc2VyLklkLCB1c2VyLkZhaWxlZEF0dGVtcHRzKzEpOyBwYXNzRXJyICE9IG5p\nbCB7CgkJCXJldHVybiBwYXNzRXJyCgkJfQoJCXJldHVybiBlcnIKCX0KCglp\nZiBlcnIgOj0gYS5DaGVja1VzZXJNZmEodXNlciwgbWZhVG9rZW4pOyBlcnIg\nIT0gbmlsIHsKCQkvLyBJZiB0aGUgbWZhVG9rZW4gaXMgbm90IHNldCwgd2Ug\nYXNzdW1lIHRoZSBjbGllbnQgdXNlZCB0aGlzIGFzIGEgcHJlLWZsaWdodCBy\nZXF1ZXN0IHRvIHF1ZXJ5IHRoZSBzZXJ2ZXIKCQkvLyBhYm91dCB0aGUgTUZB\nIHN0YXRlIG9mIHRoZSB1c2VyIGluIHF1ZXN0aW9uCgkJaWYgbWZhVG9rZW4g\nIT0gIiIgewoJCQlpZiBwYXNzRXJyIDo9IGEuU3J2LlN0b3JlLlVzZXIoKS5V\ncGRhdGVGYWlsZWRQYXNzd29yZEF0dGVtcHRzKHVzZXIuSWQsIHVzZXIuRmFp\nbGVkQXR0ZW1wdHMrMSk7IHBhc3NFcnIgIT0gbmlsIHsKCQkJCXJldHVybiBw\nYXNzRXJyCgkJCX0KCQl9CgkJcmV0dXJuIGVycgoJfQoKCWlmIHBhc3NFcnIg\nOj0gYS5TcnYuU3RvcmUuVXNlcigpLlVwZGF0ZUZhaWxlZFBhc3N3b3JkQXR0\nZW1wdHModXNlci5JZCwgMCk7IHBhc3NFcnIgIT0gbmlsIHsKCQlyZXR1cm4g\ncGFzc0VycgoJfQoKCWlmIGVyciA6PSBhLkNoZWNrVXNlclBvc3RmbGlnaHRB\ndXRoZW50aWNhdGlvbkNyaXRlcmlhKHVzZXIpOyBlcnIgIT0gbmlsIHsKCQly\nZXR1cm4gZXJyCgl9CgoJcmV0dXJuIG5pbAp9CgovLyBUaGlzIHRvIGJlIHVz\nZWQgZm9yIHBsYWNlcyB3ZSBjaGVjayB0aGUgdXNlcnMgcGFzc3dvcmQgd2hl\nbiB0aGV5IGFyZSBhbHJlYWR5IGxvZ2dlZCBpbgpmdW5jIChhICpBcHApIERv\ndWJsZUNoZWNrUGFzc3dvcmQodXNlciAqbW9kZWwuVXNlciwgcGFzc3dvcmQg\nc3RyaW5nKSAqbW9kZWwuQXBwRXJyb3IgewoJaWYgZXJyIDo9IGNoZWNrVXNl\nckxvZ2luQXR0ZW1wdHModXNlciwgKmEuQ29uZmlnKCkuU2VydmljZVNldHRp\nbmdzLk1heGltdW1Mb2dpbkF0dGVtcHRzKTsgZXJyICE9IG5pbCB7CgkJcmV0\ndXJuIGVycgoJfQoKCWlmIGVyciA6PSBhLmNoZWNrVXNlclBhc3N3b3JkKHVz\nZXIsIHBhc3N3b3JkKTsgZXJyICE9IG5pbCB7CgkJaWYgcGFzc0VyciA6PSBh\nLlNydi5TdG9yZS5Vc2VyKCkuVXBkYXRlRmFpbGVkUGFzc3dvcmRBdHRlbXB0\ncyh1c2VyLklkLCB1c2VyLkZhaWxlZEF0dGVtcHRzKzEpOyBwYXNzRXJyICE9\nIG5pbCB7CgkJCXJldHVybiBwYXNzRXJyCgkJfQoJCXJldHVybiBlcnIKCX0K\nCglpZiBwYXNzRXJyIDo9IGEuU3J2LlN0b3JlLlVzZXIoKS5VcGRhdGVGYWls\nZWRQYXNzd29yZEF0dGVtcHRzKHVzZXIuSWQsIDApOyBwYXNzRXJyICE9IG5p\nbCB7CgkJcmV0dXJuIHBhc3NFcnIKCX0KCglyZXR1cm4gbmlsCn0KCmZ1bmMg\n",
|
||||
"content_sha256": "c5c4ebf9077d04306ce8eca1e451421e4df7ca3c"
|
||||
}`)
|
||||
}
|
||||
})
|
||||
|
||||
// server is a test HTTP server used to provide mock API responses.
|
||||
server := httptest.NewServer(apiHandler)
|
||||
|
||||
// client is the GitLab client being tested and is
|
||||
// configured to use test server.
|
||||
url, _ := url.Parse(server.URL + baseURLPath + "/")
|
||||
client, _ := gitlab.NewOAuthClient("", gitlab.WithBaseURL(url.String()))
|
||||
|
||||
return client, server.Close
|
||||
}
|
||||
@@ -0,0 +1,872 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/mattermost/mattermost/server/public/model"
|
||||
"github.com/mattermost/mattermost/server/public/plugin"
|
||||
"github.com/mattermost/mattermost/server/public/pluginapi"
|
||||
"github.com/mattermost/mattermost/server/public/pluginapi/cluster"
|
||||
"github.com/mattermost/mattermost/server/public/pluginapi/experimental/bot/poster"
|
||||
"github.com/mattermost/mattermost/server/public/pluginapi/experimental/telemetry"
|
||||
"github.com/pkg/errors"
|
||||
gitlabLib "github.com/xanzy/go-gitlab"
|
||||
"golang.org/x/oauth2"
|
||||
|
||||
"github.com/mattermost/mattermost-plugin-gitlab/server/gitlab"
|
||||
"github.com/mattermost/mattermost-plugin-gitlab/server/webhook"
|
||||
)
|
||||
|
||||
const (
|
||||
GitlabUserInfoKey = "_userinfo"
|
||||
GitlabUserTokenKey = "_usertoken"
|
||||
GitlabMigrationTokenKey = "_gitlabtoken"
|
||||
TokenMutexKey = "-oauth-token" //#nosec G101 -- False positive
|
||||
GitlabUsernameKey = "_gitlabusername"
|
||||
GitlabIDUsernameKey = "_gitlabidusername"
|
||||
WsEventConnect = "gitlab_connect"
|
||||
WsEventDisconnect = "gitlab_disconnect"
|
||||
WsEventRefresh = "gitlab_refresh"
|
||||
WsChannelSubscriptionsUpdated = "gitlab_channel_subscriptions_updated"
|
||||
SettingNotifications = "notifications"
|
||||
SettingReminders = "reminders"
|
||||
SettingOn = "on"
|
||||
SettingOff = "off"
|
||||
|
||||
chimeraGitLabAppIdentifier = "plugin-gitlab"
|
||||
|
||||
NotificationActionNameMemberAccessRequest = "member_access_requested"
|
||||
|
||||
invalidTokenError = "401 {error: invalid_token}" //#nosec G101 -- False positive
|
||||
)
|
||||
|
||||
type Plugin struct {
|
||||
plugin.MattermostPlugin
|
||||
client *pluginapi.Client
|
||||
|
||||
// configurationLock synchronizes access to the configuration.
|
||||
configurationLock sync.RWMutex
|
||||
|
||||
// configuration is the active plugin configuration. Consult getConfiguration and
|
||||
// setConfiguration for usage.
|
||||
configuration *configuration
|
||||
|
||||
chimeraURL string
|
||||
|
||||
router *mux.Router
|
||||
|
||||
telemetryClient telemetry.Client
|
||||
tracker telemetry.Tracker
|
||||
|
||||
BotUserID string
|
||||
poster poster.Poster
|
||||
flowManager *FlowManager
|
||||
|
||||
oauthBroker *OAuthBroker
|
||||
|
||||
WebhookHandler webhook.Webhook
|
||||
GitlabClient gitlab.Gitlab
|
||||
}
|
||||
|
||||
// gitlabPermalinkRegex is used to parse gitlab permalinks in post messages.
|
||||
var gitlabPermalinkRegex = regexp.MustCompile(`https?://(?P<haswww>www\.)?gitlab\.com/(?P<user>[\w/.?-]+)/(?P<repo>[\w-]+)/-/blob/(?P<commit>\w+)/(?P<path>[\w-/.]+)#(?P<line>[\w-]+)?`)
|
||||
|
||||
// NewPlugin returns an instance of a Plugin.
|
||||
func NewPlugin() *Plugin {
|
||||
return &Plugin{}
|
||||
}
|
||||
|
||||
func (p *Plugin) OnActivate() error {
|
||||
if p.client == nil {
|
||||
p.client = pluginapi.NewClient(p.API, p.Driver)
|
||||
}
|
||||
siteURL := p.client.Configuration.GetConfig().ServiceSettings.SiteURL
|
||||
if siteURL == nil || *siteURL == "" {
|
||||
return errors.New("siteURL is not set. Please set it and restart the plugin")
|
||||
}
|
||||
|
||||
err := p.setDefaultConfiguration()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to set default configuration")
|
||||
}
|
||||
|
||||
p.registerChimeraURL()
|
||||
|
||||
if p.getConfiguration().UsePreregisteredApplication && p.chimeraURL == "" {
|
||||
return errors.New("cannot use pre-registered application if Chimera URL is not set or empty. " +
|
||||
"For now using pre-registered application is intended for Cloud instances only. " +
|
||||
"If you are running on-prem disable the setting and use a custom application, otherwise set PluginSettings.ChimeraOAuthProxyURL " +
|
||||
"or MM_PLUGINSETTINGS_CHIMERAOAUTHPROXYURL environment variable")
|
||||
}
|
||||
|
||||
p.initializeAPI()
|
||||
p.initializeTelemetry()
|
||||
|
||||
p.oauthBroker = NewOAuthBroker(p.sendOAuthCompleteEvent)
|
||||
|
||||
botID, err := p.client.Bot.EnsureBot(&model.Bot{
|
||||
OwnerId: manifest.Id, // Workaround to support older server version affected by https://github.com/mattermost/mattermost-server/pull/21560
|
||||
Username: "gitlab",
|
||||
DisplayName: "GitLab Plugin",
|
||||
Description: "A bot account created by the plugin GitLab.",
|
||||
}, pluginapi.ProfileImagePath(filepath.Join("assets", "profile.png")))
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "can't ensure bot")
|
||||
}
|
||||
p.BotUserID = botID
|
||||
|
||||
p.WebhookHandler = webhook.NewWebhook(&gitlabRetreiver{p: p})
|
||||
|
||||
p.poster = poster.NewPoster(&p.client.Post, p.BotUserID)
|
||||
p.flowManager = p.NewFlowManager()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Plugin) OnDeactivate() error {
|
||||
p.oauthBroker.Close()
|
||||
|
||||
if err := p.telemetryClient.Close(); err != nil {
|
||||
p.client.Log.Warn("Telemetry client failed to close", "error", err.Error())
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Plugin) OnInstall(c *plugin.Context, event model.OnInstallEvent) error {
|
||||
conf := p.getConfiguration()
|
||||
|
||||
// Don't start wizard if OAuth is configured
|
||||
if conf.IsOAuthConfigured() {
|
||||
p.client.Log.Debug("OAuth is configured, skipping setup wizard",
|
||||
"GitlabOAuthClientID", lastN(conf.GitlabOAuthClientID, 4),
|
||||
"GitlabOAuthClientSecret", lastN(conf.GitlabOAuthClientSecret, 4),
|
||||
"UsePreregisteredApplication", conf.UsePreregisteredApplication)
|
||||
return nil
|
||||
}
|
||||
|
||||
return p.flowManager.StartSetupWizard(event.UserId, "")
|
||||
}
|
||||
|
||||
func (p *Plugin) OnSendDailyTelemetry() {
|
||||
p.SendDailyTelemetry()
|
||||
}
|
||||
|
||||
func (p *Plugin) OnPluginClusterEvent(c *plugin.Context, ev model.PluginClusterEvent) {
|
||||
p.HandleClusterEvent(ev)
|
||||
}
|
||||
|
||||
func (p *Plugin) UserHasBeenDeactivated(c *plugin.Context, user *model.User) {
|
||||
if info, _ := p.getGitlabUserInfoByMattermostID(user.Id); info != nil {
|
||||
p.disconnectGitlabAccount(user.Id)
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Plugin) MessageWillBePosted(c *plugin.Context, post *model.Post) (*model.Post, string) {
|
||||
// If not enabled in config, ignore.
|
||||
if p.getConfiguration().EnableCodePreview == "disable" {
|
||||
return nil, ""
|
||||
}
|
||||
|
||||
if post.UserId == "" {
|
||||
return nil, ""
|
||||
}
|
||||
|
||||
msg := post.Message
|
||||
replacements := p.getPermalinkReplacements(msg)
|
||||
if len(replacements) == 0 {
|
||||
return nil, ""
|
||||
}
|
||||
info, err := p.getGitlabUserInfoByMattermostID(post.UserId)
|
||||
if err != nil {
|
||||
if err.ID == APIErrorIDNotConnected {
|
||||
p.API.LogDebug("Error while processing permalinks in the post", "Error", err.Error())
|
||||
} else {
|
||||
p.API.LogDebug("Error in getting user info", "Error", err.Error())
|
||||
}
|
||||
return nil, ""
|
||||
}
|
||||
|
||||
var glClient *gitlabLib.Client
|
||||
if cErr := p.useGitlabClient(info, func(info *gitlab.UserInfo, token *oauth2.Token) error {
|
||||
resp, err := p.GitlabClient.GitlabConnect(*token)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
glClient = resp
|
||||
return nil
|
||||
}); cErr != nil {
|
||||
p.API.LogDebug("Error in getting GitLab client", "Error", cErr.Error())
|
||||
return nil, ""
|
||||
}
|
||||
|
||||
post.Message = p.makeReplacements(msg, replacements, glClient)
|
||||
return post, ""
|
||||
}
|
||||
|
||||
func (p *Plugin) setDefaultConfiguration() error {
|
||||
config := p.getConfiguration()
|
||||
|
||||
changed, err := config.setDefaults(pluginapi.IsCloud(p.client.System.GetLicense()))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if changed {
|
||||
configMap, err := config.ToMap()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = p.client.Configuration.SavePluginConfig(configMap)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Plugin) getGitlabClient() gitlab.Gitlab {
|
||||
return p.GitlabClient
|
||||
}
|
||||
|
||||
func (p *Plugin) getOAuthConfig() *oauth2.Config {
|
||||
config := p.getConfiguration()
|
||||
|
||||
scopes := []string{"api", "read_user"}
|
||||
redirectURL := fmt.Sprintf("%s/plugins/%s/oauth/complete", *p.client.Configuration.GetConfig().ServiceSettings.SiteURL, manifest.Id)
|
||||
|
||||
if config.UsePreregisteredApplication {
|
||||
p.client.Log.Debug("Using Chimera Proxy OAuth configuration")
|
||||
return p.getOAuthConfigForChimeraApp(scopes, redirectURL)
|
||||
}
|
||||
|
||||
authURL, _ := url.Parse(config.GitlabURL)
|
||||
tokenURL, _ := url.Parse(config.GitlabURL)
|
||||
|
||||
authURL.Path = path.Join(authURL.Path, "oauth", "authorize")
|
||||
tokenURL.Path = path.Join(tokenURL.Path, "oauth", "token")
|
||||
|
||||
return &oauth2.Config{
|
||||
ClientID: config.GitlabOAuthClientID,
|
||||
ClientSecret: config.GitlabOAuthClientSecret,
|
||||
Scopes: scopes,
|
||||
RedirectURL: redirectURL,
|
||||
Endpoint: oauth2.Endpoint{
|
||||
AuthURL: authURL.String(),
|
||||
TokenURL: tokenURL.String(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Plugin) getOAuthConfigForChimeraApp(scopes []string, redirectURL string) *oauth2.Config {
|
||||
baseURL := fmt.Sprintf("%s/v1/gitlab/%s", p.chimeraURL, chimeraGitLabAppIdentifier)
|
||||
authURL, _ := url.Parse(baseURL)
|
||||
tokenURL, _ := url.Parse(baseURL)
|
||||
|
||||
authURL.Path = path.Join(authURL.Path, "oauth", "authorize")
|
||||
tokenURL.Path = path.Join(tokenURL.Path, "oauth", "token")
|
||||
|
||||
return &oauth2.Config{
|
||||
ClientID: "placeholder",
|
||||
ClientSecret: "placeholder",
|
||||
Scopes: scopes,
|
||||
RedirectURL: redirectURL,
|
||||
Endpoint: oauth2.Endpoint{
|
||||
AuthURL: authURL.String(),
|
||||
TokenURL: tokenURL.String(),
|
||||
AuthStyle: oauth2.AuthStyleInHeader,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Plugin) storeGitlabUserInfo(info *gitlab.UserInfo) error {
|
||||
jsonInfo, err := json.Marshal(info)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := p.client.KV.Set(info.UserID+GitlabUserInfoKey, jsonInfo); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Plugin) storeGitlabUserToken(userID string, token *oauth2.Token) error {
|
||||
config := p.getConfiguration()
|
||||
|
||||
jsonToken, err := json.Marshal(token)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
encryptedToken, err := encrypt([]byte(config.EncryptionKey), string(jsonToken))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := p.client.KV.Set(userID+GitlabUserTokenKey, []byte(encryptedToken)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Plugin) deleteGitlabUserInfo(userID string) error {
|
||||
if err := p.client.KV.Delete(userID + GitlabUserInfoKey); err != nil {
|
||||
return errors.Wrap(err, "encountered error deleting GitLab user info")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Plugin) deleteGitlabUserToken(userID string) error {
|
||||
if err := p.client.KV.Delete(userID + GitlabUserTokenKey); err != nil {
|
||||
return errors.Wrap(err, "encountered error deleting GitLab user token")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Plugin) getGitlabUserInfoByMattermostID(userID string) (*gitlab.UserInfo, *APIErrorResponse) {
|
||||
var userInfo gitlab.UserInfo
|
||||
|
||||
var infoBytes []byte
|
||||
err := p.client.KV.Get(userID+GitlabUserInfoKey, &infoBytes)
|
||||
|
||||
if err != nil || infoBytes == nil {
|
||||
var gitlabTokenBytes []byte
|
||||
appErr := p.client.KV.Get(userID+GitlabMigrationTokenKey, &gitlabTokenBytes)
|
||||
if appErr != nil || gitlabTokenBytes == nil {
|
||||
return nil, &APIErrorResponse{ID: APIErrorIDNotConnected, Message: "Must connect user account to GitLab first.", StatusCode: http.StatusBadRequest}
|
||||
}
|
||||
if err := json.Unmarshal(gitlabTokenBytes, &userInfo); err != nil {
|
||||
return nil, &APIErrorResponse{ID: "", Message: "Unable to parse user info from migration key.", StatusCode: http.StatusInternalServerError}
|
||||
}
|
||||
} else if err := json.Unmarshal(infoBytes, &userInfo); err != nil {
|
||||
return nil, &APIErrorResponse{ID: "", Message: "Unable to parse user info.", StatusCode: http.StatusInternalServerError}
|
||||
}
|
||||
|
||||
return &userInfo, nil
|
||||
}
|
||||
|
||||
func (p *Plugin) migrateGitlabToken(userID string) (*oauth2.Token, *APIErrorResponse) {
|
||||
config := p.getConfiguration()
|
||||
|
||||
var userInfo struct {
|
||||
gitlab.UserInfo
|
||||
Token *oauth2.Token
|
||||
}
|
||||
|
||||
mutex, err := cluster.NewMutex(p.API, userID+TokenMutexKey)
|
||||
if err != nil {
|
||||
return nil, &APIErrorResponse{ID: "", Message: "Unable to obtain mutex for KV migration.", StatusCode: http.StatusInternalServerError}
|
||||
}
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
|
||||
var gitlabTokenBytes []byte
|
||||
err = p.client.KV.Get(userID+GitlabMigrationTokenKey, &gitlabTokenBytes)
|
||||
if err != nil || gitlabTokenBytes == nil {
|
||||
return p.getGitlabUserTokenByMattermostID(userID)
|
||||
}
|
||||
|
||||
if err = json.Unmarshal(gitlabTokenBytes, &userInfo); err != nil {
|
||||
return nil, &APIErrorResponse{ID: "", Message: "Unable to parse user info for KV migration.", StatusCode: http.StatusInternalServerError}
|
||||
}
|
||||
|
||||
unencryptedToken, err := decrypt([]byte(config.EncryptionKey), userInfo.Token.AccessToken)
|
||||
if err != nil {
|
||||
return nil, &APIErrorResponse{ID: "", Message: "Unable to decrypt token for KV migration.", StatusCode: http.StatusInternalServerError}
|
||||
}
|
||||
|
||||
userInfo.Token.AccessToken = unencryptedToken
|
||||
|
||||
var userInfoWithoutToken = &gitlab.UserInfo{
|
||||
UserID: userInfo.UserID,
|
||||
GitlabUserID: userInfo.GitlabUserID,
|
||||
GitlabUsername: userInfo.GitlabUsername,
|
||||
LastToDoPostAt: userInfo.LastToDoPostAt,
|
||||
Settings: userInfo.Settings,
|
||||
}
|
||||
|
||||
if err = p.storeGitlabUserInfo(userInfoWithoutToken); err != nil {
|
||||
return nil, &APIErrorResponse{ID: "", Message: "Unable to store user info for KV migration.", StatusCode: http.StatusInternalServerError}
|
||||
}
|
||||
|
||||
if err = p.storeGitlabUserToken(userInfo.UserID, userInfo.Token); err != nil {
|
||||
return nil, &APIErrorResponse{ID: "", Message: "Unable to store token for KV migration.", StatusCode: http.StatusInternalServerError}
|
||||
}
|
||||
|
||||
if err = p.client.KV.Delete(userInfo.UserID + GitlabMigrationTokenKey); err != nil {
|
||||
return nil, &APIErrorResponse{ID: "", Message: "Unable to delete KV entry for migration.", StatusCode: http.StatusInternalServerError}
|
||||
}
|
||||
|
||||
return userInfo.Token, nil
|
||||
}
|
||||
|
||||
func (p *Plugin) getGitlabUserTokenByMattermostID(userID string) (*oauth2.Token, *APIErrorResponse) {
|
||||
config := p.getConfiguration()
|
||||
var token oauth2.Token
|
||||
|
||||
var tokenBytes []byte
|
||||
err := p.client.KV.Get(userID+GitlabUserTokenKey, &tokenBytes)
|
||||
if err != nil || tokenBytes == nil {
|
||||
return nil, &APIErrorResponse{ID: APIErrorIDNotConnected, Message: "Must connect user account to GitLab first.", StatusCode: http.StatusBadRequest}
|
||||
}
|
||||
|
||||
unencryptedToken, err := decrypt([]byte(config.EncryptionKey), string(tokenBytes))
|
||||
if err != nil {
|
||||
p.client.Log.Warn("can't decrypt token", "err", err.Error())
|
||||
return nil, &APIErrorResponse{ID: "", Message: "Unable to decrypt access token.", StatusCode: http.StatusInternalServerError}
|
||||
}
|
||||
|
||||
if err := json.Unmarshal([]byte(unencryptedToken), &token); err != nil {
|
||||
return nil, &APIErrorResponse{ID: "", Message: "Unable to parse token.", StatusCode: http.StatusInternalServerError}
|
||||
}
|
||||
|
||||
return &token, nil
|
||||
}
|
||||
|
||||
func (p *Plugin) storeGitlabToUserIDMapping(gitlabUsername, userID string) error {
|
||||
if _, err := p.client.KV.Set(gitlabUsername+GitlabUsernameKey, []byte(userID)); err != nil {
|
||||
return errors.Wrap(err, "encountered error saving GitLab username mapping")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Plugin) storeGitlabIDToUserIDMapping(gitlabUsername string, gitlabID int) error {
|
||||
if _, err := p.client.KV.Set(fmt.Sprintf("%d%s", gitlabID, GitlabIDUsernameKey), []byte(gitlabUsername)); err != nil {
|
||||
return errors.Wrap(err, "encountered error saving GitLab id mapping")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Plugin) deleteGitlabToUserIDMapping(gitlabUsername string) error {
|
||||
if err := p.client.KV.Delete(gitlabUsername + GitlabUsernameKey); err != nil {
|
||||
return errors.Wrap(err, "encountered error deleting GitLab username mapping")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Plugin) deleteGitlabIDToUserIDMapping(gitlabID int) error {
|
||||
if err := p.client.KV.Delete(fmt.Sprintf("%d%s", gitlabID, GitlabIDUsernameKey)); err != nil {
|
||||
return errors.Wrap(err, "encountered error deleting GitLab id mapping")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Plugin) getGitlabToUserIDMapping(gitlabUsername string) string {
|
||||
var userID []byte
|
||||
err := p.client.KV.Get(gitlabUsername+GitlabUsernameKey, &userID)
|
||||
if err != nil {
|
||||
p.client.Log.Warn("can't get userId from store with username", "err", err.Error(), "username", gitlabUsername)
|
||||
}
|
||||
return string(userID)
|
||||
}
|
||||
|
||||
func (p *Plugin) getGitlabIDToUsernameMapping(gitlabUserID string) string {
|
||||
var gitlabUsername []byte
|
||||
err := p.client.KV.Get(gitlabUserID+GitlabIDUsernameKey, &gitlabUsername)
|
||||
if err != nil {
|
||||
p.client.Log.Warn("can't get user id by login", "err", err.Error())
|
||||
}
|
||||
return string(gitlabUsername)
|
||||
}
|
||||
|
||||
func (p *Plugin) disconnectGitlabAccount(userID string) {
|
||||
userInfo, err := p.getGitlabUserInfoByMattermostID(userID)
|
||||
if err != nil {
|
||||
p.client.Log.Warn("can't get GitLab user info from mattermost id", "err", err.Message)
|
||||
return
|
||||
}
|
||||
if userInfo == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if err := p.deleteGitlabUserInfo(userID); err != nil {
|
||||
p.client.Log.Warn("can't delete user info in store", "err", err.Error, "userId", userID)
|
||||
}
|
||||
if err := p.deleteGitlabUserToken(userID); err != nil {
|
||||
p.client.Log.Warn("can't delete token in store", "err", err.Error, "userId", userID)
|
||||
}
|
||||
if err := p.deleteGitlabToUserIDMapping(userInfo.GitlabUsername); err != nil {
|
||||
p.client.Log.Warn("can't delete username in store", "err", err.Error, "username", userInfo.GitlabUsername)
|
||||
}
|
||||
if err := p.deleteGitlabIDToUserIDMapping(userInfo.GitlabUserID); err != nil {
|
||||
p.client.Log.Warn("can't delete user id in store", "err", err.Error, "id", userInfo.GitlabUserID)
|
||||
}
|
||||
|
||||
if user, err := p.client.User.Get(userID); err == nil && user.Props != nil && len(user.Props["git_user"]) > 0 {
|
||||
delete(user.Props, "git_user")
|
||||
if err := p.client.User.Update(user); err != nil {
|
||||
p.client.Log.Warn("can't update user after delete git account", "err", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
p.client.Frontend.PublishWebSocketEvent(
|
||||
WsEventDisconnect,
|
||||
nil,
|
||||
&model.WebsocketBroadcast{UserId: userID},
|
||||
)
|
||||
}
|
||||
|
||||
// registerChimeraURL fetches the Chimera URL from server settings or env var and sets it in the plugin object.
|
||||
func (p *Plugin) registerChimeraURL() {
|
||||
chimeraURLSetting := p.client.Configuration.GetConfig().PluginSettings.ChimeraOAuthProxyURL
|
||||
if chimeraURLSetting != nil && *chimeraURLSetting != "" {
|
||||
p.chimeraURL = *chimeraURLSetting
|
||||
return
|
||||
}
|
||||
// Due to setting name change in v6 (ChimeraOAuthProxyUrl -> ChimeraOAuthProxyURL)
|
||||
// fall back to env var to work with older servers.
|
||||
p.chimeraURL = os.Getenv("MM_PLUGINSETTINGS_CHIMERAOAUTHPROXYURL")
|
||||
}
|
||||
|
||||
func (p *Plugin) CreateBotDMPost(userID, message, postType string) error {
|
||||
channel, err := p.client.Channel.GetDirect(userID, p.BotUserID)
|
||||
if err != nil {
|
||||
p.client.Log.Warn("Couldn't get bot's DM channel", "user_id", userID)
|
||||
return err
|
||||
}
|
||||
|
||||
post := &model.Post{
|
||||
UserId: p.BotUserID,
|
||||
ChannelId: channel.Id,
|
||||
Message: message,
|
||||
Type: postType,
|
||||
}
|
||||
|
||||
if err := p.client.Post.CreatePost(post); err != nil {
|
||||
p.client.Log.Warn("can't post DM", "err", err.Error())
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Plugin) PostToDo(ctx context.Context, info *gitlab.UserInfo) {
|
||||
hasTodo, text, err := p.GetToDo(ctx, info)
|
||||
if err != nil {
|
||||
p.client.Log.Warn("can't post todo", "err", err.Error())
|
||||
return
|
||||
}
|
||||
if !hasTodo {
|
||||
return
|
||||
}
|
||||
|
||||
if err := p.CreateBotDMPost(info.UserID, text, "custom_git_todo"); err != nil {
|
||||
p.client.Log.Warn("can't create dm post in post todo", "err", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Plugin) GetToDo(ctx context.Context, user *gitlab.UserInfo) (bool, string, error) {
|
||||
hasTodo := false
|
||||
|
||||
var notificationText, reviewText, assignmentText, mergeRequestText string
|
||||
err := p.useGitlabClient(user, func(info *gitlab.UserInfo, token *oauth2.Token) error {
|
||||
resp, err := p.GitlabClient.GetLHSData(ctx, info, token)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
todos := resp.Todos
|
||||
notificationCount := 0
|
||||
notificationContent := ""
|
||||
|
||||
for _, n := range todos {
|
||||
if n == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
if n.Project != nil && p.isNamespaceAllowed(n.Project.NameWithNamespace) != nil {
|
||||
continue
|
||||
}
|
||||
notificationCount++
|
||||
|
||||
switch n.ActionName {
|
||||
// Handle special cases where the provided "Title" value is blank
|
||||
case NotificationActionNameMemberAccessRequest:
|
||||
notificationContent += fmt.Sprintf("* %v : [%v](%v) has requested access to [%v](%v)\n", n.ActionName, n.Author.Name, n.Author.WebURL, n.Body, n.TargetURL)
|
||||
default:
|
||||
notificationContent += fmt.Sprintf("* %v : [%v](%v)\n", n.ActionName, n.Target.Title, n.TargetURL)
|
||||
}
|
||||
}
|
||||
|
||||
if notificationCount == 0 {
|
||||
notificationText += "You don't have any todos.\n"
|
||||
} else {
|
||||
notificationText += fmt.Sprintf("You have %v todos:\n", notificationCount)
|
||||
notificationText += notificationContent
|
||||
|
||||
hasTodo = true
|
||||
}
|
||||
|
||||
reviews := resp.Reviews
|
||||
if len(reviews) == 0 {
|
||||
reviewText += "You don't have any merge requests awaiting your review.\n"
|
||||
} else {
|
||||
reviewText += fmt.Sprintf("You have %v merge requests awaiting your review:\n", len(reviews))
|
||||
|
||||
for _, pr := range reviews {
|
||||
reviewText += fmt.Sprintf("* [%v](%v)\n", pr.Title, pr.WebURL)
|
||||
}
|
||||
|
||||
hasTodo = true
|
||||
}
|
||||
|
||||
yourAssignedIssues := resp.AssignedIssues
|
||||
if len(yourAssignedIssues) == 0 {
|
||||
assignmentText += "You don't have any issues awaiting your dev.\n"
|
||||
} else {
|
||||
assignmentText += fmt.Sprintf("You have %v issues awaiting dev:\n", len(yourAssignedIssues))
|
||||
|
||||
for _, pr := range yourAssignedIssues {
|
||||
assignmentText += fmt.Sprintf("* [%v](%v)\n", pr.Title, pr.WebURL)
|
||||
}
|
||||
|
||||
hasTodo = true
|
||||
}
|
||||
|
||||
mergeRequests := resp.AssignedPRs
|
||||
if len(mergeRequests) == 0 {
|
||||
mergeRequestText += "You don't have any merge requests assigned.\n"
|
||||
} else {
|
||||
mergeRequestText += fmt.Sprintf("You have %v merge requests assigned:\n", len(mergeRequests))
|
||||
|
||||
for _, pr := range mergeRequests {
|
||||
mergeRequestText += fmt.Sprintf("* [%v](%v)\n", pr.Title, pr.WebURL)
|
||||
}
|
||||
|
||||
hasTodo = true
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return false, "", err
|
||||
}
|
||||
|
||||
text := "##### To-Do list\n"
|
||||
text += notificationText
|
||||
|
||||
text += "##### Review Requests\n"
|
||||
text += reviewText
|
||||
|
||||
text += "##### Issues\n"
|
||||
text += assignmentText
|
||||
|
||||
text += "##### Merge Requests Assigned\n"
|
||||
text += mergeRequestText
|
||||
|
||||
return hasTodo, text, nil
|
||||
}
|
||||
|
||||
func (p *Plugin) isNamespaceAllowed(namespace string) error {
|
||||
allowedNamespace := strings.TrimSpace(p.getConfiguration().GitlabGroup)
|
||||
if allowedNamespace != "" && allowedNamespace != namespace && !strings.HasPrefix(namespace, allowedNamespace) {
|
||||
return errors.Errorf("only repositories in the %s namespace are allowed", allowedNamespace)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Plugin) sendRefreshEvent(userID string) {
|
||||
p.client.Frontend.PublishWebSocketEvent(
|
||||
WsEventRefresh,
|
||||
nil,
|
||||
&model.WebsocketBroadcast{UserId: userID},
|
||||
)
|
||||
}
|
||||
|
||||
func (p *Plugin) sendChannelSubscriptionsUpdated(subs *Subscriptions, channelID string) {
|
||||
config := p.getConfiguration()
|
||||
|
||||
subscriptions := filterSubscriptionsByChannel(subs, channelID)
|
||||
|
||||
var payload struct {
|
||||
ChannelID string `json:"channel_id"`
|
||||
Subscriptions []SubscriptionResponse `json:"subscriptions"`
|
||||
}
|
||||
payload.ChannelID = channelID
|
||||
payload.Subscriptions = subscriptionsToResponse(config, subscriptions)
|
||||
|
||||
payloadJSON, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
p.client.Log.Warn(
|
||||
"unable to marshal payload for updated channel subscriptions",
|
||||
"err", err.Error(),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
p.client.Frontend.PublishWebSocketEvent(
|
||||
WsChannelSubscriptionsUpdated,
|
||||
map[string]interface{}{"payload": string(payloadJSON)},
|
||||
&model.WebsocketBroadcast{ChannelId: channelID},
|
||||
)
|
||||
}
|
||||
|
||||
// HasProjectHook checks if the subscribed GitLab Project or its parrent Group has a webhook
|
||||
// with a URL that matches the Mattermost Site URL.
|
||||
func (p *Plugin) HasProjectHook(ctx context.Context, user *gitlab.UserInfo, namespace string, project string) (bool, error) {
|
||||
var hooks []*gitlab.WebhookInfo
|
||||
err := p.useGitlabClient(user, func(info *gitlab.UserInfo, token *oauth2.Token) error {
|
||||
resp, err := p.GitlabClient.GetProjectHooks(ctx, info, token, namespace, project)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
hooks = resp
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return false, errors.New("unable to connect to GitLab")
|
||||
}
|
||||
|
||||
// ignore error because many project won't be part of groups
|
||||
hasGroupHook, _ := p.HasGroupHook(ctx, user, namespace)
|
||||
|
||||
if hasGroupHook {
|
||||
return true, err
|
||||
}
|
||||
|
||||
siteURL := *p.client.Configuration.GetConfig().ServiceSettings.SiteURL
|
||||
|
||||
found := false
|
||||
for _, hook := range hooks {
|
||||
if strings.Contains(hook.URL, siteURL) {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
return found, nil
|
||||
}
|
||||
|
||||
// HasGroupHook checks if the subscribed GitLab Group has a webhook
|
||||
// with a URL that matches the Mattermost Site URL.
|
||||
func (p *Plugin) HasGroupHook(ctx context.Context, user *gitlab.UserInfo, namespace string) (bool, error) {
|
||||
var hooks []*gitlab.WebhookInfo
|
||||
err := p.useGitlabClient(user, func(info *gitlab.UserInfo, token *oauth2.Token) error {
|
||||
resp, err := p.GitlabClient.GetGroupHooks(ctx, info, token, namespace)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
hooks = resp
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return false, errors.New("unable to connect to GitLab")
|
||||
}
|
||||
|
||||
siteURL := *p.client.Configuration.GetConfig().ServiceSettings.SiteURL
|
||||
|
||||
found := false
|
||||
for _, hook := range hooks {
|
||||
if strings.Contains(hook.URL, siteURL) {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
|
||||
return found, err
|
||||
}
|
||||
|
||||
func (p *Plugin) refreshToken(userInfo *gitlab.UserInfo, token *oauth2.Token) (*oauth2.Token, error) {
|
||||
conf := p.getOAuthConfig()
|
||||
src := conf.TokenSource(context.Background(), token)
|
||||
|
||||
newToken, err := src.Token() // this actually goes and renews the tokens
|
||||
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "\"error\":\"invalid_grant\"") {
|
||||
p.handleRevokedToken(userInfo)
|
||||
}
|
||||
return nil, errors.Wrap(err, "unable to get the new refreshed token")
|
||||
}
|
||||
|
||||
if newToken.AccessToken != token.AccessToken {
|
||||
p.client.Log.Debug("Gitlab token refreshed.", "UserID", userInfo.UserID)
|
||||
|
||||
if err := p.storeGitlabUserToken(userInfo.UserID, newToken); err != nil {
|
||||
return nil, errors.Wrap(err, "unable to store user info with refreshed token")
|
||||
}
|
||||
|
||||
return newToken, nil
|
||||
}
|
||||
|
||||
return token, nil
|
||||
}
|
||||
|
||||
func (p *Plugin) handleRevokedToken(info *gitlab.UserInfo) {
|
||||
p.disconnectGitlabAccount(info.UserID)
|
||||
err := p.CreateBotDMPost(info.UserID, "Your GitLab account was disconnected due to an invalid or revoked authorization token. Reconnect your account using the `/gitlab connect` command.", "custom_git_revoked_token")
|
||||
|
||||
if err != nil {
|
||||
p.client.Log.Warn("Error sending revoked token DM post", "err", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Plugin) getOrRefreshTokenWithMutex(info *gitlab.UserInfo) (*oauth2.Token, error) {
|
||||
token, apiErr := p.getGitlabUserTokenByMattermostID(info.UserID)
|
||||
|
||||
if apiErr != nil {
|
||||
token, apiErr = p.migrateGitlabToken(info.UserID)
|
||||
if apiErr != nil {
|
||||
return nil, apiErr
|
||||
}
|
||||
}
|
||||
|
||||
if time.Until(token.Expiry) > 1*time.Minute {
|
||||
return token, nil
|
||||
}
|
||||
|
||||
mutex, err := cluster.NewMutex(p.API, info.UserID+TokenMutexKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
|
||||
lockedToken, apiErr := p.getGitlabUserTokenByMattermostID(info.UserID)
|
||||
if apiErr != nil {
|
||||
return nil, apiErr
|
||||
}
|
||||
|
||||
if time.Until(lockedToken.Expiry) > 1*time.Minute {
|
||||
return lockedToken, nil
|
||||
}
|
||||
|
||||
newToken, err := p.refreshToken(info, lockedToken)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return newToken, nil
|
||||
}
|
||||
|
||||
func (p *Plugin) useGitlabClient(info *gitlab.UserInfo, toRun func(info *gitlab.UserInfo, token *oauth2.Token) error) error {
|
||||
token, err := p.getOrRefreshTokenWithMutex(info)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = toRun(info, token)
|
||||
|
||||
if err != nil && strings.Contains(err.Error(), invalidTokenError) {
|
||||
p.handleRevokedToken(info)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package subscription
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
var allFeatures = map[string]bool{
|
||||
"merges": true,
|
||||
"jobs": true,
|
||||
"issues": true,
|
||||
"pushes": true,
|
||||
"issue_comments": true,
|
||||
"merge_request_comments": true,
|
||||
"pipeline": true,
|
||||
"tag": true,
|
||||
"pull_reviews": true,
|
||||
"confidential_issues": true,
|
||||
// "label:": true,//particular case for label:XXX
|
||||
}
|
||||
|
||||
type Subscription struct {
|
||||
ChannelID string
|
||||
CreatorID string
|
||||
Features string
|
||||
Repository string
|
||||
}
|
||||
|
||||
func New(channelID, creatorID, features, repository string) (*Subscription, error) {
|
||||
if strings.Contains(features, "label:") && len(strings.Split(features, "\"")) < 3 {
|
||||
return nil, errors.New("the label is formatted incorrectly")
|
||||
}
|
||||
if strings.Contains(features, "label:") && len(strings.Split(features, "\"")) > 3 {
|
||||
return nil, errors.New("can't add multiple labels on the same subscription")
|
||||
}
|
||||
|
||||
badFeatures := make([]string, 0)
|
||||
for _, feature := range strings.Split(features, ",") {
|
||||
if _, ok := allFeatures[feature]; !strings.HasPrefix(feature, "label:") && !ok {
|
||||
badFeatures = append(badFeatures, feature)
|
||||
}
|
||||
}
|
||||
if len(badFeatures) > 0 {
|
||||
return nil, errors.Errorf("unknown features %s", strings.Join(badFeatures, ","))
|
||||
}
|
||||
return &Subscription{
|
||||
ChannelID: channelID,
|
||||
CreatorID: creatorID,
|
||||
Features: features,
|
||||
Repository: repository,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Subscription) Merges() bool {
|
||||
return strings.Contains(s.Features, "merges")
|
||||
}
|
||||
|
||||
func (s *Subscription) Jobs() bool {
|
||||
return strings.Contains(s.Features, "jobs")
|
||||
}
|
||||
|
||||
func (s *Subscription) Issues() bool {
|
||||
return strings.Contains(s.Features, "issues")
|
||||
}
|
||||
|
||||
func (s *Subscription) ConfidentialIssues() bool {
|
||||
return strings.Contains(s.Features, "confidential_issues")
|
||||
}
|
||||
|
||||
func (s *Subscription) Pushes() bool {
|
||||
return strings.Contains(s.Features, "pushes")
|
||||
}
|
||||
|
||||
func (s *Subscription) IssueComments() bool {
|
||||
return strings.Contains(s.Features, "issue_comments")
|
||||
}
|
||||
|
||||
func (s *Subscription) MergeRequestComments() bool {
|
||||
return strings.Contains(s.Features, "merge_request_comments")
|
||||
}
|
||||
|
||||
func (s *Subscription) Pipeline() bool {
|
||||
return strings.Contains(s.Features, "pipeline")
|
||||
}
|
||||
|
||||
func (s *Subscription) Tag() bool {
|
||||
return strings.Contains(s.Features, "tag")
|
||||
}
|
||||
|
||||
func (s *Subscription) PullReviews() bool {
|
||||
return strings.Contains(s.Features, "pull_reviews")
|
||||
}
|
||||
|
||||
func (s *Subscription) Label() string {
|
||||
if !strings.Contains(s.Features, "label:") {
|
||||
return ""
|
||||
}
|
||||
return strings.Split(s.Features, "\"")[1]
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package subscription
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestNewSubscriptionSimple(t *testing.T) {
|
||||
s, err := New("", "", "issues", "")
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, &Subscription{Features: "issues"}, s)
|
||||
assert.True(t, s.Issues())
|
||||
assert.False(t, s.Merges())
|
||||
assert.False(t, s.Pushes())
|
||||
assert.False(t, s.IssueComments())
|
||||
assert.False(t, s.MergeRequestComments())
|
||||
assert.False(t, s.Pipeline())
|
||||
assert.False(t, s.Tag())
|
||||
assert.False(t, s.PullReviews())
|
||||
assert.Equal(t, "", s.Label())
|
||||
}
|
||||
|
||||
func TestNewSubscriptionMultiple(t *testing.T) {
|
||||
s, err := New("", "", "issues,merges", "")
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, &Subscription{Features: "issues,merges"}, s)
|
||||
assert.True(t, s.Issues())
|
||||
assert.True(t, s.Merges())
|
||||
assert.False(t, s.Pushes())
|
||||
assert.False(t, s.IssueComments())
|
||||
assert.False(t, s.MergeRequestComments())
|
||||
assert.False(t, s.Pipeline())
|
||||
assert.False(t, s.Tag())
|
||||
assert.False(t, s.PullReviews())
|
||||
assert.Equal(t, "", s.Label())
|
||||
}
|
||||
|
||||
func TestNewSubscriptionAll(t *testing.T) {
|
||||
s, err := New("", "", "issues,merges,pushes,issue_comments,merge_request_comments,pipeline,tag,pull_reviews", "")
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, &Subscription{Features: "issues,merges,pushes,issue_comments,merge_request_comments,pipeline,tag,pull_reviews"}, s)
|
||||
assert.True(t, s.Issues())
|
||||
assert.True(t, s.Merges())
|
||||
assert.True(t, s.Pushes())
|
||||
assert.True(t, s.IssueComments())
|
||||
assert.True(t, s.MergeRequestComments())
|
||||
assert.True(t, s.Pipeline())
|
||||
assert.True(t, s.Tag())
|
||||
assert.True(t, s.PullReviews())
|
||||
assert.Equal(t, "", s.Label())
|
||||
}
|
||||
|
||||
func TestNewSubscriptionUnknown(t *testing.T) {
|
||||
s, err := New("", "", "unknown,merges,missing", "")
|
||||
assert.Nil(t, s)
|
||||
assert.Equal(t, err.Error(), "unknown features unknown,missing")
|
||||
}
|
||||
|
||||
func TestNewSubscriptionLabel(t *testing.T) {
|
||||
s, err := New("", "", `issues,label:"test",merges`, "")
|
||||
assert.Nil(t, err)
|
||||
assert.True(t, s.Merges())
|
||||
assert.True(t, s.Issues())
|
||||
assert.Equal(t, "test", s.Label())
|
||||
}
|
||||
|
||||
func TestNewSubscriptionBadFormated(t *testing.T) {
|
||||
s, err := New("", "", `label:"`, "")
|
||||
assert.Nil(t, s)
|
||||
assert.Equal(t, err.Error(), "the label is formatted incorrectly")
|
||||
}
|
||||
|
||||
func TestNewSubscriptionMultipleLabel(t *testing.T) {
|
||||
s, err := New("", "", `label:"1",label:"2"`, "")
|
||||
assert.Nil(t, s)
|
||||
assert.Equal(t, err.Error(), "can't add multiple labels on the same subscription")
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
|
||||
"github.com/mattermost/mattermost-plugin-gitlab/server/gitlab"
|
||||
"github.com/mattermost/mattermost-plugin-gitlab/server/subscription"
|
||||
)
|
||||
|
||||
const (
|
||||
SubscriptionsKey = "subscriptions"
|
||||
)
|
||||
|
||||
type Subscriptions struct {
|
||||
Repositories map[string][]*subscription.Subscription
|
||||
}
|
||||
|
||||
func (p *Plugin) Subscribe(info *gitlab.UserInfo, namespace, project, channelID, features string) (*Subscriptions, error) {
|
||||
if err := p.isNamespaceAllowed(namespace); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
fullPath := fullPathFromNamespaceAndProject(namespace, project)
|
||||
sub, err := subscription.New(channelID, info.UserID, features, fullPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
subs, err := p.AddSubscription(fullPath, sub)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return subs, nil
|
||||
}
|
||||
|
||||
func (p *Plugin) GetSubscriptionsByChannel(channelID string) ([]*subscription.Subscription, error) {
|
||||
subs, err := p.GetSubscriptions()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return filterSubscriptionsByChannel(subs, channelID), nil
|
||||
}
|
||||
|
||||
func filterSubscriptionsByChannel(subs *Subscriptions, channelID string) []*subscription.Subscription {
|
||||
var filteredSubs []*subscription.Subscription
|
||||
|
||||
for _, v := range subs.Repositories {
|
||||
for _, s := range v {
|
||||
if s.ChannelID == channelID {
|
||||
filteredSubs = append(filteredSubs, s)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return filteredSubs
|
||||
}
|
||||
|
||||
func (p *Plugin) AddSubscription(fullPath string, sub *subscription.Subscription) (*Subscriptions, error) {
|
||||
subs, err := p.GetSubscriptions()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
repoSubs := subs.Repositories[fullPath]
|
||||
if repoSubs == nil {
|
||||
repoSubs = []*subscription.Subscription{sub}
|
||||
} else {
|
||||
exists := false
|
||||
for index, s := range repoSubs {
|
||||
if s.ChannelID == sub.ChannelID {
|
||||
repoSubs[index] = sub
|
||||
exists = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !exists {
|
||||
repoSubs = append(repoSubs, sub)
|
||||
}
|
||||
}
|
||||
|
||||
subs.Repositories[fullPath] = repoSubs
|
||||
return subs, p.StoreSubscriptions(subs)
|
||||
}
|
||||
|
||||
func (p *Plugin) GetSubscriptions() (*Subscriptions, error) {
|
||||
var subscriptions *Subscriptions
|
||||
|
||||
err := p.client.KV.Get(SubscriptionsKey, &subscriptions)
|
||||
if err != nil {
|
||||
p.client.Log.Warn("can't get subscriptions from kvstore", "err", err.Error())
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if subscriptions == nil {
|
||||
subscriptions = &Subscriptions{Repositories: map[string][]*subscription.Subscription{}}
|
||||
}
|
||||
|
||||
return subscriptions, nil
|
||||
}
|
||||
|
||||
func (p *Plugin) StoreSubscriptions(s *Subscriptions) error {
|
||||
if _, err := p.client.KV.Set(SubscriptionsKey, s); err != nil {
|
||||
p.client.Log.Warn("can't set subscriptions in kvstore", "err", err.Error())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Plugin) GetSubscribedChannelsForProject(
|
||||
ctx context.Context,
|
||||
namespace string,
|
||||
project string,
|
||||
isPublicVisibility bool,
|
||||
) []*subscription.Subscription {
|
||||
var subsForRepo []*subscription.Subscription
|
||||
|
||||
subs, err := p.GetSubscriptions()
|
||||
if err != nil {
|
||||
p.client.Log.Warn("can't retrieve subscriptions", "err", err.Error())
|
||||
return nil
|
||||
}
|
||||
|
||||
// Add subscriptions for the specific repo
|
||||
fullPath := fullPathFromNamespaceAndProject(namespace, project)
|
||||
if subs.Repositories[fullPath] != nil {
|
||||
subsForRepo = append(subsForRepo, subs.Repositories[fullPath]...)
|
||||
}
|
||||
|
||||
// Add subscriptions for the namespace
|
||||
namespacePath := fullPathFromNamespaceAndProject(namespace, "")
|
||||
if namespacePath != fullPath && subs.Repositories[namespacePath] != nil {
|
||||
subsForRepo = append(subsForRepo, subs.Repositories[namespacePath]...)
|
||||
}
|
||||
|
||||
if len(subsForRepo) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
subsToReturn := make([]*subscription.Subscription, 0, len(subsForRepo))
|
||||
for _, sub := range subsForRepo {
|
||||
if !isPublicVisibility && !p.permissionToProject(ctx, sub.CreatorID, namespace, project) {
|
||||
continue
|
||||
}
|
||||
subsToReturn = append(subsToReturn, sub)
|
||||
}
|
||||
|
||||
return subsToReturn
|
||||
}
|
||||
|
||||
// Unsubscribe deletes the link between namespace/project and channelID.
|
||||
// Returns true if subscription was found, false otherwise.
|
||||
func (p *Plugin) Unsubscribe(channelID string, fullPath string) (bool, *Subscriptions, error) {
|
||||
if fullPath == "" {
|
||||
return false, nil, errors.New("invalid repository")
|
||||
}
|
||||
|
||||
subs, err := p.GetSubscriptions()
|
||||
if err != nil {
|
||||
return false, nil, err
|
||||
}
|
||||
|
||||
var removed bool
|
||||
|
||||
// We don't know whether fullPath is a namespace or project, so we have to check both cases
|
||||
for _, path := range []string{fullPath, fullPath + "/"} {
|
||||
pathSubs := subs.Repositories[path]
|
||||
if pathSubs == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
pathRemoved := false
|
||||
for index, sub := range pathSubs {
|
||||
if sub.ChannelID == channelID {
|
||||
pathSubs = append(pathSubs[:index], pathSubs[index+1:]...)
|
||||
pathRemoved = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if pathRemoved {
|
||||
if len(pathSubs) > 0 {
|
||||
subs.Repositories[path] = pathSubs
|
||||
} else {
|
||||
delete(subs.Repositories, path)
|
||||
}
|
||||
removed = true
|
||||
}
|
||||
}
|
||||
|
||||
if !removed {
|
||||
return false, subs, nil
|
||||
}
|
||||
return true, subs, p.StoreSubscriptions(subs)
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/mattermost/mattermost/server/public/plugin/plugintest"
|
||||
"github.com/mattermost/mattermost/server/public/pluginapi"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/mattermost/mattermost-plugin-gitlab/server/gitlab"
|
||||
"github.com/mattermost/mattermost-plugin-gitlab/server/subscription"
|
||||
)
|
||||
|
||||
func TestSubscribe(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
info *gitlab.UserInfo
|
||||
namespace string
|
||||
project string
|
||||
channelID string
|
||||
features string
|
||||
initialSubscriptions *Subscriptions
|
||||
|
||||
initMock func() *plugintest.API
|
||||
expectedError error
|
||||
expectedUpdatedSubscriptions *Subscriptions
|
||||
}{
|
||||
{
|
||||
name: "should add new subscription",
|
||||
info: &gitlab.UserInfo{UserID: "user_id"},
|
||||
namespace: "namespace",
|
||||
project: "project",
|
||||
channelID: "channelID",
|
||||
features: "merges",
|
||||
initialSubscriptions: &Subscriptions{Repositories: map[string][]*subscription.Subscription{}},
|
||||
|
||||
expectedError: nil,
|
||||
expectedUpdatedSubscriptions: &Subscriptions{
|
||||
Repositories: map[string][]*subscription.Subscription{
|
||||
"namespace/project": {
|
||||
{ChannelID: "channelID", CreatorID: "user_id", Features: "merges", Repository: "namespace/project"},
|
||||
},
|
||||
},
|
||||
},
|
||||
}, {
|
||||
name: "should keep existing subscriptions",
|
||||
info: &gitlab.UserInfo{UserID: "user_id"},
|
||||
namespace: "namespace",
|
||||
project: "project",
|
||||
channelID: "channelID2",
|
||||
features: "merges",
|
||||
initialSubscriptions: &Subscriptions{
|
||||
Repositories: map[string][]*subscription.Subscription{
|
||||
"namespace/project": {
|
||||
{ChannelID: "channelID", CreatorID: "user_id", Features: "merges", Repository: "namespace/project"},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
expectedError: nil,
|
||||
expectedUpdatedSubscriptions: &Subscriptions{
|
||||
Repositories: map[string][]*subscription.Subscription{
|
||||
"namespace/project": {
|
||||
{ChannelID: "channelID", CreatorID: "user_id", Features: "merges", Repository: "namespace/project"},
|
||||
{ChannelID: "channelID2", CreatorID: "user_id", Features: "merges", Repository: "namespace/project"},
|
||||
},
|
||||
},
|
||||
},
|
||||
}, {
|
||||
name: "should error on invalid features",
|
||||
info: &gitlab.UserInfo{UserID: "user_id"},
|
||||
namespace: "namespace",
|
||||
project: "project",
|
||||
channelID: "channelID2",
|
||||
features: "invalid",
|
||||
initialSubscriptions: &Subscriptions{
|
||||
Repositories: map[string][]*subscription.Subscription{
|
||||
"namespace/project": {
|
||||
{ChannelID: "channelID", CreatorID: "user_id", Features: "merges", Repository: "namespace/project"},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
expectedError: errors.New("unknown features invalid"),
|
||||
expectedUpdatedSubscriptions: nil,
|
||||
},
|
||||
}
|
||||
|
||||
t.Parallel()
|
||||
for _, test := range testCases {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
m := &plugintest.API{}
|
||||
if test.expectedError == nil {
|
||||
initialSubscriptions, err := json.Marshal(test.initialSubscriptions)
|
||||
require.NoError(t, err)
|
||||
|
||||
expectedSubscriptions, err := json.Marshal(test.expectedUpdatedSubscriptions)
|
||||
require.NoError(t, err)
|
||||
|
||||
m.On("KVGet", SubscriptionsKey).Return(initialSubscriptions, nil).Once()
|
||||
m.On("KVSetWithOptions", SubscriptionsKey, expectedSubscriptions, mock.AnythingOfType("model.PluginKVSetOptions")).Return(true, nil).Once()
|
||||
}
|
||||
|
||||
p := &Plugin{configuration: &configuration{}}
|
||||
p.SetAPI(m)
|
||||
p.client = pluginapi.NewClient(m, p.Driver)
|
||||
|
||||
updatedSubscriptions, err := p.Subscribe(test.info, test.namespace, test.project, test.channelID, test.features)
|
||||
if test.expectedError == nil {
|
||||
assert.NoError(t, err)
|
||||
} else {
|
||||
assert.Error(t, test.expectedError, err)
|
||||
}
|
||||
assert.Equal(t, test.expectedUpdatedSubscriptions, updatedSubscriptions)
|
||||
m.AssertExpectations(t)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnsubscribe(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
channelID string
|
||||
repoName string
|
||||
initMock func() *plugintest.API
|
||||
shouldDelete bool
|
||||
shouldError bool
|
||||
expectedUpdatedSubscriptions *Subscriptions
|
||||
}{
|
||||
{
|
||||
name: "should delete existing subscription",
|
||||
channelID: "1",
|
||||
repoName: "owner/project",
|
||||
initMock: func() *plugintest.API {
|
||||
m := &plugintest.API{}
|
||||
kvget := `{"Repositories":{"owner/project":[{"ChannelID":"1","CreatorID":"1","Features":"all","Repository":"owner/project"}]}}`
|
||||
kvset := `{"Repositories":{}}`
|
||||
m.On("KVGet", SubscriptionsKey).Return([]byte(kvget), nil).Once()
|
||||
m.On("KVSetWithOptions", SubscriptionsKey, []byte(kvset), mock.AnythingOfType("model.PluginKVSetOptions")).Return(true, nil).Once()
|
||||
return m
|
||||
},
|
||||
shouldDelete: true,
|
||||
shouldError: false,
|
||||
expectedUpdatedSubscriptions: &Subscriptions{
|
||||
Repositories: map[string][]*subscription.Subscription{},
|
||||
},
|
||||
}, {
|
||||
name: "should keep other channel",
|
||||
channelID: "1",
|
||||
repoName: "owner/project",
|
||||
initMock: func() *plugintest.API {
|
||||
m := &plugintest.API{}
|
||||
kvget := `{"Repositories":{"owner/project":[{"ChannelID":"1","CreatorID":"1","Features":"all","Repository":"owner/project"},{"ChannelID":"2","CreatorID":"1","Features":"all","Repository":"owner/project"}]}}`
|
||||
kvset := `{"Repositories":{"owner/project":[{"ChannelID":"2","CreatorID":"1","Features":"all","Repository":"owner/project"}]}}`
|
||||
m.On("KVGet", SubscriptionsKey).Return([]byte(kvget), nil).Once()
|
||||
m.On("KVSetWithOptions", SubscriptionsKey, []byte(kvset), mock.AnythingOfType("model.PluginKVSetOptions")).Return(true, nil).Once()
|
||||
return m
|
||||
},
|
||||
shouldDelete: true,
|
||||
shouldError: false,
|
||||
expectedUpdatedSubscriptions: &Subscriptions{
|
||||
Repositories: map[string][]*subscription.Subscription{
|
||||
"owner/project": {
|
||||
{ChannelID: "2", CreatorID: "1", Features: "all", Repository: "owner/project"},
|
||||
},
|
||||
},
|
||||
},
|
||||
}, {
|
||||
name: "should not delete if not exist",
|
||||
channelID: "2",
|
||||
repoName: "owner/project",
|
||||
initMock: func() *plugintest.API {
|
||||
m := &plugintest.API{}
|
||||
kvget := `{"Repositories":{"owner/project":[{"ChannelID":"1","CreatorID":"1","Features":"all","Repository":"owner/project"}]}}`
|
||||
m.On("KVGet", SubscriptionsKey).Return([]byte(kvget), nil).Once()
|
||||
return m
|
||||
},
|
||||
shouldDelete: false,
|
||||
shouldError: false,
|
||||
expectedUpdatedSubscriptions: &Subscriptions{
|
||||
Repositories: map[string][]*subscription.Subscription{
|
||||
"owner/project": {
|
||||
{ChannelID: "1", CreatorID: "1", Features: "all", Repository: "owner/project"},
|
||||
},
|
||||
},
|
||||
},
|
||||
}, {
|
||||
name: "should refuse empty repo",
|
||||
channelID: "1",
|
||||
repoName: "",
|
||||
initMock: func() *plugintest.API {
|
||||
return &plugintest.API{}
|
||||
},
|
||||
shouldDelete: false,
|
||||
shouldError: true,
|
||||
expectedUpdatedSubscriptions: nil,
|
||||
}, {
|
||||
name: "should delete organization",
|
||||
channelID: "1",
|
||||
repoName: "owner",
|
||||
initMock: func() *plugintest.API {
|
||||
m := &plugintest.API{}
|
||||
kvget := `{"Repositories":{"owner/":[{"ChannelID":"1","CreatorID":"1","Features":"all","Repository":"owner/"}]}}`
|
||||
kvset := `{"Repositories":{}}`
|
||||
m.On("KVGet", SubscriptionsKey).Return([]byte(kvget), nil).Once()
|
||||
m.On("KVSetWithOptions", SubscriptionsKey, []byte(kvset), mock.AnythingOfType("model.PluginKVSetOptions")).Return(true, nil).Once()
|
||||
return m
|
||||
},
|
||||
shouldDelete: true,
|
||||
shouldError: false,
|
||||
expectedUpdatedSubscriptions: &Subscriptions{
|
||||
Repositories: map[string][]*subscription.Subscription{},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
t.Parallel()
|
||||
for _, test := range testCases {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
m := test.initMock()
|
||||
p := &Plugin{configuration: &configuration{}}
|
||||
p.SetAPI(m)
|
||||
p.client = pluginapi.NewClient(m, p.Driver)
|
||||
res, updatedSubscriptions, err := p.Unsubscribe(test.channelID, test.repoName)
|
||||
assert.Equal(t, test.shouldDelete, res)
|
||||
assert.Equal(t, test.shouldError, err != nil)
|
||||
assert.Equal(t, test.expectedUpdatedSubscriptions, updatedSubscriptions)
|
||||
m.AssertExpectations(t)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/mattermost/mattermost/server/public/pluginapi"
|
||||
"github.com/mattermost/mattermost/server/public/pluginapi/experimental/bot/logger"
|
||||
"github.com/mattermost/mattermost/server/public/pluginapi/experimental/telemetry"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
const (
|
||||
keysPerPage = 1000
|
||||
)
|
||||
|
||||
func (p *Plugin) TrackEvent(event string, properties map[string]interface{}) {
|
||||
err := p.tracker.TrackEvent(event, properties)
|
||||
if err != nil {
|
||||
p.API.LogDebug("Error sending telemetry event", "event", event, "error", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Plugin) TrackUserEvent(event, userID string, properties map[string]interface{}) {
|
||||
err := p.tracker.TrackUserEvent(event, userID, properties)
|
||||
if err != nil {
|
||||
p.API.LogDebug("Error sending user telemetry event", "event", event, "error", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Plugin) SendDailyTelemetry() {
|
||||
config := p.getConfiguration()
|
||||
|
||||
connectedUserCount, err := p.getConnectedUserCount()
|
||||
if err != nil {
|
||||
p.client.Log.Warn("Failed to get the number of connected users for telemetry", "error", err)
|
||||
}
|
||||
|
||||
p.TrackEvent("stats", map[string]interface{}{
|
||||
"connected_user_count": connectedUserCount,
|
||||
"is_oauth_configured": config.IsOAuthConfigured(),
|
||||
"is_sass": config.IsSASS(),
|
||||
"is_group_locked": config.GitlabGroup != "",
|
||||
"enable_private_repo": config.EnablePrivateRepo,
|
||||
"Use_preregistered_application": config.UsePreregisteredApplication,
|
||||
})
|
||||
}
|
||||
|
||||
func (p *Plugin) getConnectedUserCount() (int64, error) {
|
||||
checker := func(key string) (keep bool, err error) {
|
||||
return strings.HasSuffix(key, GitlabUserInfoKey), nil
|
||||
}
|
||||
|
||||
var count int64
|
||||
|
||||
for i := 0; ; i++ {
|
||||
keys, err := p.client.KV.ListKeys(i, keysPerPage, pluginapi.WithChecker(checker))
|
||||
if err != nil {
|
||||
return 0, errors.Wrapf(err, "failed to list keys - page, %d", i)
|
||||
}
|
||||
|
||||
count += int64(len(keys))
|
||||
|
||||
if len(keys) < keysPerPage {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return count, nil
|
||||
}
|
||||
|
||||
// Initialize telemetry setups the tracker/clients needed to send telemetry data.
|
||||
// The telemetry.NewTrackerConfig(...) param will take care of extract/parse the config to set rge right settings.
|
||||
// If you don't want the default behavior you still can pass a different telemetry.TrackerConfig data.
|
||||
func (p *Plugin) initializeTelemetry() {
|
||||
var err error
|
||||
|
||||
// Telemetry client
|
||||
p.telemetryClient, err = telemetry.NewRudderClient()
|
||||
if err != nil {
|
||||
p.API.LogWarn("Telemetry client not started", "error", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Get config values
|
||||
p.tracker = telemetry.NewTracker(
|
||||
p.telemetryClient,
|
||||
p.API.GetDiagnosticId(),
|
||||
p.API.GetServerVersion(),
|
||||
manifest.Id,
|
||||
manifest.Version,
|
||||
"gitlab",
|
||||
telemetry.NewTrackerConfig(p.API.GetConfig()),
|
||||
logger.New(p.API),
|
||||
)
|
||||
}
|
||||
+283
@@ -0,0 +1,283 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
"path"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
func pad(src []byte) []byte {
|
||||
padding := aes.BlockSize - len(src)%aes.BlockSize
|
||||
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
|
||||
return append(src, padtext...)
|
||||
}
|
||||
|
||||
func unpad(src []byte) ([]byte, error) {
|
||||
length := len(src)
|
||||
unpadding := int(src[length-1])
|
||||
|
||||
if unpadding > length {
|
||||
return nil, errors.New("unpad error. This could happen when incorrect encryption key is used")
|
||||
}
|
||||
|
||||
return src[:(length - unpadding)], nil
|
||||
}
|
||||
|
||||
func encrypt(key []byte, text string) (string, error) {
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
msg := pad([]byte(text))
|
||||
ciphertext := make([]byte, aes.BlockSize+len(msg))
|
||||
iv := ciphertext[:aes.BlockSize]
|
||||
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
cfb := cipher.NewCFBEncrypter(block, iv)
|
||||
cfb.XORKeyStream(ciphertext[aes.BlockSize:], msg)
|
||||
finalMsg := base64.URLEncoding.EncodeToString(ciphertext)
|
||||
return finalMsg, nil
|
||||
}
|
||||
|
||||
func decrypt(key []byte, text string) (string, error) {
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
decodedMsg, err := base64.URLEncoding.DecodeString(text)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if (len(decodedMsg) % aes.BlockSize) != 0 {
|
||||
return "", errors.New("blocksize must be multiple of decoded message length")
|
||||
}
|
||||
|
||||
iv := decodedMsg[:aes.BlockSize]
|
||||
msg := decodedMsg[aes.BlockSize:]
|
||||
|
||||
cfb := cipher.NewCFBDecrypter(block, iv)
|
||||
cfb.XORKeyStream(msg, msg)
|
||||
|
||||
unpadMsg, err := unpad(msg)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return string(unpadMsg), nil
|
||||
}
|
||||
|
||||
// normalizePath is responsible for parsing GitLab project URL leaving only <GROUP>/<SUBGROUP>/<REPO> components.
|
||||
func normalizePath(full, baseURL string) string {
|
||||
if baseURL == "" {
|
||||
baseURL = "https://gitlab.com/"
|
||||
} else if !strings.HasSuffix(baseURL, "/") {
|
||||
baseURL += "/"
|
||||
}
|
||||
|
||||
return strings.TrimSuffix(strings.TrimSpace(strings.Replace(full, baseURL, "", 1)), "/")
|
||||
}
|
||||
|
||||
func parseGitlabUsernamesFromText(text string) []string {
|
||||
usernameMap := map[string]bool{}
|
||||
usernames := []string{}
|
||||
|
||||
for _, word := range strings.FieldsFunc(text, func(c rune) bool {
|
||||
return !(c == '-' || c == '@' || unicode.IsLetter(c) || unicode.IsNumber(c))
|
||||
}) {
|
||||
if len(word) < 2 || word[0] != '@' {
|
||||
continue
|
||||
}
|
||||
|
||||
if word[1] == '-' || word[len(word)-1] == '-' {
|
||||
continue
|
||||
}
|
||||
|
||||
if strings.Contains(word, "--") {
|
||||
continue
|
||||
}
|
||||
|
||||
name := word[1:]
|
||||
if !usernameMap[name] {
|
||||
usernames = append(usernames, name)
|
||||
usernameMap[name] = true
|
||||
}
|
||||
}
|
||||
|
||||
return usernames
|
||||
}
|
||||
|
||||
func fullPathFromNamespaceAndProject(namespace, project string) string {
|
||||
return fmt.Sprintf("%s/%s", namespace, project)
|
||||
}
|
||||
|
||||
// isValidURL checks if a given URL is a valid URL with a host and a http or http scheme.
|
||||
func isValidURL(rawURL string) error {
|
||||
u, err := url.ParseRequestURI(rawURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if u.Scheme != "http" && u.Scheme != "https" {
|
||||
return errors.Errorf("URL schema must either be %q or %q", "http", "https")
|
||||
}
|
||||
|
||||
if u.Host == "" {
|
||||
return errors.New("URL must contain a host")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// filterLines filters lines in a string from start to end.
|
||||
func filterLines(s string, start, end int) (string, error) {
|
||||
scanner := bufio.NewScanner(strings.NewReader(s))
|
||||
var buf strings.Builder
|
||||
for i := 1; scanner.Scan() && i <= end; i++ {
|
||||
if i < start {
|
||||
continue
|
||||
}
|
||||
buf.Write(scanner.Bytes())
|
||||
buf.WriteByte(byte('\n'))
|
||||
}
|
||||
|
||||
return buf.String(), scanner.Err()
|
||||
}
|
||||
|
||||
// getLineNumbers returns the start and end lines from an anchor tag
|
||||
// of a GitLab permalink.
|
||||
func getLineNumbers(s string) (start, end int) {
|
||||
// split till -
|
||||
parts := strings.Split(s, "-")
|
||||
|
||||
if len(parts) > 2 {
|
||||
return -1, -1
|
||||
}
|
||||
|
||||
switch len(parts) {
|
||||
case 1:
|
||||
// just a single line
|
||||
l := getLine(parts[0])
|
||||
if l == -1 {
|
||||
return -1, -1
|
||||
}
|
||||
if l < permalinkLineContext {
|
||||
return 0, l + permalinkLineContext
|
||||
}
|
||||
return l - permalinkLineContext, l + permalinkLineContext
|
||||
case 2:
|
||||
// a line range
|
||||
start := getLine(parts[0])
|
||||
end := getLine(parts[1])
|
||||
if start != -1 && end != -1 && start > end {
|
||||
return -1, -1
|
||||
}
|
||||
return start, end
|
||||
}
|
||||
return -1, -1
|
||||
}
|
||||
|
||||
// getLine returns the line number in int from a string
|
||||
// of form L<num>.
|
||||
func getLine(s string) int {
|
||||
// check starting L and minimum length.
|
||||
if !strings.HasPrefix(s, "L") || len(s) < 2 {
|
||||
return -1
|
||||
}
|
||||
|
||||
line, err := strconv.Atoi(s[1:])
|
||||
if err != nil {
|
||||
return -1
|
||||
}
|
||||
return line
|
||||
}
|
||||
|
||||
// isInsideLink reports whether the given index in a string is preceded
|
||||
// by zero or more space, then (, then ].
|
||||
//
|
||||
// It is a poor man's version of checking markdown hyperlinks without
|
||||
// using a full-blown markdown parser. The idea is to quickly confirm
|
||||
// whether a permalink is inside a markdown link or not. Something like
|
||||
// "text ]( permalink" is rare enough. Even then, it is okay if
|
||||
// there are false positives, but there cannot be any false negatives.
|
||||
//
|
||||
// Note: it is fine to go one byte at a time instead of one rune because
|
||||
// we are anyways looking for ASCII chars.
|
||||
// Ref: mattermost plugin github (https://github.com/mattermost/mattermost-plugin-github/blob/fcc50523c17c2670cb595a8038864a8a7f7fd1e5/server/plugin/utils.go#L273)
|
||||
func isInsideLink(msg string, index int) bool {
|
||||
stage := 0 // 0 is looking for space or ( and 1 for ]
|
||||
|
||||
for i := index; i > 0; i-- {
|
||||
char := msg[i-1]
|
||||
switch stage {
|
||||
case 0:
|
||||
if char == ' ' {
|
||||
continue
|
||||
}
|
||||
if char == '(' {
|
||||
stage++
|
||||
continue
|
||||
}
|
||||
return false
|
||||
case 1:
|
||||
if char == ']' {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// getCodeMarkdown returns the constructed markdown for a permalink.
|
||||
func getCodeMarkdown(user, repo, repoPath, word, lines string, isTruncated bool) string {
|
||||
final := fmt.Sprintf("\n[%s/%s/%s](%s)\n", user, repo, repoPath, word)
|
||||
ext := path.Ext(repoPath)
|
||||
// remove the preceding dot
|
||||
if len(ext) > 1 {
|
||||
ext = strings.TrimPrefix(ext, ".")
|
||||
}
|
||||
final += "```" + ext + "\n"
|
||||
final += lines
|
||||
if isTruncated { // add an ellipsis if lines were cut off
|
||||
final += "...\n"
|
||||
}
|
||||
final += "```\n"
|
||||
return final
|
||||
}
|
||||
|
||||
// lastN returns the last n characters of a string, with the rest replaced by *.
|
||||
// At most 3 characters are replaced. The rest is cut off.
|
||||
func lastN(s string, n int) string {
|
||||
if n < 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
out := []byte(s)
|
||||
if len(out) > n+3 {
|
||||
out = out[len(out)-n-3:]
|
||||
}
|
||||
for i := range out {
|
||||
if i < len(out)-n {
|
||||
out[i] = '*'
|
||||
}
|
||||
}
|
||||
|
||||
return string(out)
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestParseGitlabUsernamesFromText(t *testing.T) {
|
||||
tcs := []struct {
|
||||
Text string
|
||||
Expected []string
|
||||
}{
|
||||
{Text: "@jwilander", Expected: []string{"jwilander"}},
|
||||
{Text: "@jwilander.", Expected: []string{"jwilander"}},
|
||||
{Text: ".@jwilander", Expected: []string{"jwilander"}},
|
||||
{Text: " @jwilander ", Expected: []string{"jwilander"}},
|
||||
{Text: "@1jwilander", Expected: []string{"1jwilander"}},
|
||||
{Text: "@j", Expected: []string{"j"}},
|
||||
{Text: "@", Expected: []string{}},
|
||||
{Text: "", Expected: []string{}},
|
||||
{Text: "jwilander", Expected: []string{}},
|
||||
{Text: "@jwilander-", Expected: []string{}},
|
||||
{Text: "@-jwilander", Expected: []string{}},
|
||||
{Text: "@jwil--ander", Expected: []string{}},
|
||||
{Text: "@jwilander @jwilander2", Expected: []string{"jwilander", "jwilander2"}},
|
||||
{Text: "@jwilander2 @jwilander", Expected: []string{"jwilander2", "jwilander"}},
|
||||
{Text: "Hey @jwilander and @jwilander2!", Expected: []string{"jwilander", "jwilander2"}},
|
||||
{Text: "@jwilander @jwilan--der2", Expected: []string{"jwilander"}},
|
||||
}
|
||||
|
||||
for _, tc := range tcs {
|
||||
assert.Equal(t, tc.Expected, parseGitlabUsernamesFromText(tc.Text))
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizePath(t *testing.T) {
|
||||
tcs := []struct {
|
||||
Full string
|
||||
BaseURL string
|
||||
Expected string
|
||||
}{
|
||||
{Full: "mattermost", BaseURL: "", Expected: "mattermost"},
|
||||
{Full: "mattermost", BaseURL: "https://gitlab.com/", Expected: "mattermost"},
|
||||
{Full: "https://gitlab.com/mattermost", BaseURL: "", Expected: "mattermost"},
|
||||
{Full: "https://gitlab.com/mattermost", BaseURL: "https://gitlab.com/", Expected: "mattermost"},
|
||||
{Full: "mattermost/mattermost-server", BaseURL: "", Expected: "mattermost/mattermost-server"},
|
||||
{Full: "mattermost/mattermost-server", BaseURL: "https://gitlab.com/", Expected: "mattermost/mattermost-server"},
|
||||
{Full: "https://gitlab.com/mattermost/mattermost-server", BaseURL: "", Expected: "mattermost/mattermost-server"},
|
||||
{Full: "https://gitlab.com/mattermost/mattermost-server", BaseURL: "https://gitlab.com/", Expected: "mattermost/mattermost-server"},
|
||||
{Full: "", BaseURL: "", Expected: ""},
|
||||
{Full: "group/subgroup/project", BaseURL: "", Expected: "group/subgroup/project"},
|
||||
{Full: "https://gitlab.com/group/subgroup/project", BaseURL: "", Expected: "group/subgroup/project"},
|
||||
{Full: "http://127.0.0.1:3000/manland/personal", BaseURL: "http://127.0.0.1:3000", Expected: "manland/personal"},
|
||||
}
|
||||
|
||||
for _, tc := range tcs {
|
||||
assert.Equal(t, tc.Expected, normalizePath(tc.Full, tc.BaseURL))
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetLineNumbers(t *testing.T) {
|
||||
tcs := []struct {
|
||||
input string
|
||||
start, end int
|
||||
}{
|
||||
{
|
||||
input: "L19",
|
||||
start: 16,
|
||||
end: 22,
|
||||
}, {
|
||||
input: "L19-L23",
|
||||
start: 19,
|
||||
end: 23,
|
||||
}, {
|
||||
input: "L23-L19",
|
||||
start: -1,
|
||||
end: -1,
|
||||
}, {
|
||||
input: "L",
|
||||
start: -1,
|
||||
end: -1,
|
||||
}, {
|
||||
input: "bad",
|
||||
start: -1,
|
||||
end: -1,
|
||||
}, {
|
||||
input: "L99-",
|
||||
start: 99,
|
||||
end: -1,
|
||||
}, {
|
||||
input: "L2",
|
||||
start: 0,
|
||||
end: 5,
|
||||
},
|
||||
}
|
||||
for _, tc := range tcs {
|
||||
start, end := getLineNumbers(tc.input)
|
||||
assert.Equalf(t, tc.start, start, "unexpected start index for getLineNumbers(%q)", tc.input)
|
||||
assert.Equalf(t, tc.end, end, "unexpected end index for getLineNumbers(%q)", tc.input)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInsideLink(t *testing.T) {
|
||||
tcs := []struct {
|
||||
input string
|
||||
index int
|
||||
expected bool
|
||||
}{
|
||||
{
|
||||
input: "[text](link)",
|
||||
index: 7,
|
||||
expected: true,
|
||||
}, {
|
||||
input: "[text]( link space)",
|
||||
index: 8,
|
||||
expected: true,
|
||||
}, {
|
||||
input: "text](link",
|
||||
index: 6,
|
||||
expected: true,
|
||||
}, {
|
||||
input: "text] (link)",
|
||||
index: 7,
|
||||
expected: false,
|
||||
}, {
|
||||
input: "text](link)",
|
||||
index: 6,
|
||||
expected: true,
|
||||
}, {
|
||||
input: "link",
|
||||
index: 0,
|
||||
expected: false,
|
||||
}, {
|
||||
input: " (link)",
|
||||
index: 2,
|
||||
expected: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tcs {
|
||||
assert.Equalf(t, tc.expected, isInsideLink(tc.input, tc.index), "unexpected result for isInsideLink(%q, %d)", tc.input, tc.index)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLastN(t *testing.T) {
|
||||
tcs := []struct {
|
||||
Text string
|
||||
N int
|
||||
Expected string
|
||||
}{
|
||||
{Text: "", N: -99, Expected: ""},
|
||||
{Text: "", N: -1, Expected: ""},
|
||||
{Text: "", N: 0, Expected: ""},
|
||||
{Text: "", N: 1, Expected: ""},
|
||||
{Text: "", N: 99, Expected: ""},
|
||||
{Text: "abcdef", N: 4, Expected: "**cdef"},
|
||||
{Text: "abcdefghi", N: 2, Expected: "***hi"},
|
||||
{Text: "abcdefghi", N: 0, Expected: "***"},
|
||||
{Text: "abcdefghi", N: 99, Expected: "abcdefghi"},
|
||||
}
|
||||
|
||||
for _, tc := range tcs {
|
||||
assert.Equal(t, tc.Expected, lastN(tc.Text, tc.N))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
gitlabLib "github.com/xanzy/go-gitlab"
|
||||
"golang.org/x/oauth2"
|
||||
|
||||
"github.com/mattermost/mattermost-plugin-gitlab/server/gitlab"
|
||||
"github.com/mattermost/mattermost-plugin-gitlab/server/subscription"
|
||||
"github.com/mattermost/mattermost-plugin-gitlab/server/webhook"
|
||||
|
||||
"github.com/mattermost/mattermost/server/public/model"
|
||||
)
|
||||
|
||||
const (
|
||||
webhookTimeout = 10 * time.Second
|
||||
eventSourceParentPipeline = "parent_pipeline"
|
||||
)
|
||||
|
||||
type gitlabRetreiver struct {
|
||||
p *Plugin
|
||||
}
|
||||
|
||||
func (g *gitlabRetreiver) GetPipelineURL(pathWithNamespace string, pipelineID int) string {
|
||||
config := g.p.getConfiguration()
|
||||
return fmt.Sprintf("%s/%s/-/pipelines/%d", config.GitlabURL, pathWithNamespace, pipelineID)
|
||||
}
|
||||
|
||||
func (g *gitlabRetreiver) GetJobURL(pathWithNamespace string, jobID int) string {
|
||||
config := g.p.getConfiguration()
|
||||
return fmt.Sprintf("%s/%s/-/jobs/%d", config.GitlabURL, pathWithNamespace, jobID)
|
||||
}
|
||||
|
||||
func (g *gitlabRetreiver) GetUserURL(username string) string {
|
||||
config := g.p.getConfiguration()
|
||||
return fmt.Sprintf("%s/%s", config.GitlabURL, username)
|
||||
}
|
||||
|
||||
func (g *gitlabRetreiver) GetUsernameByID(id int) string {
|
||||
return g.p.getGitlabIDToUsernameMapping(fmt.Sprintf("%d", id))
|
||||
}
|
||||
|
||||
func (g *gitlabRetreiver) ParseGitlabUsernamesFromText(text string) []string {
|
||||
return parseGitlabUsernamesFromText(text)
|
||||
}
|
||||
|
||||
func (g *gitlabRetreiver) GetSubscribedChannelsForProject(
|
||||
ctx context.Context,
|
||||
namespace string,
|
||||
project string,
|
||||
isPublicVisibility bool,
|
||||
) []*subscription.Subscription {
|
||||
return g.p.GetSubscribedChannelsForProject(ctx, namespace, project, isPublicVisibility)
|
||||
}
|
||||
|
||||
func (p *Plugin) handleWebhook(w http.ResponseWriter, r *http.Request) {
|
||||
config := p.getConfiguration()
|
||||
|
||||
signature := r.Header.Get("X-Gitlab-Token")
|
||||
if config.WebhookSecret != signature {
|
||||
http.Error(w, "Not authorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
http.Error(w, "Bad request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
eventType := gitlabLib.WebhookEventType(r)
|
||||
event, err := gitlabLib.ParseWebhook(eventType, body)
|
||||
if err != nil {
|
||||
p.client.Log.Debug("Can't parse webhook", "err", err.Error(), "header", r.Header.Get("X-Gitlab-Event"), "event", string(body))
|
||||
http.Error(w, "Unable to handle request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), webhookTimeout)
|
||||
defer cancel()
|
||||
|
||||
var repoPrivate bool
|
||||
var pathWithNamespace string
|
||||
var handlers []*webhook.HandleWebhook
|
||||
var errHandler error
|
||||
fromUser := ""
|
||||
|
||||
switch event := event.(type) {
|
||||
case *gitlabLib.MergeEvent:
|
||||
repoPrivate = event.Project.Visibility == gitlabLib.PrivateVisibility
|
||||
pathWithNamespace = event.Project.PathWithNamespace
|
||||
fromUser = event.User.Username
|
||||
handlers, errHandler = p.WebhookHandler.HandleMergeRequest(ctx, event)
|
||||
case *gitlabLib.IssueEvent:
|
||||
repoPrivate = event.Project.Visibility == gitlabLib.PrivateVisibility
|
||||
pathWithNamespace = event.Project.PathWithNamespace
|
||||
fromUser = event.User.Username
|
||||
handlers, errHandler = p.WebhookHandler.HandleIssue(ctx, event, eventType)
|
||||
case *gitlabLib.IssueCommentEvent:
|
||||
repoPrivate = event.Project.Visibility == gitlabLib.PrivateVisibility
|
||||
pathWithNamespace = event.Project.PathWithNamespace
|
||||
fromUser = event.User.Username
|
||||
handlers, errHandler = p.WebhookHandler.HandleIssueComment(ctx, event)
|
||||
case *gitlabLib.MergeCommentEvent:
|
||||
repoPrivate = event.Project.Visibility == gitlabLib.PrivateVisibility
|
||||
pathWithNamespace = event.Project.PathWithNamespace
|
||||
fromUser = event.User.Username
|
||||
handlers, errHandler = p.WebhookHandler.HandleMergeRequestComment(ctx, event)
|
||||
case *gitlabLib.PushEvent:
|
||||
repoPrivate = event.Project.Visibility == gitlabLib.PrivateVisibility
|
||||
pathWithNamespace = event.Project.PathWithNamespace
|
||||
fromUser = event.UserName
|
||||
handlers, errHandler = p.WebhookHandler.HandlePush(ctx, event)
|
||||
case *gitlabLib.PipelineEvent:
|
||||
repoPrivate = event.Project.Visibility == gitlabLib.PrivateVisibility
|
||||
pathWithNamespace = event.Project.PathWithNamespace
|
||||
fromUser = event.User.Username
|
||||
if !p.configuration.EnableChildPipelineNotifications && event.ObjectAttributes.Source == eventSourceParentPipeline {
|
||||
return
|
||||
}
|
||||
|
||||
handlers, errHandler = p.WebhookHandler.HandlePipeline(ctx, event)
|
||||
case *gitlabLib.JobEvent:
|
||||
repoPrivate = event.Repository.Visibility == gitlabLib.PrivateVisibility
|
||||
pathWithNamespace = event.ProjectName
|
||||
fromUser = event.User.Name
|
||||
handlers, errHandler = p.WebhookHandler.HandleJobs(ctx, event)
|
||||
case *gitlabLib.TagEvent:
|
||||
repoPrivate = event.Project.Visibility == gitlabLib.PrivateVisibility
|
||||
pathWithNamespace = event.Project.PathWithNamespace
|
||||
fromUser = event.UserName
|
||||
handlers, errHandler = p.WebhookHandler.HandleTag(ctx, event)
|
||||
default:
|
||||
p.client.Log.Debug("Event type not implemented", "type", string(gitlabLib.WebhookEventType(r)))
|
||||
return
|
||||
}
|
||||
|
||||
if repoPrivate && !config.EnablePrivateRepo {
|
||||
return
|
||||
}
|
||||
|
||||
if err = p.isNamespaceAllowed(pathWithNamespace); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if errHandler != nil {
|
||||
p.client.Log.Debug("Error when handling webhook event", "err", errHandler)
|
||||
return
|
||||
}
|
||||
|
||||
alreadySentRefresh := make(map[string]bool)
|
||||
p.sendRefreshIfNotAlreadySent(alreadySentRefresh, fromUser)
|
||||
for _, res := range handlers {
|
||||
p.client.Log.Info("new msg", "message", res.Message, "from", res.From)
|
||||
for _, to := range res.ToUsers {
|
||||
userTo := p.sendRefreshIfNotAlreadySent(alreadySentRefresh, to)
|
||||
if len(userTo) > 0 && len(res.Message) > 0 {
|
||||
info, err := p.getGitlabUserInfoByMattermostID(userTo)
|
||||
if err != nil {
|
||||
p.client.Log.Warn("can't get user info to know if user wants to receive notifications", "err", err.Message)
|
||||
continue
|
||||
}
|
||||
if info.Settings.Notifications {
|
||||
if err := p.CreateBotDMPost(userTo, res.Message, "custom_git_review_request"); err != nil {
|
||||
p.client.Log.Warn("can't send dm post", "err", err.Error())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, to := range res.ToChannels {
|
||||
if len(res.Message) > 0 {
|
||||
post := &model.Post{
|
||||
UserId: p.BotUserID,
|
||||
Message: res.Message,
|
||||
ChannelId: to,
|
||||
}
|
||||
if err := p.client.Post.CreatePost(post); err != nil {
|
||||
p.client.Log.Warn("can't create post for webhook event", "err", err.Error())
|
||||
}
|
||||
}
|
||||
}
|
||||
p.sendRefreshIfNotAlreadySent(alreadySentRefresh, res.From)
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Plugin) sendRefreshIfNotAlreadySent(alreadySentRefresh map[string]bool, gitlabUsername string) string {
|
||||
if len(gitlabUsername) == 0 || alreadySentRefresh[gitlabUsername] {
|
||||
return ""
|
||||
}
|
||||
alreadySentRefresh[gitlabUsername] = true
|
||||
userMattermostID := p.getGitlabToUserIDMapping(gitlabUsername)
|
||||
if len(userMattermostID) > 0 {
|
||||
p.sendRefreshEvent(userMattermostID)
|
||||
}
|
||||
return userMattermostID
|
||||
}
|
||||
|
||||
func (p *Plugin) permissionToProject(ctx context.Context, userID, namespace, project string) bool {
|
||||
if userID == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
if err := p.isNamespaceAllowed(namespace); err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
info, apiErr := p.getGitlabUserInfoByMattermostID(userID)
|
||||
if apiErr != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
var result *gitlabLib.Project
|
||||
err := p.useGitlabClient(info, func(info *gitlab.UserInfo, token *oauth2.Token) error {
|
||||
resp, err := p.GitlabClient.GetProject(ctx, info, token, namespace, project)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result = resp
|
||||
return nil
|
||||
})
|
||||
if result == nil || err != nil {
|
||||
if err != nil {
|
||||
p.client.Log.Warn("Can't get project in webhook", "err", err.Error(), "project", namespace+"/"+project)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Check for guest level permissions
|
||||
if result.Permissions.ProjectAccess == nil || result.Permissions.ProjectAccess.AccessLevel == gitlabLib.GuestPermissions {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func (p *Plugin) createHook(ctx context.Context, gitlabClient gitlab.Gitlab, info *gitlab.UserInfo, group, project string, hookOptions *gitlab.AddWebhookOptions) (*gitlab.WebhookInfo, error) {
|
||||
// If project scope
|
||||
if project != "" {
|
||||
var gitProject *gitlabLib.Project
|
||||
getProjectErr := p.useGitlabClient(info, func(info *gitlab.UserInfo, token *oauth2.Token) error {
|
||||
resp, err := p.GitlabClient.GetProject(ctx, info, token, group, project)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
gitProject = resp
|
||||
return nil
|
||||
})
|
||||
if getProjectErr != nil {
|
||||
return nil, getProjectErr
|
||||
}
|
||||
var newWebhook *gitlab.WebhookInfo
|
||||
getGroupErr := p.useGitlabClient(info, func(info *gitlab.UserInfo, token *oauth2.Token) error {
|
||||
resp, err := p.GitlabClient.NewProjectHook(ctx, info, token, gitProject.ID, hookOptions)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
newWebhook = resp
|
||||
return nil
|
||||
})
|
||||
if getGroupErr != nil {
|
||||
return nil, getGroupErr
|
||||
}
|
||||
return newWebhook, nil
|
||||
}
|
||||
|
||||
// If webhook is group scoped
|
||||
var newWebhook *gitlab.WebhookInfo
|
||||
err := p.useGitlabClient(info, func(info *gitlab.UserInfo, token *oauth2.Token) error {
|
||||
resp, err := p.GitlabClient.NewGroupHook(ctx, info, token, group, hookOptions)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
newWebhook = resp
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return newWebhook, nil
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package webhook
|
||||
|
||||
const (
|
||||
actionOpen = "open"
|
||||
actionClose = "close"
|
||||
actionMerge = "merge"
|
||||
actionReopen = "reopen"
|
||||
actionUpdate = "update"
|
||||
actionApproved = "approved"
|
||||
actionUnapproved = "unapproved"
|
||||
|
||||
stateOpened = "opened"
|
||||
stateClosed = "closed"
|
||||
stateMerged = "merged"
|
||||
|
||||
statusSuccess = "success"
|
||||
statusRunning = "running"
|
||||
statusPending = "pending"
|
||||
statusFailed = "failed"
|
||||
)
|
||||
@@ -0,0 +1,122 @@
|
||||
package webhook
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/xanzy/go-gitlab"
|
||||
)
|
||||
|
||||
func (w *webhook) HandleIssue(ctx context.Context, event *gitlab.IssueEvent, eventType gitlab.EventType) ([]*HandleWebhook, error) {
|
||||
handlers, err := w.handleDMIssue(event)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
handlers2, err := w.handleChannelIssue(ctx, event, eventType)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cleanWebhookHandlers(append(handlers, handlers2...)), nil
|
||||
}
|
||||
|
||||
func (w *webhook) handleDMIssue(event *gitlab.IssueEvent) ([]*HandleWebhook, error) {
|
||||
authorGitlabUsername := w.gitlabRetreiver.GetUsernameByID(event.ObjectAttributes.AuthorID)
|
||||
senderGitlabUsername := event.User.Username
|
||||
|
||||
message := ""
|
||||
|
||||
switch event.ObjectAttributes.Action {
|
||||
case actionOpen:
|
||||
if event.Assignees != nil && len(*event.Assignees) > 0 {
|
||||
message = fmt.Sprintf("[%s](%s) assigned you to issue [%s#%v](%s)", senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.Project.PathWithNamespace, event.ObjectAttributes.IID, event.ObjectAttributes.URL)
|
||||
}
|
||||
case actionClose:
|
||||
message = fmt.Sprintf("[%s](%s) closed your issue [%s#%v](%s)", senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.Project.PathWithNamespace, event.ObjectAttributes.IID, event.ObjectAttributes.URL)
|
||||
case actionReopen:
|
||||
message = fmt.Sprintf("[%s](%s) reopened your issue [%s#%v](%s)", senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.Project.PathWithNamespace, event.ObjectAttributes.IID, event.ObjectAttributes.URL)
|
||||
}
|
||||
|
||||
if message != "" {
|
||||
toUsers := []string{}
|
||||
if event.Assignees != nil {
|
||||
for _, assignee := range *event.Assignees {
|
||||
toUsers = append(toUsers, assignee.Username)
|
||||
}
|
||||
}
|
||||
toUsers = append(toUsers, authorGitlabUsername)
|
||||
|
||||
handlers := []*HandleWebhook{{
|
||||
Message: message,
|
||||
ToUsers: toUsers,
|
||||
From: senderGitlabUsername,
|
||||
}}
|
||||
|
||||
if mention := w.handleMention(mentionDetails{
|
||||
senderUsername: senderGitlabUsername,
|
||||
pathWithNamespace: event.Project.PathWithNamespace,
|
||||
IID: fmt.Sprintf("%d", event.ObjectAttributes.IID),
|
||||
URL: event.ObjectAttributes.URL,
|
||||
body: sanitizeDescription(event.ObjectAttributes.Description),
|
||||
}); mention != nil {
|
||||
handlers = append(handlers, mention)
|
||||
}
|
||||
return handlers, nil
|
||||
}
|
||||
return []*HandleWebhook{}, nil
|
||||
}
|
||||
|
||||
func (w *webhook) handleChannelIssue(ctx context.Context, event *gitlab.IssueEvent, eventType gitlab.EventType) ([]*HandleWebhook, error) {
|
||||
issue := event.ObjectAttributes
|
||||
senderGitlabUsername := event.User.Username
|
||||
repo := event.Project
|
||||
res := []*HandleWebhook{}
|
||||
|
||||
message := ""
|
||||
|
||||
switch issue.Action {
|
||||
case actionOpen:
|
||||
message = fmt.Sprintf("#### %s\n##### [%s#%v](%s)\n###### new issue by [%s](%s) on [%s](%s)\n\n%s", issue.Title, repo.PathWithNamespace, issue.IID, issue.URL, senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), issue.CreatedAt, issue.URL, sanitizeDescription(issue.Description))
|
||||
case actionClose:
|
||||
message = fmt.Sprintf("[%s](%s) Issue [%s](%s) closed by [%s](%s)", repo.PathWithNamespace, repo.WebURL, issue.Title, issue.URL, senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername))
|
||||
case actionReopen:
|
||||
message = fmt.Sprintf("[%s](%s) Issue [%s](%s) reopened by [%s](%s)", repo.PathWithNamespace, repo.WebURL, issue.Title, issue.URL, senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername))
|
||||
case actionUpdate:
|
||||
if len(event.Changes.Labels.Current) > 0 && !sameLabels(event.Changes.Labels.Current, event.Changes.Labels.Previous) {
|
||||
message = fmt.Sprintf("#### %s\n##### [%s#%v](%s)\n###### issue labeled `%s` by [%s](%s) on [%s](%s)\n\n%s", issue.Title, repo.PathWithNamespace, issue.IID, issue.URL, labelToString(event.Changes.Labels.Current), event.User.Username, w.gitlabRetreiver.GetUserURL(event.User.Username), issue.UpdatedAt, issue.URL, sanitizeDescription(issue.Description))
|
||||
}
|
||||
}
|
||||
|
||||
if len(message) > 0 {
|
||||
toChannels := make([]string, 0)
|
||||
namespace, project := normalizeNamespacedProject(repo.PathWithNamespace)
|
||||
subs := w.gitlabRetreiver.GetSubscribedChannelsForProject(
|
||||
ctx, namespace, project,
|
||||
repo.Visibility == gitlab.PublicVisibility,
|
||||
)
|
||||
for _, sub := range subs {
|
||||
if !sub.Issues() {
|
||||
continue
|
||||
}
|
||||
|
||||
if eventType == gitlab.EventConfidentialIssue && !sub.ConfidentialIssues() {
|
||||
continue
|
||||
}
|
||||
|
||||
if sub.Label() != "" && !containsLabel(event.Labels, sub.Label()) {
|
||||
continue
|
||||
}
|
||||
|
||||
toChannels = append(toChannels, sub.ChannelID)
|
||||
}
|
||||
|
||||
if len(toChannels) > 0 {
|
||||
res = append(res, &HandleWebhook{
|
||||
From: senderGitlabUsername,
|
||||
Message: message,
|
||||
ToUsers: []string{},
|
||||
ToChannels: toChannels,
|
||||
})
|
||||
}
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
@@ -0,0 +1,412 @@
|
||||
package webhook
|
||||
|
||||
const NewIssue = `{
|
||||
"object_kind":"issue",
|
||||
"event_type":"issue",
|
||||
"user":{
|
||||
"name":"Administrator",
|
||||
"username":"root",
|
||||
"avatar_url":"https://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80\\u0026d=identicon"
|
||||
},
|
||||
"project":{
|
||||
"id":24,
|
||||
"name":"webhook",
|
||||
"description":"",
|
||||
"web_url":"http://localhost:3000/manland/webhook",
|
||||
"avatar_url":null,
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"git_http_url":"http://localhost:3000/manland/webhook.git",
|
||||
"namespace":"manland",
|
||||
"visibility_level":20,
|
||||
"path_with_namespace":"manland/webhook",
|
||||
"default_branch":"master",
|
||||
"ci_config_path":null,
|
||||
"homepage":"http://localhost:3000/manland/webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"http_url":"http://localhost:3000/manland/webhook.git"
|
||||
},
|
||||
"object_attributes":{
|
||||
"author_id":1,
|
||||
"closed_at":null,
|
||||
"confidential":false,
|
||||
"created_at":"2019-04-06 21:03:04 UTC",
|
||||
"description":"hello world!",
|
||||
"due_date":null,
|
||||
"id":181,
|
||||
"iid":1,
|
||||
"last_edited_at":null,
|
||||
"last_edited_by_id":null,
|
||||
"milestone_id":null,
|
||||
"moved_to_id":null,
|
||||
"project_id":24,
|
||||
"relative_position":1073742323,
|
||||
"state":"opened",
|
||||
"time_estimate":0,
|
||||
"title":"test new issue",
|
||||
"updated_at":"2019-04-06 21:03:04 UTC",
|
||||
"updated_by_id":null,
|
||||
"url":"http://localhost:3000/manland/webhook/issues/1",
|
||||
"total_time_spent":0,
|
||||
"human_total_time_spent":null,
|
||||
"human_time_estimate":null,
|
||||
"assignee_ids":[50],
|
||||
"assignee_id":50,
|
||||
"action":"open"
|
||||
},
|
||||
"labels":[],
|
||||
"changes":{
|
||||
"author_id":{
|
||||
"previous":null,
|
||||
"current":1
|
||||
},
|
||||
"created_at":{
|
||||
"previous":null,
|
||||
"current":"2019-04-06 21:03:04 UTC"
|
||||
},
|
||||
"description":{
|
||||
"previous":null,
|
||||
"current":"hello world!"
|
||||
},
|
||||
"id":{
|
||||
"previous":null,
|
||||
"current":181
|
||||
},
|
||||
"iid":{
|
||||
"previous":null,
|
||||
"current":1
|
||||
},
|
||||
"project_id":{
|
||||
"previous":null,
|
||||
"current":24
|
||||
},
|
||||
"relative_position":{
|
||||
"previous":null,
|
||||
"current":1073742323
|
||||
},
|
||||
"state":{
|
||||
"previous":null,
|
||||
"current":"opened"
|
||||
},
|
||||
"title":{
|
||||
"previous":null,
|
||||
"current":"test new issue"
|
||||
},
|
||||
"updated_at":{
|
||||
"previous":null,
|
||||
"current":"2019-04-06 21:03:04 UTC"
|
||||
},
|
||||
"assignees":{
|
||||
"previous":[],
|
||||
"current":[{
|
||||
"name":"manland",
|
||||
"username":"manland",
|
||||
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
|
||||
}]
|
||||
},
|
||||
"total_time_spent":{
|
||||
"previous":null,
|
||||
"current":0
|
||||
}
|
||||
},
|
||||
"repository":{
|
||||
"name":"webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"description":"",
|
||||
"homepage":"http://localhost:3000/manland/webhook"
|
||||
},
|
||||
"assignees":[{
|
||||
"name":"manland",
|
||||
"username":"manland",
|
||||
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
|
||||
}]
|
||||
}`
|
||||
|
||||
const NewIssueUnassigned = `{
|
||||
"object_kind":"issue",
|
||||
"event_type":"issue",
|
||||
"user":{
|
||||
"name":"Administrator",
|
||||
"username":"root",
|
||||
"avatar_url":"https://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80\\u0026d=identicon"
|
||||
},
|
||||
"project":{
|
||||
"id":24,
|
||||
"name":"webhook",
|
||||
"description":"",
|
||||
"web_url":"http://localhost:3000/manland/webhook",
|
||||
"avatar_url":null,
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"git_http_url":"http://localhost:3000/manland/webhook.git",
|
||||
"namespace":"manland",
|
||||
"visibility_level":20,
|
||||
"path_with_namespace":"manland/webhook",
|
||||
"default_branch":"master",
|
||||
"ci_config_path":null,
|
||||
"homepage":"http://localhost:3000/manland/webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"http_url":"http://localhost:3000/manland/webhook.git"
|
||||
},
|
||||
"object_attributes":{
|
||||
"author_id":1,
|
||||
"closed_at":null,
|
||||
"confidential":false,
|
||||
"created_at":"2019-04-06 21:13:03 UTC",
|
||||
"description":"Hello world",
|
||||
"due_date":null,
|
||||
"id":182,
|
||||
"iid":2,
|
||||
"last_edited_at":null,
|
||||
"last_edited_by_id":null,
|
||||
"milestone_id":null,
|
||||
"moved_to_id":null,
|
||||
"project_id":24,
|
||||
"relative_position":1073742823,
|
||||
"state":"opened",
|
||||
"time_estimate":0,
|
||||
"title":"new issue",
|
||||
"updated_at":"2019-04-06 21:13:03 UTC",
|
||||
"updated_by_id":null,
|
||||
"url":"http://localhost:3000/manland/webhook/issues/2",
|
||||
"total_time_spent":0,
|
||||
"human_total_time_spent":null,
|
||||
"human_time_estimate":null,
|
||||
"assignee_ids":[],
|
||||
"assignee_id":null,
|
||||
"action":"open"
|
||||
},
|
||||
"labels":[],
|
||||
"changes":{
|
||||
"author_id":{
|
||||
"previous":null,
|
||||
"current":1
|
||||
},
|
||||
"created_at":{
|
||||
"previous":null,
|
||||
"current":"2019-04-06 21:13:03 UTC"
|
||||
},
|
||||
"description":{
|
||||
"previous":null,
|
||||
"current":"Hello world"
|
||||
},
|
||||
"id":{
|
||||
"previous":null,
|
||||
"current":182
|
||||
},
|
||||
"iid":{
|
||||
"previous":null,
|
||||
"current":2
|
||||
},
|
||||
"project_id":{
|
||||
"previous":null,
|
||||
"current":24
|
||||
},
|
||||
"relative_position":{
|
||||
"previous":null,
|
||||
"current":1073742823
|
||||
},
|
||||
"state":{
|
||||
"previous":null,
|
||||
"current":"opened"
|
||||
},
|
||||
"title":{
|
||||
"previous":null,
|
||||
"current":"new issue"
|
||||
},
|
||||
"updated_at":{
|
||||
"previous":null,
|
||||
"current":"2019-04-06 21:13:03 UTC"
|
||||
},
|
||||
"total_time_spent":{
|
||||
"previous":null,
|
||||
"current":0
|
||||
}
|
||||
},
|
||||
"repository":{
|
||||
"name":"webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"description":"",
|
||||
"homepage":"http://localhost:3000/manland/webhook"
|
||||
}
|
||||
}`
|
||||
|
||||
const CloseIssue = `{
|
||||
"object_kind":"issue",
|
||||
"event_type":"issue",
|
||||
"user":{
|
||||
"name":"manland",
|
||||
"username":"manland",
|
||||
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
|
||||
},
|
||||
"project":{
|
||||
"id":24,
|
||||
"name":"webhook",
|
||||
"description":"",
|
||||
"web_url":"http://localhost:3000/manland/webhook",
|
||||
"avatar_url":null,
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"git_http_url":"http://localhost:3000/manland/webhook.git",
|
||||
"namespace":"manland",
|
||||
"visibility_level":20,
|
||||
"path_with_namespace":"manland/webhook",
|
||||
"default_branch":"master",
|
||||
"ci_config_path":null,
|
||||
"homepage":"http://localhost:3000/manland/webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"http_url":"http://localhost:3000/manland/webhook.git"
|
||||
},
|
||||
"object_attributes":{
|
||||
"author_id":1,
|
||||
"closed_at":"2019-04-06 21:08:00 UTC",
|
||||
"confidential":false,
|
||||
"created_at":"2019-04-06 21:03:04 UTC",
|
||||
"description":"hello world!",
|
||||
"due_date":null,
|
||||
"id":181,
|
||||
"iid":1,
|
||||
"last_edited_at":null,
|
||||
"last_edited_by_id":null,
|
||||
"milestone_id":null,
|
||||
"moved_to_id":null,
|
||||
"project_id":24,
|
||||
"relative_position":1073742323,
|
||||
"state":"closed",
|
||||
"time_estimate":0,
|
||||
"title":"test new issue",
|
||||
"updated_at":"2019-04-06 21:08:00 UTC",
|
||||
"updated_by_id":null,
|
||||
"url":"http://localhost:3000/manland/webhook/issues/1",
|
||||
"total_time_spent":0,
|
||||
"human_total_time_spent":null,
|
||||
"human_time_estimate":null,
|
||||
"assignee_ids":[50],
|
||||
"assignee_id":50,
|
||||
"action":"close"
|
||||
},
|
||||
"labels":[],
|
||||
"changes":{
|
||||
"updated_at":{
|
||||
"previous":"2019-04-06 21:08:00 UTC",
|
||||
"current":"2019-04-06 21:08:00 UTC"
|
||||
},
|
||||
"assignees":{
|
||||
"previous":[],
|
||||
"current":[{
|
||||
"name":"manland",
|
||||
"username":"manland",
|
||||
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
|
||||
}]
|
||||
},
|
||||
"total_time_spent":{
|
||||
"previous":null,
|
||||
"current":0
|
||||
}
|
||||
},
|
||||
"repository":{
|
||||
"name":"webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"description":"",
|
||||
"homepage":"http://localhost:3000/manland/webhook"
|
||||
},
|
||||
"assignees":[{
|
||||
"name":"manland",
|
||||
"username":"manland",
|
||||
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
|
||||
}]
|
||||
}`
|
||||
|
||||
const ReopenIssue = `{
|
||||
"object_kind":"issue",
|
||||
"event_type":"issue",
|
||||
"user":{
|
||||
"name":"manland",
|
||||
"username":"manland",
|
||||
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
|
||||
},
|
||||
"project":{
|
||||
"id":24,
|
||||
"name":"webhook",
|
||||
"description":"",
|
||||
"web_url":"http://localhost:3000/manland/webhook",
|
||||
"avatar_url":null,
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"git_http_url":"http://localhost:3000/manland/webhook.git",
|
||||
"namespace":"manland",
|
||||
"visibility_level":20,
|
||||
"path_with_namespace":"manland/webhook",
|
||||
"default_branch":"master",
|
||||
"ci_config_path":null,
|
||||
"homepage":"http://localhost:3000/manland/webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"http_url":"http://localhost:3000/manland/webhook.git"
|
||||
},
|
||||
"object_attributes":{
|
||||
"author_id":1,
|
||||
"closed_at":null,
|
||||
"confidential":false,
|
||||
"created_at":"2019-04-06 21:03:04 UTC",
|
||||
"description":"hello world!",
|
||||
"due_date":null,
|
||||
"id":181,
|
||||
"iid":1,
|
||||
"last_edited_at":null,
|
||||
"last_edited_by_id":null,
|
||||
"milestone_id":null,
|
||||
"moved_to_id":null,
|
||||
"project_id":24,
|
||||
"relative_position":1073742323,
|
||||
"state":"opened",
|
||||
"time_estimate":0,
|
||||
"title":"test new issue",
|
||||
"updated_at":"2019-04-09 21:36:00 UTC",
|
||||
"updated_by_id":null,
|
||||
"url":"http://localhost:3000/manland/webhook/issues/1",
|
||||
"total_time_spent":0,
|
||||
"human_total_time_spent":null,
|
||||
"human_time_estimate":null,
|
||||
"assignee_ids":[50],
|
||||
"assignee_id":50,
|
||||
"action":"reopen"
|
||||
},
|
||||
"labels":[],
|
||||
"changes":{
|
||||
"closed_at":{
|
||||
"previous":"2019-04-06 21:08:00 UTC",
|
||||
"current":null
|
||||
},
|
||||
"state":{
|
||||
"previous":"closed",
|
||||
"current":"opened"
|
||||
},
|
||||
"updated_at":{
|
||||
"previous":"2019-04-06 21:08:00 UTC",
|
||||
"current":"2019-04-09 21:36:00 UTC"
|
||||
},
|
||||
"assignees":{
|
||||
"previous":[],
|
||||
"current":[{
|
||||
"name":"manland",
|
||||
"username":"manland",
|
||||
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
|
||||
}]
|
||||
},
|
||||
"total_time_spent":{
|
||||
"previous":null,
|
||||
"current":0
|
||||
}
|
||||
},
|
||||
"repository":{
|
||||
"name":"webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"description":"",
|
||||
"homepage":"http://localhost:3000/manland/webhook"
|
||||
},
|
||||
"assignees":[{
|
||||
"name":"manland",
|
||||
"username":"manland",
|
||||
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
|
||||
}]
|
||||
}`
|
||||
@@ -0,0 +1,124 @@
|
||||
package webhook
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/xanzy/go-gitlab"
|
||||
|
||||
"github.com/mattermost/mattermost-plugin-gitlab/server/subscription"
|
||||
)
|
||||
|
||||
type testDataIssueStr struct {
|
||||
testTitle string
|
||||
fixture string
|
||||
gitlabRetreiver *fakeWebhook
|
||||
res []*HandleWebhook
|
||||
}
|
||||
|
||||
var testDataIssue = []testDataIssueStr{
|
||||
{
|
||||
testTitle: "root open issue with manland assignee and display in channel1",
|
||||
fixture: NewIssue,
|
||||
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
|
||||
{ChannelID: "channel1", CreatorID: "1", Features: "issues", Repository: "manland/webhook"},
|
||||
}),
|
||||
res: []*HandleWebhook{{
|
||||
Message: "[root](http://my.gitlab.com/root) assigned you to issue [manland/webhook#1](http://localhost:3000/manland/webhook/issues/1)",
|
||||
ToUsers: []string{"manland"},
|
||||
ToChannels: []string{},
|
||||
From: "root",
|
||||
}, {
|
||||
Message: "#### test new issue\n##### [manland/webhook#1](http://localhost:3000/manland/webhook/issues/1)\n###### new issue by [root](http://my.gitlab.com/root) on [2019-04-06 21:03:04 UTC](http://localhost:3000/manland/webhook/issues/1)\n\nhello world!",
|
||||
ToUsers: []string{},
|
||||
ToChannels: []string{"channel1"},
|
||||
From: "root",
|
||||
}},
|
||||
}, {
|
||||
testTitle: "root open issue with manland assignee and display in channel1 (subgroup)",
|
||||
fixture: strings.ReplaceAll(NewIssue, "manland/webhook", "manland/subgroup/webhook"),
|
||||
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
|
||||
{ChannelID: "channel1", CreatorID: "1", Features: "issues", Repository: "manland/subgroup/webhook"},
|
||||
}),
|
||||
res: []*HandleWebhook{{
|
||||
Message: "[root](http://my.gitlab.com/root) assigned you to issue [manland/subgroup/webhook#1](http://localhost:3000/manland/subgroup/webhook/issues/1)",
|
||||
ToUsers: []string{"manland"},
|
||||
ToChannels: []string{},
|
||||
From: "root",
|
||||
}, {
|
||||
Message: "#### test new issue\n##### [manland/subgroup/webhook#1](http://localhost:3000/manland/subgroup/webhook/issues/1)\n###### new issue by [root](http://my.gitlab.com/root) on [2019-04-06 21:03:04 UTC](http://localhost:3000/manland/subgroup/webhook/issues/1)\n\nhello world!",
|
||||
ToUsers: []string{},
|
||||
ToChannels: []string{"channel1"},
|
||||
From: "root",
|
||||
}},
|
||||
}, {
|
||||
testTitle: "root open unassigned issue and display in channel",
|
||||
fixture: NewIssueUnassigned,
|
||||
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
|
||||
{ChannelID: "channel1", CreatorID: "1", Features: "issues", Repository: "manland/webhook"},
|
||||
}),
|
||||
res: []*HandleWebhook{{
|
||||
Message: "#### new issue\n##### [manland/webhook#2](http://localhost:3000/manland/webhook/issues/2)\n###### new issue by [root](http://my.gitlab.com/root) on [2019-04-06 21:13:03 UTC](http://localhost:3000/manland/webhook/issues/2)\n\nHello world",
|
||||
ToUsers: []string{},
|
||||
ToChannels: []string{"channel1"},
|
||||
From: "root",
|
||||
}}, // no DM message because root don't received its own action and manland is not assigned
|
||||
}, {
|
||||
testTitle: "manland close issue of root",
|
||||
fixture: CloseIssue,
|
||||
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
|
||||
{ChannelID: "channel1", CreatorID: "1", Features: "issues", Repository: "manland/webhook"},
|
||||
}),
|
||||
res: []*HandleWebhook{{
|
||||
Message: "[manland](http://my.gitlab.com/manland) closed your issue [manland/webhook#1](http://localhost:3000/manland/webhook/issues/1)",
|
||||
ToUsers: []string{"root"},
|
||||
ToChannels: []string{},
|
||||
From: "manland",
|
||||
}, {
|
||||
Message: "[manland/webhook](http://localhost:3000/manland/webhook) Issue [test new issue](http://localhost:3000/manland/webhook/issues/1) closed by [manland](http://my.gitlab.com/manland)",
|
||||
ToUsers: []string{},
|
||||
ToChannels: []string{"channel1"},
|
||||
From: "manland",
|
||||
}},
|
||||
}, {
|
||||
testTitle: "manland reopen issue of root and display in channel",
|
||||
fixture: ReopenIssue,
|
||||
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
|
||||
{ChannelID: "channel1", CreatorID: "1", Features: "issues", Repository: "manland/webhook"},
|
||||
}),
|
||||
res: []*HandleWebhook{{
|
||||
Message: "[manland](http://my.gitlab.com/manland) reopened your issue [manland/webhook#1](http://localhost:3000/manland/webhook/issues/1)",
|
||||
ToUsers: []string{"root"},
|
||||
From: "manland",
|
||||
}, {
|
||||
Message: "[manland/webhook](http://localhost:3000/manland/webhook) Issue [test new issue](http://localhost:3000/manland/webhook/issues/1) reopened by [manland](http://my.gitlab.com/manland)",
|
||||
ToUsers: []string{},
|
||||
ToChannels: []string{"channel1"},
|
||||
From: "manland",
|
||||
}},
|
||||
},
|
||||
}
|
||||
|
||||
func TestIssueWebhook(t *testing.T) {
|
||||
t.Parallel()
|
||||
for _, test := range testDataIssue {
|
||||
t.Run(test.testTitle, func(t *testing.T) {
|
||||
w := NewWebhook(test.gitlabRetreiver)
|
||||
issueEvent := &gitlab.IssueEvent{}
|
||||
if err := json.Unmarshal([]byte(test.fixture), issueEvent); err != nil {
|
||||
assert.Fail(t, "can't unmarshal fixture")
|
||||
}
|
||||
res, err := w.HandleIssue(context.Background(), issueEvent, gitlab.EventTypeIssue)
|
||||
assert.Empty(t, err)
|
||||
assert.Equal(t, len(test.res), len(res))
|
||||
for index := range res {
|
||||
assert.Equal(t, test.res[index].Message, res[index].Message)
|
||||
assert.EqualValues(t, test.res[index].ToUsers, res[index].ToUsers)
|
||||
assert.Equal(t, test.res[index].From, res[index].From)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
package webhook
|
||||
|
||||
const JobPending = `{
|
||||
"object_kind": "build",
|
||||
"ref": "gitlab-script-trigger",
|
||||
"tag": false,
|
||||
"before_sha": "2293ada6b400935a1378653304eaf6221e0fdb8f",
|
||||
"sha": "2293ada6b400935a1378653304eaf6221e0fdb8f",
|
||||
"build_id": 1977,
|
||||
"build_name": "test",
|
||||
"build_stage": "test",
|
||||
"build_status": "pending",
|
||||
"build_created_at": "2021-02-23T02:41:37.886Z",
|
||||
"build_started_at": null,
|
||||
"build_finished_at": null,
|
||||
"build_duration": null,
|
||||
"build_allow_failure": false,
|
||||
"build_failure_reason": "script_failure",
|
||||
"pipeline_id": 2366,
|
||||
"project_id": 380,
|
||||
"project_name": "gitlab-org/gitlab-test",
|
||||
"user": {
|
||||
"id": 3,
|
||||
"name": "User",
|
||||
"email": "user@gitlab.com",
|
||||
"avatar_url": "http://www.gravatar.com/avatar/e32bd13e2add097461cb96824b7a829c?s=80\u0026d=identicon"
|
||||
},
|
||||
"commit": {
|
||||
"id": 2366,
|
||||
"sha": "2293ada6b400935a1378653304eaf6221e0fdb8f",
|
||||
"message": "test\n",
|
||||
"author_name": "User",
|
||||
"author_email": "user@gitlab.com",
|
||||
"status": "pending",
|
||||
"duration": null,
|
||||
"started_at": null,
|
||||
"finished_at": null
|
||||
},
|
||||
"repository": {
|
||||
"name": "gitlab_test",
|
||||
"description": "Atque in sunt eos similique dolores voluptatem.",
|
||||
"homepage": "http://192.168.64.1:3005/gitlab-org/gitlab-test",
|
||||
"git_ssh_url": "git@192.168.64.1:gitlab-org/gitlab-test.git",
|
||||
"git_http_url": "http://192.168.64.1:3005/gitlab-org/gitlab-test.git",
|
||||
"visibility_level": 20
|
||||
},
|
||||
"runner": {
|
||||
"active": true,
|
||||
"runner_type": "project_type",
|
||||
"is_shared": false,
|
||||
"id": 380987,
|
||||
"description": "shared-runners-manager-6.gitlab.com",
|
||||
"tags": [
|
||||
"linux",
|
||||
"docker"
|
||||
]
|
||||
},
|
||||
"environment": null
|
||||
}`
|
||||
|
||||
const JobRunning = `{
|
||||
"object_kind": "build",
|
||||
"ref": "gitlab-script-trigger",
|
||||
"tag": false,
|
||||
"before_sha": "2293ada6b400935a1378653304eaf6221e0fdb8f",
|
||||
"sha": "2293ada6b400935a1378653304eaf6221e0fdb8f",
|
||||
"build_id": 1977,
|
||||
"build_name": "test",
|
||||
"build_stage": "test",
|
||||
"build_status": "running",
|
||||
"build_created_at": "2021-02-23T02:41:37.886Z",
|
||||
"build_started_at": null,
|
||||
"build_finished_at": null,
|
||||
"build_duration": null,
|
||||
"build_allow_failure": false,
|
||||
"build_failure_reason": "script_failure",
|
||||
"pipeline_id": 2366,
|
||||
"project_id": 380,
|
||||
"project_name": "gitlab-org/gitlab-test",
|
||||
"user": {
|
||||
"id": 3,
|
||||
"name": "User",
|
||||
"email": "user@gitlab.com",
|
||||
"avatar_url": "http://www.gravatar.com/avatar/e32bd13e2add097461cb96824b7a829c?s=80\u0026d=identicon"
|
||||
},
|
||||
"commit": {
|
||||
"id": 2366,
|
||||
"sha": "2293ada6b400935a1378653304eaf6221e0fdb8f",
|
||||
"message": "test\n",
|
||||
"author_name": "User",
|
||||
"author_email": "user@gitlab.com",
|
||||
"status": "running",
|
||||
"duration": null,
|
||||
"started_at": null,
|
||||
"finished_at": null
|
||||
},
|
||||
"repository": {
|
||||
"name": "gitlab_test",
|
||||
"description": "Atque in sunt eos similique dolores voluptatem.",
|
||||
"homepage": "http://192.168.64.1:3005/gitlab-org/gitlab-test",
|
||||
"git_ssh_url": "git@192.168.64.1:gitlab-org/gitlab-test.git",
|
||||
"git_http_url": "http://192.168.64.1:3005/gitlab-org/gitlab-test.git",
|
||||
"visibility_level": 20
|
||||
},
|
||||
"runner": {
|
||||
"active": true,
|
||||
"runner_type": "project_type",
|
||||
"is_shared": false,
|
||||
"id": 380987,
|
||||
"description": "shared-runners-manager-6.gitlab.com",
|
||||
"tags": [
|
||||
"linux",
|
||||
"docker"
|
||||
]
|
||||
},
|
||||
"environment": null
|
||||
}`
|
||||
|
||||
const JobSuccess = `{
|
||||
"object_kind": "build",
|
||||
"ref": "gitlab-script-trigger",
|
||||
"tag": false,
|
||||
"before_sha": "2293ada6b400935a1378653304eaf6221e0fdb8f",
|
||||
"sha": "2293ada6b400935a1378653304eaf6221e0fdb8f",
|
||||
"build_id": 1977,
|
||||
"build_name": "test",
|
||||
"build_stage": "test",
|
||||
"build_status": "success",
|
||||
"build_created_at": "2021-02-23T02:41:37.886Z",
|
||||
"build_started_at": null,
|
||||
"build_finished_at": null,
|
||||
"build_duration": null,
|
||||
"build_allow_failure": false,
|
||||
"build_failure_reason": "script_failure",
|
||||
"pipeline_id": 2366,
|
||||
"project_id": 380,
|
||||
"project_name": "gitlab-org/gitlab-test",
|
||||
"user": {
|
||||
"id": 3,
|
||||
"name": "User",
|
||||
"email": "user@gitlab.com",
|
||||
"avatar_url": "http://www.gravatar.com/avatar/e32bd13e2add097461cb96824b7a829c?s=80\u0026d=identicon"
|
||||
},
|
||||
"commit": {
|
||||
"id": 2366,
|
||||
"sha": "2293ada6b400935a1378653304eaf6221e0fdb8f",
|
||||
"message": "test\n",
|
||||
"author_name": "User",
|
||||
"author_email": "user@gitlab.com",
|
||||
"status": "success",
|
||||
"duration": null,
|
||||
"started_at": null,
|
||||
"finished_at": null
|
||||
},
|
||||
"repository": {
|
||||
"name": "gitlab_test",
|
||||
"description": "Atque in sunt eos similique dolores voluptatem.",
|
||||
"homepage": "http://192.168.64.1:3005/gitlab-org/gitlab-test",
|
||||
"git_ssh_url": "git@192.168.64.1:gitlab-org/gitlab-test.git",
|
||||
"git_http_url": "http://192.168.64.1:3005/gitlab-org/gitlab-test.git",
|
||||
"visibility_level": 20
|
||||
},
|
||||
"runner": {
|
||||
"active": true,
|
||||
"runner_type": "project_type",
|
||||
"is_shared": false,
|
||||
"id": 380987,
|
||||
"description": "shared-runners-manager-6.gitlab.com",
|
||||
"tags": [
|
||||
"linux",
|
||||
"docker"
|
||||
]
|
||||
},
|
||||
"environment": null
|
||||
}`
|
||||
|
||||
const JobFailed = `{
|
||||
"object_kind": "build",
|
||||
"ref": "gitlab-script-trigger",
|
||||
"tag": false,
|
||||
"before_sha": "2293ada6b400935a1378653304eaf6221e0fdb8f",
|
||||
"sha": "2293ada6b400935a1378653304eaf6221e0fdb8f",
|
||||
"build_id": 1977,
|
||||
"build_name": "test",
|
||||
"build_stage": "test",
|
||||
"build_status": "failed",
|
||||
"build_created_at": "2021-02-23T02:41:37.886Z",
|
||||
"build_started_at": null,
|
||||
"build_finished_at": null,
|
||||
"build_duration": null,
|
||||
"build_allow_failure": false,
|
||||
"build_failure_reason": "script_failure",
|
||||
"pipeline_id": 2366,
|
||||
"project_id": 380,
|
||||
"project_name": "gitlab-org/gitlab-test",
|
||||
"user": {
|
||||
"id": 3,
|
||||
"name": "User",
|
||||
"email": "user@gitlab.com",
|
||||
"avatar_url": "http://www.gravatar.com/avatar/e32bd13e2add097461cb96824b7a829c?s=80\u0026d=identicon"
|
||||
},
|
||||
"commit": {
|
||||
"id": 2366,
|
||||
"sha": "2293ada6b400935a1378653304eaf6221e0fdb8f",
|
||||
"message": "test\n",
|
||||
"author_name": "User",
|
||||
"author_email": "user@gitlab.com",
|
||||
"status": "failed",
|
||||
"duration": null,
|
||||
"started_at": null,
|
||||
"finished_at": null
|
||||
},
|
||||
"repository": {
|
||||
"name": "gitlab_test",
|
||||
"description": "Atque in sunt eos similique dolores voluptatem.",
|
||||
"homepage": "http://192.168.64.1:3005/gitlab-org/gitlab-test",
|
||||
"git_ssh_url": "git@192.168.64.1:gitlab-org/gitlab-test.git",
|
||||
"git_http_url": "http://192.168.64.1:3005/gitlab-org/gitlab-test.git",
|
||||
"visibility_level": 20
|
||||
},
|
||||
"runner": {
|
||||
"active": true,
|
||||
"runner_type": "project_type",
|
||||
"is_shared": false,
|
||||
"id": 380987,
|
||||
"description": "shared-runners-manager-6.gitlab.com",
|
||||
"tags": [
|
||||
"linux",
|
||||
"docker"
|
||||
]
|
||||
},
|
||||
"environment": null
|
||||
}`
|
||||
@@ -0,0 +1,71 @@
|
||||
package webhook
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/xanzy/go-gitlab"
|
||||
)
|
||||
|
||||
func (w *webhook) HandleJobs(ctx context.Context, event *gitlab.JobEvent) ([]*HandleWebhook, error) {
|
||||
handlers, err := w.handleChannelJob(ctx, event)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cleanWebhookHandlers(handlers), nil
|
||||
}
|
||||
|
||||
func (w *webhook) handleChannelJob(ctx context.Context, event *gitlab.JobEvent) ([]*HandleWebhook, error) {
|
||||
senderGitlabUsername := event.User.Name
|
||||
repo := event.Repository
|
||||
res := []*HandleWebhook{}
|
||||
message := ""
|
||||
message = fmt.Sprintf("### Pipeline Job Stage: **%s**\n", event.BuildStage)
|
||||
|
||||
switch event.BuildStatus {
|
||||
case statusRunning:
|
||||
message += fmt.Sprintf(":rocket: **Status**: %s\n", event.BuildStatus)
|
||||
case statusPending:
|
||||
message = fmt.Sprintf("### Pipeline Job Stage: **%s**\n", event.BuildStage)
|
||||
message += fmt.Sprintf(":clock1: **Status**: %s\n", event.BuildStatus)
|
||||
case statusSuccess:
|
||||
message = fmt.Sprintf("### Pipeline Job Stage: **%s**\n", event.BuildStage)
|
||||
message += fmt.Sprintf(":large_green_circle: **Status**: %s\n", event.BuildStatus)
|
||||
case statusFailed:
|
||||
message = fmt.Sprintf("### Pipeline Job Stage: **%s**\n", event.BuildStage)
|
||||
message += fmt.Sprintf(":red_circle: **Status**: %s\n", event.BuildStatus)
|
||||
message += fmt.Sprintf("**Reason Failed**: %s\n", event.BuildFailureReason)
|
||||
default:
|
||||
return res, nil
|
||||
}
|
||||
namespaceMetadata, err := normalizeNamespacedProjectByHomepage(event.Repository.Homepage)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fullNamespacePath := fmt.Sprintf("%s/%s", namespaceMetadata.Namespace, namespaceMetadata.Project)
|
||||
message += fmt.Sprintf("**Repository**: [%s](%s)\n", fullNamespacePath, event.Repository.GitHTTPURL)
|
||||
message += fmt.Sprintf("**Triggered By**: %s\n", senderGitlabUsername)
|
||||
message += fmt.Sprintf("**Visit job [here](%s)** \n", w.gitlabRetreiver.GetJobURL(fullNamespacePath, event.BuildID))
|
||||
toChannels := make([]string, 0)
|
||||
subs := w.gitlabRetreiver.GetSubscribedChannelsForProject(
|
||||
ctx, namespaceMetadata.Namespace, namespaceMetadata.Project,
|
||||
repo.Visibility == gitlab.PublicVisibility,
|
||||
)
|
||||
for _, sub := range subs {
|
||||
if !sub.Jobs() {
|
||||
continue
|
||||
}
|
||||
|
||||
toChannels = append(toChannels, sub.ChannelID)
|
||||
}
|
||||
if len(toChannels) > 0 {
|
||||
res = append(res, &HandleWebhook{
|
||||
From: senderGitlabUsername,
|
||||
Message: message,
|
||||
ToUsers: []string{},
|
||||
ToChannels: toChannels,
|
||||
})
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package webhook
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/xanzy/go-gitlab"
|
||||
|
||||
"github.com/mattermost/mattermost-plugin-gitlab/server/subscription"
|
||||
)
|
||||
|
||||
type testDataJobsStr struct {
|
||||
testTitle string
|
||||
fixture string
|
||||
gitlabRetreiver *fakeWebhook
|
||||
res []*HandleWebhook
|
||||
}
|
||||
|
||||
var testDataJobs = []testDataJobsStr{
|
||||
{
|
||||
testTitle: "root start a job in running",
|
||||
fixture: JobRunning,
|
||||
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
|
||||
{ChannelID: "channel1", CreatorID: "1", Features: "jobs", Repository: "manland/webhook"},
|
||||
}),
|
||||
res: []*HandleWebhook{{
|
||||
Message: "### Pipeline Job Stage: **test**\n:rocket: **Status**: running\n**Repository**: [gitlab-org/gitlab-test](http://192.168.64.1:3005/gitlab-org/gitlab-test.git)\n**Triggered By**: User\n**Visit job [here](http://my.gitlab.com/gitlab-org/gitlab-test/-/jobs/1977)** \n",
|
||||
ToUsers: []string{}, // No DM because user know he has launch a pipeline
|
||||
ToChannels: []string{"channel1"},
|
||||
From: "User",
|
||||
}},
|
||||
},
|
||||
{
|
||||
testTitle: "root start a job in pending",
|
||||
fixture: JobPending,
|
||||
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
|
||||
{ChannelID: "channel1", CreatorID: "1", Features: "jobs", Repository: "manland/webhook"},
|
||||
}),
|
||||
res: []*HandleWebhook{{
|
||||
Message: "### Pipeline Job Stage: **test**\n:clock1: **Status**: pending\n**Repository**: [gitlab-org/gitlab-test](http://192.168.64.1:3005/gitlab-org/gitlab-test.git)\n**Triggered By**: User\n**Visit job [here](http://my.gitlab.com/gitlab-org/gitlab-test/-/jobs/1977)** \n",
|
||||
ToUsers: []string{}, // No DM because user know he has launch a pipeline
|
||||
ToChannels: []string{"channel1"},
|
||||
From: "User",
|
||||
}},
|
||||
},
|
||||
{
|
||||
testTitle: "root start a job in running (subgroup)",
|
||||
fixture: strings.ReplaceAll(JobRunning, "manland/webhook", "manland/subgroup/webhook"),
|
||||
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
|
||||
{ChannelID: "channel1", CreatorID: "1", Features: "jobs", Repository: "manland/subgroup/webhook"},
|
||||
}),
|
||||
res: []*HandleWebhook{{
|
||||
Message: "### Pipeline Job Stage: **test**\n:rocket: **Status**: running\n**Repository**: [gitlab-org/gitlab-test](http://192.168.64.1:3005/gitlab-org/gitlab-test.git)\n**Triggered By**: User\n**Visit job [here](http://my.gitlab.com/gitlab-org/gitlab-test/-/jobs/1977)** \n",
|
||||
ToUsers: []string{}, // No DM because user know he has launch a pipeline
|
||||
ToChannels: []string{"channel1"},
|
||||
From: "User",
|
||||
}},
|
||||
},
|
||||
{
|
||||
testTitle: "root start a job in success",
|
||||
fixture: JobSuccess,
|
||||
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
|
||||
{ChannelID: "channel1", CreatorID: "1", Features: "jobs", Repository: "manland/webhook"},
|
||||
}),
|
||||
res: []*HandleWebhook{{
|
||||
Message: "### Pipeline Job Stage: **test**\n:large_green_circle: **Status**: success\n**Repository**: [gitlab-org/gitlab-test](http://192.168.64.1:3005/gitlab-org/gitlab-test.git)\n**Triggered By**: User\n**Visit job [here](http://my.gitlab.com/gitlab-org/gitlab-test/-/jobs/1977)** \n",
|
||||
ToUsers: []string{}, // No DM because user know he has launch a pipeline
|
||||
ToChannels: []string{"channel1"},
|
||||
From: "User",
|
||||
}},
|
||||
},
|
||||
{
|
||||
testTitle: "root start a job in failed",
|
||||
fixture: JobFailed,
|
||||
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
|
||||
{ChannelID: "channel1", CreatorID: "1", Features: "jobs", Repository: "manland/webhook"},
|
||||
}),
|
||||
res: []*HandleWebhook{{
|
||||
Message: "### Pipeline Job Stage: **test**\n:red_circle: **Status**: failed\n**Reason Failed**: script_failure\n**Repository**: [gitlab-org/gitlab-test](http://192.168.64.1:3005/gitlab-org/gitlab-test.git)\n**Triggered By**: User\n**Visit job [here](http://my.gitlab.com/gitlab-org/gitlab-test/-/jobs/1977)** \n",
|
||||
ToUsers: []string{}, // No DM because user know he has launch a pipeline
|
||||
ToChannels: []string{"channel1"},
|
||||
From: "User",
|
||||
}},
|
||||
},
|
||||
}
|
||||
|
||||
func TestJobWebhook(t *testing.T) {
|
||||
t.Parallel()
|
||||
for _, test := range testDataJobs {
|
||||
t.Run(test.testTitle, func(t *testing.T) {
|
||||
w := NewWebhook(test.gitlabRetreiver)
|
||||
jobEvent := &gitlab.JobEvent{}
|
||||
if err := json.Unmarshal([]byte(test.fixture), jobEvent); err != nil {
|
||||
assert.Fail(t, "can't unmarshal fixture")
|
||||
}
|
||||
res, err := w.HandleJobs(context.Background(), jobEvent)
|
||||
assert.Empty(t, err)
|
||||
assert.Equal(t, len(test.res), len(res))
|
||||
for index := range res {
|
||||
assert.Equal(t, test.res[index].Message, res[index].Message)
|
||||
assert.Equal(t, test.res[index].ToUsers, res[index].ToUsers)
|
||||
assert.Equal(t, test.res[index].From, res[index].From)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package webhook
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/xanzy/go-gitlab"
|
||||
)
|
||||
|
||||
func (w *webhook) HandleMergeRequest(ctx context.Context, event *gitlab.MergeEvent) ([]*HandleWebhook, error) {
|
||||
handlers, err := w.handleDMMergeRequest(event)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
handlers2, err := w.handleChannelMergeRequest(ctx, event)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cleanWebhookHandlers(append(handlers, handlers2...)), nil
|
||||
}
|
||||
|
||||
func (w *webhook) handleDMMergeRequest(event *gitlab.MergeEvent) ([]*HandleWebhook, error) {
|
||||
authorGitlabUsername := w.gitlabRetreiver.GetUsernameByID(event.ObjectAttributes.AuthorID)
|
||||
senderGitlabUsername := event.User.Username
|
||||
|
||||
toUsers := []string{authorGitlabUsername}
|
||||
for _, assigneeID := range event.ObjectAttributes.AssigneeIDs {
|
||||
toUsers = append(toUsers, w.gitlabRetreiver.GetUsernameByID(assigneeID))
|
||||
}
|
||||
|
||||
message := ""
|
||||
|
||||
switch event.ObjectAttributes.State {
|
||||
case stateOpened:
|
||||
switch event.ObjectAttributes.Action {
|
||||
case actionOpen:
|
||||
message = fmt.Sprintf("[%s](%s) requested your review on [%s!%v](%s)", senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.ObjectAttributes.Target.PathWithNamespace, event.ObjectAttributes.IID, event.ObjectAttributes.URL)
|
||||
case actionReopen:
|
||||
message = fmt.Sprintf("[%s](%s) reopened your merge request [%s!%v](%s)", senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.ObjectAttributes.Target.PathWithNamespace, event.ObjectAttributes.IID, event.ObjectAttributes.URL)
|
||||
case actionUpdate:
|
||||
toUsers = []string{authorGitlabUsername}
|
||||
|
||||
// Not going to show notification in case of commit push.
|
||||
if event.ObjectAttributes.OldRev != "" {
|
||||
break
|
||||
}
|
||||
|
||||
for _, currentAssigneeID := range event.ObjectAttributes.AssigneeIDs {
|
||||
assignedInPrevious := false
|
||||
for _, previousAssignee := range event.Changes.Assignees.Previous {
|
||||
if previousAssignee.ID == currentAssigneeID {
|
||||
assignedInPrevious = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !assignedInPrevious {
|
||||
toUsers = append(toUsers, w.gitlabRetreiver.GetUsernameByID(currentAssigneeID))
|
||||
}
|
||||
}
|
||||
|
||||
message = fmt.Sprintf("[%s](%s) assigned you to merge request [%s!%v](%s)", senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.ObjectAttributes.Target.PathWithNamespace, event.ObjectAttributes.IID, event.ObjectAttributes.URL)
|
||||
case actionApproved:
|
||||
message = fmt.Sprintf("[%s](%s) approved your merge request [%s!%v](%s)", senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.ObjectAttributes.Target.PathWithNamespace, event.ObjectAttributes.IID, event.ObjectAttributes.URL)
|
||||
case actionUnapproved:
|
||||
message = fmt.Sprintf("[%s](%s) requested changes to your merge request [%s!%v](%s)", senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.ObjectAttributes.Target.PathWithNamespace, event.ObjectAttributes.IID, event.ObjectAttributes.URL)
|
||||
}
|
||||
case stateClosed:
|
||||
message = fmt.Sprintf("[%s](%s) closed your merge request [%s!%v](%s)", senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.ObjectAttributes.Target.PathWithNamespace, event.ObjectAttributes.IID, event.ObjectAttributes.URL)
|
||||
case stateMerged:
|
||||
if event.ObjectAttributes.Action == actionMerge {
|
||||
message = fmt.Sprintf("[%s](%s) merged your merge request [%s!%v](%s)", senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.ObjectAttributes.Target.PathWithNamespace, event.ObjectAttributes.IID, event.ObjectAttributes.URL)
|
||||
}
|
||||
}
|
||||
|
||||
if len(message) > 0 {
|
||||
handlers := []*HandleWebhook{{
|
||||
Message: message,
|
||||
ToUsers: toUsers,
|
||||
ToChannels: []string{},
|
||||
From: senderGitlabUsername,
|
||||
}}
|
||||
|
||||
if mention := w.handleMention(mentionDetails{
|
||||
senderUsername: senderGitlabUsername,
|
||||
pathWithNamespace: event.Project.PathWithNamespace,
|
||||
IID: fmt.Sprintf("%d", event.ObjectAttributes.IID),
|
||||
URL: event.ObjectAttributes.URL,
|
||||
body: sanitizeDescription(event.ObjectAttributes.Description),
|
||||
}); mention != nil {
|
||||
handlers = append(handlers, mention)
|
||||
}
|
||||
return handlers, nil
|
||||
}
|
||||
return []*HandleWebhook{{From: senderGitlabUsername}}, nil
|
||||
}
|
||||
|
||||
func (w *webhook) handleChannelMergeRequest(ctx context.Context, event *gitlab.MergeEvent) ([]*HandleWebhook, error) {
|
||||
senderGitlabUsername := event.User.Username
|
||||
pr := event.ObjectAttributes
|
||||
repo := event.Project
|
||||
res := []*HandleWebhook{}
|
||||
|
||||
message := ""
|
||||
|
||||
switch pr.Action {
|
||||
case actionOpen:
|
||||
message = fmt.Sprintf("#### %s\n##### [%s!%v](%s) new merge-request by [%s](%s) on [%s](%s)\n\n%s", pr.Title, repo.PathWithNamespace, pr.IID, pr.URL, senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), pr.CreatedAt, pr.URL, sanitizeDescription(pr.Description))
|
||||
case actionMerge:
|
||||
message = fmt.Sprintf("[%s](%s) Merge request [!%v %s](%s) was merged by [%s](%s)", repo.PathWithNamespace, repo.WebURL, pr.IID, pr.Title, pr.URL, senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername))
|
||||
case actionClose:
|
||||
message = fmt.Sprintf("[%s](%s) Merge request [!%v %s](%s) was closed by [%s](%s)", repo.PathWithNamespace, repo.WebURL, pr.IID, pr.Title, pr.URL, senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername))
|
||||
case actionReopen:
|
||||
message = fmt.Sprintf("[%s](%s) Merge request [!%v %s](%s) was reopened by [%s](%s)", repo.PathWithNamespace, repo.WebURL, pr.IID, pr.Title, pr.URL, senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername))
|
||||
case actionApproved:
|
||||
message = fmt.Sprintf("[%s](%s) Merge request [!%v %s](%s) was approved by [%s](%s)", repo.PathWithNamespace, repo.WebURL, pr.IID, pr.Title, pr.URL, senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername))
|
||||
case actionUnapproved:
|
||||
message = fmt.Sprintf("[%s](%s) Merge request [!%v %s](%s) changes were requested by [%s](%s)", repo.PathWithNamespace, repo.WebURL, pr.IID, pr.Title, pr.URL, senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername))
|
||||
}
|
||||
|
||||
if len(message) > 0 {
|
||||
toChannels := make([]string, 0)
|
||||
namespace, project := normalizeNamespacedProject(repo.PathWithNamespace)
|
||||
subs := w.gitlabRetreiver.GetSubscribedChannelsForProject(
|
||||
ctx, namespace, project,
|
||||
repo.Visibility == gitlab.PublicVisibility,
|
||||
)
|
||||
for _, sub := range subs {
|
||||
if !sub.Merges() {
|
||||
continue
|
||||
}
|
||||
|
||||
if sub.Label() != "" && !containsLabel(event.Labels, sub.Label()) {
|
||||
continue
|
||||
}
|
||||
|
||||
toChannels = append(toChannels, sub.ChannelID)
|
||||
}
|
||||
|
||||
if len(toChannels) > 0 {
|
||||
res = append(res, &HandleWebhook{
|
||||
From: senderGitlabUsername,
|
||||
Message: message,
|
||||
ToUsers: []string{},
|
||||
ToChannels: toChannels,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
@@ -0,0 +1,968 @@
|
||||
package webhook
|
||||
|
||||
const OpenMergeRequest = `{
|
||||
"object_kind":"merge_request",
|
||||
"event_type":"merge_request",
|
||||
"user":{
|
||||
"name":"Administrator",
|
||||
"username":"root",
|
||||
"avatar_url":"https://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80\\u0026d=identicon"
|
||||
},
|
||||
"project":{
|
||||
"id":24,
|
||||
"name":"webhook",
|
||||
"description":"",
|
||||
"web_url":"http://localhost:3000/manland/webhook",
|
||||
"avatar_url":null,
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"git_http_url":"http://localhost:3000/manland/webhook.git",
|
||||
"namespace":"manland",
|
||||
"visibility_level":20,
|
||||
"path_with_namespace":"manland/webhook",
|
||||
"default_branch":"master",
|
||||
"ci_config_path":null,
|
||||
"homepage":"http://localhost:3000/manland/webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"http_url":"http://localhost:3000/manland/webhook.git"
|
||||
},
|
||||
"object_attributes":{
|
||||
"assignee_id":50,
|
||||
"author_id":1,
|
||||
"created_at":"2019-04-03 21:07:32 UTC",
|
||||
"description":"test open merge request",
|
||||
"head_pipeline_id":57,
|
||||
"id":35,
|
||||
"iid":4,
|
||||
"last_edited_at":null,
|
||||
"last_edited_by_id":null,
|
||||
"merge_commit_sha":null,
|
||||
"merge_error":null,
|
||||
"merge_params":{
|
||||
"force_remove_source_branch":null
|
||||
},
|
||||
"merge_status":"unchecked",
|
||||
"merge_user_id":null,
|
||||
"merge_when_pipeline_succeeds":false,
|
||||
"milestone_id":null,
|
||||
"source_branch":"master",
|
||||
"source_project_id":25,
|
||||
"state":"opened",
|
||||
"target_branch":"master",
|
||||
"target_project_id":24,
|
||||
"time_estimate":0,
|
||||
"title":"Master",
|
||||
"updated_at":"2019-04-03 21:07:32 UTC",
|
||||
"updated_by_id":null,
|
||||
"url":"http://localhost:3000/manland/webhook/merge_requests/4",
|
||||
"source":{
|
||||
"id":25,
|
||||
"name":"webhook",
|
||||
"description":"",
|
||||
"web_url":"http://localhost:3000/root/webhook",
|
||||
"avatar_url":null,
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
|
||||
"git_http_url":"http://localhost:3000/root/webhook.git",
|
||||
"namespace":"root",
|
||||
"visibility_level":20,
|
||||
"path_with_namespace":"root/webhook",
|
||||
"default_branch":"master",
|
||||
"ci_config_path":null,
|
||||
"homepage":"http://localhost:3000/root/webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
|
||||
"ssh_url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
|
||||
"http_url":"http://localhost:3000/root/webhook.git"
|
||||
},
|
||||
"target":{
|
||||
"id":24,
|
||||
"name":"webhook",
|
||||
"description":"",
|
||||
"web_url":"http://localhost:3000/manland/webhook",
|
||||
"avatar_url":null,
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"git_http_url":"http://localhost:3000/manland/webhook.git",
|
||||
"namespace":"manland",
|
||||
"visibility_level":20,
|
||||
"path_with_namespace":"manland/webhook",
|
||||
"default_branch":"master",
|
||||
"ci_config_path":null,
|
||||
"homepage":"http://localhost:3000/manland/webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"http_url":"http://localhost:3000/manland/webhook.git"
|
||||
},
|
||||
"last_commit":{
|
||||
"id":"1fd967c14f8265a6056525c343d984ce56472d5c",
|
||||
"message":"Update README.md",
|
||||
"timestamp":"2019-04-03T21:04:58Z",
|
||||
"url":"http://localhost:3000/manland/webhook/commit/1fd967c14f8265a6056525c343d984ce56472d5c",
|
||||
"author":{
|
||||
"name":"Administrator",
|
||||
"email":"admin@example.com"
|
||||
}
|
||||
},
|
||||
"work_in_progress":false,
|
||||
"total_time_spent":0,
|
||||
"human_total_time_spent":null,
|
||||
"human_time_estimate":null,
|
||||
"assignee_ids": [
|
||||
50
|
||||
],
|
||||
"action":"open"
|
||||
},
|
||||
"labels":[],
|
||||
"changes":{
|
||||
"head_pipeline_id":{
|
||||
"previous":null,
|
||||
"current":57
|
||||
},
|
||||
"updated_at":{
|
||||
"previous":"2019-04-03 21:07:32 UTC",
|
||||
"current":"2019-04-03 21:07:32 UTC"
|
||||
},
|
||||
"assignee":{
|
||||
"previous":null,
|
||||
"current":{
|
||||
"name":"manland",
|
||||
"username":"manland",
|
||||
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
|
||||
}
|
||||
},
|
||||
"total_time_spent":{
|
||||
"previous":null,
|
||||
"current":0
|
||||
}
|
||||
},
|
||||
"repository":{
|
||||
"name":"webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"description":"",
|
||||
"homepage":"http://localhost:3000/manland/webhook"
|
||||
},
|
||||
"assignee":{
|
||||
"name":"manland",
|
||||
"username":"manland",
|
||||
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
|
||||
}
|
||||
}`
|
||||
|
||||
const ReopenMerge = `{
|
||||
"object_kind":"merge_request",
|
||||
"event_type":"merge_request",
|
||||
"user":{
|
||||
"name":"manland",
|
||||
"username":"manland",
|
||||
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
|
||||
},
|
||||
"project":{
|
||||
"id":24,
|
||||
"name":"webhook",
|
||||
"description":"",
|
||||
"web_url":"http://localhost:3000/manland/webhook",
|
||||
"avatar_url":null,
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"git_http_url":"http://localhost:3000/manland/webhook.git",
|
||||
"namespace":"manland",
|
||||
"visibility_level":20,
|
||||
"path_with_namespace":"manland/webhook",
|
||||
"default_branch":"master",
|
||||
"ci_config_path":null,
|
||||
"homepage":"http://localhost:3000/manland/webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"http_url":"http://localhost:3000/manland/webhook.git"
|
||||
},
|
||||
"object_attributes":{
|
||||
"assignee_id":null,
|
||||
"author_id":1,
|
||||
"created_at":"2019-04-01 20:25:41 UTC",
|
||||
"description":"# Et voila\\n\\nC'est tro pbien",
|
||||
"head_pipeline_id":56,
|
||||
"id":34,
|
||||
"iid":1,
|
||||
"last_edited_at":null,
|
||||
"last_edited_by_id":null,
|
||||
"merge_commit_sha":null,
|
||||
"merge_error":null,
|
||||
"merge_params":{
|
||||
"force_remove_source_branch":null
|
||||
},
|
||||
"merge_status":"can_be_merged",
|
||||
"merge_user_id":null,
|
||||
"merge_when_pipeline_succeeds":false,
|
||||
"milestone_id":null,
|
||||
"source_branch":"master",
|
||||
"source_project_id":25,
|
||||
"state":"opened",
|
||||
"target_branch":"master",
|
||||
"target_project_id":24,
|
||||
"time_estimate":0,
|
||||
"title":"Update README.md",
|
||||
"updated_at":"2019-04-01 21:34:16 UTC",
|
||||
"updated_by_id":50,
|
||||
"url":"http://localhost:3000/manland/webhook/merge_requests/1",
|
||||
"source":{
|
||||
"id":25,
|
||||
"name":"webhook",
|
||||
"description":"",
|
||||
"web_url":"http://localhost:3000/root/webhook",
|
||||
"avatar_url":null,
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
|
||||
"git_http_url":"http://localhost:3000/root/webhook.git",
|
||||
"namespace":"root",
|
||||
"visibility_level":20,
|
||||
"path_with_namespace":"root/webhook",
|
||||
"default_branch":"master",
|
||||
"ci_config_path":null,
|
||||
"homepage":"http://localhost:3000/root/webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
|
||||
"ssh_url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
|
||||
"http_url":"http://localhost:3000/root/webhook.git"
|
||||
},
|
||||
"target":{
|
||||
"id":24,
|
||||
"name":"webhook",
|
||||
"description":"",
|
||||
"web_url":"http://localhost:3000/manland/webhook",
|
||||
"avatar_url":null,
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"git_http_url":"http://localhost:3000/manland/webhook.git",
|
||||
"namespace":"manland",
|
||||
"visibility_level":20,
|
||||
"path_with_namespace":"manland/webhook",
|
||||
"default_branch":"master",
|
||||
"ci_config_path":null,
|
||||
"homepage":"http://localhost:3000/manland/webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"http_url":"http://localhost:3000/manland/webhook.git"
|
||||
},
|
||||
"last_commit":{
|
||||
"id":"9efcb9dc895dc6dbf19fdd6f2bdbf3e778870eb2",
|
||||
"message":"Update README.md",
|
||||
"timestamp":"2019-04-01T20:44:25Z",
|
||||
"url":"http://localhost:3000/manland/webhook/commit/9efcb9dc895dc6dbf19fdd6f2bdbf3e778870eb2",
|
||||
"author":{
|
||||
"name":"Administrator",
|
||||
"email":"admin@example.com"
|
||||
}
|
||||
},
|
||||
"work_in_progress":false,
|
||||
"total_time_spent":0,
|
||||
"human_total_time_spent":null,
|
||||
"human_time_estimate":null,
|
||||
"action":"reopen"
|
||||
},
|
||||
"labels":[],
|
||||
"changes":{
|
||||
"state":{
|
||||
"previous":"closed",
|
||||
"current":"opened"
|
||||
},
|
||||
"updated_at":{
|
||||
"previous":"2019-04-01 21:34:13 UTC",
|
||||
"current":"2019-04-01 21:34:16 UTC"
|
||||
},
|
||||
"total_time_spent":{
|
||||
"previous":null,
|
||||
"current":0
|
||||
}
|
||||
},
|
||||
"repository":{
|
||||
"name":"webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"description":"",
|
||||
"homepage":"http://localhost:3000/manland/webhook"
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
const CloseMergeRequestByAssignee = `{
|
||||
"object_kind":"merge_request",
|
||||
"event_type":"merge_request",
|
||||
"user":{
|
||||
"name":"manland",
|
||||
"username":"manland",
|
||||
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
|
||||
},
|
||||
"project":{
|
||||
"id":24,
|
||||
"name":"webhook",
|
||||
"description":"",
|
||||
"web_url":"http://localhost:3000/manland/webhook",
|
||||
"avatar_url":null,
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"git_http_url":"http://localhost:3000/manland/webhook.git",
|
||||
"namespace":"manland",
|
||||
"visibility_level":20,
|
||||
"path_with_namespace":"manland/webhook",
|
||||
"default_branch":"master",
|
||||
"ci_config_path":null,
|
||||
"homepage":"http://localhost:3000/manland/webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"http_url":"http://localhost:3000/manland/webhook.git"
|
||||
},
|
||||
"object_attributes":{
|
||||
"assignee_id":50,
|
||||
"author_id":1,
|
||||
"created_at":"2019-04-03 21:07:32 UTC",
|
||||
"description":"test open merge request",
|
||||
"head_pipeline_id":57,
|
||||
"id":35,
|
||||
"iid":4,
|
||||
"last_edited_at":null,
|
||||
"last_edited_by_id":null,
|
||||
"merge_commit_sha":null,
|
||||
"merge_error":null,
|
||||
"merge_params":{
|
||||
"force_remove_source_branch":null
|
||||
},
|
||||
"merge_status":"can_be_merged",
|
||||
"merge_user_id":null,
|
||||
"merge_when_pipeline_succeeds":false,
|
||||
"milestone_id":null,
|
||||
"source_branch":"master",
|
||||
"source_project_id":25,
|
||||
"state":"closed",
|
||||
"target_branch":"master",
|
||||
"target_project_id":24,
|
||||
"time_estimate":0,
|
||||
"title":"Master",
|
||||
"updated_at":"2019-04-03 21:29:41 UTC",
|
||||
"updated_by_id":null,
|
||||
"url":"http://localhost:3000/manland/webhook/merge_requests/4",
|
||||
"source":{
|
||||
"id":25,
|
||||
"name":"webhook",
|
||||
"description":"",
|
||||
"web_url":"http://localhost:3000/root/webhook",
|
||||
"avatar_url":null,
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
|
||||
"git_http_url":"http://localhost:3000/root/webhook.git",
|
||||
"namespace":"root",
|
||||
"visibility_level":20,
|
||||
"path_with_namespace":"root/webhook",
|
||||
"default_branch":"master",
|
||||
"ci_config_path":null,
|
||||
"homepage":"http://localhost:3000/root/webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
|
||||
"ssh_url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
|
||||
"http_url":"http://localhost:3000/root/webhook.git"
|
||||
},
|
||||
"target":{
|
||||
"id":24,
|
||||
"name":"webhook",
|
||||
"description":"",
|
||||
"web_url":"http://localhost:3000/manland/webhook",
|
||||
"avatar_url":null,
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"git_http_url":"http://localhost:3000/manland/webhook.git",
|
||||
"namespace":"manland",
|
||||
"visibility_level":20,
|
||||
"path_with_namespace":"manland/webhook",
|
||||
"default_branch":"master",
|
||||
"ci_config_path":null,
|
||||
"homepage":"http://localhost:3000/manland/webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"http_url":"http://localhost:3000/manland/webhook.git"
|
||||
},
|
||||
"last_commit":{
|
||||
"id":"1fd967c14f8265a6056525c343d984ce56472d5c",
|
||||
"message":"Update README.md",
|
||||
"timestamp":"2019-04-03T21:04:58Z",
|
||||
"url":"http://localhost:3000/manland/webhook/commit/1fd967c14f8265a6056525c343d984ce56472d5c",
|
||||
"author":{
|
||||
"name":"Administrator",
|
||||
"email":"admin@example.com"
|
||||
}
|
||||
},
|
||||
"work_in_progress":false,
|
||||
"total_time_spent":0,
|
||||
"human_total_time_spent":null,
|
||||
"human_time_estimate":null,
|
||||
"action":"close"
|
||||
},
|
||||
"labels":[],
|
||||
"changes":{
|
||||
"state":{
|
||||
"previous":"opened",
|
||||
"current":"closed"
|
||||
},
|
||||
"updated_at":{
|
||||
"previous":"2019-04-03 21:07:32 UTC",
|
||||
"current":"2019-04-03 21:29:41 UTC"
|
||||
},
|
||||
"assignee":{
|
||||
"previous":null,
|
||||
"current":{
|
||||
"name":"manland",
|
||||
"username":"manland",
|
||||
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
|
||||
}
|
||||
},
|
||||
"total_time_spent":{
|
||||
"previous":null,
|
||||
"current":0
|
||||
}
|
||||
},
|
||||
"repository":{
|
||||
"name":"webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"description":"",
|
||||
"homepage":"http://localhost:3000/manland/webhook"
|
||||
},
|
||||
"assignee":{
|
||||
"name":"manland",
|
||||
"username":"manland",
|
||||
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
|
||||
}
|
||||
}`
|
||||
|
||||
const CloseMergeRequestByCreator = `{
|
||||
"object_kind":"merge_request",
|
||||
"event_type":"merge_request",
|
||||
"user":{
|
||||
"name":"Administrator",
|
||||
"username":"root",
|
||||
"avatar_url":"https://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80\\u0026d=identicon"
|
||||
},
|
||||
"project":{
|
||||
"id":24,
|
||||
"name":"webhook",
|
||||
"description":"",
|
||||
"web_url":"http://localhost:3000/manland/webhook",
|
||||
"avatar_url":null,
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"git_http_url":"http://localhost:3000/manland/webhook.git",
|
||||
"namespace":"manland",
|
||||
"visibility_level":20,
|
||||
"path_with_namespace":"manland/webhook",
|
||||
"default_branch":"master",
|
||||
"ci_config_path":null,
|
||||
"homepage":"http://localhost:3000/manland/webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"http_url":"http://localhost:3000/manland/webhook.git"
|
||||
},
|
||||
"object_attributes":{
|
||||
"assignee_id":null,
|
||||
"author_id":1,
|
||||
"created_at":"2019-04-01 20:25:41 UTC",
|
||||
"description":"# Et voila\\n\\nC'est tro pbien",
|
||||
"head_pipeline_id":57,
|
||||
"id":34,
|
||||
"iid":1,
|
||||
"last_edited_at":null,
|
||||
"last_edited_by_id":null,
|
||||
"merge_commit_sha":null,
|
||||
"merge_error":null,
|
||||
"merge_params":{
|
||||
"force_remove_source_branch":null},
|
||||
"merge_status":"can_be_merged",
|
||||
"merge_user_id":null,
|
||||
"merge_when_pipeline_succeeds":false,
|
||||
"milestone_id":null,
|
||||
"source_branch":"master",
|
||||
"source_project_id":25,
|
||||
"state":"closed",
|
||||
"target_branch":"master",
|
||||
"target_project_id":24,
|
||||
"time_estimate":0,
|
||||
"title":"Update README.md",
|
||||
"updated_at":"2019-04-03 21:06:08 UTC",
|
||||
"updated_by_id":50,
|
||||
"url":"http://localhost:3000/manland/webhook/merge_requests/1",
|
||||
"source":{
|
||||
"id":25,
|
||||
"name":"webhook",
|
||||
"description":"",
|
||||
"web_url":"http://localhost:3000/root/webhook",
|
||||
"avatar_url":null,
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
|
||||
"git_http_url":"http://localhost:3000/root/webhook.git",
|
||||
"namespace":"root",
|
||||
"visibility_level":20,
|
||||
"path_with_namespace":"root/webhook",
|
||||
"default_branch":"master",
|
||||
"ci_config_path":null,
|
||||
"homepage":"http://localhost:3000/root/webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
|
||||
"ssh_url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
|
||||
"http_url":"http://localhost:3000/root/webhook.git"
|
||||
},
|
||||
"target":{
|
||||
"id":24,
|
||||
"name":"webhook",
|
||||
"description":"",
|
||||
"web_url":"http://localhost:3000/manland/webhook",
|
||||
"avatar_url":null,
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"git_http_url":"http://localhost:3000/manland/webhook.git",
|
||||
"namespace":"manland",
|
||||
"visibility_level":20,
|
||||
"path_with_namespace":"manland/webhook",
|
||||
"default_branch":"master",
|
||||
"ci_config_path":null,
|
||||
"homepage":"http://localhost:3000/manland/webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"http_url":"http://localhost:3000/manland/webhook.git"
|
||||
},
|
||||
"last_commit":{
|
||||
"id":"1fd967c14f8265a6056525c343d984ce56472d5c",
|
||||
"message":"Update README.md",
|
||||
"timestamp":"2019-04-03T21:04:58Z",
|
||||
"url":"http://localhost:3000/manland/webhook/commit/1fd967c14f8265a6056525c343d984ce56472d5c",
|
||||
"author":{
|
||||
"name":"Administrator",
|
||||
"email":"admin@example.com"
|
||||
}
|
||||
},
|
||||
"work_in_progress":false,
|
||||
"total_time_spent":0,
|
||||
"human_total_time_spent":null,
|
||||
"human_time_estimate":null,
|
||||
"action":"close"
|
||||
},
|
||||
"labels":[],
|
||||
"changes":{
|
||||
"state":{
|
||||
"previous":"opened",
|
||||
"current":"closed"
|
||||
},
|
||||
"updated_at":{
|
||||
"previous":"2019-04-03 21:05:03 UTC",
|
||||
"current":"2019-04-03 21:06:08 UTC"
|
||||
},
|
||||
"total_time_spent":{
|
||||
"previous":null,
|
||||
"current":0}
|
||||
},
|
||||
"repository":{
|
||||
"name":"webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"description":"",
|
||||
"homepage":"http://localhost:3000/manland/webhook"
|
||||
}
|
||||
}
|
||||
`
|
||||
const AssigneeMergeRequest = `{
|
||||
"object_kind":"merge_request",
|
||||
"event_type":"merge_request",
|
||||
"user":{
|
||||
"name":"Administrator",
|
||||
"username":"root",
|
||||
"avatar_url":"https://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80\\u0026d=identicon"
|
||||
},
|
||||
"project":{
|
||||
"id":24,
|
||||
"name":"webhook",
|
||||
"description":"",
|
||||
"web_url":"http://localhost:3000/manland/webhook",
|
||||
"avatar_url":null,
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"git_http_url":"http://localhost:3000/manland/webhook.git",
|
||||
"namespace":"manland",
|
||||
"visibility_level":20,
|
||||
"path_with_namespace":"manland/webhook",
|
||||
"default_branch":"master",
|
||||
"ci_config_path":null,
|
||||
"homepage":"http://localhost:3000/manland/webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"http_url":"http://localhost:3000/manland/webhook.git"
|
||||
},
|
||||
"object_attributes":{
|
||||
"assignee_id":50,
|
||||
"author_id":1,
|
||||
"created_at":"2019-04-03 21:07:32 UTC",
|
||||
"description":"test open merge request",
|
||||
"head_pipeline_id":57,
|
||||
"id":35,
|
||||
"iid":4,
|
||||
"last_edited_at":null,
|
||||
"last_edited_by_id":null,
|
||||
"merge_commit_sha":null,
|
||||
"merge_error":null,
|
||||
"merge_params":{
|
||||
"force_remove_source_branch":null
|
||||
},
|
||||
"merge_status":"can_be_merged",
|
||||
"merge_user_id":null,
|
||||
"merge_when_pipeline_succeeds":false,
|
||||
"milestone_id":null,
|
||||
"source_branch":"master",
|
||||
"source_project_id":25,
|
||||
"state":"opened",
|
||||
"target_branch":"master",
|
||||
"target_project_id":24,
|
||||
"time_estimate":0,
|
||||
"title":"Master",
|
||||
"updated_at":"2019-04-04 21:03:46 UTC",
|
||||
"updated_by_id":1,
|
||||
"url":"http://localhost:3000/manland/webhook/merge_requests/4",
|
||||
"source":{
|
||||
"id":25,
|
||||
"name":"webhook",
|
||||
"description":"",
|
||||
"web_url":"http://localhost:3000/root/webhook",
|
||||
"avatar_url":null,
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
|
||||
"git_http_url":"http://localhost:3000/root/webhook.git",
|
||||
"namespace":"root",
|
||||
"visibility_level":20,
|
||||
"path_with_namespace":"root/webhook",
|
||||
"default_branch":"master",
|
||||
"ci_config_path":null,
|
||||
"homepage":"http://localhost:3000/root/webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
|
||||
"ssh_url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
|
||||
"http_url":"http://localhost:3000/root/webhook.git"
|
||||
},
|
||||
"target":{
|
||||
"id":24,
|
||||
"name":"webhook",
|
||||
"description":"",
|
||||
"web_url":"http://localhost:3000/manland/webhook",
|
||||
"avatar_url":null,
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"git_http_url":"http://localhost:3000/manland/webhook.git",
|
||||
"namespace":"manland",
|
||||
"visibility_level":20,
|
||||
"path_with_namespace":"manland/webhook",
|
||||
"default_branch":"master",
|
||||
"ci_config_path":null,
|
||||
"homepage":"http://localhost:3000/manland/webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"http_url":"http://localhost:3000/manland/webhook.git"
|
||||
},
|
||||
"last_commit":{
|
||||
"id":"1fd967c14f8265a6056525c343d984ce56472d5c",
|
||||
"message":"Update README.md",
|
||||
"timestamp":"2019-04-03T21:04:58Z",
|
||||
"url":"http://localhost:3000/manland/webhook/commit/1fd967c14f8265a6056525c343d984ce56472d5c",
|
||||
"author":{
|
||||
"name":"Administrator",
|
||||
"email":"admin@example.com"
|
||||
}
|
||||
},
|
||||
"work_in_progress":false,
|
||||
"total_time_spent":0,
|
||||
"human_total_time_spent":null,
|
||||
"human_time_estimate":null,
|
||||
"assignee_ids": [
|
||||
50
|
||||
],
|
||||
"action":"update"
|
||||
},
|
||||
"labels":[],
|
||||
"changes":{
|
||||
"assignee_id":{
|
||||
"previous":1,
|
||||
"current":50
|
||||
},
|
||||
"updated_at":{
|
||||
"previous":"2019-04-04 21:02:42 UTC",
|
||||
"current":"2019-04-04 21:03:46 UTC"
|
||||
},
|
||||
"assignee":{
|
||||
"previous":{
|
||||
"name":"Administrator",
|
||||
"username":"root",
|
||||
"avatar_url":"https://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80\\u0026d=identicon"
|
||||
},
|
||||
"current":{
|
||||
"name":"manland",
|
||||
"username":"manland",
|
||||
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
|
||||
}
|
||||
}
|
||||
},
|
||||
"repository":{
|
||||
"name":"webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"description":"",
|
||||
"homepage":"http://localhost:3000/manland/webhook"
|
||||
},
|
||||
"assignee":{
|
||||
"name":"manland",
|
||||
"username":"manland",
|
||||
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
|
||||
}
|
||||
}`
|
||||
const MergeRequestMerged = `{
|
||||
"object_kind":"merge_request",
|
||||
"event_type":"merge_request",
|
||||
"user":{
|
||||
"name":"manland",
|
||||
"username":"manland",
|
||||
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
|
||||
},
|
||||
"project":{
|
||||
"id":24,
|
||||
"name":"webhook",
|
||||
"description":"",
|
||||
"web_url":"http://localhost:3000/manland/webhook",
|
||||
"avatar_url":null,
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"git_http_url":"http://localhost:3000/manland/webhook.git",
|
||||
"namespace":"manland",
|
||||
"visibility_level":20,
|
||||
"path_with_namespace":"manland/webhook",
|
||||
"default_branch":"master",
|
||||
"ci_config_path":null,
|
||||
"homepage":"http://localhost:3000/manland/webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"http_url":"http://localhost:3000/manland/webhook.git"
|
||||
},
|
||||
"object_attributes":{
|
||||
"assignee_id":50,
|
||||
"author_id":1,
|
||||
"created_at":"2019-04-03 21:07:32 UTC",
|
||||
"description":"test open merge request",
|
||||
"head_pipeline_id":57,
|
||||
"id":35,
|
||||
"iid":4,
|
||||
"last_edited_at":null,
|
||||
"last_edited_by_id":null,
|
||||
"merge_commit_sha":"44213d704986b25e21e2d0f086d0c1503fd659e2",
|
||||
"merge_error":null,
|
||||
"merge_params":{
|
||||
"force_remove_source_branch":null
|
||||
},
|
||||
"merge_status":"can_be_merged",
|
||||
"merge_user_id":null,
|
||||
"merge_when_pipeline_succeeds":false,
|
||||
"milestone_id":null,
|
||||
"source_branch":"master",
|
||||
"source_project_id":25,
|
||||
"state":"merged",
|
||||
"target_branch":"master",
|
||||
"target_project_id":24,
|
||||
"time_estimate":0,
|
||||
"title":"Master",
|
||||
"updated_at":"2019-04-04 21:40:41 UTC",
|
||||
"updated_by_id":1,
|
||||
"url":"http://localhost:3000/manland/webhook/merge_requests/4",
|
||||
"source":{
|
||||
"id":25,
|
||||
"name":"webhook",
|
||||
"description":"",
|
||||
"web_url":"http://localhost:3000/root/webhook",
|
||||
"avatar_url":null,
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
|
||||
"git_http_url":"http://localhost:3000/root/webhook.git",
|
||||
"namespace":"root",
|
||||
"visibility_level":20,
|
||||
"path_with_namespace":"root/webhook",
|
||||
"default_branch":"master",
|
||||
"ci_config_path":null,
|
||||
"homepage":"http://localhost:3000/root/webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
|
||||
"ssh_url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
|
||||
"http_url":"http://localhost:3000/root/webhook.git"
|
||||
},
|
||||
"target":{
|
||||
"id":24,
|
||||
"name":"webhook",
|
||||
"description":"",
|
||||
"web_url":"http://localhost:3000/manland/webhook",
|
||||
"avatar_url":null,
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"git_http_url":"http://localhost:3000/manland/webhook.git",
|
||||
"namespace":"manland",
|
||||
"visibility_level":20,
|
||||
"path_with_namespace":"manland/webhook",
|
||||
"default_branch":"master",
|
||||
"ci_config_path":null,
|
||||
"homepage":"http://localhost:3000/manland/webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"http_url":"http://localhost:3000/manland/webhook.git"
|
||||
},
|
||||
"last_commit":{
|
||||
"id":"1fd967c14f8265a6056525c343d984ce56472d5c",
|
||||
"message":"Update README.md",
|
||||
"timestamp":"2019-04-03T21:04:58Z",
|
||||
"url":"http://localhost:3000/manland/webhook/commit/1fd967c14f8265a6056525c343d984ce56472d5c",
|
||||
"author":{
|
||||
"name":"Administrator",
|
||||
"email":"admin@example.com"
|
||||
}
|
||||
},
|
||||
"work_in_progress":false,
|
||||
"total_time_spent":0,
|
||||
"human_total_time_spent":null,
|
||||
"human_time_estimate":null,
|
||||
"action":"merge"
|
||||
},
|
||||
"labels":[],
|
||||
"changes":{
|
||||
"merge_commit_sha":{
|
||||
"previous":null,
|
||||
"current":"44213d704986b25e21e2d0f086d0c1503fd659e2"
|
||||
},
|
||||
"state":{
|
||||
"previous":"opened",
|
||||
"current":"merged"
|
||||
},
|
||||
"updated_at":{
|
||||
"previous":"2019-04-04 21:15:52 UTC",
|
||||
"current":"2019-04-04 21:40:41 UTC"
|
||||
},
|
||||
"assignee":{
|
||||
"previous":null,
|
||||
"current":{
|
||||
"name":"manland",
|
||||
"username":"manland",
|
||||
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
|
||||
}
|
||||
},
|
||||
"total_time_spent":{
|
||||
"previous":null,
|
||||
"current":0
|
||||
}
|
||||
},
|
||||
"repository":{
|
||||
"name":"webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"description":"",
|
||||
"homepage":"http://localhost:3000/manland/webhook"
|
||||
},
|
||||
"assignee":{
|
||||
"name":"manland",
|
||||
"username":"manland",
|
||||
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
|
||||
}
|
||||
}`
|
||||
|
||||
const ApproveMergeRequest = `{
|
||||
"object_kind":"merge_request",
|
||||
"event_type":"merge_request",
|
||||
"user":{
|
||||
"name":"manland",
|
||||
"username":"manland",
|
||||
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
|
||||
},
|
||||
"project":{
|
||||
"id":24,
|
||||
"name":"webhook",
|
||||
"description":"",
|
||||
"web_url":"http://localhost:3000/manland/webhook",
|
||||
"avatar_url":null,
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"git_http_url":"http://localhost:3000/manland/webhook.git",
|
||||
"namespace":"manland",
|
||||
"visibility_level":20,
|
||||
"path_with_namespace":"manland/webhook",
|
||||
"default_branch":"master",
|
||||
"ci_config_path":null,
|
||||
"homepage":"http://localhost:3000/manland/webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"http_url":"http://localhost:3000/manland/webhook.git"
|
||||
},
|
||||
"object_attributes":{
|
||||
"assignee_id":50,
|
||||
"author_id":1,
|
||||
"created_at":"2019-04-03 21:07:32 UTC",
|
||||
"description":"test open merge request",
|
||||
"head_pipeline_id":57,
|
||||
"id":35,
|
||||
"iid":4,
|
||||
"last_edited_at":null,
|
||||
"last_edited_by_id":null,
|
||||
"merge_commit_sha":null,
|
||||
"merge_error":null,
|
||||
"merge_params":{
|
||||
"force_remove_source_branch":null
|
||||
},
|
||||
"merge_status":"can_be_merged",
|
||||
"merge_user_id":null,
|
||||
"merge_when_pipeline_succeeds":false,
|
||||
"milestone_id":null,
|
||||
"source_branch":"master",
|
||||
"source_project_id":25,
|
||||
"state":"opened",
|
||||
"target_branch":"master",
|
||||
"target_project_id":24,
|
||||
"time_estimate":0,
|
||||
"title":"Master",
|
||||
"updated_at":"2019-04-03 21:29:41 UTC",
|
||||
"updated_by_id":null,
|
||||
"url":"http://localhost:3000/manland/webhook/merge_requests/4",
|
||||
"source":{
|
||||
"id":25,
|
||||
"name":"webhook",
|
||||
"description":"",
|
||||
"web_url":"http://localhost:3000/root/webhook",
|
||||
"avatar_url":null,
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
|
||||
"git_http_url":"http://localhost:3000/root/webhook.git",
|
||||
"namespace":"root",
|
||||
"visibility_level":20,
|
||||
"path_with_namespace":"root/webhook",
|
||||
"default_branch":"master",
|
||||
"ci_config_path":null,
|
||||
"homepage":"http://localhost:3000/root/webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
|
||||
"ssh_url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
|
||||
"http_url":"http://localhost:3000/root/webhook.git"
|
||||
},
|
||||
"target":{
|
||||
"id":24,
|
||||
"name":"webhook",
|
||||
"description":"",
|
||||
"web_url":"http://localhost:3000/manland/webhook",
|
||||
"avatar_url":null,
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"git_http_url":"http://localhost:3000/manland/webhook.git",
|
||||
"namespace":"manland",
|
||||
"visibility_level":20,
|
||||
"path_with_namespace":"manland/webhook",
|
||||
"default_branch":"master",
|
||||
"ci_config_path":null,
|
||||
"homepage":"http://localhost:3000/manland/webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"http_url":"http://localhost:3000/manland/webhook.git"
|
||||
},
|
||||
"last_commit":{
|
||||
"id":"1fd967c14f8265a6056525c343d984ce56472d5c",
|
||||
"message":"Update README.md",
|
||||
"timestamp":"2019-04-03T21:04:58Z",
|
||||
"url":"http://localhost:3000/manland/webhook/commit/1fd967c14f8265a6056525c343d984ce56472d5c",
|
||||
"author":{
|
||||
"name":"Administrator",
|
||||
"email":"admin@example.com"
|
||||
}
|
||||
},
|
||||
"work_in_progress":false,
|
||||
"total_time_spent":0,
|
||||
"human_total_time_spent":null,
|
||||
"human_time_estimate":null,
|
||||
"action":"approved"
|
||||
},
|
||||
"labels":[],
|
||||
"changes":{
|
||||
"updated_at":{
|
||||
"previous":"2019-04-03 21:07:32 UTC",
|
||||
"current":"2019-04-03 21:29:41 UTC"
|
||||
}
|
||||
},
|
||||
"repository":{
|
||||
"name":"webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"description":"",
|
||||
"homepage":"http://localhost:3000/manland/webhook"
|
||||
},
|
||||
"assignee":{
|
||||
"name":"manland",
|
||||
"username":"manland",
|
||||
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
|
||||
}
|
||||
}`
|
||||
@@ -0,0 +1,204 @@
|
||||
package webhook
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/xanzy/go-gitlab"
|
||||
|
||||
"github.com/mattermost/mattermost-plugin-gitlab/server/subscription"
|
||||
)
|
||||
|
||||
type testDataMergeRequestStr struct {
|
||||
testTitle string
|
||||
fixture string
|
||||
gitlabRetreiver *fakeWebhook
|
||||
res []*HandleWebhook
|
||||
}
|
||||
|
||||
var testDataMergeRequest = []testDataMergeRequestStr{
|
||||
{
|
||||
testTitle: "root open merge request for manland and display in channel1",
|
||||
fixture: OpenMergeRequest,
|
||||
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
|
||||
{ChannelID: "channel1", CreatorID: "1", Features: "merges", Repository: "manland/webhook"},
|
||||
}),
|
||||
res: []*HandleWebhook{{
|
||||
Message: "[root](http://my.gitlab.com/root) requested your review on [manland/webhook!4](http://localhost:3000/manland/webhook/merge_requests/4)",
|
||||
ToUsers: []string{"manland"},
|
||||
ToChannels: []string{},
|
||||
From: "root",
|
||||
}, {
|
||||
Message: "#### Master\n##### [manland/webhook!4](http://localhost:3000/manland/webhook/merge_requests/4) new merge-request by [root](http://my.gitlab.com/root) on [2019-04-03 21:07:32 UTC](http://localhost:3000/manland/webhook/merge_requests/4)\n\ntest open merge request",
|
||||
ToUsers: []string{},
|
||||
ToChannels: []string{"channel1"},
|
||||
From: "root",
|
||||
}},
|
||||
}, {
|
||||
testTitle: "root open merge request for manland and display in channel1 (subgroup)",
|
||||
fixture: strings.ReplaceAll(OpenMergeRequest, "manland/webhook", "manland/subgroup/webhook"),
|
||||
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
|
||||
{ChannelID: "channel1", CreatorID: "1", Features: "merges", Repository: "manland/subgroup/webhook"},
|
||||
}),
|
||||
res: []*HandleWebhook{{
|
||||
Message: "[root](http://my.gitlab.com/root) requested your review on [manland/subgroup/webhook!4](http://localhost:3000/manland/subgroup/webhook/merge_requests/4)",
|
||||
ToUsers: []string{"manland"},
|
||||
ToChannels: []string{},
|
||||
From: "root",
|
||||
}, {
|
||||
Message: "#### Master\n##### [manland/subgroup/webhook!4](http://localhost:3000/manland/subgroup/webhook/merge_requests/4) new merge-request by [root](http://my.gitlab.com/root) on [2019-04-03 21:07:32 UTC](http://localhost:3000/manland/subgroup/webhook/merge_requests/4)\n\ntest open merge request",
|
||||
ToUsers: []string{},
|
||||
ToChannels: []string{"channel1"},
|
||||
From: "root",
|
||||
}},
|
||||
}, {
|
||||
testTitle: "manland close merge request of root and display in channel1",
|
||||
fixture: CloseMergeRequestByAssignee,
|
||||
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
|
||||
{ChannelID: "channel1", CreatorID: "1", Features: "merges", Repository: "manland/webhook"},
|
||||
}),
|
||||
res: []*HandleWebhook{{
|
||||
Message: "[manland](http://my.gitlab.com/manland) closed your merge request [manland/webhook!4](http://localhost:3000/manland/webhook/merge_requests/4)",
|
||||
ToUsers: []string{"root"},
|
||||
ToChannels: []string{},
|
||||
From: "manland",
|
||||
}, {
|
||||
Message: "[manland/webhook](http://localhost:3000/manland/webhook) Merge request [!4 Master](http://localhost:3000/manland/webhook/merge_requests/4) was closed by [manland](http://my.gitlab.com/manland)",
|
||||
ToUsers: []string{},
|
||||
ToChannels: []string{"channel1"},
|
||||
From: "manland",
|
||||
}},
|
||||
}, {
|
||||
testTitle: "manland reopened merge request of root and display in channel1",
|
||||
fixture: ReopenMerge,
|
||||
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
|
||||
{ChannelID: "channel1", CreatorID: "1", Features: "merges", Repository: "manland/webhook"},
|
||||
}),
|
||||
res: []*HandleWebhook{{
|
||||
Message: "[manland](http://my.gitlab.com/manland) reopened your merge request [manland/webhook!1](http://localhost:3000/manland/webhook/merge_requests/1)",
|
||||
ToUsers: []string{"root"},
|
||||
ToChannels: []string{},
|
||||
From: "manland",
|
||||
}, {
|
||||
Message: "[manland/webhook](http://localhost:3000/manland/webhook) Merge request [!1 Update README.md](http://localhost:3000/manland/webhook/merge_requests/1) was reopened by [manland](http://my.gitlab.com/manland)",
|
||||
ToUsers: []string{},
|
||||
ToChannels: []string{"channel1"},
|
||||
From: "manland",
|
||||
}},
|
||||
}, {
|
||||
testTitle: "root affect manland to merge-request",
|
||||
fixture: AssigneeMergeRequest,
|
||||
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{}),
|
||||
res: []*HandleWebhook{{
|
||||
Message: "[root](http://my.gitlab.com/root) assigned you to merge request [manland/webhook!4](http://localhost:3000/manland/webhook/merge_requests/4)",
|
||||
ToUsers: []string{"manland"},
|
||||
ToChannels: []string{},
|
||||
From: "root",
|
||||
}},
|
||||
}, {
|
||||
testTitle: "manland merge root merge-request and display in channel1",
|
||||
fixture: MergeRequestMerged,
|
||||
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
|
||||
{ChannelID: "channel1", CreatorID: "1", Features: "merges", Repository: "manland/webhook"},
|
||||
}),
|
||||
res: []*HandleWebhook{{
|
||||
Message: "[manland](http://my.gitlab.com/manland) merged your merge request [manland/webhook!4](http://localhost:3000/manland/webhook/merge_requests/4)",
|
||||
ToUsers: []string{"root"},
|
||||
ToChannels: []string{},
|
||||
From: "manland",
|
||||
}, {
|
||||
Message: "[manland/webhook](http://localhost:3000/manland/webhook) Merge request [!4 Master](http://localhost:3000/manland/webhook/merge_requests/4) was merged by [manland](http://my.gitlab.com/manland)",
|
||||
ToUsers: []string{},
|
||||
ToChannels: []string{"channel1"},
|
||||
From: "manland",
|
||||
}},
|
||||
}, {
|
||||
testTitle: "manland approve root merge-request and display in channel1",
|
||||
fixture: ApproveMergeRequest,
|
||||
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
|
||||
{ChannelID: "channel1", CreatorID: "1", Features: "merges", Repository: "manland/webhook"},
|
||||
}),
|
||||
res: []*HandleWebhook{{
|
||||
Message: "[manland](http://my.gitlab.com/manland) approved your merge request [manland/webhook!4](http://localhost:3000/manland/webhook/merge_requests/4)",
|
||||
ToUsers: []string{"root"},
|
||||
ToChannels: []string{},
|
||||
From: "manland",
|
||||
}, {
|
||||
Message: "[manland/webhook](http://localhost:3000/manland/webhook) Merge request [!4 Master](http://localhost:3000/manland/webhook/merge_requests/4) was approved by [manland](http://my.gitlab.com/manland)",
|
||||
ToUsers: []string{},
|
||||
ToChannels: []string{"channel1"},
|
||||
From: "manland",
|
||||
}},
|
||||
}, {
|
||||
testTitle: "manland unapprove root merge-request and display in channel1",
|
||||
fixture: strings.ReplaceAll(ApproveMergeRequest, "approved", "unapproved"),
|
||||
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
|
||||
{ChannelID: "channel1", CreatorID: "1", Features: "merges", Repository: "manland/webhook"},
|
||||
}),
|
||||
res: []*HandleWebhook{{
|
||||
Message: "[manland](http://my.gitlab.com/manland) requested changes to your merge request [manland/webhook!4](http://localhost:3000/manland/webhook/merge_requests/4)",
|
||||
ToUsers: []string{"root"},
|
||||
ToChannels: []string{},
|
||||
From: "manland",
|
||||
}, {
|
||||
Message: "[manland/webhook](http://localhost:3000/manland/webhook) Merge request [!4 Master](http://localhost:3000/manland/webhook/merge_requests/4) changes were requested by [manland](http://my.gitlab.com/manland)",
|
||||
ToUsers: []string{},
|
||||
ToChannels: []string{"channel1"},
|
||||
From: "manland",
|
||||
}},
|
||||
}, {
|
||||
testTitle: "root close its own MR without assignee and display in channel1",
|
||||
fixture: CloseMergeRequestByCreator,
|
||||
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
|
||||
{ChannelID: "channel1", CreatorID: "1", Features: "merges", Repository: "manland/webhook"},
|
||||
}),
|
||||
res: []*HandleWebhook{{
|
||||
Message: "[root](http://my.gitlab.com/root) closed your merge request [manland/webhook!1](http://localhost:3000/manland/webhook/merge_requests/1)",
|
||||
ToUsers: []string{}, // no assignee
|
||||
ToChannels: []string{},
|
||||
From: "root",
|
||||
}, {
|
||||
Message: "[manland/webhook](http://localhost:3000/manland/webhook) Merge request [!1 Update README.md](http://localhost:3000/manland/webhook/merge_requests/1) was closed by [root](http://my.gitlab.com/root)",
|
||||
ToUsers: []string{},
|
||||
ToChannels: []string{"channel1"},
|
||||
From: "root",
|
||||
}},
|
||||
}, {
|
||||
testTitle: "root open merge request for manland + channel but not subscription to merges",
|
||||
fixture: OpenMergeRequest,
|
||||
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
|
||||
{ChannelID: "channel1", CreatorID: "1", Features: "issues", Repository: "manland/webhook"},
|
||||
}),
|
||||
res: []*HandleWebhook{{
|
||||
Message: "[root](http://my.gitlab.com/root) requested your review on [manland/webhook!4](http://localhost:3000/manland/webhook/merge_requests/4)",
|
||||
ToUsers: []string{"manland"},
|
||||
ToChannels: []string{},
|
||||
From: "root",
|
||||
}},
|
||||
},
|
||||
}
|
||||
|
||||
func TestMergeRequestWebhook(t *testing.T) {
|
||||
t.Parallel()
|
||||
for _, test := range testDataMergeRequest {
|
||||
t.Run(test.testTitle, func(t *testing.T) {
|
||||
w := NewWebhook(test.gitlabRetreiver)
|
||||
mergeEvent := &gitlab.MergeEvent{}
|
||||
if err := json.Unmarshal([]byte(test.fixture), mergeEvent); err != nil {
|
||||
assert.Fail(t, "can't unmarshal fixture")
|
||||
}
|
||||
res, err := w.HandleMergeRequest(context.Background(), mergeEvent)
|
||||
assert.Empty(t, err)
|
||||
assert.Equal(t, len(test.res), len(res))
|
||||
for index := range res {
|
||||
assert.Equal(t, test.res[index].Message, res[index].Message)
|
||||
assert.Equal(t, test.res[index].ToUsers, res[index].ToUsers)
|
||||
assert.Equal(t, test.res[index].ToChannels, res[index].ToChannels)
|
||||
assert.Equal(t, test.res[index].From, res[index].From)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package webhook
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/xanzy/go-gitlab"
|
||||
)
|
||||
|
||||
func (w *webhook) HandleIssueComment(ctx context.Context, event *gitlab.IssueCommentEvent) ([]*HandleWebhook, error) {
|
||||
handlers, err := w.handleDMIssueComment(event)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
handlers2, err := w.handleChannelIssueComment(ctx, event)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cleanWebhookHandlers(append(handlers, handlers2...)), nil
|
||||
}
|
||||
|
||||
func (w *webhook) handleDMIssueComment(event *gitlab.IssueCommentEvent) ([]*HandleWebhook, error) {
|
||||
senderGitlabUsername := event.User.Username
|
||||
message := fmt.Sprintf("[%s](%s) commented on your issue [%s#%v](%s)", senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.Project.PathWithNamespace, event.Issue.IID, event.ObjectAttributes.URL)
|
||||
|
||||
toUsers := make([]string, len(event.Issue.AssigneeIDs)+1)
|
||||
for index, assigneeID := range event.Issue.AssigneeIDs {
|
||||
toUsers[index] = w.gitlabRetreiver.GetUsernameByID(assigneeID)
|
||||
}
|
||||
toUsers[len(toUsers)-1] = w.gitlabRetreiver.GetUsernameByID(event.Issue.AuthorID)
|
||||
|
||||
handlers := []*HandleWebhook{
|
||||
{
|
||||
Message: message,
|
||||
ToUsers: toUsers,
|
||||
From: senderGitlabUsername,
|
||||
},
|
||||
}
|
||||
|
||||
if mention := w.handleMention(mentionDetails{
|
||||
senderUsername: senderGitlabUsername,
|
||||
pathWithNamespace: event.Project.PathWithNamespace,
|
||||
IID: fmt.Sprintf("%d", event.Issue.IID),
|
||||
URL: event.ObjectAttributes.URL,
|
||||
body: event.ObjectAttributes.Description,
|
||||
}); mention != nil {
|
||||
handlers = append(handlers, mention)
|
||||
}
|
||||
|
||||
return handlers, nil
|
||||
}
|
||||
|
||||
func (w *webhook) handleChannelIssueComment(ctx context.Context, event *gitlab.IssueCommentEvent) ([]*HandleWebhook, error) {
|
||||
senderGitlabUsername := event.User.Username
|
||||
repo := event.Project
|
||||
body := event.ObjectAttributes.Description
|
||||
res := []*HandleWebhook{}
|
||||
|
||||
message := fmt.Sprintf("[%s](%s) New comment by [%s](%s) on [#%v %s](%s):\n\n%s", repo.PathWithNamespace, repo.WebURL, senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.Issue.IID, event.Issue.Title, event.ObjectAttributes.URL, body)
|
||||
|
||||
toChannels := make([]string, 0)
|
||||
namespace, project := normalizeNamespacedProject(repo.PathWithNamespace)
|
||||
subs := w.gitlabRetreiver.GetSubscribedChannelsForProject(
|
||||
ctx, namespace, project,
|
||||
repo.Visibility == gitlab.PublicVisibility,
|
||||
)
|
||||
for _, sub := range subs {
|
||||
if !sub.IssueComments() {
|
||||
continue
|
||||
}
|
||||
|
||||
if sub.Label() != "" && !containsLabel(event.Issue.Labels, sub.Label()) {
|
||||
continue
|
||||
}
|
||||
|
||||
toChannels = append(toChannels, sub.ChannelID)
|
||||
}
|
||||
if len(toChannels) > 0 {
|
||||
res = append(res, &HandleWebhook{
|
||||
From: senderGitlabUsername,
|
||||
Message: message,
|
||||
ToUsers: []string{},
|
||||
ToChannels: toChannels,
|
||||
})
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func (w *webhook) HandleMergeRequestComment(ctx context.Context, event *gitlab.MergeCommentEvent) ([]*HandleWebhook, error) {
|
||||
handlers, err := w.handleDMMergeRequestComment(event)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
handlers2, err := w.handleChannelMergeRequestComment(ctx, event)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cleanWebhookHandlers(append(handlers, handlers2...)), nil
|
||||
}
|
||||
|
||||
func (w *webhook) handleDMMergeRequestComment(event *gitlab.MergeCommentEvent) ([]*HandleWebhook, error) {
|
||||
senderGitlabUsername := event.User.Username
|
||||
message := fmt.Sprintf("[%s](%s) commented on your merge request [%s#%v](%s)", senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.Project.PathWithNamespace, event.MergeRequest.IID, event.ObjectAttributes.URL)
|
||||
|
||||
handlers := []*HandleWebhook{{
|
||||
Message: message,
|
||||
ToUsers: []string{w.gitlabRetreiver.GetUsernameByID(event.MergeRequest.AssigneeID), w.gitlabRetreiver.GetUsernameByID(event.MergeRequest.AuthorID)},
|
||||
From: senderGitlabUsername,
|
||||
}}
|
||||
|
||||
if mention := w.handleMention(mentionDetails{
|
||||
senderUsername: senderGitlabUsername,
|
||||
pathWithNamespace: event.Project.PathWithNamespace,
|
||||
IID: fmt.Sprintf("%d", event.MergeRequest.IID),
|
||||
URL: event.ObjectAttributes.URL,
|
||||
body: event.ObjectAttributes.Description,
|
||||
}); mention != nil {
|
||||
handlers = append(handlers, mention)
|
||||
}
|
||||
return handlers, nil
|
||||
}
|
||||
|
||||
func (w *webhook) handleChannelMergeRequestComment(ctx context.Context, event *gitlab.MergeCommentEvent) ([]*HandleWebhook, error) {
|
||||
senderGitlabUsername := event.User.Username
|
||||
repo := event.Project
|
||||
body := event.ObjectAttributes.Description
|
||||
res := []*HandleWebhook{}
|
||||
|
||||
message := fmt.Sprintf("[%s](%s) New comment by [%s](%s) on [#%v %s](%s):\n\n%s", repo.PathWithNamespace, repo.WebURL, senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.MergeRequest.IID, event.MergeRequest.Title, event.ObjectAttributes.URL, body)
|
||||
|
||||
toChannels := make([]string, 0)
|
||||
namespace, project := normalizeNamespacedProject(repo.PathWithNamespace)
|
||||
subs := w.gitlabRetreiver.GetSubscribedChannelsForProject(
|
||||
ctx, namespace, project,
|
||||
repo.Visibility == gitlab.PublicVisibility,
|
||||
)
|
||||
for _, sub := range subs {
|
||||
if !sub.MergeRequestComments() {
|
||||
continue
|
||||
}
|
||||
|
||||
toChannels = append(toChannels, sub.ChannelID)
|
||||
}
|
||||
if len(toChannels) > 0 {
|
||||
res = append(res, &HandleWebhook{
|
||||
From: senderGitlabUsername,
|
||||
Message: message,
|
||||
ToUsers: []string{},
|
||||
ToChannels: toChannels,
|
||||
})
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
package webhook
|
||||
|
||||
const MergeRequestComment = `{
|
||||
"object_kind":"note",
|
||||
"event_type":"note",
|
||||
"user":{
|
||||
"name":"manland",
|
||||
"username":"manland",
|
||||
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
|
||||
},
|
||||
"project_id":24,
|
||||
"project":{
|
||||
"id":24,
|
||||
"name":"webhook",
|
||||
"description":"",
|
||||
"web_url":"http://localhost:3000/manland/webhook",
|
||||
"avatar_url":null,
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"git_http_url":"http://localhost:3000/manland/webhook.git",
|
||||
"namespace":"manland",
|
||||
"visibility_level":20,
|
||||
"path_with_namespace":"manland/webhook",
|
||||
"default_branch":"master",
|
||||
"ci_config_path":null,
|
||||
"homepage":"http://localhost:3000/manland/webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"http_url":"http://localhost:3000/manland/webhook.git"
|
||||
},
|
||||
"object_attributes":{
|
||||
"attachment":null,
|
||||
"author_id":50,
|
||||
"change_position":null,
|
||||
"commit_id":null,
|
||||
"created_at":"2019-04-10 10:50:44 UTC",
|
||||
"discussion_id":"5e4e2988f1bd8133cb7be80e9549a053ded5d79c",
|
||||
"id":999,
|
||||
"line_code":null,
|
||||
"note":"coucou",
|
||||
"noteable_id":37,
|
||||
"noteable_type":"MergeRequest",
|
||||
"original_position":null,
|
||||
"position":null,
|
||||
"project_id":24,
|
||||
"resolved_at":null,
|
||||
"resolved_by_id":null,
|
||||
"resolved_by_push":null,
|
||||
"st_diff":null,
|
||||
"system":false,
|
||||
"type":null,
|
||||
"updated_at":"2019-04-10 10:50:44 UTC",
|
||||
"updated_by_id":null,
|
||||
"description":"coucou",
|
||||
"url":"http://localhost:3000/manland/webhook/merge_requests/6#note_999"
|
||||
},
|
||||
"repository":{
|
||||
"name":"webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"description":"",
|
||||
"homepage":"http://localhost:3000/manland/webhook"
|
||||
},
|
||||
"merge_request":{
|
||||
"assignee_id":50,
|
||||
"author_id":1,
|
||||
"created_at":"2019-04-06 20:29:15 UTC",
|
||||
"description":"kikou",
|
||||
"head_pipeline_id":null,
|
||||
"id":37,
|
||||
"iid":6,
|
||||
"last_edited_at":null,
|
||||
"last_edited_by_id":null,
|
||||
"merge_commit_sha":null,
|
||||
"merge_error":null,
|
||||
"merge_params":{
|
||||
"force_remove_source_branch":null
|
||||
},
|
||||
"merge_status":"cannot_be_merged",
|
||||
"merge_user_id":null,
|
||||
"merge_when_pipeline_succeeds":false,
|
||||
"milestone_id":null,
|
||||
"source_branch":"master",
|
||||
"source_project_id":25,
|
||||
"state":"opened",
|
||||
"target_branch":"master",
|
||||
"target_project_id":24,
|
||||
"time_estimate":0,
|
||||
"title":"Update README.md",
|
||||
"updated_at":"2019-04-10 10:50:26 UTC",
|
||||
"updated_by_id":null,
|
||||
"url":"http://localhost:3000/manland/webhook/merge_requests/6",
|
||||
"source":{
|
||||
"id":25,
|
||||
"name":"webhook",
|
||||
"description":"",
|
||||
"web_url":"http://localhost:3000/root/webhook",
|
||||
"avatar_url":null,
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
|
||||
"git_http_url":"http://localhost:3000/root/webhook.git",
|
||||
"namespace":"root",
|
||||
"visibility_level":20,
|
||||
"path_with_namespace":"root/webhook",
|
||||
"default_branch":"master",
|
||||
"ci_config_path":null,
|
||||
"homepage":"http://localhost:3000/root/webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
|
||||
"ssh_url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
|
||||
"http_url":"http://localhost:3000/root/webhook.git"
|
||||
},
|
||||
"target":{
|
||||
"id":24,
|
||||
"name":"webhook",
|
||||
"description":"",
|
||||
"web_url":"http://localhost:3000/manland/webhook",
|
||||
"avatar_url":null,
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"git_http_url":"http://localhost:3000/manland/webhook.git",
|
||||
"namespace":"manland",
|
||||
"visibility_level":20,
|
||||
"path_with_namespace":"manland/webhook",
|
||||
"default_branch":"master",
|
||||
"ci_config_path":null,
|
||||
"homepage":"http://localhost:3000/manland/webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"http_url":"http://localhost:3000/manland/webhook.git"
|
||||
},
|
||||
"last_commit":{
|
||||
"id":"a4b713084b7fcfc3570391964f6c5b5c40684a0e",
|
||||
"message":"Update README.md",
|
||||
"timestamp":"2019-04-06T20:28:44Z",
|
||||
"url":"http://localhost:3000/manland/webhook/commit/a4b713084b7fcfc3570391964f6c5b5c40684a0e",
|
||||
"author":{
|
||||
"name":"Administrator",
|
||||
"email":"admin@example.com"
|
||||
}
|
||||
},
|
||||
"work_in_progress":false,
|
||||
"total_time_spent":0,
|
||||
"human_total_time_spent":null,
|
||||
"human_time_estimate":null
|
||||
}
|
||||
}`
|
||||
|
||||
const IssueComment = `{
|
||||
"object_kind":"note",
|
||||
"event_type":"note",
|
||||
"user":{
|
||||
"name":"manland",
|
||||
"username":"manland",
|
||||
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
|
||||
},
|
||||
"project_id":24,
|
||||
"project":{
|
||||
"id":24,
|
||||
"name":"webhook",
|
||||
"description":"",
|
||||
"web_url":"http://localhost:3000/manland/webhook",
|
||||
"avatar_url":null,
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"git_http_url":"http://localhost:3000/manland/webhook.git",
|
||||
"namespace":"manland",
|
||||
"visibility_level":20,
|
||||
"path_with_namespace":"manland/webhook",
|
||||
"default_branch":"master",
|
||||
"ci_config_path":null,
|
||||
"homepage":"http://localhost:3000/manland/webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"http_url":"http://localhost:3000/manland/webhook.git"
|
||||
},
|
||||
"object_attributes":{
|
||||
"attachment":null,
|
||||
"author_id":50,
|
||||
"change_position":null,
|
||||
"commit_id":null,
|
||||
"created_at":"2019-04-10 10:44:13 UTC",
|
||||
"discussion_id":"f86a43ac361b0d51b3a1c12b1c178ab060097a2d",
|
||||
"id":997,
|
||||
"line_code":null,
|
||||
"note":"coucou3",
|
||||
"noteable_id":181,
|
||||
"noteable_type":"Issue",
|
||||
"original_position":null,
|
||||
"position":null,
|
||||
"project_id":24,
|
||||
"resolved_at":null,
|
||||
"resolved_by_id":null,
|
||||
"resolved_by_push":null,
|
||||
"st_diff":null,
|
||||
"system":false,
|
||||
"type":null,
|
||||
"updated_at":"2019-04-10 10:44:13 UTC",
|
||||
"updated_by_id":null,
|
||||
"description":"coucou3",
|
||||
"url":"http://localhost:3000/manland/webhook/issues/1#note_997"
|
||||
},
|
||||
"repository":{
|
||||
"name":"webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"description":"",
|
||||
"homepage":"http://localhost:3000/manland/webhook"
|
||||
},
|
||||
"issue":{
|
||||
"author_id":1,
|
||||
"closed_at":null,
|
||||
"confidential":false,
|
||||
"created_at":"2019-04-06 21:03:04 UTC",
|
||||
"description":"hello world!",
|
||||
"due_date":null,
|
||||
"id":181,
|
||||
"iid":1,
|
||||
"last_edited_at":null,
|
||||
"last_edited_by_id":null,
|
||||
"milestone_id":null,
|
||||
"moved_to_id":null,
|
||||
"project_id":24,
|
||||
"relative_position":1073742323,
|
||||
"state":"opened",
|
||||
"time_estimate":0,
|
||||
"title":"test new issue",
|
||||
"updated_at":"2019-04-10 10:44:13 UTC",
|
||||
"updated_by_id":null,
|
||||
"url":"http://localhost:3000/manland/webhook/issues/1",
|
||||
"total_time_spent":0,
|
||||
"human_total_time_spent":null,
|
||||
"human_time_estimate":null,
|
||||
"assignee_ids":[50],
|
||||
"assignee_id":50
|
||||
}
|
||||
}`
|
||||
@@ -0,0 +1,110 @@
|
||||
package webhook
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/mattermost/mattermost-plugin-gitlab/server/subscription"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/xanzy/go-gitlab"
|
||||
)
|
||||
|
||||
type testDataNoteStr struct {
|
||||
testTitle string
|
||||
fixture string
|
||||
kind string
|
||||
gitlabRetreiver *fakeWebhook
|
||||
res []*HandleWebhook
|
||||
}
|
||||
|
||||
var testDataNote = []testDataNoteStr{
|
||||
{
|
||||
testTitle: "manland comment issue of root",
|
||||
kind: "issue",
|
||||
fixture: IssueComment,
|
||||
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
|
||||
{ChannelID: "channel1", CreatorID: "1", Features: "issue_comments", Repository: "manland/webhook"},
|
||||
}),
|
||||
res: []*HandleWebhook{{
|
||||
Message: "[manland](http://my.gitlab.com/manland) commented on your issue [manland/webhook#1](http://localhost:3000/manland/webhook/issues/1#note_997)",
|
||||
ToUsers: []string{"root"},
|
||||
ToChannels: []string{},
|
||||
From: "manland",
|
||||
}, {
|
||||
Message: "[manland/webhook](http://localhost:3000/manland/webhook) New comment by [manland](http://my.gitlab.com/manland) on [#1 test new issue](http://localhost:3000/manland/webhook/issues/1#note_997):\n\ncoucou3",
|
||||
ToUsers: []string{},
|
||||
ToChannels: []string{"channel1"},
|
||||
From: "manland",
|
||||
}},
|
||||
}, {
|
||||
testTitle: "manland comment issue of root (subgroup)",
|
||||
kind: "issue",
|
||||
fixture: strings.ReplaceAll(IssueComment, "manland/webhook", "manland/subgroup/webhook"),
|
||||
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
|
||||
{ChannelID: "channel1", CreatorID: "1", Features: "issue_comments", Repository: "manland/subgroup/webhook"},
|
||||
}),
|
||||
res: []*HandleWebhook{{
|
||||
Message: "[manland](http://my.gitlab.com/manland) commented on your issue [manland/subgroup/webhook#1](http://localhost:3000/manland/subgroup/webhook/issues/1#note_997)",
|
||||
ToUsers: []string{"root"},
|
||||
ToChannels: []string{},
|
||||
From: "manland",
|
||||
}, {
|
||||
Message: "[manland/subgroup/webhook](http://localhost:3000/manland/subgroup/webhook) New comment by [manland](http://my.gitlab.com/manland) on [#1 test new issue](http://localhost:3000/manland/subgroup/webhook/issues/1#note_997):\n\ncoucou3",
|
||||
ToUsers: []string{},
|
||||
ToChannels: []string{"channel1"},
|
||||
From: "manland",
|
||||
}},
|
||||
}, {
|
||||
testTitle: "manland comment merge request of root",
|
||||
kind: "mr",
|
||||
fixture: MergeRequestComment,
|
||||
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
|
||||
{ChannelID: "channel1", CreatorID: "1", Features: "merge_request_comments", Repository: "manland/webhook"},
|
||||
}),
|
||||
res: []*HandleWebhook{{
|
||||
Message: "[manland](http://my.gitlab.com/manland) commented on your merge request [manland/webhook#6](http://localhost:3000/manland/webhook/merge_requests/6#note_999)",
|
||||
ToUsers: []string{"root"},
|
||||
ToChannels: []string{},
|
||||
From: "manland",
|
||||
}, {
|
||||
Message: "[manland/webhook](http://localhost:3000/manland/webhook) New comment by [manland](http://my.gitlab.com/manland) on [#6 Update README.md](http://localhost:3000/manland/webhook/merge_requests/6#note_999):\n\ncoucou",
|
||||
ToUsers: []string{},
|
||||
ToChannels: []string{"channel1"},
|
||||
From: "manland",
|
||||
}},
|
||||
},
|
||||
}
|
||||
|
||||
func TestNoteWebhook(t *testing.T) {
|
||||
t.Parallel()
|
||||
for _, test := range testDataNote {
|
||||
t.Run(test.testTitle, func(t *testing.T) {
|
||||
w := NewWebhook(test.gitlabRetreiver)
|
||||
var res []*HandleWebhook
|
||||
var err error
|
||||
if test.kind == "issue" {
|
||||
issueCommentEvent := &gitlab.IssueCommentEvent{}
|
||||
if err = json.Unmarshal([]byte(test.fixture), issueCommentEvent); err != nil {
|
||||
assert.Fail(t, "can't unmarshal fixture")
|
||||
}
|
||||
res, err = w.HandleIssueComment(context.Background(), issueCommentEvent)
|
||||
} else {
|
||||
mergeCommentEvent := &gitlab.MergeCommentEvent{}
|
||||
if err = json.Unmarshal([]byte(test.fixture), mergeCommentEvent); err != nil {
|
||||
assert.Fail(t, "can't unmarshal fixture")
|
||||
}
|
||||
res, err = w.HandleMergeRequestComment(context.Background(), mergeCommentEvent)
|
||||
}
|
||||
assert.Empty(t, err)
|
||||
assert.Equal(t, len(test.res), len(res))
|
||||
for index := range res {
|
||||
assert.Equal(t, test.res[index].Message, res[index].Message)
|
||||
assert.Equal(t, test.res[index].ToUsers, res[index].ToUsers)
|
||||
assert.Equal(t, test.res[index].From, res[index].From)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package webhook
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/xanzy/go-gitlab"
|
||||
)
|
||||
|
||||
func (w *webhook) HandlePipeline(ctx context.Context, event *gitlab.PipelineEvent) ([]*HandleWebhook, error) {
|
||||
handlers, err := w.handleDMPipeline(event)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
handlers2, err := w.handleChannelPipeline(ctx, event)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cleanWebhookHandlers(append(handlers, handlers2...)), nil
|
||||
}
|
||||
|
||||
func (w *webhook) handleDMPipeline(event *gitlab.PipelineEvent) ([]*HandleWebhook, error) {
|
||||
senderGitlabUsername := event.User.Username
|
||||
repo := event.Project
|
||||
|
||||
handlers := []*HandleWebhook{}
|
||||
|
||||
if event.ObjectAttributes.Status == statusFailed {
|
||||
message := fmt.Sprintf("[%s](%s) Your pipeline has failed for %s [%s](%s)", repo.PathWithNamespace, repo.WebURL, event.Commit.Message, "View Pipeline", w.gitlabRetreiver.GetPipelineURL(repo.PathWithNamespace, event.ObjectAttributes.ID))
|
||||
handlers = append(handlers, &HandleWebhook{
|
||||
Message: message,
|
||||
From: "", // don't put senderGitlabUsername because we filter message where from == to
|
||||
ToUsers: []string{senderGitlabUsername},
|
||||
ToChannels: []string{},
|
||||
})
|
||||
}
|
||||
|
||||
if mention := w.handleMention(mentionDetails{
|
||||
senderUsername: senderGitlabUsername,
|
||||
pathWithNamespace: event.Project.PathWithNamespace,
|
||||
IID: fmt.Sprintf("%d", event.ObjectAttributes.ID),
|
||||
URL: event.Commit.URL,
|
||||
body: event.Commit.Message,
|
||||
}); mention != nil {
|
||||
handlers = append(handlers, mention)
|
||||
}
|
||||
|
||||
return handlers, nil
|
||||
}
|
||||
|
||||
func (w *webhook) handleChannelPipeline(ctx context.Context, event *gitlab.PipelineEvent) ([]*HandleWebhook, error) {
|
||||
senderGitlabUsername := event.User.Username
|
||||
repo := event.Project
|
||||
res := []*HandleWebhook{}
|
||||
message := ""
|
||||
|
||||
switch event.ObjectAttributes.Status {
|
||||
case statusRunning:
|
||||
message = fmt.Sprintf("[%s](%s) New pipeline from %s by [%s](%s) for %s [%s](%s)", repo.PathWithNamespace, repo.WebURL, event.ObjectAttributes.Source, senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.Commit.Message, "View Pipeline", w.gitlabRetreiver.GetPipelineURL(repo.PathWithNamespace, event.ObjectAttributes.ID))
|
||||
case statusSuccess:
|
||||
message = fmt.Sprintf("[%s](%s) Pipeline by [%s](%s) success for %s [%s](%s)", repo.PathWithNamespace, repo.WebURL, senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.Commit.Message, "View Pipeline", w.gitlabRetreiver.GetPipelineURL(repo.PathWithNamespace, event.ObjectAttributes.ID))
|
||||
case statusFailed:
|
||||
message = fmt.Sprintf("[%s](%s) Pipeline by [%s](%s) fail for %s [%s](%s)", repo.PathWithNamespace, repo.WebURL, senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.Commit.Message, "View Pipeline", w.gitlabRetreiver.GetPipelineURL(repo.PathWithNamespace, event.ObjectAttributes.ID))
|
||||
default:
|
||||
return res, nil
|
||||
}
|
||||
|
||||
toChannels := make([]string, 0)
|
||||
namespace, project := normalizeNamespacedProject(repo.PathWithNamespace)
|
||||
subs := w.gitlabRetreiver.GetSubscribedChannelsForProject(
|
||||
ctx, namespace, project,
|
||||
repo.Visibility == gitlab.PublicVisibility,
|
||||
)
|
||||
for _, sub := range subs {
|
||||
if !sub.Pipeline() {
|
||||
continue
|
||||
}
|
||||
|
||||
toChannels = append(toChannels, sub.ChannelID)
|
||||
}
|
||||
|
||||
if len(toChannels) > 0 {
|
||||
res = append(res, &HandleWebhook{
|
||||
From: senderGitlabUsername,
|
||||
Message: message,
|
||||
ToUsers: []string{},
|
||||
ToChannels: toChannels,
|
||||
})
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
package webhook
|
||||
|
||||
const PipelinePending = `{
|
||||
"object_kind":"pipeline",
|
||||
"object_attributes":{
|
||||
"id":58,
|
||||
"ref":"master",
|
||||
"tag":false,
|
||||
"sha":"ec0a1bcd4580bfec3495674e412f4834ee2c2550",
|
||||
"before_sha":"c30217b62542c586fdbadc7b5ee762bfdca10663",
|
||||
"source": "merge_request_event",
|
||||
"status":"pending",
|
||||
"detailed_status":"pending",
|
||||
"stages":["deploy"],
|
||||
"created_at":"2019-04-17 20:38:44 UTC",
|
||||
"finished_at":null,
|
||||
"duration":null,
|
||||
"variables":[]
|
||||
},
|
||||
"user":{
|
||||
"name":"Administrator",
|
||||
"username":"root",
|
||||
"avatar_url":"https://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80\\u0026d=identicon"
|
||||
},
|
||||
"project":{
|
||||
"id":24,
|
||||
"name":"webhook",
|
||||
"description":"",
|
||||
"web_url":"http://localhost:3000/manland/webhook",
|
||||
"avatar_url":null,
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"git_http_url":"http://localhost:3000/manland/webhook.git",
|
||||
"namespace":"manland",
|
||||
"visibility_level":20,
|
||||
"path_with_namespace":"manland/webhook",
|
||||
"default_branch":"master",
|
||||
"ci_config_path":null
|
||||
},
|
||||
"commit":{
|
||||
"id":"ec0a1bcd4580bfec3495674e412f4834ee2c2550",
|
||||
"message":"Start gitlab-ci\n",
|
||||
"timestamp":"2019-04-17T20:38:43Z",
|
||||
"url":"http://localhost:3000/manland/webhook/commit/ec0a1bcd4580bfec3495674e412f4834ee2c2550",
|
||||
"author":{
|
||||
"name":"Administrator",
|
||||
"email":"admin@example.com"
|
||||
}
|
||||
},
|
||||
"builds":[{
|
||||
"id":1126,
|
||||
"stage":"deploy",
|
||||
"name":"pages",
|
||||
"status":"pending",
|
||||
"created_at":"2019-04-17 20:38:44 UTC",
|
||||
"started_at":null,
|
||||
"finished_at":null,
|
||||
"when":"on_success",
|
||||
"manual":false,
|
||||
"user":{
|
||||
"name":"Administrator",
|
||||
"username":"root",
|
||||
"avatar_url":"https://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80\\u0026d=identicon"},
|
||||
"runner":null,
|
||||
"artifacts_file":{
|
||||
"filename":null,
|
||||
"size":0
|
||||
}
|
||||
}]
|
||||
}`
|
||||
|
||||
const PipelineRun = `{
|
||||
"object_kind":"pipeline",
|
||||
"object_attributes":{
|
||||
"id":62,
|
||||
"ref":"master",
|
||||
"tag":false,
|
||||
"sha":"ec0a1bcd4580bfec3495674e412f4834ee2c2550",
|
||||
"before_sha":"0000000000000000000000000000000000000000",
|
||||
"source": "merge_request_event",
|
||||
"status":"running",
|
||||
"detailed_status":"running",
|
||||
"stages":["deploy"],
|
||||
"created_at":"2019-05-01 12:32:47 UTC",
|
||||
"finished_at":null,
|
||||
"duration":null,
|
||||
"variables":[]
|
||||
},
|
||||
"user":{
|
||||
"name":"Administrator",
|
||||
"username":"root",
|
||||
"avatar_url":"https://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80\\u0026d=identicon"
|
||||
},
|
||||
"project":{
|
||||
"id":24,
|
||||
"name":"webhook",
|
||||
"description":"",
|
||||
"web_url":"http://localhost:3000/manland/webhook",
|
||||
"avatar_url":null,
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"git_http_url":"http://localhost:3000/manland/webhook.git",
|
||||
"namespace":"manland",
|
||||
"visibility_level":20,
|
||||
"path_with_namespace":"manland/webhook",
|
||||
"default_branch":"master",
|
||||
"ci_config_path":null
|
||||
},
|
||||
"commit":{
|
||||
"id":"ec0a1bcd4580bfec3495674e412f4834ee2c2550",
|
||||
"message":"Start gitlab-ci\n",
|
||||
"timestamp":"2019-04-17T20:38:43Z",
|
||||
"url":"http://localhost:3000/manland/webhook/commit/ec0a1bcd4580bfec3495674e412f4834ee2c2550",
|
||||
"author":{
|
||||
"name":"Administrator",
|
||||
"email":"admin@example.com"
|
||||
}
|
||||
},
|
||||
"builds": [
|
||||
{
|
||||
"id":1136,
|
||||
"stage":"deploy",
|
||||
"name":"pages",
|
||||
"status":"running",
|
||||
"created_at":"2019-05-01 12:32:47 UTC",
|
||||
"started_at":"2019-05-01 12:32:49 UTC",
|
||||
"finished_at":null,
|
||||
"when":"on_success",
|
||||
"manual":false,
|
||||
"user":{
|
||||
"name":"Administrator",
|
||||
"username":"root",
|
||||
"avatar_url":"https://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80\\u0026d=identicon"
|
||||
},
|
||||
"runner":{
|
||||
"id":1,
|
||||
"description":"localhost",
|
||||
"active":true,
|
||||
"is_shared":true
|
||||
},
|
||||
"artifacts_file":{
|
||||
"filename":null,
|
||||
"size":0
|
||||
}
|
||||
}]
|
||||
}`
|
||||
|
||||
const PipelineFail = `{
|
||||
"object_kind":"pipeline",
|
||||
"object_attributes":{
|
||||
"id":62,
|
||||
"ref":"master",
|
||||
"tag":false,
|
||||
"sha":"ec0a1bcd4580bfec3495674e412f4834ee2c2550",
|
||||
"before_sha":"0000000000000000000000000000000000000000",
|
||||
"source": "merge_request_event",
|
||||
"status":"failed",
|
||||
"detailed_status":"failed",
|
||||
"stages":["deploy"],
|
||||
"created_at":"2019-05-01 12:32:47 UTC",
|
||||
"finished_at":"2019-05-01 12:33:04 UTC",
|
||||
"duration":14,
|
||||
"variables":[]
|
||||
},
|
||||
"user":{
|
||||
"name":"Administrator",
|
||||
"username":"root",
|
||||
"avatar_url":"https://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80\\u0026d=identicon"
|
||||
},
|
||||
"project":{
|
||||
"id":24,
|
||||
"name":"webhook",
|
||||
"description":"",
|
||||
"web_url":"http://localhost:3000/manland/webhook",
|
||||
"avatar_url":null,
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"git_http_url":"http://localhost:3000/manland/webhook.git",
|
||||
"namespace":"manland",
|
||||
"visibility_level":20,
|
||||
"path_with_namespace":"manland/webhook",
|
||||
"default_branch":"master",
|
||||
"ci_config_path":null
|
||||
},
|
||||
"commit":{
|
||||
"id":"ec0a1bcd4580bfec3495674e412f4834ee2c2550",
|
||||
"message":"Start gitlab-ci\n",
|
||||
"timestamp":"2019-04-17T20:38:43Z",
|
||||
"url":"http://localhost:3000/manland/webhook/commit/ec0a1bcd4580bfec3495674e412f4834ee2c2550",
|
||||
"author":{
|
||||
"name":"Administrator",
|
||||
"email":"admin@example.com"
|
||||
}
|
||||
},
|
||||
"builds":[
|
||||
{
|
||||
"id":1136,
|
||||
"stage":"deploy",
|
||||
"name":"pages",
|
||||
"status":"failed",
|
||||
"created_at":"2019-05-01 12:32:47 UTC",
|
||||
"started_at":"2019-05-01 12:32:49 UTC",
|
||||
"finished_at":"2019-05-01 12:33:04 UTC",
|
||||
"when":"on_success",
|
||||
"manual":false,
|
||||
"user":{
|
||||
"name":"Administrator",
|
||||
"username":"root",
|
||||
"avatar_url":"https://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80\\u0026d=identicon"
|
||||
},
|
||||
"runner":{
|
||||
"id":1,
|
||||
"description":"localhost",
|
||||
"active":true,
|
||||
"is_shared":true
|
||||
},
|
||||
"artifacts_file":{
|
||||
"filename":null,
|
||||
"size":0
|
||||
}
|
||||
}]
|
||||
}`
|
||||
|
||||
const PipelineSuccess = `{
|
||||
"object_kind":"pipeline",
|
||||
"object_attributes":{
|
||||
"id":62,
|
||||
"ref":"master",
|
||||
"tag":false,
|
||||
"sha":"ec0a1bcd4580bfec3495674e412f4834ee2c2550",
|
||||
"before_sha":"0000000000000000000000000000000000000000",
|
||||
"source": "merge_request_event",
|
||||
"status":"success",
|
||||
"detailed_status":"passed",
|
||||
"stages":["deploy", "deploy"],
|
||||
"created_at":"2019-05-01 12:32:47 UTC",
|
||||
"finished_at":"2019-05-01 13:55:51 UTC",
|
||||
"duration":19,
|
||||
"variables":[]
|
||||
},
|
||||
"user":{
|
||||
"name":"Administrator",
|
||||
"username":"root",
|
||||
"avatar_url":"https://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80\\u0026d=identicon"
|
||||
},
|
||||
"project":{
|
||||
"id":24,
|
||||
"name":"webhook",
|
||||
"description":"",
|
||||
"web_url":"http://localhost:3000/manland/webhook",
|
||||
"avatar_url":null,
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"git_http_url":"http://localhost:3000/manland/webhook.git",
|
||||
"namespace":"manland",
|
||||
"visibility_level":20,
|
||||
"path_with_namespace":"manland/webhook",
|
||||
"default_branch":"master",
|
||||
"ci_config_path":null
|
||||
},
|
||||
"commit":{
|
||||
"id":"ec0a1bcd4580bfec3495674e412f4834ee2c2550",
|
||||
"message":"Start gitlab-ci\n",
|
||||
"timestamp":"2019-04-17T20:38:43Z",
|
||||
"url":"http://localhost:3000/manland/webhook/commit/ec0a1bcd4580bfec3495674e412f4834ee2c2550",
|
||||
"author":{
|
||||
"name":"Administrator",
|
||||
"email":"admin@example.com"
|
||||
}
|
||||
},
|
||||
"builds":[
|
||||
{
|
||||
"id":1142,
|
||||
"stage":"deploy",
|
||||
"name":"pages",
|
||||
"status":"success",
|
||||
"created_at":"2019-05-01 13:55:29 UTC",
|
||||
"started_at":"2019-05-01 13:55:31 UTC",
|
||||
"finished_at":"2019-05-01 13:55:51 UTC",
|
||||
"when":"on_success",
|
||||
"manual":false,
|
||||
"user":{
|
||||
"name":"Administrator",
|
||||
"username":"root",
|
||||
"avatar_url":"https://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80\\u0026d=identicon"
|
||||
},
|
||||
"runner":{
|
||||
"id":3,
|
||||
"description":"ip",
|
||||
"active":true,
|
||||
"is_shared":true
|
||||
},
|
||||
"artifacts_file":{
|
||||
"filename":"artifacts.zip",
|
||||
"size":2520
|
||||
}
|
||||
}
|
||||
]
|
||||
}`
|
||||
@@ -0,0 +1,105 @@
|
||||
package webhook
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/xanzy/go-gitlab"
|
||||
|
||||
"github.com/mattermost/mattermost-plugin-gitlab/server/subscription"
|
||||
)
|
||||
|
||||
type testDataPipelineStr struct {
|
||||
testTitle string
|
||||
fixture string
|
||||
gitlabRetreiver *fakeWebhook
|
||||
res []*HandleWebhook
|
||||
}
|
||||
|
||||
var testDataPipeline = []testDataPipelineStr{
|
||||
{
|
||||
testTitle: "root start a pipeline in pending",
|
||||
fixture: PipelinePending,
|
||||
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
|
||||
{ChannelID: "channel1", CreatorID: "1", Features: "pipeline", Repository: "manland/webhook"},
|
||||
}),
|
||||
res: []*HandleWebhook{}, // we don't care about pending pipeline
|
||||
}, {
|
||||
testTitle: "root start a pipeline in running",
|
||||
fixture: PipelineRun,
|
||||
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
|
||||
{ChannelID: "channel1", CreatorID: "1", Features: "pipeline", Repository: "manland/webhook"},
|
||||
}),
|
||||
res: []*HandleWebhook{{
|
||||
Message: "[manland/webhook](http://localhost:3000/manland/webhook) New pipeline from merge_request_event by [root](http://my.gitlab.com/root) for Start gitlab-ci\n [View Pipeline](http://my.gitlab.com/manland/webhook/-/pipelines/62)",
|
||||
ToUsers: []string{}, // No DM because user know he has launch a pipeline
|
||||
ToChannels: []string{"channel1"},
|
||||
From: "root",
|
||||
}},
|
||||
}, {
|
||||
testTitle: "root start a pipeline in running (subgroup)",
|
||||
fixture: strings.ReplaceAll(PipelineRun, "manland/webhook", "manland/subgroup/webhook"),
|
||||
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
|
||||
{ChannelID: "channel1", CreatorID: "1", Features: "pipeline", Repository: "manland/subgroup/webhook"},
|
||||
}),
|
||||
res: []*HandleWebhook{{
|
||||
Message: "[manland/subgroup/webhook](http://localhost:3000/manland/subgroup/webhook) New pipeline from merge_request_event by [root](http://my.gitlab.com/root) for Start gitlab-ci\n [View Pipeline](http://my.gitlab.com/manland/subgroup/webhook/-/pipelines/62)",
|
||||
ToUsers: []string{}, // No DM because user know he has launch a pipeline
|
||||
ToChannels: []string{"channel1"},
|
||||
From: "root",
|
||||
}},
|
||||
}, {
|
||||
testTitle: "root fail a pipeline",
|
||||
fixture: PipelineFail,
|
||||
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
|
||||
{ChannelID: "channel1", CreatorID: "1", Features: "pipeline", Repository: "manland/webhook"},
|
||||
}),
|
||||
res: []*HandleWebhook{{
|
||||
Message: "[manland/webhook](http://localhost:3000/manland/webhook) Your pipeline has failed for Start gitlab-ci\n [View Pipeline](http://my.gitlab.com/manland/webhook/-/pipelines/62)",
|
||||
ToUsers: []string{"root"},
|
||||
ToChannels: []string{},
|
||||
From: "",
|
||||
}, {
|
||||
Message: "[manland/webhook](http://localhost:3000/manland/webhook) Pipeline by [root](http://my.gitlab.com/root) fail for Start gitlab-ci\n [View Pipeline](http://my.gitlab.com/manland/webhook/-/pipelines/62)",
|
||||
ToUsers: []string{},
|
||||
ToChannels: []string{},
|
||||
From: "root",
|
||||
}},
|
||||
}, {
|
||||
testTitle: "root success a pipeline",
|
||||
fixture: PipelineSuccess,
|
||||
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
|
||||
{ChannelID: "channel1", CreatorID: "1", Features: "pipeline", Repository: "manland/webhook"},
|
||||
}),
|
||||
res: []*HandleWebhook{{
|
||||
Message: "[manland/webhook](http://localhost:3000/manland/webhook) Pipeline by [root](http://my.gitlab.com/root) success for Start gitlab-ci\n [View Pipeline](http://my.gitlab.com/manland/webhook/-/pipelines/62)",
|
||||
ToUsers: []string{},
|
||||
ToChannels: []string{"channel1"},
|
||||
From: "root",
|
||||
}},
|
||||
},
|
||||
}
|
||||
|
||||
func TestPipelineWebhook(t *testing.T) {
|
||||
t.Parallel()
|
||||
for _, test := range testDataPipeline {
|
||||
t.Run(test.testTitle, func(t *testing.T) {
|
||||
w := NewWebhook(test.gitlabRetreiver)
|
||||
pipelineEvent := &gitlab.PipelineEvent{}
|
||||
if err := json.Unmarshal([]byte(test.fixture), pipelineEvent); err != nil {
|
||||
assert.Fail(t, "can't unmarshal fixture")
|
||||
}
|
||||
res, err := w.HandlePipeline(context.Background(), pipelineEvent)
|
||||
assert.Empty(t, err)
|
||||
assert.Equal(t, len(test.res), len(res))
|
||||
for index := range res {
|
||||
assert.Equal(t, test.res[index].Message, res[index].Message)
|
||||
assert.Equal(t, test.res[index].ToUsers, res[index].ToUsers)
|
||||
assert.Equal(t, test.res[index].From, res[index].From)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package webhook
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/xanzy/go-gitlab"
|
||||
)
|
||||
|
||||
func (w *webhook) HandlePush(ctx context.Context, event *gitlab.PushEvent) ([]*HandleWebhook, error) {
|
||||
handlers, err := w.handleDMPush(event)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
handlers2, err := w.handleChannelPush(ctx, event)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cleanWebhookHandlers(append(handlers, handlers2...)), nil
|
||||
}
|
||||
|
||||
func (w *webhook) handleDMPush(event *gitlab.PushEvent) ([]*HandleWebhook, error) {
|
||||
senderGitlabUsername := event.UserName
|
||||
handlers := []*HandleWebhook{}
|
||||
|
||||
for _, commit := range event.Commits {
|
||||
if mention := w.handleMention(mentionDetails{
|
||||
senderUsername: senderGitlabUsername,
|
||||
pathWithNamespace: event.Project.PathWithNamespace,
|
||||
IID: commit.ID,
|
||||
URL: commit.URL,
|
||||
body: commit.Message,
|
||||
}); mention != nil {
|
||||
handlers = append(handlers, mention)
|
||||
}
|
||||
}
|
||||
|
||||
return handlers, nil
|
||||
}
|
||||
|
||||
func (w *webhook) handleChannelPush(ctx context.Context, event *gitlab.PushEvent) ([]*HandleWebhook, error) {
|
||||
senderGitlabUsername := event.UserUsername
|
||||
repo := event.Project
|
||||
res := []*HandleWebhook{}
|
||||
|
||||
if event.TotalCommitsCount == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
plural := "commits"
|
||||
|
||||
if event.TotalCommitsCount == 1 {
|
||||
plural = "commit"
|
||||
}
|
||||
|
||||
message := fmt.Sprintf("[%s](%s) has pushed %d %s to [%s](%s)", senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.TotalCommitsCount, plural, event.Project.PathWithNamespace, event.Project.WebURL)
|
||||
|
||||
for _, commit := range event.Commits {
|
||||
message += fmt.Sprintf("\n%s [%s](%s)", commit.Message, "View Commit", commit.URL)
|
||||
}
|
||||
|
||||
toChannels := make([]string, 0)
|
||||
namespace, project := normalizeNamespacedProject(repo.PathWithNamespace)
|
||||
subs := w.gitlabRetreiver.GetSubscribedChannelsForProject(
|
||||
ctx, namespace, project,
|
||||
repo.Visibility == gitlab.PublicVisibility,
|
||||
)
|
||||
for _, sub := range subs {
|
||||
if !sub.Pushes() {
|
||||
continue
|
||||
}
|
||||
|
||||
toChannels = append(toChannels, sub.ChannelID)
|
||||
}
|
||||
|
||||
if len(toChannels) > 0 {
|
||||
res = append(res, &HandleWebhook{
|
||||
From: senderGitlabUsername,
|
||||
Message: message,
|
||||
ToUsers: []string{},
|
||||
ToChannels: toChannels,
|
||||
})
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
package webhook
|
||||
|
||||
const PushEvent = `{
|
||||
"object_kind":"push",
|
||||
"event_name":"push",
|
||||
"before":"9a7226e89f24282680dfa845587e14895ce62780",
|
||||
"after":"c30217b62542c586fdbadc7b5ee762bfdca10663",
|
||||
"ref":"refs/heads/master",
|
||||
"checkout_sha":"c30217b62542c586fdbadc7b5ee762bfdca10663",
|
||||
"message":null,
|
||||
"user_id":50,
|
||||
"user_name":"manland",
|
||||
"user_username":"manland",
|
||||
"user_email":"",
|
||||
"user_avatar":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon",
|
||||
"project_id":24,
|
||||
"project":{
|
||||
"id":24,
|
||||
"name":"webhook",
|
||||
"description":"",
|
||||
"web_url":"http://localhost:3000/manland/webhook",
|
||||
"avatar_url":null,
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"git_http_url":"http://localhost:3000/manland/webhook.git",
|
||||
"namespace":"manland",
|
||||
"visibility_level":20,
|
||||
"path_with_namespace":"manland/webhook",
|
||||
"default_branch":"master",
|
||||
"ci_config_path":null,
|
||||
"homepage":"http://localhost:3000/manland/webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"http_url":"http://localhost:3000/manland/webhook.git"
|
||||
},
|
||||
"commits":[{
|
||||
"id":"c30217b62542c586fdbadc7b5ee762bfdca10663",
|
||||
"message":"really cool commit\n",
|
||||
"timestamp":"2019-04-17T20:22:03Z",
|
||||
"url":"http://localhost:3000/manland/webhook/commit/c30217b62542c586fdbadc7b5ee762bfdca10663",
|
||||
"author":{
|
||||
"name":"manland",
|
||||
"email":"rmaneschi@gmail.com"
|
||||
},
|
||||
"added":[],
|
||||
"modified":["README.md"],
|
||||
"removed":[]
|
||||
}],
|
||||
"total_commits_count":1,
|
||||
"push_options":{},
|
||||
"repository":{
|
||||
"name":"webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"description":"",
|
||||
"homepage":"http://localhost:3000/manland/webhook",
|
||||
"git_http_url":"http://localhost:3000/manland/webhook.git",
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"visibility_level":20
|
||||
}
|
||||
}`
|
||||
|
||||
const pushEventWithTwoCommits = `{
|
||||
"object_kind":"push",
|
||||
"event_name":"push",
|
||||
"before":"9a7226e89f24282680dfa845587e14895ce62780",
|
||||
"after":"c30217b62542c586fdbadc7b5ee762bfdca10663",
|
||||
"ref":"refs/heads/master",
|
||||
"checkout_sha":"c30217b62542c586fdbadc7b5ee762bfdca10663",
|
||||
"message":null,
|
||||
"user_id":50,
|
||||
"user_name":"manland",
|
||||
"user_username":"manland",
|
||||
"user_email":"",
|
||||
"user_avatar":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon",
|
||||
"project_id":24,
|
||||
"project":{
|
||||
"id":24,
|
||||
"name":"webhook",
|
||||
"description":"",
|
||||
"web_url":"http://localhost:3000/manland/webhook",
|
||||
"avatar_url":null,
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"git_http_url":"http://localhost:3000/manland/webhook.git",
|
||||
"namespace":"manland",
|
||||
"visibility_level":20,
|
||||
"path_with_namespace":"manland/webhook",
|
||||
"default_branch":"master",
|
||||
"ci_config_path":null,
|
||||
"homepage":"http://localhost:3000/manland/webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"http_url":"http://localhost:3000/manland/webhook.git"
|
||||
},
|
||||
"commits":[{
|
||||
"id":"c30217b62542c586fdbadc7b5ee762bfdca10663",
|
||||
"message":"really cool commit\n",
|
||||
"timestamp":"2019-04-17T20:22:03Z",
|
||||
"url":"http://localhost:3000/manland/webhook/commit/c30217b62542c586fdbadc7b5ee762bfdca10663",
|
||||
"author":{
|
||||
"name":"manland",
|
||||
"email":"rmaneschi@gmail.com"
|
||||
},
|
||||
"added":[],
|
||||
"modified":["README.md"],
|
||||
"removed":[]
|
||||
}, {
|
||||
"id":"595f2a068cce60954565b224bc7c966c9e708cbf",
|
||||
"message":"another cool commit\n",
|
||||
"timestamp":"2019-04-17T20:23:05Z",
|
||||
"url":"http://localhost:3000/manland/webhook/commit/595f2a068cce60954565b224bc7c966c9e708cbf",
|
||||
"author":{
|
||||
"name":"manland",
|
||||
"email":"rmaneschi@gmail.com"
|
||||
},
|
||||
"added":[],
|
||||
"modified":["README.md"],
|
||||
"removed":[]
|
||||
}],
|
||||
"total_commits_count":2,
|
||||
"push_options":{},
|
||||
"repository":{
|
||||
"name":"webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"description":"",
|
||||
"homepage":"http://localhost:3000/manland/webhook",
|
||||
"git_http_url":"http://localhost:3000/manland/webhook.git",
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"visibility_level":20
|
||||
}
|
||||
}`
|
||||
|
||||
const pushEventWithoutCommits = `{
|
||||
"object_kind":"push",
|
||||
"event_name":"push",
|
||||
"before":"9a7226e89f24282680dfa845587e14895ce62780",
|
||||
"after":"c30217b62542c586fdbadc7b5ee762bfdca10663",
|
||||
"ref":"refs/heads/master",
|
||||
"checkout_sha":"c30217b62542c586fdbadc7b5ee762bfdca10663",
|
||||
"message":null,
|
||||
"user_id":50,
|
||||
"user_name":"manland",
|
||||
"user_username":"manland",
|
||||
"user_email":"",
|
||||
"user_avatar":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon",
|
||||
"project_id":24,
|
||||
"project":{
|
||||
"id":24,
|
||||
"name":"webhook",
|
||||
"description":"",
|
||||
"web_url":"http://localhost:3000/manland/webhook",
|
||||
"avatar_url":null,
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"git_http_url":"http://localhost:3000/manland/webhook.git",
|
||||
"namespace":"manland",
|
||||
"visibility_level":20,
|
||||
"path_with_namespace":"manland/webhook",
|
||||
"default_branch":"master",
|
||||
"ci_config_path":null,
|
||||
"homepage":"http://localhost:3000/manland/webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"http_url":"http://localhost:3000/manland/webhook.git"
|
||||
},
|
||||
"commits":[],
|
||||
"total_commits_count":0,
|
||||
"push_options":{},
|
||||
"repository":{
|
||||
"name":"webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"description":"",
|
||||
"homepage":"http://localhost:3000/manland/webhook",
|
||||
"git_http_url":"http://localhost:3000/manland/webhook.git",
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"visibility_level":20
|
||||
}
|
||||
}`
|
||||
@@ -0,0 +1,92 @@
|
||||
package webhook
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/xanzy/go-gitlab"
|
||||
|
||||
"github.com/mattermost/mattermost-plugin-gitlab/server/subscription"
|
||||
)
|
||||
|
||||
type testDataPushStr struct {
|
||||
testTitle string
|
||||
fixture string
|
||||
gitlabRetreiver *fakeWebhook
|
||||
res []*HandleWebhook
|
||||
}
|
||||
|
||||
var testDataPush = []testDataPushStr{
|
||||
{
|
||||
testTitle: "manland push 1 commit",
|
||||
fixture: PushEvent,
|
||||
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
|
||||
{ChannelID: "channel1", CreatorID: "1", Features: "pushes", Repository: "manland/webhook"},
|
||||
}),
|
||||
res: []*HandleWebhook{{
|
||||
Message: "[manland](http://my.gitlab.com/manland) has pushed 1 commit to [manland/webhook](http://localhost:3000/manland/webhook)\n" +
|
||||
"really cool commit\n [View Commit](http://localhost:3000/manland/webhook/commit/c30217b62542c586fdbadc7b5ee762bfdca10663)",
|
||||
ToUsers: []string{}, // No DM because user know he has push commits
|
||||
ToChannels: []string{"channel1"},
|
||||
From: "manland",
|
||||
}},
|
||||
}, {
|
||||
testTitle: "manland push 1 commit (subgroup)",
|
||||
fixture: strings.ReplaceAll(PushEvent, "manland/webhook", "manland/subgroup/webhook"),
|
||||
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
|
||||
{ChannelID: "channel1", CreatorID: "1", Features: "pushes", Repository: "manland/subgroup/webhook"},
|
||||
}),
|
||||
res: []*HandleWebhook{{
|
||||
Message: "[manland](http://my.gitlab.com/manland) has pushed 1 commit to [manland/subgroup/webhook](http://localhost:3000/manland/subgroup/webhook)\n" +
|
||||
"really cool commit\n [View Commit](http://localhost:3000/manland/subgroup/webhook/commit/c30217b62542c586fdbadc7b5ee762bfdca10663)",
|
||||
ToUsers: []string{}, // No DM because user know he has push commits
|
||||
ToChannels: []string{"channel1"},
|
||||
From: "manland",
|
||||
}},
|
||||
}, {
|
||||
testTitle: "manland push 2 commits",
|
||||
fixture: pushEventWithTwoCommits,
|
||||
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
|
||||
{ChannelID: "channel1", CreatorID: "1", Features: "pushes", Repository: "manland/webhook"},
|
||||
}),
|
||||
res: []*HandleWebhook{{
|
||||
Message: "[manland](http://my.gitlab.com/manland) has pushed 2 commits to [manland/webhook](http://localhost:3000/manland/webhook)\n" +
|
||||
"really cool commit\n [View Commit](http://localhost:3000/manland/webhook/commit/c30217b62542c586fdbadc7b5ee762bfdca10663)\n" +
|
||||
"another cool commit\n [View Commit](http://localhost:3000/manland/webhook/commit/595f2a068cce60954565b224bc7c966c9e708cbf)",
|
||||
ToUsers: []string{}, // No DM because user know he has push commits
|
||||
ToChannels: []string{"channel1"},
|
||||
From: "manland",
|
||||
}},
|
||||
}, {
|
||||
testTitle: "manland push 0 commits",
|
||||
fixture: pushEventWithoutCommits,
|
||||
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
|
||||
{ChannelID: "channel1", CreatorID: "1", Features: "pushes", Repository: "manland/webhook"},
|
||||
}),
|
||||
res: nil,
|
||||
},
|
||||
}
|
||||
|
||||
func TestPushWebhook(t *testing.T) {
|
||||
t.Parallel()
|
||||
for _, test := range testDataPush {
|
||||
t.Run(test.testTitle, func(t *testing.T) {
|
||||
w := NewWebhook(test.gitlabRetreiver)
|
||||
pushEvent := &gitlab.PushEvent{}
|
||||
if err := json.Unmarshal([]byte(test.fixture), pushEvent); err != nil {
|
||||
assert.Fail(t, "can't unmarshal fixture")
|
||||
}
|
||||
res, err := w.HandlePush(context.Background(), pushEvent)
|
||||
assert.Empty(t, err)
|
||||
assert.Equal(t, len(test.res), len(res))
|
||||
for index := range res {
|
||||
assert.Equal(t, test.res[index].Message, res[index].Message)
|
||||
assert.Equal(t, test.res[index].ToUsers, res[index].ToUsers)
|
||||
assert.Equal(t, test.res[index].From, res[index].From)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package webhook
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/xanzy/go-gitlab"
|
||||
)
|
||||
|
||||
func (w *webhook) HandleTag(ctx context.Context, event *gitlab.TagEvent) ([]*HandleWebhook, error) {
|
||||
handlers, err := w.handleDMTag(event)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
handlers2, err := w.handleChannelTag(ctx, event)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cleanWebhookHandlers(append(handlers, handlers2...)), nil
|
||||
}
|
||||
|
||||
func (w *webhook) handleDMTag(event *gitlab.TagEvent) ([]*HandleWebhook, error) {
|
||||
senderGitlabUsername := event.UserName
|
||||
handlers := []*HandleWebhook{}
|
||||
tagNames := strings.Split(event.Ref, "/")
|
||||
tagName := tagNames[len(tagNames)-1]
|
||||
URL := fmt.Sprintf("%s/-/tags/%s", event.Project.WebURL, tagName)
|
||||
|
||||
if mention := w.handleMention(mentionDetails{
|
||||
senderUsername: senderGitlabUsername,
|
||||
pathWithNamespace: event.Project.PathWithNamespace,
|
||||
IID: tagName,
|
||||
URL: URL,
|
||||
body: event.Message,
|
||||
}); mention != nil {
|
||||
handlers = append(handlers, mention)
|
||||
}
|
||||
|
||||
return handlers, nil
|
||||
}
|
||||
|
||||
func (w *webhook) handleChannelTag(ctx context.Context, event *gitlab.TagEvent) ([]*HandleWebhook, error) {
|
||||
senderGitlabUsername := w.gitlabRetreiver.GetUsernameByID(event.UserID)
|
||||
repo := event.Project
|
||||
tagNames := strings.Split(event.Ref, "/")
|
||||
tagName := tagNames[len(tagNames)-1]
|
||||
URL := fmt.Sprintf("%s/-/tags/%s", repo.WebURL, tagName)
|
||||
res := []*HandleWebhook{}
|
||||
|
||||
message := fmt.Sprintf("[%s](%s) New tag [%s](%s) by [%s](%s): %s", repo.PathWithNamespace, repo.WebURL, tagName, URL, senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.Message)
|
||||
|
||||
toChannels := make([]string, 0)
|
||||
namespace, project := normalizeNamespacedProject(repo.PathWithNamespace)
|
||||
subs := w.gitlabRetreiver.GetSubscribedChannelsForProject(
|
||||
ctx, namespace, project,
|
||||
repo.Visibility == gitlab.PublicVisibility,
|
||||
)
|
||||
for _, sub := range subs {
|
||||
if !sub.Tag() {
|
||||
continue
|
||||
}
|
||||
|
||||
toChannels = append(toChannels, sub.ChannelID)
|
||||
}
|
||||
|
||||
if len(toChannels) > 0 {
|
||||
res = append(res, &HandleWebhook{
|
||||
From: senderGitlabUsername,
|
||||
Message: message,
|
||||
ToUsers: []string{},
|
||||
ToChannels: toChannels,
|
||||
})
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package webhook
|
||||
|
||||
const SimpleTag = `{
|
||||
"object_kind":"tag_push",
|
||||
"event_name":"tag_push",
|
||||
"before":"0000000000000000000000000000000000000000",
|
||||
"after":"48bb9a42241a84ec7c03850f0096ac671bb06641",
|
||||
"ref":"refs/tags/tag1",
|
||||
"checkout_sha":"c30217b62542c586fdbadc7b5ee762bfdca10663",
|
||||
"message":"Really beautiful tag",
|
||||
"user_id":50,
|
||||
"user_name":"manland",
|
||||
"user_username":"manland",
|
||||
"user_email":"",
|
||||
"user_avatar":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon",
|
||||
"project_id":24,
|
||||
"project":{
|
||||
"id":24,
|
||||
"name":"webhook",
|
||||
"description":"",
|
||||
"web_url":"http://localhost:3000/manland/webhook",
|
||||
"avatar_url":null,
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"git_http_url":"http://localhost:3000/manland/webhook.git",
|
||||
"namespace":"manland",
|
||||
"visibility_level":20,
|
||||
"path_with_namespace":"manland/webhook",
|
||||
"default_branch":"master",
|
||||
"ci_config_path":null,
|
||||
"homepage":"http://localhost:3000/manland/webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"http_url":"http://localhost:3000/manland/webhook.git"
|
||||
},
|
||||
"commits":[{
|
||||
"id":"c30217b62542c586fdbadc7b5ee762bfdca10663",
|
||||
"message":"really cool commit",
|
||||
"timestamp":"2019-04-17T20:22:03Z",
|
||||
"url":"http://localhost:3000/manland/webhook/commit/c30217b62542c586fdbadc7b5ee762bfdca10663",
|
||||
"author":{
|
||||
"name":"manland",
|
||||
"email":"rmaneschi@gmail.com"
|
||||
},
|
||||
"added":[],
|
||||
"modified":["README.md"],
|
||||
"removed":[]
|
||||
}],
|
||||
"total_commits_count":1,
|
||||
"push_options":{
|
||||
|
||||
},
|
||||
"repository":{
|
||||
"name":"webhook",
|
||||
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"description":"",
|
||||
"homepage":"http://localhost:3000/manland/webhook",
|
||||
"git_http_url":"http://localhost:3000/manland/webhook.git",
|
||||
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
|
||||
"visibility_level":20
|
||||
}
|
||||
}`
|
||||
@@ -0,0 +1,70 @@
|
||||
package webhook
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/xanzy/go-gitlab"
|
||||
|
||||
"github.com/mattermost/mattermost-plugin-gitlab/server/subscription"
|
||||
)
|
||||
|
||||
type testDataTagStr struct {
|
||||
testTitle string
|
||||
fixture string
|
||||
gitlabRetreiver *fakeWebhook
|
||||
res []*HandleWebhook
|
||||
}
|
||||
|
||||
var testDataTag = []testDataTagStr{
|
||||
{
|
||||
testTitle: "manland create a tag",
|
||||
fixture: SimpleTag,
|
||||
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
|
||||
{ChannelID: "channel1", CreatorID: "1", Features: "tag", Repository: "manland/webhook"},
|
||||
}),
|
||||
res: []*HandleWebhook{{
|
||||
Message: "[manland/webhook](http://localhost:3000/manland/webhook) New tag [tag1](http://localhost:3000/manland/webhook/-/tags/tag1) by [manland](http://my.gitlab.com/manland): Really beautiful tag",
|
||||
ToUsers: []string{}, // No DM because user know he has created a tag
|
||||
ToChannels: []string{"channel1"},
|
||||
From: "manland",
|
||||
}},
|
||||
},
|
||||
{
|
||||
testTitle: "manland create a tag (subgroup)",
|
||||
fixture: strings.ReplaceAll(SimpleTag, "manland/webhook", "manland/subgroup/webhook"),
|
||||
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
|
||||
{ChannelID: "channel1", CreatorID: "1", Features: "tag", Repository: "manland/subgroup/webhook"},
|
||||
}),
|
||||
res: []*HandleWebhook{{
|
||||
Message: "[manland/subgroup/webhook](http://localhost:3000/manland/subgroup/webhook) New tag [tag1](http://localhost:3000/manland/subgroup/webhook/-/tags/tag1) by [manland](http://my.gitlab.com/manland): Really beautiful tag",
|
||||
ToUsers: []string{}, // No DM because user know he has created a tag
|
||||
ToChannels: []string{"channel1"},
|
||||
From: "manland",
|
||||
}},
|
||||
},
|
||||
}
|
||||
|
||||
func TestTagWebhook(t *testing.T) {
|
||||
t.Parallel()
|
||||
for _, test := range testDataTag {
|
||||
t.Run(test.testTitle, func(t *testing.T) {
|
||||
w := NewWebhook(test.gitlabRetreiver)
|
||||
tagEvent := &gitlab.TagEvent{}
|
||||
if err := json.Unmarshal([]byte(test.fixture), tagEvent); err != nil {
|
||||
assert.Fail(t, "can't unmarshal fixture")
|
||||
}
|
||||
res, err := w.HandleTag(context.Background(), tagEvent)
|
||||
assert.Empty(t, err)
|
||||
assert.Equal(t, len(test.res), len(res))
|
||||
for index := range res {
|
||||
assert.Equal(t, test.res[index].Message, res[index].Message)
|
||||
assert.Equal(t, test.res[index].ToUsers, res[index].ToUsers)
|
||||
assert.Equal(t, test.res[index].From, res[index].From)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package webhook
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
|
||||
"github.com/mattermost/mattermost-plugin-gitlab/server/subscription"
|
||||
|
||||
"github.com/microcosm-cc/bluemonday"
|
||||
"github.com/xanzy/go-gitlab"
|
||||
)
|
||||
|
||||
// GitlabRetreiver return infos of current GitLab instance
|
||||
type GitlabRetreiver interface {
|
||||
// GetPipelineURL return the url of this pipeline depending on the instance and project path
|
||||
GetPipelineURL(pathWithNamespace string, pipelineID int) string
|
||||
GetJobURL(pathWithNamespace string, jobID int) string
|
||||
// GetUserURL return the url of this GitLab user depending on domain3 instance (e.g. https://gitlab.com/username)
|
||||
GetUserURL(username string) string
|
||||
// GetUsernameById return a username by GitLab id
|
||||
GetUsernameByID(id int) string
|
||||
// ParseGitlabUsernamesFromText from a text return an array of username
|
||||
ParseGitlabUsernamesFromText(text string) []string
|
||||
// GetSubscribedChannelsForProject returns all subscriptions for given project.
|
||||
GetSubscribedChannelsForProject(ctx context.Context, namespace, project string, isPublicVisibility bool) []*subscription.Subscription
|
||||
}
|
||||
|
||||
type HandleWebhook struct {
|
||||
Message string
|
||||
From string
|
||||
ToUsers []string
|
||||
ToChannels []string
|
||||
}
|
||||
|
||||
type Webhook interface {
|
||||
HandleIssue(ctx context.Context, event *gitlab.IssueEvent, eventType gitlab.EventType) ([]*HandleWebhook, error)
|
||||
HandleMergeRequest(ctx context.Context, event *gitlab.MergeEvent) ([]*HandleWebhook, error)
|
||||
HandleIssueComment(ctx context.Context, event *gitlab.IssueCommentEvent) ([]*HandleWebhook, error)
|
||||
HandleMergeRequestComment(ctx context.Context, event *gitlab.MergeCommentEvent) ([]*HandleWebhook, error)
|
||||
HandlePipeline(ctx context.Context, event *gitlab.PipelineEvent) ([]*HandleWebhook, error)
|
||||
HandleTag(ctx context.Context, event *gitlab.TagEvent) ([]*HandleWebhook, error)
|
||||
HandlePush(ctx context.Context, event *gitlab.PushEvent) ([]*HandleWebhook, error)
|
||||
HandleJobs(ctx context.Context, event *gitlab.JobEvent) ([]*HandleWebhook, error)
|
||||
}
|
||||
|
||||
type webhook struct {
|
||||
gitlabRetreiver GitlabRetreiver
|
||||
}
|
||||
|
||||
func NewWebhook(g GitlabRetreiver) Webhook {
|
||||
return &webhook{gitlabRetreiver: g}
|
||||
}
|
||||
|
||||
func cleanWebhookHandlers(handlers []*HandleWebhook) []*HandleWebhook {
|
||||
res := make([]*HandleWebhook, 0)
|
||||
for _, handle := range handlers {
|
||||
res = append(res, cleanWebhookHandlerTo(handle))
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func cleanWebhookHandlerTo(handler *HandleWebhook) *HandleWebhook {
|
||||
users := map[string]bool{}
|
||||
for _, v := range handler.ToUsers {
|
||||
if handler.From != v && v != "" { // don't send message to webhook sender or unknown user
|
||||
users[v] = true
|
||||
}
|
||||
}
|
||||
|
||||
cleanedUsers := []string{}
|
||||
for key := range users {
|
||||
cleanedUsers = append(cleanedUsers, key)
|
||||
}
|
||||
|
||||
channels := map[string]bool{}
|
||||
for _, v := range handler.ToChannels {
|
||||
channels[v] = true
|
||||
}
|
||||
|
||||
cleanedChannels := []string{}
|
||||
for key := range channels {
|
||||
cleanedChannels = append(cleanedChannels, key)
|
||||
}
|
||||
|
||||
return &HandleWebhook{
|
||||
From: handler.From,
|
||||
Message: handler.Message,
|
||||
ToUsers: cleanedUsers,
|
||||
ToChannels: cleanedChannels,
|
||||
}
|
||||
}
|
||||
|
||||
type mentionDetails struct {
|
||||
senderUsername string
|
||||
pathWithNamespace string
|
||||
IID string
|
||||
URL string
|
||||
body string
|
||||
}
|
||||
|
||||
func (w *webhook) handleMention(m mentionDetails) *HandleWebhook {
|
||||
mentionedUsernames := w.gitlabRetreiver.ParseGitlabUsernamesFromText(m.body)
|
||||
if len(mentionedUsernames) > 0 {
|
||||
return &HandleWebhook{
|
||||
From: m.senderUsername,
|
||||
Message: fmt.Sprintf("[%s](%s) mentioned you on [%s#%s](%s):\n>%s", m.senderUsername, w.gitlabRetreiver.GetUserURL(m.senderUsername), m.pathWithNamespace, m.IID, m.URL, m.body),
|
||||
ToUsers: mentionedUsernames,
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func sameLabels(a []*gitlab.EventLabel, b []*gitlab.EventLabel) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
for index, l := range a {
|
||||
if l.ID != b[index].ID {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func containsLabel(a []*gitlab.EventLabel, labelName string) bool {
|
||||
for _, l := range a {
|
||||
if l != nil && l.Title == labelName {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func labelToString(a []*gitlab.EventLabel) string {
|
||||
names := make([]string, len(a))
|
||||
for index, l := range a {
|
||||
names[index] = l.Title
|
||||
}
|
||||
return strings.Join(names, ", ")
|
||||
}
|
||||
|
||||
// normalizeNamespacedProject converts data from web hooks to format expected by our plugin.
|
||||
//
|
||||
// The difference is that this plugin requires separate namespace and project path parts.
|
||||
// However in web hooks only pathWithNamespace is available.
|
||||
// In other words,
|
||||
// group/subgroup/project
|
||||
// becomes
|
||||
// namespace = group/subgroup; project = project
|
||||
func normalizeNamespacedProject(pathWithNamespace string) (namespace string, project string) {
|
||||
splits := strings.Split(pathWithNamespace, "/")
|
||||
if len(splits) < 2 {
|
||||
return "", ""
|
||||
}
|
||||
return strings.Join(splits[:len(splits)-1], "/"), splits[len(splits)-1]
|
||||
}
|
||||
|
||||
type namespaceProjectMetadata struct {
|
||||
Namespace string
|
||||
Project string
|
||||
}
|
||||
|
||||
// normalizeNamespacedProjectByHomepage converts data from web hooks to format expected by our plugin.
|
||||
func normalizeNamespacedProjectByHomepage(homepage string) (*namespaceProjectMetadata, error) {
|
||||
u, err := url.Parse(homepage)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "failed to parse homepage URL")
|
||||
}
|
||||
splits := strings.Split(u.Path, "/")
|
||||
if len(splits) < 2 {
|
||||
return nil, errors.New("")
|
||||
}
|
||||
|
||||
return &namespaceProjectMetadata{
|
||||
Namespace: strings.Join(splits[1:len(splits)-1], "/"),
|
||||
Project: splits[len(splits)-1],
|
||||
}, nil
|
||||
}
|
||||
|
||||
func sanitizeDescription(description string) string {
|
||||
var policy = bluemonday.StrictPolicy()
|
||||
policy.SkipElementsContent("details")
|
||||
return strings.TrimSpace(policy.Sanitize(description))
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package webhook
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"github.com/mattermost/mattermost-plugin-gitlab/server/subscription"
|
||||
)
|
||||
|
||||
type fakeWebhook struct {
|
||||
subs []*subscription.Subscription
|
||||
}
|
||||
|
||||
func newFakeWebhook(subs []*subscription.Subscription) *fakeWebhook {
|
||||
return &fakeWebhook{
|
||||
subs: subs,
|
||||
}
|
||||
}
|
||||
|
||||
func (*fakeWebhook) GetPipelineURL(pathWithNamespace string, pipelineID int) string {
|
||||
return fmt.Sprintf("http://my.gitlab.com/%s/-/pipelines/%d", pathWithNamespace, pipelineID)
|
||||
}
|
||||
|
||||
func (*fakeWebhook) GetJobURL(pathWithNamespace string, jobID int) string {
|
||||
return fmt.Sprintf("http://my.gitlab.com/%s/-/jobs/%d", pathWithNamespace, jobID)
|
||||
}
|
||||
|
||||
func (*fakeWebhook) GetUserURL(username string) string {
|
||||
return fmt.Sprintf("http://my.gitlab.com/%s", username)
|
||||
}
|
||||
|
||||
func (*fakeWebhook) GetUsernameByID(id int) string {
|
||||
switch id {
|
||||
case 1:
|
||||
return "root"
|
||||
case 50:
|
||||
return "manland"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func (*fakeWebhook) ParseGitlabUsernamesFromText(body string) []string {
|
||||
return []string{}
|
||||
}
|
||||
|
||||
func (f *fakeWebhook) GetSubscribedChannelsForProject(ctx context.Context, namespace, project string, isPublicVisibility bool) []*subscription.Subscription {
|
||||
return f.subs
|
||||
}
|
||||
|
||||
type testDataNormalizeNamespacedProjectStr struct {
|
||||
Title string
|
||||
InputNamespace string
|
||||
InputPathWithNamespace string
|
||||
ExpectedNamespace string
|
||||
ExpectedProject string
|
||||
}
|
||||
|
||||
var testDataNormalizeNamespacedProject = []testDataNormalizeNamespacedProjectStr{
|
||||
{
|
||||
Title: "project in group",
|
||||
InputPathWithNamespace: "group/project",
|
||||
ExpectedNamespace: "group",
|
||||
ExpectedProject: "project",
|
||||
},
|
||||
{
|
||||
Title: "project in subgroup",
|
||||
InputPathWithNamespace: "group/subgroup/project",
|
||||
ExpectedNamespace: "group/subgroup",
|
||||
ExpectedProject: "project",
|
||||
},
|
||||
}
|
||||
|
||||
func TestNormalizeNamespacedProject(t *testing.T) {
|
||||
t.Parallel()
|
||||
for _, test := range testDataNormalizeNamespacedProject {
|
||||
t.Run(test.Title, func(t *testing.T) {
|
||||
namespace, project := normalizeNamespacedProject(test.InputPathWithNamespace)
|
||||
assert.Equal(t, test.ExpectedNamespace, namespace)
|
||||
assert.Equal(t, test.ExpectedProject, project)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
var testDataNormalizeNamespacedProjectByHomepage = []testDataNormalizeNamespacedProjectStr{
|
||||
{
|
||||
Title: "homepage with group",
|
||||
InputPathWithNamespace: "http://test.url/group/project",
|
||||
ExpectedNamespace: "group",
|
||||
ExpectedProject: "project",
|
||||
},
|
||||
{
|
||||
Title: "homepage with subgroup",
|
||||
InputPathWithNamespace: "http://test.url/group/subgroup/project",
|
||||
ExpectedNamespace: "group/subgroup",
|
||||
ExpectedProject: "project",
|
||||
},
|
||||
{
|
||||
Title: "homepage with subgroup of a subgroup",
|
||||
InputPathWithNamespace: "http://test.url/group/subgroup/subgroup/project",
|
||||
ExpectedNamespace: "group/subgroup/subgroup",
|
||||
ExpectedProject: "project",
|
||||
},
|
||||
}
|
||||
|
||||
func TestNormalizeNamespacedProjectByHomePate(t *testing.T) {
|
||||
t.Parallel()
|
||||
for _, test := range testDataNormalizeNamespacedProjectByHomepage {
|
||||
t.Run(test.Title, func(t *testing.T) {
|
||||
namespaceMetadata, err := normalizeNamespacedProjectByHomepage(test.InputPathWithNamespace)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, test.ExpectedNamespace, namespaceMetadata.Namespace)
|
||||
assert.Equal(t, test.ExpectedProject, namespaceMetadata.Project)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/mattermost/mattermost/server/public/model"
|
||||
"github.com/mattermost/mattermost/server/public/plugin/plugintest"
|
||||
"github.com/mattermost/mattermost/server/public/pluginapi"
|
||||
"github.com/stretchr/testify/assert"
|
||||
gitlabLib "github.com/xanzy/go-gitlab"
|
||||
|
||||
"github.com/mattermost/mattermost-plugin-gitlab/server/webhook"
|
||||
)
|
||||
|
||||
type fakeWebhookHandler struct{}
|
||||
|
||||
func (fakeWebhookHandler) HandleIssue(_ context.Context, _ *gitlabLib.IssueEvent, _ gitlabLib.EventType) ([]*webhook.HandleWebhook, error) {
|
||||
return []*webhook.HandleWebhook{{
|
||||
Message: "hello",
|
||||
From: "test",
|
||||
ToUsers: []string{"unknown"},
|
||||
}}, nil
|
||||
}
|
||||
func (fakeWebhookHandler) HandleMergeRequest(_ context.Context, _ *gitlabLib.MergeEvent) ([]*webhook.HandleWebhook, error) {
|
||||
return []*webhook.HandleWebhook{{
|
||||
Message: "hello",
|
||||
From: "test",
|
||||
ToChannels: []string{"town-square"},
|
||||
}}, nil
|
||||
}
|
||||
func (fakeWebhookHandler) HandleIssueComment(_ context.Context, _ *gitlabLib.IssueCommentEvent) ([]*webhook.HandleWebhook, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (fakeWebhookHandler) HandleMergeRequestComment(_ context.Context, _ *gitlabLib.MergeCommentEvent) ([]*webhook.HandleWebhook, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (fakeWebhookHandler) HandlePipeline(_ context.Context, _ *gitlabLib.PipelineEvent) ([]*webhook.HandleWebhook, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (fakeWebhookHandler) HandleTag(_ context.Context, _ *gitlabLib.TagEvent) ([]*webhook.HandleWebhook, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (fakeWebhookHandler) HandlePush(_ context.Context, _ *gitlabLib.PushEvent) ([]*webhook.HandleWebhook, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (fakeWebhookHandler) HandleJobs(_ context.Context, _ *gitlabLib.JobEvent) ([]*webhook.HandleWebhook, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func TestHandleWebhookBadSecret(t *testing.T) {
|
||||
p := &Plugin{configuration: &configuration{WebhookSecret: "secret"}}
|
||||
req := httptest.NewRequest("POST", "http://example.com/foo", bytes.NewBufferString(""))
|
||||
req.Header.Add("X-Gitlab-Token", "bad_secret")
|
||||
w := httptest.NewRecorder()
|
||||
p.handleWebhook(w, req)
|
||||
resp := w.Result()
|
||||
assert.Equal(t, http.StatusUnauthorized, resp.StatusCode)
|
||||
}
|
||||
|
||||
func TestHandleWebhookBadBody(t *testing.T) {
|
||||
p := &Plugin{configuration: &configuration{WebhookSecret: "secret"}, WebhookHandler: fakeWebhookHandler{}}
|
||||
mock := &plugintest.API{}
|
||||
mock.On("LogDebug", "Can't parse webhook", "err", "unexpected event type: ", "header", "", "event", "{}").Return(nil)
|
||||
p.SetAPI(mock)
|
||||
p.client = pluginapi.NewClient(mock, p.Driver)
|
||||
req := httptest.NewRequest("POST", "/", bytes.NewBufferString(`{}`))
|
||||
req.Header.Add("X-Gitlab-Token", "secret")
|
||||
w := httptest.NewRecorder()
|
||||
p.handleWebhook(w, req)
|
||||
resp := w.Result()
|
||||
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
|
||||
mock.AssertCalled(t, "LogDebug", "Can't parse webhook", "err", "unexpected event type: ", "header", "", "event", "{}")
|
||||
}
|
||||
|
||||
func TestHandleWebhookWithKnowAuthorButUnknowToUser(t *testing.T) {
|
||||
p := &Plugin{configuration: &configuration{WebhookSecret: "secret"}, WebhookHandler: fakeWebhookHandler{}}
|
||||
|
||||
mock := &plugintest.API{}
|
||||
mock.On("KVGet", "test_gitlabusername").Return([]byte("1"), nil).Once()
|
||||
mock.On("KVGet", "unknown_gitlabusername").Return(nil, nil).Once()
|
||||
mock.On("PublishWebSocketEvent", WsEventRefresh, map[string]interface{}(nil), &model.WebsocketBroadcast{UserId: "1"}).Return(nil).Once()
|
||||
mock.On("LogInfo", "new msg", "message", "hello", "from", "test").Return(nil)
|
||||
mock.On("LogInfo", "userFrom", "from", "1").Return(nil)
|
||||
p.SetAPI(mock)
|
||||
p.client = pluginapi.NewClient(mock, p.Driver)
|
||||
|
||||
req := httptest.NewRequest("POST", "/", bytes.NewBufferString(`{"user": {"username":"test"}}`))
|
||||
req.Header.Add("X-Gitlab-Token", "secret")
|
||||
req.Header.Add("X-Gitlab-Event", string(gitlabLib.EventTypeIssue))
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
p.handleWebhook(w, req)
|
||||
resp := w.Result()
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
mock.AssertCalled(t, "KVGet", "test_gitlabusername")
|
||||
mock.AssertCalled(t, "KVGet", "unknown_gitlabusername")
|
||||
mock.AssertNumberOfCalls(t, "KVGet", 2)
|
||||
mock.AssertCalled(t, "PublishWebSocketEvent", WsEventRefresh, map[string]interface{}(nil), &model.WebsocketBroadcast{UserId: "1"})
|
||||
mock.AssertNumberOfCalls(t, "PublishWebSocketEvent", 1)
|
||||
}
|
||||
|
||||
func TestHandleWebhookToChannel(t *testing.T) {
|
||||
p := &Plugin{configuration: &configuration{WebhookSecret: "secret"}, WebhookHandler: fakeWebhookHandler{}}
|
||||
|
||||
mock := &plugintest.API{}
|
||||
mock.On("KVGet", "test_gitlabusername").Return([]byte("1"), nil).Once()
|
||||
mock.On("PublishWebSocketEvent", WsEventRefresh, map[string]interface{}(nil), &model.WebsocketBroadcast{UserId: "1"}).Return(nil).Once()
|
||||
mock.On("LogInfo", "new msg", "message", "hello", "from", "test").Return(nil)
|
||||
mock.On("LogInfo", "userFrom", "from", "1").Return(nil)
|
||||
mock.On("CreatePost", &model.Post{Id: "", CreateAt: 0, UpdateAt: 0, EditAt: 0, DeleteAt: 0, IsPinned: false, UserId: "", ChannelId: "town-square", RootId: "", OriginalId: "", Message: "hello", MessageSource: "", Type: "", Hashtags: "", Filenames: model.StringArray(nil), FileIds: model.StringArray(nil), PendingPostId: "", HasReactions: false, Metadata: (*model.PostMetadata)(nil)}).Return(&model.Post{}, nil)
|
||||
p.SetAPI(mock)
|
||||
p.client = pluginapi.NewClient(mock, p.Driver)
|
||||
|
||||
req := httptest.NewRequest("POST", "/", bytes.NewBufferString(`{"user": {"username":"test"}}`))
|
||||
req.Header.Add("X-Gitlab-Token", "secret")
|
||||
req.Header.Add("X-Gitlab-Event", string(gitlabLib.EventTypeMergeRequest))
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
p.handleWebhook(w, req)
|
||||
resp := w.Result()
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
mock.AssertCalled(t, "KVGet", "test_gitlabusername")
|
||||
mock.AssertNumberOfCalls(t, "KVGet", 1)
|
||||
mock.AssertCalled(t, "PublishWebSocketEvent", WsEventRefresh, map[string]interface{}(nil), &model.WebsocketBroadcast{UserId: "1"})
|
||||
mock.AssertNumberOfCalls(t, "PublishWebSocketEvent", 1)
|
||||
mock.AssertNumberOfCalls(t, "CreatePost", 1)
|
||||
}
|
||||
|
||||
func TestHandleWebhookForChildPipelineNotficationDisabled(t *testing.T) {
|
||||
p := &Plugin{configuration: &configuration{WebhookSecret: "secret", EnableChildPipelineNotifications: false}, WebhookHandler: fakeWebhookHandler{}}
|
||||
|
||||
mock := &plugintest.API{}
|
||||
p.SetAPI(mock)
|
||||
p.client = pluginapi.NewClient(mock, p.Driver)
|
||||
|
||||
req := httptest.NewRequest("POST", "/", bytes.NewBufferString(`{"user": {"username":"test"}, "object_attributes": {"source":"parent_pipeline"}}`))
|
||||
req.Header.Add("X-Gitlab-Token", "secret")
|
||||
req.Header.Add("X-Gitlab-Event", string(gitlabLib.EventTypePipeline))
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
p.handleWebhook(w, req)
|
||||
resp := w.Result()
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
}
|
||||
|
||||
func TestHandleWebhookForChildPipelineNotficationEnabled(t *testing.T) {
|
||||
p := &Plugin{configuration: &configuration{WebhookSecret: "secret", EnableChildPipelineNotifications: true}, WebhookHandler: fakeWebhookHandler{}}
|
||||
|
||||
mock := &plugintest.API{}
|
||||
mock.On("KVGet", "test_gitlabusername").Return([]byte("1"), nil).Once()
|
||||
mock.On("PublishWebSocketEvent", WsEventRefresh, map[string]interface{}(nil), &model.WebsocketBroadcast{UserId: "1"}).Return(nil).Once()
|
||||
p.SetAPI(mock)
|
||||
p.client = pluginapi.NewClient(mock, p.Driver)
|
||||
|
||||
req := httptest.NewRequest("POST", "/", bytes.NewBufferString(`{"user": {"username":"test"}, "object_attributes": {"source":"parent_pipeline"}}`))
|
||||
req.Header.Add("X-Gitlab-Token", "secret")
|
||||
req.Header.Add("X-Gitlab-Event", string(gitlabLib.EventTypePipeline))
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
p.handleWebhook(w, req)
|
||||
resp := w.Result()
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
mock.AssertCalled(t, "KVGet", "test_gitlabusername")
|
||||
mock.AssertNumberOfCalls(t, "KVGet", 1)
|
||||
mock.AssertCalled(t, "PublishWebSocketEvent", WsEventRefresh, map[string]interface{}(nil), &model.WebsocketBroadcast{UserId: "1"})
|
||||
mock.AssertNumberOfCalls(t, "PublishWebSocketEvent", 1)
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"presets": ["@babel/preset-env","@babel/preset-react"],
|
||||
"plugins": ["@babel/plugin-proposal-class-properties"]
|
||||
}
|
||||
@@ -0,0 +1,665 @@
|
||||
{
|
||||
"extends": "eslint:recommended",
|
||||
"parserOptions": {
|
||||
"ecmaVersion": 8,
|
||||
"sourceType": "module",
|
||||
"ecmaFeatures": {
|
||||
"jsx": true,
|
||||
"impliedStrict": true,
|
||||
"modules": true,
|
||||
"experimentalObjectRestSpread": true
|
||||
}
|
||||
},
|
||||
"parser": "@typescript-eslint/parser",
|
||||
"plugins": [
|
||||
"@typescript-eslint",
|
||||
"react",
|
||||
"import"
|
||||
],
|
||||
"env": {
|
||||
"browser": true,
|
||||
"node": true,
|
||||
"jquery": true,
|
||||
"es6": true,
|
||||
"jest": true
|
||||
},
|
||||
"globals": {
|
||||
"jest": true,
|
||||
"describe": true,
|
||||
"it": true,
|
||||
"expect": true,
|
||||
"before": true,
|
||||
"after": true,
|
||||
"beforeEach": true
|
||||
},
|
||||
"settings": {
|
||||
"import/resolver": {
|
||||
"typescript": {
|
||||
"project": ["tsconfig.json"]
|
||||
}
|
||||
},
|
||||
"react": {
|
||||
"version": "detect"
|
||||
}
|
||||
},
|
||||
"rules": {
|
||||
"array-bracket-spacing": [
|
||||
2,
|
||||
"never"
|
||||
],
|
||||
"array-callback-return": 2,
|
||||
"arrow-body-style": 0,
|
||||
"arrow-parens": [
|
||||
2,
|
||||
"always"
|
||||
],
|
||||
"arrow-spacing": [
|
||||
2,
|
||||
{
|
||||
"before": true,
|
||||
"after": true
|
||||
}
|
||||
],
|
||||
"block-scoped-var": 2,
|
||||
"brace-style": [
|
||||
2,
|
||||
"1tbs",
|
||||
{
|
||||
"allowSingleLine": false
|
||||
}
|
||||
],
|
||||
"camelcase": 0,
|
||||
"capitalized-comments": 0,
|
||||
"class-methods-use-this": 0,
|
||||
"comma-dangle": [
|
||||
2,
|
||||
"always-multiline"
|
||||
],
|
||||
"comma-spacing": [
|
||||
2,
|
||||
{
|
||||
"before": false,
|
||||
"after": true
|
||||
}
|
||||
],
|
||||
"comma-style": [
|
||||
2,
|
||||
"last"
|
||||
],
|
||||
"complexity": [
|
||||
0,
|
||||
10
|
||||
],
|
||||
"computed-property-spacing": [
|
||||
2,
|
||||
"never"
|
||||
],
|
||||
"consistent-return": 2,
|
||||
"consistent-this": [
|
||||
2,
|
||||
"self"
|
||||
],
|
||||
"constructor-super": 2,
|
||||
"curly": [
|
||||
2,
|
||||
"all"
|
||||
],
|
||||
"dot-location": [
|
||||
2,
|
||||
"object"
|
||||
],
|
||||
"dot-notation": 2,
|
||||
"eqeqeq": [
|
||||
2,
|
||||
"smart"
|
||||
],
|
||||
"func-call-spacing": [
|
||||
2,
|
||||
"never"
|
||||
],
|
||||
"func-name-matching": 0,
|
||||
"func-names": 2,
|
||||
"func-style": [
|
||||
2,
|
||||
"declaration",
|
||||
{
|
||||
"allowArrowFunctions": true
|
||||
}
|
||||
],
|
||||
"generator-star-spacing": [
|
||||
2,
|
||||
{
|
||||
"before": false,
|
||||
"after": true
|
||||
}
|
||||
],
|
||||
"global-require": 2,
|
||||
"guard-for-in": 2,
|
||||
"id-blacklist": 0,
|
||||
"import/no-unresolved": 2,
|
||||
"import/order": [
|
||||
"error",
|
||||
{
|
||||
"newlines-between": "always-and-inside-groups",
|
||||
"groups": [
|
||||
"builtin",
|
||||
"external",
|
||||
[
|
||||
"internal",
|
||||
"parent"
|
||||
],
|
||||
"sibling",
|
||||
"index"
|
||||
]
|
||||
}
|
||||
],
|
||||
"indent": [
|
||||
2,
|
||||
4,
|
||||
{
|
||||
"SwitchCase": 0
|
||||
}
|
||||
],
|
||||
"jsx-quotes": [
|
||||
2,
|
||||
"prefer-single"
|
||||
],
|
||||
"key-spacing": [
|
||||
2,
|
||||
{
|
||||
"beforeColon": false,
|
||||
"afterColon": true,
|
||||
"mode": "strict"
|
||||
}
|
||||
],
|
||||
"keyword-spacing": [
|
||||
2,
|
||||
{
|
||||
"before": true,
|
||||
"after": true,
|
||||
"overrides": {}
|
||||
}
|
||||
],
|
||||
"line-comment-position": 0,
|
||||
"linebreak-style": 2,
|
||||
"lines-around-comment": [
|
||||
2,
|
||||
{
|
||||
"beforeBlockComment": true,
|
||||
"beforeLineComment": true,
|
||||
"allowBlockStart": true,
|
||||
"allowBlockEnd": true
|
||||
}
|
||||
],
|
||||
"max-lines": [
|
||||
1,
|
||||
{
|
||||
"max": 450,
|
||||
"skipBlankLines": true,
|
||||
"skipComments": false
|
||||
}
|
||||
],
|
||||
"max-nested-callbacks": [
|
||||
2,
|
||||
{
|
||||
"max": 2
|
||||
}
|
||||
],
|
||||
"max-statements-per-line": [
|
||||
2,
|
||||
{
|
||||
"max": 1
|
||||
}
|
||||
],
|
||||
"multiline-ternary": [
|
||||
1,
|
||||
"never"
|
||||
],
|
||||
"new-cap": 2,
|
||||
"new-parens": 2,
|
||||
"newline-before-return": 0,
|
||||
"newline-per-chained-call": 0,
|
||||
"no-alert": 2,
|
||||
"no-array-constructor": 2,
|
||||
"no-await-in-loop": 2,
|
||||
"no-caller": 2,
|
||||
"no-case-declarations": 2,
|
||||
"no-class-assign": 2,
|
||||
"no-compare-neg-zero": 2,
|
||||
"no-cond-assign": [
|
||||
2,
|
||||
"except-parens"
|
||||
],
|
||||
"no-confusing-arrow": 2,
|
||||
"no-console": 2,
|
||||
"no-const-assign": 2,
|
||||
"no-constant-condition": 2,
|
||||
"no-debugger": 2,
|
||||
"no-div-regex": 2,
|
||||
"no-dupe-args": 2,
|
||||
"no-dupe-class-members": 2,
|
||||
"no-dupe-keys": 2,
|
||||
"no-duplicate-case": 2,
|
||||
"no-duplicate-imports": [
|
||||
2,
|
||||
{
|
||||
"includeExports": true
|
||||
}
|
||||
],
|
||||
"no-else-return": 2,
|
||||
"no-empty": 2,
|
||||
"no-empty-function": 2,
|
||||
"no-empty-pattern": 2,
|
||||
"no-eval": 2,
|
||||
"no-ex-assign": 2,
|
||||
"no-extend-native": 2,
|
||||
"no-extra-bind": 2,
|
||||
"no-extra-label": 2,
|
||||
"no-extra-parens": 0,
|
||||
"no-extra-semi": 2,
|
||||
"no-fallthrough": 2,
|
||||
"no-floating-decimal": 2,
|
||||
"no-func-assign": 2,
|
||||
"no-global-assign": 2,
|
||||
"no-implicit-coercion": 2,
|
||||
"no-implicit-globals": 0,
|
||||
"no-implied-eval": 2,
|
||||
"no-inner-declarations": 0,
|
||||
"no-invalid-regexp": 2,
|
||||
"no-irregular-whitespace": 2,
|
||||
"no-iterator": 2,
|
||||
"no-labels": 2,
|
||||
"no-lone-blocks": 2,
|
||||
"no-lonely-if": 2,
|
||||
"no-loop-func": 2,
|
||||
"no-magic-numbers": "off",
|
||||
"no-mixed-operators": [
|
||||
2,
|
||||
{
|
||||
"allowSamePrecedence": false
|
||||
}
|
||||
],
|
||||
"no-mixed-spaces-and-tabs": 2,
|
||||
"no-multi-assign": 2,
|
||||
"no-multi-spaces": [
|
||||
2,
|
||||
{
|
||||
"exceptions": {
|
||||
"Property": false
|
||||
}
|
||||
}
|
||||
],
|
||||
"no-multi-str": 0,
|
||||
"no-multiple-empty-lines": [
|
||||
2,
|
||||
{
|
||||
"max": 1
|
||||
}
|
||||
],
|
||||
"no-native-reassign": 2,
|
||||
"no-negated-condition": 2,
|
||||
"no-nested-ternary": 2,
|
||||
"no-new": 2,
|
||||
"no-new-func": 2,
|
||||
"no-new-object": 2,
|
||||
"no-new-symbol": 2,
|
||||
"no-new-wrappers": 2,
|
||||
"no-octal-escape": 2,
|
||||
"no-param-reassign": 2,
|
||||
"no-process-env": 2,
|
||||
"no-process-exit": 2,
|
||||
"no-proto": 2,
|
||||
"no-redeclare": 2,
|
||||
"no-return-assign": [
|
||||
2,
|
||||
"always"
|
||||
],
|
||||
"no-return-await": 2,
|
||||
"no-script-url": 2,
|
||||
"no-self-assign": [
|
||||
2,
|
||||
{
|
||||
"props": true
|
||||
}
|
||||
],
|
||||
"no-self-compare": 2,
|
||||
"no-sequences": 2,
|
||||
"no-shadow": [
|
||||
2,
|
||||
{
|
||||
"hoist": "functions"
|
||||
}
|
||||
],
|
||||
"no-shadow-restricted-names": 2,
|
||||
"no-spaced-func": 2,
|
||||
"no-tabs": 0,
|
||||
"no-template-curly-in-string": 2,
|
||||
"no-ternary": 0,
|
||||
"no-this-before-super": 2,
|
||||
"no-throw-literal": 2,
|
||||
"no-trailing-spaces": [
|
||||
2,
|
||||
{
|
||||
"skipBlankLines": false
|
||||
}
|
||||
],
|
||||
"no-undef-init": 2,
|
||||
"no-undefined": 2,
|
||||
"no-underscore-dangle": 2,
|
||||
"no-unexpected-multiline": 2,
|
||||
"no-unmodified-loop-condition": 2,
|
||||
"no-unneeded-ternary": [
|
||||
2,
|
||||
{
|
||||
"defaultAssignment": false
|
||||
}
|
||||
],
|
||||
"no-unreachable": 2,
|
||||
"no-unsafe-finally": 2,
|
||||
"no-unsafe-negation": 2,
|
||||
"no-unused-expressions": 2,
|
||||
"no-unused-vars": [
|
||||
2,
|
||||
{
|
||||
"vars": "all",
|
||||
"args": "after-used"
|
||||
}
|
||||
],
|
||||
"no-use-before-define": "off",
|
||||
"no-useless-computed-key": 2,
|
||||
"no-useless-concat": 2,
|
||||
"no-useless-constructor": 2,
|
||||
"no-useless-escape": 2,
|
||||
"no-useless-rename": 2,
|
||||
"no-useless-return": 2,
|
||||
"no-var": 0,
|
||||
"no-void": 2,
|
||||
"no-warning-comments": 1,
|
||||
"no-whitespace-before-property": 2,
|
||||
"no-with": 2,
|
||||
"object-curly-newline": 0,
|
||||
"object-curly-spacing": [
|
||||
2,
|
||||
"never"
|
||||
],
|
||||
"object-property-newline": [
|
||||
2,
|
||||
{
|
||||
"allowMultiplePropertiesPerLine": true
|
||||
}
|
||||
],
|
||||
"object-shorthand": [
|
||||
2,
|
||||
"always"
|
||||
],
|
||||
"one-var": [
|
||||
2,
|
||||
"never"
|
||||
],
|
||||
"one-var-declaration-per-line": 0,
|
||||
"operator-assignment": [
|
||||
2,
|
||||
"always"
|
||||
],
|
||||
"operator-linebreak": [
|
||||
2,
|
||||
"after"
|
||||
],
|
||||
"padded-blocks": [
|
||||
2,
|
||||
"never"
|
||||
],
|
||||
"prefer-arrow-callback": 2,
|
||||
"prefer-const": 2,
|
||||
"prefer-destructuring": 0,
|
||||
"prefer-numeric-literals": 2,
|
||||
"prefer-promise-reject-errors": 2,
|
||||
"prefer-rest-params": 2,
|
||||
"prefer-spread": 2,
|
||||
"prefer-template": 0,
|
||||
"quote-props": [
|
||||
2,
|
||||
"as-needed"
|
||||
],
|
||||
"quotes": [
|
||||
2,
|
||||
"single",
|
||||
"avoid-escape"
|
||||
],
|
||||
"radix": 2,
|
||||
"react/display-name": [
|
||||
0,
|
||||
{
|
||||
"ignoreTranspilerName": false
|
||||
}
|
||||
],
|
||||
"react/forbid-component-props": 0,
|
||||
"react/forbid-elements": [
|
||||
2,
|
||||
{
|
||||
"forbid": [
|
||||
"embed"
|
||||
]
|
||||
}
|
||||
],
|
||||
"react/jsx-boolean-value": [
|
||||
2,
|
||||
"always"
|
||||
],
|
||||
"react/jsx-closing-bracket-location": [
|
||||
2,
|
||||
{
|
||||
"location": "tag-aligned"
|
||||
}
|
||||
],
|
||||
"react/jsx-curly-spacing": [
|
||||
2,
|
||||
"never"
|
||||
],
|
||||
"react/jsx-equals-spacing": [
|
||||
2,
|
||||
"never"
|
||||
],
|
||||
"react/jsx-filename-extension": 2,
|
||||
"react/jsx-first-prop-new-line": [
|
||||
2,
|
||||
"multiline"
|
||||
],
|
||||
"react/jsx-handler-names": 0,
|
||||
"react/jsx-indent": [
|
||||
2,
|
||||
4
|
||||
],
|
||||
"react/jsx-indent-props": [
|
||||
2,
|
||||
4
|
||||
],
|
||||
"react/jsx-key": 2,
|
||||
"react/jsx-max-props-per-line": [
|
||||
2,
|
||||
{
|
||||
"maximum": 1
|
||||
}
|
||||
],
|
||||
"react/jsx-no-bind": 0,
|
||||
"react/jsx-no-comment-textnodes": 2,
|
||||
"react/jsx-no-duplicate-props": [
|
||||
2,
|
||||
{
|
||||
"ignoreCase": false
|
||||
}
|
||||
],
|
||||
"react/jsx-no-literals": 2,
|
||||
"react/jsx-no-target-blank": 2,
|
||||
"react/jsx-no-undef": 2,
|
||||
"react/jsx-pascal-case": 2,
|
||||
"react/jsx-tag-spacing": [
|
||||
2,
|
||||
{
|
||||
"closingSlash": "never",
|
||||
"beforeSelfClosing": "never",
|
||||
"afterOpening": "never"
|
||||
}
|
||||
],
|
||||
"react/jsx-uses-react": 2,
|
||||
"react/jsx-uses-vars": 2,
|
||||
"react/jsx-wrap-multilines": 2,
|
||||
"react/no-array-index-key": 1,
|
||||
"react/no-children-prop": 2,
|
||||
"react/no-danger": 0,
|
||||
"react/no-danger-with-children": 2,
|
||||
"react/no-deprecated": 1,
|
||||
"react/no-did-mount-set-state": 2,
|
||||
"react/no-did-update-set-state": 2,
|
||||
"react/no-direct-mutation-state": 2,
|
||||
"react/no-find-dom-node": 1,
|
||||
"react/no-is-mounted": 2,
|
||||
"react/no-multi-comp": [
|
||||
2,
|
||||
{
|
||||
"ignoreStateless": true
|
||||
}
|
||||
],
|
||||
"react/no-render-return-value": 2,
|
||||
"react/no-set-state": 0,
|
||||
"react/no-string-refs": 0,
|
||||
"react/no-unescaped-entities": 2,
|
||||
"react/no-unknown-property": 2,
|
||||
"react/no-unused-prop-types": [
|
||||
1,
|
||||
{
|
||||
"skipShapeProps": true
|
||||
}
|
||||
],
|
||||
"react/prefer-es6-class": 2,
|
||||
"react/prefer-stateless-function": 0,
|
||||
"react/prop-types": [
|
||||
2,
|
||||
{
|
||||
"ignore": [
|
||||
"location",
|
||||
"history",
|
||||
"component"
|
||||
]
|
||||
}
|
||||
],
|
||||
"react/require-default-props": 0,
|
||||
"react/require-optimization": 1,
|
||||
"react/require-render-return": 2,
|
||||
"react/self-closing-comp": 2,
|
||||
"react/sort-comp": 0,
|
||||
"react/style-prop-object": 2,
|
||||
"require-yield": 2,
|
||||
"rest-spread-spacing": [
|
||||
2,
|
||||
"never"
|
||||
],
|
||||
"semi": [
|
||||
2,
|
||||
"always"
|
||||
],
|
||||
"semi-spacing": [
|
||||
2,
|
||||
{
|
||||
"before": false,
|
||||
"after": true
|
||||
}
|
||||
],
|
||||
"sort-imports": 0,
|
||||
"sort-keys": 0,
|
||||
"space-before-blocks": [
|
||||
2,
|
||||
"always"
|
||||
],
|
||||
"space-before-function-paren": [
|
||||
2,
|
||||
{
|
||||
"anonymous": "never",
|
||||
"named": "never",
|
||||
"asyncArrow": "always"
|
||||
}
|
||||
],
|
||||
"space-in-parens": [
|
||||
2,
|
||||
"never"
|
||||
],
|
||||
"space-infix-ops": 2,
|
||||
"space-unary-ops": [
|
||||
2,
|
||||
{
|
||||
"words": true,
|
||||
"nonwords": false
|
||||
}
|
||||
],
|
||||
"symbol-description": 2,
|
||||
"template-curly-spacing": [
|
||||
2,
|
||||
"never"
|
||||
],
|
||||
"valid-typeof": [
|
||||
2,
|
||||
{
|
||||
"requireStringLiterals": false
|
||||
}
|
||||
],
|
||||
"vars-on-top": 0,
|
||||
"wrap-iife": [
|
||||
2,
|
||||
"outside"
|
||||
],
|
||||
"wrap-regex": 2,
|
||||
"yoda": [
|
||||
2,
|
||||
"never",
|
||||
{
|
||||
"exceptRange": false,
|
||||
"onlyEquality": false
|
||||
}
|
||||
]
|
||||
},
|
||||
"overrides": [
|
||||
{
|
||||
"files": [
|
||||
"**/*.tsx",
|
||||
"**/*.ts"
|
||||
],
|
||||
"extends": [
|
||||
"plugin:@typescript-eslint/recommended",
|
||||
"plugin:import/typescript"
|
||||
],
|
||||
"rules": {
|
||||
"@typescript-eslint/ban-ts-ignore": 0,
|
||||
"@typescript-eslint/ban-types": 1,
|
||||
"@typescript-eslint/ban-ts-comment": 0,
|
||||
"@typescript-eslint/no-var-requires": 0,
|
||||
"@typescript-eslint/prefer-interface": 0,
|
||||
"@typescript-eslint/explicit-function-return-type": 0,
|
||||
"@typescript-eslint/explicit-module-boundary-types": 0,
|
||||
"@typescript-eslint/indent": [
|
||||
2,
|
||||
4,
|
||||
{
|
||||
"SwitchCase": 0
|
||||
}
|
||||
],
|
||||
"@typescript-eslint/no-use-before-define": [
|
||||
2,
|
||||
{
|
||||
"classes": false,
|
||||
"functions": false,
|
||||
"variables": false
|
||||
}
|
||||
],
|
||||
"react/jsx-filename-extension": [
|
||||
1,
|
||||
{
|
||||
"extensions": [
|
||||
".jsx",
|
||||
".tsx"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
node_modules
|
||||
.npminstall
|
||||
.eslintcache
|
||||
@@ -0,0 +1 @@
|
||||
save-exact=true
|
||||
@@ -0,0 +1,46 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
const config = {
|
||||
presets: [
|
||||
['@babel/preset-env', {
|
||||
targets: {
|
||||
chrome: 66,
|
||||
firefox: 60,
|
||||
edge: 42,
|
||||
safari: 12,
|
||||
},
|
||||
modules: false,
|
||||
corejs: 3,
|
||||
debug: false,
|
||||
useBuiltIns: 'usage',
|
||||
shippedProposals: true,
|
||||
}],
|
||||
['@babel/preset-react', {
|
||||
useBuiltIns: true,
|
||||
}],
|
||||
['@babel/typescript', {
|
||||
allExtensions: true,
|
||||
isTSX: true,
|
||||
}],
|
||||
],
|
||||
plugins: [
|
||||
'@babel/plugin-proposal-class-properties',
|
||||
'@babel/plugin-syntax-dynamic-import',
|
||||
'@babel/proposal-object-rest-spread',
|
||||
'@babel/plugin-proposal-optional-chaining',
|
||||
'babel-plugin-typescript-to-proptypes',
|
||||
'@babel/plugin-proposal-nullish-coalescing-operator',
|
||||
],
|
||||
};
|
||||
|
||||
// Jest needs module transformation
|
||||
config.env = {
|
||||
test: {
|
||||
presets: config.presets,
|
||||
plugins: config.plugins,
|
||||
},
|
||||
};
|
||||
config.env.test.presets[0][1].modules = 'auto';
|
||||
|
||||
module.exports = config;
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"transform": {
|
||||
"^.+\\.[t|j]sx?$": "babel-jest"
|
||||
},
|
||||
"moduleNameMapper": {
|
||||
"^.+\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "identity-obj-proxy",
|
||||
"^.+\\.(css|less|scss)$": "identity-obj-proxy",
|
||||
"^.*i18n.*\\.(json)$": "<rootDir>/tests/i18n_mock.json",
|
||||
"^bundle-loader\\?lazy\\!(.*)$": "$1"
|
||||
}
|
||||
}
|
||||
Generated
+36300
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,75 @@
|
||||
{
|
||||
"name": "gitlab",
|
||||
"version": "0.1.0",
|
||||
"description": "GitLab plugin for Mattermost",
|
||||
"main": "src/index.js",
|
||||
"scripts": {
|
||||
"build": "webpack --mode=production",
|
||||
"build:watch": "webpack --mode=production --watch",
|
||||
"debug": "webpack --mode=none",
|
||||
"debug:watch": "webpack --mode=development --watch",
|
||||
"lint": "eslint --ignore-pattern node_modules --ignore-pattern dist --ext .js --ext .jsx --ext tsx --ext ts . --quiet --cache",
|
||||
"fix": "eslint --ignore-pattern node_modules --ignore-pattern dist --ext .js --ext .jsx --ext tsx --ext ts . --quiet --fix --cache",
|
||||
"test": "jest --forceExit --detectOpenHandles --verbose",
|
||||
"test:watch": "jest --watch",
|
||||
"test-ci": "jest --forceExit --detectOpenHandles --maxWorkers=2",
|
||||
"check-types": "tsc"
|
||||
},
|
||||
"dependencies": {
|
||||
"@primer/octicons-react": "10.1.0",
|
||||
"core-js": "3.6.5",
|
||||
"csstype": "3.0.3",
|
||||
"jest": "26.4.2",
|
||||
"mattermost-redux": "5.33.1",
|
||||
"prop-types": "15.7.2",
|
||||
"react": "16.13.1",
|
||||
"react-bootstrap": "1.3.0",
|
||||
"react-custom-scrollbars": "4.2.1",
|
||||
"react-dom": "16.13.1",
|
||||
"react-markdown": "^4.3.1",
|
||||
"react-redux": "7.2.1",
|
||||
"redux": "4.0.5",
|
||||
"reselect": "4.1.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"babel-jest": "29.5.0",
|
||||
"enzyme": "3.11.0",
|
||||
"enzyme-adapter-react-16": "1.15.7",
|
||||
"enzyme-to-json": "3.6.2",
|
||||
"identity-obj-proxy": "3.0.0",
|
||||
"@babel/cli": "7.11.6",
|
||||
"@babel/core": "7.11.6",
|
||||
"@babel/eslint-parser": "7.22.15",
|
||||
"@babel/plugin-proposal-class-properties": "7.10.4",
|
||||
"@babel/plugin-proposal-nullish-coalescing-operator": "7.17.12",
|
||||
"@babel/plugin-proposal-optional-chaining": "7.11.0",
|
||||
"@babel/plugin-syntax-dynamic-import": "7.8.3",
|
||||
"@babel/polyfill": "7.11.5",
|
||||
"@babel/preset-env": "7.11.5",
|
||||
"@babel/preset-react": "7.10.4",
|
||||
"@babel/preset-typescript": "7.10.4",
|
||||
"@babel/runtime": "7.11.2",
|
||||
"@types/react": "16.9.49",
|
||||
"@types/react-bootstrap": "0.32.29",
|
||||
"@types/react-custom-scrollbars": "4.0.10",
|
||||
"@types/react-intl": "3.0.0",
|
||||
"@types/react-redux": "7.1.9",
|
||||
"@types/react-transition-group": "4.4.0",
|
||||
"@typescript-eslint/eslint-plugin": "4.1.1",
|
||||
"@typescript-eslint/parser": "4.1.1",
|
||||
"babel-loader": "8.1.0",
|
||||
"babel-plugin-typescript-to-proptypes": "1.4.1",
|
||||
"css-loader": "4.3.0",
|
||||
"eslint": "7.9.0",
|
||||
"eslint-import-resolver-typescript": "3.6.1",
|
||||
"eslint-import-resolver-webpack": "0.12.2",
|
||||
"eslint-plugin-import": "2.22.0",
|
||||
"eslint-plugin-react": "7.20.6",
|
||||
"eslint-plugin-react-hooks": "4.1.2",
|
||||
"file-loader": "6.1.0",
|
||||
"style-loader": "1.2.1",
|
||||
"typescript": "4.6.4",
|
||||
"webpack": "4.44.2",
|
||||
"webpack-cli": "3.3.12"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import manifest from '../manifest';
|
||||
|
||||
const {id} = manifest;
|
||||
|
||||
export default {
|
||||
RECEIVED_YOUR_PR_DETAILS: `${id}_received_your_pr_details`,
|
||||
RECEIVED_REVIEW_DETAILS: `${id}_received_review_details`,
|
||||
RECEIVED_MENTIONS: `${id}_received_mentions`,
|
||||
RECEIVED_LHS_DATA: `${id}_received_lhs_data`,
|
||||
RECEIVED_CONNECTED: `${id}_received_connected`,
|
||||
RECEIVED_GITLAB_USER: `${id}_received_gitlab_user`,
|
||||
RECEIVED_SHOW_RHS_ACTION: `${id}_received_rhs_action`,
|
||||
UPDATE_RHS_STATE: `${id}_update_rhs_state`,
|
||||
RECEIVED_CHANNEL_SUBSCRIPTIONS: `${id}_received_channel_subscriptions`,
|
||||
};
|
||||
@@ -0,0 +1,254 @@
|
||||
import {getCurrentChannelId, getCurrentUserId} from 'mattermost-redux/selectors/entities/common';
|
||||
|
||||
import {PostTypes} from 'mattermost-redux/action_types';
|
||||
|
||||
import Client from '../client';
|
||||
import ActionTypes from '../action_types';
|
||||
import manifest from '../manifest';
|
||||
|
||||
export function getConnected(reminder = false) {
|
||||
return async (dispatch) => {
|
||||
let data;
|
||||
try {
|
||||
data = await Client.getConnected(reminder);
|
||||
} catch (error) {
|
||||
return {error};
|
||||
}
|
||||
|
||||
dispatch({
|
||||
type: ActionTypes.RECEIVED_CONNECTED,
|
||||
data,
|
||||
});
|
||||
|
||||
return {data};
|
||||
};
|
||||
}
|
||||
|
||||
function checkAndHandleNotConnected(data) {
|
||||
return async (dispatch) => {
|
||||
if (data && data.id === 'not_connected') {
|
||||
dispatch({
|
||||
type: ActionTypes.RECEIVED_CONNECTED,
|
||||
data: {
|
||||
connected: false,
|
||||
gitlab_username: '',
|
||||
gitlab_client_id: '',
|
||||
settings: {},
|
||||
},
|
||||
});
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
}
|
||||
|
||||
export function getReviewDetails(prList) {
|
||||
return async (dispatch, getState) => {
|
||||
let data;
|
||||
try {
|
||||
data = await Client.getPrsDetails(prList);
|
||||
} catch (error) {
|
||||
return {error};
|
||||
}
|
||||
|
||||
const connected = await checkAndHandleNotConnected(data)(dispatch, getState);
|
||||
if (!connected) {
|
||||
return {error: data};
|
||||
}
|
||||
|
||||
dispatch({
|
||||
type: ActionTypes.RECEIVED_REVIEW_DETAILS,
|
||||
data,
|
||||
});
|
||||
|
||||
return {data};
|
||||
};
|
||||
}
|
||||
|
||||
export function getYourPrDetails(prList) {
|
||||
return async (dispatch, getState) => {
|
||||
let data;
|
||||
try {
|
||||
data = await Client.getPrsDetails(prList);
|
||||
} catch (error) {
|
||||
return {error};
|
||||
}
|
||||
|
||||
const connected = await checkAndHandleNotConnected(data)(dispatch, getState);
|
||||
if (!connected) {
|
||||
return {error: data};
|
||||
}
|
||||
|
||||
dispatch({
|
||||
type: ActionTypes.RECEIVED_YOUR_PR_DETAILS,
|
||||
data,
|
||||
});
|
||||
|
||||
return {data};
|
||||
};
|
||||
}
|
||||
|
||||
export function getMentions() {
|
||||
return async (dispatch, getState) => {
|
||||
let data;
|
||||
try {
|
||||
data = await Client.getMentions();
|
||||
} catch (error) {
|
||||
return {error};
|
||||
}
|
||||
|
||||
const connected = await checkAndHandleNotConnected(data)(
|
||||
dispatch,
|
||||
getState,
|
||||
);
|
||||
if (!connected) {
|
||||
return {error: data};
|
||||
}
|
||||
|
||||
dispatch({
|
||||
type: ActionTypes.RECEIVED_MENTIONS,
|
||||
data,
|
||||
});
|
||||
|
||||
return {data};
|
||||
};
|
||||
}
|
||||
|
||||
export function getLHSData() {
|
||||
return async (dispatch, getState) => {
|
||||
let data;
|
||||
try {
|
||||
data = await Client.getLHSData();
|
||||
} catch (error) {
|
||||
return {error};
|
||||
}
|
||||
|
||||
const connected = await checkAndHandleNotConnected(data)(
|
||||
dispatch,
|
||||
getState,
|
||||
);
|
||||
if (!connected) {
|
||||
return {error: data};
|
||||
}
|
||||
|
||||
dispatch({
|
||||
type: ActionTypes.RECEIVED_LHS_DATA,
|
||||
data,
|
||||
});
|
||||
|
||||
return {data};
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores "showRHSPlugin" action returned by
|
||||
* "registerRightHandSidebarComponent" in plugin initialization.
|
||||
*/
|
||||
export function setShowRHSAction(showRHSPluginAction) {
|
||||
return {
|
||||
type: ActionTypes.RECEIVED_SHOW_RHS_ACTION,
|
||||
showRHSPluginAction,
|
||||
};
|
||||
}
|
||||
|
||||
export function updateRHSState(rhsState) {
|
||||
return {
|
||||
type: ActionTypes.UPDATE_RHS_STATE,
|
||||
state: rhsState,
|
||||
};
|
||||
}
|
||||
|
||||
const GITLAB_USER_GET_TIMEOUT_MILLISECONDS = 1000 * 60 * 60; // 1 hour
|
||||
|
||||
export function getGitlabUser(userID) {
|
||||
return async (dispatch, getState) => {
|
||||
if (!userID) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const user = getState()[`plugins-${manifest.id}`].gitlabUsers[userID];
|
||||
if (
|
||||
user &&
|
||||
user.last_try &&
|
||||
Date.now() - user.last_try < GITLAB_USER_GET_TIMEOUT_MILLISECONDS
|
||||
) {
|
||||
return {};
|
||||
}
|
||||
|
||||
if (user && user.username) {
|
||||
return {data: user};
|
||||
}
|
||||
|
||||
let data;
|
||||
try {
|
||||
data = await Client.getGitlabUser(userID);
|
||||
} catch (error) {
|
||||
if (error.status === 404) {
|
||||
dispatch({
|
||||
type: ActionTypes.RECEIVED_GITLAB_USER,
|
||||
userID,
|
||||
data: {last_try: Date.now()},
|
||||
});
|
||||
}
|
||||
return {error};
|
||||
}
|
||||
|
||||
dispatch({
|
||||
type: ActionTypes.RECEIVED_GITLAB_USER,
|
||||
userID,
|
||||
data,
|
||||
});
|
||||
|
||||
return {data};
|
||||
};
|
||||
}
|
||||
|
||||
export function getChannelSubscriptions(channelId) {
|
||||
return async (dispatch) => {
|
||||
if (!channelId) {
|
||||
return {};
|
||||
}
|
||||
|
||||
let subscriptions;
|
||||
try {
|
||||
subscriptions = await Client.getChannelSubscriptions(channelId);
|
||||
} catch (error) {
|
||||
return {error};
|
||||
}
|
||||
|
||||
dispatch({
|
||||
type: ActionTypes.RECEIVED_CHANNEL_SUBSCRIPTIONS,
|
||||
data: {
|
||||
channelId,
|
||||
subscriptions,
|
||||
},
|
||||
});
|
||||
|
||||
return {subscriptions};
|
||||
};
|
||||
}
|
||||
|
||||
export function sendEphemeralPost(message) {
|
||||
return (dispatch, getState) => {
|
||||
const timestamp = Date.now();
|
||||
const state = getState();
|
||||
|
||||
const post = {
|
||||
id: 'gitlabPlugin' + Date.now(),
|
||||
user_id: getCurrentUserId(state),
|
||||
channel_id: getCurrentChannelId(state),
|
||||
message,
|
||||
type: 'system_ephemeral',
|
||||
create_at: timestamp,
|
||||
update_at: timestamp,
|
||||
root_id: '',
|
||||
parent_id: '',
|
||||
props: {},
|
||||
};
|
||||
|
||||
dispatch({
|
||||
type: PostTypes.RECEIVED_NEW_POST,
|
||||
data: post,
|
||||
});
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import {Client4} from 'mattermost-redux/client';
|
||||
import {ClientError} from 'mattermost-redux/client/client4';
|
||||
|
||||
export default class Client {
|
||||
setServerRoute = (url) => {
|
||||
this.url = `${url}/api/v1`;
|
||||
}
|
||||
|
||||
getConnected = async (reminder = false) => {
|
||||
return this.doGet(`${this.url}/connected?reminder=` + reminder);
|
||||
};
|
||||
|
||||
getPrsDetails = async (prList) => {
|
||||
return this.doPost(`${this.url}/prdetails`, prList);
|
||||
}
|
||||
|
||||
getLHSData= async () => {
|
||||
return this.doGet(`${this.url}/lhs-data`);
|
||||
}
|
||||
|
||||
getMentions = async () => {
|
||||
return this.doGet(`${this.url}/mentions`);
|
||||
};
|
||||
|
||||
getGitlabUser = async (userID) => {
|
||||
return this.doPost(`${this.url}/user`, {user_id: userID});
|
||||
};
|
||||
|
||||
getIssue = async (owner, repo, issueNumber) => {
|
||||
return this.doGet(`${this.url}/issue?owner=${owner}&repo=${repo}&number=${issueNumber}`);
|
||||
}
|
||||
|
||||
getPullRequest = async (owner, repo, prNumber) => {
|
||||
return this.doGet(`${this.url}/mergerequest?owner=${owner}&repo=${repo}&number=${prNumber}`);
|
||||
}
|
||||
|
||||
getChannelSubscriptions = async (channelID) => {
|
||||
return this.doGet(`${this.url}/channel/${channelID}/subscriptions`);
|
||||
};
|
||||
|
||||
doGet = async (url, body, headers = {}) => {
|
||||
headers['X-Timezone-Offset'] = new Date().getTimezoneOffset();
|
||||
|
||||
const options = {
|
||||
method: 'get',
|
||||
headers,
|
||||
};
|
||||
|
||||
const response = await fetch(url, Client4.getOptions(options));
|
||||
|
||||
if (response.ok) {
|
||||
return response.json();
|
||||
}
|
||||
|
||||
const text = await response.text();
|
||||
|
||||
throw new ClientError(Client4.url, {
|
||||
message: text || '',
|
||||
status_code: response.status,
|
||||
url,
|
||||
});
|
||||
};
|
||||
|
||||
doPost = async (url, body, headers = {}) => {
|
||||
headers['X-Timezone-Offset'] = new Date().getTimezoneOffset();
|
||||
|
||||
const options = {
|
||||
method: 'post',
|
||||
body: JSON.stringify(body),
|
||||
headers,
|
||||
};
|
||||
|
||||
const response = await fetch(url, Client4.getOptions(options));
|
||||
|
||||
if (response.ok) {
|
||||
return response.json();
|
||||
}
|
||||
|
||||
const text = await response.text();
|
||||
|
||||
throw new ClientError(Client4.url, {
|
||||
message: text || '',
|
||||
status_code: response.status,
|
||||
url,
|
||||
});
|
||||
};
|
||||
|
||||
doDelete = async (url, body, headers = {}) => {
|
||||
headers['X-Timezone-Offset'] = new Date().getTimezoneOffset();
|
||||
|
||||
const options = {
|
||||
method: 'delete',
|
||||
headers,
|
||||
};
|
||||
|
||||
const response = await fetch(url, Client4.getOptions(options));
|
||||
|
||||
if (response.ok) {
|
||||
return response.json();
|
||||
}
|
||||
|
||||
const text = await response.text();
|
||||
|
||||
throw new ClientError(Client4.url, {
|
||||
message: text || '',
|
||||
status_code: response.status,
|
||||
url,
|
||||
});
|
||||
};
|
||||
|
||||
doPut = async (url, body, headers = {}) => {
|
||||
headers['X-Timezone-Offset'] = new Date().getTimezoneOffset();
|
||||
|
||||
const options = {
|
||||
method: 'put',
|
||||
body: JSON.stringify(body),
|
||||
headers,
|
||||
};
|
||||
|
||||
const response = await fetch(url, Client4.getOptions(options));
|
||||
|
||||
if (response.ok) {
|
||||
return response.json();
|
||||
}
|
||||
|
||||
const text = await response.text();
|
||||
|
||||
throw new ClientError(Client4.url, {
|
||||
message: text || '',
|
||||
status_code: response.status,
|
||||
url,
|
||||
});
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import ClientClass from './client.js';
|
||||
|
||||
const Client = new ClientClass();
|
||||
|
||||
export default Client;
|
||||
@@ -0,0 +1,198 @@
|
||||
import React, {useEffect, useState} from 'react';
|
||||
import ReactMarkdown from 'react-markdown';
|
||||
import {useDispatch, useSelector} from 'react-redux';
|
||||
|
||||
import {logError} from 'mattermost-redux/actions/errors';
|
||||
|
||||
import {GitLabIssueOpenIcon, GitLabMergeRequestIcon, GitLabMergeRequestClosedIcon, GitLabMergedIcon, GitLabIssueClosedIcon} from '../../utils/icons';
|
||||
|
||||
import Client from '../../client';
|
||||
import {getTruncatedText, validateGitlabUrl, isValidUrl, getInfoAboutLink} from '../../utils/tooltip_utils';
|
||||
import {TooltipData} from 'src/types/gitlab_items';
|
||||
import {getConnected, getConnectedGitlabUrl} from 'src/selectors';
|
||||
|
||||
import './tooltip.css';
|
||||
|
||||
const STATE_COLOR_MAP = {
|
||||
OPENED_COLOR: '#28a745',
|
||||
CLOSED_COLOR: '#cb2431',
|
||||
MERGED_COLOR: '#6f42c1',
|
||||
ISSUE_CLOSED_COLOR: '#0b5cad',
|
||||
};
|
||||
|
||||
const STATE_TYPES = {
|
||||
OPENED: 'opened',
|
||||
CLOSED: 'closed',
|
||||
MERGED: 'merged',
|
||||
};
|
||||
|
||||
const LINK_TYPES = {
|
||||
MERGE_REQUESTS: 'merge_requests',
|
||||
ISSUES: 'issues',
|
||||
};
|
||||
|
||||
const TOOLTIP_ICON_DIMENSION = 16;
|
||||
const TOOLTIP_MAX_TITLE_LENGTH = 70;
|
||||
|
||||
type Props = {
|
||||
href: string;
|
||||
show: boolean;
|
||||
}
|
||||
|
||||
const LinkTooltip = ({href, show}: Props) => {
|
||||
const [data, setData] = useState<TooltipData | null>(null);
|
||||
|
||||
const connected = useSelector(getConnected);
|
||||
const connectedGitlabUrl = useSelector(getConnectedGitlabUrl);
|
||||
|
||||
const dispatch = useDispatch();
|
||||
useEffect(() => {
|
||||
if (!connected || !show) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isValidUrl(href)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const url = new URL(href);
|
||||
const gitlabUrl = new URL(connectedGitlabUrl);
|
||||
const init = async () => {
|
||||
if (url.host === gitlabUrl.host && validateGitlabUrl(href)) {
|
||||
const linkInfo = getInfoAboutLink(href, url.hostname);
|
||||
let res;
|
||||
switch (linkInfo?.type) {
|
||||
case LINK_TYPES.ISSUES:
|
||||
res = await Client.getIssue(linkInfo.owner, linkInfo.repo, linkInfo.number);
|
||||
break;
|
||||
case LINK_TYPES.MERGE_REQUESTS:
|
||||
res = await Client.getPullRequest(linkInfo.owner, linkInfo.repo, linkInfo.number);
|
||||
break;
|
||||
default:
|
||||
dispatch(logError({message: `link type ${linkInfo.type} is not supported to display a tooltip`}));
|
||||
return;
|
||||
}
|
||||
|
||||
if (res) {
|
||||
res = {...res, owner: linkInfo.owner, repo: linkInfo.repo, type: linkInfo.type};
|
||||
setData(res);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
init();
|
||||
}, [connected, href, show]);
|
||||
|
||||
if (!data || !show) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const getIconElement = () => {
|
||||
let color;
|
||||
let icon;
|
||||
const {OPENED_COLOR, CLOSED_COLOR, MERGED_COLOR, ISSUE_CLOSED_COLOR} = STATE_COLOR_MAP;
|
||||
switch (data.type) {
|
||||
case LINK_TYPES.MERGE_REQUESTS:
|
||||
icon = (
|
||||
<GitLabMergeRequestIcon
|
||||
fill={OPENED_COLOR}
|
||||
width={TOOLTIP_ICON_DIMENSION}
|
||||
height={TOOLTIP_ICON_DIMENSION}
|
||||
/>
|
||||
);
|
||||
if (data.state === STATE_TYPES.CLOSED) {
|
||||
icon = <GitLabMergeRequestClosedIcon fill={CLOSED_COLOR}/>;
|
||||
} else if (data.state === STATE_TYPES.MERGED) {
|
||||
icon = <GitLabMergedIcon fill={MERGED_COLOR}/>;
|
||||
}
|
||||
break;
|
||||
case LINK_TYPES.ISSUES:
|
||||
color = data.state === STATE_TYPES.OPENED ? OPENED_COLOR : CLOSED_COLOR;
|
||||
icon = data.state === STATE_TYPES.OPENED ? <GitLabIssueOpenIcon fill={OPENED_COLOR}/> : <GitLabIssueClosedIcon fill={ISSUE_CLOSED_COLOR}/>;
|
||||
break;
|
||||
default:
|
||||
dispatch(logError({message: `link type ${data.type} is not supported to display a tooltip`}));
|
||||
}
|
||||
|
||||
return (
|
||||
<span style={{color}}>
|
||||
{icon}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
const date = new Date(data.created_at).toDateString();
|
||||
|
||||
return (
|
||||
<div className='gitlab-tooltip'>
|
||||
<div className='gitlab-tooltip box gitlab-tooltip--large gitlab-tooltip--bottom-left p-4'>
|
||||
<div className='header mb-1'>
|
||||
<a
|
||||
title={data.repo}
|
||||
href={href}
|
||||
>
|
||||
{data.repo}
|
||||
</a>
|
||||
{' on '}
|
||||
<span>{date}</span>
|
||||
</div>
|
||||
|
||||
<div className='body d-flex mt-1'>
|
||||
<span className='tooltip-icon'>
|
||||
{getIconElement()}
|
||||
</span>
|
||||
|
||||
<div className='tooltip-info mt-1'>
|
||||
<a href={href}>
|
||||
<h5 className='mr-1'>{getTruncatedText(data.title, TOOLTIP_MAX_TITLE_LENGTH)}</h5>
|
||||
<span className='mr-number'>{`#${data.iid}`}</span>
|
||||
</a>
|
||||
<div className='markdown-text mt-1 mb-1'>
|
||||
<ReactMarkdown
|
||||
source={data.description}
|
||||
disallowedTypes={['heading']}
|
||||
linkTarget='_blank'
|
||||
/>
|
||||
</div>
|
||||
|
||||
{data.type === LINK_TYPES.MERGE_REQUESTS && (
|
||||
<div className='base-head mt-1 mr-3'>
|
||||
<span
|
||||
title={data.target_branch}
|
||||
className='commit-ref'
|
||||
>
|
||||
{data.target_branch}
|
||||
</span>
|
||||
<span className='mx-1'>{'←'}</span>
|
||||
<span
|
||||
title={data.source_branch}
|
||||
className='commit-ref'
|
||||
>
|
||||
{data.source_branch}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Labels */}
|
||||
<div className='labels mt-3'>
|
||||
{data.labels && data.labels_with_details?.length && data.labels_with_details.map((label) => {
|
||||
return (
|
||||
<span
|
||||
key={label.name}
|
||||
className='label mr-1'
|
||||
title={label.description}
|
||||
style={{backgroundColor: label.color as string}}
|
||||
>
|
||||
<span style={{color: label.text_color as string}}>{label.name}</span>
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default LinkTooltip;
|
||||
@@ -0,0 +1,65 @@
|
||||
import {describe, expect, it} from '@jest/globals';
|
||||
|
||||
const {getInfoAboutLink} = require('../../utils/tooltip_utils');
|
||||
|
||||
describe('getInfoAboutLink should work as expected', () => {
|
||||
it('Should return an object of correct owner, repo, type, and number when given a valid GitLab hostname and href with all required information', () => {
|
||||
const href = 'https://gitlab.com/mattermost/test/-/merge_requests/123';
|
||||
const hostname = 'gitlab.com';
|
||||
const expected = {
|
||||
owner: 'mattermost',
|
||||
repo: 'test',
|
||||
type: 'merge_requests',
|
||||
number: '123',
|
||||
};
|
||||
|
||||
const result = getInfoAboutLink(href, hostname);
|
||||
expect(result).toEqual(expected);
|
||||
});
|
||||
|
||||
it('Should return an empty object when given a valid GitLab hostname and href missing the number', () => {
|
||||
const href = 'https://gitlab.com/mattermost/test/-/merge_requests';
|
||||
const hostname = 'gitlab.com';
|
||||
|
||||
const result = getInfoAboutLink(href, hostname);
|
||||
expect(result).toEqual({});
|
||||
});
|
||||
|
||||
it('Should return an empty object when given a valid GitLab hostname and href with missing the type parameter', () => {
|
||||
const href = 'https://gitlab.com/mattermost/test/123';
|
||||
const hostname = 'gitlab.com';
|
||||
|
||||
const result = getInfoAboutLink(href, hostname);
|
||||
expect(result).toEqual({});
|
||||
});
|
||||
|
||||
it('Should return an empty object when given an empty hostname and valid href', () => {
|
||||
const href = 'https://gitlab.com/mattermost/test/-/merge_requests/123';
|
||||
const hostname = '';
|
||||
|
||||
const result = getInfoAboutLink(href, hostname);
|
||||
expect(result).toEqual({});
|
||||
});
|
||||
|
||||
it('Should return an empty object when given a valid hostname and a invalid href', () => {
|
||||
const href = 'https://gitlab.com/mattermost/test/123Yes I think this is the right MR';
|
||||
const hostname = 'gitlab.com';
|
||||
|
||||
const result = getInfoAboutLink(href, hostname);
|
||||
expect(result).toEqual({});
|
||||
});
|
||||
|
||||
it('Should return an object valid owner, repo, type, and number with comment id when given a valid hostname and issue comment as href', () => {
|
||||
const href = 'https://gitlab.com/mattermost/test/-/issues/3#note_1340573704';
|
||||
const hostname = 'gitlab.com';
|
||||
const expected = {
|
||||
owner: 'mattermost',
|
||||
repo: 'test',
|
||||
type: 'issues',
|
||||
number: '3#note_1340573704',
|
||||
};
|
||||
|
||||
const result = getInfoAboutLink(href, hostname);
|
||||
expect(result).toEqual(expected);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,143 @@
|
||||
:root {
|
||||
--light-gray: #6a737d;
|
||||
--gray: #586069;
|
||||
--dark-gray: #24292e;
|
||||
--blue: #274466;
|
||||
--light-blue: #eff7ff;
|
||||
}
|
||||
|
||||
@media (min-width: 544px) {
|
||||
.gitlab-tooltip--large {
|
||||
min-width: 320px;
|
||||
}
|
||||
}
|
||||
|
||||
/* Gitlab Tooltip */
|
||||
.gitlab-tooltip .box {
|
||||
background-color: white;
|
||||
position: relative;
|
||||
width: 360px;
|
||||
border: 1px solid rgba(var(--center-channel-color-rgb), 0.16);
|
||||
box-shadow: 0 8px 24px rgba(0,0,0,.12);
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.gitlab-tooltip--bottom-left, .gitlab-tooltip--top-left {
|
||||
left: -9px;
|
||||
margin-left: 0;
|
||||
}
|
||||
|
||||
/* Header */
|
||||
.gitlab-tooltip .header {
|
||||
color: var(--light-gray);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.gitlab-tooltip .header a {
|
||||
text-decoration: none;
|
||||
color: var(--gray);
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
/* Body */
|
||||
.gitlab-tooltip .body > span {
|
||||
line-height: 1.25;
|
||||
}
|
||||
|
||||
/* Icon */
|
||||
.gitlab-tooltip .tooltip-icon {
|
||||
margin: 5px 5px 0 0;
|
||||
}
|
||||
|
||||
/* Info */
|
||||
.gitlab-tooltip .tooltip-info {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
font-family: Metropolis,sans-serif;
|
||||
font-size: 16px;
|
||||
line-height: 22px;
|
||||
}
|
||||
|
||||
/* Info */
|
||||
.gitlab-tooltip .tooltip-info a {
|
||||
line-height: normal;
|
||||
}
|
||||
|
||||
.gitlab-tooltip .tooltip-info > a, .gitlab-tooltip .tooltip-info > a:hover {
|
||||
display: block;
|
||||
text-decoration: none;
|
||||
color: var(--dark-gray);
|
||||
}
|
||||
|
||||
.mr-number {
|
||||
color: var(--light-gray);
|
||||
}
|
||||
|
||||
.gitlab-tooltip .tooltip-info h5 {
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
display: inline;
|
||||
}
|
||||
|
||||
.gitlab-tooltip .tooltip-info .markdown-text {
|
||||
-webkit-hyphens: auto;
|
||||
-ms-hyphens: auto;
|
||||
hyphens: auto;
|
||||
max-height: 150px;
|
||||
overflow: hidden;
|
||||
font-size: 12px;
|
||||
word-break: break-word;
|
||||
line-height: 16px;
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 3;
|
||||
-webkit-box-orient: vertical;
|
||||
}
|
||||
|
||||
.gitlab-tooltip .tooltip-info .markdown-text::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.gitlab-tooltip .see-more {
|
||||
font-weight: 600;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
/* Labels */
|
||||
.gitlab-tooltip .labels {
|
||||
justify-content: flex-start;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.gitlab-tooltip .label {
|
||||
height: 20px;
|
||||
padding: 2.4px 4px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
line-height: 15px;
|
||||
border-radius: 4px;
|
||||
box-shadow: inset 0 -1px 0 rgba(27,31,35,.12);
|
||||
display: inline-block;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
max-width: 125px;
|
||||
}
|
||||
|
||||
.gitlab-tooltip .base-head {
|
||||
display: flex;
|
||||
line-height: 1;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.gitlab-tooltip .commit-ref {
|
||||
position: relative;
|
||||
display: inline-block;
|
||||
padding: 0 5px;
|
||||
font: .75em/2 SFMono-Regular,Consolas,Liberation Mono,Menlo,monospace;
|
||||
color: var(--blue);
|
||||
white-space: nowrap;
|
||||
background-color: var(--light-blue);
|
||||
border-radius: 4px;
|
||||
max-width: 140px;
|
||||
text-overflow: ellipsis;
|
||||
overflow: hidden;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import {connect} from 'react-redux';
|
||||
import {bindActionCreators} from 'redux';
|
||||
|
||||
import {getCurrentChannelId} from 'mattermost-redux/selectors/entities/common';
|
||||
import {getCurrentUserId} from 'mattermost-redux/selectors/entities/users';
|
||||
|
||||
import manifest from '../../manifest';
|
||||
import {
|
||||
getChannelSubscriptions,
|
||||
sendEphemeralPost,
|
||||
} from '../../actions';
|
||||
import {getPluginServerRoute} from '../../selectors';
|
||||
|
||||
import RHSSidebar from './rhs_sidebar.jsx';
|
||||
|
||||
const noSubscriptions = [];
|
||||
|
||||
function mapStateToProps(state) {
|
||||
const currentUserId = getCurrentUserId(state);
|
||||
const currentChannelId = getCurrentChannelId(state);
|
||||
const {id} = manifest;
|
||||
return {
|
||||
currentUserId,
|
||||
connected: state[`plugins-${id}`].connected,
|
||||
username: state[`plugins-${id}`].username,
|
||||
gitlabURL: state[`plugins-${id}`].gitlabURL,
|
||||
currentChannelId,
|
||||
currentChannelSubscriptions: state[`plugins-${id}`].subscriptions[currentChannelId] || noSubscriptions,
|
||||
pluginServerRoute: getPluginServerRoute(state),
|
||||
};
|
||||
}
|
||||
|
||||
function mapDispatchToProps(dispatch) {
|
||||
return {
|
||||
actions: bindActionCreators(
|
||||
{
|
||||
getChannelSubscriptions,
|
||||
sendEphemeralPost,
|
||||
},
|
||||
dispatch,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export default connect(mapStateToProps, mapDispatchToProps)(RHSSidebar);
|
||||
@@ -0,0 +1,130 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import React from 'react';
|
||||
|
||||
const MattermostGitLab = () => (
|
||||
<svg
|
||||
width='100%'
|
||||
height='100%'
|
||||
viewBox='0 0 218 72'
|
||||
fill='none'
|
||||
xmlns='http://www.w3.org/2000/svg'
|
||||
>
|
||||
<g clipPath='url(#clip0_352_166600)'>
|
||||
<rect
|
||||
x='0.0476074'
|
||||
width='72'
|
||||
height='72'
|
||||
rx='36'
|
||||
fill='white'
|
||||
/>
|
||||
<path
|
||||
d='M35.1232 50.0665H17.5176L35.1232 28.8111V50.0665ZM55.6352 50.0665H38.0296C38.0296 45.2017 41.9669 41.2629 46.8332 41.2629C51.698 41.2629 55.6352 45.2049 55.6352 50.0665ZM38.0296 42.4366V21.1765H55.6352L38.0296 42.4366ZM35.1232 21.1765C35.1232 26.0381 31.1828 29.9816 26.3196 29.9816C21.4596 29.9816 17.5176 26.0412 17.5176 21.1796H35.1232V21.1765Z'
|
||||
fill='white'
|
||||
/>
|
||||
<circle
|
||||
cx='36.1426'
|
||||
cy='36'
|
||||
r='36'
|
||||
fill='url(#pattern0)'
|
||||
/>
|
||||
</g>
|
||||
<rect
|
||||
x='0.475209'
|
||||
y='0.427602'
|
||||
width='71.1448'
|
||||
height='71.1448'
|
||||
rx='35.5724'
|
||||
stroke='#3F4350'
|
||||
strokeOpacity='0.08'
|
||||
strokeWidth='0.855204'
|
||||
/>
|
||||
<path
|
||||
d='M130.557 26.3423C130.891 26.0083 130.891 25.4668 130.557 25.1328L125.115 19.6903C124.781 19.3564 124.239 19.3564 123.905 19.6903C123.571 20.0243 123.571 20.5658 123.905 20.8998L128.743 25.7375L123.905 30.5753C123.571 30.9093 123.571 31.4508 123.905 31.7848C124.239 32.1187 124.781 32.1187 125.115 31.7848L130.557 26.3423ZM88.0476 26.5928H129.953V24.8823H88.0476V26.5928Z'
|
||||
fill='#3F4350'
|
||||
fillOpacity='0.24'
|
||||
/>
|
||||
<path
|
||||
d='M87.4429 46.8672C87.109 46.5332 87.109 45.9917 87.4429 45.6577L92.8854 40.2152C93.2194 39.8813 93.7609 39.8813 94.0949 40.2152C94.4288 40.5492 94.4288 41.0907 94.0949 41.4247L89.2571 46.2624L94.0949 51.1002C94.4288 51.4342 94.4288 51.9757 94.0949 52.3096C93.7609 52.6436 93.2194 52.6436 92.8854 52.3096L87.4429 46.8672ZM129.953 47.1176H88.0477V45.4072H129.953V47.1176Z'
|
||||
fill='#3F4350'
|
||||
fillOpacity='0.24'
|
||||
/>
|
||||
<g clipPath='url(#clip1_352_166600)'>
|
||||
<rect
|
||||
x='145.953'
|
||||
width='72'
|
||||
height='72'
|
||||
rx='36'
|
||||
fill='white'
|
||||
/>
|
||||
<path
|
||||
d='M181.028 50.0665H163.423L181.028 28.8111V50.0665ZM201.54 50.0665H183.935C183.935 45.2017 187.872 41.2629 192.738 41.2629C197.603 41.2629 201.54 45.2049 201.54 50.0665ZM183.935 42.4366V21.1765H201.54L183.935 42.4366ZM181.028 21.1765C181.028 26.0381 177.088 29.9816 172.225 29.9816C167.365 29.9816 163.423 26.0412 163.423 21.1796H181.028V21.1765Z'
|
||||
fill='white'
|
||||
/>
|
||||
<circle
|
||||
cx='182.048'
|
||||
cy='36'
|
||||
r='36'
|
||||
fill='url(#pattern1)'
|
||||
/>
|
||||
</g>
|
||||
<defs>
|
||||
<pattern
|
||||
id='pattern0'
|
||||
patternContentUnits='objectBoundingBox'
|
||||
width='1'
|
||||
height='1'
|
||||
>
|
||||
<use
|
||||
xlinkHref='#image0_352_166600'
|
||||
transform='scale(0.000488281)'
|
||||
/>
|
||||
</pattern>
|
||||
<pattern
|
||||
id='pattern1'
|
||||
patternContentUnits='objectBoundingBox'
|
||||
width='1'
|
||||
height='1'
|
||||
>
|
||||
<use
|
||||
xlinkHref='#image1_352_166600'
|
||||
transform='translate(-0.333333 -0.291667) scale(0.00438597)'
|
||||
/>
|
||||
</pattern>
|
||||
<clipPath id='clip0_352_166600'>
|
||||
<rect
|
||||
x='0.0476074'
|
||||
width='72'
|
||||
height='72'
|
||||
rx='36'
|
||||
fill='white'
|
||||
/>
|
||||
</clipPath>
|
||||
<clipPath id='clip1_352_166600'>
|
||||
<rect
|
||||
x='145.953'
|
||||
width='72'
|
||||
height='72'
|
||||
rx='36'
|
||||
fill='white'
|
||||
/>
|
||||
</clipPath>
|
||||
<image
|
||||
id='image0_352_166600'
|
||||
width='2048'
|
||||
height='2048'
|
||||
xlinkHref='data:image/png;base64,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 truncated
|
||||
/>
|
||||
<image
|
||||
id='image1_352_166600'
|
||||
width='380'
|
||||
height='380'
|
||||
xlinkHref='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAXwAAAF8CAYAAADM5wDKAAAACXBIWXMAAAsSAAALEgHS3X78AAAVOUlEQVR4nO3dW4zc110H8PNf3+3Y6yR1ExKMc6HN1oCSvvUBKZFq8YYaHlBVKEqKKlQhQEFCQAQIIUBpEQ8VQgghaLmUIp4aHpAQClIr9aFvDS+pA4QkuEkTpWl8ie/rGXTWs4nj7O7M7s7M/5zz+3wkq1HqeP+XM1+f+c75n+mGw2ECoH0L7jFADAIfIAiBDxCEwAcIQuADBCHwAYIQ+ABBCHyAIAQ+QBACHyAIgQ8QhMAHCELgAwQh8AGCEPgAQQh8gCAEPkAQAh8gCIEPEITABwhC4AMEIfABghD4AEEIfIAgBD5AEAIfIAiBDxCEwAcIQuADBCHwAYIQ+ABBCHyAIAQ+QBACHyAIgQ8QhMAHCELgAwQh8AGCEPgAQQh8gCAEPkAQAh8gCIEPEITABwhC4AMEIfABghD4AEEIfIAgBD5AEAIfIAiBDxCEwAcIQuADBCHwAYIQ+ABBCHyAIAQ+QBACHyAIgQ8QhMAHCELgAwQh8AGCEPgAQQh8gCAEPkAQAh8gCIEPEITABwhC4AMEIfABghD4AEEIfIAgBD5AEAIfIAiBDxCEwAcIQuADBCHwAYIQ+ABBCHyAIAQ+QBACHyAIgQ8QhMAHCELgAwQh8AGCEPgAQQh8gCAEPkAQAh8gCIEPEITABwhC4AMEIfABghD4AEEIfIAgdrrRcZ06cfyhlNKjN12Ap48+89yz0a9NC264v4dTSqdHp+T+BtYNh8Po1yCcUyeO35NS+tuU0sPrnPs3UkqPH33muZeiX6saub+sR+AHM5r1fT2ltDjmzM+klB4xG6yL+8tGBH4gp04cz2/t8wv82IRn/XJK6aGjzzx3eoLfS8/cX8bxoW0sj28iDNLo9z4e/aJVxP1lQwI/lie2cLYCoR5buVdbGRNUSuAHcerE8Uc2Oftb9eDoQ0AKNrpHD27hCI+NxgYBCPw4tjNTv3npJuXZzj3yLi4IgR/A6MM8gdC2bf2FPhojNE7gx/DoBMv0NqLWKdg26pxVi97FxSDwY5jGDF0glGsa98a7uAAEfuNGs7/1nrjcDIFQrmkE/sPexbVP4LdvWsvuHtTzlmd0T6bxF3qyRLN9Ar9906xi1DrlcX+ZmMBv2KkTxx/d4tr79QiE8kzznhwbjRkaJfDbNu3e/RNqnXKM7sUnpnxAPqtpmMBv1IzCIJnlF2UW98Jf6g0T+O2a1UxN4JdjVvfCLL9RAr9ds1pxYQZYgBm+g0tW67RL4Ddo9CUY0/yw9mZm+f2b5T04NhpDNEbgt2nWMzSB379Z3wOz/Ab5xqsGnTpx/PQ2986ZxK2+KakfozrnrRn/8PwViPe4x20xw2/MqRPHH59D2Cez/F7N49rbUK1BAr8981phIQz6M69rb7VOYwR+Q6a4UdokZrVChPHmde1tqNYYgd+Wuc7IPIY/fz1cc7P8hgj8tsz7xSnw50/gs2UCvxEz2ChtEgJ//uZ9zW2o1hCB344+XpSLwmB+Rtd6HiuwbuYeN0LgN2C0Lvuxns5EGMxPX9f6MdtptEHgt6HPnlXgz0+f11qX3wCB34Y+X4xqnTnosc5ZJfAbIPArN9rk6sGez0Lgz17f1/hBG6rVT+DXr4RNrgT+7JVwjW2oVjmBX78SgkCtM0MF1Dmr3OPKCfyKzXGjtEkIg9kp5doujsYclRL4dSspZAX+7JR0bQV+xQR+pUabWpW0gVme/T1SwHE0ZfRBaSnv4pIN1eom8OtV4kzLLH/6SrzPZvmVEvj1EvgxlHhNBX6lBH6FRtXJvDdKm4Qvv56iOXwZ/VYdU9/VSeDXqeQZltnf9LjPTJXAr0zPG6VNQq0zPSVfSxuqVUjg16f0QFXrTEHBdc6N/OVeGYFfnxoeb/d2f/tquIa2WqiMwK9IIRulTcLMb/tquIY2VKuMwK9LLTNntc42VFLnrPJuriICvy41vbgEwda5z8yEwK9EYRulTUKts3U1XTsbqlVE4NejtgBV62xBZXXOKn+5V0LgV6DAjdIm5WnMzavxmn3Chmp1EPh1qHUG5a3+5tV6zczyKyDw61DreucHzfwmN7pWNSy7XYs1+RUQ+IUreKO0SZn5Ta7ma2VDtQoI/PLVXouodSbnXjNT3XA4dIULNdqc6qXKlmOu5d6jzzz3UnmHVY5RnfNi5adxJqV0z9FnnjtdwLGwBjP8sj3aQNgntc5EWrhGi+512QR+2Vr5IMxb/fFauUY+vC2YSqdQjbzFv5FaZx3uNfOy05UuVmszpS+eOnH82QKOo0StPZH8hJl+mczwC3XqxPHTjfT3xHPm6DPP+TasAunwC3TqxPFWPqwlpsXRGKYwAr9MPuSkdsZwgVQ6hRmtvX8r+nWgCT68LYwZfnnMjGiFWqcwAr88VjfQCmO5MAK/IJV++QWsx5fgFEbgl8WMiNYY0wXxoW0hGtooDW5kQ7WCmOGXw9p7WmRDtYII/HJYnUOrjO1CqHQK0ODmWXAza/ILYIZfBh9s0TpjvABm+AW48ssPXE3DtPPqpS5dPt+lKxdSyv8Mtdq1d5h2709pz4Hhyj+nLi3v/ovnd7mh/RL4PTv7C0tPHbh1+Ns3H8VgkNKlszn8u3TpXJcG16JdGWqysCOlvQdzyA/T3kPDtLBGd3D+re7zh/7h5JNubH/sh9+znbvSz651BPkFs//wcOVXlmf8F05fD/9rV+NcH8q1Y9f1kM9jdGUWP8ZorAv8Hgn8nu3eP7xvkiPIL6jFO/OvtDLrXw1/M3/maXUmn0M+z+Y3Y9Kxzuz40LZHZz+99ES3kDZd1ucX2uG7BumDH7q28r+TzK5gO/IYu3HMbTbsszzW85h3I/pjht+jHbvSY9v56TfWPrnyOf+D6zN/mJY8tg7cNlllM4nRmP+iG9QPgd+jnXuGD0zrp1+fgQ3TwSMpvf3mQrp4Rt3D1uTaZt/iMN1y+2Clp5+maY55Nk/g92jn7rRv2j89v0AX7xykgx9M6fybeda/IPiZSA76A7cN0oHb115lMw2zGPNMToffk1l3mfkFe/DIcKVzXV3pA+vJYySPlTxmZhX2q/T4/RH4PVnYkR6ex0/OL978IdsdH7q2sroCbpTHxB2jD2JnHfTvjMk5jX3eT6XTk24h3TPPn5yrntuODlaWdL71yoK1/MHl8XDr3VtbbbNd8x77vEvg92THrn4GfX6B5xnduTf0+xGt9vS5uulLX2Mfgd+bbmG4p8+fn1/w+w9fS6dfXVjZv4f25X1tcnUz7ZU3m9X32I9M4PekhNUK+YV/+7HByvr9c2+Y7bcqz+oPHhmsrKcvgZU6/RH4rATB7v2DdPrVzi6djVl9PsPT2CSrdFiVA+HIfeXMAtm+fC/zPRX2rBL4PSh5HXJ+aCuv5sk1AHXK9y7fw3wvS2Utfj8EPu+T12Yfue+amWGFrr9T88wFaxP4rCl/oKviqctqhdP3KhzK5UNbNpRrgT0HupXlm1bxlClXOHm5pVk94/iKw55c+7UHqrrwefWOVTzlqXUVzo4/e95A6oFKh4nkQLn9noGN2AqS70W+Jz5rYVIqHSa2uhHb7v1dOvu6iqcvucI5dIe/fNk8gd+Ta8tpecfOOq//9S+t9qBWH1p4kGpl7BdwHBGpdHoyWO7ervn4VTzz10qFU/vYr5nA78lgOb1Z+zmsVjwre6mbss3M6iqcee5ZP0vXrqaX6j+LOgn8ngwG6butnMvKzPOYDw9nYeWd1LG23kkNBwK/LwK/J4Pl9HRL56Pimb5WV+EMrqVvFHAYIQn8ngwG6WutndNqxVPyHi61yNewlQrnZi2O/Vp48KpHlz/3wIVW9wbPq3d+cMpXKW7W6ldRtlqPLV9JF/f85fP7CziUkMzwe7R8uXu+1XNb2cTrfpt4bcbKpnX3t71pXctjvgYCv0fXltO/tXx+uY4ofZveUryzLXXjr8jWx3zpVDo9q21Pna1S8ayt9QrnZvbQ6ZcZfs+uXOhei3CeKp73i1Dh3CjKWC+ZwO/Z8pX0r1HOVcXzrigVzo0ijfVSqXQKsPwrDwy6hRTqrW6ueN58Od4GbPmp2YgPqQ0Habjzz583weyZG1CAy+e7/4x2zjnwPviha2nPgTjBl881n3PEJ5IjjvESCfwCLF9OvxrxvHOdkWe7B4+0X/Hkc8znGqnCuVHUMV4alU4hLn526Xu79w/vjHr+Vy5cX8XTWsWTK5zc1e/eH/d1lj+s3ffXJ3+ogEMJzwy/EFcvpS9EPv8ciK1VPKsVTuSwT8Z2UczwC3Lpl5be2rV3eDj6dTj3RpfOvVH3XCRXOAePeG1dvdSd3vtXJ28t4FDCS2b4Zbl8Pn0u+jVIK2E5TB+4p8499vMx52MX9tcZ02Uxwy/MhV9c+p89twzvj34d0vVdFdNbpxbyCo8Cjma8XOHcGmxt/UYuv929sP9LJ3+03COMx9AszJVL6eN5zXL065BuWMVz4LbyL0c+xsircG6Wx3Aey2UdFYZnYQ5/9eTLl851/xL9OtzonadSC6x4VlfheHr4vfIYzmO5pGNCpVMsH+C+X954LS/dzE/pliA/QJXDPm+Axrt8UFsuM/xCXX47/bRq571ysB65r4yKJx9DPhZh/155zOaxW9Ix8S6BX6jFr5785oUznfXLa+iz4lHhbCyP2Tx2Sz7GyFQ6hTv/maVv7z04fCj6dVjLvCseFc7GLp3rnj3w5ZMfLfkYoxP4FYi+7cI4Z15bSOd/MNvQzxWOWf36bJ9QB5VOBS5fSB/LX/4c/TqsZ5YVjwpnvDw28xgt/Tgxw6/G6Z9bOrbv0PA7O3enfdGvxXpytXP61W5qFU+ucA7fNQy5nfGkcthfPNt9xBLMOgj8igj98fLTuWdfW0gXTm8v9PcfHqZDd3qQaiPCvj4CvzJCfzI58MLine truncated
|
||||
/>
|
||||
</defs>
|
||||
</svg>
|
||||
);
|
||||
|
||||
export default MattermostGitLab;
|
||||
|
||||
@@ -0,0 +1,322 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import React from 'react';
|
||||
|
||||
const NoSubscriptions = () => (
|
||||
<svg
|
||||
width='100%'
|
||||
height='100%'
|
||||
viewBox='0 0 606 503'
|
||||
fill='none'
|
||||
xmlns='http://www.w3.org/2000/svg'
|
||||
>
|
||||
<path
|
||||
fillRule='evenodd'
|
||||
clipRule='evenodd'
|
||||
d='M606 298C606 411.218 514.218 503 401 503C287.782 503 196 411.218 196 298C196 184.782 287.782 93 401 93C514.218 93 606 184.782 606 298ZM604 298C604 410.114 513.114 501 401 501C288.886 501 198 410.114 198 298C198 185.886 288.886 95 401 95C513.114 95 604 185.886 604 298Z'
|
||||
fill='#3F4350'
|
||||
fillOpacity='0.16'
|
||||
/>
|
||||
<path
|
||||
d='M401 501C513.114 501 604 410.114 604 298C604 185.886 513.114 95 401 95C288.886 95 198 185.886 198 298C198 410.114 288.886 501 401 501Z'
|
||||
fill='white'
|
||||
/>
|
||||
<path
|
||||
d='M401 501C513.114 501 604 410.114 604 298C604 185.886 513.114 95 401 95C288.886 95 198 185.886 198 298C198 410.114 288.886 501 401 501Z'
|
||||
fill='#3F4350'
|
||||
fillOpacity='0.16'
|
||||
/>
|
||||
<path
|
||||
d='M104.121 419.252C115.406 400.934 168.893 362.15 187.986 351.806C248.492 319.069 316.625 293.508 385.256 300.861C394.035 301.792 402.972 303.32 410.668 307.617C403.649 322.037 409.63 338.937 410.961 354.885C411.205 356.448 411.018 358.046 410.42 359.514C409.294 361.194 407.637 362.462 405.703 363.124C340.864 393.292 275.461 423.04 215.812 462.2C202.271 471.06 189.881 482.29 174.399 486.897C158.918 491.504 125.133 486.897 113.104 476.376C102.677 467.184 86.5407 447.869 104.121 419.252Z'
|
||||
fill='#FFBC1F'
|
||||
/>
|
||||
<path
|
||||
d='M357.112 195.163C339.17 201.808 329.398 223.294 333.777 241.678C338.155 260.062 354.652 274.305 373.249 279.022C379.122 280.819 385.408 280.857 391.304 279.133C396.006 277.219 400.192 274.262 403.536 270.495C408.169 265.784 412.256 260.584 415.722 254.99C419.652 249.114 422.183 242.444 423.125 235.476C424.321 223.161 417.799 210.845 407.959 203.115C398.119 195.385 385.391 191.863 372.775 191.265C371.398 191.11 357.112 195.163 357.112 195.163Z'
|
||||
fill='#6F370B'
|
||||
/>
|
||||
<mask
|
||||
id='mask0_485_13954'
|
||||
style={{maskType: 'alpha'}}
|
||||
maskUnits='userSpaceOnUse'
|
||||
x='197'
|
||||
y='95'
|
||||
width='407'
|
||||
height='406'
|
||||
>
|
||||
<path
|
||||
d='M401 501C513.114 501 604 410.114 604 298C604 185.886 513.114 95 401 95C288.886 95 198 185.886 198 298C198 410.114 288.886 501 401 501Z'
|
||||
fill='white'
|
||||
/>
|
||||
</mask>
|
||||
<g mask='url(#mask0_485_13954)'>
|
||||
<mask
|
||||
id='mask1_485_13954'
|
||||
style={{maskType: 'alpha'}}
|
||||
maskUnits='userSpaceOnUse'
|
||||
x='96'
|
||||
y='299'
|
||||
width='316'
|
||||
height='190'
|
||||
>
|
||||
<path
|
||||
d='M104.121 419.252C115.405 400.934 168.893 362.15 187.985 351.806C248.491 319.069 316.625 293.508 385.256 300.861C394.035 301.792 402.972 303.32 410.668 307.617C403.649 322.037 409.63 338.937 410.961 354.885C411.205 356.448 411.018 358.046 410.419 359.514C409.294 361.194 407.636 362.462 405.703 363.124C340.864 393.292 275.46 423.04 215.812 462.2C202.271 471.06 189.881 482.29 174.399 486.897C158.917 491.504 125.132 486.897 113.103 476.376C102.677 467.184 86.5404 447.869 104.121 419.252Z'
|
||||
fill='#CB8E00'
|
||||
/>
|
||||
</mask>
|
||||
<g mask='url(#mask1_485_13954)'>
|
||||
<rect
|
||||
opacity='0.72'
|
||||
x='96.2966'
|
||||
y='298.906'
|
||||
width='224.941'
|
||||
height='182.381'
|
||||
fill='url(#pattern0)'
|
||||
/>
|
||||
</g>
|
||||
<path
|
||||
fillRule='evenodd'
|
||||
clipRule='evenodd'
|
||||
d='M403.919 302.344C401.194 304.991 398.479 307.701 395.782 310.471C402.292 309.606 408.788 308.88 415.172 308.338C409.483 305.267 405.417 303.128 403.919 302.344ZM403.457 302.102C396.296 300.513 322.982 285.942 226.616 332.141C226.579 332.144 226.55 332.158 226.531 332.181L226.616 332.141C229.237 331.909 275.794 382.735 253.117 450.727C261.344 452.092 271.435 452.65 282.015 452.674C284.61 475.331 289.97 494.872 299.834 503.953C338.832 539.791 473.25 510.642 511.255 473.807C516.091 469.129 519.877 461.212 522.831 451.466C532.998 464 544.049 476.585 552.419 483.952C580.239 461.246 606.867 437.168 632.198 411.81C633.062 411.129 633.64 410.159 633.823 409.086C633.788 408.253 633.514 407.447 633.033 406.76C617.338 379.622 596.206 365.854 568.582 347.856C566.692 346.625 564.773 345.374 562.823 344.098C540.741 329.61 511.595 320.02 484.263 313.713C479.28 312.333 474.251 311.118 469.232 310.009C464.6 308.988 459.562 308.275 454.213 307.828C425.125 303.066 403.287 302.014 403.287 302.014C403.287 302.014 403.344 302.044 403.457 302.102Z'
|
||||
fill='white'
|
||||
/>
|
||||
<path
|
||||
fillRule='evenodd'
|
||||
clipRule='evenodd'
|
||||
d='M403.919 302.344C401.194 304.991 398.479 307.701 395.782 310.471C402.292 309.606 408.788 308.88 415.172 308.338C409.483 305.267 405.417 303.128 403.919 302.344ZM403.457 302.102C396.296 300.513 322.982 285.942 226.616 332.141C226.579 332.144 226.55 332.158 226.531 332.181L226.616 332.141C229.237 331.909 275.794 382.735 253.117 450.727C261.344 452.092 271.435 452.65 282.015 452.674C284.61 475.331 289.97 494.872 299.834 503.953C338.832 539.791 473.25 510.642 511.255 473.807C516.091 469.129 519.877 461.212 522.831 451.466C532.998 464 544.049 476.585 552.419 483.952C580.239 461.246 606.867 437.168 632.198 411.81C633.062 411.129 633.64 410.159 633.823 409.086C633.788 408.253 633.514 407.447 633.033 406.76C617.338 379.622 596.206 365.854 568.582 347.856C566.692 346.625 564.773 345.374 562.823 344.098C540.741 329.61 511.595 320.02 484.263 313.713C479.28 312.333 474.251 311.118 469.232 310.009C464.6 308.988 459.562 308.275 454.213 307.828C425.125 303.066 403.287 302.014 403.287 302.014C403.287 302.014 403.344 302.044 403.457 302.102Z'
|
||||
fill='#3F4350'
|
||||
fillOpacity='0.04'
|
||||
/>
|
||||
<path
|
||||
d='M226.577 333.444C243.412 352.218 254.037 375.569 257.044 400.403C257.225 401.865 259.504 401.311 259.301 399.849C256.209 374.618 245.379 350.904 228.247 331.849C227.254 330.742 225.539 332.337 226.554 333.444H226.577Z'
|
||||
fill='#6F370B'
|
||||
/>
|
||||
<mask
|
||||
id='mask2_485_13954'
|
||||
style={{maskType: 'alpha'}}
|
||||
maskUnits='userSpaceOnUse'
|
||||
x='226'
|
||||
y='298'
|
||||
width='408'
|
||||
height='223'
|
||||
>
|
||||
<path
|
||||
fillRule='evenodd'
|
||||
clipRule='evenodd'
|
||||
d='M403.459 302.103C396.309 300.515 322.99 285.938 226.616 332.141C226.579 332.144 226.551 332.158 226.531 332.181L226.616 332.141C229.238 331.909 275.794 382.735 253.117 450.727C261.345 452.092 271.435 452.65 282.015 452.674C284.609 475.331 289.969 494.872 299.834 503.953C338.832 539.791 473.249 510.642 511.255 473.807C516.091 469.128 519.878 461.211 522.831 451.464C532.998 463.999 544.049 476.585 552.42 483.952C580.24 461.246 606.868 437.167 632.199 411.81C633.063 411.128 633.641 410.158 633.824 409.085C633.789 408.253 633.515 407.446 633.034 406.76C617.339 379.622 596.207 365.853 568.583 347.856C566.694 346.625 564.774 345.374 562.824 344.098C540.739 329.607 511.587 320.017 484.251 313.709C479.272 312.331 474.247 311.117 469.232 310.009C464.601 308.988 459.566 308.275 454.219 307.829C425.128 303.066 403.288 302.013 403.288 302.013C403.288 302.013 403.346 302.044 403.459 302.103ZM403.92 302.344C401.195 304.99 398.479 307.701 395.783 310.471C402.293 309.606 408.789 308.88 415.173 308.337C409.484 305.266 405.417 303.127 403.92 302.344Z'
|
||||
fill='white'
|
||||
/>
|
||||
</mask>
|
||||
<g mask='url(#mask2_485_13954)'>
|
||||
<rect
|
||||
opacity='0.5'
|
||||
x='225.493'
|
||||
y='297.773'
|
||||
width='401.432'
|
||||
height='223.162'
|
||||
fill='url(#pattern1)'
|
||||
/>
|
||||
<rect
|
||||
opacity='0.5'
|
||||
x='225.493'
|
||||
y='297.773'
|
||||
width='183.413'
|
||||
height='223.162'
|
||||
fill='url(#pattern2)'
|
||||
/>
|
||||
</g>
|
||||
<path
|
||||
d='M527.008 414.749C524.141 427.574 522.494 440.62 519.65 453.467C519.334 454.907 521.591 455.682 521.907 454.132C524.638 441.263 526.421 428.216 529.264 415.392C529.58 413.952 527.324 413.177 527.008 414.749Z'
|
||||
fill='#6F370B'
|
||||
/>
|
||||
<path
|
||||
d='M390.74 312.136L389.589 275.367C389.682 272.181 389.208 269.003 388.19 265.976C386.887 263.304 385.225 260.815 383.247 258.578C366.795 237.53 359.187 211.094 361.988 184.708C362.502 178.471 364.145 172.373 366.84 166.701C373.317 153.987 386.858 146.345 400.264 140.941C409.923 137.064 420.417 133.897 430.663 135.758C443.166 137.973 453.412 147.652 458.535 159.059C463.658 170.466 464.222 183.424 462.688 195.783C461.952 204.35 459.342 212.661 455.037 220.148C450.794 226.926 444.543 232.353 440.255 239.13C433.033 250.538 443.166 264.868 443.031 278.313C442.895 291.758 457.52 310.165 452.555 322.613C447.59 335.061 420.733 360.666 399.18 353.623C382.412 348.152 385.775 324.54 388.821 317.939L390.74 312.136Z'
|
||||
fill='#FFBC1F'
|
||||
/>
|
||||
<path
|
||||
d='M416.422 266.175C408.185 268.125 393.064 268.39 384.826 260.66C386.176 262.274 387.292 264.063 388.144 265.976C389.163 269.003 389.636 272.181 389.543 275.367C389.701 280.24 389.837 285.113 389.995 289.986C393.538 269.299 408.726 273.064 416.919 268.523L416.422 266.175Z'
|
||||
fill='#CC8F00'
|
||||
/>
|
||||
</g>
|
||||
<path
|
||||
d='M389.509 250.49C395.949 250.555 402.235 248.566 407.424 244.822C408.625 243.939 407.367 241.982 406.144 242.862C401.309 246.4 395.417 248.268 389.387 248.177C387.887 248.176 388.012 250.467 389.518 250.424L389.509 250.49Z'
|
||||
fill='#6F370B'
|
||||
/>
|
||||
<path
|
||||
d='M380.855 220.967C381.227 222.959 381.227 225.001 380.855 226.992C380.55 228.244 380.55 229.55 380.855 230.802C381.803 233.548 384.691 233.017 386.655 231.732C387.873 230.891 386.655 228.875 385.526 229.717C384.398 230.558 382.999 230.669 382.976 229.118C383.03 228.188 383.15 227.263 383.337 226.35C383.582 224.371 383.498 222.366 383.089 220.414C382.796 218.952 380.516 219.506 380.832 220.967H380.855Z'
|
||||
fill='#6F370B'
|
||||
/>
|
||||
<path
|
||||
d='M550.343 185.816C525.022 161.451 490.086 167.099 471.76 176.956C467.247 165.194 461.763 137.086 422.11 131.017C411.209 129.334 392.139 134.207 379.23 141.494C366.321 148.781 354.675 160.72 356.21 176.557C356.729 181.873 361.559 187.056 361.807 186.037L362.98 177.664C369.187 180.455 377.176 175.56 378.282 171.883C382.209 180.5 413.692 187.122 423.419 187.078C429.467 187.078 436.644 185.218 440.774 189.559C445.874 194.897 440.954 203.425 435.944 208.829C430.934 214.234 425.495 222.119 429.896 228.1C432.401 231.422 437.592 232.862 438.517 236.959C439.217 239.994 437.073 242.896 435.47 245.576C427.684 258.666 435.335 279.088 441.654 287.66C455.421 306.51 486.994 334.684 534.185 312.357C575.011 292.998 589.612 223.647 550.343 185.816Z'
|
||||
fill='#6F370B'
|
||||
/>
|
||||
<mask
|
||||
id='mask3_485_13954'
|
||||
style={{maskType: 'alpha'}}
|
||||
maskUnits='userSpaceOnUse'
|
||||
x='356'
|
||||
y='130'
|
||||
width='218'
|
||||
height='191'
|
||||
>
|
||||
<path
|
||||
d='M550.343 185.816C525.022 161.451 490.086 167.099 471.76 176.956C467.247 165.194 461.763 137.086 422.11 131.017C411.209 129.334 392.139 134.207 379.23 141.494C366.321 148.781 354.675 160.72 356.21 176.557C356.729 181.873 361.559 187.056 361.807 186.037L362.98 177.664C369.187 180.455 377.176 175.56 378.282 171.883C382.209 180.5 413.692 187.122 423.419 187.078C429.467 187.078 436.644 185.218 440.774 189.559C445.874 194.897 440.954 203.425 435.944 208.829C430.934 214.234 425.495 222.119 429.896 228.1C432.401 231.422 437.592 232.862 438.517 236.959C439.217 239.994 437.073 242.896 435.47 245.576C427.684 258.666 435.335 279.088 441.654 287.66C455.421 306.51 486.994 334.684 534.185 312.357C575.011 292.998 589.612 223.647 550.343 185.816Z'
|
||||
fill='#1A0C00'
|
||||
/>
|
||||
</mask>
|
||||
<g mask='url(#mask3_485_13954)'>
|
||||
<rect
|
||||
x='-28.2854'
|
||||
y='76.877'
|
||||
width='655.212'
|
||||
height='286.599'
|
||||
fill='url(#pattern3)'
|
||||
/>
|
||||
</g>
|
||||
<path
|
||||
d='M185.142 417.812C210.58 416.245 235.901 422.309 257.744 435.2C259.031 435.975 260.001 433.849 258.692 432.985C236.483 419.925 210.754 413.799 184.916 415.42C183.404 415.42 183.63 417.813 185.142 417.635V417.812Z'
|
||||
fill='#6F370B'
|
||||
/>
|
||||
<path
|
||||
d='M424.593 196.824C416.274 196.242 407.913 196.839 399.767 198.596C398.639 198.84 399.113 201.21 400.219 200.966C408.184 199.282 416.352 198.715 424.48 199.283C425.811 199.371 425.834 196.913 424.593 196.824Z'
|
||||
fill='white'
|
||||
/>
|
||||
<path
|
||||
d='M398.842 199.97C399.948 203.159 401.843 208.697 400.061 211.997C396.337 218.841 389.182 209.782 388.099 206.858C387.016 203.935 385.842 199.283 388.099 196.293C391.778 191.176 397.33 195.673 398.548 199.372C399.067 200.878 401.776 200.258 401.257 198.729C399.767 194.299 395.321 190.379 389.769 192.084C382.841 194.299 383.586 202.517 385.436 207.456C387.287 212.396 392.365 218.531 398.977 216.316C406.019 213.924 403.22 204.045 401.618 199.416C401.099 197.91 398.39 198.53 398.909 200.058L398.842 199.97Z'
|
||||
fill='white'
|
||||
/>
|
||||
<path
|
||||
d='M363.364 209.582C363.184 206.238 362.89 200.39 365.621 197.71C371.195 192.15 375.596 202.893 375.845 205.95C376.093 209.006 375.845 213.835 372.911 216.094C367.855 220.015 363.703 214.167 363.567 210.269C363.567 208.674 360.679 208.519 360.746 210.136C360.707 211.368 360.919 212.594 361.37 213.744C361.822 214.893 362.503 215.943 363.373 216.83C364.244 217.718 365.287 218.426 366.44 218.912C367.594 219.398 368.834 219.652 370.09 219.661C377.447 219.505 379.117 211.354 378.666 206.083C378.214 200.811 374.987 193.612 367.923 193.945C360.385 194.299 360.34 204.554 360.588 209.45C360.588 211.066 363.477 211.199 363.409 209.582H363.364Z'
|
||||
fill='white'
|
||||
/>
|
||||
<path
|
||||
d='M378.553 206.282C379.151 205.847 379.838 205.544 380.566 205.395C381.295 205.246 382.048 205.254 382.773 205.418C383.111 205.514 383.436 205.648 383.743 205.817C383.992 205.95 384.127 206.082 384.059 206.016C385.256 207.057 387.061 205.329 385.842 204.288C384.627 203.363 383.14 202.848 381.603 202.821C380.066 202.793 378.56 203.253 377.311 204.133C375.935 204.975 377.176 207.124 378.553 206.348V206.282Z'
|
||||
fill='white'
|
||||
/>
|
||||
<path
|
||||
d='M395.368 202.894L392.343 203.204C392.101 203.293 391.896 203.458 391.759 203.674C391.623 203.89 391.563 204.144 391.589 204.396C391.615 204.649 391.725 204.886 391.902 205.071C392.079 205.256 392.314 205.378 392.569 205.419L395.593 205.086C395.825 204.991 396.02 204.825 396.149 204.613C396.278 204.401 396.334 204.154 396.308 203.908C396.283 203.662 396.178 203.431 396.009 203.248C395.839 203.066 395.614 202.941 395.368 202.894Z'
|
||||
fill='#6F370B'
|
||||
/>
|
||||
<path
|
||||
d='M370.88 205.618L367.856 205.95C367.614 206.04 367.409 206.205 367.272 206.421C367.136 206.637 367.076 206.89 367.102 207.143C367.127 207.396 367.237 207.633 367.415 207.818C367.592 208.003 367.826 208.125 368.081 208.165L371.106 207.855C371.359 207.773 371.576 207.609 371.722 207.39C371.867 207.17 371.932 206.909 371.906 206.648C371.88 206.388 371.764 206.143 371.577 205.956C371.391 205.769 371.145 205.65 370.88 205.618Z'
|
||||
fill='#6F370B'
|
||||
/>
|
||||
<path
|
||||
d='M178.89 492.745C227.412 496.621 264.966 499.035 305.68 500.01C344.655 500.962 379.907 505.437 400.647 485.613C420.146 466.963 446.777 462.71 474.288 463.197C476.545 463.197 477.944 460.539 476.138 459.277C472.189 457.033 467.762 455.721 463.207 455.445C453.886 454.714 445.897 454.536 445.874 454.492C444.117 451.384 441.207 449.06 437.75 448.002C433.148 446.794 428.369 446.375 423.622 446.762C419.356 447.205 420.981 444.768 413.534 443.838C406.264 443.26 398.946 443.798 391.845 445.433C383.066 447.648 370.067 452.986 359.167 457.66C342.714 464.725 307.011 454.093 290.152 447.869C273.858 441.867 252.282 431.257 236.349 424.634C216.466 416.395 206.852 408.554 188.685 405.143C167.651 401.178 151.176 398.963 130.503 405.785C109.831 412.607 92.1372 431.368 95.3871 450.084C97.0138 457.433 100.596 464.227 105.768 469.775C122.243 489.068 141.494 490.419 169.366 492.058L178.89 492.745Z'
|
||||
fill='#FFBC1F'
|
||||
/>
|
||||
<path
|
||||
d='M419.221 456.442C424.538 454.606 430.092 453.51 435.719 453.186C441.531 452.363 447.41 452.081 453.277 452.344C453.522 452.413 453.738 452.558 453.891 452.758C454.045 452.958 454.128 453.201 454.128 453.452C454.128 453.702 454.045 453.945 453.891 454.145C453.738 454.345 453.522 454.49 453.277 454.559C447.615 454.296 441.94 454.556 436.328 455.334C430.945 455.644 425.63 456.673 420.53 458.391C419.153 458.967 418.025 456.929 419.424 456.353L419.221 456.442Z'
|
||||
fill='#6F370B'
|
||||
/>
|
||||
<path
|
||||
d='M414.076 446.718C415.872 445.844 417.8 445.261 419.786 444.99C421.17 444.913 422.549 444.757 423.916 444.525C424.193 444.508 424.468 444.588 424.691 444.751C424.914 444.915 425.07 445.15 425.133 445.416C425.195 445.682 425.159 445.961 425.031 446.204C424.903 446.446 424.692 446.636 424.435 446.74C421.253 447.493 418.206 447.205 415.182 448.711C413.827 449.376 412.722 447.338 414.076 446.673V446.718Z'
|
||||
fill='#6F370B'
|
||||
/>
|
||||
<path
|
||||
d='M249.431 98.3025V243.231C249.468 244.689 249.192 246.139 248.623 247.482C248.055 248.825 247.205 250.031 246.133 251.019C243.96 253.082 241.139 254.326 238.152 254.539H81.6957C83.5487 254.407 85.3377 253.878 86.9477 253.003C85.2656 253.813 83.4016 254.207 81.5135 254.138C78.6954 254.207 75.9641 253.158 73.9156 251.219C71.8188 249.227 70.5666 246.504 70.4175 243.614V145.122H92.9921V63.6299H215.195C216.111 63.6659 216.98 64.0465 217.629 64.6956C218.043 65.1104 218.348 65.6154 218.523 66.1653L248.265 95.5847L248.669 96.1862C248.784 96.3325 248.887 96.4869 248.978 96.648L249.048 96.752H249.035C249.284 97.2277 249.427 97.7568 249.449 98.3025H249.431Z'
|
||||
fill='white'
|
||||
/>
|
||||
<path
|
||||
d='M147.871 249.468L92.9921 245.565C92.3041 248.015 90.8791 250.193 88.9108 251.803C86.7875 253.411 84.1744 254.236 81.5135 254.137C78.6954 254.207 75.9641 253.158 73.9156 251.219C71.8188 249.227 70.5666 246.504 70.4175 243.614V145.122H147.871V249.468Z'
|
||||
fill='#989DAE'
|
||||
/>
|
||||
<path
|
||||
d='M249.431 98.3025V243.231C249.468 244.689 249.192 246.139 248.624 247.482C248.055 248.825 247.206 250.031 246.133 251.019C243.96 253.082 241.139 254.326 238.152 254.539H81.6958C84.6828 254.326 87.5033 253.082 89.6762 251.019C90.7512 250.032 91.6032 248.827 92.1751 247.484C92.747 246.14 93.0255 244.691 92.9922 243.231V63.6299H215.195C216.111 63.6659 216.98 64.0465 217.629 64.6956C218.277 65.3447 218.657 66.2146 218.693 67.1319V75.7043L224.16 94.8006H226.109V78.0571L245.568 94.8006H245.951C246.867 94.8366 247.736 95.2171 248.384 95.8662C249.033 96.5153 249.413 97.3853 249.449 98.3025H249.431Z'
|
||||
fill='white'
|
||||
/>
|
||||
<path
|
||||
d='M249.431 98.3025V243.231C249.468 244.689 249.192 246.139 248.624 247.482C248.055 248.825 247.206 250.031 246.133 251.019C243.96 253.082 241.139 254.326 238.153 254.539H81.6958C84.6828 254.326 87.5033 253.082 89.6763 251.019C90.7512 250.032 91.6032 248.827 92.1751 247.484C92.747 246.14 93.0255 244.691 92.9922 243.231V63.6299H215.195C216.111 63.6659 216.98 64.0465 217.629 64.6956C218.277 65.3447 218.658 66.2146 218.693 67.1319V75.7043L224.16 94.8006H226.109V78.0571L245.568 94.8006H245.951C246.867 94.8366 247.736 95.2171 248.384 95.8662C249.033 96.5153 249.413 97.3853 249.449 98.3025H249.431Z'
|
||||
fill='#E8E9ED'
|
||||
/>
|
||||
<path
|
||||
d='M129.961 83.5105H113.235V80.3916H129.961V83.5105ZM229.206 134.142H113.235V137.663H229.206V134.142ZM229.206 241.279H113.235V237.777H229.206V241.279Z'
|
||||
fill='#BABEC9'
|
||||
/>
|
||||
<path
|
||||
d='M173.945 175.454H113.235V168.432H173.945V175.454ZM174.327 185.576H113.235V192.197H174.327V185.576ZM174.327 202.32H113.235V209.342H174.327V202.32ZM174.327 219.465H113.235V226.086H174.327V219.465ZM229.206 219.465H184.439V226.086H229.206V219.465Z'
|
||||
fill='#BABEC9'
|
||||
/>
|
||||
<path
|
||||
d='M204.299 91.6816C205.216 91.7177 206.085 92.0982 206.733 92.7473C207.381 93.3964 207.761 94.2664 207.797 95.1836V108.826C207.615 109.648 207.179 110.391 206.551 110.951C205.923 111.51 205.135 111.858 204.299 111.945H116.332C115.526 111.89 114.767 111.542 114.198 110.969C113.628 110.395 113.286 109.634 113.235 108.826V95.1836C113.189 94.7462 113.235 94.304 113.369 93.8853C113.503 93.4665 113.723 93.0803 114.014 92.751C114.306 92.4217 114.662 92.1566 115.061 91.9725C115.46 91.7885 115.893 91.6894 116.332 91.6816H204.299ZM113.198 155.19C113.134 155.613 113.17 156.045 113.302 156.452C113.435 156.858 113.661 157.228 113.962 157.531C114.263 157.834 114.631 158.063 115.036 158.198C115.442 158.333 115.873 158.371 116.296 158.309H170.792C171.231 158.355 171.674 158.309 172.093 158.173C172.513 158.038 172.9 157.816 173.229 157.523C173.558 157.229 173.823 156.87 174.006 156.469C174.188 156.067 174.285 155.632 174.29 155.19V148.168C174.285 147.727 174.188 147.292 174.006 146.89C173.823 146.489 173.558 146.13 173.229 145.836C172.9 145.543 172.513 145.321 172.093 145.186C171.674 145.05 171.231 145.004 170.792 145.049H116.296C115.874 144.991 115.444 145.032 115.041 145.169C114.637 145.306 114.271 145.534 113.971 145.836C113.67 146.139 113.444 146.507 113.31 146.911C113.176 147.316 113.138 147.746 113.198 148.168V155.19ZM229.17 148.168C229.159 147.727 229.058 147.293 228.872 146.892C228.687 146.492 228.421 146.134 228.091 145.842C227.761 145.549 227.374 145.328 226.954 145.191C226.535 145.055 226.092 145.007 225.653 145.049H187.61C187.187 144.992 186.757 145.033 186.353 145.17C185.949 145.306 185.582 145.535 185.28 145.836C184.978 146.138 184.751 146.506 184.614 146.91C184.478 147.315 184.437 147.745 184.494 148.168V205.841C184.448 206.279 184.495 206.723 184.63 207.143C184.765 207.563 184.987 207.95 185.28 208.28C185.573 208.609 185.932 208.874 186.333 209.057C186.734 209.24 187.169 209.337 187.61 209.342H225.744C226.664 209.311 227.537 208.932 228.19 208.283C228.842 207.633 229.225 206.761 229.261 205.841L229.17 148.168Z'
|
||||
fill='#1E325C'
|
||||
/>
|
||||
<path
|
||||
d='M249.048 96.7526H217.527V65.1807L248.265 95.5853L249.048 96.7526Z'
|
||||
fill='#AFB3C0'
|
||||
/>
|
||||
<defs>
|
||||
<pattern
|
||||
id='pattern0'
|
||||
patternContentUnits='objectBoundingBox'
|
||||
width='1'
|
||||
height='1'
|
||||
>
|
||||
<use
|
||||
xlinkHref='#image0_485_13954'
|
||||
transform='scale(0.00512821 0.00621118)'
|
||||
/>
|
||||
</pattern>
|
||||
<pattern
|
||||
id='pattern1'
|
||||
patternContentUnits='objectBoundingBox'
|
||||
width='1'
|
||||
height='1'
|
||||
>
|
||||
<use
|
||||
xlinkHref='#image1_485_13954'
|
||||
transform='scale(0.00287356 0.00507614)'
|
||||
/>
|
||||
</pattern>
|
||||
<pattern
|
||||
id='pattern2'
|
||||
patternContentUnits='objectBoundingBox'
|
||||
width='1'
|
||||
height='1'
|
||||
>
|
||||
<use
|
||||
xlinkHref='#image2_485_13954'
|
||||
transform='scale(0.00628931 0.00507614)'
|
||||
/>
|
||||
</pattern>
|
||||
<pattern
|
||||
id='pattern3'
|
||||
patternContentUnits='objectBoundingBox'
|
||||
width='1'
|
||||
height='1'
|
||||
>
|
||||
<use
|
||||
xlinkHref='#image3_485_13954'
|
||||
transform='scale(0.00176056 0.00395257)'
|
||||
/>
|
||||
</pattern>
|
||||
<image
|
||||
id='image0_485_13954'
|
||||
width='195'
|
||||
height='161'
|
||||
xlinkHref='data:image/png;base64,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 truncated
|
||||
/>
|
||||
<image
|
||||
id='image1_485_13954'
|
||||
width='348'
|
||||
height='197'
|
||||
xlinkHref='data:image/png;base64,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 truncated
|
||||
/>
|
||||
<image
|
||||
id='image2_485_13954'
|
||||
width='159'
|
||||
height='197'
|
||||
xlinkHref='data:image/png;base64,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 truncated
|
||||
/>
|
||||
<image
|
||||
id='image3_485_13954'
|
||||
width='568'
|
||||
height='253'
|
||||
xlinkHref='data:image/png;base64,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 truncated
|
||||
/>
|
||||
</defs>
|
||||
</svg>
|
||||
);
|
||||
|
||||
export default NoSubscriptions;
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
.gitlab-rhs-NotSignedInDiv {
|
||||
margin: 24px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.gitlab-rhs-Welcome {
|
||||
font-family: 'Metropolis';
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
line-height: 24px;
|
||||
color: var(--center-channel-color);
|
||||
}
|
||||
|
||||
.gitlab-rhs-Hr {
|
||||
width: 244px;
|
||||
border-top: 1px solid rgba(var(--center-channel-color-rgb), 0.08);
|
||||
margin: 24px 0 0 0;
|
||||
}
|
||||
|
||||
.gitlab-rhs-MattermostGitLab {
|
||||
width: 217px;
|
||||
height: 72px;
|
||||
margin-top: 24px;
|
||||
}
|
||||
|
||||
.gitlab-rhs-ConnectPrompt {
|
||||
font-family: 'Metropolis';
|
||||
font-size: 22px;
|
||||
font-weight: 600;
|
||||
line-height: 28px;
|
||||
margin-top: 16px;
|
||||
color: var(--center-channel-color);
|
||||
}
|
||||
|
||||
.gitlab-rhs-Connect.gitlab-rhs-Connect.gitlab-rhs-Connect {
|
||||
background-color: var(--button-bg);
|
||||
color: var(--button-color);
|
||||
font-family: 'Open Sans';
|
||||
font-weight: 600;
|
||||
padding: 12px 16px 12px 16px;
|
||||
border-radius: 4px;
|
||||
margin-top: 24px;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.gitlab-rhs-Connect.gitlab-rhs-Connect.gitlab-rhs-Connect:active {
|
||||
color: var(--button-color);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.gitlab-rhs-Connect.gitlab-rhs-Connect.gitlab-rhs-Connect:visited {
|
||||
color: var(--button-color);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.gitlab-rhs-Connect.gitlab-rhs-Connect.gitlab-rhs-Connect:hover {
|
||||
color: var(--button-color);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.gitlab-rhs-UserHeaderContainer {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
justify-content: flex-start;
|
||||
align-items: center;
|
||||
background-color: rgba(var(--center-channel-color-rgb), 0.04);
|
||||
padding: 12px 20px;
|
||||
}
|
||||
|
||||
.gitlab-rhs-UserProfile {
|
||||
margin: 0 8px 0 0;
|
||||
}
|
||||
|
||||
.gitlab-rhs-UserDetails {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
align-items: left;
|
||||
font-family: 'Open Sans';
|
||||
line-height: 16px;
|
||||
text-align: left;
|
||||
color: var(--center-channel-color);
|
||||
}
|
||||
|
||||
.gitlab-rhs-Description {
|
||||
font-size: 12px;
|
||||
font-weight: 400;
|
||||
letterSpacing: 0;
|
||||
}
|
||||
|
||||
.gitlab-rhs-Username {
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
letterSpacing: 0.02em;
|
||||
}
|
||||
|
||||
.gitlab-rhs-GitLabURL {
|
||||
display: flex;
|
||||
margin-left: auto;
|
||||
padding: 10px 16px;
|
||||
gap: 10px;
|
||||
border: 1px solid var(--button-bg);
|
||||
border-radius: 4px;
|
||||
font-family: 'Open Sans';
|
||||
font-weight: 600;
|
||||
font-size: 12px;
|
||||
line-height: 10px;
|
||||
color: var(--button-bg);
|
||||
}
|
||||
|
||||
.gitlab-rhs-SubscriptionContainer {
|
||||
background-color: var(--center-channel-bg);
|
||||
padding: 14px 16px 14px 16px;
|
||||
border: 1px solid rgba(var(--center-channel-color-rgb), 0.04);
|
||||
box-shadow: 0px 2px 3px 0px rgba(0, 0, 0, 0.08);
|
||||
transition: box-shadow 0.3s ease-in-out;
|
||||
border-radius: 4px;
|
||||
margin-top: 12px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.gitlab-rhs-SubscriptionContainer:hover {
|
||||
box-shadow: 0px 4px 6px 0px rgba(0, 0, 0, 0.12);
|
||||
}
|
||||
|
||||
.gitlab-rhs-SubscriptionHeader {
|
||||
font-family: 'Open Sans';
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
line-height: 16px;
|
||||
letterSpacing: 0.02em;
|
||||
textTransform: uppercase;
|
||||
margin: 0 0 4px 0;
|
||||
color: rgba(var(--center-channel-color-rgb), 0.72);
|
||||
}
|
||||
|
||||
.gitlab-rhs-SubscriptionDetails {
|
||||
font-family: 'Open Sans';
|
||||
font-size: 14px;
|
||||
font-weight: 400;
|
||||
line-height: 20px;
|
||||
color: var(--button-bg);
|
||||
}
|
||||
|
||||
.gitlab-rhs-Features {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
flex-direction: row;
|
||||
justify-content: flex-start;
|
||||
align-content: flex-start;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.gitlab-rhs-Features span {
|
||||
font-family: 'Open Sans';
|
||||
font-weight: 600;
|
||||
font-size: 12px;
|
||||
background-color: rgba(var(--center-channel-color-rgb), 0.08);
|
||||
color: var(--center-channel-color);
|
||||
padding: 2px 5px;
|
||||
border-radius: 4px;
|
||||
line-height: 16px;
|
||||
}
|
||||
|
||||
.gitlab-rhs-Container {
|
||||
margin: 24px;
|
||||
}
|
||||
|
||||
.gitlab-rhs-NoSubscriptionsContainer {
|
||||
margin: 24px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.gitlab-rhs-NoSubscriptionsImg {
|
||||
width: 264px;
|
||||
margin: 10px 0 30px 0;
|
||||
}
|
||||
|
||||
.gitlab-rhs-NoSubscriptions {
|
||||
font-family: 'Metropolis';
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
line-height: 24px;
|
||||
text-align: center;
|
||||
color: var(--center-channel-color);
|
||||
}
|
||||
|
||||
.gitlab-rhs-UseGitLabSlashCommand {
|
||||
font-family: 'Open Sans';
|
||||
font-size: 14px;
|
||||
font-weight: 400;
|
||||
line-height: 20px;
|
||||
text-align: center;
|
||||
color: var(--center-channel-color);
|
||||
margin: 8px 0 0 0;
|
||||
}
|
||||
|
||||
.gitlab-rhs-Header {
|
||||
font-family: 'Metropolis';
|
||||
font-size: 16px;
|
||||
font-weight: 400;
|
||||
line-height: 24px;
|
||||
color: var(--center-channel-color);
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
import React from 'react';
|
||||
import PropTypes from 'prop-types';
|
||||
|
||||
import {isDesktopApp} from 'src/utils/user_agent';
|
||||
import {connectUsingBrowserMessage} from 'src/constants';
|
||||
|
||||
import MattermostGitLabSVG from './mattermost_gitlab';
|
||||
import NoSubscriptionsSVG from './no_subscriptions';
|
||||
|
||||
import './rhs_sidebar.css';
|
||||
|
||||
const NotSignedIn = (props) => {
|
||||
const openConnectWindow = (e) => {
|
||||
e.preventDefault();
|
||||
if (isDesktopApp()) {
|
||||
props.sendEphemeralPost(connectUsingBrowserMessage);
|
||||
return;
|
||||
}
|
||||
window.open(`${props.pluginServerRoute}/oauth/connect`, 'Connect Mattermost to GitLab', 'height=570,width=520');
|
||||
};
|
||||
|
||||
return (
|
||||
<div className='gitlab-rhs-NotSignedInDiv'>
|
||||
<div className='gitlab-rhs-Welcome'>{'Welcome to the Mattermost GitLab plugin'}</div>
|
||||
<hr className='gitlab-rhs-Hr'/>
|
||||
<div className='gitlab-rhs-MattermostGitLab'>
|
||||
<MattermostGitLabSVG/>
|
||||
</div>
|
||||
<div className='gitlab-rhs-ConnectPrompt'>{'Connect your account'}<br/>{'to get started'}</div>
|
||||
<a
|
||||
className='gitlab-rhs-Connect'
|
||||
href={`${props.pluginServerRoute}/oauth/connect`}
|
||||
onClick={openConnectWindow}
|
||||
>
|
||||
{'Connect account'}
|
||||
</a>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
NotSignedIn.propTypes = {
|
||||
pluginServerRoute: PropTypes.string.isRequired,
|
||||
sendEphemeralPost: PropTypes.func.isRequired,
|
||||
};
|
||||
|
||||
const UserHeader = (props) => (
|
||||
<div className='gitlab-rhs-UserHeaderContainer'>
|
||||
<img
|
||||
className='gitlab-rhs-UserProfile Avatar Avatar-lg'
|
||||
alt='user profile image'
|
||||
src={`/api/v4/users/${props.currentUserId}/image`}
|
||||
/>
|
||||
<div className='gitlab-rhs-UserDetails'>
|
||||
<div className='gitlab-rhs-Description'>{'Signed in as'}</div>
|
||||
<div className='gitlab-rhs-Username'>{props.username}</div>
|
||||
</div>
|
||||
<a
|
||||
className='gitlab-rhs-GitLabURL'
|
||||
href={props.gitlabURL}
|
||||
target='_new'
|
||||
>{'GitLab'}</a>
|
||||
</div>
|
||||
);
|
||||
|
||||
UserHeader.propTypes = {
|
||||
currentUserId: PropTypes.string.isRequired,
|
||||
username: PropTypes.string.isRequired,
|
||||
gitlabURL: PropTypes.string.isRequired,
|
||||
};
|
||||
|
||||
const Subscription = (props) => {
|
||||
return (
|
||||
<div className='gitlab-rhs-SubscriptionContainer'>
|
||||
<div>
|
||||
<h2 className='gitlab-rhs-SubscriptionHeader'>{'Repository'}</h2>
|
||||
<a
|
||||
className='gitlab-rhs-SubscriptionDetails'
|
||||
href={props.url}
|
||||
target='_new'
|
||||
>{props.name}</a>
|
||||
</div>
|
||||
<div>
|
||||
<h2 className='gitlab-rhs-SubscriptionHeader'>{'Features'}</h2>
|
||||
<div className='gitlab-rhs-Features'>
|
||||
{props.features.map((feature) => (
|
||||
<span key={feature}>{feature}</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
Subscription.propTypes = {
|
||||
url: PropTypes.string.isRequired,
|
||||
name: PropTypes.string.isRequired,
|
||||
features: PropTypes.arrayOf(PropTypes.string).isRequired,
|
||||
};
|
||||
|
||||
const Subscriptions = (props) => {
|
||||
if (props.subscriptions.length === 0) {
|
||||
return (
|
||||
<div className='gitlab-rhs-NoSubscriptionsContainer'>
|
||||
<div className='gitlab-rhs-NoSubscriptionsImg'>
|
||||
<NoSubscriptionsSVG/>
|
||||
</div>
|
||||
<div className='gitlab-rhs-NoSubscriptions'>{'There are no GitLab subscriptions available in this channel.'}</div>
|
||||
<div className='gitlab-rhs-UseGitLabSlashCommand'>{'Use the /gitlab slash command to create a subscription.'}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className='gitlab-rhs-Container'>
|
||||
<div className='gitlab-rhs-Header'>{'GitLab Subscriptions'}</div>
|
||||
{props.subscriptions.map((subscription) => (
|
||||
<Subscription
|
||||
key={subscription.repository_url + props.currentChannelId}
|
||||
name={subscription.repository_name}
|
||||
url={subscription.repository_url}
|
||||
features={subscription.features}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
Subscriptions.propTypes = {
|
||||
currentChannelId: PropTypes.string,
|
||||
subscriptions: PropTypes.arrayOf(PropTypes.shape({
|
||||
repository_name: PropTypes.string.isRequired,
|
||||
repository_url: PropTypes.string.isRequired,
|
||||
})).isRequired,
|
||||
};
|
||||
|
||||
export default class RHSSidebar extends React.PureComponent {
|
||||
static propTypes = {
|
||||
currentUserId: PropTypes.string.isRequired,
|
||||
connected: PropTypes.bool.isRequired,
|
||||
username: PropTypes.string,
|
||||
gitlabURL: PropTypes.string,
|
||||
currentChannelId: PropTypes.string,
|
||||
currentChannelSubscriptions: PropTypes.arrayOf(PropTypes.shape({
|
||||
repository_name: PropTypes.string,
|
||||
repository_url: PropTypes.string,
|
||||
features: PropTypes.arrayOf(PropTypes.string),
|
||||
})).isRequired,
|
||||
pluginServerRoute: PropTypes.string.isRequired,
|
||||
actions: PropTypes.shape({
|
||||
getChannelSubscriptions: PropTypes.func.isRequired,
|
||||
sendEphemeralPost: PropTypes.func.isRequired,
|
||||
}).isRequired,
|
||||
};
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
|
||||
this.state = {
|
||||
refreshing: false,
|
||||
};
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
if (this.props.connected) {
|
||||
this.getData();
|
||||
}
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps) {
|
||||
if ((this.props.connected && !prevProps.connected) || (this.props.currentChannelId !== prevProps.currentChannelId)) {
|
||||
this.getData();
|
||||
}
|
||||
}
|
||||
|
||||
getData = async (e) => {
|
||||
if (this.state.refreshing) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (e) {
|
||||
e.preventDefault();
|
||||
}
|
||||
|
||||
this.setState({refreshing: true});
|
||||
await this.props.actions.getChannelSubscriptions(this.props.currentChannelId);
|
||||
this.setState({refreshing: false});
|
||||
}
|
||||
|
||||
render() {
|
||||
if (!this.props.connected) {
|
||||
return (
|
||||
<NotSignedIn
|
||||
pluginServerRoute={this.props.pluginServerRoute}
|
||||
sendEphemeralPost={this.props.actions.sendEphemeralPost}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<UserHeader
|
||||
currentUserId={this.props.currentUserId}
|
||||
gitlabURL={this.props.gitlabURL}
|
||||
username={this.props.username}
|
||||
/>
|
||||
<Subscriptions
|
||||
currentChannelId={this.props.currentChannelId}
|
||||
subscriptions={this.props.currentChannelSubscriptions}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 133 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user