Merge branch 'master' of github.com:spotify/backstage into shmidt-i/universal-file-github-actions

This commit is contained in:
Ivan Shmidt
2020-10-07 16:48:36 +02:00
980 changed files with 36131 additions and 11244 deletions
@@ -60,7 +60,10 @@ const WidgetContent = ({
metadata={{
status: (
<>
<WorkflowRunStatus status={lastRun.status} />
<WorkflowRunStatus
status={lastRun.status}
conclusion={lastRun.conclusion}
/>
</>
),
message: lastRun.message,
@@ -0,0 +1,131 @@
/*
* Copyright 2020 Spotify AB
*
* 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 type { Props as RecentWorkflowRunsCardProps } from './RecentWorkflowRunsCard';
import React from 'react';
import { render } from '@testing-library/react';
import { RecentWorkflowRunsCard } from './RecentWorkflowRunsCard';
import { ApiProvider, ApiRegistry, errorApiRef } from '@backstage/core-api';
import { useWorkflowRuns } from '../useWorkflowRuns';
import { ThemeProvider } from '@material-ui/core';
import { lightTheme } from '@backstage/theme';
import { MemoryRouter } from 'react-router';
jest.mock('../useWorkflowRuns', () => ({
useWorkflowRuns: jest.fn(),
}));
const mockErrorApi: jest.Mocked<typeof errorApiRef.T> = {
post: jest.fn(),
error$: jest.fn(),
};
describe('<RecentWorkflowRunsCard />', () => {
const entity = {
apiVersion: 'v1',
kind: 'Component',
metadata: {
name: 'software',
annotations: {
'github.com/project-slug': 'theorg/the-service',
},
},
spec: {
owner: 'guest',
type: 'service',
lifecycle: 'production',
},
};
const workflowRuns = [1, 2, 3, 4, 5].map(n => ({
id: `run-id-${n}`,
message: `Commit message for workflow ${n}`,
source: { branchName: `branch-${n}` },
status: 'completed',
}));
beforeEach(() => {
(useWorkflowRuns as jest.Mock).mockReturnValue([{ runs: workflowRuns }]);
});
afterEach(() => {
jest.resetAllMocks();
});
const renderSubject = (props: RecentWorkflowRunsCardProps = { entity }) =>
render(
<ThemeProvider theme={lightTheme}>
<MemoryRouter>
<ApiProvider apis={ApiRegistry.with(errorApiRef, mockErrorApi)}>
<RecentWorkflowRunsCard {...props} />
</ApiProvider>
</MemoryRouter>
</ThemeProvider>,
);
it('renders a table with a row for each workflow', async () => {
const subject = renderSubject();
workflowRuns.forEach(run => {
expect(subject.getByText(run.message)).toBeInTheDocument();
});
});
it('renders a workflow row correctly', async () => {
const subject = renderSubject();
const [run] = workflowRuns;
expect(subject.getByText(run.message).closest('a')).toHaveAttribute(
'href',
`/ci-cd/${run.id}`,
);
expect(subject.getByText(run.source.branchName)).toBeInTheDocument();
});
it('requests only the required number of workflow runs', async () => {
const limit = 3;
renderSubject({ entity, limit });
expect(useWorkflowRuns).toHaveBeenCalledWith(
expect.objectContaining({ initialPageSize: limit }),
);
});
it('uses the github repo and owner from the entity annotation', async () => {
renderSubject();
expect(useWorkflowRuns).toHaveBeenCalledWith(
expect.objectContaining({ owner: 'theorg', repo: 'the-service' }),
);
});
it('filters workflows by branch if one is specified', async () => {
const branch = 'master';
renderSubject({ entity, branch });
expect(useWorkflowRuns).toHaveBeenCalledWith(
expect.objectContaining({ branch }),
);
});
describe('where there is an error fetching workflows', () => {
const error = 'error getting workflows';
beforeEach(() => {
(useWorkflowRuns as jest.Mock).mockReturnValue([{ runs: [], error }]);
});
it('sends the error to the errorApi', async () => {
renderSubject();
expect(mockErrorApi.post).toHaveBeenCalledWith(error);
});
});
});
@@ -0,0 +1,103 @@
/*
* Copyright 2020 Spotify AB
*
* 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 } from '@backstage/catalog-model';
import { errorApiRef, useApi } from '@backstage/core-api';
import { GITHUB_ACTIONS_ANNOTATION } from '../useProjectName';
import { useWorkflowRuns } from '../useWorkflowRuns';
import React, { useEffect } from 'react';
import { EmptyState, Table } from '@backstage/core';
import { WorkflowRunStatus } from '../WorkflowRunStatus';
import { Button, Card, Link, TableContainer } from '@material-ui/core';
import { generatePath, Link as RouterLink } from 'react-router-dom';
const firstLine = (message: string): string => message.split('\n')[0];
export type Props = {
entity: Entity;
branch?: string;
dense?: boolean;
limit?: number;
};
export const RecentWorkflowRunsCard = ({
entity,
branch,
dense = false,
limit = 5,
}: Props) => {
const errorApi = useApi(errorApiRef);
const [owner, repo] = (
entity?.metadata.annotations?.[GITHUB_ACTIONS_ANNOTATION] ?? '/'
).split('/');
const [{ runs = [], loading, error }] = useWorkflowRuns({
owner,
repo,
branch,
initialPageSize: limit,
});
useEffect(() => {
if (error) {
errorApi.post(error);
}
}, [error, errorApi]);
return !runs.length ? (
<EmptyState
missing="data"
title="No Workflow Data"
description="This component has Github Actions enabled, but no data was found. Have you created any Workflows? Click the button below to create a new Workflow."
action={
<Button
variant="contained"
color="primary"
href={`https://github.com/${owner}/${repo}/actions/new`}
>
Create new Workflow
</Button>
}
/>
) : (
<TableContainer component={Card}>
<Table
title="Recent Workflow Runs"
subtitle={branch ? `Branch: ${branch}` : 'All Branches'}
isLoading={loading}
options={{
search: false,
paging: false,
padding: dense ? 'dense' : 'default',
}}
columns={[
{
title: 'Commit Message',
field: 'message',
render: data => (
<Link
component={RouterLink}
to={generatePath('./ci-cd/:id', { id: data.id! })}
>
{firstLine(data.message)}
</Link>
),
},
{ title: 'Branch', field: 'source.branchName' },
{ title: 'Status', field: 'status', render: WorkflowRunStatus },
]}
data={runs}
/>
</TableContainer>
);
};
@@ -14,3 +14,4 @@
* limitations under the License.
*/
export { LatestWorkflowRunCard, LatestWorkflowsForBranchCard } from './Cards';
export { RecentWorkflowRunsCard } from './RecentWorkflowRunsCard';
@@ -20,19 +20,14 @@ import { rootRouteRef, buildRouteRef } from '../plugin';
import { WorkflowRunDetails } from './WorkflowRunDetails';
import { WorkflowRunsTable } from './WorkflowRunsTable';
import { GITHUB_ACTIONS_ANNOTATION } from '../../universal';
import { WarningPanel } from '@backstage/core';
import { MissingAnnotationEmptyState } from '@backstage/core';
export const isPluginApplicableToEntity = (entity: Entity) =>
Boolean(entity.metadata.annotations?.[GITHUB_ACTIONS_ANNOTATION]) &&
entity.metadata.annotations?.[GITHUB_ACTIONS_ANNOTATION] !== '';
Boolean(entity.metadata.annotations?.[GITHUB_ACTIONS_ANNOTATION]);
export const Router = ({ entity }: { entity: Entity }) =>
// TODO(shmidt-i): move warning to a separate standardized component
!isPluginApplicableToEntity(entity) ? (
<WarningPanel title=" GitHubActions plugin:">
<pre>{GITHUB_ACTIONS_ANNOTATION}</pre> annotation is missing on the
entity.
</WarningPanel>
<MissingAnnotationEmptyState annotation={GITHUB_ACTIONS_ANNOTATION} />
) : (
<Routes>
<Route
@@ -106,7 +106,10 @@ const StepView = ({ step }: { step: Step }) => {
/>
</TableCell>
<TableCell>
<WorkflowRunStatus status={step.status.toUpperCase()} />
<WorkflowRunStatus
status={step.status.toUpperCase()}
conclusion={step.conclusion.toUpperCase()}
/>
</TableCell>
</TableRow>
);
@@ -204,7 +207,10 @@ export const WorkflowRunDetails = ({ entity }: { entity: Entity }) => {
<Typography noWrap>Status</Typography>
</TableCell>
<TableCell>
<WorkflowRunStatus status={details.value?.status} />
<WorkflowRunStatus
status={details.value?.status}
conclusion={details.value?.conclusion}
/>
</TableCell>
</TableRow>
<TableRow>
@@ -14,13 +14,22 @@
* limitations under the License.
*/
import { StatusPending, StatusRunning, StatusOK } from '@backstage/core';
import {
StatusPending,
StatusRunning,
StatusOK,
StatusWarning,
StatusAborted,
StatusError,
} from '@backstage/core';
import React from 'react';
export const WorkflowRunStatus = ({
status,
conclusion,
}: {
status: string | undefined;
conclusion: string | undefined;
}) => {
if (status === undefined) return null;
switch (status.toLowerCase()) {
@@ -37,11 +46,32 @@ export const WorkflowRunStatus = ({
</>
);
case 'completed':
return (
<>
<StatusOK /> Completed
</>
);
switch (conclusion?.toLowerCase()) {
case 'skipped' || 'canceled':
return (
<>
<StatusAborted /> Aborted
</>
);
case 'timed_out':
return (
<>
<StatusWarning /> Timed out
</>
);
case 'failure':
return (
<>
<StatusError /> Error
</>
);
default:
return (
<>
<StatusOK /> Completed
</>
);
}
default:
return (
<>
@@ -14,11 +14,18 @@
* limitations under the License.
*/
import React, { FC } from 'react';
import { Link, Typography, Box, IconButton, Tooltip } from '@material-ui/core';
import {
Link,
Typography,
Box,
IconButton,
Tooltip,
Button,
} from '@material-ui/core';
import RetryIcon from '@material-ui/icons/Replay';
import GitHubIcon from '@material-ui/icons/GitHub';
import { Link as RouterLink, generatePath } from 'react-router-dom';
import { Table, TableColumn } from '@backstage/core';
import { EmptyState, Table, TableColumn } from '@backstage/core';
import { useWorkflowRuns } from '../useWorkflowRuns';
import { WorkflowRunStatus } from '../WorkflowRunStatus';
import SyncIcon from '@material-ui/icons/Sync';
@@ -39,6 +46,7 @@ export type WorkflowRun = {
};
};
status: string;
conclusion: string;
onReRunClick: () => void;
};
@@ -77,7 +85,7 @@ const generatedColumns: TableColumn[] = [
render: (row: Partial<WorkflowRun>) => (
<Box display="flex" alignItems="center">
<WorkflowRunStatus status={row.status} />
<WorkflowRunStatus status={row.status} conclusion={row.conclusion} />
</Box>
),
},
@@ -156,15 +164,34 @@ export const WorkflowRunsTable = ({
}) => {
const { value: projectName, loading } = useProjectName(entity);
const [owner, repo] = (projectName ?? '/').split('/');
const [tableProps, { retry, setPage, setPageSize }] = useWorkflowRuns({
const [
{ runs, ...tableProps },
{ retry, setPage, setPageSize },
] = useWorkflowRuns({
owner,
repo,
branch,
});
return (
return !runs ? (
<EmptyState
missing="data"
title="No Workflow Data"
description="This component has Github Actions enabled, but no data was found. Have you created any Workflows? Click the button below to create a new Workflow."
action={
<Button
variant="contained"
color="primary"
href={`https://github.com/${projectName}/actions/new`}
>
Create new Workflow
</Button>
}
/>
) : (
<WorkflowRunsTableView
{...tableProps}
runs={runs}
loading={loading || tableProps.loading}
retry={retry}
onChangePageSize={setPageSize}
@@ -24,10 +24,12 @@ export function useWorkflowRuns({
owner,
repo,
branch,
initialPageSize = 5,
}: {
owner: string;
repo: string;
branch?: string;
initialPageSize?: number;
}) {
const api = useApi(githubActionsApiRef);
const auth = useApi(githubAuthApiRef);
@@ -36,7 +38,7 @@ export function useWorkflowRuns({
const [total, setTotal] = useState(0);
const [page, setPage] = useState(0);
const [pageSize, setPageSize] = useState(5);
const [pageSize, setPageSize] = useState(initialPageSize);
const { loading, value: runs, retry, error } = useAsyncRetry<
WorkflowRun[]
@@ -85,6 +87,7 @@ export function useWorkflowRuns({
},
},
status: run.status,
conclusion: run.conclusion,
url: run.url,
githubUrl: run.html_url,
}));