integrationCodeMappings.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. import {Fragment} from 'react';
  2. import styled from '@emotion/styled';
  3. import sortBy from 'lodash/sortBy';
  4. import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
  5. import {openModal} from 'sentry/actionCreators/modal';
  6. import {Button, LinkButton} from 'sentry/components/button';
  7. import DeprecatedAsyncComponent from 'sentry/components/deprecatedAsyncComponent';
  8. import EmptyMessage from 'sentry/components/emptyMessage';
  9. import ExternalLink from 'sentry/components/links/externalLink';
  10. import type {CursorHandler} from 'sentry/components/pagination';
  11. import Pagination from 'sentry/components/pagination';
  12. import Panel from 'sentry/components/panels/panel';
  13. import PanelBody from 'sentry/components/panels/panelBody';
  14. import PanelHeader from 'sentry/components/panels/panelHeader';
  15. import PanelItem from 'sentry/components/panels/panelItem';
  16. import {IconAdd} from 'sentry/icons';
  17. import {t, tct} from 'sentry/locale';
  18. import {space} from 'sentry/styles/space';
  19. import type {
  20. Integration,
  21. Repository,
  22. RepositoryProjectPathConfig,
  23. } from 'sentry/types/integrations';
  24. import type {Organization} from 'sentry/types/organization';
  25. import type {Project} from 'sentry/types/project';
  26. import {trackAnalytics} from 'sentry/utils/analytics';
  27. import {getIntegrationIcon} from 'sentry/utils/integrationUtil';
  28. import type {WithRouteAnalyticsProps} from 'sentry/utils/routeAnalytics/withRouteAnalytics';
  29. import withRouteAnalytics from 'sentry/utils/routeAnalytics/withRouteAnalytics';
  30. import withOrganization from 'sentry/utils/withOrganization';
  31. import withProjects from 'sentry/utils/withProjects';
  32. import TextBlock from 'sentry/views/settings/components/text/textBlock';
  33. import RepositoryProjectPathConfigForm from './repositoryProjectPathConfigForm';
  34. import RepositoryProjectPathConfigRow, {
  35. ButtonWrapper,
  36. InputPathColumn,
  37. NameRepoColumn,
  38. OutputPathColumn,
  39. } from './repositoryProjectPathConfigRow';
  40. type Props = DeprecatedAsyncComponent['props'] &
  41. WithRouteAnalyticsProps & {
  42. integration: Integration;
  43. organization: Organization;
  44. projects: Project[];
  45. };
  46. type State = DeprecatedAsyncComponent['state'] & {
  47. pathConfigs: RepositoryProjectPathConfig[];
  48. repos: Repository[];
  49. };
  50. class IntegrationCodeMappings extends DeprecatedAsyncComponent<Props, State> {
  51. getDefaultState(): State {
  52. return {
  53. ...super.getDefaultState(),
  54. pathConfigs: [],
  55. repos: [],
  56. };
  57. }
  58. get integrationId() {
  59. return this.props.integration.id;
  60. }
  61. get pathConfigs() {
  62. // we want to sort by the project slug and the
  63. // id of the config
  64. return sortBy(this.state.pathConfigs, [
  65. ({projectSlug}) => projectSlug,
  66. ({id}) => parseInt(id, 10),
  67. ]);
  68. }
  69. get repos() {
  70. // endpoint doesn't support loading only the repos for this integration
  71. // but most people only have one source code repo so this should be fine
  72. return this.state.repos.filter(repo => repo.integrationId === this.integrationId);
  73. }
  74. getEndpoints(): ReturnType<DeprecatedAsyncComponent['getEndpoints']> {
  75. const orgSlug = this.props.organization.slug;
  76. return [
  77. [
  78. 'pathConfigs',
  79. `/organizations/${orgSlug}/code-mappings/`,
  80. {query: {integrationId: this.integrationId}},
  81. ],
  82. ['repos', `/organizations/${orgSlug}/repos/`, {query: {status: 'active'}}],
  83. ];
  84. }
  85. getMatchingProject(pathConfig: RepositoryProjectPathConfig) {
  86. return this.props.projects.find(project => project.id === pathConfig.projectId);
  87. }
  88. componentDidMount() {
  89. super.componentDidMount();
  90. this.props.setEventNames(
  91. 'integrations.code_mappings_viewed',
  92. 'Integrations: Code Mappings Viewed'
  93. );
  94. this.props.setRouteAnalyticsParams({
  95. integration: this.props.integration.provider.key,
  96. integration_type: 'first_party',
  97. });
  98. }
  99. trackDocsClick = () => {
  100. trackAnalytics('integrations.stacktrace_docs_clicked', {
  101. view: 'integration_configuration_detail',
  102. provider: this.props.integration.provider.key,
  103. organization: this.props.organization,
  104. });
  105. };
  106. handleDelete = async (pathConfig: RepositoryProjectPathConfig) => {
  107. const {organization} = this.props;
  108. const endpoint = `/organizations/${organization.slug}/code-mappings/${pathConfig.id}/`;
  109. try {
  110. await this.api.requestPromise(endpoint, {
  111. method: 'DELETE',
  112. });
  113. // remove config and update state
  114. let {pathConfigs} = this.state;
  115. pathConfigs = pathConfigs.filter(config => config.id !== pathConfig.id);
  116. this.setState({pathConfigs});
  117. addSuccessMessage(t('Deletion successful'));
  118. } catch (err) {
  119. addErrorMessage(`${err.statusText}: ${err.responseText}`);
  120. }
  121. };
  122. handleSubmitSuccess = (pathConfig: RepositoryProjectPathConfig) => {
  123. trackAnalytics('integrations.stacktrace_complete_setup', {
  124. setup_type: 'manual',
  125. view: 'integration_configuration_detail',
  126. provider: this.props.integration.provider.key,
  127. organization: this.props.organization,
  128. });
  129. let {pathConfigs} = this.state;
  130. pathConfigs = pathConfigs.filter(config => config.id !== pathConfig.id);
  131. // our getter handles the order of the configs
  132. pathConfigs = pathConfigs.concat([pathConfig]);
  133. this.setState({pathConfigs});
  134. this.setState({pathConfig: undefined});
  135. };
  136. openModal = (pathConfig?: RepositoryProjectPathConfig) => {
  137. const {organization, projects, integration} = this.props;
  138. trackAnalytics('integrations.stacktrace_start_setup', {
  139. setup_type: 'manual',
  140. view: 'integration_configuration_detail',
  141. provider: this.props.integration.provider.key,
  142. organization: this.props.organization,
  143. });
  144. openModal(({Body, Header, closeModal}) => (
  145. <Fragment>
  146. <Header closeButton>
  147. <h4>{t('Configure code path mapping')}</h4>
  148. </Header>
  149. <Body>
  150. <RepositoryProjectPathConfigForm
  151. organization={organization}
  152. integration={integration}
  153. projects={projects}
  154. repos={this.repos}
  155. onSubmitSuccess={config => {
  156. this.handleSubmitSuccess(config);
  157. closeModal();
  158. }}
  159. existingConfig={pathConfig}
  160. onCancel={closeModal}
  161. />
  162. </Body>
  163. </Fragment>
  164. ));
  165. };
  166. /**
  167. * This is a workaround to paginate without affecting browserHistory or modifiying the URL
  168. * It's necessary because we don't want to affect the pagination state of other tabs on the page.
  169. */
  170. handleCursor: CursorHandler = async (cursor, _path, query, _direction) => {
  171. const orgSlug = this.props.organization.slug;
  172. const [pathConfigs, _, responseMeta] = await this.api.requestPromise(
  173. `/organizations/${orgSlug}/code-mappings/`,
  174. {includeAllArgs: true, query: {...query, cursor}}
  175. );
  176. this.setState({
  177. pathConfigs,
  178. pathConfigsPageLinks: responseMeta?.getResponseHeader('link'),
  179. });
  180. };
  181. getDocsLink(): string {
  182. /** Accounts for some asymmetry between docs links and provider keys */
  183. const {integration} = this.props;
  184. let docsKey = integration.provider.key;
  185. switch (integration.provider.key) {
  186. case 'vsts':
  187. docsKey = 'azure-devops';
  188. break;
  189. case 'github_enterprise':
  190. docsKey = 'github';
  191. break;
  192. default:
  193. docsKey = integration.provider.key;
  194. break;
  195. }
  196. return `https://docs.sentry.io/product/integrations/source-code-mgmt/${docsKey}/#stack-trace-linking`;
  197. }
  198. renderBody() {
  199. const pathConfigs = this.pathConfigs;
  200. const {integration} = this.props;
  201. const {pathConfigsPageLinks} = this.state;
  202. const docsLink = this.getDocsLink();
  203. return (
  204. <Fragment>
  205. <TextBlock>
  206. {tct(
  207. `Code Mappings are used to map stack trace file paths to source code file paths. These mappings are the basis for features like Stack Trace Linking. To learn more, [link: read the docs].`,
  208. {
  209. link: <ExternalLink href={docsLink} onClick={this.trackDocsClick} />,
  210. }
  211. )}
  212. </TextBlock>
  213. <Panel>
  214. <PanelHeader disablePadding hasButtons>
  215. <HeaderLayout>
  216. <NameRepoColumn>{t('Code Mappings')}</NameRepoColumn>
  217. <InputPathColumn>{t('Stack Trace Root')}</InputPathColumn>
  218. <OutputPathColumn>{t('Source Code Root')}</OutputPathColumn>
  219. <ButtonWrapper>
  220. <Button
  221. data-test-id="add-mapping-button"
  222. onClick={() => this.openModal()}
  223. size="xs"
  224. icon={<IconAdd isCircled />}
  225. >
  226. {t('Add Code Mapping')}
  227. </Button>
  228. </ButtonWrapper>
  229. </HeaderLayout>
  230. </PanelHeader>
  231. <PanelBody>
  232. {pathConfigs.length === 0 && (
  233. <EmptyMessage
  234. icon={getIntegrationIcon(integration.provider.key, 'lg')}
  235. action={
  236. <LinkButton
  237. href={docsLink}
  238. size="sm"
  239. external
  240. onClick={this.trackDocsClick}
  241. >
  242. {t('View Documentation')}
  243. </LinkButton>
  244. }
  245. >
  246. {t('Set up stack trace linking by adding a code mapping.')}
  247. </EmptyMessage>
  248. )}
  249. {pathConfigs
  250. .map(pathConfig => {
  251. const project = this.getMatchingProject(pathConfig);
  252. // this should never happen since our pathConfig would be deleted
  253. // if project was deleted
  254. if (!project) {
  255. return null;
  256. }
  257. return (
  258. <ConfigPanelItem key={pathConfig.id}>
  259. <Layout>
  260. <RepositoryProjectPathConfigRow
  261. pathConfig={pathConfig}
  262. project={project}
  263. onEdit={this.openModal}
  264. onDelete={this.handleDelete}
  265. />
  266. </Layout>
  267. </ConfigPanelItem>
  268. );
  269. })
  270. .filter(item => !!item)}
  271. </PanelBody>
  272. </Panel>
  273. {pathConfigsPageLinks && (
  274. <Pagination pageLinks={pathConfigsPageLinks} onCursor={this.handleCursor} />
  275. )}
  276. </Fragment>
  277. );
  278. }
  279. }
  280. export default withRouteAnalytics(
  281. withProjects(withOrganization(IntegrationCodeMappings))
  282. );
  283. const Layout = styled('div')`
  284. display: grid;
  285. grid-column-gap: ${space(1)};
  286. width: 100%;
  287. align-items: center;
  288. grid-template-columns: 4.5fr 2.5fr 2.5fr max-content;
  289. grid-template-areas: 'name-repo input-path output-path button';
  290. `;
  291. const HeaderLayout = styled(Layout)`
  292. align-items: center;
  293. margin: 0 ${space(1)} 0 ${space(2)};
  294. `;
  295. const ConfigPanelItem = styled(PanelItem)``;