immobiliare / backstage-plugin-gitlab

Backstage plugins to interact with GitLab
Apache License 2.0
115 stars 39 forks source link
backstage backstage-plugin gitlab gitlab-ci hacktoberfest plugin

logo

Backstage Plugin GitLab

code style: prettier semantic-release npm (scoped) license

Backstage plugins to interact with GitLab

Table of contents

Features

Screenshots

Contributors Languages Pipeline Status Merge Request Information

Setup

  1. Install packages:
# From your Backstage root directory
yarn --cwd packages/app add @immobiliarelabs/backstage-plugin-gitlab
yarn --cwd packages/backend add @immobiliarelabs/backstage-plugin-gitlab-backend

Setup Frontend Plugin

  1. Add a new GitLab tab to the entity page.

NOTE: By default the EntityGitlabContent does not load the README, see the Optional section.

packages/app/src/components/catalog/EntityPage.tsx

// packages/app/src/components/catalog/EntityPage.tsx

import {
    isGitlabAvailable,
    EntityGitlabContent,
} from '@immobiliarelabs/backstage-plugin-gitlab';

// Farther down at the serviceEntityPage declaration
const serviceEntityPage = (
    <EntityLayout>
        {/* Place the following section where you want the tab to appear */}
        <EntityLayout.Route
            if={isGitlabAvailable}
            path="/gitlab"
            title="Gitlab"
        >
            <EntityGitlabContent />
        </EntityLayout.Route>
    </EntityLayout>
);
  1. (Optional) Add the GitLab cards to the Overview tab on the entity page.

packages/app/src/components/catalog/EntityPage.tsx

// packages/app/src/components/catalog/EntityPage.tsx

import {
    isGitlabAvailable,
    EntityGitlabContent,
    EntityGitlabLanguageCard,
    EntityGitlabMergeRequestsTable,
    EntityGitlabMergeRequestStatsCard,
    EntityGitlabPeopleCard,
    EntityGitlabPipelinesTable,
    EntityGitlabReadmeCard,
    EntityGitlabReleasesCard,
} from '@immobiliarelabs/backstage-plugin-gitlab';

//Farther down at the overviewContent declaration
//You can add only selected widgets or all of them.
const overviewContent = (
    <Grid container spacing={3} alignItems="stretch">
        <EntitySwitch>
            <EntitySwitch.Case if={isGitlabAvailable}>
                <Grid item md={12}>
                    <EntityGitlabReadmeCard />
                </Grid>
                <Grid item sm={12} md={3} lg={3}>
                    <EntityGitlabPeopleCard />
                </Grid>
                <Grid item sm={12} md={3} lg={3}>
                    <EntityGitlabLanguageCard />
                </Grid>
                <Grid item sm={12} md={3} lg={3}>
                    <EntityGitlabMergeRequestStatsCard />
                </Grid>
                <Grid item sm={12} md={3} lg={3}>
                    <EntityGitlabReleasesCard />
                </Grid>
                <Grid item md={12}>
                    <EntityGitlabPipelinesTable />
                </Grid>
                <Grid item md={12}>
                    <EntityGitlabMergeRequestsTable />
                </Grid>
            </EntitySwitch.Case>
        </EntitySwitch>
    </Grid>
);
  1. Add the integration: app-config.yaml add the integration for gitlab:
integrations:
    gitlab:
        - host: gitlab.com
          token: ${GITLAB_TOKEN}

Note: You can have more than one GitLab instance.

Setup Backend Plugin

NOTE: Currently backstage supports a new way to register backend plugins, see the Register To The New Backend System section.

  1. Add the GitLab Filler Processor, this allows auto-filling of the annotations like the project id and slug:

packages/backend/src/plugins/catalog.ts

// packages/backend/src/plugins/catalog.ts
import { GitlabFillerProcessor } from '@immobiliarelabs/backstage-plugin-gitlab-backend';

export default async function createPlugin(
    env: PluginEnvironment
): Promise<Router> {
    const builder = await CatalogBuilder.create(env);
    //...
    // Add this line
    builder.addProcessor(new GitlabFillerProcessor(env.config));
    //...
    const { processingEngine, router } = await builder.build();
    await processingEngine.start();
    return router;
}

This allows auto-filling of the annotations.

  1. Add the gitlab route by creating the file packages/backend/src/plugins/gitlab.ts:

packages/backend/src/plugins/gitlab.ts

// packages/backend/src/plugins/gitlab.ts
import { PluginEnvironment } from '../types';
import { Router } from 'express-serve-static-core';
import { createRouter } from '@immobiliarelabs/backstage-plugin-gitlab-backend';

export default async function createPlugin(
    env: PluginEnvironment
): Promise<Router> {
    return createRouter({
        logger: env.logger,
        config: env.config,
    });
}

then you have to add the route as follows:

packages/backend/src/index.ts

// packages/backend/src/index.ts
import gitlab from './plugins/gitlab';

async function main() {
    //...
    const gitlabEnv = useHotMemoize(module, () => createEnv('gitlab'));
    //...
    apiRouter.use('/gitlab', await gitlab(gitlabEnv));
    //...
}
  1. (Optional): You can also add plugin configurations in app-config.yaml file:

app-config.yaml

