integrationCodeMappings.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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} 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 Pagination, {CursorHandler} from 'sentry/components/pagination';
  11. import Panel from 'sentry/components/panels/panel';
  12. import PanelBody from 'sentry/components/panels/panelBody';
  13. import PanelHeader from 'sentry/components/panels/panelHeader';
  14. import PanelItem from 'sentry/components/panels/panelItem';
  15. import {IconAdd} from 'sentry/icons';
  16. import {t, tct} from 'sentry/locale';
  17. import {space} from 'sentry/styles/space';
  18. import {
  19. Integration,
  20. Organization,
  21. Project,
  22. Repository,
  23. RepositoryProjectPathConfig,
  24. } from 'sentry/types';
  25. import {trackAnalytics} from 'sentry/utils/analytics';
  26. import {getIntegrationIcon} from 'sentry/utils/integrationUtil';
  27. import withRouteAnalytics, {
  28. WithRouteAnalyticsProps,
  29. } 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. renderBody() {
  182. const pathConfigs = this.pathConfigs;
  183. const {integration} = this.props;
  184. const {pathConfigsPageLinks} = this.state;
  185. const docsLink = `https://docs.sentry.io/product/integrations/source-code-mgmt/${integration.provider.key}/#stack-trace-linking`;
  186. return (
  187. <Fragment>
  188. <TextBlock>
  189. {tct(
  190. `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].`,
  191. {
  192. link: <ExternalLink href={docsLink} onClick={this.trackDocsClick} />,
  193. }
  194. )}
  195. </TextBlock>
  196. <Panel>
  197. <PanelHeader disablePadding hasButtons>
  198. <HeaderLayout>
  199. <NameRepoColumn>{t('Code Mappings')}</NameRepoColumn>
  200. <InputPathColumn>{t('Stack Trace Root')}</InputPathColumn>
  201. <OutputPathColumn>{t('Source Code Root')}</OutputPathColumn>
  202. <ButtonWrapper>
  203. <Button
  204. data-test-id="add-mapping-button"
  205. onClick={() => this.openModal()}
  206. size="xs"
  207. icon={<IconAdd size="xs" isCircled />}
  208. >
  209. {t('Add Code Mapping')}
  210. </Button>
  211. </ButtonWrapper>
  212. </HeaderLayout>
  213. </PanelHeader>
  214. <PanelBody>
  215. {pathConfigs.length === 0 && (
  216. <EmptyMessage
  217. icon={getIntegrationIcon(integration.provider.key, 'lg')}
  218. action={
  219. <Button
  220. href={docsLink}
  221. size="sm"
  222. external
  223. onClick={this.trackDocsClick}
  224. >
  225. {t('View Documentation')}
  226. </Button>
  227. }
  228. >
  229. {t('Set up stack trace linking by adding a code mapping.')}
  230. </EmptyMessage>
  231. )}
  232. {pathConfigs
  233. .map(pathConfig => {
  234. const project = this.getMatchingProject(pathConfig);
  235. // this should never happen since our pathConfig would be deleted
  236. // if project was deleted
  237. if (!project) {
  238. return null;
  239. }
  240. return (
  241. <ConfigPanelItem key={pathConfig.id}>
  242. <Layout>
  243. <RepositoryProjectPathConfigRow
  244. pathConfig={pathConfig}
  245. project={project}
  246. onEdit={this.openModal}
  247. onDelete={this.handleDelete}
  248. />
  249. </Layout>
  250. </ConfigPanelItem>
  251. );
  252. })
  253. .filter(item => !!item)}
  254. </PanelBody>
  255. </Panel>
  256. {pathConfigsPageLinks && (
  257. <Pagination pageLinks={pathConfigsPageLinks} onCursor={this.handleCursor} />
  258. )}
  259. </Fragment>
  260. );
  261. }
  262. }
  263. export default withRouteAnalytics(
  264. withProjects(withOrganization(IntegrationCodeMappings))
  265. );
  266. const Layout = styled('div')`
  267. display: grid;
  268. grid-column-gap: ${space(1)};
  269. width: 100%;
  270. align-items: center;
  271. grid-template-columns: 4.5fr 2.5fr 2.5fr max-content;
  272. grid-template-areas: 'name-repo input-path output-path button';
  273. `;
  274. const HeaderLayout = styled(Layout)`
  275. align-items: center;
  276. margin: 0 ${space(1)} 0 ${space(2)};
  277. `;
  278. const ConfigPanelItem = styled(PanelItem)``;