addCodeOwnerModal.tsx 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. import {Fragment} from 'react';
  2. import styled from '@emotion/styled';
  3. import {addErrorMessage} from 'sentry/actionCreators/indicator';
  4. import {ModalRenderProps} from 'sentry/actionCreators/modal';
  5. import Alert from 'sentry/components/alert';
  6. import AsyncComponent from 'sentry/components/asyncComponent';
  7. import Button from 'sentry/components/button';
  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, PanelBody} from 'sentry/components/panels';
  13. import {IconCheckmark, IconNot} from 'sentry/icons';
  14. import {t, tct} from 'sentry/locale';
  15. import space from 'sentry/styles/space';
  16. import {
  17. CodeOwner,
  18. CodeownersFile,
  19. Integration,
  20. Organization,
  21. Project,
  22. RepositoryProjectPathConfig,
  23. } from 'sentry/types';
  24. import {getIntegrationIcon} from 'sentry/utils/integrationUtil';
  25. type Props = {
  26. organization: Organization;
  27. project: Project;
  28. onSave?: (data: CodeOwner) => void;
  29. } & ModalRenderProps &
  30. AsyncComponent['props'];
  31. type State = {
  32. codeMappingId: string | null;
  33. codeMappings: RepositoryProjectPathConfig[];
  34. codeownersFile: CodeownersFile | null;
  35. error: boolean;
  36. errorJSON: {raw?: string} | null;
  37. integrations: Integration[];
  38. isLoading: boolean;
  39. } & AsyncComponent['state'];
  40. class AddCodeOwnerModal extends AsyncComponent<Props, State> {
  41. getDefaultState() {
  42. return {
  43. ...super.getDefaultState(),
  44. codeownersFile: null,
  45. codeMappingId: null,
  46. isLoading: false,
  47. error: false,
  48. errorJSON: null,
  49. };
  50. }
  51. getEndpoints(): ReturnType<AsyncComponent['getEndpoints']> {
  52. const {organization, project} = this.props;
  53. const endpoints: ReturnType<AsyncComponent['getEndpoints']> = [
  54. [
  55. 'codeMappings',
  56. `/organizations/${organization.slug}/code-mappings/`,
  57. {query: {project: project.id}},
  58. ],
  59. [
  60. 'integrations',
  61. `/organizations/${organization.slug}/integrations/`,
  62. {query: {features: ['codeowners']}},
  63. ],
  64. ];
  65. return endpoints;
  66. }
  67. fetchFile = async (codeMappingId: string) => {
  68. const {organization} = this.props;
  69. this.setState({
  70. codeMappingId,
  71. codeownersFile: null,
  72. error: false,
  73. errorJSON: null,
  74. isLoading: true,
  75. });
  76. try {
  77. const data: CodeownersFile = await this.api.requestPromise(
  78. `/organizations/${organization.slug}/code-mappings/${codeMappingId}/codeowners/`,
  79. {
  80. method: 'GET',
  81. }
  82. );
  83. this.setState({codeownersFile: data, isLoading: false});
  84. } catch (_err) {
  85. this.setState({isLoading: false});
  86. }
  87. };
  88. addFile = async () => {
  89. const {organization, project} = this.props;
  90. const {codeownersFile, codeMappingId, codeMappings} = this.state;
  91. if (codeownersFile) {
  92. const postData: {
  93. codeMappingId: string | null;
  94. raw: string;
  95. } = {
  96. codeMappingId,
  97. raw: codeownersFile.raw,
  98. };
  99. try {
  100. const data = await this.api.requestPromise(
  101. `/projects/${organization.slug}/${project.slug}/codeowners/`,
  102. {
  103. method: 'POST',
  104. data: postData,
  105. }
  106. );
  107. const codeMapping = codeMappings.find(
  108. mapping => mapping.id === codeMappingId?.toString()
  109. );
  110. this.handleAddedFile({...data, codeMapping});
  111. } catch (err) {
  112. if (err.responseJSON.raw) {
  113. this.setState({error: true, errorJSON: err.responseJSON, isLoading: false});
  114. } else {
  115. addErrorMessage(Object.values(err.responseJSON).flat().join(' '));
  116. }
  117. }
  118. }
  119. };
  120. handleAddedFile(data: CodeOwner) {
  121. this.props.onSave && this.props.onSave(data);
  122. this.props.closeModal();
  123. }
  124. sourceFile(codeownersFile: CodeownersFile) {
  125. return (
  126. <Panel>
  127. <SourceFileBody>
  128. <IconCheckmark size="md" isCircled color="green200" />
  129. {codeownersFile.filepath}
  130. <Button size="sm" href={codeownersFile.html_url} external>
  131. {t('Preview File')}
  132. </Button>
  133. </SourceFileBody>
  134. </Panel>
  135. );
  136. }
  137. errorMessage(baseUrl) {
  138. const {errorJSON, codeMappingId, codeMappings} = this.state;
  139. const codeMapping = codeMappings.find(mapping => mapping.id === codeMappingId);
  140. const {integrationId, provider} = codeMapping as RepositoryProjectPathConfig;
  141. const errActors = errorJSON?.raw?.[0].split('\n').map((el, i) => <p key={i}>{el}</p>);
  142. return (
  143. <Alert type="error" showIcon>
  144. {errActors}
  145. {codeMapping && (
  146. <p>
  147. {tct(
  148. 'Configure [userMappingsLink:User Mappings] or [teamMappingsLink:Team Mappings] for any missing associations.',
  149. {
  150. userMappingsLink: (
  151. <Link
  152. to={`${baseUrl}/${provider?.key}/${integrationId}/?tab=userMappings&referrer=add-codeowners`}
  153. />
  154. ),
  155. teamMappingsLink: (
  156. <Link
  157. to={`${baseUrl}/${provider?.key}/${integrationId}/?tab=teamMappings&referrer=add-codeowners`}
  158. />
  159. ),
  160. }
  161. )}
  162. </p>
  163. )}
  164. {tct(
  165. '[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.',
  166. {addAndSkip: <strong>Add and Skip Missing Associations</strong>}
  167. )}
  168. </Alert>
  169. );
  170. }
  171. noSourceFile() {
  172. const {codeMappingId, isLoading} = this.state;
  173. if (isLoading) {
  174. return (
  175. <Container>
  176. <LoadingIndicator mini />
  177. </Container>
  178. );
  179. }
  180. if (!codeMappingId) {
  181. return null;
  182. }
  183. return (
  184. <Panel>
  185. <NoSourceFileBody>
  186. {codeMappingId ? (
  187. <Fragment>
  188. <IconNot size="md" color="red200" />
  189. {t('No codeowner file found.')}
  190. </Fragment>
  191. ) : null}
  192. </NoSourceFileBody>
  193. </Panel>
  194. );
  195. }
  196. renderBody() {
  197. const {Header, Body, Footer} = this.props;
  198. const {codeownersFile, error, errorJSON, codeMappings, integrations} = this.state;
  199. const {organization} = this.props;
  200. const baseUrl = `/settings/${organization.slug}/integrations`;
  201. return (
  202. <Fragment>
  203. <Header closeButton>{t('Add Code Owner File')}</Header>
  204. <Body>
  205. {!codeMappings.length ? (
  206. !integrations.length ? (
  207. <Fragment>
  208. <div>
  209. {t('Install a GitHub or GitLab integration to use this feature.')}
  210. </div>
  211. <Container style={{paddingTop: space(2)}}>
  212. <Button type="button" priority="primary" size="sm" to={baseUrl}>
  213. Setup Integration
  214. </Button>
  215. </Container>
  216. </Fragment>
  217. ) : (
  218. <Fragment>
  219. <div>
  220. {t(
  221. "Configure code mapping to add your CODEOWNERS file. Select the integration you'd like to use for mapping:"
  222. )}
  223. </div>
  224. <IntegrationsList>
  225. {integrations.map(integration => (
  226. <Button
  227. key={integration.id}
  228. type="button"
  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. `;