Merge branch 'marley/7641-export-ado-types' of https://github.com/marleypowell/backstage into marley/7641-export-ado-types

This commit is contained in:
Marley Powell
2021-10-19 10:15:37 +01:00
110 changed files with 4237 additions and 828 deletions
+5
View File
@@ -0,0 +1,5 @@
---
'@backstage/core-components': patch
---
Switched to relying on the built-in support for async loading in `react-syntax-highlighter`. This should provide further improvements to async rendering and lazy loading, and avoid test flakiness that was happening because of the significant number or resources being loaded in lazily all at once.
+5
View File
@@ -0,0 +1,5 @@
---
'@backstage/plugin-fossa': patch
---
Add `entitiesFilter` option to `FossaPage` to filter entities displayed in the table.
+5
View File
@@ -0,0 +1,5 @@
---
'@backstage/plugin-catalog-graph': patch
---
Capture analytics events for clicks in the graph.
+14
View File
@@ -0,0 +1,14 @@
---
'@backstage/create-app': minor
---
Removed `@backstage/plugin-welcome`, no new updates to the packages will be
published in the future.
The welcome plugin was used by early alpha versions of Backstage, but today only
contained a simple page with welcome instructions. It was superseded by
`@backstage/plugin-home` which can be used to build a homepage customized to the
needs of your organization.
If it's still used in your app, remove the dependency from your `package.json`
as well as left over code.
+5
View File
@@ -0,0 +1,5 @@
---
'@backstage/plugin-jenkins': patch
---
Sort Jenkins build by timestamp in `CITable`
+5
View File
@@ -0,0 +1,5 @@
---
'@backstage/plugin-git-release-manager': patch
---
Minor internal type improvement
@@ -0,0 +1,5 @@
---
'@backstage/plugin-techdocs': patch
---
Only replace the shadow dom if the content is changed to avoid a flickering UI.
+1 -1
View File
@@ -58,7 +58,7 @@ jobs:
run: lerna run --scope @backstage/core-* build
- name: test
run: yarn lerna -- run test --runInBand
run: yarn lerna -- run test
env:
BACKSTAGE_TEST_DISABLE_DOCKER: 1
+60 -60
View File
@@ -1,60 +1,60 @@
| Organization | Contact | Description of Use |
| ------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Spotify](https://www.spotify.com) | [@leemills83](https://github.com/leemills83) | Main interface towards all of Spotify's infrastructure and technical documentation. |
| [bol.com](https://www.bol.com) | [@sagacity](https://github.com/sagacity) | Initial work being done to unify platform tooling. |
| [DFDS](https://www.dfds.com) | [@carlsendk](https://github.com/carlsendk) | V2 self-service platform. |
| [Roadie](https://roadie.io) | [@dtuite](https://github.com/dtuite) | Hosted, managed Backstage with easy set-up |
| [Roku](https://www.roku.com) | [@timurista](https://github.com/timurista) | Initial work on Cloud engineering service platform. |
| [SDA SE](https://sda.se) | [@Fox32](https://github.com/Fox32) | Central place for developing and sharing services in our insurance ecosystem. |
| [H-E-B](https://www.heb.com) | [@german-j-rodriguez](https://github.com/german-j-rodriguez) | Initial work on Engineering Portal service platform. |
| [American Airlines](https://www.aa.com) | [@paulpach](https://github.com/paulpach) | Central place for developers to develop and maintain applications |
| [Kiwi.com](https://kiwi.com) | [@aexvir](https://github.com/aexvir) | Replacing the frontend of [The Zoo](https://github.com/kiwicom/the-zoo), their service registry. |
| [Voi](https://www.voiscooters.com/) | [@K-Phoen](https://github.com/K-Phoen) | Developer portal, main gateway to our infrastructure, documentation and internal tooling. |
| [Talkdesk](https://www.talkdesk.com) | [@jaime-talkdesk](https://github.com/jaime-talkdesk) | Initial work for Engineering Portal and Self Provisioning to R&D |
| [Wealthsimple](https://www.wealthsimple.com) | [@andrewthauer](https://github.com/andrewthauer) | Developer portal, service catalog, documentation and tooling |
| [Grab](https://www.grab.com) | [@althafh](https://github.com/althafh) | Initial work as a unified interface for all of Grab's internal tooling |
| [Telenor Sweden](https://www.telenor.se) | [@O5ten](https://github.com/O5ten) | Building a developer portal for scaffolding projects towards our unified build environment and microservice stacks |
| [Fiverr](https://www.fiverr.com) | [@nirga](https://github.com/nirga) | Unifying separate tools that developers are using today (i.e. monitoring, dead letter queues management, etc.) into a single platform. |
| [Zalando SE](https://www.zalando.de) | [@leviferreira](https://github.com/leviferreira) | Building V2 of the Internal Development Portal. |
| [LegalZoom](https://legalzoom.com) | [@backjo](https://github.com/backjo) | Developer portal - hub for all engineering projects and metadata. |
| [Expedia Group](https://www.expediagroup.com) | [Mike Turner](mailto:miturner@expediagroup.com), [Sneha Kumar](mailto:snkumar@expediagroup.com), [@guillermomanzo](https://github.com/guillermomanzo), [Erik Lindgren](https://github.com/lindgren) | EG Common Developer Toolkit |
| [Paddle.com](https://paddle.com) | [Ioannis Georgoulas](https://github.com/geototti21) | Developer portal (Tech Docs, Service Catalog, Internal Tooling), we use vanilla Backstage FE and custom BE implementation in Go |
| [Acast.com](https://acast.com) | [Olle Lundberg](https://github.com/lndbrg) | Developer portal with tech docs, service catalog and a bunch of other internal tooling |
| [Lunar](https://lunar.app) | [Jacob Valdemar](https://github.com/JacobValdemar) | Internal developer portal for service overview and insights, API documentation, technical guides, onboarding guides and RFC's. |
| [Trendyol](https://trendyol.com) | [Gamze Senturk](https://github.com/gmzsenturk), [Mert Can Bilgic](https://github.com/mertcb) | The Developer Portal has been called `Pandora`. Provides an overview of Trendyol tech ecosystem. TechDocs, Catalog, Custom Plugins and Theme. |
| [Peloton](https://www.onepeloton.com/) | [Jim Haughwout](https://github.com/JimHaughwout) | Creating our first developer portal and tech-docs. Exploring Service Catalog, Tech Insights and Cost Insights as well. |
| [TELUS](https://telus.com) | [Seb Barre](https://github.com/sbarre) | The Go-to place to find answers about development and delivery at TELUS. |
| [Brex](https://www.brex.com/) | [Vamsi Chitters](https://github.com/vamsikc) | A centralized UI to understand how a service fits in the whole Brex architecture and manage a teams engineering dependencies. |
| [Oriflame](https://www.oriflame.com/) | [Oriflame](https://github.com/oriflame) | Internal developer portal for services, single page apps and packages overview, API documentation, technical guides, tech-radar and more. |
| [Booz Allen Hamilton](https://www.boozallen.com/) | [Jason Miller](https://github.com/JasonMiller-BAH) | Developer portal for a full-stack software development ecosystem that accelerates consistent and repeatable Modern Software Development practices for internal innovation and investments. |
| [Netflix](https://www.netflix.com/) | [bleathem](https://github.com/bleathem) | Our Backstage implementation will be the front door to a unified experience connecting our internal platform products across important workflows with integrated knowledge and support. |
| [b.well](https://www.icanbwell.com/) | [Jacob Rosales](https://github.com/jrosales) | Foundation for our engineering portal and cloud insights. |
| [PagerDuty](https://www.pagerduty.com/) | [Mark Shaw](https://github.com/markshawtoronto) | Developer portal, initially focused on software templates and tech-docs. |
| [MoonShiner](https://moonshiner.at) | [Fabian Hippmann](https://github.com/FabianHippmann) | Developer portal - helps us keep track of our customer projects, onboard new developers & improve our development process 🌕🚀🧑‍🚀 |
| [FundApps](https://www.fundapps.co/) | [Elliot Greenwood](https://github.com/egnwd) | Developer Portal - A place for us to keep track of our projects and documentation for all services and processes |
| [DAZN](https://dazn.com/) | [Lou Bichard](https://twitter.com/loujaybee), [Marco Crivellaro](https://github.com/crivetechie), [Alex Hollerith](mailto:alex.hollerith@dazn.com) | Ingesting all of DAZN's repos for the catalog, migrating our internal platform apps (pull request boards, release information, inner source marketplace etc) to Backstage plugins (where applicable). |
| [HelloFresh](https://www.hellofresh.de/) | [@iammuho](https://github.com/iammuho), [@ElenaForester](https://github.com/ElenaForester), [@diegomarangoni](https://github.com/diegomarangoni) | Our developer portal at HelloFresh - Spread across an organisation of 500+ engineers globally. |
| [FactSet](https://www.factset.com/) | [@kuangp](https://github.com/kuangp) | Developer portal to provide discoverability to all internal components, APIs, documentation, and scaffold templates with integrations to our internal infrastructure tools. |
| [Workrise](https://www.workrise.com/) | [Michael Rode](https://github.com/michaelrode) | Developer portal, main gateway to our infrastructure, documentation and internal tooling. |
| [RedVentures](https://www.redventures.com/) | [Chris Diaz](https://github.com/codingdiaz) | Developer portal that brings everything an engineer needs to provide value into a single pane of glass. |
| [MavTek](https://www.mavtek.com/) | [@fgascon](https://github.com/fgascon) | Developer portal focused on standardizing practices, centralizing documentation and streamlining developer practices. |
| [QuintoAndar](https://www.quintoandar.com.br/) | [@quintoandar](https://github.com/quintoandar) | Developer portal, services catalog and centralization of service metrics. |
| [empathy.co](https://empathy.co/) | [@guillermotti](https://github.com/guillermotti) | Developer portal for tech docs, service catalog, plugin discovery and much more. |
| [creditas.com](https://creditas.com/) | [@aureliosaraiva](https://github.com/aureliosaraiva) [@Creditas](https://github.com/creditas) | Centralization of all services, standards, documentation, etc. We started the deployment process. |
| [Prisjakt](https://www.prisjakt.nu) / [PriceSpy](https://pricespy.co.uk) | [@kennylindahl](https://github.com/kennylindahl) | Internal developer portal - Documentation, scaffolding, software catalog, TechRadar, Gitlab org data integration |
| [Powerspike](https://powerspike.tv/) | [@trelore](https://github.com/trelore) | Developer portal for documentation of core libraries and repositories. |
| [2U](https://2u.com) | [Andrew Thal](https://github.com/athal7) | Development team home-base, promoting service discoverability, resource dependencies, and tech radar |
| [Taxfix](https://taxfix.de/) | [Sami Ur Rehman](https://github.com/samiurrehman92) | Developer's portal with software catalog at it's core. Hosts API Specs, Tech Docs, Tech Radar and some custom plugins. |
| [Busuu](https://busuu.com/) | [Adam Tester](https://github.com/adamtester) | Developer portal with service catalog, API docs, Event docs, service templating, and cost insights. |
| [Loadsmart](https://loadsmart.com/) | [Loadsmart](https://github.com/loadsmart) | Improve services visibility and operations for service owners and developers. |
| [Monzo](https://monzo.com/) | [@WillSewell](https://github.com/WillSewell), [@joechrisellis](https://github.com/joechrisellis) | Developer portal showing metadata and docs for over 2000 microservices. We have built a number of plugins such as a UI for our system to measure [software excellence](https://monzo.com/blog/2021/09/15/how-we-measure-software-excellence), and a UI to show deployment and config change events. |
| [Vaimo](https://www.vaimo.com) | [@vaimo-magnus](https://github.com/vaimo-magnus) | Developer Portal for our developers at Vaimo, currently docs and self-service towards our internal PaaS based on k8s. Plans to extend the catalog into Projects, Environments etc |
| [Wayfair](https://www.wayfair.com) | [@fransan](https://github.com/fransan), [@errskipower](https://github.com/errskipower), [@hrrs](https://github.com/hrrs) | Developer portal for service catalog, technical documentation, and APIs. |
| [CircleHD](https://www.circlehd.com) | [@circlehddev](https://github.com/circlehddev) | Developer Portal for internal dev team across the globe |
| [CastDesk](https://castdesk.com) | [@circlehddev](https://github.com/circlehddev) | Developer Portal for internal dev team across the globe |
| [Santagostino](https://santagostino.it) | [@santagostino](https://github.com/santagostino) | Developer portal, gateway to our infrastructure, documentation, service catalog and internal tooling. |
| [Peak](https://peak.ai) | [Luke Beamish](https://github.com/lukebeamish-peak) | Developer portal for all internal engineers to access documentation and tooling. |
| [Gelato](https://gelato.com/) | [Dmitry Makarenko](https://github.com/dmitry-makarenko-gelato) | Developer portal: documentation, service templates, org structure, service catalog, plugins for integration with internal and third-party systems🚀. |
| [GoCardless](https://gocardless.com/) | [James Turley](https://github.com/tragiclifestories) | Developer portal: documentation, service templates, org structure, service catalog, plugins for integration with internal systems. |
| [Box](https://www.box.com) | [@kielosz](https://github.com/kielosz), [@jluk-box](https://github.com/jluk-box), [@ptychu](https://github.com/ptychu), [@alexrybch](https://github.com/alexrybch), [@szubster](https://github.com/szubster) | Developer portal for service catalog, integration with internal systems, new service onboarding. |
| [Bazaarvoice](https://www.bazaarvoice.com) | [@niallmccullagh](https://github.com/niallmccullagh) | Developer portal for service catalog and scaffolds, publishing Github docs and API documentation, visualising our internal tech radar and our product engineering org structure. |
| Organization | Contact | Description of Use |
| ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Spotify](https://www.spotify.com) | [@leemills83](https://github.com/leemills83) | Main interface towards all of Spotify's infrastructure and technical documentation. |
| [bol.com](https://www.bol.com) | [@sagacity](https://github.com/sagacity) | Initial work being done to unify platform tooling. |
| [DFDS](https://www.dfds.com) | [@carlsendk](https://github.com/carlsendk) | V2 self-service platform. |
| [Roadie](https://roadie.io) | [@dtuite](https://github.com/dtuite) | Hosted, managed Backstage with easy set-up |
| [Roku](https://www.roku.com) | [@timurista](https://github.com/timurista) | Initial work on Cloud engineering service platform. |
| [SDA SE](https://sda.se) | [@Fox32](https://github.com/Fox32) | Central place for developing and sharing services in our insurance ecosystem. |
| [H-E-B](https://www.heb.com) | [@german-j-rodriguez](https://github.com/german-j-rodriguez) | Initial work on Engineering Portal service platform. |
| [American Airlines](https://www.aa.com) | [@paulpach](https://github.com/paulpach) | Central place for developers to develop and maintain applications |
| [Kiwi.com](https://kiwi.com) | [@aexvir](https://github.com/aexvir) | Replacing the frontend of [The Zoo](https://github.com/kiwicom/the-zoo), their service registry. |
| [Voi](https://www.voiscooters.com/) | [@K-Phoen](https://github.com/K-Phoen) | Developer portal, main gateway to our infrastructure, documentation and internal tooling. |
| [Talkdesk](https://www.talkdesk.com) | [@jaime-talkdesk](https://github.com/jaime-talkdesk) | Initial work for Engineering Portal and Self Provisioning to R&D |
| [Wealthsimple](https://www.wealthsimple.com) | [@andrewthauer](https://github.com/andrewthauer) | Developer portal, service catalog, documentation and tooling |
| [Grab](https://www.grab.com) | [@althafh](https://github.com/althafh) | Initial work as a unified interface for all of Grab's internal tooling |
| [Telenor Sweden](https://www.telenor.se) | [@O5ten](https://github.com/O5ten) | Building a developer portal for scaffolding projects towards our unified build environment and microservice stacks |
| [Fiverr](https://www.fiverr.com) | [@nirga](https://github.com/nirga) | Unifying separate tools that developers are using today (i.e. monitoring, dead letter queues management, etc.) into a single platform. |
| [Zalando SE](https://www.zalando.de) | [@leviferreira](https://github.com/leviferreira) | Building V2 of the Internal Development Portal. |
| [LegalZoom](https://legalzoom.com) | [@backjo](https://github.com/backjo) | Developer portal - hub for all engineering projects and metadata. |
| [Expedia Group](https://www.expediagroup.com) | [Mike Turner](mailto:miturner@expediagroup.com), [Sneha Kumar](mailto:snkumar@expediagroup.com), [@guillermomanzo](https://github.com/guillermomanzo), [Erik Lindgren](https://github.com/lindgren) | EG Common Developer Toolkit |
| [Paddle.com](https://paddle.com) | [Ioannis Georgoulas](https://github.com/geototti21) | Developer portal (Tech Docs, Service Catalog, Internal Tooling), we use vanilla Backstage FE and custom BE implementation in Go |
| [Acast.com](https://acast.com) | [Olle Lundberg](https://github.com/lndbrg) | Developer portal with tech docs, service catalog and a bunch of other internal tooling |
| [Lunar](https://lunar.app) | [Jacob Valdemar](https://github.com/JacobValdemar) | Internal developer portal for service overview and insights, API documentation, technical guides, onboarding guides and RFC's. |
| [Trendyol](https://trendyol.com) | [Gamze Senturk](https://github.com/gmzsenturk), [Mert Can Bilgic](https://github.com/mertcb) | The Developer Portal has been called `Pandora`. Provides an overview of Trendyol tech ecosystem. TechDocs, Catalog, Custom Plugins and Theme. |
| [Peloton](https://www.onepeloton.com/) | [Jim Haughwout](https://github.com/JimHaughwout) | Creating our first developer portal and tech-docs. Exploring Service Catalog, Tech Insights and Cost Insights as well. |
| [TELUS](https://telus.com) | [Seb Barre](https://github.com/sbarre) | The Go-to place to find answers about development and delivery at TELUS. |
| [Brex](https://www.brex.com/) | [Vamsi Chitters](https://github.com/vamsikc) | A centralized UI to understand how a service fits in the whole Brex architecture and manage a teams engineering dependencies. |
| [Oriflame](https://www.oriflame.com/) | [Oriflame](https://github.com/oriflame) | Internal developer portal for services, single page apps and packages overview, API documentation, technical guides, tech-radar and more. |
| [Booz Allen Hamilton](https://www.boozallen.com/) | [Jason Miller](https://github.com/JasonMiller-BAH) | Developer portal for a full-stack software development ecosystem that accelerates consistent and repeatable Modern Software Development practices for internal innovation and investments. |
| [Netflix](https://www.netflix.com/) | [bleathem](https://github.com/bleathem) | Our Backstage implementation will be the front door to a unified experience connecting our internal platform products across important workflows with integrated knowledge and support. |
| [b.well](https://www.icanbwell.com/) | [Jacob Rosales](https://github.com/jrosales) | Foundation for our engineering portal and cloud insights. |
| [PagerDuty](https://www.pagerduty.com/) | [Mark Shaw](https://github.com/markshawtoronto) | Developer portal, initially focused on software templates and tech-docs. |
| [MoonShiner](https://moonshiner.at) | [Fabian Hippmann](https://github.com/FabianHippmann) | Developer portal - helps us keep track of our customer projects, onboard new developers & improve our development process 🌕🚀🧑‍🚀 |
| [FundApps](https://www.fundapps.co/) | [Elliot Greenwood](https://github.com/egnwd) | Developer Portal - A place for us to keep track of our projects and documentation for all services and processes |
| [DAZN](https://dazn.com/) | [Lou Bichard](https://twitter.com/loujaybee), [Marco Crivellaro](https://github.com/crivetechie), [Alex Hollerith](mailto:alex.hollerith@dazn.com) | Ingesting all of DAZN's repos for the catalog, migrating our internal platform apps (pull request boards, release information, inner source marketplace etc) to Backstage plugins (where applicable). |
| [HelloFresh](https://www.hellofresh.de/) | [@iammuho](https://github.com/iammuho), [@ElenaForester](https://github.com/ElenaForester), [@diegomarangoni](https://github.com/diegomarangoni) | Our developer portal at HelloFresh - Spread across an organisation of 500+ engineers globally. |
| [FactSet](https://www.factset.com/) | [@kuangp](https://github.com/kuangp) | Developer portal to provide discoverability to all internal components, APIs, documentation, and scaffold templates with integrations to our internal infrastructure tools. |
| [Workrise](https://www.workrise.com/) | [Michael Rode](https://github.com/michaelrode) | Developer portal, main gateway to our infrastructure, documentation and internal tooling. |
| [RedVentures](https://www.redventures.com/) | [Chris Diaz](https://github.com/codingdiaz) | Developer portal that brings everything an engineer needs to provide value into a single pane of glass. |
| [MavTek](https://www.mavtek.com/) | [@fgascon](https://github.com/fgascon) | Developer portal focused on standardizing practices, centralizing documentation and streamlining developer practices. |
| [QuintoAndar](https://www.quintoandar.com.br/) | [@quintoandar](https://github.com/quintoandar) | Developer portal, services catalog and centralization of service metrics. |
| [empathy.co](https://empathy.co/) | [@guillermotti](https://github.com/guillermotti) | Developer portal for tech docs, service catalog, plugin discovery and much more. |
| [creditas.com](https://creditas.com/) | [@aureliosaraiva](https://github.com/aureliosaraiva) [@Creditas](https://github.com/creditas) | Centralization of all services, standards, documentation, etc. We started the deployment process. |
| [Prisjakt](https://www.prisjakt.nu) / [PriceSpy](https://pricespy.co.uk) | [@kennylindahl](https://github.com/kennylindahl) | Internal developer portal - Documentation, scaffolding, software catalog, TechRadar, Gitlab org data integration |
| [Powerspike](https://powerspike.tv/) | [@trelore](https://github.com/trelore) | Developer portal for documentation of core libraries and repositories. |
| [2U](https://2u.com) | [Andrew Thal](https://github.com/athal7) | Development team home-base, promoting service discoverability, resource dependencies, and tech radar |
| [Taxfix](https://taxfix.de/) | [Sami Ur Rehman](https://github.com/samiurrehman92) | Developer's portal with software catalog at it's core. Hosts API Specs, Tech Docs, Tech Radar and some custom plugins. |
| [Busuu](https://busuu.com/) | [Adam Tester](https://github.com/adamtester) | Developer portal with service catalog, API docs, Event docs, service templating, and cost insights. |
| [Loadsmart](https://loadsmart.com/) | [Loadsmart](https://github.com/loadsmart) | Improve services visibility and operations for service owners and developers. |
| [Monzo](https://monzo.com/) | [@WillSewell](https://github.com/WillSewell), [@joechrisellis](https://github.com/joechrisellis) | Developer portal showing metadata and docs for over 2000 microservices. We have built a number of plugins such as a UI for our system to measure [software excellence](https://monzo.com/blog/2021/09/15/how-we-measure-software-excellence), and a UI to show deployment and config change events. |
| [Vaimo](https://www.vaimo.com) | [@vaimo-magnus](https://github.com/vaimo-magnus) | Developer Portal for our developers at Vaimo, currently docs and self-service towards our internal PaaS based on k8s. Plans to extend the catalog into Projects, Environments etc |
| [Wayfair](https://www.wayfair.com) | [@fransan](https://github.com/fransan), [@errskipower](https://github.com/errskipower), [@hrrs](https://github.com/hrrs) | Developer portal for service catalog, technical documentation, and APIs. |
| [CircleHD](https://www.circlehd.com) | [@circlehddev](https://github.com/circlehddev) | Developer Portal for internal dev team across the globe |
| [CastDesk](https://castdesk.com) | [@circlehddev](https://github.com/circlehddev) | Developer Portal for internal dev team across the globe |
| [Santagostino](https://santagostino.it) | [@santagostino](https://github.com/santagostino) | Developer portal, gateway to our infrastructure, documentation, service catalog and internal tooling. |
| [Peak](https://peak.ai) | [Luke Beamish](https://github.com/lukebeamish-peak) | Developer portal for all internal engineers to access documentation and tooling. |
| [Gelato](https://gelato.com/) | [Dmitry Makarenko](https://github.com/dmitry-makarenko-gelato) | Developer portal: documentation, service templates, org structure, service catalog, plugins for integration with internal and third-party systems🚀. |
| [GoCardless](https://gocardless.com/) | [James Turley](https://github.com/tragiclifestories) | Developer portal: documentation, service templates, org structure, service catalog, plugins for integration with internal systems. |
| [Box](https://www.box.com) | [@kielosz](https://github.com/kielosz), [@jluk-box](https://github.com/jluk-box), [@ptychu](https://github.com/ptychu), [@alexrybch](https://github.com/alexrybch), [@szubster](https://github.com/szubster) | Developer portal for service catalog, integration with internal systems, new service onboarding. |
| [Bazaarvoice](https://www.bazaarvoice.com) | [@niallmccullagh](https://github.com/niallmccullagh) | Developer portal for service catalog and scaffolds, publishing Github docs and API documentation, visualising our internal tech radar and our product engineering org structure. |
@@ -47,5 +47,5 @@ sentry:
organization: {{ .Values.appConfig.sentry.organization | quote }}
techdocs:
generators:
techdocs: 'local'
generator:
runIn: 'local'
@@ -32,7 +32,7 @@ spec:
ports:
- containerPort: {{ .Values.frontend.containerPort }}
resources:
{{- toYaml .Values.backend.resources | nindent 12 }}
{{- toYaml .Values.frontend.resources | nindent 12 }}
envFrom:
- configMapRef:
name: {{ include "backstage.fullname" . }}-app-env
+8 -8
View File
@@ -47,18 +47,18 @@ const app = createApp({
## How to index TechDocs documents
The techdocs-plugin has supported integrations to Search, meaning that it
The TechDocs plugin has supported integrations to Search, meaning that it
provides a default collator ready to be used.
The purpose of this how-to guide is to walk you through how to register the
The purpose of this guide is to walk you through how to register the
[DefaultTechDocsCollator](https://github.com/backstage/backstage/blob/master/plugins/techdocs-backend/src/search/DefaultTechDocsCollator.ts)
in your App in two steps, so that you can get TechDocs documents indexed.
in your App, so that you can get TechDocs documents indexed.
If you have been through the
[getting started guide](https://backstage.io/docs/features/search/getting-started)
already, you should have the `packages/backend/src/plugins/search.ts` file
available. If you have that, you can jump to the first step of this guide, if
not - start by go through the getting started guide.
[Getting Started with Search guide](https://backstage.io/docs/features/search/getting-started),
you should have the `packages/backend/src/plugins/search.ts` file available. If
so, you can go ahead and follow this guide - if not, start by going through the
getting started guide.
1. Import the DefaultTechDocsCollator from `@backstage/plugin-techdocs-backend`.
@@ -82,7 +82,7 @@ You should now have your TechDocs documents indexed to your search engine of
choice!
If you want your users to be able to filter down to the techdocs type when
searching. You can update your `SearchPage.tsx` file in
searching, you can update your `SearchPage.tsx` file in
`packages/app/src/components/search` by adding `techdocs` to the list of values
of the `SearchType` component.
@@ -5,11 +5,12 @@ sidebar_label: Creating and Publishing Documentation
description: Guidance on how to create and publish documentation
---
This section will guide you through:
This section will guide you through how to:
- [Create a basic documentation setup](#create-a-basic-documentation-setup)
- [Use any software template](#use-any-software-template)
- [Use the documentation template](#use-the-documentation-template)
- [Manually add documentation setup to already existing repository](#manually-add-documentation-setup-to-already-existing-repository)
- [Enable documentation for an already existing entity](#enable-documentation-for-an-already-existing-entity)
- [Writing and previewing your documentation](#writing-and-previewing-your-documentation)
## Prerequisites
@@ -21,29 +22,47 @@ This section will guide you through:
If you have an existing repository that you'd like to add documentation to, skip
to the
[Manually add documentation setup](#manually-add-documentation-setup-to-already-existing-repository)
section below. Otherwise, continue reading to start a documentation repo from
scratch.
[Enable documentation for an already existing entity setup](#enable-documentation-for-an-already-existing-entity)
section below. Otherwise, continue reading to create a new software entity
including documentation from scratch.
### Use any software template
TechDocs is built on top of the
[docs like code approach](https://www.docslikecode.com/about/). This, in short,
means that you should keep documentation close to the code.
Your Backstage app has a set of software templates added by default. All of
these software templates include everything you need to get your TechDocs site
up and running and to start writing your documentation.
If you have created software templates that do not include documentation by
default, we highly recommend you to set that up. Follow our how-to guide
[How to add documentation setup to your software templates](./how-to-guides.md#how-to-add-documentation-setup-to-your-software-templates)
to get started.
### Use the documentation template
Your working Backstage instance should by default have a documentation template
added. If not, copy the catalog locations from the
There could be _some_ situations where you don't want to keep your docs close to
your code, but still want to publish documentation - for example, an onboarding
tutorial. For this use case, we have put together a documentation template. Your
Backstage instance should by default have a documentation template added. If
not, copy the catalog locations from the
[create-app template](https://github.com/backstage/backstage/blob/master/packages/create-app/templates/default-app/app-config.yaml.hbs)
to add the documentation template. The template creates a component with only
TechDocs configuration and default markdown files as below mentioned in manual
documentation setup, and is otherwise empty.
to add the documentation template. The template creates a component with
**only** TechDocs configuration and default markdown files, and is otherwise
empty.
![Documentation Template](../../assets/techdocs/documentation-template.png)
Create an entity from the documentation template and you will get the needed
setup for free.
### Manually add documentation setup to already existing repository
### Enable documentation for an already existing entity
Prerequisites:
- An existing component
- An existing entity
[registered in backstage](../software-catalog/index.md#adding-components-to-the-catalog)
(e.g. via a `catalog-info.yaml` file).
@@ -72,11 +91,11 @@ metadata:
The
[`backstage.io/techdocs-ref` annotation](../software-catalog/well-known-annotations.md#backstageiotechdocs-ref)
is used by TechDocs to download the documentation source files for generating an
Entity's TechDocs site.
entity's TechDocs site.
Create a `/docs` folder in the root of the project with at least an `index.md`
file. _(If you add more markdown files, make sure to update the nav in the
mkdocs.yml file to get a proper navigation for your documentation.)_
Create a `/docs` folder in the root of your repository with at least an
`index.md` file in it. _(If you add more markdown files, make sure to update the
nav in the mkdocs.yml file to get a proper navigation for your documentation.)_
> Note - Although `docs` is a popular directory name for storing documentation,
> it can be renamed to something else and can be configured by `mkdocs.yml`. See
@@ -95,9 +114,10 @@ updated documentation next time you run Backstage!
## Writing and previewing your documentation
Using the `techdocs-cli` you can preview your docs inside a local Backstage
instance and get live reload on changes. This is useful when you want to preview
your documentation while writing.
Using the [techdocs-cli](https://github.com/backstage/techdocs-cli) you can
preview your docs inside a local Backstage instance and get live reload on
changes. This is useful when you want to preview your documentation while
writing.
To do this you can run:
+72
View File
@@ -348,3 +348,75 @@ const app = createApp({
],
});
```
## How to add the documentation setup to your software templates
[Software Templates](https://backstage.io/docs/features/software-templates/software-templates-index)
in Backstage is a tool that can help your users to create new components out of
already configured templates. It comes with a set of default templates to use,
but you can also
[add your own templates](https://backstage.io/docs/features/software-templates/adding-templates).
If you have your own templates set up, we highly recommend that you include the
required setup for TechDocs in those templates. When creating a new component,
your users will then get a TechDocs site up and running automatically, ready for
them to start writing technical documentation.
The purpose of this how-to guide is to walk you through how to add the required
configuration and some default markdown files to your new template. You can use
the
[react-ssr-template](https://github.com/backstage/software-templates/tree/main/scaffolder-templates/react-ssr-template)
as a reference when walking through the steps.
Prerequisites:
- An existing software template including a `template.yaml` together with a
skeleton folder including at least a `catalog-info.yaml`.
1. Update your component's entity description by adding the following lines to
the `catalog-info.yaml` in your skeleton folder.
```yaml
annotations:
backstage.io/techdocs-ref: dir:.
```
The
[`backstage.io/techdocs-ref` annotation](../software-catalog/well-known-annotations.md#backstageiotechdocs-ref)
is used by TechDocs to download the documentation source files for generating an
entity's TechDocs site.
2. Create an `mkdocs.yml` file in the root of your skeleton folder with the
following content:
```yaml
site_name: ${{values.component_id}}
site_description: ${{values.description}}
nav:
- Introduction: index.md
plugins:
- techdocs-core
```
3. Create a `/docs` folder in the skeleton folder with at least an `index.md`
file in it.
The `docs/index.md` can for example have the following content:
```md
# ${{ values.component_id }}
${{ values.description }}
## Getting started
Start writing your documentation by adding more markdown (.md) files to this
folder (/docs) or replace the content in this file.
```
> Note: The values of `site_name`, `component_id` and `site_description` depends
> on how you have configured your `template.yaml`
Done! You now have support for TechDocs in your own software template!
+1 -1
View File
@@ -96,7 +96,7 @@ yarn start # Start serving the example app, use --check to include type checks a
yarn storybook # Start local storybook, useful for working on components in @backstage/core-components
yarn workspace @backstage/plugin-welcome start # Serve welcome plugin only, also supports --check
yarn workspace @backstage/plugin-api-docs start # Serve api-docs plugin only, also supports --check
yarn tsc # Run typecheck, use --watch for watch mode
yarn tsc:full # Run full type checking, for example without skipLibCheck, use in CI
+1 -1
View File
@@ -287,7 +287,7 @@ describe('SomeComponent', () => {
await waitFor(() => {
expect(apiSpy.getEvents()[0]).toMatchObject({
action: 'expected action',
subject: 'expected subject'',
subject: 'expected subject',
attributes: {
foo: 'bar',
},
+1 -1
View File
@@ -1,7 +1,7 @@
---
title: GKE Usage
author: BESTSELLER
authorUrl: bestsellerit.com
authorUrl: https://bestsellerit.com
category: Discovery
description: This plugin will show you the cost and resource usage of your application within Google Kubernetes Engine (GKE).
documentation: https://github.com/BESTSELLER/backstage-plugin-gkeusage/blob/master/README.md
+1 -1
View File
@@ -1,7 +1,7 @@
---
title: Harbor
author: BESTSELLER
authorUrl: bestsellerit.com
authorUrl: https://bestsellerit.com
category: Discovery
description: This plugin will show you information about Docker images within the Harbor cloud native registry.
documentation: https://github.com/BESTSELLER/backstage-plugin-harbor/blob/master/README.md
+2 -2
View File
@@ -56,14 +56,14 @@
"react-dom": "^16.12.0",
"react-helmet": "6.1.0",
"react-hook-form": "^7.12.2",
"react-markdown": "^5.0.2",
"react-markdown": "^7.0.1",
"react-router": "6.0.0-beta.0",
"react-router-dom": "6.0.0-beta.0",
"react-sparklines": "^1.7.0",
"react-syntax-highlighter": "^15.4.3",
"react-text-truncate": "^0.16.0",
"react-use": "^17.2.4",
"remark-gfm": "^1.0.0",
"remark-gfm": "^2.0.0",
"zen-observable": "^0.8.15"
},
"devDependencies": {
@@ -31,6 +31,12 @@ const minProps = {
};
describe('<CodeSnippet />', () => {
// react-syntax-highlighter is large and can cause significant slowdowns
// This test makes sure we're loading things in asynchronously and not too broadly.
it('renders quickly', async () => {
await renderInTestApp(<CodeSnippet text="" language="javascript" />);
}, 1000);
it('renders text without exploding', async () => {
const { getByText } = await renderInTestApp(<CodeSnippet {...minProps} />);
expect(getByText(/"Hello"/)).toBeInTheDocument();
@@ -14,56 +14,13 @@
* limitations under the License.
*/
import React, { lazy, Suspense } from 'react';
import React from 'react';
import { useTheme } from '@material-ui/core/styles';
import { BackstageTheme } from '@backstage/theme';
import { CopyTextButton } from '../CopyTextButton';
import { Progress } from '../Progress';
const LazySyntaxHighlighter = lazy(async () => {
const [{ default: SyntaxHighlighter }, { docco, dark }] = await Promise.all([
import('react-syntax-highlighter'),
import('react-syntax-highlighter/dist/cjs/styles/hljs'),
]);
function LazyHighlighter(props: CodeSnippetProps) {
const {
text,
language,
showLineNumbers = false,
highlightedNumbers,
customStyle,
} = props;
const theme = useTheme<BackstageTheme>();
const mode = theme.palette.type === 'dark' ? dark : docco;
const highlightColor =
theme.palette.type === 'dark' ? '#256bf3' : '#e6ffed';
return (
<SyntaxHighlighter
customStyle={customStyle}
language={language}
style={mode}
showLineNumbers={showLineNumbers}
wrapLines
lineNumberStyle={{ color: theme.palette.textVerySubtle }}
lineProps={(lineNumber: number) =>
highlightedNumbers?.includes(lineNumber)
? {
style: {
backgroundColor: highlightColor,
},
}
: {}
}
>
{text}
</SyntaxHighlighter>
);
}
return { default: LazyHighlighter };
});
import { LightAsync } from 'react-syntax-highlighter';
import dark from 'react-syntax-highlighter/dist/esm/styles/hljs/dark';
import docco from 'react-syntax-highlighter/dist/esm/styles/hljs/docco';
/**
* Properties for {@link CodeSnippet}
@@ -112,12 +69,39 @@ export interface CodeSnippetProps {
* providing consistent theming and copy code button
*/
export function CodeSnippet(props: CodeSnippetProps) {
const { text, showCopyCodeButton = false } = props;
const {
text,
language,
showLineNumbers = false,
highlightedNumbers,
customStyle,
showCopyCodeButton = false,
} = props;
const theme = useTheme<BackstageTheme>();
const mode = theme.palette.type === 'dark' ? dark : docco;
const highlightColor = theme.palette.type === 'dark' ? '#256bf3' : '#e6ffed';
return (
<div style={{ position: 'relative' }}>
<Suspense fallback={<Progress />}>
<LazySyntaxHighlighter {...props} />
</Suspense>
<LightAsync
customStyle={customStyle}
language={language}
style={mode}
showLineNumbers={showLineNumbers}
wrapLines
lineNumberStyle={{ color: theme.palette.textVerySubtle }}
lineProps={(lineNumber: number) =>
highlightedNumbers?.includes(lineNumber)
? {
style: {
backgroundColor: highlightColor,
},
}
: {}
}
>
{text}
</LightAsync>
{showCopyCodeButton && (
<div style={{ position: 'absolute', top: 0, right: 0 }}>
<CopyTextButton text={text} />
@@ -52,14 +52,14 @@ describe('<MarkdownContent />', () => {
it('render MarkdownContent component with CodeSnippet for code blocks', async () => {
const rendered = await renderWithEffects(
wrapInTestApp(<MarkdownContent content=" jest(test: string);" />),
wrapInTestApp(
<MarkdownContent content={'```typescript\njest(test: string);\n```'} />,
),
);
const fp1 = rendered.getByText('jest', { selector: 'span' });
const fp1 = await rendered.findByText('jest(test:', { selector: 'span' });
expect(fp1).toBeInTheDocument();
expect(fp1.className).toEqual('hljs-function');
const fp2 = rendered.getByText('(test: string)', { selector: 'span' });
const fp2 = rendered.getByText('string', { selector: 'span' });
expect(fp2).toBeInTheDocument();
expect(fp2.className).toEqual('hljs-function');
expect(rendered.getByText(';', { selector: 'span' })).toBeInTheDocument();
expect(rendered.getByText(');', { selector: 'span' })).toBeInTheDocument();
});
});
@@ -15,7 +15,7 @@
*/
import { makeStyles } from '@material-ui/core/styles';
import ReactMarkdown from 'react-markdown';
import ReactMarkdown, { Options } from 'react-markdown';
import gfm from 'remark-gfm';
import React from 'react';
import { BackstageTheme } from '@backstage/theme';
@@ -69,9 +69,17 @@ type Props = {
dialect?: 'gfm' | 'common-mark';
};
const renderers = {
code: ({ language, value }: { language: string; value?: string }) => {
return <CodeSnippet language={language} text={value ?? ''} />;
const components: Options['components'] = {
code: ({ inline, className, children, ...props }) => {
const text = String(children).replace(/\n+$/, '');
const match = /language-(\w+)/.exec(className || '');
return !inline && match ? (
<CodeSnippet language={match[1]} text={text} />
) : (
<code className={className} {...props}>
{children}
</code>
);
},
};
@@ -86,10 +94,10 @@ export function MarkdownContent(props: Props) {
const classes = useStyles();
return (
<ReactMarkdown
plugins={dialect === 'gfm' ? [gfm] : []}
remarkPlugins={dialect === 'gfm' ? [gfm] : []}
className={classes.markdown}
children={content}
renderers={renderers}
components={components}
/>
);
}
+1 -1
View File
@@ -256,7 +256,7 @@ export class TechdocsGenerator implements GeneratorBase {
config: Config;
scmIntegrations: ScmIntegrationRegistry;
});
static readonly defaultDockerImage = 'spotify/techdocs:v0.3.3';
static readonly defaultDockerImage = 'spotify/techdocs:v0.3.4';
// (undocumented)
static fromConfig(
config: Config,
@@ -42,7 +42,7 @@ export class TechdocsGenerator implements GeneratorBase {
* The default docker image (and version) used to generate content. Public
* and static so that techdocs-common consumers can use the same version.
*/
public static readonly defaultDockerImage = 'spotify/techdocs:v0.3.3';
public static readonly defaultDockerImage = 'spotify/techdocs:v0.3.4';
private readonly logger: Logger;
private readonly containerRunner: ContainerRunner;
private readonly options: GeneratorConfig;
+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;
};

Some files were not shown because too many files have changed in this diff Show More