integrationRepos.tsx 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. import {Fragment} from 'react';
  2. import styled from '@emotion/styled';
  3. import debounce from 'lodash/debounce';
  4. import {addRepository, migrateRepository} from 'sentry/actionCreators/integrations';
  5. import {Alert} from 'sentry/components/alert';
  6. import {Button} from 'sentry/components/button';
  7. import DeprecatedAsyncComponent from 'sentry/components/deprecatedAsyncComponent';
  8. import DropdownAutoComplete from 'sentry/components/dropdownAutoComplete';
  9. import DropdownButton from 'sentry/components/dropdownButton';
  10. import EmptyMessage from 'sentry/components/emptyMessage';
  11. import Pagination from 'sentry/components/pagination';
  12. import Panel from 'sentry/components/panels/panel';
  13. import PanelBody from 'sentry/components/panels/panelBody';
  14. import PanelHeader from 'sentry/components/panels/panelHeader';
  15. import RepositoryRow from 'sentry/components/repositoryRow';
  16. import {IconCommit} from 'sentry/icons';
  17. import {t} from 'sentry/locale';
  18. import RepositoryStore from 'sentry/stores/repositoryStore';
  19. import {space} from 'sentry/styles/space';
  20. import type {
  21. Integration,
  22. IntegrationRepository,
  23. Organization,
  24. Repository,
  25. } from 'sentry/types';
  26. import withOrganization from 'sentry/utils/withOrganization';
  27. type Props = DeprecatedAsyncComponent['props'] & {
  28. integration: Integration;
  29. organization: Organization;
  30. };
  31. type State = DeprecatedAsyncComponent['state'] & {
  32. adding: boolean;
  33. dropdownBusy: boolean;
  34. integrationRepos: {
  35. repos: IntegrationRepository[];
  36. searchable: boolean;
  37. };
  38. integrationReposErrorStatus: number | null;
  39. itemList: Repository[];
  40. };
  41. class IntegrationRepos extends DeprecatedAsyncComponent<Props, State> {
  42. getDefaultState(): State {
  43. return {
  44. ...super.getDefaultState(),
  45. adding: false,
  46. itemList: [],
  47. integrationRepos: {repos: [], searchable: false},
  48. integrationReposErrorStatus: null,
  49. dropdownBusy: true,
  50. };
  51. }
  52. componentDidMount() {
  53. super.componentDidMount();
  54. this.searchRepositoriesRequest();
  55. }
  56. getEndpoints(): ReturnType<DeprecatedAsyncComponent['getEndpoints']> {
  57. const orgId = this.props.organization.slug;
  58. return [
  59. [
  60. 'itemList',
  61. `/organizations/${orgId}/repos/`,
  62. {query: {status: 'active', integration_id: this.props.integration.id}},
  63. ],
  64. ];
  65. }
  66. // Called by row to signal repository change.
  67. onRepositoryChange = data => {
  68. const itemList = this.state.itemList;
  69. itemList.forEach(item => {
  70. if (item.id === data.id) {
  71. item.status = data.status;
  72. // allow for custom scm repositories to be updated, and
  73. // url is optional and therefore can be an empty string
  74. item.url = data.url === undefined ? item.url : data.url;
  75. item.name = data.name || item.name;
  76. }
  77. });
  78. this.setState({itemList});
  79. RepositoryStore.resetRepositories();
  80. };
  81. debouncedSearchRepositoriesRequest = debounce(
  82. query => this.searchRepositoriesRequest(query),
  83. 200
  84. );
  85. searchRepositoriesRequest = (searchQuery?: string) => {
  86. const orgId = this.props.organization.slug;
  87. const query = {search: searchQuery};
  88. const endpoint = `/organizations/${orgId}/integrations/${this.props.integration.id}/repos/`;
  89. return this.api.request(endpoint, {
  90. method: 'GET',
  91. query,
  92. success: data => {
  93. this.setState({integrationRepos: data, dropdownBusy: false});
  94. },
  95. error: error => {
  96. this.setState({dropdownBusy: false, integrationReposErrorStatus: error?.status});
  97. },
  98. });
  99. };
  100. handleSearchRepositories = (e?: React.ChangeEvent<HTMLInputElement>) => {
  101. this.setState({dropdownBusy: true, integrationReposErrorStatus: null});
  102. this.debouncedSearchRepositoriesRequest(e?.target.value);
  103. };
  104. addRepo(selection: {label: JSX.Element; searchKey: string; value: string}) {
  105. const {integration} = this.props;
  106. const {itemList} = this.state;
  107. const orgId = this.props.organization.slug;
  108. this.setState({adding: true});
  109. const migratableRepo = itemList.filter(item => {
  110. if (!(selection.value && item.externalSlug)) {
  111. return false;
  112. }
  113. return selection.value === item.externalSlug;
  114. })[0];
  115. let promise: Promise<Repository>;
  116. if (migratableRepo) {
  117. promise = migrateRepository(this.api, orgId, migratableRepo.id, integration);
  118. } else {
  119. promise = addRepository(this.api, orgId, selection.value, integration);
  120. }
  121. promise.then(
  122. (repo: Repository) => {
  123. this.setState({adding: false, itemList: itemList.concat(repo)});
  124. RepositoryStore.resetRepositories();
  125. },
  126. () => this.setState({adding: false})
  127. );
  128. }
  129. renderDropdown() {
  130. if (
  131. !['github', 'gitlab'].includes(this.props.integration.provider.key) &&
  132. !this.props.organization.access.includes('org:integrations')
  133. ) {
  134. return (
  135. <DropdownButton
  136. disabled
  137. title={t(
  138. 'You must be an organization owner, manager or admin to add repositories'
  139. )}
  140. isOpen={false}
  141. size="xs"
  142. >
  143. {t('Add Repository')}
  144. </DropdownButton>
  145. );
  146. }
  147. const repositories = new Set(
  148. this.state.itemList.filter(item => item.integrationId).map(i => i.externalSlug)
  149. );
  150. const repositoryOptions = (this.state.integrationRepos.repos || []).filter(
  151. repo => !repositories.has(repo.identifier)
  152. );
  153. const items = repositoryOptions.map(repo => ({
  154. searchKey: repo.name,
  155. value: repo.identifier,
  156. label: (
  157. <StyledListElement>
  158. <StyledName>{repo.name}</StyledName>
  159. </StyledListElement>
  160. ),
  161. }));
  162. const menuHeader = <StyledReposLabel>{t('Repositories')}</StyledReposLabel>;
  163. const onChange = this.state.integrationRepos.searchable
  164. ? this.handleSearchRepositories
  165. : undefined;
  166. return (
  167. <DropdownAutoComplete
  168. items={items}
  169. onSelect={this.addRepo.bind(this)}
  170. onChange={onChange}
  171. menuHeader={menuHeader}
  172. emptyMessage={t('No repositories available')}
  173. noResultsMessage={t('No repositories found')}
  174. busy={this.state.dropdownBusy}
  175. alignMenu="right"
  176. >
  177. {({isOpen}) => (
  178. <DropdownButton isOpen={isOpen} size="xs" busy={this.state.adding}>
  179. {t('Add Repository')}
  180. </DropdownButton>
  181. )}
  182. </DropdownAutoComplete>
  183. );
  184. }
  185. renderBody() {
  186. const {itemListPageLinks, integrationReposErrorStatus, itemList} = this.state;
  187. const orgId = this.props.organization.slug;
  188. return (
  189. <Fragment>
  190. {integrationReposErrorStatus === 400 && (
  191. <Alert type="error" showIcon>
  192. {t(
  193. 'We were unable to fetch repositories for this integration. Try again later. If this error continues, please reconnect this integration by uninstalling and then reinstalling.'
  194. )}
  195. </Alert>
  196. )}
  197. <Panel>
  198. <PanelHeader hasButtons>
  199. <div>{t('Repositories')}</div>
  200. <DropdownWrapper>{this.renderDropdown()}</DropdownWrapper>
  201. </PanelHeader>
  202. <PanelBody>
  203. {itemList.length === 0 && (
  204. <EmptyMessage
  205. icon={<IconCommit />}
  206. title={t('Sentry is better with commit data')}
  207. description={t(
  208. 'Add a repository to begin tracking its commit data. Then, set up release tracking to unlock features like suspect commits, suggested issue owners, and deploy emails.'
  209. )}
  210. action={
  211. <Button href="https://docs.sentry.io/product/releases/">
  212. {t('Learn More')}
  213. </Button>
  214. }
  215. />
  216. )}
  217. {itemList.map(repo => (
  218. <RepositoryRow
  219. api={this.api}
  220. key={repo.id}
  221. repository={repo}
  222. orgId={orgId}
  223. onRepositoryChange={this.onRepositoryChange}
  224. />
  225. ))}
  226. </PanelBody>
  227. </Panel>
  228. {itemListPageLinks && (
  229. <Pagination pageLinks={itemListPageLinks} {...this.props} />
  230. )}
  231. </Fragment>
  232. );
  233. }
  234. }
  235. export default withOrganization(IntegrationRepos);
  236. const StyledReposLabel = styled('div')`
  237. width: 250px;
  238. font-size: 0.875em;
  239. padding: ${space(1)} 0;
  240. text-transform: uppercase;
  241. `;
  242. const DropdownWrapper = styled('div')`
  243. text-transform: none;
  244. `;
  245. const StyledListElement = styled('div')`
  246. display: flex;
  247. align-items: center;
  248. padding: ${space(0.5)};
  249. `;
  250. const StyledName = styled('div')`
  251. flex-shrink: 1;
  252. min-width: 0;
  253. ${p => p.theme.overflowEllipsis};
  254. `;