hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
sequencelengths
5
5
{ "id": 2, "code_window": [ " disabled,\n", " draggable,\n", " collapsable,\n", " index,\n", " id,\n", "}: QueryOperationRowProps) {\n", " const [isContentVisible, setIsContentVisible] = useState(isOpen !== undefined ? isOpen : true);\n", " const styles = useStyles2(getQueryOperationRowStyles);\n", " const onRowToggle = useCallback(() => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " expanderMessages,\n" ], "file_path": "public/app/core/components/QueryOperationRow/QueryOperationRow.tsx", "type": "add", "edit_start_line_idx": 47 }
import React, { Fragment, useMemo, useState } from 'react'; import { ConfirmModal, useStyles2 } from '@grafana/ui'; import { AlertManagerCortexConfig } from 'app/plugins/datasource/alertmanager/types'; import { useDispatch } from 'app/types'; import { Authorize } from '../../components/Authorize'; import { AlertmanagerAction } from '../../hooks/useAbilities'; import { deleteTemplateAction } from '../../state/actions'; import { getAlertTableStyles } from '../../styles/table'; import { makeAMLink } from '../../utils/misc'; import { CollapseToggle } from '../CollapseToggle'; import { DetailsField } from '../DetailsField'; import { ProvisioningBadge } from '../Provisioning'; import { ActionIcon } from '../rules/ActionIcon'; import { TemplateEditor } from './TemplateEditor'; interface Props { config: AlertManagerCortexConfig; alertManagerName: string; } export const TemplatesTable = ({ config, alertManagerName }: Props) => { const dispatch = useDispatch(); const [expandedTemplates, setExpandedTemplates] = useState<Record<string, boolean>>({}); const tableStyles = useStyles2(getAlertTableStyles); const templateRows = useMemo(() => { const templates = Object.entries(config.template_files); return templates.map(([name, template]) => ({ name, template, provenance: (config.template_file_provenances ?? {})[name], })); }, [config]); const [templateToDelete, setTemplateToDelete] = useState<string>(); const deleteTemplate = () => { if (templateToDelete) { dispatch(deleteTemplateAction(templateToDelete, alertManagerName)); } setTemplateToDelete(undefined); }; return ( <> <table className={tableStyles.table} data-testid="templates-table"> <colgroup> <col className={tableStyles.colExpand} /> <col /> <col /> </colgroup> <thead> <tr> <th></th> <th>Template</th> <Authorize actions={[ AlertmanagerAction.CreateNotificationTemplate, AlertmanagerAction.UpdateNotificationTemplate, AlertmanagerAction.DeleteNotificationTemplate, ]} > <th>Actions</th> </Authorize> </tr> </thead> <tbody> {!templateRows.length && ( <tr className={tableStyles.evenRow}> <td colSpan={3}>No templates defined.</td> </tr> )} {templateRows.map(({ name, template, provenance }, idx) => { const isExpanded = !!expandedTemplates[name]; return ( <Fragment key={name}> <tr key={name} className={idx % 2 === 0 ? tableStyles.evenRow : undefined}> <td> <CollapseToggle isCollapsed={!expandedTemplates[name]} onToggle={() => setExpandedTemplates({ ...expandedTemplates, [name]: !isExpanded })} /> </td> <td> {name} {provenance && <ProvisioningBadge />} </td> <td className={tableStyles.actionsCell}> {provenance && ( <ActionIcon to={makeAMLink( `/alerting/notifications/templates/${encodeURIComponent(name)}/edit`, alertManagerName )} tooltip="view template" icon="file-alt" /> )} {!provenance && ( <Authorize actions={[AlertmanagerAction.UpdateNotificationTemplate]}> <ActionIcon to={makeAMLink( `/alerting/notifications/templates/${encodeURIComponent(name)}/edit`, alertManagerName )} tooltip="edit template" icon="pen" /> </Authorize> )} <Authorize actions={[AlertmanagerAction.CreateContactPoint]}> <ActionIcon to={makeAMLink( `/alerting/notifications/templates/${encodeURIComponent(name)}/duplicate`, alertManagerName )} tooltip="Copy template" icon="copy" /> </Authorize> {!provenance && ( <Authorize actions={[AlertmanagerAction.DeleteNotificationTemplate]}> <ActionIcon onClick={() => setTemplateToDelete(name)} tooltip="delete template" icon="trash-alt" /> </Authorize> )} </td> </tr> {isExpanded && ( <tr className={idx % 2 === 0 ? tableStyles.evenRow : undefined}> <td></td> <td colSpan={2}> <DetailsField label="Description" horizontal={true}> <TemplateEditor width={'auto'} height={'auto'} autoHeight={true} value={template} showLineNumbers={false} monacoOptions={{ readOnly: true, scrollBeyondLastLine: false, }} /> </DetailsField> </td> </tr> )} </Fragment> ); })} </tbody> </table> {!!templateToDelete && ( <ConfirmModal isOpen={true} title="Delete template" body={`Are you sure you want to delete template "${templateToDelete}"?`} confirmText="Yes, delete" onConfirm={deleteTemplate} onDismiss={() => setTemplateToDelete(undefined)} /> )} </> ); };
public/app/features/alerting/unified/components/receivers/TemplatesTable.tsx
0
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.008321557193994522, 0.0006247342680580914, 0.000167529855389148, 0.0001706871553324163, 0.0018667584517970681 ]
{ "id": 2, "code_window": [ " disabled,\n", " draggable,\n", " collapsable,\n", " index,\n", " id,\n", "}: QueryOperationRowProps) {\n", " const [isContentVisible, setIsContentVisible] = useState(isOpen !== undefined ? isOpen : true);\n", " const styles = useStyles2(getQueryOperationRowStyles);\n", " const onRowToggle = useCallback(() => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " expanderMessages,\n" ], "file_path": "public/app/core/components/QueryOperationRow/QueryOperationRow.tsx", "type": "add", "edit_start_line_idx": 47 }
<svg width="180" height="48" viewBox="0 0 180 48" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M0 9.79071V21.7499H15V8.74988H0.626828C0.460583 8.74988 0.301147 8.85954 0.183594 9.05473C0.0660407 9.24992 0 9.51466 0 9.79071Z" fill="url(#paint0_linear_1248_126664)"/> <path d="M15 26.2499H0V39.2499H15V26.2499Z" fill="#84AFF1"/> <path d="M8.5 30H7.07158L5.5 30.9199V32.1738L6.92531 31.3535H6.96266V36H8.5V30Z" fill="#24292E"/> <path d="M19 9.79083V21.75H34V8.75H19.6268C19.4606 8.75 19 8.75 19 8.75C19 8.75 19 9.51479 19 9.79083Z" fill="url(#paint1_linear_1248_126664)"/> <path d="M34 26.25H19V39.25H34V26.25Z" fill="#84AFF1"/> <path d="M26.5739 18.25C25.3778 18.2443 24.2472 17.5199 24.25 15.3812C24.2557 13.4192 25.179 12.25 26.6165 12.25C27.7784 12.25 28.5739 13 28.6903 13.961H27.4773C27.3835 13.5532 27.0625 13.308 26.6165 13.308C25.858 13.308 25.4602 14.0152 25.4545 15.153H25.4943C25.7557 14.6369 26.321 14.3289 26.9602 14.3289C27.9915 14.3289 28.7528 15.1188 28.75 16.2139C28.7528 17.403 27.8693 18.2557 26.5739 18.25ZM26.5682 17.2804C27.1364 17.2804 27.5597 16.8327 27.5568 16.2481C27.5597 15.6692 27.1449 15.2215 26.5767 15.2215C26.0114 15.2215 25.5824 15.6834 25.5795 16.2509C25.5795 16.8213 26 17.2804 26.5682 17.2804Z" fill="#24292E"/> <path d="M26.2292 35.75C27.5585 35.75 28.5028 35.0257 28.5 34.0105C28.5028 33.2918 28.0458 32.7785 27.1708 32.673V32.6274C27.8271 32.5304 28.2923 32.077 28.2895 31.4211C28.2923 30.4686 27.456 29.75 26.2403 29.75C25.0163 29.75 24.1246 30.48 24.1135 31.5181H25.4234C25.4345 31.1188 25.7834 30.8508 26.2403 30.8508C26.6751 30.8508 26.9714 31.1217 26.9686 31.5124C26.9714 31.9173 26.6225 32.1968 26.1185 32.1968H25.5674V33.2006H26.1185C26.6917 33.2006 27.0655 33.4914 27.06 33.9021C27.0655 34.3156 26.7221 34.6036 26.2348 34.6036C25.7501 34.6036 25.3929 34.3384 25.3791 33.9534H24C24.0111 35.0086 24.9332 35.75 26.2292 35.75Z" fill="#24292E"/> <path d="M38 9.79083V21.75H53V8.75H38.6268C38.4606 8.75 38 8.75 38 8.75C38 8.75 38 9.51479 38 9.79083Z" fill="url(#paint2_linear_1248_126664)"/> <path d="M53 26.25H38V39.25H53V26.25Z" fill="#84AFF1"/> <path d="M43.6884 18.25L46.3471 13.3281V13.2871H43.25V12.25H47.75V13.3018L45.0882 18.25H43.6884Z" fill="#24292E"/> <path d="M43 34.6953V33.6963L45.5893 29.75H47.2308V33.6787H48V34.6953H47.2308V35.75H45.977V34.6953H43ZM46.0012 33.6787V31.1328H45.9528L44.3204 33.6318V33.6787H46.0012Z" fill="#24292E"/> <path d="M57 21.7499H72V9.79071C72 9.51466 71.934 9.24992 71.8164 9.05473C71.6989 8.85954 71.5394 8.74988 71.3732 8.74988H57V21.7499Z" fill="url(#paint3_linear_1248_126664)"/> <path d="M72 26.2499H57V39.2499H72V26.2499Z" fill="#84AFF1"/> <path d="M64.4602 35.75C63.0525 35.75 62.0266 35.0188 62 33.9957H63.3944C63.4276 34.4552 63.8891 34.7673 64.4602 34.7673C65.1341 34.7673 65.6155 34.3425 65.6155 33.7269C65.6155 33.1055 65.1242 32.6749 64.4402 32.672C64.0385 32.672 63.6335 32.8251 63.4243 33.0708L62.1461 32.8714L62.4681 29.75H66.6248V30.7731H63.6534L63.4774 32.2558H63.5173C63.7563 31.9639 64.2709 31.7471 64.8685 31.7471C66.0936 31.7471 67.0033 32.5621 67 33.6951C67.0033 34.8916 65.9741 35.75 64.4602 35.75Z" fill="#24292E"/> <path d="M64.4986 18.25C63.1902 18.25 62.2472 17.5456 62.25 16.5989C62.2472 15.8688 62.7994 15.2728 63.5074 15.1559V15.116C62.89 14.9905 62.4624 14.4601 62.4652 13.8213C62.4624 12.9173 63.3233 12.25 64.4986 12.25C65.671 12.25 66.5319 12.9173 66.5348 13.8213C66.5319 14.4629 66.0986 14.9905 65.4926 15.116V15.1559C66.1893 15.2728 66.7472 15.8688 66.75 16.5989C66.7472 17.5456 65.807 18.25 64.4986 18.25ZM64.4986 17.3432C65.0791 17.3432 65.4728 16.9981 65.4728 16.5019C65.4728 15.9971 65.0593 15.6321 64.4986 15.6321C63.935 15.6321 63.5244 15.9971 63.5244 16.5019C63.5244 16.9952 63.9152 17.3432 64.4986 17.3432ZM64.4986 14.7338C64.9857 14.7338 65.3369 14.4116 65.3369 13.9496C65.3369 13.4962 64.9914 13.1797 64.4986 13.1797C64.003 13.1797 63.6603 13.4933 63.6603 13.9496C63.6603 14.4116 64.0087 14.7338 64.4986 14.7338Z" fill="#24292E"/> <path d="M85.9067 30C86.6011 30 91.9327 26 91.9327 24C91.9327 22 86.7357 18 85.9067 18C85.0778 18 84.4023 18.5 84.4023 19.4756C84.4023 20.4512 87.9067 22.9206 87.9067 22.9206C87.9067 22.9206 80.2539 22.25 80 22.9206C79.7461 23.5911 79.7461 24.4089 80 25.0794C80.2539 25.75 87.9067 25.0794 87.9067 25.0794C87.9067 25.0794 84.4023 27.75 84.4023 28.5301C84.4023 29.3103 85.2124 30 85.9067 30Z" fill="#24292E"/> <g clip-path="url(#clip0_1248_126664)"> <path d="M100 0.800641V10H124V0H101.003C100.737 0 100.482 0.084353 100.294 0.234502C100.106 0.384651 100 0.588297 100 0.800641Z" fill="url(#paint4_linear_1248_126664)"/> <path d="M124 13H100V22.5H124V13Z" fill="#84AFF1"/> <path d="M124 25.75H100V35.25H124V25.75Z" fill="#84AFF1"/> <path d="M124 38.5H100V48H112H124V38.5Z" fill="#84AFF1"/> <path d="M113.5 40.25H112.072L110.5 41.1699V42.4238L111.925 41.6035H111.963V46.25H113.5V40.25Z" fill="#24292E"/> <path d="M113.5 14.75H112.072L110.5 15.6699V16.9238L111.925 16.1035H111.963V20.75H113.5V14.75Z" fill="#24292E"/> <path d="M113.5 27.5H112.072L110.5 28.4199V29.6738L111.925 28.8535H111.963V33.5H113.5V27.5Z" fill="#24292E"/> </g> <g clip-path="url(#clip1_1248_126664)"> <path d="M152 13H128V22.5H152V13Z" fill="#84AFF1"/> <path d="M152 25.75H128V35.25H152V25.75Z" fill="#84AFF1"/> <path d="M152 38.5H128V48H140H152V38.5Z" fill="#84AFF1"/> <path d="M128 0.800641V10H152V1.05456e-06H129.003L128 0L128 0.800641Z" fill="url(#paint5_linear_1248_126664)"/> <path d="M139.979 20.75C141.308 20.75 142.253 20.0257 142.25 19.0105C142.253 18.2918 141.796 17.7785 140.921 17.673V17.6274C141.577 17.5304 142.042 17.077 142.04 16.4211C142.042 15.4686 141.206 14.75 139.99 14.75C138.766 14.75 137.875 15.48 137.864 16.5181H139.173C139.184 16.1188 139.533 15.8508 139.99 15.8508C140.425 15.8508 140.721 16.1217 140.719 16.5124C140.721 16.9173 140.372 17.1968 139.868 17.1968H139.317V18.2006H139.868C140.442 18.2006 140.816 18.4914 140.81 18.9021C140.816 19.3156 140.472 19.6036 139.985 19.6036C139.5 19.6036 139.143 19.3384 139.129 18.9534H137.75C137.761 20.0086 138.683 20.75 139.979 20.75Z" fill="#24292E"/> <path d="M137.75 32.4453V31.4463L140.339 27.5H141.981V31.4287H142.75V32.4453H141.981V33.5H140.727V32.4453H137.75ZM140.751 31.4287V28.8828H140.703L139.07 31.3818V31.4287H140.751Z" fill="#24292E"/> <path d="M140.21 46.25C138.802 46.25 137.777 45.5188 137.75 44.4957H139.144C139.178 44.9552 139.639 45.2673 140.21 45.2673C140.884 45.2673 141.366 44.8425 141.366 44.2269C141.366 43.6055 140.874 43.1749 140.19 43.172C139.789 43.172 139.383 43.3251 139.174 43.5708L137.896 43.3714L138.218 40.25H142.375V41.2731H139.403L139.227 42.7558H139.267C139.506 42.4639 140.021 42.2471 140.619 42.2471C141.844 42.2471 142.753 43.0621 142.75 44.1951C142.753 45.3916 141.724 46.25 140.21 46.25Z" fill="#24292E"/> </g> <g clip-path="url(#clip2_1248_126664)"> <path d="M180 13H156V22.5H180V13Z" fill="#84AFF1"/> <path d="M180 25.75H156V35.25H180V25.75Z" fill="#84AFF1"/> <path d="M180 38.5H156V48H168H180V38.5Z" fill="#84AFF1"/> <path d="M156 10H180V0.800641C180 0.588297 179.894 0.384651 179.706 0.234502C179.518 0.084353 179.263 0 178.997 0L156 0V10Z" fill="url(#paint6_linear_1248_126664)"/> <path d="M167.999 46.25C166.69 46.25 165.747 45.5456 165.75 44.5989C165.747 43.8688 166.299 43.2728 167.007 43.1559V43.116C166.39 42.9905 165.962 42.4601 165.965 41.8213C165.962 40.9173 166.823 40.25 167.999 40.25C169.171 40.25 170.032 40.9173 170.035 41.8213C170.032 42.4629 169.599 42.9905 168.993 43.116V43.1559C169.689 43.2728 170.247 43.8688 170.25 44.5989C170.247 45.5456 169.307 46.25 167.999 46.25ZM167.999 45.3432C168.579 45.3432 168.973 44.9981 168.973 44.5019C168.973 43.9971 168.559 43.6321 167.999 43.6321C167.435 43.6321 167.024 43.9971 167.024 44.5019C167.024 44.9952 167.415 45.3432 167.999 45.3432ZM167.999 42.7338C168.486 42.7338 168.837 42.4116 168.837 41.9496C168.837 41.4962 168.491 41.1797 167.999 41.1797C167.503 41.1797 167.16 41.4933 167.16 41.9496C167.16 42.4116 167.509 42.7338 167.999 42.7338Z" fill="#24292E"/> <path d="M166.188 33.5L168.847 28.5781V28.5371H165.75V27.5H170.25V28.5518L167.588 33.5H166.188Z" fill="#24292E"/> <path d="M168.074 20.75C166.878 20.7443 165.747 20.0199 165.75 17.8812C165.756 15.9192 166.679 14.75 168.116 14.75C169.278 14.75 170.074 15.5 170.19 16.461H168.977C168.884 16.0532 168.562 15.808 168.116 15.808C167.358 15.808 166.96 16.5152 166.955 17.653H166.994C167.256 17.1369 167.821 16.8289 168.46 16.8289C169.491 16.8289 170.253 17.6188 170.25 18.7139C170.253 19.903 169.369 20.7557 168.074 20.75ZM168.068 19.7804C168.636 19.7804 169.06 19.3327 169.057 18.7481C169.06 18.1692 168.645 17.7215 168.077 17.7215C167.511 17.7215 167.082 18.1834 167.08 18.7509C167.08 19.3213 167.5 19.7804 168.068 19.7804Z" fill="#24292E"/> </g> <defs> <linearGradient id="paint0_linear_1248_126664" x1="0" y1="15.2551" x2="15" y2="15.2551" gradientUnits="userSpaceOnUse"> <stop stop-color="#F2CC0C"/> <stop offset="1" stop-color="#FF9830"/> </linearGradient> <linearGradient id="paint1_linear_1248_126664" x1="19" y1="15.2552" x2="34" y2="15.2552" gradientUnits="userSpaceOnUse"> <stop stop-color="#F2CC0C"/> <stop offset="1" stop-color="#FF9830"/> </linearGradient> <linearGradient id="paint2_linear_1248_126664" x1="38" y1="15.2552" x2="53" y2="15.2552" gradientUnits="userSpaceOnUse"> <stop stop-color="#F2CC0C"/> <stop offset="1" stop-color="#FF9830"/> </linearGradient> <linearGradient id="paint3_linear_1248_126664" x1="57" y1="15.2551" x2="72" y2="15.2551" gradientUnits="userSpaceOnUse"> <stop stop-color="#F2CC0C"/> <stop offset="1" stop-color="#FF9830"/> </linearGradient> <linearGradient id="paint4_linear_1248_126664" x1="100" y1="5.004" x2="124" y2="5.004" gradientUnits="userSpaceOnUse"> <stop stop-color="#F2CC0C"/> <stop offset="1" stop-color="#FF9830"/> </linearGradient> <linearGradient id="paint5_linear_1248_126664" x1="128.008" y1="5.004" x2="152.008" y2="5.004" gradientUnits="userSpaceOnUse"> <stop stop-color="#F2CC0C"/> <stop offset="1" stop-color="#FF9830"/> </linearGradient> <linearGradient id="paint6_linear_1248_126664" x1="156" y1="5.004" x2="180" y2="5.004" gradientUnits="userSpaceOnUse"> <stop stop-color="#F2CC0C"/> <stop offset="1" stop-color="#FF9830"/> </linearGradient> <clipPath id="clip0_1248_126664"> <rect width="24" height="48" fill="white" transform="translate(100)"/> </clipPath> <clipPath id="clip1_1248_126664"> <rect width="24" height="48" fill="white" transform="translate(128)"/> </clipPath> <clipPath id="clip2_1248_126664"> <rect width="24" height="48" fill="white" transform="translate(156)"/> </clipPath> </defs> </svg>
public/img/transformations/light/prepareTimeSeries.svg
0
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.0007734678802080452, 0.00024755613412708044, 0.00016554980538785458, 0.0001755134726408869, 0.00018679958884604275 ]
{ "id": 3, "code_window": [ " onRowToggle={onRowToggle}\n", " reportDragMousePosition={reportDragMousePosition}\n", " title={title}\n", " />\n", " </div>\n", " {isContentVisible && <div className={styles.content}>{children}</div>}\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " expanderMessages={expanderMessages}\n" ], "file_path": "public/app/core/components/QueryOperationRow/QueryOperationRow.tsx", "type": "add", "edit_start_line_idx": 125 }
import { css, cx } from '@emotion/css'; import React, { MouseEventHandler } from 'react'; import { DraggableProvided } from 'react-beautiful-dnd'; import { GrafanaTheme2 } from '@grafana/data'; import { Stack } from '@grafana/experimental'; import { IconButton, useStyles2 } from '@grafana/ui'; export interface QueryOperationRowHeaderProps { actionsElement?: React.ReactNode; disabled?: boolean; draggable: boolean; collapsable?: boolean; dragHandleProps?: DraggableProvided['dragHandleProps']; headerElement?: React.ReactNode; isContentVisible: boolean; onRowToggle: () => void; reportDragMousePosition: MouseEventHandler<HTMLButtonElement>; title?: string; id: string; } export const QueryOperationRowHeader = ({ actionsElement, disabled, draggable, collapsable = true, dragHandleProps, headerElement, isContentVisible, onRowToggle, reportDragMousePosition, title, id, }: QueryOperationRowHeaderProps) => { const styles = useStyles2(getStyles); return ( <div className={styles.header}> <div className={styles.column}> {collapsable && ( <IconButton name={isContentVisible ? 'angle-down' : 'angle-right'} tooltip={isContentVisible ? 'Collapse query row' : 'Expand query row'} className={styles.collapseIcon} onClick={onRowToggle} aria-expanded={isContentVisible} aria-controls={id} /> )} {title && ( // disabling the a11y rules here as the IconButton above handles keyboard interactions // this is just to provide a better experience for mouse users // eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions <div className={styles.titleWrapper} onClick={onRowToggle} aria-label="Query operation row title"> <div className={cx(styles.title, disabled && styles.disabled)}>{title}</div> </div> )} {headerElement} </div> <Stack gap={1} alignItems="center" wrap={false}> {actionsElement} {draggable && ( <IconButton title="Drag and drop to reorder" name="draggabledots" tooltip="Drag and drop to reorder" tooltipPlacement="bottom" size="lg" className={styles.dragIcon} onMouseMove={reportDragMousePosition} {...dragHandleProps} /> )} </Stack> </div> ); }; const getStyles = (theme: GrafanaTheme2) => ({ header: css` label: Header; padding: ${theme.spacing(0.5, 0.5)}; border-radius: ${theme.shape.radius.default}; background: ${theme.colors.background.secondary}; min-height: ${theme.spacing(4)}; display: grid; grid-template-columns: minmax(100px, max-content) min-content; align-items: center; justify-content: space-between; white-space: nowrap; &:focus { outline: none; } `, column: css` label: Column; display: flex; align-items: center; `, dragIcon: css` cursor: grab; color: ${theme.colors.text.disabled}; margin: ${theme.spacing(0, 0.5)}; &:hover { color: ${theme.colors.text}; } `, collapseIcon: css` margin-left: ${theme.spacing(0.5)}; color: ${theme.colors.text.disabled}; } `, titleWrapper: css` display: flex; align-items: center; flex-grow: 1; cursor: pointer; overflow: hidden; margin-right: ${theme.spacing(0.5)}; `, title: css` font-weight: ${theme.typography.fontWeightBold}; color: ${theme.colors.text.link}; margin-left: ${theme.spacing(0.5)}; overflow: hidden; text-overflow: ellipsis; `, disabled: css` color: ${theme.colors.text.disabled}; `, }); QueryOperationRowHeader.displayName = 'QueryOperationRowHeader';
public/app/core/components/QueryOperationRow/QueryOperationRowHeader.tsx
1
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.7654998302459717, 0.11052898317575455, 0.00016355262778233737, 0.00017540747649036348, 0.2671024203300476 ]
{ "id": 3, "code_window": [ " onRowToggle={onRowToggle}\n", " reportDragMousePosition={reportDragMousePosition}\n", " title={title}\n", " />\n", " </div>\n", " {isContentVisible && <div className={styles.content}>{children}</div>}\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " expanderMessages={expanderMessages}\n" ], "file_path": "public/app/core/components/QueryOperationRow/QueryOperationRow.tsx", "type": "add", "edit_start_line_idx": 125 }
--- aliases: - metrics/ - unified-alerting/fundamentals/ canonical: https://grafana.com/docs/grafana/latest/alerting/fundamentals/ description: Intro to the key concepts in Alerting and how it works labels: products: - cloud - enterprise - oss menuTitle: Introduction title: Introduction to Alerting weight: 105 --- # Introduction to Alerting Whether you’re starting or expanding your implementation of Grafana Alerting, learn more about the key concepts and available features that help you create, manage, and take action on your alerts and improve your team’s ability to resolve issues quickly. The following diagram gives you an overview of how Grafana Alerting works and introduces you to some of the key concepts that work together and form the core of our flexible and powerful alerting engine. {{< figure src="/media/docs/alerting/how-alerting-works.png" max-width="750px" caption="How Alerting works" >}} You can either create your alerting resources (alert rules, notification policies, and so on) directly in the Grafana UI, using provisioning, or in your Grafana Mimir or Loki instances. **Alert rules** An alert rule is a set of evaluation criteria for when an alert rule should fire. An alert rule consists of one or more queries and expressions, a condition, and the duration over which the condition needs to be met to start firing. Add annotations to your alert rule to provide additional information about the alert rule and add labels to uniquely identify your alert rule and configure alert routing. Labels link alert rules to notification policies, so you can easily manage which policy should handle which alerts and who gets notified. Once alert rules are created, they go through various states and transitions. An alert rule can produce multiple alert instances - one alert instance for each time series. The alert rule state is determined by the “worst case” state of the alert instances produced and the states can be Normal, Pending, or Firing. For example, if one alert instance is firing, the alert rule state will also be firing. The alert rule health is determined by the status of the evaluation of the alert rule, which can be Ok, Error, and NoData. **Alert instances** For Grafana-managed alert rules, multiple alert instances can be created as a result of one alert rule (also known as a multi-dimensional alerting). Both Grafana-managed alert and Mimir or Loki-managed alert instances can be in Normal, Pending, Alerting, No Data, Error states. **Note:** For Mimir or Loki-managed alert rules, alert instances are only created when the threshold condition defined in an alert rule is breached. Alerting alert instances are grouped by labels according to the notification policy. This controls de-duplication and groups alert instances to send to your contact points. **Notification policy** Set where, when, and how firing alert instances get routed. Each notification policy contains a set of label matchers to indicate which alerts rules or instances it is responsible for. It also has a contact point assigned to it that consists of one or more contact point types, such as Slack or email. Contact points define how your contacts are notified when an alert instance fires. For more information on notification policies, see [fundamentals of Notification Policies][notification-policies]. **Message templates** Use message templates for your notifications to create reusable custom templates and use them in contact points. **Silences and mute timings** Add silences to stop notifications from one or more alert instances or use mute timings to specify time intervals when you don’t want new notifications to be generated or sent out. The difference between the two being that a silence only lasts for only a specified window of time whereas a mute timing recurs on a schedule, for example, during a maintenance period. {{% docs/reference %}} [notification-policies]: "/docs/grafana/ -> /docs/grafana/<GRAFANA VERSION>/alerting/fundamentals/notification-policies" [notification-policies]: "/docs/grafana-cloud/ -> /docs/grafana-cloud/alerting-and-irm/alerting/fundamentals/notification-policies" {{% /docs/reference %}}
docs/sources/alerting/fundamentals/_index.md
0
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.0001752806711010635, 0.00016942419460974634, 0.0001654920488363132, 0.00016958593914750963, 0.000003317148639325751 ]
{ "id": 3, "code_window": [ " onRowToggle={onRowToggle}\n", " reportDragMousePosition={reportDragMousePosition}\n", " title={title}\n", " />\n", " </div>\n", " {isContentVisible && <div className={styles.content}>{children}</div>}\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " expanderMessages={expanderMessages}\n" ], "file_path": "public/app/core/components/QueryOperationRow/QueryOperationRow.tsx", "type": "add", "edit_start_line_idx": 125 }
{ "schema": { "name": "cpu", "fields": [ { "name": "labels", "type": "string", "typeInfo": { "frame": "string" } }, { "name": "time", "type": "time", "typeInfo": { "frame": "time.Time" } }, { "name": "usage_guest", "type": "number", "typeInfo": { "frame": "float64", "nullable": true } }, { "name": "usage_guest_nice", "type": "number", "typeInfo": { "frame": "float64", "nullable": true } }, { "name": "usage_idle", "type": "number", "typeInfo": { "frame": "float64", "nullable": true } }, { "name": "usage_iowait", "type": "number", "typeInfo": { "frame": "float64", "nullable": true } }, { "name": "usage_irq", "type": "number", "typeInfo": { "frame": "float64", "nullable": true } }, { "name": "usage_nice", "type": "number", "typeInfo": { "frame": "float64", "nullable": true } }, { "name": "usage_softirq", "type": "number", "typeInfo": { "frame": "float64", "nullable": true } }, { "name": "usage_steal", "type": "number", "typeInfo": { "frame": "float64", "nullable": true } }, { "name": "usage_system", "type": "number", "typeInfo": { "frame": "float64", "nullable": true } }, { "name": "usage_user", "type": "number", "typeInfo": { "frame": "float64", "nullable": true } } ] }, "data": { "values": [ [ "cpu=cpu0, host=MacBook-Pro-Alexander.local", "cpu=cpu1, host=MacBook-Pro-Alexander.local", "cpu=cpu2, host=MacBook-Pro-Alexander.local", "cpu=cpu3, host=MacBook-Pro-Alexander.local", "cpu=cpu4, host=MacBook-Pro-Alexander.local", "cpu=cpu5, host=MacBook-Pro-Alexander.local", "cpu=cpu6, host=MacBook-Pro-Alexander.local", "cpu=cpu7, host=MacBook-Pro-Alexander.local", "cpu=cpu8, host=MacBook-Pro-Alexander.local", "cpu=cpu9, host=MacBook-Pro-Alexander.local", "cpu=cpu10, host=MacBook-Pro-Alexander.local", "cpu=cpu11, host=MacBook-Pro-Alexander.local", "cpu=cpu-total, host=MacBook-Pro-Alexander.local" ], [ 1616403090000, 1616403090000, 1616403090000, 1616403090000, 1616403090000, 1616403090000, 1616403090000, 1616403090000, 1616403090000, 1616403090000, 1616403090000, 1616403090000, 1616403090000 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 82.00000000012005, 100, 88.23529411773097, 100, 91.91919191902859, 100, 93.0000000000291, 100, 95.04950495055924, 100, 100, 100, 95.8368026645606 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 6.000000000005457, 0, 4.901960784315911, 0, 3.0303030303011163, 0, 2.000000000001023, 0, 1.9801980198033176, 0, 0, 0, 1.4987510408004405 ], [ 12.000000000033651, 0, 6.862745098042275, 0, 5.0505050504922915, 0, 5.000000000006821, 0, 2.970297029704976, 0, 0, 0, 2.6644462947563388 ] ] } }
pkg/services/live/telemetry/telegraf/testdata/golden_labels_column.json
0
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.00017502947594039142, 0.00017101784760598093, 0.00016824381600599736, 0.0001711318618617952, 0.000001959688461283804 ]
{ "id": 3, "code_window": [ " onRowToggle={onRowToggle}\n", " reportDragMousePosition={reportDragMousePosition}\n", " title={title}\n", " />\n", " </div>\n", " {isContentVisible && <div className={styles.content}>{children}</div>}\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " expanderMessages={expanderMessages}\n" ], "file_path": "public/app/core/components/QueryOperationRow/QueryOperationRow.tsx", "type": "add", "edit_start_line_idx": 125 }
{ "cost": 0, "timespan": "2019-02-08T10:13:50Z\/2019-02-08T16:13:50Z", "interval": "PT1M", "value": [ { "id": "\/subscriptions\/xxx\/resourceGroups\/grafanastaging\/providers\/Microsoft.Compute\/virtualMachines\/grafana\/providers\/Microsoft.Insights\/metrics\/Percentage CPU", "type": "Microsoft.Insights\/metrics", "name": { "value": "Percentage CPU", "localizedValue": "Percentage CPU" }, "unit": "Unspecified", "timeseries": [ { "metadatavalues": [ ], "data": [ { "timeStamp": "2019-02-08T10:13:00Z", "average": 2.0875 } ] } ] } ], "namespace": "Microsoft.Compute\/virtualMachines", "resourceregion": "westeurope" }
pkg/tsdb/azuremonitor/testdata/azuremonitor/8-azure-monitor-response-unspecified-unit.json
0
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.00017180221038870513, 0.00017078132077585906, 0.00017004854453261942, 0.000170637242263183, 6.667872298748989e-7 ]
{ "id": 4, "code_window": [ " isContentVisible={isContentVisible}\n", " onRowToggle={onRowToggle}\n", " reportDragMousePosition={reportDragMousePosition}\n", " title={title}\n", " />\n", " {isContentVisible && <div className={styles.content}>{children}</div>}\n", " </div>\n", " );\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " expanderMessages={expanderMessages}\n" ], "file_path": "public/app/core/components/QueryOperationRow/QueryOperationRow.tsx", "type": "add", "edit_start_line_idx": 149 }
import React, { useCallback } from 'react'; import { useToggle } from 'react-use'; import { DataFrame, DataTransformerConfig, TransformerRegistryItem, FrameMatcherID } from '@grafana/data'; import { reportInteraction } from '@grafana/runtime'; import { ConfirmModal } from '@grafana/ui'; import { OperationRowHelp } from 'app/core/components/QueryOperationRow/OperationRowHelp'; import { QueryOperationAction, QueryOperationToggleAction, } from 'app/core/components/QueryOperationRow/QueryOperationAction'; import { QueryOperationRow, QueryOperationRowRenderProps, } from 'app/core/components/QueryOperationRow/QueryOperationRow'; import config from 'app/core/config'; import { PluginStateInfo } from 'app/features/plugins/components/PluginStateInfo'; import { TransformationEditor } from './TransformationEditor'; import { TransformationFilter } from './TransformationFilter'; import { TransformationsEditorTransformation } from './types'; interface TransformationOperationRowProps { id: string; index: number; data: DataFrame[]; uiConfig: TransformerRegistryItem<null>; configs: TransformationsEditorTransformation[]; onRemove: (index: number) => void; onChange: (index: number, config: DataTransformerConfig) => void; } export const TransformationOperationRow = ({ onRemove, index, id, data, configs, uiConfig, onChange, }: TransformationOperationRowProps) => { const [showDeleteModal, setShowDeleteModal] = useToggle(false); const [showDebug, toggleShowDebug] = useToggle(false); const [showHelp, toggleShowHelp] = useToggle(false); const disabled = !!configs[index].transformation.disabled; const filter = configs[index].transformation.filter != null; const showFilter = filter || data.length > 1; const onDisableToggle = useCallback( (index: number) => { const current = configs[index].transformation; onChange(index, { ...current, disabled: current.disabled ? undefined : true, }); }, [onChange, configs] ); const toggleExpand = useCallback(() => { if (showHelp) { return true; } // We return `undefined` here since the QueryOperationRow component ignores an `undefined` value for the `isOpen` prop. // If we returned `false` here, the row would be collapsed when the user toggles off `showHelp`, which is not what we want. return undefined; }, [showHelp]); // Adds or removes the frame filter const toggleFilter = useCallback(() => { let current = { ...configs[index].transformation }; if (current.filter) { delete current.filter; } else { current.filter = { id: FrameMatcherID.byRefId, options: '', // empty string will not do anything }; } onChange(index, current); }, [onChange, index, configs]); // Instrument toggle callback const instrumentToggleCallback = useCallback( (callback: (e: React.MouseEvent) => void, toggleId: string, active: boolean | undefined) => (e: React.MouseEvent) => { let eventName = 'panel_editor_tabs_transformations_toggle'; if (config.featureToggles.transformationsRedesign) { eventName = 'transformations_redesign_' + eventName; } reportInteraction(eventName, { action: active ? 'off' : 'on', toggleId, transformationId: configs[index].transformation.id, }); callback(e); }, [configs, index] ); const renderActions = ({ isOpen }: QueryOperationRowRenderProps) => { return ( <> {uiConfig.state && <PluginStateInfo state={uiConfig.state} />} <QueryOperationToggleAction title="Show transform help" icon="info-circle" // `instrumentToggleCallback` expects a function that takes a MouseEvent, is unused in the state setter. Instead, we simply toggle the state. onClick={instrumentToggleCallback((_e) => toggleShowHelp(!showHelp), 'help', showHelp)} active={!!showHelp} /> {showFilter && ( <QueryOperationToggleAction title="Filter" icon="filter" onClick={instrumentToggleCallback(toggleFilter, 'filter', filter)} active={filter} /> )} <QueryOperationToggleAction title="Debug" disabled={!isOpen} icon="bug" onClick={instrumentToggleCallback(toggleShowDebug, 'debug', showDebug)} active={showDebug} /> <QueryOperationToggleAction title="Disable transformation" icon={disabled ? 'eye-slash' : 'eye'} onClick={instrumentToggleCallback(() => onDisableToggle(index), 'disabled', disabled)} active={disabled} /> <QueryOperationAction title="Remove" icon="trash-alt" onClick={() => (config.featureToggles.transformationsRedesign ? setShowDeleteModal(true) : onRemove(index))} /> {config.featureToggles.transformationsRedesign && ( <ConfirmModal isOpen={showDeleteModal} title={`Delete ${uiConfig.name}?`} body="Note that removing one transformation may break others. If there is only a single transformation, you will go back to the main selection screen." confirmText="Delete" onConfirm={() => { setShowDeleteModal(false); onRemove(index); }} onDismiss={() => setShowDeleteModal(false)} /> )} </> ); }; return ( <QueryOperationRow id={id} index={index} title={uiConfig.name} draggable actions={renderActions} disabled={disabled} isOpen={toggleExpand()} // Assure that showHelp is untoggled when the row becomes collapsed. onClose={() => toggleShowHelp(false)} > {showHelp && <OperationRowHelp markdown={prepMarkdown(uiConfig)} />} {filter && ( <TransformationFilter index={index} config={configs[index].transformation} data={data} onChange={onChange} /> )} <TransformationEditor debugMode={showDebug} index={index} data={data} configs={configs} uiConfig={uiConfig} onChange={onChange} /> </QueryOperationRow> ); }; function prepMarkdown(uiConfig: TransformerRegistryItem<null>) { let helpMarkdown = uiConfig.help ?? uiConfig.description; return ` ${helpMarkdown} Go the <a href="https://grafana.com/docs/grafana/latest/panels/transformations/?utm_source=grafana" target="_blank" rel="noreferrer"> transformation documentation </a> for more. `; }
public/app/features/dashboard/components/TransformationsEditor/TransformationOperationRow.tsx
1
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.0006139035103842616, 0.00019848777446895838, 0.00016541333752684295, 0.0001710558426566422, 0.00009715251508168876 ]
{ "id": 4, "code_window": [ " isContentVisible={isContentVisible}\n", " onRowToggle={onRowToggle}\n", " reportDragMousePosition={reportDragMousePosition}\n", " title={title}\n", " />\n", " {isContentVisible && <div className={styles.content}>{children}</div>}\n", " </div>\n", " );\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " expanderMessages={expanderMessages}\n" ], "file_path": "public/app/core/components/QueryOperationRow/QueryOperationRow.tsx", "type": "add", "edit_start_line_idx": 149 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M15.71,6.29l-5.3,5.3L8.29,9.47a1,1,0,1,0-1.41,1.41l2.83,2.83a1,1,0,0,0,.7.29,1,1,0,0,0,.71-.29l6-6a1,1,0,0,0,0-1.42A1,1,0,0,0,15.71,6.29ZM19,2H5A3,3,0,0,0,2,5V15a3,3,0,0,0,3,3H16.59l3.7,3.71A1,1,0,0,0,21,22a.84.84,0,0,0,.38-.08A1,1,0,0,0,22,21V5A3,3,0,0,0,19,2Zm1,16.59-2.29-2.3A1,1,0,0,0,17,16H5a1,1,0,0,1-1-1V5A1,1,0,0,1,5,4H19a1,1,0,0,1,1,1Z"/></svg>
public/img/icons/unicons/comment-alt-verify.svg
0
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.00017331064736936241, 0.00017331064736936241, 0.00017331064736936241, 0.00017331064736936241, 0 ]
{ "id": 4, "code_window": [ " isContentVisible={isContentVisible}\n", " onRowToggle={onRowToggle}\n", " reportDragMousePosition={reportDragMousePosition}\n", " title={title}\n", " />\n", " {isContentVisible && <div className={styles.content}>{children}</div>}\n", " </div>\n", " );\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " expanderMessages={expanderMessages}\n" ], "file_path": "public/app/core/components/QueryOperationRow/QueryOperationRow.tsx", "type": "add", "edit_start_line_idx": 149 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M21,11a1,1,0,0,0-1,1v2.59l-6.29-6.3a1,1,0,0,0-1.42,0L9,11.59,3.71,6.29A1,1,0,0,0,2.29,7.71l6,6a1,1,0,0,0,1.42,0L13,10.41,18.59,16H16a1,1,0,0,0,0,2h5a1,1,0,0,0,.38-.08,1,1,0,0,0,.54-.54A1,1,0,0,0,22,17V12A1,1,0,0,0,21,11Z"/></svg>
public/img/icons/unicons/chart-down.svg
0
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.0001745911140460521, 0.0001745911140460521, 0.0001745911140460521, 0.0001745911140460521, 0 ]
{ "id": 4, "code_window": [ " isContentVisible={isContentVisible}\n", " onRowToggle={onRowToggle}\n", " reportDragMousePosition={reportDragMousePosition}\n", " title={title}\n", " />\n", " {isContentVisible && <div className={styles.content}>{children}</div>}\n", " </div>\n", " );\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " expanderMessages={expanderMessages}\n" ], "file_path": "public/app/core/components/QueryOperationRow/QueryOperationRow.tsx", "type": "add", "edit_start_line_idx": 149 }
.singlestat-panel { position: relative; display: table; width: 100%; height: 100%; } .singlestat-panel-value-container { display: table-cell; vertical-align: middle; text-align: center; position: relative; z-index: 1; font-weight: $font-weight-semi-bold; line-height: 1; } // Helps .panel-container--no-title { .singlestat-panel-value-container { padding-bottom: 0; } } .singlestat-panel-prefix { padding-right: 20px; } #flotGaugeValue0 { font-weight: $font-weight-semi-bold; //please dont hurt me for this! }
public/sass/components/_panel_singlestat.scss
0
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.00017641815065871924, 0.00017353249131701887, 0.00017103072605095804, 0.00017334052245132625, 0.000002488430027369759 ]
{ "id": 5, "code_window": [ " isContentVisible: boolean;\n", " onRowToggle: () => void;\n", " reportDragMousePosition: MouseEventHandler<HTMLButtonElement>;\n", " title?: string;\n", " id: string;\n", "}\n", "\n", "export const QueryOperationRowHeader = ({\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " expanderMessages?: ExpanderMessages;\n", "}\n", "\n", "export interface ExpanderMessages {\n", " open: string;\n", " close: string;\n" ], "file_path": "public/app/core/components/QueryOperationRow/QueryOperationRowHeader.tsx", "type": "add", "edit_start_line_idx": 20 }
import { css } from '@emotion/css'; import React, { useCallback, useEffect, useState } from 'react'; import { Draggable } from 'react-beautiful-dnd'; import { useUpdateEffect } from 'react-use'; import { GrafanaTheme2 } from '@grafana/data'; import { reportInteraction } from '@grafana/runtime'; import { ReactUtils, useStyles2 } from '@grafana/ui'; import { QueryOperationRowHeader } from './QueryOperationRowHeader'; export interface QueryOperationRowProps { index: number; id: string; title?: string; headerElement?: QueryOperationRowRenderProp; actions?: QueryOperationRowRenderProp; onOpen?: () => void; onClose?: () => void; children: React.ReactNode; isOpen?: boolean; draggable?: boolean; collapsable?: boolean; disabled?: boolean; } export type QueryOperationRowRenderProp = ((props: QueryOperationRowRenderProps) => React.ReactNode) | React.ReactNode; export interface QueryOperationRowRenderProps { isOpen: boolean; onOpen: () => void; onClose: () => void; } export function QueryOperationRow({ children, actions, title, headerElement, onClose, onOpen, isOpen, disabled, draggable, collapsable, index, id, }: QueryOperationRowProps) { const [isContentVisible, setIsContentVisible] = useState(isOpen !== undefined ? isOpen : true); const styles = useStyles2(getQueryOperationRowStyles); const onRowToggle = useCallback(() => { setIsContentVisible(!isContentVisible); }, [isContentVisible, setIsContentVisible]); // Force QueryOperationRow expansion when `isOpen` prop updates in parent component. // `undefined` can be deliberately passed value here, but we only want booleans to trigger the effect. useEffect(() => { if (typeof isOpen === 'boolean') { setIsContentVisible(isOpen); } }, [isOpen]); const reportDragMousePosition = useCallback((e: React.MouseEvent) => { // When drag detected react-beautiful-dnd will preventDefault the event // Ref: https://github.com/atlassian/react-beautiful-dnd/blob/master/docs/guides/how-we-use-dom-events.md#a-mouse-drag-has-started-and-the-user-is-now-dragging if (e.defaultPrevented) { const rect = e.currentTarget.getBoundingClientRect(); const x = e.clientX - rect.left; const y = e.clientY - rect.top; // report relative mouse position within the header element reportInteraction('query_row_reorder_drag_position', { x: x / rect.width, y: y / rect.height, width: rect.width, height: rect.height, }); } }, []); useUpdateEffect(() => { if (isContentVisible) { if (onOpen) { onOpen(); } } else { if (onClose) { onClose(); } } }, [isContentVisible]); const renderPropArgs: QueryOperationRowRenderProps = { isOpen: isContentVisible, onOpen: () => { setIsContentVisible(true); }, onClose: () => { setIsContentVisible(false); }, }; const actionsElement = actions && ReactUtils.renderOrCallToRender(actions, renderPropArgs); const headerElementRendered = headerElement && ReactUtils.renderOrCallToRender(headerElement, renderPropArgs); if (draggable) { return ( <Draggable draggableId={id} index={index}> {(provided) => { return ( <> <div ref={provided.innerRef} className={styles.wrapper} {...provided.draggableProps}> <div> <QueryOperationRowHeader id={id} actionsElement={actionsElement} disabled={disabled} draggable collapsable={collapsable} dragHandleProps={provided.dragHandleProps} headerElement={headerElementRendered} isContentVisible={isContentVisible} onRowToggle={onRowToggle} reportDragMousePosition={reportDragMousePosition} title={title} /> </div> {isContentVisible && <div className={styles.content}>{children}</div>} </div> </> ); }} </Draggable> ); } return ( <div className={styles.wrapper}> <QueryOperationRowHeader id={id} actionsElement={actionsElement} disabled={disabled} draggable={false} collapsable={collapsable} headerElement={headerElementRendered} isContentVisible={isContentVisible} onRowToggle={onRowToggle} reportDragMousePosition={reportDragMousePosition} title={title} /> {isContentVisible && <div className={styles.content}>{children}</div>} </div> ); } const getQueryOperationRowStyles = (theme: GrafanaTheme2) => { return { wrapper: css` margin-bottom: ${theme.spacing(2)}; `, content: css` margin-top: ${theme.spacing(0.5)}; margin-left: ${theme.spacing(3)}; `, }; }; QueryOperationRow.displayName = 'QueryOperationRow';
public/app/core/components/QueryOperationRow/QueryOperationRow.tsx
1
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.9986715316772461, 0.5274286270141602, 0.00016967863484751433, 0.9454754590988159, 0.4891600012779236 ]
{ "id": 5, "code_window": [ " isContentVisible: boolean;\n", " onRowToggle: () => void;\n", " reportDragMousePosition: MouseEventHandler<HTMLButtonElement>;\n", " title?: string;\n", " id: string;\n", "}\n", "\n", "export const QueryOperationRowHeader = ({\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " expanderMessages?: ExpanderMessages;\n", "}\n", "\n", "export interface ExpanderMessages {\n", " open: string;\n", " close: string;\n" ], "file_path": "public/app/core/components/QueryOperationRow/QueryOperationRowHeader.tsx", "type": "add", "edit_start_line_idx": 20 }
--- aliases: - ../../../enterprise/activate-aws-marketplace-license/transfer-ge-license/ - ../../../enterprise/license/activate-aws-marketplace-license/transfer-ge-license/ description: Transfer your AWS Marketplace Grafana Enterprise license keywords: - grafana - enterprise - aws - marketplace - transfer - move labels: products: - enterprise - oss title: Transfer your AWS Marketplace Grafana Enterprise license weight: 400 --- # Transfer your AWS Marketplace Grafana Enterprise license You can transfer your AWS Marketplace Grafana Enterprise license to another Grafana Enterprise instance. The transfer process requires that you first remove your license from one instance, and then apply the license to another instance. > When you remove an Enterprise license, the system immediately disables all Grafana Enterprise features. To remove an Enterprise license from a Grafana Enterprise instance, perform one of the following steps: - If you are using Amazon ECS or Amazon EKS, remove the `GF_ENTERPRISE_LICENSE_VALIDATION_TYPE` environment variable from the container. - If you have deployed Grafana Enterprise outside of AWS, remove the `aws` license_validation_type value from the grafana.ini configuration file. It can take the system up to one hour to clear the license. After the system clears the license, you can apply the same license to another Grafana Enterprise instance. To determine that the system has returned your license, check the license details in AWS License Manager.
docs/sources/administration/enterprise-licensing/activate-aws-marketplace-license/transfer-ge-license/index.md
0
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.0001800636964617297, 0.000174760352820158, 0.00017049747111741453, 0.00017424010729882866, 0.0000037661495753127383 ]
{ "id": 5, "code_window": [ " isContentVisible: boolean;\n", " onRowToggle: () => void;\n", " reportDragMousePosition: MouseEventHandler<HTMLButtonElement>;\n", " title?: string;\n", " id: string;\n", "}\n", "\n", "export const QueryOperationRowHeader = ({\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " expanderMessages?: ExpanderMessages;\n", "}\n", "\n", "export interface ExpanderMessages {\n", " open: string;\n", " close: string;\n" ], "file_path": "public/app/core/components/QueryOperationRow/QueryOperationRowHeader.tsx", "type": "add", "edit_start_line_idx": 20 }
import { css, cx } from '@emotion/css'; import React, { PropsWithChildren, useState } from 'react'; import { GrafanaTheme2 } from '@grafana/data'; import { Icon, InlineSegmentGroup, useTheme2 } from '@grafana/ui'; import { segmentStyles } from './styles'; const getStyles = (theme: GrafanaTheme2, hidden: boolean) => { return { wrapper: css` max-width: 500px; display: flex; flex-direction: column; `, settingsWrapper: css` padding-top: ${theme.spacing(0.5)}; `, icon: css` margin-right: ${theme.spacing(0.5)}; `, button: css` justify-content: start; ${hidden && css` color: ${theme.colors.text.disabled}; `} `, }; }; interface Props { label: string; hidden?: boolean; } export const SettingsEditorContainer = ({ label, children, hidden = false }: PropsWithChildren<Props>) => { const [open, setOpen] = useState(false); const theme = useTheme2(); const styles = getStyles(theme, hidden); return ( <InlineSegmentGroup> <div className={cx(styles.wrapper)}> <button className={cx('gf-form-label query-part', styles.button, segmentStyles)} onClick={() => setOpen(!open)} aria-expanded={open} type="button" > <Icon name={open ? 'angle-down' : 'angle-right'} aria-hidden="true" className={styles.icon} /> {label} </button> {open && <div className={styles.settingsWrapper}>{children}</div>} </div> </InlineSegmentGroup> ); };
public/app/plugins/datasource/elasticsearch/components/QueryEditor/SettingsEditorContainer.tsx
0
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.00018912300583906472, 0.0001750061201164499, 0.00016851144027896225, 0.00017265007772948593, 0.000006514134383905912 ]
{ "id": 5, "code_window": [ " isContentVisible: boolean;\n", " onRowToggle: () => void;\n", " reportDragMousePosition: MouseEventHandler<HTMLButtonElement>;\n", " title?: string;\n", " id: string;\n", "}\n", "\n", "export const QueryOperationRowHeader = ({\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " expanderMessages?: ExpanderMessages;\n", "}\n", "\n", "export interface ExpanderMessages {\n", " open: string;\n", " close: string;\n" ], "file_path": "public/app/core/components/QueryOperationRow/QueryOperationRowHeader.tsx", "type": "add", "edit_start_line_idx": 20 }
<?xml version="1.0" encoding="utf-8"?> <!-- Generator: Adobe Illustrator 19.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) --> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="121px" height="100px" viewBox="0 0 121 100" style="enable-background:new 0 0 121 100;" xml:space="preserve"> <style type="text/css"> .st0{fill:url(#SVGID_1_);} .st1{fill:#FFFFFF;} .st2{fill:url(#SVGID_2_);} .st3{fill:url(#SVGID_3_);} </style> <g> <g> <linearGradient id="SVGID_1_" gradientUnits="userSpaceOnUse" x1="60.5" y1="130.7753" x2="60.5" y2="18.6673"> <stop offset="0" style="stop-color:#FBB017"/> <stop offset="1" style="stop-color:#EF4E28"/> </linearGradient> <path class="st0" d="M120.8,50L87.2,16.4C78.1,6.3,64.9,0,50.2,0c-27.6,0-50,22.4-50,50s22.4,50,50,50c14.4,0,27.5-6.1,36.6-15.9 c0.1-0.1,0.1-0.1,0.2-0.2L120.8,50z"/> </g> <path class="st1" d="M94.1,50c0-24.4-19.9-44.3-44.3-44.3S5.6,25.6,5.6,50s19.9,44.3,44.3,44.3S94.1,74.4,94.1,50z"/> <g> <linearGradient id="SVGID_2_" gradientUnits="userSpaceOnUse" x1="50.2576" y1="115.6711" x2="50.2576" y2="19.8747"> <stop offset="0" style="stop-color:#FBB017"/> <stop offset="1" style="stop-color:#EF4E28"/> </linearGradient> <path class="st2" d="M77.8,65.9H25.4V30.5c0-1.5-1.2-2.8-2.8-2.8c-1.5,0-2.8,1.2-2.8,2.8v38.1c0,1.5,1.2,2.8,2.8,2.8h55.2 c1.5,0,2.8-1.2,2.8-2.8S79.4,65.9,77.8,65.9z"/> <g> <linearGradient id="SVGID_3_" gradientUnits="userSpaceOnUse" x1="53.116" y1="115.6711" x2="53.116" y2="19.8747"> <stop offset="0" style="stop-color:#FBB017"/> <stop offset="1" style="stop-color:#EF4E28"/> </linearGradient> <polygon class="st3" points="77.7,63.1 78,49 62.9,28.3 47.1,49.5 35.8,38.7 28.2,43.1 28.2,63.1 "/> </g> </g> </g> </svg>
public/img/icons_light_theme/icon_visualize_active.svg
0
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.00017277868755627424, 0.00016925828822422773, 0.0001648793404456228, 0.00016968758427537978, 0.0000030854655506118434 ]
{ "id": 6, "code_window": [ " onRowToggle,\n", " reportDragMousePosition,\n", " title,\n", " id,\n", "}: QueryOperationRowHeaderProps) => {\n", " const styles = useStyles2(getStyles);\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " expanderMessages,\n" ], "file_path": "public/app/core/components/QueryOperationRow/QueryOperationRowHeader.tsx", "type": "add", "edit_start_line_idx": 34 }
import { css, cx } from '@emotion/css'; import React, { MouseEventHandler } from 'react'; import { DraggableProvided } from 'react-beautiful-dnd'; import { GrafanaTheme2 } from '@grafana/data'; import { Stack } from '@grafana/experimental'; import { IconButton, useStyles2 } from '@grafana/ui'; export interface QueryOperationRowHeaderProps { actionsElement?: React.ReactNode; disabled?: boolean; draggable: boolean; collapsable?: boolean; dragHandleProps?: DraggableProvided['dragHandleProps']; headerElement?: React.ReactNode; isContentVisible: boolean; onRowToggle: () => void; reportDragMousePosition: MouseEventHandler<HTMLButtonElement>; title?: string; id: string; } export const QueryOperationRowHeader = ({ actionsElement, disabled, draggable, collapsable = true, dragHandleProps, headerElement, isContentVisible, onRowToggle, reportDragMousePosition, title, id, }: QueryOperationRowHeaderProps) => { const styles = useStyles2(getStyles); return ( <div className={styles.header}> <div className={styles.column}> {collapsable && ( <IconButton name={isContentVisible ? 'angle-down' : 'angle-right'} tooltip={isContentVisible ? 'Collapse query row' : 'Expand query row'} className={styles.collapseIcon} onClick={onRowToggle} aria-expanded={isContentVisible} aria-controls={id} /> )} {title && ( // disabling the a11y rules here as the IconButton above handles keyboard interactions // this is just to provide a better experience for mouse users // eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions <div className={styles.titleWrapper} onClick={onRowToggle} aria-label="Query operation row title"> <div className={cx(styles.title, disabled && styles.disabled)}>{title}</div> </div> )} {headerElement} </div> <Stack gap={1} alignItems="center" wrap={false}> {actionsElement} {draggable && ( <IconButton title="Drag and drop to reorder" name="draggabledots" tooltip="Drag and drop to reorder" tooltipPlacement="bottom" size="lg" className={styles.dragIcon} onMouseMove={reportDragMousePosition} {...dragHandleProps} /> )} </Stack> </div> ); }; const getStyles = (theme: GrafanaTheme2) => ({ header: css` label: Header; padding: ${theme.spacing(0.5, 0.5)}; border-radius: ${theme.shape.radius.default}; background: ${theme.colors.background.secondary}; min-height: ${theme.spacing(4)}; display: grid; grid-template-columns: minmax(100px, max-content) min-content; align-items: center; justify-content: space-between; white-space: nowrap; &:focus { outline: none; } `, column: css` label: Column; display: flex; align-items: center; `, dragIcon: css` cursor: grab; color: ${theme.colors.text.disabled}; margin: ${theme.spacing(0, 0.5)}; &:hover { color: ${theme.colors.text}; } `, collapseIcon: css` margin-left: ${theme.spacing(0.5)}; color: ${theme.colors.text.disabled}; } `, titleWrapper: css` display: flex; align-items: center; flex-grow: 1; cursor: pointer; overflow: hidden; margin-right: ${theme.spacing(0.5)}; `, title: css` font-weight: ${theme.typography.fontWeightBold}; color: ${theme.colors.text.link}; margin-left: ${theme.spacing(0.5)}; overflow: hidden; text-overflow: ellipsis; `, disabled: css` color: ${theme.colors.text.disabled}; `, }); QueryOperationRowHeader.displayName = 'QueryOperationRowHeader';
public/app/core/components/QueryOperationRow/QueryOperationRowHeader.tsx
1
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.9990634322166443, 0.3558734357357025, 0.00016996133490465581, 0.005010274238884449, 0.47424983978271484 ]
{ "id": 6, "code_window": [ " onRowToggle,\n", " reportDragMousePosition,\n", " title,\n", " id,\n", "}: QueryOperationRowHeaderProps) => {\n", " const styles = useStyles2(getStyles);\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " expanderMessages,\n" ], "file_path": "public/app/core/components/QueryOperationRow/QueryOperationRowHeader.tsx", "type": "add", "edit_start_line_idx": 34 }
const wp = require('@cypress/webpack-preprocessor'); const { resolve } = require('path'); const anyNodeModules = /node_modules/; const packageRoot = resolve(`${__dirname}/../../`); const packageModules = `${packageRoot}/node_modules`; const webpackOptions = { module: { rules: [ { include: (modulePath) => { if (!anyNodeModules.test(modulePath)) { // Is a file within the project return true; } else { // Is a file within this package return modulePath.startsWith(packageRoot) && !modulePath.startsWith(packageModules); } }, test: /\.ts$/, use: [ { loader: 'ts-loader', options: { transpileOnly: true, }, }, ], }, ], }, resolve: { extensions: ['.ts', '.js'], }, }; const options = { webpackOptions, }; module.exports = wp(options);
packages/grafana-e2e/cypress/plugins/typescriptPreprocessor.js
0
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.0001761950843501836, 0.00017280034080613405, 0.00017035707423929125, 0.00017193265375681221, 0.000002264450813527219 ]
{ "id": 6, "code_window": [ " onRowToggle,\n", " reportDragMousePosition,\n", " title,\n", " id,\n", "}: QueryOperationRowHeaderProps) => {\n", " const styles = useStyles2(getStyles);\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " expanderMessages,\n" ], "file_path": "public/app/core/components/QueryOperationRow/QueryOperationRowHeader.tsx", "type": "add", "edit_start_line_idx": 34 }
package schedule import ( "context" "encoding/binary" "errors" "fmt" "hash/fnv" "math" "sort" "sync" "time" "unsafe" "github.com/grafana/grafana/pkg/services/ngalert/models" "github.com/grafana/grafana/pkg/util" ) var errRuleDeleted = errors.New("rule deleted") type alertRuleInfoRegistry struct { mu sync.Mutex alertRuleInfo map[models.AlertRuleKey]*alertRuleInfo } // getOrCreateInfo gets rule routine information from registry by the key. If it does not exist, it creates a new one. // Returns a pointer to the rule routine information and a flag that indicates whether it is a new struct or not. func (r *alertRuleInfoRegistry) getOrCreateInfo(context context.Context, key models.AlertRuleKey) (*alertRuleInfo, bool) { r.mu.Lock() defer r.mu.Unlock() info, ok := r.alertRuleInfo[key] if !ok { info = newAlertRuleInfo(context) r.alertRuleInfo[key] = info } return info, !ok } func (r *alertRuleInfoRegistry) exists(key models.AlertRuleKey) bool { r.mu.Lock() defer r.mu.Unlock() _, ok := r.alertRuleInfo[key] return ok } // del removes pair that has specific key from alertRuleInfo. // Returns 2-tuple where the first element is value of the removed pair // and the second element indicates whether element with the specified key existed. func (r *alertRuleInfoRegistry) del(key models.AlertRuleKey) (*alertRuleInfo, bool) { r.mu.Lock() defer r.mu.Unlock() info, ok := r.alertRuleInfo[key] if ok { delete(r.alertRuleInfo, key) } return info, ok } func (r *alertRuleInfoRegistry) keyMap() map[models.AlertRuleKey]struct{} { r.mu.Lock() defer r.mu.Unlock() definitionsIDs := make(map[models.AlertRuleKey]struct{}, len(r.alertRuleInfo)) for k := range r.alertRuleInfo { definitionsIDs[k] = struct{}{} } return definitionsIDs } type ruleVersionAndPauseStatus struct { Fingerprint fingerprint IsPaused bool } type alertRuleInfo struct { evalCh chan *evaluation updateCh chan ruleVersionAndPauseStatus ctx context.Context stop func(reason error) } func newAlertRuleInfo(parent context.Context) *alertRuleInfo { ctx, stop := util.WithCancelCause(parent) return &alertRuleInfo{evalCh: make(chan *evaluation), updateCh: make(chan ruleVersionAndPauseStatus), ctx: ctx, stop: stop} } // eval signals the rule evaluation routine to perform the evaluation of the rule. Does nothing if the loop is stopped. // Before sending a message into the channel, it does non-blocking read to make sure that there is no concurrent send operation. // Returns a tuple where first element is // - true when message was sent // - false when the send operation is stopped // // the second element contains a dropped message that was sent by a concurrent sender. func (a *alertRuleInfo) eval(eval *evaluation) (bool, *evaluation) { // read the channel in unblocking manner to make sure that there is no concurrent send operation. var droppedMsg *evaluation select { case droppedMsg = <-a.evalCh: default: } select { case a.evalCh <- eval: return true, droppedMsg case <-a.ctx.Done(): return false, droppedMsg } } // update sends an instruction to the rule evaluation routine to update the scheduled rule to the specified version. The specified version must be later than the current version, otherwise no update will happen. func (a *alertRuleInfo) update(lastVersion ruleVersionAndPauseStatus) bool { // check if the channel is not empty. select { case <-a.updateCh: case <-a.ctx.Done(): return false default: } select { case a.updateCh <- lastVersion: return true case <-a.ctx.Done(): return false } } type evaluation struct { scheduledAt time.Time rule *models.AlertRule folderTitle string } type alertRulesRegistry struct { rules map[models.AlertRuleKey]*models.AlertRule folderTitles map[string]string mu sync.Mutex } // all returns all rules in the registry. func (r *alertRulesRegistry) all() ([]*models.AlertRule, map[string]string) { r.mu.Lock() defer r.mu.Unlock() result := make([]*models.AlertRule, 0, len(r.rules)) for _, rule := range r.rules { result = append(result, rule) } return result, r.folderTitles } func (r *alertRulesRegistry) get(k models.AlertRuleKey) *models.AlertRule { r.mu.Lock() defer r.mu.Unlock() return r.rules[k] } // set replaces all rules in the registry. Returns difference between previous and the new current version of the registry func (r *alertRulesRegistry) set(rules []*models.AlertRule, folders map[string]string) diff { r.mu.Lock() defer r.mu.Unlock() rulesMap := make(map[models.AlertRuleKey]*models.AlertRule) for _, rule := range rules { rulesMap[rule.GetKey()] = rule } d := r.getDiff(rulesMap) r.rules = rulesMap // return the map as is without copying because it is not mutated r.folderTitles = folders return d } // update inserts or replaces a rule in the registry. func (r *alertRulesRegistry) update(rule *models.AlertRule) { r.mu.Lock() defer r.mu.Unlock() r.rules[rule.GetKey()] = rule } // del removes pair that has specific key from alertRulesRegistry. // Returns 2-tuple where the first element is value of the removed pair // and the second element indicates whether element with the specified key existed. func (r *alertRulesRegistry) del(k models.AlertRuleKey) (*models.AlertRule, bool) { r.mu.Lock() defer r.mu.Unlock() rule, ok := r.rules[k] if ok { delete(r.rules, k) } return rule, ok } func (r *alertRulesRegistry) isEmpty() bool { r.mu.Lock() defer r.mu.Unlock() return len(r.rules) == 0 } func (r *alertRulesRegistry) needsUpdate(keys []models.AlertRuleKeyWithVersion) bool { if len(r.rules) != len(keys) { return true } for _, key := range keys { rule, ok := r.rules[key.AlertRuleKey] if !ok || rule.Version != key.Version { return true } } return false } type diff struct { updated map[models.AlertRuleKey]struct{} } func (d diff) IsEmpty() bool { return len(d.updated) == 0 } // getDiff calculates difference between the list of rules fetched previously and provided keys. Returns diff where // updated - a list of keys that exist in the registry but with different version, func (r *alertRulesRegistry) getDiff(rules map[models.AlertRuleKey]*models.AlertRule) diff { result := diff{ updated: map[models.AlertRuleKey]struct{}{}, } for key, newRule := range rules { oldRule, ok := r.rules[key] if !ok || newRule.Version == oldRule.Version { // a new rule or not updated continue } result.updated[key] = struct{}{} } return result } type fingerprint uint64 func (f fingerprint) String() string { return fmt.Sprintf("%016x", uint64(f)) } // fingerprintSeparator used during calculation of fingerprint to separate different fields. Contains a byte sequence that cannot happen in UTF-8 strings. var fingerprintSeparator = []byte{255} type ruleWithFolder struct { rule *models.AlertRule folderTitle string } // fingerprint calculates a fingerprint that includes all fields except rule's Version and Update timestamp. func (r ruleWithFolder) Fingerprint() fingerprint { rule := r.rule sum := fnv.New64() writeBytes := func(b []byte) { _, _ = sum.Write(b) _, _ = sum.Write(fingerprintSeparator) } writeString := func(s string) { if len(s) == 0 { writeBytes(nil) return } // avoid allocation when converting string to byte slice writeBytes(unsafe.Slice(unsafe.StringData(s), len(s))) } // this temp slice is used to convert ints to bytes. tmp := make([]byte, 8) writeInt := func(u int64) { binary.LittleEndian.PutUint64(tmp, uint64(u)) writeBytes(tmp) } // allocate a slice that will be used for sorting keys, so we allocate it only once var keys []string maxLen := int(math.Max(math.Max(float64(len(rule.Annotations)), float64(len(rule.Labels))), float64(len(rule.Data)))) if maxLen > 0 { keys = make([]string, maxLen) } writeLabels := func(lbls map[string]string) { // maps do not guarantee predictable sequence of keys. // Therefore, to make hash stable, we need to sort keys if len(lbls) == 0 { return } idx := 0 for labelName := range lbls { keys[idx] = labelName idx++ } sub := keys[:idx] sort.Strings(sub) for _, name := range sub { writeString(name) writeString(lbls[name]) } } writeQuery := func() { // The order of queries is not important as they represent an expression tree. // Therefore, the order of elements should not change the hash. Sort by RefID because it is the unique key. for i, q := range rule.Data { keys[i] = q.RefID } sub := keys[:len(rule.Data)] sort.Strings(sub) for _, id := range sub { for _, q := range rule.Data { if q.RefID == id { writeString(q.RefID) writeString(q.DatasourceUID) writeString(q.QueryType) writeInt(int64(q.RelativeTimeRange.From)) writeInt(int64(q.RelativeTimeRange.To)) writeBytes(q.Model) break } } } } // fields that determine the rule state writeString(rule.UID) writeString(rule.Title) writeString(rule.NamespaceUID) writeString(r.folderTitle) writeLabels(rule.Labels) writeString(rule.Condition) writeQuery() if rule.IsPaused { writeInt(1) } else { writeInt(0) } // fields that do not affect the state. // TODO consider removing fields below from the fingerprint writeInt(rule.ID) writeInt(rule.OrgID) writeInt(rule.IntervalSeconds) writeInt(int64(rule.For)) writeLabels(rule.Annotations) if rule.DashboardUID != nil { writeString(*rule.DashboardUID) } if rule.PanelID != nil { writeInt(*rule.PanelID) } writeString(rule.RuleGroup) writeInt(int64(rule.RuleGroupIndex)) writeString(string(rule.NoDataState)) writeString(string(rule.ExecErrState)) return fingerprint(sum.Sum64()) }
pkg/services/ngalert/schedule/registry.go
0
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.00018285222176928073, 0.0001718526764307171, 0.00016357758431695402, 0.0001723306195344776, 0.0000034843728826672304 ]
{ "id": 6, "code_window": [ " onRowToggle,\n", " reportDragMousePosition,\n", " title,\n", " id,\n", "}: QueryOperationRowHeaderProps) => {\n", " const styles = useStyles2(getStyles);\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " expanderMessages,\n" ], "file_path": "public/app/core/components/QueryOperationRow/QueryOperationRowHeader.tsx", "type": "add", "edit_start_line_idx": 34 }
import { ArgTypes } from '@storybook/blocks'; import { DateTimePicker } from './DateTimePicker'; # DateTimePicker A component for selecting a date _and_ time. ### Usage ```tsx import React, { useState } from 'react'; import { DateTime, dateTime } from '@grafana/data'; import { DateTimePicker } from '@grafana/ui'; const [date, setDate] = useState<DateTime>(dateTime('2021-05-05 12:00:00')); return <DateTimePicker label="Date" date={date} onChange={setDate} />; ``` ### With disbled hours, minutes or seconds ```tsx import React, { useState } from 'react'; import { DateTime, dateTime } from '@grafana/data'; import { DateTimePicker } from '@grafana/ui'; const [date, setDate] = useState<DateTime>(dateTime('2021-05-05 12:00:00')); return ( <DateTimePicker label="Date" date={date} onChange={setDate} disabledHours={() => [0, 1, 2]} disabledMinutes={() => [10, 15, 30]} disabledSeconds={() => [5, 10, 15, 20]} /> ); ``` ### Props <ArgTypes of={DateTimePicker} />
packages/grafana-ui/src/components/DateTimePickers/DateTimePicker/DateTimePicker.mdx
0
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.0001766501081874594, 0.00017457015928812325, 0.00017087734886445105, 0.00017444284458179027, 0.000002092403747155913 ]
{ "id": 7, "code_window": [ "}: QueryOperationRowHeaderProps) => {\n", " const styles = useStyles2(getStyles);\n", "\n", " return (\n", " <div className={styles.header}>\n", " <div className={styles.column}>\n", " {collapsable && (\n", " <IconButton\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " let tooltipMessage = isContentVisible ? 'Collapse query row' : 'Expand query row';\n", " if (expanderMessages !== undefined && isContentVisible) {\n", " tooltipMessage = expanderMessages.close;\n", " } else if (expanderMessages !== undefined) {\n", " tooltipMessage = expanderMessages?.open;\n", " }\n", "\n" ], "file_path": "public/app/core/components/QueryOperationRow/QueryOperationRowHeader.tsx", "type": "add", "edit_start_line_idx": 37 }
import { css } from '@emotion/css'; import React, { useCallback, useEffect, useState } from 'react'; import { Draggable } from 'react-beautiful-dnd'; import { useUpdateEffect } from 'react-use'; import { GrafanaTheme2 } from '@grafana/data'; import { reportInteraction } from '@grafana/runtime'; import { ReactUtils, useStyles2 } from '@grafana/ui'; import { QueryOperationRowHeader } from './QueryOperationRowHeader'; export interface QueryOperationRowProps { index: number; id: string; title?: string; headerElement?: QueryOperationRowRenderProp; actions?: QueryOperationRowRenderProp; onOpen?: () => void; onClose?: () => void; children: React.ReactNode; isOpen?: boolean; draggable?: boolean; collapsable?: boolean; disabled?: boolean; } export type QueryOperationRowRenderProp = ((props: QueryOperationRowRenderProps) => React.ReactNode) | React.ReactNode; export interface QueryOperationRowRenderProps { isOpen: boolean; onOpen: () => void; onClose: () => void; } export function QueryOperationRow({ children, actions, title, headerElement, onClose, onOpen, isOpen, disabled, draggable, collapsable, index, id, }: QueryOperationRowProps) { const [isContentVisible, setIsContentVisible] = useState(isOpen !== undefined ? isOpen : true); const styles = useStyles2(getQueryOperationRowStyles); const onRowToggle = useCallback(() => { setIsContentVisible(!isContentVisible); }, [isContentVisible, setIsContentVisible]); // Force QueryOperationRow expansion when `isOpen` prop updates in parent component. // `undefined` can be deliberately passed value here, but we only want booleans to trigger the effect. useEffect(() => { if (typeof isOpen === 'boolean') { setIsContentVisible(isOpen); } }, [isOpen]); const reportDragMousePosition = useCallback((e: React.MouseEvent) => { // When drag detected react-beautiful-dnd will preventDefault the event // Ref: https://github.com/atlassian/react-beautiful-dnd/blob/master/docs/guides/how-we-use-dom-events.md#a-mouse-drag-has-started-and-the-user-is-now-dragging if (e.defaultPrevented) { const rect = e.currentTarget.getBoundingClientRect(); const x = e.clientX - rect.left; const y = e.clientY - rect.top; // report relative mouse position within the header element reportInteraction('query_row_reorder_drag_position', { x: x / rect.width, y: y / rect.height, width: rect.width, height: rect.height, }); } }, []); useUpdateEffect(() => { if (isContentVisible) { if (onOpen) { onOpen(); } } else { if (onClose) { onClose(); } } }, [isContentVisible]); const renderPropArgs: QueryOperationRowRenderProps = { isOpen: isContentVisible, onOpen: () => { setIsContentVisible(true); }, onClose: () => { setIsContentVisible(false); }, }; const actionsElement = actions && ReactUtils.renderOrCallToRender(actions, renderPropArgs); const headerElementRendered = headerElement && ReactUtils.renderOrCallToRender(headerElement, renderPropArgs); if (draggable) { return ( <Draggable draggableId={id} index={index}> {(provided) => { return ( <> <div ref={provided.innerRef} className={styles.wrapper} {...provided.draggableProps}> <div> <QueryOperationRowHeader id={id} actionsElement={actionsElement} disabled={disabled} draggable collapsable={collapsable} dragHandleProps={provided.dragHandleProps} headerElement={headerElementRendered} isContentVisible={isContentVisible} onRowToggle={onRowToggle} reportDragMousePosition={reportDragMousePosition} title={title} /> </div> {isContentVisible && <div className={styles.content}>{children}</div>} </div> </> ); }} </Draggable> ); } return ( <div className={styles.wrapper}> <QueryOperationRowHeader id={id} actionsElement={actionsElement} disabled={disabled} draggable={false} collapsable={collapsable} headerElement={headerElementRendered} isContentVisible={isContentVisible} onRowToggle={onRowToggle} reportDragMousePosition={reportDragMousePosition} title={title} /> {isContentVisible && <div className={styles.content}>{children}</div>} </div> ); } const getQueryOperationRowStyles = (theme: GrafanaTheme2) => { return { wrapper: css` margin-bottom: ${theme.spacing(2)}; `, content: css` margin-top: ${theme.spacing(0.5)}; margin-left: ${theme.spacing(3)}; `, }; }; QueryOperationRow.displayName = 'QueryOperationRow';
public/app/core/components/QueryOperationRow/QueryOperationRow.tsx
1
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.7193366885185242, 0.05943388119339943, 0.00016661416157148778, 0.0019418150186538696, 0.1726551055908203 ]
{ "id": 7, "code_window": [ "}: QueryOperationRowHeaderProps) => {\n", " const styles = useStyles2(getStyles);\n", "\n", " return (\n", " <div className={styles.header}>\n", " <div className={styles.column}>\n", " {collapsable && (\n", " <IconButton\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " let tooltipMessage = isContentVisible ? 'Collapse query row' : 'Expand query row';\n", " if (expanderMessages !== undefined && isContentVisible) {\n", " tooltipMessage = expanderMessages.close;\n", " } else if (expanderMessages !== undefined) {\n", " tooltipMessage = expanderMessages?.open;\n", " }\n", "\n" ], "file_path": "public/app/core/components/QueryOperationRow/QueryOperationRowHeader.tsx", "type": "add", "edit_start_line_idx": 37 }
package log import ( "os" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func (w *FileLogWriter) WriteLine(line string) error { _, err := w.Write([]byte(line)) return err } func TestLogFile(t *testing.T) { fileLogWrite := NewFileWriter() require.NotNil(t, fileLogWrite) t.Cleanup(func() { err := fileLogWrite.Close() assert.NoError(t, err) err = os.Remove(fileLogWrite.Filename) assert.NoError(t, err) }) fileLogWrite.Filename = "grafana_test.log" err := fileLogWrite.Init() require.NoError(t, err) assert.Zero(t, fileLogWrite.maxlinesCurlines) t.Run("adding lines", func(t *testing.T) { err := fileLogWrite.WriteLine("test1\n") require.NoError(t, err) err = fileLogWrite.WriteLine("test2\n") require.NoError(t, err) err = fileLogWrite.WriteLine("test3\n") require.NoError(t, err) assert.Equal(t, 3, fileLogWrite.maxlinesCurlines) }) }
pkg/infra/log/file_test.go
0
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.00017851998563855886, 0.00017630714864935726, 0.00017408492567483336, 0.00017632801609579474, 0.0000019587191673053894 ]
{ "id": 7, "code_window": [ "}: QueryOperationRowHeaderProps) => {\n", " const styles = useStyles2(getStyles);\n", "\n", " return (\n", " <div className={styles.header}>\n", " <div className={styles.column}>\n", " {collapsable && (\n", " <IconButton\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " let tooltipMessage = isContentVisible ? 'Collapse query row' : 'Expand query row';\n", " if (expanderMessages !== undefined && isContentVisible) {\n", " tooltipMessage = expanderMessages.close;\n", " } else if (expanderMessages !== undefined) {\n", " tooltipMessage = expanderMessages?.open;\n", " }\n", "\n" ], "file_path": "public/app/core/components/QueryOperationRow/QueryOperationRowHeader.tsx", "type": "add", "edit_start_line_idx": 37 }
import { createDataFrame, FieldType } from '@grafana/data'; import { FlameGraphDataContainer, LevelItem } from './dataTransform'; import { getRectDimensionsForLevel } from './rendering'; function makeDataFrame(fields: Record<string, Array<number | string>>) { return createDataFrame({ fields: Object.keys(fields).map((key) => ({ name: key, values: fields[key], type: typeof fields[key][0] === 'string' ? FieldType.string : FieldType.number, })), }); } describe('getRectDimensionsForLevel', () => { it('should render a single item', () => { const level: LevelItem[] = [{ start: 0, itemIndexes: [0], children: [], value: 100 }]; const container = new FlameGraphDataContainer(makeDataFrame({ value: [100], level: [1], label: ['1'], self: [0] })); const result = getRectDimensionsForLevel(container, level, 1, 100, 0, 10); expect(result).toEqual([ { width: 999, height: 22, itemIndex: 0, x: 0, y: 22, collapsed: false, ticks: 100, label: '1', unitLabel: '100', }, ]); }); it('should render a multiple items', () => { const level: LevelItem[] = [ { start: 0, itemIndexes: [0], children: [], value: 100 }, { start: 100, itemIndexes: [1], children: [], value: 50 }, { start: 150, itemIndexes: [2], children: [], value: 50 }, ]; const container = new FlameGraphDataContainer( makeDataFrame({ value: [100, 50, 50], level: [2, 2, 2], label: ['1', '2', '3'], self: [0, 0, 0] }) ); const result = getRectDimensionsForLevel(container, level, 2, 100, 0, 10); expect(result).toEqual([ { width: 999, height: 22, x: 0, y: 44, collapsed: false, ticks: 100, label: '1', unitLabel: '100', itemIndex: 0 }, { width: 499, height: 22, x: 1000, y: 44, collapsed: false, ticks: 50, label: '2', unitLabel: '50', itemIndex: 1, }, { width: 499, height: 22, x: 1500, y: 44, collapsed: false, ticks: 50, label: '3', unitLabel: '50', itemIndex: 2, }, ]); }); it('should render a collapsed items', () => { const level: LevelItem[] = [ { start: 0, itemIndexes: [0], children: [], value: 100 }, { start: 100, itemIndexes: [1], children: [], value: 2 }, { start: 102, itemIndexes: [2], children: [], value: 1 }, ]; const container = new FlameGraphDataContainer( makeDataFrame({ value: [100, 2, 1], level: [2, 2, 2], label: ['1', '2', '3'], self: [0, 0, 0] }) ); const result = getRectDimensionsForLevel(container, level, 2, 100, 0, 1); expect(result).toEqual([ { width: 99, height: 22, x: 0, y: 44, collapsed: false, ticks: 100, label: '1', unitLabel: '100', itemIndex: 0 }, { width: 3, height: 22, x: 100, y: 44, collapsed: true, ticks: 3, label: '2', unitLabel: '2', itemIndex: 1 }, ]); }); });
packages/grafana-flamegraph/src/FlameGraph/rendering.test.ts
0
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.00017823815869633108, 0.0001748821814544499, 0.00017145134916063398, 0.00017519478569738567, 0.0000020272732399462257 ]
{ "id": 7, "code_window": [ "}: QueryOperationRowHeaderProps) => {\n", " const styles = useStyles2(getStyles);\n", "\n", " return (\n", " <div className={styles.header}>\n", " <div className={styles.column}>\n", " {collapsable && (\n", " <IconButton\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " let tooltipMessage = isContentVisible ? 'Collapse query row' : 'Expand query row';\n", " if (expanderMessages !== undefined && isContentVisible) {\n", " tooltipMessage = expanderMessages.close;\n", " } else if (expanderMessages !== undefined) {\n", " tooltipMessage = expanderMessages?.open;\n", " }\n", "\n" ], "file_path": "public/app/core/components/QueryOperationRow/QueryOperationRowHeader.tsx", "type": "add", "edit_start_line_idx": 37 }
package pushurl import ( "net/url" "testing" "github.com/stretchr/testify/require" ) func TestFrameFormatFromValues(t *testing.T) { values := url.Values{} require.Equal(t, "labels_column", FrameFormatFromValues(values)) values.Set(frameFormatParam, "wide") require.Equal(t, "wide", FrameFormatFromValues(values)) }
pkg/services/live/pushurl/values_test.go
0
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.00017467669385951012, 0.00017096410738304257, 0.0001672515063546598, 0.00017096410738304257, 0.000003712593752425164 ]
{ "id": 8, "code_window": [ " <div className={styles.column}>\n", " {collapsable && (\n", " <IconButton\n", " name={isContentVisible ? 'angle-down' : 'angle-right'}\n", " tooltip={isContentVisible ? 'Collapse query row' : 'Expand query row'}\n", " className={styles.collapseIcon}\n", " onClick={onRowToggle}\n", " aria-expanded={isContentVisible}\n", " aria-controls={id}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " tooltip={tooltipMessage}\n" ], "file_path": "public/app/core/components/QueryOperationRow/QueryOperationRowHeader.tsx", "type": "replace", "edit_start_line_idx": 43 }
import React, { useCallback } from 'react'; import { useToggle } from 'react-use'; import { DataFrame, DataTransformerConfig, TransformerRegistryItem, FrameMatcherID } from '@grafana/data'; import { reportInteraction } from '@grafana/runtime'; import { ConfirmModal } from '@grafana/ui'; import { OperationRowHelp } from 'app/core/components/QueryOperationRow/OperationRowHelp'; import { QueryOperationAction, QueryOperationToggleAction, } from 'app/core/components/QueryOperationRow/QueryOperationAction'; import { QueryOperationRow, QueryOperationRowRenderProps, } from 'app/core/components/QueryOperationRow/QueryOperationRow'; import config from 'app/core/config'; import { PluginStateInfo } from 'app/features/plugins/components/PluginStateInfo'; import { TransformationEditor } from './TransformationEditor'; import { TransformationFilter } from './TransformationFilter'; import { TransformationsEditorTransformation } from './types'; interface TransformationOperationRowProps { id: string; index: number; data: DataFrame[]; uiConfig: TransformerRegistryItem<null>; configs: TransformationsEditorTransformation[]; onRemove: (index: number) => void; onChange: (index: number, config: DataTransformerConfig) => void; } export const TransformationOperationRow = ({ onRemove, index, id, data, configs, uiConfig, onChange, }: TransformationOperationRowProps) => { const [showDeleteModal, setShowDeleteModal] = useToggle(false); const [showDebug, toggleShowDebug] = useToggle(false); const [showHelp, toggleShowHelp] = useToggle(false); const disabled = !!configs[index].transformation.disabled; const filter = configs[index].transformation.filter != null; const showFilter = filter || data.length > 1; const onDisableToggle = useCallback( (index: number) => { const current = configs[index].transformation; onChange(index, { ...current, disabled: current.disabled ? undefined : true, }); }, [onChange, configs] ); const toggleExpand = useCallback(() => { if (showHelp) { return true; } // We return `undefined` here since the QueryOperationRow component ignores an `undefined` value for the `isOpen` prop. // If we returned `false` here, the row would be collapsed when the user toggles off `showHelp`, which is not what we want. return undefined; }, [showHelp]); // Adds or removes the frame filter const toggleFilter = useCallback(() => { let current = { ...configs[index].transformation }; if (current.filter) { delete current.filter; } else { current.filter = { id: FrameMatcherID.byRefId, options: '', // empty string will not do anything }; } onChange(index, current); }, [onChange, index, configs]); // Instrument toggle callback const instrumentToggleCallback = useCallback( (callback: (e: React.MouseEvent) => void, toggleId: string, active: boolean | undefined) => (e: React.MouseEvent) => { let eventName = 'panel_editor_tabs_transformations_toggle'; if (config.featureToggles.transformationsRedesign) { eventName = 'transformations_redesign_' + eventName; } reportInteraction(eventName, { action: active ? 'off' : 'on', toggleId, transformationId: configs[index].transformation.id, }); callback(e); }, [configs, index] ); const renderActions = ({ isOpen }: QueryOperationRowRenderProps) => { return ( <> {uiConfig.state && <PluginStateInfo state={uiConfig.state} />} <QueryOperationToggleAction title="Show transform help" icon="info-circle" // `instrumentToggleCallback` expects a function that takes a MouseEvent, is unused in the state setter. Instead, we simply toggle the state. onClick={instrumentToggleCallback((_e) => toggleShowHelp(!showHelp), 'help', showHelp)} active={!!showHelp} /> {showFilter && ( <QueryOperationToggleAction title="Filter" icon="filter" onClick={instrumentToggleCallback(toggleFilter, 'filter', filter)} active={filter} /> )} <QueryOperationToggleAction title="Debug" disabled={!isOpen} icon="bug" onClick={instrumentToggleCallback(toggleShowDebug, 'debug', showDebug)} active={showDebug} /> <QueryOperationToggleAction title="Disable transformation" icon={disabled ? 'eye-slash' : 'eye'} onClick={instrumentToggleCallback(() => onDisableToggle(index), 'disabled', disabled)} active={disabled} /> <QueryOperationAction title="Remove" icon="trash-alt" onClick={() => (config.featureToggles.transformationsRedesign ? setShowDeleteModal(true) : onRemove(index))} /> {config.featureToggles.transformationsRedesign && ( <ConfirmModal isOpen={showDeleteModal} title={`Delete ${uiConfig.name}?`} body="Note that removing one transformation may break others. If there is only a single transformation, you will go back to the main selection screen." confirmText="Delete" onConfirm={() => { setShowDeleteModal(false); onRemove(index); }} onDismiss={() => setShowDeleteModal(false)} /> )} </> ); }; return ( <QueryOperationRow id={id} index={index} title={uiConfig.name} draggable actions={renderActions} disabled={disabled} isOpen={toggleExpand()} // Assure that showHelp is untoggled when the row becomes collapsed. onClose={() => toggleShowHelp(false)} > {showHelp && <OperationRowHelp markdown={prepMarkdown(uiConfig)} />} {filter && ( <TransformationFilter index={index} config={configs[index].transformation} data={data} onChange={onChange} /> )} <TransformationEditor debugMode={showDebug} index={index} data={data} configs={configs} uiConfig={uiConfig} onChange={onChange} /> </QueryOperationRow> ); }; function prepMarkdown(uiConfig: TransformerRegistryItem<null>) { let helpMarkdown = uiConfig.help ?? uiConfig.description; return ` ${helpMarkdown} Go the <a href="https://grafana.com/docs/grafana/latest/panels/transformations/?utm_source=grafana" target="_blank" rel="noreferrer"> transformation documentation </a> for more. `; }
public/app/features/dashboard/components/TransformationsEditor/TransformationOperationRow.tsx
1
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.003436874132603407, 0.0003374620864633471, 0.00016446811787318438, 0.00017176015535369515, 0.0007111840532161295 ]
{ "id": 8, "code_window": [ " <div className={styles.column}>\n", " {collapsable && (\n", " <IconButton\n", " name={isContentVisible ? 'angle-down' : 'angle-right'}\n", " tooltip={isContentVisible ? 'Collapse query row' : 'Expand query row'}\n", " className={styles.collapseIcon}\n", " onClick={onRowToggle}\n", " aria-expanded={isContentVisible}\n", " aria-controls={id}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " tooltip={tooltipMessage}\n" ], "file_path": "public/app/core/components/QueryOperationRow/QueryOperationRowHeader.tsx", "type": "replace", "edit_start_line_idx": 43 }
package main import ( "fmt" "log" "os" "os/exec" "github.com/urfave/cli/v2" "github.com/grafana/grafana/pkg/build/config" "github.com/grafana/grafana/pkg/build/docker" "github.com/grafana/grafana/pkg/build/gcloud" ) func Enterprise2(c *cli.Context) error { if c.NArg() > 0 { if err := cli.ShowSubcommandHelp(c); err != nil { return cli.Exit(err.Error(), 1) } return cli.Exit("", 1) } if err := gcloud.ActivateServiceAccount(); err != nil { return fmt.Errorf("couldn't activate service account, err: %w", err) } metadata, err := config.GenerateMetadata(c) if err != nil { return err } buildConfig, err := config.GetBuildConfig(metadata.ReleaseMode.Mode) if err != nil { return err } cfg := docker.Config{ Archs: buildConfig.Docker.Architectures, Distribution: buildConfig.Docker.Distribution, DockerHubRepo: c.String("dockerhub-repo"), Tag: metadata.GrafanaVersion, } err = dockerLoginEnterprise2() if err != nil { return err } var distributionStr []string for _, distribution := range cfg.Distribution { switch distribution { case alpine: distributionStr = append(distributionStr, "") case ubuntu: distributionStr = append(distributionStr, "-ubuntu") default: return fmt.Errorf("unrecognized distribution %q", distribution) } } for _, distribution := range distributionStr { var imageFileNames []string for _, arch := range cfg.Archs { imageFilename := fmt.Sprintf("%s:%s%s-%s", cfg.DockerHubRepo, cfg.Tag, distribution, arch) err := docker.PushImage(imageFilename) if err != nil { return err } imageFileNames = append(imageFileNames, imageFilename) } manifest := fmt.Sprintf("%s:%s%s", cfg.DockerHubRepo, cfg.Tag, distribution) args := []string{"manifest", "create", manifest} args = append(args, imageFileNames...) //nolint:gosec cmd := exec.Command("docker", args...) cmd.Env = append(os.Environ(), "DOCKER_CLI_EXPERIMENTAL=enabled") if output, err := cmd.CombinedOutput(); err != nil { return fmt.Errorf("failed to create Docker manifest: %w\n%s", err, output) } err = docker.PushManifest(manifest) if err != nil { return err } } return nil } func dockerLoginEnterprise2() error { log.Println("Docker login...") cmd := exec.Command("gcloud", "auth", "configure-docker") if out, err := cmd.CombinedOutput(); err != nil { return fmt.Errorf("error logging in to DockerHub: %s %q", out, err) } log.Println("Successful login!") return nil }
pkg/build/cmd/publishimages_enterprise2.go
0
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.0001756656711222604, 0.00017268332885578275, 0.0001696034159976989, 0.0001720034924801439, 0.0000017916864862854709 ]
{ "id": 8, "code_window": [ " <div className={styles.column}>\n", " {collapsable && (\n", " <IconButton\n", " name={isContentVisible ? 'angle-down' : 'angle-right'}\n", " tooltip={isContentVisible ? 'Collapse query row' : 'Expand query row'}\n", " className={styles.collapseIcon}\n", " onClick={onRowToggle}\n", " aria-expanded={isContentVisible}\n", " aria-controls={id}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " tooltip={tooltipMessage}\n" ], "file_path": "public/app/core/components/QueryOperationRow/QueryOperationRowHeader.tsx", "type": "replace", "edit_start_line_idx": 43 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M21,14a1,1,0,0,0-1,1v3.59L5.41,4H9A1,1,0,0,0,9,2H3a1,1,0,0,0-.38.08,1,1,0,0,0-.54.54A1,1,0,0,0,2,3V9A1,1,0,0,0,4,9V5.41L18.59,20H15a1,1,0,0,0,0,2h6a1,1,0,0,0,.38-.08,1,1,0,0,0,.54-.54A1,1,0,0,0,22,21V15A1,1,0,0,0,21,14Z"/></svg>
public/img/icons/unicons/arrows-maximize.svg
0
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.00017402136290911585, 0.00017402136290911585, 0.00017402136290911585, 0.00017402136290911585, 0 ]
{ "id": 8, "code_window": [ " <div className={styles.column}>\n", " {collapsable && (\n", " <IconButton\n", " name={isContentVisible ? 'angle-down' : 'angle-right'}\n", " tooltip={isContentVisible ? 'Collapse query row' : 'Expand query row'}\n", " className={styles.collapseIcon}\n", " onClick={onRowToggle}\n", " aria-expanded={isContentVisible}\n", " aria-controls={id}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " tooltip={tooltipMessage}\n" ], "file_path": "public/app/core/components/QueryOperationRow/QueryOperationRowHeader.tsx", "type": "replace", "edit_start_line_idx": 43 }
# Grafana MSI Generator Creates a docker image that can be included within CircleCI or run locally to generate an MSI for Grafana. ## Docker Image The docker image is created and published via CircleCI, and can also be built locally. The image is self contained with all of the code in `/master`. The detection process expects a zip file in `/master/dist`. There are two patterns that will be matched for a build in the dist directory: ``` grafana-6.0.0-ca0bc2c5pre3.windows-amd64.zip grafana-5.4.3.windows-amd64.zip ``` ### Building an MSI The process is automated to expect a dist directory, and will build an msi for first matching grafana-\*.windows-amd64.zip file found. ``` grafana-5.4.3.windows-amd64.zip ``` ## CircleCI ## Manual A wrapper script takes a single argument for the path to a zip file, or searches for a file in dist. A manual build can be initiated using docker-compose ``` cd oss docker-compose up --build ``` ## Automated ## Testing ## Change Log v1.0.0 - initial commit
scripts/build/ci-msi-build/README.md
0
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.0001712262019282207, 0.000165853911312297, 0.000160869603860192, 0.00016696308739483356, 0.000003686524678414571 ]
{ "id": 9, "code_window": [ " disabled={disabled}\n", " isOpen={toggleExpand()}\n", " // Assure that showHelp is untoggled when the row becomes collapsed.\n", " onClose={() => toggleShowHelp(false)}\n", " >\n", " {showHelp && <OperationRowHelp markdown={prepMarkdown(uiConfig)} />}\n", " {filter && (\n", " <TransformationFilter index={index} config={configs[index].transformation} data={data} onChange={onChange} />\n", " )}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " expanderMessages={{\n", " close: 'Collapse transformation row',\n", " open: 'Expand transformation row',\n", " }}\n" ], "file_path": "public/app/features/dashboard/components/TransformationsEditor/TransformationOperationRow.tsx", "type": "add", "edit_start_line_idx": 169 }
import { css } from '@emotion/css'; import React, { useCallback, useEffect, useState } from 'react'; import { Draggable } from 'react-beautiful-dnd'; import { useUpdateEffect } from 'react-use'; import { GrafanaTheme2 } from '@grafana/data'; import { reportInteraction } from '@grafana/runtime'; import { ReactUtils, useStyles2 } from '@grafana/ui'; import { QueryOperationRowHeader } from './QueryOperationRowHeader'; export interface QueryOperationRowProps { index: number; id: string; title?: string; headerElement?: QueryOperationRowRenderProp; actions?: QueryOperationRowRenderProp; onOpen?: () => void; onClose?: () => void; children: React.ReactNode; isOpen?: boolean; draggable?: boolean; collapsable?: boolean; disabled?: boolean; } export type QueryOperationRowRenderProp = ((props: QueryOperationRowRenderProps) => React.ReactNode) | React.ReactNode; export interface QueryOperationRowRenderProps { isOpen: boolean; onOpen: () => void; onClose: () => void; } export function QueryOperationRow({ children, actions, title, headerElement, onClose, onOpen, isOpen, disabled, draggable, collapsable, index, id, }: QueryOperationRowProps) { const [isContentVisible, setIsContentVisible] = useState(isOpen !== undefined ? isOpen : true); const styles = useStyles2(getQueryOperationRowStyles); const onRowToggle = useCallback(() => { setIsContentVisible(!isContentVisible); }, [isContentVisible, setIsContentVisible]); // Force QueryOperationRow expansion when `isOpen` prop updates in parent component. // `undefined` can be deliberately passed value here, but we only want booleans to trigger the effect. useEffect(() => { if (typeof isOpen === 'boolean') { setIsContentVisible(isOpen); } }, [isOpen]); const reportDragMousePosition = useCallback((e: React.MouseEvent) => { // When drag detected react-beautiful-dnd will preventDefault the event // Ref: https://github.com/atlassian/react-beautiful-dnd/blob/master/docs/guides/how-we-use-dom-events.md#a-mouse-drag-has-started-and-the-user-is-now-dragging if (e.defaultPrevented) { const rect = e.currentTarget.getBoundingClientRect(); const x = e.clientX - rect.left; const y = e.clientY - rect.top; // report relative mouse position within the header element reportInteraction('query_row_reorder_drag_position', { x: x / rect.width, y: y / rect.height, width: rect.width, height: rect.height, }); } }, []); useUpdateEffect(() => { if (isContentVisible) { if (onOpen) { onOpen(); } } else { if (onClose) { onClose(); } } }, [isContentVisible]); const renderPropArgs: QueryOperationRowRenderProps = { isOpen: isContentVisible, onOpen: () => { setIsContentVisible(true); }, onClose: () => { setIsContentVisible(false); }, }; const actionsElement = actions && ReactUtils.renderOrCallToRender(actions, renderPropArgs); const headerElementRendered = headerElement && ReactUtils.renderOrCallToRender(headerElement, renderPropArgs); if (draggable) { return ( <Draggable draggableId={id} index={index}> {(provided) => { return ( <> <div ref={provided.innerRef} className={styles.wrapper} {...provided.draggableProps}> <div> <QueryOperationRowHeader id={id} actionsElement={actionsElement} disabled={disabled} draggable collapsable={collapsable} dragHandleProps={provided.dragHandleProps} headerElement={headerElementRendered} isContentVisible={isContentVisible} onRowToggle={onRowToggle} reportDragMousePosition={reportDragMousePosition} title={title} /> </div> {isContentVisible && <div className={styles.content}>{children}</div>} </div> </> ); }} </Draggable> ); } return ( <div className={styles.wrapper}> <QueryOperationRowHeader id={id} actionsElement={actionsElement} disabled={disabled} draggable={false} collapsable={collapsable} headerElement={headerElementRendered} isContentVisible={isContentVisible} onRowToggle={onRowToggle} reportDragMousePosition={reportDragMousePosition} title={title} /> {isContentVisible && <div className={styles.content}>{children}</div>} </div> ); } const getQueryOperationRowStyles = (theme: GrafanaTheme2) => { return { wrapper: css` margin-bottom: ${theme.spacing(2)}; `, content: css` margin-top: ${theme.spacing(0.5)}; margin-left: ${theme.spacing(3)}; `, }; }; QueryOperationRow.displayName = 'QueryOperationRow';
public/app/core/components/QueryOperationRow/QueryOperationRow.tsx
1
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.0025521842762827873, 0.0006225939723663032, 0.00016328679339494556, 0.0002602402528282255, 0.0007697864202782512 ]
{ "id": 9, "code_window": [ " disabled={disabled}\n", " isOpen={toggleExpand()}\n", " // Assure that showHelp is untoggled when the row becomes collapsed.\n", " onClose={() => toggleShowHelp(false)}\n", " >\n", " {showHelp && <OperationRowHelp markdown={prepMarkdown(uiConfig)} />}\n", " {filter && (\n", " <TransformationFilter index={index} config={configs[index].transformation} data={data} onChange={onChange} />\n", " )}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " expanderMessages={{\n", " close: 'Collapse transformation row',\n", " open: 'Expand transformation row',\n", " }}\n" ], "file_path": "public/app/features/dashboard/components/TransformationsEditor/TransformationOperationRow.tsx", "type": "add", "edit_start_line_idx": 169 }
import { render, screen } from '@testing-library/react'; import React from 'react'; import selectEvent from 'react-select-event'; import { DataSourceInstanceSettings } from '@grafana/data'; import * as ui from '@grafana/ui'; import { TimeSrv } from 'app/features/dashboard/services/TimeSrv'; import { TemplateSrv } from 'app/features/templating/template_srv'; import { CustomVariableModel, initialVariableModelState } from '../../../../../../features/variables/types'; import { CloudWatchDatasource } from '../../../datasource'; import { CloudWatchJsonData, MetricEditorMode, MetricQueryType } from '../../../types'; import { MetricsQueryEditor, Props } from './MetricsQueryEditor'; jest.mock('@grafana/ui', () => ({ ...jest.requireActual<typeof ui>('@grafana/ui'), CodeEditor: function CodeEditor({ value }: { value: string }) { return <pre>{value}</pre>; }, })); const setup = () => { const instanceSettings = { jsonData: { defaultRegion: 'us-east-1' }, } as DataSourceInstanceSettings<CloudWatchJsonData>; const templateSrv = new TemplateSrv(); const variable: CustomVariableModel = { ...initialVariableModelState, id: 'var3', index: 0, name: 'var3', options: [ { selected: true, value: 'var3-foo', text: 'var3-foo' }, { selected: false, value: 'var3-bar', text: 'var3-bar' }, { selected: true, value: 'var3-baz', text: 'var3-baz' }, ], current: { selected: true, value: ['var3-foo', 'var3-baz'], text: 'var3-foo + var3-baz' }, multi: true, includeAll: false, query: '', type: 'custom', }; templateSrv.init([variable]); const datasource = new CloudWatchDatasource(instanceSettings, templateSrv, {} as TimeSrv); datasource.metricFindQuery = async () => [{ value: 'test', label: 'test', text: 'test' }]; datasource.resources.getNamespaces = jest.fn().mockResolvedValue([]); datasource.resources.getMetrics = jest.fn().mockResolvedValue([]); datasource.resources.getRegions = jest.fn().mockResolvedValue([]); datasource.resources.getDimensionKeys = jest.fn().mockResolvedValue([]); datasource.resources.isMonitoringAccount = jest.fn().mockResolvedValue(false); const props: Props = { query: { queryMode: 'Metrics', refId: '', id: '', region: 'us-east-1', namespace: 'ec2', metricName: 'CPUUtilization', dimensions: { somekey: 'somevalue' }, statistic: '', period: '', expression: '', alias: '', matchExact: true, metricQueryType: MetricQueryType.Search, metricEditorMode: MetricEditorMode.Builder, }, extraHeaderElementLeft: () => {}, extraHeaderElementRight: () => {}, datasource, history: [], onChange: jest.fn(), onRunQuery: jest.fn(), }; return props; }; describe('QueryEditor', () => { describe('should handle expression options correctly', () => { it('should display match exact switch', async () => { const props = setup(); render(<MetricsQueryEditor {...props} />); expect(await screen.findByText('Match exact')).toBeInTheDocument(); }); it('should display wildcard option in dimension value dropdown', async () => { const props = setup(); if (props.query.queryMode !== 'Metrics') { fail(`expected props.query.queryMode to be 'Metrics', got '${props.query.queryMode}' instead`); } props.datasource.resources.getDimensionValues = jest .fn() .mockResolvedValue([[{ label: 'dimVal1', value: 'dimVal1' }]]); props.query.metricQueryType = MetricQueryType.Search; props.query.metricEditorMode = MetricEditorMode.Builder; props.query.dimensions = { instanceId: 'instance-123' }; render(<MetricsQueryEditor {...props} />); expect(screen.getByText('Match exact')).toBeInTheDocument(); expect(screen.getByText('instance-123')).toBeInTheDocument(); expect(screen.queryByText('*')).toBeNull(); selectEvent.openMenu(screen.getByLabelText('Dimensions filter value')); expect(await screen.findByText('*')).toBeInTheDocument(); }); }); it('should render label field and not alias field', async () => { const props = setup(); render( <MetricsQueryEditor {...props} query={{ ...props.query, refId: 'A', alias: 'Period: {{period}} InstanceId: {{InstanceId}}' }} /> ); expect(await screen.findByText('Label')).toBeInTheDocument(); expect(screen.queryByText('Alias')).toBeNull(); expect(screen.getByText("Period: ${PROP('Period')} InstanceId: ${PROP('Dim.InstanceId')}")); }); });
public/app/plugins/datasource/cloudwatch/components/QueryEditor/MetricsQueryEditor/MetricsQueryEditor.test.tsx
0
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.00017868977738544345, 0.00017536969971843064, 0.00016880575276445597, 0.00017568559269420803, 0.000002558883124947897 ]
{ "id": 9, "code_window": [ " disabled={disabled}\n", " isOpen={toggleExpand()}\n", " // Assure that showHelp is untoggled when the row becomes collapsed.\n", " onClose={() => toggleShowHelp(false)}\n", " >\n", " {showHelp && <OperationRowHelp markdown={prepMarkdown(uiConfig)} />}\n", " {filter && (\n", " <TransformationFilter index={index} config={configs[index].transformation} data={data} onChange={onChange} />\n", " )}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " expanderMessages={{\n", " close: 'Collapse transformation row',\n", " open: 'Expand transformation row',\n", " }}\n" ], "file_path": "public/app/features/dashboard/components/TransformationsEditor/TransformationOperationRow.tsx", "type": "add", "edit_start_line_idx": 169 }
package pluginsettings import ( "context" "time" ) type FakePluginSettings struct { Service Plugins map[string]*DTO } // GetPluginSettings returns all Plugin Settings for the provided Org func (ps *FakePluginSettings) GetPluginSettings(_ context.Context, _ *GetArgs) ([]*InfoDTO, error) { res := []*InfoDTO{} for _, dto := range ps.Plugins { res = append(res, &InfoDTO{ PluginID: dto.PluginID, OrgID: dto.OrgID, Enabled: dto.Enabled, Pinned: dto.Pinned, PluginVersion: dto.PluginVersion, }) } return res, nil } // GetPluginSettingByPluginID returns a Plugin Settings by Plugin ID func (ps *FakePluginSettings) GetPluginSettingByPluginID(ctx context.Context, args *GetByPluginIDArgs) (*DTO, error) { if res, ok := ps.Plugins[args.PluginID]; ok { return res, nil } return nil, ErrPluginSettingNotFound } // UpdatePluginSetting updates a Plugin Setting func (ps *FakePluginSettings) UpdatePluginSetting(ctx context.Context, args *UpdateArgs) error { var secureData map[string][]byte if args.SecureJSONData != nil { secureData := map[string][]byte{} for k, v := range args.SecureJSONData { secureData[k] = ([]byte)(v) } } // save ps.Plugins[args.PluginID] = &DTO{ ID: int64(len(ps.Plugins)), OrgID: args.OrgID, PluginID: args.PluginID, PluginVersion: args.PluginVersion, JSONData: args.JSONData, SecureJSONData: secureData, Enabled: args.Enabled, Pinned: args.Pinned, Updated: time.Now(), } return nil } // UpdatePluginSettingPluginVersion updates a Plugin Setting's plugin version func (ps *FakePluginSettings) UpdatePluginSettingPluginVersion(ctx context.Context, args *UpdatePluginVersionArgs) error { if res, ok := ps.Plugins[args.PluginID]; ok { res.PluginVersion = args.PluginVersion return nil } return ErrPluginSettingNotFound } // DecryptedValues decrypts the encrypted secureJSONData of the provided plugin setting and // returns the decrypted values. func (ps *FakePluginSettings) DecryptedValues(dto *DTO) map[string]string { // TODO: Implement return nil }
pkg/services/pluginsintegration/pluginsettings/fake.go
0
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.0001902245858218521, 0.00017086006118915975, 0.00016278016846626997, 0.00016756882541812956, 0.000008270973921753466 ]
{ "id": 9, "code_window": [ " disabled={disabled}\n", " isOpen={toggleExpand()}\n", " // Assure that showHelp is untoggled when the row becomes collapsed.\n", " onClose={() => toggleShowHelp(false)}\n", " >\n", " {showHelp && <OperationRowHelp markdown={prepMarkdown(uiConfig)} />}\n", " {filter && (\n", " <TransformationFilter index={index} config={configs[index].transformation} data={data} onChange={onChange} />\n", " )}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " expanderMessages={{\n", " close: 'Collapse transformation row',\n", " open: 'Expand transformation row',\n", " }}\n" ], "file_path": "public/app/features/dashboard/components/TransformationsEditor/TransformationOperationRow.tsx", "type": "add", "edit_start_line_idx": 169 }
import { SelectableValue } from '@grafana/data'; import { SelectableOptGroup } from './types'; /** * Normalize the value format to SelectableValue[] | []. Only used for single select */ export const cleanValue = ( value: unknown, options: Array<SelectableValue | SelectableOptGroup | SelectableOptGroup[]> ) => { if (Array.isArray(value)) { const filtered = value.filter(Boolean); return filtered?.length ? filtered : undefined; } if (typeof value === 'object') { // we want to allow null through into here, so the Select value can be unset return [value]; } if (typeof value === 'string' || typeof value === 'number') { const selectedValue = findSelectedValue(value, options); if (selectedValue) { return [selectedValue]; } } return undefined; }; /** * Find the label for a string|number value inside array of options or optgroups */ export const findSelectedValue = ( value: string | number, options: Array<SelectableValue | SelectableOptGroup | SelectableOptGroup[]> ): SelectableValue | null => { for (const option of options) { if ('options' in option) { let found = findSelectedValue(value, option.options); if (found) { return found; } } else if ('value' in option && option.value === value) { return option; } } return null; }; /** * Omit descriptions from an array of options */ export const omitDescriptions = (options: SelectableValue[]): SelectableValue[] => { return options.map(({ description, ...rest }) => rest); };
packages/grafana-ui/src/components/Select/utils.ts
0
https://github.com/grafana/grafana/commit/0e0f1183e6d534a3a2ae449daaeee67559312c2b
[ 0.0001770063681760803, 0.00017190347716677934, 0.0001604924036655575, 0.00017499946989119053, 0.000006142920938145835 ]
{ "id": 0, "code_window": [ " \"gl\": \"^5.0.0\",\n", " \"xml2js\": \"^0.4.23\"\n", " },\n", " \"publishConfig\": {\n", " \"access\": \"public\"\n", " },\n", " \"transpile\": \"es6\"\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"nodeDependencies\": [\"fs\", \"path\"],\n" ], "file_path": "bundles/pixi.js-node/package.json", "type": "add", "edit_start_line_idx": 73 }
{ "name": "@pixi/node", "version": "6.5.0-rc", "description": "Bundle for PixiJS with support for NodeJS", "homepage": "http://pixijs.com/", "bugs": "https://github.com/pixijs/pixi.js/issues", "repository": { "type": "git", "url": "https://github.com/pixijs/pixi.js.git" }, "license": "MIT", "author": "PixiJS Team", "main": "dist/cjs/node.cjs", "module": "dist/esm/node.mjs", "types": "index.d.ts", "exports": { ".": { "import": { "types": "./index.d.ts", "default": "./dist/esm/node.mjs" }, "require": { "types": "./index.d.ts", "default": "./dist/cjs/node.cjs" } } }, "files": [ "dist", "*.d.ts" ], "engines": { "node": ">=16" }, "dependencies": { "@pixi/app": "6.5.0-rc", "@pixi/assets": "6.5.0-rc", "@pixi/constants": "6.5.0-rc", "@pixi/core": "6.5.0-rc", "@pixi/display": "6.5.0-rc", "@pixi/extract": "6.5.0-rc", "@pixi/filter-alpha": "6.5.0-rc", "@pixi/filter-blur": "6.5.0-rc", "@pixi/filter-color-matrix": "6.5.0-rc", "@pixi/filter-displacement": "6.5.0-rc", "@pixi/filter-fxaa": "6.5.0-rc", "@pixi/filter-noise": "6.5.0-rc", "@pixi/graphics": "6.5.0-rc", "@pixi/math": "6.5.0-rc", "@pixi/mesh": "6.5.0-rc", "@pixi/mesh-extras": "6.5.0-rc", "@pixi/mixin-cache-as-bitmap": "6.5.0-rc", "@pixi/mixin-get-child-by-name": "6.5.0-rc", "@pixi/mixin-get-global-position": "6.5.0-rc", "@pixi/particle-container": "6.5.0-rc", "@pixi/prepare": "6.5.0-rc", "@pixi/runner": "6.5.0-rc", "@pixi/settings": "6.5.0-rc", "@pixi/sprite": "6.5.0-rc", "@pixi/sprite-animated": "6.5.0-rc", "@pixi/sprite-tiling": "6.5.0-rc", "@pixi/spritesheet": "6.5.0-rc", "@pixi/text": "6.5.0-rc", "@pixi/text-bitmap": "6.5.0-rc", "@pixi/ticker": "6.5.0-rc", "@pixi/utils": "6.5.0-rc", "@types/gl": "^4.1.0", "@types/xml2js": "^0.4.11", "canvas": "^2.9.1", "cross-fetch": "^3.1.5", "gl": "^5.0.0", "xml2js": "^0.4.23" }, "publishConfig": { "access": "public" }, "transpile": "es6" }
bundles/pixi.js-node/package.json
1
https://github.com/pixijs/pixijs/commit/b92879837d8b9461fb324606335c0f814ec55465
[ 0.9956617951393127, 0.12460558116436005, 0.00016322375449817628, 0.0001698199921520427, 0.3292282819747925 ]
{ "id": 0, "code_window": [ " \"gl\": \"^5.0.0\",\n", " \"xml2js\": \"^0.4.23\"\n", " },\n", " \"publishConfig\": {\n", " \"access\": \"public\"\n", " },\n", " \"transpile\": \"es6\"\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"nodeDependencies\": [\"fs\", \"path\"],\n" ], "file_path": "bundles/pixi.js-node/package.json", "type": "add", "edit_start_line_idx": 73 }
let UUID = 0; let MAX_WORKERS: number; const workerCode = { id: 'loadImageBitmap', code: ` self.onmessage = function(event) { async function loadImageBitmap(url) { const response = await fetch(url); const imageBlob = await response.blob(); const imageBitmap = await createImageBitmap(imageBlob); return imageBitmap; } loadImageBitmap(event.data.data[0]).then(imageBitmap => { self.postMessage({ data: imageBitmap, uuid: event.data.uuid, id: event.data.id, }, [imageBitmap]); }).catch(error => { self.postMessage({ data: null, uuid: event.data.uuid, id: event.data.id, }); }); }`, }; let workerURL: string; class WorkerManagerClass { public worker: Worker; private resolveHash: {[key: string]: (...param: any[]) => void}; private readonly workerPool: Worker[]; private readonly queue: { id: string; arguments: any[]; resolve: (...param: any[]) => void }[]; private _initialized = false; private _createdWorkers = 0; constructor() { this.workerPool = []; this.queue = []; this.resolveHash = {}; } public loadImageBitmap(src: string): Promise<ImageBitmap> { return this._run('loadImageBitmap', [src]) as Promise<ImageBitmap>; } private async _initWorkers() { if (this._initialized) return; this._initialized = true; } private getWorker(): Worker { if (MAX_WORKERS === undefined) { MAX_WORKERS = navigator.hardwareConcurrency || 4; } let worker = this.workerPool.pop(); if (!worker && this._createdWorkers < MAX_WORKERS) { if (!workerURL) { workerURL = URL.createObjectURL(new Blob([workerCode.code], { type: 'application/javascript' })); } // only create as many as MAX_WORKERS allows.. this._createdWorkers++; worker = new Worker(workerURL); worker.addEventListener('message', (event: MessageEvent) => { this.complete(event.data); this.returnWorker(event.target as Worker); this.next(); }); } return worker; } private returnWorker(worker: Worker) { this.workerPool.push(worker); } private complete(data: any): void { const result = data.data; this.resolveHash[data.uuid](result); this.resolveHash[data.uuid] = null; } private _run(id: string, args: any[]): Promise<any> { this._initWorkers(); // push into the queue... const promise = new Promise((resolve) => { this.queue.push({ id, arguments: args, resolve }); }); this.next(); return promise; } private next(): void { // nothing to do if (!this.queue.length) return; const worker = this.getWorker(); // no workers available... if (!worker) { return; } const toDo = this.queue.pop(); const id = toDo.id; this.resolveHash[UUID] = toDo.resolve; worker.postMessage({ data: toDo.arguments, uuid: UUID++, id, }); } } const WorkerManager = new WorkerManagerClass(); export { WorkerManager, };
packages/assets/src/loader/parsers/WorkerManager.ts
0
https://github.com/pixijs/pixijs/commit/b92879837d8b9461fb324606335c0f814ec55465
[ 0.00019789191719610244, 0.0001718255807645619, 0.00016548448184039444, 0.00016938603948801756, 0.000007658594768145122 ]
{ "id": 0, "code_window": [ " \"gl\": \"^5.0.0\",\n", " \"xml2js\": \"^0.4.23\"\n", " },\n", " \"publishConfig\": {\n", " \"access\": \"public\"\n", " },\n", " \"transpile\": \"es6\"\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"nodeDependencies\": [\"fs\", \"path\"],\n" ], "file_path": "bundles/pixi.js-node/package.json", "type": "add", "edit_start_line_idx": 73 }
import type { Polygon } from '@pixi/math'; import { SHAPES } from '@pixi/math'; import type { CanvasRenderer } from '../CanvasRenderer'; import type { Graphics } from '@pixi/graphics'; import type { MaskData } from '@pixi/core'; import type { Container } from '@pixi/display'; /** * A set of functions used to handle masking. * * Sprite masking is not supported on the CanvasRenderer. * @class * @memberof PIXI */ export class CanvasMaskManager { /** A reference to the current renderer */ private renderer: CanvasRenderer; private _foundShapes: Array<Graphics> = []; /** @param renderer - A reference to the current renderer */ constructor(renderer: CanvasRenderer) { this.renderer = renderer; } /** * This method adds it to the current stack of masks. * @param maskData - the maskData that will be pushed */ pushMask(maskData: MaskData | Graphics): void { const renderer = this.renderer; const maskObject = ((maskData as MaskData).maskObject || maskData) as Container; renderer.context.save(); // TODO support sprite alpha masks?? // lots of effort required. If demand is great enough.. const foundShapes = this._foundShapes; this.recursiveFindShapes(maskObject, foundShapes); if (foundShapes.length > 0) { const { context } = renderer; context.beginPath(); for (let i = 0; i < foundShapes.length; i++) { const shape = foundShapes[i]; const transform = shape.transform.worldTransform; this.renderer.setContextTransform(transform); this.renderGraphicsShape(shape); } foundShapes.length = 0; context.clip(); } } /** * Renders all PIXI.Graphics shapes in a subtree. * @param container - container to scan. * @param out - where to put found shapes */ recursiveFindShapes(container: Container, out: Array<Graphics>): void { if ((container as Graphics).geometry && (container as Graphics).geometry.graphicsData) { out.push(container as Graphics); } const { children } = container; if (children) { for (let i = 0; i < children.length; i++) { this.recursiveFindShapes(children[i] as Container, out); } } } /** * Renders a PIXI.Graphics shape. * @param graphics - The object to render. */ renderGraphicsShape(graphics: Graphics): void { graphics.finishPoly(); const context = this.renderer.context; const graphicsData = graphics.geometry.graphicsData; const len = graphicsData.length; if (len === 0) { return; } for (let i = 0; i < len; i++) { const data = graphicsData[i]; const shape = data.shape; if (shape.type === SHAPES.POLY) { let points = shape.points; const holes = data.holes; let outerArea; let innerArea; let px; let py; context.moveTo(points[0], points[1]); for (let j = 1; j < points.length / 2; j++) { context.lineTo(points[j * 2], points[(j * 2) + 1]); } if (holes.length > 0) { outerArea = 0; px = points[0]; py = points[1]; for (let j = 2; j + 2 < points.length; j += 2) { outerArea += ((points[j] - px) * (points[j + 3] - py)) - ((points[j + 2] - px) * (points[j + 1] - py)); } for (let k = 0; k < holes.length; k++) { points = (holes[k].shape as Polygon).points; if (!points) { continue; } innerArea = 0; px = points[0]; py = points[1]; for (let j = 2; j + 2 < points.length; j += 2) { innerArea += ((points[j] - px) * (points[j + 3] - py)) - ((points[j + 2] - px) * (points[j + 1] - py)); } if (innerArea * outerArea < 0) { context.moveTo(points[0], points[1]); for (let j = 2; j < points.length; j += 2) { context.lineTo(points[j], points[j + 1]); } } else { context.moveTo(points[points.length - 2], points[points.length - 1]); for (let j = points.length - 4; j >= 0; j -= 2) { context.lineTo(points[j], points[j + 1]); } } if ((holes[k].shape as Polygon).closeStroke) { context.closePath(); } } } // if the first and last point are the same close the path - much neater :) if (points[0] === points[points.length - 2] && points[1] === points[points.length - 1]) { context.closePath(); } } else if (shape.type === SHAPES.RECT) { context.rect(shape.x, shape.y, shape.width, shape.height); context.closePath(); } else if (shape.type === SHAPES.CIRC) { // TODO - need to be Undefined! context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); context.closePath(); } else if (shape.type === SHAPES.ELIP) { // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas const w = shape.width * 2; const h = shape.height * 2; const x = shape.x - (w / 2); const y = shape.y - (h / 2); const kappa = 0.5522848; const ox = (w / 2) * kappa; // control point offset horizontal const oy = (h / 2) * kappa; // control point offset vertical const xe = x + w; // x-end const ye = y + h; // y-end const xm = x + (w / 2); // x-middle const ym = y + (h / 2); // y-middle context.moveTo(x, ym); context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); context.closePath(); } else if (shape.type === SHAPES.RREC) { const rx = shape.x; const ry = shape.y; const width = shape.width; const height = shape.height; let radius = shape.radius; const maxRadius = Math.min(width, height) / 2; radius = radius > maxRadius ? maxRadius : radius; context.moveTo(rx, ry + radius); context.lineTo(rx, ry + height - radius); context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); context.lineTo(rx + width - radius, ry + height); context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); context.lineTo(rx + width, ry + radius); context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); context.lineTo(rx + radius, ry); context.quadraticCurveTo(rx, ry, rx, ry + radius); context.closePath(); } } } /** * Restores the current drawing context to the state it was before the mask was applied. * @param renderer - The renderer context to use. */ popMask(renderer: CanvasRenderer): void { renderer.context.restore(); renderer.invalidateBlendMode(); } /** Destroys this canvas mask manager. */ public destroy(): void { /* empty */ } }
packages/canvas-renderer/src/utils/CanvasMaskManager.ts
0
https://github.com/pixijs/pixijs/commit/b92879837d8b9461fb324606335c0f814ec55465
[ 0.00018428081239107996, 0.00017087443848140538, 0.00016639157547615469, 0.00016968864656519145, 0.0000041287003114121035 ]
{ "id": 0, "code_window": [ " \"gl\": \"^5.0.0\",\n", " \"xml2js\": \"^0.4.23\"\n", " },\n", " \"publishConfig\": {\n", " \"access\": \"public\"\n", " },\n", " \"transpile\": \"es6\"\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"nodeDependencies\": [\"fs\", \"path\"],\n" ], "file_path": "bundles/pixi.js-node/package.json", "type": "add", "edit_start_line_idx": 73 }
/** * Used to check whether the given URL is an absolute URL or not. * An absolute URL is defined as a URL that contains the complete details needed to locate a file * * Taken directly from here: https://github.com/sindresorhus/is-absolute-url/blob/master/index.js * * returns true if the URL is absolute, false if relative. * @param url - The URL to test */ export function isAbsoluteUrl(url: string): boolean { // Don't match Windows paths `c:\` if ((/^[a-zA-Z]:\\/).test(url)) { return false; } // Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 // Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 return (/^[a-zA-Z][a-zA-Z\d+\-.]*:/).test(url); }
packages/assets/src/utils/url/isAbsoluteUrl.ts
0
https://github.com/pixijs/pixijs/commit/b92879837d8b9461fb324606335c0f814ec55465
[ 0.00017169804777950048, 0.00016915368905756623, 0.0001658253459027037, 0.0001699376734904945, 0.0000024607763862150023 ]
{ "id": 1, "code_window": [ " bundleNoExports,\n", " standalone,\n", " version,\n", " dependencies,\n", " peerDependencies,\n", " // TODO: remove this in v7, along with the declaration in the package.json\n", " // This is a temporary fix to skip transpiling on the @pixi/node package\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " nodeDependencies,\n" ], "file_path": "rollup.config.js", "type": "add", "edit_start_line_idx": 121 }
import path from 'path'; import transpile from '@rollup/plugin-buble'; import resolve from '@rollup/plugin-node-resolve'; import { string } from 'rollup-plugin-string'; import sourcemaps from 'rollup-plugin-sourcemaps'; import typescript from 'rollup-plugin-typescript'; import commonjs from '@rollup/plugin-commonjs'; import json from '@rollup/plugin-json'; import { terser } from 'rollup-plugin-terser'; import jscc from 'rollup-plugin-jscc'; import alias from '@rollup/plugin-alias'; import workspacesRun from 'workspaces-run'; import repo from './lerna.json'; import fs from 'fs'; const isProduction = process.env.NODE_ENV === 'production'; /** * Get the JSCC plugin for preprocessing code. * @param {boolean} debug Build is for debugging */ function preprocessPlugin(debug) { return jscc({ values: { _DEBUG: debug, _PROD: !debug, _VERSION: repo.version, } }); } /** * Convert a development file name to minified. * @param {string} name */ function prodName(name) { return name.replace(/\.(m)?js$/, '.min.$1js'); } async function main() { let commonPlugins = [ sourcemaps(), resolve({ browser: true, preferBuiltins: false, }), commonjs(), json(), typescript({ downlevelIteration: false }), string({ include: [ '**/*.frag', '**/*.vert', ], }), transpile(), ]; let plugins = [ preprocessPlugin(true), ...commonPlugins ]; let prodPlugins = [ preprocessPlugin(false), ...commonPlugins, terser({ output: { comments: (node, comment) => comment.line === 1, }, }) ]; const prodBundlePlugins = [ alias({ entries: [{ find: /^(@pixi\/([^\/]+))$/, replacement: '$1/dist/esm/$2.min.js', }] }), ...prodPlugins ]; const compiled = (new Date()).toUTCString().replace(/GMT/g, 'UTC'); const sourcemap = true; const results = []; const packages = []; // Collect the list of packages await workspacesRun({ cwd: __dirname, orderByDeps: true }, async (pkg) => { if (!pkg.config.private) { packages.push(pkg); } }); const namespaces = {}; // Create a map of globals to use for bundled packages packages.forEach((pkg) => { namespaces[pkg.name] = pkg.config.namespace || 'PIXI'; }); packages.forEach((pkg) => { const { main, module, bundle, bundleModule, bundleInput, bundleOutput, bundleNoExports, standalone, version, dependencies, peerDependencies, // TODO: remove this in v7, along with the declaration in the package.json // This is a temporary fix to skip transpiling on the @pixi/node package transpile } = pkg.config; const banner = [ `/*!`, ` * ${pkg.name} - v${version}`, ` * Compiled ${compiled}`, ` *`, ` * ${pkg.name} is licensed under the MIT License.`, ` * http://www.opensource.org/licenses/mit-license`, ` */`, ].join('\n'); // Check for bundle folder const external = Object.keys(dependencies || []) .concat(Object.keys(peerDependencies || [])); const basePath = path.relative(__dirname, pkg.dir); const input = path.join(basePath, 'src/index.ts'); const freeze = false; if (transpile === 'es6') { // TODO: this hack is for the @pixi/node package to skip transpiling. // This can be removed in v7 where transpiling is no longer required. commonPlugins = [ sourcemaps(), resolve({ browser: true, preferBuiltins: false, }), commonjs(), json(), // TODO: We do still need to keep this plugin for the @pixi/node package as `importHelpers` is required typescript({ importHelpers: true, target: 'ES2020', }), string({ include: [ '**/*.frag', '**/*.vert', ], }), ]; plugins = [ preprocessPlugin(true), ...commonPlugins ]; prodPlugins = [ preprocessPlugin(false), ...commonPlugins, terser({ output: { comments: (node, comment) => comment.line === 1, }, }) ]; } results.push({ input, output: [ { banner, file: path.join(basePath, main), format: 'cjs', freeze, sourcemap, }, { banner, file: path.join(basePath, module), format: 'esm', freeze, sourcemap, }, ], external, plugins, }); if (isProduction) { results.push({ input, output: [ { banner, file: path.join(basePath, prodName(main)), format: 'cjs', freeze, sourcemap, }, { banner, file: path.join(basePath, prodName(module)), format: 'esm', freeze, sourcemap, }, ], external, plugins: prodPlugins, }); } // The package.json file has a bundle field // we'll use this to generate the bundle file // this will package all dependencies if (bundle) { let input = path.join(basePath, bundleInput || 'src/index.ts'); // TODO: remove check once all packages have been converted to typescript if (!fs.existsSync(input)) { input = path.join(basePath, bundleInput || 'src/index.js'); } const file = path.join(basePath, bundle); const moduleFile = bundleModule ? path.join(basePath, bundleModule) : ''; const external = standalone ? null : Object.keys(namespaces); const globals = standalone ? null : namespaces; const ns = namespaces[pkg.name]; const name = pkg.name.replace(/[^a-z]+/g, '_'); let footer; let nsBanner = banner; // Ignore self-contained packages like polyfills and unsafe-eval // as well as the bundles pixi.js and pixi.js-legacy if (!standalone) { if (bundleNoExports !== true) { footer = `Object.assign(this.${ns}, ${name});`; } if (ns.includes('.')) { const base = ns.split('.')[0]; nsBanner += `\nthis.${base} = this.${base} || {};`; } nsBanner += `\nthis.${ns} = this.${ns} || {};`; } results.push({ input, external, output: [ Object.assign({ banner: nsBanner, file, format: 'iife', freeze, globals, name, footer, sourcemap, }, bundleOutput), ...moduleFile ? [{ banner, file: moduleFile, format: 'esm', freeze, sourcemap, }] : [] ], treeshake: false, plugins, }); if (isProduction) { results.push({ input, external, output: [ Object.assign({ banner: nsBanner, file: prodName(file), format: 'iife', freeze, globals, name, footer, sourcemap, }, bundleOutput), ...moduleFile ? [{ banner, file: prodName(moduleFile), format: 'esm', freeze, sourcemap, }] : [] ], treeshake: false, plugins: prodBundlePlugins, }); } } }); return results; } export default main();
rollup.config.js
1
https://github.com/pixijs/pixijs/commit/b92879837d8b9461fb324606335c0f814ec55465
[ 0.995179295539856, 0.08417665958404541, 0.00016446152585558593, 0.0001708106865407899, 0.2502377927303314 ]
{ "id": 1, "code_window": [ " bundleNoExports,\n", " standalone,\n", " version,\n", " dependencies,\n", " peerDependencies,\n", " // TODO: remove this in v7, along with the declaration in the package.json\n", " // This is a temporary fix to skip transpiling on the @pixi/node package\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " nodeDependencies,\n" ], "file_path": "rollup.config.js", "type": "add", "edit_start_line_idx": 121 }
The MIT License Copyright (c) 2013-2018 Mathew Groves, Chad Engler Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
packages/sprite/LICENSE
0
https://github.com/pixijs/pixijs/commit/b92879837d8b9461fb324606335c0f814ec55465
[ 0.00017521415429655463, 0.00017140251293312758, 0.00016846839571371675, 0.0001705249451333657, 0.0000028229876534169307 ]
{ "id": 1, "code_window": [ " bundleNoExports,\n", " standalone,\n", " version,\n", " dependencies,\n", " peerDependencies,\n", " // TODO: remove this in v7, along with the declaration in the package.json\n", " // This is a temporary fix to skip transpiling on the @pixi/node package\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " nodeDependencies,\n" ], "file_path": "rollup.config.js", "type": "add", "edit_start_line_idx": 121 }
import { Rectangle, Matrix } from '@pixi/math'; describe('Rectangle', () => { it('should create a new rectangle', () => { const rect = new Rectangle(5, 5, 1, 1); expect(rect.left).toEqual(5); expect(rect.top).toEqual(5); expect(rect.right).toEqual(6); expect(rect.bottom).toEqual(6); }); it('should cast quantities to number types', () => { const rect = new Rectangle('5', '5', '1', '1'); expect(rect.left).toEqual(5); expect(rect.top).toEqual(5); expect(rect.right).toEqual(6); expect(rect.bottom).toEqual(6); }); it('should clone a new rectangle', () => { const rect1 = new Rectangle(10, 10, 10, 10); expect(rect1.x).toEqual(10); expect(rect1.y).toEqual(10); expect(rect1.width).toEqual(10); expect(rect1.height).toEqual(10); const rect2 = rect1.clone(); expect(rect2.x).toEqual(10); expect(rect2.y).toEqual(10); expect(rect2.width).toEqual(10); expect(rect2.height).toEqual(10); expect(rect1).not.toBe(rect2); }); it('should copy from one rectangle to another', () => { const rect1 = new Rectangle(10, 10, 10, 10); const rect2 = new Rectangle(2, 2, 5, 5); rect1.copyFrom(rect2); expect(rect1.x).toEqual(2); expect(rect1.y).toEqual(2); expect(rect1.width).toEqual(5); expect(rect1.height).toEqual(5); }); it('should check if point is within rectangle', () => { const rect1 = new Rectangle(10, 10, 10, 10); expect(rect1.contains(10, 10)).toBe(true); expect(rect1.contains(10, 19)).toBe(true); expect(rect1.contains(19, 10)).toBe(true); expect(rect1.contains(15, 15)).toBe(true); expect(rect1.contains(10, 9)).toBe(false); expect(rect1.contains(9, 10)).toBe(false); expect(rect1.contains(10, 20)).toBe(false); expect(rect1.contains(20, 10)).toBe(false); expect(rect1.contains(21, 21)).toBe(false); const rect2 = new Rectangle(10, 10, 10, 0); expect(rect2.contains(10, 10)).toBe(false); expect(rect2.contains(20, 20)).toBe(false); expect(rect2.contains(15, 15)).toBe(false); expect(rect2.contains(10, 9)).toBe(false); expect(rect2.contains(9, 10)).toBe(false); expect(rect2.contains(21, 21)).toBe(false); }); it('should enlarge rectangle', () => { const rect1 = new Rectangle(10, 10, 10, 10); const rect2 = new Rectangle(15, 15, 10, 10); rect1.enlarge(rect2); expect(rect1.left).toEqual(10); expect(rect1.top).toEqual(10); expect(rect1.right).toEqual(25); expect(rect1.bottom).toEqual(25); const rect3 = new Rectangle(0, 0, 0, 0); const rect4 = new Rectangle(10, 10, 10, 10); rect4.enlarge(rect3); expect(rect4.left).toEqual(0); expect(rect4.top).toEqual(0); expect(rect4.right).toEqual(20); expect(rect4.bottom).toEqual(20); }); it('should pad a rectangle', () => { // Pad with X & Y const rect = new Rectangle(10, 10, 10, 10); rect.pad(10, 10); expect(rect.left).toEqual(0); expect(rect.top).toEqual(0); expect(rect.right).toEqual(30); expect(rect.bottom).toEqual(30); // Pad with X const rect1 = new Rectangle(10, 10, 10, 10); rect1.pad(10); expect(rect1.left).toEqual(0); expect(rect1.top).toEqual(0); expect(rect1.right).toEqual(30); expect(rect1.bottom).toEqual(30); // Pad with nothing const rect2 = new Rectangle(10, 10, 10, 10); rect2.pad(); expect(rect2.left).toEqual(10); expect(rect2.top).toEqual(10); expect(rect2.right).toEqual(20); expect(rect2.bottom).toEqual(20); // Pad with Y const rect3 = new Rectangle(10, 10, 10, 10); rect3.pad(null, 10); expect(rect3.left).toEqual(10); expect(rect3.top).toEqual(0); expect(rect3.right).toEqual(20); expect(rect3.bottom).toEqual(30); }); it('should fit a rectangle', () => { const rect1 = new Rectangle(0, 0, 10, 10); const rect2 = new Rectangle(-10, -10, 5, 5); rect2.fit(rect1); expect(rect2.left).toEqual(0); expect(rect2.top).toEqual(0); expect(rect2.right).toEqual(0); expect(rect2.bottom).toEqual(0); const rect3 = new Rectangle(0, 0, 20, 20); const rect4 = new Rectangle(10, 0, 20, 20); rect3.fit(rect4); expect(rect3.left).toEqual(10); expect(rect3.top).toEqual(0); expect(rect3.right).toEqual(20); expect(rect3.bottom).toEqual(20); const rect5 = new Rectangle(10, 10, 20, 25); const rect6 = new Rectangle(22, 24, 20, 20); rect5.fit(rect6); expect(rect5.left).toEqual(22); expect(rect5.top).toEqual(24); expect(rect5.right).toEqual(30); expect(rect5.bottom).toEqual(35); const rect7 = new Rectangle(11, 10, 20, 25); const rect8 = new Rectangle(10, 9, 13, 10); rect7.fit(rect8); expect(rect7.left).toEqual(11); expect(rect7.top).toEqual(10); expect(rect7.right).toEqual(23); expect(rect7.bottom).toEqual(19); }); it('should generate an empty rectangle', () => { const rect = Rectangle.EMPTY; expect(rect.left).toEqual(0); expect(rect.top).toEqual(0); expect(rect.right).toEqual(0); expect(rect.bottom).toEqual(0); }); it('should return true if the area of the intersection > 0', () => { /* ! SHARING A SIDE IS NOT INTERSECTING ! +--------+--------+ | A | B | | +---+--+ | | | E| | | +----|---+--|-----+ | | | | | | C +---+--+ D | | | 🄵 | +--------+--------+ */ const a = new Rectangle(0, 0, 100, 100); const b = new Rectangle(100, 0, 100, 100); const c = new Rectangle(0, 100, 100, 100); const d = new Rectangle(100, 100, 100, 100); const e = new Rectangle(50, 50, 100, 100); const f = new Rectangle(150, 175, 0, 0); // e intersects a,b,c,d expect(e.intersects(a)).toEqual(true); expect(e.intersects(b)).toEqual(true); expect(e.intersects(c)).toEqual(true); expect(e.intersects(d)).toEqual(true); expect(e.intersects(a, new Matrix())).toEqual(true); expect(e.intersects(b, new Matrix())).toEqual(true); expect(e.intersects(c, new Matrix())).toEqual(true); expect(e.intersects(d, new Matrix())).toEqual(true); // works the other way arround expect(a.intersects(e)).toEqual(true); expect(b.intersects(e)).toEqual(true); expect(c.intersects(e)).toEqual(true); expect(d.intersects(e)).toEqual(true); expect(a.intersects(e, new Matrix())).toEqual(true); expect(b.intersects(e, new Matrix())).toEqual(true); expect(c.intersects(e, new Matrix())).toEqual(true); expect(d.intersects(e, new Matrix())).toEqual(true); // none of the other intersect (sharing a side it is NOT intersecting!) expect(a.intersects(b)).toEqual(false); // share Y side expect(b.intersects(d)).toEqual(false); // share X side expect(c.intersects(b)).toEqual(false); // share single point expect(a.intersects(b, new Matrix())).toEqual(false); // share Y side expect(b.intersects(d, new Matrix())).toEqual(false); // share X side expect(c.intersects(b, new Matrix())).toEqual(false); // share single point // Since F has no area, the intersection with D it's 0 so it's false. expect(f.intersects(d)).toEqual(false); expect(f.intersects(d, new Matrix())).toEqual(false); // Any rectangle with area intersects itself expect(a.intersects(a.clone())).toEqual(true); expect(b.intersects(b.clone())).toEqual(true); expect(c.intersects(c.clone())).toEqual(true); expect(d.intersects(d.clone())).toEqual(true); expect(e.intersects(e.clone())).toEqual(true); expect(a.intersects(a.clone(), new Matrix())).toEqual(true); expect(b.intersects(b.clone(), new Matrix())).toEqual(true); expect(c.intersects(c.clone(), new Matrix())).toEqual(true); expect(d.intersects(d.clone(), new Matrix())).toEqual(true); expect(e.intersects(e.clone(), new Matrix())).toEqual(true); // A point without area can't have an intersection, thus it can't even intersect itself expect(f.intersects(f.clone())).toEqual(false); expect(f.intersects(f.clone(), new Matrix())).toEqual(false); // No intersection if the transform is degenerate expect(a.intersects(a.clone(), new Matrix().scale(0, 1))).toEqual(false); expect(a.intersects(a.clone(), new Matrix().scale(0.5, 0.5))).toEqual(true); expect(a.intersects(a.clone(), new Matrix().scale(2, 2))).toEqual(true); const m = new Matrix().translate(-50, -50).rotate(Math.PI / 4); expect(a.intersects(a.clone(), m.clone().translate(-35, -35))).toEqual(true); expect(a.intersects(a.clone(), m.clone().translate(-36, -36))).toEqual(false); expect(a.intersects(a.clone(), m.clone().translate(135, -35))).toEqual(true); expect(a.intersects(a.clone(), m.clone().translate(136, -36))).toEqual(false); expect(a.intersects(a.clone(), m.clone().translate(-35, 135))).toEqual(true); expect(a.intersects(a.clone(), m.clone().translate(-36, 136))).toEqual(false); expect(a.intersects(a.clone(), m.clone().translate(135, 135))).toEqual(true); expect(a.intersects(a.clone(), m.clone().translate(136, 136))).toEqual(false); expect(a.intersects(a.clone(), m.clone().scale(-1, +1).translate(-35, -35))).toEqual(true); expect(a.intersects(a.clone(), m.clone().scale(-1, +1).translate(-36, -36))).toEqual(false); expect(a.intersects(a.clone(), m.clone().scale(-1, +1).translate(135, -35))).toEqual(true); expect(a.intersects(a.clone(), m.clone().scale(-1, +1).translate(136, -36))).toEqual(false); expect(a.intersects(a.clone(), m.clone().scale(-1, +1).translate(-35, 135))).toEqual(true); expect(a.intersects(a.clone(), m.clone().scale(-1, +1).translate(-36, 136))).toEqual(false); expect(a.intersects(a.clone(), m.clone().scale(-1, +1).translate(135, 135))).toEqual(true); expect(a.intersects(a.clone(), m.clone().scale(-1, +1).translate(136, 136))).toEqual(false); }); });
packages/math/test/Rectangle.tests.ts
0
https://github.com/pixijs/pixijs/commit/b92879837d8b9461fb324606335c0f814ec55465
[ 0.00017772581486497074, 0.00017463126278016716, 0.0001705405447864905, 0.00017450291488785297, 0.0000016378393183913431 ]
{ "id": 1, "code_window": [ " bundleNoExports,\n", " standalone,\n", " version,\n", " dependencies,\n", " peerDependencies,\n", " // TODO: remove this in v7, along with the declaration in the package.json\n", " // This is a temporary fix to skip transpiling on the @pixi/node package\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " nodeDependencies,\n" ], "file_path": "rollup.config.js", "type": "add", "edit_start_line_idx": 121 }
/** * @namespace PIXI.glCore * @private */ /** * @namespace PIXI.glCore.shader * @private */ export * from './compileShader'; export * from './logProgramError'; export * from './defaultValue'; export * from './getMaxFragmentPrecision'; export * from './setPrecision'; export * from './mapSize'; export * from './mapType'; export * from './generateUniformsSync'; export * from './uniformParsers'; export * from './getTestContext'; export * from './checkMaxIfStatementsInShader'; export * from './unsafeEvalSupported';
packages/core/src/shader/utils/index.ts
0
https://github.com/pixijs/pixijs/commit/b92879837d8b9461fb324606335c0f814ec55465
[ 0.00017195854161400348, 0.00017168234626296908, 0.00017119028780143708, 0.0001718982239253819, 3.488115964955796e-7 ]
{ "id": 2, "code_window": [ " ].join('\\n');\n", "\n", " // Check for bundle folder\n", " const external = Object.keys(dependencies || [])\n", " .concat(Object.keys(peerDependencies || []));\n", " const basePath = path.relative(__dirname, pkg.dir);\n", " const input = path.join(basePath, 'src/index.ts');\n", " const freeze = false;\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " .concat(Object.keys(peerDependencies || []))\n", " .concat(nodeDependencies || []);\n" ], "file_path": "rollup.config.js", "type": "replace", "edit_start_line_idx": 139 }
import path from 'path'; import transpile from '@rollup/plugin-buble'; import resolve from '@rollup/plugin-node-resolve'; import { string } from 'rollup-plugin-string'; import sourcemaps from 'rollup-plugin-sourcemaps'; import typescript from 'rollup-plugin-typescript'; import commonjs from '@rollup/plugin-commonjs'; import json from '@rollup/plugin-json'; import { terser } from 'rollup-plugin-terser'; import jscc from 'rollup-plugin-jscc'; import alias from '@rollup/plugin-alias'; import workspacesRun from 'workspaces-run'; import repo from './lerna.json'; import fs from 'fs'; const isProduction = process.env.NODE_ENV === 'production'; /** * Get the JSCC plugin for preprocessing code. * @param {boolean} debug Build is for debugging */ function preprocessPlugin(debug) { return jscc({ values: { _DEBUG: debug, _PROD: !debug, _VERSION: repo.version, } }); } /** * Convert a development file name to minified. * @param {string} name */ function prodName(name) { return name.replace(/\.(m)?js$/, '.min.$1js'); } async function main() { let commonPlugins = [ sourcemaps(), resolve({ browser: true, preferBuiltins: false, }), commonjs(), json(), typescript({ downlevelIteration: false }), string({ include: [ '**/*.frag', '**/*.vert', ], }), transpile(), ]; let plugins = [ preprocessPlugin(true), ...commonPlugins ]; let prodPlugins = [ preprocessPlugin(false), ...commonPlugins, terser({ output: { comments: (node, comment) => comment.line === 1, }, }) ]; const prodBundlePlugins = [ alias({ entries: [{ find: /^(@pixi\/([^\/]+))$/, replacement: '$1/dist/esm/$2.min.js', }] }), ...prodPlugins ]; const compiled = (new Date()).toUTCString().replace(/GMT/g, 'UTC'); const sourcemap = true; const results = []; const packages = []; // Collect the list of packages await workspacesRun({ cwd: __dirname, orderByDeps: true }, async (pkg) => { if (!pkg.config.private) { packages.push(pkg); } }); const namespaces = {}; // Create a map of globals to use for bundled packages packages.forEach((pkg) => { namespaces[pkg.name] = pkg.config.namespace || 'PIXI'; }); packages.forEach((pkg) => { const { main, module, bundle, bundleModule, bundleInput, bundleOutput, bundleNoExports, standalone, version, dependencies, peerDependencies, // TODO: remove this in v7, along with the declaration in the package.json // This is a temporary fix to skip transpiling on the @pixi/node package transpile } = pkg.config; const banner = [ `/*!`, ` * ${pkg.name} - v${version}`, ` * Compiled ${compiled}`, ` *`, ` * ${pkg.name} is licensed under the MIT License.`, ` * http://www.opensource.org/licenses/mit-license`, ` */`, ].join('\n'); // Check for bundle folder const external = Object.keys(dependencies || []) .concat(Object.keys(peerDependencies || [])); const basePath = path.relative(__dirname, pkg.dir); const input = path.join(basePath, 'src/index.ts'); const freeze = false; if (transpile === 'es6') { // TODO: this hack is for the @pixi/node package to skip transpiling. // This can be removed in v7 where transpiling is no longer required. commonPlugins = [ sourcemaps(), resolve({ browser: true, preferBuiltins: false, }), commonjs(), json(), // TODO: We do still need to keep this plugin for the @pixi/node package as `importHelpers` is required typescript({ importHelpers: true, target: 'ES2020', }), string({ include: [ '**/*.frag', '**/*.vert', ], }), ]; plugins = [ preprocessPlugin(true), ...commonPlugins ]; prodPlugins = [ preprocessPlugin(false), ...commonPlugins, terser({ output: { comments: (node, comment) => comment.line === 1, }, }) ]; } results.push({ input, output: [ { banner, file: path.join(basePath, main), format: 'cjs', freeze, sourcemap, }, { banner, file: path.join(basePath, module), format: 'esm', freeze, sourcemap, }, ], external, plugins, }); if (isProduction) { results.push({ input, output: [ { banner, file: path.join(basePath, prodName(main)), format: 'cjs', freeze, sourcemap, }, { banner, file: path.join(basePath, prodName(module)), format: 'esm', freeze, sourcemap, }, ], external, plugins: prodPlugins, }); } // The package.json file has a bundle field // we'll use this to generate the bundle file // this will package all dependencies if (bundle) { let input = path.join(basePath, bundleInput || 'src/index.ts'); // TODO: remove check once all packages have been converted to typescript if (!fs.existsSync(input)) { input = path.join(basePath, bundleInput || 'src/index.js'); } const file = path.join(basePath, bundle); const moduleFile = bundleModule ? path.join(basePath, bundleModule) : ''; const external = standalone ? null : Object.keys(namespaces); const globals = standalone ? null : namespaces; const ns = namespaces[pkg.name]; const name = pkg.name.replace(/[^a-z]+/g, '_'); let footer; let nsBanner = banner; // Ignore self-contained packages like polyfills and unsafe-eval // as well as the bundles pixi.js and pixi.js-legacy if (!standalone) { if (bundleNoExports !== true) { footer = `Object.assign(this.${ns}, ${name});`; } if (ns.includes('.')) { const base = ns.split('.')[0]; nsBanner += `\nthis.${base} = this.${base} || {};`; } nsBanner += `\nthis.${ns} = this.${ns} || {};`; } results.push({ input, external, output: [ Object.assign({ banner: nsBanner, file, format: 'iife', freeze, globals, name, footer, sourcemap, }, bundleOutput), ...moduleFile ? [{ banner, file: moduleFile, format: 'esm', freeze, sourcemap, }] : [] ], treeshake: false, plugins, }); if (isProduction) { results.push({ input, external, output: [ Object.assign({ banner: nsBanner, file: prodName(file), format: 'iife', freeze, globals, name, footer, sourcemap, }, bundleOutput), ...moduleFile ? [{ banner, file: prodName(moduleFile), format: 'esm', freeze, sourcemap, }] : [] ], treeshake: false, plugins: prodBundlePlugins, }); } } }); return results; } export default main();
rollup.config.js
1
https://github.com/pixijs/pixijs/commit/b92879837d8b9461fb324606335c0f814ec55465
[ 0.9990479350090027, 0.3816600739955902, 0.00016353142564184964, 0.00039387092692777514, 0.48436227440834045 ]
{ "id": 2, "code_window": [ " ].join('\\n');\n", "\n", " // Check for bundle folder\n", " const external = Object.keys(dependencies || [])\n", " .concat(Object.keys(peerDependencies || []));\n", " const basePath = path.relative(__dirname, pkg.dir);\n", " const input = path.join(basePath, 'src/index.ts');\n", " const freeze = false;\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " .concat(Object.keys(peerDependencies || []))\n", " .concat(nodeDependencies || []);\n" ], "file_path": "rollup.config.js", "type": "replace", "edit_start_line_idx": 139 }
{ "name": "@pixi/canvas-prepare", "version": "6.5.0-rc", "main": "dist/cjs/canvas-prepare.js", "module": "dist/esm/canvas-prepare.js", "bundle": "dist/browser/canvas-prepare.js", "types": "index.d.ts", "exports": { ".": { "import": { "types": "./index.d.ts", "default": "./dist/esm/canvas-prepare.js" }, "require": { "types": "./index.d.ts", "default": "./dist/cjs/canvas-prepare.js" } } }, "description": "Canvas mixin for the prepare package", "author": "Mat Groves", "contributors": [ "Matt Karl <[email protected]>" ], "homepage": "http://pixijs.com/", "bugs": "https://github.com/pixijs/pixi.js/issues", "license": "MIT", "repository": { "type": "git", "url": "https://github.com/pixijs/pixi.js.git" }, "publishConfig": { "access": "public" }, "files": [ "lib", "dist", "*.d.ts" ], "peerDependencies": { "@pixi/canvas-renderer": "6.5.0-rc", "@pixi/core": "6.5.0-rc", "@pixi/prepare": "6.5.0-rc" } }
packages/canvas-prepare/package.json
0
https://github.com/pixijs/pixijs/commit/b92879837d8b9461fb324606335c0f814ec55465
[ 0.00017708336235955358, 0.00017301324987784028, 0.00017176615074276924, 0.0001721278385957703, 0.000002045570681730169 ]
{ "id": 2, "code_window": [ " ].join('\\n');\n", "\n", " // Check for bundle folder\n", " const external = Object.keys(dependencies || [])\n", " .concat(Object.keys(peerDependencies || []));\n", " const basePath = path.relative(__dirname, pkg.dir);\n", " const input = path.join(basePath, 'src/index.ts');\n", " const freeze = false;\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " .concat(Object.keys(peerDependencies || []))\n", " .concat(nodeDependencies || []);\n" ], "file_path": "rollup.config.js", "type": "replace", "edit_start_line_idx": 139 }
import type { IBatchableElement } from '@pixi/core'; import { Renderer, BatchRenderer, CanvasResource, Texture, BaseTexture } from '@pixi/core'; import { skipHello } from '@pixi/utils'; import { BLEND_MODES } from '@pixi/constants'; skipHello(); describe('BatchRenderer', () => { function createTexture(w: number, h: number) { const canvas = document.createElement('canvas'); const context = canvas.getContext('2d'); canvas.width = w; canvas.height = h; context.fillStyle = 'white'; context.fillRect(0, 0, w, h); return new BaseTexture(new CanvasResource(canvas)); } const uvs = [0, 0, 1, 0, 1, 1, 0, 1]; const vertexData = uvs; const indices = [0, 1, 2, 0, 2, 3]; const uvs2 = [0, 0, 1, 0, 1, 1, 0.5, 1, 1, 1]; const vertexData2 = uvs2; const indices2 = [0, 1, 2, 3, 4]; const tex1 = createTexture(10, 10); const tex2 = createTexture(20, 20); const tex3 = createTexture(16, 24); const tex4 = createTexture(24, 16); const tint1 = 0xffffff; const tint2 = 0xffff00; const tint3 = 0x00ffff; it('should pass the batching test', () => { const renderer = new Renderer({ width: 1, height: 1 }); const batchRenderer = new BatchRenderer(renderer); const drawCalls = [] as number[]; renderer.gl.drawElements = (_type, size, _indexType, start) => { drawCalls.push(start, size); }; // optimal is three drawCalls, but due to priority of bindTexture there are four const elements = [ { uvs, vertexData, indices, _tintRGB: tint1, worldAlpha: 1.0, _texture: new Texture(tex1), blendMode: 0 }, { uvs, vertexData, indices, _tintRGB: tint1, worldAlpha: 0.5, _texture: new Texture(tex2), blendMode: 0 }, { uvs, vertexData, indices, _tintRGB: tint2, worldAlpha: 1.0, _texture: new Texture(tex1), blendMode: 0 }, { uvs, vertexData, indices, _tintRGB: tint2, worldAlpha: 0.5, _texture: new Texture(tex2), blendMode: 1 }, { uvs, vertexData, indices, _tintRGB: tint1, worldAlpha: 1.0, _texture: new Texture(tex3), blendMode: 0 }, { uvs: uvs2, vertexData: vertexData2, indices: indices2, _tintRGB: tint2, worldAlpha: 1.0, _texture: new Texture(tex1), blendMode: 0 }, { uvs, vertexData, indices, _tintRGB: tint3, worldAlpha: 1.0, _texture: new Texture(tex2), blendMode: 0 }, { uvs, vertexData, indices, _tintRGB: tint1, worldAlpha: 0.5, _texture: new Texture(tex4), blendMode: 0 }, ] as unknown as IBatchableElement[]; const nullArray = [null, null, null, null, null, null, null, null] as null[]; try { batchRenderer.size = 300; batchRenderer.contextChange(); batchRenderer.MAX_TEXTURES = 2; batchRenderer.start(); elements.forEach((element) => batchRenderer.render(element)); expect(batchRenderer['_bufferedElements'].length).toEqual(8); expect(batchRenderer['_bufferedTextures'].length).toEqual(8); batchRenderer.flush(); expect(batchRenderer['_bufferedElements']).toEqual(nullArray); expect(batchRenderer['_bufferedTextures']).toEqual(nullArray); const attrCount = batchRenderer['_aIndex']; // first number is start * 2, second is size expect(drawCalls).toEqual([0, 18, 36, 6, 48, 11, 70, 12]); expect(attrCount).toEqual(198); // eslint-disable-next-line no-console const attr = [0x0, 0x0, 0x0, 0x0, 0xffffffff, 0x0, 0x3f800000, 0x0, 0x3f800000, 0x0, 0xffffffff, 0x0, 0x3f800000, 0x3f800000, 0x3f800000, 0x3f800000, 0xffffffff, 0x0, 0x0, 0x3f800000, 0x0, 0x3f800000, 0xffffffff, 0x0, 0x0, 0x0, 0x0, 0x0, 0x7f808080, 0x3f800000, 0x3f800000, 0x0, 0x3f800000, 0x0, 0x7f808080, 0x3f800000, 0x3f800000, 0x3f800000, 0x3f800000, 0x3f800000, 0x7f808080, 0x3f800000, 0x0, 0x3f800000, 0x0, 0x3f800000, 0x7f808080, 0x3f800000, 0x0, 0x0, 0x0, 0x0, 0xffffff00, 0x0, 0x3f800000, 0x0, 0x3f800000, 0x0, 0xffffff00, 0x0, 0x3f800000, 0x3f800000, 0x3f800000, 0x3f800000, 0xffffff00, 0x0, 0x0, 0x3f800000, 0x0, 0x3f800000, 0xffffff00, 0x0, 0x0, 0x0, 0x0, 0x0, 0x7f808000, 0x3f800000, 0x3f800000, 0x0, 0x3f800000, 0x0, 0x7f808000, 0x3f800000, 0x3f800000, 0x3f800000, 0x3f800000, 0x3f800000, 0x7f808000, 0x3f800000, 0x0, 0x3f800000, 0x0, 0x3f800000, 0x7f808000, 0x3f800000, 0x0, 0x0, 0x0, 0x0, 0xffffffff, 0x3f800000, 0x3f800000, 0x0, 0x3f800000, 0x0, 0xffffffff, 0x3f800000, 0x3f800000, 0x3f800000, 0x3f800000, 0x3f800000, 0xffffffff, 0x3f800000, 0x0, 0x3f800000, 0x0, 0x3f800000, 0xffffffff, 0x3f800000, 0x0, 0x0, 0x0, 0x0, 0xffffff00, 0x0, 0x3f800000, 0x0, 0x3f800000, 0x0, 0xffffff00, 0x0, 0x3f800000, 0x3f800000, 0x3f800000, 0x3f800000, 0xffffff00, 0x0, 0x3f000000, 0x3f800000, 0x3f000000, 0x3f800000, 0xffffff00, 0x0, 0x3f800000, 0x3f800000, 0x3f800000, 0x3f800000, 0xffffff00, 0x0, 0x0, 0x0, 0x0, 0x0, 0xff00ffff, 0x0, 0x3f800000, 0x0, 0x3f800000, 0x0, 0xff00ffff, 0x0, 0x3f800000, 0x3f800000, 0x3f800000, 0x3f800000, 0xff00ffff, 0x0, 0x0, 0x3f800000, 0x0, 0x3f800000, 0xff00ffff, 0x0, 0x0, 0x0, 0x0, 0x0, 0x7f808080, 0x3f800000, 0x3f800000, 0x0, 0x3f800000, 0x0, 0x7f808080, 0x3f800000, 0x3f800000, 0x3f800000, 0x3f800000, 0x3f800000, 0x7f808080, 0x3f800000, 0x0, 0x3f800000, 0x0, 0x3f800000, 0x7f808080, 0x3f800000, ]; const ind = [ 0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, 8, 9, 10, 8, 10, 11, 12, 13, 14, 12, 14, 15, 16, 17, 18, 16, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 25, 27, 28, 29, 30, 31, 29, 31, 32, ]; const resultAttr: number[] = []; const resultInd: number[] = []; batchRenderer['_attributeBuffer'].uint32View.slice(0, 198).forEach((x) => { resultAttr.push(x); }); batchRenderer['_indexBuffer'].slice(0, 47).forEach((x) => { resultInd.push(x); }); expect(resultAttr).toEqual(attr); expect(resultInd).toEqual(ind); } finally { batchRenderer.destroy(); renderer.destroy(); } }); it('should ask StateSystem to call gl.disable(gl.BLEND) if sprite has BLEND_MODES.NONE', () => { const renderer = new Renderer({ width: 1, height: 1 }); const batchRenderer = new BatchRenderer(renderer); const { gl } = renderer; const elements = [ { uvs, vertexData, indices, _tintRGB: tint1, worldAlpha: 1.0, _texture: new Texture(tex1), blendMode: BLEND_MODES.NONE }, { uvs, vertexData, indices, _tintRGB: tint1, worldAlpha: 0.5, _texture: new Texture(tex1), blendMode: BLEND_MODES.NORMAL }, ] as unknown as IBatchableElement[]; try { batchRenderer.size = 300; batchRenderer.contextChange(); batchRenderer.MAX_TEXTURES = 2; batchRenderer.start(); const glEnable = jest.spyOn(gl, 'enable'); const glDisable = jest.spyOn(gl, 'disable'); elements.forEach((element) => batchRenderer.render(element)); batchRenderer.flush(); expect(glDisable).toBeCalledTimes(1); expect(glDisable).toBeCalledWith(gl.BLEND); expect(glEnable).toBeCalledTimes(1); expect(glEnable).toBeCalledWith(gl.BLEND); } finally { batchRenderer.destroy(); renderer.destroy(); } }); });
packages/core/test/BatchRenderer.tests.ts
0
https://github.com/pixijs/pixijs/commit/b92879837d8b9461fb324606335c0f814ec55465
[ 0.0001789366506272927, 0.0001737686397973448, 0.0001691058714641258, 0.00017406567349098623, 0.000002337744717806345 ]
{ "id": 2, "code_window": [ " ].join('\\n');\n", "\n", " // Check for bundle folder\n", " const external = Object.keys(dependencies || [])\n", " .concat(Object.keys(peerDependencies || []));\n", " const basePath = path.relative(__dirname, pkg.dir);\n", " const input = path.join(basePath, 'src/index.ts');\n", " const freeze = false;\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " .concat(Object.keys(peerDependencies || []))\n", " .concat(nodeDependencies || []);\n" ], "file_path": "rollup.config.js", "type": "replace", "edit_start_line_idx": 139 }
{"frames": { "goldmine_10_5.png": { "frame": {"x":0,"y":0,"w":190,"h":229}, "rotated": false, "trimmed": false, "spriteSourceSize": {"x":0,"y":0,"w":190,"h":229}, "sourceSize": {"w":190,"h":229} }}, "animations": { }, "meta": { "app": "https://www.codeandweb.com/texturepacker", "version": "1.0", "image": "multi-pack-1.png", "format": "RGBA8888", "size": {"w":190,"h":229}, "scale": "1", "related_multi_packs": [ "multi-pack-0.json" ], "smartupdate": "$TexturePacker:SmartUpdate:5f1e3e3af16b7f3e5f4097ccfd45634f:8acde9d234ecca966a410602c71bffad:e9ee6f100f514069f43ab3a680b02726$" } }
packages/assets/test/assets/spritesheet/multi-pack-1.json
0
https://github.com/pixijs/pixijs/commit/b92879837d8b9461fb324606335c0f814ec55465
[ 0.00017471000319346786, 0.00017240317538380623, 0.000170159648405388, 0.0001723398600006476, 0.0000018582139773570816 ]
{ "id": 1, "code_window": [ " function getDeclarationName(node: Declaration): string {\n", " if (node.name) {\n", " if (node.kind === SyntaxKind.ModuleDeclaration && node.name.kind === SyntaxKind.StringLiteral) {\n", " return '\"' + (<LiteralExpression>node.name).text + '\"';\n", " }\n", " Debug.assert(!hasDynamicName(node));\n", " return (<Identifier | LiteralExpression>node.name).text;\n", " }\n", " switch (node.kind) {\n", " case SyntaxKind.ConstructorType:\n", " case SyntaxKind.Constructor:\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (node.name.kind === SyntaxKind.ComputedPropertyName) {\n", " var nameExpression = (<ComputedPropertyName>node.name).expression;\n", " Debug.assert(isWellKnownSymbolSyntactically(nameExpression));\n", " return \"__@\" + (<PropertyAccessExpression>nameExpression).name.text;\n", " }\n" ], "file_path": "src/compiler/binder.ts", "type": "replace", "edit_start_line_idx": 95 }
=== tests/cases/conformance/parser/ecmascript6/Symbols/parserSymbolProperty8.ts === var x: { >x : {} [Symbol.toPrimitive](): string >Symbol.toPrimitive : Symbol >Symbol : SymbolConstructor >toPrimitive : Symbol }
tests/baselines/reference/parserSymbolProperty8.types
1
https://github.com/microsoft/TypeScript/commit/f344654460c0772eb781754a0c5b460cf740e114
[ 0.0001644267322262749, 0.0001644267322262749, 0.0001644267322262749, 0.0001644267322262749, 0 ]
{ "id": 1, "code_window": [ " function getDeclarationName(node: Declaration): string {\n", " if (node.name) {\n", " if (node.kind === SyntaxKind.ModuleDeclaration && node.name.kind === SyntaxKind.StringLiteral) {\n", " return '\"' + (<LiteralExpression>node.name).text + '\"';\n", " }\n", " Debug.assert(!hasDynamicName(node));\n", " return (<Identifier | LiteralExpression>node.name).text;\n", " }\n", " switch (node.kind) {\n", " case SyntaxKind.ConstructorType:\n", " case SyntaxKind.Constructor:\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (node.name.kind === SyntaxKind.ComputedPropertyName) {\n", " var nameExpression = (<ComputedPropertyName>node.name).expression;\n", " Debug.assert(isWellKnownSymbolSyntactically(nameExpression));\n", " return \"__@\" + (<PropertyAccessExpression>nameExpression).name.text;\n", " }\n" ], "file_path": "src/compiler/binder.ts", "type": "replace", "edit_start_line_idx": 95 }
var a,
tests/cases/conformance/parser/ecmascript5/VariableDeclarations/parserVariableDeclaration5.ts
0
https://github.com/microsoft/TypeScript/commit/f344654460c0772eb781754a0c5b460cf740e114
[ 0.00016245190636254847, 0.00016245190636254847, 0.00016245190636254847, 0.00016245190636254847, 0 ]
{ "id": 1, "code_window": [ " function getDeclarationName(node: Declaration): string {\n", " if (node.name) {\n", " if (node.kind === SyntaxKind.ModuleDeclaration && node.name.kind === SyntaxKind.StringLiteral) {\n", " return '\"' + (<LiteralExpression>node.name).text + '\"';\n", " }\n", " Debug.assert(!hasDynamicName(node));\n", " return (<Identifier | LiteralExpression>node.name).text;\n", " }\n", " switch (node.kind) {\n", " case SyntaxKind.ConstructorType:\n", " case SyntaxKind.Constructor:\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (node.name.kind === SyntaxKind.ComputedPropertyName) {\n", " var nameExpression = (<ComputedPropertyName>node.name).expression;\n", " Debug.assert(isWellKnownSymbolSyntactically(nameExpression));\n", " return \"__@\" + (<PropertyAccessExpression>nameExpression).name.text;\n", " }\n" ], "file_path": "src/compiler/binder.ts", "type": "replace", "edit_start_line_idx": 95 }
///<reference path='syntaxKind.ts' /> module TypeScript.SyntaxFacts { var textToKeywordKind: any = { "any": SyntaxKind.AnyKeyword, "async": SyntaxKind.AsyncKeyword, "await": SyntaxKind.AwaitKeyword, "boolean": SyntaxKind.BooleanKeyword, "break": SyntaxKind.BreakKeyword, "case": SyntaxKind.CaseKeyword, "catch": SyntaxKind.CatchKeyword, "class": SyntaxKind.ClassKeyword, "continue": SyntaxKind.ContinueKeyword, "const": SyntaxKind.ConstKeyword, "constructor": SyntaxKind.ConstructorKeyword, "debugger": SyntaxKind.DebuggerKeyword, "declare": SyntaxKind.DeclareKeyword, "default": SyntaxKind.DefaultKeyword, "delete": SyntaxKind.DeleteKeyword, "do": SyntaxKind.DoKeyword, "else": SyntaxKind.ElseKeyword, "enum": SyntaxKind.EnumKeyword, "export": SyntaxKind.ExportKeyword, "extends": SyntaxKind.ExtendsKeyword, "false": SyntaxKind.FalseKeyword, "finally": SyntaxKind.FinallyKeyword, "for": SyntaxKind.ForKeyword, "function": SyntaxKind.FunctionKeyword, "get": SyntaxKind.GetKeyword, "if": SyntaxKind.IfKeyword, "implements": SyntaxKind.ImplementsKeyword, "import": SyntaxKind.ImportKeyword, "in": SyntaxKind.InKeyword, "instanceof": SyntaxKind.InstanceOfKeyword, "interface": SyntaxKind.InterfaceKeyword, "let": SyntaxKind.LetKeyword, "module": SyntaxKind.ModuleKeyword, "new": SyntaxKind.NewKeyword, "null": SyntaxKind.NullKeyword, "number":SyntaxKind.NumberKeyword, "package": SyntaxKind.PackageKeyword, "private": SyntaxKind.PrivateKeyword, "protected": SyntaxKind.ProtectedKeyword, "public": SyntaxKind.PublicKeyword, "require": SyntaxKind.RequireKeyword, "return": SyntaxKind.ReturnKeyword, "set": SyntaxKind.SetKeyword, "static": SyntaxKind.StaticKeyword, "string": SyntaxKind.StringKeyword, "super": SyntaxKind.SuperKeyword, "switch": SyntaxKind.SwitchKeyword, "this": SyntaxKind.ThisKeyword, "throw": SyntaxKind.ThrowKeyword, "true": SyntaxKind.TrueKeyword, "try": SyntaxKind.TryKeyword, "type": SyntaxKind.TypeKeyword, "typeof": SyntaxKind.TypeOfKeyword, "var": SyntaxKind.VarKeyword, "void": SyntaxKind.VoidKeyword, "while": SyntaxKind.WhileKeyword, "with": SyntaxKind.WithKeyword, "yield": SyntaxKind.YieldKeyword, "{": SyntaxKind.OpenBraceToken, "}": SyntaxKind.CloseBraceToken, "(": SyntaxKind.OpenParenToken, ")": SyntaxKind.CloseParenToken, "[": SyntaxKind.OpenBracketToken, "]": SyntaxKind.CloseBracketToken, ".": SyntaxKind.DotToken, "...": SyntaxKind.DotDotDotToken, ";": SyntaxKind.SemicolonToken, ",": SyntaxKind.CommaToken, "<": SyntaxKind.LessThanToken, ">": SyntaxKind.GreaterThanToken, "<=": SyntaxKind.LessThanEqualsToken, ">=": SyntaxKind.GreaterThanEqualsToken, "==": SyntaxKind.EqualsEqualsToken, "=>": SyntaxKind.EqualsGreaterThanToken, "!=": SyntaxKind.ExclamationEqualsToken, "===": SyntaxKind.EqualsEqualsEqualsToken, "!==": SyntaxKind.ExclamationEqualsEqualsToken, "+": SyntaxKind.PlusToken, "-": SyntaxKind.MinusToken, "*": SyntaxKind.AsteriskToken, "%": SyntaxKind.PercentToken, "++": SyntaxKind.PlusPlusToken, "--": SyntaxKind.MinusMinusToken, "<<": SyntaxKind.LessThanLessThanToken, ">>": SyntaxKind.GreaterThanGreaterThanToken, ">>>": SyntaxKind.GreaterThanGreaterThanGreaterThanToken, "&": SyntaxKind.AmpersandToken, "|": SyntaxKind.BarToken, "^": SyntaxKind.CaretToken, "!": SyntaxKind.ExclamationToken, "~": SyntaxKind.TildeToken, "&&": SyntaxKind.AmpersandAmpersandToken, "||": SyntaxKind.BarBarToken, "?": SyntaxKind.QuestionToken, ":": SyntaxKind.ColonToken, "=": SyntaxKind.EqualsToken, "+=": SyntaxKind.PlusEqualsToken, "-=": SyntaxKind.MinusEqualsToken, "*=": SyntaxKind.AsteriskEqualsToken, "%=": SyntaxKind.PercentEqualsToken, "<<=": SyntaxKind.LessThanLessThanEqualsToken, ">>=": SyntaxKind.GreaterThanGreaterThanEqualsToken, ">>>=": SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken, "&=": SyntaxKind.AmpersandEqualsToken, "|=": SyntaxKind.BarEqualsToken, "^=": SyntaxKind.CaretEqualsToken, "/": SyntaxKind.SlashToken, "/=": SyntaxKind.SlashEqualsToken, }; var kindToText = new Array<string>(); for (var name in textToKeywordKind) { if (textToKeywordKind.hasOwnProperty(name)) { // Debug.assert(kindToText[textToKeywordKind[name]] === undefined); kindToText[textToKeywordKind[name]] = name; } } // Manually work around a bug in the CScript 5.8 runtime where 'constructor' is not // listed when SyntaxFacts.textToKeywordKind is enumerated because it is the name of // the constructor function. kindToText[SyntaxKind.ConstructorKeyword] = "constructor"; export function getTokenKind(text: string): SyntaxKind { if (textToKeywordKind.hasOwnProperty(text)) { return textToKeywordKind[text]; } return SyntaxKind.None; } export function getText(kind: SyntaxKind): string { var result = kindToText[kind]; return result;// !== undefined ? result : undefined; } export function isAnyKeyword(kind: SyntaxKind): boolean { return kind >= SyntaxKind.FirstKeyword && kind <= SyntaxKind.LastKeyword; } export function isAnyPunctuation(kind: SyntaxKind): boolean { return kind >= SyntaxKind.FirstPunctuation && kind <= SyntaxKind.LastPunctuation; } export function isPrefixUnaryExpressionOperatorToken(tokenKind: SyntaxKind): boolean { switch (tokenKind) { case SyntaxKind.PlusToken: case SyntaxKind.MinusToken: case SyntaxKind.TildeToken: case SyntaxKind.ExclamationToken: case SyntaxKind.PlusPlusToken: case SyntaxKind.MinusMinusToken: return true; default: return false; } } export function isBinaryExpressionOperatorToken(tokenKind: SyntaxKind): boolean { switch (tokenKind) { case SyntaxKind.AsteriskToken: case SyntaxKind.SlashToken: case SyntaxKind.PercentToken: case SyntaxKind.PlusToken: case SyntaxKind.MinusToken: case SyntaxKind.LessThanLessThanToken: case SyntaxKind.GreaterThanGreaterThanToken: case SyntaxKind.GreaterThanGreaterThanGreaterThanToken: case SyntaxKind.LessThanToken: case SyntaxKind.GreaterThanToken: case SyntaxKind.LessThanEqualsToken: case SyntaxKind.GreaterThanEqualsToken: case SyntaxKind.InstanceOfKeyword: case SyntaxKind.InKeyword: case SyntaxKind.EqualsEqualsToken: case SyntaxKind.ExclamationEqualsToken: case SyntaxKind.EqualsEqualsEqualsToken: case SyntaxKind.ExclamationEqualsEqualsToken: case SyntaxKind.AmpersandToken: case SyntaxKind.CaretToken: case SyntaxKind.BarToken: case SyntaxKind.AmpersandAmpersandToken: case SyntaxKind.BarBarToken: case SyntaxKind.BarEqualsToken: case SyntaxKind.AmpersandEqualsToken: case SyntaxKind.CaretEqualsToken: case SyntaxKind.LessThanLessThanEqualsToken: case SyntaxKind.GreaterThanGreaterThanEqualsToken: case SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken: case SyntaxKind.PlusEqualsToken: case SyntaxKind.MinusEqualsToken: case SyntaxKind.AsteriskEqualsToken: case SyntaxKind.SlashEqualsToken: case SyntaxKind.PercentEqualsToken: case SyntaxKind.EqualsToken: case SyntaxKind.CommaToken: return true; default: return false; } } export function isAssignmentOperatorToken(tokenKind: SyntaxKind): boolean { switch (tokenKind) { case SyntaxKind.BarEqualsToken: case SyntaxKind.AmpersandEqualsToken: case SyntaxKind.CaretEqualsToken: case SyntaxKind.LessThanLessThanEqualsToken: case SyntaxKind.GreaterThanGreaterThanEqualsToken: case SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken: case SyntaxKind.PlusEqualsToken: case SyntaxKind.MinusEqualsToken: case SyntaxKind.AsteriskEqualsToken: case SyntaxKind.SlashEqualsToken: case SyntaxKind.PercentEqualsToken: case SyntaxKind.EqualsToken: return true; default: return false; } } export function isType(kind: SyntaxKind): boolean { switch (kind) { case SyntaxKind.ArrayType: case SyntaxKind.AnyKeyword: case SyntaxKind.NumberKeyword: case SyntaxKind.BooleanKeyword: case SyntaxKind.StringKeyword: case SyntaxKind.VoidKeyword: case SyntaxKind.FunctionType: case SyntaxKind.ObjectType: case SyntaxKind.ConstructorType: case SyntaxKind.TypeQuery: case SyntaxKind.GenericType: case SyntaxKind.QualifiedName: case SyntaxKind.IdentifierName: return true; } return false; } }
src/services/syntax/syntaxFacts.ts
0
https://github.com/microsoft/TypeScript/commit/f344654460c0772eb781754a0c5b460cf740e114
[ 0.01065078191459179, 0.000783925352152437, 0.0001641674607526511, 0.00023450027219951153, 0.002011651871725917 ]
{ "id": 1, "code_window": [ " function getDeclarationName(node: Declaration): string {\n", " if (node.name) {\n", " if (node.kind === SyntaxKind.ModuleDeclaration && node.name.kind === SyntaxKind.StringLiteral) {\n", " return '\"' + (<LiteralExpression>node.name).text + '\"';\n", " }\n", " Debug.assert(!hasDynamicName(node));\n", " return (<Identifier | LiteralExpression>node.name).text;\n", " }\n", " switch (node.kind) {\n", " case SyntaxKind.ConstructorType:\n", " case SyntaxKind.Constructor:\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (node.name.kind === SyntaxKind.ComputedPropertyName) {\n", " var nameExpression = (<ComputedPropertyName>node.name).expression;\n", " Debug.assert(isWellKnownSymbolSyntactically(nameExpression));\n", " return \"__@\" + (<PropertyAccessExpression>nameExpression).name.text;\n", " }\n" ], "file_path": "src/compiler/binder.ts", "type": "replace", "edit_start_line_idx": 95 }
=================================================================== JsFile: out-flag.js mapUrl: out-flag.js.map sourceRoot: sources: out-flag.ts =================================================================== ------------------------------------------------------------------- emittedFile:tests/cases/compiler/out-flag.js sourceFile:out-flag.ts ------------------------------------------------------------------- >>>//// @out: bin\ 1 > 2 >^^^^^^^^^^^^^^^ 3 > ^^^^^^-> 1 > 2 >//// @out: bin\ 1 >Emitted(1, 1) Source(1, 1) + SourceIndex(0) 2 >Emitted(1, 16) Source(1, 16) + SourceIndex(0) --- >>>// my class comments 1-> 2 > 3 >^^^^^^^^^^^^^^^^^^^^ 4 > ^^^^^^^^^-> 1-> > >// my class comments > 2 > 3 >// my class comments 1->Emitted(2, 1) Source(4, 1) + SourceIndex(0) 2 >Emitted(2, 1) Source(3, 1) + SourceIndex(0) 3 >Emitted(2, 21) Source(3, 21) + SourceIndex(0) --- >>>var MyClass = (function () { 1->^^^^ 2 > ^^^^^^^ 3 > ^^^^^^^^^^^^^^-> 1-> >class 2 > MyClass 1->Emitted(3, 5) Source(4, 7) + SourceIndex(0) 2 >Emitted(3, 12) Source(4, 14) + SourceIndex(0) --- >>> function MyClass() { 1->^^^^ 2 > ^^^^^^^^^ 3 > ^^^^^^^ 1-> 2 > class 3 > MyClass 1->Emitted(4, 5) Source(4, 1) + SourceIndex(0) name (MyClass) 2 >Emitted(4, 14) Source(4, 7) + SourceIndex(0) name (MyClass) 3 >Emitted(4, 21) Source(4, 14) + SourceIndex(0) name (MyClass) --- >>> } 1 >^^^^ 2 > ^ 3 > ^^^^^^^^^^^^^^^^^^^^^^^-> 1 > >{ > // my function comments > public Count(): number > { > return 42; > } > > public SetCount(value: number) > { > // > } > 2 > } 1 >Emitted(5, 5) Source(16, 1) + SourceIndex(0) name (MyClass.constructor) 2 >Emitted(5, 6) Source(16, 2) + SourceIndex(0) name (MyClass.constructor) --- >>> // my function comments 1->^^^^ 2 > ^^^^^^^^^^^^^^^^^^^^^^^ 3 > ^^^^^^^^^^^^^^^^^-> 1-> 2 > // my function comments 1->Emitted(6, 5) Source(6, 5) + SourceIndex(0) name (MyClass) 2 >Emitted(6, 28) Source(6, 28) + SourceIndex(0) name (MyClass) --- >>> MyClass.prototype.Count = function () { 1->^^^^ 2 > ^^^^^^^^^^^^^^^^^^^^^^^ 3 > ^^^ 1-> > public 2 > Count 3 > 1->Emitted(7, 5) Source(7, 12) + SourceIndex(0) name (MyClass) 2 >Emitted(7, 28) Source(7, 17) + SourceIndex(0) name (MyClass) 3 >Emitted(7, 31) Source(7, 5) + SourceIndex(0) name (MyClass) --- >>> return 42; 1 >^^^^^^^^ 2 > ^^^^^^ 3 > ^ 4 > ^^ 5 > ^ 1 >public Count(): number > { > 2 > return 3 > 4 > 42 5 > ; 1 >Emitted(8, 9) Source(9, 9) + SourceIndex(0) name (MyClass.Count) 2 >Emitted(8, 15) Source(9, 15) + SourceIndex(0) name (MyClass.Count) 3 >Emitted(8, 16) Source(9, 16) + SourceIndex(0) name (MyClass.Count) 4 >Emitted(8, 18) Source(9, 18) + SourceIndex(0) name (MyClass.Count) 5 >Emitted(8, 19) Source(9, 19) + SourceIndex(0) name (MyClass.Count) --- >>> }; 1 >^^^^ 2 > ^ 3 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> 1 > > 2 > } 1 >Emitted(9, 5) Source(10, 5) + SourceIndex(0) name (MyClass.Count) 2 >Emitted(9, 6) Source(10, 6) + SourceIndex(0) name (MyClass.Count) --- >>> MyClass.prototype.SetCount = function (value) { 1->^^^^ 2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^ 3 > ^^^ 4 > ^^^^^^^^^^ 5 > ^^^^^ 1-> > > public 2 > SetCount 3 > 4 > public SetCount( 5 > value: number 1->Emitted(10, 5) Source(12, 12) + SourceIndex(0) name (MyClass) 2 >Emitted(10, 31) Source(12, 20) + SourceIndex(0) name (MyClass) 3 >Emitted(10, 34) Source(12, 5) + SourceIndex(0) name (MyClass) 4 >Emitted(10, 44) Source(12, 21) + SourceIndex(0) name (MyClass) 5 >Emitted(10, 49) Source(12, 34) + SourceIndex(0) name (MyClass) --- >>> // 1 >^^^^^^^^ 2 > ^^ 1 >) > { > 2 > // 1 >Emitted(11, 9) Source(14, 9) + SourceIndex(0) name (MyClass.SetCount) 2 >Emitted(11, 11) Source(14, 11) + SourceIndex(0) name (MyClass.SetCount) --- >>> }; 1 >^^^^ 2 > ^ 3 > ^^^^^^^^^^^^^^^-> 1 > > 2 > } 1 >Emitted(12, 5) Source(15, 5) + SourceIndex(0) name (MyClass.SetCount) 2 >Emitted(12, 6) Source(15, 6) + SourceIndex(0) name (MyClass.SetCount) --- >>> return MyClass; 1->^^^^ 2 > ^^^^^^^^^^^^^^ 1-> > 2 > } 1->Emitted(13, 5) Source(16, 1) + SourceIndex(0) name (MyClass) 2 >Emitted(13, 19) Source(16, 2) + SourceIndex(0) name (MyClass) --- >>>})(); 1 > 2 >^ 3 > 4 > ^^^^ 5 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> 1 > 2 >} 3 > 4 > class MyClass > { > // my function comments > public Count(): number > { > return 42; > } > > public SetCount(value: number) > { > // > } > } 1 >Emitted(14, 1) Source(16, 1) + SourceIndex(0) name (MyClass) 2 >Emitted(14, 2) Source(16, 2) + SourceIndex(0) name (MyClass) 3 >Emitted(14, 2) Source(4, 1) + SourceIndex(0) 4 >Emitted(14, 6) Source(16, 2) + SourceIndex(0) --- >>>//# sourceMappingURL=out-flag.js.map
tests/baselines/reference/out-flag.sourcemap.txt
0
https://github.com/microsoft/TypeScript/commit/f344654460c0772eb781754a0c5b460cf740e114
[ 0.00017616216791793704, 0.000173294436535798, 0.00016824911290314049, 0.00017370206478517503, 0.0000018100315628544195 ]
{ "id": 5, "code_window": [ "=== tests/cases/conformance/parser/ecmascript6/Symbols/parserSymbolProperty8.ts ===\n", "var x: {\n", ">x : {}\n", "\n", " [Symbol.toPrimitive](): string\n", ">Symbol.toPrimitive : Symbol\n", ">Symbol : SymbolConstructor\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ ">x : { [Symbol.toPrimitive](): string; }\n" ], "file_path": "tests/baselines/reference/parserSymbolProperty8.types", "type": "replace", "edit_start_line_idx": 2 }
/// <reference path="types.ts" /> module ts { export interface ReferencePathMatchResult { fileReference?: FileReference diagnosticMessage?: DiagnosticMessage isNoDefaultLib?: boolean } export function getDeclarationOfKind(symbol: Symbol, kind: SyntaxKind): Declaration { var declarations = symbol.declarations; for (var i = 0; i < declarations.length; i++) { var declaration = declarations[i]; if (declaration.kind === kind) { return declaration; } } return undefined; } export interface StringSymbolWriter extends SymbolWriter { string(): string; } export interface EmitHost extends ScriptReferenceHost { getSourceFiles(): SourceFile[]; getCommonSourceDirectory(): string; getCanonicalFileName(fileName: string): string; getNewLine(): string; writeFile: WriteFileCallback; } // Pool writers to avoid needing to allocate them for every symbol we write. var stringWriters: StringSymbolWriter[] = []; export function getSingleLineStringWriter(): StringSymbolWriter { if (stringWriters.length == 0) { var str = ""; var writeText: (text: string) => void = text => str += text; return { string: () => str, writeKeyword: writeText, writeOperator: writeText, writePunctuation: writeText, writeSpace: writeText, writeStringLiteral: writeText, writeParameter: writeText, writeSymbol: writeText, // Completely ignore indentation for string writers. And map newlines to // a single space. writeLine: () => str += " ", increaseIndent: () => { }, decreaseIndent: () => { }, clear: () => str = "", trackSymbol: () => { } }; } return stringWriters.pop(); } export function releaseStringWriter(writer: StringSymbolWriter) { writer.clear() stringWriters.push(writer); } export function getFullWidth(node: Node) { return node.end - node.pos; } // Returns true if this node contains a parse error anywhere underneath it. export function containsParseError(node: Node): boolean { aggregateChildData(node); return (node.parserContextFlags & ParserContextFlags.ThisNodeOrAnySubNodesHasError) !== 0 } function aggregateChildData(node: Node): void { if (!(node.parserContextFlags & ParserContextFlags.HasAggregatedChildData)) { // A node is considered to contain a parse error if: // a) the parser explicitly marked that it had an error // b) any of it's children reported that it had an error. var thisNodeOrAnySubNodesHasError = ((node.parserContextFlags & ParserContextFlags.ThisNodeHasError) !== 0) || forEachChild(node, containsParseError); // If so, mark ourselves accordingly. if (thisNodeOrAnySubNodesHasError) { node.parserContextFlags |= ParserContextFlags.ThisNodeOrAnySubNodesHasError; } // Also mark that we've propogated the child information to this node. This way we can // always consult the bit directly on this node without needing to check its children // again. node.parserContextFlags |= ParserContextFlags.HasAggregatedChildData; } } export function getSourceFileOfNode(node: Node): SourceFile { while (node && node.kind !== SyntaxKind.SourceFile) { node = node.parent; } return <SourceFile>node; } // This is a useful function for debugging purposes. export function nodePosToString(node: Node): string { var file = getSourceFileOfNode(node); var loc = getLineAndCharacterOfPosition(file, node.pos); return file.fileName + "(" + loc.line + "," + loc.character + ")"; } export function getStartPosOfNode(node: Node): number { return node.pos; } // Returns true if this node is missing from the actual source code. 'missing' is different // from 'undefined/defined'. When a node is undefined (which can happen for optional nodes // in the tree), it is definitel missing. HOwever, a node may be defined, but still be // missing. This happens whenever the parser knows it needs to parse something, but can't // get anything in the source code that it expects at that location. For example: // // var a: ; // // Here, the Type in the Type-Annotation is not-optional (as there is a colon in the source // code). So the parser will attempt to parse out a type, and will create an actual node. // However, this node will be 'missing' in the sense that no actual source-code/tokens are // contained within it. export function nodeIsMissing(node: Node) { if (!node) { return true; } return node.pos === node.end && node.kind !== SyntaxKind.EndOfFileToken; } export function nodeIsPresent(node: Node) { return !nodeIsMissing(node); } export function getTokenPosOfNode(node: Node, sourceFile?: SourceFile): number { // With nodes that have no width (i.e. 'Missing' nodes), we actually *don't* // want to skip trivia because this will launch us forward to the next token. if (nodeIsMissing(node)) { return node.pos; } return skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); } export function getSourceTextOfNodeFromSourceFile(sourceFile: SourceFile, node: Node): string { if (nodeIsMissing(node)) { return ""; } var text = sourceFile.text; return text.substring(skipTrivia(text, node.pos), node.end); } export function getTextOfNodeFromSourceText(sourceText: string, node: Node): string { if (nodeIsMissing(node)) { return ""; } return sourceText.substring(skipTrivia(sourceText, node.pos), node.end); } export function getTextOfNode(node: Node): string { return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node); } // Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' export function escapeIdentifier(identifier: string): string { return identifier.length >= 2 && identifier.charCodeAt(0) === CharacterCodes._ && identifier.charCodeAt(1) === CharacterCodes._ ? "_" + identifier : identifier; } // Remove extra underscore from escaped identifier export function unescapeIdentifier(identifier: string): string { return identifier.length >= 3 && identifier.charCodeAt(0) === CharacterCodes._ && identifier.charCodeAt(1) === CharacterCodes._ && identifier.charCodeAt(2) === CharacterCodes._ ? identifier.substr(1) : identifier; } // Return display name of an identifier // Computed property names will just be emitted as "[<expr>]", where <expr> is the source // text of the expression in the computed property. export function declarationNameToString(name: DeclarationName) { return getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name); } export function createDiagnosticForNode(node: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): Diagnostic { node = getErrorSpanForNode(node); var file = getSourceFileOfNode(node); var start = getTokenPosOfNode(node, file); var length = node.end - start; return createFileDiagnostic(file, start, length, message, arg0, arg1, arg2); } export function createDiagnosticForNodeFromMessageChain(node: Node, messageChain: DiagnosticMessageChain): Diagnostic { node = getErrorSpanForNode(node); var file = getSourceFileOfNode(node); var start = skipTrivia(file.text, node.pos); var length = node.end - start; return { file, start, length, code: messageChain.code, category: messageChain.category, messageText: messageChain.next ? messageChain : messageChain.messageText }; } export function getErrorSpanForNode(node: Node): Node { var errorSpan: Node; switch (node.kind) { // This list is a work in progress. Add missing node kinds to improve their error // spans. case SyntaxKind.VariableDeclaration: case SyntaxKind.BindingElement: case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.ModuleDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.EnumMember: errorSpan = (<Declaration>node).name; break; } // We now have the ideal error span, but it may be a node that is optional and absent // (e.g. the name of a function expression), in which case errorSpan will be undefined. // Alternatively, it might be required and missing (e.g. the name of a module), in which // case its pos will equal its end (length 0). In either of these cases, we should fall // back to the original node that the error was issued on. return errorSpan && errorSpan.pos < errorSpan.end ? errorSpan : node; } export function isExternalModule(file: SourceFile): boolean { return file.externalModuleIndicator !== undefined; } export function isDeclarationFile(file: SourceFile): boolean { return (file.flags & NodeFlags.DeclarationFile) !== 0; } export function isConstEnumDeclaration(node: Node): boolean { return node.kind === SyntaxKind.EnumDeclaration && isConst(node); } function walkUpBindingElementsAndPatterns(node: Node): Node { while (node && (node.kind === SyntaxKind.BindingElement || isBindingPattern(node))) { node = node.parent; } return node; } // Returns the node flags for this node and all relevant parent nodes. This is done so that // nodes like variable declarations and binding elements can returned a view of their flags // that includes the modifiers from their container. i.e. flags like export/declare aren't // stored on the variable declaration directly, but on the containing variable statement // (if it has one). Similarly, flags for let/const are store on the variable declaration // list. By calling this function, all those flags are combined so that the client can treat // the node as if it actually had those flags. export function getCombinedNodeFlags(node: Node): NodeFlags { node = walkUpBindingElementsAndPatterns(node); var flags = node.flags; if (node.kind === SyntaxKind.VariableDeclaration) { node = node.parent; } if (node && node.kind === SyntaxKind.VariableDeclarationList) { flags |= node.flags; node = node.parent; } if (node && node.kind === SyntaxKind.VariableStatement) { flags |= node.flags; } return flags; } export function isConst(node: Node): boolean { return !!(getCombinedNodeFlags(node) & NodeFlags.Const); } export function isLet(node: Node): boolean { return !!(getCombinedNodeFlags(node) & NodeFlags.Let); } export function isPrologueDirective(node: Node): boolean { return node.kind === SyntaxKind.ExpressionStatement && (<ExpressionStatement>node).expression.kind === SyntaxKind.StringLiteral; } export function getLeadingCommentRangesOfNode(node: Node, sourceFileOfNode?: SourceFile) { sourceFileOfNode = sourceFileOfNode || getSourceFileOfNode(node); // If parameter/type parameter, the prev token trailing comments are part of this node too if (node.kind === SyntaxKind.Parameter || node.kind === SyntaxKind.TypeParameter) { // e.g. (/** blah */ a, /** blah */ b); return concatenate(getTrailingCommentRanges(sourceFileOfNode.text, node.pos), // e.g.: ( // /** blah */ a, // /** blah */ b); getLeadingCommentRanges(sourceFileOfNode.text, node.pos)); } else { return getLeadingCommentRanges(sourceFileOfNode.text, node.pos); } } export function getJsDocComments(node: Node, sourceFileOfNode: SourceFile) { return filter(getLeadingCommentRangesOfNode(node, sourceFileOfNode), isJsDocComment); function isJsDocComment(comment: CommentRange) { // True if the comment starts with '/**' but not if it is '/**/' return sourceFileOfNode.text.charCodeAt(comment.pos + 1) === CharacterCodes.asterisk && sourceFileOfNode.text.charCodeAt(comment.pos + 2) === CharacterCodes.asterisk && sourceFileOfNode.text.charCodeAt(comment.pos + 3) !== CharacterCodes.slash; } } export var fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*<reference\s+path\s*=\s*)('|")(.+?)\2.*?\/>/ // Warning: This has the same semantics as the forEach family of functions, // in that traversal terminates in the event that 'visitor' supplies a truthy value. export function forEachReturnStatement<T>(body: Block, visitor: (stmt: ReturnStatement) => T): T { return traverse(body); function traverse(node: Node): T { switch (node.kind) { case SyntaxKind.ReturnStatement: return visitor(<ReturnStatement>node); case SyntaxKind.Block: case SyntaxKind.IfStatement: case SyntaxKind.DoStatement: case SyntaxKind.WhileStatement: case SyntaxKind.ForStatement: case SyntaxKind.ForInStatement: case SyntaxKind.WithStatement: case SyntaxKind.SwitchStatement: case SyntaxKind.CaseClause: case SyntaxKind.DefaultClause: case SyntaxKind.LabeledStatement: case SyntaxKind.TryStatement: case SyntaxKind.CatchClause: return forEachChild(node, traverse); } } } export function isAnyFunction(node: Node): boolean { if (node) { switch (node.kind) { case SyntaxKind.Constructor: case SyntaxKind.FunctionExpression: case SyntaxKind.FunctionDeclaration: case SyntaxKind.ArrowFunction: case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: case SyntaxKind.CallSignature: case SyntaxKind.ConstructSignature: case SyntaxKind.IndexSignature: case SyntaxKind.FunctionType: case SyntaxKind.ConstructorType: case SyntaxKind.FunctionExpression: case SyntaxKind.ArrowFunction: case SyntaxKind.FunctionDeclaration: return true; } } return false; } export function isFunctionBlock(node: Node) { return node && node.kind === SyntaxKind.Block && isAnyFunction(node.parent); } export function isObjectLiteralMethod(node: Node) { return node && node.kind === SyntaxKind.MethodDeclaration && node.parent.kind === SyntaxKind.ObjectLiteralExpression; } export function getContainingFunction(node: Node): FunctionLikeDeclaration { while (true) { node = node.parent; if (!node || isAnyFunction(node)) { return <FunctionLikeDeclaration>node; } } } export function getThisContainer(node: Node, includeArrowFunctions: boolean): Node { while (true) { node = node.parent; if (!node) { return undefined; } switch (node.kind) { case SyntaxKind.ComputedPropertyName: // If the grandparent node is an object literal (as opposed to a class), // then the computed property is not a 'this' container. // A computed property name in a class needs to be a this container // so that we can error on it. if (node.parent.parent.kind === SyntaxKind.ClassDeclaration) { return node; } // If this is a computed property, then the parent should not // make it a this container. The parent might be a property // in an object literal, like a method or accessor. But in order for // such a parent to be a this container, the reference must be in // the *body* of the container. node = node.parent; break; case SyntaxKind.ArrowFunction: if (!includeArrowFunctions) { continue; } // Fall through case SyntaxKind.FunctionDeclaration: case SyntaxKind.FunctionExpression: case SyntaxKind.ModuleDeclaration: case SyntaxKind.PropertyDeclaration: case SyntaxKind.PropertySignature: case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: case SyntaxKind.Constructor: case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: case SyntaxKind.EnumDeclaration: case SyntaxKind.SourceFile: return node; } } } export function getSuperContainer(node: Node, includeFunctions: boolean): Node { while (true) { node = node.parent; if (!node) return node; switch (node.kind) { case SyntaxKind.ComputedPropertyName: // If the grandparent node is an object literal (as opposed to a class), // then the computed property is not a 'super' container. // A computed property name in a class needs to be a super container // so that we can error on it. if (node.parent.parent.kind === SyntaxKind.ClassDeclaration) { return node; } // If this is a computed property, then the parent should not // make it a super container. The parent might be a property // in an object literal, like a method or accessor. But in order for // such a parent to be a super container, the reference must be in // the *body* of the container. node = node.parent; break; case SyntaxKind.FunctionDeclaration: case SyntaxKind.FunctionExpression: case SyntaxKind.ArrowFunction: if (!includeFunctions) { continue; } case SyntaxKind.PropertyDeclaration: case SyntaxKind.PropertySignature: case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: case SyntaxKind.Constructor: case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: return node; } } } export function getInvokedExpression(node: CallLikeExpression): Expression { if (node.kind === SyntaxKind.TaggedTemplateExpression) { return (<TaggedTemplateExpression>node).tag; } // Will either be a CallExpression or NewExpression. return (<CallExpression>node).expression; } export function isExpression(node: Node): boolean { switch (node.kind) { case SyntaxKind.ThisKeyword: case SyntaxKind.SuperKeyword: case SyntaxKind.NullKeyword: case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: case SyntaxKind.RegularExpressionLiteral: case SyntaxKind.ArrayLiteralExpression: case SyntaxKind.ObjectLiteralExpression: case SyntaxKind.PropertyAccessExpression: case SyntaxKind.ElementAccessExpression: case SyntaxKind.CallExpression: case SyntaxKind.NewExpression: case SyntaxKind.TaggedTemplateExpression: case SyntaxKind.TypeAssertionExpression: case SyntaxKind.ParenthesizedExpression: case SyntaxKind.FunctionExpression: case SyntaxKind.ArrowFunction: case SyntaxKind.VoidExpression: case SyntaxKind.DeleteExpression: case SyntaxKind.TypeOfExpression: case SyntaxKind.PrefixUnaryExpression: case SyntaxKind.PostfixUnaryExpression: case SyntaxKind.BinaryExpression: case SyntaxKind.ConditionalExpression: case SyntaxKind.SpreadElementExpression: case SyntaxKind.TemplateExpression: case SyntaxKind.NoSubstitutionTemplateLiteral: case SyntaxKind.OmittedExpression: return true; case SyntaxKind.QualifiedName: while (node.parent.kind === SyntaxKind.QualifiedName) { node = node.parent; } return node.parent.kind === SyntaxKind.TypeQuery; case SyntaxKind.Identifier: if (node.parent.kind === SyntaxKind.TypeQuery) { return true; } // fall through case SyntaxKind.NumericLiteral: case SyntaxKind.StringLiteral: var parent = node.parent; switch (parent.kind) { case SyntaxKind.VariableDeclaration: case SyntaxKind.Parameter: case SyntaxKind.PropertyDeclaration: case SyntaxKind.PropertySignature: case SyntaxKind.EnumMember: case SyntaxKind.PropertyAssignment: case SyntaxKind.BindingElement: return (<VariableLikeDeclaration>parent).initializer === node; case SyntaxKind.ExpressionStatement: case SyntaxKind.IfStatement: case SyntaxKind.DoStatement: case SyntaxKind.WhileStatement: case SyntaxKind.ReturnStatement: case SyntaxKind.WithStatement: case SyntaxKind.SwitchStatement: case SyntaxKind.CaseClause: case SyntaxKind.ThrowStatement: case SyntaxKind.SwitchStatement: return (<ExpressionStatement>parent).expression === node; case SyntaxKind.ForStatement: var forStatement = <ForStatement>parent; return (forStatement.initializer === node && forStatement.initializer.kind !== SyntaxKind.VariableDeclarationList) || forStatement.condition === node || forStatement.iterator === node; case SyntaxKind.ForInStatement: var forInStatement = <ForInStatement>parent; return (forInStatement.initializer === node && forInStatement.initializer.kind !== SyntaxKind.VariableDeclarationList) || forInStatement.expression === node; case SyntaxKind.TypeAssertionExpression: return node === (<TypeAssertion>parent).expression; case SyntaxKind.TemplateSpan: return node === (<TemplateSpan>parent).expression; case SyntaxKind.ComputedPropertyName: return node === (<ComputedPropertyName>parent).expression; default: if (isExpression(parent)) { return true; } } } return false; } export function isInstantiatedModule(node: ModuleDeclaration, preserveConstEnums: boolean) { var moduleState = getModuleInstanceState(node) return moduleState === ModuleInstanceState.Instantiated || (preserveConstEnums && moduleState === ModuleInstanceState.ConstEnumOnly); } export function isExternalModuleImportDeclaration(node: Node) { return node.kind === SyntaxKind.ImportDeclaration && (<ImportDeclaration>node).moduleReference.kind === SyntaxKind.ExternalModuleReference; } export function getExternalModuleImportDeclarationExpression(node: Node) { Debug.assert(isExternalModuleImportDeclaration(node)); return (<ExternalModuleReference>(<ImportDeclaration>node).moduleReference).expression; } export function isInternalModuleImportDeclaration(node: Node) { return node.kind === SyntaxKind.ImportDeclaration && (<ImportDeclaration>node).moduleReference.kind !== SyntaxKind.ExternalModuleReference; } export function hasDotDotDotToken(node: Node) { return node && node.kind === SyntaxKind.Parameter && (<ParameterDeclaration>node).dotDotDotToken !== undefined; } export function hasQuestionToken(node: Node) { if (node) { switch (node.kind) { case SyntaxKind.Parameter: return (<ParameterDeclaration>node).questionToken !== undefined; case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: return (<MethodDeclaration>node).questionToken !== undefined; case SyntaxKind.ShorthandPropertyAssignment: case SyntaxKind.PropertyAssignment: case SyntaxKind.PropertyDeclaration: case SyntaxKind.PropertySignature: return (<PropertyDeclaration>node).questionToken !== undefined; } } return false; } export function hasRestParameters(s: SignatureDeclaration): boolean { return s.parameters.length > 0 && s.parameters[s.parameters.length - 1].dotDotDotToken !== undefined; } export function isLiteralKind(kind: SyntaxKind): boolean { return SyntaxKind.FirstLiteralToken <= kind && kind <= SyntaxKind.LastLiteralToken; } export function isTextualLiteralKind(kind: SyntaxKind): boolean { return kind === SyntaxKind.StringLiteral || kind === SyntaxKind.NoSubstitutionTemplateLiteral; } export function isTemplateLiteralKind(kind: SyntaxKind): boolean { return SyntaxKind.FirstTemplateToken <= kind && kind <= SyntaxKind.LastTemplateToken; } export function isBindingPattern(node: Node) { return node.kind === SyntaxKind.ArrayBindingPattern || node.kind === SyntaxKind.ObjectBindingPattern; } export function isInAmbientContext(node: Node): boolean { while (node) { if (node.flags & (NodeFlags.Ambient | NodeFlags.DeclarationFile)) { return true; } node = node.parent; } return false; } export function isDeclaration(node: Node): boolean { switch (node.kind) { case SyntaxKind.TypeParameter: case SyntaxKind.Parameter: case SyntaxKind.VariableDeclaration: case SyntaxKind.BindingElement: case SyntaxKind.PropertyDeclaration: case SyntaxKind.PropertySignature: case SyntaxKind.PropertyAssignment: case SyntaxKind.ShorthandPropertyAssignment: case SyntaxKind.EnumMember: case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: case SyntaxKind.FunctionDeclaration: case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: case SyntaxKind.Constructor: case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.TypeAliasDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.ModuleDeclaration: case SyntaxKind.ImportDeclaration: return true; } return false; } export function isStatement(n: Node): boolean { switch (n.kind) { case SyntaxKind.BreakStatement: case SyntaxKind.ContinueStatement: case SyntaxKind.DebuggerStatement: case SyntaxKind.DoStatement: case SyntaxKind.ExpressionStatement: case SyntaxKind.EmptyStatement: case SyntaxKind.ForInStatement: case SyntaxKind.ForStatement: case SyntaxKind.IfStatement: case SyntaxKind.LabeledStatement: case SyntaxKind.ReturnStatement: case SyntaxKind.SwitchStatement: case SyntaxKind.ThrowKeyword: case SyntaxKind.TryStatement: case SyntaxKind.VariableStatement: case SyntaxKind.WhileStatement: case SyntaxKind.WithStatement: case SyntaxKind.ExportAssignment: return true; default: return false; } } // True if the given identifier, string literal, or number literal is the name of a declaration node export function isDeclarationOrFunctionExpressionOrCatchVariableName(name: Node): boolean { if (name.kind !== SyntaxKind.Identifier && name.kind !== SyntaxKind.StringLiteral && name.kind !== SyntaxKind.NumericLiteral) { return false; } var parent = name.parent; if (isDeclaration(parent) || parent.kind === SyntaxKind.FunctionExpression) { return (<Declaration>parent).name === name; } if (parent.kind === SyntaxKind.CatchClause) { return (<CatchClause>parent).name === name; } return false; } export function getClassBaseTypeNode(node: ClassDeclaration) { var heritageClause = getHeritageClause(node.heritageClauses, SyntaxKind.ExtendsKeyword); return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; } export function getClassImplementedTypeNodes(node: ClassDeclaration) { var heritageClause = getHeritageClause(node.heritageClauses, SyntaxKind.ImplementsKeyword); return heritageClause ? heritageClause.types : undefined; } export function getInterfaceBaseTypeNodes(node: InterfaceDeclaration) { var heritageClause = getHeritageClause(node.heritageClauses, SyntaxKind.ExtendsKeyword); return heritageClause ? heritageClause.types : undefined; } export function getHeritageClause(clauses: NodeArray<HeritageClause>, kind: SyntaxKind) { if (clauses) { for (var i = 0, n = clauses.length; i < n; i++) { if (clauses[i].token === kind) { return clauses[i]; } } } return undefined; } export function tryResolveScriptReference(host: ScriptReferenceHost, sourceFile: SourceFile, reference: FileReference) { if (!host.getCompilerOptions().noResolve) { var referenceFileName = isRootedDiskPath(reference.fileName) ? reference.fileName : combinePaths(getDirectoryPath(sourceFile.fileName), reference.fileName); referenceFileName = getNormalizedAbsolutePath(referenceFileName, host.getCurrentDirectory()); return host.getSourceFile(referenceFileName); } } export function getAncestor(node: Node, kind: SyntaxKind): Node { switch (kind) { // special-cases that can be come first case SyntaxKind.ClassDeclaration: while (node) { switch (node.kind) { case SyntaxKind.ClassDeclaration: return <ClassDeclaration>node; case SyntaxKind.EnumDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.TypeAliasDeclaration: case SyntaxKind.ModuleDeclaration: case SyntaxKind.ImportDeclaration: // early exit cases - declarations cannot be nested in classes return undefined; default: node = node.parent; continue; } } break; default: while (node) { if (node.kind === kind) { return node; } node = node.parent; } break; } return undefined; } export function getFileReferenceFromReferencePath(comment: string, commentRange: CommentRange): ReferencePathMatchResult { var simpleReferenceRegEx = /^\/\/\/\s*<reference\s+/gim; var isNoDefaultLibRegEx = /^(\/\/\/\s*<reference\s+no-default-lib\s*=\s*)('|")(.+?)\2\s*\/>/gim; if (simpleReferenceRegEx.exec(comment)) { if (isNoDefaultLibRegEx.exec(comment)) { return { isNoDefaultLib: true } } else { var matchResult = fullTripleSlashReferencePathRegEx.exec(comment); if (matchResult) { var start = commentRange.pos; var end = commentRange.end; return { fileReference: { pos: start, end: end, fileName: matchResult[3] }, isNoDefaultLib: false }; } else { return { diagnosticMessage: Diagnostics.Invalid_reference_directive_syntax, isNoDefaultLib: false }; } } } return undefined; } export function isKeyword(token: SyntaxKind): boolean { return SyntaxKind.FirstKeyword <= token && token <= SyntaxKind.LastKeyword; } export function isTrivia(token: SyntaxKind) { return SyntaxKind.FirstTriviaToken <= token && token <= SyntaxKind.LastTriviaToken; } /** * A declaration has a dynamic name if both of the following are true: * 1. The declaration has a computed property name * 2. The computed name is *not* expressed as Symbol.<name>, where name * is a property of the Symbol constructor that denotes a built in * Symbol. */ export function hasDynamicName(declaration: Declaration): boolean { return declaration.name && declaration.name.kind === SyntaxKind.ComputedPropertyName && !isWellKnownSymbolSyntactically((<ComputedPropertyName>declaration.name).expression); } export function isWellKnownSymbolSyntactically(node: Node): boolean { return node.kind === SyntaxKind.PropertyAccessExpression && isESSymbolIdentifier((<PropertyAccessExpression>node).expression); } export function isESSymbolTypeNode(node: Node): boolean { return node.kind === SyntaxKind.TypeReference && (<TypeReferenceNode>node).typeArguments === undefined && isESSymbolIdentifier((<TypeReferenceNode>node).typeName); } /** * Includes the word "Symbol" with unicode escapes */ export function isESSymbolIdentifier(node: Node): boolean { return node.kind === SyntaxKind.Identifier && (<Identifier>node).text === "Symbol"; } export function isModifier(token: SyntaxKind): boolean { switch (token) { case SyntaxKind.PublicKeyword: case SyntaxKind.PrivateKeyword: case SyntaxKind.ProtectedKeyword: case SyntaxKind.StaticKeyword: case SyntaxKind.ExportKeyword: case SyntaxKind.DeclareKeyword: case SyntaxKind.ConstKeyword: return true; } return false; } export function textSpanEnd(span: TextSpan) { return span.start + span.length } export function textSpanIsEmpty(span: TextSpan) { return span.length === 0 } export function textSpanContainsPosition(span: TextSpan, position: number) { return position >= span.start && position < textSpanEnd(span); } // Returns true if 'span' contains 'other'. export function textSpanContainsTextSpan(span: TextSpan, other: TextSpan) { return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span); } export function textSpanOverlapsWith(span: TextSpan, other: TextSpan) { var overlapStart = Math.max(span.start, other.start); var overlapEnd = Math.min(textSpanEnd(span), textSpanEnd(other)); return overlapStart < overlapEnd; } export function textSpanOverlap(span1: TextSpan, span2: TextSpan) { var overlapStart = Math.max(span1.start, span2.start); var overlapEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2)); if (overlapStart < overlapEnd) { return createTextSpanFromBounds(overlapStart, overlapEnd); } return undefined; } export function textSpanIntersectsWithTextSpan(span: TextSpan, other: TextSpan) { return other.start <= textSpanEnd(span) && textSpanEnd(other) >= span.start } export function textSpanIntersectsWith(span: TextSpan, start: number, length: number) { var end = start + length; return start <= textSpanEnd(span) && end >= span.start; } export function textSpanIntersectsWithPosition(span: TextSpan, position: number) { return position <= textSpanEnd(span) && position >= span.start; } export function textSpanIntersection(span1: TextSpan, span2: TextSpan) { var intersectStart = Math.max(span1.start, span2.start); var intersectEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2)); if (intersectStart <= intersectEnd) { return createTextSpanFromBounds(intersectStart, intersectEnd); } return undefined; } export function createTextSpan(start: number, length: number): TextSpan { if (start < 0) { throw new Error("start < 0"); } if (length < 0) { throw new Error("length < 0"); } return { start, length }; } export function createTextSpanFromBounds(start: number, end: number) { return createTextSpan(start, end - start); } export function textChangeRangeNewSpan(range: TextChangeRange) { return createTextSpan(range.span.start, range.newLength); } export function textChangeRangeIsUnchanged(range: TextChangeRange) { return textSpanIsEmpty(range.span) && range.newLength === 0; } export function createTextChangeRange(span: TextSpan, newLength: number): TextChangeRange { if (newLength < 0) { throw new Error("newLength < 0"); } return { span, newLength }; } export var unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); /** * Called to merge all the changes that occurred across several versions of a script snapshot * into a single change. i.e. if a user keeps making successive edits to a script we will * have a text change from V1 to V2, V2 to V3, ..., Vn. * * This function will then merge those changes into a single change range valid between V1 and * Vn. */ export function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange { if (changes.length === 0) { return unchangedTextChangeRange; } if (changes.length === 1) { return changes[0]; } // We change from talking about { { oldStart, oldLength }, newLength } to { oldStart, oldEnd, newEnd } // as it makes things much easier to reason about. var change0 = changes[0]; var oldStartN = change0.span.start; var oldEndN = textSpanEnd(change0.span); var newEndN = oldStartN + change0.newLength; for (var i = 1; i < changes.length; i++) { var nextChange = changes[i]; // Consider the following case: // i.e. two edits. The first represents the text change range { { 10, 50 }, 30 }. i.e. The span starting // at 10, with length 50 is reduced to length 30. The second represents the text change range { { 30, 30 }, 40 }. // i.e. the span starting at 30 with length 30 is increased to length 40. // // 0 10 20 30 40 50 60 70 80 90 100 // ------------------------------------------------------------------------------------------------------- // | / // | /---- // T1 | /---- // | /---- // | /---- // ------------------------------------------------------------------------------------------------------- // | \ // | \ // T2 | \ // | \ // | \ // ------------------------------------------------------------------------------------------------------- // // Merging these turns out to not be too difficult. First, determining the new start of the change is trivial // it's just the min of the old and new starts. i.e.: // // 0 10 20 30 40 50 60 70 80 90 100 // ------------------------------------------------------------*------------------------------------------ // | / // | /---- // T1 | /---- // | /---- // | /---- // ----------------------------------------$-------------------$------------------------------------------ // . | \ // . | \ // T2 . | \ // . | \ // . | \ // ----------------------------------------------------------------------*-------------------------------- // // (Note the dots represent the newly inferrred start. // Determining the new and old end is also pretty simple. Basically it boils down to paying attention to the // absolute positions at the asterixes, and the relative change between the dollar signs. Basically, we see // which if the two $'s precedes the other, and we move that one forward until they line up. in this case that // means: // // 0 10 20 30 40 50 60 70 80 90 100 // --------------------------------------------------------------------------------*---------------------- // | / // | /---- // T1 | /---- // | /---- // | /---- // ------------------------------------------------------------$------------------------------------------ // . | \ // . | \ // T2 . | \ // . | \ // . | \ // ----------------------------------------------------------------------*-------------------------------- // // In other words (in this case), we're recognizing that the second edit happened after where the first edit // ended with a delta of 20 characters (60 - 40). Thus, if we go back in time to where the first edit started // that's the same as if we started at char 80 instead of 60. // // As it so happens, the same logic applies if the second edit precedes the first edit. In that case rahter // than pusing the first edit forward to match the second, we'll push the second edit forward to match the // first. // // In this case that means we have { oldStart: 10, oldEnd: 80, newEnd: 70 } or, in TextChangeRange // semantics: { { start: 10, length: 70 }, newLength: 60 } // // The math then works out as follows. // If we have { oldStart1, oldEnd1, newEnd1 } and { oldStart2, oldEnd2, newEnd2 } then we can compute the // final result like so: // // { // oldStart3: Min(oldStart1, oldStart2), // oldEnd3 : Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)), // newEnd3 : Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)) // } var oldStart1 = oldStartN; var oldEnd1 = oldEndN; var newEnd1 = newEndN; var oldStart2 = nextChange.span.start; var oldEnd2 = textSpanEnd(nextChange.span); var newEnd2 = oldStart2 + nextChange.newLength; oldStartN = Math.min(oldStart1, oldStart2); oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)); newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)); } return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength: */newEndN - oldStartN); } // @internal export function createDiagnosticCollection(): DiagnosticCollection { var nonFileDiagnostics: Diagnostic[] = []; var fileDiagnostics: Map<Diagnostic[]> = {}; var diagnosticsModified = false; var modificationCount = 0; return { add, getGlobalDiagnostics, getDiagnostics, getModificationCount }; function getModificationCount() { return modificationCount; } function add(diagnostic: Diagnostic): void { var diagnostics: Diagnostic[]; if (diagnostic.file) { diagnostics = fileDiagnostics[diagnostic.file.fileName]; if (!diagnostics) { diagnostics = []; fileDiagnostics[diagnostic.file.fileName] = diagnostics; } } else { diagnostics = nonFileDiagnostics; } diagnostics.push(diagnostic); diagnosticsModified = true; modificationCount++; } function getGlobalDiagnostics(): Diagnostic[] { sortAndDeduplicate(); return nonFileDiagnostics; } function getDiagnostics(fileName?: string): Diagnostic[] { sortAndDeduplicate(); if (fileName) { return fileDiagnostics[fileName] || []; } var allDiagnostics: Diagnostic[] = []; function pushDiagnostic(d: Diagnostic) { allDiagnostics.push(d); } forEach(nonFileDiagnostics, pushDiagnostic); for (var key in fileDiagnostics) { if (hasProperty(fileDiagnostics, key)) { forEach(fileDiagnostics[key], pushDiagnostic); } } return sortAndDeduplicateDiagnostics(allDiagnostics); } function sortAndDeduplicate() { if (!diagnosticsModified) { return; } diagnosticsModified = false; nonFileDiagnostics = sortAndDeduplicateDiagnostics(nonFileDiagnostics); for (var key in fileDiagnostics) { if (hasProperty(fileDiagnostics, key)) { fileDiagnostics[key] = sortAndDeduplicateDiagnostics(fileDiagnostics[key]); } } } } }
src/compiler/utilities.ts
1
https://github.com/microsoft/TypeScript/commit/f344654460c0772eb781754a0c5b460cf740e114
[ 0.0009806439047679305, 0.00018621845811139792, 0.0001652509527048096, 0.00017216839478351176, 0.00007688113691983745 ]
{ "id": 5, "code_window": [ "=== tests/cases/conformance/parser/ecmascript6/Symbols/parserSymbolProperty8.ts ===\n", "var x: {\n", ">x : {}\n", "\n", " [Symbol.toPrimitive](): string\n", ">Symbol.toPrimitive : Symbol\n", ">Symbol : SymbolConstructor\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ ">x : { [Symbol.toPrimitive](): string; }\n" ], "file_path": "tests/baselines/reference/parserSymbolProperty8.types", "type": "replace", "edit_start_line_idx": 2 }
tests/cases/compiler/sourceMapValidationEnums.ts(2,5): error TS2300: Duplicate identifier 'x'. tests/cases/compiler/sourceMapValidationEnums.ts(4,5): error TS2300: Duplicate identifier 'x'. ==== tests/cases/compiler/sourceMapValidationEnums.ts (2 errors) ==== enum e { x, ~ !!! error TS2300: Duplicate identifier 'x'. y, x ~ !!! error TS2300: Duplicate identifier 'x'. } enum e2 { x = 10, y = 10, z, x2 } enum e3 { }
tests/baselines/reference/sourceMapValidationEnums.errors.txt
0
https://github.com/microsoft/TypeScript/commit/f344654460c0772eb781754a0c5b460cf740e114
[ 0.007614472880959511, 0.0028693077620118856, 0.00017487216973677278, 0.0008185776532627642, 0.00336561375297606 ]
{ "id": 5, "code_window": [ "=== tests/cases/conformance/parser/ecmascript6/Symbols/parserSymbolProperty8.ts ===\n", "var x: {\n", ">x : {}\n", "\n", " [Symbol.toPrimitive](): string\n", ">Symbol.toPrimitive : Symbol\n", ">Symbol : SymbolConstructor\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ ">x : { [Symbol.toPrimitive](): string; }\n" ], "file_path": "tests/baselines/reference/parserSymbolProperty8.types", "type": "replace", "edit_start_line_idx": 2 }
//// [genericConstraintOnExtendedBuiltinTypes.ts] declare module EndGate { export interface ICloneable { Clone(): any; } } interface Number extends EndGate.ICloneable { } module EndGate.Tweening { export class Tween<T extends ICloneable>{ private _from: T; constructor(from: T) { this._from = from.Clone(); } } } module EndGate.Tweening { export class NumberTween extends Tween<number>{ constructor(from: number) { super(from); } } } //// [genericConstraintOnExtendedBuiltinTypes.js] var __extends = this.__extends || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; var EndGate; (function (EndGate) { var Tweening; (function (Tweening) { var Tween = (function () { function Tween(from) { this._from = from.Clone(); } return Tween; })(); Tweening.Tween = Tween; })(Tweening = EndGate.Tweening || (EndGate.Tweening = {})); })(EndGate || (EndGate = {})); var EndGate; (function (EndGate) { var Tweening; (function (Tweening) { var NumberTween = (function (_super) { __extends(NumberTween, _super); function NumberTween(from) { _super.call(this, from); } return NumberTween; })(Tweening.Tween); Tweening.NumberTween = NumberTween; })(Tweening = EndGate.Tweening || (EndGate.Tweening = {})); })(EndGate || (EndGate = {}));
tests/baselines/reference/genericConstraintOnExtendedBuiltinTypes.js
0
https://github.com/microsoft/TypeScript/commit/f344654460c0772eb781754a0c5b460cf740e114
[ 0.00017551114433445036, 0.00016997894272208214, 0.00016185663116630167, 0.0001718349667498842, 0.000004566827101371018 ]
{ "id": 5, "code_window": [ "=== tests/cases/conformance/parser/ecmascript6/Symbols/parserSymbolProperty8.ts ===\n", "var x: {\n", ">x : {}\n", "\n", " [Symbol.toPrimitive](): string\n", ">Symbol.toPrimitive : Symbol\n", ">Symbol : SymbolConstructor\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ ">x : { [Symbol.toPrimitive](): string; }\n" ], "file_path": "tests/baselines/reference/parserSymbolProperty8.types", "type": "replace", "edit_start_line_idx": 2 }
function foo() { bar( return x; }
tests/cases/conformance/parser/ecmascript5/ErrorRecovery/ArgumentLists/parserErrorRecovery_ArgumentList1.ts
0
https://github.com/microsoft/TypeScript/commit/f344654460c0772eb781754a0c5b460cf740e114
[ 0.01505560614168644, 0.01505560614168644, 0.01505560614168644, 0.01505560614168644, 0 ]
{ "id": 0, "code_window": [ "};\n", "\n", "if (commander.eval) {\n", " var code = to5.transform(commander.eval, { filename: \"eval\" }).code;\n", "\n", " var result = _eval(code, \"eval\");\n", " if (commander.print) console.log(result);\n", "} else {\n", " var filenames = commander.args;\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " var result = _eval(commander.eval, \"eval\");\n" ], "file_path": "bin/6to5-node", "type": "replace", "edit_start_line_idx": 43 }
#!/usr/bin/env node var commander = require("commander"); var Module = require("module"); var util = require("../lib/6to5/util"); var path = require("path"); var repl = require("repl"); var to5 = require("../lib/6to5"); var vm = require("vm"); var _ = require("lodash"); commander.option("-e, --eval [script]", "evaluate script"); commander.option("-p, --print", "evaluate script and print result"); commander.option("-i, --ignore [regex]", "ignore all files that match this regex when using the require hook"); commander.option("-x, --extensions [extensions]", "list of extensions to hook into [.es6,.js]", util.list); var pkg = require("../package.json"); commander.version(pkg.version); commander.usage("[options] [ -e script | script.js ] [arguments]"); commander.parse(process.argv); // var registerOpts = {}; if (commander.ignore) { registerOpts.ignoreRegex = new RegExp(commander.ignore); } if (commander.extensions && commander.extensions.length) { registerOpts.extensions = commander.extensions } to5.register(registerOpts); // var _eval = function (code, filename) { code = to5.transform(code, { filename: filename }).code; return vm.runInThisContext(code, filename); }; if (commander.eval) { var code = to5.transform(commander.eval, { filename: "eval" }).code; var result = _eval(code, "eval"); if (commander.print) console.log(result); } else { var filenames = commander.args; if (filenames.length) { _.each(filenames, function (filename) { if (!util.isAbsolute(filename)) { filename = path.join(process.cwd(), filename); } require(require.resolve(filename)); }); } else { replStart(); } } function replStart() { repl.start({ prompt: "> ", input: process.stdin, output: process.stdout, eval: replEval, useGlobal: true }); } function replEval(code, context, filename, callback) { var err; var result; try { code = code.slice(1, -2); // remove "(" and "\n)" result = _eval(code, filename); } catch (e) { err = e; } callback(err, result); }
bin/6to5-node
1
https://github.com/babel/babel/commit/2be2e4e1aefd93f8ce1fb0fea65899f2601c5159
[ 0.9986904263496399, 0.2667430639266968, 0.0001763966283760965, 0.012191852554678917, 0.4024921953678131 ]
{ "id": 0, "code_window": [ "};\n", "\n", "if (commander.eval) {\n", " var code = to5.transform(commander.eval, { filename: \"eval\" }).code;\n", "\n", " var result = _eval(code, \"eval\");\n", " if (commander.print) console.log(result);\n", "} else {\n", " var filenames = commander.args;\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " var result = _eval(commander.eval, \"eval\");\n" ], "file_path": "bin/6to5-node", "type": "replace", "edit_start_line_idx": 43 }
// Based upon the excellent jsx-transpiler by Ingvar Stepanyan (RReverser) // https://github.com/RReverser/jsx-transpiler var esutils = require("esutils"); var b = require("recast").types.builders; var _ = require("lodash"); var JSX_ANNOTATION_REGEX = /^\*\s*@jsx\s+([^\s]+)/; var KNOWN_TAGS = require("./known-tags"); exports.Program = function (node, parent, file) { var jsx = "React.DOM"; // looking for namespace annotation _.each(node.comments, function (comment) { if (!comment.possiblyLeading) return; var matches = JSX_ANNOTATION_REGEX.exec(comment.value); if (matches) jsx = matches[1]; }); // prebuilding AST node file.jsx = jsx.split(".").map(b.identifier).reduce(function (object, property) { return b.memberExpression(object, property, false); }); }; exports.XJSIdentifier = function (node) { if (esutils.keyword.isIdentifierName(node.name)) { node.type = "Identifier"; } else { return b.literal(node.name); } }; exports.XJSNamespacedName = function () { throw new Error("Namespace tags are not supported. ReactJSX is not XML."); }; exports.XJSMemberExpression = { exit: function (node) { node.computed = node.property.type === "Literal"; node.type = "MemberExpression"; } }; exports.XJSEmptyExpression = function (node) { node.value = null; node.type = "Literal"; }; exports.XJSExpressionContainer = function (node) { return node.expression; }; exports.XJSAttribute = { exit: function (node) { var value = node.value || b.literal(true); var propNode = b.property("init", node.name, value); propNode.loc = node.loc; return propNode; } }; exports.XJSOpeningElement = { exit: function (node, parent, file) { var tagExpr = node.name; if (_.contains(KNOWN_TAGS, tagExpr.name)) { tagExpr = b.memberExpression(file.jsx, tagExpr, false); } var props = node.attributes; if (props.length) { props = b.objectExpression(props); } else { props = b.literal(null); } return b.callExpression(tagExpr, [props]); } }; exports.XJSElement = { exit: function (node) { var callExpr = node.openingElement; var children = node.children; var args = callExpr.arguments; switch (children.length) { case 0: break; case 1: args.push(children[0]); break; default: args.push(b.arrayExpression(children)); } callExpr.loc = node.loc; return callExpr; } };
lib/6to5/transformers/jsx/index.js
0
https://github.com/babel/babel/commit/2be2e4e1aefd93f8ce1fb0fea65899f2601c5159
[ 0.00017843964451458305, 0.00017209873476531357, 0.00016359738947357982, 0.0001710939104668796, 0.000004678864115703618 ]
{ "id": 0, "code_window": [ "};\n", "\n", "if (commander.eval) {\n", " var code = to5.transform(commander.eval, { filename: \"eval\" }).code;\n", "\n", " var result = _eval(code, \"eval\");\n", " if (commander.print) console.log(result);\n", "} else {\n", " var filenames = commander.args;\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " var result = _eval(commander.eval, \"eval\");\n" ], "file_path": "bin/6to5-node", "type": "replace", "edit_start_line_idx": 43 }
"use strict"; var foo = require("foo").default; var xyz = require("foo").baz; var foo = require("foo").default; var bar = require("foo");
test/fixtures/syntax/modules/imports-mixing/expected.js
0
https://github.com/babel/babel/commit/2be2e4e1aefd93f8ce1fb0fea65899f2601c5159
[ 0.00017512663907837123, 0.00017512663907837123, 0.00017512663907837123, 0.00017512663907837123, 0 ]
{ "id": 0, "code_window": [ "};\n", "\n", "if (commander.eval) {\n", " var code = to5.transform(commander.eval, { filename: \"eval\" }).code;\n", "\n", " var result = _eval(code, \"eval\");\n", " if (commander.print) console.log(result);\n", "} else {\n", " var filenames = commander.args;\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " var result = _eval(commander.eval, \"eval\");\n" ], "file_path": "bin/6to5-node", "type": "replace", "edit_start_line_idx": 43 }
var coords = { x, y, foo: "bar" };
test/fixtures/syntax/property-name-shorthand/mixed/actual.js
0
https://github.com/babel/babel/commit/2be2e4e1aefd93f8ce1fb0fea65899f2601c5159
[ 0.0001733813842292875, 0.0001733813842292875, 0.0001733813842292875, 0.0001733813842292875, 0 ]
{ "id": 1, "code_window": [ "\n", " var write = function (src, relative) {\n", " var dest = path.join(commander.outDir, relative);\n", "\n", " var data = util.compile(src, dest);\n", "\n", " var up = path.normalize(dest + \"/..\");\n", " mkdirp.sync(up);\n", "\n", " if (commander.sourceMaps) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " var data = util.compile(src, { sourceMapName: dest });\n" ], "file_path": "bin/6to5/dir.js", "type": "replace", "edit_start_line_idx": 15 }
var readdir = require("fs-readdir-recursive"); var index = require("./index"); var util = require("../../lib/6to5/util"); var to5 = require("../../lib/6to5"); var fs = require("fs"); var _ = require("lodash"); exports.readdirFilter = function (filename) { return readdir(filename).filter(util.canCompile); }; exports.transform = function (filename, code, to) { var opts = _.extend({ filename: filename }, index.opts); if (to) opts.sourceMapName = to; var result = to5.transform(code, opts); result.filename = filename; result.actual = code; return result; }; exports.compile = function (filename, to) { var code = fs.readFileSync(filename, "utf8"); return exports.transform(filename, code, to); };
bin/6to5/util.js
1
https://github.com/babel/babel/commit/2be2e4e1aefd93f8ce1fb0fea65899f2601c5159
[ 0.0012058228021487594, 0.0005314418231137097, 0.00017078024393413216, 0.000217722452362068, 0.00047724429168738425 ]
{ "id": 1, "code_window": [ "\n", " var write = function (src, relative) {\n", " var dest = path.join(commander.outDir, relative);\n", "\n", " var data = util.compile(src, dest);\n", "\n", " var up = path.normalize(dest + \"/..\");\n", " mkdirp.sync(up);\n", "\n", " if (commander.sourceMaps) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " var data = util.compile(src, { sourceMapName: dest });\n" ], "file_path": "bin/6to5/dir.js", "type": "replace", "edit_start_line_idx": 15 }
"use strict"; arr.map(function(x) { return x * x; });
test/fixtures/syntax/arrow-functions/expression/expected.js
0
https://github.com/babel/babel/commit/2be2e4e1aefd93f8ce1fb0fea65899f2601c5159
[ 0.00016525127284694463, 0.00016525127284694463, 0.00016525127284694463, 0.00016525127284694463, 0 ]
{ "id": 1, "code_window": [ "\n", " var write = function (src, relative) {\n", " var dest = path.join(commander.outDir, relative);\n", "\n", " var data = util.compile(src, dest);\n", "\n", " var up = path.normalize(dest + \"/..\");\n", " mkdirp.sync(up);\n", "\n", " if (commander.sourceMaps) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " var data = util.compile(src, { sourceMapName: dest });\n" ], "file_path": "bin/6to5/dir.js", "type": "replace", "edit_start_line_idx": 15 }
"use strict"; var _slice = Array.prototype.slice; function foo() { return bar.apply(null, ["test"].concat(_slice.call(arguments))); } function bar(one, two, three) { return [one, two, three]; } foo("foo", "bar");
test/fixtures/syntax/spread/arguments/expected.js
0
https://github.com/babel/babel/commit/2be2e4e1aefd93f8ce1fb0fea65899f2601c5159
[ 0.00016629879246465862, 0.00016531808068975806, 0.00016433738346677274, 0.00016531808068975806, 9.807044989429414e-7 ]
{ "id": 1, "code_window": [ "\n", " var write = function (src, relative) {\n", " var dest = path.join(commander.outDir, relative);\n", "\n", " var data = util.compile(src, dest);\n", "\n", " var up = path.normalize(dest + \"/..\");\n", " mkdirp.sync(up);\n", "\n", " if (commander.sourceMaps) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " var data = util.compile(src, { sourceMapName: dest });\n" ], "file_path": "bin/6to5/dir.js", "type": "replace", "edit_start_line_idx": 15 }
class Test { get constructor() { } }
test/fixtures/syntax/classes/defining-constructor-as-a-mutator/actual.js
0
https://github.com/babel/babel/commit/2be2e4e1aefd93f8ce1fb0fea65899f2601c5159
[ 0.00016594065527897328, 0.00016594065527897328, 0.00016594065527897328, 0.00016594065527897328, 0 ]
{ "id": 2, "code_window": [ " } else {\n", " _filenames.push(filename);\n", " }\n", " });\n", "\n", " _.each(_filenames, function (filename) {\n", " results.push(util.compile(filename));\n", " });\n", "\n", " output();\n", " };\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " _.each(_filenames, function (filename, i) {\n", " results.push(util.compile(filename, { _noStrict: i != 0 }));\n" ], "file_path": "bin/6to5/file.js", "type": "replace", "edit_start_line_idx": 102 }
var readdir = require("fs-readdir-recursive"); var index = require("./index"); var util = require("../../lib/6to5/util"); var to5 = require("../../lib/6to5"); var fs = require("fs"); var _ = require("lodash"); exports.readdirFilter = function (filename) { return readdir(filename).filter(util.canCompile); }; exports.transform = function (filename, code, to) { var opts = _.extend({ filename: filename }, index.opts); if (to) opts.sourceMapName = to; var result = to5.transform(code, opts); result.filename = filename; result.actual = code; return result; }; exports.compile = function (filename, to) { var code = fs.readFileSync(filename, "utf8"); return exports.transform(filename, code, to); };
bin/6to5/util.js
1
https://github.com/babel/babel/commit/2be2e4e1aefd93f8ce1fb0fea65899f2601c5159
[ 0.0017018852522596717, 0.0010696477256715298, 0.00035951496101915836, 0.001147543080151081, 0.0005507814348675311 ]
{ "id": 2, "code_window": [ " } else {\n", " _filenames.push(filename);\n", " }\n", " });\n", "\n", " _.each(_filenames, function (filename) {\n", " results.push(util.compile(filename));\n", " });\n", "\n", " output();\n", " };\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " _.each(_filenames, function (filename, i) {\n", " results.push(util.compile(filename, { _noStrict: i != 0 }));\n" ], "file_path": "bin/6to5/file.js", "type": "replace", "edit_start_line_idx": 102 }
var arr = [for (x of "abcdefgh".split("")) for (y of "12345678".split("")) (x + y)];
test/fixtures/syntax/array-comprehension/multiple/actual.js
0
https://github.com/babel/babel/commit/2be2e4e1aefd93f8ce1fb0fea65899f2601c5159
[ 0.0001743480534059927, 0.0001743480534059927, 0.0001743480534059927, 0.0001743480534059927, 0 ]
{ "id": 2, "code_window": [ " } else {\n", " _filenames.push(filename);\n", " }\n", " });\n", "\n", " _.each(_filenames, function (filename) {\n", " results.push(util.compile(filename));\n", " });\n", "\n", " output();\n", " };\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " _.each(_filenames, function (filename, i) {\n", " results.push(util.compile(filename, { _noStrict: i != 0 }));\n" ], "file_path": "bin/6to5/file.js", "type": "replace", "edit_start_line_idx": 102 }
import * as foo from "foo";
test/fixtures/syntax/modules/imports-glob/actual.js
0
https://github.com/babel/babel/commit/2be2e4e1aefd93f8ce1fb0fea65899f2601c5159
[ 0.00016818061703816056, 0.00016818061703816056, 0.00016818061703816056, 0.00016818061703816056, 0 ]
{ "id": 2, "code_window": [ " } else {\n", " _filenames.push(filename);\n", " }\n", " });\n", "\n", " _.each(_filenames, function (filename) {\n", " results.push(util.compile(filename));\n", " });\n", "\n", " output();\n", " };\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " _.each(_filenames, function (filename, i) {\n", " results.push(util.compile(filename, { _noStrict: i != 0 }));\n" ], "file_path": "bin/6to5/file.js", "type": "replace", "edit_start_line_idx": 102 }
"use strict"; var bar = require("foo").bar; var bar = require("foo").bar; var baz = require("foo").baz; var baz = require("foo").bar; var baz = require("foo").bar; var xyz = require("foo").xyz;
test/fixtures/syntax/modules/imports-named/expected.js
0
https://github.com/babel/babel/commit/2be2e4e1aefd93f8ce1fb0fea65899f2601c5159
[ 0.00017279943858738989, 0.00017279943858738989, 0.00017279943858738989, 0.00017279943858738989, 0 ]
{ "id": 3, "code_window": [ " return readdir(filename).filter(util.canCompile);\n", "};\n", "\n", "exports.transform = function (filename, code, to) {\n", " var opts = _.extend({ filename: filename }, index.opts);\n", " if (to) opts.sourceMapName = to;\n", "\n", " var result = to5.transform(code, opts);\n", " result.filename = filename;\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "exports.transform = function (filename, code, opts) {\n", " opts = _.extend(opts || {}, index.opts);\n", " opts.filename = filename;\n" ], "file_path": "bin/6to5/util.js", "type": "replace", "edit_start_line_idx": 11 }
var readdir = require("fs-readdir-recursive"); var index = require("./index"); var util = require("../../lib/6to5/util"); var to5 = require("../../lib/6to5"); var fs = require("fs"); var _ = require("lodash"); exports.readdirFilter = function (filename) { return readdir(filename).filter(util.canCompile); }; exports.transform = function (filename, code, to) { var opts = _.extend({ filename: filename }, index.opts); if (to) opts.sourceMapName = to; var result = to5.transform(code, opts); result.filename = filename; result.actual = code; return result; }; exports.compile = function (filename, to) { var code = fs.readFileSync(filename, "utf8"); return exports.transform(filename, code, to); };
bin/6to5/util.js
1
https://github.com/babel/babel/commit/2be2e4e1aefd93f8ce1fb0fea65899f2601c5159
[ 0.9983298182487488, 0.6601995825767517, 0.010004867799580097, 0.9722639918327332, 0.45988020300865173 ]
{ "id": 3, "code_window": [ " return readdir(filename).filter(util.canCompile);\n", "};\n", "\n", "exports.transform = function (filename, code, to) {\n", " var opts = _.extend({ filename: filename }, index.opts);\n", " if (to) opts.sourceMapName = to;\n", "\n", " var result = to5.transform(code, opts);\n", " result.filename = filename;\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "exports.transform = function (filename, code, opts) {\n", " opts = _.extend(opts || {}, index.opts);\n", " opts.filename = filename;\n" ], "file_path": "bin/6to5/util.js", "type": "replace", "edit_start_line_idx": 11 }
{ "version": 3, "file": "source-maps/full/expected.js", "sources": ["source-maps/full/actual.js"], "names": [], "mappings": ";AAAA,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,UAAC;SAAK,EAAE,EAAE;CAAC,CAAC", "sourcesContent": ["arr.map(x => x * x);"] }
test/fixtures/syntax/source-maps/full/source-map.json
0
https://github.com/babel/babel/commit/2be2e4e1aefd93f8ce1fb0fea65899f2601c5159
[ 0.0001729502691887319, 0.0001729502691887319, 0.0001729502691887319, 0.0001729502691887319, 0 ]
{ "id": 3, "code_window": [ " return readdir(filename).filter(util.canCompile);\n", "};\n", "\n", "exports.transform = function (filename, code, to) {\n", " var opts = _.extend({ filename: filename }, index.opts);\n", " if (to) opts.sourceMapName = to;\n", "\n", " var result = to5.transform(code, opts);\n", " result.filename = filename;\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "exports.transform = function (filename, code, opts) {\n", " opts = _.extend(opts || {}, index.opts);\n", " opts.filename = filename;\n" ], "file_path": "bin/6to5/util.js", "type": "replace", "edit_start_line_idx": 11 }
"use strict"; var Test = function() { var Test = function Test() {}; return Test; }(); arr.map(function(x) { return x * MULTIPLIER; });
test/fixtures/bin/6to5/filenames --out-file/out-files/script3.js
0
https://github.com/babel/babel/commit/2be2e4e1aefd93f8ce1fb0fea65899f2601c5159
[ 0.0003648418060038239, 0.0003648418060038239, 0.0003648418060038239, 0.0003648418060038239, 0 ]
{ "id": 3, "code_window": [ " return readdir(filename).filter(util.canCompile);\n", "};\n", "\n", "exports.transform = function (filename, code, to) {\n", " var opts = _.extend({ filename: filename }, index.opts);\n", " if (to) opts.sourceMapName = to;\n", "\n", " var result = to5.transform(code, opts);\n", " result.filename = filename;\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "exports.transform = function (filename, code, opts) {\n", " opts = _.extend(opts || {}, index.opts);\n", " opts.filename = filename;\n" ], "file_path": "bin/6to5/util.js", "type": "replace", "edit_start_line_idx": 11 }
"use strict"; var coords = { x: x, y: y };
test/fixtures/syntax/property-name-shorthand/multiple/expected.js
0
https://github.com/babel/babel/commit/2be2e4e1aefd93f8ce1fb0fea65899f2601c5159
[ 0.0002873128105420619, 0.0002873128105420619, 0.0002873128105420619, 0.0002873128105420619, 0 ]
{ "id": 4, "code_window": [ " result.actual = code;\n", " return result;\n", "};\n", "\n", "exports.compile = function (filename, to) {\n", " var code = fs.readFileSync(filename, \"utf8\");\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "exports.compile = function (filename, opts) {\n" ], "file_path": "bin/6to5/util.js", "type": "replace", "edit_start_line_idx": 21 }
var sourceMap = require("source-map"); var chokidar = require("chokidar"); var util2 = require("../../lib/6to5/util"); var path = require("path"); var util = require("./util"); var fs = require("fs"); var _ = require("lodash"); module.exports = function (commander, filenames, opts) { var results = []; var buildResult = function () { var map = new sourceMap.SourceMapGenerator({ file: commander.outFile || "stdout" }); var code = ""; var offset = 0; _.each(results, function (result) { var filename = result.filename; code += result.code + "\n"; if (result.map) { var consumer = new sourceMap.SourceMapConsumer(result.map); map._sources.add(filename); map.setSourceContent(filename, result.actual); consumer.eachMapping(function (mapping) { map._mappings.push({ generatedLine: mapping.generatedLine + offset, generatedColumn: mapping.generatedColumn, originalLine: mapping.originalLine, originalColumn: mapping.originalColumn, source: filename }); }); offset = code.split("\n").length; } }); if (commander.sourceMapsInline || (!commander.outFile && commander.sourceMaps)) { code += "\n" + util2.sourceMapToComment(map); } return { map: map, code: code } }; var output = function () { var result = buildResult(); if (commander.outFile) { if (commander.sourceMaps) { fs.writeFileSync(commander.outFile + ".map", JSON.stringify(result.map)); } fs.writeFileSync(commander.outFile, result.code); } else { console.log(result.code); } }; var stdin = function () { var code = ""; process.stdin.setEncoding("utf8"); process.stdin.on("readable", function () { var chunk = process.stdin.read(); if (chunk !== null) code += chunk; }); process.stdin.on("end", function() { results.push(util.transform(commander.filename, code)); output(); }); }; var walk = function () { var _filenames = []; results = []; _.each(filenames, function (filename) { if (!fs.existsSync(filename)) return; var stat = fs.statSync(filename); if (stat.isDirectory()) { var dirname = filename; _.each(util.readdirFilter(filename), function (filename) { _filenames.push(path.join(dirname, filename)); }); } else { _filenames.push(filename); } }); _.each(_filenames, function (filename) { results.push(util.compile(filename)); }); output(); }; var files = function () { walk(); if (commander.watch) { var watcher = chokidar.watch(filenames, { persistent: true, ignoreInitial: true }); _.each(["add", "change", "unlink"], function (type) { watcher.on(type, function (filename) { console.log(type, filename); walk(); }); }); } }; if (filenames.length) { files(); } else { stdin(); } };
bin/6to5/file.js
1
https://github.com/babel/babel/commit/2be2e4e1aefd93f8ce1fb0fea65899f2601c5159
[ 0.9821186065673828, 0.29138118028640747, 0.0003690400335472077, 0.021554026752710342, 0.39273905754089355 ]
{ "id": 4, "code_window": [ " result.actual = code;\n", " return result;\n", "};\n", "\n", "exports.compile = function (filename, to) {\n", " var code = fs.readFileSync(filename, \"utf8\");\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "exports.compile = function (filename, opts) {\n" ], "file_path": "bin/6to5/util.js", "type": "replace", "edit_start_line_idx": 21 }
var util = require("../util"); var b = require("recast").types.builders; var _ = require("lodash"); exports.ImportDeclaration = function (node) { var nodes = []; if (node.specifiers.length) { _.each(node.specifiers, function (specifier) { var variableName = getSpecifierName(specifier); var key = specifier.id.name; // import foo from "foo"; if (specifier.type === "ImportDefaultSpecifier") { key = b.identifier("default"); } var templateName = "require-assign"; // import * as bar from "foo"; if (specifier.type !== "ImportNamespaceSpecifier") templateName += "-key"; nodes.push(util.template(templateName, { VARIABLE_NAME: variableName.name, MODULE_NAME: node.source.raw, KEY: key })); }); } else { // import "foo"; nodes.push(util.template("require", { MODULE_NAME: node.source.raw }, true)); } return nodes; }; var pushExportSpecifiers = function (node, nodes) { _.each(node.specifiers, function (specifier) { var variableName = getSpecifierName(specifier); if (node.source) { if (specifier.type === "ExportBatchSpecifier") { // export * from "foo"; nodes.push(util.template("exports-wildcard", { MODULE_NAME: node.source.raw }, true)); } else { // export { foo } from "test"; nodes.push(util.template("exports-require-assign-key", { VARIABLE_NAME: variableName.name, MODULE_NAME: node.source.raw, KEY: specifier.id }, true)); } } else { // export { foo }; nodes.push(util.template("exports-assign", { VALUE: specifier.id, KEY: variableName }, true)); } }); }; var getSpecifierName = function (specifier) { return specifier.name || specifier.id; }; var pushExportDeclaration = function (node, parent, nodes) { var declar = node.declaration; if (node.default) { util.ensureExpressionType(declar); nodes.push(util.template("exports-default", { VALUE: declar }, true)); } else { var id = declar.id; if (declar.type === "VariableDeclaration") { id = declar.declarations[0].id; } var assign = util.template("exports-assign", { VALUE: id, KEY: id }, true); nodes.push(declar); if (declar.type === "FunctionDeclaration") { assign._blockHoist = true; } nodes.push(assign); } }; exports.ExportDeclaration = function (node, parent) { var nodes = []; if (node.declaration) { pushExportDeclaration(node, parent, nodes); } else { pushExportSpecifiers(node, nodes); } return nodes; };
lib/6to5/transformers/modules.js
0
https://github.com/babel/babel/commit/2be2e4e1aefd93f8ce1fb0fea65899f2601c5159
[ 0.0012022519949823618, 0.0003941760223824531, 0.00016730412608012557, 0.0002997653791680932, 0.0002898761595133692 ]
{ "id": 4, "code_window": [ " result.actual = code;\n", " return result;\n", "};\n", "\n", "exports.compile = function (filename, to) {\n", " var code = fs.readFileSync(filename, \"utf8\");\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "exports.compile = function (filename, opts) {\n" ], "file_path": "bin/6to5/util.js", "type": "replace", "edit_start_line_idx": 21 }
{ "args": ["script.js", "script2.js", "--out-file", "script3.js"] }
test/fixtures/bin/6to5/filenames --out-file/options.json
0
https://github.com/babel/babel/commit/2be2e4e1aefd93f8ce1fb0fea65899f2601c5159
[ 0.00017884623957797885, 0.00017884623957797885, 0.00017884623957797885, 0.00017884623957797885, 0 ]
{ "id": 4, "code_window": [ " result.actual = code;\n", " return result;\n", "};\n", "\n", "exports.compile = function (filename, to) {\n", " var code = fs.readFileSync(filename, \"utf8\");\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "exports.compile = function (filename, opts) {\n" ], "file_path": "bin/6to5/util.js", "type": "replace", "edit_start_line_idx": 21 }
"use strict"; var _slice = Array.prototype.slice; add.apply(null, _slice.call(numbers));
test/fixtures/syntax/spread/method-call-single-arg/expected.js
0
https://github.com/babel/babel/commit/2be2e4e1aefd93f8ce1fb0fea65899f2601c5159
[ 0.00017054039926733822, 0.00017054039926733822, 0.00017054039926733822, 0.00017054039926733822, 0 ]
{ "id": 5, "code_window": [ " var code = fs.readFileSync(filename, \"utf8\");\n", " return exports.transform(filename, code, to);\n", "};" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ " return exports.transform(filename, code, opts);\n" ], "file_path": "bin/6to5/util.js", "type": "replace", "edit_start_line_idx": 23 }
var chokidar = require("chokidar"); var mkdirp = require("mkdirp"); var path = require("path"); var util = require("./util"); var fs = require("fs"); var _ = require("lodash"); module.exports = function (commander, filenames, opts) { if (commander.sourceMapsInline) { opts.sourceMap = "inline"; } var write = function (src, relative) { var dest = path.join(commander.outDir, relative); var data = util.compile(src, dest); var up = path.normalize(dest + "/.."); mkdirp.sync(up); if (commander.sourceMaps) { fs.writeFileSync(dest + ".map", JSON.stringify(data.map)); } fs.writeFileSync(dest, data.code); console.log(src + " -> " + dest); }; var handle = function (filename) { if (!fs.existsSync(filename)) return; var stat = fs.statSync(filename); if (stat.isDirectory(filename)) { var dirname = filename; _.each(util.readdirFilter(dirname), function (filename) { write(path.join(dirname, filename), filename); }); } else { write(filename, filename); } }; _.each(filenames, handle); if (commander.watch) { _.each(filenames, function (dirname) { var watcher = chokidar.watch(dirname, { persistent: true, ignoreInitial: true }); _.each(["add", "change", "unlink"], function (type) { watcher.on(type, function (filename) { // chop off the dirname plus the path separator var relative = filename.slice(dirname.length + 1); console.log(type, filename); write(filename, relative); }); }); }); } };
bin/6to5/dir.js
1
https://github.com/babel/babel/commit/2be2e4e1aefd93f8ce1fb0fea65899f2601c5159
[ 0.03321506083011627, 0.008974038064479828, 0.00016820596647448838, 0.0014823455130681396, 0.011399402283132076 ]
{ "id": 5, "code_window": [ " var code = fs.readFileSync(filename, \"utf8\");\n", " return exports.transform(filename, code, to);\n", "};" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ " return exports.transform(filename, code, opts);\n" ], "file_path": "bin/6to5/util.js", "type": "replace", "edit_start_line_idx": 23 }
var t = x => this.x + x;
test/fixtures/syntax/arrow-functions/this/actual.js
0
https://github.com/babel/babel/commit/2be2e4e1aefd93f8ce1fb0fea65899f2601c5159
[ 0.00017092525376938283, 0.00017092525376938283, 0.00017092525376938283, 0.00017092525376938283, 0 ]
{ "id": 5, "code_window": [ " var code = fs.readFileSync(filename, \"utf8\");\n", " return exports.transform(filename, code, to);\n", "};" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ " return exports.transform(filename, code, opts);\n" ], "file_path": "bin/6to5/util.js", "type": "replace", "edit_start_line_idx": 23 }
const MULTIPLIER = 5; function MULTIPLIER() { }
test/fixtures/syntax/constants/no-functions/actual.js
0
https://github.com/babel/babel/commit/2be2e4e1aefd93f8ce1fb0fea65899f2601c5159
[ 0.00017371283320244402, 0.00017371283320244402, 0.00017371283320244402, 0.00017371283320244402, 0 ]
{ "id": 5, "code_window": [ " var code = fs.readFileSync(filename, \"utf8\");\n", " return exports.transform(filename, code, to);\n", "};" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ " return exports.transform(filename, code, opts);\n" ], "file_path": "bin/6to5/util.js", "type": "replace", "edit_start_line_idx": 23 }
{ "throws": "MULTIPLIER is read-only" }
test/fixtures/syntax/constants/no-assignment/options.json
0
https://github.com/babel/babel/commit/2be2e4e1aefd93f8ce1fb0fea65899f2601c5159
[ 0.0001698382111499086, 0.0001698382111499086, 0.0001698382111499086, 0.0001698382111499086, 0 ]
{ "id": 0, "code_window": [ "\t\"description\": \"Configures an attached to container\",\n", "\t\"allowComments\": true,\n", "\t\"type\": \"object\",\n", "\t\"additionalProperties\": false,\n", "\t\"definitions\": {\n", "\t\t\"attachContainer\": {\n", "\t\t\t\"type\": \"object\",\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "extensions/configuration-editing/schemas/attachContainer.schema.json", "type": "replace", "edit_start_line_idx": 5 }
{ "$schema": "http://json-schema.org/draft-07/schema#", "description": "Defines a dev container", "allowComments": true, "type": "object", "additionalProperties": false, "definitions": { "devContainerCommon": { "type": "object", "additionalProperties": false, "properties": { "name": { "type": "string", "description": "A name to show for the workspace folder." }, "extensions": { "type": "array", "description": "An array of extensions that should be installed into the container.", "items": { "type": "string", "pattern": "^([a-z0-9A-Z][a-z0-9\\-A-Z]*)\\.([a-z0-9A-Z][a-z0-9\\-A-Z]*)$", "errorMessage": "Expected format '${publisher}.${name}'. Example: 'vscode.csharp'." } }, "settings": { "$ref": "vscode://schemas/settings/machine", "description": "Machine specific settings that should be copied into the container." }, "forwardPorts": { "type": "array", "description": "Ports that are forwarded from the container to the local machine.", "items": { "type": "integer" } }, "remoteEnv": { "type": "object", "additionalProperties": { "type": [ "string", "null" ] }, "description": "Remote environment variables." }, "remoteUser": { "type": "string", "description": "The user VS Code Server will be started with. The default is the same user as the container." }, "postCreateCommand": { "type": [ "string", "array" ], "description": "A command to run after creating the container. If this is a single string, it will be run in a shell. If this is an array of strings, it will be run as a single command without shell.", "items": { "type": "string" } }, "devPort": { "type": "integer", "description": "The port VS Code can use to connect to its backend." } } }, "nonComposeBase": { "type": "object", "additionalProperties": false, "properties": { "appPort": { "type": [ "integer", "string", "array" ], "description": "Application ports that are exposed by the container. This can be a single port or an array of ports. Each port can be a number or a string. A number is mapped to the same port on the host. A string is passed to Docker unchanged and can be used to map ports differently, e.g. \"8000:8010\".", "items": { "type": [ "integer", "string" ] } }, "containerEnv": { "type": "object", "additionalProperties": { "type": "string" }, "description": "Container environment variables." }, "containerUser": { "type": "string", "description": "The user the container will be started with. The default is the user on the Docker image." }, "updateRemoteUserUID": { "type": "boolean", "description": "Controls whether on Linux the container's user should be updated with the local user's UID and GID. On by default." }, "mounts": { "type": "array", "description": "Mount points to set up when creating the container. See Docker's documentation for the --mount option for the supported syntax.", "items": { "type": "string" } }, "runArgs": { "type": "array", "description": "The arguments required when starting in the container.", "items": { "type": "string" } }, "shutdownAction": { "type": "string", "enum": [ "none", "stopContainer" ], "description": "Action to take when the VS Code window is closed. The default is to stop the container." }, "overrideCommand": { "type": "boolean", "description": "Whether to overwrite the command specified in the image. The default is true." }, "workspaceFolder": { "type": "string", "description": "The path of the workspace folder inside the container." }, "workspaceMount": { "type": "string", "description": "The --mount parameter for docker run. The default is to mount the project folder at /workspaces/$project." } } }, "dockerFileContainer": { "type": "object", "additionalProperties": false, "properties": { "dockerFile": { "type": "string", "description": "The location of the Dockerfile that defines the contents of the container. The path is relative to the folder containing the `devcontainer.json` file." }, "context": { "type": "string", "description": "The location of the context folder for building the Docker image. The path is relative to the folder containing the `devcontainer.json` file." } }, "required": [ "dockerFile" ] }, "imageContainer": { "type": "object", "additionalProperties": false, "properties": { "image": { "type": "string", "description": "The docker image that will be used to create the container." } }, "required": [ "image" ] }, "composeContainer": { "type": "object", "additionalProperties": false, "properties": { "dockerComposeFile": { "type": [ "string", "array" ], "description": "The name of the docker-compose file(s) used to start the services.", "items": { "type": "string" } }, "service": { "type": "string", "description": "The service you want to work on." }, "runServices": { "type": "array", "description": "An array of services that should be started and stopped.", "items": { "type": "string" } }, "workspaceFolder": { "type": "string", "description": "The path of the workspace folder inside the container." }, "shutdownAction": { "type": "string", "enum": [ "none", "stopCompose" ], "description": "Action to take when the VS Code window is closed. The default is to stop the containers." } }, "required": [ "dockerComposeFile", "service", "workspaceFolder" ] } }, "allOf": [ { "oneOf": [ { "allOf": [ { "oneOf": [ { "$ref": "#/definitions/dockerFileContainer" }, { "$ref": "#/definitions/imageContainer" } ] }, { "$ref": "#/definitions/nonComposeBase" } ] }, { "$ref": "#/definitions/composeContainer" } ] }, { "$ref": "#/definitions/devContainerCommon" } ] }
extensions/configuration-editing/schemas/devContainer.schema.json
1
https://github.com/microsoft/vscode/commit/8046438bb13cc424399978a895530f9076a7045e
[ 0.00033330352744087577, 0.00019048382819164544, 0.0001643333089305088, 0.00017656348063610494, 0.00003533200651872903 ]
{ "id": 0, "code_window": [ "\t\"description\": \"Configures an attached to container\",\n", "\t\"allowComments\": true,\n", "\t\"type\": \"object\",\n", "\t\"additionalProperties\": false,\n", "\t\"definitions\": {\n", "\t\t\"attachContainer\": {\n", "\t\t\t\"type\": \"object\",\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "extensions/configuration-editing/schemas/attachContainer.schema.json", "type": "replace", "edit_start_line_idx": 5 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; import { HtmlNode } from 'EmmetNode'; import { getHtmlNode, parseDocument, validate } from './util'; let balanceOutStack: Array<vscode.Selection[]> = []; let lastOut = false; let lastBalancedSelections: vscode.Selection[] = []; export function balanceOut() { balance(true); } export function balanceIn() { balance(false); } function balance(out: boolean) { if (!validate(false) || !vscode.window.activeTextEditor) { return; } const editor = vscode.window.activeTextEditor; let rootNode = <HtmlNode>parseDocument(editor.document); if (!rootNode) { return; } let getRangeFunction = out ? getRangeToBalanceOut : getRangeToBalanceIn; let newSelections: vscode.Selection[] = []; editor.selections.forEach(selection => { let range = getRangeFunction(editor.document, selection, rootNode); newSelections.push(range); }); if (areSameSelections(newSelections, editor.selections)) { return; } if (areSameSelections(lastBalancedSelections, editor.selections)) { if (out) { if (!balanceOutStack.length) { balanceOutStack.push(editor.selections); } balanceOutStack.push(newSelections); } else { if (lastOut) { balanceOutStack.pop(); } newSelections = balanceOutStack.pop() || newSelections; } } else { balanceOutStack = out ? [editor.selections, newSelections] : []; } lastOut = out; lastBalancedSelections = editor.selections = newSelections; } function getRangeToBalanceOut(document: vscode.TextDocument, selection: vscode.Selection, rootNode: HtmlNode): vscode.Selection { let nodeToBalance = getHtmlNode(document, rootNode, selection.start, false); if (!nodeToBalance) { return selection; } if (!nodeToBalance.close) { return new vscode.Selection(nodeToBalance.start, nodeToBalance.end); } let innerSelection = new vscode.Selection(nodeToBalance.open.end, nodeToBalance.close.start); let outerSelection = new vscode.Selection(nodeToBalance.start, nodeToBalance.end); if (innerSelection.contains(selection) && !innerSelection.isEqual(selection)) { return innerSelection; } if (outerSelection.contains(selection) && !outerSelection.isEqual(selection)) { return outerSelection; } return selection; } function getRangeToBalanceIn(document: vscode.TextDocument, selection: vscode.Selection, rootNode: HtmlNode): vscode.Selection { let nodeToBalance = getHtmlNode(document, rootNode, selection.start, true); if (!nodeToBalance) { return selection; } if (nodeToBalance.close) { const entireNodeSelected = selection.start.isEqual(nodeToBalance.start) && selection.end.isEqual(nodeToBalance.end); const startInOpenTag = selection.start.isAfter(nodeToBalance.open.start) && selection.start.isBefore(nodeToBalance.open.end); const startInCloseTag = selection.start.isAfter(nodeToBalance.close.start) && selection.start.isBefore(nodeToBalance.close.end); if (entireNodeSelected || startInOpenTag || startInCloseTag) { return new vscode.Selection(nodeToBalance.open.end, nodeToBalance.close.start); } } if (!nodeToBalance.firstChild) { return selection; } if (selection.start.isEqual(nodeToBalance.firstChild.start) && selection.end.isEqual(nodeToBalance.firstChild.end) && nodeToBalance.firstChild.close) { return new vscode.Selection(nodeToBalance.firstChild.open.end, nodeToBalance.firstChild.close.start); } return new vscode.Selection(nodeToBalance.firstChild.start, nodeToBalance.firstChild.end); } function areSameSelections(a: vscode.Selection[], b: vscode.Selection[]): boolean { if (a.length !== b.length) { return false; } for (let i = 0; i < a.length; i++) { if (!a[i].isEqual(b[i])) { return false; } } return true; }
extensions/emmet/src/balance.ts
0
https://github.com/microsoft/vscode/commit/8046438bb13cc424399978a895530f9076a7045e
[ 0.00017830036813393235, 0.0001740958687150851, 0.0001702500449027866, 0.00017473632760811597, 0.0000020487182155193295 ]
{ "id": 0, "code_window": [ "\t\"description\": \"Configures an attached to container\",\n", "\t\"allowComments\": true,\n", "\t\"type\": \"object\",\n", "\t\"additionalProperties\": false,\n", "\t\"definitions\": {\n", "\t\t\"attachContainer\": {\n", "\t\t\t\"type\": \"object\",\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "extensions/configuration-editing/schemas/attachContainer.schema.json", "type": "replace", "edit_start_line_idx": 5 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as strings from 'vs/base/common/strings'; import { Range } from 'vs/editor/common/core/range'; import { LanguageIdentifier } from 'vs/editor/common/modes'; import { CharacterPair } from 'vs/editor/common/modes/languageConfiguration'; interface InternalBracket { open: string[]; close: string[]; } export class RichEditBracket { _richEditBracketBrand: void; readonly languageIdentifier: LanguageIdentifier; readonly index: number; readonly open: string[]; readonly close: string[]; readonly forwardRegex: RegExp; readonly reversedRegex: RegExp; private readonly _openSet: Set<string>; private readonly _closeSet: Set<string>; constructor(languageIdentifier: LanguageIdentifier, index: number, open: string[], close: string[], forwardRegex: RegExp, reversedRegex: RegExp) { this.languageIdentifier = languageIdentifier; this.index = index; this.open = open; this.close = close; this.forwardRegex = forwardRegex; this.reversedRegex = reversedRegex; this._openSet = RichEditBracket._toSet(this.open); this._closeSet = RichEditBracket._toSet(this.close); } public isOpen(text: string) { return this._openSet.has(text); } public isClose(text: string) { return this._closeSet.has(text); } private static _toSet(arr: string[]): Set<string> { const result = new Set<string>(); for (const element of arr) { result.add(element); } return result; } } function groupFuzzyBrackets(brackets: CharacterPair[]): InternalBracket[] { const N = brackets.length; brackets = brackets.map(b => [b[0].toLowerCase(), b[1].toLowerCase()]); const group: number[] = []; for (let i = 0; i < N; i++) { group[i] = i; } const areOverlapping = (a: CharacterPair, b: CharacterPair) => { const [aOpen, aClose] = a; const [bOpen, bClose] = b; return (aOpen === bOpen || aOpen === bClose || aClose === bOpen || aClose === bClose); }; const mergeGroups = (g1: number, g2: number) => { const newG = Math.min(g1, g2); const oldG = Math.max(g1, g2); for (let i = 0; i < N; i++) { if (group[i] === oldG) { group[i] = newG; } } }; // group together brackets that have the same open or the same close sequence for (let i = 0; i < N; i++) { const a = brackets[i]; for (let j = i + 1; j < N; j++) { const b = brackets[j]; if (areOverlapping(a, b)) { mergeGroups(group[i], group[j]); } } } const result: InternalBracket[] = []; for (let g = 0; g < N; g++) { let currentOpen: string[] = []; let currentClose: string[] = []; for (let i = 0; i < N; i++) { if (group[i] === g) { const [open, close] = brackets[i]; currentOpen.push(open); currentClose.push(close); } } if (currentOpen.length > 0) { result.push({ open: currentOpen, close: currentClose }); } } return result; } export class RichEditBrackets { _richEditBracketsBrand: void; public readonly brackets: RichEditBracket[]; public readonly forwardRegex: RegExp; public readonly reversedRegex: RegExp; public readonly maxBracketLength: number; public readonly textIsBracket: { [text: string]: RichEditBracket; }; public readonly textIsOpenBracket: { [text: string]: boolean; }; constructor(languageIdentifier: LanguageIdentifier, _brackets: CharacterPair[]) { const brackets = groupFuzzyBrackets(_brackets); this.brackets = brackets.map((b, index) => { return new RichEditBracket( languageIdentifier, index, b.open, b.close, getRegexForBracketPair(b.open, b.close, brackets, index), getReversedRegexForBracketPair(b.open, b.close, brackets, index) ); }); this.forwardRegex = getRegexForBrackets(this.brackets); this.reversedRegex = getReversedRegexForBrackets(this.brackets); this.textIsBracket = {}; this.textIsOpenBracket = {}; this.maxBracketLength = 0; for (const bracket of this.brackets) { for (const open of bracket.open) { this.textIsBracket[open] = bracket; this.textIsOpenBracket[open] = true; this.maxBracketLength = Math.max(this.maxBracketLength, open.length); } for (const close of bracket.close) { this.textIsBracket[close] = bracket; this.textIsOpenBracket[close] = false; this.maxBracketLength = Math.max(this.maxBracketLength, close.length); } } } } function collectSuperstrings(str: string, brackets: InternalBracket[], currentIndex: number, dest: string[]): void { for (let i = 0, len = brackets.length; i < len; i++) { if (i === currentIndex) { continue; } const bracket = brackets[i]; for (const open of bracket.open) { if (open.indexOf(str) >= 0) { dest.push(open); } } for (const close of bracket.close) { if (close.indexOf(str) >= 0) { dest.push(close); } } } } function lengthcmp(a: string, b: string) { return a.length - b.length; } function unique(arr: string[]): string[] { if (arr.length <= 1) { return arr; } const result: string[] = []; const seen = new Set<string>(); for (const element of arr) { if (seen.has(element)) { continue; } result.push(element); seen.add(element); } return result; } function getRegexForBracketPair(open: string[], close: string[], brackets: InternalBracket[], currentIndex: number): RegExp { // search in all brackets for other brackets that are a superstring of these brackets let pieces: string[] = []; pieces = pieces.concat(open); pieces = pieces.concat(close); for (let i = 0, len = pieces.length; i < len; i++) { collectSuperstrings(pieces[i], brackets, currentIndex, pieces); } pieces = unique(pieces); pieces.sort(lengthcmp); pieces.reverse(); return createBracketOrRegExp(pieces); } function getReversedRegexForBracketPair(open: string[], close: string[], brackets: InternalBracket[], currentIndex: number): RegExp { // search in all brackets for other brackets that are a superstring of these brackets let pieces: string[] = []; pieces = pieces.concat(open); pieces = pieces.concat(close); for (let i = 0, len = pieces.length; i < len; i++) { collectSuperstrings(pieces[i], brackets, currentIndex, pieces); } pieces = unique(pieces); pieces.sort(lengthcmp); pieces.reverse(); return createBracketOrRegExp(pieces.map(toReversedString)); } function getRegexForBrackets(brackets: RichEditBracket[]): RegExp { let pieces: string[] = []; for (const bracket of brackets) { for (const open of bracket.open) { pieces.push(open); } for (const close of bracket.close) { pieces.push(close); } } pieces = unique(pieces); return createBracketOrRegExp(pieces); } function getReversedRegexForBrackets(brackets: RichEditBracket[]): RegExp { let pieces: string[] = []; for (const bracket of brackets) { for (const open of bracket.open) { pieces.push(open); } for (const close of bracket.close) { pieces.push(close); } } pieces = unique(pieces); return createBracketOrRegExp(pieces.map(toReversedString)); } function prepareBracketForRegExp(str: string): string { // This bracket pair uses letters like e.g. "begin" - "end" const insertWordBoundaries = (/^[\w ]+$/.test(str)); str = strings.escapeRegExpCharacters(str); return (insertWordBoundaries ? `\\b${str}\\b` : str); } function createBracketOrRegExp(pieces: string[]): RegExp { let regexStr = `(${pieces.map(prepareBracketForRegExp).join(')|(')})`; return strings.createRegExp(regexStr, true); } let toReversedString = (function () { function reverse(str: string): string { let reversedStr = ''; for (let i = str.length - 1; i >= 0; i--) { reversedStr += str.charAt(i); } return reversedStr; } let lastInput: string | null = null; let lastOutput: string | null = null; return function toReversedString(str: string): string { if (lastInput !== str) { lastInput = str; lastOutput = reverse(lastInput); } return lastOutput!; }; })(); export class BracketsUtils { private static _findPrevBracketInText(reversedBracketRegex: RegExp, lineNumber: number, reversedText: string, offset: number): Range | null { let m = reversedText.match(reversedBracketRegex); if (!m) { return null; } let matchOffset = reversedText.length - (m.index || 0); let matchLength = m[0].length; let absoluteMatchOffset = offset + matchOffset; return new Range(lineNumber, absoluteMatchOffset - matchLength + 1, lineNumber, absoluteMatchOffset + 1); } public static findPrevBracketInRange(reversedBracketRegex: RegExp, lineNumber: number, lineText: string, startOffset: number, endOffset: number): Range | null { // Because JS does not support backwards regex search, we search forwards in a reversed string with a reversed regex ;) const reversedLineText = toReversedString(lineText); const reversedSubstr = reversedLineText.substring(lineText.length - endOffset, lineText.length - startOffset); return this._findPrevBracketInText(reversedBracketRegex, lineNumber, reversedSubstr, startOffset); } public static findNextBracketInText(bracketRegex: RegExp, lineNumber: number, text: string, offset: number): Range | null { let m = text.match(bracketRegex); if (!m) { return null; } let matchOffset = m.index || 0; let matchLength = m[0].length; if (matchLength === 0) { return null; } let absoluteMatchOffset = offset + matchOffset; return new Range(lineNumber, absoluteMatchOffset + 1, lineNumber, absoluteMatchOffset + 1 + matchLength); } public static findNextBracketInRange(bracketRegex: RegExp, lineNumber: number, lineText: string, startOffset: number, endOffset: number): Range | null { const substr = lineText.substring(startOffset, endOffset); return this.findNextBracketInText(bracketRegex, lineNumber, substr, startOffset); } }
src/vs/editor/common/modes/supports/richEditBrackets.ts
0
https://github.com/microsoft/vscode/commit/8046438bb13cc424399978a895530f9076a7045e
[ 0.0002412325848126784, 0.00017685568309389055, 0.00016898241301532835, 0.00017476212815381587, 0.000011978789189015515 ]
{ "id": 0, "code_window": [ "\t\"description\": \"Configures an attached to container\",\n", "\t\"allowComments\": true,\n", "\t\"type\": \"object\",\n", "\t\"additionalProperties\": false,\n", "\t\"definitions\": {\n", "\t\t\"attachContainer\": {\n", "\t\t\t\"type\": \"object\",\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "extensions/configuration-editing/schemas/attachContainer.schema.json", "type": "replace", "edit_start_line_idx": 5 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./messageController'; import * as nls from 'vs/nls'; import { TimeoutTimer } from 'vs/base/common/async'; import { KeyCode } from 'vs/base/common/keyCodes'; import { IDisposable, Disposable, DisposableStore, MutableDisposable } from 'vs/base/common/lifecycle'; import { alert } from 'vs/base/browser/ui/aria/aria'; import { Range } from 'vs/editor/common/core/range'; import { IEditorContribution, ScrollType } from 'vs/editor/common/editorCommon'; import { registerEditorContribution, EditorCommand, registerEditorCommand } from 'vs/editor/browser/editorExtensions'; import { ICodeEditor, IContentWidget, IContentWidgetPosition, ContentWidgetPositionPreference } from 'vs/editor/browser/editorBrowser'; import { IContextKeyService, RawContextKey, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { IPosition } from 'vs/editor/common/core/position'; import { registerThemingParticipant, HIGH_CONTRAST } from 'vs/platform/theme/common/themeService'; import { inputValidationInfoBorder, inputValidationInfoBackground, inputValidationInfoForeground } from 'vs/platform/theme/common/colorRegistry'; import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; export class MessageController extends Disposable implements IEditorContribution { public static readonly ID = 'editor.contrib.messageController'; static readonly MESSAGE_VISIBLE = new RawContextKey<boolean>('messageVisible', false); static get(editor: ICodeEditor): MessageController { return editor.getContribution<MessageController>(MessageController.ID); } private readonly closeTimeout = 3000; // close after 3s private readonly _editor: ICodeEditor; private readonly _visible: IContextKey<boolean>; private readonly _messageWidget = this._register(new MutableDisposable<MessageWidget>()); private readonly _messageListeners = this._register(new DisposableStore()); constructor( editor: ICodeEditor, @IContextKeyService contextKeyService: IContextKeyService ) { super(); this._editor = editor; this._visible = MessageController.MESSAGE_VISIBLE.bindTo(contextKeyService); this._register(this._editor.onDidAttemptReadOnlyEdit(() => this._onDidAttemptReadOnlyEdit())); } dispose(): void { super.dispose(); this._visible.reset(); } isVisible() { return this._visible.get(); } showMessage(message: string, position: IPosition): void { alert(message); this._visible.set(true); this._messageWidget.clear(); this._messageListeners.clear(); this._messageWidget.value = new MessageWidget(this._editor, position, message); // close on blur, cursor, model change, dispose this._messageListeners.add(this._editor.onDidBlurEditorText(() => this.closeMessage())); this._messageListeners.add(this._editor.onDidChangeCursorPosition(() => this.closeMessage())); this._messageListeners.add(this._editor.onDidDispose(() => this.closeMessage())); this._messageListeners.add(this._editor.onDidChangeModel(() => this.closeMessage())); this._messageListeners.add(new TimeoutTimer(() => this.closeMessage(), this.closeTimeout)); // close on mouse move let bounds: Range; this._messageListeners.add(this._editor.onMouseMove(e => { // outside the text area if (!e.target.position) { return; } if (!bounds) { // define bounding box around position and first mouse occurance bounds = new Range(position.lineNumber - 3, 1, e.target.position.lineNumber + 3, 1); } else if (!bounds.containsPosition(e.target.position)) { // check if position is still in bounds this.closeMessage(); } })); } closeMessage(): void { this._visible.reset(); this._messageListeners.clear(); if (this._messageWidget.value) { this._messageListeners.add(MessageWidget.fadeOut(this._messageWidget.value)); } } private _onDidAttemptReadOnlyEdit(): void { if (this._editor.hasModel()) { this.showMessage(nls.localize('editor.readonly', "Cannot edit in read-only editor"), this._editor.getPosition()); } } } const MessageCommand = EditorCommand.bindToContribution<MessageController>(MessageController.get); registerEditorCommand(new MessageCommand({ id: 'leaveEditorMessage', precondition: MessageController.MESSAGE_VISIBLE, handler: c => c.closeMessage(), kbOpts: { weight: KeybindingWeight.EditorContrib + 30, primary: KeyCode.Escape } })); class MessageWidget implements IContentWidget { // Editor.IContentWidget.allowEditorOverflow readonly allowEditorOverflow = true; readonly suppressMouseDown = false; private readonly _editor: ICodeEditor; private readonly _position: IPosition; private readonly _domNode: HTMLDivElement; static fadeOut(messageWidget: MessageWidget): IDisposable { let handle: any; const dispose = () => { messageWidget.dispose(); clearTimeout(handle); messageWidget.getDomNode().removeEventListener('animationend', dispose); }; handle = setTimeout(dispose, 110); messageWidget.getDomNode().addEventListener('animationend', dispose); messageWidget.getDomNode().classList.add('fadeOut'); return { dispose }; } constructor(editor: ICodeEditor, { lineNumber, column }: IPosition, text: string) { this._editor = editor; this._editor.revealLinesInCenterIfOutsideViewport(lineNumber, lineNumber, ScrollType.Smooth); this._position = { lineNumber, column: column - 1 }; this._domNode = document.createElement('div'); this._domNode.classList.add('monaco-editor-overlaymessage'); const message = document.createElement('div'); message.classList.add('message'); message.textContent = text; this._domNode.appendChild(message); const anchor = document.createElement('div'); anchor.classList.add('anchor'); this._domNode.appendChild(anchor); this._editor.addContentWidget(this); this._domNode.classList.add('fadeIn'); } dispose() { this._editor.removeContentWidget(this); } getId(): string { return 'messageoverlay'; } getDomNode(): HTMLElement { return this._domNode; } getPosition(): IContentWidgetPosition { return { position: this._position, preference: [ContentWidgetPositionPreference.ABOVE, ContentWidgetPositionPreference.BELOW] }; } } registerEditorContribution(MessageController.ID, MessageController); registerThemingParticipant((theme, collector) => { const border = theme.getColor(inputValidationInfoBorder); if (border) { let borderWidth = theme.type === HIGH_CONTRAST ? 2 : 1; collector.addRule(`.monaco-editor .monaco-editor-overlaymessage .anchor { border-top-color: ${border}; }`); collector.addRule(`.monaco-editor .monaco-editor-overlaymessage .message { border: ${borderWidth}px solid ${border}; }`); } const background = theme.getColor(inputValidationInfoBackground); if (background) { collector.addRule(`.monaco-editor .monaco-editor-overlaymessage .message { background-color: ${background}; }`); } const foreground = theme.getColor(inputValidationInfoForeground); if (foreground) { collector.addRule(`.monaco-editor .monaco-editor-overlaymessage .message { color: ${foreground}; }`); } });
src/vs/editor/contrib/message/messageController.ts
0
https://github.com/microsoft/vscode/commit/8046438bb13cc424399978a895530f9076a7045e
[ 0.0001791075337678194, 0.00017274488345719874, 0.00016610242892056704, 0.00017315338482148945, 0.000003433239953665179 ]
{ "id": 1, "code_window": [ "\t\"definitions\": {\n", "\t\t\"attachContainer\": {\n", "\t\t\t\"type\": \"object\",\n", "\t\t\t\"additionalProperties\": false,\n", "\t\t\t\"properties\": {\n", "\t\t\t\t\"workspaceFolder\": {\n", "\t\t\t\t\t\"type\": \"string\",\n", "\t\t\t\t\t\"description\": \"The path of the workspace folder inside the container.\"\n", "\t\t\t\t},\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "extensions/configuration-editing/schemas/attachContainer.schema.json", "type": "replace", "edit_start_line_idx": 9 }
{ "$schema": "http://json-schema.org/draft-07/schema#", "description": "Defines a dev container", "allowComments": true, "type": "object", "additionalProperties": false, "definitions": { "devContainerCommon": { "type": "object", "additionalProperties": false, "properties": { "name": { "type": "string", "description": "A name to show for the workspace folder." }, "extensions": { "type": "array", "description": "An array of extensions that should be installed into the container.", "items": { "type": "string", "pattern": "^([a-z0-9A-Z][a-z0-9\\-A-Z]*)\\.([a-z0-9A-Z][a-z0-9\\-A-Z]*)$", "errorMessage": "Expected format '${publisher}.${name}'. Example: 'vscode.csharp'." } }, "settings": { "$ref": "vscode://schemas/settings/machine", "description": "Machine specific settings that should be copied into the container." }, "forwardPorts": { "type": "array", "description": "Ports that are forwarded from the container to the local machine.", "items": { "type": "integer" } }, "remoteEnv": { "type": "object", "additionalProperties": { "type": [ "string", "null" ] }, "description": "Remote environment variables." }, "remoteUser": { "type": "string", "description": "The user VS Code Server will be started with. The default is the same user as the container." }, "postCreateCommand": { "type": [ "string", "array" ], "description": "A command to run after creating the container. If this is a single string, it will be run in a shell. If this is an array of strings, it will be run as a single command without shell.", "items": { "type": "string" } }, "devPort": { "type": "integer", "description": "The port VS Code can use to connect to its backend." } } }, "nonComposeBase": { "type": "object", "additionalProperties": false, "properties": { "appPort": { "type": [ "integer", "string", "array" ], "description": "Application ports that are exposed by the container. This can be a single port or an array of ports. Each port can be a number or a string. A number is mapped to the same port on the host. A string is passed to Docker unchanged and can be used to map ports differently, e.g. \"8000:8010\".", "items": { "type": [ "integer", "string" ] } }, "containerEnv": { "type": "object", "additionalProperties": { "type": "string" }, "description": "Container environment variables." }, "containerUser": { "type": "string", "description": "The user the container will be started with. The default is the user on the Docker image." }, "updateRemoteUserUID": { "type": "boolean", "description": "Controls whether on Linux the container's user should be updated with the local user's UID and GID. On by default." }, "mounts": { "type": "array", "description": "Mount points to set up when creating the container. See Docker's documentation for the --mount option for the supported syntax.", "items": { "type": "string" } }, "runArgs": { "type": "array", "description": "The arguments required when starting in the container.", "items": { "type": "string" } }, "shutdownAction": { "type": "string", "enum": [ "none", "stopContainer" ], "description": "Action to take when the VS Code window is closed. The default is to stop the container." }, "overrideCommand": { "type": "boolean", "description": "Whether to overwrite the command specified in the image. The default is true." }, "workspaceFolder": { "type": "string", "description": "The path of the workspace folder inside the container." }, "workspaceMount": { "type": "string", "description": "The --mount parameter for docker run. The default is to mount the project folder at /workspaces/$project." } } }, "dockerFileContainer": { "type": "object", "additionalProperties": false, "properties": { "dockerFile": { "type": "string", "description": "The location of the Dockerfile that defines the contents of the container. The path is relative to the folder containing the `devcontainer.json` file." }, "context": { "type": "string", "description": "The location of the context folder for building the Docker image. The path is relative to the folder containing the `devcontainer.json` file." } }, "required": [ "dockerFile" ] }, "imageContainer": { "type": "object", "additionalProperties": false, "properties": { "image": { "type": "string", "description": "The docker image that will be used to create the container." } }, "required": [ "image" ] }, "composeContainer": { "type": "object", "additionalProperties": false, "properties": { "dockerComposeFile": { "type": [ "string", "array" ], "description": "The name of the docker-compose file(s) used to start the services.", "items": { "type": "string" } }, "service": { "type": "string", "description": "The service you want to work on." }, "runServices": { "type": "array", "description": "An array of services that should be started and stopped.", "items": { "type": "string" } }, "workspaceFolder": { "type": "string", "description": "The path of the workspace folder inside the container." }, "shutdownAction": { "type": "string", "enum": [ "none", "stopCompose" ], "description": "Action to take when the VS Code window is closed. The default is to stop the containers." } }, "required": [ "dockerComposeFile", "service", "workspaceFolder" ] } }, "allOf": [ { "oneOf": [ { "allOf": [ { "oneOf": [ { "$ref": "#/definitions/dockerFileContainer" }, { "$ref": "#/definitions/imageContainer" } ] }, { "$ref": "#/definitions/nonComposeBase" } ] }, { "$ref": "#/definitions/composeContainer" } ] }, { "$ref": "#/definitions/devContainerCommon" } ] }
extensions/configuration-editing/schemas/devContainer.schema.json
1
https://github.com/microsoft/vscode/commit/8046438bb13cc424399978a895530f9076a7045e
[ 0.22706206142902374, 0.011026513762772083, 0.0001647572498768568, 0.00025455764262005687, 0.04538695886731148 ]
{ "id": 1, "code_window": [ "\t\"definitions\": {\n", "\t\t\"attachContainer\": {\n", "\t\t\t\"type\": \"object\",\n", "\t\t\t\"additionalProperties\": false,\n", "\t\t\t\"properties\": {\n", "\t\t\t\t\"workspaceFolder\": {\n", "\t\t\t\t\t\"type\": \"string\",\n", "\t\t\t\t\t\"description\": \"The path of the workspace folder inside the container.\"\n", "\t\t\t\t},\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "extensions/configuration-editing/schemas/attachContainer.schema.json", "type": "replace", "edit_start_line_idx": 9 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; import { getNodesInBetween, getNode, getHtmlNode, parseDocument, sameNodes, isStyleSheet, validate } from './util'; import { Node, Stylesheet, Rule } from 'EmmetNode'; import parseStylesheet from '@emmetio/css-parser'; import { DocumentStreamReader } from './bufferStream'; const startCommentStylesheet = '/*'; const endCommentStylesheet = '*/'; const startCommentHTML = '<!--'; const endCommentHTML = '-->'; export function toggleComment(): Thenable<boolean> | undefined { if (!validate() || !vscode.window.activeTextEditor) { return; } const editor = vscode.window.activeTextEditor; let rootNode = parseDocument(editor.document); if (!rootNode) { return; } return editor.edit(editBuilder => { let allEdits: vscode.TextEdit[][] = []; editor.selections.reverse().forEach(selection => { let edits = isStyleSheet(editor.document.languageId) ? toggleCommentStylesheet(selection, <Stylesheet>rootNode) : toggleCommentHTML(editor.document, selection, rootNode!); if (edits.length > 0) { allEdits.push(edits); } }); // Apply edits in order so we can skip nested ones. allEdits.sort((arr1, arr2) => { let result = arr1[0].range.start.line - arr2[0].range.start.line; return result === 0 ? arr1[0].range.start.character - arr2[0].range.start.character : result; }); let lastEditPosition = new vscode.Position(0, 0); for (const edits of allEdits) { if (edits[0].range.end.isAfterOrEqual(lastEditPosition)) { edits.forEach(x => { editBuilder.replace(x.range, x.newText); lastEditPosition = x.range.end; }); } } }); } function toggleCommentHTML(document: vscode.TextDocument, selection: vscode.Selection, rootNode: Node): vscode.TextEdit[] { const selectionStart = selection.isReversed ? selection.active : selection.anchor; const selectionEnd = selection.isReversed ? selection.anchor : selection.active; let startNode = getHtmlNode(document, rootNode, selectionStart, true); let endNode = getHtmlNode(document, rootNode, selectionEnd, true); if (!startNode || !endNode) { return []; } if (sameNodes(startNode, endNode) && startNode.name === 'style' && startNode.open.end.isBefore(selectionStart) && startNode.close.start.isAfter(selectionEnd)) { let buffer = new DocumentStreamReader(document, startNode.open.end, new vscode.Range(startNode.open.end, startNode.close.start)); let cssRootNode = parseStylesheet(buffer); return toggleCommentStylesheet(selection, cssRootNode); } let allNodes: Node[] = getNodesInBetween(startNode, endNode); let edits: vscode.TextEdit[] = []; allNodes.forEach(node => { edits = edits.concat(getRangesToUnCommentHTML(node, document)); }); if (startNode.type === 'comment') { return edits; } edits.push(new vscode.TextEdit(new vscode.Range(allNodes[0].start, allNodes[0].start), startCommentHTML)); edits.push(new vscode.TextEdit(new vscode.Range(allNodes[allNodes.length - 1].end, allNodes[allNodes.length - 1].end), endCommentHTML)); return edits; } function getRangesToUnCommentHTML(node: Node, document: vscode.TextDocument): vscode.TextEdit[] { let unCommentTextEdits: vscode.TextEdit[] = []; // If current node is commented, then uncomment and return if (node.type === 'comment') { unCommentTextEdits.push(new vscode.TextEdit(new vscode.Range(node.start, node.start.translate(0, startCommentHTML.length)), '')); unCommentTextEdits.push(new vscode.TextEdit(new vscode.Range(node.end.translate(0, -endCommentHTML.length), node.end), '')); return unCommentTextEdits; } // All children of current node should be uncommented node.children.forEach(childNode => { unCommentTextEdits = unCommentTextEdits.concat(getRangesToUnCommentHTML(childNode, document)); }); return unCommentTextEdits; } function toggleCommentStylesheet(selection: vscode.Selection, rootNode: Stylesheet): vscode.TextEdit[] { let selectionStart = selection.isReversed ? selection.active : selection.anchor; let selectionEnd = selection.isReversed ? selection.anchor : selection.active; let startNode = getNode(rootNode, selectionStart, true); let endNode = getNode(rootNode, selectionEnd, true); if (!selection.isEmpty) { selectionStart = adjustStartNodeCss(startNode, selectionStart, rootNode); selectionEnd = adjustEndNodeCss(endNode, selectionEnd, rootNode); selection = new vscode.Selection(selectionStart, selectionEnd); } else if (startNode) { selectionStart = startNode.start; selectionEnd = startNode.end; selection = new vscode.Selection(selectionStart, selectionEnd); } // Uncomment the comments that intersect with the selection. let rangesToUnComment: vscode.Range[] = []; let edits: vscode.TextEdit[] = []; rootNode.comments.forEach(comment => { let commentRange = new vscode.Range(comment.start, comment.end); if (selection.intersection(commentRange)) { rangesToUnComment.push(commentRange); edits.push(new vscode.TextEdit(new vscode.Range(comment.start, comment.start.translate(0, startCommentStylesheet.length)), '')); edits.push(new vscode.TextEdit(new vscode.Range(comment.end.translate(0, -endCommentStylesheet.length), comment.end), '')); } }); if (edits.length > 0) { return edits; } return [ new vscode.TextEdit(new vscode.Range(selection.start, selection.start), startCommentStylesheet), new vscode.TextEdit(new vscode.Range(selection.end, selection.end), endCommentStylesheet) ]; } function adjustStartNodeCss(node: Node | null, pos: vscode.Position, rootNode: Stylesheet): vscode.Position { for (const comment of rootNode.comments) { let commentRange = new vscode.Range(comment.start, comment.end); if (commentRange.contains(pos)) { return pos; } } if (!node) { return pos; } if (node.type === 'property') { return node.start; } const rule = <Rule>node; if (pos.isBefore(rule.contentStartToken.end) || !rule.firstChild) { return rule.start; } if (pos.isBefore(rule.firstChild.start)) { return pos; } let newStartNode = rule.firstChild; while (newStartNode.nextSibling && pos.isAfter(newStartNode.end)) { newStartNode = newStartNode.nextSibling; } return newStartNode.start; } function adjustEndNodeCss(node: Node | null, pos: vscode.Position, rootNode: Stylesheet): vscode.Position { for (const comment of rootNode.comments) { let commentRange = new vscode.Range(comment.start, comment.end); if (commentRange.contains(pos)) { return pos; } } if (!node) { return pos; } if (node.type === 'property') { return node.end; } const rule = <Rule>node; if (pos.isEqual(rule.contentEndToken.end) || !rule.firstChild) { return rule.end; } if (pos.isAfter(rule.children[rule.children.length - 1].end)) { return pos; } let newEndNode = rule.children[rule.children.length - 1]; while (newEndNode.previousSibling && pos.isBefore(newEndNode.start)) { newEndNode = newEndNode.previousSibling; } return newEndNode.end; }
extensions/emmet/src/toggleComment.ts
0
https://github.com/microsoft/vscode/commit/8046438bb13cc424399978a895530f9076a7045e
[ 0.0001762901956681162, 0.00017291121184825897, 0.00016788164793979377, 0.00017342009232379496, 0.0000017856144722827594 ]
{ "id": 1, "code_window": [ "\t\"definitions\": {\n", "\t\t\"attachContainer\": {\n", "\t\t\t\"type\": \"object\",\n", "\t\t\t\"additionalProperties\": false,\n", "\t\t\t\"properties\": {\n", "\t\t\t\t\"workspaceFolder\": {\n", "\t\t\t\t\t\"type\": \"string\",\n", "\t\t\t\t\t\"description\": \"The path of the workspace folder inside the container.\"\n", "\t\t\t\t},\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "extensions/configuration-editing/schemas/attachContainer.schema.json", "type": "replace", "edit_start_line_idx": 9 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { URI } from 'vs/base/common/uri'; import { Event, IWaitUntil } from 'vs/base/common/event'; import { IDisposable } from 'vs/base/common/lifecycle'; import { IEncodingSupport, IModeSupport, ISaveOptions, IRevertOptions, SaveReason } from 'vs/workbench/common/editor'; import { IBaseStatWithMetadata, IFileStatWithMetadata, IReadFileOptions, IWriteFileOptions, FileOperationError, FileOperationResult, FileOperation } from 'vs/platform/files/common/files'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { ITextEditorModel } from 'vs/editor/common/services/resolverService'; import { ITextBufferFactory, ITextModel, ITextSnapshot } from 'vs/editor/common/model'; import { VSBuffer, VSBufferReadable } from 'vs/base/common/buffer'; import { isUndefinedOrNull } from 'vs/base/common/types'; import { isNative } from 'vs/base/common/platform'; import { IWorkingCopy } from 'vs/workbench/services/workingCopy/common/workingCopyService'; import { IUntitledTextEditorModelManager } from 'vs/workbench/services/untitled/common/untitledTextEditorService'; export const ITextFileService = createDecorator<ITextFileService>('textFileService'); export interface ITextFileService extends IDisposable { _serviceBrand: undefined; /** * An event that is fired before attempting a certain file operation. */ readonly onWillRunOperation: Event<FileOperationWillRunEvent>; /** * An event that is fired after a file operation has been performed. */ readonly onDidRunOperation: Event<FileOperationDidRunEvent>; /** * Access to the manager of text file editor models providing further * methods to work with them. */ readonly files: ITextFileEditorModelManager; /** * Access to the manager of untitled text editor models providing further * methods to work with them. */ readonly untitled: IUntitledTextEditorModelManager; /** * Helper to determine encoding for resources. */ readonly encoding: IResourceEncodings; /** * The handler that should be called when saving fails. Can be overridden * to handle save errors in a custom way. */ saveErrorHandler: ISaveErrorHandler; /** * The save participant if any. By default, no save participant is registered. */ saveParticipant: ISaveParticipant | undefined; /** * A resource is dirty if it has unsaved changes or is an untitled file not yet saved. * * @param resource the resource to check for being dirty */ isDirty(resource: URI): boolean; /** * Saves the resource. * * @param resource the resource to save * @param options optional save options * @return Path of the saved resource or undefined if canceled. */ save(resource: URI, options?: ITextFileSaveOptions): Promise<URI | undefined>; /** * Saves the provided resource asking the user for a file name or using the provided one. * * @param resource the resource to save as. * @param targetResource the optional target to save to. * @param options optional save options * @return Path of the saved resource or undefined if canceled. */ saveAs(resource: URI, targetResource?: URI, options?: ITextFileSaveOptions): Promise<URI | undefined>; /** * Reverts the provided resource. * * @param resource the resource of the file to revert. * @param force to force revert even when the file is not dirty */ revert(resource: URI, options?: IRevertOptions): Promise<boolean>; /** * Read the contents of a file identified by the resource. */ read(resource: URI, options?: IReadTextFileOptions): Promise<ITextFileContent>; /** * Read the contents of a file identified by the resource as stream. */ readStream(resource: URI, options?: IReadTextFileOptions): Promise<ITextFileStreamContent>; /** * Update a file with given contents. */ write(resource: URI, value: string | ITextSnapshot, options?: IWriteTextFileOptions): Promise<IFileStatWithMetadata>; /** * Create a file. If the file exists it will be overwritten with the contents if * the options enable to overwrite. */ create(resource: URI, contents?: string | ITextSnapshot, options?: { overwrite?: boolean }): Promise<IFileStatWithMetadata>; /** * Move a file. If the file is dirty, its contents will be preserved and restored. */ move(source: URI, target: URI, overwrite?: boolean): Promise<IFileStatWithMetadata>; /** * Copy a file. If the file is dirty, its contents will be preserved and restored. */ copy(source: URI, target: URI, overwrite?: boolean): Promise<IFileStatWithMetadata>; /** * Delete a file. If the file is dirty, it will get reverted and then deleted from disk. */ delete(resource: URI, options?: { useTrash?: boolean, recursive?: boolean }): Promise<void>; } export interface FileOperationWillRunEvent extends IWaitUntil { operation: FileOperation; target: URI; source?: URI; } export class FileOperationDidRunEvent { constructor( readonly operation: FileOperation, readonly target: URI, readonly source?: URI | undefined ) { } } export interface IReadTextFileOptions extends IReadFileOptions { /** * The optional acceptTextOnly parameter allows to fail this request early if the file * contents are not textual. */ acceptTextOnly?: boolean; /** * The optional encoding parameter allows to specify the desired encoding when resolving * the contents of the file. */ encoding?: string; /** * The optional guessEncoding parameter allows to guess encoding from content of the file. */ autoGuessEncoding?: boolean; } export interface IWriteTextFileOptions extends IWriteFileOptions { /** * The encoding to use when updating a file. */ encoding?: string; /** * If set to true, will enforce the selected encoding and not perform any detection using BOMs. */ overwriteEncoding?: boolean; /** * Whether to overwrite a file even if it is readonly. */ overwriteReadonly?: boolean; /** * Whether to write to the file as elevated (admin) user. When setting this option a prompt will * ask the user to authenticate as super user. */ writeElevated?: boolean; } export const enum TextFileOperationResult { FILE_IS_BINARY } export class TextFileOperationError extends FileOperationError { constructor(message: string, public textFileOperationResult: TextFileOperationResult, public options?: IReadTextFileOptions & IWriteTextFileOptions) { super(message, FileOperationResult.FILE_OTHER_ERROR); } static isTextFileOperationError(obj: unknown): obj is TextFileOperationError { return obj instanceof Error && !isUndefinedOrNull((obj as TextFileOperationError).textFileOperationResult); } } export interface IResourceEncodings { getPreferredWriteEncoding(resource: URI, preferredEncoding?: string): IResourceEncoding; } export interface IResourceEncoding { encoding: string; hasBOM: boolean; } /** * The save error handler can be installed on the text file editor model to install code that executes when save errors occur. */ export interface ISaveErrorHandler { /** * Called whenever a save fails. */ onSaveError(error: Error, model: ITextFileEditorModel): void; } export interface ISaveParticipant { /** * Participate in a save of a model. Allows to change the model before it is being saved to disk. */ participate(model: IResolvedTextFileEditorModel, env: { reason: SaveReason }): Promise<void>; } /** * States the text file editor model can be in. */ export const enum ModelState { /** * A model is saved. */ SAVED, /** * A model is dirty. */ DIRTY, /** * A model is currently being saved but this operation has not completed yet. */ PENDING_SAVE, /** * A model is in conflict mode when changes cannot be saved because the * underlying file has changed. Models in conflict mode are always dirty. */ CONFLICT, /** * A model is in orphan state when the underlying file has been deleted. */ ORPHAN, /** * Any error that happens during a save that is not causing the CONFLICT state. * Models in error mode are always dirty. */ ERROR } export interface ITextFileOperationResult { results: IResult[]; } export interface IResult { source: URI; target?: URI; error?: boolean; } export const enum LoadReason { EDITOR = 1, REFERENCE = 2, OTHER = 3 } interface IBaseTextFileContent extends IBaseStatWithMetadata { /** * The encoding of the content if known. */ encoding: string; } export interface ITextFileContent extends IBaseTextFileContent { /** * The content of a text file. */ value: string; } export interface ITextFileStreamContent extends IBaseTextFileContent { /** * The line grouped content of a text file. */ value: ITextBufferFactory; } export interface IModelLoadOrCreateOptions { /** * Context why the model is being loaded or created. */ reason?: LoadReason; /** * The language mode to use for the model text content. */ mode?: string; /** * The encoding to use when resolving the model text content. */ encoding?: string; /** * If the model was already loaded before, allows to trigger * a reload of it to fetch the latest contents: * - async: resolve() will return immediately and trigger * a reload that will run in the background. * - sync: resolve() will only return resolved when the * model has finished reloading. */ reload?: { async: boolean }; /** * Allow to load a model even if we think it is a binary file. */ allowBinary?: boolean; } export interface ITextFileModelSaveEvent { model: ITextFileEditorModel; reason: SaveReason; } export interface ITextFileModelLoadEvent { model: ITextFileEditorModel; reason: LoadReason; } export interface ITextFileEditorModelManager { readonly onDidLoad: Event<ITextFileModelLoadEvent>; readonly onDidChangeDirty: Event<ITextFileEditorModel>; readonly onDidSaveError: Event<ITextFileEditorModel>; readonly onDidSave: Event<ITextFileModelSaveEvent>; readonly onDidRevert: Event<ITextFileEditorModel>; readonly onDidChangeEncoding: Event<ITextFileEditorModel>; readonly onDidChangeOrphaned: Event<ITextFileEditorModel>; get(resource: URI): ITextFileEditorModel | undefined; getAll(): ITextFileEditorModel[]; resolve(resource: URI, options?: IModelLoadOrCreateOptions): Promise<ITextFileEditorModel>; disposeModel(model: ITextFileEditorModel): void; } export interface ITextFileSaveOptions extends ISaveOptions { overwriteReadonly?: boolean; overwriteEncoding?: boolean; writeElevated?: boolean; ignoreModifiedSince?: boolean; ignoreErrorHandler?: boolean; } export interface ILoadOptions { /** * Go to disk bypassing any cache of the model if any. */ forceReadFromDisk?: boolean; /** * Allow to load a model even if we think it is a binary file. */ allowBinary?: boolean; /** * Context why the model is being loaded. */ reason?: LoadReason; } export interface ITextFileEditorModel extends ITextEditorModel, IEncodingSupport, IModeSupport, IWorkingCopy { readonly onDidChangeContent: Event<void>; readonly onDidLoad: Event<LoadReason>; readonly onDidSaveError: Event<void>; readonly onDidSave: Event<SaveReason>; readonly onDidRevert: Event<void>; readonly onDidChangeEncoding: Event<void>; readonly onDidChangeOrphaned: Event<void>; hasState(state: ModelState): boolean; updatePreferredEncoding(encoding: string | undefined): void; save(options?: ITextFileSaveOptions): Promise<boolean>; load(options?: ILoadOptions): Promise<ITextFileEditorModel>; revert(options?: IRevertOptions): Promise<boolean>; isDirty(): this is IResolvedTextFileEditorModel; setDirty(dirty: boolean): void; getMode(): string | undefined; isResolved(): this is IResolvedTextFileEditorModel; isDisposed(): boolean; } export interface IResolvedTextFileEditorModel extends ITextFileEditorModel { readonly textEditorModel: ITextModel; createSnapshot(): ITextSnapshot; } export function snapshotToString(snapshot: ITextSnapshot): string { const chunks: string[] = []; let chunk: string | null; while (typeof (chunk = snapshot.read()) === 'string') { chunks.push(chunk); } return chunks.join(''); } export function stringToSnapshot(value: string): ITextSnapshot { let done = false; return { read(): string | null { if (!done) { done = true; return value; } return null; } }; } export class TextSnapshotReadable implements VSBufferReadable { private preambleHandled = false; constructor(private snapshot: ITextSnapshot, private preamble?: string) { } read(): VSBuffer | null { let value = this.snapshot.read(); // Handle preamble if provided if (!this.preambleHandled) { this.preambleHandled = true; if (typeof this.preamble === 'string') { if (typeof value === 'string') { value = this.preamble + value; } else { value = this.preamble; } } } if (typeof value === 'string') { return VSBuffer.fromString(value); } return null; } } export function toBufferOrReadable(value: string): VSBuffer; export function toBufferOrReadable(value: ITextSnapshot): VSBufferReadable; export function toBufferOrReadable(value: string | ITextSnapshot): VSBuffer | VSBufferReadable; export function toBufferOrReadable(value: string | ITextSnapshot | undefined): VSBuffer | VSBufferReadable | undefined; export function toBufferOrReadable(value: string | ITextSnapshot | undefined): VSBuffer | VSBufferReadable | undefined { if (typeof value === 'undefined') { return undefined; } if (typeof value === 'string') { return VSBuffer.fromString(value); } return new TextSnapshotReadable(value); } export const SUPPORTED_ENCODINGS: { [encoding: string]: { labelLong: string; labelShort: string; order: number; encodeOnly?: boolean; alias?: string } } = // Desktop isNative ? { utf8: { labelLong: 'UTF-8', labelShort: 'UTF-8', order: 1, alias: 'utf8bom' }, utf8bom: { labelLong: 'UTF-8 with BOM', labelShort: 'UTF-8 with BOM', encodeOnly: true, order: 2, alias: 'utf8' }, utf16le: { labelLong: 'UTF-16 LE', labelShort: 'UTF-16 LE', order: 3 }, utf16be: { labelLong: 'UTF-16 BE', labelShort: 'UTF-16 BE', order: 4 }, windows1252: { labelLong: 'Western (Windows 1252)', labelShort: 'Windows 1252', order: 5 }, iso88591: { labelLong: 'Western (ISO 8859-1)', labelShort: 'ISO 8859-1', order: 6 }, iso88593: { labelLong: 'Western (ISO 8859-3)', labelShort: 'ISO 8859-3', order: 7 }, iso885915: { labelLong: 'Western (ISO 8859-15)', labelShort: 'ISO 8859-15', order: 8 }, macroman: { labelLong: 'Western (Mac Roman)', labelShort: 'Mac Roman', order: 9 }, cp437: { labelLong: 'DOS (CP 437)', labelShort: 'CP437', order: 10 }, windows1256: { labelLong: 'Arabic (Windows 1256)', labelShort: 'Windows 1256', order: 11 }, iso88596: { labelLong: 'Arabic (ISO 8859-6)', labelShort: 'ISO 8859-6', order: 12 }, windows1257: { labelLong: 'Baltic (Windows 1257)', labelShort: 'Windows 1257', order: 13 }, iso88594: { labelLong: 'Baltic (ISO 8859-4)', labelShort: 'ISO 8859-4', order: 14 }, iso885914: { labelLong: 'Celtic (ISO 8859-14)', labelShort: 'ISO 8859-14', order: 15 }, windows1250: { labelLong: 'Central European (Windows 1250)', labelShort: 'Windows 1250', order: 16 }, iso88592: { labelLong: 'Central European (ISO 8859-2)', labelShort: 'ISO 8859-2', order: 17 }, cp852: { labelLong: 'Central European (CP 852)', labelShort: 'CP 852', order: 18 }, windows1251: { labelLong: 'Cyrillic (Windows 1251)', labelShort: 'Windows 1251', order: 19 }, cp866: { labelLong: 'Cyrillic (CP 866)', labelShort: 'CP 866', order: 20 }, iso88595: { labelLong: 'Cyrillic (ISO 8859-5)', labelShort: 'ISO 8859-5', order: 21 }, koi8r: { labelLong: 'Cyrillic (KOI8-R)', labelShort: 'KOI8-R', order: 22 }, koi8u: { labelLong: 'Cyrillic (KOI8-U)', labelShort: 'KOI8-U', order: 23 }, iso885913: { labelLong: 'Estonian (ISO 8859-13)', labelShort: 'ISO 8859-13', order: 24 }, windows1253: { labelLong: 'Greek (Windows 1253)', labelShort: 'Windows 1253', order: 25 }, iso88597: { labelLong: 'Greek (ISO 8859-7)', labelShort: 'ISO 8859-7', order: 26 }, windows1255: { labelLong: 'Hebrew (Windows 1255)', labelShort: 'Windows 1255', order: 27 }, iso88598: { labelLong: 'Hebrew (ISO 8859-8)', labelShort: 'ISO 8859-8', order: 28 }, iso885910: { labelLong: 'Nordic (ISO 8859-10)', labelShort: 'ISO 8859-10', order: 29 }, iso885916: { labelLong: 'Romanian (ISO 8859-16)', labelShort: 'ISO 8859-16', order: 30 }, windows1254: { labelLong: 'Turkish (Windows 1254)', labelShort: 'Windows 1254', order: 31 }, iso88599: { labelLong: 'Turkish (ISO 8859-9)', labelShort: 'ISO 8859-9', order: 32 }, windows1258: { labelLong: 'Vietnamese (Windows 1258)', labelShort: 'Windows 1258', order: 33 }, gbk: { labelLong: 'Simplified Chinese (GBK)', labelShort: 'GBK', order: 34 }, gb18030: { labelLong: 'Simplified Chinese (GB18030)', labelShort: 'GB18030', order: 35 }, cp950: { labelLong: 'Traditional Chinese (Big5)', labelShort: 'Big5', order: 36 }, big5hkscs: { labelLong: 'Traditional Chinese (Big5-HKSCS)', labelShort: 'Big5-HKSCS', order: 37 }, shiftjis: { labelLong: 'Japanese (Shift JIS)', labelShort: 'Shift JIS', order: 38 }, eucjp: { labelLong: 'Japanese (EUC-JP)', labelShort: 'EUC-JP', order: 39 }, euckr: { labelLong: 'Korean (EUC-KR)', labelShort: 'EUC-KR', order: 40 }, windows874: { labelLong: 'Thai (Windows 874)', labelShort: 'Windows 874', order: 41 }, iso885911: { labelLong: 'Latin/Thai (ISO 8859-11)', labelShort: 'ISO 8859-11', order: 42 }, koi8ru: { labelLong: 'Cyrillic (KOI8-RU)', labelShort: 'KOI8-RU', order: 43 }, koi8t: { labelLong: 'Tajik (KOI8-T)', labelShort: 'KOI8-T', order: 44 }, gb2312: { labelLong: 'Simplified Chinese (GB 2312)', labelShort: 'GB 2312', order: 45 }, cp865: { labelLong: 'Nordic DOS (CP 865)', labelShort: 'CP 865', order: 46 }, cp850: { labelLong: 'Western European DOS (CP 850)', labelShort: 'CP 850', order: 47 } } : // Web (https://github.com/microsoft/vscode/issues/79275) { utf8: { labelLong: 'UTF-8', labelShort: 'UTF-8', order: 1, alias: 'utf8bom' } };
src/vs/workbench/services/textfile/common/textfiles.ts
0
https://github.com/microsoft/vscode/commit/8046438bb13cc424399978a895530f9076a7045e
[ 0.0004513997118920088, 0.0001747288479236886, 0.00016277194663416594, 0.00017036372446455061, 0.00003227088018320501 ]
{ "id": 1, "code_window": [ "\t\"definitions\": {\n", "\t\t\"attachContainer\": {\n", "\t\t\t\"type\": \"object\",\n", "\t\t\t\"additionalProperties\": false,\n", "\t\t\t\"properties\": {\n", "\t\t\t\t\"workspaceFolder\": {\n", "\t\t\t\t\t\"type\": \"string\",\n", "\t\t\t\t\t\"description\": \"The path of the workspace folder inside the container.\"\n", "\t\t\t\t},\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "extensions/configuration-editing/schemas/attachContainer.schema.json", "type": "replace", "edit_start_line_idx": 9 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { ClassifiedEvent, StrictPropertyCheck, GDPRClassification } from 'vs/platform/telemetry/common/gdprTypings'; export const ITelemetryService = createDecorator<ITelemetryService>('telemetryService'); export interface ITelemetryInfo { sessionId: string; machineId: string; instanceId: string; msftInternal?: boolean; } export interface ITelemetryData { from?: string; target?: string; [key: string]: any; } export interface ITelemetryService { _serviceBrand: undefined; /** * Sends a telemetry event that has been privacy approved. * Do not call this unless you have been given approval. */ publicLog(eventName: string, data?: ITelemetryData, anonymizeFilePaths?: boolean): Promise<void>; publicLog2<E extends ClassifiedEvent<T> = never, T extends GDPRClassification<T> = never>(eventName: string, data?: StrictPropertyCheck<T, E>, anonymizeFilePaths?: boolean): Promise<void>; setEnabled(value: boolean): void; getTelemetryInfo(): Promise<ITelemetryInfo>; isOptedIn: boolean; } // Keys export const instanceStorageKey = 'telemetry.instanceId'; export const currentSessionDateStorageKey = 'telemetry.currentSessionDate'; export const firstSessionDateStorageKey = 'telemetry.firstSessionDate'; export const lastSessionDateStorageKey = 'telemetry.lastSessionDate';
src/vs/platform/telemetry/common/telemetry.ts
0
https://github.com/microsoft/vscode/commit/8046438bb13cc424399978a895530f9076a7045e
[ 0.00017575193487573415, 0.00017307889356743544, 0.00017064774874597788, 0.00017362672952003777, 0.0000017630786715017166 ]
{ "id": 2, "code_window": [ "\t\"$schema\": \"http://json-schema.org/draft-07/schema#\",\n", "\t\"description\": \"Defines a dev container\",\n", "\t\"allowComments\": true,\n", "\t\"type\": \"object\",\n", "\t\"additionalProperties\": false,\n", "\t\"definitions\": {\n", "\t\t\"devContainerCommon\": {\n", "\t\t\t\"type\": \"object\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "extensions/configuration-editing/schemas/devContainer.schema.json", "type": "replace", "edit_start_line_idx": 5 }
{ "$schema": "http://json-schema.org/draft-07/schema#", "description": "Defines a dev container", "allowComments": true, "type": "object", "additionalProperties": false, "definitions": { "devContainerCommon": { "type": "object", "additionalProperties": false, "properties": { "name": { "type": "string", "description": "A name to show for the workspace folder." }, "extensions": { "type": "array", "description": "An array of extensions that should be installed into the container.", "items": { "type": "string", "pattern": "^([a-z0-9A-Z][a-z0-9\\-A-Z]*)\\.([a-z0-9A-Z][a-z0-9\\-A-Z]*)$", "errorMessage": "Expected format '${publisher}.${name}'. Example: 'vscode.csharp'." } }, "settings": { "$ref": "vscode://schemas/settings/machine", "description": "Machine specific settings that should be copied into the container." }, "forwardPorts": { "type": "array", "description": "Ports that are forwarded from the container to the local machine.", "items": { "type": "integer" } }, "remoteEnv": { "type": "object", "additionalProperties": { "type": [ "string", "null" ] }, "description": "Remote environment variables." }, "remoteUser": { "type": "string", "description": "The user VS Code Server will be started with. The default is the same user as the container." }, "postCreateCommand": { "type": [ "string", "array" ], "description": "A command to run after creating the container. If this is a single string, it will be run in a shell. If this is an array of strings, it will be run as a single command without shell.", "items": { "type": "string" } }, "devPort": { "type": "integer", "description": "The port VS Code can use to connect to its backend." } } }, "nonComposeBase": { "type": "object", "additionalProperties": false, "properties": { "appPort": { "type": [ "integer", "string", "array" ], "description": "Application ports that are exposed by the container. This can be a single port or an array of ports. Each port can be a number or a string. A number is mapped to the same port on the host. A string is passed to Docker unchanged and can be used to map ports differently, e.g. \"8000:8010\".", "items": { "type": [ "integer", "string" ] } }, "containerEnv": { "type": "object", "additionalProperties": { "type": "string" }, "description": "Container environment variables." }, "containerUser": { "type": "string", "description": "The user the container will be started with. The default is the user on the Docker image." }, "updateRemoteUserUID": { "type": "boolean", "description": "Controls whether on Linux the container's user should be updated with the local user's UID and GID. On by default." }, "mounts": { "type": "array", "description": "Mount points to set up when creating the container. See Docker's documentation for the --mount option for the supported syntax.", "items": { "type": "string" } }, "runArgs": { "type": "array", "description": "The arguments required when starting in the container.", "items": { "type": "string" } }, "shutdownAction": { "type": "string", "enum": [ "none", "stopContainer" ], "description": "Action to take when the VS Code window is closed. The default is to stop the container." }, "overrideCommand": { "type": "boolean", "description": "Whether to overwrite the command specified in the image. The default is true." }, "workspaceFolder": { "type": "string", "description": "The path of the workspace folder inside the container." }, "workspaceMount": { "type": "string", "description": "The --mount parameter for docker run. The default is to mount the project folder at /workspaces/$project." } } }, "dockerFileContainer": { "type": "object", "additionalProperties": false, "properties": { "dockerFile": { "type": "string", "description": "The location of the Dockerfile that defines the contents of the container. The path is relative to the folder containing the `devcontainer.json` file." }, "context": { "type": "string", "description": "The location of the context folder for building the Docker image. The path is relative to the folder containing the `devcontainer.json` file." } }, "required": [ "dockerFile" ] }, "imageContainer": { "type": "object", "additionalProperties": false, "properties": { "image": { "type": "string", "description": "The docker image that will be used to create the container." } }, "required": [ "image" ] }, "composeContainer": { "type": "object", "additionalProperties": false, "properties": { "dockerComposeFile": { "type": [ "string", "array" ], "description": "The name of the docker-compose file(s) used to start the services.", "items": { "type": "string" } }, "service": { "type": "string", "description": "The service you want to work on." }, "runServices": { "type": "array", "description": "An array of services that should be started and stopped.", "items": { "type": "string" } }, "workspaceFolder": { "type": "string", "description": "The path of the workspace folder inside the container." }, "shutdownAction": { "type": "string", "enum": [ "none", "stopCompose" ], "description": "Action to take when the VS Code window is closed. The default is to stop the containers." } }, "required": [ "dockerComposeFile", "service", "workspaceFolder" ] } }, "allOf": [ { "oneOf": [ { "allOf": [ { "oneOf": [ { "$ref": "#/definitions/dockerFileContainer" }, { "$ref": "#/definitions/imageContainer" } ] }, { "$ref": "#/definitions/nonComposeBase" } ] }, { "$ref": "#/definitions/composeContainer" } ] }, { "$ref": "#/definitions/devContainerCommon" } ] }
extensions/configuration-editing/schemas/devContainer.schema.json
1
https://github.com/microsoft/vscode/commit/8046438bb13cc424399978a895530f9076a7045e
[ 0.9922093152999878, 0.04151085019111633, 0.00016389325901400298, 0.00016856665024533868, 0.19823433458805084 ]
{ "id": 2, "code_window": [ "\t\"$schema\": \"http://json-schema.org/draft-07/schema#\",\n", "\t\"description\": \"Defines a dev container\",\n", "\t\"allowComments\": true,\n", "\t\"type\": \"object\",\n", "\t\"additionalProperties\": false,\n", "\t\"definitions\": {\n", "\t\t\"devContainerCommon\": {\n", "\t\t\t\"type\": \"object\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "extensions/configuration-editing/schemas/devContainer.schema.json", "type": "replace", "edit_start_line_idx": 5 }
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" clip-rule="evenodd" d="M10.0719 7.99999L5.71461 12.3573L6.33333 12.976L11 8.30935V7.69064L6.33333 3.02397L5.71461 3.64269L10.0719 7.99999Z" fill="#C5C5C5"/> </svg>
src/vs/base/browser/ui/tree/media/tree-collapsed-dark.svg
0
https://github.com/microsoft/vscode/commit/8046438bb13cc424399978a895530f9076a7045e
[ 0.00017381059296894819, 0.00017381059296894819, 0.00017381059296894819, 0.00017381059296894819, 0 ]
{ "id": 2, "code_window": [ "\t\"$schema\": \"http://json-schema.org/draft-07/schema#\",\n", "\t\"description\": \"Defines a dev container\",\n", "\t\"allowComments\": true,\n", "\t\"type\": \"object\",\n", "\t\"additionalProperties\": false,\n", "\t\"definitions\": {\n", "\t\t\"devContainerCommon\": {\n", "\t\t\t\"type\": \"object\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "extensions/configuration-editing/schemas/devContainer.schema.json", "type": "replace", "edit_start_line_idx": 5 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import { OperatingSystem } from 'vs/base/common/platform'; export interface ModifierLabels { readonly ctrlKey: string; readonly shiftKey: string; readonly altKey: string; readonly metaKey: string; readonly separator: string; } export interface Modifiers { readonly ctrlKey: boolean; readonly shiftKey: boolean; readonly altKey: boolean; readonly metaKey: boolean; } export interface KeyLabelProvider<T extends Modifiers> { (keybinding: T): string | null; } export class ModifierLabelProvider { public readonly modifierLabels: ModifierLabels[]; constructor(mac: ModifierLabels, windows: ModifierLabels, linux: ModifierLabels = windows) { this.modifierLabels = [null!]; // index 0 will never me accessed. this.modifierLabels[OperatingSystem.Macintosh] = mac; this.modifierLabels[OperatingSystem.Windows] = windows; this.modifierLabels[OperatingSystem.Linux] = linux; } public toLabel<T extends Modifiers>(OS: OperatingSystem, parts: T[], keyLabelProvider: KeyLabelProvider<T>): string | null { if (parts.length === 0) { return null; } const result: string[] = []; for (let i = 0, len = parts.length; i < len; i++) { const part = parts[i]; const keyLabel = keyLabelProvider(part); if (keyLabel === null) { // this keybinding cannot be expressed... return null; } result[i] = _simpleAsString(part, keyLabel, this.modifierLabels[OS]); } return result.join(' '); } } /** * A label provider that prints modifiers in a suitable format for displaying in the UI. */ export const UILabelProvider = new ModifierLabelProvider( { ctrlKey: '⌃', shiftKey: '⇧', altKey: '⌥', metaKey: '⌘', separator: '', }, { ctrlKey: nls.localize({ key: 'ctrlKey', comment: ['This is the short form for the Control key on the keyboard'] }, "Ctrl"), shiftKey: nls.localize({ key: 'shiftKey', comment: ['This is the short form for the Shift key on the keyboard'] }, "Shift"), altKey: nls.localize({ key: 'altKey', comment: ['This is the short form for the Alt key on the keyboard'] }, "Alt"), metaKey: nls.localize({ key: 'windowsKey', comment: ['This is the short form for the Windows key on the keyboard'] }, "Windows"), separator: '+', }, { ctrlKey: nls.localize({ key: 'ctrlKey', comment: ['This is the short form for the Control key on the keyboard'] }, "Ctrl"), shiftKey: nls.localize({ key: 'shiftKey', comment: ['This is the short form for the Shift key on the keyboard'] }, "Shift"), altKey: nls.localize({ key: 'altKey', comment: ['This is the short form for the Alt key on the keyboard'] }, "Alt"), metaKey: nls.localize({ key: 'superKey', comment: ['This is the short form for the Super key on the keyboard'] }, "Super"), separator: '+', } ); /** * A label provider that prints modifiers in a suitable format for ARIA. */ export const AriaLabelProvider = new ModifierLabelProvider( { ctrlKey: nls.localize({ key: 'ctrlKey.long', comment: ['This is the long form for the Control key on the keyboard'] }, "Control"), shiftKey: nls.localize({ key: 'shiftKey.long', comment: ['This is the long form for the Shift key on the keyboard'] }, "Shift"), altKey: nls.localize({ key: 'altKey.long', comment: ['This is the long form for the Alt key on the keyboard'] }, "Alt"), metaKey: nls.localize({ key: 'cmdKey.long', comment: ['This is the long form for the Command key on the keyboard'] }, "Command"), separator: '+', }, { ctrlKey: nls.localize({ key: 'ctrlKey.long', comment: ['This is the long form for the Control key on the keyboard'] }, "Control"), shiftKey: nls.localize({ key: 'shiftKey.long', comment: ['This is the long form for the Shift key on the keyboard'] }, "Shift"), altKey: nls.localize({ key: 'altKey.long', comment: ['This is the long form for the Alt key on the keyboard'] }, "Alt"), metaKey: nls.localize({ key: 'windowsKey.long', comment: ['This is the long form for the Windows key on the keyboard'] }, "Windows"), separator: '+', }, { ctrlKey: nls.localize({ key: 'ctrlKey.long', comment: ['This is the long form for the Control key on the keyboard'] }, "Control"), shiftKey: nls.localize({ key: 'shiftKey.long', comment: ['This is the long form for the Shift key on the keyboard'] }, "Shift"), altKey: nls.localize({ key: 'altKey.long', comment: ['This is the long form for the Alt key on the keyboard'] }, "Alt"), metaKey: nls.localize({ key: 'superKey.long', comment: ['This is the long form for the Super key on the keyboard'] }, "Super"), separator: '+', } ); /** * A label provider that prints modifiers in a suitable format for Electron Accelerators. * See https://github.com/electron/electron/blob/master/docs/api/accelerator.md */ export const ElectronAcceleratorLabelProvider = new ModifierLabelProvider( { ctrlKey: 'Ctrl', shiftKey: 'Shift', altKey: 'Alt', metaKey: 'Cmd', separator: '+', }, { ctrlKey: 'Ctrl', shiftKey: 'Shift', altKey: 'Alt', metaKey: 'Super', separator: '+', } ); /** * A label provider that prints modifiers in a suitable format for user settings. */ export const UserSettingsLabelProvider = new ModifierLabelProvider( { ctrlKey: 'ctrl', shiftKey: 'shift', altKey: 'alt', metaKey: 'cmd', separator: '+', }, { ctrlKey: 'ctrl', shiftKey: 'shift', altKey: 'alt', metaKey: 'win', separator: '+', }, { ctrlKey: 'ctrl', shiftKey: 'shift', altKey: 'alt', metaKey: 'meta', separator: '+', } ); function _simpleAsString(modifiers: Modifiers, key: string, labels: ModifierLabels): string { if (key === null) { return ''; } const result: string[] = []; // translate modifier keys: Ctrl-Shift-Alt-Meta if (modifiers.ctrlKey) { result.push(labels.ctrlKey); } if (modifiers.shiftKey) { result.push(labels.shiftKey); } if (modifiers.altKey) { result.push(labels.altKey); } if (modifiers.metaKey) { result.push(labels.metaKey); } // the actual key result.push(key); return result.join(labels.separator); }
src/vs/base/common/keybindingLabels.ts
0
https://github.com/microsoft/vscode/commit/8046438bb13cc424399978a895530f9076a7045e
[ 0.0001779029844328761, 0.00017323375504929572, 0.00016605462587904185, 0.00017438943905290216, 0.0000035923974337492837 ]
{ "id": 2, "code_window": [ "\t\"$schema\": \"http://json-schema.org/draft-07/schema#\",\n", "\t\"description\": \"Defines a dev container\",\n", "\t\"allowComments\": true,\n", "\t\"type\": \"object\",\n", "\t\"additionalProperties\": false,\n", "\t\"definitions\": {\n", "\t\t\"devContainerCommon\": {\n", "\t\t\t\"type\": \"object\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "extensions/configuration-editing/schemas/devContainer.schema.json", "type": "replace", "edit_start_line_idx": 5 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { URI } from 'vs/base/common/uri'; import { IRange } from 'vs/editor/common/core/range'; import { Comment, CommentThread, CommentThreadChangedEvent } from 'vs/editor/common/modes'; import { groupBy, firstIndex, flatten } from 'vs/base/common/arrays'; import { localize } from 'vs/nls'; import { values } from 'vs/base/common/map'; export interface ICommentThreadChangedEvent extends CommentThreadChangedEvent { owner: string; } export class CommentNode { owner: string; threadId: string; range: IRange; comment: Comment; replies: CommentNode[] = []; resource: URI; isRoot: boolean; constructor(owner: string, threadId: string, resource: URI, comment: Comment, range: IRange) { this.owner = owner; this.threadId = threadId; this.comment = comment; this.resource = resource; this.range = range; this.isRoot = false; } hasReply(): boolean { return this.replies && this.replies.length !== 0; } } export class ResourceWithCommentThreads { id: string; owner: string; commentThreads: CommentNode[]; // The top level comments on the file. Replys are nested under each node. resource: URI; constructor(owner: string, resource: URI, commentThreads: CommentThread[]) { this.owner = owner; this.id = resource.toString(); this.resource = resource; this.commentThreads = commentThreads.filter(thread => thread.comments && thread.comments.length).map(thread => ResourceWithCommentThreads.createCommentNode(owner, resource, thread)); } public static createCommentNode(owner: string, resource: URI, commentThread: CommentThread): CommentNode { const { threadId, comments, range } = commentThread; const commentNodes: CommentNode[] = comments!.map(comment => new CommentNode(owner, threadId!, resource, comment, range)); if (commentNodes.length > 1) { commentNodes[0].replies = commentNodes.slice(1, commentNodes.length); } commentNodes[0].isRoot = true; return commentNodes[0]; } } export class CommentsModel { resourceCommentThreads: ResourceWithCommentThreads[]; commentThreadsMap: Map<string, ResourceWithCommentThreads[]>; constructor() { this.resourceCommentThreads = []; this.commentThreadsMap = new Map<string, ResourceWithCommentThreads[]>(); } public setCommentThreads(owner: string, commentThreads: CommentThread[]): void { this.commentThreadsMap.set(owner, this.groupByResource(owner, commentThreads)); this.resourceCommentThreads = flatten(values(this.commentThreadsMap)); } public updateCommentThreads(event: ICommentThreadChangedEvent): boolean { const { owner, removed, changed, added } = event; let threadsForOwner = this.commentThreadsMap.get(owner) || []; removed.forEach(thread => { // Find resource that has the comment thread const matchingResourceIndex = firstIndex(threadsForOwner, (resourceData) => resourceData.id === thread.resource); const matchingResourceData = threadsForOwner[matchingResourceIndex]; // Find comment node on resource that is that thread and remove it const index = firstIndex(matchingResourceData.commentThreads, (commentThread) => commentThread.threadId === thread.threadId); matchingResourceData.commentThreads.splice(index, 1); // If the comment thread was the last thread for a resource, remove that resource from the list if (matchingResourceData.commentThreads.length === 0) { threadsForOwner.splice(matchingResourceIndex, 1); } }); changed.forEach(thread => { // Find resource that has the comment thread const matchingResourceIndex = firstIndex(threadsForOwner, (resourceData) => resourceData.id === thread.resource); const matchingResourceData = threadsForOwner[matchingResourceIndex]; // Find comment node on resource that is that thread and replace it const index = firstIndex(matchingResourceData.commentThreads, (commentThread) => commentThread.threadId === thread.threadId); if (index >= 0) { matchingResourceData.commentThreads[index] = ResourceWithCommentThreads.createCommentNode(owner, URI.parse(matchingResourceData.id), thread); } else if (thread.comments && thread.comments.length) { matchingResourceData.commentThreads.push(ResourceWithCommentThreads.createCommentNode(owner, URI.parse(matchingResourceData.id), thread)); } }); added.forEach(thread => { const existingResource = threadsForOwner.filter(resourceWithThreads => resourceWithThreads.resource.toString() === thread.resource); if (existingResource.length) { const resource = existingResource[0]; if (thread.comments && thread.comments.length) { resource.commentThreads.push(ResourceWithCommentThreads.createCommentNode(owner, resource.resource, thread)); } } else { threadsForOwner.push(new ResourceWithCommentThreads(owner, URI.parse(thread.resource!), [thread])); } }); this.commentThreadsMap.set(owner, threadsForOwner); this.resourceCommentThreads = flatten(values(this.commentThreadsMap)); return removed.length > 0 || changed.length > 0 || added.length > 0; } public hasCommentThreads(): boolean { return !!this.resourceCommentThreads.length; } public getMessage(): string { if (!this.resourceCommentThreads.length) { return localize('noComments', "There are no comments on this review."); } else { return ''; } } private groupByResource(owner: string, commentThreads: CommentThread[]): ResourceWithCommentThreads[] { const resourceCommentThreads: ResourceWithCommentThreads[] = []; const commentThreadsByResource = new Map<string, ResourceWithCommentThreads>(); for (const group of groupBy(commentThreads, CommentsModel._compareURIs)) { commentThreadsByResource.set(group[0].resource!, new ResourceWithCommentThreads(owner, URI.parse(group[0].resource!), group)); } commentThreadsByResource.forEach((v, i, m) => { resourceCommentThreads.push(v); }); return resourceCommentThreads; } private static _compareURIs(a: CommentThread, b: CommentThread) { const resourceA = a.resource!.toString(); const resourceB = b.resource!.toString(); if (resourceA < resourceB) { return -1; } else if (resourceA > resourceB) { return 1; } else { return 0; } } }
src/vs/workbench/contrib/comments/common/commentModel.ts
0
https://github.com/microsoft/vscode/commit/8046438bb13cc424399978a895530f9076a7045e
[ 0.00022237988014239818, 0.00017494452185928822, 0.00016701515414752066, 0.00017211832164321095, 0.000012315743333601858 ]
{ "id": 3, "code_window": [ "\t\"definitions\": {\n", "\t\t\"devContainerCommon\": {\n", "\t\t\t\"type\": \"object\",\n", "\t\t\t\"additionalProperties\": false,\n", "\t\t\t\"properties\": {\n", "\t\t\t\t\"name\": {\n", "\t\t\t\t\t\"type\": \"string\",\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "extensions/configuration-editing/schemas/devContainer.schema.json", "type": "replace", "edit_start_line_idx": 9 }
{ "$schema": "http://json-schema.org/draft-07/schema#", "description": "Defines a dev container", "allowComments": true, "type": "object", "additionalProperties": false, "definitions": { "devContainerCommon": { "type": "object", "additionalProperties": false, "properties": { "name": { "type": "string", "description": "A name to show for the workspace folder." }, "extensions": { "type": "array", "description": "An array of extensions that should be installed into the container.", "items": { "type": "string", "pattern": "^([a-z0-9A-Z][a-z0-9\\-A-Z]*)\\.([a-z0-9A-Z][a-z0-9\\-A-Z]*)$", "errorMessage": "Expected format '${publisher}.${name}'. Example: 'vscode.csharp'." } }, "settings": { "$ref": "vscode://schemas/settings/machine", "description": "Machine specific settings that should be copied into the container." }, "forwardPorts": { "type": "array", "description": "Ports that are forwarded from the container to the local machine.", "items": { "type": "integer" } }, "remoteEnv": { "type": "object", "additionalProperties": { "type": [ "string", "null" ] }, "description": "Remote environment variables." }, "remoteUser": { "type": "string", "description": "The user VS Code Server will be started with. The default is the same user as the container." }, "postCreateCommand": { "type": [ "string", "array" ], "description": "A command to run after creating the container. If this is a single string, it will be run in a shell. If this is an array of strings, it will be run as a single command without shell.", "items": { "type": "string" } }, "devPort": { "type": "integer", "description": "The port VS Code can use to connect to its backend." } } }, "nonComposeBase": { "type": "object", "additionalProperties": false, "properties": { "appPort": { "type": [ "integer", "string", "array" ], "description": "Application ports that are exposed by the container. This can be a single port or an array of ports. Each port can be a number or a string. A number is mapped to the same port on the host. A string is passed to Docker unchanged and can be used to map ports differently, e.g. \"8000:8010\".", "items": { "type": [ "integer", "string" ] } }, "containerEnv": { "type": "object", "additionalProperties": { "type": "string" }, "description": "Container environment variables." }, "containerUser": { "type": "string", "description": "The user the container will be started with. The default is the user on the Docker image." }, "updateRemoteUserUID": { "type": "boolean", "description": "Controls whether on Linux the container's user should be updated with the local user's UID and GID. On by default." }, "mounts": { "type": "array", "description": "Mount points to set up when creating the container. See Docker's documentation for the --mount option for the supported syntax.", "items": { "type": "string" } }, "runArgs": { "type": "array", "description": "The arguments required when starting in the container.", "items": { "type": "string" } }, "shutdownAction": { "type": "string", "enum": [ "none", "stopContainer" ], "description": "Action to take when the VS Code window is closed. The default is to stop the container." }, "overrideCommand": { "type": "boolean", "description": "Whether to overwrite the command specified in the image. The default is true." }, "workspaceFolder": { "type": "string", "description": "The path of the workspace folder inside the container." }, "workspaceMount": { "type": "string", "description": "The --mount parameter for docker run. The default is to mount the project folder at /workspaces/$project." } } }, "dockerFileContainer": { "type": "object", "additionalProperties": false, "properties": { "dockerFile": { "type": "string", "description": "The location of the Dockerfile that defines the contents of the container. The path is relative to the folder containing the `devcontainer.json` file." }, "context": { "type": "string", "description": "The location of the context folder for building the Docker image. The path is relative to the folder containing the `devcontainer.json` file." } }, "required": [ "dockerFile" ] }, "imageContainer": { "type": "object", "additionalProperties": false, "properties": { "image": { "type": "string", "description": "The docker image that will be used to create the container." } }, "required": [ "image" ] }, "composeContainer": { "type": "object", "additionalProperties": false, "properties": { "dockerComposeFile": { "type": [ "string", "array" ], "description": "The name of the docker-compose file(s) used to start the services.", "items": { "type": "string" } }, "service": { "type": "string", "description": "The service you want to work on." }, "runServices": { "type": "array", "description": "An array of services that should be started and stopped.", "items": { "type": "string" } }, "workspaceFolder": { "type": "string", "description": "The path of the workspace folder inside the container." }, "shutdownAction": { "type": "string", "enum": [ "none", "stopCompose" ], "description": "Action to take when the VS Code window is closed. The default is to stop the containers." } }, "required": [ "dockerComposeFile", "service", "workspaceFolder" ] } }, "allOf": [ { "oneOf": [ { "allOf": [ { "oneOf": [ { "$ref": "#/definitions/dockerFileContainer" }, { "$ref": "#/definitions/imageContainer" } ] }, { "$ref": "#/definitions/nonComposeBase" } ] }, { "$ref": "#/definitions/composeContainer" } ] }, { "$ref": "#/definitions/devContainerCommon" } ] }
extensions/configuration-editing/schemas/devContainer.schema.json
1
https://github.com/microsoft/vscode/commit/8046438bb13cc424399978a895530f9076a7045e
[ 0.7587699294090271, 0.0318724662065506, 0.0001639228139538318, 0.00023356842575594783, 0.15156866610050201 ]
{ "id": 3, "code_window": [ "\t\"definitions\": {\n", "\t\t\"devContainerCommon\": {\n", "\t\t\t\"type\": \"object\",\n", "\t\t\t\"additionalProperties\": false,\n", "\t\t\t\"properties\": {\n", "\t\t\t\t\"name\": {\n", "\t\t\t\t\t\"type\": \"string\",\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "extensions/configuration-editing/schemas/devContainer.schema.json", "type": "replace", "edit_start_line_idx": 9 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as ts from 'typescript'; import * as lazy from 'lazy.js'; import { duplex, through } from 'event-stream'; import * as File from 'vinyl'; import * as sm from 'source-map'; import * as path from 'path'; declare class FileSourceMap extends File { public sourceMap: sm.RawSourceMap; } enum CollectStepResult { Yes, YesAndRecurse, No, NoAndRecurse } function collect(node: ts.Node, fn: (node: ts.Node) => CollectStepResult): ts.Node[] { const result: ts.Node[] = []; function loop(node: ts.Node) { const stepResult = fn(node); if (stepResult === CollectStepResult.Yes || stepResult === CollectStepResult.YesAndRecurse) { result.push(node); } if (stepResult === CollectStepResult.YesAndRecurse || stepResult === CollectStepResult.NoAndRecurse) { ts.forEachChild(node, loop); } } loop(node); return result; } function clone<T>(object: T): T { const result = <T>{}; for (const id in object) { result[id] = object[id]; } return result; } function template(lines: string[]): string { let indent = '', wrap = ''; if (lines.length > 1) { indent = '\t'; wrap = '\n'; } return `/*--------------------------------------------------------- * Copyright (C) Microsoft Corporation. All rights reserved. *--------------------------------------------------------*/ define([], [${ wrap + lines.map(l => indent + l).join(',\n') + wrap}]);`; } /** * Returns a stream containing the patched JavaScript and source maps. */ function nls(): NodeJS.ReadWriteStream { const input = through(); const output = input.pipe(through(function (f: FileSourceMap) { if (!f.sourceMap) { return this.emit('error', new Error(`File ${f.relative} does not have sourcemaps.`)); } let source = f.sourceMap.sources[0]; if (!source) { return this.emit('error', new Error(`File ${f.relative} does not have a source in the source map.`)); } const root = f.sourceMap.sourceRoot; if (root) { source = path.join(root, source); } const typescript = f.sourceMap.sourcesContent![0]; if (!typescript) { return this.emit('error', new Error(`File ${f.relative} does not have the original content in the source map.`)); } nls.patchFiles(f, typescript).forEach(f => this.emit('data', f)); })); return duplex(input, output); } function isImportNode(node: ts.Node): boolean { return node.kind === ts.SyntaxKind.ImportDeclaration || node.kind === ts.SyntaxKind.ImportEqualsDeclaration; } module nls { export interface INlsStringResult { javascript: string; sourcemap: sm.RawSourceMap; nls?: string; nlsKeys?: string; } export interface ISpan { start: ts.LineAndCharacter; end: ts.LineAndCharacter; } export interface ILocalizeCall { keySpan: ISpan; key: string; valueSpan: ISpan; value: string; } export interface ILocalizeAnalysisResult { localizeCalls: ILocalizeCall[]; nlsExpressions: ISpan[]; } export interface IPatch { span: ISpan; content: string; } export function fileFrom(file: File, contents: string, path: string = file.path) { return new File({ contents: Buffer.from(contents), base: file.base, cwd: file.cwd, path: path }); } export function mappedPositionFrom(source: string, lc: ts.LineAndCharacter): sm.MappedPosition { return { source, line: lc.line + 1, column: lc.character }; } export function lcFrom(position: sm.Position): ts.LineAndCharacter { return { line: position.line - 1, character: position.column }; } export class SingleFileServiceHost implements ts.LanguageServiceHost { private file: ts.IScriptSnapshot; private lib: ts.IScriptSnapshot; constructor(private options: ts.CompilerOptions, private filename: string, contents: string) { this.file = ts.ScriptSnapshot.fromString(contents); this.lib = ts.ScriptSnapshot.fromString(''); } getCompilationSettings = () => this.options; getScriptFileNames = () => [this.filename]; getScriptVersion = () => '1'; getScriptSnapshot = (name: string) => name === this.filename ? this.file : this.lib; getCurrentDirectory = () => ''; getDefaultLibFileName = () => 'lib.d.ts'; } function isCallExpressionWithinTextSpanCollectStep(textSpan: ts.TextSpan, node: ts.Node): CollectStepResult { if (!ts.textSpanContainsTextSpan({ start: node.pos, length: node.end - node.pos }, textSpan)) { return CollectStepResult.No; } return node.kind === ts.SyntaxKind.CallExpression ? CollectStepResult.YesAndRecurse : CollectStepResult.NoAndRecurse; } export function analyze(contents: string, options: ts.CompilerOptions = {}): ILocalizeAnalysisResult { const filename = 'file.ts'; const serviceHost = new SingleFileServiceHost(Object.assign(clone(options), { noResolve: true }), filename, contents); const service = ts.createLanguageService(serviceHost); const sourceFile = ts.createSourceFile(filename, contents, ts.ScriptTarget.ES5, true); // all imports const imports = lazy(collect(sourceFile, n => isImportNode(n) ? CollectStepResult.YesAndRecurse : CollectStepResult.NoAndRecurse)); // import nls = require('vs/nls'); const importEqualsDeclarations = imports .filter(n => n.kind === ts.SyntaxKind.ImportEqualsDeclaration) .map(n => <ts.ImportEqualsDeclaration>n) .filter(d => d.moduleReference.kind === ts.SyntaxKind.ExternalModuleReference) .filter(d => (<ts.ExternalModuleReference>d.moduleReference).expression.getText() === '\'vs/nls\''); // import ... from 'vs/nls'; const importDeclarations = imports .filter(n => n.kind === ts.SyntaxKind.ImportDeclaration) .map(n => <ts.ImportDeclaration>n) .filter(d => d.moduleSpecifier.kind === ts.SyntaxKind.StringLiteral) .filter(d => d.moduleSpecifier.getText() === '\'vs/nls\'') .filter(d => !!d.importClause && !!d.importClause.namedBindings); const nlsExpressions = importEqualsDeclarations .map(d => (<ts.ExternalModuleReference>d.moduleReference).expression) .concat(importDeclarations.map(d => d.moduleSpecifier)) .map<ISpan>(d => ({ start: ts.getLineAndCharacterOfPosition(sourceFile, d.getStart()), end: ts.getLineAndCharacterOfPosition(sourceFile, d.getEnd()) })); // `nls.localize(...)` calls const nlsLocalizeCallExpressions = importDeclarations .filter(d => !!(d.importClause && d.importClause.namedBindings && d.importClause.namedBindings.kind === ts.SyntaxKind.NamespaceImport)) .map(d => (<ts.NamespaceImport>d.importClause!.namedBindings).name) .concat(importEqualsDeclarations.map(d => d.name)) // find read-only references to `nls` .map(n => service.getReferencesAtPosition(filename, n.pos + 1)) .flatten() .filter(r => !r.isWriteAccess) // find the deepest call expressions AST nodes that contain those references .map(r => collect(sourceFile, n => isCallExpressionWithinTextSpanCollectStep(r.textSpan, n))) .map(a => lazy(a).last()) .filter(n => !!n) .map(n => <ts.CallExpression>n) // only `localize` calls .filter(n => n.expression.kind === ts.SyntaxKind.PropertyAccessExpression && (<ts.PropertyAccessExpression>n.expression).name.getText() === 'localize'); // `localize` named imports const allLocalizeImportDeclarations = importDeclarations .filter(d => !!(d.importClause && d.importClause.namedBindings && d.importClause.namedBindings.kind === ts.SyntaxKind.NamedImports)) .map(d => ([] as any[]).concat((<ts.NamedImports>d.importClause!.namedBindings!).elements)) .flatten(); // `localize` read-only references const localizeReferences = allLocalizeImportDeclarations .filter(d => d.name.getText() === 'localize') .map(n => service.getReferencesAtPosition(filename, n.pos + 1)) .flatten() .filter(r => !r.isWriteAccess); // custom named `localize` read-only references const namedLocalizeReferences = allLocalizeImportDeclarations .filter(d => d.propertyName && d.propertyName.getText() === 'localize') .map(n => service.getReferencesAtPosition(filename, n.name.pos + 1)) .flatten() .filter(r => !r.isWriteAccess); // find the deepest call expressions AST nodes that contain those references const localizeCallExpressions = localizeReferences .concat(namedLocalizeReferences) .map(r => collect(sourceFile, n => isCallExpressionWithinTextSpanCollectStep(r.textSpan, n))) .map(a => lazy(a).last()) .filter(n => !!n) .map(n => <ts.CallExpression>n); // collect everything const localizeCalls = nlsLocalizeCallExpressions .concat(localizeCallExpressions) .map(e => e.arguments) .filter(a => a.length > 1) .sort((a, b) => a[0].getStart() - b[0].getStart()) .map<ILocalizeCall>(a => ({ keySpan: { start: ts.getLineAndCharacterOfPosition(sourceFile, a[0].getStart()), end: ts.getLineAndCharacterOfPosition(sourceFile, a[0].getEnd()) }, key: a[0].getText(), valueSpan: { start: ts.getLineAndCharacterOfPosition(sourceFile, a[1].getStart()), end: ts.getLineAndCharacterOfPosition(sourceFile, a[1].getEnd()) }, value: a[1].getText() })); return { localizeCalls: localizeCalls.toArray(), nlsExpressions: nlsExpressions.toArray() }; } export class TextModel { private lines: string[]; private lineEndings: string[]; constructor(contents: string) { const regex = /\r\n|\r|\n/g; let index = 0; let match: RegExpExecArray | null; this.lines = []; this.lineEndings = []; while (match = regex.exec(contents)) { this.lines.push(contents.substring(index, match.index)); this.lineEndings.push(match[0]); index = regex.lastIndex; } if (contents.length > 0) { this.lines.push(contents.substring(index, contents.length)); this.lineEndings.push(''); } } public get(index: number): string { return this.lines[index]; } public set(index: number, line: string): void { this.lines[index] = line; } public get lineCount(): number { return this.lines.length; } /** * Applies patch(es) to the model. * Multiple patches must be ordered. * Does not support patches spanning multiple lines. */ public apply(patch: IPatch): void { const startLineNumber = patch.span.start.line; const endLineNumber = patch.span.end.line; const startLine = this.lines[startLineNumber] || ''; const endLine = this.lines[endLineNumber] || ''; this.lines[startLineNumber] = [ startLine.substring(0, patch.span.start.character), patch.content, endLine.substring(patch.span.end.character) ].join(''); for (let i = startLineNumber + 1; i <= endLineNumber; i++) { this.lines[i] = ''; } } public toString(): string { return lazy(this.lines).zip(this.lineEndings) .flatten().toArray().join(''); } } export function patchJavascript(patches: IPatch[], contents: string, moduleId: string): string { const model = new nls.TextModel(contents); // patch the localize calls lazy(patches).reverse().each(p => model.apply(p)); // patch the 'vs/nls' imports const firstLine = model.get(0); const patchedFirstLine = firstLine.replace(/(['"])vs\/nls\1/g, `$1vs/nls!${moduleId}$1`); model.set(0, patchedFirstLine); return model.toString(); } export function patchSourcemap(patches: IPatch[], rsm: sm.RawSourceMap, smc: sm.SourceMapConsumer): sm.RawSourceMap { const smg = new sm.SourceMapGenerator({ file: rsm.file, sourceRoot: rsm.sourceRoot }); patches = patches.reverse(); let currentLine = -1; let currentLineDiff = 0; let source: string | null = null; smc.eachMapping(m => { const patch = patches[patches.length - 1]; const original = { line: m.originalLine, column: m.originalColumn }; const generated = { line: m.generatedLine, column: m.generatedColumn }; if (currentLine !== generated.line) { currentLineDiff = 0; } currentLine = generated.line; generated.column += currentLineDiff; if (patch && m.generatedLine - 1 === patch.span.end.line && m.generatedColumn === patch.span.end.character) { const originalLength = patch.span.end.character - patch.span.start.character; const modifiedLength = patch.content.length; const lengthDiff = modifiedLength - originalLength; currentLineDiff += lengthDiff; generated.column += lengthDiff; patches.pop(); } source = rsm.sourceRoot ? path.relative(rsm.sourceRoot, m.source) : m.source; source = source.replace(/\\/g, '/'); smg.addMapping({ source, name: m.name, original, generated }); }, null, sm.SourceMapConsumer.GENERATED_ORDER); if (source) { smg.setSourceContent(source, smc.sourceContentFor(source)); } return JSON.parse(smg.toString()); } export function patch(moduleId: string, typescript: string, javascript: string, sourcemap: sm.RawSourceMap): INlsStringResult { const { localizeCalls, nlsExpressions } = analyze(typescript); if (localizeCalls.length === 0) { return { javascript, sourcemap }; } const nlsKeys = template(localizeCalls.map(lc => lc.key)); const nls = template(localizeCalls.map(lc => lc.value)); const smc = new sm.SourceMapConsumer(sourcemap); const positionFrom = mappedPositionFrom.bind(null, sourcemap.sources[0]); let i = 0; // build patches const patches = lazy(localizeCalls) .map(lc => ([ { range: lc.keySpan, content: '' + (i++) }, { range: lc.valueSpan, content: 'null' } ])) .flatten() .map<IPatch>(c => { const start = lcFrom(smc.generatedPositionFor(positionFrom(c.range.start))); const end = lcFrom(smc.generatedPositionFor(positionFrom(c.range.end))); return { span: { start, end }, content: c.content }; }) .toArray(); javascript = patchJavascript(patches, javascript, moduleId); // since imports are not within the sourcemap information, // we must do this MacGyver style if (nlsExpressions.length) { javascript = javascript.replace(/^define\(.*$/m, line => { return line.replace(/(['"])vs\/nls\1/g, `$1vs/nls!${moduleId}$1`); }); } sourcemap = patchSourcemap(patches, sourcemap, smc); return { javascript, sourcemap, nlsKeys, nls }; } export function patchFiles(javascriptFile: File, typescript: string): File[] { // hack? const moduleId = javascriptFile.relative .replace(/\.js$/, '') .replace(/\\/g, '/'); const { javascript, sourcemap, nlsKeys, nls } = patch( moduleId, typescript, javascriptFile.contents.toString(), (<any>javascriptFile).sourceMap ); const result: File[] = [fileFrom(javascriptFile, javascript)]; (<any>result[0]).sourceMap = sourcemap; if (nlsKeys) { result.push(fileFrom(javascriptFile, nlsKeys, javascriptFile.path.replace(/\.js$/, '.nls.keys.js'))); } if (nls) { result.push(fileFrom(javascriptFile, nls, javascriptFile.path.replace(/\.js$/, '.nls.js'))); } return result; } } export = nls;
build/lib/nls.ts
0
https://github.com/microsoft/vscode/commit/8046438bb13cc424399978a895530f9076a7045e
[ 0.00018103187903761864, 0.00017106239101849496, 0.0001629746111575514, 0.0001715448743198067, 0.0000031368354029837064 ]
{ "id": 3, "code_window": [ "\t\"definitions\": {\n", "\t\t\"devContainerCommon\": {\n", "\t\t\t\"type\": \"object\",\n", "\t\t\t\"additionalProperties\": false,\n", "\t\t\t\"properties\": {\n", "\t\t\t\t\"name\": {\n", "\t\t\t\t\t\"type\": \"string\",\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "extensions/configuration-editing/schemas/devContainer.schema.json", "type": "replace", "edit_start_line_idx": 9 }
// CamelCase 'use strict'; var Conway; (function (Conway) { var Cell = (function () { function Cell() { } return Cell; })(); (function (property, number, property, number, property, boolean) { if (property === undefined) { property = row; } if (property === undefined) { property = col; } if (property === undefined) { property = live; } }); var GameOfLife = (function () { function GameOfLife() { } return GameOfLife; })(); (function () { property; gridSize = 50; property; canvasSize = 600; property; lineColor = '#cdcdcd'; property; liveColor = '#666'; property; deadColor = '#eee'; property; initialLifeProbability = 0.5; property; animationRate = 60; property; cellSize = 0; property; context: ICanvasRenderingContext2D; property; world = createWorld(); circleOfLife(); function createWorld() { return travelWorld(function (cell) { cell.live = Math.random() < initialLifeProbability; return cell; }); } function circleOfLife() { world = travelWorld(function (cell) { cell = world[cell.row][cell.col]; draw(cell); return resolveNextGeneration(cell); }); setTimeout(function () { circleOfLife(); }, animationRate); } function resolveNextGeneration(cell) { var count = countNeighbors(cell); var newCell = new Cell(cell.row, cell.col, cell.live); if (count < 2 || count > 3) newCell.live = false; else if (count == 3) newCell.live = true; return newCell; } function countNeighbors(cell) { var neighbors = 0; for (var row = -1; row <= 1; row++) { for (var col = -1; col <= 1; col++) { if (row == 0 && col == 0) continue; if (isAlive(cell.row + row, cell.col + col)) { neighbors++; } } } return neighbors; } function isAlive(row, col) { // todo - need to guard with worl[row] exists? if (row < 0 || col < 0 || row >= gridSize || col >= gridSize) return false; return world[row][col].live; } function travelWorld(callback) { var result = []; for (var row = 0; row < gridSize; row++) { var rowData = []; for (var col = 0; col < gridSize; col++) { rowData.push(callback(new Cell(row, col, false))); } result.push(rowData); } return result; } function draw(cell) { if (context == null) context = createDrawingContext(); if (cellSize == 0) cellSize = canvasSize / gridSize; context.strokeStyle = lineColor; context.strokeRect(cell.row * cellSize, cell.col * cellSize, cellSize, cellSize); context.fillStyle = cell.live ? liveColor : deadColor; context.fillRect(cell.row * cellSize, cell.col * cellSize, cellSize, cellSize); } function createDrawingContext() { var canvas = document.getElementById('conway-canvas'); if (canvas == null) { canvas = document.createElement('canvas'); canvas.id = "conway-canvas"; canvas.width = canvasSize; canvas.height = canvasSize; document.body.appendChild(canvas); } return canvas.getContext('2d'); } }); })(Conway || (Conway = {})); var game = new Conway.GameOfLife();
src/vs/workbench/services/search/test/node/fixtures/examples/NullPoinderException.js
0
https://github.com/microsoft/vscode/commit/8046438bb13cc424399978a895530f9076a7045e
[ 0.00020751258125528693, 0.00017375768220517784, 0.00016556245100218803, 0.00017139711417257786, 0.000010586324606265407 ]
{ "id": 3, "code_window": [ "\t\"definitions\": {\n", "\t\t\"devContainerCommon\": {\n", "\t\t\t\"type\": \"object\",\n", "\t\t\t\"additionalProperties\": false,\n", "\t\t\t\"properties\": {\n", "\t\t\t\t\"name\": {\n", "\t\t\t\t\t\"type\": \"string\",\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "extensions/configuration-editing/schemas/devContainer.schema.json", "type": "replace", "edit_start_line_idx": 9 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as platform from 'vs/platform/registry/common/platform'; import { Color } from 'vs/base/common/color'; import { ITheme } from 'vs/platform/theme/common/themeService'; import * as nls from 'vs/nls'; import { Extensions as JSONExtensions, IJSONContributionRegistry } from 'vs/platform/jsonschemas/common/jsonContributionRegistry'; import { RunOnceScheduler } from 'vs/base/common/async'; import { Event, Emitter } from 'vs/base/common/event'; import { IJSONSchema, IJSONSchemaMap } from 'vs/base/common/jsonSchema'; export const TOKEN_TYPE_WILDCARD = '*'; export const TOKEN_TYPE_WILDCARD_NUM = -1; // qualified string [type|*](.modifier)* export type TokenClassificationString = string; export const typeAndModifierIdPattern = '^\\w+[-_\\w+]*$'; export const fontStylePattern = '^(\\s*(-?italic|-?bold|-?underline))*\\s*$'; export interface TokenClassification { type: number; modifiers: number; } export interface TokenTypeOrModifierContribution { readonly num: number; readonly id: string; readonly description: string; readonly deprecationMessage: string | undefined; } export interface TokenStyleData { foreground?: Color; bold?: boolean; underline?: boolean; italic?: boolean; } export class TokenStyle implements Readonly<TokenStyleData> { constructor( public readonly foreground?: Color, public readonly bold?: boolean, public readonly underline?: boolean, public readonly italic?: boolean, ) { } } export namespace TokenStyle { export function fromData(data: { foreground?: Color, bold?: boolean, underline?: boolean, italic?: boolean }) { return new TokenStyle(data.foreground, data.bold, data.underline, data.italic); } export function fromSettings(foreground: string | undefined, fontStyle: string | undefined): TokenStyle { let foregroundColor = undefined; if (foreground !== undefined) { foregroundColor = Color.fromHex(foreground); } let bold, underline, italic; if (fontStyle !== undefined) { fontStyle = fontStyle.trim(); if (fontStyle.length === 0) { bold = italic = underline = false; } else { const expression = /-?italic|-?bold|-?underline/g; let match; while ((match = expression.exec(fontStyle))) { switch (match[0]) { case 'bold': bold = true; break; case 'italic': italic = true; break; case 'underline': underline = true; break; } } } } return new TokenStyle(foregroundColor, bold, underline, italic); } } export type ProbeScope = string[]; export interface TokenStyleFunction { (theme: ITheme): TokenStyle | undefined; } export interface TokenStyleDefaults { scopesToProbe?: ProbeScope[]; light?: TokenStyleValue; dark?: TokenStyleValue; hc?: TokenStyleValue; } export interface TokenStylingDefaultRule { match(classification: TokenClassification): number; selector: TokenClassification; defaults: TokenStyleDefaults; } export interface TokenStylingRule { match(classification: TokenClassification): number; value: TokenStyle; selector: TokenClassification; } /** * A TokenStyle Value is either a token style literal, or a TokenClassificationString */ export type TokenStyleValue = TokenStyle | TokenClassificationString; // TokenStyle registry export const Extensions = { TokenClassificationContribution: 'base.contributions.tokenClassification' }; export interface ITokenClassificationRegistry { readonly onDidChangeSchema: Event<void>; /** * Register a token type to the registry. * @param id The TokenType id as used in theme description files * @description the description */ registerTokenType(id: string, description: string): void; /** * Register a token modifier to the registry. * @param id The TokenModifier id as used in theme description files * @description the description */ registerTokenModifier(id: string, description: string): void; getTokenClassification(type: string, modifiers: string[]): TokenClassification | undefined; getTokenStylingRule(classification: TokenClassification, value: TokenStyle): TokenStylingRule; /** * Register a TokenStyle default to the registry. * @param selector The rule selector * @param defaults The default values */ registerTokenStyleDefault(selector: TokenClassification, defaults: TokenStyleDefaults): void; /** * Deregister a TokenStyle default to the registry. * @param selector The rule selector */ deregisterTokenStyleDefault(selector: TokenClassification): void; /** * Deregister a TokenType from the registry. */ deregisterTokenType(id: string): void; /** * Deregister a TokenModifier from the registry. */ deregisterTokenModifier(id: string): void; /** * Get all TokenType contributions */ getTokenTypes(): TokenTypeOrModifierContribution[]; /** * Get all TokenModifier contributions */ getTokenModifiers(): TokenTypeOrModifierContribution[]; /** * The styling rules to used when a schema does not define any styling rules. */ getTokenStylingDefaultRules(): TokenStylingDefaultRule[]; /** * JSON schema for an object to assign styling to token classifications */ getTokenStylingSchema(): IJSONSchema; } class TokenClassificationRegistry implements ITokenClassificationRegistry { private readonly _onDidChangeSchema = new Emitter<void>(); readonly onDidChangeSchema: Event<void> = this._onDidChangeSchema.event; private currentTypeNumber = 0; private currentModifierBit = 1; private tokenTypeById: { [key: string]: TokenTypeOrModifierContribution }; private tokenModifierById: { [key: string]: TokenTypeOrModifierContribution }; private tokenStylingDefaultRules: TokenStylingDefaultRule[] = []; private tokenStylingSchema: IJSONSchema & { properties: IJSONSchemaMap } = { type: 'object', properties: {}, additionalProperties: getStylingSchemeEntry(), definitions: { style: { type: 'object', description: nls.localize('schema.token.settings', 'Colors and styles for the token.'), properties: { foreground: { type: 'string', description: nls.localize('schema.token.foreground', 'Foreground color for the token.'), format: 'color-hex', default: '#ff0000' }, background: { type: 'string', deprecationMessage: nls.localize('schema.token.background.warning', 'Token background colors are currently not supported.') }, fontStyle: { type: 'string', description: nls.localize('schema.token.fontStyle', 'Font style of the rule: \'italic\', \'bold\' or \'underline\' or a combination. The empty string unsets inherited settings.'), pattern: fontStylePattern, patternErrorMessage: nls.localize('schema.fontStyle.error', 'Font style must be \'italic\', \'bold\' or \'underline\' or a combination. The empty string unsets all styles.'), defaultSnippets: [{ label: nls.localize('schema.token.fontStyle.none', 'None (clear inherited style)'), bodyText: '""' }, { body: 'italic' }, { body: 'bold' }, { body: 'underline' }, { body: 'italic underline' }, { body: 'bold underline' }, { body: 'italic bold underline' }] } }, additionalProperties: false, defaultSnippets: [{ body: { foreground: '${1:#FF0000}', fontStyle: '${2:bold}' } }] } } }; constructor() { this.tokenTypeById = {}; this.tokenModifierById = {}; this.tokenTypeById[TOKEN_TYPE_WILDCARD] = { num: TOKEN_TYPE_WILDCARD_NUM, id: TOKEN_TYPE_WILDCARD, description: '', deprecationMessage: undefined }; } public registerTokenType(id: string, description: string, deprecationMessage?: string): void { if (!id.match(typeAndModifierIdPattern)) { throw new Error('Invalid token type id.'); } const num = this.currentTypeNumber++; let tokenStyleContribution: TokenTypeOrModifierContribution = { num, id, description, deprecationMessage }; this.tokenTypeById[id] = tokenStyleContribution; this.tokenStylingSchema.properties[id] = getStylingSchemeEntry(description, deprecationMessage); } public registerTokenModifier(id: string, description: string, deprecationMessage?: string): void { if (!id.match(typeAndModifierIdPattern)) { throw new Error('Invalid token modifier id.'); } const num = this.currentModifierBit; this.currentModifierBit = this.currentModifierBit * 2; let tokenStyleContribution: TokenTypeOrModifierContribution = { num, id, description, deprecationMessage }; this.tokenModifierById[id] = tokenStyleContribution; this.tokenStylingSchema.properties[`*.${id}`] = getStylingSchemeEntry(description, deprecationMessage); } public getTokenClassification(type: string, modifiers: string[]): TokenClassification | undefined { const tokenTypeDesc = this.tokenTypeById[type]; if (!tokenTypeDesc) { return undefined; } let allModifierBits = 0; for (const modifier of modifiers) { const tokenModifierDesc = this.tokenModifierById[modifier]; if (tokenModifierDesc) { allModifierBits |= tokenModifierDesc.num; } } return { type: tokenTypeDesc.num, modifiers: allModifierBits }; } private newMatcher(selector: TokenClassification) { const score = getTokenStylingScore(selector); return (classification: TokenClassification) => { const selectorType = selector.type; if (selectorType !== TOKEN_TYPE_WILDCARD_NUM && selectorType !== classification.type) { return -1; } const selectorModifier = selector.modifiers; if ((classification.modifiers & selectorModifier) !== selectorModifier) { return -1; } return score; }; } public getTokenStylingRule(selector: TokenClassification, value: TokenStyle): TokenStylingRule { return { match: this.newMatcher(selector), value, selector }; } public registerTokenStyleDefault(selector: TokenClassification, defaults: TokenStyleDefaults): void { this.tokenStylingDefaultRules.push({ selector, match: this.newMatcher(selector), defaults }); } public deregisterTokenStyleDefault(classification: TokenClassification): void { this.tokenStylingDefaultRules = this.tokenStylingDefaultRules.filter(r => !(r.selector.type === classification.type && r.selector.modifiers === classification.modifiers)); } public deregisterTokenType(id: string): void { delete this.tokenTypeById[id]; delete this.tokenStylingSchema.properties[id]; } public deregisterTokenModifier(id: string): void { delete this.tokenModifierById[id]; delete this.tokenStylingSchema.properties[`*.${id}`]; } public getTokenTypes(): TokenTypeOrModifierContribution[] { return Object.keys(this.tokenTypeById).map(id => this.tokenTypeById[id]); } public getTokenModifiers(): TokenTypeOrModifierContribution[] { return Object.keys(this.tokenModifierById).map(id => this.tokenModifierById[id]); } public getTokenStylingSchema(): IJSONSchema { return this.tokenStylingSchema; } public getTokenStylingDefaultRules(): TokenStylingDefaultRule[] { return this.tokenStylingDefaultRules; } public toString() { let sorter = (a: string, b: string) => { let cat1 = a.indexOf('.') === -1 ? 0 : 1; let cat2 = b.indexOf('.') === -1 ? 0 : 1; if (cat1 !== cat2) { return cat1 - cat2; } return a.localeCompare(b); }; return Object.keys(this.tokenTypeById).sort(sorter).map(k => `- \`${k}\`: ${this.tokenTypeById[k].description}`).join('\n'); } } const tokenClassificationRegistry = new TokenClassificationRegistry(); platform.Registry.add(Extensions.TokenClassificationContribution, tokenClassificationRegistry); registerDefaultClassifications(); function registerDefaultClassifications(): void { function registerTokenType(id: string, description: string, scopesToProbe: ProbeScope[] = [], extendsTC?: string, deprecationMessage?: string): string { tokenClassificationRegistry.registerTokenType(id, description, deprecationMessage); if (scopesToProbe || extendsTC) { const classification = tokenClassificationRegistry.getTokenClassification(id, []); tokenClassificationRegistry.registerTokenStyleDefault(classification!, { scopesToProbe, light: extendsTC, dark: extendsTC, hc: extendsTC }); } return id; } // default token types registerTokenType('comment', nls.localize('comment', "Style for comments."), [['comment']]); registerTokenType('string', nls.localize('string', "Style for strings."), [['string']]); registerTokenType('keyword', nls.localize('keyword', "Style for keywords."), [['keyword.control']]); registerTokenType('number', nls.localize('number', "Style for numbers."), [['constant.numeric']]); registerTokenType('regexp', nls.localize('regexp', "Style for expressions."), [['constant.regexp']]); registerTokenType('operator', nls.localize('operator', "Style for operators."), [['keyword.operator']]); registerTokenType('namespace', nls.localize('namespace', "Style for namespaces."), [['entity.name.namespace']]); registerTokenType('type', nls.localize('type', "Style for types."), [['entity.name.type'], ['support.type'], ['support.class']]); registerTokenType('struct', nls.localize('struct', "Style for structs."), [['storage.type.struct']], 'type'); registerTokenType('class', nls.localize('class', "Style for classes."), [['entity.name.type.class']], 'type'); registerTokenType('interface', nls.localize('interface', "Style for interfaces."), [['entity.name.type.interface']], 'type'); registerTokenType('enum', nls.localize('enum', "Style for enums."), [['entity.name.type.enum']], 'type'); registerTokenType('typeParameter', nls.localize('typeParameter', "Style for type parameters."), [['entity.name.type', 'meta.type.parameters']], 'type'); registerTokenType('function', nls.localize('function', "Style for functions"), [['entity.name.function'], ['support.function']]); registerTokenType('member', nls.localize('member', "Style for member"), [['entity.name.function.member'], ['support.function']]); registerTokenType('macro', nls.localize('macro', "Style for macros."), [['entity.name.other.preprocessor.macro']], 'function'); registerTokenType('variable', nls.localize('variable', "Style for variables."), [['variable'], ['entity.name.variable']]); registerTokenType('constant', nls.localize('constant', "Style for constants."), [['variable.other.constant']], 'variable'); registerTokenType('parameter', nls.localize('parameter', "Style for parameters."), [['variable.parameter']], 'variable'); registerTokenType('property', nls.localize('property', "Style for properties."), [['variable.other.property']], 'variable'); registerTokenType('label', nls.localize('labels', "Style for labels. "), undefined); // default token modifiers tokenClassificationRegistry.registerTokenModifier('declaration', nls.localize('declaration', "Style for all symbol declarations."), undefined); tokenClassificationRegistry.registerTokenModifier('documentation', nls.localize('documentation', "Style to use for references in documentation."), undefined); tokenClassificationRegistry.registerTokenModifier('static', nls.localize('static', "Style to use for symbols that are static."), undefined); tokenClassificationRegistry.registerTokenModifier('abstract', nls.localize('abstract', "Style to use for symbols that are abstract."), undefined); tokenClassificationRegistry.registerTokenModifier('deprecated', nls.localize('deprecated', "Style to use for symbols that are deprecated."), undefined); tokenClassificationRegistry.registerTokenModifier('modification', nls.localize('modification', "Style to use for write accesses."), undefined); tokenClassificationRegistry.registerTokenModifier('async', nls.localize('async', "Style to use for symbols that are async."), undefined); tokenClassificationRegistry.registerTokenModifier('readonly', nls.localize('readonly', "Style to use for symbols that are readonly."), undefined); } export function getTokenClassificationRegistry(): ITokenClassificationRegistry { return tokenClassificationRegistry; } function bitCount(u: number) { // https://blogs.msdn.microsoft.com/jeuge/2005/06/08/bit-fiddling-3/ const uCount = u - ((u >> 1) & 0o33333333333) - ((u >> 2) & 0o11111111111); return ((uCount + (uCount >> 3)) & 0o30707070707) % 63; } function getTokenStylingScore(classification: TokenClassification) { return bitCount(classification.modifiers) + ((classification.type !== TOKEN_TYPE_WILDCARD_NUM) ? 1 : 0); } function getStylingSchemeEntry(description?: string, deprecationMessage?: string): IJSONSchema { return { description, deprecationMessage, defaultSnippets: [{ body: '${1:#ff0000}' }], anyOf: [ { type: 'string', format: 'color-hex' }, { $ref: '#definitions/style' } ] }; } export const tokenStylingSchemaId = 'vscode://schemas/token-styling'; let schemaRegistry = platform.Registry.as<IJSONContributionRegistry>(JSONExtensions.JSONContribution); schemaRegistry.registerSchema(tokenStylingSchemaId, tokenClassificationRegistry.getTokenStylingSchema()); const delayer = new RunOnceScheduler(() => schemaRegistry.notifySchemaChanged(tokenStylingSchemaId), 200); tokenClassificationRegistry.onDidChangeSchema(() => { if (!delayer.isScheduled()) { delayer.schedule(); } });
src/vs/platform/theme/common/tokenClassificationRegistry.ts
0
https://github.com/microsoft/vscode/commit/8046438bb13cc424399978a895530f9076a7045e
[ 0.000490075268317014, 0.00019313968368805945, 0.00016412220429629087, 0.0001706301118247211, 0.0000683564503560774 ]
{ "id": 4, "code_window": [ "\t\t\t}\n", "\t\t},\n", "\t\t\"nonComposeBase\": {\n", "\t\t\t\"type\": \"object\",\n", "\t\t\t\"additionalProperties\": false,\n", "\t\t\t\"properties\": {\n", "\t\t\t\t\"appPort\": {\n", "\t\t\t\t\t\"type\": [\n", "\t\t\t\t\t\t\"integer\",\n", "\t\t\t\t\t\t\"string\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "extensions/configuration-editing/schemas/devContainer.schema.json", "type": "replace", "edit_start_line_idx": 67 }
{ "$schema": "http://json-schema.org/draft-07/schema#", "description": "Defines a dev container", "allowComments": true, "type": "object", "additionalProperties": false, "definitions": { "devContainerCommon": { "type": "object", "additionalProperties": false, "properties": { "name": { "type": "string", "description": "A name to show for the workspace folder." }, "extensions": { "type": "array", "description": "An array of extensions that should be installed into the container.", "items": { "type": "string", "pattern": "^([a-z0-9A-Z][a-z0-9\\-A-Z]*)\\.([a-z0-9A-Z][a-z0-9\\-A-Z]*)$", "errorMessage": "Expected format '${publisher}.${name}'. Example: 'vscode.csharp'." } }, "settings": { "$ref": "vscode://schemas/settings/machine", "description": "Machine specific settings that should be copied into the container." }, "forwardPorts": { "type": "array", "description": "Ports that are forwarded from the container to the local machine.", "items": { "type": "integer" } }, "remoteEnv": { "type": "object", "additionalProperties": { "type": [ "string", "null" ] }, "description": "Remote environment variables." }, "remoteUser": { "type": "string", "description": "The user VS Code Server will be started with. The default is the same user as the container." }, "postCreateCommand": { "type": [ "string", "array" ], "description": "A command to run after creating the container. If this is a single string, it will be run in a shell. If this is an array of strings, it will be run as a single command without shell.", "items": { "type": "string" } }, "devPort": { "type": "integer", "description": "The port VS Code can use to connect to its backend." } } }, "nonComposeBase": { "type": "object", "additionalProperties": false, "properties": { "appPort": { "type": [ "integer", "string", "array" ], "description": "Application ports that are exposed by the container. This can be a single port or an array of ports. Each port can be a number or a string. A number is mapped to the same port on the host. A string is passed to Docker unchanged and can be used to map ports differently, e.g. \"8000:8010\".", "items": { "type": [ "integer", "string" ] } }, "containerEnv": { "type": "object", "additionalProperties": { "type": "string" }, "description": "Container environment variables." }, "containerUser": { "type": "string", "description": "The user the container will be started with. The default is the user on the Docker image." }, "updateRemoteUserUID": { "type": "boolean", "description": "Controls whether on Linux the container's user should be updated with the local user's UID and GID. On by default." }, "mounts": { "type": "array", "description": "Mount points to set up when creating the container. See Docker's documentation for the --mount option for the supported syntax.", "items": { "type": "string" } }, "runArgs": { "type": "array", "description": "The arguments required when starting in the container.", "items": { "type": "string" } }, "shutdownAction": { "type": "string", "enum": [ "none", "stopContainer" ], "description": "Action to take when the VS Code window is closed. The default is to stop the container." }, "overrideCommand": { "type": "boolean", "description": "Whether to overwrite the command specified in the image. The default is true." }, "workspaceFolder": { "type": "string", "description": "The path of the workspace folder inside the container." }, "workspaceMount": { "type": "string", "description": "The --mount parameter for docker run. The default is to mount the project folder at /workspaces/$project." } } }, "dockerFileContainer": { "type": "object", "additionalProperties": false, "properties": { "dockerFile": { "type": "string", "description": "The location of the Dockerfile that defines the contents of the container. The path is relative to the folder containing the `devcontainer.json` file." }, "context": { "type": "string", "description": "The location of the context folder for building the Docker image. The path is relative to the folder containing the `devcontainer.json` file." } }, "required": [ "dockerFile" ] }, "imageContainer": { "type": "object", "additionalProperties": false, "properties": { "image": { "type": "string", "description": "The docker image that will be used to create the container." } }, "required": [ "image" ] }, "composeContainer": { "type": "object", "additionalProperties": false, "properties": { "dockerComposeFile": { "type": [ "string", "array" ], "description": "The name of the docker-compose file(s) used to start the services.", "items": { "type": "string" } }, "service": { "type": "string", "description": "The service you want to work on." }, "runServices": { "type": "array", "description": "An array of services that should be started and stopped.", "items": { "type": "string" } }, "workspaceFolder": { "type": "string", "description": "The path of the workspace folder inside the container." }, "shutdownAction": { "type": "string", "enum": [ "none", "stopCompose" ], "description": "Action to take when the VS Code window is closed. The default is to stop the containers." } }, "required": [ "dockerComposeFile", "service", "workspaceFolder" ] } }, "allOf": [ { "oneOf": [ { "allOf": [ { "oneOf": [ { "$ref": "#/definitions/dockerFileContainer" }, { "$ref": "#/definitions/imageContainer" } ] }, { "$ref": "#/definitions/nonComposeBase" } ] }, { "$ref": "#/definitions/composeContainer" } ] }, { "$ref": "#/definitions/devContainerCommon" } ] }
extensions/configuration-editing/schemas/devContainer.schema.json
1
https://github.com/microsoft/vscode/commit/8046438bb13cc424399978a895530f9076a7045e
[ 0.9866510629653931, 0.04133107513189316, 0.00016337120905518532, 0.000167948252055794, 0.19711293280124664 ]
{ "id": 4, "code_window": [ "\t\t\t}\n", "\t\t},\n", "\t\t\"nonComposeBase\": {\n", "\t\t\t\"type\": \"object\",\n", "\t\t\t\"additionalProperties\": false,\n", "\t\t\t\"properties\": {\n", "\t\t\t\t\"appPort\": {\n", "\t\t\t\t\t\"type\": [\n", "\t\t\t\t\t\t\"integer\",\n", "\t\t\t\t\t\t\"string\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "extensions/configuration-editing/schemas/devContainer.schema.json", "type": "replace", "edit_start_line_idx": 67 }
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. # yarn lockfile v1 "@types/node@^12.11.7": version "12.11.7" resolved "https://registry.yarnpkg.com/@types/node/-/node-12.11.7.tgz#57682a9771a3f7b09c2497f28129a0462966524a" integrity sha512-JNbGaHFCLwgHn/iCckiGSOZ1XYHsKFwREtzPwSGCVld1SGhOlmZw2D4ZI94HQCrBHbADzW9m4LER/8olJTRGHA== vscode-nls@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/vscode-nls/-/vscode-nls-4.0.0.tgz#4001c8a6caba5cedb23a9c5ce1090395c0e44002" integrity sha512-qCfdzcH+0LgQnBpZA53bA32kzp9rpq/f66Som577ObeuDlFIrtbEJ+A/+CCxjIh4G8dpJYNCKIsxpRAHIfsbNw==
extensions/gulp/yarn.lock
0
https://github.com/microsoft/vscode/commit/8046438bb13cc424399978a895530f9076a7045e
[ 0.00016655508079566061, 0.00016646500444039702, 0.0001663749135332182, 0.00016646500444039702, 9.0083631221205e-8 ]
{ "id": 4, "code_window": [ "\t\t\t}\n", "\t\t},\n", "\t\t\"nonComposeBase\": {\n", "\t\t\t\"type\": \"object\",\n", "\t\t\t\"additionalProperties\": false,\n", "\t\t\t\"properties\": {\n", "\t\t\t\t\"appPort\": {\n", "\t\t\t\t\t\"type\": [\n", "\t\t\t\t\t\t\"integer\",\n", "\t\t\t\t\t\t\"string\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "extensions/configuration-editing/schemas/devContainer.schema.json", "type": "replace", "edit_start_line_idx": 67 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as arrays from 'vs/base/common/arrays'; import { localize } from 'vs/nls'; import { Event } from 'vs/base/common/event'; import { onUnexpectedError } from 'vs/base/common/errors'; import { Disposable } from 'vs/base/common/lifecycle'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IExtensionManagementService, ILocalExtension, IExtensionIdentifier, InstallOperation } from 'vs/platform/extensionManagement/common/extensionManagement'; import { IWorkbenchExtensionEnablementService, EnablementState, IExtensionTipsService } from 'vs/workbench/services/extensionManagement/common/extensionManagement'; import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle'; import { IWorkbenchContribution } from 'vs/workbench/common/contributions'; import { ServicesAccessor, IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { areSameExtensions } from 'vs/platform/extensionManagement/common/extensionManagementUtil'; import { Severity, INotificationService } from 'vs/platform/notification/common/notification'; export interface IExtensionStatus { identifier: IExtensionIdentifier; local: ILocalExtension; globallyEnabled: boolean; } export class KeymapExtensions extends Disposable implements IWorkbenchContribution { constructor( @IInstantiationService private readonly instantiationService: IInstantiationService, @IWorkbenchExtensionEnablementService private readonly extensionEnablementService: IWorkbenchExtensionEnablementService, @IExtensionTipsService private readonly tipsService: IExtensionTipsService, @ILifecycleService lifecycleService: ILifecycleService, @INotificationService private readonly notificationService: INotificationService, @ITelemetryService private readonly telemetryService: ITelemetryService, ) { super(); this._register(lifecycleService.onShutdown(() => this.dispose())); this._register(instantiationService.invokeFunction(onExtensionChanged)((identifiers => { Promise.all(identifiers.map(identifier => this.checkForOtherKeymaps(identifier))) .then(undefined, onUnexpectedError); }))); } private checkForOtherKeymaps(extensionIdentifier: IExtensionIdentifier): Promise<void> { return this.instantiationService.invokeFunction(getInstalledExtensions).then(extensions => { const keymaps = extensions.filter(extension => isKeymapExtension(this.tipsService, extension)); const extension = arrays.first(keymaps, extension => areSameExtensions(extension.identifier, extensionIdentifier)); if (extension && extension.globallyEnabled) { const otherKeymaps = keymaps.filter(extension => !areSameExtensions(extension.identifier, extensionIdentifier) && extension.globallyEnabled); if (otherKeymaps.length) { return this.promptForDisablingOtherKeymaps(extension, otherKeymaps); } } return undefined; }); } private promptForDisablingOtherKeymaps(newKeymap: IExtensionStatus, oldKeymaps: IExtensionStatus[]): void { const onPrompt = (confirmed: boolean) => { const telemetryData: { [key: string]: any; } = { newKeymap: newKeymap.identifier, oldKeymaps: oldKeymaps.map(k => k.identifier), confirmed }; /* __GDPR__ "disableOtherKeymaps" : { "newKeymap": { "${inline}": [ "${ExtensionIdentifier}" ] }, "oldKeymaps": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "confirmed" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ this.telemetryService.publicLog('disableOtherKeymaps', telemetryData); if (confirmed) { this.extensionEnablementService.setEnablement(oldKeymaps.map(keymap => keymap.local), EnablementState.DisabledGlobally); } }; this.notificationService.prompt(Severity.Info, localize('disableOtherKeymapsConfirmation', "Disable other keymaps ({0}) to avoid conflicts between keybindings?", oldKeymaps.map(k => `'${k.local.manifest.displayName}'`).join(', ')), [{ label: localize('yes', "Yes"), run: () => onPrompt(true) }, { label: localize('no', "No"), run: () => onPrompt(false) }] ); } } export function onExtensionChanged(accessor: ServicesAccessor): Event<IExtensionIdentifier[]> { const extensionService = accessor.get(IExtensionManagementService); const extensionEnablementService = accessor.get(IWorkbenchExtensionEnablementService); const onDidInstallExtension = Event.chain(extensionService.onDidInstallExtension) .filter(e => e.operation === InstallOperation.Install) .event; return Event.debounce<IExtensionIdentifier[], IExtensionIdentifier[]>(Event.any( Event.chain(Event.any(onDidInstallExtension, extensionService.onDidUninstallExtension)) .map(e => [e.identifier]) .event, Event.map(extensionEnablementService.onEnablementChanged, extensions => extensions.map(e => e.identifier)) ), (result: IExtensionIdentifier[] | undefined, identifiers: IExtensionIdentifier[]) => { result = result || []; for (const identifier of identifiers) { if (result.some(l => !areSameExtensions(l, identifier))) { result.push(identifier); } } return result; }); } export async function getInstalledExtensions(accessor: ServicesAccessor): Promise<IExtensionStatus[]> { const extensionService = accessor.get(IExtensionManagementService); const extensionEnablementService = accessor.get(IWorkbenchExtensionEnablementService); const extensions = await extensionService.getInstalled(); return extensions.map(extension => { return { identifier: extension.identifier, local: extension, globallyEnabled: extensionEnablementService.isEnabled(extension) }; }); } export function isKeymapExtension(tipsService: IExtensionTipsService, extension: IExtensionStatus): boolean { const cats = extension.local.manifest.categories; return cats && cats.indexOf('Keymaps') !== -1 || tipsService.getKeymapRecommendations().some(({ extensionId }) => areSameExtensions({ id: extensionId }, extension.local.identifier)); }
src/vs/workbench/contrib/extensions/common/extensionsUtils.ts
0
https://github.com/microsoft/vscode/commit/8046438bb13cc424399978a895530f9076a7045e
[ 0.00017372459114994854, 0.00017067650333046913, 0.00016868139209691435, 0.00017020459927152842, 0.000001622703962311789 ]
{ "id": 4, "code_window": [ "\t\t\t}\n", "\t\t},\n", "\t\t\"nonComposeBase\": {\n", "\t\t\t\"type\": \"object\",\n", "\t\t\t\"additionalProperties\": false,\n", "\t\t\t\"properties\": {\n", "\t\t\t\t\"appPort\": {\n", "\t\t\t\t\t\"type\": [\n", "\t\t\t\t\t\t\"integer\",\n", "\t\t\t\t\t\t\"string\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "extensions/configuration-editing/schemas/devContainer.schema.json", "type": "replace", "edit_start_line_idx": 67 }
{ "registrations": [ { "component": { "type": "git", "git": { "name": "ionide/ionide-fsgrammar", "repositoryUrl": "https://github.com/ionide/ionide-fsgrammar", "commitHash": "b4f43aafa6f843707410fabe9f904ec04fa536dc" } }, "license": "MIT", "description": "The file syntaxes/fsharp.json was included from https://github.com/ionide/ionide-fsgrammar/blob/master/grammar/fsharp.json.", "version": "0.0.0" } ], "version": 1 }
extensions/fsharp/cgmanifest.json
0
https://github.com/microsoft/vscode/commit/8046438bb13cc424399978a895530f9076a7045e
[ 0.000172216838109307, 0.0001703477610135451, 0.0001684786839177832, 0.0001703477610135451, 0.0000018690770957618952 ]
{ "id": 5, "code_window": [ "\t\t\t\t}\n", "\t\t\t}\n", "\t\t},\n", "\t\t\"dockerFileContainer\": {\n", "\t\t\t\"type\": \"object\",\n", "\t\t\t\"additionalProperties\": false,\n", "\t\t\t\"properties\": {\n", "\t\t\t\t\"dockerFile\": {\n", "\t\t\t\t\t\"type\": \"string\",\n", "\t\t\t\t\t\"description\": \"The location of the Dockerfile that defines the contents of the container. The path is relative to the folder containing the `devcontainer.json` file.\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "extensions/configuration-editing/schemas/devContainer.schema.json", "type": "replace", "edit_start_line_idx": 136 }
{ "$schema": "http://json-schema.org/draft-07/schema#", "description": "Defines a dev container", "allowComments": true, "type": "object", "additionalProperties": false, "definitions": { "devContainerCommon": { "type": "object", "additionalProperties": false, "properties": { "name": { "type": "string", "description": "A name to show for the workspace folder." }, "extensions": { "type": "array", "description": "An array of extensions that should be installed into the container.", "items": { "type": "string", "pattern": "^([a-z0-9A-Z][a-z0-9\\-A-Z]*)\\.([a-z0-9A-Z][a-z0-9\\-A-Z]*)$", "errorMessage": "Expected format '${publisher}.${name}'. Example: 'vscode.csharp'." } }, "settings": { "$ref": "vscode://schemas/settings/machine", "description": "Machine specific settings that should be copied into the container." }, "forwardPorts": { "type": "array", "description": "Ports that are forwarded from the container to the local machine.", "items": { "type": "integer" } }, "remoteEnv": { "type": "object", "additionalProperties": { "type": [ "string", "null" ] }, "description": "Remote environment variables." }, "remoteUser": { "type": "string", "description": "The user VS Code Server will be started with. The default is the same user as the container." }, "postCreateCommand": { "type": [ "string", "array" ], "description": "A command to run after creating the container. If this is a single string, it will be run in a shell. If this is an array of strings, it will be run as a single command without shell.", "items": { "type": "string" } }, "devPort": { "type": "integer", "description": "The port VS Code can use to connect to its backend." } } }, "nonComposeBase": { "type": "object", "additionalProperties": false, "properties": { "appPort": { "type": [ "integer", "string", "array" ], "description": "Application ports that are exposed by the container. This can be a single port or an array of ports. Each port can be a number or a string. A number is mapped to the same port on the host. A string is passed to Docker unchanged and can be used to map ports differently, e.g. \"8000:8010\".", "items": { "type": [ "integer", "string" ] } }, "containerEnv": { "type": "object", "additionalProperties": { "type": "string" }, "description": "Container environment variables." }, "containerUser": { "type": "string", "description": "The user the container will be started with. The default is the user on the Docker image." }, "updateRemoteUserUID": { "type": "boolean", "description": "Controls whether on Linux the container's user should be updated with the local user's UID and GID. On by default." }, "mounts": { "type": "array", "description": "Mount points to set up when creating the container. See Docker's documentation for the --mount option for the supported syntax.", "items": { "type": "string" } }, "runArgs": { "type": "array", "description": "The arguments required when starting in the container.", "items": { "type": "string" } }, "shutdownAction": { "type": "string", "enum": [ "none", "stopContainer" ], "description": "Action to take when the VS Code window is closed. The default is to stop the container." }, "overrideCommand": { "type": "boolean", "description": "Whether to overwrite the command specified in the image. The default is true." }, "workspaceFolder": { "type": "string", "description": "The path of the workspace folder inside the container." }, "workspaceMount": { "type": "string", "description": "The --mount parameter for docker run. The default is to mount the project folder at /workspaces/$project." } } }, "dockerFileContainer": { "type": "object", "additionalProperties": false, "properties": { "dockerFile": { "type": "string", "description": "The location of the Dockerfile that defines the contents of the container. The path is relative to the folder containing the `devcontainer.json` file." }, "context": { "type": "string", "description": "The location of the context folder for building the Docker image. The path is relative to the folder containing the `devcontainer.json` file." } }, "required": [ "dockerFile" ] }, "imageContainer": { "type": "object", "additionalProperties": false, "properties": { "image": { "type": "string", "description": "The docker image that will be used to create the container." } }, "required": [ "image" ] }, "composeContainer": { "type": "object", "additionalProperties": false, "properties": { "dockerComposeFile": { "type": [ "string", "array" ], "description": "The name of the docker-compose file(s) used to start the services.", "items": { "type": "string" } }, "service": { "type": "string", "description": "The service you want to work on." }, "runServices": { "type": "array", "description": "An array of services that should be started and stopped.", "items": { "type": "string" } }, "workspaceFolder": { "type": "string", "description": "The path of the workspace folder inside the container." }, "shutdownAction": { "type": "string", "enum": [ "none", "stopCompose" ], "description": "Action to take when the VS Code window is closed. The default is to stop the containers." } }, "required": [ "dockerComposeFile", "service", "workspaceFolder" ] } }, "allOf": [ { "oneOf": [ { "allOf": [ { "oneOf": [ { "$ref": "#/definitions/dockerFileContainer" }, { "$ref": "#/definitions/imageContainer" } ] }, { "$ref": "#/definitions/nonComposeBase" } ] }, { "$ref": "#/definitions/composeContainer" } ] }, { "$ref": "#/definitions/devContainerCommon" } ] }
extensions/configuration-editing/schemas/devContainer.schema.json
1
https://github.com/microsoft/vscode/commit/8046438bb13cc424399978a895530f9076a7045e
[ 0.4666632413864136, 0.0383976586163044, 0.00016407121438533068, 0.0003504797932691872, 0.1259480118751526 ]
{ "id": 5, "code_window": [ "\t\t\t\t}\n", "\t\t\t}\n", "\t\t},\n", "\t\t\"dockerFileContainer\": {\n", "\t\t\t\"type\": \"object\",\n", "\t\t\t\"additionalProperties\": false,\n", "\t\t\t\"properties\": {\n", "\t\t\t\t\"dockerFile\": {\n", "\t\t\t\t\t\"type\": \"string\",\n", "\t\t\t\t\t\"description\": \"The location of the Dockerfile that defines the contents of the container. The path is relative to the folder containing the `devcontainer.json` file.\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "extensions/configuration-editing/schemas/devContainer.schema.json", "type": "replace", "edit_start_line_idx": 136 }
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" clip-rule="evenodd" d="M5.56253 2.51577C3.46348 3.4501 2 5.55414 2 7.99999C2 11.3137 4.68629 14 8 14C11.3137 14 14 11.3137 14 7.99999C14 5.32519 12.2497 3.05919 9.83199 2.28482L9.52968 3.23832C11.5429 3.88454 13 5.7721 13 7.99999C13 10.7614 10.7614 13 8 13C5.23858 13 3 10.7614 3 7.99999C3 6.31104 3.83742 4.81767 5.11969 3.91245L5.56253 2.51577Z" fill="#424242"/> <path fill-rule="evenodd" clip-rule="evenodd" d="M5 3H2V2H5.5L6 2.5V6H5V3Z" fill="#424242"/> </svg>
extensions/git/resources/icons/light/refresh.svg
0
https://github.com/microsoft/vscode/commit/8046438bb13cc424399978a895530f9076a7045e
[ 0.00016858811432030052, 0.00016858811432030052, 0.00016858811432030052, 0.00016858811432030052, 0 ]
{ "id": 5, "code_window": [ "\t\t\t\t}\n", "\t\t\t}\n", "\t\t},\n", "\t\t\"dockerFileContainer\": {\n", "\t\t\t\"type\": \"object\",\n", "\t\t\t\"additionalProperties\": false,\n", "\t\t\t\"properties\": {\n", "\t\t\t\t\"dockerFile\": {\n", "\t\t\t\t\t\"type\": \"string\",\n", "\t\t\t\t\t\"description\": \"The location of the Dockerfile that defines the contents of the container. The path is relative to the folder containing the `devcontainer.json` file.\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "extensions/configuration-editing/schemas/devContainer.schema.json", "type": "replace", "edit_start_line_idx": 136 }
src/vs/workbench/services/search/test/node/fixtures/examples/subfolder/anotherfolder/anotherfile.txt
0
https://github.com/microsoft/vscode/commit/8046438bb13cc424399978a895530f9076a7045e
[ 0.00016954437887761742, 0.00016954437887761742, 0.00016954437887761742, 0.00016954437887761742, 0 ]
{ "id": 5, "code_window": [ "\t\t\t\t}\n", "\t\t\t}\n", "\t\t},\n", "\t\t\"dockerFileContainer\": {\n", "\t\t\t\"type\": \"object\",\n", "\t\t\t\"additionalProperties\": false,\n", "\t\t\t\"properties\": {\n", "\t\t\t\t\"dockerFile\": {\n", "\t\t\t\t\t\"type\": \"string\",\n", "\t\t\t\t\t\"description\": \"The location of the Dockerfile that defines the contents of the container. The path is relative to the folder containing the `devcontainer.json` file.\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "extensions/configuration-editing/schemas/devContainer.schema.json", "type": "replace", "edit_start_line_idx": 136 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as fs from 'fs'; import * as path from 'path'; import { commands, CompletionItem, CompletionItemKind, ExtensionContext, languages, Position, Range, SnippetString, TextEdit, window, workspace, TextDocument, CompletionContext, CancellationToken, ProviderResult, CompletionList } from 'vscode'; import { Disposable, LanguageClient, LanguageClientOptions, ServerOptions, TransportKind, ProvideCompletionItemsSignature } from 'vscode-languageclient'; import * as nls from 'vscode-nls'; import { getCustomDataPathsFromAllExtensions, getCustomDataPathsInAllWorkspaces } from './customData'; const localize = nls.loadMessageBundle(); // this method is called when vs code is activated export function activate(context: ExtensionContext) { let serverMain = readJSONFile(context.asAbsolutePath('./server/package.json')).main; let serverModule = context.asAbsolutePath(path.join('server', serverMain)); // The debug options for the server let debugOptions = { execArgv: ['--nolazy', '--inspect=6044'] }; // If the extension is launch in debug mode the debug server options are use // Otherwise the run options are used let serverOptions: ServerOptions = { run: { module: serverModule, transport: TransportKind.ipc }, debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions } }; let documentSelector = ['css', 'scss', 'less']; let dataPaths = [ ...getCustomDataPathsInAllWorkspaces(workspace.workspaceFolders), ...getCustomDataPathsFromAllExtensions() ]; // Options to control the language client let clientOptions: LanguageClientOptions = { documentSelector, synchronize: { configurationSection: ['css', 'scss', 'less'] }, initializationOptions: { dataPaths }, middleware: { provideCompletionItem(document: TextDocument, position: Position, context: CompletionContext, token: CancellationToken, next: ProvideCompletionItemsSignature): ProviderResult<CompletionItem[] | CompletionList> { // testing the replace / insert mode function updateRanges(item: CompletionItem) { const range = item.range; if (range instanceof Range && range.end.isAfter(position) && range.start.isBeforeOrEqual(position)) { item.range = { inserting: new Range(range.start, position), replacing: range }; } } function updateLabel(item: CompletionItem) { if (item.kind === CompletionItemKind.Color) { item.label2 = { name: item.label, type: (item.documentation as string) }; } } // testing the new completion function updateProposals(r: CompletionItem[] | CompletionList | null | undefined): CompletionItem[] | CompletionList | null | undefined { if (r) { (Array.isArray(r) ? r : r.items).forEach(updateRanges); (Array.isArray(r) ? r : r.items).forEach(updateLabel); } return r; } const isThenable = <T>(obj: ProviderResult<T>): obj is Thenable<T> => obj && (<any>obj)['then']; const r = next(document, position, context, token); if (isThenable<CompletionItem[] | CompletionList | null | undefined>(r)) { return r.then(updateProposals); } return updateProposals(r); } } }; // Create the language client and start the client. let client = new LanguageClient('css', localize('cssserver.name', 'CSS Language Server'), serverOptions, clientOptions); client.registerProposedFeatures(); let disposable = client.start(); // Push the disposable to the context's subscriptions so that the // client can be deactivated on extension deactivation context.subscriptions.push(disposable); let indentationRules = { increaseIndentPattern: /(^.*\{[^}]*$)/, decreaseIndentPattern: /^\s*\}/ }; languages.setLanguageConfiguration('css', { wordPattern: /(#?-?\d*\.\d\w*%?)|(::?[\w-]*(?=[^,{;]*[,{]))|(([@#.!])?[\w-?]+%?|[@#!.])/g, indentationRules: indentationRules }); languages.setLanguageConfiguration('less', { wordPattern: /(#?-?\d*\.\d\w*%?)|(::?[\w-]+(?=[^,{;]*[,{]))|(([@#.!])?[\w-?]+%?|[@#!.])/g, indentationRules: indentationRules }); languages.setLanguageConfiguration('scss', { wordPattern: /(#?-?\d*\.\d\w*%?)|(::?[\w-]*(?=[^,{;]*[,{]))|(([@$#.!])?[\w-?]+%?|[@#!$.])/g, indentationRules: indentationRules }); client.onReady().then(() => { context.subscriptions.push(initCompletionProvider()); }); function initCompletionProvider(): Disposable { const regionCompletionRegExpr = /^(\s*)(\/(\*\s*(#\w*)?)?)?$/; return languages.registerCompletionItemProvider(documentSelector, { provideCompletionItems(doc, pos) { let lineUntilPos = doc.getText(new Range(new Position(pos.line, 0), pos)); let match = lineUntilPos.match(regionCompletionRegExpr); if (match) { let range = new Range(new Position(pos.line, match[1].length), pos); let beginProposal = new CompletionItem('#region', CompletionItemKind.Snippet); beginProposal.range = range; TextEdit.replace(range, '/* #region */'); beginProposal.insertText = new SnippetString('/* #region $1*/'); beginProposal.documentation = localize('folding.start', 'Folding Region Start'); beginProposal.filterText = match[2]; beginProposal.sortText = 'za'; let endProposal = new CompletionItem('#endregion', CompletionItemKind.Snippet); endProposal.range = range; endProposal.insertText = '/* #endregion */'; endProposal.documentation = localize('folding.end', 'Folding Region End'); endProposal.sortText = 'zb'; endProposal.filterText = match[2]; return [beginProposal, endProposal]; } return null; } }); } commands.registerCommand('_css.applyCodeAction', applyCodeAction); function applyCodeAction(uri: string, documentVersion: number, edits: TextEdit[]) { let textEditor = window.activeTextEditor; if (textEditor && textEditor.document.uri.toString() === uri) { if (textEditor.document.version !== documentVersion) { window.showInformationMessage(`CSS fix is outdated and can't be applied to the document.`); } textEditor.edit(mutator => { for (let edit of edits) { mutator.replace(client.protocol2CodeConverter.asRange(edit.range), edit.newText); } }).then(success => { if (!success) { window.showErrorMessage('Failed to apply CSS fix to the document. Please consider opening an issue with steps to reproduce.'); } }); } } } function readJSONFile(location: string) { try { return JSON.parse(fs.readFileSync(location).toString()); } catch (e) { console.log(`Problems reading ${location}: ${e}`); return {}; } }
extensions/css-language-features/client/src/cssMain.ts
0
https://github.com/microsoft/vscode/commit/8046438bb13cc424399978a895530f9076a7045e
[ 0.0001992739416891709, 0.00017217613640241325, 0.00016502437938470393, 0.00017055975331459194, 0.0000070279861574817915 ]
{ "id": 6, "code_window": [ "\t\t\t]\n", "\t\t},\n", "\t\t\"imageContainer\": {\n", "\t\t\t\"type\": \"object\",\n", "\t\t\t\"additionalProperties\": false,\n", "\t\t\t\"properties\": {\n", "\t\t\t\t\"image\": {\n", "\t\t\t\t\t\"type\": \"string\",\n", "\t\t\t\t\t\"description\": \"The docker image that will be used to create the container.\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "extensions/configuration-editing/schemas/devContainer.schema.json", "type": "replace", "edit_start_line_idx": 153 }
{ "$schema": "http://json-schema.org/draft-07/schema#", "description": "Configures an attached to container", "allowComments": true, "type": "object", "additionalProperties": false, "definitions": { "attachContainer": { "type": "object", "additionalProperties": false, "properties": { "workspaceFolder": { "type": "string", "description": "The path of the workspace folder inside the container." }, "forwardPorts": { "type": "array", "description": "Ports that are forwarded from the container to the local machine.", "items": { "type": "integer" } }, "settings": { "$ref": "vscode://schemas/settings/machine", "description": "Machine specific settings that should be copied into the container." }, "remoteEnv": { "type": "object", "additionalProperties": { "type": [ "string", "null" ] }, "description": "Remote environment variables." }, "remoteUser": { "type": "string", "description": "The user VS Code Server will be started with. The default is the same user as the container." }, "extensions": { "type": "array", "description": "An array of extensions that should be installed into the container.", "items": { "type": "string", "pattern": "^([a-z0-9A-Z][a-z0-9\\-A-Z]*)\\.([a-z0-9A-Z][a-z0-9\\-A-Z]*)$", "errorMessage": "Expected format '${publisher}.${name}'. Example: 'vscode.csharp'." } } } } }, "allOf": [ { "$ref": "#/definitions/attachContainer" } ] }
extensions/configuration-editing/schemas/attachContainer.schema.json
1
https://github.com/microsoft/vscode/commit/8046438bb13cc424399978a895530f9076a7045e
[ 0.0004766574129462242, 0.0002670956018846482, 0.00016427940863650292, 0.0002340048085898161, 0.000107662366644945 ]
{ "id": 6, "code_window": [ "\t\t\t]\n", "\t\t},\n", "\t\t\"imageContainer\": {\n", "\t\t\t\"type\": \"object\",\n", "\t\t\t\"additionalProperties\": false,\n", "\t\t\t\"properties\": {\n", "\t\t\t\t\"image\": {\n", "\t\t\t\t\t\"type\": \"string\",\n", "\t\t\t\t\t\"description\": \"The docker image that will be used to create the container.\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "extensions/configuration-editing/schemas/devContainer.schema.json", "type": "replace", "edit_start_line_idx": 153 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { extHostNamedCustomer } from 'vs/workbench/api/common/extHostCustomers'; import { MainContext, MainThreadConsoleShape, IExtHostContext } from 'vs/workbench/api/common/extHost.protocol'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { IRemoteConsoleLog, log } from 'vs/base/common/console'; import { logRemoteEntry } from 'vs/workbench/services/extensions/common/remoteConsoleUtil'; import { parseExtensionDevOptions } from 'vs/workbench/services/extensions/common/extensionDevOptions'; import { ILogService } from 'vs/platform/log/common/log'; import { IExtensionHostDebugService } from 'vs/platform/debug/common/extensionHostDebug'; @extHostNamedCustomer(MainContext.MainThreadConsole) export class MainThreadConsole implements MainThreadConsoleShape { private readonly _isExtensionDevHost: boolean; private readonly _isExtensionDevTestFromCli: boolean; constructor( extHostContext: IExtHostContext, @IEnvironmentService private readonly _environmentService: IEnvironmentService, @ILogService private readonly _logService: ILogService, @IExtensionHostDebugService private readonly _extensionHostDebugService: IExtensionHostDebugService, ) { const devOpts = parseExtensionDevOptions(this._environmentService); this._isExtensionDevHost = devOpts.isExtensionDevHost; this._isExtensionDevTestFromCli = devOpts.isExtensionDevTestFromCli; } dispose(): void { // } $logExtensionHostMessage(entry: IRemoteConsoleLog): void { // Send to local console unless we run tests from cli if (!this._isExtensionDevTestFromCli) { log(entry, 'Extension Host'); } // Log on main side if running tests from cli if (this._isExtensionDevTestFromCli) { logRemoteEntry(this._logService, entry); } // Broadcast to other windows if we are in development mode else if (this._environmentService.debugExtensionHost.debugId && (!this._environmentService.isBuilt || this._isExtensionDevHost)) { this._extensionHostDebugService.logToSession(this._environmentService.debugExtensionHost.debugId, entry); } } }
src/vs/workbench/api/browser/mainThreadConsole.ts
0
https://github.com/microsoft/vscode/commit/8046438bb13cc424399978a895530f9076a7045e
[ 0.00017300040053669363, 0.00016835215501487255, 0.00016454324941150844, 0.00016759286518208683, 0.0000033420294585084775 ]