Merge branch 'backstage:master' into marley/7641-export-ado-types

This commit is contained in:
Marley
2021-10-19 10:19:42 +02:00
committed by GitHub
110 changed files with 4237 additions and 828 deletions
+3
View File
@@ -0,0 +1,3 @@
module.exports = {
extends: [require.resolve('@backstage/cli/config/eslint.backend')],
};
+49
View File
@@ -0,0 +1,49 @@
# Bazaar Backend
Welcome to the Bazaar backend plugin!
# Installation
## Install the package
```bash
# From your Backstage root directory
cd packages/backend
yarn add @backstage/plugin-bazaar-backend
```
## Adding the plugin to your `packages/backend`
You'll need to add the plugin to the router in your `backend` package. You can do this by creating a file called `packages/backend/src/plugins/bazaar.ts`
```tsx
import { PluginEnvironment } from '../types';
import { createRouter } from '@backstage/plugin-bazaar-backend';
export default async function createPlugin({
logger,
database,
config,
}: PluginEnvironment) {
return await createRouter({ logger, config, database });
}
```
With the `bazaar.ts` router setup in place, add the router to `packages/backend/src/index.ts`:
```diff
+ import bazaar from './plugins/bazaar';
async function main() {
...
const createEnv = makeCreateEnv(config);
const catalogEnv = useHotMemoize(module, () => createEnv('catalog'));
+ const bazaarEnv = useHotMemoize(module, () => createEnv('bazaar'));
const apiRouter = Router();
+ apiRouter.use('/bazaar', await bazaar(bazaarEnv));
...
apiRouter.use(notFoundHandler());
```
+29
View File
@@ -0,0 +1,29 @@
## API Report File for "@backstage/plugin-bazaar-backend"
> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).
```ts
import { Config } from '@backstage/config';
import express from 'express';
import { Logger as Logger_2 } from 'winston';
import { PluginDatabaseManager } from '@backstage/backend-common';
// Warning: (ae-missing-release-tag) "createRouter" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal)
//
// @public (undocumented)
export function createRouter(options: RouterOptions): Promise<express.Router>;
// Warning: (ae-missing-release-tag) "RouterOptions" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal)
//
// @public (undocumented)
export interface RouterOptions {
// (undocumented)
config: Config;
// (undocumented)
database: PluginDatabaseManager;
// (undocumented)
logger: Logger_2;
}
// (No @packageDocumentation comment for this package)
```
@@ -0,0 +1,65 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
exports.up = async function up(knex) {
await knex.schema.createTable('metadata', table => {
table.comment('The table of Bazaar metadata');
table
.text('entity_ref')
.notNullable()
.unique()
.comment('The ref of the entity');
table.text('name').notNullable().comment('The name of the entity');
table
.text('community')
.comment('Link to where the community can discuss ideas');
table
.text('announcement')
.notNullable()
.comment('The announcement of the Bazaar project');
table
.text('status')
.defaultTo('proposed')
.notNullable()
.comment('The status of the Bazaar project');
table
.text('updated_at')
.notNullable()
.comment('Timestamp on ISO 8601 format when entity was last updated');
});
await knex.schema.createTable('members', table => {
table.comment('The table of Bazaar members');
table
.text('entity_ref')
.notNullable()
.references('metadata.entity_ref')
.onDelete('CASCADE')
.comment('The ref of the entity');
table.text('user_id').notNullable().comment('The user id of the member');
table
.dateTime('join_date')
.defaultTo(knex.fn.now())
.notNullable()
.comment('The timestamp when this member joined');
table.text('picture').comment('Link to profile picture');
});
};
exports.down = async function down(knex) {
await knex.schema.dropTable('metadata');
await knex.schema.dropTable('members');
};
+40
View File
@@ -0,0 +1,40 @@
{
"name": "@backstage/plugin-bazaar-backend",
"version": "0.1.1",
"main": "src/index.ts",
"types": "src/index.ts",
"license": "Apache-2.0",
"private": false,
"publishConfig": {
"access": "public",
"main": "dist/index.cjs.js",
"types": "dist/index.d.ts"
},
"scripts": {
"start": "backstage-cli backend:dev",
"build": "backstage-cli backend:build",
"lint": "backstage-cli lint",
"test": "backstage-cli test",
"prepack": "backstage-cli prepack",
"postpack": "backstage-cli postpack",
"clean": "backstage-cli clean"
},
"dependencies": {
"@backstage/backend-common": "^0.9.2",
"@backstage/backend-test-utils": "^0.1.7",
"@backstage/config": "^0.1.5",
"@types/express": "^4.17.6",
"express": "^4.17.1",
"express-promise-router": "^4.1.0",
"knex": "^0.95.1",
"winston": "^3.2.1",
"yn": "^4.0.0"
},
"devDependencies": {
"@backstage/cli": "^0.7.6"
},
"files": [
"dist",
"migrations/**/*.{js,d.ts}"
]
}
@@ -14,4 +14,4 @@
* limitations under the License.
*/
export { default } from './WelcomePage';
export * from './service/router';
@@ -14,27 +14,20 @@
* limitations under the License.
*/
import {
createPlugin,
createRoutableExtension,
createRouteRef,
} from '@backstage/core-plugin-api';
import { getRootLogger } from '@backstage/backend-common';
import yn from 'yn';
import { startStandaloneServer } from './service/standaloneServer';
export const rootRouteRef = createRouteRef({
title: 'Welcome',
const port = process.env.PLUGIN_PORT ? Number(process.env.PLUGIN_PORT) : 7000;
const enableCors = yn(process.env.PLUGIN_CORS, { default: false });
const logger = getRootLogger();
startStandaloneServer({ port, enableCors, logger }).catch(err => {
logger.error(err);
process.exit(1);
});
export const welcomePlugin = createPlugin({
id: 'welcome',
register({ featureFlags }) {
featureFlags.register('enable-welcome-box');
},
process.on('SIGINT', () => {
logger.info('CTRL+C pressed; exiting.');
process.exit(0);
});
export const WelcomePage = welcomePlugin.provide(
createRoutableExtension({
name: 'WelcomePage',
component: () => import('./components/WelcomePage').then(m => m.default),
mountPoint: rootRouteRef,
}),
);
@@ -0,0 +1,51 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
import { DatabaseHandler } from './DatabaseHandler';
import { TestDatabaseId, TestDatabases } from '@backstage/backend-test-utils';
const bazaarProject: any = {
name: 'name',
entityRef: 'ref',
community: '',
status: 'proposed',
announcement: 'a',
membersCount: 0,
};
describe('DatabaseHandler', () => {
const databases = TestDatabases.create({
ids: ['POSTGRES_13'],
});
async function createDatabaseHandler(databaseId: TestDatabaseId) {
const knex = await databases.init(databaseId);
return await DatabaseHandler.create({ database: knex });
}
it.each(databases.eachSupportedId())(
'should do a full sync with the locations on connect, %p',
async databaseId => {
const db = await createDatabaseHandler(databaseId);
await db.insertMetadata(bazaarProject);
const entities = await db.getEntities();
expect(entities.length).toEqual(1);
expect(entities[0].entity_ref).toEqual(bazaarProject.entityRef);
},
60_000,
);
});
@@ -0,0 +1,145 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
import { resolvePackagePath } from '@backstage/backend-common';
import { Knex } from 'knex';
const migrationsDir = resolvePackagePath(
'@backstage/plugin-bazaar-backend',
'migrations',
);
type Options = {
database: Knex;
};
export class DatabaseHandler {
static async create(options: Options): Promise<DatabaseHandler> {
const { database } = options;
await database.migrate.latest({
directory: migrationsDir,
});
return new DatabaseHandler(options);
}
private readonly database: Knex;
private constructor(options: Options) {
this.database = options.database;
}
async getMembers(entityRef: string) {
return await this.database
.select('*')
.from('members')
.where({ entity_ref: entityRef });
}
async addMember(userId: string, entityRef: string, picture?: string) {
await this.database
.insert({
entity_ref: entityRef,
user_id: userId,
picture: picture,
})
.into('members');
}
async deleteMember(userId: string, entityRef: string) {
return await this.database('members')
.where({ entity_ref: decodeURIComponent(entityRef) })
.andWhere('user_id', userId)
.del();
}
async getMetadata(entityRef: string) {
const coalesce = this.database.raw(
'coalesce(count(members.entity_ref), 0) as members_count',
);
const columns = [
'members.entity_ref',
'metadata.entity_ref',
'metadata.name',
'metadata.announcement',
'metadata.status',
'metadata.updated_at',
'metadata.community',
];
return await this.database('metadata')
.select([...columns, coalesce])
.where({ 'metadata.entity_ref': entityRef })
.groupBy(columns)
.leftJoin('members', 'metadata.entity_ref', '=', 'members.entity_ref');
}
async insertMetadata(bazaarProject: any) {
const { name, entityRef, community, announcement, status } = bazaarProject;
await this.database
.insert({
name: name,
entity_ref: entityRef,
community: community,
announcement: announcement,
status: status,
updated_at: new Date().toISOString(),
})
.into('metadata');
}
async updateMetadata(bazaarProject: any) {
const { entityRef, community, announcement, status } = bazaarProject;
return await this.database('metadata')
.where({ entity_ref: entityRef })
.update({
announcement: announcement,
community: community,
status: status,
updated_at: new Date().toISOString(),
});
}
async deleteMetadata(entityRef: string) {
return await this.database('metadata')
.where({ entity_ref: entityRef })
.del();
}
async getEntities() {
const coalesce = this.database.raw(
'coalesce(count(members.entity_ref), 0) as members_count',
);
const columns = [
'members.entity_ref',
'metadata.entity_ref',
'metadata.name',
'metadata.announcement',
'metadata.status',
'metadata.updated_at',
'metadata.community',
];
return await this.database('metadata')
.select([...columns, coalesce])
.groupBy(columns)
.leftJoin('members', 'metadata.entity_ref', '=', 'members.entity_ref');
}
}
@@ -0,0 +1,113 @@
/*
* Copyright 2020 The Backstage Authors
*
* 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.
*/
import { errorHandler, PluginDatabaseManager } from '@backstage/backend-common';
import express from 'express';
import Router from 'express-promise-router';
import { Logger } from 'winston';
import { Config } from '@backstage/config';
import { DatabaseHandler } from './DatabaseHandler';
export interface RouterOptions {
logger: Logger;
database: PluginDatabaseManager;
config: Config;
}
export async function createRouter(
options: RouterOptions,
): Promise<express.Router> {
const { logger, database } = options;
const db = await database.getClient();
const dbHandler = await DatabaseHandler.create({ database: db });
logger.info('Initializing Bazaar backend');
const router = Router();
router.use(express.json());
router.get('/members/:ref', async (request, response) => {
const entity_ref = decodeURIComponent(request.params.ref);
const data = await dbHandler.getMembers(entity_ref);
if (data?.length) {
response.json({ status: 'ok', data: data });
} else {
response.json({ status: 'ok', data: [] });
}
});
router.put('/member', async (request, response) => {
const { user_id, entity_ref, picture } = request.body;
await dbHandler.addMember(user_id, entity_ref, picture);
response.json({ status: 'ok' });
});
router.delete('/member/:ref/:id', async (request, response) => {
const { ref, id } = request.params;
const count = await dbHandler.deleteMember(id, ref);
if (count) {
response.json({ status: 'ok' });
} else {
response.status(404).json({ message: 'Record not found' });
}
});
router.get('/metadata/:ref', async (request, response) => {
const ref = decodeURIComponent(request.params.ref);
const data = await dbHandler.getMetadata(ref);
response.json({ status: 'ok', data: data });
});
router.get('/entities', async (_, response) => {
const data = await dbHandler.getEntities();
response.json({ status: 'ok', data: data });
});
router.put('/metadata', async (request, response) => {
const bazaarProject = request.body;
const count = await dbHandler.updateMetadata(bazaarProject);
if (count) {
response.json({ status: 'ok' });
} else {
await dbHandler.insertMetadata(bazaarProject);
response.json({ status: 'ok' });
}
});
router.delete('/metadata/:ref', async (request, response) => {
const ref = decodeURIComponent(request.params.ref);
const count = await dbHandler.deleteMetadata(ref);
if (count) {
response.json({ status: 'ok' });
} else {
response.status(404).json({ message: 'Record not found' });
}
});
router.use(errorHandler());
return router;
}
@@ -0,0 +1,72 @@
/*
* Copyright 2020 The Backstage Authors
*
* 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.
*/
import {
createServiceBuilder,
loadBackendConfig,
useHotMemoize,
} from '@backstage/backend-common';
import { Server } from 'http';
import { Logger } from 'winston';
import { createRouter } from './router';
import knexFactory from 'knex';
export interface ServerOptions {
port: number;
enableCors: boolean;
logger: Logger;
}
export async function startStandaloneServer(
options: ServerOptions,
): Promise<Server> {
const logger = options.logger.child({ service: 'bazaar-backend' });
const config = await loadBackendConfig({ logger, argv: process.argv });
const db = useHotMemoize(module, () => {
const knex = knexFactory({
client: 'sqlite3',
connection: ':memory:',
useNullAsDefault: true,
});
knex.client.pool.on('createSuccess', (_eventId: any, resource: any) => {
resource.run('PRAGMA foreign_keys = ON', () => {});
});
return knex;
});
const router = await createRouter({
logger,
database: { getClient: async () => db },
config: config,
});
let service = createServiceBuilder(module)
.setPort(options.port)
.addRouter('/bazaar', router);
if (options.enableCors) {
service = service.enableCors({ origin: 'http://localhost:3000' });
}
return await service.start().catch(err => {
logger.error(err);
process.exit(1);
});
}
module.hot?.accept();
@@ -14,4 +14,4 @@
* limitations under the License.
*/
import '@testing-library/jest-dom';
export {};
+127
View File
@@ -0,0 +1,127 @@
# @backstage/plugin-bazaar
### What is the Bazaar?
The Bazaar is a place where teams can propose projects for cross-functional team development. Essentially a marketplace for internal projects suitable for [Inner Sourcing](https://en.wikipedia.org/wiki/Inner_source). With "Inner Sourcing", we mean projects that are developed internally within a company, but with Open Source best practices.
### Why?
Many companies today are of high need to increase the ease of cross-team cooperation. In large organizations, engineers often have limited ways of discovering or announcing the projects which could benefit from a wider development effort in terms of different expertise, experiences, and teams spread across the organization. With no good way to find these existing internal projects to join, the possibility of working with Inner Sourcing practices suffers.
### How?
The Bazaar allows engineers and teams to open up and announce their new and exciting projects for transparent cooperation in other parts of larger organizations. The Bazaar ensures that new Inner Sourcing friendly projects gain visibility through Backstage and a way for interested engineers to show their interest and in the future contribute with their specific skill set. The Bazaar also provides an easy way to manage, catalog, and browse these Inner Sourcing friendly projects and components.
## Getting Started
First install the plugin into your app:
```sh
# From your Backstage root directory
cd packages/app
yarn add @backstage/plugin-bazaar
```
Modify your app routes in `packages/app/src/App.tsx` to include the `Bazaar` component exported from the plugin, for example:
```diff
+ import { BazaarPage } from '@backstage/plugin-bazaar';
const routes = (
<FlatRoutes>
...
+ <Route path="bazaar" element={<BazaarPage />} />
{/* other routes... */}
```
Add a **Bazaar icon** to the Sidebar to easily access the Bazaar. In `packages/app/src/components/Root.tsx` add:
```diff
+ import StorefrontIcon from '@material-ui/icons/Storefront';
<SidebarDivider />
<SidebarScrollWrapper>
+ <SidebarItem icon={StorefrontIcon} to="bazaar" text="Bazaar" />
{/* ...other sidebar-items */}
```
Add a **Bazaar card** to the overview tab on the `packages/app/src/components/catalog/EntityPage.tsx` add:
```diff
+ import { EntityBazaarInfoCard } from '@backstage/plugin-bazaar';
const overviewContent = (
<Grid item md={8} xs={12}>
<EntityAboutCard variant="gridItem" />
</Grid>
+ <Grid item sm={4}>
+ <EntityBazaarInfoCard />
+ </Grid>
{/* ...other entity-cards */}
```
## How does the Bazaar work?
### Layout
The latest modified Bazaar projects are displayed in the Bazaar landing page, located at the Bazaar icon in the sidebar. Each project is represented as a card containing its most relevant data to give an overview of the project. The list of project is paginated.
![home](media/bazaar_pr_fullscreen.png)
### Workflow
To add a project to the Bazaar, you need to create a project with one of the templates in Backstage. Click the add project-button, choose the project and fill in the form. You will be asked to add an announcement for new team members. The purpose of the announcement is for you to present your ideas and what skills you are looking for. Further you need to provide the status of the project.
When the project is added, you will see the Bazaar information in the Bazaar card on the entity page. There you can join a project, edit or delete it.
![workflow](media/bazaar_demo.gif)
### Database
The metadata related to the Bazaar is stored in a database. Right now there are two tables, one for storing the metadata and one for storing the members of a Bazaar project.
**metadata**:
- name - name of the entity
- entity_ref - namespace/kind/name of the entity
- announcement - announcement of the project and its current need of skills/team member
- status - status of the project, 'proposed' or 'ongoing'
- updated_at - date when the Bazaar information was last modified (ISO 8601 format)
**members**:
- entity_ref - namespace/kind/name of the entity
- user_name
- join_date - date when the user joined the project (ISO 8601 format)
## Future work and ideas
- Workflow
- Make it possible to add a Bazaar project without linking it to a Backstage entity, this would make it easier to just add an idea to the Bazaar.
- Bazaar landing page
- Add a tab 'My page', where your personal data is displayed. For example: your projects and its latest activities, projects or tags you are following etc.
- Make it possible to sort the project based on the number of members
- Bazaar card
- Make it possible to follow tags/projects
- Bazaar tab on the EntityPage
- Fill Bazaar-tab with more content, for example images and achievements
- Show all the members that have joined the project
- Dialogues
- Extend the dialogue for adding a project with more fields, e.g. the possibility to add images
- Testing
- Add tests to all the components
+32
View File
@@ -0,0 +1,32 @@
## API Report File for "@backstage/plugin-bazaar"
> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).
```ts
/// <reference types="react" />
import { BackstagePlugin } from '@backstage/core-plugin-api';
import { RouteRef } from '@backstage/core-plugin-api';
// Warning: (ae-missing-release-tag) "BazaarPage" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal)
//
// @public (undocumented)
export const BazaarPage: () => JSX.Element;
// Warning: (ae-missing-release-tag) "bazaarPlugin" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal)
//
// @public (undocumented)
export const bazaarPlugin: BackstagePlugin<
{
root: RouteRef<undefined>;
},
{}
>;
// Warning: (ae-missing-release-tag) "EntityBazaarInfoCard" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal)
//
// @public (undocumented)
export const EntityBazaarInfoCard: () => JSX.Element | null;
// (No @packageDocumentation comment for this package)
```
@@ -1,5 +1,5 @@
/*
* Copyright 2020 The Backstage Authors
* Copyright 2021 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,12 +16,12 @@
import React from 'react';
import { createDevApp } from '@backstage/dev-utils';
import { welcomePlugin, WelcomePage } from '../src/plugin';
import { bazaarPlugin, BazaarPage } from '../src/plugin';
createDevApp()
.registerPlugin(welcomePlugin)
.registerPlugin(bazaarPlugin)
.addPage({
title: 'Welcome',
element: <WelcomePage />,
element: <BazaarPage />,
title: 'Root Page',
})
.render();
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 389 KiB

@@ -1,59 +1,48 @@
{
"name": "@backstage/plugin-welcome",
"description": "An old Backstage plugin that provides a welcome page",
"version": "0.3.8",
"name": "@backstage/plugin-bazaar",
"version": "0.1.1",
"main": "src/index.ts",
"types": "src/index.ts",
"private": false,
"license": "Apache-2.0",
"private": false,
"publishConfig": {
"access": "public",
"main": "dist/index.esm.js",
"types": "dist/index.d.ts"
},
"homepage": "https://backstage.io",
"repository": {
"type": "git",
"url": "https://github.com/backstage/backstage",
"directory": "plugins/welcome"
},
"keywords": [
"backstage"
],
"scripts": {
"build": "backstage-cli plugin:build",
"start": "backstage-cli plugin:serve",
"lint": "backstage-cli lint",
"test": "backstage-cli test",
"diff": "backstage-cli plugin:diff",
"prepack": "backstage-cli prepack",
"postpack": "backstage-cli postpack",
"clean": "backstage-cli clean",
"start": "backstage-cli plugin:serve"
"clean": "backstage-cli clean"
},
"dependencies": {
"@backstage/catalog-model": "^0.9.0",
"@backstage/cli": "^0.7.16",
"@backstage/core-components": "^0.7.0",
"@backstage/core-plugin-api": "^0.1.10",
"@backstage/theme": "^0.2.11",
"@backstage/plugin-catalog": "^0.7.0",
"@backstage/plugin-catalog-react": "^0.5.0",
"@material-ui/core": "^4.12.2",
"@material-ui/icons": "^4.9.1",
"@material-ui/lab": "4.0.0-alpha.57",
"@testing-library/jest-dom": "^5.10.1",
"luxon": "^2.0.2",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-hook-form": "^7.13.0",
"react-router-dom": "6.0.0-beta.0",
"react-use": "^17.2.4"
},
"devDependencies": {
"@backstage/cli": "^0.7.16",
"@backstage/core-app-api": "^0.1.17",
"@backstage/dev-utils": "^0.2.12",
"@backstage/test-utils": "^0.1.19",
"@testing-library/jest-dom": "^5.10.1",
"@testing-library/react": "^11.2.5",
"@testing-library/user-event": "^13.1.8",
"@types/jest": "^26.0.7",
"@types/node": "^14.14.32",
"cross-fetch": "^3.0.6",
"msw": "^0.29.0"
"cross-fetch": "^3.0.6"
},
"files": [
"dist"
+141
View File
@@ -0,0 +1,141 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
import { Entity, stringifyEntityRef } from '@backstage/catalog-model';
import {
createApiRef,
DiscoveryApi,
IdentityApi,
} from '@backstage/core-plugin-api';
import { BazaarProject } from './types';
export const bazaarApiRef = createApiRef<BazaarApi>({
id: 'bazaar',
description: 'Used to make requests towards the bazaar backend',
});
export interface BazaarApi {
updateMetadata(bazaarProject: BazaarProject): Promise<any>;
getMetadata(entity: Entity): Promise<any>;
getMembers(entity: Entity): Promise<any>;
deleteMember(entity: Entity): Promise<void>;
addMember(entity: Entity): Promise<void>;
getEntities(): Promise<any>;
deleteEntity(bazaarProject: BazaarProject): Promise<void>;
}
export class BazaarClient implements BazaarApi {
private readonly identityApi: IdentityApi;
private readonly discoveryApi: DiscoveryApi;
constructor(options: {
identityApi: IdentityApi;
discoveryApi: DiscoveryApi;
}) {
this.identityApi = options.identityApi;
this.discoveryApi = options.discoveryApi;
}
async updateMetadata(bazaarProject: BazaarProject): Promise<any> {
const baseUrl = await this.discoveryApi.getBaseUrl('bazaar');
return await fetch(`${baseUrl}/metadata`, {
method: 'PUT',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(bazaarProject),
}).then(resp => resp.json());
}
async getMetadata(entity: Entity): Promise<any> {
const baseUrl = await this.discoveryApi.getBaseUrl('bazaar');
const response = await fetch(
`${baseUrl}/metadata/${encodeURIComponent(stringifyEntityRef(entity))}`,
{
method: 'GET',
},
);
return response.ok ? response : null;
}
async getMembers(entity: Entity): Promise<any> {
const baseUrl = await this.discoveryApi.getBaseUrl('bazaar');
return await fetch(
`${baseUrl}/members/${encodeURIComponent(stringifyEntityRef(entity))}`,
{
method: 'GET',
},
).then(resp => resp.json());
}
async addMember(entity: Entity): Promise<void> {
const baseUrl = await this.discoveryApi.getBaseUrl('bazaar');
await fetch(`${baseUrl}/member`, {
method: 'PUT',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
entity_ref: stringifyEntityRef(entity),
user_id: this.identityApi.getUserId(),
picture: this.identityApi.getProfile()?.picture,
}),
});
}
async deleteMember(entity: Entity): Promise<void> {
const baseUrl = await this.discoveryApi.getBaseUrl('bazaar');
await fetch(
`${baseUrl}/member/${encodeURIComponent(
stringifyEntityRef(entity),
)}/${this.identityApi.getUserId()}`,
{
method: 'DELETE',
},
);
}
async getEntities(): Promise<any> {
const baseUrl = await this.discoveryApi.getBaseUrl('bazaar');
return await fetch(`${baseUrl}/entities`, {
method: 'GET',
}).then(resp => resp.json());
}
async deleteEntity(bazaarProject: BazaarProject): Promise<void> {
const baseUrl = await this.discoveryApi.getBaseUrl('bazaar');
const entityRef = bazaarProject.entityRef as string;
await fetch(`${baseUrl}/metadata/${encodeURIComponent(entityRef)}`, {
method: 'DELETE',
});
}
}
@@ -0,0 +1,78 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
import React from 'react';
import { Grid, Typography, Link, makeStyles } from '@material-ui/core';
import { InfoCard } from '@backstage/core-components';
const useStyles = makeStyles({
subheader: {
fontWeight: 'bold',
},
});
export const About = () => {
const classes = useStyles();
return (
<Grid container spacing={4}>
<Grid item xs={5}>
<InfoCard title="About Bazaar">
<Typography className={classes.subheader} variant="body1">
What is the Bazaar?
</Typography>
<Typography paragraph>
The Bazaar is a place where teams can propose projects for
cross-functional team development. Essentially a marketplace for
internal projects suitable for{' '}
<Link
target="_blank"
href="https://en.wikipedia.org/wiki/Inner_source"
>
Inner Sourcing
</Link>
. With "Inner Sourcing", we mean projects that are developed
internally within a company, but with Open Source best practices.
</Typography>
<Typography className={classes.subheader} variant="body1">
Why?
</Typography>
<Typography paragraph>
Many companies today are of high need to increase the ease of
cross-team cooperation. In large organizations, engineers often have
limited ways of discovering or announcing the projects which could
benefit from a wider development effort in terms of different
expertise, experiences, and teams spread across the organization.
With no good way to find these existing internal projects to join,
the possibility of working with Inner Sourcing practices suffers.
</Typography>
<Typography className={classes.subheader} variant="body1">
How?
</Typography>
<Typography paragraph>
The Bazaar allows engineers and teams to open up and announce their
new and exciting projects for transparent cooperation in other parts
of larger organizations. The Bazaar ensures that new Inner Sourcing
friendly projects gain visibility through Backstage and a way for
interested engineers to show their interest and in the future
contribute with their specific skill set. The Bazaar also provides
an easy way to manage, catalog, and browse these Inner Sourcing
friendly projects and components.
</Typography>
</InfoCard>
</Grid>
</Grid>
);
};
@@ -0,0 +1,17 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
export { About } from './About';
@@ -0,0 +1,108 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
import React, { useState, useEffect } from 'react';
import { Entity, stringifyEntityRef } from '@backstage/catalog-model';
import { SubmitHandler } from 'react-hook-form';
import { useApi } from '@backstage/core-plugin-api';
import { ProjectDialog } from '../ProjectDialog';
import { ProjectSelector } from '../ProjectSelector';
import { BazaarProject, FormValues, Status } from '../../types';
import { bazaarApiRef } from '../../api';
type Props = {
catalogEntities: Entity[];
open: boolean;
handleClose: () => void;
fetchBazaarProjects: () => Promise<BazaarProject[]>;
fetchCatalogEntities: () => Promise<Entity[]>;
};
export const AddProjectDialog = ({
catalogEntities,
open,
handleClose,
fetchBazaarProjects,
fetchCatalogEntities,
}: Props) => {
const bazaarApi = useApi(bazaarApiRef);
const [selectedEntity, setSelectedEntity] = useState(
catalogEntities ? catalogEntities[0] : null,
);
useEffect(() => {
setSelectedEntity(catalogEntities ? catalogEntities[0] : null);
}, [catalogEntities]);
const defaultValues = {
title: 'Add project',
community: '',
announcement: '',
status: 'proposed' as Status,
};
const handleListItemClick = (entity: Entity) => {
setSelectedEntity(entity);
};
const handleCloseDialog = () => {
setSelectedEntity(catalogEntities ? catalogEntities[0] : null);
handleClose();
};
const handleSave: SubmitHandler<FormValues> = async (
getValues: any,
reset: any,
) => {
const formValues = getValues();
if (selectedEntity) {
await bazaarApi.updateMetadata({
name: selectedEntity.metadata.name,
entityRef: stringifyEntityRef(selectedEntity),
announcement: formValues.announcement,
status: formValues.status,
community: formValues.community,
membersCount: 0,
} as BazaarProject);
fetchBazaarProjects();
fetchCatalogEntities();
handleClose();
reset(defaultValues);
}
};
return (
<ProjectDialog
handleSave={handleSave}
title="Add project"
isAddForm
defaultValues={defaultValues}
open={open}
projectSelector={
<ProjectSelector
value={selectedEntity?.metadata?.name || ''}
onChange={handleListItemClick}
isFormInvalid={selectedEntity === null}
entities={catalogEntities || []}
/>
}
handleClose={handleCloseDialog}
/>
);
};
@@ -0,0 +1,17 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
export { AddProjectDialog } from './AddProjectDialog';
@@ -0,0 +1,51 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
import React from 'react';
import { Snackbar, IconButton } from '@material-ui/core';
import CloseIcon from '@material-ui/icons/Close';
import { Alert } from '@material-ui/lab';
type Props = {
open: boolean;
message: JSX.Element;
handleClose: () => void;
};
export const AlertBanner = ({ open, message, handleClose }: Props) => {
return (
<Snackbar
open={open}
anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
>
<Alert
severity="error"
action={
<IconButton
color="inherit"
size="small"
onClick={handleClose}
data-testid="error-button-close"
>
<CloseIcon />
</IconButton>
}
>
{message}
</Alert>
</Snackbar>
);
};
@@ -0,0 +1,17 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
export { AlertBanner } from './AlertBanner';
@@ -0,0 +1,139 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
import React, { Dispatch, SetStateAction } from 'react';
import {
createStyles,
Theme,
withStyles,
WithStyles,
} from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import MuiDialogTitle from '@material-ui/core/DialogTitle';
import MuiDialogContent from '@material-ui/core/DialogContent';
import MuiDialogActions from '@material-ui/core/DialogActions';
import IconButton from '@material-ui/core/IconButton';
import CloseIcon from '@material-ui/icons/Close';
import Typography from '@material-ui/core/Typography';
import { useApi } from '@backstage/core-plugin-api';
import { bazaarApiRef } from '../../api';
import { BazaarProject } from '../../types';
const styles = (theme: Theme) =>
createStyles({
root: {
margin: 0,
padding: theme.spacing(2),
},
closeButton: {
position: 'absolute',
right: theme.spacing(1),
top: theme.spacing(1),
color: theme.palette.grey[500],
},
});
/*
DialogTitleProps, DialogTitle, DialogContent and DialogActions
are copied from the git-release plugin
*/
export interface DialogTitleProps extends WithStyles<typeof styles> {
id: string;
children: React.ReactNode;
onClose: () => void;
}
const DialogTitle = withStyles(styles)((props: DialogTitleProps) => {
const { children, classes, onClose, ...other } = props;
return (
<MuiDialogTitle disableTypography className={classes.root} {...other}>
<Typography variant="h6">{children}</Typography>
{onClose ? (
<IconButton
aria-label="close"
className={classes.closeButton}
onClick={onClose}
>
<CloseIcon />
</IconButton>
) : null}
</MuiDialogTitle>
);
});
const DialogContent = withStyles((theme: Theme) => ({
root: {
padding: theme.spacing(2),
},
}))(MuiDialogContent);
const DialogActions = withStyles((theme: Theme) => ({
root: {
margin: 0,
padding: theme.spacing(1),
},
}))(MuiDialogActions);
type Props = {
bazaarProject: BazaarProject;
openDelete: boolean;
handleClose: () => void;
setIsBazaar: Dispatch<SetStateAction<boolean>>;
};
export const DeleteProjectDialog = ({
bazaarProject,
openDelete,
handleClose,
setIsBazaar,
}: Props) => {
const handleCloseAndClear = () => {
handleClose();
};
const bazaarApi = useApi(bazaarApiRef);
const handleSubmit = async () => {
await bazaarApi.deleteEntity(bazaarProject);
setIsBazaar(false);
handleCloseAndClear();
};
return (
<Dialog
fullWidth
maxWidth="xs"
onClose={handleCloseAndClear}
aria-labelledby="customized-dialog-title"
open={openDelete}
>
<DialogTitle id="customized-dialog-title" onClose={handleCloseAndClear}>
Delete project
</DialogTitle>
<DialogContent dividers>
Are you sure you want to delete this project from the Bazaar?
</DialogContent>
<DialogActions>
<Button onClick={handleSubmit} color="primary" type="submit">
Delete
</Button>
</DialogActions>
</Dialog>
);
};
@@ -0,0 +1,17 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
export { DeleteProjectDialog } from './DeleteProjectDialog';
@@ -0,0 +1,82 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
import React, { useState, useEffect } from 'react';
import { Entity, stringifyEntityRef } from '@backstage/catalog-model';
import { useApi } from '@backstage/core-plugin-api';
import { ProjectDialog } from '../ProjectDialog';
import { BazaarProject, FormValues } from '../../types';
import { bazaarApiRef } from '../../api';
type Props = {
entity: Entity;
bazaarProject: BazaarProject;
fetchBazaarProject: () => Promise<BazaarProject | null>;
open: boolean;
handleClose: () => void;
isAddForm: boolean;
};
export const EditProjectDialog = ({
entity,
bazaarProject,
fetchBazaarProject,
open,
handleClose,
}: Props) => {
const [defaultValues, setDefaultValues] = useState<FormValues>({
announcement: bazaarProject.announcement,
community: bazaarProject.community,
status: bazaarProject.status,
});
const bazaarApi = useApi(bazaarApiRef);
useEffect(() => {
setDefaultValues({
announcement: bazaarProject.announcement,
community: bazaarProject.community,
status: bazaarProject.status,
});
}, [bazaarProject]);
const handleSave: any = async (getValues: any, _: any) => {
const formValues = getValues();
const updateResponse = await bazaarApi.updateMetadata({
name: entity.metadata.name,
entityRef: stringifyEntityRef(entity),
announcement: formValues.announcement,
status: formValues.status,
community: formValues.community,
membersCount: bazaarProject.membersCount,
});
if (updateResponse.status === 'ok') fetchBazaarProject();
handleClose();
};
return (
<ProjectDialog
title="Edit project"
handleSave={handleSave}
isAddForm={false}
defaultValues={defaultValues}
open={open}
handleClose={handleClose}
/>
);
};
@@ -0,0 +1,17 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
export { EditProjectDialog } from './EditProjectDialog';
@@ -0,0 +1,324 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
import React, { useState, useEffect } from 'react';
import {
Grid,
makeStyles,
Card,
CardContent,
CardHeader,
Typography,
Divider,
IconButton,
Popover,
MenuList,
MenuItem,
ListItemText,
Link,
} from '@material-ui/core';
import {
Progress,
HeaderIconLinkRow,
IconLinkVerticalProps,
Avatar,
} from '@backstage/core-components';
import { useEntity } from '@backstage/plugin-catalog-react';
import { AboutField } from '@backstage/plugin-catalog';
import { StatusTag } from '../StatusTag';
import EditIcon from '@material-ui/icons/Edit';
import ChatIcon from '@material-ui/icons/Chat';
import PersonAddIcon from '@material-ui/icons/PersonAdd';
import MoreVertIcon from '@material-ui/icons/MoreVert';
import DeleteIcon from '@material-ui/icons/Delete';
import { EditProjectDialog } from '../EditProjectDialog';
import { DeleteProjectDialog } from '../DeleteProjectDialog';
import ExitToAppIcon from '@material-ui/icons/ExitToApp';
import { useApi, identityApiRef } from '@backstage/core-plugin-api';
import { Member, BazaarProject } from '../../types';
import { bazaarApiRef } from '../../api';
import { Alert } from '@material-ui/lab';
import { useAsyncFn } from 'react-use';
const useStyles = makeStyles({
description: {
wordBreak: 'break-word',
},
icon: {
marginRight: '1.75rem',
},
link: {
color: '#9cc9ff',
'&:hover': {
textDecoration: 'underline',
},
},
memberLink: {
display: 'block',
marginBottom: '0.3rem',
},
});
const sortMembers = (m1: Member, m2: Member) => {
return new Date(m2.joinDate!).getTime() - new Date(m1.joinDate!).getTime();
};
export const EntityBazaarInfoCard = () => {
const { entity } = useEntity();
const classes = useStyles();
const bazaarApi = useApi(bazaarApiRef);
const identity = useApi(identityApiRef);
const [anchorEl, setAnchorEl] = useState<HTMLButtonElement>();
const [open, setOpen] = useState(false);
const [popoverOpen, setPopoverOpen] = useState(false);
const [openDelete, setOpenDelete] = useState(false);
const [isMember, setIsMember] = useState(false);
const [isBazaar, setIsBazaar] = useState(false);
const [members, fetchMembers] = useAsyncFn(async () => {
const response = await bazaarApi.getMembers(entity);
const dbMembers = response.data.map((obj: any) => {
const member: Member = {
userId: obj.user_id,
entityRef: obj.entity_ref,
joinDate: obj.join_date,
picture: obj.picture,
};
return member;
});
dbMembers.sort(sortMembers);
return dbMembers;
});
const [bazaarProject, fetchBazaarProject] = useAsyncFn(async () => {
const response = await bazaarApi.getMetadata(entity);
if (response) {
const metadata = await response.json().then((resp: any) => resp.data[0]);
if (metadata) {
return {
entityRef: metadata.entity_ref,
name: metadata.name,
community: metadata.community,
announcement: metadata.announcement,
status: metadata.status,
updatedAt: metadata.updated_at,
membersCount: metadata.members_count,
} as BazaarProject;
}
}
return null;
});
useEffect(() => {
fetchMembers();
fetchBazaarProject();
}, [fetchMembers, fetchBazaarProject]);
useEffect(() => {
const isBazaarMember =
members?.value
?.map((member: Member) => member.userId)
.indexOf(identity.getUserId()) >= 0;
const isBazaarProject = bazaarProject.value !== null;
setIsMember(isBazaarMember);
setIsBazaar(isBazaarProject);
}, [bazaarProject, members, identity]);
const onOpen = (event: React.SyntheticEvent<HTMLButtonElement>) => {
setAnchorEl(event.currentTarget);
setPopoverOpen(true);
};
const closeEdit = () => {
setOpen(false);
};
const closeDelete = () => {
setOpenDelete(false);
};
const popoverCloseHandler = () => {
setPopoverOpen(false);
};
const handleMembersClick = async () => {
if (!isMember) {
await bazaarApi.addMember(entity);
} else {
await bazaarApi.deleteMember(entity);
}
fetchMembers();
fetchBazaarProject();
};
const links: IconLinkVerticalProps[] = [
{
label: isMember ? 'Leave' : 'Join',
icon: isMember ? <ExitToAppIcon /> : <PersonAddIcon />,
href: '',
onClick: async () => {
handleMembersClick();
},
},
{
label: 'Community',
icon: <ChatIcon />,
href: bazaarProject?.value?.community,
disabled: !bazaarProject?.value?.community || !isMember,
},
];
if (!isBazaar) {
return null;
} else if (bazaarProject.loading || members.loading) {
return <Progress />;
} else if (bazaarProject.error) {
return <Alert severity="error">{bazaarProject?.error?.message}</Alert>;
} else if (members.error) {
return <Alert severity="error">{members?.error?.message}</Alert>;
}
return (
<Card>
{bazaarProject?.value && (
<EditProjectDialog
open={open}
entity={entity}
bazaarProject={bazaarProject.value}
fetchBazaarProject={fetchBazaarProject}
handleClose={closeEdit}
isAddForm={false}
/>
)}
{bazaarProject?.value && (
<DeleteProjectDialog
bazaarProject={bazaarProject.value}
openDelete={openDelete}
handleClose={closeDelete}
setIsBazaar={setIsBazaar}
/>
)}
<CardHeader
title="Bazaar"
action={
<IconButton onClick={onOpen}>
<MoreVertIcon />
</IconButton>
}
subheader={<HeaderIconLinkRow links={links} />}
/>
<Divider />
<CardContent>
<Popover
open={popoverOpen}
onClose={popoverCloseHandler}
anchorEl={anchorEl}
anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
transformOrigin={{ vertical: 'top', horizontal: 'right' }}
>
<MenuList>
<MenuItem
onClick={() => {
setOpen(true);
setPopoverOpen(false);
}}
>
<EditIcon className={classes.icon} />
<ListItemText primary="Edit project" />
</MenuItem>
<Divider />
<MenuItem
onClick={() => {
setOpenDelete(true);
setPopoverOpen(false);
}}
>
<DeleteIcon className={classes.icon} />
<ListItemText primary="Remove from Bazaar" />
</MenuItem>
</MenuList>
</Popover>
<Grid container>
<Grid item xs={12}>
<AboutField label="Announcement">
{bazaarProject?.value?.announcement
? bazaarProject?.value?.announcement
.split('\n')
.map((str: string, i: number) => (
<Typography
key={i}
variant="body2"
paragraph
className={classes.description}
>
{str}
</Typography>
))
: 'No announcement'}
</AboutField>
</Grid>
<Grid item xs={6}>
<AboutField label="Status">
<StatusTag status={bazaarProject?.value?.status || 'proposed'} />
</AboutField>
</Grid>
<Grid item xs={6}>
{' '}
<AboutField label="Latest members">
{members?.value?.length ? (
members.value.slice(0, 3).map((member: Member) => {
return (
<div key={member.userId}>
<Avatar
displayName={member.userId}
customStyles={{
width: '19px',
height: '19px',
fontSize: '8px',
float: 'left',
marginRight: '0.3rem',
}}
picture={member.picture}
/>
<Link
className={classes.memberLink}
href={`http://github.com/${member.userId}`}
target="_blank"
>
{member?.userId}
</Link>
</div>
);
})
) : (
<div />
)}
</AboutField>
</Grid>
</Grid>
</CardContent>
</Card>
);
};
@@ -0,0 +1,17 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
export { EntityBazaarInfoCard } from './EntityBazaarInfoCard';
@@ -0,0 +1,47 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
import React from 'react';
import { Header, RoutedTabs } from '@backstage/core-components';
import { Route } from 'react-router-dom';
import { SortView } from '../SortView';
import { About } from '../About';
export const HomePage = () => {
const tabContent = [
{
path: '/',
title: 'Home',
children: <Route path="/" element={<SortView />} />,
},
{
path: '/about',
title: 'About',
children: <Route path="/about" element={<About />} />,
},
];
return (
<div>
<Header
data-testid="bazaar-header"
title="Bazaar"
subtitle="Marketplace for inner source projects"
/>
<RoutedTabs routes={tabContent} />
</div>
);
};
@@ -0,0 +1,17 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
export { HomePage } from './HomePage';
@@ -0,0 +1,63 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
import React from 'react';
import { Controller, Control, FieldError } from 'react-hook-form';
import { TextField } from '@material-ui/core';
import { FormValues } from '../../types';
type Props = {
inputType: 'announcement' | 'community';
error?: FieldError | undefined;
control: Control<FormValues, object>;
helperText?: string;
placeholder?: string;
rules?: Object;
};
export const InputField = ({
inputType,
error,
control,
helperText,
placeholder,
rules,
}: Props) => {
const label =
inputType.charAt(0).toLocaleUpperCase('en-US') + inputType.slice(1);
return (
<Controller
name={inputType}
control={control}
rules={rules}
render={({ field }) => (
<TextField
{...field}
margin="dense"
multiline
id="title"
type="text"
fullWidth
label={label}
placeholder={placeholder}
error={!!error}
helperText={error && helperText}
/>
)}
/>
);
};
@@ -0,0 +1,17 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
export { InputField } from './InputField';
@@ -0,0 +1,75 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
import React from 'react';
import InputLabel from '@material-ui/core/InputLabel';
import MenuItem from '@material-ui/core/MenuItem';
import FormControl from '@material-ui/core/FormControl';
import Select from '@material-ui/core/Select';
import { Controller, Control, FieldError } from 'react-hook-form';
import { FormValues } from '../../types';
type Props = {
options: string[];
control: Control<FormValues, object>;
name: 'announcement' | 'status';
error?: FieldError | undefined;
};
export const InputSelector = ({ name, options, control, error }: Props) => {
const label = name.charAt(0).toLocaleUpperCase('en-US') + name.slice(1);
return (
<Controller
name={name}
control={control}
rules={{
required: true,
}}
render={({ field }) => (
<FormControl fullWidth>
<InputLabel
htmlFor="demo-simple-select-outlined"
id="demo-simple-select-outlined-label"
>
{label}
</InputLabel>
<Select
{...field}
required
labelId="demo-simple-select-outlined-label"
id="demo-simple-select-outlined"
label={label}
error={!!error}
>
{options.map(option => {
return (
<MenuItem
data-testid="menu-item"
button
key={option}
value={option}
>
{option}
</MenuItem>
);
})}
</Select>
</FormControl>
)}
/>
);
};
@@ -0,0 +1,17 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
export { InputSelector } from './InputSelector';
@@ -0,0 +1,98 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
import React from 'react';
import { ItemCardHeader } from '@backstage/core-components';
import {
Card,
CardActionArea,
CardContent,
makeStyles,
Typography,
} from '@material-ui/core';
import { StatusTag } from '../StatusTag/StatusTag';
import { Link as RouterLink } from 'react-router-dom';
import { catalogRouteRef } from '@backstage/plugin-catalog-react';
import { useRouteRef } from '@backstage/core-plugin-api';
import { BazaarProject } from '../../types';
import { parseEntityName } from '@backstage/catalog-model';
import { DateTime } from 'luxon';
const useStyles = makeStyles({
statusTag: {
display: 'inline-block',
whiteSpace: 'nowrap',
marginBottom: '0.5rem',
},
announcement: {
display: '-webkit-box',
WebkitLineClamp: 5,
WebkitBoxOrient: 'vertical',
marginBottom: '0.8rem',
overflow: 'hidden',
},
memberCount: {
float: 'right',
},
});
type Props = {
bazaarProject: BazaarProject;
};
export const ProjectCard = ({ bazaarProject }: Props) => {
const classes = useStyles();
const { entityRef, name, status, updatedAt, announcement, membersCount } =
bazaarProject;
const catalogLink = useRouteRef(catalogRouteRef);
const { namespace, kind } = parseEntityName(entityRef);
return (
<Card key={entityRef as string}>
<CardActionArea
style={{
height: '100%',
overflow: 'hidden',
width: '100%',
}}
component={RouterLink}
to={`${catalogLink()}/${namespace}/${kind}/${name}`}
>
<ItemCardHeader
title={name}
subtitle={`updated ${DateTime.fromISO(
new Date(updatedAt!).toISOString(),
).toRelative({
base: DateTime.now(),
})}`}
/>
<CardContent style={{ height: '12rem' }}>
<StatusTag styles={classes.statusTag} status={status} />
<Typography variant="body2" className={classes.memberCount}>
{membersCount === 1
? `${membersCount} member`
: `${membersCount} members`}
</Typography>
<div style={{ minHeight: '6.5rem', maxHeight: '6.5rem' }}>
<Typography variant="body2" className={classes.announcement}>
{announcement}
</Typography>
</div>
</CardContent>
</CardActionArea>
</Card>
);
};
@@ -0,0 +1,17 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
export { ProjectCard } from './ProjectCard';
@@ -0,0 +1,186 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
import React from 'react';
import {
createStyles,
Theme,
withStyles,
WithStyles,
} from '@material-ui/core/styles';
import MuiDialogTitle from '@material-ui/core/DialogTitle';
import MuiDialogContent from '@material-ui/core/DialogContent';
import MuiDialogActions from '@material-ui/core/DialogActions';
import CloseIcon from '@material-ui/icons/Close';
import { Button, Dialog, Typography, IconButton } from '@material-ui/core';
import { useForm, SubmitHandler } from 'react-hook-form';
import { InputField } from '../InputField/InputField';
import { InputSelector } from '../InputSelector/InputSelector';
import { FormValues } from '../../types';
const styles = (theme: Theme) =>
createStyles({
root: {
margin: 0,
padding: theme.spacing(2),
},
closeButton: {
position: 'absolute',
right: theme.spacing(1),
top: theme.spacing(1),
color: theme.palette.grey[500],
},
});
/*
DialogTitleProps, DialogTitle, DialogContent and DialogActions
are copied from the git-release plugin
*/
export interface DialogTitleProps extends WithStyles<typeof styles> {
id: string;
children: React.ReactNode;
onClose: () => void;
}
const DialogTitle = withStyles(styles)((props: DialogTitleProps) => {
const { children, classes, onClose, ...other } = props;
return (
<MuiDialogTitle disableTypography className={classes.root} {...other}>
<Typography variant="h6">{children}</Typography>
{onClose ? (
<IconButton
aria-label="close"
className={classes.closeButton}
onClick={onClose}
>
<CloseIcon />
</IconButton>
) : null}
</MuiDialogTitle>
);
});
const DialogContent = withStyles((theme: Theme) => ({
root: {
padding: theme.spacing(2),
},
}))(MuiDialogContent);
const DialogActions = withStyles((theme: Theme) => ({
root: {
margin: 0,
padding: theme.spacing(1),
},
}))(MuiDialogActions);
type Props = {
handleSave: (getValues: any, reset: any) => SubmitHandler<FormValues>;
isAddForm: boolean;
title: string;
defaultValues: FormValues;
open: boolean;
projectSelector?: JSX.Element;
handleClose: () => void;
};
export const ProjectDialog = ({
handleSave,
isAddForm,
title,
defaultValues,
open,
projectSelector,
handleClose,
}: Props) => {
const {
handleSubmit,
reset,
control,
getValues,
formState: { errors },
} = useForm<FormValues>({
mode: 'onChange',
defaultValues: defaultValues,
});
const handleCloseAndClear = () => {
handleClose();
reset(defaultValues);
};
const handleSaveProject = () => {
handleSave(getValues, reset);
};
return (
<div>
<Dialog
fullWidth
maxWidth="xs"
onClose={handleCloseAndClear}
aria-labelledby="customized-dialog-title"
open={open}
>
<DialogTitle id="customized-dialog-title" onClose={handleCloseAndClear}>
{title}
</DialogTitle>
<DialogContent dividers>
{isAddForm && projectSelector}
<InputField
error={errors.announcement}
control={control}
rules={{
required: true,
}}
inputType="announcement"
helperText="please enter an announcement"
placeholder="Describe who you are and what skills you are looking for"
/>
<InputField
error={errors.community}
control={control}
rules={{
required: false,
pattern: RegExp('^(https?)://[^s$.?#].[^s]*$'),
}}
inputType="community"
helperText="please enter a link starting with http/https"
placeholder="Community link to e.g. Teams or Discord"
/>
<InputSelector
control={control}
name="status"
options={['proposed', 'ongoing']}
/>
</DialogContent>
<DialogActions>
<Button
onClick={handleSubmit(handleSaveProject)}
color="primary"
type="submit"
>
Submit
</Button>
</DialogActions>
</Dialog>
</div>
);
};
@@ -0,0 +1,17 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
export { ProjectDialog } from './ProjectDialog';
@@ -0,0 +1,109 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
import React, { useState } from 'react';
import { Content } from '@backstage/core-components';
import { ProjectCard } from '../ProjectCard/ProjectCard';
import { makeStyles, Grid } from '@material-ui/core';
import Pagination from '@material-ui/lab/Pagination';
import { BazaarProject } from '../../types';
type Props = {
bazaarProjects: BazaarProject[];
sortingMethod: (arg0: BazaarProject, arg1: BazaarProject) => number;
};
const useStyles = makeStyles({
content: {
width: '100%',
display: 'flex',
flexWrap: 'wrap',
alignItems: 'center',
},
item: {
minWidth: '20.5rem',
maxWidth: '20.5rem',
width: '20%',
},
});
export const ProjectPreview = ({ bazaarProjects, sortingMethod }: Props) => {
const classes = useStyles();
const [currentPage, setCurrentPage] = useState(1);
const pageSize = 10;
const pageCount = Math.ceil(bazaarProjects.length / pageSize);
const handlePageClick = (_: any, pageIndex: number) => {
setCurrentPage(pageIndex);
};
if (!bazaarProjects.length) {
return (
<div
data-testid="empty-bazaar"
style={{
height: '10rem',
textAlign: 'center',
verticalAlign: 'middle',
lineHeight: '10rem',
}}
>
Please add projects to the Bazaar.
</div>
);
}
bazaarProjects.sort(sortingMethod);
return (
<Content className={classes.content} noPadding>
<Grid wrap="wrap" container spacing={3}>
{bazaarProjects
.slice(pageSize * (currentPage - 1), pageSize * currentPage)
.map((bazaarProject: BazaarProject) => {
const entityRef = bazaarProject.entityRef;
return (
<Grid
key={(entityRef as string) || ''}
className={classes.item}
item
xs={3}
>
<ProjectCard
bazaarProject={bazaarProject}
key={Math.random()}
/>
</Grid>
);
})}
</Grid>
<Pagination
showFirstButton
showLastButton
siblingCount={2}
style={{
marginTop: '1rem',
marginLeft: 'auto',
marginRight: '0',
}}
count={pageCount}
page={currentPage}
onChange={handlePageClick}
/>
</Content>
);
};
@@ -0,0 +1,17 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
export { ProjectPreview } from './ProjectPreview';
@@ -0,0 +1,54 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
import React from 'react';
import { Entity } from '@backstage/catalog-model';
import { Autocomplete } from '@material-ui/lab';
import { TextField } from '@material-ui/core';
type Props = {
entities: Entity[];
value: string;
onChange: (entity: Entity) => void;
isFormInvalid: boolean;
};
export const ProjectSelector = ({
entities,
value,
onChange,
isFormInvalid,
}: Props) => {
return (
<Autocomplete
defaultValue={entities[0]}
options={entities}
getOptionLabel={option => option?.metadata?.name}
renderOption={option => <span>{option?.metadata?.name}</span>}
renderInput={params => (
<TextField
error={isFormInvalid && value === ''}
helperText={
isFormInvalid && value === '' ? 'Please select a project' : ''
}
{...params}
label="Select a project"
/>
)}
onChange={(_, data) => onChange(data!)}
/>
);
};
@@ -0,0 +1,17 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
export { ProjectSelector } from './ProjectSelector';
@@ -0,0 +1,183 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
import React, { useEffect, useState } from 'react';
import {
Content,
ContentHeader,
SupportButton,
Progress,
} from '@backstage/core-components';
import { AddProjectDialog } from '../AddProjectDialog';
import { AlertBanner } from '../AlertBanner';
import { ProjectPreview } from '../ProjectPreview/ProjectPreview';
import { Button, makeStyles, Link } from '@material-ui/core';
import { useAsyncFn } from 'react-use';
import { Entity, stringifyEntityRef } from '@backstage/catalog-model';
import { useApi } from '@backstage/core-plugin-api';
import { catalogApiRef } from '@backstage/plugin-catalog-react';
import { BazaarProject } from '../../types';
import { bazaarApiRef } from '../../api';
import { Alert } from '@material-ui/lab';
const useStyles = makeStyles({
container: {
marginTop: '2rem',
},
});
const filterCatalogEntities = (
bazaarProjects: BazaarProject[],
catalogEntities: Entity[],
) => {
const bazaarProjectRefs = bazaarProjects.map(
(project: BazaarProject) => project.entityRef,
);
const filtered = catalogEntities.filter((entity: Entity) => {
return !bazaarProjectRefs?.includes(stringifyEntityRef(entity));
});
return filtered;
};
export const SortView = () => {
const classes = useStyles();
const [openAdd, setOpenAdd] = useState(false);
const [openNoProjects, setOpenNoProjects] = useState(false);
const bazaarApi = useApi(bazaarApiRef);
const catalogApi = useApi(catalogApiRef);
const [filteredCatalogEntites, setFilteredCatalogEntities] =
useState<Entity[]>();
const compareProjectsByDate = (
a: BazaarProject,
b: BazaarProject,
): number => {
const dateA = new Date(a.updatedAt!).getTime();
const dateB = new Date(b.updatedAt!).getTime();
return dateB - dateA;
};
const handleCloseNoProjects = () => {
setOpenNoProjects(false);
};
const [catalogEntities, fetchCatalogEntities] = useAsyncFn(async () => {
const entities = await catalogApi.getEntities({
filter: {
kind: ['Component', 'Resource'],
},
fields: ['kind', 'metadata.name', 'metadata.namespace'],
});
return entities.items;
});
const [bazaarProjects, fetchBazaarProjects] = useAsyncFn(async () => {
const response = await bazaarApi.getEntities();
const dbProjects: BazaarProject[] = [];
response.data.forEach((project: any) => {
dbProjects.push({
entityRef: project.entity_ref,
name: project.name,
status: project.status,
announcement: project.announcement,
community: project.community,
updatedAt: project.updated_at,
membersCount: project.members_count,
});
});
return dbProjects;
});
useEffect(() => {
fetchCatalogEntities();
fetchBazaarProjects();
}, [fetchBazaarProjects, fetchCatalogEntities]);
useEffect(() => {
const filteredCatalogEntities = filterCatalogEntities(
bazaarProjects.value || [],
catalogEntities.value || [],
);
if (filteredCatalogEntities) {
setFilteredCatalogEntities(filteredCatalogEntities);
}
}, [bazaarProjects, catalogEntities]);
if (catalogEntities.loading || bazaarProjects.loading) return <Progress />;
if (catalogEntities.error)
return <Alert severity="error">{catalogEntities.error.message}</Alert>;
if (bazaarProjects.error)
return <Alert severity="error">{bazaarProjects.error.message}</Alert>;
return (
<Content noPadding>
<AlertBanner
open={openNoProjects}
message={
<div>
No project available. Please{' '}
<Link
style={{ color: 'inherit', fontWeight: 'bold' }}
href="/create"
>
create a project
</Link>{' '}
from a template first.
</div>
}
handleClose={handleCloseNoProjects}
/>
<ContentHeader title="Latest updated">
<Button
variant="contained"
color="primary"
onClick={() => {
if (filteredCatalogEntites?.length !== 0) {
setOpenAdd(true);
} else {
setOpenNoProjects(true);
}
}}
>
Add project
</Button>
<AddProjectDialog
catalogEntities={filteredCatalogEntites || []}
handleClose={() => {
setOpenAdd(false);
}}
open={openAdd}
fetchBazaarProjects={fetchBazaarProjects}
fetchCatalogEntities={fetchCatalogEntities}
/>
<SupportButton />
</ContentHeader>
<ProjectPreview
bazaarProjects={bazaarProjects.value || []}
sortingMethod={compareProjectsByDate}
/>
<Content noPadding className={classes.container} />
</Content>
);
};
@@ -0,0 +1,17 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
export { SortView } from './SortView';
@@ -0,0 +1,37 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
import React from 'react';
import { StatusOK, StatusWarning } from '@backstage/core-components';
import { Status } from '../../types';
interface StatusComponent {
[key: string]: JSX.Element | undefined;
}
const statuses: StatusComponent = {
proposed: <StatusWarning>proposed</StatusWarning>,
ongoing: <StatusOK>ongoing</StatusOK>,
};
type Props = {
status: Status;
styles?: string;
};
export const StatusTag = ({ status, styles }: Props) => {
return <div className={styles}>{statuses[status]}</div>;
};
@@ -0,0 +1,17 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
export { StatusTag } from './StatusTag';
+18
View File
@@ -0,0 +1,18 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
export { bazaarPlugin, BazaarPage } from './plugin';
export { EntityBazaarInfoCard } from './components/EntityBazaarInfoCard';
@@ -1,5 +1,5 @@
/*
* Copyright 2020 The Backstage Authors
* Copyright 2021 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -14,10 +14,10 @@
* limitations under the License.
*/
import { welcomePlugin } from './plugin';
import { bazaarPlugin } from './plugin';
describe('welcome', () => {
describe('bazaar', () => {
it('should export plugin', () => {
expect(welcomePlugin).toBeDefined();
expect(bazaarPlugin).toBeDefined();
});
});
+50
View File
@@ -0,0 +1,50 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
import { rootRouteRef } from './routes';
import {
createApiFactory,
createPlugin,
createRoutableExtension,
identityApiRef,
discoveryApiRef,
} from '@backstage/core-plugin-api';
import { bazaarApiRef, BazaarClient } from './api';
export const bazaarPlugin = createPlugin({
id: 'bazaar',
routes: {
root: rootRouteRef,
},
apis: [
createApiFactory({
api: bazaarApiRef,
deps: {
identityApi: identityApiRef,
discoveryApi: discoveryApiRef,
},
factory: ({ identityApi, discoveryApi }) =>
new BazaarClient({ identityApi, discoveryApi }),
}),
],
});
export const BazaarPage = bazaarPlugin.provide(
createRoutableExtension({
component: () => import('./components/HomePage').then(m => m.HomePage),
mountPoint: rootRouteRef,
}),
);
@@ -1,5 +1,5 @@
/*
* Copyright 2020 The Backstage Authors
* Copyright 2021 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -14,10 +14,8 @@
* limitations under the License.
*/
/**
* An old Backstage plugin that provides a welcome page
*
* @packageDocumentation
*/
import { createRouteRef } from '@backstage/core-plugin-api';
export { welcomePlugin, welcomePlugin as plugin, WelcomePage } from './plugin';
export const rootRouteRef = createRouteRef({
title: 'bazaar',
});
+18
View File
@@ -0,0 +1,18 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
import '@testing-library/jest-dom';
import 'cross-fetch/polyfill';
+42
View File
@@ -0,0 +1,42 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
import { EntityRef } from '@backstage/catalog-model';
export type Member = {
entityRef: EntityRef;
userId: string;
joinDate?: string;
picture?: string;
};
export type Status = 'ongoing' | 'proposed';
export type BazaarProject = {
name: string;
entityRef: EntityRef;
community: string;
status: Status;
announcement: string;
updatedAt?: string;
membersCount: number;
};
export type FormValues = {
announcement: string;
community: string;
status: string;
};
@@ -15,12 +15,14 @@
*/
import { Entity } from '@backstage/catalog-model';
import { ApiProvider, ApiRegistry } from '@backstage/core-app-api';
import { analyticsApiRef } from '@backstage/core-plugin-api';
import {
CatalogApi,
catalogApiRef,
EntityProvider,
} from '@backstage/plugin-catalog-react';
import { renderInTestApp } from '@backstage/test-utils';
import { MockAnalyticsApi, renderInTestApp } from '@backstage/test-utils';
import userEvent from '@testing-library/user-event';
import React from 'react';
import { catalogEntityRouteRef, catalogGraphRouteRef } from '../../routes';
import { CatalogGraphCard } from './CatalogGraphCard';
@@ -117,4 +119,30 @@ describe('<CatalogGraphCard/>', () => {
'/catalog-graph?rootEntityRefs%5B%5D=b%3Ad%2Fc',
);
});
test('captures analytics event on click', async () => {
const analyticsSpy = new MockAnalyticsApi();
const { findByText } = await renderInTestApp(
<ApiProvider apis={ApiRegistry.from([[analyticsApiRef, analyticsSpy]])}>
{wrapper}
</ApiProvider>,
{
mountedRoutes: {
'/entity/{kind}/{namespace}/{name}': catalogEntityRouteRef,
'/catalog-graph': catalogGraphRouteRef,
},
},
);
expect(await findByText('b:d/c')).toBeInTheDocument();
userEvent.click(await findByText('b:d/c'));
expect(analyticsSpy.getEvents()[0]).toMatchObject({
action: 'click',
subject: 'b:d/c',
attributes: {
to: '/entity/{kind}/{namespace}/{name}',
},
});
});
});
@@ -19,8 +19,11 @@ import {
stringifyEntityRef,
} from '@backstage/catalog-model';
import { InfoCard, InfoCardVariants } from '@backstage/core-components';
import { useRouteRef } from '@backstage/core-plugin-api';
import { useEntity } from '@backstage/plugin-catalog-react';
import { useAnalytics, useRouteRef } from '@backstage/core-plugin-api';
import {
formatEntityRefTitle,
useEntity,
} from '@backstage/plugin-catalog-react';
import { makeStyles, Theme } from '@material-ui/core';
import qs from 'qs';
import React, { MouseEvent, useCallback } from 'react';
@@ -78,6 +81,7 @@ export const CatalogGraphCard = ({
const catalogGraphRoute = useRouteRef(catalogGraphRouteRef);
const navigate = useNavigate();
const classes = useStyles({ height });
const analytics = useAnalytics();
const onNodeClick = useCallback(
(node: EntityNode, _: MouseEvent<unknown>) => {
@@ -87,9 +91,14 @@ export const CatalogGraphCard = ({
namespace: nodeEntityName.namespace.toLocaleLowerCase('en-US'),
name: nodeEntityName.name,
});
analytics.captureEvent(
'click',
node.title ?? formatEntityRefTitle(nodeEntityName),
{ attributes: { to: path } },
);
navigate(path);
},
[catalogEntityRoute, navigate],
[catalogEntityRoute, navigate, analytics],
);
const catalogGraphParams = qs.stringify(
@@ -15,8 +15,9 @@
*/
import { RELATION_HAS_PART, RELATION_PART_OF } from '@backstage/catalog-model';
import { ApiProvider, ApiRegistry } from '@backstage/core-app-api';
import { analyticsApiRef } from '@backstage/core-plugin-api';
import { CatalogApi, catalogApiRef } from '@backstage/plugin-catalog-react';
import { renderInTestApp } from '@backstage/test-utils';
import { MockAnalyticsApi, renderInTestApp } from '@backstage/test-utils';
import userEvent from '@testing-library/user-event';
import React from 'react';
import { catalogEntityRouteRef } from '../../routes';
@@ -167,4 +168,53 @@ describe('<CatalogGraphPage/>', () => {
expect(navigate).toBeCalledWith('/entity/{kind}/{namespace}/{name}');
});
test('should capture analytics event when selecting other entity', async () => {
const analyticsSpy = new MockAnalyticsApi();
const { getByText, findAllByTestId } = await renderInTestApp(
<ApiProvider apis={ApiRegistry.from([[analyticsApiRef, analyticsSpy]])}>
{wrapper}
</ApiProvider>,
{
mountedRoutes: {
'/entity/{kind}/{namespace}/{name}': catalogEntityRouteRef,
},
},
);
expect(await findAllByTestId('node')).toHaveLength(2);
userEvent.click(getByText('b:d/e'));
expect(analyticsSpy.getEvents()[0]).toMatchObject({
action: 'click',
subject: 'b:d/e',
});
});
test('should capture analytics event when navigating to entity', async () => {
const analyticsSpy = new MockAnalyticsApi();
const { getByText, findAllByTestId } = await renderInTestApp(
<ApiProvider apis={ApiRegistry.from([[analyticsApiRef, analyticsSpy]])}>
{wrapper}
</ApiProvider>,
{
mountedRoutes: {
'/entity/{kind}/{namespace}/{name}': catalogEntityRouteRef,
},
},
);
expect(await findAllByTestId('node')).toHaveLength(2);
userEvent.click(getByText('b:d/e'), { shiftKey: true });
expect(analyticsSpy.getEvents()[0]).toMatchObject({
action: 'click',
subject: 'b:d/e',
attributes: {
to: '/entity/{kind}/{namespace}/{name}',
},
});
});
});
@@ -21,7 +21,7 @@ import {
Page,
SupportButton,
} from '@backstage/core-components';
import { useRouteRef } from '@backstage/core-plugin-api';
import { useAnalytics, useRouteRef } from '@backstage/core-plugin-api';
import { formatEntityRefTitle } from '@backstage/plugin-catalog-react';
import { Grid, makeStyles, Paper, Typography } from '@material-ui/core';
import FilterListIcon from '@material-ui/icons/FilterList';
@@ -31,11 +31,11 @@ import React, { MouseEvent, useCallback } from 'react';
import { useNavigate } from 'react-router';
import { catalogEntityRouteRef } from '../../routes';
import {
ALL_RELATION_PAIRS,
Direction,
EntityNode,
EntityRelationsGraph,
RelationPairs,
ALL_RELATION_PAIRS,
} from '../EntityRelationsGraph';
import { DirectionFilter } from './DirectionFilter';
import { MaxDepthFilter } from './MaxDepthFilter';
@@ -133,6 +133,7 @@ export const CatalogGraphPage = ({
showFilters,
toggleShowFilters,
} = useCatalogGraphPage({ initialState });
const analytics = useAnalytics();
const onNodeClick = useCallback(
(node: EntityNode, event: MouseEvent<unknown>) => {
const nodeEntityName = parseEntityRef(node.id);
@@ -143,12 +144,22 @@ export const CatalogGraphPage = ({
namespace: nodeEntityName.namespace.toLocaleLowerCase('en-US'),
name: nodeEntityName.name,
});
analytics.captureEvent(
'click',
node.title ?? formatEntityRefTitle(nodeEntityName),
{ attributes: { to: path } },
);
navigate(path);
} else {
analytics.captureEvent(
'click',
node.title ?? formatEntityRefTitle(nodeEntityName),
);
setRootEntityNames([nodeEntityName]);
}
},
[catalogEntityRoute, navigate, setRootEntityNames],
[catalogEntityRoute, navigate, setRootEntityNames, analytics],
);
return (
@@ -45,7 +45,7 @@ const entities: Entity[] = [
];
describe('<PreviewCatalogInfoComponent />', () => {
it('renders without exploding', async () => {
it('renders without exploding', () => {
render(
<PreviewCatalogInfoComponent
repositoryUrl="http://my-repository/a/"
@@ -56,14 +56,14 @@ describe('<PreviewCatalogInfoComponent />', () => {
const repositoryUrl = screen.getByText(
'http://my-repository/a/catalog-info.yaml',
);
const kindText = await screen.findByText('Kind_2');
const kindText = screen.getByText(/Kind_2/);
expect(repositoryUrl).toBeInTheDocument();
expect(repositoryUrl).toBeVisible();
expect(kindText).toBeInTheDocument();
expect(kindText).toBeVisible();
});
it('renders card with custom styles', async () => {
it('renders card with custom styles', () => {
const { result } = renderHook(() => useStyles());
render(
@@ -77,14 +77,14 @@ describe('<PreviewCatalogInfoComponent />', () => {
const repositoryUrl = screen.getByText(
'http://my-repository/a/catalog-info.yaml',
);
const kindText = await screen.findByText('Kind_2');
const kindText = screen.getByText(/Kind_2/);
expect(repositoryUrl).toBeInTheDocument();
expect(repositoryUrl).not.toBeVisible();
expect(kindText).toBeInTheDocument();
expect(kindText).not.toBeVisible();
});
it('renders with custom styles', async () => {
it('renders with custom styles', () => {
const { result } = renderHook(() => useStyles());
render(
@@ -98,7 +98,7 @@ describe('<PreviewCatalogInfoComponent />', () => {
const repositoryUrl = screen.getByText(
'http://my-repository/a/catalog-info.yaml',
);
const kindText = await screen.findByText('Kind_2');
const kindText = screen.getByText(/Kind_2/);
expect(repositoryUrl).toBeInTheDocument();
expect(repositoryUrl).toBeVisible();
expect(kindText).toBeInTheDocument();
+11 -1
View File
@@ -21,7 +21,17 @@ export const EntityFossaCard: ({
// Warning: (ae-missing-release-tag) "FossaPage" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal)
//
// @public (undocumented)
export const FossaPage: () => JSX.Element;
export const FossaPage: ({ entitiesFilter }: FossaPageProps) => JSX.Element;
// Warning: (ae-missing-release-tag) "FossaPageProps" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal)
//
// @public (undocumented)
export type FossaPageProps = {
entitiesFilter?:
| Record<string, string | symbol | (string | symbol)[]>[]
| Record<string, string | symbol | (string | symbol)[]>
| undefined;
};
// Warning: (ae-missing-release-tag) "fossaPlugin" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal)
//
@@ -142,4 +142,38 @@ describe('<FossaPage />', () => {
expect(getByText(/0 Issues/i)).toBeInTheDocument();
expect(getByText(/10 Issues/i)).toBeInTheDocument();
});
it('has configurable entity filter', async () => {
const entity: Entity = {
apiVersion: 'v1',
kind: 'API',
metadata: {
name: 'my-name-0',
annotations: {
'fossa.io/project-name': 'my-name-0',
},
},
};
fossaApi.getFindingSummaries.mockResolvedValue(new Map());
catalogApi.getEntities.mockResolvedValue({ items: [entity] });
const { getByText } = await renderInTestApp(
<Wrapper>
<FossaPage entitiesFilter={{ kind: 'API' }} />
</Wrapper>,
{
mountedRoutes: {
'/catalog/:namespace/:kind/:name/*': entityRouteRef,
},
},
);
expect(catalogApi.getEntities).toBeCalledWith(
expect.objectContaining({
filter: { kind: 'API' },
}),
);
expect(getByText(/my-name-0/i)).toBeInTheDocument();
});
});
@@ -30,8 +30,8 @@ import { Tooltip } from '@material-ui/core';
import { Skeleton } from '@material-ui/lab';
import { DateTime } from 'luxon';
import * as React from 'react';
import { useMemo } from 'react';
import { useAsync } from 'react-use';
import { useMemo, useState } from 'react';
import { useAsync, useDeepCompareEffect } from 'react-use';
import { FindingSummary, fossaApiRef } from '../../api';
import { getProjectName } from '../getProjectName';
@@ -166,14 +166,25 @@ const filters: TableFilter[] = [
{ column: 'Branch', type: 'select' },
];
export const FossaPage = () => {
export type FossaPageProps = {
entitiesFilter?:
| Record<string, string | symbol | (string | symbol)[]>[]
| Record<string, string | symbol | (string | symbol)[]>
| undefined;
};
export const FossaPage = ({
entitiesFilter = { kind: 'Component' },
}: FossaPageProps) => {
const catalogApi = useApi(catalogApiRef);
const fossaApi = useApi(fossaApiRef);
const [filter, setFilter] = useState(entitiesFilter);
useDeepCompareEffect(() => setFilter(entitiesFilter), [entitiesFilter]);
// Get a list of all relevant entities
const { value: entities, loading: entitiesLoading } = useAsync(() => {
return catalogApi.getEntities({
filter: { kind: 'Component' },
filter,
fields: [
'kind',
'metadata.namespace',
@@ -182,7 +193,7 @@ export const FossaPage = () => {
'relations',
],
});
});
}, [filter]);
// get the project names of all entities. the idx of both lists match.
const projectNames = useMemo(
@@ -15,3 +15,4 @@
*/
export { FossaPage } from './FossaPage';
export type { FossaPageProps } from './FossaPage';
+1 -1
View File
@@ -14,4 +14,4 @@
* limitations under the License.
*/
export * from './FossaCard';
export type { FossaPageProps } from './FossaPage';
+2 -1
View File
@@ -20,5 +20,6 @@
* @packageDocumentation
*/
export { fossaPlugin } from './plugin';
export * from './components';
export { EntityFossaCard, FossaPage } from './extensions';
export { fossaPlugin } from './plugin';
@@ -391,6 +391,6 @@ export function usePatchDryRun({
asyncCatcher,
abortIfError,
selectedPatchCommit: latestCommitOnReleaseBranchRes.value
?.selectedPatchCommit as any,
?.selectedPatchCommit as GetRecentCommitsResultSingle,
};
}
@@ -80,6 +80,12 @@ const FailSkippedWidget = ({
};
const generatedColumns: TableColumn[] = [
{
title: 'Timestamp',
defaultSort: 'desc',
hidden: true,
field: 'lastBuild.timestamp',
},
{
title: 'Build',
field: 'fullName',
+7
View File
@@ -1,5 +1,12 @@
# @backstage/plugin-scaffolder-backend
## 0.15.9
### Patch Changes
- 0f99f1170e: Make sure `sourcePath` of `publish:github:pull-request` can only be used to
retrieve files from the workspace.
## 0.15.8
### Patch Changes
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@backstage/plugin-scaffolder-backend",
"description": "The Backstage backend plugin that helps you create new things",
"version": "0.15.8",
"version": "0.15.9",
"main": "src/index.ts",
"types": "src/index.ts",
"license": "Apache-2.0",
@@ -14,21 +14,20 @@
* limitations under the License.
*/
import { getRootLogger } from '@backstage/backend-common';
import { ConfigReader } from '@backstage/config';
import { ScmIntegrations } from '@backstage/integration';
import mockFs from 'mock-fs';
import { Writable } from 'stream';
import os from 'os';
import { resolve as resolvePath } from 'path';
import {
PullRequestCreator,
GithubPullRequestActionInput,
createPublishGithubPullRequestAction,
ClientFactoryInput,
} from './githubPullRequest';
import { Writable } from 'stream';
import { ActionContext, TemplateAction } from '../../types';
import { getRootLogger } from '@backstage/backend-common';
import { ScmIntegrations } from '@backstage/integration';
import { ConfigReader } from '@backstage/config';
import {
ClientFactoryInput,
createPublishGithubPullRequestAction,
GithubPullRequestActionInput,
PullRequestCreator,
} from './githubPullRequest';
const root = os.platform() === 'win32' ? 'C:\\root' : '/root';
const workspacePath = resolvePath(root, 'my-workspace');
@@ -174,6 +173,14 @@ describe('createPublishGithubPullRequestAction', () => {
],
});
});
it('should not allow to use files outside of the workspace', async () => {
input.sourcePath = '../../test';
await expect(instance.handler(ctx)).rejects.toThrow(
'Relative path is not allowed to refer to a directory outside its parent',
);
});
});
describe('with repoUrl', () => {
@@ -28,6 +28,7 @@ import { Octokit } from '@octokit/rest';
import { InputError, CustomErrorBase } from '@backstage/errors';
import { createPullRequest } from 'octokit-plugin-create-pull-request';
import globby from 'globby';
import { resolveSafeChildPath } from '@backstage/backend-common';
class GithubResponseError extends CustomErrorBase {}
@@ -183,7 +184,7 @@ export const createPublishGithubPullRequestAction = ({
const client = await clientFactory({ integrations, host, owner, repo });
const fileRoot = sourcePath
? path.resolve(ctx.workspacePath, sourcePath)
? resolveSafeChildPath(ctx.workspacePath, sourcePath)
: ctx.workspacePath;
const localFilePaths = await globby(['./**', './**/.*', '!.git'], {
@@ -0,0 +1,43 @@
/*
* Copyright 2021 The Backstage Authors
*
* 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.
*/
import { getRepoSourceDirectory } from './util';
describe('getRepoSourceDirectory', () => {
test('should return workspace root if no sub folder is given', () => {
expect(getRepoSourceDirectory('/var/workspace', undefined)).toEqual(
'/var/workspace',
);
});
test('should return path in workspace if sub folder is given', () => {
expect(
getRepoSourceDirectory('/var/workspace', 'path/of/subfolder'),
).toEqual('/var/workspace/path/of/subfolder');
});
test('should not allow traversal outside the workspace root', () => {
expect(getRepoSourceDirectory('/var/workspace', '../secret')).toEqual(
'/var/workspace/secret',
);
expect(
getRepoSourceDirectory('/var/workspace', './path/../../secret'),
).toEqual('/var/workspace/secret');
expect(
getRepoSourceDirectory('/var/workspace', '/absolute/secret'),
).toEqual('/var/workspace/absolute/secret');
});
});
@@ -15,6 +15,7 @@
*/
import { InputError } from '@backstage/errors';
import { isChildPath } from '@backstage/backend-common';
import { join as joinPath, normalize as normalizePath } from 'path';
import { ScmIntegrationRegistry } from '@backstage/integration';
@@ -27,7 +28,11 @@ export const getRepoSourceDirectory = (
/^(\.\.(\/|\\|$))+/,
'',
);
return joinPath(workspacePath, safeSuffix);
const path = joinPath(workspacePath, safeSuffix);
if (!isChildPath(workspacePath, path)) {
throw new Error('Invalid source path');
}
return path;
}
return workspacePath;
};
@@ -13,7 +13,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import os from 'os';
import mockFs from 'mock-fs';
import * as winston from 'winston';
import { getVoidLogger } from '@backstage/backend-common';
import { DefaultWorkflowRunner } from './DefaultWorkflowRunner';
import { TemplateActionRegistry } from '../actions';
@@ -22,7 +25,6 @@ import { ConfigReader } from '@backstage/config';
import { Task, TaskSpec } from './types';
describe('DefaultWorkflowRunner', () => {
const workingDirectory = os.tmpdir();
const logger = getVoidLogger();
let actionRegistry = new TemplateActionRegistry();
let runner: DefaultWorkflowRunner;
@@ -45,6 +47,11 @@ describe('DefaultWorkflowRunner', () => {
});
beforeEach(() => {
winston.format.simple(); // put logform the require cache before mocking fs
mockFs({
'/tmp': mockFs.directory(),
});
jest.resetAllMocks();
actionRegistry = new TemplateActionRegistry();
fakeActionHandler = jest.fn();
@@ -84,11 +91,15 @@ describe('DefaultWorkflowRunner', () => {
runner = new DefaultWorkflowRunner({
actionRegistry,
integrations,
workingDirectory,
workingDirectory: '/tmp',
logger,
});
});
afterEach(() => {
mockFs.restore();
});
it('should throw an error if the action does not exist', async () => {
const task = createMockTaskWithSpec({
apiVersion: 'scaffolder.backstage.io/v1beta3',
@@ -13,18 +13,19 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import mockFs from 'mock-fs';
import * as winston from 'winston';
import { createTemplateAction, TemplateActionRegistry } from '../actions';
import { ScmIntegrations } from '@backstage/integration';
import { ConfigReader } from '@backstage/config';
import { getVoidLogger } from '@backstage/backend-common';
import { LegacyWorkflowRunner } from './LegacyWorkflowRunner';
import os from 'os';
import { Task, TaskSpec } from './types';
import { RepoSpec } from '../actions/builtin/publish/util';
describe('LegacyWorkflowRunner', () => {
let runner: LegacyWorkflowRunner;
const workingDirectory = os.tmpdir();
const logger = getVoidLogger();
let actionRegistry = new TemplateActionRegistry();
@@ -45,6 +46,11 @@ describe('LegacyWorkflowRunner', () => {
});
beforeEach(() => {
winston.format.simple(); // put logform the require cache before mocking fs
mockFs({
'/tmp': mockFs.directory(),
});
actionRegistry = new TemplateActionRegistry();
actionRegistry.register({
id: 'test-action',
@@ -57,11 +63,15 @@ describe('LegacyWorkflowRunner', () => {
runner = new LegacyWorkflowRunner({
actionRegistry,
integrations,
workingDirectory,
workingDirectory: '/tmp',
logger,
});
});
afterEach(() => {
mockFs.restore();
});
it('should fail when the action does not exist', async () => {
const task = createMockTaskWithSpec({
apiVersion: 'backstage.io/v1beta2',
+1 -1
View File
@@ -51,7 +51,7 @@ entries.push({
title: 'JavaScript',
quadrant: 'languages',
description:
'Excepteur **sint** occaecat *cupidatat* non proident, sunt in culpa qui officia deserunt mollit anim id est laborum',
'Excepteur **sint** occaecat *cupidatat* non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n\n```ts\nconst x = "3";\n```\n',
});
entries.push({
timeline: [
@@ -397,6 +397,11 @@ const TheReader = ({
const dom = useTechDocsReaderDom();
const shadowDomRef = useRef<HTMLDivElement>(null);
const onReadyRef = useRef<() => void>(onReady);
useEffect(() => {
onReadyRef.current = onReady;
}, [onReady]);
useEffect(() => {
if (!dom || !shadowDomRef.current) return;
const shadowDiv = shadowDomRef.current;
@@ -406,8 +411,10 @@ const TheReader = ({
shadowRoot.removeChild(child),
);
shadowRoot.appendChild(dom);
onReady();
}, [dom, onReady]);
onReadyRef.current();
// this hook must ONLY be triggered by a changed dom
}, [dom]);
return (
<>
-212
View File
@@ -1,212 +0,0 @@
# @backstage/plugin-welcome
## 0.3.8
### Patch Changes
- Updated dependencies
- @backstage/core-components@0.7.0
- @backstage/theme@0.2.11
## 0.3.7
### Patch Changes
- 81a41ec249: Added a `name` key to all extensions in order to improve Analytics API metadata.
- Updated dependencies
- @backstage/core-components@0.6.1
- @backstage/core-plugin-api@0.1.10
## 0.3.6
### Patch Changes
- Updated dependencies
- @backstage/core-plugin-api@0.1.9
- @backstage/core-components@0.6.0
## 0.3.5
### Patch Changes
- Updated dependencies
- @backstage/core-components@0.5.0
## 0.3.4
### Patch Changes
- 9f1362dcc1: Upgrade `@material-ui/lab` to `4.0.0-alpha.57`.
- Updated dependencies
- @backstage/core-components@0.4.2
- @backstage/core-plugin-api@0.1.8
## 0.3.3
### Patch Changes
- Updated dependencies
- @backstage/core-components@0.4.0
## 0.3.2
### Patch Changes
- Updated dependencies
- @backstage/core-components@0.3.0
- @backstage/core-plugin-api@0.1.5
## 0.3.1
### Patch Changes
- 9d40fcb1e: - Bumping `material-ui/core` version to at least `4.12.2` as they made some breaking changes in later versions which broke `Pagination` of the `Table`.
- Switching out `material-table` to `@material-table/core` for support for the later versions of `material-ui/core`
- This causes a minor API change to `@backstage/core-components` as the interface for `Table` re-exports the `prop` from the underlying `Table` components.
- `onChangeRowsPerPage` has been renamed to `onRowsPerPageChange`
- `onChangePage` has been renamed to `onPageChange`
- Migration guide is here: https://material-table-core.com/docs/breaking-changes
- Updated dependencies
- @backstage/core-components@0.2.0
- @backstage/core-plugin-api@0.1.4
- @backstage/theme@0.2.9
## 0.3.0
### Minor Changes
- d719926d2: **BREAKING CHANGE** Remove deprecated route registrations, meaning that it is no longer enough to only import the plugin in the app and the exported page extension must be used instead.
### Patch Changes
- 48c9fcd33: Migrated to use the new `@backstage/core-*` packages rather than `@backstage/core`.
- Updated dependencies
- @backstage/core-plugin-api@0.1.3
## 0.2.8
### Patch Changes
- 062bbf90f: chore: bump `@testing-library/user-event` from 12.8.3 to 13.1.8
- 675a569a9: chore: bump `react-use` dependency in all packages
- Updated dependencies [062bbf90f]
- Updated dependencies [889d89b6e]
- Updated dependencies [3f988cb63]
- Updated dependencies [675a569a9]
- @backstage/core@0.7.9
## 0.2.7
### Patch Changes
- f85851837: Australian Greeting
- Updated dependencies [94da20976]
- Updated dependencies [d8cc7e67a]
- Updated dependencies [99fbef232]
- Updated dependencies [ab07d77f6]
- Updated dependencies [931b21a12]
- Updated dependencies [937ed39ce]
- Updated dependencies [9a9e7a42f]
- Updated dependencies [50ce875a0]
- @backstage/core@0.7.6
- @backstage/theme@0.2.6
## 0.2.6
### Patch Changes
- Updated dependencies [40c0fdbaa]
- Updated dependencies [2a271d89e]
- Updated dependencies [bece09057]
- Updated dependencies [169f48deb]
- Updated dependencies [8a1566719]
- Updated dependencies [4c049a1a1]
- @backstage/core@0.7.0
## 0.2.5
### Patch Changes
- 8dfdec613: Migrated to new composability API, exporting the plugin as `welcomePlugin` and the page as `WelcomePage`.
- Updated dependencies [12ece98cd]
- Updated dependencies [d82246867]
- Updated dependencies [c810082ae]
- Updated dependencies [5fa3bdb55]
- Updated dependencies [21e624ba9]
- Updated dependencies [da9f53c60]
- Updated dependencies [32c95605f]
- Updated dependencies [54c7d02f7]
- @backstage/core@0.6.0
- @backstage/theme@0.2.3
## 0.2.4
### Patch Changes
- Updated dependencies [efd6ef753]
- Updated dependencies [a187b8ad0]
- @backstage/core@0.5.0
## 0.2.3
### Patch Changes
- Updated dependencies [2527628e1]
- Updated dependencies [1c69d4716]
- Updated dependencies [1665ae8bb]
- Updated dependencies [04f26f88d]
- Updated dependencies [ff243ce96]
- @backstage/core@0.4.0
- @backstage/theme@0.2.2
## 0.2.2
### Patch Changes
- 303c5ea17: Refactor route registration to remove deprecating code
## 0.2.1
### Patch Changes
- Updated dependencies [7b37d65fd]
- Updated dependencies [4aca74e08]
- Updated dependencies [e8f69ba93]
- Updated dependencies [0c0798f08]
- Updated dependencies [0c0798f08]
- Updated dependencies [199237d2f]
- Updated dependencies [6627b626f]
- Updated dependencies [4577e377b]
- @backstage/core@0.3.0
- @backstage/theme@0.2.1
## 0.2.0
### Minor Changes
- 28edd7d29: Create backend plugin through CLI
### Patch Changes
- Updated dependencies [819a70229]
- Updated dependencies [ae5983387]
- Updated dependencies [0d4459c08]
- Updated dependencies [482b6313d]
- Updated dependencies [1c60f716e]
- Updated dependencies [144c66d50]
- Updated dependencies [b79017fd3]
- Updated dependencies [6d97d2d6f]
- Updated dependencies [93a3fa3ae]
- Updated dependencies [782f3b354]
- Updated dependencies [2713f28f4]
- Updated dependencies [406015b0d]
- Updated dependencies [82759d3e4]
- Updated dependencies [ac8d5d5c7]
- Updated dependencies [ebca83d48]
- Updated dependencies [aca79334f]
- Updated dependencies [c0d5242a0]
- Updated dependencies [3beb5c9fc]
- Updated dependencies [754e31db5]
- Updated dependencies [1611c6dbc]
- @backstage/core@0.2.0
- @backstage/theme@0.2.0
-10
View File
@@ -1,10 +0,0 @@
# Title
> This plugin formerly provided the "homepage" of early alpha versions of Backstage.
> It is no longer in active use and in most cases can be removed from your instance.
Welcome to the welcome plugin!
## Sub-section 1
## Sub-section 2
-21
View File
@@ -1,21 +0,0 @@
## API Report File for "@backstage/plugin-welcome"
> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).
```ts
/// <reference types="react" />
import { BackstagePlugin } from '@backstage/core-plugin-api';
// Warning: (ae-missing-release-tag) "WelcomePage" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal)
//
// @public (undocumented)
export const WelcomePage: () => JSX.Element;
// Warning: (ae-missing-release-tag) "welcomePlugin" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal)
//
// @public (undocumented)
const welcomePlugin: BackstagePlugin<{}, {}>;
export { welcomePlugin as plugin };
export { welcomePlugin };
```
@@ -1,46 +0,0 @@
/*
* Copyright 2020 The Backstage Authors
*
* 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.
*/
import { renderInTestApp } from '@backstage/test-utils';
import { lightTheme } from '@backstage/theme';
import { ThemeProvider } from '@material-ui/core';
import React from 'react';
import WelcomePage from './WelcomePage';
import {
ApiProvider,
ApiRegistry,
ConfigReader,
} from '@backstage/core-app-api';
import { configApiRef, errorApiRef } from '@backstage/core-plugin-api';
describe('WelcomePage', () => {
it('should render', async () => {
const { baseElement } = await renderInTestApp(
<ApiProvider
apis={ApiRegistry.from([
[errorApiRef, { post: jest.fn() }],
[configApiRef, new ConfigReader({})],
])}
>
<ThemeProvider theme={lightTheme}>
<WelcomePage />
</ThemeProvider>
</ApiProvider>,
);
expect(baseElement).toBeInTheDocument();
});
});
@@ -1,166 +0,0 @@
/*
* Copyright 2020 The Backstage Authors
*
* 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.
*/
import React from 'react';
import { Link as RouterLink } from 'react-router-dom';
import {
Typography,
Grid,
List,
ListItem,
ListItemText,
Link,
} from '@material-ui/core';
import {
Content,
InfoCard,
Header,
HomepageTimer,
Page,
ContentHeader,
SupportButton,
WarningPanel,
} from '@backstage/core-components';
import { useApi, configApiRef } from '@backstage/core-plugin-api';
const WelcomePage = () => {
const appTitle =
useApi(configApiRef).getOptionalString('app.title') ?? 'Backstage';
const profile = { givenName: '' };
return (
<Page themeId="home">
<Header
title={`Welcome ${profile.givenName || `to ${appTitle}`}`}
subtitle="Let's start building a better developer experience"
>
<HomepageTimer />
</Header>
<Content>
<ContentHeader title="Getting Started">
<SupportButton />
</ContentHeader>
<Grid container>
<Grid item xs={12}>
<WarningPanel
title="Backstage is in early development"
message={
<>
We created Backstage about 4 years ago. While Spotify's
internal version of Backstage has had the benefit of time to
mature and evolve, the first iteration of our open source
version is still nascent. We are envisioning three phases of
the project and we have already begun work on various aspects
of these phases. The best way to keep track of the progress is
through the&nbsp;
<Link
href="https://github.com/backstage/backstage/milestones"
rel="noopener noreferrer"
>
Milestones
</Link>
.
</>
}
/>
</Grid>
<Grid item xs={12} md={6}>
<InfoCard title="What Now?">
<Typography variant="body1" gutterBottom>
You now have a running instance of Backstage!&nbsp;
<span role="img" aria-label="confetti">
🎉
</span>
&nbsp;Let's make sure you get the most out of this platform by
walking you through the basics.
</Typography>
<Typography variant="h6" gutterBottom>
The Setup
</Typography>
<Typography variant="body1" paragraph>
Backstage is put together from three base concepts: the core,
the app and the plugins.
</Typography>
<List>
<ListItem>
<ListItemText primary="The core is responsible for base functionality." />
</ListItem>
<ListItem>
<ListItemText primary="The app provides the base UI and connects the plugins." />
</ListItem>
<ListItem>
<ListItemText
primary="The plugins make Backstage useful for the end users with
specific views and functionality."
/>
</ListItem>
</List>
<Typography variant="h6" gutterBottom>
Build Your Plugins
</Typography>
<Typography variant="body1" paragraph>
We suggest you either check out the documentation for{' '}
<Link
href="https://github.com/backstage/backstage/blob/master/docs/plugins/create-a-plugin.md"
rel="noopener noreferrer"
>
creating a plugin
</Link>{' '}
or have a look in the code for the{' '}
<Link component={RouterLink} to="/explore">
existing plugins
</Link>{' '}
in the directory{' '}
<Link
href="https://github.com/backstage/backstage/tree/master/plugins"
rel="noopener noreferrer"
>
<code>plugins/</code>
</Link>
.
</Typography>
</InfoCard>
</Grid>
<Grid item>
<InfoCard title="Quick Links">
<List>
<ListItem>
<Link href="https://backstage.io">backstage.io</Link>
</ListItem>
<ListItem>
<Link
href="https://github.com/backstage/backstage/blob/master/docs/plugins/create-a-plugin.md"
rel="noopener noreferrer"
>
Create a plugin
</Link>
</ListItem>
<ListItem>
<Link href="/explore">Plugin gallery</Link>
</ListItem>
</List>
</InfoCard>
</Grid>
</Grid>
</Content>
</Page>
);
};
export default WelcomePage;