integrationCodeMappings.tsx 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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 {
  23. getIntegrationIcon,
  24. trackIntegrationAnalytics,
  25. } from 'sentry/utils/integrationUtil';
  26. import withRouteAnalytics, {
  27. WithRouteAnalyticsProps,
  28. } from 'sentry/utils/routeAnalytics/withRouteAnalytics';
  29. import withOrganization from 'sentry/utils/withOrganization';
  30. import withProjects from 'sentry/utils/withProjects';
  31. import TextBlock from 'sentry/views/settings/components/text/textBlock';
  32. import RepositoryProjectPathConfigForm from './repositoryProjectPathConfigForm';
  33. import RepositoryProjectPathConfigRow, {
  34. ButtonWrapper,
  35. InputPathColumn,
  36. NameRepoColumn,
  37. OutputPathColumn,
  38. } from './repositoryProjectPathConfigRow';
  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>
  150. <h4>{t('Configure code path mapping')}</h4>
  151. </Header>
  152. <Body>
  153. <RepositoryProjectPathConfigForm
  154. organization={organization}
  155. integration={integration}
  156. projects={projects}
  157. repos={this.repos}
  158. onSubmitSuccess={config => {
  159. this.handleSubmitSuccess(config);
  160. closeModal();
  161. }}
  162. existingConfig={pathConfig}
  163. onCancel={closeModal}
  164. />
  165. </Body>
  166. </Fragment>
  167. ));
  168. };
  169. /**
  170. * This is a workaround to paginate without affecting browserHistory or modifiying the URL
  171. * It's necessary because we don't want to affect the pagination state of other tabs on the page.
  172. */
  173. handleCursor: CursorHandler = async (cursor, _path, query, _direction) => {
  174. const orgSlug = this.props.organization.slug;
  175. const [pathConfigs, _, responseMeta] = await this.api.requestPromise(
  176. `/organizations/${orgSlug}/code-mappings/`,
  177. {includeAllArgs: true, query: {...query, cursor}}
  178. );
  179. this.setState({
  180. pathConfigs,
  181. pathConfigsPageLinks: responseMeta?.getResponseHeader('link'),
  182. });
  183. };
  184. renderBody() {
  185. const pathConfigs = this.pathConfigs;
  186. const {integration} = this.props;
  187. const {pathConfigsPageLinks} = this.state;
  188. const docsLink = `https://docs.sentry.io/product/integrations/source-code-mgmt/${integration.provider.key}/#stack-trace-linking`;
  189. return (
  190. <Fragment>
  191. <TextBlock>
  192. {tct(
  193. `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].`,
  194. {
  195. link: <ExternalLink href={docsLink} onClick={this.trackDocsClick} />,
  196. }
  197. )}
  198. </TextBlock>
  199. <Panel>
  200. <PanelHeader disablePadding hasButtons>
  201. <HeaderLayout>
  202. <NameRepoColumn>{t('Code Mappings')}</NameRepoColumn>
  203. <InputPathColumn>{t('Stack Trace Root')}</InputPathColumn>
  204. <OutputPathColumn>{t('Source Code Root')}</OutputPathColumn>
  205. <ButtonWrapper>
  206. <Button
  207. data-test-id="add-mapping-button"
  208. onClick={() => this.openModal()}
  209. size="xs"
  210. icon={<IconAdd size="xs" isCircled />}
  211. >
  212. {t('Add Code Mapping')}
  213. </Button>
  214. </ButtonWrapper>
  215. </HeaderLayout>
  216. </PanelHeader>
  217. <PanelBody>
  218. {pathConfigs.length === 0 && (
  219. <EmptyMessage
  220. icon={getIntegrationIcon(integration.provider.key, 'lg')}
  221. action={
  222. <Button
  223. href={docsLink}
  224. size="sm"
  225. external
  226. onClick={this.trackDocsClick}
  227. >
  228. {t('View Documentation')}
  229. </Button>
  230. }
  231. >
  232. {t('Set up stack trace linking by adding a code mapping.')}
  233. </EmptyMessage>
  234. )}
  235. {pathConfigs
  236. .map(pathConfig => {
  237. const project = this.getMatchingProject(pathConfig);
  238. // this should never happen since our pathConfig would be deleted
  239. // if project was deleted
  240. if (!project) {
  241. return null;
  242. }
  243. return (
  244. <ConfigPanelItem key={pathConfig.id}>
  245. <Layout>
  246. <RepositoryProjectPathConfigRow
  247. pathConfig={pathConfig}
  248. project={project}
  249. onEdit={this.openModal}
  250. onDelete={this.handleDelete}
  251. />
  252. </Layout>
  253. </ConfigPanelItem>
  254. );
  255. })
  256. .filter(item => !!item)}
  257. </PanelBody>
  258. </Panel>
  259. {pathConfigsPageLinks && (
  260. <Pagination pageLinks={pathConfigsPageLinks} onCursor={this.handleCursor} />
  261. )}
  262. </Fragment>
  263. );
  264. }
  265. }
  266. export default withRouteAnalytics(
  267. withProjects(withOrganization(IntegrationCodeMappings))
  268. );
  269. const Layout = styled('div')`
  270. display: grid;
  271. grid-column-gap: ${space(1)};
  272. width: 100%;
  273. align-items: center;
  274. grid-template-columns: 4.5fr 2.5fr 2.5fr max-content;
  275. grid-template-areas: 'name-repo input-path output-path button';
  276. `;
  277. const HeaderLayout = styled(Layout)`
  278. align-items: center;
  279. margin: 0 ${space(1)} 0 ${space(2)};
  280. `;
  281. const ConfigPanelItem = styled(PanelItem)``;