integrationCodeMappings.tsx 9.9 KB

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