integrationRepos.tsx 8.4 KB

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