integrationCodeMappings.tsx 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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. this.props.setEventNames(
  87. 'integrations.code_mappings_viewed',
  88. 'Integrations: Code Mappings Viewed'
  89. );
  90. this.props.setRouteAnalyticsParams({
  91. integration: this.props.integration.provider.key,
  92. integration_type: 'first_party',
  93. });
  94. }
  95. trackDocsClick = () => {
  96. trackAnalytics('integrations.stacktrace_docs_clicked', {
  97. view: 'integration_configuration_detail',
  98. provider: this.props.integration.provider.key,
  99. organization: this.props.organization,
  100. });
  101. };
  102. handleDelete = async (pathConfig: RepositoryProjectPathConfig) => {
  103. const {organization} = this.props;
  104. const endpoint = `/organizations/${organization.slug}/code-mappings/${pathConfig.id}/`;
  105. try {
  106. await this.api.requestPromise(endpoint, {
  107. method: 'DELETE',
  108. });
  109. // remove config and update state
  110. let {pathConfigs} = this.state;
  111. pathConfigs = pathConfigs.filter(config => config.id !== pathConfig.id);
  112. this.setState({pathConfigs});
  113. addSuccessMessage(t('Deletion successful'));
  114. } catch (err) {
  115. addErrorMessage(`${err.statusText}: ${err.responseText}`);
  116. }
  117. };
  118. handleSubmitSuccess = (pathConfig: RepositoryProjectPathConfig) => {
  119. trackAnalytics('integrations.stacktrace_complete_setup', {
  120. setup_type: 'manual',
  121. view: 'integration_configuration_detail',
  122. provider: this.props.integration.provider.key,
  123. organization: this.props.organization,
  124. });
  125. let {pathConfigs} = this.state;
  126. pathConfigs = pathConfigs.filter(config => config.id !== pathConfig.id);
  127. // our getter handles the order of the configs
  128. pathConfigs = pathConfigs.concat([pathConfig]);
  129. this.setState({pathConfigs});
  130. this.setState({pathConfig: undefined});
  131. };
  132. openModal = (pathConfig?: RepositoryProjectPathConfig) => {
  133. const {organization, projects, integration} = this.props;
  134. trackAnalytics('integrations.stacktrace_start_setup', {
  135. setup_type: 'manual',
  136. view: 'integration_configuration_detail',
  137. provider: this.props.integration.provider.key,
  138. organization: this.props.organization,
  139. });
  140. openModal(({Body, Header, closeModal}) => (
  141. <Fragment>
  142. <Header closeButton>
  143. <h4>{t('Configure code path mapping')}</h4>
  144. </Header>
  145. <Body>
  146. <RepositoryProjectPathConfigForm
  147. organization={organization}
  148. integration={integration}
  149. projects={projects}
  150. repos={this.repos}
  151. onSubmitSuccess={config => {
  152. this.handleSubmitSuccess(config);
  153. closeModal();
  154. }}
  155. existingConfig={pathConfig}
  156. onCancel={closeModal}
  157. />
  158. </Body>
  159. </Fragment>
  160. ));
  161. };
  162. /**
  163. * This is a workaround to paginate without affecting browserHistory or modifiying the URL
  164. * It's necessary because we don't want to affect the pagination state of other tabs on the page.
  165. */
  166. handleCursor: CursorHandler = async (cursor, _path, query, _direction) => {
  167. const orgSlug = this.props.organization.slug;
  168. const [pathConfigs, _, responseMeta] = await this.api.requestPromise(
  169. `/organizations/${orgSlug}/code-mappings/`,
  170. {includeAllArgs: true, query: {...query, cursor}}
  171. );
  172. this.setState({
  173. pathConfigs,
  174. pathConfigsPageLinks: responseMeta?.getResponseHeader('link'),
  175. });
  176. };
  177. renderBody() {
  178. const pathConfigs = this.pathConfigs;
  179. const {integration} = this.props;
  180. const {pathConfigsPageLinks} = this.state;
  181. const docsLink = `https://docs.sentry.io/product/integrations/source-code-mgmt/${integration.provider.key}/#stack-trace-linking`;
  182. return (
  183. <Fragment>
  184. <TextBlock>
  185. {tct(
  186. `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].`,
  187. {
  188. link: <ExternalLink href={docsLink} onClick={this.trackDocsClick} />,
  189. }
  190. )}
  191. </TextBlock>
  192. <Panel>
  193. <PanelHeader disablePadding hasButtons>
  194. <HeaderLayout>
  195. <NameRepoColumn>{t('Code Mappings')}</NameRepoColumn>
  196. <InputPathColumn>{t('Stack Trace Root')}</InputPathColumn>
  197. <OutputPathColumn>{t('Source Code Root')}</OutputPathColumn>
  198. <ButtonWrapper>
  199. <Button
  200. data-test-id="add-mapping-button"
  201. onClick={() => this.openModal()}
  202. size="xs"
  203. icon={<IconAdd size="xs" isCircled />}
  204. >
  205. {t('Add Code Mapping')}
  206. </Button>
  207. </ButtonWrapper>
  208. </HeaderLayout>
  209. </PanelHeader>
  210. <PanelBody>
  211. {pathConfigs.length === 0 && (
  212. <EmptyMessage
  213. icon={getIntegrationIcon(integration.provider.key, 'lg')}
  214. action={
  215. <Button
  216. href={docsLink}
  217. size="sm"
  218. external
  219. onClick={this.trackDocsClick}
  220. >
  221. {t('View Documentation')}
  222. </Button>
  223. }
  224. >
  225. {t('Set up stack trace linking by adding a code mapping.')}
  226. </EmptyMessage>
  227. )}
  228. {pathConfigs
  229. .map(pathConfig => {
  230. const project = this.getMatchingProject(pathConfig);
  231. // this should never happen since our pathConfig would be deleted
  232. // if project was deleted
  233. if (!project) {
  234. return null;
  235. }
  236. return (
  237. <ConfigPanelItem key={pathConfig.id}>
  238. <Layout>
  239. <RepositoryProjectPathConfigRow
  240. pathConfig={pathConfig}
  241. project={project}
  242. onEdit={this.openModal}
  243. onDelete={this.handleDelete}
  244. />
  245. </Layout>
  246. </ConfigPanelItem>
  247. );
  248. })
  249. .filter(item => !!item)}
  250. </PanelBody>
  251. </Panel>
  252. {pathConfigsPageLinks && (
  253. <Pagination pageLinks={pathConfigsPageLinks} onCursor={this.handleCursor} />
  254. )}
  255. </Fragment>
  256. );
  257. }
  258. }
  259. export default withRouteAnalytics(
  260. withProjects(withOrganization(IntegrationCodeMappings))
  261. );
  262. const Layout = styled('div')`
  263. display: grid;
  264. grid-column-gap: ${space(1)};
  265. width: 100%;
  266. align-items: center;
  267. grid-template-columns: 4.5fr 2.5fr 2.5fr max-content;
  268. grid-template-areas: 'name-repo input-path output-path button';
  269. `;
  270. const HeaderLayout = styled(Layout)`
  271. align-items: center;
  272. margin: 0 ${space(1)} 0 ${space(2)};
  273. `;
  274. const ConfigPanelItem = styled(PanelItem)``;