# app-config.yaml
# ...
gitlab:
    # Default path for CODEOWNERS file
    # Default: CODEOWNERS
    defaultCodeOwnersPath: .gitlab/CODEOWNERS
    # Default path for README file
    # Default: README.md
    defaultReadmePath: .gitlab/README.md
    # Entity Kinds to witch the plugin works, if you want to render gitlab
    # information for one Kind you have to add it in this list.
    # Default: ['Component']
    allowedKinds: ['Component', 'Resource']
    # This parameter controls SSL Certs verification
    # Default: true
    proxySecure: false
    # Activate Oauth/OIDC
    # Default: false
    useOAuth: false

Extra OIDC/OAuth

By default, this plugin utilizes the token specified in the configuration file app-config.yaml under the key: integrations.gitlab[i].token. However, you can opt out of using this token by activating OIDC as shown below:

gitlab:
    useOAuth: true

Note:: To use OIDC you have to configure the @backstage/plugin-auth-backend-module-gitlab-provider plugin. Note:: OIDC does not allow multi GitLab instances!

Register To The New Backend System

If you're already using the New Backend System, registering backend plugins will become much easier:

packages/backend/src/index.ts

// packages/backend/src/index.ts
import {
    gitlabPlugin,
    catalogPluginGitlabFillerProcessorModule,
} from '@immobiliarelabs/backstage-plugin-gitlab-backend';

async function start() {
    const backend = createBackend();

    // ...
    backend.add(gitlabPlugin);
    backend.add(catalogPluginGitlabFillerProcessorModule);

    // ...
}

Annotations

By default, the plugin automatically shows the project info corresponding to the location of the catalog.yaml file. But you could need some time to force another project, you can do it with the annotations gitlab.com/project-id or gitlab.com/project-slug:

# Example catalog-info.yaml entity definition file
apiVersion: backstage.io/v1alpha1
kind: Component
metadata:
    # ...
    annotations:
        gitlab.com/project-id: 'project-id' #1234. This must be in quotes and can be found under Settings --> General
        # or
        gitlab.com/project-slug: 'project-slug' # group_name/project_name
        # or
        gitlab.com/instance: gitlab.internal.abcd # abcd, represents local instance used
spec:
    type: service
    # ...

It's possible to disable the GitLab plugins and cards by setting these annotations to an empty string.

This is useful if the entity (catalog-info.yaml) is hosted on GitLab but the actual source code is hosted somewhere else or GitLab isn't used for issue tracking.

# Example catalog-info.yaml entity definition file
apiVersion: backstage.io/v1alpha1
kind: Component
metadata:
    # ...
    annotations:
        gitlab.com/instance: '' # don't show the issue and merge requests cards
        gitlab.com/project-slug: ''
spec:
    type: service
    # ...

Code owners file

The plugins support also the gitlab.com/codeowners-path annotation:

# Example catalog-info.yaml entity definition file
apiVersion: backstage.io/v1alpha1
kind: Component
metadata:
    # ...
    annotations:
        # You can change the CODEOWNERS path
        # if it is not passed default specified in `app-config.yaml` is used
        gitlab.com/codeowners-path: 'somewhere/CODEOWNERS'
spec:
    type: service
    # ...

Old/New GitLab Versions

If you have an old GitLab version, or a new one, we allow you to extend the GitLab Client as follows:

packages/app/src/api.ts

import { GitlabCIApiRef } from '@immobiliarelabs/backstage-plugin-gitlab';
import { CustomGitlabCIClient } from '@immobiliarelabs/backstage-plugin-gitlab';
import { discoveryApiRef, configApiRef } from '@backstage/core-plugin-api';
import { CustomGitlabCIClient } from 'packages/app/src/myCustomClient.ts';

export const apis: AnyApiFactory[] = [
    createApiFactory({
        api: GitlabCIApiRef,
        deps: { configApi: configApiRef, discoveryApi: discoveryApiRef },
        factory: ({ configApi, discoveryApi }) =>
            CustomGitlabCIClient.setupAPI({
                discoveryApi,
                codeOwnersPath: configApi.getOptionalString(
                    'gitlab.defaultCodeOwnersPath'
                ),
                readmePath: configApi.getOptionalString(
                    'gitlab.defaultReadmePath'
                ),
            }),
    }),
];

packages/app/src/myCustomClient.ts

import { GitlabCIClient } from '@immobiliarelabs/backstage-plugin-gitlab';

export class CustomGitlabCIClient extends GitlabCIClient {
    // Override methods
    async getPipelineSummary(projectID: string | undefined): Promise<PipelineSummary | undefined> {
        this.callApi(...)
        .
        .
        .
    }
}

see here.

Migration guides

If you have an old gitlab-plugin version, you can consult the migration guide.

Support & Contribute

Made with ❤️ by ImmobiliareLabs & Contributors

We'd love for you to contribute to Backstage GitLab Plugin! Here some tips on how to contribute. If you have any questions on how to use Backstage GitLab Plugin, bugs and enhancement please feel free to reach out by opening a GitHub Issue.

License

This plugin is based on the original work of loblaw-sre/backstage-plugin-gitlab by satrox28 and balasundaram

This plugin is under Apache 2.0 license, see NOTICE for copyright.