### OnInstall Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/plugin.md Called when the plugin is installed. Starts the setup wizard unless OAuth is already configured. ```APIDOC ## Method: OnInstall ### Description Called when the plugin is installed. Starts the setup wizard unless OAuth is already configured. ### Signature ```go func (p *Plugin) OnInstall(c *plugin.Context, event model.OnInstallEvent) error ``` ### Parameters - **c** (*plugin.Context) - Required - Plugin context. - **event** (model.OnInstallEvent) - Required - Installation event containing UserId. ### Returns `error` - nil on success or error from flow manager. ### Example ```go ctx := &plugin.Context{} event := model.OnInstallEvent{UserId: "user123"} if err := p.OnInstall(ctx, event); err != nil { log.Printf("Error during install: %v", err) } ``` ``` -------------------------------- ### Start GitLab Plugin Setup Wizard Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/configuration.md Initiates the setup wizard if OAuth is not yet configured. This is called automatically on plugin installation. ```go func (p *Plugin) OnInstall(c *plugin.Context, event model.OnInstallEvent) error { conf := p.getConfiguration() if conf.IsOAuthConfigured() { return nil } return p.flowManager.StartSetupWizard(event.UserId, "") } ``` -------------------------------- ### Install Plugin Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/plugin.md Called when the plugin is installed. Starts the setup wizard unless OAuth is already configured. Returns nil on success or an error from the flow manager. ```go ctx := &plugin.Context{} event := model.OnInstallEvent{UserId: "user123"} if err := p.OnInstall(ctx, event); err != nil { log.Printf("Error during install: %v", err) } ``` -------------------------------- ### ServeHTTP Example Usage Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/plugin.md Example of how to call the ServeHTTP method with necessary context and request objects. ```go p.ServeHTTP(ctx, responseWriter, request) ``` -------------------------------- ### OnConfigurationChange Example Usage Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/plugin.md Example demonstrating how to call OnConfigurationChange and log any errors that occur during configuration updates. ```go if err := p.OnConfigurationChange(); err != nil { log.Printf("Configuration update failed: %v", err) } ``` -------------------------------- ### GitLab Plugin Information Output Example Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/slash-commands.md Example output for the /gitlab about command, showing plugin name, version, build details, and commit information. ```text GitLab Plugin Version: 1.4.2 Build: abc123def456 Git Commit: abcdef123456 Built: 2024-01-15 10:30:00 UTC ``` -------------------------------- ### Subscription Validation Example Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/INDEX.md Example of validating subscription data before processing, ensuring data integrity. ```Go func (p *Plugin) validateSubscription(sub *model.Subscription) error { if sub.ChannelID == "" { return errors.New("channel ID is required") } if sub.ProjectID == 0 { return errors.New("project ID is required") } return nil } ``` -------------------------------- ### Webhook Processing Example Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/INDEX.md Illustrates the basic structure for processing incoming webhooks from GitLab. ```Go func (p *Plugin) processWebhook(c echo.Context) error { var event model.WebhookEvent if err := c.Bind(&event); err != nil { return errors.Wrap(err, "failed to decode webhook event") } // Process the event based on its type s// ... return c.NoContent(http.StatusOK) } ``` -------------------------------- ### Plugin Logging Examples Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/errors.md Provides examples of logging messages at Debug, Warn, and Error levels using the plugin's client logger. These are used for monitoring and debugging plugin behavior. ```go p.client.Log.Debug("Debug message", "field", value) p.client.Log.Warn("Warning", "field", value) p.client.Log.Error("Error", "field", value) ``` -------------------------------- ### Mattermost Cloud (gitlab.com) Configuration Example Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/configuration.md Example JSON configuration for Mattermost Cloud using gitlab.com. This setup disables private repository access and uses a pre-registered application, while other settings like OAuth client ID/secret are left blank. ```json { "gitlaburl": "https://gitlab.com", "gitlaboauthclientid": "", "gitlaboauthclientsecret": "", "webhooksecret": "auto-generated", "encryptionkey": "auto-generated", "gitlabgroup": "", "enableprivaterepo": false, "enablecodepreview": "public", "usepreregisteredapplication": true, "enablechildpipelinenotifications": true } ``` -------------------------------- ### GitLab Pipeline Run Output Example Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/slash-commands.md Example output when a pipeline is successfully triggered. It includes the pipeline ID, current status, and a direct link for monitoring. ```text Pipeline triggered for owner/repo:main - Pipeline ID: 98765 - Status: pending - View: https://gitlab.com/owner/repo/-/pipelines/98765 ``` -------------------------------- ### OAuth Connection Flow Example Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/INDEX.md Illustrates the initiation of the OAuth 2.0 connection process to authenticate with GitLab. ```Go func (p *Plugin) connectOAuth(c echo.Context) error { url, err := p.gitlab.OAuth.AuthCodeURL(p.getConfiguration().GitLabOAuthClientId) if err != nil { return errors.Wrap(err, "failed to create auth url") } return c.Redirect(http.StatusFound, url) } ``` -------------------------------- ### GitLab API Client Usage Example Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/INDEX.md Demonstrates how to use the go-gitlab library to interact with the GitLab API, specifically for retrieving user information. ```Go func (p *Plugin) checkUserConnected(userID string) (*gitlab.User, error) { token, err := p.getAPIToken(userID) if err != nil { return nil, err } client, err := gitlab.NewClient(token) if err != nil { return nil, errors.Wrap(err, "failed to create gitlab client") } user, _, err := client.Users.CurrentUser() if err != nil { return nil, errors.Wrap(err, "failed to get current user") } return user, nil } ``` -------------------------------- ### Add Subscription Command Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/subscriptions.md Example of a user command to add a new subscription, specifying the repository and desired features. ```Shell /gitlab subscriptions add myorg/myrepo merges,issues,tag ``` -------------------------------- ### Self-Hosted GitLab Configuration Example Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/configuration.md Example JSON configuration for a self-hosted GitLab instance. This includes settings for the GitLab URL, OAuth client ID and secret, webhook secret, encryption key, group, private repository access, code preview settings, pre-registered application usage, and child pipeline notifications. ```json { "gitlaburl": "https://gitlab.example.com", "gitlaboauthclientid": "your-client-id", "gitlaboauthclientsecret": "your-client-secret", "webhooksecret": "auto-generated", "encryptionkey": "auto-generated", "gitlabgroup": "mycompany", "enableprivaterepo": true, "enablecodepreview": "public", "usepreregisteredapplication": false, "enablechildpipelinenotifications": true } ``` -------------------------------- ### NewPlugin Function Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/plugin.md Use this function to create a new `Plugin` instance. It returns a pointer to a `Plugin` struct with all fields zero-initialized, ready for further setup. ```go func NewPlugin() *Plugin ``` ```go plugin := NewPlugin() ``` -------------------------------- ### Add Subscription with Label Filter Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/subscriptions.md Example of adding a subscription with a label filter, ensuring the 'merges' feature is enabled. ```bash /gitlab subscriptions add owner/repo merges,label:"bug" ``` -------------------------------- ### OnActivate Method Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/plugin.md Call this method to activate the plugin after it has been instantiated. It handles essential setup tasks like configuration initialization, API routing, and creating necessary components such as the OAuth broker and webhook handler. Ensure the site URL is configured before activation. ```go func (p *Plugin) OnActivate() error ``` ```go p := NewPlugin() if err := p.OnActivate(); err != nil { log.Fatalf("Failed to activate plugin: %v", err) } ``` -------------------------------- ### Valid Label Filtering Examples Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/subscriptions.md These examples demonstrate valid formats for filtering by labels in feature strings. They show single labels, multiple labels, and labels with spaces that should be trimmed. ```Text label:"bug" label:"feature request",label:"urgent" label: "with spaces" label: " leading/trailing spaces " ``` -------------------------------- ### Webapp Component Integration Example Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/INDEX.md A placeholder for how a webapp component might be integrated, likely involving React and TypeScript. ```TypeScript import React, { useState, useEffect } from 'react'; interface Props { // Component props } const GitLabSettings: React.FC = (props) => { // Component logic return (
{/* Component UI */}
); }; export default GitLabSettings; ``` -------------------------------- ### Error Handling Pattern Example Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/INDEX.md Shows a pattern for handling errors when interacting with GitLab API, including wrapping errors for context. ```Go func (p *Plugin) getAPIToken(userID string) (string, error) { var token string if err := p.API.KVStore.Load(store.TokenKey(userID), &token); err != nil { return "", errors.Wrap(err, "failed to load token from KV store") } if token == "" { return "", store.ErrNotFound } return token, nil } ``` -------------------------------- ### Get Plugin Configuration Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/configuration.md Retrieves the current plugin configuration. Ensures thread-safe access using a RWMutex. ```go func (p *Plugin) getConfiguration() *configuration { p.configurationLock.RLock() defer p.configurationLock.RUnlock() if p.configuration == nil { return &configuration{} } return p.configuration } ``` -------------------------------- ### Resolve Namespace and Project Path Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/gitlab-client.md Resolves a full path to a namespace and project name, used for subscription setup. Handles not found and private resource errors. ```go func (g *gitlab) ResolveNamespaceAndProject( ctx context.Context, userInfo *UserInfo, token *oauth2.Token, fullPath string, allowPrivate bool, ) (namespace string, project string, err error) ``` ```go ns, proj, err := glClient.ResolveNamespaceAndProject(ctx, user, token, "mattermost/mattermost-plugin-gitlab", true) if err == ErrNotFound { fmt.Println("Repository not found") } ``` -------------------------------- ### Delete Subscription Command Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/subscriptions.md Example of a user command to delete an existing subscription, specifying the repository. ```Shell /gitlab subscriptions delete myorg/myrepo ``` -------------------------------- ### GET /api/v1/projects Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/endpoints.md Retrieves projects accessible to the authenticated user. Requires a Mattermost User ID in the header. ```APIDOC ## GET /api/v1/projects ### Description Retrieves projects accessible to the authenticated user. ### Method GET ### Endpoint /plugins/com.github.manland.mattermost-plugin-gitlab/api/v1/projects ### Parameters #### Header Parameters - **Mattermost-User-ID** (string) - Yes - User ID from Mattermost ### Response #### Success Response (200 OK) - **Response Body**: Array of project objects ``` -------------------------------- ### Get User's GitLab To-Do List Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/gitlab-client.md Retrieves the user's GitLab todo list. Requires context, user info, and a connected GitLab API client. ```go func (g *gitlab) GetToDoList(ctx context.Context, user *UserInfo, client *internGitlab.Client) ([]*internGitlab.Todo, error) ``` -------------------------------- ### Example API Error Response (JSON) Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/errors.md Illustrates a typical JSON structure for an API error response, indicating a user is not connected to GitLab. ```json { "id": "not_connected", "message": "User is not connected to GitLab", "status_code": 400 } ``` -------------------------------- ### Initiate GitLab OAuth Connection Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/endpoints.md Use this endpoint to start the OAuth connection flow with GitLab. It requires the Mattermost User ID in the header and redirects the user to GitLab's authorization page. Ensure the Mattermost-User-ID header is correctly set. ```bash curl -i -X GET http://mattermost.example.com/plugins/com.github.manland.mattermost-plugin-gitlab/oauth/connect \ -H "Mattermost-User-ID: user123" ``` -------------------------------- ### Get User Details (Go) Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/gitlab-client.md Retrieves detailed user information from the GitLab API. Requires context, user info, and an OAuth2 token. ```go func (g *gitlab) GetUserDetails(ctx context.Context, user *UserInfo, token *oauth2.Token) (*internGitlab.User, error) ``` -------------------------------- ### Get User's GitLab Todo List Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/slash-commands.md Use this command to retrieve and display your GitLab todo list within Mattermost. It shows assigned merge requests, issues, and items awaiting review. ```bash /gitlab todo ``` -------------------------------- ### Build Server Component Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/README.md Build the server component of the plugin using Go. Ensure you are in the plugin's root directory. ```bash go build ./server ``` -------------------------------- ### Build Both Components with Makefile Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/README.md Build both the server and webapp components simultaneously using the provided Makefile. ```bash make dist ``` -------------------------------- ### Invalid Label Filtering Examples Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/subscriptions.md These examples illustrate invalid formats for label filtering. They include unquoted labels and missing the required 'features' context. ```Text label:bug // unquoted label:"name1",label:"name2" // missing "features" requirement ``` -------------------------------- ### Private GET Request Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/webapp-client.md Internal method for performing GET requests. Automatically includes timezone offset and Mattermost authentication headers. Throws ClientError on non-200 responses. ```typescript private async doGet(url: string, headers?: {[x: string]: string}): Promise ``` -------------------------------- ### Build Webapp Component Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/README.md Build the webapp component of the plugin using npm. Navigate to the webapp directory first. ```bash cd webapp && npm run build ``` -------------------------------- ### Get Milestones Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/endpoints.md Retrieves a list of milestones for a specified GitLab project. Requires user authentication. ```APIDOC ## GET /api/v1/milestones ### Description Retrieves milestones for a specific project. ### Method GET ### Endpoint `/plugins/com.github.manland.mattermost-plugin-gitlab/api/v1/milestones` ### Parameters #### Query Parameters - **projectID** (number) - Required - GitLab project ID ### Response #### Success Response (200) Array of milestone objects ``` -------------------------------- ### Run Server Tests Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/README.md Execute all server-side tests for the plugin using the Go testing framework. ```bash go test ./... ``` -------------------------------- ### New Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/gitlab-client.md Creates a new GitLab client instance with optional configuration for URL, group, and project validation. ```APIDOC ## Function: New ```go func New(gitlabURL string, gitlabGroup string, checkGroup func(projectNameWithGroup string) error) Gitlab ``` Creates a new GitLab client instance. ### Parameters - **gitlabURL** (string) - Optional - Base URL of GitLab instance. Defaults to "https://gitlab.com". - **gitlabGroup** (string) - Optional - Optional group name to restrict access to single group. - **checkGroup** (func(string) error) - Required - Callback to validate if project is allowed. ### Returns - `Gitlab` - A new GitLab client interface implementation. ### Example ```go client := New("https://gitlab.com", "", func(project string) error { return nil // Allow all projects }) ``` ``` -------------------------------- ### Run Webapp Tests Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/README.md Execute all webapp tests for the plugin using npm. Navigate to the webapp directory first. ```bash cd webapp && npm test ``` -------------------------------- ### Load Plugin Configuration Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/configuration.md Loads the plugin configuration at activation and on changes. Ensures the configuration is sanitized before being applied. ```go func (p *Plugin) OnConfigurationChange() error { configuration := new(configuration) if err := p.client.Configuration.LoadPluginConfiguration(configuration); err != nil { return errors.Wrap(err, "failed to load plugin configuration") } configuration.sanitize() p.setConfiguration(configuration, serverConfiguration) return nil } ``` -------------------------------- ### Display Help for GitLab Slash Commands Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/slash-commands.md Use this command to view all available subcommands and their usage instructions for the GitLab plugin. ```bash /gitlab help ``` -------------------------------- ### GET /api/v1/labels Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/endpoints.md Retrieves labels for a specific project. Requires a Mattermost User ID in the header and a projectID query parameter. ```APIDOC ## GET /api/v1/labels ### Description Retrieves labels for a specific project. ### Method GET ### Endpoint /plugins/com.github.manland.mattermost-plugin-gitlab/api/v1/labels ### Parameters #### Query Parameters - **projectID** (number) - Yes - GitLab project ID #### Header Parameters - **Mattermost-User-ID** (string) - Yes - User ID from Mattermost ### Response #### Success Response (200 OK) - **Response Body**: Array of label objects ``` -------------------------------- ### Get Channel Subscriptions Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/webapp-client.md Retrieves all GitLab subscriptions configured for a Mattermost channel. Requires the Mattermost channel ID as input. ```typescript const subscriptions = await client.getChannelSubscriptions("channel123"); subscriptions.forEach(sub => { console.log(`Subscribed to ${sub.repository_name}: ${sub.features.join(', ')}`); }); ``` -------------------------------- ### NewPlugin Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/plugin.md Creates and returns a new Plugin instance. This function initializes a Plugin object with zero-valued fields, ready for further configuration and activation. ```APIDOC ## Function: NewPlugin ```go func NewPlugin() *Plugin ``` ### Description Creates and returns a new Plugin instance with zero-initialized fields. ### Parameters There are no parameters for this function. ### Returns - `*Plugin` — A new Plugin instance ready for initialization. ### Example ```go plugin := NewPlugin() ``` ``` -------------------------------- ### GET /api/v1/assignees Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/endpoints.md Retrieves members who can be assigned to issues in a project. Requires a Mattermost User ID in the header and a projectID query parameter. ```APIDOC ## GET /api/v1/assignees ### Description Retrieves members who can be assigned to issues in a project. ### Method GET ### Endpoint /plugins/com.github.manland.mattermost-plugin-gitlab/api/v1/assignees ### Parameters #### Query Parameters - **projectID** (number) - Yes - GitLab project ID #### Header Parameters - **Mattermost-User-ID** (string) - Yes - User ID from Mattermost ### Response #### Success Response (200 OK) - **Response Body**: Array of assignee (user) objects ``` -------------------------------- ### GET /api/v1/connected Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/endpoints.md Checks if a user is connected to GitLab and retrieves their connected status and settings. It can optionally trigger a daily reminder check. ```APIDOC ## GET /api/v1/connected ### Description Checks if user is connected to GitLab and retrieves their connected status and settings. ### Method GET ### Endpoint /plugins/com.github.manland.mattermost-plugin-gitlab/api/v1/connected ### Parameters #### Query Parameters - **reminder** (boolean) - Optional - If true, triggers daily reminder check #### Header Parameters - **Mattermost-User-ID** (string) - Yes - User ID from Mattermost ### Response #### Success Response (200 OK) - **gitlab_url** (string) - **connected** (boolean) - **organization** (string) - **gitlab_username** (string) - **settings** (object) - **sidebar_buttons** (string) - **daily_reminder** (boolean) - **notifications** (boolean) - **gitlab_client_id** (string) ### Request Example ```bash curl -X GET "http://mattermost.example.com/plugins/com.github.manland.mattermost-plugin-gitlab/api/v1/connected?reminder=true" \ -H "Mattermost-User-ID: user123" ``` ``` -------------------------------- ### OnActivate Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/plugin.md Called when the plugin is activated. This method handles the initialization of the plugin's core components, including configuration, API routes, OAuth, bot user, webhook handler, and the GitLab client. ```APIDOC ## Method: OnActivate ```go func (p *Plugin) OnActivate() error ``` ### Description Called when the plugin is activated. Initializes configuration, API routes, OAuth broker, bot user, webhook handler, and flow manager. Sets up the GitLab client. ### Parameters This method operates on a receiver `p *Plugin` and does not accept additional parameters. ### Returns - `error` — nil on success; returns an error if configuration is invalid, the site URL is not set, bot creation fails, or flow manager creation fails. ### Throws - Error if `siteURL` is not configured - Error if default configuration cannot be set - Error if bot user creation fails - Error if flow manager creation fails ### Example ```go p := NewPlugin() if err := p.OnActivate(); err != nil { log.Fatalf("Failed to activate plugin: %v", err) } ``` ``` -------------------------------- ### Display GitLab Plugin Information Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/slash-commands.md Displays build and version details for the GitLab plugin. This command is useful for verifying the plugin's current version and build status. ```bash /gitlab about ``` -------------------------------- ### Get LHS Dashboard Data Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/endpoints.md Retrieves data for the left-hand sidebar, including assigned PRs, reviews, and todos. No request parameters are needed. ```typescript { reviews: Item[]; yourAssignedPrs: Item[]; yourAssignedIssues: Item[]; todos: Item[]; } ``` -------------------------------- ### Create New GitLab Client Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/gitlab-client.md Use this function to create a new GitLab client instance. It requires the GitLab URL and a callback function to validate projects within a group. ```go func New(gitlabURL string, gitlabGroup string, checkGroup func(projectNameWithGroup string) error) Gitlab ``` ```go client := New("https://gitlab.com", "", func(project string) error { return nil // Allow all projects }) ``` -------------------------------- ### Create and Validate New Subscription Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/subscriptions.md Creates and validates a new subscription instance. Ensure all feature names are valid and label-based features include 'merges' or 'issues'. Labels must be quoted. ```go func New(channelID, creatorID, features, repository string) (*Subscription, error) ``` ```go sub, err := subscription.New("channel123", "user456", "merges,issues,tag", "myorg/myrepo") if err != nil { log.Fatalf("Invalid subscription: %v", err) } ``` -------------------------------- ### Get Project Assignees Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/webapp-client.md Retrieves users who can be assigned to issues within a specific GitLab project. Use this to populate assignee dropdowns or lists. ```typescript const assignees = await client.getAssignees(123); assignees.forEach(user => { console.log(`Assignee: ${user.username}`); }); ``` -------------------------------- ### Get Project Milestones Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/webapp-client.md Retrieves all milestones for a given GitLab project ID. Use this method to fetch milestone data for display or processing. ```typescript const milestones = await client.getMilestones(123); milestones.forEach(milestone => { console.log(`Milestone: ${milestone.title}`); }); ``` -------------------------------- ### Use GitLab Client for API Operations Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/README.md Demonstrates the usage of the GitLab client to perform operations like creating an issue. It includes fetching user info and handling potential errors during the API call. ```go info, err := p.getGitlabUserInfoByMattermostID(userID) if err != nil { return err } if cErr := p.useGitlabClient(info, func(info *gitlab.UserInfo, token *oauth2.Token) error { issue, err := p.GitlabClient.CreateIssue(ctx, info, issueReq, token) return err }); cErr != nil { return cErr } ``` -------------------------------- ### Get Connected User Data Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/webapp-client.md Retrieves the current user's GitLab connection status and settings. Optionally triggers a daily reminder notification. ```typescript const connected = await client.getConnected(true); if (connected.connected) { console.log(`Connected as ${connected.gitlab_username}`); } ``` -------------------------------- ### Supported Features Table Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/subscriptions.md This table lists the features supported by GitLab subscriptions, their descriptions, and the related webhook events. It also includes an example of filtering by label. ```Markdown | Feature | | Description | | Related Webhook Events | |---|---|---| | issues | Open and closed issues | issues_events | | confidential_issues | Private/confidential issues | confidential_issues_events | | merges | Merge requests | merge_request_events | | pushes | Code pushes | push_events | | issue_comments | Comments on issues | note_events (issue scope) | | merge_request_comments | Comments on merge requests | note_events (MR scope) | | merge_request_assigns | MR assignment changes | merge_request_events | | pipeline | Pipeline runs | pipeline_events | | tag | Tag creation | tag_push_events | | pull_reviews | MR reviews and approvals | merge_request_events | | jobs | Job/build completion | job_events | | deployments | Deployment events | deployment_events | | releases | Release creation | release_events | | label:"name" | Filter by label | Filters issues or merges | ``` -------------------------------- ### Connect to GitLab with OAuth Token Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/gitlab-client.md Establishes a connection to GitLab using an OAuth token. This method returns a go-gitlab client instance for interacting with the GitLab API. ```go func (g *gitlab) GitlabConnect(token oauth2.Token) (*internGitlab.Client, error) ``` ```go client, err := glClient.GitlabConnect(token) if err != nil { log.Fatal(err) } ``` -------------------------------- ### GitlabConnect Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/gitlab-client.md Establishes a connection to GitLab using an OAuth token and returns a go-gitlab client. ```APIDOC ## Method: GitlabConnect ```go func (g *gitlab) GitlabConnect(token oauth2.Token) (*internGitlab.Client, error) ``` Establishes a connection to GitLab using an OAuth token and returns a go-gitlab client. ### Parameters - **token** (oauth2.Token) - Required - OAuth2 access token. ### Returns - `(*internGitlab.Client, error)` - GitLab API client or error. ### Example ```go client, err := glClient.GitlabConnect(token) if err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### NewProjectHook Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/gitlab-client.md Creates a webhook for a GitLab project. Requires context, user info, OAuth token, project ID, and webhook options. ```APIDOC ## Method: NewProjectHook ### Description Creates a webhook for a GitLab project. ### Method Signature ```go func (g *gitlab) NewProjectHook(ctx context.Context, user *UserInfo, token *oauth2.Token, projectID any, webhookOptions *AddWebhookOptions) (*WebhookInfo, error) ``` ### Parameters #### Path Parameters - **ctx** (context.Context) - Required - Context for cancellation and timeout - **user** (*UserInfo) - Required - User creating webhook - **token** (*oauth2.Token) - Required - OAuth2 token - **projectID** (any) - Required - Project ID (int or string) - **webhookOptions** (*AddWebhookOptions) - Required - Webhook configuration ### Returns - **WebhookInfo** - Information about the created webhook. - **error** - An error if the webhook creation fails. ``` -------------------------------- ### GET /api/v1/channel/{channel_id}/subscriptions Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/endpoints.md Retrieves GitLab subscriptions for a specific Mattermost channel. This endpoint returns a list of repositories and the features subscribed to for a given channel. ```APIDOC ## GET /api/v1/channel/{channel_id}/subscriptions ### Description Retrieves GitLab subscriptions for a specific Mattermost channel. This endpoint returns a list of repositories and the features subscribed to for a given channel. ### Method GET ### Endpoint /plugins/com.github.manland.mattermost-plugin-gitlab/api/v1/channel/{channel_id}/subscriptions ### Parameters #### Path Parameters - **channel_id** (string) - Required - Mattermost channel ID ### Response #### Success Response (200 OK) - **(array)** - Array of subscription objects - **repository_url** (string) - URL of the repository - **repository_name** (string) - Name of the repository - **features** (array) - List of subscribed features - **creator_id** (string) - ID of the user who created the subscription ### Response Example [ { "repository_url": "https://gitlab.com/user/repo", "repository_name": "user/repo", "features": ["issues", "merge_requests"], "creator_id": "user123" } ] ``` -------------------------------- ### Get GitLab User Information Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/webapp-client.md Retrieves a Mattermost user's GitLab username and the last attempted connection time. Requires the Mattermost user ID. ```typescript const userData = await client.getGitlabUser("user123"); console.log(`GitLab user: ${userData.username}, Last try: ${userData.last_try}`); ``` -------------------------------- ### Create Shallow Copy of Configuration in Go Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/configuration.md Helper method to create a shallow copy of the configuration struct. This is useful for thread-safe updates to the configuration. ```go func (c *configuration) Clone() *configuration { clone := *c return &clone } ``` -------------------------------- ### Get LHS Dashboard Data Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/endpoints.md Retrieves dashboard data for the left-hand sidebar, including assigned pull requests, reviews, assigned issues, and todos. Requires user authentication. ```APIDOC ## GET /api/v1/lhs-data ### Description Retrieves dashboard data for left-hand sidebar (assigned PRs, reviews, assigned issues, todos). ### Method GET ### Endpoint `/plugins/com.github.manland.mattermost-plugin-gitlab/api/v1/lhs-data` ### Response #### Success Response (200) ```typescript { reviews: Item[]; yourAssignedPrs: Item[]; yourAssignedIssues: Item[]; todos: Item[]; } ``` ``` -------------------------------- ### Get LHS Dashboard Data Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/webapp-client.md Retrieves dashboard data for the left sidebar, including assigned PRs, reviews, assigned issues, and todos. Handles potential API errors. ```typescript try { const lhsData = await client.getLHSData(); console.log(`Reviews pending: ${lhsData.reviews.length}`); } catch (err) { console.error(err); } ``` -------------------------------- ### Retrieve User's GitLab Todo List Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/endpoints.md This endpoint retrieves the user's GitLab todo list and posts it in Mattermost. Authentication is required. ```typescript { message: string; } ``` -------------------------------- ### Thread-Safe Configuration Access in Go Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/README.md Access plugin configuration in a thread-safe manner using RLock and RUnlock to prevent race conditions. Ensure the configuration is read-only during access. ```go func (p *Plugin) getConfiguration() *configuration { p.configurationLock.RLock() defer p.configurationLock.RUnlock() return p.configuration } ``` -------------------------------- ### Get Current GitLab User Information Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/gitlab-client.md Retrieves the current authenticated user's information from GitLab using the provided context, Mattermost user ID, and OAuth token. Handles potential errors during the retrieval process. ```go func (g *gitlab) GetCurrentUser(ctx context.Context, userID string, token oauth2.Token) (*UserInfo, error) ``` ```go userInfo, err := glClient.GetCurrentUser(ctx, "mm_user_123", token) if err != nil { return err } fmt.Println(userInfo.GitlabUsername) ``` -------------------------------- ### GetProjectHooks Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/gitlab-client.md Lists all webhooks configured for a project. Requires user authentication and project details. ```APIDOC ## GetProjectHooks ### Description Lists all webhooks configured for a project. ### Method Signature func (g *gitlab) GetProjectHooks(ctx context.Context, user *UserInfo, token *oauth2.Token, owner string, repo string) ([]*WebhookInfo, error) ### Parameters #### Path Parameters - **ctx** (context.Context) - Required - Context for cancellation and timeout - **user** (*UserInfo) - Required - User listing webhooks - **token** (*oauth2.Token) - Required - OAuth2 token - **owner** (string) - Required - Project owner/namespace - **repo** (string) - Required - Project name ### Returns - **([]*WebhookInfo, error)** - List of webhooks or error. ``` -------------------------------- ### Convert Configuration to Map in Go Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/configuration.md Method to convert the configuration struct into a map[string]any. This is typically used for storing configuration data or for API responses. ```go func (c *configuration) ToMap() (map[string]any, error) ``` -------------------------------- ### CreateIssue Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/gitlab-client.md Creates a new GitLab issue with the specified details, using the provided context, user info, and OAuth2 token. ```APIDOC ## Method: CreateIssue ### Description Creates a new GitLab issue. ### Parameters #### Path Parameters - ctx (context.Context) - Required - Context for cancellation and timeout - user (*UserInfo) - Required - User creating the issue - issue (*IssueRequest) - Required - Issue details (see Types section) - token (*oauth2.Token) - Required - OAuth2 token ### Returns - (*internGitlab.Issue, error) - Created issue or error. ### Request Example ```go issue, err := glClient.CreateIssue(ctx, userInfo, &IssueRequest{ ProjectID: 123, Title: "Bug: Login fails", Description: "Users cannot log in", Labels: internGitlab.LabelOptions{Labels: &[]string{"bug"}}, }, token) ``` ``` -------------------------------- ### OnConfigurationChange Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/plugin.md Called when plugin configuration changes. Loads, validates configuration, handles encryption key rotation, registers slash commands, and initializes the GitLab client. ```APIDOC ## OnConfigurationChange ### Description Called when plugin configuration changes. Loads configuration, validates it, handles encryption key rotation, registers slash commands, and initializes the GitLab client. ### Method OnConfigurationChange ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go if err := p.OnConfigurationChange(); err != nil { log.Printf("Configuration update failed: %v", err) } ``` ### Response #### Success Response (nil) Returns nil on successful configuration change. #### Response Example None explicitly defined. ### Error Handling - Error if plugin configuration fails to load - Error if slash command registration fails ``` -------------------------------- ### Go Struct for Plugin Configuration Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/types.md Defines the structure for storing GitLab plugin settings loaded from Mattermost server configuration. Includes fields for GitLab URL, OAuth credentials, webhook secrets, encryption keys, and feature flags. ```Go type configuration struct { GitlabURL string `json:"gitlaburl"` GitlabOAuthClientID string `json:"gitlaboauthclientid"` GitlabOAuthClientSecret string `json:"gitlaboauthclientsecret"` DefaultInstanceName string `json:"defaultinstancename"` 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"` PreviousEncryptionKey string `json:"-"` } ``` -------------------------------- ### List Channel GitLab Subscriptions Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/slash-commands.md View all current GitLab repository subscriptions for the channel where the command is executed. Displays repository path, enabled features, and the subscription creator. ```bash /gitlab subscriptions list ``` -------------------------------- ### List GitLab Webhooks Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/slash-commands.md Use this command to view all webhooks configured for a specific repository or group. It displays webhook details like ID, URL, enabled events, SSL verification status, and creation timestamp. ```bash /gitlab webhook list owner/repo /gitlab webhook list groupname ``` -------------------------------- ### Create GitLab Issue (Go) Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/gitlab-client.md Creates a new GitLab issue using the provided context, user information, issue details, and OAuth2 token. The issue details include project ID, title, description, and labels. ```go func (g *gitlab) CreateIssue(ctx context.Context, user *UserInfo, issue *IssueRequest, token *oauth2.Token) (*internGitlab.Issue, error) ``` ```go issue, err := glClient.CreateIssue(ctx, userInfo, &IssueRequest{ ProjectID: 123, Title: "Bug: Login fails", Description: "Users cannot log in", Labels: internGitlab.LabelOptions{Labels: &[]string{"bug"}}, }, token) ``` -------------------------------- ### createIssue Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/webapp-client.md Creates a new GitLab issue with details from Mattermost context. ```APIDOC ## createIssue ### Description Creates a new GitLab issue with details from Mattermost context. ### Method ```typescript createIssue(payload: IssueBody): Promise ``` ### Parameters #### Path Parameters - **payload** (IssueBody) - Required - Issue creation parameters (see Types) ### Returns `Promise` — Created issue response or error message. ### Request Example ```typescript const response = await client.createIssue({ title: "Bug: Feature X broken", description: "Description from Mattermost", project_id: 123, labels: ["bug", "urgent"], assignees: [456], post_id: "post123", channel_id: "channel123" }); ``` ``` -------------------------------- ### Define AddWebhookOptions Type Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/types.md Defines the structure for configuring GitLab webhook options. Use this to specify which events should trigger the webhook and other settings like the URL and token. ```Go 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 DeploymentEvents bool ReleaseEvents bool EnableSSLVerification bool Token string } ``` -------------------------------- ### OnConfigurationChange Method Signature Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/plugin.md The OnConfigurationChange method is called when plugin configuration is updated. It handles loading, validation, encryption key rotation, slash command registration, and GitLab client initialization. It returns an error if any of these operations fail. ```go func (p *Plugin) OnConfigurationChange() error ``` -------------------------------- ### Identify SaaS GitLab Instance in Go Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/configuration.md Helper method to check if the configured GitLab URL points to the official gitlab.com (Software-as-a-Service). Returns true for gitlab.com and false for self-hosted instances. ```go func (c *configuration) IsSASS() bool { return c.GitlabURL == "https://gitlab.com" } ``` -------------------------------- ### Validate Configuration Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/configuration.md Validates the plugin configuration based on several rules, including URL validity, required OAuth credentials, and correct usage of pre-registered applications. ```go 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 } ``` -------------------------------- ### ServeHTTP Method Signature Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/_autodocs/api-reference/plugin.md The ServeHTTP method routes HTTP requests to the appropriate handler and sets the Content-Type to application/json. It requires plugin context, a response writer, and an HTTP request. ```go func (p *Plugin) ServeHTTP(c *plugin.Context, w http.ResponseWriter, r *http.Request) ``` -------------------------------- ### Trigger Minor Release Candidate (RC) Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/README.md Execute this command to create a minor release candidate. This allows for testing of new features or improvements in a pre-release environment. ```bash make minor-rc ``` -------------------------------- ### Trigger Patch Release Candidate (RC) Source: https://github.com/mattermost/mattermost-plugin-gitlab/blob/master/README.md Run this command to create a patch release candidate. This is useful for testing upcoming patch releases before a stable release. ```bash make patch-rc ```