addCodeOwnerModal.tsx 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. import {Fragment} from 'react';
  2. import styled from '@emotion/styled';
  3. import {addErrorMessage} from 'sentry/actionCreators/indicator';
  4. import type {ModalRenderProps} from 'sentry/actionCreators/modal';
  5. import {Alert} from 'sentry/components/alert';
  6. import {Button} from 'sentry/components/button';
  7. import DeprecatedAsyncComponent from 'sentry/components/deprecatedAsyncComponent';
  8. import SelectField from 'sentry/components/forms/fields/selectField';
  9. import Form from 'sentry/components/forms/form';
  10. import Link from 'sentry/components/links/link';
  11. import LoadingIndicator from 'sentry/components/loadingIndicator';
  12. import Panel from 'sentry/components/panels/panel';
  13. import PanelBody from 'sentry/components/panels/panelBody';
  14. import {IconCheckmark, IconNot} from 'sentry/icons';
  15. import {t, tct} from 'sentry/locale';
  16. import {space} from 'sentry/styles/space';
  17. import type {
  18. CodeOwner,
  19. CodeownersFile,
  20. Integration,
  21. Organization,
  22. Project,
  23. RepositoryProjectPathConfig,
  24. } from 'sentry/types';
  25. import {getIntegrationIcon} from 'sentry/utils/integrationUtil';
  26. type Props = {
  27. organization: Organization;
  28. project: Project;
  29. onSave?: (data: CodeOwner) => void;
  30. } & ModalRenderProps &
  31. DeprecatedAsyncComponent['props'];
  32. type State = {
  33. codeMappingId: string | null;
  34. codeMappings: RepositoryProjectPathConfig[];
  35. codeownersFile: CodeownersFile | null;
  36. error: boolean;
  37. errorJSON: {raw?: string} | null;
  38. integrations: Integration[];
  39. isLoading: boolean;
  40. } & DeprecatedAsyncComponent['state'];
  41. class AddCodeOwnerModal extends DeprecatedAsyncComponent<Props, State> {
  42. getDefaultState() {
  43. return {
  44. ...super.getDefaultState(),
  45. codeownersFile: null,
  46. codeMappingId: null,
  47. isLoading: false,
  48. error: false,
  49. errorJSON: null,
  50. };
  51. }
  52. getEndpoints(): ReturnType<DeprecatedAsyncComponent['getEndpoints']> {
  53. const {organization, project} = this.props;
  54. const endpoints: ReturnType<DeprecatedAsyncComponent['getEndpoints']> = [
  55. [
  56. 'codeMappings',
  57. `/organizations/${organization.slug}/code-mappings/`,
  58. {query: {project: project.id}},
  59. ],
  60. [
  61. 'integrations',
  62. `/organizations/${organization.slug}/integrations/`,
  63. {query: {features: ['codeowners']}},
  64. ],
  65. ];
  66. return endpoints;
  67. }
  68. fetchFile = async (codeMappingId: string) => {
  69. const {organization} = this.props;
  70. this.setState({
  71. codeMappingId,
  72. codeownersFile: null,
  73. error: false,
  74. errorJSON: null,
  75. isLoading: true,
  76. });
  77. try {
  78. const data: CodeownersFile = await this.api.requestPromise(
  79. `/organizations/${organization.slug}/code-mappings/${codeMappingId}/codeowners/`,
  80. {
  81. method: 'GET',
  82. }
  83. );
  84. this.setState({codeownersFile: data, isLoading: false});
  85. } catch (_err) {
  86. this.setState({isLoading: false});
  87. }
  88. };
  89. addFile = async () => {
  90. const {organization, project} = this.props;
  91. const {codeownersFile, codeMappingId, codeMappings} = this.state;
  92. if (codeownersFile) {
  93. const postData: {
  94. codeMappingId: string | null;
  95. raw: string;
  96. } = {
  97. codeMappingId,
  98. raw: codeownersFile.raw,
  99. };
  100. try {
  101. const data = await this.api.requestPromise(
  102. `/projects/${organization.slug}/${project.slug}/codeowners/`,
  103. {
  104. method: 'POST',
  105. data: postData,
  106. }
  107. );
  108. const codeMapping = codeMappings.find(
  109. mapping => mapping.id === codeMappingId?.toString()
  110. );
  111. this.handleAddedFile({...data, codeMapping});
  112. } catch (err) {
  113. if (err.responseJSON.raw) {
  114. this.setState({error: true, errorJSON: err.responseJSON, isLoading: false});
  115. } else {
  116. addErrorMessage(Object.values(err.responseJSON).flat().join(' '));
  117. }
  118. }
  119. }
  120. };
  121. handleAddedFile(data: CodeOwner) {
  122. this.props.onSave?.(data);
  123. this.props.closeModal();
  124. }
  125. sourceFile(codeownersFile: CodeownersFile) {
  126. return (
  127. <Panel>
  128. <SourceFileBody>
  129. <IconCheckmark size="md" isCircled color="green200" />
  130. {codeownersFile.filepath}
  131. <Button size="sm" href={codeownersFile.html_url} external>
  132. {t('Preview File')}
  133. </Button>
  134. </SourceFileBody>
  135. </Panel>
  136. );
  137. }
  138. errorMessage(baseUrl) {
  139. const {errorJSON, codeMappingId, codeMappings} = this.state;
  140. const codeMapping = codeMappings.find(mapping => mapping.id === codeMappingId);
  141. const {integrationId, provider} = codeMapping as RepositoryProjectPathConfig;
  142. const errActors = errorJSON?.raw?.[0].split('\n').map((el, i) => <p key={i}>{el}</p>);
  143. return (
  144. <Alert type="error" showIcon>
  145. {errActors}
  146. {codeMapping && (
  147. <p>
  148. {tct(
  149. 'Configure [userMappingsLink:User Mappings] or [teamMappingsLink:Team Mappings] for any missing associations.',
  150. {
  151. userMappingsLink: (
  152. <Link
  153. to={`${baseUrl}/${provider?.key}/${integrationId}/?tab=userMappings&referrer=add-codeowners`}
  154. />
  155. ),
  156. teamMappingsLink: (
  157. <Link
  158. to={`${baseUrl}/${provider?.key}/${integrationId}/?tab=teamMappings&referrer=add-codeowners`}
  159. />
  160. ),
  161. }
  162. )}
  163. </p>
  164. )}
  165. {tct(
  166. '[addAndSkip:Add and Skip Missing Associations] will add your codeowner file and skip any rules that having missing associations. You can add associations later for any skipped rules.',
  167. {addAndSkip: <strong>Add and Skip Missing Associations</strong>}
  168. )}
  169. </Alert>
  170. );
  171. }
  172. noSourceFile() {
  173. const {codeMappingId, isLoading} = this.state;
  174. if (isLoading) {
  175. return (
  176. <Container>
  177. <LoadingIndicator mini />
  178. </Container>
  179. );
  180. }
  181. if (!codeMappingId) {
  182. return null;
  183. }
  184. return (
  185. <Panel>
  186. <NoSourceFileBody>
  187. {codeMappingId ? (
  188. <Fragment>
  189. <IconNot size="md" color="red200" />
  190. {t('No codeowner file found.')}
  191. </Fragment>
  192. ) : null}
  193. </NoSourceFileBody>
  194. </Panel>
  195. );
  196. }
  197. renderBody() {
  198. const {Header, Body, Footer} = this.props;
  199. const {codeownersFile, error, errorJSON, codeMappings, integrations} = this.state;
  200. const {organization} = this.props;
  201. const baseUrl = `/settings/${organization.slug}/integrations`;
  202. return (
  203. <Fragment>
  204. <Header closeButton>{t('Add Code Owner File')}</Header>
  205. <Body>
  206. {!codeMappings.length ? (
  207. !integrations.length ? (
  208. <Fragment>
  209. <div>
  210. {t('Install a GitHub or GitLab integration to use this feature.')}
  211. </div>
  212. <Container style={{paddingTop: space(2)}}>
  213. <Button priority="primary" size="sm" to={baseUrl}>
  214. Setup Integration
  215. </Button>
  216. </Container>
  217. </Fragment>
  218. ) : (
  219. <Fragment>
  220. <div>
  221. {t(
  222. "Configure code mapping to add your CODEOWNERS file. Select the integration you'd like to use for mapping:"
  223. )}
  224. </div>
  225. <IntegrationsList>
  226. {integrations.map(integration => (
  227. <Button
  228. key={integration.id}
  229. to={`${baseUrl}/${integration.provider.key}/${integration.id}/?tab=codeMappings&referrer=add-codeowners`}
  230. >
  231. {getIntegrationIcon(integration.provider.key)}
  232. <IntegrationName>{integration.name}</IntegrationName>
  233. </Button>
  234. ))}
  235. </IntegrationsList>
  236. </Fragment>
  237. )
  238. ) : null}
  239. {codeMappings.length > 0 && (
  240. <Form
  241. apiMethod="POST"
  242. apiEndpoint="/code-mappings/"
  243. hideFooter
  244. initialData={{}}
  245. >
  246. <StyledSelectField
  247. name="codeMappingId"
  248. label={t('Apply an existing code mapping')}
  249. options={codeMappings.map((cm: RepositoryProjectPathConfig) => ({
  250. value: cm.id,
  251. label: cm.repoName,
  252. }))}
  253. onChange={this.fetchFile}
  254. required
  255. inline={false}
  256. flexibleControlStateSize
  257. stacked
  258. />
  259. <FileResult>
  260. {codeownersFile ? this.sourceFile(codeownersFile) : this.noSourceFile()}
  261. {error && errorJSON && this.errorMessage(baseUrl)}
  262. </FileResult>
  263. </Form>
  264. )}
  265. </Body>
  266. <Footer>
  267. <Button
  268. disabled={codeownersFile ? false : true}
  269. aria-label={t('Add File')}
  270. priority="primary"
  271. onClick={this.addFile}
  272. >
  273. {t('Add File')}
  274. </Button>
  275. </Footer>
  276. </Fragment>
  277. );
  278. }
  279. }
  280. export default AddCodeOwnerModal;
  281. export {AddCodeOwnerModal};
  282. const StyledSelectField = styled(SelectField)`
  283. border-bottom: None;
  284. padding-right: 16px;
  285. `;
  286. const FileResult = styled('div')`
  287. width: inherit;
  288. `;
  289. const NoSourceFileBody = styled(PanelBody)`
  290. display: grid;
  291. padding: 12px;
  292. grid-template-columns: 30px 1fr;
  293. align-items: center;
  294. `;
  295. const SourceFileBody = styled(PanelBody)`
  296. display: grid;
  297. padding: 12px;
  298. grid-template-columns: 30px 1fr 100px;
  299. align-items: center;
  300. `;
  301. const IntegrationsList = styled('div')`
  302. display: grid;
  303. gap: ${space(1)};
  304. justify-items: center;
  305. margin-top: ${space(2)};
  306. `;
  307. const IntegrationName = styled('p')`
  308. padding-left: 10px;
  309. `;
  310. const Container = styled('div')`
  311. display: flex;
  312. justify-content: center;
  313. `;