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