Merge branch 'master' of github.com:backstage/backstage into feat/scaff-logs
* 'master' of github.com:backstage/backstage: (1292 commits)
chore: Fixing prettier formatting
Create six-experts-destroy.md
Add config schema for Bitbucket scaffolder
bug: use the legacy version of graphiql on master right now until we port to app routes
Revert "build(deps): bump jose from 1.27.1 to 3.2.0"
docs: show how to assign annotations to primitive array item types in config schema
changesets: add cli build extension fix
cli: use same extension for chunks as for the main built file
Create swift-ears-fetch.md
[ImgBot] Optimize images
Add missing IncludeSecret type
Update .changeset/friendly-numbers-accept.md
Use bitbucket as location identifier instead of bitbucket/api
Add documentation for config $include
Use msw for mocking external Bitbucket apis
Remove the dependency from the catalog plugin to techdocs
Added changeset for config $include
Add deprecation notice to $data
Config: Add $include which replaces $data and can include any value
chore: bump to the latest and hope that it works 🤞
...
This commit is contained in:
@@ -0,0 +1,181 @@
|
||||
# @backstage/plugin-scaffolder
|
||||
|
||||
## 0.3.5
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 19554f6d6: Added Github Actions for Create React App, and allow better imports of files inside a module when they're exposed using `files` in `package.json`
|
||||
- Updated dependencies [1dc445e89]
|
||||
- Updated dependencies [342270e4d]
|
||||
- @backstage/core@0.4.2
|
||||
- @backstage/plugin-catalog@0.2.8
|
||||
|
||||
## 0.3.4
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [c911061b7]
|
||||
- Updated dependencies [8ef71ed32]
|
||||
- Updated dependencies [0e6298f7e]
|
||||
- Updated dependencies [ac3560b42]
|
||||
- @backstage/catalog-model@0.6.0
|
||||
- @backstage/core@0.4.1
|
||||
- @backstage/plugin-catalog@0.2.7
|
||||
|
||||
## 0.3.3
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [2527628e1]
|
||||
- Updated dependencies [6011b7d3e]
|
||||
- Updated dependencies [1c69d4716]
|
||||
- Updated dependencies [83b6e0c1f]
|
||||
- Updated dependencies [1665ae8bb]
|
||||
- Updated dependencies [04f26f88d]
|
||||
- Updated dependencies [ff243ce96]
|
||||
- @backstage/core@0.4.0
|
||||
- @backstage/plugin-catalog@0.2.6
|
||||
- @backstage/catalog-model@0.5.0
|
||||
- @backstage/theme@0.2.2
|
||||
|
||||
## 0.3.2
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- a9fd599f7: Add Analyze location endpoint to catalog backend. Add catalog-import plugin and replace import-component with it. To start using Analyze location endpoint, you have add it to the `createRouter` function options in the `\backstage\packages\backend\src\plugins\catalog.ts` file:
|
||||
|
||||
```ts
|
||||
export default async function createPlugin(env: PluginEnvironment) {
|
||||
const builder = new CatalogBuilder(env);
|
||||
const {
|
||||
entitiesCatalog,
|
||||
locationsCatalog,
|
||||
higherOrderOperation,
|
||||
locationAnalyzer, //<--
|
||||
} = await builder.build();
|
||||
|
||||
return await createRouter({
|
||||
entitiesCatalog,
|
||||
locationsCatalog,
|
||||
higherOrderOperation,
|
||||
locationAnalyzer, //<--
|
||||
logger: env.logger,
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
- Updated dependencies [08835a61d]
|
||||
- Updated dependencies [a9fd599f7]
|
||||
- Updated dependencies [bcc211a08]
|
||||
- Updated dependencies [ebf37bbae]
|
||||
- @backstage/catalog-model@0.4.0
|
||||
- @backstage/plugin-catalog@0.2.5
|
||||
|
||||
## 0.3.1
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- ef2831dde: Move constructing the catalog-info.yaml URL for scaffolded components to the publishers
|
||||
- Updated dependencies [475fc0aaa]
|
||||
- Updated dependencies [1166fcc36]
|
||||
- Updated dependencies [1185919f3]
|
||||
- @backstage/core@0.3.2
|
||||
- @backstage/catalog-model@0.3.0
|
||||
- @backstage/plugin-catalog@0.2.3
|
||||
|
||||
## 0.3.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- 59166e5ec: `createRouter` of scaffolder backend will now require additional option as `entityClient` which could be generated by `CatalogEntityClient` in `plugin-scaffolder-backend` package. Here is example to generate `entityClient`.
|
||||
|
||||
```js
|
||||
import { CatalogEntityClient } from '@backstage/plugin-scaffolder-backend';
|
||||
import { SingleHostDiscovery } from '@backstage/backend-common';
|
||||
|
||||
const discovery = SingleHostDiscovery.fromConfig(config);
|
||||
const entityClient = new CatalogEntityClient({ discovery });
|
||||
```
|
||||
|
||||
- Scaffolder's API `/v1/jobs` will accept `templateName` instead of `template` Entity.
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [7b37d65fd]
|
||||
- Updated dependencies [4aca74e08]
|
||||
- Updated dependencies [e8f69ba93]
|
||||
- Updated dependencies [0c0798f08]
|
||||
- Updated dependencies [0c0798f08]
|
||||
- Updated dependencies [199237d2f]
|
||||
- Updated dependencies [6627b626f]
|
||||
- Updated dependencies [4577e377b]
|
||||
- Updated dependencies [2d0bd1be7]
|
||||
- @backstage/core@0.3.0
|
||||
- @backstage/theme@0.2.1
|
||||
- @backstage/plugin-catalog@0.2.1
|
||||
|
||||
## 0.2.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- 28edd7d29: Create backend plugin through CLI
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- fb74f1db6: Make title meaningful after component creation
|
||||
|
||||
Fixes #2458.
|
||||
|
||||
After the change, the UX should look like this:
|
||||
|
||||
### If the component creation was successful:
|
||||
|
||||

|
||||
|
||||
### If the component creation failed:
|
||||
|
||||

|
||||
|
||||
- c5ef12926: fix the accordion details design when job stage fail
|
||||
- 1c8c43756: The new `scaffolder.github.baseUrl` config property allows to specify a custom base url for GitHub Enterprise instances
|
||||
- Updated dependencies [28edd7d29]
|
||||
- Updated dependencies [819a70229]
|
||||
- Updated dependencies [3a4236570]
|
||||
- Updated dependencies [ae5983387]
|
||||
- Updated dependencies [0d4459c08]
|
||||
- Updated dependencies [482b6313d]
|
||||
- Updated dependencies [e0be86b6f]
|
||||
- Updated dependencies [f70a52868]
|
||||
- Updated dependencies [12b5fe940]
|
||||
- Updated dependencies [368fd8243]
|
||||
- Updated dependencies [1c60f716e]
|
||||
- Updated dependencies [144c66d50]
|
||||
- Updated dependencies [a768a07fb]
|
||||
- Updated dependencies [b79017fd3]
|
||||
- Updated dependencies [6d97d2d6f]
|
||||
- Updated dependencies [5adfc005e]
|
||||
- Updated dependencies [f0aa01bcc]
|
||||
- Updated dependencies [0aecfded0]
|
||||
- Updated dependencies [93a3fa3ae]
|
||||
- Updated dependencies [782f3b354]
|
||||
- Updated dependencies [8b9c8196f]
|
||||
- Updated dependencies [2713f28f4]
|
||||
- Updated dependencies [406015b0d]
|
||||
- Updated dependencies [82759d3e4]
|
||||
- Updated dependencies [60d40892c]
|
||||
- Updated dependencies [ac8d5d5c7]
|
||||
- Updated dependencies [2ebcfac8d]
|
||||
- Updated dependencies [fa56f4615]
|
||||
- Updated dependencies [ebca83d48]
|
||||
- Updated dependencies [aca79334f]
|
||||
- Updated dependencies [c0d5242a0]
|
||||
- Updated dependencies [b3d57961c]
|
||||
- Updated dependencies [0b956f21b]
|
||||
- Updated dependencies [97c2cb19b]
|
||||
- Updated dependencies [3beb5c9fc]
|
||||
- Updated dependencies [754e31db5]
|
||||
- Updated dependencies [1611c6dbc]
|
||||
- @backstage/plugin-catalog@0.2.0
|
||||
- @backstage/core@0.2.0
|
||||
- @backstage/catalog-model@0.2.0
|
||||
- @backstage/theme@0.2.0
|
||||
@@ -6,5 +6,5 @@ This is the frontend part of the default scaffolder plugin.
|
||||
|
||||
## Links
|
||||
|
||||
- [Backend part of the plugin](https://github.com/spotify/backstage/tree/master/plugins/scaffolder-backend)
|
||||
- [Backend part of the plugin](https://github.com/backstage/backstage/tree/master/plugins/scaffolder-backend)
|
||||
- [The Backstage homepage](https://backstage.io)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@backstage/plugin-scaffolder",
|
||||
"version": "0.1.1-alpha.26",
|
||||
"version": "0.3.5",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
"license": "Apache-2.0",
|
||||
@@ -10,6 +10,15 @@
|
||||
"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/scaffolder"
|
||||
},
|
||||
"keywords": [
|
||||
"backstage"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "backstage-cli plugin:build",
|
||||
"start": "backstage-cli plugin:serve",
|
||||
@@ -21,10 +30,10 @@
|
||||
"clean": "backstage-cli clean"
|
||||
},
|
||||
"dependencies": {
|
||||
"@backstage/catalog-model": "^0.1.1-alpha.26",
|
||||
"@backstage/core": "^0.1.1-alpha.26",
|
||||
"@backstage/plugin-catalog": "^0.1.1-alpha.26",
|
||||
"@backstage/theme": "^0.1.1-alpha.26",
|
||||
"@backstage/catalog-model": "^0.6.0",
|
||||
"@backstage/core": "^0.4.3",
|
||||
"@backstage/plugin-catalog": "^0.2.8",
|
||||
"@backstage/theme": "^0.2.2",
|
||||
"@material-ui/core": "^4.11.0",
|
||||
"@material-ui/icons": "^4.9.1",
|
||||
"@material-ui/lab": "4.0.0-alpha.45",
|
||||
@@ -41,9 +50,9 @@
|
||||
"swr": "^0.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@backstage/cli": "^0.1.1-alpha.26",
|
||||
"@backstage/dev-utils": "^0.1.1-alpha.26",
|
||||
"@backstage/test-utils": "^0.1.1-alpha.26",
|
||||
"@backstage/cli": "^0.4.4",
|
||||
"@backstage/dev-utils": "^0.1.7",
|
||||
"@backstage/test-utils": "^0.1.6",
|
||||
"@testing-library/jest-dom": "^5.10.1",
|
||||
"@testing-library/react": "^10.4.1",
|
||||
"@testing-library/user-event": "^12.0.7",
|
||||
|
||||
@@ -15,7 +15,6 @@
|
||||
*/
|
||||
|
||||
import { createApiRef, DiscoveryApi } from '@backstage/core';
|
||||
import { TemplateEntityV1alpha1 } from '@backstage/catalog-model';
|
||||
|
||||
export const scaffolderApiRef = createApiRef<ScaffolderApi>({
|
||||
id: 'plugin.scaffolder.service',
|
||||
@@ -33,20 +32,17 @@ export class ScaffolderApi {
|
||||
* Executes the scaffolding of a component, given a template and its
|
||||
* parameter values.
|
||||
*
|
||||
* @param template Template entity for the scaffolder to use. New project is going to be created out of this template.
|
||||
* @param templateName Template name for the scaffolder to use. New project is going to be created out of this template.
|
||||
* @param values Parameters for the template, e.g. name, description
|
||||
*/
|
||||
async scaffold(
|
||||
template: TemplateEntityV1alpha1,
|
||||
values: Record<string, any>,
|
||||
) {
|
||||
async scaffold(templateName: string, values: Record<string, any>) {
|
||||
const url = `${await this.discoveryApi.getBaseUrl('scaffolder')}/v1/jobs`;
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ template, values: { ...values } }),
|
||||
body: JSON.stringify({ templateName, values: { ...values } }),
|
||||
});
|
||||
|
||||
if (response.status !== 201) {
|
||||
|
||||
@@ -76,6 +76,18 @@ const useStyles = makeStyles(theme => ({
|
||||
boxShadow: `inset 4px 0px 0px ${theme.palette.success.main}`,
|
||||
},
|
||||
},
|
||||
jobStatusTitle: {
|
||||
display: 'flex',
|
||||
width: '100%',
|
||||
alignItems: 'center',
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
[theme.breakpoints.down('xs')]: {
|
||||
flexDirection: 'column',
|
||||
alignItems: 'flex-start',
|
||||
justifyContent: 'flex-start',
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
type Props = {
|
||||
@@ -124,7 +136,7 @@ export const JobStage = ({ endedAt, startedAt, name, log, status }: Props) => {
|
||||
className: classes.button,
|
||||
}}
|
||||
>
|
||||
<Typography variant="button">
|
||||
<Typography variant="button" className={classes.jobStatusTitle}>
|
||||
{name} {timeElapsed && `(${timeElapsed})`}{' '}
|
||||
{startedAt && !endedAt && <CircularProgress size="1em" />}
|
||||
</Typography>
|
||||
|
||||
@@ -13,49 +13,57 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
import { TemplateEntityV1alpha1 } from '@backstage/catalog-model';
|
||||
import { Button } from '@backstage/core';
|
||||
import { entityRoute, entityRouteParams } from '@backstage/plugin-catalog';
|
||||
import {
|
||||
Button as Action,
|
||||
Dialog,
|
||||
DialogActions,
|
||||
DialogContent,
|
||||
DialogTitle,
|
||||
LinearProgress,
|
||||
} from '@material-ui/core';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { generatePath } from 'react-router-dom';
|
||||
|
||||
import React, { useCallback } from 'react';
|
||||
import { Job } from '../../types';
|
||||
import { JobStage } from '../JobStage/JobStage';
|
||||
import { useJobPolling } from './useJobPolling';
|
||||
|
||||
type Props = {
|
||||
onClose: () => void;
|
||||
onComplete: (job: Job) => void;
|
||||
jobId: string;
|
||||
entity: TemplateEntityV1alpha1 | null;
|
||||
job: Job | null;
|
||||
toCatalogLink?: string;
|
||||
open: boolean;
|
||||
onModalClose: () => void;
|
||||
};
|
||||
|
||||
export const JobStatusModal = ({
|
||||
onClose,
|
||||
jobId,
|
||||
onComplete,
|
||||
entity,
|
||||
job,
|
||||
toCatalogLink,
|
||||
open,
|
||||
onModalClose,
|
||||
}: Props) => {
|
||||
const job = useJobPolling(jobId);
|
||||
const [dialogTitle, setDialogTitle] = useState('Creating component...');
|
||||
const renderTitle = () => {
|
||||
switch (job?.status) {
|
||||
case 'COMPLETED':
|
||||
return 'Successfully created component';
|
||||
case 'FAILED':
|
||||
return 'Failed to create component';
|
||||
default:
|
||||
return 'Create component';
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (job?.status === 'COMPLETED') {
|
||||
setDialogTitle('Successfully created component');
|
||||
onComplete(job);
|
||||
} else if (job?.status === 'FAILED')
|
||||
setDialogTitle('Failed to create component');
|
||||
}, [job, onComplete, setDialogTitle]);
|
||||
const onClose = useCallback(() => {
|
||||
if (!job) {
|
||||
return;
|
||||
}
|
||||
// Disallow closing modal if the job is in progress.
|
||||
if (job.status === 'COMPLETED' || job.status === 'FAILED') {
|
||||
onModalClose();
|
||||
}
|
||||
}, [job, onModalClose]);
|
||||
|
||||
return (
|
||||
<Dialog open onClose={onClose} fullWidth>
|
||||
<DialogTitle id="responsive-dialog-title">{dialogTitle}</DialogTitle>
|
||||
<Dialog open={open} onClose={onClose} fullWidth>
|
||||
<DialogTitle id="responsive-dialog-title">{renderTitle()}</DialogTitle>
|
||||
<DialogContent>
|
||||
{!job ? (
|
||||
<LinearProgress />
|
||||
@@ -72,16 +80,14 @@ export const JobStatusModal = ({
|
||||
))
|
||||
)}
|
||||
</DialogContent>
|
||||
{entity && (
|
||||
{job?.status && toCatalogLink && (
|
||||
<DialogActions>
|
||||
<Button
|
||||
to={generatePath(
|
||||
`/catalog/${entityRoute.path}`,
|
||||
entityRouteParams(entity),
|
||||
)}
|
||||
>
|
||||
View in catalog
|
||||
</Button>
|
||||
<Button to={toCatalogLink}>View in catalog</Button>
|
||||
</DialogActions>
|
||||
)}
|
||||
{job?.status === 'FAILED' && (
|
||||
<DialogActions>
|
||||
<Action onClick={onClose}>Close</Action>
|
||||
</DialogActions>
|
||||
)}
|
||||
</Dialog>
|
||||
|
||||
@@ -69,8 +69,9 @@ export const MultistepJsonForm = ({
|
||||
{steps.map(({ label, schema, ...formProps }) => (
|
||||
<Step key={label}>
|
||||
<StepLabel>{label}</StepLabel>
|
||||
<StepContent>
|
||||
<StepContent key={label}>
|
||||
<Form
|
||||
key={label}
|
||||
noHtml5Validate
|
||||
formData={formData}
|
||||
onChange={onChange}
|
||||
|
||||
@@ -53,10 +53,12 @@ export const ScaffolderPage = () => {
|
||||
|
||||
const { data: templates, isValidating, error } = useStaleWhileRevalidate(
|
||||
'templates/all',
|
||||
async () =>
|
||||
catalogApi.getEntities({ kind: 'Template' }) as Promise<
|
||||
TemplateEntityV1alpha1[]
|
||||
>,
|
||||
async () => {
|
||||
const response = await catalogApi.getEntities({
|
||||
filter: { kind: 'Template' },
|
||||
});
|
||||
return response.items as TemplateEntityV1alpha1[];
|
||||
},
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -81,7 +83,7 @@ export const ScaffolderPage = () => {
|
||||
variant="contained"
|
||||
color="primary"
|
||||
component={RouterLink}
|
||||
to="/register-component"
|
||||
to="/catalog-import"
|
||||
>
|
||||
Register Existing Component
|
||||
</Button>
|
||||
|
||||
@@ -13,18 +13,17 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
import React from 'react';
|
||||
import { TemplatePage } from './TemplatePage';
|
||||
import { wrapInTestApp, renderWithEffects } from '@backstage/test-utils';
|
||||
import { ApiRegistry, errorApiRef, ApiProvider } from '@backstage/core';
|
||||
import { scaffolderApiRef, ScaffolderApi } from '../../api';
|
||||
import { catalogApiRef, CatalogApi } from '@backstage/plugin-catalog';
|
||||
import { mutate } from 'swr';
|
||||
import { act } from 'react-dom/test-utils';
|
||||
import { Route, MemoryRouter } from 'react-router';
|
||||
import { rootRoute } from '../../routes';
|
||||
import { ThemeProvider } from '@material-ui/core';
|
||||
import { ApiProvider, ApiRegistry, errorApiRef } from '@backstage/core';
|
||||
import { CatalogApi, catalogApiRef } from '@backstage/plugin-catalog';
|
||||
import { renderInTestApp, renderWithEffects } from '@backstage/test-utils';
|
||||
import { lightTheme } from '@backstage/theme';
|
||||
import { ThemeProvider } from '@material-ui/core';
|
||||
import React from 'react';
|
||||
import { act } from 'react-dom/test-utils';
|
||||
import { MemoryRouter, Route } from 'react-router';
|
||||
import { ScaffolderApi, scaffolderApiRef } from '../../api';
|
||||
import { rootRoute } from '../../routes';
|
||||
import { TemplatePage } from './TemplatePage';
|
||||
|
||||
const templateMock = {
|
||||
apiVersion: 'backstage.io/v1alpha1',
|
||||
@@ -90,48 +89,43 @@ const apis = ApiRegistry.from([
|
||||
]);
|
||||
|
||||
describe('TemplatePage', () => {
|
||||
afterEach(async () => {
|
||||
// Cleaning up swr's cache
|
||||
await act(async () => {
|
||||
await mutate('templates/test');
|
||||
});
|
||||
});
|
||||
beforeEach(() => jest.resetAllMocks());
|
||||
|
||||
it('renders correctly', async () => {
|
||||
catalogApiMock.getEntities.mockResolvedValueOnce([templateMock]);
|
||||
const rendered = await renderWithEffects(
|
||||
wrapInTestApp(
|
||||
<ApiProvider apis={apis}>
|
||||
<TemplatePage />
|
||||
</ApiProvider>,
|
||||
),
|
||||
catalogApiMock.getEntities.mockResolvedValueOnce({ items: [templateMock] });
|
||||
const rendered = await renderInTestApp(
|
||||
<ApiProvider apis={apis}>
|
||||
<TemplatePage />
|
||||
</ApiProvider>,
|
||||
);
|
||||
|
||||
expect(rendered.queryByText('Create a new component')).toBeInTheDocument();
|
||||
expect(rendered.queryByText('React SSR Template')).toBeInTheDocument();
|
||||
// await act(async () => await mutate('templates/test'));
|
||||
});
|
||||
|
||||
it('renders spinner while loading', async () => {
|
||||
let resolve: Function;
|
||||
const promise = new Promise<any>(res => {
|
||||
resolve = res;
|
||||
});
|
||||
catalogApiMock.getEntities.mockResolvedValueOnce(promise);
|
||||
const rendered = await renderWithEffects(
|
||||
wrapInTestApp(
|
||||
<ApiProvider apis={apis}>
|
||||
<TemplatePage />
|
||||
</ApiProvider>,
|
||||
),
|
||||
catalogApiMock.getEntities.mockReturnValueOnce(promise);
|
||||
const rendered = await renderInTestApp(
|
||||
<ApiProvider apis={apis}>
|
||||
<TemplatePage />
|
||||
</ApiProvider>,
|
||||
);
|
||||
|
||||
expect(rendered.queryByText('Create a new component')).toBeInTheDocument();
|
||||
expect(rendered.queryByTestId('loading-progress')).toBeInTheDocument();
|
||||
// Need to cleanup the promise or will timeout
|
||||
resolve!();
|
||||
act(() => {
|
||||
resolve!({ items: [] });
|
||||
});
|
||||
});
|
||||
|
||||
it('navigates away if no template was loaded', async () => {
|
||||
catalogApiMock.getEntities.mockResolvedValueOnce([]);
|
||||
catalogApiMock.getEntities.mockResolvedValueOnce({ items: [] });
|
||||
|
||||
const rendered = await renderWithEffects(
|
||||
<ApiProvider apis={apis}>
|
||||
|
||||
@@ -23,32 +23,34 @@ import {
|
||||
Page,
|
||||
useApi,
|
||||
} from '@backstage/core';
|
||||
import { catalogApiRef } from '@backstage/plugin-catalog';
|
||||
import {
|
||||
catalogApiRef,
|
||||
entityRoute,
|
||||
entityRouteParams,
|
||||
} from '@backstage/plugin-catalog';
|
||||
import { LinearProgress } from '@material-ui/core';
|
||||
import { IChangeEvent } from '@rjsf/core';
|
||||
import React, { useState } from 'react';
|
||||
import React, { useState, useCallback } from 'react';
|
||||
import { generatePath, Navigate } from 'react-router';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import useStaleWhileRevalidate from 'swr';
|
||||
import { useAsync } from 'react-use';
|
||||
import { scaffolderApiRef } from '../../api';
|
||||
import { JobStatusModal } from '../JobStatusModal';
|
||||
import { Job } from '../../types';
|
||||
import { MultistepJsonForm } from '../MultistepJsonForm';
|
||||
import { Navigate } from 'react-router';
|
||||
import { rootRoute } from '../../routes';
|
||||
import { JobStatusModal } from '../JobStatusModal';
|
||||
import { MultistepJsonForm } from '../MultistepJsonForm';
|
||||
import { useJobPolling } from '../hooks/useJobPolling';
|
||||
|
||||
const useTemplate = (
|
||||
templateName: string,
|
||||
catalogApi: typeof catalogApiRef.T,
|
||||
) => {
|
||||
const { data, error } = useStaleWhileRevalidate(
|
||||
`templates/${templateName}`,
|
||||
async () =>
|
||||
catalogApi.getEntities({
|
||||
kind: 'Template',
|
||||
'metadata.name': templateName,
|
||||
}) as Promise<TemplateEntityV1alpha1[]>,
|
||||
);
|
||||
return { template: data?.[0], loading: !error && !data, error };
|
||||
const { value, loading, error } = useAsync(async () => {
|
||||
const response = await catalogApi.getEntities({
|
||||
filter: { kind: 'Template', 'metadata.name': templateName },
|
||||
});
|
||||
return response.items as TemplateEntityV1alpha1[];
|
||||
});
|
||||
return { template: value?.[0], loading, error };
|
||||
};
|
||||
|
||||
const OWNER_REPO_SCHEMA = {
|
||||
@@ -83,53 +85,53 @@ export const TemplatePage = () => {
|
||||
const catalogApi = useApi(catalogApiRef);
|
||||
const scaffolderApi = useApi(scaffolderApiRef);
|
||||
const { templateName } = useParams();
|
||||
const [catalogLink, setCatalogLink] = useState<string | undefined>();
|
||||
const { template, loading } = useTemplate(templateName, catalogApi);
|
||||
|
||||
const [formState, setFormState] = useState({});
|
||||
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const handleFormReset = () => setFormState({});
|
||||
const handleChange = (e: IChangeEvent) =>
|
||||
setFormState({ ...formState, ...e.formData });
|
||||
|
||||
const [jobId, setJobId] = useState<string | null>(null);
|
||||
const handleClose = () => setJobId(null);
|
||||
|
||||
const handleCreate = async () => {
|
||||
try {
|
||||
const job = await scaffolderApi.scaffold(template!, formState);
|
||||
setJobId(job);
|
||||
} catch (e) {
|
||||
errorApi.post(e);
|
||||
}
|
||||
};
|
||||
|
||||
const [entity, setEntity] = React.useState<TemplateEntityV1alpha1 | null>(
|
||||
null,
|
||||
const handleChange = useCallback(
|
||||
(e: IChangeEvent) => setFormState({ ...formState, ...e.formData }),
|
||||
[setFormState, formState],
|
||||
);
|
||||
|
||||
const handleCreateComplete = async (job: Job) => {
|
||||
const target = job.metadata.remoteUrl?.replace(
|
||||
/\.git$/,
|
||||
// TODO(Rugvip): This is not the location we want. As part of scaffodler v2 we
|
||||
// want this to be more flexible, but before that we might want
|
||||
// to update all templates to use catalog-info.yaml instead.
|
||||
'/blob/master/component-info.yaml',
|
||||
);
|
||||
|
||||
if (!target) {
|
||||
const [jobId, setJobId] = useState<string | null>(null);
|
||||
const job = useJobPolling(jobId, async job => {
|
||||
if (!job.metadata.catalogInfoUrl) {
|
||||
errorApi.post(
|
||||
new Error(
|
||||
`Failed to find component-info.yaml file in ${job.metadata.remoteUrl}.`,
|
||||
),
|
||||
new Error(`No catalogInfoUrl returned from the scaffolder`),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const {
|
||||
entities: [createdEntity],
|
||||
} = await catalogApi.addLocation({ target });
|
||||
try {
|
||||
const {
|
||||
entities: [createdEntity],
|
||||
} = await catalogApi.addLocation({ target: job.metadata.catalogInfoUrl });
|
||||
|
||||
setEntity((createdEntity as any) as TemplateEntityV1alpha1);
|
||||
const resolvedPath = generatePath(
|
||||
`/catalog/${entityRoute.path}`,
|
||||
entityRouteParams(createdEntity),
|
||||
);
|
||||
|
||||
setCatalogLink(resolvedPath);
|
||||
} catch (ex) {
|
||||
errorApi.post(
|
||||
new Error(
|
||||
`Something went wrong trying to add the new 'catalog-info.yaml' to the catalog`,
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const handleCreate = async () => {
|
||||
try {
|
||||
const jobId = await scaffolderApi.scaffold(templateName, formState);
|
||||
setJobId(jobId);
|
||||
setModalOpen(true);
|
||||
} catch (e) {
|
||||
errorApi.post(e);
|
||||
}
|
||||
};
|
||||
|
||||
if (!loading && !template) {
|
||||
@@ -159,14 +161,12 @@ export const TemplatePage = () => {
|
||||
/>
|
||||
<Content>
|
||||
{loading && <LinearProgress data-testid="loading-progress" />}
|
||||
{jobId && (
|
||||
<JobStatusModal
|
||||
onComplete={handleCreateComplete}
|
||||
jobId={jobId}
|
||||
onClose={handleClose}
|
||||
entity={entity}
|
||||
/>
|
||||
)}
|
||||
<JobStatusModal
|
||||
job={job}
|
||||
toCatalogLink={catalogLink}
|
||||
open={modalOpen}
|
||||
onModalClose={() => setModalOpen(false)}
|
||||
/>
|
||||
{template && (
|
||||
<InfoCard title={template.metadata.title} noPadding>
|
||||
<MultistepJsonForm
|
||||
|
||||
+30
-30
@@ -13,50 +13,50 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Job } from '../../types';
|
||||
import { useApi } from '@backstage/core';
|
||||
import { scaffolderApiRef } from '../../api';
|
||||
import { useInterval } from 'react-use';
|
||||
|
||||
const DEFAULT_POLLING_INTERVAL = 1000;
|
||||
const poll = (thunk: () => Promise<void>, ms: number) => {
|
||||
let shouldStop = false;
|
||||
(async () => {
|
||||
while (!shouldStop) {
|
||||
await thunk();
|
||||
await new Promise(res => setTimeout(res, ms));
|
||||
}
|
||||
})();
|
||||
|
||||
return () => {
|
||||
shouldStop = true;
|
||||
};
|
||||
};
|
||||
|
||||
export const useJobPolling = (
|
||||
jobId: string | null,
|
||||
onFinish?: (j: Job) => void,
|
||||
pollingInterval = DEFAULT_POLLING_INTERVAL,
|
||||
) => {
|
||||
const scaffolderApi = useApi(scaffolderApiRef);
|
||||
const [job, setJob] = useState<Job | null>(null);
|
||||
const [currentJob, setCurrentJob] = useState<Job | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!jobId) return () => {};
|
||||
|
||||
const stopPolling = poll(async () => {
|
||||
const nextJobState = await scaffolderApi.getJob(jobId);
|
||||
if (
|
||||
nextJobState.status === 'FAILED' ||
|
||||
nextJobState.status === 'COMPLETED'
|
||||
) {
|
||||
stopPolling();
|
||||
const resetCurrentJob = async () => {
|
||||
if (jobId) {
|
||||
const job = await scaffolderApi.getJob(jobId);
|
||||
setCurrentJob(job);
|
||||
}
|
||||
setJob(nextJobState);
|
||||
}, pollingInterval);
|
||||
return () => {
|
||||
stopPolling();
|
||||
};
|
||||
}, [jobId, setJob, scaffolderApi, pollingInterval]);
|
||||
|
||||
return job;
|
||||
resetCurrentJob();
|
||||
}, [jobId, scaffolderApi]);
|
||||
|
||||
const shouldBeRunningInterval =
|
||||
jobId &&
|
||||
currentJob?.status !== 'COMPLETED' &&
|
||||
currentJob?.status !== 'FAILED';
|
||||
|
||||
useInterval(
|
||||
async () => {
|
||||
if (jobId) {
|
||||
const job = await scaffolderApi.getJob(jobId);
|
||||
if (job?.status === 'COMPLETED' || job?.status === 'FAILED') {
|
||||
onFinish?.(job);
|
||||
}
|
||||
setCurrentJob(job);
|
||||
}
|
||||
},
|
||||
shouldBeRunningInterval ? pollingInterval : null,
|
||||
);
|
||||
|
||||
return currentJob;
|
||||
};
|
||||
@@ -13,14 +13,17 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
export type JobStatus = 'PENDING' | 'STARTED' | 'COMPLETED' | 'FAILED';
|
||||
export type Job = {
|
||||
id: string;
|
||||
metadata: {
|
||||
entity: any;
|
||||
values: any;
|
||||
remoteUrl?: string;
|
||||
catalogInfoUrl?: string;
|
||||
};
|
||||
status: 'PENDING' | 'STARTED' | 'COMPLETED' | 'FAILED';
|
||||
status: JobStatus;
|
||||
stages: Stage[];
|
||||
error?: Error;
|
||||
};
|
||||
@@ -28,7 +31,7 @@ export type Job = {
|
||||
export type Stage = {
|
||||
name: string;
|
||||
log: string[];
|
||||
status: 'PENDING' | 'STARTED' | 'COMPLETED' | 'FAILED';
|
||||
status: JobStatus;
|
||||
startedAt: string;
|
||||
endedAt?: string;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user