hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
listlengths
5
5
{ "id": 0, "code_window": [ " displayName: Generate SBOM (client)\n", " inputs:\n", " BuildDropPath: $(agent.builddirectory)/VSCode-darwin-$(VSCODE_ARCH)\n", " PackageName: Visual Studio Code\n", "\n", " - publish: $(agent.builddirectory)/VSCode-darwin-$(VSCODE_ARCH)/_manifest\n", " displayName: Publish SBOM (client)\n", " artifact: $(ARTIFACT_PREFIX)sbom_client_darwin_$(VSCODE_ARCH)_sbom\n", "\n", " - task: AzureArtifacts.manifest-generator-task.manifest-generator-task.ManifestGeneratorTask@0\n", " displayName: Generate SBOM (server)\n", " inputs:\n", " BuildDropPath: $(agent.builddirectory)/vscode-server-darwin-$(VSCODE_ARCH)\n", " PackageName: Visual Studio Code Server\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "build/azure-pipelines/darwin/product-build-darwin.yml", "type": "replace", "edit_start_line_idx": 214 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { main } from './sign'; import * as path from 'path'; main([ process.env['EsrpCliDllPath']!, 'windows', process.env['ESRPPKI']!, process.env['ESRPAADUsername']!, process.env['ESRPAADPassword']!, path.dirname(process.argv[2]), path.basename(process.argv[2]) ]);
build/azure-pipelines/common/sign-win32.ts
0
https://github.com/microsoft/vscode/commit/6bad769697ec3e4ad65287d9345624328377fdd5
[ 0.0001733121316647157, 0.00017206199117936194, 0.00017081185069400817, 0.00017206199117936194, 0.0000012501404853537679 ]
{ "id": 0, "code_window": [ " displayName: Generate SBOM (client)\n", " inputs:\n", " BuildDropPath: $(agent.builddirectory)/VSCode-darwin-$(VSCODE_ARCH)\n", " PackageName: Visual Studio Code\n", "\n", " - publish: $(agent.builddirectory)/VSCode-darwin-$(VSCODE_ARCH)/_manifest\n", " displayName: Publish SBOM (client)\n", " artifact: $(ARTIFACT_PREFIX)sbom_client_darwin_$(VSCODE_ARCH)_sbom\n", "\n", " - task: AzureArtifacts.manifest-generator-task.manifest-generator-task.ManifestGeneratorTask@0\n", " displayName: Generate SBOM (server)\n", " inputs:\n", " BuildDropPath: $(agent.builddirectory)/vscode-server-darwin-$(VSCODE_ARCH)\n", " PackageName: Visual Studio Code Server\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "build/azure-pipelines/darwin/product-build-darwin.yml", "type": "replace", "edit_start_line_idx": 214 }
{ "displayName": "TypeScript Language Basics", "description": "Provides snippets, syntax highlighting, bracket matching and folding in TypeScript files." }
extensions/typescript-basics/package.nls.json
0
https://github.com/microsoft/vscode/commit/6bad769697ec3e4ad65287d9345624328377fdd5
[ 0.00016218818200286478, 0.00016218818200286478, 0.00016218818200286478, 0.00016218818200286478, 0 ]
{ "id": 1, "code_window": [ " BuildDropPath: $(agent.builddirectory)/vscode-server-darwin-$(VSCODE_ARCH)\n", " PackageName: Visual Studio Code Server\n", "\n", " - publish: $(agent.builddirectory)/vscode-server-darwin-$(VSCODE_ARCH)/_manifest\n", " displayName: Publish SBOM (server)\n", " artifact: $(ARTIFACT_PREFIX)sbom_server_darwin_$(VSCODE_ARCH)_sbom\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " - publish: $(agent.builddirectory)/VSCode-darwin-$(VSCODE_ARCH)/_manifest\n", " displayName: Publish SBOM (client)\n", " artifact: $(ARTIFACT_PREFIX)sbom_client_darwin_$(VSCODE_ARCH)_sbom\n", "\n" ], "file_path": "build/azure-pipelines/darwin/product-build-darwin.yml", "type": "add", "edit_start_line_idx": 224 }
parameters: - name: VSCODE_QUALITY type: string - name: VSCODE_ARCH type: string - name: VSCODE_CIBUILD type: boolean - name: VSCODE_RUN_UNIT_TESTS type: boolean - name: VSCODE_RUN_INTEGRATION_TESTS type: boolean - name: VSCODE_RUN_SMOKE_TESTS type: boolean steps: - ${{ if eq(parameters.VSCODE_QUALITY, 'oss') }}: - checkout: self fetchDepth: 1 retryCountOnTaskFailure: 3 - task: NodeTool@0 inputs: versionSpec: "16.x" - task: UsePythonVersion@0 inputs: versionSpec: "3.x" addToPath: true - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - template: ../distro/download-distro.yml - task: AzureKeyVault@1 displayName: "Azure Key Vault: Get Secrets" inputs: azureSubscription: "vscode-builds-subscription" KeyVaultName: vscode-build-secrets SecretsFilter: "github-distro-mixin-password,ESRP-PKI,esrp-aad-username,esrp-aad-password" - task: DownloadPipelineArtifact@2 inputs: artifact: Compilation path: $(Build.ArtifactStagingDirectory) displayName: Download compilation output - task: ExtractFiles@1 displayName: Extract compilation output inputs: archiveFilePatterns: "$(Build.ArtifactStagingDirectory)/compilation.tar.gz" cleanDestinationFolder: false - powershell: node build/setup-npm-registry.js $env:NPM_REGISTRY condition: and(succeeded(), ne(variables['NPM_REGISTRY'], 'none')) displayName: Setup NPM Registry - pwsh: | mkdir .build -ea 0 node build/azure-pipelines/common/computeNodeModulesCacheKey.js win32 $(VSCODE_ARCH) > .build/yarnlockhash displayName: Prepare node_modules cache key - task: Cache@2 inputs: key: '"node_modules" | .build/yarnlockhash' path: .build/node_modules_cache cacheHitVar: NODE_MODULES_RESTORED displayName: Restore node_modules cache - powershell: 7z.exe x .build/node_modules_cache/cache.7z -aoa condition: and(succeeded(), eq(variables.NODE_MODULES_RESTORED, 'true')) displayName: Extract node_modules cache - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" exec { npm config set registry "$env:NPM_REGISTRY" --location=project } exec { npm config set always-auth=true --location=project } exec { yarn config set registry "$env:NPM_REGISTRY" } condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'), ne(variables['NPM_REGISTRY'], 'none')) displayName: Setup NPM & Yarn - task: npmAuthenticate@0 inputs: workingFile: .npmrc condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'), ne(variables['NPM_REGISTRY'], 'none')) displayName: Setup NPM Authentication - powershell: | mkdir -Force .build/node-gyp displayName: Create custom node-gyp directory condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - powershell: | . ../../build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" # TODO: Should be replaced with upstream URL once https://github.com/nodejs/node-gyp/pull/2825 # gets merged. exec { git clone https://github.com/rzhao271/node-gyp.git . } "Cloning rzhao271/node-gyp failed" exec { git checkout 102b347da0c92c29f9c67df22e864e70249cf086 } "Checking out 102b347 failed" exec { npm install } "Building rzhao271/node-gyp failed" displayName: Install custom node-gyp workingDirectory: .build/node-gyp condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - powershell: | . build/azure-pipelines/win32/exec.ps1 . build/azure-pipelines/win32/retry.ps1 $ErrorActionPreference = "Stop" $env:npm_config_node_gyp="$(Join-Path $pwd.Path '.build/node-gyp/bin/node-gyp.js')" $env:npm_config_arch="$(VSCODE_ARCH)" $env:CHILD_CONCURRENCY="1" retry { exec { yarn --frozen-lockfile --check-files } } env: ELECTRON_SKIP_BINARY_DOWNLOAD: 1 PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1 GITHUB_TOKEN: "$(github-distro-mixin-password)" displayName: Install dependencies condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - powershell: node build/azure-pipelines/distro/mixin-npm condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) displayName: Mixin distro node modules - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" exec { node build/azure-pipelines/common/listNodeModules.js .build/node_modules_list.txt } exec { mkdir -Force .build/node_modules_cache } exec { 7z.exe a .build/node_modules_cache/cache.7z -mx3 `@.build/node_modules_list.txt } condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) displayName: Create node_modules archive - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - powershell: node build/azure-pipelines/distro/mixin-quality displayName: Mixin distro quality - template: ../common/install-builtin-extensions.yml - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - powershell: node build\lib\policies displayName: Generate Group Policy definitions retryCountOnTaskFailure: 3 - ${{ if eq(parameters.VSCODE_QUALITY, 'oss') }}: - powershell: yarn gulp "transpile-client-swc" "transpile-extensions" env: GITHUB_TOKEN: "$(github-distro-mixin-password)" displayName: Transpile - ${{ else }}: - ${{ if eq(parameters.VSCODE_QUALITY, 'insider') }}: - powershell: node build/win32/explorer-appx-fetcher .build/win32/appx displayName: Download Explorer Sparse Package - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" exec { yarn gulp "vscode-win32-$(VSCODE_ARCH)-min-ci" } exec { yarn gulp "vscode-win32-$(VSCODE_ARCH)-inno-updater" } echo "##vso[task.setvariable variable=BUILT_CLIENT]true" echo "##vso[task.setvariable variable=CodeSigningFolderPath]$(agent.builddirectory)/VSCode-win32-$(VSCODE_ARCH)" env: GITHUB_TOKEN: "$(github-distro-mixin-password)" displayName: Build client - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" exec { yarn gulp "vscode-reh-win32-$(VSCODE_ARCH)-min-ci" } mv ..\vscode-reh-win32-$(VSCODE_ARCH) ..\vscode-server-win32-$(VSCODE_ARCH) # TODO@joaomoreno echo "##vso[task.setvariable variable=BUILT_SERVER]true" echo "##vso[task.setvariable variable=CodeSigningFolderPath]$(CodeSigningFolderPath),$(agent.builddirectory)/vscode-server-win32-$(VSCODE_ARCH)" env: GITHUB_TOKEN: "$(github-distro-mixin-password)" displayName: Build server condition: and(succeeded(), ne(variables['VSCODE_ARCH'], 'arm64')) - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" exec { yarn gulp "vscode-reh-web-win32-$(VSCODE_ARCH)-min-ci" } mv ..\vscode-reh-web-win32-$(VSCODE_ARCH) ..\vscode-server-win32-$(VSCODE_ARCH)-web # TODO@joaomoreno echo "##vso[task.setvariable variable=BUILT_WEB]true" env: GITHUB_TOKEN: "$(github-distro-mixin-password)" displayName: Build server (web) condition: and(succeeded(), ne(variables['VSCODE_ARCH'], 'arm64')) - ${{ if or(eq(parameters.VSCODE_RUN_UNIT_TESTS, true), eq(parameters.VSCODE_RUN_INTEGRATION_TESTS, true), eq(parameters.VSCODE_RUN_SMOKE_TESTS, true)) }}: - template: product-build-win32-test.yml parameters: VSCODE_QUALITY: ${{ parameters.VSCODE_QUALITY }} VSCODE_ARCH: ${{ parameters.VSCODE_ARCH }} VSCODE_RUN_UNIT_TESTS: ${{ parameters.VSCODE_RUN_UNIT_TESTS }} VSCODE_RUN_INTEGRATION_TESTS: ${{ parameters.VSCODE_RUN_INTEGRATION_TESTS }} VSCODE_RUN_SMOKE_TESTS: ${{ parameters.VSCODE_RUN_SMOKE_TESTS }} - ${{ if ne(parameters.VSCODE_CIBUILD, true) }}: - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - task: DownloadPipelineArtifact@2 inputs: artifact: unsigned_vscode_cli_win32_$(VSCODE_ARCH)_cli patterns: "**" path: $(Build.ArtifactStagingDirectory)/cli displayName: Download VS Code CLI - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" $ArtifactName = (gci -Path "$(Build.ArtifactStagingDirectory)/cli" | Select-Object -last 1).FullName Expand-Archive -Path $ArtifactName -DestinationPath "$(Build.ArtifactStagingDirectory)/cli" $AppProductJson = Get-Content -Raw -Path "$(agent.builddirectory)\VSCode-win32-$(VSCODE_ARCH)\resources\app\product.json" | ConvertFrom-Json $CliAppName = $AppProductJson.tunnelApplicationName $AppName = $AppProductJson.applicationName Move-Item -Path "$(Build.ArtifactStagingDirectory)/cli/$AppName.exe" -Destination "$(agent.builddirectory)/VSCode-win32-$(VSCODE_ARCH)/bin/$CliAppName.exe" displayName: Move VS Code CLI - task: UseDotNet@2 inputs: version: 6.x - task: EsrpClientTool@1 displayName: Download ESRPClient - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" $EsrpClientTool = (gci -directory -filter EsrpClientTool_* $(Agent.RootDirectory)\_tasks | Select-Object -last 1).FullName $EsrpCliZip = (gci -recurse -filter esrpcli.*.zip $EsrpClientTool | Select-Object -last 1).FullName mkdir -p $(Agent.TempDirectory)\esrpcli Expand-Archive -Path $EsrpCliZip -DestinationPath $(Agent.TempDirectory)\esrpcli $EsrpCliDllPath = (gci -recurse -filter esrpcli.dll $(Agent.TempDirectory)\esrpcli | Select-Object -last 1).FullName echo "##vso[task.setvariable variable=EsrpCliDllPath]$EsrpCliDllPath" displayName: Find ESRP CLI - powershell: node build\azure-pipelines\common\sign $env:EsrpCliDllPath windows $(ESRP-PKI) $(esrp-aad-username) $(esrp-aad-password) $(CodeSigningFolderPath) '*.dll,*.exe,*.node' displayName: Codesign - ${{ if eq(parameters.VSCODE_QUALITY, 'insider') }}: - powershell: node build\azure-pipelines\common\sign $env:EsrpCliDllPath windows-appx $(ESRP-PKI) $(esrp-aad-username) $(esrp-aad-password) $(CodeSigningFolderPath) '*.appx' displayName: Codesign context menu appx package - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - powershell: | $PackageJson = Get-Content -Raw -Path ..\VSCode-win32-$(VSCODE_ARCH)\resources\app\package.json | ConvertFrom-Json $Version = $PackageJson.version echo "##vso[task.setvariable variable=VSCODE_VERSION]$Version" condition: succeededOrFailed() displayName: Get product version - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" $ArchivePath = ".build\win32-$(VSCODE_ARCH)\VSCode-win32-$(VSCODE_ARCH)-$(VSCODE_VERSION).zip" New-Item -ItemType Directory -Path .build\win32-$(VSCODE_ARCH) -Force exec { 7z.exe a -tzip $ArchivePath -x!CodeSignSummary*.md ..\VSCode-win32-$(VSCODE_ARCH)\* -r } echo "##vso[task.setvariable variable=CLIENT_PATH]$ArchivePath" condition: and(succeededOrFailed(), eq(variables['BUILT_CLIENT'], 'true')) displayName: Package client - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" $ArchivePath = ".build\win32-$(VSCODE_ARCH)\vscode-server-win32-$(VSCODE_ARCH).zip" New-Item -ItemType Directory -Path .build\win32-$(VSCODE_ARCH) -Force exec { 7z.exe a -tzip $ArchivePath ..\vscode-server-win32-$(VSCODE_ARCH)\* -r } echo "##vso[task.setvariable variable=SERVER_PATH]$ArchivePath" condition: and(succeededOrFailed(), eq(variables['BUILT_SERVER'], 'true')) displayName: Package server - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" $ArchivePath = ".build\win32-$(VSCODE_ARCH)\vscode-server-win32-$(VSCODE_ARCH)-web.zip" New-Item -ItemType Directory -Path .build\win32-$(VSCODE_ARCH) -Force exec { 7z.exe a -tzip $ArchivePath ..\vscode-server-win32-$(VSCODE_ARCH)-web\* -r } echo "##vso[task.setvariable variable=WEB_PATH]$ArchivePath" condition: and(succeededOrFailed(), eq(variables['BUILT_WEB'], 'true')) displayName: Package server (web) - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" $env:ESRPPKI = "$(ESRP-PKI)" $env:ESRPAADUsername = "$(esrp-aad-username)" $env:ESRPAADPassword = "$(esrp-aad-password)" exec { yarn gulp "vscode-win32-$(VSCODE_ARCH)-system-setup" --sign } $SetupPath = ".build\win32-$(VSCODE_ARCH)\system-setup\VSCodeSetup-$(VSCODE_ARCH)-$(VSCODE_VERSION).exe" mv .build\win32-$(VSCODE_ARCH)\system-setup\VSCodeSetup.exe $SetupPath echo "##vso[task.setvariable variable=SYSTEM_SETUP_PATH]$SetupPath" displayName: Build system setup - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" $env:ESRPPKI = "$(ESRP-PKI)" $env:ESRPAADUsername = "$(esrp-aad-username)" $env:ESRPAADPassword = "$(esrp-aad-password)" exec { yarn gulp "vscode-win32-$(VSCODE_ARCH)-user-setup" --sign } $SetupPath = ".build\win32-$(VSCODE_ARCH)\user-setup\VSCodeUserSetup-$(VSCODE_ARCH)-$(VSCODE_VERSION).exe" mv .build\win32-$(VSCODE_ARCH)\user-setup\VSCodeSetup.exe $SetupPath echo "##vso[task.setvariable variable=USER_SETUP_PATH]$SetupPath" displayName: Build user setup - powershell: echo "##vso[task.setvariable variable=ARTIFACT_PREFIX]attempt$(System.JobAttempt)_" condition: and(succeededOrFailed(), notIn(variables['Agent.JobStatus'], 'Succeeded', 'SucceededWithIssues')) displayName: Generate artifact prefix - task: AzureArtifacts.manifest-generator-task.manifest-generator-task.ManifestGeneratorTask@0 displayName: Generate SBOM (client) inputs: BuildDropPath: $(agent.builddirectory)/VSCode-win32-$(VSCODE_ARCH) PackageName: Visual Studio Code - publish: $(agent.builddirectory)/VSCode-win32-$(VSCODE_ARCH)/_manifest displayName: Publish SBOM (client) artifact: $(ARTIFACT_PREFIX)sbom_client_win32_$(VSCODE_ARCH) - task: AzureArtifacts.manifest-generator-task.manifest-generator-task.ManifestGeneratorTask@0 displayName: Generate SBOM (server) inputs: BuildDropPath: $(agent.builddirectory)/vscode-server-win32-$(VSCODE_ARCH) PackageName: Visual Studio Code Server condition: and(succeeded(), ne(variables['VSCODE_ARCH'], 'arm64')) - publish: $(agent.builddirectory)/vscode-server-win32-$(VSCODE_ARCH)/_manifest displayName: Publish SBOM (server) artifact: $(ARTIFACT_PREFIX)sbom_server_win32_$(VSCODE_ARCH) condition: and(succeeded(), ne(variables['VSCODE_ARCH'], 'arm64')) - publish: $(CLIENT_PATH) artifact: $(ARTIFACT_PREFIX)vscode_client_win32_$(VSCODE_ARCH)_archive condition: and(succeededOrFailed(), ne(variables['CLIENT_PATH'], '')) displayName: Publish archive - publish: $(SERVER_PATH) artifact: $(ARTIFACT_PREFIX)vscode_server_win32_$(VSCODE_ARCH)_archive condition: and(succeededOrFailed(), ne(variables['SERVER_PATH'], ''), ne(variables['VSCODE_ARCH'], 'arm64')) displayName: Publish server archive - publish: $(WEB_PATH) artifact: $(ARTIFACT_PREFIX)vscode_web_win32_$(VSCODE_ARCH)_archive condition: and(succeededOrFailed(), ne(variables['WEB_PATH'], ''), ne(variables['VSCODE_ARCH'], 'arm64')) displayName: Publish web server archive - publish: $(SYSTEM_SETUP_PATH) artifact: $(ARTIFACT_PREFIX)vscode_client_win32_$(VSCODE_ARCH)_setup condition: and(succeededOrFailed(), ne(variables['SYSTEM_SETUP_PATH'], '')) displayName: Publish system setup - publish: $(USER_SETUP_PATH) artifact: $(ARTIFACT_PREFIX)vscode_client_win32_$(VSCODE_ARCH)_user-setup condition: and(succeededOrFailed(), ne(variables['USER_SETUP_PATH'], '')) displayName: Publish user setup
build/azure-pipelines/win32/product-build-win32.yml
1
https://github.com/microsoft/vscode/commit/6bad769697ec3e4ad65287d9345624328377fdd5
[ 0.04420727863907814, 0.0033551035448908806, 0.00016640426474623382, 0.0003798598190769553, 0.008002374321222305 ]
{ "id": 1, "code_window": [ " BuildDropPath: $(agent.builddirectory)/vscode-server-darwin-$(VSCODE_ARCH)\n", " PackageName: Visual Studio Code Server\n", "\n", " - publish: $(agent.builddirectory)/vscode-server-darwin-$(VSCODE_ARCH)/_manifest\n", " displayName: Publish SBOM (server)\n", " artifact: $(ARTIFACT_PREFIX)sbom_server_darwin_$(VSCODE_ARCH)_sbom\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " - publish: $(agent.builddirectory)/VSCode-darwin-$(VSCODE_ARCH)/_manifest\n", " displayName: Publish SBOM (client)\n", " artifact: $(ARTIFACT_PREFIX)sbom_client_darwin_$(VSCODE_ARCH)_sbom\n", "\n" ], "file_path": "build/azure-pipelines/darwin/product-build-darwin.yml", "type": "add", "edit_start_line_idx": 224 }
// 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/6bad769697ec3e4ad65287d9345624328377fdd5
[ 0.00017561692220624536, 0.00017160974675789475, 0.00016561787924729288, 0.00017278599261771888, 0.0000029899254059273517 ]
{ "id": 1, "code_window": [ " BuildDropPath: $(agent.builddirectory)/vscode-server-darwin-$(VSCODE_ARCH)\n", " PackageName: Visual Studio Code Server\n", "\n", " - publish: $(agent.builddirectory)/vscode-server-darwin-$(VSCODE_ARCH)/_manifest\n", " displayName: Publish SBOM (server)\n", " artifact: $(ARTIFACT_PREFIX)sbom_server_darwin_$(VSCODE_ARCH)_sbom\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " - publish: $(agent.builddirectory)/VSCode-darwin-$(VSCODE_ARCH)/_manifest\n", " displayName: Publish SBOM (client)\n", " artifact: $(ARTIFACT_PREFIX)sbom_client_darwin_$(VSCODE_ARCH)_sbom\n", "\n" ], "file_path": "build/azure-pipelines/darwin/product-build-darwin.yml", "type": "add", "edit_start_line_idx": 224 }
// lss is mor
src/vs/workbench/services/search/test/node/fixtures/site.less
0
https://github.com/microsoft/vscode/commit/6bad769697ec3e4ad65287d9345624328377fdd5
[ 0.00017351748829241842, 0.00017351748829241842, 0.00017351748829241842, 0.00017351748829241842, 0 ]
{ "id": 1, "code_window": [ " BuildDropPath: $(agent.builddirectory)/vscode-server-darwin-$(VSCODE_ARCH)\n", " PackageName: Visual Studio Code Server\n", "\n", " - publish: $(agent.builddirectory)/vscode-server-darwin-$(VSCODE_ARCH)/_manifest\n", " displayName: Publish SBOM (server)\n", " artifact: $(ARTIFACT_PREFIX)sbom_server_darwin_$(VSCODE_ARCH)_sbom\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " - publish: $(agent.builddirectory)/VSCode-darwin-$(VSCODE_ARCH)/_manifest\n", " displayName: Publish SBOM (client)\n", " artifact: $(ARTIFACT_PREFIX)sbom_client_darwin_$(VSCODE_ARCH)_sbom\n", "\n" ], "file_path": "build/azure-pipelines/darwin/product-build-darwin.yml", "type": "add", "edit_start_line_idx": 224 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { CachedFunction } from 'vs/base/common/cache'; import { LanguageConfiguration } from 'vs/editor/common/languages/languageConfiguration'; /** * Captures all bracket related configurations for a single language. * Immutable. */ export class LanguageBracketsConfiguration { private readonly _openingBrackets: ReadonlyMap<string, OpeningBracketKind>; private readonly _closingBrackets: ReadonlyMap<string, ClosingBracketKind>; constructor( public readonly languageId: string, config: LanguageConfiguration, ) { const bracketPairs = config.brackets ? filterValidBrackets(config.brackets) : []; const openingBracketInfos = new CachedFunction((bracket: string) => { const closing = new Set<ClosingBracketKind>(); return { info: new OpeningBracketKind(this, bracket, closing), closing, }; }); const closingBracketInfos = new CachedFunction((bracket: string) => { const opening = new Set<OpeningBracketKind>(); const openingColorized = new Set<OpeningBracketKind>(); return { info: new ClosingBracketKind(this, bracket, opening, openingColorized), opening, openingColorized, }; }); for (const [open, close] of bracketPairs) { const opening = openingBracketInfos.get(open); const closing = closingBracketInfos.get(close); opening.closing.add(closing.info); closing.opening.add(opening.info); } // Treat colorized brackets as brackets, and mark them as colorized. const colorizedBracketPairs = config.colorizedBracketPairs ? filterValidBrackets(config.colorizedBracketPairs) // If not configured: Take all brackets except `<` ... `>` // Many languages set < ... > as bracket pair, even though they also use it as comparison operator. // This leads to problems when colorizing this bracket, so we exclude it if not explicitly configured otherwise. // https://github.com/microsoft/vscode/issues/132476 : bracketPairs.filter((p) => !(p[0] === '<' && p[1] === '>')); for (const [open, close] of colorizedBracketPairs) { const opening = openingBracketInfos.get(open); const closing = closingBracketInfos.get(close); opening.closing.add(closing.info); closing.openingColorized.add(opening.info); closing.opening.add(opening.info); } this._openingBrackets = new Map([...openingBracketInfos.cachedValues].map(([k, v]) => [k, v.info])); this._closingBrackets = new Map([...closingBracketInfos.cachedValues].map(([k, v]) => [k, v.info])); } /** * No two brackets have the same bracket text. */ public get openingBrackets(): readonly OpeningBracketKind[] { return [...this._openingBrackets.values()]; } /** * No two brackets have the same bracket text. */ public get closingBrackets(): readonly ClosingBracketKind[] { return [...this._closingBrackets.values()]; } public getOpeningBracketInfo(bracketText: string): OpeningBracketKind | undefined { return this._openingBrackets.get(bracketText); } public getClosingBracketInfo(bracketText: string): ClosingBracketKind | undefined { return this._closingBrackets.get(bracketText); } public getBracketInfo(bracketText: string): BracketKind | undefined { return this.getOpeningBracketInfo(bracketText) || this.getClosingBracketInfo(bracketText); } } function filterValidBrackets(bracketPairs: [string, string][]): [string, string][] { return bracketPairs.filter(([open, close]) => open !== '' && close !== ''); } export type BracketKind = OpeningBracketKind | ClosingBracketKind; export class BracketKindBase { constructor( protected readonly config: LanguageBracketsConfiguration, public readonly bracketText: string, ) { } public get languageId(): string { return this.config.languageId; } } export class OpeningBracketKind extends BracketKindBase { public readonly isOpeningBracket = true; constructor( config: LanguageBracketsConfiguration, bracketText: string, public readonly openedBrackets: ReadonlySet<ClosingBracketKind>, ) { super(config, bracketText); } } export class ClosingBracketKind extends BracketKindBase { public readonly isOpeningBracket = false; constructor( config: LanguageBracketsConfiguration, bracketText: string, /** * Non empty array of all opening brackets this bracket closes. */ public readonly openingBrackets: ReadonlySet<OpeningBracketKind>, private readonly openingColorizedBrackets: ReadonlySet<OpeningBracketKind>, ) { super(config, bracketText); } /** * Checks if this bracket closes the given other bracket. * If the bracket infos come from different configurations, this method will return false. */ public closes(other: OpeningBracketKind): boolean { if (other['config'] !== this.config) { return false; } return this.openingBrackets.has(other); } public closesColorized(other: OpeningBracketKind): boolean { if (other['config'] !== this.config) { return false; } return this.openingColorizedBrackets.has(other); } public getOpeningBrackets(): readonly OpeningBracketKind[] { return [...this.openingBrackets]; } }
src/vs/editor/common/languages/supports/languageBracketsConfiguration.ts
0
https://github.com/microsoft/vscode/commit/6bad769697ec3e4ad65287d9345624328377fdd5
[ 0.00017473800107836723, 0.00017035794735420495, 0.0001648906763875857, 0.00017114850925281644, 0.00000296683219858096 ]
{ "id": 2, "code_window": [ " displayName: Generate SBOM (client)\n", " inputs:\n", " BuildDropPath: $(agent.builddirectory)/VSCode-linux-$(VSCODE_ARCH)\n", " PackageName: Visual Studio Code\n", "\n", " - publish: $(agent.builddirectory)/VSCode-linux-$(VSCODE_ARCH)/_manifest\n", " displayName: Publish SBOM (client)\n", " artifact: $(ARTIFACT_PREFIX)sbom_vscode_client_linux_$(VSCODE_ARCH)\n", "\n", " - task: AzureArtifacts.manifest-generator-task.manifest-generator-task.ManifestGeneratorTask@0\n", " displayName: Generate SBOM (server)\n", " inputs:\n", " BuildDropPath: $(agent.builddirectory)/vscode-server-linux-$(VSCODE_ARCH)\n", " PackageName: Visual Studio Code Server\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "build/azure-pipelines/linux/product-build-linux.yml", "type": "replace", "edit_start_line_idx": 292 }
parameters: - name: VSCODE_QUALITY type: string - name: VSCODE_CIBUILD type: boolean - name: VSCODE_RUN_UNIT_TESTS type: boolean - name: VSCODE_RUN_INTEGRATION_TESTS type: boolean - name: VSCODE_RUN_SMOKE_TESTS type: boolean - name: VSCODE_ARCH type: string steps: - ${{ if eq(parameters.VSCODE_QUALITY, 'oss') }}: - checkout: self fetchDepth: 1 retryCountOnTaskFailure: 3 - task: NodeTool@0 inputs: versionSpec: "16.x" - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - template: ../distro/download-distro.yml - task: AzureKeyVault@1 displayName: "Azure Key Vault: Get Secrets" inputs: azureSubscription: "vscode-builds-subscription" KeyVaultName: vscode-build-secrets SecretsFilter: "github-distro-mixin-password,ESRP-PKI,esrp-aad-username,esrp-aad-password" - task: DownloadPipelineArtifact@2 inputs: artifact: Compilation path: $(Build.ArtifactStagingDirectory) displayName: Download compilation output - script: tar -xzf $(Build.ArtifactStagingDirectory)/compilation.tar.gz displayName: Extract compilation output - script: | set -e # Start X server /etc/init.d/xvfb start # Start dbus session DBUS_LAUNCH_RESULT=$(sudo dbus-daemon --config-file=/usr/share/dbus-1/system.conf --print-address) echo "##vso[task.setvariable variable=DBUS_SESSION_BUS_ADDRESS]$DBUS_LAUNCH_RESULT" displayName: Setup system services condition: and(succeeded(), eq(variables['VSCODE_ARCH'], 'x64')) - script: node build/setup-npm-registry.js $NPM_REGISTRY condition: and(succeeded(), ne(variables['NPM_REGISTRY'], 'none')) displayName: Setup NPM Registry - script: mkdir -p .build && node build/azure-pipelines/common/computeNodeModulesCacheKey.js linux $VSCODE_ARCH > .build/yarnlockhash displayName: Prepare node_modules cache key - task: Cache@2 inputs: key: '"node_modules" | .build/yarnlockhash' path: .build/node_modules_cache cacheHitVar: NODE_MODULES_RESTORED displayName: Restore node_modules cache - script: tar -xzf .build/node_modules_cache/cache.tgz condition: and(succeeded(), eq(variables.NODE_MODULES_RESTORED, 'true')) displayName: Extract node_modules cache - script: | set -e npm config set registry "$NPM_REGISTRY" --location=project npm config set always-auth=true --location=project yarn config set registry "$NPM_REGISTRY" condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'), ne(variables['NPM_REGISTRY'], 'none')) displayName: Setup NPM & Yarn - task: npmAuthenticate@0 inputs: workingFile: .npmrc condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'), ne(variables['NPM_REGISTRY'], 'none')) displayName: Setup NPM Authentication # TODO@joaomoreno TODO@deepak1556 this should be part of the base image - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - script: | sudo apt-get update && sudo apt-get install -y ca-certificates curl gnupg sudo mkdir -m 0755 -p /etc/apt/keyrings curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg echo "deb [arch="$(dpkg --print-architecture)" signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu "$(. /etc/os-release && echo "$VERSION_CODENAME")" stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null sudo apt update && sudo apt install -y docker-ce-cli displayName: Install Docker client condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - ${{ if and(ne(parameters.VSCODE_QUALITY, 'oss'), or(eq(parameters.VSCODE_ARCH, 'x64'), eq(parameters.VSCODE_ARCH, 'arm64'))) }}: - task: Docker@1 displayName: "Pull Docker image" inputs: azureSubscriptionEndpoint: "vscode-builds-subscription" azureContainerRegistry: vscodehub.azurecr.io command: "Run an image" imageName: vscode-linux-build-agent:centos7-devtoolset8-$(VSCODE_ARCH) containerCommand: uname condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - ${{ if and(ne(parameters.VSCODE_QUALITY, 'oss'), eq(parameters.VSCODE_ARCH, 'arm64')) }}: - script: docker run --rm --privileged multiarch/qemu-user-static --reset -p yes displayName: Register Docker QEMU condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'), eq(variables['VSCODE_ARCH'], 'arm64')) - script: | set -e for i in {1..5}; do # try 5 times yarn --cwd build --frozen-lockfile --check-files && break if [ $i -eq 3 ]; then echo "Yarn failed too many times" >&2 exit 1 fi echo "Yarn failed $i, trying again..." done if [ -z "$CC" ] || [ -z "$CXX" ]; then # Download clang based on chromium revision used by vscode curl -s https://raw.githubusercontent.com/chromium/chromium/108.0.5359.215/tools/clang/scripts/update.py | python - --output-dir=$PWD/.build/CR_Clang --host-os=linux # Download libcxx headers and objects from upstream electron releases DEBUG=libcxx-fetcher \ VSCODE_LIBCXX_OBJECTS_DIR=$PWD/.build/libcxx-objects \ VSCODE_LIBCXX_HEADERS_DIR=$PWD/.build/libcxx_headers \ VSCODE_LIBCXXABI_HEADERS_DIR=$PWD/.build/libcxxabi_headers \ VSCODE_ARCH="$(NPM_ARCH)" \ node build/linux/libcxx-fetcher.js # Set compiler toolchain # Flags for the client build are based on # https://source.chromium.org/chromium/chromium/src/+/refs/tags/108.0.5359.215:build/config/arm.gni # https://source.chromium.org/chromium/chromium/src/+/refs/tags/108.0.5359.215:build/config/compiler/BUILD.gn # https://source.chromium.org/chromium/chromium/src/+/refs/tags/108.0.5359.215:build/config/c++/BUILD.gn export CC=$PWD/.build/CR_Clang/bin/clang export CXX=$PWD/.build/CR_Clang/bin/clang++ export CXXFLAGS="-nostdinc++ -D__NO_INLINE__ -I$PWD/.build/libcxx_headers -isystem$PWD/.build/libcxx_headers/include -isystem$PWD/.build/libcxxabi_headers/include -fPIC -flto=thin -fsplit-lto-unit -D_LIBCPP_ABI_NAMESPACE=Cr" export LDFLAGS="-stdlib=libc++ -fuse-ld=lld -flto=thin -L$PWD/.build/libcxx-objects -lc++abi -Wl,--lto-O0" export VSCODE_REMOTE_CC=$(which gcc) export VSCODE_REMOTE_CXX=$(which g++) fi for i in {1..5}; do # try 5 times yarn --frozen-lockfile --check-files && break if [ $i -eq 3 ]; then echo "Yarn failed too many times" >&2 exit 1 fi echo "Yarn failed $i, trying again..." done env: npm_config_arch: $(NPM_ARCH) ELECTRON_SKIP_BINARY_DOWNLOAD: 1 PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1 GITHUB_TOKEN: "$(github-distro-mixin-password)" ${{ if and(ne(parameters.VSCODE_QUALITY, 'oss'), or(eq(parameters.VSCODE_ARCH, 'x64'), eq(parameters.VSCODE_ARCH, 'arm64'))) }}: VSCODE_REMOTE_DEPENDENCIES_CONTAINER_NAME: vscodehub.azurecr.io/vscode-linux-build-agent:centos7-devtoolset8-$(VSCODE_ARCH) displayName: Install dependencies condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - script: node build/azure-pipelines/distro/mixin-npm condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) displayName: Mixin distro node modules - script: | set -e node build/azure-pipelines/common/listNodeModules.js .build/node_modules_list.txt mkdir -p .build/node_modules_cache tar -czf .build/node_modules_cache/cache.tgz --files-from .build/node_modules_list.txt condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) displayName: Create node_modules archive - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - script: node build/azure-pipelines/distro/mixin-quality displayName: Mixin distro quality - template: ../common/install-builtin-extensions.yml - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - script: | set -e yarn gulp vscode-linux-$(VSCODE_ARCH)-min-ci ARCHIVE_PATH=".build/linux/client/code-${{ parameters.VSCODE_QUALITY }}-$(VSCODE_ARCH)-$(date +%s).tar.gz" mkdir -p $(dirname $ARCHIVE_PATH) tar -czf $ARCHIVE_PATH -C .. VSCode-linux-$(VSCODE_ARCH) echo "##vso[task.setvariable variable=CLIENT_PATH]$ARCHIVE_PATH" env: GITHUB_TOKEN: "$(github-distro-mixin-password)" displayName: Build client - script: | set -e yarn gulp vscode-reh-linux-$(VSCODE_ARCH)-min-ci mv ../vscode-reh-linux-$(VSCODE_ARCH) ../vscode-server-linux-$(VSCODE_ARCH) # TODO@joaomoreno ARCHIVE_PATH=".build/linux/server/vscode-server-linux-$(VSCODE_ARCH).tar.gz" mkdir -p $(dirname $ARCHIVE_PATH) tar --owner=0 --group=0 -czf $ARCHIVE_PATH -C .. vscode-server-linux-$(VSCODE_ARCH) echo "##vso[task.setvariable variable=SERVER_PATH]$ARCHIVE_PATH" env: GITHUB_TOKEN: "$(github-distro-mixin-password)" displayName: Build server - script: | set -e yarn gulp vscode-reh-web-linux-$(VSCODE_ARCH)-min-ci mv ../vscode-reh-web-linux-$(VSCODE_ARCH) ../vscode-server-linux-$(VSCODE_ARCH)-web # TODO@joaomoreno ARCHIVE_PATH=".build/linux/web/vscode-server-linux-$(VSCODE_ARCH)-web.tar.gz" mkdir -p $(dirname $ARCHIVE_PATH) tar --owner=0 --group=0 -czf $ARCHIVE_PATH -C .. vscode-server-linux-$(VSCODE_ARCH)-web echo "##vso[task.setvariable variable=WEB_PATH]$ARCHIVE_PATH" env: GITHUB_TOKEN: "$(github-distro-mixin-password)" displayName: Build server (web) - ${{ else }}: - script: yarn gulp "transpile-client-swc" "transpile-extensions" env: GITHUB_TOKEN: "$(github-distro-mixin-password)" displayName: Transpile - ${{ if or(eq(parameters.VSCODE_RUN_UNIT_TESTS, true), eq(parameters.VSCODE_RUN_INTEGRATION_TESTS, true), eq(parameters.VSCODE_RUN_SMOKE_TESTS, true)) }}: - template: product-build-linux-test.yml parameters: VSCODE_QUALITY: ${{ parameters.VSCODE_QUALITY }} VSCODE_RUN_UNIT_TESTS: ${{ parameters.VSCODE_RUN_UNIT_TESTS }} VSCODE_RUN_INTEGRATION_TESTS: ${{ parameters.VSCODE_RUN_INTEGRATION_TESTS }} VSCODE_RUN_SMOKE_TESTS: ${{ parameters.VSCODE_RUN_SMOKE_TESTS }} - ${{ if and(ne(parameters.VSCODE_CIBUILD, true), ne(parameters.VSCODE_QUALITY, 'oss')) }}: - task: DownloadPipelineArtifact@2 inputs: artifact: $(ARTIFACT_PREFIX)vscode_cli_linux_$(VSCODE_ARCH)_cli patterns: "**" path: $(Build.ArtifactStagingDirectory)/cli displayName: Download VS Code CLI - script: | set -e tar -xzvf $(Build.ArtifactStagingDirectory)/cli/*.tar.gz -C $(Build.ArtifactStagingDirectory)/cli CLI_APP_NAME=$(node -p "require(\"$(agent.builddirectory)/VSCode-linux-$(VSCODE_ARCH)/resources/app/product.json\").tunnelApplicationName") APP_NAME=$(node -p "require(\"$(agent.builddirectory)/VSCode-linux-$(VSCODE_ARCH)/resources/app/product.json\").applicationName") mv $(Build.ArtifactStagingDirectory)/cli/$APP_NAME $(agent.builddirectory)/VSCode-linux-$(VSCODE_ARCH)/bin/$CLI_APP_NAME displayName: Make CLI executable - script: | set -e yarn gulp "vscode-linux-$(VSCODE_ARCH)-build-deb" echo "##vso[task.setvariable variable=DEB_PATH]$(ls .build/linux/deb/*/deb/*.deb)" displayName: Build deb package - script: | set -e yarn gulp "vscode-linux-$(VSCODE_ARCH)-build-rpm" echo "##vso[task.setvariable variable=RPM_PATH]$(ls .build/linux/rpm/*/*.rpm)" displayName: Build rpm package - script: | set -e yarn gulp "vscode-linux-$(VSCODE_ARCH)-prepare-snap" ARCHIVE_PATH=".build/linux/snap-tarball/snap-$(VSCODE_ARCH).tar.gz" mkdir -p $(dirname $ARCHIVE_PATH) tar -czf $ARCHIVE_PATH -C .build/linux snap echo "##vso[task.setvariable variable=SNAP_PATH]$ARCHIVE_PATH" displayName: Prepare snap package - task: UseDotNet@2 inputs: version: 6.x - task: EsrpClientTool@1 continueOnError: true displayName: Download ESRPClient - script: node build/azure-pipelines/common/sign $(Agent.ToolsDirectory)/esrpclient/*/*/net6.0/esrpcli.dll rpm $(ESRP-PKI) $(esrp-aad-username) $(esrp-aad-password) .build/linux/rpm '*.rpm' displayName: Codesign rpm - script: echo "##vso[task.setvariable variable=ARTIFACT_PREFIX]attempt$(System.JobAttempt)_" condition: and(succeededOrFailed(), notIn(variables['Agent.JobStatus'], 'Succeeded', 'SucceededWithIssues')) displayName: Generate artifact prefix - task: AzureArtifacts.manifest-generator-task.manifest-generator-task.ManifestGeneratorTask@0 displayName: Generate SBOM (client) inputs: BuildDropPath: $(agent.builddirectory)/VSCode-linux-$(VSCODE_ARCH) PackageName: Visual Studio Code - publish: $(agent.builddirectory)/VSCode-linux-$(VSCODE_ARCH)/_manifest displayName: Publish SBOM (client) artifact: $(ARTIFACT_PREFIX)sbom_vscode_client_linux_$(VSCODE_ARCH) - task: AzureArtifacts.manifest-generator-task.manifest-generator-task.ManifestGeneratorTask@0 displayName: Generate SBOM (server) inputs: BuildDropPath: $(agent.builddirectory)/vscode-server-linux-$(VSCODE_ARCH) PackageName: Visual Studio Code Server - publish: $(agent.builddirectory)/vscode-server-linux-$(VSCODE_ARCH)/_manifest displayName: Publish SBOM (server) artifact: $(ARTIFACT_PREFIX)sbom_vscode_server_linux_$(VSCODE_ARCH) - publish: $(CLIENT_PATH) artifact: $(ARTIFACT_PREFIX)vscode_client_linux_$(VSCODE_ARCH)_archive-unsigned condition: and(succeededOrFailed(), ne(variables['CLIENT_PATH'], '')) displayName: Publish client archive - publish: $(SERVER_PATH) artifact: $(ARTIFACT_PREFIX)vscode_server_linux_$(VSCODE_ARCH)_archive-unsigned condition: and(succeededOrFailed(), ne(variables['SERVER_PATH'], '')) displayName: Publish server archive - publish: $(WEB_PATH) artifact: $(ARTIFACT_PREFIX)vscode_web_linux_$(VSCODE_ARCH)_archive-unsigned condition: and(succeededOrFailed(), ne(variables['WEB_PATH'], '')) displayName: Publish web server archive - publish: $(DEB_PATH) artifact: $(ARTIFACT_PREFIX)vscode_client_linux_$(VSCODE_ARCH)_deb-package condition: and(succeededOrFailed(), ne(variables['DEB_PATH'], '')) displayName: Publish deb package - publish: $(RPM_PATH) artifact: $(ARTIFACT_PREFIX)vscode_client_linux_$(VSCODE_ARCH)_rpm-package condition: and(succeededOrFailed(), ne(variables['RPM_PATH'], '')) displayName: Publish rpm package - publish: $(SNAP_PATH) artifact: $(ARTIFACT_PREFIX)snap-$(VSCODE_ARCH) condition: and(succeededOrFailed(), ne(variables['SNAP_PATH'], '')) displayName: Publish snap pre-package
build/azure-pipelines/linux/product-build-linux.yml
1
https://github.com/microsoft/vscode/commit/6bad769697ec3e4ad65287d9345624328377fdd5
[ 0.9970097541809082, 0.036459531635046005, 0.00016478693578392267, 0.00019230248290114105, 0.16927528381347656 ]
{ "id": 2, "code_window": [ " displayName: Generate SBOM (client)\n", " inputs:\n", " BuildDropPath: $(agent.builddirectory)/VSCode-linux-$(VSCODE_ARCH)\n", " PackageName: Visual Studio Code\n", "\n", " - publish: $(agent.builddirectory)/VSCode-linux-$(VSCODE_ARCH)/_manifest\n", " displayName: Publish SBOM (client)\n", " artifact: $(ARTIFACT_PREFIX)sbom_vscode_client_linux_$(VSCODE_ARCH)\n", "\n", " - task: AzureArtifacts.manifest-generator-task.manifest-generator-task.ManifestGeneratorTask@0\n", " displayName: Generate SBOM (server)\n", " inputs:\n", " BuildDropPath: $(agent.builddirectory)/vscode-server-linux-$(VSCODE_ARCH)\n", " PackageName: Visual Studio Code Server\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "build/azure-pipelines/linux/product-build-linux.yml", "type": "replace", "edit_start_line_idx": 292 }
/*--------------------------------------------------------------------------------------------- * 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 * as dom from 'vs/base/browser/dom'; import { Action, IAction } from 'vs/base/common/actions'; import { URI, UriComponents } from 'vs/base/common/uri'; import { ActionViewItem } from 'vs/base/browser/ui/actionbar/actionViewItems'; export class ToggleReactionsAction extends Action { static readonly ID = 'toolbar.toggle.pickReactions'; private _menuActions: IAction[] = []; private toggleDropdownMenu: () => void; constructor(toggleDropdownMenu: () => void, title?: string) { super(ToggleReactionsAction.ID, title || nls.localize('pickReactions', "Pick Reactions..."), 'toggle-reactions', true); this.toggleDropdownMenu = toggleDropdownMenu; } override run(): Promise<any> { this.toggleDropdownMenu(); return Promise.resolve(true); } get menuActions() { return this._menuActions; } set menuActions(actions: IAction[]) { this._menuActions = actions; } } export class ReactionActionViewItem extends ActionViewItem { constructor(action: ReactionAction) { super(null, action, {}); } protected override updateLabel(): void { if (!this.label) { return; } const action = this.action as ReactionAction; if (action.class) { this.label.classList.add(action.class); } if (!action.icon) { const reactionLabel = dom.append(this.label, dom.$('span.reaction-label')); reactionLabel.innerText = action.label; } else { const reactionIcon = dom.append(this.label, dom.$('.reaction-icon')); const uri = URI.revive(action.icon); reactionIcon.style.backgroundImage = dom.asCSSUrl(uri); reactionIcon.title = action.label; } if (action.count) { const reactionCount = dom.append(this.label, dom.$('span.reaction-count')); reactionCount.innerText = `${action.count}`; } } protected override getTooltip(): string | undefined { const action = this.action as ReactionAction; const toggleMessage = action.enabled ? nls.localize('comment.toggleableReaction', "Toggle reaction, ") : ''; if (action.count === undefined) { return nls.localize({ key: 'comment.reactionLabelNone', comment: [ 'This is a tooltip for an emoji button so that the current user can toggle their reaction to a comment.', 'The first arg is localized message "Toggle reaction" or empty if the user doesn\'t have permission to toggle the reaction, the second is the name of the reaction.'] }, "{0}{1} reaction", toggleMessage, action.label); } else if (action.count === 1) { return nls.localize({ key: 'comment.reactionLabelOne', comment: [ 'This is a tooltip for an emoji that is a "reaction" to a comment where the count of the reactions is 1.', 'The emoji is also a button so that the current user can also toggle their own emoji reaction.', 'The first arg is localized message "Toggle reaction" or empty if the user doesn\'t have permission to toggle the reaction, the second is the name of the reaction.'] }, "{0}1 reaction with {1}", toggleMessage, action.label); } else if (action.count > 1) { return nls.localize({ key: 'comment.reactionLabelMany', comment: [ 'This is a tooltip for an emoji that is a "reaction" to a comment where the count of the reactions is greater than 1.', 'The emoji is also a button so that the current user can also toggle their own emoji reaction.', 'The first arg is localized message "Toggle reaction" or empty if the user doesn\'t have permission to toggle the reaction, the second is number of users who have reacted with that reaction, and the third is the name of the reaction.'] }, "{0}{1} reactions with {2}", toggleMessage, action.count, action.label); } return undefined; } } export class ReactionAction extends Action { static readonly ID = 'toolbar.toggle.reaction'; constructor(id: string, label: string = '', cssClass: string = '', enabled: boolean = true, actionCallback?: (event?: any) => Promise<any>, public icon?: UriComponents, public count?: number) { super(ReactionAction.ID, label, cssClass, enabled, actionCallback); } }
src/vs/workbench/contrib/comments/browser/reactionsAction.ts
0
https://github.com/microsoft/vscode/commit/6bad769697ec3e4ad65287d9345624328377fdd5
[ 0.0001765241613611579, 0.00017310907423961908, 0.00016571342712268233, 0.00017465464770793915, 0.0000035226764794060728 ]
{ "id": 2, "code_window": [ " displayName: Generate SBOM (client)\n", " inputs:\n", " BuildDropPath: $(agent.builddirectory)/VSCode-linux-$(VSCODE_ARCH)\n", " PackageName: Visual Studio Code\n", "\n", " - publish: $(agent.builddirectory)/VSCode-linux-$(VSCODE_ARCH)/_manifest\n", " displayName: Publish SBOM (client)\n", " artifact: $(ARTIFACT_PREFIX)sbom_vscode_client_linux_$(VSCODE_ARCH)\n", "\n", " - task: AzureArtifacts.manifest-generator-task.manifest-generator-task.ManifestGeneratorTask@0\n", " displayName: Generate SBOM (server)\n", " inputs:\n", " BuildDropPath: $(agent.builddirectory)/vscode-server-linux-$(VSCODE_ARCH)\n", " PackageName: Visual Studio Code Server\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "build/azure-pipelines/linux/product-build-linux.yml", "type": "replace", "edit_start_line_idx": 292 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Emitter, Event } from 'vs/base/common/event'; import { KeyCode } from 'vs/base/common/keyCodes'; import { combinedDisposable, DisposableStore, dispose, IDisposable } from 'vs/base/common/lifecycle'; import { isEqual } from 'vs/base/common/resources'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { EditorCommand, registerEditorCommand } from 'vs/editor/browser/editorExtensions'; import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService'; import { Range } from 'vs/editor/common/core/range'; import { OneReference, ReferencesModel } from 'vs/editor/contrib/gotoSymbol/browser/referencesModel'; import { localize } from 'vs/nls'; import { IContextKey, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey'; import { TextEditorSelectionRevealType } from 'vs/platform/editor/common/editor'; import { InstantiationType, registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { createDecorator, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { KeybindingsRegistry, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { INotificationService } from 'vs/platform/notification/common/notification'; export const ctxHasSymbols = new RawContextKey('hasSymbols', false, localize('hasSymbols', "Whether there are symbol locations that can be navigated via keyboard-only.")); export const ISymbolNavigationService = createDecorator<ISymbolNavigationService>('ISymbolNavigationService'); export interface ISymbolNavigationService { readonly _serviceBrand: undefined; reset(): void; put(anchor: OneReference): void; revealNext(source: ICodeEditor): Promise<any>; } class SymbolNavigationService implements ISymbolNavigationService { declare readonly _serviceBrand: undefined; private readonly _ctxHasSymbols: IContextKey<boolean>; private _currentModel?: ReferencesModel = undefined; private _currentIdx: number = -1; private _currentState?: IDisposable; private _currentMessage?: IDisposable; private _ignoreEditorChange: boolean = false; constructor( @IContextKeyService contextKeyService: IContextKeyService, @ICodeEditorService private readonly _editorService: ICodeEditorService, @INotificationService private readonly _notificationService: INotificationService, @IKeybindingService private readonly _keybindingService: IKeybindingService, ) { this._ctxHasSymbols = ctxHasSymbols.bindTo(contextKeyService); } reset(): void { this._ctxHasSymbols.reset(); this._currentState?.dispose(); this._currentMessage?.dispose(); this._currentModel = undefined; this._currentIdx = -1; } put(anchor: OneReference): void { const refModel = anchor.parent.parent; if (refModel.references.length <= 1) { this.reset(); return; } this._currentModel = refModel; this._currentIdx = refModel.references.indexOf(anchor); this._ctxHasSymbols.set(true); this._showMessage(); const editorState = new EditorState(this._editorService); const listener = editorState.onDidChange(_ => { if (this._ignoreEditorChange) { return; } const editor = this._editorService.getActiveCodeEditor(); if (!editor) { return; } const model = editor.getModel(); const position = editor.getPosition(); if (!model || !position) { return; } let seenUri: boolean = false; let seenPosition: boolean = false; for (const reference of refModel.references) { if (isEqual(reference.uri, model.uri)) { seenUri = true; seenPosition = seenPosition || Range.containsPosition(reference.range, position); } else if (seenUri) { break; } } if (!seenUri || !seenPosition) { this.reset(); } }); this._currentState = combinedDisposable(editorState, listener); } revealNext(source: ICodeEditor): Promise<any> { if (!this._currentModel) { return Promise.resolve(); } // get next result and advance this._currentIdx += 1; this._currentIdx %= this._currentModel.references.length; const reference = this._currentModel.references[this._currentIdx]; // status this._showMessage(); // open editor, ignore events while that happens this._ignoreEditorChange = true; return this._editorService.openCodeEditor({ resource: reference.uri, options: { selection: Range.collapseToStart(reference.range), selectionRevealType: TextEditorSelectionRevealType.NearTopIfOutsideViewport } }, source).finally(() => { this._ignoreEditorChange = false; }); } private _showMessage(): void { this._currentMessage?.dispose(); const kb = this._keybindingService.lookupKeybinding('editor.gotoNextSymbolFromResult'); const message = kb ? localize('location.kb', "Symbol {0} of {1}, {2} for next", this._currentIdx + 1, this._currentModel!.references.length, kb.getLabel()) : localize('location', "Symbol {0} of {1}", this._currentIdx + 1, this._currentModel!.references.length); this._currentMessage = this._notificationService.status(message); } } registerSingleton(ISymbolNavigationService, SymbolNavigationService, InstantiationType.Delayed); registerEditorCommand(new class extends EditorCommand { constructor() { super({ id: 'editor.gotoNextSymbolFromResult', precondition: ctxHasSymbols, kbOpts: { weight: KeybindingWeight.EditorContrib, primary: KeyCode.F12 } }); } runEditorCommand(accessor: ServicesAccessor, editor: ICodeEditor): void | Promise<void> { return accessor.get(ISymbolNavigationService).revealNext(editor); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'editor.gotoNextSymbolFromResult.cancel', weight: KeybindingWeight.EditorContrib, when: ctxHasSymbols, primary: KeyCode.Escape, handler(accessor) { accessor.get(ISymbolNavigationService).reset(); } }); // class EditorState { private readonly _listener = new Map<ICodeEditor, IDisposable>(); private readonly _disposables = new DisposableStore(); private readonly _onDidChange = new Emitter<{ editor: ICodeEditor }>(); readonly onDidChange: Event<{ editor: ICodeEditor }> = this._onDidChange.event; constructor(@ICodeEditorService editorService: ICodeEditorService) { this._disposables.add(editorService.onCodeEditorRemove(this._onDidRemoveEditor, this)); this._disposables.add(editorService.onCodeEditorAdd(this._onDidAddEditor, this)); editorService.listCodeEditors().forEach(this._onDidAddEditor, this); } dispose(): void { this._disposables.dispose(); this._onDidChange.dispose(); dispose(this._listener.values()); } private _onDidAddEditor(editor: ICodeEditor): void { this._listener.set(editor, combinedDisposable( editor.onDidChangeCursorPosition(_ => this._onDidChange.fire({ editor })), editor.onDidChangeModelContent(_ => this._onDidChange.fire({ editor })), )); } private _onDidRemoveEditor(editor: ICodeEditor): void { this._listener.get(editor)?.dispose(); this._listener.delete(editor); } }
src/vs/editor/contrib/gotoSymbol/browser/symbolNavigation.ts
0
https://github.com/microsoft/vscode/commit/6bad769697ec3e4ad65287d9345624328377fdd5
[ 0.00017582284635864198, 0.00017198361456394196, 0.0001686944015091285, 0.00017183308955281973, 0.0000019471353880362585 ]
{ "id": 2, "code_window": [ " displayName: Generate SBOM (client)\n", " inputs:\n", " BuildDropPath: $(agent.builddirectory)/VSCode-linux-$(VSCODE_ARCH)\n", " PackageName: Visual Studio Code\n", "\n", " - publish: $(agent.builddirectory)/VSCode-linux-$(VSCODE_ARCH)/_manifest\n", " displayName: Publish SBOM (client)\n", " artifact: $(ARTIFACT_PREFIX)sbom_vscode_client_linux_$(VSCODE_ARCH)\n", "\n", " - task: AzureArtifacts.manifest-generator-task.manifest-generator-task.ManifestGeneratorTask@0\n", " displayName: Generate SBOM (server)\n", " inputs:\n", " BuildDropPath: $(agent.builddirectory)/vscode-server-linux-$(VSCODE_ARCH)\n", " PackageName: Visual Studio Code Server\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "build/azure-pipelines/linux/product-build-linux.yml", "type": "replace", "edit_start_line_idx": 292 }
"use strict"; /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ Object.defineProperty(exports, "__esModule", { value: true }); exports.createAsar = void 0; const path = require("path"); const es = require("event-stream"); const pickle = require('chromium-pickle-js'); const Filesystem = require('asar/lib/filesystem'); const VinylFile = require("vinyl"); const minimatch = require("minimatch"); function createAsar(folderPath, unpackGlobs, destFilename) { const shouldUnpackFile = (file) => { for (let i = 0; i < unpackGlobs.length; i++) { if (minimatch(file.relative, unpackGlobs[i])) { return true; } } return false; }; const filesystem = new Filesystem(folderPath); const out = []; // Keep track of pending inserts let pendingInserts = 0; let onFileInserted = () => { pendingInserts--; }; // Do not insert twice the same directory const seenDir = {}; const insertDirectoryRecursive = (dir) => { if (seenDir[dir]) { return; } let lastSlash = dir.lastIndexOf('/'); if (lastSlash === -1) { lastSlash = dir.lastIndexOf('\\'); } if (lastSlash !== -1) { insertDirectoryRecursive(dir.substring(0, lastSlash)); } seenDir[dir] = true; filesystem.insertDirectory(dir); }; const insertDirectoryForFile = (file) => { let lastSlash = file.lastIndexOf('/'); if (lastSlash === -1) { lastSlash = file.lastIndexOf('\\'); } if (lastSlash !== -1) { insertDirectoryRecursive(file.substring(0, lastSlash)); } }; const insertFile = (relativePath, stat, shouldUnpack) => { insertDirectoryForFile(relativePath); pendingInserts++; // Do not pass `onFileInserted` directly because it gets overwritten below. // Create a closure capturing `onFileInserted`. filesystem.insertFile(relativePath, shouldUnpack, { stat: stat }, {}).then(() => onFileInserted(), () => onFileInserted()); }; return es.through(function (file) { if (file.stat.isDirectory()) { return; } if (!file.stat.isFile()) { throw new Error(`unknown item in stream!`); } const shouldUnpack = shouldUnpackFile(file); insertFile(file.relative, { size: file.contents.length, mode: file.stat.mode }, shouldUnpack); if (shouldUnpack) { // The file goes outside of xx.asar, in a folder xx.asar.unpacked const relative = path.relative(folderPath, file.path); this.queue(new VinylFile({ base: '.', path: path.join(destFilename + '.unpacked', relative), stat: file.stat, contents: file.contents })); } else { // The file goes inside of xx.asar out.push(file.contents); } }, function () { const finish = () => { { const headerPickle = pickle.createEmpty(); headerPickle.writeString(JSON.stringify(filesystem.header)); const headerBuf = headerPickle.toBuffer(); const sizePickle = pickle.createEmpty(); sizePickle.writeUInt32(headerBuf.length); const sizeBuf = sizePickle.toBuffer(); out.unshift(headerBuf); out.unshift(sizeBuf); } const contents = Buffer.concat(out); out.length = 0; this.queue(new VinylFile({ base: '.', path: destFilename, contents: contents })); this.queue(null); }; // Call finish() only when all file inserts have finished... if (pendingInserts === 0) { finish(); } else { onFileInserted = () => { pendingInserts--; if (pendingInserts === 0) { finish(); } }; } }); } exports.createAsar = createAsar; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYXNhci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbImFzYXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBOzs7Z0dBR2dHOzs7QUFFaEcsNkJBQTZCO0FBQzdCLG1DQUFtQztBQUNuQyxNQUFNLE1BQU0sR0FBRyxPQUFPLENBQUMsb0JBQW9CLENBQUMsQ0FBQztBQUM3QyxNQUFNLFVBQVUsR0FBMEIsT0FBTyxDQUFDLHFCQUFxQixDQUFDLENBQUM7QUFDekUsbUNBQW1DO0FBQ25DLHVDQUF1QztBQVN2QyxTQUFnQixVQUFVLENBQUMsVUFBa0IsRUFBRSxXQUFxQixFQUFFLFlBQW9CO0lBRXpGLE1BQU0sZ0JBQWdCLEdBQUcsQ0FBQyxJQUFlLEVBQVcsRUFBRTtRQUNyRCxLQUFLLElBQUksQ0FBQyxHQUFHLENBQUMsRUFBRSxDQUFDLEdBQUcsV0FBVyxDQUFDLE1BQU0sRUFBRSxDQUFDLEVBQUUsRUFBRTtZQUM1QyxJQUFJLFNBQVMsQ0FBQyxJQUFJLENBQUMsUUFBUSxFQUFFLFdBQVcsQ0FBQyxDQUFDLENBQUMsQ0FBQyxFQUFFO2dCQUM3QyxPQUFPLElBQUksQ0FBQzthQUNaO1NBQ0Q7UUFDRCxPQUFPLEtBQUssQ0FBQztJQUNkLENBQUMsQ0FBQztJQUVGLE1BQU0sVUFBVSxHQUFHLElBQUksVUFBVSxDQUFDLFVBQVUsQ0FBQyxDQUFDO0lBQzlDLE1BQU0sR0FBRyxHQUFhLEVBQUUsQ0FBQztJQUV6QixnQ0FBZ0M7SUFDaEMsSUFBSSxjQUFjLEdBQUcsQ0FBQyxDQUFDO0lBQ3ZCLElBQUksY0FBYyxHQUFHLEdBQUcsRUFBRSxHQUFHLGNBQWMsRUFBRSxDQUFDLENBQUMsQ0FBQyxDQUFDO0lBRWpELHlDQUF5QztJQUN6QyxNQUFNLE9BQU8sR0FBK0IsRUFBRSxDQUFDO0lBQy9DLE1BQU0sd0JBQXdCLEdBQUcsQ0FBQyxHQUFXLEVBQUUsRUFBRTtRQUNoRCxJQUFJLE9BQU8sQ0FBQyxHQUFHLENBQUMsRUFBRTtZQUNqQixPQUFPO1NBQ1A7UUFFRCxJQUFJLFNBQVMsR0FBRyxHQUFHLENBQUMsV0FBVyxDQUFDLEdBQUcsQ0FBQyxDQUFDO1FBQ3JDLElBQUksU0FBUyxLQUFLLENBQUMsQ0FBQyxFQUFFO1lBQ3JCLFNBQVMsR0FBRyxHQUFHLENBQUMsV0FBVyxDQUFDLElBQUksQ0FBQyxDQUFDO1NBQ2xDO1FBQ0QsSUFBSSxTQUFTLEtBQUssQ0FBQyxDQUFDLEVBQUU7WUFDckIsd0JBQXdCLENBQUMsR0FBRyxDQUFDLFNBQVMsQ0FBQyxDQUFDLEVBQUUsU0FBUyxDQUFDLENBQUMsQ0FBQztTQUN0RDtRQUNELE9BQU8sQ0FBQyxHQUFHLENBQUMsR0FBRyxJQUFJLENBQUM7UUFDcEIsVUFBVSxDQUFDLGVBQWUsQ0FBQyxHQUFHLENBQUMsQ0FBQztJQUNqQyxDQUFDLENBQUM7SUFFRixNQUFNLHNCQUFzQixHQUFHLENBQUMsSUFBWSxFQUFFLEVBQUU7UUFDL0MsSUFBSSxTQUFTLEdBQUcsSUFBSSxDQUFDLFdBQVcsQ0FBQyxHQUFHLENBQUMsQ0FBQztRQUN0QyxJQUFJLFNBQVMsS0FBSyxDQUFDLENBQUMsRUFBRTtZQUNyQixTQUFTLEdBQUcsSUFBSSxDQUFDLFdBQVcsQ0FBQyxJQUFJLENBQUMsQ0FBQztTQUNuQztRQUNELElBQUksU0FBUyxLQUFLLENBQUMsQ0FBQyxFQUFFO1lBQ3JCLHdCQUF3QixDQUFDLElBQUksQ0FBQyxTQUFTLENBQUMsQ0FBQyxFQUFFLFNBQVMsQ0FBQyxDQUFDLENBQUM7U0FDdkQ7SUFDRixDQUFDLENBQUM7SUFFRixNQUFNLFVBQVUsR0FBRyxDQUFDLFlBQW9CLEVBQUUsSUFBb0MsRUFBRSxZQUFxQixFQUFFLEVBQUU7UUFDeEcsc0JBQXNCLENBQUMsWUFBWSxDQUFDLENBQUM7UUFDckMsY0FBYyxFQUFFLENBQUM7UUFDakIsMkVBQTJFO1FBQzNFLCtDQUErQztRQUMvQyxVQUFVLENBQUMsVUFBVSxDQUFDLFlBQVksRUFBRSxZQUFZLEVBQUUsRUFBRSxJQUFJLEVBQUUsSUFBSSxFQUFFLEVBQUUsRUFBRSxDQUFDLENBQUMsSUFBSSxDQUFDLEdBQUcsRUFBRSxDQUFDLGNBQWMsRUFBRSxFQUFFLEdBQUcsRUFBRSxDQUFDLGNBQWMsRUFBRSxDQUFDLENBQUM7SUFDNUgsQ0FBQyxDQUFDO0lBRUYsT0FBTyxFQUFFLENBQUMsT0FBTyxDQUFDLFVBQVUsSUFBSTtRQUMvQixJQUFJLElBQUksQ0FBQyxJQUFJLENBQUMsV0FBVyxFQUFFLEVBQUU7WUFDNUIsT0FBTztTQUNQO1FBQ0QsSUFBSSxDQUFDLElBQUksQ0FBQyxJQUFJLENBQUMsTUFBTSxFQUFFLEVBQUU7WUFDeEIsTUFBTSxJQUFJLEtBQUssQ0FBQyx5QkFBeUIsQ0FBQyxDQUFDO1NBQzNDO1FBQ0QsTUFBTSxZQUFZLEdBQUcsZ0JBQWdCLENBQUMsSUFBSSxDQUFDLENBQUM7UUFDNUMsVUFBVSxDQUFDLElBQUksQ0FBQyxRQUFRLEVBQUUsRUFBRSxJQUFJLEVBQUUsSUFBSSxDQUFDLFFBQVEsQ0FBQyxNQUFNLEVBQUUsSUFBSSxFQUFFLElBQUksQ0FBQyxJQUFJLENBQUMsSUFBSSxFQUFFLEVBQUUsWUFBWSxDQUFDLENBQUM7UUFFOUYsSUFBSSxZQUFZLEVBQUU7WUFDakIsaUVBQWlFO1lBQ2pFLE1BQU0sUUFBUSxHQUFHLElBQUksQ0FBQyxRQUFRLENBQUMsVUFBVSxFQUFFLElBQUksQ0FBQyxJQUFJLENBQUMsQ0FBQztZQUN0RCxJQUFJLENBQUMsS0FBSyxDQUFDLElBQUksU0FBUyxDQUFDO2dCQUN4QixJQUFJLEVBQUUsR0FBRztnQkFDVCxJQUFJLEVBQUUsSUFBSSxDQUFDLElBQUksQ0FBQyxZQUFZLEdBQUcsV0FBVyxFQUFFLFFBQVEsQ0FBQztnQkFDckQsSUFBSSxFQUFFLElBQUksQ0FBQyxJQUFJO2dCQUNmLFFBQVEsRUFBRSxJQUFJLENBQUMsUUFBUTthQUN2QixDQUFDLENBQUMsQ0FBQztTQUNKO2FBQU07WUFDTixrQ0FBa0M7WUFDbEMsR0FBRyxDQUFDLElBQUksQ0FBQyxJQUFJLENBQUMsUUFBUSxDQUFDLENBQUM7U0FDeEI7SUFDRixDQUFDLEVBQUU7UUFFRixNQUFNLE1BQU0sR0FBRyxHQUFHLEVBQUU7WUFDbkI7Z0JBQ0MsTUFBTSxZQUFZLEdBQUcsTUFBTSxDQUFDLFdBQVcsRUFBRSxDQUFDO2dCQUMxQyxZQUFZLENBQUMsV0FBVyxDQUFDLElBQUksQ0FBQyxTQUFTLENBQUMsVUFBVSxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUM7Z0JBQzVELE1BQU0sU0FBUyxHQUFHLFlBQVksQ0FBQyxRQUFRLEVBQUUsQ0FBQztnQkFFMUMsTUFBTSxVQUFVLEdBQUcsTUFBTSxDQUFDLFdBQVcsRUFBRSxDQUFDO2dCQUN4QyxVQUFVLENBQUMsV0FBVyxDQUFDLFNBQVMsQ0FBQyxNQUFNLENBQUMsQ0FBQztnQkFDekMsTUFBTSxPQUFPLEdBQUcsVUFBVSxDQUFDLFFBQVEsRUFBRSxDQUFDO2dCQUV0QyxHQUFHLENBQUMsT0FBTyxDQUFDLFNBQVMsQ0FBQyxDQUFDO2dCQUN2QixHQUFHLENBQUMsT0FBTyxDQUFDLE9BQU8sQ0FBQyxDQUFDO2FBQ3JCO1lBRUQsTUFBTSxRQUFRLEdBQUcsTUFBTSxDQUFDLE1BQU0sQ0FBQyxHQUFHLENBQUMsQ0FBQztZQUNwQyxHQUFHLENBQUMsTUFBTSxHQUFHLENBQUMsQ0FBQztZQUVmLElBQUksQ0FBQyxLQUFLLENBQUMsSUFBSSxTQUFTLENBQUM7Z0JBQ3hCLElBQUksRUFBRSxHQUFHO2dCQUNULElBQUksRUFBRSxZQUFZO2dCQUNsQixRQUFRLEVBQUUsUUFBUTthQUNsQixDQUFDLENBQUMsQ0FBQztZQUNKLElBQUksQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLENBQUM7UUFDbEIsQ0FBQyxDQUFDO1FBRUYsNERBQTREO1FBQzVELElBQUksY0FBYyxLQUFLLENBQUMsRUFBRTtZQUN6QixNQUFNLEVBQUUsQ0FBQztTQUNUO2FBQU07WUFDTixjQUFjLEdBQUcsR0FBRyxFQUFFO2dCQUNyQixjQUFjLEVBQUUsQ0FBQztnQkFDakIsSUFBSSxjQUFjLEtBQUssQ0FBQyxFQUFFO29CQUN6QixNQUFNLEVBQUUsQ0FBQztpQkFDVDtZQUNGLENBQUMsQ0FBQztTQUNGO0lBQ0YsQ0FBQyxDQUFDLENBQUM7QUFDSixDQUFDO0FBcEhELGdDQW9IQyJ9
build/lib/asar.js
0
https://github.com/microsoft/vscode/commit/6bad769697ec3e4ad65287d9345624328377fdd5
[ 0.00017538749671075493, 0.00017115478112827986, 0.0001633314968785271, 0.00017145180027000606, 0.0000030948260700824903 ]
{ "id": 3, "code_window": [ " inputs:\n", " BuildDropPath: $(agent.builddirectory)/vscode-server-linux-$(VSCODE_ARCH)\n", " PackageName: Visual Studio Code Server\n", "\n", " - publish: $(agent.builddirectory)/vscode-server-linux-$(VSCODE_ARCH)/_manifest\n", " displayName: Publish SBOM (server)\n", " artifact: $(ARTIFACT_PREFIX)sbom_vscode_server_linux_$(VSCODE_ARCH)\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " - publish: $(agent.builddirectory)/VSCode-linux-$(VSCODE_ARCH)/_manifest\n", " displayName: Publish SBOM (client)\n", " artifact: $(ARTIFACT_PREFIX)sbom_vscode_client_linux_$(VSCODE_ARCH)\n", "\n" ], "file_path": "build/azure-pipelines/linux/product-build-linux.yml", "type": "add", "edit_start_line_idx": 302 }
parameters: - name: VSCODE_QUALITY type: string - name: VSCODE_ARCH type: string - name: VSCODE_CIBUILD type: boolean - name: VSCODE_RUN_UNIT_TESTS type: boolean - name: VSCODE_RUN_INTEGRATION_TESTS type: boolean - name: VSCODE_RUN_SMOKE_TESTS type: boolean steps: - ${{ if eq(parameters.VSCODE_QUALITY, 'oss') }}: - checkout: self fetchDepth: 1 retryCountOnTaskFailure: 3 - task: NodeTool@0 inputs: versionSpec: "16.x" - task: UsePythonVersion@0 inputs: versionSpec: "3.x" addToPath: true - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - template: ../distro/download-distro.yml - task: AzureKeyVault@1 displayName: "Azure Key Vault: Get Secrets" inputs: azureSubscription: "vscode-builds-subscription" KeyVaultName: vscode-build-secrets SecretsFilter: "github-distro-mixin-password,ESRP-PKI,esrp-aad-username,esrp-aad-password" - task: DownloadPipelineArtifact@2 inputs: artifact: Compilation path: $(Build.ArtifactStagingDirectory) displayName: Download compilation output - task: ExtractFiles@1 displayName: Extract compilation output inputs: archiveFilePatterns: "$(Build.ArtifactStagingDirectory)/compilation.tar.gz" cleanDestinationFolder: false - powershell: node build/setup-npm-registry.js $env:NPM_REGISTRY condition: and(succeeded(), ne(variables['NPM_REGISTRY'], 'none')) displayName: Setup NPM Registry - pwsh: | mkdir .build -ea 0 node build/azure-pipelines/common/computeNodeModulesCacheKey.js win32 $(VSCODE_ARCH) > .build/yarnlockhash displayName: Prepare node_modules cache key - task: Cache@2 inputs: key: '"node_modules" | .build/yarnlockhash' path: .build/node_modules_cache cacheHitVar: NODE_MODULES_RESTORED displayName: Restore node_modules cache - powershell: 7z.exe x .build/node_modules_cache/cache.7z -aoa condition: and(succeeded(), eq(variables.NODE_MODULES_RESTORED, 'true')) displayName: Extract node_modules cache - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" exec { npm config set registry "$env:NPM_REGISTRY" --location=project } exec { npm config set always-auth=true --location=project } exec { yarn config set registry "$env:NPM_REGISTRY" } condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'), ne(variables['NPM_REGISTRY'], 'none')) displayName: Setup NPM & Yarn - task: npmAuthenticate@0 inputs: workingFile: .npmrc condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'), ne(variables['NPM_REGISTRY'], 'none')) displayName: Setup NPM Authentication - powershell: | mkdir -Force .build/node-gyp displayName: Create custom node-gyp directory condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - powershell: | . ../../build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" # TODO: Should be replaced with upstream URL once https://github.com/nodejs/node-gyp/pull/2825 # gets merged. exec { git clone https://github.com/rzhao271/node-gyp.git . } "Cloning rzhao271/node-gyp failed" exec { git checkout 102b347da0c92c29f9c67df22e864e70249cf086 } "Checking out 102b347 failed" exec { npm install } "Building rzhao271/node-gyp failed" displayName: Install custom node-gyp workingDirectory: .build/node-gyp condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - powershell: | . build/azure-pipelines/win32/exec.ps1 . build/azure-pipelines/win32/retry.ps1 $ErrorActionPreference = "Stop" $env:npm_config_node_gyp="$(Join-Path $pwd.Path '.build/node-gyp/bin/node-gyp.js')" $env:npm_config_arch="$(VSCODE_ARCH)" $env:CHILD_CONCURRENCY="1" retry { exec { yarn --frozen-lockfile --check-files } } env: ELECTRON_SKIP_BINARY_DOWNLOAD: 1 PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1 GITHUB_TOKEN: "$(github-distro-mixin-password)" displayName: Install dependencies condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - powershell: node build/azure-pipelines/distro/mixin-npm condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) displayName: Mixin distro node modules - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" exec { node build/azure-pipelines/common/listNodeModules.js .build/node_modules_list.txt } exec { mkdir -Force .build/node_modules_cache } exec { 7z.exe a .build/node_modules_cache/cache.7z -mx3 `@.build/node_modules_list.txt } condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) displayName: Create node_modules archive - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - powershell: node build/azure-pipelines/distro/mixin-quality displayName: Mixin distro quality - template: ../common/install-builtin-extensions.yml - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - powershell: node build\lib\policies displayName: Generate Group Policy definitions retryCountOnTaskFailure: 3 - ${{ if eq(parameters.VSCODE_QUALITY, 'oss') }}: - powershell: yarn gulp "transpile-client-swc" "transpile-extensions" env: GITHUB_TOKEN: "$(github-distro-mixin-password)" displayName: Transpile - ${{ else }}: - ${{ if eq(parameters.VSCODE_QUALITY, 'insider') }}: - powershell: node build/win32/explorer-appx-fetcher .build/win32/appx displayName: Download Explorer Sparse Package - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" exec { yarn gulp "vscode-win32-$(VSCODE_ARCH)-min-ci" } exec { yarn gulp "vscode-win32-$(VSCODE_ARCH)-inno-updater" } echo "##vso[task.setvariable variable=BUILT_CLIENT]true" echo "##vso[task.setvariable variable=CodeSigningFolderPath]$(agent.builddirectory)/VSCode-win32-$(VSCODE_ARCH)" env: GITHUB_TOKEN: "$(github-distro-mixin-password)" displayName: Build client - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" exec { yarn gulp "vscode-reh-win32-$(VSCODE_ARCH)-min-ci" } mv ..\vscode-reh-win32-$(VSCODE_ARCH) ..\vscode-server-win32-$(VSCODE_ARCH) # TODO@joaomoreno echo "##vso[task.setvariable variable=BUILT_SERVER]true" echo "##vso[task.setvariable variable=CodeSigningFolderPath]$(CodeSigningFolderPath),$(agent.builddirectory)/vscode-server-win32-$(VSCODE_ARCH)" env: GITHUB_TOKEN: "$(github-distro-mixin-password)" displayName: Build server condition: and(succeeded(), ne(variables['VSCODE_ARCH'], 'arm64')) - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" exec { yarn gulp "vscode-reh-web-win32-$(VSCODE_ARCH)-min-ci" } mv ..\vscode-reh-web-win32-$(VSCODE_ARCH) ..\vscode-server-win32-$(VSCODE_ARCH)-web # TODO@joaomoreno echo "##vso[task.setvariable variable=BUILT_WEB]true" env: GITHUB_TOKEN: "$(github-distro-mixin-password)" displayName: Build server (web) condition: and(succeeded(), ne(variables['VSCODE_ARCH'], 'arm64')) - ${{ if or(eq(parameters.VSCODE_RUN_UNIT_TESTS, true), eq(parameters.VSCODE_RUN_INTEGRATION_TESTS, true), eq(parameters.VSCODE_RUN_SMOKE_TESTS, true)) }}: - template: product-build-win32-test.yml parameters: VSCODE_QUALITY: ${{ parameters.VSCODE_QUALITY }} VSCODE_ARCH: ${{ parameters.VSCODE_ARCH }} VSCODE_RUN_UNIT_TESTS: ${{ parameters.VSCODE_RUN_UNIT_TESTS }} VSCODE_RUN_INTEGRATION_TESTS: ${{ parameters.VSCODE_RUN_INTEGRATION_TESTS }} VSCODE_RUN_SMOKE_TESTS: ${{ parameters.VSCODE_RUN_SMOKE_TESTS }} - ${{ if ne(parameters.VSCODE_CIBUILD, true) }}: - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - task: DownloadPipelineArtifact@2 inputs: artifact: unsigned_vscode_cli_win32_$(VSCODE_ARCH)_cli patterns: "**" path: $(Build.ArtifactStagingDirectory)/cli displayName: Download VS Code CLI - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" $ArtifactName = (gci -Path "$(Build.ArtifactStagingDirectory)/cli" | Select-Object -last 1).FullName Expand-Archive -Path $ArtifactName -DestinationPath "$(Build.ArtifactStagingDirectory)/cli" $AppProductJson = Get-Content -Raw -Path "$(agent.builddirectory)\VSCode-win32-$(VSCODE_ARCH)\resources\app\product.json" | ConvertFrom-Json $CliAppName = $AppProductJson.tunnelApplicationName $AppName = $AppProductJson.applicationName Move-Item -Path "$(Build.ArtifactStagingDirectory)/cli/$AppName.exe" -Destination "$(agent.builddirectory)/VSCode-win32-$(VSCODE_ARCH)/bin/$CliAppName.exe" displayName: Move VS Code CLI - task: UseDotNet@2 inputs: version: 6.x - task: EsrpClientTool@1 displayName: Download ESRPClient - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" $EsrpClientTool = (gci -directory -filter EsrpClientTool_* $(Agent.RootDirectory)\_tasks | Select-Object -last 1).FullName $EsrpCliZip = (gci -recurse -filter esrpcli.*.zip $EsrpClientTool | Select-Object -last 1).FullName mkdir -p $(Agent.TempDirectory)\esrpcli Expand-Archive -Path $EsrpCliZip -DestinationPath $(Agent.TempDirectory)\esrpcli $EsrpCliDllPath = (gci -recurse -filter esrpcli.dll $(Agent.TempDirectory)\esrpcli | Select-Object -last 1).FullName echo "##vso[task.setvariable variable=EsrpCliDllPath]$EsrpCliDllPath" displayName: Find ESRP CLI - powershell: node build\azure-pipelines\common\sign $env:EsrpCliDllPath windows $(ESRP-PKI) $(esrp-aad-username) $(esrp-aad-password) $(CodeSigningFolderPath) '*.dll,*.exe,*.node' displayName: Codesign - ${{ if eq(parameters.VSCODE_QUALITY, 'insider') }}: - powershell: node build\azure-pipelines\common\sign $env:EsrpCliDllPath windows-appx $(ESRP-PKI) $(esrp-aad-username) $(esrp-aad-password) $(CodeSigningFolderPath) '*.appx' displayName: Codesign context menu appx package - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - powershell: | $PackageJson = Get-Content -Raw -Path ..\VSCode-win32-$(VSCODE_ARCH)\resources\app\package.json | ConvertFrom-Json $Version = $PackageJson.version echo "##vso[task.setvariable variable=VSCODE_VERSION]$Version" condition: succeededOrFailed() displayName: Get product version - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" $ArchivePath = ".build\win32-$(VSCODE_ARCH)\VSCode-win32-$(VSCODE_ARCH)-$(VSCODE_VERSION).zip" New-Item -ItemType Directory -Path .build\win32-$(VSCODE_ARCH) -Force exec { 7z.exe a -tzip $ArchivePath -x!CodeSignSummary*.md ..\VSCode-win32-$(VSCODE_ARCH)\* -r } echo "##vso[task.setvariable variable=CLIENT_PATH]$ArchivePath" condition: and(succeededOrFailed(), eq(variables['BUILT_CLIENT'], 'true')) displayName: Package client - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" $ArchivePath = ".build\win32-$(VSCODE_ARCH)\vscode-server-win32-$(VSCODE_ARCH).zip" New-Item -ItemType Directory -Path .build\win32-$(VSCODE_ARCH) -Force exec { 7z.exe a -tzip $ArchivePath ..\vscode-server-win32-$(VSCODE_ARCH)\* -r } echo "##vso[task.setvariable variable=SERVER_PATH]$ArchivePath" condition: and(succeededOrFailed(), eq(variables['BUILT_SERVER'], 'true')) displayName: Package server - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" $ArchivePath = ".build\win32-$(VSCODE_ARCH)\vscode-server-win32-$(VSCODE_ARCH)-web.zip" New-Item -ItemType Directory -Path .build\win32-$(VSCODE_ARCH) -Force exec { 7z.exe a -tzip $ArchivePath ..\vscode-server-win32-$(VSCODE_ARCH)-web\* -r } echo "##vso[task.setvariable variable=WEB_PATH]$ArchivePath" condition: and(succeededOrFailed(), eq(variables['BUILT_WEB'], 'true')) displayName: Package server (web) - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" $env:ESRPPKI = "$(ESRP-PKI)" $env:ESRPAADUsername = "$(esrp-aad-username)" $env:ESRPAADPassword = "$(esrp-aad-password)" exec { yarn gulp "vscode-win32-$(VSCODE_ARCH)-system-setup" --sign } $SetupPath = ".build\win32-$(VSCODE_ARCH)\system-setup\VSCodeSetup-$(VSCODE_ARCH)-$(VSCODE_VERSION).exe" mv .build\win32-$(VSCODE_ARCH)\system-setup\VSCodeSetup.exe $SetupPath echo "##vso[task.setvariable variable=SYSTEM_SETUP_PATH]$SetupPath" displayName: Build system setup - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" $env:ESRPPKI = "$(ESRP-PKI)" $env:ESRPAADUsername = "$(esrp-aad-username)" $env:ESRPAADPassword = "$(esrp-aad-password)" exec { yarn gulp "vscode-win32-$(VSCODE_ARCH)-user-setup" --sign } $SetupPath = ".build\win32-$(VSCODE_ARCH)\user-setup\VSCodeUserSetup-$(VSCODE_ARCH)-$(VSCODE_VERSION).exe" mv .build\win32-$(VSCODE_ARCH)\user-setup\VSCodeSetup.exe $SetupPath echo "##vso[task.setvariable variable=USER_SETUP_PATH]$SetupPath" displayName: Build user setup - powershell: echo "##vso[task.setvariable variable=ARTIFACT_PREFIX]attempt$(System.JobAttempt)_" condition: and(succeededOrFailed(), notIn(variables['Agent.JobStatus'], 'Succeeded', 'SucceededWithIssues')) displayName: Generate artifact prefix - task: AzureArtifacts.manifest-generator-task.manifest-generator-task.ManifestGeneratorTask@0 displayName: Generate SBOM (client) inputs: BuildDropPath: $(agent.builddirectory)/VSCode-win32-$(VSCODE_ARCH) PackageName: Visual Studio Code - publish: $(agent.builddirectory)/VSCode-win32-$(VSCODE_ARCH)/_manifest displayName: Publish SBOM (client) artifact: $(ARTIFACT_PREFIX)sbom_client_win32_$(VSCODE_ARCH) - task: AzureArtifacts.manifest-generator-task.manifest-generator-task.ManifestGeneratorTask@0 displayName: Generate SBOM (server) inputs: BuildDropPath: $(agent.builddirectory)/vscode-server-win32-$(VSCODE_ARCH) PackageName: Visual Studio Code Server condition: and(succeeded(), ne(variables['VSCODE_ARCH'], 'arm64')) - publish: $(agent.builddirectory)/vscode-server-win32-$(VSCODE_ARCH)/_manifest displayName: Publish SBOM (server) artifact: $(ARTIFACT_PREFIX)sbom_server_win32_$(VSCODE_ARCH) condition: and(succeeded(), ne(variables['VSCODE_ARCH'], 'arm64')) - publish: $(CLIENT_PATH) artifact: $(ARTIFACT_PREFIX)vscode_client_win32_$(VSCODE_ARCH)_archive condition: and(succeededOrFailed(), ne(variables['CLIENT_PATH'], '')) displayName: Publish archive - publish: $(SERVER_PATH) artifact: $(ARTIFACT_PREFIX)vscode_server_win32_$(VSCODE_ARCH)_archive condition: and(succeededOrFailed(), ne(variables['SERVER_PATH'], ''), ne(variables['VSCODE_ARCH'], 'arm64')) displayName: Publish server archive - publish: $(WEB_PATH) artifact: $(ARTIFACT_PREFIX)vscode_web_win32_$(VSCODE_ARCH)_archive condition: and(succeededOrFailed(), ne(variables['WEB_PATH'], ''), ne(variables['VSCODE_ARCH'], 'arm64')) displayName: Publish web server archive - publish: $(SYSTEM_SETUP_PATH) artifact: $(ARTIFACT_PREFIX)vscode_client_win32_$(VSCODE_ARCH)_setup condition: and(succeededOrFailed(), ne(variables['SYSTEM_SETUP_PATH'], '')) displayName: Publish system setup - publish: $(USER_SETUP_PATH) artifact: $(ARTIFACT_PREFIX)vscode_client_win32_$(VSCODE_ARCH)_user-setup condition: and(succeededOrFailed(), ne(variables['USER_SETUP_PATH'], '')) displayName: Publish user setup
build/azure-pipelines/win32/product-build-win32.yml
1
https://github.com/microsoft/vscode/commit/6bad769697ec3e4ad65287d9345624328377fdd5
[ 0.04272831976413727, 0.0022336426191031933, 0.00016476133896503597, 0.0003775959194172174, 0.00717916339635849 ]
{ "id": 3, "code_window": [ " inputs:\n", " BuildDropPath: $(agent.builddirectory)/vscode-server-linux-$(VSCODE_ARCH)\n", " PackageName: Visual Studio Code Server\n", "\n", " - publish: $(agent.builddirectory)/vscode-server-linux-$(VSCODE_ARCH)/_manifest\n", " displayName: Publish SBOM (server)\n", " artifact: $(ARTIFACT_PREFIX)sbom_vscode_server_linux_$(VSCODE_ARCH)\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " - publish: $(agent.builddirectory)/VSCode-linux-$(VSCODE_ARCH)/_manifest\n", " displayName: Publish SBOM (client)\n", " artifact: $(ARTIFACT_PREFIX)sbom_vscode_client_linux_$(VSCODE_ARCH)\n", "\n" ], "file_path": "build/azure-pipelines/linux/product-build-linux.yml", "type": "add", "edit_start_line_idx": 302 }
{ "original": { "content": "import * as path from 'path';\nimport { Command } from 'vscode';\nimport * as nls from 'vscode-nls';\n\n\"()()()()()()()()()()()()()\"", "fileName": "./1.tst" }, "modified": { "content": "import * as path from 'path';\nimport { Command, commands } from 'vscode';\nimport * as nls from 'vscode-nls';\n\n\"Gallicum()est()divisa()in()partres()tres()quarum()unam()est()()()()()()()()()()()()\"", "fileName": "./2.tst" }, "diffs": [ { "originalRange": "[2,3)", "modifiedRange": "[2,3)", "innerChanges": [ { "originalRange": "[2,17 -> 2,17]", "modifiedRange": "[2,17 -> 2,27]" } ] }, { "originalRange": "[5,6)", "modifiedRange": "[5,6)", "innerChanges": [ { "originalRange": "[5,2 -> 5,4]", "modifiedRange": "[5,2 -> 5,61]" } ] } ] }
src/vs/editor/test/node/diffing/fixtures/minimal-diff-character/legacy.expected.diff.json
0
https://github.com/microsoft/vscode/commit/6bad769697ec3e4ad65287d9345624328377fdd5
[ 0.00017399962234776467, 0.00017265768838115036, 0.00017136700625997037, 0.00017263207701034844, 0.0000010494142088646186 ]
{ "id": 3, "code_window": [ " inputs:\n", " BuildDropPath: $(agent.builddirectory)/vscode-server-linux-$(VSCODE_ARCH)\n", " PackageName: Visual Studio Code Server\n", "\n", " - publish: $(agent.builddirectory)/vscode-server-linux-$(VSCODE_ARCH)/_manifest\n", " displayName: Publish SBOM (server)\n", " artifact: $(ARTIFACT_PREFIX)sbom_vscode_server_linux_$(VSCODE_ARCH)\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " - publish: $(agent.builddirectory)/VSCode-linux-$(VSCODE_ARCH)/_manifest\n", " displayName: Publish SBOM (client)\n", " artifact: $(ARTIFACT_PREFIX)sbom_vscode_client_linux_$(VSCODE_ARCH)\n", "\n" ], "file_path": "build/azure-pipelines/linux/product-build-linux.yml", "type": "add", "edit_start_line_idx": 302 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /* ---------- Find input ---------- */ .monaco-findInput { position: relative; } .monaco-findInput .monaco-inputbox { font-size: 13px; width: 100%; } .monaco-findInput > .controls { position: absolute; top: 3px; right: 2px; } .vs .monaco-findInput.disabled { background-color: #E1E1E1; } /* Theming */ .vs-dark .monaco-findInput.disabled { background-color: #333; } /* Highlighting */ .monaco-findInput.highlight-0 .controls, .hc-light .monaco-findInput.highlight-0 .controls { animation: monaco-findInput-highlight-0 100ms linear 0s; } .monaco-findInput.highlight-1 .controls, .hc-light .monaco-findInput.highlight-1 .controls { animation: monaco-findInput-highlight-1 100ms linear 0s; } .hc-black .monaco-findInput.highlight-0 .controls, .vs-dark .monaco-findInput.highlight-0 .controls { animation: monaco-findInput-highlight-dark-0 100ms linear 0s; } .hc-black .monaco-findInput.highlight-1 .controls, .vs-dark .monaco-findInput.highlight-1 .controls { animation: monaco-findInput-highlight-dark-1 100ms linear 0s; } @keyframes monaco-findInput-highlight-0 { 0% { background: rgba(253, 255, 0, 0.8); } 100% { background: transparent; } } @keyframes monaco-findInput-highlight-1 { 0% { background: rgba(253, 255, 0, 0.8); } /* Made intentionally different such that the CSS minifier does not collapse the two animations into a single one*/ 99% { background: transparent; } } @keyframes monaco-findInput-highlight-dark-0 { 0% { background: rgba(255, 255, 255, 0.44); } 100% { background: transparent; } } @keyframes monaco-findInput-highlight-dark-1 { 0% { background: rgba(255, 255, 255, 0.44); } /* Made intentionally different such that the CSS minifier does not collapse the two animations into a single one*/ 99% { background: transparent; } }
src/vs/base/browser/ui/findinput/findInput.css
0
https://github.com/microsoft/vscode/commit/6bad769697ec3e4ad65287d9345624328377fdd5
[ 0.00017543819558341056, 0.00017326287343166769, 0.00016797227726783603, 0.00017393144662491977, 0.000002103481165249832 ]
{ "id": 3, "code_window": [ " inputs:\n", " BuildDropPath: $(agent.builddirectory)/vscode-server-linux-$(VSCODE_ARCH)\n", " PackageName: Visual Studio Code Server\n", "\n", " - publish: $(agent.builddirectory)/vscode-server-linux-$(VSCODE_ARCH)/_manifest\n", " displayName: Publish SBOM (server)\n", " artifact: $(ARTIFACT_PREFIX)sbom_vscode_server_linux_$(VSCODE_ARCH)\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " - publish: $(agent.builddirectory)/VSCode-linux-$(VSCODE_ARCH)/_manifest\n", " displayName: Publish SBOM (client)\n", " artifact: $(ARTIFACT_PREFIX)sbom_vscode_client_linux_$(VSCODE_ARCH)\n", "\n" ], "file_path": "build/azure-pipelines/linux/product-build-linux.yml", "type": "add", "edit_start_line_idx": 302 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { KeyboardLayoutContribution } from 'vs/workbench/services/keybinding/browser/keyboardLayouts/_.contribution'; KeyboardLayoutContribution.INSTANCE.registerKeyboardLayout({ layout: { id: 'com.apple.keylayout.Spanish-ISO', lang: 'es', localizedName: 'Spanish - ISO' }, secondaryLayouts: [], mapping: { KeyA: ['a', 'A', 'å', 'Å', 0], KeyB: ['b', 'B', 'ß', '', 0], KeyC: ['c', 'C', '©', ' ', 0], KeyD: ['d', 'D', '∂', '∆', 0], KeyE: ['e', 'E', '€', '€', 0], KeyF: ['f', 'F', 'ƒ', 'fi', 0], KeyG: ['g', 'G', '', 'fl', 0], KeyH: ['h', 'H', '™', ' ', 0], KeyI: ['i', 'I', ' ', ' ', 0], KeyJ: ['j', 'J', '¶', '¯', 0], KeyK: ['k', 'K', '§', 'ˇ', 0], KeyL: ['l', 'L', ' ', '˘', 0], KeyM: ['m', 'M', 'µ', '˚', 0], KeyN: ['n', 'N', ' ', '˙', 0], KeyO: ['o', 'O', 'ø', 'Ø', 0], KeyP: ['p', 'P', 'π', '∏', 0], KeyQ: ['q', 'Q', 'œ', 'Œ', 0], KeyR: ['r', 'R', '®', ' ', 0], KeyS: ['s', 'S', '∫', ' ', 0], KeyT: ['t', 'T', '†', '‡', 0], KeyU: ['u', 'U', ' ', ' ', 0], KeyV: ['v', 'V', '√', '◊', 0], KeyW: ['w', 'W', 'æ', 'Æ', 0], KeyX: ['x', 'X', '∑', '›', 0], KeyY: ['y', 'Y', '¥', ' ', 0], KeyZ: ['z', 'Z', 'Ω', '‹', 0], Digit1: ['1', '!', '|', 'ı', 0], Digit2: ['2', '"', '@', '˝', 0], Digit3: ['3', '·', '#', '•', 0], Digit4: ['4', '$', '¢', '£', 0], Digit5: ['5', '%', '∞', '‰', 0], Digit6: ['6', '&', '¬', ' ', 0], Digit7: ['7', '/', '÷', '⁄', 0], Digit8: ['8', '(', '“', '‘', 0], Digit9: ['9', ')', '”', '’', 0], Digit0: ['0', '=', '≠', '≈', 0], Enter: [], Escape: [], Backspace: [], Tab: [], Space: [' ', ' ', ' ', ' ', 0], Minus: ['\'', '?', '´', '¸', 0], Equal: ['¡', '¿', '‚', '˛', 0], BracketLeft: ['`', '^', '[', 'ˆ', 3], BracketRight: ['+', '*', ']', '±', 0], Backslash: ['ç', 'Ç', '}', '»', 0], Semicolon: ['ñ', 'Ñ', '~', '˜', 4], Quote: ['´', '¨', '{', '«', 3], Backquote: ['<', '>', '≤', '≥', 0], Comma: [',', ';', '„', '', 0], Period: ['.', ':', '…', '…', 0], Slash: ['-', '_', '–', '—', 0], CapsLock: [], F1: [], F2: [], F3: [], F4: [], F5: [], F6: [], F7: [], F8: [], F9: [], F10: [], F11: [], F12: [], Insert: [], Home: [], PageUp: [], Delete: [], End: [], PageDown: [], ArrowRight: [], ArrowLeft: [], ArrowDown: [], ArrowUp: [], NumLock: [], NumpadDivide: ['/', '/', '/', '/', 0], NumpadMultiply: ['*', '*', '*', '*', 0], NumpadSubtract: ['-', '-', '-', '-', 0], NumpadAdd: ['+', '+', '+', '+', 0], NumpadEnter: [], Numpad1: ['1', '1', '1', '1', 0], Numpad2: ['2', '2', '2', '2', 0], Numpad3: ['3', '3', '3', '3', 0], Numpad4: ['4', '4', '4', '4', 0], Numpad5: ['5', '5', '5', '5', 0], Numpad6: ['6', '6', '6', '6', 0], Numpad7: ['7', '7', '7', '7', 0], Numpad8: ['8', '8', '8', '8', 0], Numpad9: ['9', '9', '9', '9', 0], Numpad0: ['0', '0', '0', '0', 0], NumpadDecimal: [',', ',', ',', ',', 0], IntlBackslash: ['º', 'ª', '\\', '°', 0], ContextMenu: [], NumpadEqual: ['=', '=', '=', '=', 0], F13: [], F14: [], F15: [], F16: [], F17: [], F18: [], F19: [], F20: [], AudioVolumeMute: [], AudioVolumeUp: ['', '=', '', '=', 0], AudioVolumeDown: [], NumpadComma: [], IntlRo: [], KanaMode: [], IntlYen: [], ControlLeft: [], ShiftLeft: [], AltLeft: [], MetaLeft: [], ControlRight: [], ShiftRight: [], AltRight: [], MetaRight: [] } });
src/vs/workbench/services/keybinding/browser/keyboardLayouts/es.darwin.ts
0
https://github.com/microsoft/vscode/commit/6bad769697ec3e4ad65287d9345624328377fdd5
[ 0.0001745318586472422, 0.00017152889631688595, 0.0001676202955422923, 0.00017143352306447923, 0.0000016188746485568117 ]
{ "id": 4, "code_window": [ " displayName: Generate SBOM (client)\n", " inputs:\n", " BuildDropPath: $(agent.builddirectory)/VSCode-win32-$(VSCODE_ARCH)\n", " PackageName: Visual Studio Code\n", "\n", " - publish: $(agent.builddirectory)/VSCode-win32-$(VSCODE_ARCH)/_manifest\n", " displayName: Publish SBOM (client)\n", " artifact: $(ARTIFACT_PREFIX)sbom_client_win32_$(VSCODE_ARCH)\n", "\n", " - task: AzureArtifacts.manifest-generator-task.manifest-generator-task.ManifestGeneratorTask@0\n", " displayName: Generate SBOM (server)\n", " inputs:\n", " BuildDropPath: $(agent.builddirectory)/vscode-server-win32-$(VSCODE_ARCH)\n", " PackageName: Visual Studio Code Server\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "build/azure-pipelines/win32/product-build-win32.yml", "type": "replace", "edit_start_line_idx": 314 }
parameters: - name: VSCODE_QUALITY type: string - name: VSCODE_CIBUILD type: boolean - name: VSCODE_RUN_UNIT_TESTS type: boolean - name: VSCODE_RUN_INTEGRATION_TESTS type: boolean - name: VSCODE_RUN_SMOKE_TESTS type: boolean steps: - ${{ if eq(parameters.VSCODE_QUALITY, 'oss') }}: - checkout: self fetchDepth: 1 retryCountOnTaskFailure: 3 - task: NodeTool@0 inputs: versionSpec: "16.x" - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - template: ../distro/download-distro.yml - task: AzureKeyVault@1 displayName: "Azure Key Vault: Get Secrets" inputs: azureSubscription: "vscode-builds-subscription" KeyVaultName: vscode-build-secrets SecretsFilter: "github-distro-mixin-password,macos-developer-certificate,macos-developer-certificate-key" - task: DownloadPipelineArtifact@2 inputs: artifact: Compilation path: $(Build.ArtifactStagingDirectory) displayName: Download compilation output - script: tar -xzf $(Build.ArtifactStagingDirectory)/compilation.tar.gz displayName: Extract compilation output - script: node build/setup-npm-registry.js $NPM_REGISTRY condition: and(succeeded(), ne(variables['NPM_REGISTRY'], 'none')) displayName: Setup NPM Registry - script: mkdir -p .build && node build/azure-pipelines/common/computeNodeModulesCacheKey.js darwin $VSCODE_ARCH > .build/yarnlockhash displayName: Prepare node_modules cache key - task: Cache@2 inputs: key: '"node_modules" | .build/yarnlockhash' path: .build/node_modules_cache cacheHitVar: NODE_MODULES_RESTORED displayName: Restore node_modules cache - script: tar -xzf .build/node_modules_cache/cache.tgz condition: and(succeeded(), eq(variables.NODE_MODULES_RESTORED, 'true')) displayName: Extract node_modules cache - script: | set -e npm config set registry "$NPM_REGISTRY" --location=project npm config set always-auth=true --location=project yarn config set registry "$NPM_REGISTRY" condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'), ne(variables['NPM_REGISTRY'], 'none')) displayName: Setup NPM & Yarn - task: npmAuthenticate@0 inputs: workingFile: .npmrc condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'), ne(variables['NPM_REGISTRY'], 'none')) displayName: Setup NPM Authentication - script: | set -e export npm_config_arch=$(VSCODE_ARCH) export npm_config_node_gyp=$(which node-gyp) for i in {1..5}; do # try 5 times yarn --frozen-lockfile --check-files && break if [ $i -eq 3 ]; then echo "Yarn failed too many times" >&2 exit 1 fi echo "Yarn failed $i, trying again..." done env: ELECTRON_SKIP_BINARY_DOWNLOAD: 1 PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1 GITHUB_TOKEN: "$(github-distro-mixin-password)" displayName: Install dependencies condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - script: node build/azure-pipelines/distro/mixin-npm condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) displayName: Mixin distro node modules - script: | set -e node build/azure-pipelines/common/listNodeModules.js .build/node_modules_list.txt mkdir -p .build/node_modules_cache tar -czf .build/node_modules_cache/cache.tgz --files-from .build/node_modules_list.txt condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) displayName: Create node_modules archive - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - script: node build/azure-pipelines/distro/mixin-quality displayName: Mixin distro quality - template: ../common/install-builtin-extensions.yml - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - script: | set -e yarn gulp vscode-darwin-$(VSCODE_ARCH)-min-ci echo "##vso[task.setvariable variable=BUILT_CLIENT]true" env: GITHUB_TOKEN: "$(github-distro-mixin-password)" displayName: Build client - script: | set -e yarn gulp vscode-reh-darwin-$(VSCODE_ARCH)-min-ci mv ../vscode-reh-darwin-$(VSCODE_ARCH) ../vscode-server-darwin-$(VSCODE_ARCH) # TODO@joaomoreno ARCHIVE_PATH=".build/darwin/server/vscode-server-darwin-$(VSCODE_ARCH).zip" mkdir -p $(dirname $ARCHIVE_PATH) (cd .. && zip -Xry $(Build.SourcesDirectory)/$ARCHIVE_PATH vscode-server-darwin-$(VSCODE_ARCH)) echo "##vso[task.setvariable variable=SERVER_PATH]$ARCHIVE_PATH" env: GITHUB_TOKEN: "$(github-distro-mixin-password)" displayName: Build server - script: | set -e yarn gulp vscode-reh-web-darwin-$(VSCODE_ARCH)-min-ci mv ../vscode-reh-web-darwin-$(VSCODE_ARCH) ../vscode-server-darwin-$(VSCODE_ARCH)-web # TODO@joaomoreno ARCHIVE_PATH=".build/darwin/server/vscode-server-darwin-$(VSCODE_ARCH)-web.zip" mkdir -p $(dirname $ARCHIVE_PATH) (cd .. && zip -Xry $(Build.SourcesDirectory)/$ARCHIVE_PATH vscode-server-darwin-$(VSCODE_ARCH)-web) echo "##vso[task.setvariable variable=WEB_PATH]$ARCHIVE_PATH" env: GITHUB_TOKEN: "$(github-distro-mixin-password)" displayName: Build server (web) - ${{ else }}: - script: yarn gulp transpile-client-swc transpile-extensions env: GITHUB_TOKEN: "$(github-distro-mixin-password)" displayName: Transpile - ${{ if or(eq(parameters.VSCODE_RUN_UNIT_TESTS, true), eq(parameters.VSCODE_RUN_INTEGRATION_TESTS, true), eq(parameters.VSCODE_RUN_SMOKE_TESTS, true)) }}: - template: product-build-darwin-test.yml parameters: VSCODE_QUALITY: ${{ parameters.VSCODE_QUALITY }} VSCODE_RUN_UNIT_TESTS: ${{ parameters.VSCODE_RUN_UNIT_TESTS }} VSCODE_RUN_INTEGRATION_TESTS: ${{ parameters.VSCODE_RUN_INTEGRATION_TESTS }} VSCODE_RUN_SMOKE_TESTS: ${{ parameters.VSCODE_RUN_SMOKE_TESTS }} - ${{ elseif and(ne(parameters.VSCODE_CIBUILD, true), ne(parameters.VSCODE_QUALITY, 'oss')) }}: - task: DownloadPipelineArtifact@2 inputs: artifact: unsigned_vscode_cli_darwin_$(VSCODE_ARCH)_cli patterns: "**" path: $(Build.ArtifactStagingDirectory)/cli displayName: Download VS Code CLI - script: | set -e APP_ROOT="$(Agent.BuildDirectory)/VSCode-darwin-$(VSCODE_ARCH)" APP_NAME="`ls $APP_ROOT | head -n 1`" APP_PATH="$APP_ROOT/$APP_NAME" ARCHIVE_NAME=$(ls "$(Build.ArtifactStagingDirectory)/cli" | head -n 1) unzip "$(Build.ArtifactStagingDirectory)/cli/$ARCHIVE_NAME" -d "$(Build.ArtifactStagingDirectory)/cli" CLI_APP_NAME=$(node -p "require(\"$APP_PATH/Contents/Resources/app/product.json\").tunnelApplicationName") APP_NAME=$(node -p "require(\"$APP_PATH/Contents/Resources/app/product.json\").applicationName") mv "$(Build.ArtifactStagingDirectory)/cli/$APP_NAME" "$APP_PATH/Contents/Resources/app/bin/$CLI_APP_NAME" chmod +x "$APP_PATH/Contents/Resources/app/bin/$CLI_APP_NAME" displayName: Make CLI executable # Setting hardened entitlements is a requirement for: # * Apple notarization # * Running tests on Big Sur (because Big Sur has additional security precautions) - script: | set -e security create-keychain -p pwd $(agent.tempdirectory)/buildagent.keychain security default-keychain -s $(agent.tempdirectory)/buildagent.keychain security unlock-keychain -p pwd $(agent.tempdirectory)/buildagent.keychain echo "$(macos-developer-certificate)" | base64 -D > $(agent.tempdirectory)/cert.p12 security import $(agent.tempdirectory)/cert.p12 -k $(agent.tempdirectory)/buildagent.keychain -P "$(macos-developer-certificate-key)" -T /usr/bin/codesign export CODESIGN_IDENTITY=$(security find-identity -v -p codesigning $(agent.tempdirectory)/buildagent.keychain | grep -oEi "([0-9A-F]{40})" | head -n 1) security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k pwd $(agent.tempdirectory)/buildagent.keychain DEBUG=electron-osx-sign* node build/darwin/sign.js $(agent.builddirectory) displayName: Set Hardened Entitlements - script: | set -e ARCHIVE_PATH=".build/darwin/client/VSCode-darwin-$(VSCODE_ARCH).zip" mkdir -p $(dirname $ARCHIVE_PATH) (cd ../VSCode-darwin-$(VSCODE_ARCH) && zip -Xry $(Build.SourcesDirectory)/$ARCHIVE_PATH *) echo "##vso[task.setvariable variable=CLIENT_PATH]$ARCHIVE_PATH" condition: and(succeededOrFailed(), eq(variables['BUILT_CLIENT'], 'true')) displayName: Package client - script: echo "##vso[task.setvariable variable=ARTIFACT_PREFIX]attempt$(System.JobAttempt)_" condition: and(succeededOrFailed(), notIn(variables['Agent.JobStatus'], 'Succeeded', 'SucceededWithIssues')) displayName: Generate artifact prefix - task: AzureArtifacts.manifest-generator-task.manifest-generator-task.ManifestGeneratorTask@0 displayName: Generate SBOM (client) inputs: BuildDropPath: $(agent.builddirectory)/VSCode-darwin-$(VSCODE_ARCH) PackageName: Visual Studio Code - publish: $(agent.builddirectory)/VSCode-darwin-$(VSCODE_ARCH)/_manifest displayName: Publish SBOM (client) artifact: $(ARTIFACT_PREFIX)sbom_client_darwin_$(VSCODE_ARCH)_sbom - task: AzureArtifacts.manifest-generator-task.manifest-generator-task.ManifestGeneratorTask@0 displayName: Generate SBOM (server) inputs: BuildDropPath: $(agent.builddirectory)/vscode-server-darwin-$(VSCODE_ARCH) PackageName: Visual Studio Code Server - publish: $(agent.builddirectory)/vscode-server-darwin-$(VSCODE_ARCH)/_manifest displayName: Publish SBOM (server) artifact: $(ARTIFACT_PREFIX)sbom_server_darwin_$(VSCODE_ARCH)_sbom - publish: $(CLIENT_PATH) artifact: $(ARTIFACT_PREFIX)unsigned_vscode_client_darwin_$(VSCODE_ARCH)_archive condition: and(succeededOrFailed(), ne(variables['CLIENT_PATH'], '')) displayName: Publish client archive - publish: $(SERVER_PATH) artifact: $(ARTIFACT_PREFIX)vscode_server_darwin_$(VSCODE_ARCH)_archive-unsigned condition: and(succeededOrFailed(), ne(variables['SERVER_PATH'], '')) displayName: Publish server archive - publish: $(WEB_PATH) artifact: $(ARTIFACT_PREFIX)vscode_web_darwin_$(VSCODE_ARCH)_archive-unsigned condition: and(succeededOrFailed(), ne(variables['WEB_PATH'], '')) displayName: Publish web server archive
build/azure-pipelines/darwin/product-build-darwin.yml
1
https://github.com/microsoft/vscode/commit/6bad769697ec3e4ad65287d9345624328377fdd5
[ 0.9915169477462769, 0.05881365388631821, 0.00016288466576952487, 0.00016890525876078755, 0.20040825009346008 ]
{ "id": 4, "code_window": [ " displayName: Generate SBOM (client)\n", " inputs:\n", " BuildDropPath: $(agent.builddirectory)/VSCode-win32-$(VSCODE_ARCH)\n", " PackageName: Visual Studio Code\n", "\n", " - publish: $(agent.builddirectory)/VSCode-win32-$(VSCODE_ARCH)/_manifest\n", " displayName: Publish SBOM (client)\n", " artifact: $(ARTIFACT_PREFIX)sbom_client_win32_$(VSCODE_ARCH)\n", "\n", " - task: AzureArtifacts.manifest-generator-task.manifest-generator-task.ManifestGeneratorTask@0\n", " displayName: Generate SBOM (server)\n", " inputs:\n", " BuildDropPath: $(agent.builddirectory)/vscode-server-win32-$(VSCODE_ARCH)\n", " PackageName: Visual Studio Code Server\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "build/azure-pipelines/win32/product-build-win32.yml", "type": "replace", "edit_start_line_idx": 314 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Emitter } from 'vs/base/common/event'; import { Disposable } from 'vs/base/common/lifecycle'; import { IProcessDataEvent, ITerminalChildProcess, ITerminalLaunchError, IProcessProperty, IProcessPropertyMap, ProcessPropertyType, IProcessReadyEvent, IPtyService } from 'vs/platform/terminal/common/terminal'; import { URI } from 'vs/base/common/uri'; import { IPtyHostProcessReplayEvent, ISerializedCommandDetectionCapability } from 'vs/platform/terminal/common/capabilities/capabilities'; import { mark } from 'vs/base/common/performance'; /** * Responsible for establishing and maintaining a connection with an existing terminal process * created on the local pty host. */ export class LocalPty extends Disposable implements ITerminalChildProcess { private readonly _properties: IProcessPropertyMap = { cwd: '', initialCwd: '', fixedDimensions: { cols: undefined, rows: undefined }, title: '', shellType: undefined, hasChildProcesses: true, resolvedShellLaunchConfig: {}, overrideDimensions: undefined, failedShellIntegrationActivation: false, usedShellIntegrationInjection: undefined }; private readonly _lastDimensions: { cols: number; rows: number } = { cols: -1, rows: -1 }; private _inReplay = false; private readonly _onProcessData = this._register(new Emitter<IProcessDataEvent | string>()); readonly onProcessData = this._onProcessData.event; private readonly _onProcessReplayComplete = this._register(new Emitter<void>()); readonly onProcessReplayComplete = this._onProcessReplayComplete.event; private readonly _onProcessReady = this._register(new Emitter<IProcessReadyEvent>()); readonly onProcessReady = this._onProcessReady.event; private readonly _onDidChangeProperty = this._register(new Emitter<IProcessProperty<any>>()); readonly onDidChangeProperty = this._onDidChangeProperty.event; private readonly _onProcessExit = this._register(new Emitter<number | undefined>()); readonly onProcessExit = this._onProcessExit.event; private readonly _onRestoreCommands = this._register(new Emitter<ISerializedCommandDetectionCapability>()); readonly onRestoreCommands = this._onRestoreCommands.event; constructor( readonly id: number, readonly shouldPersist: boolean, private readonly _proxy: IPtyService ) { super(); } start(): Promise<ITerminalLaunchError | { injectedArgs: string[] } | undefined> { return this._proxy.start(this.id); } detach(forcePersist?: boolean): Promise<void> { return this._proxy.detachFromProcess(this.id, forcePersist); } shutdown(immediate: boolean): void { this._proxy.shutdown(this.id, immediate); } async processBinary(data: string): Promise<void> { if (this._inReplay) { return; } return this._proxy.processBinary(this.id, data); } input(data: string): void { if (this._inReplay) { return; } this._proxy.input(this.id, data); } resize(cols: number, rows: number): void { if (this._inReplay || this._lastDimensions.cols === cols && this._lastDimensions.rows === rows) { return; } this._lastDimensions.cols = cols; this._lastDimensions.rows = rows; this._proxy.resize(this.id, cols, rows); } async clearBuffer(): Promise<void> { this._proxy.clearBuffer?.(this.id); } freePortKillProcess(port: string): Promise<{ port: string; processId: string }> { if (!this._proxy.freePortKillProcess) { throw new Error('freePortKillProcess does not exist on the local pty service'); } return this._proxy.freePortKillProcess(port); } async getInitialCwd(): Promise<string> { return this._properties.initialCwd; } async getCwd(): Promise<string> { return this._properties.cwd || this._properties.initialCwd; } async refreshProperty<T extends ProcessPropertyType>(type: T): Promise<IProcessPropertyMap[T]> { return this._proxy.refreshProperty(this.id, type); } async updateProperty<T extends ProcessPropertyType>(type: T, value: IProcessPropertyMap[T]): Promise<void> { return this._proxy.updateProperty(this.id, type, value); } acknowledgeDataEvent(charCount: number): void { if (this._inReplay) { return; } this._proxy.acknowledgeDataEvent(this.id, charCount); } setUnicodeVersion(version: '6' | '11'): Promise<void> { return this._proxy.setUnicodeVersion(this.id, version); } handleData(e: string | IProcessDataEvent) { this._onProcessData.fire(e); } handleExit(e: number | undefined) { this._onProcessExit.fire(e); } handleReady(e: IProcessReadyEvent) { this._onProcessReady.fire(e); } handleDidChangeProperty({ type, value }: IProcessProperty<any>) { switch (type) { case ProcessPropertyType.Cwd: this._properties.cwd = value; break; case ProcessPropertyType.InitialCwd: this._properties.initialCwd = value; break; case ProcessPropertyType.ResolvedShellLaunchConfig: if (value.cwd && typeof value.cwd !== 'string') { value.cwd = URI.revive(value.cwd); } } this._onDidChangeProperty.fire({ type, value }); } async handleReplay(e: IPtyHostProcessReplayEvent) { mark(`code/terminal/willHandleReplay/${this.id}`); try { this._inReplay = true; for (const innerEvent of e.events) { if (innerEvent.cols !== 0 || innerEvent.rows !== 0) { // never override with 0x0 as that is a marker for an unknown initial size this._onDidChangeProperty.fire({ type: ProcessPropertyType.OverrideDimensions, value: { cols: innerEvent.cols, rows: innerEvent.rows, forceExactSize: true } }); } const e: IProcessDataEvent = { data: innerEvent.data, trackCommit: true }; this._onProcessData.fire(e); await e.writePromise; } } finally { this._inReplay = false; } if (e.commands) { this._onRestoreCommands.fire(e.commands); } // remove size override this._onDidChangeProperty.fire({ type: ProcessPropertyType.OverrideDimensions, value: undefined }); mark(`code/terminal/didHandleReplay/${this.id}`); this._onProcessReplayComplete.fire(); } handleOrphanQuestion() { this._proxy.orphanQuestionReply(this.id); } }
src/vs/workbench/contrib/terminal/electron-sandbox/localPty.ts
0
https://github.com/microsoft/vscode/commit/6bad769697ec3e4ad65287d9345624328377fdd5
[ 0.00017643549654167145, 0.0001738468708936125, 0.0001632341736694798, 0.00017486837168689817, 0.000003195459157723235 ]
{ "id": 4, "code_window": [ " displayName: Generate SBOM (client)\n", " inputs:\n", " BuildDropPath: $(agent.builddirectory)/VSCode-win32-$(VSCODE_ARCH)\n", " PackageName: Visual Studio Code\n", "\n", " - publish: $(agent.builddirectory)/VSCode-win32-$(VSCODE_ARCH)/_manifest\n", " displayName: Publish SBOM (client)\n", " artifact: $(ARTIFACT_PREFIX)sbom_client_win32_$(VSCODE_ARCH)\n", "\n", " - task: AzureArtifacts.manifest-generator-task.manifest-generator-task.ManifestGeneratorTask@0\n", " displayName: Generate SBOM (server)\n", " inputs:\n", " BuildDropPath: $(agent.builddirectory)/vscode-server-win32-$(VSCODE_ARCH)\n", " PackageName: Visual Studio Code Server\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "build/azure-pipelines/win32/product-build-win32.yml", "type": "replace", "edit_start_line_idx": 314 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { Schemas } from 'vs/base/common/network'; import { URI } from 'vs/base/common/uri'; import { EditorPart } from 'vs/workbench/browser/parts/editor/editorPart'; import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput'; import { EditorResolverService } from 'vs/workbench/services/editor/browser/editorResolverService'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { IEditorResolverService, ResolvedStatus, RegisteredEditorPriority } from 'vs/workbench/services/editor/common/editorResolverService'; import { createEditorPart, ITestInstantiationService, TestFileEditorInput, TestServiceAccessor, workbenchInstantiationService } from 'vs/workbench/test/browser/workbenchTestServices'; suite('EditorResolverService', () => { const TEST_EDITOR_INPUT_ID = 'testEditorInputForEditorResolverService'; const disposables = new DisposableStore(); teardown(() => disposables.clear()); async function createEditorResolverService(instantiationService: ITestInstantiationService = workbenchInstantiationService(undefined, disposables)): Promise<[EditorPart, EditorResolverService, TestServiceAccessor]> { const part = await createEditorPart(instantiationService, disposables); instantiationService.stub(IEditorGroupsService, part); const editorResolverService = instantiationService.createInstance(EditorResolverService); instantiationService.stub(IEditorResolverService, editorResolverService); return [part, editorResolverService, instantiationService.createInstance(TestServiceAccessor)]; } test('Simple Resolve', async () => { const [part, service] = await createEditorResolverService(); const registeredEditor = service.registerEditor('*.test', { id: 'TEST_EDITOR', label: 'Test Editor Label', detail: 'Test Editor Details', priority: RegisteredEditorPriority.default }, {}, { createEditorInput: ({ resource, options }, group) => ({ editor: new TestFileEditorInput(URI.parse(resource.toString()), TEST_EDITOR_INPUT_ID) }), } ); const resultingResolution = await service.resolveEditor({ resource: URI.file('my://resource-basics.test') }, part.activeGroup); assert.ok(resultingResolution); assert.notStrictEqual(typeof resultingResolution, 'number'); if (resultingResolution !== ResolvedStatus.ABORT && resultingResolution !== ResolvedStatus.NONE) { assert.strictEqual(resultingResolution.editor.typeId, TEST_EDITOR_INPUT_ID); resultingResolution.editor.dispose(); } registeredEditor.dispose(); }); test('Untitled Resolve', async () => { const UNTITLED_TEST_EDITOR_INPUT_ID = 'UNTITLED_TEST_INPUT'; const [part, service] = await createEditorResolverService(); const registeredEditor = service.registerEditor('*.test', { id: 'TEST_EDITOR', label: 'Test Editor Label', detail: 'Test Editor Details', priority: RegisteredEditorPriority.default }, {}, { createEditorInput: ({ resource, options }, group) => ({ editor: new TestFileEditorInput(URI.parse(resource.toString()), TEST_EDITOR_INPUT_ID) }), createUntitledEditorInput: ({ resource, options }, group) => ({ editor: new TestFileEditorInput((resource ? resource : URI.from({ scheme: Schemas.untitled })), UNTITLED_TEST_EDITOR_INPUT_ID) }), } ); // Untyped untitled - no resource let resultingResolution = await service.resolveEditor({ resource: undefined }, part.activeGroup); assert.ok(resultingResolution); // We don't expect untitled to match the *.test glob assert.strictEqual(typeof resultingResolution, 'number'); // Untyped untitled - with untitled resource resultingResolution = await service.resolveEditor({ resource: URI.from({ scheme: Schemas.untitled, path: 'foo.test' }) }, part.activeGroup); assert.ok(resultingResolution); assert.notStrictEqual(typeof resultingResolution, 'number'); if (resultingResolution !== ResolvedStatus.ABORT && resultingResolution !== ResolvedStatus.NONE) { assert.strictEqual(resultingResolution.editor.typeId, UNTITLED_TEST_EDITOR_INPUT_ID); resultingResolution.editor.dispose(); } // Untyped untitled - file resource with forceUntitled resultingResolution = await service.resolveEditor({ resource: URI.file('/fake.test'), forceUntitled: true }, part.activeGroup); assert.ok(resultingResolution); assert.notStrictEqual(typeof resultingResolution, 'number'); if (resultingResolution !== ResolvedStatus.ABORT && resultingResolution !== ResolvedStatus.NONE) { assert.strictEqual(resultingResolution.editor.typeId, UNTITLED_TEST_EDITOR_INPUT_ID); resultingResolution.editor.dispose(); } registeredEditor.dispose(); }); test('Side by side Resolve', async () => { const [part, service] = await createEditorResolverService(); const registeredEditorPrimary = service.registerEditor('*.test-primary', { id: 'TEST_EDITOR_PRIMARY', label: 'Test Editor Label Primary', detail: 'Test Editor Details Primary', priority: RegisteredEditorPriority.default }, {}, { createEditorInput: ({ resource, options }, group) => ({ editor: new TestFileEditorInput(URI.parse(resource.toString()), TEST_EDITOR_INPUT_ID) }), } ); const registeredEditorSecondary = service.registerEditor('*.test-secondary', { id: 'TEST_EDITOR_SECONDARY', label: 'Test Editor Label Secondary', detail: 'Test Editor Details Secondary', priority: RegisteredEditorPriority.default }, {}, { createEditorInput: ({ resource, options }, group) => ({ editor: new TestFileEditorInput(URI.parse(resource.toString()), TEST_EDITOR_INPUT_ID) }), } ); const resultingResolution = await service.resolveEditor({ primary: { resource: URI.file('my://resource-basics.test-primary') }, secondary: { resource: URI.file('my://resource-basics.test-secondary') } }, part.activeGroup); assert.ok(resultingResolution); assert.notStrictEqual(typeof resultingResolution, 'number'); if (resultingResolution !== ResolvedStatus.ABORT && resultingResolution !== ResolvedStatus.NONE) { assert.strictEqual(resultingResolution.editor.typeId, 'workbench.editorinputs.sidebysideEditorInput'); resultingResolution.editor.dispose(); } else { assert.fail(); } registeredEditorPrimary.dispose(); registeredEditorSecondary.dispose(); }); test('Diff editor Resolve', async () => { const [part, service, accessor] = await createEditorResolverService(); const registeredEditor = service.registerEditor('*.test-diff', { id: 'TEST_EDITOR', label: 'Test Editor Label', detail: 'Test Editor Details', priority: RegisteredEditorPriority.default }, {}, { createEditorInput: ({ resource, options }, group) => ({ editor: new TestFileEditorInput(URI.parse(resource.toString()), TEST_EDITOR_INPUT_ID) }), createDiffEditorInput: ({ modified, original, options }, group) => ({ editor: accessor.instantiationService.createInstance( DiffEditorInput, 'name', 'description', new TestFileEditorInput(URI.parse(original.toString()), TEST_EDITOR_INPUT_ID), new TestFileEditorInput(URI.parse(modified.toString()), TEST_EDITOR_INPUT_ID), undefined) }) } ); const resultingResolution = await service.resolveEditor({ original: { resource: URI.file('my://resource-basics.test-diff') }, modified: { resource: URI.file('my://resource-basics.test-diff') } }, part.activeGroup); assert.ok(resultingResolution); assert.notStrictEqual(typeof resultingResolution, 'number'); if (resultingResolution !== ResolvedStatus.ABORT && resultingResolution !== ResolvedStatus.NONE) { assert.strictEqual(resultingResolution.editor.typeId, 'workbench.editors.diffEditorInput'); resultingResolution.editor.dispose(); } else { assert.fail(); } registeredEditor.dispose(); }); test('Diff editor Resolve - Different Types', async () => { const [part, service, accessor] = await createEditorResolverService(); let diffOneCounter = 0; let diffTwoCounter = 0; let defaultDiffCounter = 0; const registeredEditor = service.registerEditor('*.test-diff', { id: 'TEST_EDITOR', label: 'Test Editor Label', detail: 'Test Editor Details', priority: RegisteredEditorPriority.default }, {}, { createEditorInput: ({ resource, options }, group) => ({ editor: new TestFileEditorInput(URI.parse(resource.toString()), TEST_EDITOR_INPUT_ID) }), createDiffEditorInput: ({ modified, original, options }, group) => { diffOneCounter++; return { editor: accessor.instantiationService.createInstance( DiffEditorInput, 'name', 'description', new TestFileEditorInput(URI.parse(original.toString()), TEST_EDITOR_INPUT_ID), new TestFileEditorInput(URI.parse(modified.toString()), TEST_EDITOR_INPUT_ID), undefined) }; } } ); const secondRegisteredEditor = service.registerEditor('*.test-secondDiff', { id: 'TEST_EDITOR_2', label: 'Test Editor Label', detail: 'Test Editor Details', priority: RegisteredEditorPriority.default }, {}, { createEditorInput: ({ resource, options }, group) => ({ editor: new TestFileEditorInput(URI.parse(resource.toString()), TEST_EDITOR_INPUT_ID) }), createDiffEditorInput: ({ modified, original, options }, group) => { diffTwoCounter++; return { editor: accessor.instantiationService.createInstance( DiffEditorInput, 'name', 'description', new TestFileEditorInput(URI.parse(original.toString()), TEST_EDITOR_INPUT_ID), new TestFileEditorInput(URI.parse(modified.toString()), TEST_EDITOR_INPUT_ID), undefined) }; } } ); const defaultRegisteredEditor = service.registerEditor('*', { id: 'default', label: 'Test Editor Label', detail: 'Test Editor Details', priority: RegisteredEditorPriority.option }, {}, { createEditorInput: ({ resource, options }, group) => ({ editor: new TestFileEditorInput(URI.parse(resource.toString()), TEST_EDITOR_INPUT_ID) }), createDiffEditorInput: ({ modified, original, options }, group) => { defaultDiffCounter++; return { editor: accessor.instantiationService.createInstance( DiffEditorInput, 'name', 'description', new TestFileEditorInput(URI.parse(original.toString()), TEST_EDITOR_INPUT_ID), new TestFileEditorInput(URI.parse(modified.toString()), TEST_EDITOR_INPUT_ID), undefined) }; } } ); let resultingResolution = await service.resolveEditor({ original: { resource: URI.file('my://resource-basics.test-diff') }, modified: { resource: URI.file('my://resource-basics.test-diff') } }, part.activeGroup); assert.ok(resultingResolution); assert.notStrictEqual(typeof resultingResolution, 'number'); if (resultingResolution !== ResolvedStatus.ABORT && resultingResolution !== ResolvedStatus.NONE) { assert.strictEqual(diffOneCounter, 1); assert.strictEqual(diffTwoCounter, 0); assert.strictEqual(defaultDiffCounter, 0); assert.strictEqual(resultingResolution.editor.typeId, 'workbench.editors.diffEditorInput'); resultingResolution.editor.dispose(); } else { assert.fail(); } resultingResolution = await service.resolveEditor({ original: { resource: URI.file('my://resource-basics.test-secondDiff') }, modified: { resource: URI.file('my://resource-basics.test-secondDiff') } }, part.activeGroup); assert.ok(resultingResolution); assert.notStrictEqual(typeof resultingResolution, 'number'); if (resultingResolution !== ResolvedStatus.ABORT && resultingResolution !== ResolvedStatus.NONE) { assert.strictEqual(diffOneCounter, 1); assert.strictEqual(diffTwoCounter, 1); assert.strictEqual(defaultDiffCounter, 0); assert.strictEqual(resultingResolution.editor.typeId, 'workbench.editors.diffEditorInput'); resultingResolution.editor.dispose(); } else { assert.fail(); } resultingResolution = await service.resolveEditor({ original: { resource: URI.file('my://resource-basics.test-secondDiff') }, modified: { resource: URI.file('my://resource-basics.test-diff') } }, part.activeGroup); assert.ok(resultingResolution); assert.notStrictEqual(typeof resultingResolution, 'number'); if (resultingResolution !== ResolvedStatus.ABORT && resultingResolution !== ResolvedStatus.NONE) { assert.strictEqual(diffOneCounter, 1); assert.strictEqual(diffTwoCounter, 1); assert.strictEqual(defaultDiffCounter, 1); assert.strictEqual(resultingResolution.editor.typeId, 'workbench.editors.diffEditorInput'); resultingResolution.editor.dispose(); } else { assert.fail(); } resultingResolution = await service.resolveEditor({ original: { resource: URI.file('my://resource-basics.test-diff') }, modified: { resource: URI.file('my://resource-basics.test-secondDiff') } }, part.activeGroup); assert.ok(resultingResolution); assert.notStrictEqual(typeof resultingResolution, 'number'); if (resultingResolution !== ResolvedStatus.ABORT && resultingResolution !== ResolvedStatus.NONE) { assert.strictEqual(diffOneCounter, 1); assert.strictEqual(diffTwoCounter, 1); assert.strictEqual(defaultDiffCounter, 2); assert.strictEqual(resultingResolution.editor.typeId, 'workbench.editors.diffEditorInput'); resultingResolution.editor.dispose(); } else { assert.fail(); } resultingResolution = await service.resolveEditor({ original: { resource: URI.file('my://resource-basics.test-secondDiff') }, modified: { resource: URI.file('my://resource-basics.test-diff') }, options: { override: 'TEST_EDITOR' } }, part.activeGroup); assert.ok(resultingResolution); assert.notStrictEqual(typeof resultingResolution, 'number'); if (resultingResolution !== ResolvedStatus.ABORT && resultingResolution !== ResolvedStatus.NONE) { assert.strictEqual(diffOneCounter, 2); assert.strictEqual(diffTwoCounter, 1); assert.strictEqual(defaultDiffCounter, 2); assert.strictEqual(resultingResolution.editor.typeId, 'workbench.editors.diffEditorInput'); resultingResolution.editor.dispose(); } else { assert.fail(); } registeredEditor.dispose(); secondRegisteredEditor.dispose(); defaultRegisteredEditor.dispose(); }); test('Registry & Events', async () => { const [, service] = await createEditorResolverService(); let eventCounter = 0; service.onDidChangeEditorRegistrations(() => { eventCounter++; }); const editors = service.getEditors(); const registeredEditor = service.registerEditor('*.test', { id: 'TEST_EDITOR', label: 'Test Editor Label', detail: 'Test Editor Details', priority: RegisteredEditorPriority.default }, {}, { createEditorInput: ({ resource, options }, group) => ({ editor: new TestFileEditorInput(URI.parse(resource.toString()), TEST_EDITOR_INPUT_ID) }) } ); assert.strictEqual(eventCounter, 1); assert.strictEqual(service.getEditors().length, editors.length + 1); assert.strictEqual(service.getEditors().some(editor => editor.id === 'TEST_EDITOR'), true); registeredEditor.dispose(); assert.strictEqual(eventCounter, 2); assert.strictEqual(service.getEditors().length, editors.length); assert.strictEqual(service.getEditors().some(editor => editor.id === 'TEST_EDITOR'), false); }); test('Multiple registrations to same glob and id #155859', async () => { const [part, service, accessor] = await createEditorResolverService(); const testEditorInfo = { id: 'TEST_EDITOR', label: 'Test Editor Label', detail: 'Test Editor Details', priority: RegisteredEditorPriority.default }; const registeredSingleEditor = service.registerEditor('*.test', testEditorInfo, {}, { createEditorInput: ({ resource, options }, group) => ({ editor: new TestFileEditorInput(URI.parse(resource.toString()), TEST_EDITOR_INPUT_ID) }) } ); const registeredDiffEditor = service.registerEditor('*.test', testEditorInfo, {}, { createDiffEditorInput: ({ modified, original, options }, group) => ({ editor: accessor.instantiationService.createInstance( DiffEditorInput, 'name', 'description', new TestFileEditorInput(URI.parse(original.toString()), TEST_EDITOR_INPUT_ID), new TestFileEditorInput(URI.parse(modified.toString()), TEST_EDITOR_INPUT_ID), undefined) }) } ); // Resolve a diff let resultingResolution = await service.resolveEditor({ original: { resource: URI.file('my://resource-basics.test') }, modified: { resource: URI.file('my://resource-basics.test') } }, part.activeGroup); assert.ok(resultingResolution); assert.notStrictEqual(typeof resultingResolution, 'number'); if (resultingResolution !== ResolvedStatus.ABORT && resultingResolution !== ResolvedStatus.NONE) { assert.strictEqual(resultingResolution.editor.typeId, 'workbench.editors.diffEditorInput'); resultingResolution.editor.dispose(); } else { assert.fail(); } // Remove diff registration registeredDiffEditor.dispose(); // Resolve a diff again, expected failure resultingResolution = await service.resolveEditor({ original: { resource: URI.file('my://resource-basics.test') }, modified: { resource: URI.file('my://resource-basics.test') } }, part.activeGroup); assert.ok(resultingResolution); assert.strictEqual(typeof resultingResolution, 'number'); if (resultingResolution !== ResolvedStatus.NONE) { assert.fail(); } registeredSingleEditor.dispose(); }); });
src/vs/workbench/services/editor/test/browser/editorResolverService.test.ts
0
https://github.com/microsoft/vscode/commit/6bad769697ec3e4ad65287d9345624328377fdd5
[ 0.00017848951392807066, 0.0001747385540511459, 0.00016671206685714424, 0.0001748960348777473, 0.000001951788362930529 ]
{ "id": 4, "code_window": [ " displayName: Generate SBOM (client)\n", " inputs:\n", " BuildDropPath: $(agent.builddirectory)/VSCode-win32-$(VSCODE_ARCH)\n", " PackageName: Visual Studio Code\n", "\n", " - publish: $(agent.builddirectory)/VSCode-win32-$(VSCODE_ARCH)/_manifest\n", " displayName: Publish SBOM (client)\n", " artifact: $(ARTIFACT_PREFIX)sbom_client_win32_$(VSCODE_ARCH)\n", "\n", " - task: AzureArtifacts.manifest-generator-task.manifest-generator-task.ManifestGeneratorTask@0\n", " displayName: Generate SBOM (server)\n", " inputs:\n", " BuildDropPath: $(agent.builddirectory)/vscode-server-win32-$(VSCODE_ARCH)\n", " PackageName: Visual Studio Code Server\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "build/azure-pipelines/win32/product-build-win32.yml", "type": "replace", "edit_start_line_idx": 314 }
{ "registrations": [ { "component": { "type": "git", "git": { "name": "marked", "repositoryUrl": "https://github.com/markedjs/marked", "commitHash": "7e2ef307846427650114591f9257b5545868e928" } }, "license": "MIT", "version": "4.1.0" } ], "version": 1 }
src/vs/base/common/marked/cgmanifest.json
0
https://github.com/microsoft/vscode/commit/6bad769697ec3e4ad65287d9345624328377fdd5
[ 0.000173801978235133, 0.0001731167867546901, 0.00017243159527424723, 0.0001731167867546901, 6.851914804428816e-7 ]
{ "id": 5, "code_window": [ " PackageName: Visual Studio Code Server\n", " condition: and(succeeded(), ne(variables['VSCODE_ARCH'], 'arm64'))\n", "\n", " - publish: $(agent.builddirectory)/vscode-server-win32-$(VSCODE_ARCH)/_manifest\n", " displayName: Publish SBOM (server)\n", " artifact: $(ARTIFACT_PREFIX)sbom_server_win32_$(VSCODE_ARCH)\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " - publish: $(agent.builddirectory)/VSCode-win32-$(VSCODE_ARCH)/_manifest\n", " displayName: Publish SBOM (client)\n", " artifact: $(ARTIFACT_PREFIX)sbom_client_win32_$(VSCODE_ARCH)\n", "\n" ], "file_path": "build/azure-pipelines/win32/product-build-win32.yml", "type": "add", "edit_start_line_idx": 325 }
parameters: - name: VSCODE_QUALITY type: string - name: VSCODE_CIBUILD type: boolean - name: VSCODE_RUN_UNIT_TESTS type: boolean - name: VSCODE_RUN_INTEGRATION_TESTS type: boolean - name: VSCODE_RUN_SMOKE_TESTS type: boolean steps: - ${{ if eq(parameters.VSCODE_QUALITY, 'oss') }}: - checkout: self fetchDepth: 1 retryCountOnTaskFailure: 3 - task: NodeTool@0 inputs: versionSpec: "16.x" - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - template: ../distro/download-distro.yml - task: AzureKeyVault@1 displayName: "Azure Key Vault: Get Secrets" inputs: azureSubscription: "vscode-builds-subscription" KeyVaultName: vscode-build-secrets SecretsFilter: "github-distro-mixin-password,macos-developer-certificate,macos-developer-certificate-key" - task: DownloadPipelineArtifact@2 inputs: artifact: Compilation path: $(Build.ArtifactStagingDirectory) displayName: Download compilation output - script: tar -xzf $(Build.ArtifactStagingDirectory)/compilation.tar.gz displayName: Extract compilation output - script: node build/setup-npm-registry.js $NPM_REGISTRY condition: and(succeeded(), ne(variables['NPM_REGISTRY'], 'none')) displayName: Setup NPM Registry - script: mkdir -p .build && node build/azure-pipelines/common/computeNodeModulesCacheKey.js darwin $VSCODE_ARCH > .build/yarnlockhash displayName: Prepare node_modules cache key - task: Cache@2 inputs: key: '"node_modules" | .build/yarnlockhash' path: .build/node_modules_cache cacheHitVar: NODE_MODULES_RESTORED displayName: Restore node_modules cache - script: tar -xzf .build/node_modules_cache/cache.tgz condition: and(succeeded(), eq(variables.NODE_MODULES_RESTORED, 'true')) displayName: Extract node_modules cache - script: | set -e npm config set registry "$NPM_REGISTRY" --location=project npm config set always-auth=true --location=project yarn config set registry "$NPM_REGISTRY" condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'), ne(variables['NPM_REGISTRY'], 'none')) displayName: Setup NPM & Yarn - task: npmAuthenticate@0 inputs: workingFile: .npmrc condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'), ne(variables['NPM_REGISTRY'], 'none')) displayName: Setup NPM Authentication - script: | set -e export npm_config_arch=$(VSCODE_ARCH) export npm_config_node_gyp=$(which node-gyp) for i in {1..5}; do # try 5 times yarn --frozen-lockfile --check-files && break if [ $i -eq 3 ]; then echo "Yarn failed too many times" >&2 exit 1 fi echo "Yarn failed $i, trying again..." done env: ELECTRON_SKIP_BINARY_DOWNLOAD: 1 PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1 GITHUB_TOKEN: "$(github-distro-mixin-password)" displayName: Install dependencies condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - script: node build/azure-pipelines/distro/mixin-npm condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) displayName: Mixin distro node modules - script: | set -e node build/azure-pipelines/common/listNodeModules.js .build/node_modules_list.txt mkdir -p .build/node_modules_cache tar -czf .build/node_modules_cache/cache.tgz --files-from .build/node_modules_list.txt condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) displayName: Create node_modules archive - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - script: node build/azure-pipelines/distro/mixin-quality displayName: Mixin distro quality - template: ../common/install-builtin-extensions.yml - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - script: | set -e yarn gulp vscode-darwin-$(VSCODE_ARCH)-min-ci echo "##vso[task.setvariable variable=BUILT_CLIENT]true" env: GITHUB_TOKEN: "$(github-distro-mixin-password)" displayName: Build client - script: | set -e yarn gulp vscode-reh-darwin-$(VSCODE_ARCH)-min-ci mv ../vscode-reh-darwin-$(VSCODE_ARCH) ../vscode-server-darwin-$(VSCODE_ARCH) # TODO@joaomoreno ARCHIVE_PATH=".build/darwin/server/vscode-server-darwin-$(VSCODE_ARCH).zip" mkdir -p $(dirname $ARCHIVE_PATH) (cd .. && zip -Xry $(Build.SourcesDirectory)/$ARCHIVE_PATH vscode-server-darwin-$(VSCODE_ARCH)) echo "##vso[task.setvariable variable=SERVER_PATH]$ARCHIVE_PATH" env: GITHUB_TOKEN: "$(github-distro-mixin-password)" displayName: Build server - script: | set -e yarn gulp vscode-reh-web-darwin-$(VSCODE_ARCH)-min-ci mv ../vscode-reh-web-darwin-$(VSCODE_ARCH) ../vscode-server-darwin-$(VSCODE_ARCH)-web # TODO@joaomoreno ARCHIVE_PATH=".build/darwin/server/vscode-server-darwin-$(VSCODE_ARCH)-web.zip" mkdir -p $(dirname $ARCHIVE_PATH) (cd .. && zip -Xry $(Build.SourcesDirectory)/$ARCHIVE_PATH vscode-server-darwin-$(VSCODE_ARCH)-web) echo "##vso[task.setvariable variable=WEB_PATH]$ARCHIVE_PATH" env: GITHUB_TOKEN: "$(github-distro-mixin-password)" displayName: Build server (web) - ${{ else }}: - script: yarn gulp transpile-client-swc transpile-extensions env: GITHUB_TOKEN: "$(github-distro-mixin-password)" displayName: Transpile - ${{ if or(eq(parameters.VSCODE_RUN_UNIT_TESTS, true), eq(parameters.VSCODE_RUN_INTEGRATION_TESTS, true), eq(parameters.VSCODE_RUN_SMOKE_TESTS, true)) }}: - template: product-build-darwin-test.yml parameters: VSCODE_QUALITY: ${{ parameters.VSCODE_QUALITY }} VSCODE_RUN_UNIT_TESTS: ${{ parameters.VSCODE_RUN_UNIT_TESTS }} VSCODE_RUN_INTEGRATION_TESTS: ${{ parameters.VSCODE_RUN_INTEGRATION_TESTS }} VSCODE_RUN_SMOKE_TESTS: ${{ parameters.VSCODE_RUN_SMOKE_TESTS }} - ${{ elseif and(ne(parameters.VSCODE_CIBUILD, true), ne(parameters.VSCODE_QUALITY, 'oss')) }}: - task: DownloadPipelineArtifact@2 inputs: artifact: unsigned_vscode_cli_darwin_$(VSCODE_ARCH)_cli patterns: "**" path: $(Build.ArtifactStagingDirectory)/cli displayName: Download VS Code CLI - script: | set -e APP_ROOT="$(Agent.BuildDirectory)/VSCode-darwin-$(VSCODE_ARCH)" APP_NAME="`ls $APP_ROOT | head -n 1`" APP_PATH="$APP_ROOT/$APP_NAME" ARCHIVE_NAME=$(ls "$(Build.ArtifactStagingDirectory)/cli" | head -n 1) unzip "$(Build.ArtifactStagingDirectory)/cli/$ARCHIVE_NAME" -d "$(Build.ArtifactStagingDirectory)/cli" CLI_APP_NAME=$(node -p "require(\"$APP_PATH/Contents/Resources/app/product.json\").tunnelApplicationName") APP_NAME=$(node -p "require(\"$APP_PATH/Contents/Resources/app/product.json\").applicationName") mv "$(Build.ArtifactStagingDirectory)/cli/$APP_NAME" "$APP_PATH/Contents/Resources/app/bin/$CLI_APP_NAME" chmod +x "$APP_PATH/Contents/Resources/app/bin/$CLI_APP_NAME" displayName: Make CLI executable # Setting hardened entitlements is a requirement for: # * Apple notarization # * Running tests on Big Sur (because Big Sur has additional security precautions) - script: | set -e security create-keychain -p pwd $(agent.tempdirectory)/buildagent.keychain security default-keychain -s $(agent.tempdirectory)/buildagent.keychain security unlock-keychain -p pwd $(agent.tempdirectory)/buildagent.keychain echo "$(macos-developer-certificate)" | base64 -D > $(agent.tempdirectory)/cert.p12 security import $(agent.tempdirectory)/cert.p12 -k $(agent.tempdirectory)/buildagent.keychain -P "$(macos-developer-certificate-key)" -T /usr/bin/codesign export CODESIGN_IDENTITY=$(security find-identity -v -p codesigning $(agent.tempdirectory)/buildagent.keychain | grep -oEi "([0-9A-F]{40})" | head -n 1) security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k pwd $(agent.tempdirectory)/buildagent.keychain DEBUG=electron-osx-sign* node build/darwin/sign.js $(agent.builddirectory) displayName: Set Hardened Entitlements - script: | set -e ARCHIVE_PATH=".build/darwin/client/VSCode-darwin-$(VSCODE_ARCH).zip" mkdir -p $(dirname $ARCHIVE_PATH) (cd ../VSCode-darwin-$(VSCODE_ARCH) && zip -Xry $(Build.SourcesDirectory)/$ARCHIVE_PATH *) echo "##vso[task.setvariable variable=CLIENT_PATH]$ARCHIVE_PATH" condition: and(succeededOrFailed(), eq(variables['BUILT_CLIENT'], 'true')) displayName: Package client - script: echo "##vso[task.setvariable variable=ARTIFACT_PREFIX]attempt$(System.JobAttempt)_" condition: and(succeededOrFailed(), notIn(variables['Agent.JobStatus'], 'Succeeded', 'SucceededWithIssues')) displayName: Generate artifact prefix - task: AzureArtifacts.manifest-generator-task.manifest-generator-task.ManifestGeneratorTask@0 displayName: Generate SBOM (client) inputs: BuildDropPath: $(agent.builddirectory)/VSCode-darwin-$(VSCODE_ARCH) PackageName: Visual Studio Code - publish: $(agent.builddirectory)/VSCode-darwin-$(VSCODE_ARCH)/_manifest displayName: Publish SBOM (client) artifact: $(ARTIFACT_PREFIX)sbom_client_darwin_$(VSCODE_ARCH)_sbom - task: AzureArtifacts.manifest-generator-task.manifest-generator-task.ManifestGeneratorTask@0 displayName: Generate SBOM (server) inputs: BuildDropPath: $(agent.builddirectory)/vscode-server-darwin-$(VSCODE_ARCH) PackageName: Visual Studio Code Server - publish: $(agent.builddirectory)/vscode-server-darwin-$(VSCODE_ARCH)/_manifest displayName: Publish SBOM (server) artifact: $(ARTIFACT_PREFIX)sbom_server_darwin_$(VSCODE_ARCH)_sbom - publish: $(CLIENT_PATH) artifact: $(ARTIFACT_PREFIX)unsigned_vscode_client_darwin_$(VSCODE_ARCH)_archive condition: and(succeededOrFailed(), ne(variables['CLIENT_PATH'], '')) displayName: Publish client archive - publish: $(SERVER_PATH) artifact: $(ARTIFACT_PREFIX)vscode_server_darwin_$(VSCODE_ARCH)_archive-unsigned condition: and(succeededOrFailed(), ne(variables['SERVER_PATH'], '')) displayName: Publish server archive - publish: $(WEB_PATH) artifact: $(ARTIFACT_PREFIX)vscode_web_darwin_$(VSCODE_ARCH)_archive-unsigned condition: and(succeededOrFailed(), ne(variables['WEB_PATH'], '')) displayName: Publish web server archive
build/azure-pipelines/darwin/product-build-darwin.yml
1
https://github.com/microsoft/vscode/commit/6bad769697ec3e4ad65287d9345624328377fdd5
[ 0.06889073550701141, 0.004472316708415747, 0.00016252844943664968, 0.0003094285202678293, 0.0134888906031847 ]
{ "id": 5, "code_window": [ " PackageName: Visual Studio Code Server\n", " condition: and(succeeded(), ne(variables['VSCODE_ARCH'], 'arm64'))\n", "\n", " - publish: $(agent.builddirectory)/vscode-server-win32-$(VSCODE_ARCH)/_manifest\n", " displayName: Publish SBOM (server)\n", " artifact: $(ARTIFACT_PREFIX)sbom_server_win32_$(VSCODE_ARCH)\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " - publish: $(agent.builddirectory)/VSCode-win32-$(VSCODE_ARCH)/_manifest\n", " displayName: Publish SBOM (client)\n", " artifact: $(ARTIFACT_PREFIX)sbom_client_win32_$(VSCODE_ARCH)\n", "\n" ], "file_path": "build/azure-pipelines/win32/product-build-win32.yml", "type": "add", "edit_start_line_idx": 325 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ declare module 'vscode' { // https://github.com/microsoft/vscode/issues/157734 export namespace workspace { /** * An event that is emitted when an edit session identity is about to be requested. */ export const onWillCreateEditSessionIdentity: Event<EditSessionIdentityWillCreateEvent>; /** * * @param scheme The URI scheme that this provider can provide edit session identities for. * @param provider A provider which can convert URIs for workspace folders of scheme @param scheme to * an edit session identifier which is stable across machines. This enables edit sessions to be resolved. */ export function registerEditSessionIdentityProvider(scheme: string, provider: EditSessionIdentityProvider): Disposable; } export interface EditSessionIdentityProvider { /** * * @param workspaceFolder The workspace folder to provide an edit session identity for. * @param token A cancellation token for the request. * @returns A string representing the edit session identity for the requested workspace folder. */ provideEditSessionIdentity(workspaceFolder: WorkspaceFolder, token: CancellationToken): ProviderResult<string>; /** * * @param identity1 An edit session identity. * @param identity2 A second edit session identity to compare to @param identity1. * @param token A cancellation token for the request. * @returns An {@link EditSessionIdentityMatch} representing the edit session identity match confidence for the provided identities. */ provideEditSessionIdentityMatch(identity1: string, identity2: string, token: CancellationToken): ProviderResult<EditSessionIdentityMatch>; } export enum EditSessionIdentityMatch { Complete = 100, Partial = 50, None = 0 } export interface EditSessionIdentityWillCreateEvent { /** * A cancellation token. */ readonly token: CancellationToken; /** * The workspace folder to create an edit session identity for. */ readonly workspaceFolder: WorkspaceFolder; /** * Allows to pause the event until the provided thenable resolves. * * *Note:* This function can only be called during event dispatch. * * @param thenable A thenable that delays saving. */ waitUntil(thenable: Thenable<any>): void; } }
src/vscode-dts/vscode.proposed.editSessionIdentityProvider.d.ts
0
https://github.com/microsoft/vscode/commit/6bad769697ec3e4ad65287d9345624328377fdd5
[ 0.0010155142517760396, 0.0002766436664387584, 0.00016839757154230028, 0.00017167298938147724, 0.0002792720915749669 ]
{ "id": 5, "code_window": [ " PackageName: Visual Studio Code Server\n", " condition: and(succeeded(), ne(variables['VSCODE_ARCH'], 'arm64'))\n", "\n", " - publish: $(agent.builddirectory)/vscode-server-win32-$(VSCODE_ARCH)/_manifest\n", " displayName: Publish SBOM (server)\n", " artifact: $(ARTIFACT_PREFIX)sbom_server_win32_$(VSCODE_ARCH)\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " - publish: $(agent.builddirectory)/VSCode-win32-$(VSCODE_ARCH)/_manifest\n", " displayName: Publish SBOM (client)\n", " artifact: $(ARTIFACT_PREFIX)sbom_client_win32_$(VSCODE_ARCH)\n", "\n" ], "file_path": "build/azure-pipelines/win32/product-build-win32.yml", "type": "add", "edit_start_line_idx": 325 }
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. # yarn lockfile v1
extensions/php/yarn.lock
0
https://github.com/microsoft/vscode/commit/6bad769697ec3e4ad65287d9345624328377fdd5
[ 0.00017118277901317924, 0.00017118277901317924, 0.00017118277901317924, 0.00017118277901317924, 0 ]
{ "id": 5, "code_window": [ " PackageName: Visual Studio Code Server\n", " condition: and(succeeded(), ne(variables['VSCODE_ARCH'], 'arm64'))\n", "\n", " - publish: $(agent.builddirectory)/vscode-server-win32-$(VSCODE_ARCH)/_manifest\n", " displayName: Publish SBOM (server)\n", " artifact: $(ARTIFACT_PREFIX)sbom_server_win32_$(VSCODE_ARCH)\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " - publish: $(agent.builddirectory)/VSCode-win32-$(VSCODE_ARCH)/_manifest\n", " displayName: Publish SBOM (client)\n", " artifact: $(ARTIFACT_PREFIX)sbom_client_win32_$(VSCODE_ARCH)\n", "\n" ], "file_path": "build/azure-pipelines/win32/product-build-win32.yml", "type": "add", "edit_start_line_idx": 325 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ declare module 'vscode' { // https://github.com/microsoft/vscode/issues/180582 export namespace workspace { /** * * @param scheme The URI scheme that this provider can provide canonical URIs for. * A canonical URI represents the conversion of a resource's alias into a source of truth URI. * Multiple aliases may convert to the same source of truth URI. * @param provider A provider which can convert URIs of scheme @param scheme to * a canonical URI which is stable across machines. */ export function registerCanonicalUriProvider(scheme: string, provider: CanonicalUriProvider): Disposable; /** * * @param uri The URI to provide a canonical URI for. * @param token A cancellation token for the request. */ export function getCanonicalUri(uri: Uri, options: CanonicalUriRequestOptions, token: CancellationToken): ProviderResult<Uri>; } export interface CanonicalUriProvider { /** * * @param uri The URI to provide a canonical URI for. * @param options Options that the provider should honor in the URI it returns. * @param token A cancellation token for the request. * @returns The canonical URI for the requested URI or undefined if no canonical URI can be provided. */ provideCanonicalUri(uri: Uri, options: CanonicalUriRequestOptions, token: CancellationToken): ProviderResult<Uri>; } export interface CanonicalUriRequestOptions { /** * * The desired scheme of the canonical URI. */ targetScheme: string; } }
src/vscode-dts/vscode.proposed.canonicalUriProvider.d.ts
0
https://github.com/microsoft/vscode/commit/6bad769697ec3e4ad65287d9345624328377fdd5
[ 0.0001726675109239295, 0.00016930518904700875, 0.00016690244956407696, 0.00016902462812140584, 0.0000018926377833849983 ]
{ "id": 0, "code_window": [ "diff --git a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js\n", "index 5e83281c0..3c995f97c 100644\n", "--- a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js\n", "+++ b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js\n" ], "labels": [ "keep", "replace", "keep", "keep" ], "after_edit": [ "index 2f3ea31dc..4ad337e85 100644\n" ], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 1 }
diff --git a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js index 5e83281c0..3c995f97c 100644 --- a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js +++ b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js @@ -963,7 +963,7 @@ describe('<Autocomplete />', () => { fireEvent.keyDown(textbox, { key: 'Enter' }); expect(handleChange.callCount).to.equal(1); expect(handleChange.args[0][1]).to.equal('a'); - expect(consoleErrorMock.callCount()).to.equal(4); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(3); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: The `getOptionLabel` method of Autocomplete returned undefined instead of a string', ); @@ -993,7 +993,7 @@ describe('<Autocomplete />', () => { />, ); - expect(consoleWarnMock.callCount()).to.equal(4); // strict mode renders twice + expect(consoleWarnMock.callCount()).to.equal(2); expect(consoleWarnMock.messages()[0]).to.include( 'None of the options match with `"not a good value"`', ); @@ -1022,7 +1022,7 @@ describe('<Autocomplete />', () => { const options = getAllByRole('option').map((el) => el.textContent); expect(options).to.have.length(7); expect(options).to.deep.equal(['A', 'D', 'E', 'B', 'G', 'F', 'C']); - expect(consoleWarnMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleWarnMock.callCount()).to.equal(1); expect(consoleWarnMock.messages()[0]).to.include('returns duplicated headers'); }); }); diff --git a/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js b/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js index 5c9d0be26..7f0862466 100644 --- a/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js +++ b/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js @@ -135,7 +135,7 @@ describe('ThemeProvider', () => { <div /> </ThemeProvider>, ); - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include('However, no outer theme is present.'); }); @@ -148,7 +148,7 @@ describe('ThemeProvider', () => { , </ThemeProvider>, ); - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: You should return an object from your theme function', ); diff --git a/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js b/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js index ed0e37f21..49d8ea9b0 100644 --- a/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js +++ b/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js @@ -102,7 +102,7 @@ describe('<Breadcrumbs />', () => { ); expect(getAllByRole('listitem', { hidden: false })).to.have.length(4); expect(getByRole('list')).to.have.text('first/second/third/fourth'); - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: You have provided an invalid combination of props to the Breadcrumbs.\nitemsAfterCollapse={2} + itemsBeforeCollapse={2} >= maxItems={3}', ); diff --git a/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js b/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js index cea126a0d..1eaf80628 100644 --- a/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js +++ b/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js @@ -261,7 +261,7 @@ describe('<TextareaAutosize />', () => { }); forceUpdate(); - expect(consoleErrorMock.callCount()).to.equal(3); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include('Material-UI: Too many re-renders.'); }); }); diff --git a/packages/material-ui/src/internal/SwitchBase.test.js b/packages/material-ui/src/internal/SwitchBase.test.js index 41a38bc07..c9397fd13 100644 --- a/packages/material-ui/src/internal/SwitchBase.test.js +++ b/packages/material-ui/src/internal/SwitchBase.test.js @@ -373,7 +373,7 @@ describe('<SwitchBase />', () => { wrapper.setProps({ checked: true }); expect(consoleErrorMock.callCount()).to.equal(2); expect(consoleErrorMock.messages()[0]).to.include( - 'Warning: A component is changing an uncontrolled input of type checkbox to be controlled.', + 'Warning: A component is changing an uncontrolled input to be controlled.', ); expect(consoleErrorMock.messages()[1]).to.include( 'Material-UI: A component is changing the uncontrolled checked state of SwitchBase to be controlled.', @@ -392,7 +392,7 @@ describe('<SwitchBase />', () => { setProps({ checked: undefined }); expect(consoleErrorMock.callCount()).to.equal(2); expect(consoleErrorMock.messages()[0]).to.include( - 'Warning: A component is changing a controlled input of type checkbox to be uncontrolled.', + 'Warning: A component is changing a controlled input to be uncontrolled.', ); expect(consoleErrorMock.messages()[1]).to.include( 'Material-UI: A component is changing the controlled checked state of SwitchBase to be uncontrolled.', diff --git a/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js b/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js index 68b0a4a5c..e31152c44 100644 --- a/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js +++ b/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js @@ -284,14 +284,10 @@ describe('useMediaQuery', () => { } render(<MyComponent />); - // logs warning twice in StrictMode - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: The `query` argument provided is invalid', ); }); }); });
scripts/react-next.diff
1
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.08335281908512115, 0.0075711761601269245, 0.0001660506532061845, 0.0002838592336047441, 0.022863224148750305 ]
{ "id": 0, "code_window": [ "diff --git a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js\n", "index 5e83281c0..3c995f97c 100644\n", "--- a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js\n", "+++ b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js\n" ], "labels": [ "keep", "replace", "keep", "keep" ], "after_edit": [ "index 2f3ea31dc..4ad337e85 100644\n" ], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 1 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M15 18.5c-2.51 0-4.68-1.42-5.76-3.5H15v-2H8.58c-.05-.33-.08-.66-.08-1s.03-.67.08-1H15V9H9.24C10.32 6.92 12.5 5.5 15 5.5c1.61 0 3.09.59 4.23 1.57L21 5.3C19.41 3.87 17.3 3 15 3c-3.92 0-7.24 2.51-8.48 6H3v2h3.06c-.04.33-.06.66-.06 1 0 .34.02.67.06 1H3v2h3.52c1.24 3.49 4.56 6 8.48 6 2.31 0 4.41-.87 6-2.3l-1.78-1.77c-1.13.98-2.6 1.57-4.22 1.57z" /> , 'EuroSymbol');
packages/material-ui-icons/src/EuroSymbol.js
0
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.00016635682550258934, 0.00016635682550258934, 0.00016635682550258934, 0.00016635682550258934, 0 ]
{ "id": 0, "code_window": [ "diff --git a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js\n", "index 5e83281c0..3c995f97c 100644\n", "--- a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js\n", "+++ b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js\n" ], "labels": [ "keep", "replace", "keep", "keep" ], "after_edit": [ "index 2f3ea31dc..4ad337e85 100644\n" ], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 1 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M20 3H6c-1.1 0-2 .9-2 2v8c0 2.21 1.79 4 4 4h6c2.21 0 4-1.79 4-4v-3h2c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 5h-2V5h2v3zM3 21h16c.55 0 1-.45 1-1s-.45-1-1-1H3c-.55 0-1 .45-1 1s.45 1 1 1z" /> , 'LocalCafeRounded');
packages/material-ui-icons/src/LocalCafeRounded.js
0
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.00016968768613878638, 0.00016968768613878638, 0.00016968768613878638, 0.00016968768613878638, 0 ]
{ "id": 0, "code_window": [ "diff --git a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js\n", "index 5e83281c0..3c995f97c 100644\n", "--- a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js\n", "+++ b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js\n" ], "labels": [ "keep", "replace", "keep", "keep" ], "after_edit": [ "index 2f3ea31dc..4ad337e85 100644\n" ], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 1 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fillOpacity=".3" d="M15.5 14.5c0-2.8 2.2-5 5-5 .36 0 .71.04 1.05.11L23.64 7c-.45-.34-4.93-4-11.64-4C5.28 3 .81 6.66.36 7L12 21.5l3.5-4.36V14.5z" /><path d="M15.5 14.5c0-.23.04-.46.07-.68-.92-.43-2.14-.82-3.57-.82-3 0-5.1 1.7-5.3 1.9l5.3 6.6 3.5-4.36V14.5zM23 16v-1.5c0-1.4-1.1-2.5-2.5-2.5S18 13.1 18 14.5V16c-.5 0-1 .5-1 1v4c0 .5.5 1 1 1h5c.5 0 1-.5 1-1v-4c0-.5-.5-1-1-1zm-1 0h-3v-1.5c0-.8.7-1.5 1.5-1.5s1.5.7 1.5 1.5V16z" /></React.Fragment> , 'SignalWifi1BarLockTwoTone');
packages/material-ui-icons/legacy/SignalWifi1BarLockTwoTone.js
0
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.0002806390111800283, 0.0002806390111800283, 0.0002806390111800283, 0.0002806390111800283, 0 ]
{ "id": 1, "code_window": [ "--- a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js\n", "+++ b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js\n", "@@ -963,7 +963,7 @@ describe('<Autocomplete />', () => {\n", " fireEvent.keyDown(textbox, { key: 'Enter' });\n", " expect(handleChange.callCount).to.equal(1);\n", " expect(handleChange.args[0][1]).to.equal('a');\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "@@ -1018,7 +1018,7 @@ describe('<Autocomplete />', () => {\n" ], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 4 }
diff --git a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js index 5e83281c0..3c995f97c 100644 --- a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js +++ b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js @@ -963,7 +963,7 @@ describe('<Autocomplete />', () => { fireEvent.keyDown(textbox, { key: 'Enter' }); expect(handleChange.callCount).to.equal(1); expect(handleChange.args[0][1]).to.equal('a'); - expect(consoleErrorMock.callCount()).to.equal(4); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(3); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: The `getOptionLabel` method of Autocomplete returned undefined instead of a string', ); @@ -993,7 +993,7 @@ describe('<Autocomplete />', () => { />, ); - expect(consoleWarnMock.callCount()).to.equal(4); // strict mode renders twice + expect(consoleWarnMock.callCount()).to.equal(2); expect(consoleWarnMock.messages()[0]).to.include( 'None of the options match with `"not a good value"`', ); @@ -1022,7 +1022,7 @@ describe('<Autocomplete />', () => { const options = getAllByRole('option').map((el) => el.textContent); expect(options).to.have.length(7); expect(options).to.deep.equal(['A', 'D', 'E', 'B', 'G', 'F', 'C']); - expect(consoleWarnMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleWarnMock.callCount()).to.equal(1); expect(consoleWarnMock.messages()[0]).to.include('returns duplicated headers'); }); }); diff --git a/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js b/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js index 5c9d0be26..7f0862466 100644 --- a/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js +++ b/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js @@ -135,7 +135,7 @@ describe('ThemeProvider', () => { <div /> </ThemeProvider>, ); - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include('However, no outer theme is present.'); }); @@ -148,7 +148,7 @@ describe('ThemeProvider', () => { , </ThemeProvider>, ); - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: You should return an object from your theme function', ); diff --git a/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js b/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js index ed0e37f21..49d8ea9b0 100644 --- a/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js +++ b/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js @@ -102,7 +102,7 @@ describe('<Breadcrumbs />', () => { ); expect(getAllByRole('listitem', { hidden: false })).to.have.length(4); expect(getByRole('list')).to.have.text('first/second/third/fourth'); - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: You have provided an invalid combination of props to the Breadcrumbs.\nitemsAfterCollapse={2} + itemsBeforeCollapse={2} >= maxItems={3}', ); diff --git a/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js b/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js index cea126a0d..1eaf80628 100644 --- a/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js +++ b/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js @@ -261,7 +261,7 @@ describe('<TextareaAutosize />', () => { }); forceUpdate(); - expect(consoleErrorMock.callCount()).to.equal(3); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include('Material-UI: Too many re-renders.'); }); }); diff --git a/packages/material-ui/src/internal/SwitchBase.test.js b/packages/material-ui/src/internal/SwitchBase.test.js index 41a38bc07..c9397fd13 100644 --- a/packages/material-ui/src/internal/SwitchBase.test.js +++ b/packages/material-ui/src/internal/SwitchBase.test.js @@ -373,7 +373,7 @@ describe('<SwitchBase />', () => { wrapper.setProps({ checked: true }); expect(consoleErrorMock.callCount()).to.equal(2); expect(consoleErrorMock.messages()[0]).to.include( - 'Warning: A component is changing an uncontrolled input of type checkbox to be controlled.', + 'Warning: A component is changing an uncontrolled input to be controlled.', ); expect(consoleErrorMock.messages()[1]).to.include( 'Material-UI: A component is changing the uncontrolled checked state of SwitchBase to be controlled.', @@ -392,7 +392,7 @@ describe('<SwitchBase />', () => { setProps({ checked: undefined }); expect(consoleErrorMock.callCount()).to.equal(2); expect(consoleErrorMock.messages()[0]).to.include( - 'Warning: A component is changing a controlled input of type checkbox to be uncontrolled.', + 'Warning: A component is changing a controlled input to be uncontrolled.', ); expect(consoleErrorMock.messages()[1]).to.include( 'Material-UI: A component is changing the controlled checked state of SwitchBase to be uncontrolled.', diff --git a/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js b/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js index 68b0a4a5c..e31152c44 100644 --- a/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js +++ b/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js @@ -284,14 +284,10 @@ describe('useMediaQuery', () => { } render(<MyComponent />); - // logs warning twice in StrictMode - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: The `query` argument provided is invalid', ); }); }); });
scripts/react-next.diff
1
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.9094310998916626, 0.07597969472408295, 0.00016354405670426786, 0.00017359906632918864, 0.2512950599193573 ]
{ "id": 1, "code_window": [ "--- a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js\n", "+++ b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js\n", "@@ -963,7 +963,7 @@ describe('<Autocomplete />', () => {\n", " fireEvent.keyDown(textbox, { key: 'Enter' });\n", " expect(handleChange.callCount).to.equal(1);\n", " expect(handleChange.args[0][1]).to.equal('a');\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "@@ -1018,7 +1018,7 @@ describe('<Autocomplete />', () => {\n" ], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 4 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M12 6c2.62 0 4.88 1.86 5.39 4.43l.3 1.5 1.53.11c1.56.1 2.78 1.41 2.78 2.96 0 1.65-1.35 3-3 3H6c-2.21 0-4-1.79-4-4 0-2.05 1.53-3.76 3.56-3.97l1.07-.11.5-.95C8.08 7.14 9.94 6 12 6m0-2C9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96C18.67 6.59 15.64 4 12 4z" /> , 'CloudOutlined');
packages/material-ui-icons/src/CloudOutlined.js
0
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.00017297120939474553, 0.00017297120939474553, 0.00017297120939474553, 0.00017297120939474553, 0 ]
{ "id": 1, "code_window": [ "--- a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js\n", "+++ b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js\n", "@@ -963,7 +963,7 @@ describe('<Autocomplete />', () => {\n", " fireEvent.keyDown(textbox, { key: 'Enter' });\n", " expect(handleChange.callCount).to.equal(1);\n", " expect(handleChange.args[0][1]).to.equal('a');\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "@@ -1018,7 +1018,7 @@ describe('<Autocomplete />', () => {\n" ], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 4 }
--- filename: /packages/material-ui/src/OutlinedInput/OutlinedInput.js --- <!--- This documentation is automatically generated, do not try to edit it. --> # OutlinedInput API <p class="description">The API documentation of the OutlinedInput React component. Learn more about the props and the CSS customization points.</p> ## Import ```js import OutlinedInput from '@material-ui/core/OutlinedInput'; // or import { OutlinedInput } from '@material-ui/core'; ``` You can learn more about the difference by [reading this guide](/guides/minimizing-bundle-size/). ## Component name The `MuiOutlinedInput` name can be used for providing [default props](/customization/globals/#default-props) or [style overrides](/customization/globals/#css) at the theme level. ## Props | Name | Type | Default | Description | |:-----|:-----|:--------|:------------| | <span class="prop-name">autoComplete</span> | <span class="prop-type">string</span> | | This prop helps users to fill forms faster, especially on mobile devices. The name can be confusing, as it's more like an autofill. You can learn more about it [following the specification](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill). | | <span class="prop-name">autoFocus</span> | <span class="prop-type">bool</span> | | If `true`, the `input` element will be focused during the first mount. | | <span class="prop-name">classes</span> | <span class="prop-type">object</span> | | Override or extend the styles applied to the component. See [CSS API](#css) below for more details. | | <span class="prop-name">color</span> | <span class="prop-type">'primary'<br>&#124;&nbsp;'secondary'</span> | | The color of the component. It supports those theme colors that make sense for this component. | | <span class="prop-name">defaultValue</span> | <span class="prop-type">any</span> | | The default `input` element value. Use when the component is not controlled. | | <span class="prop-name">disabled</span> | <span class="prop-type">bool</span> | | If `true`, the `input` element will be disabled. | | <span class="prop-name">endAdornment</span> | <span class="prop-type">node</span> | | End `InputAdornment` for this component. | | <span class="prop-name">error</span> | <span class="prop-type">bool</span> | | If `true`, the input will indicate an error. This is normally obtained via context from FormControl. | | <span class="prop-name">fullWidth</span> | <span class="prop-type">bool</span> | <span class="prop-default">false</span> | If `true`, the input will take up the full width of its container. | | <span class="prop-name">id</span> | <span class="prop-type">string</span> | | The id of the `input` element. | | <span class="prop-name">inputComponent</span> | <span class="prop-type">elementType</span> | <span class="prop-default">'input'</span> | The component used for the `input` element. Either a string to use a HTML element or a component. | | <span class="prop-name">inputProps</span> | <span class="prop-type">object</span> | | [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element. | | <span class="prop-name">inputRef</span> | <span class="prop-type">ref</span> | | Pass a ref to the `input` element. | | <span class="prop-name">label</span> | <span class="prop-type">node</span> | | The label of the input. It is only used for layout. The actual labelling is handled by `InputLabel`. If specified `labelWidth` is ignored. | | <span class="prop-name">labelWidth</span> | <span class="prop-type">number</span> | <span class="prop-default">0</span> | The width of the label. Is ignored if `label` is provided. Prefer `label` if the input label appears with a strike through. | | <span class="prop-name">margin</span> | <span class="prop-type">'dense'<br>&#124;&nbsp;'none'</span> | | If `dense`, will adjust vertical spacing. This is normally obtained via context from FormControl. | | <span class="prop-name">multiline</span> | <span class="prop-type">bool</span> | <span class="prop-default">false</span> | If `true`, a textarea element will be rendered. | | <span class="prop-name">name</span> | <span class="prop-type">string</span> | | Name attribute of the `input` element. | | <span class="prop-name">notched</span> | <span class="prop-type">bool</span> | | If `true`, the outline is notched to accommodate the label. | | <span class="prop-name">onChange</span> | <span class="prop-type">func</span> | | Callback fired when the value is changed.<br><br>**Signature:**<br>`function(event: object) => void`<br>*event:* The event source of the callback. You can pull out the new value by accessing `event.target.value` (string). | | <span class="prop-name">placeholder</span> | <span class="prop-type">string</span> | | The short hint displayed in the input before the user enters a value. | | <span class="prop-name">readOnly</span> | <span class="prop-type">bool</span> | | It prevents the user from changing the value of the field (not from interacting with the field). | | <span class="prop-name">required</span> | <span class="prop-type">bool</span> | | If `true`, the `input` element will be required. | | <span class="prop-name">rows</span> | <span class="prop-type">number<br>&#124;&nbsp;string</span> | | Number of rows to display when multiline option is set to true. | | <span class="prop-name">rowsMax</span> | <span class="prop-type">number<br>&#124;&nbsp;string</span> | | Maximum number of rows to display when multiline option is set to true. | | <span class="prop-name">startAdornment</span> | <span class="prop-type">node</span> | | Start `InputAdornment` for this component. | | <span class="prop-name">type</span> | <span class="prop-type">string</span> | <span class="prop-default">'text'</span> | Type of the `input` element. It should be [a valid HTML5 input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types). | | <span class="prop-name">value</span> | <span class="prop-type">any</span> | | The value of the `input` element, required for a controlled component. | The `ref` is forwarded to the root element. Any other props supplied will be provided to the root element ([InputBase](/api/input-base/)). ## CSS | Rule name | Global class | Description | |:-----|:-------------|:------------| | <span class="prop-name">root</span> | <span class="prop-name">.MuiOutlinedInput-root</span> | Styles applied to the root element. | <span class="prop-name">colorSecondary</span> | <span class="prop-name">.MuiOutlinedInput-colorSecondary</span> | Styles applied to the root element if the color is secondary. | <span class="prop-name">focused</span> | <span class="prop-name">.Mui-focused</span> | Styles applied to the root element if the component is focused. | <span class="prop-name">disabled</span> | <span class="prop-name">.Mui-disabled</span> | Styles applied to the root element if `disabled={true}`. | <span class="prop-name">adornedStart</span> | <span class="prop-name">.MuiOutlinedInput-adornedStart</span> | Styles applied to the root element if `startAdornment` is provided. | <span class="prop-name">adornedEnd</span> | <span class="prop-name">.MuiOutlinedInput-adornedEnd</span> | Styles applied to the root element if `endAdornment` is provided. | <span class="prop-name">error</span> | <span class="prop-name">.Mui-error</span> | Pseudo-class applied to the root element if `error={true}`. | <span class="prop-name">marginDense</span> | <span class="prop-name">.MuiOutlinedInput-marginDense</span> | Styles applied to the `input` element if `margin="dense"`. | <span class="prop-name">multiline</span> | <span class="prop-name">.MuiOutlinedInput-multiline</span> | Styles applied to the root element if `multiline={true}`. | <span class="prop-name">notchedOutline</span> | <span class="prop-name">.MuiOutlinedInput-notchedOutline</span> | Styles applied to the `NotchedOutline` element. | <span class="prop-name">input</span> | <span class="prop-name">.MuiOutlinedInput-input</span> | Styles applied to the `input` element. | <span class="prop-name">inputMarginDense</span> | <span class="prop-name">.MuiOutlinedInput-inputMarginDense</span> | Styles applied to the `input` element if `margin="dense"`. | <span class="prop-name">inputMultiline</span> | <span class="prop-name">.MuiOutlinedInput-inputMultiline</span> | Styles applied to the `input` element if `multiline={true}`. | <span class="prop-name">inputAdornedStart</span> | <span class="prop-name">.MuiOutlinedInput-inputAdornedStart</span> | Styles applied to the `input` element if `startAdornment` is provided. | <span class="prop-name">inputAdornedEnd</span> | <span class="prop-name">.MuiOutlinedInput-inputAdornedEnd</span> | Styles applied to the `input` element if `endAdornment` is provided. You can override the style of the component thanks to one of these customization points: - With a rule name of the [`classes` object prop](/customization/components/#overriding-styles-with-classes). - With a [global class name](/customization/components/#overriding-styles-with-global-class-names). - With a theme and an [`overrides` property](/customization/globals/#css). If that's not sufficient, you can check the [implementation of the component](https://github.com/mui-org/material-ui/blob/master/packages/material-ui/src/OutlinedInput/OutlinedInput.js) for more detail. ## Inheritance The props of the [InputBase](/api/input-base/) component are also available. You can take advantage of this behavior to [target nested components](/guides/api/#spread). ## Demos - [Text Fields](/components/text-fields/)
docs/pages/api-docs/outlined-input.md
0
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.00017278791347052902, 0.00016652596241328865, 0.00016123555542435497, 0.00016561627853661776, 0.000003497121497275657 ]
{ "id": 1, "code_window": [ "--- a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js\n", "+++ b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js\n", "@@ -963,7 +963,7 @@ describe('<Autocomplete />', () => {\n", " fireEvent.keyDown(textbox, { key: 'Enter' });\n", " expect(handleChange.callCount).to.equal(1);\n", " expect(handleChange.args[0][1]).to.equal('a');\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "@@ -1018,7 +1018,7 @@ describe('<Autocomplete />', () => {\n" ], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 4 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M19 4H5c-1.11 0-2 .9-2 2v12c0 1.1.89 2 2 2h4v-2H5V8h14v10h-4v2h4c1.1 0 2-.9 2-2V6c0-1.1-.89-2-2-2zm-7 6l-4 4h3v6h2v-6h3l-4-4z" /> , 'OpenInBrowser');
packages/material-ui-icons/src/OpenInBrowser.js
0
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.00017512179329060018, 0.00017512179329060018, 0.00017512179329060018, 0.00017512179329060018, 0 ]
{ "id": 2, "code_window": [ " expect(consoleErrorMock.messages()[0]).to.include(\n", " 'Material-UI: The `getOptionLabel` method of Autocomplete returned undefined instead of a string',\n", " );\n", "@@ -993,7 +993,7 @@ describe('<Autocomplete />', () => {\n", " />,\n", " );\n", " \n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "@@ -1070,7 +1070,7 @@ describe('<Autocomplete />', () => {\n" ], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 13 }
diff --git a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js index 5e83281c0..3c995f97c 100644 --- a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js +++ b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js @@ -963,7 +963,7 @@ describe('<Autocomplete />', () => { fireEvent.keyDown(textbox, { key: 'Enter' }); expect(handleChange.callCount).to.equal(1); expect(handleChange.args[0][1]).to.equal('a'); - expect(consoleErrorMock.callCount()).to.equal(4); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(3); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: The `getOptionLabel` method of Autocomplete returned undefined instead of a string', ); @@ -993,7 +993,7 @@ describe('<Autocomplete />', () => { />, ); - expect(consoleWarnMock.callCount()).to.equal(4); // strict mode renders twice + expect(consoleWarnMock.callCount()).to.equal(2); expect(consoleWarnMock.messages()[0]).to.include( 'None of the options match with `"not a good value"`', ); @@ -1022,7 +1022,7 @@ describe('<Autocomplete />', () => { const options = getAllByRole('option').map((el) => el.textContent); expect(options).to.have.length(7); expect(options).to.deep.equal(['A', 'D', 'E', 'B', 'G', 'F', 'C']); - expect(consoleWarnMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleWarnMock.callCount()).to.equal(1); expect(consoleWarnMock.messages()[0]).to.include('returns duplicated headers'); }); }); diff --git a/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js b/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js index 5c9d0be26..7f0862466 100644 --- a/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js +++ b/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js @@ -135,7 +135,7 @@ describe('ThemeProvider', () => { <div /> </ThemeProvider>, ); - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include('However, no outer theme is present.'); }); @@ -148,7 +148,7 @@ describe('ThemeProvider', () => { , </ThemeProvider>, ); - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: You should return an object from your theme function', ); diff --git a/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js b/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js index ed0e37f21..49d8ea9b0 100644 --- a/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js +++ b/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js @@ -102,7 +102,7 @@ describe('<Breadcrumbs />', () => { ); expect(getAllByRole('listitem', { hidden: false })).to.have.length(4); expect(getByRole('list')).to.have.text('first/second/third/fourth'); - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: You have provided an invalid combination of props to the Breadcrumbs.\nitemsAfterCollapse={2} + itemsBeforeCollapse={2} >= maxItems={3}', ); diff --git a/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js b/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js index cea126a0d..1eaf80628 100644 --- a/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js +++ b/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js @@ -261,7 +261,7 @@ describe('<TextareaAutosize />', () => { }); forceUpdate(); - expect(consoleErrorMock.callCount()).to.equal(3); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include('Material-UI: Too many re-renders.'); }); }); diff --git a/packages/material-ui/src/internal/SwitchBase.test.js b/packages/material-ui/src/internal/SwitchBase.test.js index 41a38bc07..c9397fd13 100644 --- a/packages/material-ui/src/internal/SwitchBase.test.js +++ b/packages/material-ui/src/internal/SwitchBase.test.js @@ -373,7 +373,7 @@ describe('<SwitchBase />', () => { wrapper.setProps({ checked: true }); expect(consoleErrorMock.callCount()).to.equal(2); expect(consoleErrorMock.messages()[0]).to.include( - 'Warning: A component is changing an uncontrolled input of type checkbox to be controlled.', + 'Warning: A component is changing an uncontrolled input to be controlled.', ); expect(consoleErrorMock.messages()[1]).to.include( 'Material-UI: A component is changing the uncontrolled checked state of SwitchBase to be controlled.', @@ -392,7 +392,7 @@ describe('<SwitchBase />', () => { setProps({ checked: undefined }); expect(consoleErrorMock.callCount()).to.equal(2); expect(consoleErrorMock.messages()[0]).to.include( - 'Warning: A component is changing a controlled input of type checkbox to be uncontrolled.', + 'Warning: A component is changing a controlled input to be uncontrolled.', ); expect(consoleErrorMock.messages()[1]).to.include( 'Material-UI: A component is changing the controlled checked state of SwitchBase to be uncontrolled.', diff --git a/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js b/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js index 68b0a4a5c..e31152c44 100644 --- a/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js +++ b/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js @@ -284,14 +284,10 @@ describe('useMediaQuery', () => { } render(<MyComponent />); - // logs warning twice in StrictMode - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: The `query` argument provided is invalid', ); }); }); });
scripts/react-next.diff
1
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.9482651948928833, 0.07954812794923782, 0.00019316306861583143, 0.0003547751111909747, 0.2619284689426422 ]
{ "id": 2, "code_window": [ " expect(consoleErrorMock.messages()[0]).to.include(\n", " 'Material-UI: The `getOptionLabel` method of Autocomplete returned undefined instead of a string',\n", " );\n", "@@ -993,7 +993,7 @@ describe('<Autocomplete />', () => {\n", " />,\n", " );\n", " \n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "@@ -1070,7 +1070,7 @@ describe('<Autocomplete />', () => {\n" ], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 13 }
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fillOpacity=".3" d="M15.5 14.5c0-2.8 2.2-5 5-5 .36 0 .71.04 1.05.11L23.64 7c-.45-.34-4.93-4-11.64-4C5.28 3 .81 6.66.36 7L12 21.5l3.5-4.36V14.5z" /><path d="M15.5 14.5c0-1.34.51-2.53 1.34-3.42C15.62 10.51 13.98 10 12 10c-4.1 0-6.8 2.2-7.2 2.5l7.2 9 3.5-4.38V14.5zM23 16v-1.5c0-1.4-1.1-2.5-2.5-2.5S18 13.1 18 14.5V16c-.5 0-1 .5-1 1v4c0 .5.5 1 1 1h5c.5 0 1-.5 1-1v-4c0-.5-.5-1-1-1zm-1 0h-3v-1.5c0-.8.7-1.5 1.5-1.5s1.5.7 1.5 1.5V16z" /></React.Fragment> , 'SignalWifi2BarLockOutlined');
packages/material-ui-icons/src/SignalWifi2BarLockOutlined.js
0
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.0001654798979870975, 0.0001654798979870975, 0.0001654798979870975, 0.0001654798979870975, 0 ]
{ "id": 2, "code_window": [ " expect(consoleErrorMock.messages()[0]).to.include(\n", " 'Material-UI: The `getOptionLabel` method of Autocomplete returned undefined instead of a string',\n", " );\n", "@@ -993,7 +993,7 @@ describe('<Autocomplete />', () => {\n", " />,\n", " );\n", " \n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "@@ -1070,7 +1070,7 @@ describe('<Autocomplete />', () => {\n" ], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 13 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zM8.75 13.68c-.13.43-.62.63-1.02.45a.749.749 0 01-.4-.9c.12-.41.18-.83.17-1.24-.01-.41-.06-.8-.17-1.18-.1-.36.06-.75.4-.9.42-.19.91.04 1.04.49.15.51.22 1.03.23 1.57 0 .56-.08 1.14-.25 1.71zm3.14 1.59c-.17.41-.67.57-1.06.35-.33-.19-.46-.59-.32-.94.33-.77.49-1.63.49-2.56 0-.96-.18-1.89-.53-2.78-.14-.36.02-.76.36-.94.39-.2.87-.02 1.03.39.42 1.06.63 2.18.63 3.33.02 1.13-.19 2.19-.6 3.15zM15 16.6c-.17.4-.64.58-1.02.39-.35-.17-.52-.59-.37-.95.59-1.39.89-2.75.89-4.06 0-1.31-.3-2.65-.88-4.01-.16-.36.01-.78.36-.95.39-.2.85-.02 1.02.38.66 1.54 1 3.08 1 4.58s-.34 3.06-1 4.62z" /> , 'ContactlessRounded');
packages/material-ui-icons/src/ContactlessRounded.js
0
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.00023727283405605704, 0.00023727283405605704, 0.00023727283405605704, 0.00023727283405605704, 0 ]
{ "id": 2, "code_window": [ " expect(consoleErrorMock.messages()[0]).to.include(\n", " 'Material-UI: The `getOptionLabel` method of Autocomplete returned undefined instead of a string',\n", " );\n", "@@ -993,7 +993,7 @@ describe('<Autocomplete />', () => {\n", " />,\n", " );\n", " \n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "@@ -1070,7 +1070,7 @@ describe('<Autocomplete />', () => {\n" ], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 13 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M21.79 18l2 2H24v-2h-2.21zM1.11 2.98l1.55 1.56c-.41.37-.66.89-.66 1.48V16c0 1.1.9 2 2.01 2H0v2h18.13l2.71 2.71 1.41-1.41L2.52 1.57 1.11 2.98zM4 6.02h.13l4.95 4.93C7.94 12.07 7.31 13.52 7 15c.96-1.29 2.13-2.08 3.67-2.46l3.46 3.48H4v-10zm16 0v10.19l1.3 1.3c.42-.37.7-.89.7-1.49v-10c0-1.11-.9-2-2-2H7.8l2 2H20zm-7.07 3.13l2.79 2.78 1.28-1.2L13 7v2.13l-.07.02z" /> , 'StopScreenShareOutlined');
packages/material-ui-icons/src/StopScreenShareOutlined.js
0
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.00017244556511286646, 0.00017244556511286646, 0.00017244556511286646, 0.00017244556511286646, 0 ]
{ "id": 3, "code_window": [ "+ expect(consoleWarnMock.callCount()).to.equal(2);\n", " expect(consoleWarnMock.messages()[0]).to.include(\n", " 'None of the options match with `\"not a good value\"`',\n", " );\n", "@@ -1022,7 +1022,7 @@ describe('<Autocomplete />', () => {\n", " const options = getAllByRole('option').map((el) => el.textContent);\n", " expect(options).to.have.length(7);\n", " expect(options).to.deep.equal(['A', 'D', 'E', 'B', 'G', 'F', 'C']);\n", "- expect(consoleWarnMock.callCount()).to.equal(2); // strict mode renders twice\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "@@ -1099,7 +1099,7 @@ describe('<Autocomplete />', () => {\n" ], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 22 }
diff --git a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js index 5e83281c0..3c995f97c 100644 --- a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js +++ b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js @@ -963,7 +963,7 @@ describe('<Autocomplete />', () => { fireEvent.keyDown(textbox, { key: 'Enter' }); expect(handleChange.callCount).to.equal(1); expect(handleChange.args[0][1]).to.equal('a'); - expect(consoleErrorMock.callCount()).to.equal(4); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(3); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: The `getOptionLabel` method of Autocomplete returned undefined instead of a string', ); @@ -993,7 +993,7 @@ describe('<Autocomplete />', () => { />, ); - expect(consoleWarnMock.callCount()).to.equal(4); // strict mode renders twice + expect(consoleWarnMock.callCount()).to.equal(2); expect(consoleWarnMock.messages()[0]).to.include( 'None of the options match with `"not a good value"`', ); @@ -1022,7 +1022,7 @@ describe('<Autocomplete />', () => { const options = getAllByRole('option').map((el) => el.textContent); expect(options).to.have.length(7); expect(options).to.deep.equal(['A', 'D', 'E', 'B', 'G', 'F', 'C']); - expect(consoleWarnMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleWarnMock.callCount()).to.equal(1); expect(consoleWarnMock.messages()[0]).to.include('returns duplicated headers'); }); }); diff --git a/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js b/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js index 5c9d0be26..7f0862466 100644 --- a/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js +++ b/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js @@ -135,7 +135,7 @@ describe('ThemeProvider', () => { <div /> </ThemeProvider>, ); - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include('However, no outer theme is present.'); }); @@ -148,7 +148,7 @@ describe('ThemeProvider', () => { , </ThemeProvider>, ); - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: You should return an object from your theme function', ); diff --git a/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js b/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js index ed0e37f21..49d8ea9b0 100644 --- a/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js +++ b/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js @@ -102,7 +102,7 @@ describe('<Breadcrumbs />', () => { ); expect(getAllByRole('listitem', { hidden: false })).to.have.length(4); expect(getByRole('list')).to.have.text('first/second/third/fourth'); - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: You have provided an invalid combination of props to the Breadcrumbs.\nitemsAfterCollapse={2} + itemsBeforeCollapse={2} >= maxItems={3}', ); diff --git a/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js b/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js index cea126a0d..1eaf80628 100644 --- a/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js +++ b/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js @@ -261,7 +261,7 @@ describe('<TextareaAutosize />', () => { }); forceUpdate(); - expect(consoleErrorMock.callCount()).to.equal(3); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include('Material-UI: Too many re-renders.'); }); }); diff --git a/packages/material-ui/src/internal/SwitchBase.test.js b/packages/material-ui/src/internal/SwitchBase.test.js index 41a38bc07..c9397fd13 100644 --- a/packages/material-ui/src/internal/SwitchBase.test.js +++ b/packages/material-ui/src/internal/SwitchBase.test.js @@ -373,7 +373,7 @@ describe('<SwitchBase />', () => { wrapper.setProps({ checked: true }); expect(consoleErrorMock.callCount()).to.equal(2); expect(consoleErrorMock.messages()[0]).to.include( - 'Warning: A component is changing an uncontrolled input of type checkbox to be controlled.', + 'Warning: A component is changing an uncontrolled input to be controlled.', ); expect(consoleErrorMock.messages()[1]).to.include( 'Material-UI: A component is changing the uncontrolled checked state of SwitchBase to be controlled.', @@ -392,7 +392,7 @@ describe('<SwitchBase />', () => { setProps({ checked: undefined }); expect(consoleErrorMock.callCount()).to.equal(2); expect(consoleErrorMock.messages()[0]).to.include( - 'Warning: A component is changing a controlled input of type checkbox to be uncontrolled.', + 'Warning: A component is changing a controlled input to be uncontrolled.', ); expect(consoleErrorMock.messages()[1]).to.include( 'Material-UI: A component is changing the controlled checked state of SwitchBase to be uncontrolled.', diff --git a/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js b/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js index 68b0a4a5c..e31152c44 100644 --- a/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js +++ b/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js @@ -284,14 +284,10 @@ describe('useMediaQuery', () => { } render(<MyComponent />); - // logs warning twice in StrictMode - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: The `query` argument provided is invalid', ); }); }); });
scripts/react-next.diff
1
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.9982514977455139, 0.08677206188440323, 0.0001624537690076977, 0.00020511809270828962, 0.2749263048171997 ]
{ "id": 3, "code_window": [ "+ expect(consoleWarnMock.callCount()).to.equal(2);\n", " expect(consoleWarnMock.messages()[0]).to.include(\n", " 'None of the options match with `\"not a good value\"`',\n", " );\n", "@@ -1022,7 +1022,7 @@ describe('<Autocomplete />', () => {\n", " const options = getAllByRole('option').map((el) => el.textContent);\n", " expect(options).to.have.length(7);\n", " expect(options).to.deep.equal(['A', 'D', 'E', 'B', 'G', 'F', 'C']);\n", "- expect(consoleWarnMock.callCount()).to.equal(2); // strict mode renders twice\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "@@ -1099,7 +1099,7 @@ describe('<Autocomplete />', () => {\n" ], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 22 }
import memoize from './memoize'; import { readFileSync } from 'fs'; import { parseSync } from '@babel/core'; import traverse from '@babel/traverse'; const getJSExports = memoize((file) => { const result = new Set(); const ast = parseSync(readFileSync(file, 'utf8'), { filename: file, }); traverse(ast, { ExportSpecifier: ({ node: { exported } }) => { result.add(exported.name); }, }); return result; }); export default getJSExports;
packages/material-ui-codemod/src/util/getJSExports.js
0
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.00021848775213584304, 0.00018938940775115043, 0.00017420414951629937, 0.00017547632160130888, 0.0000205821907002246 ]
{ "id": 3, "code_window": [ "+ expect(consoleWarnMock.callCount()).to.equal(2);\n", " expect(consoleWarnMock.messages()[0]).to.include(\n", " 'None of the options match with `\"not a good value\"`',\n", " );\n", "@@ -1022,7 +1022,7 @@ describe('<Autocomplete />', () => {\n", " const options = getAllByRole('option').map((el) => el.textContent);\n", " expect(options).to.have.length(7);\n", " expect(options).to.deep.equal(['A', 'D', 'E', 'B', 'G', 'F', 'C']);\n", "- expect(consoleWarnMock.callCount()).to.equal(2); // strict mode renders twice\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "@@ -1099,7 +1099,7 @@ describe('<Autocomplete />', () => {\n" ], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 22 }
import * as React from 'react'; import { getClasses } from '@material-ui/core/test-utils'; import createMount from 'test/utils/createMount'; import describeConformance from '@material-ui/core/test-utils/describeConformance'; import TimelineConnector from './TimelineConnector'; describe('<TimelineConnector />', () => { const mount = createMount(); let classes; before(() => { classes = getClasses(<TimelineConnector />); }); describeConformance(<TimelineConnector />, () => ({ classes, inheritComponent: 'span', mount, refInstanceof: window.HTMLSpanElement, skip: ['componentProp'], })); });
packages/material-ui-lab/src/TimelineConnector/TimelineConnector.test.js
0
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.00017663258768152446, 0.00017078399832826108, 0.0001672549988143146, 0.00016846437938511372, 0.000004164951860730071 ]
{ "id": 3, "code_window": [ "+ expect(consoleWarnMock.callCount()).to.equal(2);\n", " expect(consoleWarnMock.messages()[0]).to.include(\n", " 'None of the options match with `\"not a good value\"`',\n", " );\n", "@@ -1022,7 +1022,7 @@ describe('<Autocomplete />', () => {\n", " const options = getAllByRole('option').map((el) => el.textContent);\n", " expect(options).to.have.length(7);\n", " expect(options).to.deep.equal(['A', 'D', 'E', 'B', 'G', 'F', 'C']);\n", "- expect(consoleWarnMock.callCount()).to.equal(2); // strict mode renders twice\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "@@ -1099,7 +1099,7 @@ describe('<Autocomplete />', () => {\n" ], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 22 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M5 2c0-.55-.45-1-1-1s-1 .45-1 1v4H1v10c0 1.3.84 2.4 2 2.82V23h2v-4.18C6.16 18.4 7 17.3 7 16V6H5V2zM4 17c-.55 0-1-.45-1-1v-2h2v2c0 .55-.45 1-1 1zm-1-5V8h2v4H3zM13 2c0-.55-.45-1-1-1s-1 .45-1 1v4H9v10c0 1.3.84 2.4 2 2.82V23h2v-4.18c1.16-.42 2-1.52 2-2.82V6h-2V2zm-1 15c-.55 0-1-.45-1-1v-2h2v2c0 .55-.45 1-1 1zm-1-5V8h2v4h-2zm10-6V2c0-.55-.45-1-1-1s-1 .45-1 1v4h-2v10c0 1.3.84 2.4 2 2.82V23h2v-4.18c1.16-.42 2-1.52 2-2.82V6h-2zm-1 11c-.55 0-1-.45-1-1v-2h2v2c0 .55-.45 1-1 1zm-1-5V8h2v4h-2z" /> , 'SettingsInputComponentOutlined');
packages/material-ui-icons/src/SettingsInputComponentOutlined.js
0
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.00016341186710633337, 0.00016341186710633337, 0.00016341186710633337, 0.00016341186710633337, 0 ]
{ "id": 4, "code_window": [ " });\n", " });\n", "diff --git a/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js b/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js\n", "index 5c9d0be26..7f0862466 100644\n", "--- a/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js\n", "+++ b/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js\n", "@@ -135,7 +135,7 @@ describe('ThemeProvider', () => {\n", " <div />\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "index 9013d9095..7f0862466 100644\n" ], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 32 }
diff --git a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js index 5e83281c0..3c995f97c 100644 --- a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js +++ b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js @@ -963,7 +963,7 @@ describe('<Autocomplete />', () => { fireEvent.keyDown(textbox, { key: 'Enter' }); expect(handleChange.callCount).to.equal(1); expect(handleChange.args[0][1]).to.equal('a'); - expect(consoleErrorMock.callCount()).to.equal(4); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(3); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: The `getOptionLabel` method of Autocomplete returned undefined instead of a string', ); @@ -993,7 +993,7 @@ describe('<Autocomplete />', () => { />, ); - expect(consoleWarnMock.callCount()).to.equal(4); // strict mode renders twice + expect(consoleWarnMock.callCount()).to.equal(2); expect(consoleWarnMock.messages()[0]).to.include( 'None of the options match with `"not a good value"`', ); @@ -1022,7 +1022,7 @@ describe('<Autocomplete />', () => { const options = getAllByRole('option').map((el) => el.textContent); expect(options).to.have.length(7); expect(options).to.deep.equal(['A', 'D', 'E', 'B', 'G', 'F', 'C']); - expect(consoleWarnMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleWarnMock.callCount()).to.equal(1); expect(consoleWarnMock.messages()[0]).to.include('returns duplicated headers'); }); }); diff --git a/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js b/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js index 5c9d0be26..7f0862466 100644 --- a/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js +++ b/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js @@ -135,7 +135,7 @@ describe('ThemeProvider', () => { <div /> </ThemeProvider>, ); - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include('However, no outer theme is present.'); }); @@ -148,7 +148,7 @@ describe('ThemeProvider', () => { , </ThemeProvider>, ); - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: You should return an object from your theme function', ); diff --git a/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js b/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js index ed0e37f21..49d8ea9b0 100644 --- a/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js +++ b/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js @@ -102,7 +102,7 @@ describe('<Breadcrumbs />', () => { ); expect(getAllByRole('listitem', { hidden: false })).to.have.length(4); expect(getByRole('list')).to.have.text('first/second/third/fourth'); - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: You have provided an invalid combination of props to the Breadcrumbs.\nitemsAfterCollapse={2} + itemsBeforeCollapse={2} >= maxItems={3}', ); diff --git a/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js b/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js index cea126a0d..1eaf80628 100644 --- a/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js +++ b/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js @@ -261,7 +261,7 @@ describe('<TextareaAutosize />', () => { }); forceUpdate(); - expect(consoleErrorMock.callCount()).to.equal(3); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include('Material-UI: Too many re-renders.'); }); }); diff --git a/packages/material-ui/src/internal/SwitchBase.test.js b/packages/material-ui/src/internal/SwitchBase.test.js index 41a38bc07..c9397fd13 100644 --- a/packages/material-ui/src/internal/SwitchBase.test.js +++ b/packages/material-ui/src/internal/SwitchBase.test.js @@ -373,7 +373,7 @@ describe('<SwitchBase />', () => { wrapper.setProps({ checked: true }); expect(consoleErrorMock.callCount()).to.equal(2); expect(consoleErrorMock.messages()[0]).to.include( - 'Warning: A component is changing an uncontrolled input of type checkbox to be controlled.', + 'Warning: A component is changing an uncontrolled input to be controlled.', ); expect(consoleErrorMock.messages()[1]).to.include( 'Material-UI: A component is changing the uncontrolled checked state of SwitchBase to be controlled.', @@ -392,7 +392,7 @@ describe('<SwitchBase />', () => { setProps({ checked: undefined }); expect(consoleErrorMock.callCount()).to.equal(2); expect(consoleErrorMock.messages()[0]).to.include( - 'Warning: A component is changing a controlled input of type checkbox to be uncontrolled.', + 'Warning: A component is changing a controlled input to be uncontrolled.', ); expect(consoleErrorMock.messages()[1]).to.include( 'Material-UI: A component is changing the controlled checked state of SwitchBase to be uncontrolled.', diff --git a/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js b/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js index 68b0a4a5c..e31152c44 100644 --- a/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js +++ b/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js @@ -284,14 +284,10 @@ describe('useMediaQuery', () => { } render(<MyComponent />); - // logs warning twice in StrictMode - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: The `query` argument provided is invalid', ); }); }); });
scripts/react-next.diff
1
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.8648099303245544, 0.07235627621412277, 0.00016526719264220446, 0.0002728421241044998, 0.23893383145332336 ]
{ "id": 4, "code_window": [ " });\n", " });\n", "diff --git a/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js b/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js\n", "index 5c9d0be26..7f0862466 100644\n", "--- a/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js\n", "+++ b/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js\n", "@@ -135,7 +135,7 @@ describe('ThemeProvider', () => {\n", " <div />\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "index 9013d9095..7f0862466 100644\n" ], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 32 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M7 7l-3.2 9h1.9l.7-2h3.2l.7 2h1.9L9 7H7zm-.15 5.65L8 9l1.15 3.65h-2.3zM22 7l-1.2 6.29L19.3 7h-1.6l-1.49 6.29L15 7h-.76l-.01.01C12.76 5.18 10.53 4 8 4c-4.42 0-8 3.58-8 8s3.58 8 8 8c2.96 0 5.55-1.61 6.93-4 .03-.06.05-.12.08-.18.05-.08.09-.17.14-.25l.1.43H17l1.5-6.1L20 16h1.75l2.05-9H22zm-8.63 7.67C12.38 16.64 10.35 18 8 18c-3.31 0-6-2.69-6-6s2.69-6 6-6 6 2.69 6 6c0 .96-.23 1.86-.63 2.67z" /> , 'WbAutoOutlined');
packages/material-ui-icons/src/WbAutoOutlined.js
0
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.0001702773297438398, 0.0001702773297438398, 0.0001702773297438398, 0.0001702773297438398, 0 ]
{ "id": 4, "code_window": [ " });\n", " });\n", "diff --git a/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js b/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js\n", "index 5c9d0be26..7f0862466 100644\n", "--- a/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js\n", "+++ b/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js\n", "@@ -135,7 +135,7 @@ describe('ThemeProvider', () => {\n", " <div />\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "index 9013d9095..7f0862466 100644\n" ], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 32 }
import React from 'react'; import Switch from '@material-ui/core/Switch'; import Paper from '@material-ui/core/Paper'; import Zoom from '@material-ui/core/Zoom'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import { makeStyles } from '@material-ui/core/styles'; const useStyles = makeStyles((theme) => ({ root: { height: 180, }, container: { display: 'flex', }, paper: { margin: theme.spacing(1), }, svg: { width: 100, height: 100, }, polygon: { fill: theme.palette.common.white, stroke: theme.palette.divider, strokeWidth: 1, }, })); export default function SimpleZoom() { const classes = useStyles(); const [checked, setChecked] = React.useState(false); const handleChange = () => { setChecked((prev) => !prev); }; return ( <div className={classes.root}> <FormControlLabel control={<Switch checked={checked} onChange={handleChange} />} label="Show" /> <div className={classes.container}> <Zoom in={checked}> <Paper elevation={4} className={classes.paper}> <svg className={classes.svg}> <polygon points="0,100 50,00, 100,100" className={classes.polygon} /> </svg> </Paper> </Zoom> <Zoom in={checked} style={{ transitionDelay: checked ? '500ms' : '0ms' }}> <Paper elevation={4} className={classes.paper}> <svg className={classes.svg}> <polygon points="0,100 50,00, 100,100" className={classes.polygon} /> </svg> </Paper> </Zoom> </div> </div> ); }
docs/src/pages/components/transitions/SimpleZoom.js
0
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.00017289223615080118, 0.00016981882799882442, 0.0001640058180782944, 0.0001704072637949139, 0.000002937980298156617 ]
{ "id": 4, "code_window": [ " });\n", " });\n", "diff --git a/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js b/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js\n", "index 5c9d0be26..7f0862466 100644\n", "--- a/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js\n", "+++ b/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js\n", "@@ -135,7 +135,7 @@ describe('ThemeProvider', () => {\n", " <div />\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "index 9013d9095..7f0862466 100644\n" ], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 32 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M12.09 2.91C10.08.9 7.07.49 4.65 1.67l4.34 4.34-3 3-4.34-4.34C.48 7.1.89 10.09 2.9 12.1c1.86 1.86 4.58 2.35 6.89 1.48l9.82 9.82 3.71-3.71-9.78-9.79c.92-2.34.44-5.1-1.45-6.99z" /> , 'BuildSharp');
packages/material-ui-icons/src/BuildSharp.js
0
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.00017036097415257245, 0.00017036097415257245, 0.00017036097415257245, 0.00017036097415257245, 0 ]
{ "id": 5, "code_window": [ "+ expect(consoleErrorMock.callCount()).to.equal(1);\n", " expect(consoleErrorMock.messages()[0]).to.include(\n", " 'Material-UI: You have provided an invalid combination of props to the Breadcrumbs.\\nitemsAfterCollapse={2} + itemsBeforeCollapse={2} >= maxItems={3}',\n", " );\n", "diff --git a/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js b/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js\n", "index cea126a0d..1eaf80628 100644\n", "--- a/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js\n", "+++ b/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js\n", "@@ -261,7 +261,7 @@ describe('<TextareaAutosize />', () => {\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "index 09daadd96..1eaf80628 100644\n" ], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 67 }
diff --git a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js index 5e83281c0..3c995f97c 100644 --- a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js +++ b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js @@ -963,7 +963,7 @@ describe('<Autocomplete />', () => { fireEvent.keyDown(textbox, { key: 'Enter' }); expect(handleChange.callCount).to.equal(1); expect(handleChange.args[0][1]).to.equal('a'); - expect(consoleErrorMock.callCount()).to.equal(4); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(3); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: The `getOptionLabel` method of Autocomplete returned undefined instead of a string', ); @@ -993,7 +993,7 @@ describe('<Autocomplete />', () => { />, ); - expect(consoleWarnMock.callCount()).to.equal(4); // strict mode renders twice + expect(consoleWarnMock.callCount()).to.equal(2); expect(consoleWarnMock.messages()[0]).to.include( 'None of the options match with `"not a good value"`', ); @@ -1022,7 +1022,7 @@ describe('<Autocomplete />', () => { const options = getAllByRole('option').map((el) => el.textContent); expect(options).to.have.length(7); expect(options).to.deep.equal(['A', 'D', 'E', 'B', 'G', 'F', 'C']); - expect(consoleWarnMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleWarnMock.callCount()).to.equal(1); expect(consoleWarnMock.messages()[0]).to.include('returns duplicated headers'); }); }); diff --git a/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js b/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js index 5c9d0be26..7f0862466 100644 --- a/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js +++ b/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js @@ -135,7 +135,7 @@ describe('ThemeProvider', () => { <div /> </ThemeProvider>, ); - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include('However, no outer theme is present.'); }); @@ -148,7 +148,7 @@ describe('ThemeProvider', () => { , </ThemeProvider>, ); - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: You should return an object from your theme function', ); diff --git a/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js b/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js index ed0e37f21..49d8ea9b0 100644 --- a/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js +++ b/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js @@ -102,7 +102,7 @@ describe('<Breadcrumbs />', () => { ); expect(getAllByRole('listitem', { hidden: false })).to.have.length(4); expect(getByRole('list')).to.have.text('first/second/third/fourth'); - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: You have provided an invalid combination of props to the Breadcrumbs.\nitemsAfterCollapse={2} + itemsBeforeCollapse={2} >= maxItems={3}', ); diff --git a/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js b/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js index cea126a0d..1eaf80628 100644 --- a/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js +++ b/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js @@ -261,7 +261,7 @@ describe('<TextareaAutosize />', () => { }); forceUpdate(); - expect(consoleErrorMock.callCount()).to.equal(3); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include('Material-UI: Too many re-renders.'); }); }); diff --git a/packages/material-ui/src/internal/SwitchBase.test.js b/packages/material-ui/src/internal/SwitchBase.test.js index 41a38bc07..c9397fd13 100644 --- a/packages/material-ui/src/internal/SwitchBase.test.js +++ b/packages/material-ui/src/internal/SwitchBase.test.js @@ -373,7 +373,7 @@ describe('<SwitchBase />', () => { wrapper.setProps({ checked: true }); expect(consoleErrorMock.callCount()).to.equal(2); expect(consoleErrorMock.messages()[0]).to.include( - 'Warning: A component is changing an uncontrolled input of type checkbox to be controlled.', + 'Warning: A component is changing an uncontrolled input to be controlled.', ); expect(consoleErrorMock.messages()[1]).to.include( 'Material-UI: A component is changing the uncontrolled checked state of SwitchBase to be controlled.', @@ -392,7 +392,7 @@ describe('<SwitchBase />', () => { setProps({ checked: undefined }); expect(consoleErrorMock.callCount()).to.equal(2); expect(consoleErrorMock.messages()[0]).to.include( - 'Warning: A component is changing a controlled input of type checkbox to be uncontrolled.', + 'Warning: A component is changing a controlled input to be uncontrolled.', ); expect(consoleErrorMock.messages()[1]).to.include( 'Material-UI: A component is changing the controlled checked state of SwitchBase to be uncontrolled.', diff --git a/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js b/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js index 68b0a4a5c..e31152c44 100644 --- a/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js +++ b/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js @@ -284,14 +284,10 @@ describe('useMediaQuery', () => { } render(<MyComponent />); - // logs warning twice in StrictMode - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: The `query` argument provided is invalid', ); }); }); });
scripts/react-next.diff
1
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.8621954917907715, 0.07357581704854965, 0.0001683431473793462, 0.0007552336901426315, 0.23779243230819702 ]
{ "id": 5, "code_window": [ "+ expect(consoleErrorMock.callCount()).to.equal(1);\n", " expect(consoleErrorMock.messages()[0]).to.include(\n", " 'Material-UI: You have provided an invalid combination of props to the Breadcrumbs.\\nitemsAfterCollapse={2} + itemsBeforeCollapse={2} >= maxItems={3}',\n", " );\n", "diff --git a/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js b/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js\n", "index cea126a0d..1eaf80628 100644\n", "--- a/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js\n", "+++ b/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js\n", "@@ -261,7 +261,7 @@ describe('<TextareaAutosize />', () => {\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "index 09daadd96..1eaf80628 100644\n" ], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 67 }
Last modified: October 7th, 2018. Material-UI is committed to protecting and respecting your privacy. This Privacy Policy sets out how we collect and process personal information about you when you visit our website argos-ci.com, when you use our products and services (our “Services”), or when you otherwise do business or make contact with us. Please read this policy carefully to understand how we handle and treat your personal information. ## What information do we collect? We may collect and process the following personal information from you: - **Information you provide to us:** We collect personal information when you voluntarily provide us with such information in the course of using our website or Services. For example, when you register to use our Services, we will collect your name, email address and organization information. We also collect personal information from you when you subscribe to our newsletter, or respond to a survey. If you make an enquiry through our website, or contact us in any other way, we will keep a copy of your communications with us. - **Information we collect when you do business with us:** We may process your personal information when you do business with us – for example, as a customer or prospective customer, or as a vendor, supplier, consultant or other third party. For example, we may hold your business contact information and financial account information (if any) and other communications you have with us for the purposes of maintaining our business relations with you. - **Information we automatically collect:** We may also collect certain technical information by automatic means when you visit our website, such as IP address, browser type and operating system, referring URLs, your use of our website, and other clickstream data. We collect this information automatically through the use of various technologies, such as cookies. - **Personal information where we act as a data processor:** We also process personal information on behalf of our customers in the context of supporting our products and services. Where a customer subscribes to our Services for their website, game or app, they will be the ones who control what event data is collected and stored on our systems. For example, they may ask us to log basic user data (e.g. email address or username), device identifiers, IP addresses, event type, and related source code. In such cases, we are data processors acting in accordance with the instructions of our customers. You will need to refer to the privacy policies of our customers to find out more about how such information is handled by them. ## What do we use your information for? The personal information we collect from you may be used in one of the following ways: - To deal with your inquiries and requests - To create and administer records about any online account that you register with us - To provide you with information and access to resources that you have requested from us - To provide you with technical support (your information helps us to better respond to your individual needs) - To improve our website (we continually strive to improve our website offerings based on the information and feedback we receive from you), including to improve the navigation and content of our sites - For website and system administration and security - For general business purposes, including to improve customer service (your information helps us to more effectively respond to your customer service requests and support needs), to help us improve the content and functionality of our Services, to better understand our users, to protect against wrongdoing, to enforce our Terms of Service, and to generally manage our business - To process transactions and to provide Services to our customers and end-users - For recruitment purposes, where you apply for a job with us - To administer a contest, promotion, survey, or other site features - To send periodic emails. The email address you provide for order processing, will only be used to send you information and updates pertaining to your order. Where it is in accordance with your marketing preferences, we will send occasional marketing emails about our products and services, which you can unsubscribe from at any time using the link provided in the message. ## How do we protect your information? We implement a variety of security measures to maintain the safety of your personal information when you enter, submit, or access your personal information. We offer the use of a secure server. All supplied sensitive/credit information is transmitted via Secure Socket Layer (SSL) technology and then encrypted into our Payment gateway providers database only to be accessible by those authorized with special access rights to such systems, and are required to keep the information confidential. After a transaction, your private information (credit cards, social security numbers, financials, etc.) will not be stored on our servers. ## Do we use cookies? Yes. Cookies are small files that a site or its service provider transfers to your computers hard drive through your Web browser (if you allow) that enables the sites or service providers systems to recognize your browser and capture and remember certain information. We use cookies to understand and save your preferences for future visits, to advertise to you on other sites and compile aggregate data about site traffic and site interaction so that we can offer better site experiences and tools in the future. You may refuse to accept cookies by activating the setting on your browser which allows you to refuse the setting of cookies. You can find information on popular browsers and how to adjust your cookie preferences at the following websites: - [Microsoft Internet Explorer](https://www.microsoft.com/info/cookies.mspx) - [Mozilla Firefox](https://support.mozilla.org/en-US/kb/enable-and-disable-cookies-website-preferences) - [Google Chrome](https://support.google.com/accounts/answer/61416) - [Apple Safari](https://support.apple.com/en-us/HT201265) However, if you choose to disable cookies, you may be unable to access certain parts of our site. Unless you have adjusted your browser setting so that it will refuse cookies, our system will issue cookies when you log on to our site. ## Do we disclose any information to outside parties? We will only share your information with third parties in certain circumstances: - We engage certain trusted third parties to perform functions and provide services to us, including cloud hosting services, off-site backups, email service providers, and customer support providers. We will only share your personal information with third parties to the extent necessary to perform these functions, in accordance with the purposes set out in this Privacy Policy and applicable laws. - In the event of a corporate sale, merger, reorganization, dissolution or similar event, your personal information may be sold, disposed of, transferred or otherwise disclosed as part of that transaction. - We may also disclose information about you to third parties where we believe it necessary or appropriate under law, for example: (1) to protect or defend our rights, interests or property or that of third parties; (2) to comply with legal process, judicial orders or subpoenas; (3) to respond to requests from public or government authorities, including for national security and law enforcement purposes; (4) to prevent or investigate possible wrongdoing in connection with the Services or to enforce our Terms of Service; (5) to protect the vital interests of our users, customers and other third parties. - We may use and share aggregated non-personal information with third parties for marketing, advertising and analytics purposes. We do not sell or trade your personal information to third parties. ## Third Party Links Occasionally, at our discretion, we may include or offer third party products or services on our website. If you access other websites using the links provided, the operators of these websites may collect information from you that will be used by them in accordance with their privacy policies. These third party sites have separate and independent privacy policies. We therefore have no responsibility or liability for the content and activities of these linked sites. Nonetheless, we seek to protect the integrity of our site and welcome any feedback about these sites. ## International Transfers If you are visiting our website or using our Services from outside the United States (US), please be aware that you are sending personal information to the US where our servers are located. The US may not have data protection laws that are as comprehensive or protective as those in your country of residence; however, our collection, storage and use of your personal information will at all times be in accordance with this Privacy Policy. ## Your Rights If you are from the EU, you may have the right to access a copy of the personal information we hold about you, or to request the correction, amendment or deletion of such information where it is inaccurate or processed in violation of the Privacy Shield Principles. To make such a request, please contact us at the contact details at the left. We will consider and respond to your request in accordance with the Privacy Shield Principles and applicable laws. Furthermore, we commit to giving you an opportunity to opt-out if your personal information is to be disclosed to any other independent third parties, or to be used for a purpose materially different from those that are set out in this Privacy Policy. Where sensitive personal information is involved, we will always obtain your express opt-in consent to do such things. If you otherwise wish to limit the use or disclosure of your personal information, please write to us at the contact details further below. You can also unsubscribe from our marketing communications at any time by following the instructions or unsubscribe mechanism in the email message itself. ## Data Retention We may retain your personal information as long as you continue to use the Services, have an account with us or for as long as is necessary to fulfil the purposes outlined in the policy. You can ask to close your account by contacting us at the details below and we will delete your personal information on request. We may however retain personal information for an additional period as is permitted or required under applicable laws, for legal, tax or regulatory reasons, or for legitimate and lawful business purposes. ## Changes to our Privacy Policy If we decide to change our privacy policy, we will post those changes on this page, and/or update the Privacy Policy modification date below.
docs/src/pages/premium-themes/onepirate/modules/views/privacy-zh.md
0
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.00017351782298646867, 0.00016977760242298245, 0.00016411971591878682, 0.0001701861183391884, 0.0000029913298931205645 ]
{ "id": 5, "code_window": [ "+ expect(consoleErrorMock.callCount()).to.equal(1);\n", " expect(consoleErrorMock.messages()[0]).to.include(\n", " 'Material-UI: You have provided an invalid combination of props to the Breadcrumbs.\\nitemsAfterCollapse={2} + itemsBeforeCollapse={2} >= maxItems={3}',\n", " );\n", "diff --git a/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js b/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js\n", "index cea126a0d..1eaf80628 100644\n", "--- a/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js\n", "+++ b/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js\n", "@@ -261,7 +261,7 @@ describe('<TextareaAutosize />', () => {\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "index 09daadd96..1eaf80628 100644\n" ], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 67 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M16 5v8c0 1.1-.9 2-2 2H8c-1.1 0-2-.9-2-2V5h10m4-2H4v10c0 2.21 1.79 4 4 4h6c2.21 0 4-1.79 4-4v-3h2c1.11 0 2-.89 2-2V5c0-1.11-.89-2-2-2zm-2 5V5h2v3h-2zm2 11H2v2h18v-2z" /> , 'LocalCafeOutlined');
packages/material-ui-icons/src/LocalCafeOutlined.js
0
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.00017330683476757258, 0.00017330683476757258, 0.00017330683476757258, 0.00017330683476757258, 0 ]
{ "id": 5, "code_window": [ "+ expect(consoleErrorMock.callCount()).to.equal(1);\n", " expect(consoleErrorMock.messages()[0]).to.include(\n", " 'Material-UI: You have provided an invalid combination of props to the Breadcrumbs.\\nitemsAfterCollapse={2} + itemsBeforeCollapse={2} >= maxItems={3}',\n", " );\n", "diff --git a/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js b/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js\n", "index cea126a0d..1eaf80628 100644\n", "--- a/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js\n", "+++ b/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js\n", "@@ -261,7 +261,7 @@ describe('<TextareaAutosize />', () => {\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "index 09daadd96..1eaf80628 100644\n" ], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 67 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M4 15h16v-2H4v2zm0 4h16v-2H4v2zm0-8h16V9H4v2zm0-6v2h16V5H4z" /> , 'ViewHeadlineTwoTone');
packages/material-ui-icons/src/ViewHeadlineTwoTone.js
0
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.00017557290266267955, 0.00017557290266267955, 0.00017557290266267955, 0.00017557290266267955, 0 ]
{ "id": 6, "code_window": [ " expect(consoleErrorMock.messages()[1]).to.include(\n", " 'Material-UI: A component is changing the controlled checked state of SwitchBase to be uncontrolled.',\n", "diff --git a/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js b/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js\n", "index 68b0a4a5c..e31152c44 100644\n", "--- a/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js\n", "+++ b/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "index ba9977d1a..b5ca0ca4b 100644\n" ], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 102 }
diff --git a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js index 5e83281c0..3c995f97c 100644 --- a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js +++ b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js @@ -963,7 +963,7 @@ describe('<Autocomplete />', () => { fireEvent.keyDown(textbox, { key: 'Enter' }); expect(handleChange.callCount).to.equal(1); expect(handleChange.args[0][1]).to.equal('a'); - expect(consoleErrorMock.callCount()).to.equal(4); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(3); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: The `getOptionLabel` method of Autocomplete returned undefined instead of a string', ); @@ -993,7 +993,7 @@ describe('<Autocomplete />', () => { />, ); - expect(consoleWarnMock.callCount()).to.equal(4); // strict mode renders twice + expect(consoleWarnMock.callCount()).to.equal(2); expect(consoleWarnMock.messages()[0]).to.include( 'None of the options match with `"not a good value"`', ); @@ -1022,7 +1022,7 @@ describe('<Autocomplete />', () => { const options = getAllByRole('option').map((el) => el.textContent); expect(options).to.have.length(7); expect(options).to.deep.equal(['A', 'D', 'E', 'B', 'G', 'F', 'C']); - expect(consoleWarnMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleWarnMock.callCount()).to.equal(1); expect(consoleWarnMock.messages()[0]).to.include('returns duplicated headers'); }); }); diff --git a/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js b/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js index 5c9d0be26..7f0862466 100644 --- a/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js +++ b/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js @@ -135,7 +135,7 @@ describe('ThemeProvider', () => { <div /> </ThemeProvider>, ); - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include('However, no outer theme is present.'); }); @@ -148,7 +148,7 @@ describe('ThemeProvider', () => { , </ThemeProvider>, ); - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: You should return an object from your theme function', ); diff --git a/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js b/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js index ed0e37f21..49d8ea9b0 100644 --- a/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js +++ b/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js @@ -102,7 +102,7 @@ describe('<Breadcrumbs />', () => { ); expect(getAllByRole('listitem', { hidden: false })).to.have.length(4); expect(getByRole('list')).to.have.text('first/second/third/fourth'); - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: You have provided an invalid combination of props to the Breadcrumbs.\nitemsAfterCollapse={2} + itemsBeforeCollapse={2} >= maxItems={3}', ); diff --git a/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js b/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js index cea126a0d..1eaf80628 100644 --- a/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js +++ b/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js @@ -261,7 +261,7 @@ describe('<TextareaAutosize />', () => { }); forceUpdate(); - expect(consoleErrorMock.callCount()).to.equal(3); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include('Material-UI: Too many re-renders.'); }); }); diff --git a/packages/material-ui/src/internal/SwitchBase.test.js b/packages/material-ui/src/internal/SwitchBase.test.js index 41a38bc07..c9397fd13 100644 --- a/packages/material-ui/src/internal/SwitchBase.test.js +++ b/packages/material-ui/src/internal/SwitchBase.test.js @@ -373,7 +373,7 @@ describe('<SwitchBase />', () => { wrapper.setProps({ checked: true }); expect(consoleErrorMock.callCount()).to.equal(2); expect(consoleErrorMock.messages()[0]).to.include( - 'Warning: A component is changing an uncontrolled input of type checkbox to be controlled.', + 'Warning: A component is changing an uncontrolled input to be controlled.', ); expect(consoleErrorMock.messages()[1]).to.include( 'Material-UI: A component is changing the uncontrolled checked state of SwitchBase to be controlled.', @@ -392,7 +392,7 @@ describe('<SwitchBase />', () => { setProps({ checked: undefined }); expect(consoleErrorMock.callCount()).to.equal(2); expect(consoleErrorMock.messages()[0]).to.include( - 'Warning: A component is changing a controlled input of type checkbox to be uncontrolled.', + 'Warning: A component is changing a controlled input to be uncontrolled.', ); expect(consoleErrorMock.messages()[1]).to.include( 'Material-UI: A component is changing the controlled checked state of SwitchBase to be uncontrolled.', diff --git a/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js b/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js index 68b0a4a5c..e31152c44 100644 --- a/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js +++ b/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js @@ -284,14 +284,10 @@ describe('useMediaQuery', () => { } render(<MyComponent />); - // logs warning twice in StrictMode - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: The `query` argument provided is invalid', ); }); }); });
scripts/react-next.diff
1
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.4302719235420227, 0.04173259809613228, 0.00016619892267044634, 0.0005142379086464643, 0.11801068484783173 ]
{ "id": 6, "code_window": [ " expect(consoleErrorMock.messages()[1]).to.include(\n", " 'Material-UI: A component is changing the controlled checked state of SwitchBase to be uncontrolled.',\n", "diff --git a/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js b/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js\n", "index 68b0a4a5c..e31152c44 100644\n", "--- a/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js\n", "+++ b/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "index ba9977d1a..b5ca0ca4b 100644\n" ], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 102 }
--- title: React Grid List 网格列表组件 components: GridList, GridListTile, GridListTileBar, ListSubheader, IconButton --- # Grid List 网格列表 <p class="description">网格列表在一个系统的网格中展示了一系列的图像。</p> [网格列表](https://material.io/design/components/image-lists.html)展示了一个在重复的模式中的子集。 它们有助于提高对所持内容的视觉理解。 ## 仅有图像的网格列表 这是一个可滚动的图像的`网格列表`的简单示例。 {{"demo": "pages/components/grid-list/ImageGridList.js", "hideEditButton": true}} ## 带有标题栏的网格列表 此示例演示如何使用 `GridListTileBar` 为每个 `GridListTile` 添加一个叠加层。 叠加层可以容纳 `title`, `subtitle` 和辅助操作—在本例中为 `IconButton`。 {{"demo": "pages/components/grid-list/TitlebarGridList.js", "hideEditButton": true}} ## 单行网格列表 此示例演示了可以在水平方向滚动的单行纯图像网格列表。 我们其实不鼓励水平滚动网格列表,因为滚动会干扰典型的阅读模式,从而影响用户的理解。 一个值得注意的例外是水平滚动的单行网格图像列表,例如图库。 {{"demo": "pages/components/grid-list/SingleLineGridList.js", "hideEditButton": true}} ## 高级网格列表 此示例演示了“精选的”瓷砖效果 ,使用 `rows` 和 `cols` props 来调整磁贴的大小,并使用 `padding` 属性来调整间距。 瓷砖有一个位于顶部的自定义标题栏,并带有自定义渐变的 `titleBackground `。 而辅助操作的 `IconButton` 则位于左侧。 {{"demo": "pages/components/grid-list/AdvancedGridList.js", "hideEditButton": true, "defaultCodeOpen": false}}
docs/src/pages/components/grid-list/grid-list-zh.md
0
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.0001674384984653443, 0.0001658561232034117, 0.00016487653192598373, 0.00016555472393520176, 9.752698133524973e-7 ]
{ "id": 6, "code_window": [ " expect(consoleErrorMock.messages()[1]).to.include(\n", " 'Material-UI: A component is changing the controlled checked state of SwitchBase to be uncontrolled.',\n", "diff --git a/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js b/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js\n", "index 68b0a4a5c..e31152c44 100644\n", "--- a/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js\n", "+++ b/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "index ba9977d1a..b5ca0ca4b 100644\n" ], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 102 }
import React from 'react'; export default function Usage() { return ( <iframe title="codesandbox" src="https://codesandbox.io/embed/4j7m47vlm4?hidenavigation=1&fontsize=14&view=preview" style={{ width: '100%', height: 350, border: 0, }} sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin" /> ); }
docs/src/pages/getting-started/usage/Usage.js
0
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.0001726538612274453, 0.00017042222316376865, 0.000168190585100092, 0.00017042222316376865, 0.0000022316380636766553 ]
{ "id": 6, "code_window": [ " expect(consoleErrorMock.messages()[1]).to.include(\n", " 'Material-UI: A component is changing the controlled checked state of SwitchBase to be uncontrolled.',\n", "diff --git a/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js b/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js\n", "index 68b0a4a5c..e31152c44 100644\n", "--- a/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js\n", "+++ b/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "index ba9977d1a..b5ca0ca4b 100644\n" ], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 102 }
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"> <rect width="100%" height="100%" fill="#e57373"/> </svg>
docs/public/static/colors-preview/red-300-24x24.svg
0
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.00017271691467612982, 0.00017271691467612982, 0.00017271691467612982, 0.00017271691467612982, 0 ]
{ "id": 7, "code_window": [ "--- a/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js\n", "+++ b/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js\n", "@@ -284,14 +284,10 @@ describe('useMediaQuery', () => {\n", " }\n", " \n", " render(<MyComponent />);\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [ "@@ -285,7 +285,7 @@ describe('useMediaQuery', () => {\n" ], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 105 }
diff --git a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js index 5e83281c0..3c995f97c 100644 --- a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js +++ b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js @@ -963,7 +963,7 @@ describe('<Autocomplete />', () => { fireEvent.keyDown(textbox, { key: 'Enter' }); expect(handleChange.callCount).to.equal(1); expect(handleChange.args[0][1]).to.equal('a'); - expect(consoleErrorMock.callCount()).to.equal(4); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(3); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: The `getOptionLabel` method of Autocomplete returned undefined instead of a string', ); @@ -993,7 +993,7 @@ describe('<Autocomplete />', () => { />, ); - expect(consoleWarnMock.callCount()).to.equal(4); // strict mode renders twice + expect(consoleWarnMock.callCount()).to.equal(2); expect(consoleWarnMock.messages()[0]).to.include( 'None of the options match with `"not a good value"`', ); @@ -1022,7 +1022,7 @@ describe('<Autocomplete />', () => { const options = getAllByRole('option').map((el) => el.textContent); expect(options).to.have.length(7); expect(options).to.deep.equal(['A', 'D', 'E', 'B', 'G', 'F', 'C']); - expect(consoleWarnMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleWarnMock.callCount()).to.equal(1); expect(consoleWarnMock.messages()[0]).to.include('returns duplicated headers'); }); }); diff --git a/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js b/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js index 5c9d0be26..7f0862466 100644 --- a/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js +++ b/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js @@ -135,7 +135,7 @@ describe('ThemeProvider', () => { <div /> </ThemeProvider>, ); - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include('However, no outer theme is present.'); }); @@ -148,7 +148,7 @@ describe('ThemeProvider', () => { , </ThemeProvider>, ); - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: You should return an object from your theme function', ); diff --git a/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js b/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js index ed0e37f21..49d8ea9b0 100644 --- a/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js +++ b/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js @@ -102,7 +102,7 @@ describe('<Breadcrumbs />', () => { ); expect(getAllByRole('listitem', { hidden: false })).to.have.length(4); expect(getByRole('list')).to.have.text('first/second/third/fourth'); - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: You have provided an invalid combination of props to the Breadcrumbs.\nitemsAfterCollapse={2} + itemsBeforeCollapse={2} >= maxItems={3}', ); diff --git a/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js b/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js index cea126a0d..1eaf80628 100644 --- a/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js +++ b/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js @@ -261,7 +261,7 @@ describe('<TextareaAutosize />', () => { }); forceUpdate(); - expect(consoleErrorMock.callCount()).to.equal(3); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include('Material-UI: Too many re-renders.'); }); }); diff --git a/packages/material-ui/src/internal/SwitchBase.test.js b/packages/material-ui/src/internal/SwitchBase.test.js index 41a38bc07..c9397fd13 100644 --- a/packages/material-ui/src/internal/SwitchBase.test.js +++ b/packages/material-ui/src/internal/SwitchBase.test.js @@ -373,7 +373,7 @@ describe('<SwitchBase />', () => { wrapper.setProps({ checked: true }); expect(consoleErrorMock.callCount()).to.equal(2); expect(consoleErrorMock.messages()[0]).to.include( - 'Warning: A component is changing an uncontrolled input of type checkbox to be controlled.', + 'Warning: A component is changing an uncontrolled input to be controlled.', ); expect(consoleErrorMock.messages()[1]).to.include( 'Material-UI: A component is changing the uncontrolled checked state of SwitchBase to be controlled.', @@ -392,7 +392,7 @@ describe('<SwitchBase />', () => { setProps({ checked: undefined }); expect(consoleErrorMock.callCount()).to.equal(2); expect(consoleErrorMock.messages()[0]).to.include( - 'Warning: A component is changing a controlled input of type checkbox to be uncontrolled.', + 'Warning: A component is changing a controlled input to be uncontrolled.', ); expect(consoleErrorMock.messages()[1]).to.include( 'Material-UI: A component is changing the controlled checked state of SwitchBase to be uncontrolled.', diff --git a/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js b/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js index 68b0a4a5c..e31152c44 100644 --- a/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js +++ b/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js @@ -284,14 +284,10 @@ describe('useMediaQuery', () => { } render(<MyComponent />); - // logs warning twice in StrictMode - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: The `query` argument provided is invalid', ); }); }); });
scripts/react-next.diff
1
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.3172607421875, 0.02687232755124569, 0.00016500044148415327, 0.0002337295445613563, 0.08755739778280258 ]
{ "id": 7, "code_window": [ "--- a/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js\n", "+++ b/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js\n", "@@ -284,14 +284,10 @@ describe('useMediaQuery', () => {\n", " }\n", " \n", " render(<MyComponent />);\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [ "@@ -285,7 +285,7 @@ describe('useMediaQuery', () => {\n" ], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 105 }
import React from 'react'; import Avatar from '@material-ui/core/Avatar'; import AvatarGroup from '@material-ui/lab/AvatarGroup'; export default function GroupAvatars() { return ( <AvatarGroup max={4}> <Avatar alt="Remy Sharp" src="/static/images/avatar/1.jpg" /> <Avatar alt="Travis Howard" src="/static/images/avatar/2.jpg" /> <Avatar alt="Cindy Baker" src="/static/images/avatar/3.jpg" /> <Avatar alt="Agnes Walker" src="/static/images/avatar/4.jpg" /> <Avatar alt="Trevor Henderson" src="/static/images/avatar/5.jpg" /> </AvatarGroup> ); }
docs/src/pages/components/avatars/GroupAvatars.tsx
0
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.00017476982611697167, 0.00017212048987857997, 0.0001694711681921035, 0.00017212048987857997, 0.0000026493289624340832 ]
{ "id": 7, "code_window": [ "--- a/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js\n", "+++ b/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js\n", "@@ -284,14 +284,10 @@ describe('useMediaQuery', () => {\n", " }\n", " \n", " render(<MyComponent />);\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [ "@@ -285,7 +285,7 @@ describe('useMediaQuery', () => {\n" ], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 105 }
--- title: React Bottom Navigation 底部导航栏组件 components: BottomNavigation, BottomNavigationAction --- # Bottom Navigation 底部导航栏 <p class="description">使用底部导航栏,您可以在应用程序的主要导航项之间跳转。</p> [底部导航栏](https://material.io/design/components/bottom-navigation.html)在屏幕下方显示三到五个导航项。 每一个导航项都由一个图标和一个可选文本标签表示。 当点击底部导航图标时,用户被切换到该图标关联的目标页面顶部。 ## 底部导航栏 当只有 **三个** 导航项时,导航栏会始终显示图标和文本标签。 {{"demo": "pages/components/bottom-navigation/SimpleBottomNavigation.js", "bg": true}} ## 无标签的底部导航栏 如果有**四个**或**五个**导航项,那些未被选中的导航项会以图标的样式显示。 {{"demo": "pages/components/bottom-navigation/LabelBottomNavigation.js", "bg": true}}
docs/src/pages/components/bottom-navigation/bottom-navigation-zh.md
0
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.00016931061691138893, 0.00016710377531126142, 0.00016442326887045056, 0.00016757745470385998, 0.0000020231689177308 ]
{ "id": 7, "code_window": [ "--- a/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js\n", "+++ b/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js\n", "@@ -284,14 +284,10 @@ describe('useMediaQuery', () => {\n", " }\n", " \n", " render(<MyComponent />);\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [ "@@ -285,7 +285,7 @@ describe('useMediaQuery', () => {\n" ], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 105 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M8.1 13.34l2.83-2.83L3.91 3.5c-1.56 1.56-1.56 4.09 0 5.66l4.19 4.18zm6.78-1.81c1.53.71 3.68.21 5.27-1.38 1.91-1.91 2.28-4.65.81-6.12-1.46-1.46-4.2-1.1-6.12.81-1.59 1.59-2.09 3.74-1.38 5.27L3.7 19.87l1.41 1.41L12 14.41l6.88 6.88 1.41-1.41L13.41 13l1.47-1.47z" /> , 'LocalDining');
packages/material-ui-icons/src/LocalDining.js
0
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.00017591792857274413, 0.00017591792857274413, 0.00017591792857274413, 0.00017591792857274413, 0 ]
{ "id": 8, "code_window": [ " \n", " render(<MyComponent />);\n", "- // logs warning twice in StrictMode\n", "- expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice\n", "+ expect(consoleErrorMock.callCount()).to.equal(1);\n", " expect(consoleErrorMock.messages()[0]).to.include(\n", " 'Material-UI: The `query` argument provided is invalid',\n", " );\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " // logs warning twice in StrictMode\n" ], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 109 }
diff --git a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js index 5e83281c0..3c995f97c 100644 --- a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js +++ b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js @@ -963,7 +963,7 @@ describe('<Autocomplete />', () => { fireEvent.keyDown(textbox, { key: 'Enter' }); expect(handleChange.callCount).to.equal(1); expect(handleChange.args[0][1]).to.equal('a'); - expect(consoleErrorMock.callCount()).to.equal(4); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(3); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: The `getOptionLabel` method of Autocomplete returned undefined instead of a string', ); @@ -993,7 +993,7 @@ describe('<Autocomplete />', () => { />, ); - expect(consoleWarnMock.callCount()).to.equal(4); // strict mode renders twice + expect(consoleWarnMock.callCount()).to.equal(2); expect(consoleWarnMock.messages()[0]).to.include( 'None of the options match with `"not a good value"`', ); @@ -1022,7 +1022,7 @@ describe('<Autocomplete />', () => { const options = getAllByRole('option').map((el) => el.textContent); expect(options).to.have.length(7); expect(options).to.deep.equal(['A', 'D', 'E', 'B', 'G', 'F', 'C']); - expect(consoleWarnMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleWarnMock.callCount()).to.equal(1); expect(consoleWarnMock.messages()[0]).to.include('returns duplicated headers'); }); }); diff --git a/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js b/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js index 5c9d0be26..7f0862466 100644 --- a/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js +++ b/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js @@ -135,7 +135,7 @@ describe('ThemeProvider', () => { <div /> </ThemeProvider>, ); - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include('However, no outer theme is present.'); }); @@ -148,7 +148,7 @@ describe('ThemeProvider', () => { , </ThemeProvider>, ); - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: You should return an object from your theme function', ); diff --git a/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js b/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js index ed0e37f21..49d8ea9b0 100644 --- a/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js +++ b/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js @@ -102,7 +102,7 @@ describe('<Breadcrumbs />', () => { ); expect(getAllByRole('listitem', { hidden: false })).to.have.length(4); expect(getByRole('list')).to.have.text('first/second/third/fourth'); - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: You have provided an invalid combination of props to the Breadcrumbs.\nitemsAfterCollapse={2} + itemsBeforeCollapse={2} >= maxItems={3}', ); diff --git a/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js b/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js index cea126a0d..1eaf80628 100644 --- a/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js +++ b/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js @@ -261,7 +261,7 @@ describe('<TextareaAutosize />', () => { }); forceUpdate(); - expect(consoleErrorMock.callCount()).to.equal(3); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include('Material-UI: Too many re-renders.'); }); }); diff --git a/packages/material-ui/src/internal/SwitchBase.test.js b/packages/material-ui/src/internal/SwitchBase.test.js index 41a38bc07..c9397fd13 100644 --- a/packages/material-ui/src/internal/SwitchBase.test.js +++ b/packages/material-ui/src/internal/SwitchBase.test.js @@ -373,7 +373,7 @@ describe('<SwitchBase />', () => { wrapper.setProps({ checked: true }); expect(consoleErrorMock.callCount()).to.equal(2); expect(consoleErrorMock.messages()[0]).to.include( - 'Warning: A component is changing an uncontrolled input of type checkbox to be controlled.', + 'Warning: A component is changing an uncontrolled input to be controlled.', ); expect(consoleErrorMock.messages()[1]).to.include( 'Material-UI: A component is changing the uncontrolled checked state of SwitchBase to be controlled.', @@ -392,7 +392,7 @@ describe('<SwitchBase />', () => { setProps({ checked: undefined }); expect(consoleErrorMock.callCount()).to.equal(2); expect(consoleErrorMock.messages()[0]).to.include( - 'Warning: A component is changing a controlled input of type checkbox to be uncontrolled.', + 'Warning: A component is changing a controlled input to be uncontrolled.', ); expect(consoleErrorMock.messages()[1]).to.include( 'Material-UI: A component is changing the controlled checked state of SwitchBase to be uncontrolled.', diff --git a/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js b/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js index 68b0a4a5c..e31152c44 100644 --- a/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js +++ b/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js @@ -284,14 +284,10 @@ describe('useMediaQuery', () => { } render(<MyComponent />); - // logs warning twice in StrictMode - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: The `query` argument provided is invalid', ); }); }); });
scripts/react-next.diff
1
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.9080620408058167, 0.09701891988515854, 0.000197094603208825, 0.004121598321944475, 0.24781765043735504 ]
{ "id": 8, "code_window": [ " \n", " render(<MyComponent />);\n", "- // logs warning twice in StrictMode\n", "- expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice\n", "+ expect(consoleErrorMock.callCount()).to.equal(1);\n", " expect(consoleErrorMock.messages()[0]).to.include(\n", " 'Material-UI: The `query` argument provided is invalid',\n", " );\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " // logs warning twice in StrictMode\n" ], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 109 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-10 9H4c-.55 0-1-.45-1-1V6c0-.55.45-1 1-1h7c.55 0 1 .45 1 1v5c0 .55-.45 1-1 1z" /> , 'FeaturedVideoRounded');
packages/material-ui-icons/src/FeaturedVideoRounded.js
0
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.00017508539895061404, 0.00017508539895061404, 0.00017508539895061404, 0.00017508539895061404, 0 ]
{ "id": 8, "code_window": [ " \n", " render(<MyComponent />);\n", "- // logs warning twice in StrictMode\n", "- expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice\n", "+ expect(consoleErrorMock.callCount()).to.equal(1);\n", " expect(consoleErrorMock.messages()[0]).to.include(\n", " 'Material-UI: The `query` argument provided is invalid',\n", " );\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " // logs warning twice in StrictMode\n" ], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 109 }
{{=« »=}} import * as React from 'react'; import { addPropertyControls, ControlType } from 'framer'; // tslint:disable-next-line: ban-ts-ignore // @ts-ignore import Mui«componentName» from '@material-ui/core/«componentName»'; // tslint:disable-next-line: ban-ts-ignore // @ts-ignore import MuiBottomNavigationAction from '@material-ui/core/BottomNavigationAction'; import { Icon } from './Icon'; interface Props { «& tsInterface» } const defaultProps: Props = { «& defaultProps» }; export const «componentName»: React.SFC<Props> = (props: Props) => { const { labels, icons, ...other } = props; // tslint:disable-next-line: ban-ts-ignore // @ts-ignore const [value, setValue] =React.useState(0) const handleChange = (event, value) => { setValue(value); }; const items = icons.length > labels.length ? icons : labels; return ( <MuiBottomNavigation value={value} onChange={handleChange} {...other}> {items.map( (item, index) => (labels[index] !== undefined || icons[index] !== undefined) && ( <MuiBottomNavigationAction key={item} value={index} label={labels[index]} icon={<Icon icon={icons[index] || ''} />} /> ), )} </MuiBottomNavigation> ); } «componentName».defaultProps = defaultProps; addPropertyControls(«componentName», { «& propertyControls» });
framer/scripts/templates/bottom_navigation.txt
0
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.00017446263518650085, 0.00017122196732088923, 0.0001655725500313565, 0.00017259878222830594, 0.0000032838527204148704 ]
{ "id": 8, "code_window": [ " \n", " render(<MyComponent />);\n", "- // logs warning twice in StrictMode\n", "- expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice\n", "+ expect(consoleErrorMock.callCount()).to.equal(1);\n", " expect(consoleErrorMock.messages()[0]).to.include(\n", " 'Material-UI: The `query` argument provided is invalid',\n", " );\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " // logs warning twice in StrictMode\n" ], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 109 }
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"> <rect width="100%" height="100%" fill="#d50000"/> </svg>
docs/public/static/colors-preview/red-A700-24x24.svg
0
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.00017089639732148498, 0.00017089639732148498, 0.00017089639732148498, 0.00017089639732148498, 0 ]
{ "id": 9, "code_window": [ "- expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice\n", "+ expect(consoleErrorMock.callCount()).to.equal(1);\n", " expect(consoleErrorMock.messages()[0]).to.include(\n", " 'Material-UI: The `query` argument provided is invalid',\n", " );\n", " });\n", " });\n", " });" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace" ], "after_edit": [], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 115 }
diff --git a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js index 5e83281c0..3c995f97c 100644 --- a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js +++ b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js @@ -963,7 +963,7 @@ describe('<Autocomplete />', () => { fireEvent.keyDown(textbox, { key: 'Enter' }); expect(handleChange.callCount).to.equal(1); expect(handleChange.args[0][1]).to.equal('a'); - expect(consoleErrorMock.callCount()).to.equal(4); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(3); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: The `getOptionLabel` method of Autocomplete returned undefined instead of a string', ); @@ -993,7 +993,7 @@ describe('<Autocomplete />', () => { />, ); - expect(consoleWarnMock.callCount()).to.equal(4); // strict mode renders twice + expect(consoleWarnMock.callCount()).to.equal(2); expect(consoleWarnMock.messages()[0]).to.include( 'None of the options match with `"not a good value"`', ); @@ -1022,7 +1022,7 @@ describe('<Autocomplete />', () => { const options = getAllByRole('option').map((el) => el.textContent); expect(options).to.have.length(7); expect(options).to.deep.equal(['A', 'D', 'E', 'B', 'G', 'F', 'C']); - expect(consoleWarnMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleWarnMock.callCount()).to.equal(1); expect(consoleWarnMock.messages()[0]).to.include('returns duplicated headers'); }); }); diff --git a/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js b/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js index 5c9d0be26..7f0862466 100644 --- a/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js +++ b/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js @@ -135,7 +135,7 @@ describe('ThemeProvider', () => { <div /> </ThemeProvider>, ); - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include('However, no outer theme is present.'); }); @@ -148,7 +148,7 @@ describe('ThemeProvider', () => { , </ThemeProvider>, ); - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: You should return an object from your theme function', ); diff --git a/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js b/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js index ed0e37f21..49d8ea9b0 100644 --- a/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js +++ b/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js @@ -102,7 +102,7 @@ describe('<Breadcrumbs />', () => { ); expect(getAllByRole('listitem', { hidden: false })).to.have.length(4); expect(getByRole('list')).to.have.text('first/second/third/fourth'); - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: You have provided an invalid combination of props to the Breadcrumbs.\nitemsAfterCollapse={2} + itemsBeforeCollapse={2} >= maxItems={3}', ); diff --git a/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js b/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js index cea126a0d..1eaf80628 100644 --- a/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js +++ b/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js @@ -261,7 +261,7 @@ describe('<TextareaAutosize />', () => { }); forceUpdate(); - expect(consoleErrorMock.callCount()).to.equal(3); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include('Material-UI: Too many re-renders.'); }); }); diff --git a/packages/material-ui/src/internal/SwitchBase.test.js b/packages/material-ui/src/internal/SwitchBase.test.js index 41a38bc07..c9397fd13 100644 --- a/packages/material-ui/src/internal/SwitchBase.test.js +++ b/packages/material-ui/src/internal/SwitchBase.test.js @@ -373,7 +373,7 @@ describe('<SwitchBase />', () => { wrapper.setProps({ checked: true }); expect(consoleErrorMock.callCount()).to.equal(2); expect(consoleErrorMock.messages()[0]).to.include( - 'Warning: A component is changing an uncontrolled input of type checkbox to be controlled.', + 'Warning: A component is changing an uncontrolled input to be controlled.', ); expect(consoleErrorMock.messages()[1]).to.include( 'Material-UI: A component is changing the uncontrolled checked state of SwitchBase to be controlled.', @@ -392,7 +392,7 @@ describe('<SwitchBase />', () => { setProps({ checked: undefined }); expect(consoleErrorMock.callCount()).to.equal(2); expect(consoleErrorMock.messages()[0]).to.include( - 'Warning: A component is changing a controlled input of type checkbox to be uncontrolled.', + 'Warning: A component is changing a controlled input to be uncontrolled.', ); expect(consoleErrorMock.messages()[1]).to.include( 'Material-UI: A component is changing the controlled checked state of SwitchBase to be uncontrolled.', diff --git a/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js b/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js index 68b0a4a5c..e31152c44 100644 --- a/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js +++ b/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js @@ -284,14 +284,10 @@ describe('useMediaQuery', () => { } render(<MyComponent />); - // logs warning twice in StrictMode - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: The `query` argument provided is invalid', ); }); }); });
scripts/react-next.diff
1
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.99456787109375, 0.1675887554883957, 0.00033244671067222953, 0.011554131284356117, 0.33416759967803955 ]
{ "id": 9, "code_window": [ "- expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice\n", "+ expect(consoleErrorMock.callCount()).to.equal(1);\n", " expect(consoleErrorMock.messages()[0]).to.include(\n", " 'Material-UI: The `query` argument provided is invalid',\n", " );\n", " });\n", " });\n", " });" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace" ], "after_edit": [], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 115 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M12.5 6.9c1.78 0 2.44.85 2.5 2.1h2.21c-.07-1.72-1.12-3.3-3.21-3.81V3h-3v2.16c-.53.12-1.03.3-1.48.54l1.47 1.47c.41-.17.91-.27 1.51-.27zM5.33 4.06L4.06 5.33 7.5 8.77c0 2.08 1.56 3.21 3.91 3.91l3.51 3.51c-.34.48-1.05.91-2.42.91-2.06 0-2.87-.92-2.98-2.1h-2.2c.12 2.19 1.76 3.42 3.68 3.83V21h3v-2.15c.96-.18 1.82-.55 2.45-1.12l2.22 2.22 1.27-1.27L5.33 4.06z" /> , 'MoneyOff');
packages/material-ui-icons/src/MoneyOff.js
0
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.0001725011388771236, 0.0001725011388771236, 0.0001725011388771236, 0.0001725011388771236, 0 ]
{ "id": 9, "code_window": [ "- expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice\n", "+ expect(consoleErrorMock.callCount()).to.equal(1);\n", " expect(consoleErrorMock.messages()[0]).to.include(\n", " 'Material-UI: The `query` argument provided is invalid',\n", " );\n", " });\n", " });\n", " });" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace" ], "after_edit": [], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 115 }
export { default } from './SwipeableDrawer';
packages/material-ui/src/SwipeableDrawer/index.js
0
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.0001720336586004123, 0.0001720336586004123, 0.0001720336586004123, 0.0001720336586004123, 0 ]
{ "id": 9, "code_window": [ "- expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice\n", "+ expect(consoleErrorMock.callCount()).to.equal(1);\n", " expect(consoleErrorMock.messages()[0]).to.include(\n", " 'Material-UI: The `query` argument provided is invalid',\n", " );\n", " });\n", " });\n", " });" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace" ], "after_edit": [], "file_path": "scripts/react-next.diff", "type": "replace", "edit_start_line_idx": 115 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M10 18h5v-6h-5v6zm-6 0h5V5H4v13zm12 0h5v-6h-5v6zM10 5v6h11V5H10z" /> , 'ViewQuiltSharp');
packages/material-ui-icons/src/ViewQuiltSharp.js
0
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.0001760266604833305, 0.0001760266604833305, 0.0001760266604833305, 0.0001760266604833305, 0 ]
{ "id": 10, "code_window": [ " packageJson.devDependencies['enzyme-adapter-react-16'] = 'npm:@eps1lon/enzyme-adapter-react-next';\n", "\n", " // add newline for clean diff\n", " fs.writeFileSync(packageJsonPath, `${JSON.stringify(packageJson, null, 2)}${os.EOL}`);\n", "\n", " try {\n", " await exec(`git apply ${path.resolve(__dirname, `./react-${distTag}.diff`)}`);\n", " } catch (error) {\n", " // ignore if the patch doesn't exist\n", " if (error.code !== 128) {\n", " throw error;\n", " }\n", " }\n", "}\n", "\n", "main(process.env.REACT_DIST_TAG).catch((error) => {\n", " console.error(error);\n", " process.exit(1);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " await exec(`git apply ${path.resolve(__dirname, `./react-${distTag}.diff`)}`);\n" ], "file_path": "scripts/use-react-dist-tag.js", "type": "replace", "edit_start_line_idx": 53 }
diff --git a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js index 5e83281c0..3c995f97c 100644 --- a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js +++ b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js @@ -963,7 +963,7 @@ describe('<Autocomplete />', () => { fireEvent.keyDown(textbox, { key: 'Enter' }); expect(handleChange.callCount).to.equal(1); expect(handleChange.args[0][1]).to.equal('a'); - expect(consoleErrorMock.callCount()).to.equal(4); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(3); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: The `getOptionLabel` method of Autocomplete returned undefined instead of a string', ); @@ -993,7 +993,7 @@ describe('<Autocomplete />', () => { />, ); - expect(consoleWarnMock.callCount()).to.equal(4); // strict mode renders twice + expect(consoleWarnMock.callCount()).to.equal(2); expect(consoleWarnMock.messages()[0]).to.include( 'None of the options match with `"not a good value"`', ); @@ -1022,7 +1022,7 @@ describe('<Autocomplete />', () => { const options = getAllByRole('option').map((el) => el.textContent); expect(options).to.have.length(7); expect(options).to.deep.equal(['A', 'D', 'E', 'B', 'G', 'F', 'C']); - expect(consoleWarnMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleWarnMock.callCount()).to.equal(1); expect(consoleWarnMock.messages()[0]).to.include('returns duplicated headers'); }); }); diff --git a/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js b/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js index 5c9d0be26..7f0862466 100644 --- a/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js +++ b/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.test.js @@ -135,7 +135,7 @@ describe('ThemeProvider', () => { <div /> </ThemeProvider>, ); - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include('However, no outer theme is present.'); }); @@ -148,7 +148,7 @@ describe('ThemeProvider', () => { , </ThemeProvider>, ); - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: You should return an object from your theme function', ); diff --git a/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js b/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js index ed0e37f21..49d8ea9b0 100644 --- a/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js +++ b/packages/material-ui/src/Breadcrumbs/Breadcrumbs.test.js @@ -102,7 +102,7 @@ describe('<Breadcrumbs />', () => { ); expect(getAllByRole('listitem', { hidden: false })).to.have.length(4); expect(getByRole('list')).to.have.text('first/second/third/fourth'); - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: You have provided an invalid combination of props to the Breadcrumbs.\nitemsAfterCollapse={2} + itemsBeforeCollapse={2} >= maxItems={3}', ); diff --git a/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js b/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js index cea126a0d..1eaf80628 100644 --- a/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js +++ b/packages/material-ui/src/TextareaAutosize/TextareaAutosize.test.js @@ -261,7 +261,7 @@ describe('<TextareaAutosize />', () => { }); forceUpdate(); - expect(consoleErrorMock.callCount()).to.equal(3); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include('Material-UI: Too many re-renders.'); }); }); diff --git a/packages/material-ui/src/internal/SwitchBase.test.js b/packages/material-ui/src/internal/SwitchBase.test.js index 41a38bc07..c9397fd13 100644 --- a/packages/material-ui/src/internal/SwitchBase.test.js +++ b/packages/material-ui/src/internal/SwitchBase.test.js @@ -373,7 +373,7 @@ describe('<SwitchBase />', () => { wrapper.setProps({ checked: true }); expect(consoleErrorMock.callCount()).to.equal(2); expect(consoleErrorMock.messages()[0]).to.include( - 'Warning: A component is changing an uncontrolled input of type checkbox to be controlled.', + 'Warning: A component is changing an uncontrolled input to be controlled.', ); expect(consoleErrorMock.messages()[1]).to.include( 'Material-UI: A component is changing the uncontrolled checked state of SwitchBase to be controlled.', @@ -392,7 +392,7 @@ describe('<SwitchBase />', () => { setProps({ checked: undefined }); expect(consoleErrorMock.callCount()).to.equal(2); expect(consoleErrorMock.messages()[0]).to.include( - 'Warning: A component is changing a controlled input of type checkbox to be uncontrolled.', + 'Warning: A component is changing a controlled input to be uncontrolled.', ); expect(consoleErrorMock.messages()[1]).to.include( 'Material-UI: A component is changing the controlled checked state of SwitchBase to be uncontrolled.', diff --git a/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js b/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js index 68b0a4a5c..e31152c44 100644 --- a/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js +++ b/packages/material-ui/src/useMediaQuery/useMediaQuery.test.js @@ -284,14 +284,10 @@ describe('useMediaQuery', () => { } render(<MyComponent />); - // logs warning twice in StrictMode - expect(consoleErrorMock.callCount()).to.equal(2); // strict mode renders twice + expect(consoleErrorMock.callCount()).to.equal(1); expect(consoleErrorMock.messages()[0]).to.include( 'Material-UI: The `query` argument provided is invalid', ); }); }); });
scripts/react-next.diff
1
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.0001779304730007425, 0.00017403818492311984, 0.0001681065623415634, 0.00017360327183268964, 0.0000028582282993738772 ]
{ "id": 10, "code_window": [ " packageJson.devDependencies['enzyme-adapter-react-16'] = 'npm:@eps1lon/enzyme-adapter-react-next';\n", "\n", " // add newline for clean diff\n", " fs.writeFileSync(packageJsonPath, `${JSON.stringify(packageJson, null, 2)}${os.EOL}`);\n", "\n", " try {\n", " await exec(`git apply ${path.resolve(__dirname, `./react-${distTag}.diff`)}`);\n", " } catch (error) {\n", " // ignore if the patch doesn't exist\n", " if (error.code !== 128) {\n", " throw error;\n", " }\n", " }\n", "}\n", "\n", "main(process.env.REACT_DIST_TAG).catch((error) => {\n", " console.error(error);\n", " process.exit(1);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " await exec(`git apply ${path.resolve(__dirname, `./react-${distTag}.diff`)}`);\n" ], "file_path": "scripts/use-react-dist-tag.js", "type": "replace", "edit_start_line_idx": 53 }
import React from 'react'; import Button from '@material-ui/core/Button'; import { makeStyles } from '@material-ui/core/styles'; import SnackbarContent from '@material-ui/core/SnackbarContent'; const action = ( <Button color="secondary" size="small"> lorem ipsum dolorem </Button> ); const useStyles = makeStyles((theme) => ({ root: { maxWidth: 600, '& > * + *': { marginTop: theme.spacing(2), }, }, })); export default function LongTextSnackbar() { const classes = useStyles(); return ( <div className={classes.root}> <SnackbarContent message="I love snacks." action={action} /> <SnackbarContent message={ 'I love candy. I love cookies. I love cupcakes. \ I love cheesecake. I love chocolate.' } /> <SnackbarContent message="I love candy. I love cookies. I love cupcakes." action={action} /> <SnackbarContent message={ 'I love candy. I love cookies. I love cupcakes. \ I love cheesecake. I love chocolate.' } action={action} /> </div> ); }
docs/src/pages/components/snackbars/LongTextSnackbar.js
0
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.00017731399566400796, 0.0001734348334139213, 0.00016733667871449143, 0.00017465736891608685, 0.0000034818319818441523 ]
{ "id": 10, "code_window": [ " packageJson.devDependencies['enzyme-adapter-react-16'] = 'npm:@eps1lon/enzyme-adapter-react-next';\n", "\n", " // add newline for clean diff\n", " fs.writeFileSync(packageJsonPath, `${JSON.stringify(packageJson, null, 2)}${os.EOL}`);\n", "\n", " try {\n", " await exec(`git apply ${path.resolve(__dirname, `./react-${distTag}.diff`)}`);\n", " } catch (error) {\n", " // ignore if the patch doesn't exist\n", " if (error.code !== 128) {\n", " throw error;\n", " }\n", " }\n", "}\n", "\n", "main(process.env.REACT_DIST_TAG).catch((error) => {\n", " console.error(error);\n", " process.exit(1);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " await exec(`git apply ${path.resolve(__dirname, `./react-${distTag}.diff`)}`);\n" ], "file_path": "scripts/use-react-dist-tag.js", "type": "replace", "edit_start_line_idx": 53 }
import React from 'react'; import { makeStyles, createStyles, Theme } from '@material-ui/core/styles'; import Grid from '@material-ui/core/Grid'; import Paper from '@material-ui/core/Paper'; import Typography from '@material-ui/core/Typography'; import ButtonBase from '@material-ui/core/ButtonBase'; const useStyles = makeStyles((theme: Theme) => createStyles({ root: { flexGrow: 1, }, paper: { padding: theme.spacing(2), margin: 'auto', maxWidth: 500, }, image: { width: 128, height: 128, }, img: { margin: 'auto', display: 'block', maxWidth: '100%', maxHeight: '100%', }, }), ); export default function ComplexGrid() { const classes = useStyles(); return ( <div className={classes.root}> <Paper className={classes.paper}> <Grid container spacing={2}> <Grid item> <ButtonBase className={classes.image}> <img className={classes.img} alt="complex" src="/static/images/grid/complex.jpg" /> </ButtonBase> </Grid> <Grid item xs={12} sm container> <Grid item xs container direction="column" spacing={2}> <Grid item xs> <Typography gutterBottom variant="subtitle1"> Standard license </Typography> <Typography variant="body2" gutterBottom> Full resolution 1920x1080 • JPEG </Typography> <Typography variant="body2" color="textSecondary"> ID: 1030114 </Typography> </Grid> <Grid item> <Typography variant="body2" style={{ cursor: 'pointer' }}> Remove </Typography> </Grid> </Grid> <Grid item> <Typography variant="subtitle1">$19.00</Typography> </Grid> </Grid> </Grid> </Paper> </div> ); }
docs/src/pages/components/grid/ComplexGrid.tsx
0
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.00017829715216066688, 0.00017366241081617773, 0.00016595126362517476, 0.0001740923908073455, 0.0000036840790471615037 ]
{ "id": 10, "code_window": [ " packageJson.devDependencies['enzyme-adapter-react-16'] = 'npm:@eps1lon/enzyme-adapter-react-next';\n", "\n", " // add newline for clean diff\n", " fs.writeFileSync(packageJsonPath, `${JSON.stringify(packageJson, null, 2)}${os.EOL}`);\n", "\n", " try {\n", " await exec(`git apply ${path.resolve(__dirname, `./react-${distTag}.diff`)}`);\n", " } catch (error) {\n", " // ignore if the patch doesn't exist\n", " if (error.code !== 128) {\n", " throw error;\n", " }\n", " }\n", "}\n", "\n", "main(process.env.REACT_DIST_TAG).catch((error) => {\n", " console.error(error);\n", " process.exit(1);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " await exec(`git apply ${path.resolve(__dirname, `./react-${distTag}.diff`)}`);\n" ], "file_path": "scripts/use-react-dist-tag.js", "type": "replace", "edit_start_line_idx": 53 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M23 18h-1V5c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v13H1c-.55 0-1 .45-1 1s.45 1 1 1h22c.55 0 1-.45 1-1s-.45-1-1-1zm-9.5 0h-3c-.28 0-.5-.22-.5-.5s.22-.5.5-.5h3c.28 0 .5.22.5.5s-.22.5-.5.5zm6.5-3H4V6c0-.55.45-1 1-1h14c.55 0 1 .45 1 1v9z" /> , 'LaptopChromebookRounded');
packages/material-ui-icons/src/LaptopChromebookRounded.js
0
https://github.com/mui/material-ui/commit/151fa8155f1d63bf40174923e8d269f276f0b9b3
[ 0.00016962135850917548, 0.00016962135850917548, 0.00016962135850917548, 0.00016962135850917548, 0 ]
{ "id": 0, "code_window": [ "import { TernarySearchTree } from 'vs/base/common/ternarySearchTree';\n", "import { URI } from 'vs/base/common/uri';\n", "import { localize } from 'vs/nls';\n", "import { CommandsRegistry } from 'vs/platform/commands/common/commands';\n", "import { ConfigurationTarget, IConfigurationService } from 'vs/platform/configuration/common/configuration';\n", "import { ContextKeyExpression, ContextKeyInfo, ContextKeyValue, IContext, IContextKey, IContextKeyChangeEvent, IContextKeyService, IContextKeyServiceTarget, IReadableSet, RawContextKey, SET_CONTEXT_COMMAND_ID } from 'vs/platform/contextkey/common/contextkey';\n", "import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';\n", "\n", "const KEYBINDING_CONTEXT_ATTR = 'data-keybinding-context';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { ContextKeyExpression, ContextKeyInfo, ContextKeyValue, IContext, IContextKey, IContextKeyChangeEvent, IContextKeyService, IContextKeyServiceTarget, IReadableSet, RawContextKey } from 'vs/platform/contextkey/common/contextkey';\n" ], "file_path": "src/vs/platform/contextkey/browser/contextKeyService.ts", "type": "replace", "edit_start_line_idx": 16 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Emitter, Event, PauseableEmitter } from 'vs/base/common/event'; import { Iterable } from 'vs/base/common/iterator'; import { DisposableStore, IDisposable, MutableDisposable } from 'vs/base/common/lifecycle'; import { MarshalledObject } from 'vs/base/common/marshalling'; import { MarshalledId } from 'vs/base/common/marshallingIds'; import { cloneAndChange, distinct } from 'vs/base/common/objects'; import { TernarySearchTree } from 'vs/base/common/ternarySearchTree'; import { URI } from 'vs/base/common/uri'; import { localize } from 'vs/nls'; import { CommandsRegistry } from 'vs/platform/commands/common/commands'; import { ConfigurationTarget, IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { ContextKeyExpression, ContextKeyInfo, ContextKeyValue, IContext, IContextKey, IContextKeyChangeEvent, IContextKeyService, IContextKeyServiceTarget, IReadableSet, RawContextKey, SET_CONTEXT_COMMAND_ID } from 'vs/platform/contextkey/common/contextkey'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; const KEYBINDING_CONTEXT_ATTR = 'data-keybinding-context'; export class Context implements IContext { protected _parent: Context | null; protected _value: Record<string, any>; protected _id: number; constructor(id: number, parent: Context | null) { this._id = id; this._parent = parent; this._value = Object.create(null); this._value['_contextId'] = id; } public get value(): Record<string, any> { return { ...this._value }; } public setValue(key: string, value: any): boolean { // console.log('SET ' + key + ' = ' + value + ' ON ' + this._id); if (this._value[key] !== value) { this._value[key] = value; return true; } return false; } public removeValue(key: string): boolean { // console.log('REMOVE ' + key + ' FROM ' + this._id); if (key in this._value) { delete this._value[key]; return true; } return false; } public getValue<T>(key: string): T | undefined { const ret = this._value[key]; if (typeof ret === 'undefined' && this._parent) { return this._parent.getValue<T>(key); } return ret; } public updateParent(parent: Context): void { this._parent = parent; } public collectAllValues(): Record<string, any> { let result = this._parent ? this._parent.collectAllValues() : Object.create(null); result = { ...result, ...this._value }; delete result['_contextId']; return result; } } class NullContext extends Context { static readonly INSTANCE = new NullContext(); constructor() { super(-1, null); } public override setValue(key: string, value: any): boolean { return false; } public override removeValue(key: string): boolean { return false; } public override getValue<T>(key: string): T | undefined { return undefined; } override collectAllValues(): { [key: string]: any } { return Object.create(null); } } class ConfigAwareContextValuesContainer extends Context { private static readonly _keyPrefix = 'config.'; private readonly _values = TernarySearchTree.forConfigKeys<any>(); private readonly _listener: IDisposable; constructor( id: number, private readonly _configurationService: IConfigurationService, emitter: Emitter<IContextKeyChangeEvent> ) { super(id, null); this._listener = this._configurationService.onDidChangeConfiguration(event => { if (event.source === ConfigurationTarget.DEFAULT) { // new setting, reset everything const allKeys = Array.from(this._values, ([k]) => k); this._values.clear(); emitter.fire(new ArrayContextKeyChangeEvent(allKeys)); } else { const changedKeys: string[] = []; for (const configKey of event.affectedKeys) { const contextKey = `config.${configKey}`; const cachedItems = this._values.findSuperstr(contextKey); if (cachedItems !== undefined) { changedKeys.push(...Iterable.map(cachedItems, ([key]) => key)); this._values.deleteSuperstr(contextKey); } if (this._values.has(contextKey)) { changedKeys.push(contextKey); this._values.delete(contextKey); } } emitter.fire(new ArrayContextKeyChangeEvent(changedKeys)); } }); } dispose(): void { this._listener.dispose(); } override getValue(key: string): any { if (key.indexOf(ConfigAwareContextValuesContainer._keyPrefix) !== 0) { return super.getValue(key); } if (this._values.has(key)) { return this._values.get(key); } const configKey = key.substr(ConfigAwareContextValuesContainer._keyPrefix.length); const configValue = this._configurationService.getValue(configKey); let value: any = undefined; switch (typeof configValue) { case 'number': case 'boolean': case 'string': value = configValue; break; default: if (Array.isArray(configValue)) { value = JSON.stringify(configValue); } else { value = configValue; } } this._values.set(key, value); return value; } override setValue(key: string, value: any): boolean { return super.setValue(key, value); } override removeValue(key: string): boolean { return super.removeValue(key); } override collectAllValues(): { [key: string]: any } { const result: { [key: string]: any } = Object.create(null); this._values.forEach((value, index) => result[index] = value); return { ...result, ...super.collectAllValues() }; } } class ContextKey<T extends ContextKeyValue> implements IContextKey<T> { private _service: AbstractContextKeyService; private _key: string; private _defaultValue: T | undefined; constructor(service: AbstractContextKeyService, key: string, defaultValue: T | undefined) { this._service = service; this._key = key; this._defaultValue = defaultValue; this.reset(); } public set(value: T): void { this._service.setContext(this._key, value); } public reset(): void { if (typeof this._defaultValue === 'undefined') { this._service.removeContext(this._key); } else { this._service.setContext(this._key, this._defaultValue); } } public get(): T | undefined { return this._service.getContextKeyValue<T>(this._key); } } class SimpleContextKeyChangeEvent implements IContextKeyChangeEvent { constructor(readonly key: string) { } affectsSome(keys: IReadableSet<string>): boolean { return keys.has(this.key); } allKeysContainedIn(keys: IReadableSet<string>): boolean { return this.affectsSome(keys); } } class ArrayContextKeyChangeEvent implements IContextKeyChangeEvent { constructor(readonly keys: string[]) { } affectsSome(keys: IReadableSet<string>): boolean { for (const key of this.keys) { if (keys.has(key)) { return true; } } return false; } allKeysContainedIn(keys: IReadableSet<string>): boolean { return this.keys.every(key => keys.has(key)); } } class CompositeContextKeyChangeEvent implements IContextKeyChangeEvent { constructor(readonly events: IContextKeyChangeEvent[]) { } affectsSome(keys: IReadableSet<string>): boolean { for (const e of this.events) { if (e.affectsSome(keys)) { return true; } } return false; } allKeysContainedIn(keys: IReadableSet<string>): boolean { return this.events.every(evt => evt.allKeysContainedIn(keys)); } } function allEventKeysInContext(event: IContextKeyChangeEvent, context: Record<string, any>): boolean { return event.allKeysContainedIn(new Set(Object.keys(context))); } export abstract class AbstractContextKeyService implements IContextKeyService { declare _serviceBrand: undefined; protected _isDisposed: boolean; protected _myContextId: number; protected _onDidChangeContext = new PauseableEmitter<IContextKeyChangeEvent>({ merge: input => new CompositeContextKeyChangeEvent(input) }); readonly onDidChangeContext = this._onDidChangeContext.event; constructor(myContextId: number) { this._isDisposed = false; this._myContextId = myContextId; } public get contextId(): number { return this._myContextId; } abstract dispose(): void; public createKey<T extends ContextKeyValue>(key: string, defaultValue: T | undefined): IContextKey<T> { if (this._isDisposed) { throw new Error(`AbstractContextKeyService has been disposed`); } return new ContextKey(this, key, defaultValue); } bufferChangeEvents(callback: Function): void { this._onDidChangeContext.pause(); try { callback(); } finally { this._onDidChangeContext.resume(); } } public createScoped(domNode: IContextKeyServiceTarget): IContextKeyService { if (this._isDisposed) { throw new Error(`AbstractContextKeyService has been disposed`); } return new ScopedContextKeyService(this, domNode); } createOverlay(overlay: Iterable<[string, any]> = Iterable.empty()): IContextKeyService { if (this._isDisposed) { throw new Error(`AbstractContextKeyService has been disposed`); } return new OverlayContextKeyService(this, overlay); } public contextMatchesRules(rules: ContextKeyExpression | undefined): boolean { if (this._isDisposed) { throw new Error(`AbstractContextKeyService has been disposed`); } const context = this.getContextValuesContainer(this._myContextId); const result = (rules ? rules.evaluate(context) : true); // console.group(rules.serialize() + ' -> ' + result); // rules.keys().forEach(key => { console.log(key, ctx[key]); }); // console.groupEnd(); return result; } public getContextKeyValue<T>(key: string): T | undefined { if (this._isDisposed) { return undefined; } return this.getContextValuesContainer(this._myContextId).getValue<T>(key); } public setContext(key: string, value: any): void { if (this._isDisposed) { return; } const myContext = this.getContextValuesContainer(this._myContextId); if (!myContext) { return; } if (myContext.setValue(key, value)) { this._onDidChangeContext.fire(new SimpleContextKeyChangeEvent(key)); } } public removeContext(key: string): void { if (this._isDisposed) { return; } if (this.getContextValuesContainer(this._myContextId).removeValue(key)) { this._onDidChangeContext.fire(new SimpleContextKeyChangeEvent(key)); } } public getContext(target: IContextKeyServiceTarget | null): IContext { if (this._isDisposed) { return NullContext.INSTANCE; } return this.getContextValuesContainer(findContextAttr(target)); } public abstract getContextValuesContainer(contextId: number): Context; public abstract createChildContext(parentContextId?: number): number; public abstract disposeContext(contextId: number): void; public abstract updateParent(parentContextKeyService?: IContextKeyService): void; } export class ContextKeyService extends AbstractContextKeyService implements IContextKeyService { private _lastContextId: number; private readonly _contexts = new Map<number, Context>(); private readonly _toDispose = new DisposableStore(); constructor(@IConfigurationService configurationService: IConfigurationService) { super(0); this._lastContextId = 0; const myContext = new ConfigAwareContextValuesContainer(this._myContextId, configurationService, this._onDidChangeContext); this._contexts.set(this._myContextId, myContext); this._toDispose.add(myContext); // Uncomment this to see the contexts continuously logged // let lastLoggedValue: string | null = null; // setInterval(() => { // let values = Object.keys(this._contexts).map((key) => this._contexts[key]); // let logValue = values.map(v => JSON.stringify(v._value, null, '\t')).join('\n'); // if (lastLoggedValue !== logValue) { // lastLoggedValue = logValue; // console.log(lastLoggedValue); // } // }, 2000); } public dispose(): void { this._onDidChangeContext.dispose(); this._isDisposed = true; this._toDispose.dispose(); } public getContextValuesContainer(contextId: number): Context { if (this._isDisposed) { return NullContext.INSTANCE; } return this._contexts.get(contextId) || NullContext.INSTANCE; } public createChildContext(parentContextId: number = this._myContextId): number { if (this._isDisposed) { throw new Error(`ContextKeyService has been disposed`); } const id = (++this._lastContextId); this._contexts.set(id, new Context(id, this.getContextValuesContainer(parentContextId))); return id; } public disposeContext(contextId: number): void { if (!this._isDisposed) { this._contexts.delete(contextId); } } public updateParent(_parentContextKeyService: IContextKeyService): void { throw new Error('Cannot update parent of root ContextKeyService'); } } class ScopedContextKeyService extends AbstractContextKeyService { private _parent: AbstractContextKeyService; private _domNode: IContextKeyServiceTarget; private readonly _parentChangeListener = new MutableDisposable(); constructor(parent: AbstractContextKeyService, domNode: IContextKeyServiceTarget) { super(parent.createChildContext()); this._parent = parent; this._updateParentChangeListener(); this._domNode = domNode; if (this._domNode.hasAttribute(KEYBINDING_CONTEXT_ATTR)) { let extraInfo = ''; if ((this._domNode as HTMLElement).classList) { extraInfo = Array.from((this._domNode as HTMLElement).classList.values()).join(', '); } console.error(`Element already has context attribute${extraInfo ? ': ' + extraInfo : ''}`); } this._domNode.setAttribute(KEYBINDING_CONTEXT_ATTR, String(this._myContextId)); } private _updateParentChangeListener(): void { // Forward parent events to this listener. Parent will change. this._parentChangeListener.value = this._parent.onDidChangeContext(e => { const thisContainer = this._parent.getContextValuesContainer(this._myContextId); const thisContextValues = thisContainer.value; if (!allEventKeysInContext(e, thisContextValues)) { this._onDidChangeContext.fire(e); } }); } public dispose(): void { if (this._isDisposed) { return; } this._onDidChangeContext.dispose(); this._parent.disposeContext(this._myContextId); this._parentChangeListener.dispose(); this._domNode.removeAttribute(KEYBINDING_CONTEXT_ATTR); this._isDisposed = true; } public getContextValuesContainer(contextId: number): Context { if (this._isDisposed) { return NullContext.INSTANCE; } return this._parent.getContextValuesContainer(contextId); } public createChildContext(parentContextId: number = this._myContextId): number { if (this._isDisposed) { throw new Error(`ScopedContextKeyService has been disposed`); } return this._parent.createChildContext(parentContextId); } public disposeContext(contextId: number): void { if (this._isDisposed) { return; } this._parent.disposeContext(contextId); } public updateParent(parentContextKeyService: AbstractContextKeyService): void { const thisContainer = this._parent.getContextValuesContainer(this._myContextId); const oldAllValues = thisContainer.collectAllValues(); this._parent = parentContextKeyService; this._updateParentChangeListener(); const newParentContainer = this._parent.getContextValuesContainer(this._parent.contextId); thisContainer.updateParent(newParentContainer); const newAllValues = thisContainer.collectAllValues(); const allValuesDiff = { ...distinct(oldAllValues, newAllValues), ...distinct(newAllValues, oldAllValues) }; const changedKeys = Object.keys(allValuesDiff); this._onDidChangeContext.fire(new ArrayContextKeyChangeEvent(changedKeys)); } } class OverlayContext implements IContext { constructor(private parent: IContext, private overlay: ReadonlyMap<string, any>) { } getValue<T>(key: string): T | undefined { return this.overlay.has(key) ? this.overlay.get(key) : this.parent.getValue(key); } } class OverlayContextKeyService implements IContextKeyService { declare _serviceBrand: undefined; private overlay: Map<string, any>; get contextId(): number { return this.parent.contextId; } get onDidChangeContext(): Event<IContextKeyChangeEvent> { return this.parent.onDidChangeContext; } constructor(private parent: AbstractContextKeyService | OverlayContextKeyService, overlay: Iterable<[string, any]>) { this.overlay = new Map(overlay); } bufferChangeEvents(callback: Function): void { this.parent.bufferChangeEvents(callback); } createKey<T extends ContextKeyValue>(): IContextKey<T> { throw new Error('Not supported.'); } getContext(target: IContextKeyServiceTarget | null): IContext { return new OverlayContext(this.parent.getContext(target), this.overlay); } getContextValuesContainer(contextId: number): IContext { const parentContext = this.parent.getContextValuesContainer(contextId); return new OverlayContext(parentContext, this.overlay); } contextMatchesRules(rules: ContextKeyExpression | undefined): boolean { const context = this.getContextValuesContainer(this.contextId); const result = (rules ? rules.evaluate(context) : true); return result; } getContextKeyValue<T>(key: string): T | undefined { return this.overlay.has(key) ? this.overlay.get(key) : this.parent.getContextKeyValue(key); } createScoped(): IContextKeyService { throw new Error('Not supported.'); } createOverlay(overlay: Iterable<[string, any]> = Iterable.empty()): IContextKeyService { return new OverlayContextKeyService(this, overlay); } updateParent(): void { throw new Error('Not supported.'); } dispose(): void { // noop } } function findContextAttr(domNode: IContextKeyServiceTarget | null): number { while (domNode) { if (domNode.hasAttribute(KEYBINDING_CONTEXT_ATTR)) { const attr = domNode.getAttribute(KEYBINDING_CONTEXT_ATTR); if (attr) { return parseInt(attr, 10); } return NaN; } domNode = domNode.parentElement; } return 0; } export function setContext(accessor: ServicesAccessor, contextKey: any, contextValue: any) { const contextKeyService = accessor.get(IContextKeyService); contextKeyService.createKey(String(contextKey), stringifyURIs(contextValue)); } function stringifyURIs(contextValue: any): any { return cloneAndChange(contextValue, (obj) => { if (typeof obj === 'object' && (<MarshalledObject>obj).$mid === MarshalledId.Uri) { return URI.revive(obj).toString(); } if (obj instanceof URI) { return obj.toString(); } return undefined; }); } CommandsRegistry.registerCommand(SET_CONTEXT_COMMAND_ID, setContext); CommandsRegistry.registerCommand({ id: 'getContextKeyInfo', handler() { return [...RawContextKey.all()].sort((a, b) => a.key.localeCompare(b.key)); }, description: { description: localize('getContextKeyInfo', "A command that returns information about context keys"), args: [] } }); CommandsRegistry.registerCommand('_generateContextKeyInfo', function () { const result: ContextKeyInfo[] = []; const seen = new Set<string>(); for (const info of RawContextKey.all()) { if (!seen.has(info.key)) { seen.add(info.key); result.push(info); } } result.sort((a, b) => a.key.localeCompare(b.key)); console.log(JSON.stringify(result, undefined, 2)); });
src/vs/platform/contextkey/browser/contextKeyService.ts
1
https://github.com/microsoft/vscode/commit/bafda10a370cd7ac835c4a88f5885bf69e02037e
[ 0.9990204572677612, 0.07759155333042145, 0.0001634587679291144, 0.00018462973821442574, 0.2659190595149994 ]
{ "id": 0, "code_window": [ "import { TernarySearchTree } from 'vs/base/common/ternarySearchTree';\n", "import { URI } from 'vs/base/common/uri';\n", "import { localize } from 'vs/nls';\n", "import { CommandsRegistry } from 'vs/platform/commands/common/commands';\n", "import { ConfigurationTarget, IConfigurationService } from 'vs/platform/configuration/common/configuration';\n", "import { ContextKeyExpression, ContextKeyInfo, ContextKeyValue, IContext, IContextKey, IContextKeyChangeEvent, IContextKeyService, IContextKeyServiceTarget, IReadableSet, RawContextKey, SET_CONTEXT_COMMAND_ID } from 'vs/platform/contextkey/common/contextkey';\n", "import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';\n", "\n", "const KEYBINDING_CONTEXT_ATTR = 'data-keybinding-context';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { ContextKeyExpression, ContextKeyInfo, ContextKeyValue, IContext, IContextKey, IContextKeyChangeEvent, IContextKeyService, IContextKeyServiceTarget, IReadableSet, RawContextKey } from 'vs/platform/contextkey/common/contextkey';\n" ], "file_path": "src/vs/platform/contextkey/browser/contextKeyService.ts", "type": "replace", "edit_start_line_idx": 16 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { app, AuthenticationResponseDetails, AuthInfo, Event as ElectronEvent, WebContents } from 'electron'; import { CancellationToken } from 'vs/base/common/cancellation'; import { Event } from 'vs/base/common/event'; import { hash } from 'vs/base/common/hash'; import { Disposable } from 'vs/base/common/lifecycle'; import { generateUuid } from 'vs/base/common/uuid'; import { ICredentialsMainService } from 'vs/platform/credentials/common/credentials'; import { IEncryptionMainService } from 'vs/platform/encryption/common/encryptionService'; import { ILogService } from 'vs/platform/log/common/log'; import { IProductService } from 'vs/platform/product/common/productService'; import { IWindowsMainService } from 'vs/platform/windows/electron-main/windows'; interface ElectronAuthenticationResponseDetails extends AuthenticationResponseDetails { firstAuthAttempt?: boolean; // https://github.com/electron/electron/blob/84a42a050e7d45225e69df5bd2d2bf9f1037ea41/shell/browser/login_handler.cc#L70 } type LoginEvent = { event: ElectronEvent; authInfo: AuthInfo; req: ElectronAuthenticationResponseDetails; callback: (username?: string, password?: string) => void; }; type Credentials = { username: string; password: string; }; enum ProxyAuthState { /** * Initial state: we will try to use stored credentials * first to reply to the auth challenge. */ Initial = 1, /** * We used stored credentials and are still challenged, * so we will show a login dialog next. */ StoredCredentialsUsed, /** * Finally, if we showed a login dialog already, we will * not show any more login dialogs until restart to reduce * the UI noise. */ LoginDialogShown } export class ProxyAuthHandler extends Disposable { private readonly PROXY_CREDENTIALS_SERVICE_KEY = `${this.productService.urlProtocol}.proxy-credentials`; private pendingProxyResolve: Promise<Credentials | undefined> | undefined = undefined; private state = ProxyAuthState.Initial; private sessionCredentials: Credentials | undefined = undefined; constructor( @ILogService private readonly logService: ILogService, @IWindowsMainService private readonly windowsMainService: IWindowsMainService, @ICredentialsMainService private readonly credentialsService: ICredentialsMainService, @IEncryptionMainService private readonly encryptionMainService: IEncryptionMainService, @IProductService private readonly productService: IProductService ) { super(); this.registerListeners(); } private registerListeners(): void { const onLogin = Event.fromNodeEventEmitter<LoginEvent>(app, 'login', (event: ElectronEvent, webContents: WebContents, req: ElectronAuthenticationResponseDetails, authInfo: AuthInfo, callback) => ({ event, webContents, req, authInfo, callback })); this._register(onLogin(this.onLogin, this)); } private async onLogin({ event, authInfo, req, callback }: LoginEvent): Promise<void> { if (!authInfo.isProxy) { return; // only for proxy } if (!this.pendingProxyResolve && this.state === ProxyAuthState.LoginDialogShown && req.firstAuthAttempt) { this.logService.trace('auth#onLogin (proxy) - exit - proxy dialog already shown'); return; // only one dialog per session at max (except when firstAuthAttempt: false which indicates a login problem) } // Signal we handle this event on our own, otherwise // Electron will ignore our provided credentials. event.preventDefault(); let credentials: Credentials | undefined = undefined; if (!this.pendingProxyResolve) { this.logService.trace('auth#onLogin (proxy) - no pending proxy handling found, starting new'); this.pendingProxyResolve = this.resolveProxyCredentials(authInfo); try { credentials = await this.pendingProxyResolve; } finally { this.pendingProxyResolve = undefined; } } else { this.logService.trace('auth#onLogin (proxy) - pending proxy handling found'); credentials = await this.pendingProxyResolve; } // According to Electron docs, it is fine to call back without // username or password to signal that the authentication was handled // by us, even though without having credentials received: // // > If `callback` is called without a username or password, the authentication // > request will be cancelled and the authentication error will be returned to the // > page. callback(credentials?.username, credentials?.password); } private async resolveProxyCredentials(authInfo: AuthInfo): Promise<Credentials | undefined> { this.logService.trace('auth#resolveProxyCredentials (proxy) - enter'); try { const credentials = await this.doResolveProxyCredentials(authInfo); if (credentials) { this.logService.trace('auth#resolveProxyCredentials (proxy) - got credentials'); return credentials; } else { this.logService.trace('auth#resolveProxyCredentials (proxy) - did not get credentials'); } } finally { this.logService.trace('auth#resolveProxyCredentials (proxy) - exit'); } return undefined; } private async doResolveProxyCredentials(authInfo: AuthInfo): Promise<Credentials | undefined> { this.logService.trace('auth#doResolveProxyCredentials - enter', authInfo); // Compute a hash over the authentication info to be used // with the credentials store to return the right credentials // given the properties of the auth request // (see https://github.com/microsoft/vscode/issues/109497) const authInfoHash = String(hash({ scheme: authInfo.scheme, host: authInfo.host, port: authInfo.port })); // Find any previously stored credentials let storedUsername: string | undefined = undefined; let storedPassword: string | undefined = undefined; try { const encryptedSerializedProxyCredentials = await this.credentialsService.getPassword(this.PROXY_CREDENTIALS_SERVICE_KEY, authInfoHash); if (encryptedSerializedProxyCredentials) { const credentials: Credentials = JSON.parse(await this.encryptionMainService.decrypt(encryptedSerializedProxyCredentials)); storedUsername = credentials.username; storedPassword = credentials.password; } } catch (error) { this.logService.error(error); // handle errors by asking user for login via dialog } // Reply with stored credentials unless we used them already. // In that case we need to show a login dialog again because // they seem invalid. if (this.state !== ProxyAuthState.StoredCredentialsUsed && typeof storedUsername === 'string' && typeof storedPassword === 'string') { this.logService.trace('auth#doResolveProxyCredentials (proxy) - exit - found stored credentials to use'); this.state = ProxyAuthState.StoredCredentialsUsed; return { username: storedUsername, password: storedPassword }; } // Find suitable window to show dialog: prefer to show it in the // active window because any other network request will wait on // the credentials and we want the user to present the dialog. const window = this.windowsMainService.getFocusedWindow() || this.windowsMainService.getLastActiveWindow(); if (!window) { this.logService.trace('auth#doResolveProxyCredentials (proxy) - exit - no opened window found to show dialog in'); return undefined; // unexpected } this.logService.trace(`auth#doResolveProxyCredentials (proxy) - asking window ${window.id} to handle proxy login`); // Open proxy dialog const payload = { authInfo, username: this.sessionCredentials?.username ?? storedUsername, // prefer to show already used username (if any) over stored password: this.sessionCredentials?.password ?? storedPassword, // prefer to show already used password (if any) over stored replyChannel: `vscode:proxyAuthResponse:${generateUuid()}` }; window.sendWhenReady('vscode:openProxyAuthenticationDialog', CancellationToken.None, payload); this.state = ProxyAuthState.LoginDialogShown; // Handle reply const loginDialogCredentials = await new Promise<Credentials | undefined>(resolve => { const proxyAuthResponseHandler = async (event: ElectronEvent, channel: string, reply: Credentials & { remember: boolean } | undefined /* canceled */) => { if (channel === payload.replyChannel) { this.logService.trace(`auth#doResolveProxyCredentials - exit - received credentials from window ${window.id}`); window.win?.webContents.off('ipc-message', proxyAuthResponseHandler); // We got credentials from the window if (reply) { const credentials: Credentials = { username: reply.username, password: reply.password }; // Update stored credentials based on `remember` flag try { if (reply.remember) { const encryptedSerializedCredentials = await this.encryptionMainService.encrypt(JSON.stringify(credentials)); await this.credentialsService.setPassword(this.PROXY_CREDENTIALS_SERVICE_KEY, authInfoHash, encryptedSerializedCredentials); } else { await this.credentialsService.deletePassword(this.PROXY_CREDENTIALS_SERVICE_KEY, authInfoHash); } } catch (error) { this.logService.error(error); // handle gracefully } resolve({ username: credentials.username, password: credentials.password }); } // We did not get any credentials from the window (e.g. cancelled) else { resolve(undefined); } } }; window.win?.webContents.on('ipc-message', proxyAuthResponseHandler); }); // Remember credentials for the session in case // the credentials are wrong and we show the dialog // again this.sessionCredentials = loginDialogCredentials; return loginDialogCredentials; } }
src/vs/code/electron-main/auth.ts
0
https://github.com/microsoft/vscode/commit/bafda10a370cd7ac835c4a88f5885bf69e02037e
[ 0.00017578480765223503, 0.00016956902982201427, 0.00016337291162926704, 0.0001695514947641641, 0.0000029925281523901504 ]
{ "id": 0, "code_window": [ "import { TernarySearchTree } from 'vs/base/common/ternarySearchTree';\n", "import { URI } from 'vs/base/common/uri';\n", "import { localize } from 'vs/nls';\n", "import { CommandsRegistry } from 'vs/platform/commands/common/commands';\n", "import { ConfigurationTarget, IConfigurationService } from 'vs/platform/configuration/common/configuration';\n", "import { ContextKeyExpression, ContextKeyInfo, ContextKeyValue, IContext, IContextKey, IContextKeyChangeEvent, IContextKeyService, IContextKeyServiceTarget, IReadableSet, RawContextKey, SET_CONTEXT_COMMAND_ID } from 'vs/platform/contextkey/common/contextkey';\n", "import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';\n", "\n", "const KEYBINDING_CONTEXT_ATTR = 'data-keybinding-context';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { ContextKeyExpression, ContextKeyInfo, ContextKeyValue, IContext, IContextKey, IContextKeyChangeEvent, IContextKeyService, IContextKeyServiceTarget, IReadableSet, RawContextKey } from 'vs/platform/contextkey/common/contextkey';\n" ], "file_path": "src/vs/platform/contextkey/browser/contextKeyService.ts", "type": "replace", "edit_start_line_idx": 16 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Disposable } from 'vs/base/common/lifecycle'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { IProductService } from 'vs/platform/product/common/productService'; import { ClassifiedEvent, IGDPRProperty, OmitMetadata, StrictPropertyCheck } from 'vs/platform/telemetry/common/gdprTypings'; import { ITelemetryService, TelemetryLevel, TELEMETRY_OLD_SETTING_ID, TELEMETRY_SETTING_ID } from 'vs/platform/telemetry/common/telemetry'; import { isLoggingOnly, supportsTelemetry } from 'vs/platform/telemetry/common/telemetryUtils'; import { extHostNamedCustomer, IExtHostContext } from 'vs/workbench/services/extensions/common/extHostCustomers'; import { ExtHostContext, ExtHostTelemetryShape, MainContext, MainThreadTelemetryShape } from '../common/extHost.protocol'; @extHostNamedCustomer(MainContext.MainThreadTelemetry) export class MainThreadTelemetry extends Disposable implements MainThreadTelemetryShape { private readonly _proxy: ExtHostTelemetryShape; private static readonly _name = 'pluginHostTelemetry'; constructor( extHostContext: IExtHostContext, @ITelemetryService private readonly _telemetryService: ITelemetryService, @IConfigurationService private readonly _configurationService: IConfigurationService, @IEnvironmentService private readonly _environmentService: IEnvironmentService, @IProductService private readonly _productService: IProductService, ) { super(); this._proxy = extHostContext.getProxy(ExtHostContext.ExtHostTelemetry); if (supportsTelemetry(this._productService, this._environmentService)) { this._register(this._configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration(TELEMETRY_SETTING_ID) || e.affectsConfiguration(TELEMETRY_OLD_SETTING_ID)) { this._proxy.$onDidChangeTelemetryLevel(this.telemetryLevel); } })); } const loggingOnly = isLoggingOnly(this._productService, this._environmentService); this._proxy.$initializeTelemetryLevel(this.telemetryLevel, loggingOnly, this._productService.enabledTelemetryLevels); } private get telemetryLevel(): TelemetryLevel { if (!supportsTelemetry(this._productService, this._environmentService)) { return TelemetryLevel.NONE; } return this._telemetryService.telemetryLevel; } $publicLog(eventName: string, data: any = Object.create(null)): void { // __GDPR__COMMON__ "pluginHostTelemetry" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } data[MainThreadTelemetry._name] = true; this._telemetryService.publicLog(eventName, data); } $publicLog2<E extends ClassifiedEvent<OmitMetadata<T>> = never, T extends IGDPRProperty = never>(eventName: string, data?: StrictPropertyCheck<T, E>): void { this.$publicLog(eventName, data as any); } }
src/vs/workbench/api/browser/mainThreadTelemetry.ts
0
https://github.com/microsoft/vscode/commit/bafda10a370cd7ac835c4a88f5885bf69e02037e
[ 0.00017787229444365948, 0.00016855169087648392, 0.0001642582647036761, 0.00016767640772741288, 0.000004096514203411061 ]
{ "id": 0, "code_window": [ "import { TernarySearchTree } from 'vs/base/common/ternarySearchTree';\n", "import { URI } from 'vs/base/common/uri';\n", "import { localize } from 'vs/nls';\n", "import { CommandsRegistry } from 'vs/platform/commands/common/commands';\n", "import { ConfigurationTarget, IConfigurationService } from 'vs/platform/configuration/common/configuration';\n", "import { ContextKeyExpression, ContextKeyInfo, ContextKeyValue, IContext, IContextKey, IContextKeyChangeEvent, IContextKeyService, IContextKeyServiceTarget, IReadableSet, RawContextKey, SET_CONTEXT_COMMAND_ID } from 'vs/platform/contextkey/common/contextkey';\n", "import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';\n", "\n", "const KEYBINDING_CONTEXT_ATTR = 'data-keybinding-context';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { ContextKeyExpression, ContextKeyInfo, ContextKeyValue, IContext, IContextKey, IContextKeyChangeEvent, IContextKeyService, IContextKeyServiceTarget, IReadableSet, RawContextKey } from 'vs/platform/contextkey/common/contextkey';\n" ], "file_path": "src/vs/platform/contextkey/browser/contextKeyService.ts", "type": "replace", "edit_start_line_idx": 16 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { Range } from 'vs/editor/common/core/range'; import { LineRangeMapping, RangeMapping } from 'vs/editor/common/diff/linesDiffComputer'; import { lineRangeMappingFromRangeMappings, StandardLinesDiffComputer } from 'vs/editor/common/diff/standardLinesDiffComputer'; suite('standardLinesDiffCompute', () => { test('1', () => { assert.deepStrictEqual( toJson( lineRangeMappingFromRangeMappings([ new RangeMapping(r([1, 1, 1, 1]), r([1, 1, 1, 2])), ]) ), (["{[1,2)->[1,2)}"]) ); }); test('2', () => { assert.deepStrictEqual( toJson( lineRangeMappingFromRangeMappings([ new RangeMapping(r([1, 1, 1, 2]), r([1, 1, 1, 1])), ]) ), (["{[1,2)->[1,2)}"]) ); }); test('3', () => { assert.deepStrictEqual( toJson( lineRangeMappingFromRangeMappings([ new RangeMapping(r([1, 1, 2, 1]), r([1, 1, 1, 1])), ]) ), (["{[1,2)->[1,1)}"]) ); }); test('4', () => { assert.deepStrictEqual( toJson( lineRangeMappingFromRangeMappings([ new RangeMapping(r([1, 1, 1, 1]), r([1, 1, 2, 1])), ]) ), (["{[1,1)->[1,2)}"]) ); }); test('Suboptimal Diff (needs improving)', () => { const c = new StandardLinesDiffComputer(); const lines1 = ` FirstKeyword = BreakKeyword, LastKeyword = StringKeyword, FirstFutureReservedWord = ImplementsKeyword, LastFutureReservedWord = YieldKeyword } `.split('\n'); const lines2 = ` FirstKeyword = BreakKeyword, LastKeyword = StringKeyword, FirstFutureReservedWord = ImplementsKeyword, LastFutureReservedWord = YieldKeyword, FirstTypeNode = TypeReference, LastTypeNode = ArrayType } `.split('\n'); const diff = c.computeDiff(lines1, lines2, { maxComputationTimeMs: 1000, ignoreTrimWhitespace: false }); // TODO this diff should only have one inner, not two. assert.deepStrictEqual( toJsonWithDetails(diff.changes), [ { main: "{[5,6)->[5,8)}", inner: [ "{[5,41 -> 5,41]->[5,41 -> 7,28]}" ] } ] ); }); }); function r(values: [startLineNumber: number, startColumn: number, endLineNumber: number, endColumn: number]): Range { return new Range(values[0], values[1], values[2], values[3]); } function toJson(mappings: LineRangeMapping[]): unknown { return mappings.map(m => m.toString()); } function toJsonWithDetails(mappings: LineRangeMapping[]): unknown { return mappings.map(m => { return { main: m.toString(), inner: m.innerChanges?.map(c => c.toString()) }; }); }
src/vs/editor/test/common/diff/standardLinesDiffCompute.test.ts
0
https://github.com/microsoft/vscode/commit/bafda10a370cd7ac835c4a88f5885bf69e02037e
[ 0.0001757169229676947, 0.0001720288855722174, 0.00016783364117145538, 0.00017196380940731615, 0.0000023748680177959614 ]
{ "id": 1, "code_window": [ "\t\treturn undefined;\n", "\t});\n", "}\n", "\n", "CommandsRegistry.registerCommand(SET_CONTEXT_COMMAND_ID, setContext);\n", "\n", "CommandsRegistry.registerCommand({\n", "\tid: 'getContextKeyInfo',\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "CommandsRegistry.registerCommand('_setContext', setContext);\n" ], "file_path": "src/vs/platform/contextkey/browser/contextKeyService.ts", "type": "replace", "edit_start_line_idx": 621 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Event } from 'vs/base/common/event'; import { isChrome, isEdge, isFirefox, isLinux, isMacintosh, isSafari, isWeb, isWindows } from 'vs/base/common/platform'; import { isFalsyOrWhitespace } from 'vs/base/common/strings'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; const CONSTANT_VALUES = new Map<string, boolean>(); CONSTANT_VALUES.set('false', false); CONSTANT_VALUES.set('true', true); CONSTANT_VALUES.set('isMac', isMacintosh); CONSTANT_VALUES.set('isLinux', isLinux); CONSTANT_VALUES.set('isWindows', isWindows); CONSTANT_VALUES.set('isWeb', isWeb); CONSTANT_VALUES.set('isMacNative', isMacintosh && !isWeb); CONSTANT_VALUES.set('isEdge', isEdge); CONSTANT_VALUES.set('isFirefox', isFirefox); CONSTANT_VALUES.set('isChrome', isChrome); CONSTANT_VALUES.set('isSafari', isSafari); const hasOwnProperty = Object.prototype.hasOwnProperty; export const enum ContextKeyExprType { False = 0, True = 1, Defined = 2, Not = 3, Equals = 4, NotEquals = 5, And = 6, Regex = 7, NotRegex = 8, Or = 9, In = 10, NotIn = 11, Greater = 12, GreaterEquals = 13, Smaller = 14, SmallerEquals = 15, } export interface IContextKeyExprMapper { mapDefined(key: string): ContextKeyExpression; mapNot(key: string): ContextKeyExpression; mapEquals(key: string, value: any): ContextKeyExpression; mapNotEquals(key: string, value: any): ContextKeyExpression; mapGreater(key: string, value: any): ContextKeyExpression; mapGreaterEquals(key: string, value: any): ContextKeyExpression; mapSmaller(key: string, value: any): ContextKeyExpression; mapSmallerEquals(key: string, value: any): ContextKeyExpression; mapRegex(key: string, regexp: RegExp | null): ContextKeyRegexExpr; mapIn(key: string, valueKey: string): ContextKeyInExpr; mapNotIn(key: string, valueKey: string): ContextKeyNotInExpr; } export interface IContextKeyExpression { cmp(other: ContextKeyExpression): number; equals(other: ContextKeyExpression): boolean; substituteConstants(): ContextKeyExpression | undefined; evaluate(context: IContext): boolean; serialize(): string; keys(): string[]; map(mapFnc: IContextKeyExprMapper): ContextKeyExpression; negate(): ContextKeyExpression; } export type ContextKeyExpression = ( ContextKeyFalseExpr | ContextKeyTrueExpr | ContextKeyDefinedExpr | ContextKeyNotExpr | ContextKeyEqualsExpr | ContextKeyNotEqualsExpr | ContextKeyRegexExpr | ContextKeyNotRegexExpr | ContextKeyAndExpr | ContextKeyOrExpr | ContextKeyInExpr | ContextKeyNotInExpr | ContextKeyGreaterExpr | ContextKeyGreaterEqualsExpr | ContextKeySmallerExpr | ContextKeySmallerEqualsExpr ); export abstract class ContextKeyExpr { public static false(): ContextKeyExpression { return ContextKeyFalseExpr.INSTANCE; } public static true(): ContextKeyExpression { return ContextKeyTrueExpr.INSTANCE; } public static has(key: string): ContextKeyExpression { return ContextKeyDefinedExpr.create(key); } public static equals(key: string, value: any): ContextKeyExpression { return ContextKeyEqualsExpr.create(key, value); } public static notEquals(key: string, value: any): ContextKeyExpression { return ContextKeyNotEqualsExpr.create(key, value); } public static regex(key: string, value: RegExp): ContextKeyExpression { return ContextKeyRegexExpr.create(key, value); } public static in(key: string, value: string): ContextKeyExpression { return ContextKeyInExpr.create(key, value); } public static notIn(key: string, value: string): ContextKeyExpression { return ContextKeyNotInExpr.create(key, value); } public static not(key: string): ContextKeyExpression { return ContextKeyNotExpr.create(key); } public static and(...expr: Array<ContextKeyExpression | undefined | null>): ContextKeyExpression | undefined { return ContextKeyAndExpr.create(expr, null, true); } public static or(...expr: Array<ContextKeyExpression | undefined | null>): ContextKeyExpression | undefined { return ContextKeyOrExpr.create(expr, null, true); } public static greater(key: string, value: number): ContextKeyExpression { return ContextKeyGreaterExpr.create(key, value); } public static greaterEquals(key: string, value: number): ContextKeyExpression { return ContextKeyGreaterEqualsExpr.create(key, value); } public static smaller(key: string, value: number): ContextKeyExpression { return ContextKeySmallerExpr.create(key, value); } public static smallerEquals(key: string, value: number): ContextKeyExpression { return ContextKeySmallerEqualsExpr.create(key, value); } public static deserialize(serialized: string | null | undefined, strict: boolean = false): ContextKeyExpression | undefined { if (!serialized) { return undefined; } return this._deserializeOrExpression(serialized, strict); } private static _deserializeOrExpression(serialized: string, strict: boolean): ContextKeyExpression | undefined { const pieces = serialized.split('||'); return ContextKeyOrExpr.create(pieces.map(p => this._deserializeAndExpression(p, strict)), null, true); } private static _deserializeAndExpression(serialized: string, strict: boolean): ContextKeyExpression | undefined { const pieces = serialized.split('&&'); return ContextKeyAndExpr.create(pieces.map(p => this._deserializeOne(p, strict)), null, true); } private static _deserializeOne(serializedOne: string, strict: boolean): ContextKeyExpression { serializedOne = serializedOne.trim(); if (serializedOne.indexOf('!=') >= 0) { const pieces = serializedOne.split('!='); return ContextKeyNotEqualsExpr.create(pieces[0].trim(), this._deserializeValue(pieces[1], strict)); } if (serializedOne.indexOf('==') >= 0) { const pieces = serializedOne.split('=='); return ContextKeyEqualsExpr.create(pieces[0].trim(), this._deserializeValue(pieces[1], strict)); } if (serializedOne.indexOf('=~') >= 0) { const pieces = serializedOne.split('=~'); return ContextKeyRegexExpr.create(pieces[0].trim(), this._deserializeRegexValue(pieces[1], strict)); } if (serializedOne.indexOf(' not in ') >= 0) { const pieces = serializedOne.split(' not in '); return ContextKeyNotInExpr.create(pieces[0].trim(), this._deserializeValue(pieces[1], strict)); } if (serializedOne.indexOf(' in ') >= 0) { const pieces = serializedOne.split(' in '); return ContextKeyInExpr.create(pieces[0].trim(), this._deserializeValue(pieces[1], strict)); } if (/^[^<=>]+>=[^<=>]+$/.test(serializedOne)) { const pieces = serializedOne.split('>='); return ContextKeyGreaterEqualsExpr.create(pieces[0].trim(), pieces[1].trim()); } if (/^[^<=>]+>[^<=>]+$/.test(serializedOne)) { const pieces = serializedOne.split('>'); return ContextKeyGreaterExpr.create(pieces[0].trim(), pieces[1].trim()); } if (/^[^<=>]+<=[^<=>]+$/.test(serializedOne)) { const pieces = serializedOne.split('<='); return ContextKeySmallerEqualsExpr.create(pieces[0].trim(), pieces[1].trim()); } if (/^[^<=>]+<[^<=>]+$/.test(serializedOne)) { const pieces = serializedOne.split('<'); return ContextKeySmallerExpr.create(pieces[0].trim(), pieces[1].trim()); } if (/^\!\s*/.test(serializedOne)) { return ContextKeyNotExpr.create(serializedOne.substr(1).trim()); } return ContextKeyDefinedExpr.create(serializedOne); } private static _deserializeValue(serializedValue: string, strict: boolean): any { serializedValue = serializedValue.trim(); if (serializedValue === 'true') { return true; } if (serializedValue === 'false') { return false; } const m = /^'([^']*)'$/.exec(serializedValue); if (m) { return m[1].trim(); } return serializedValue; } private static _deserializeRegexValue(serializedValue: string, strict: boolean): RegExp | null { if (isFalsyOrWhitespace(serializedValue)) { if (strict) { throw new Error('missing regexp-value for =~-expression'); } else { console.warn('missing regexp-value for =~-expression'); } return null; } const start = serializedValue.indexOf('/'); const end = serializedValue.lastIndexOf('/'); if (start === end || start < 0 /* || to < 0 */) { if (strict) { throw new Error(`bad regexp-value '${serializedValue}', missing /-enclosure`); } else { console.warn(`bad regexp-value '${serializedValue}', missing /-enclosure`); } return null; } const value = serializedValue.slice(start + 1, end); const caseIgnoreFlag = serializedValue[end + 1] === 'i' ? 'i' : ''; try { return new RegExp(value, caseIgnoreFlag); } catch (e) { if (strict) { throw new Error(`bad regexp-value '${serializedValue}', parse error: ${e}`); } else { console.warn(`bad regexp-value '${serializedValue}', parse error: ${e}`); } return null; } } } export function expressionsAreEqualWithConstantSubstitution(a: ContextKeyExpression | null | undefined, b: ContextKeyExpression | null | undefined): boolean { const aExpr = a ? a.substituteConstants() : undefined; const bExpr = b ? b.substituteConstants() : undefined; if (!aExpr && !bExpr) { return true; } if (!aExpr || !bExpr) { return false; } return aExpr.equals(bExpr); } function cmp(a: ContextKeyExpression, b: ContextKeyExpression): number { return a.cmp(b); } export class ContextKeyFalseExpr implements IContextKeyExpression { public static INSTANCE = new ContextKeyFalseExpr(); public readonly type = ContextKeyExprType.False; protected constructor() { } public cmp(other: ContextKeyExpression): number { return this.type - other.type; } public equals(other: ContextKeyExpression): boolean { return (other.type === this.type); } public substituteConstants(): ContextKeyExpression | undefined { return this; } public evaluate(context: IContext): boolean { return false; } public serialize(): string { return 'false'; } public keys(): string[] { return []; } public map(mapFnc: IContextKeyExprMapper): ContextKeyExpression { return this; } public negate(): ContextKeyExpression { return ContextKeyTrueExpr.INSTANCE; } } export class ContextKeyTrueExpr implements IContextKeyExpression { public static INSTANCE = new ContextKeyTrueExpr(); public readonly type = ContextKeyExprType.True; protected constructor() { } public cmp(other: ContextKeyExpression): number { return this.type - other.type; } public equals(other: ContextKeyExpression): boolean { return (other.type === this.type); } public substituteConstants(): ContextKeyExpression | undefined { return this; } public evaluate(context: IContext): boolean { return true; } public serialize(): string { return 'true'; } public keys(): string[] { return []; } public map(mapFnc: IContextKeyExprMapper): ContextKeyExpression { return this; } public negate(): ContextKeyExpression { return ContextKeyFalseExpr.INSTANCE; } } export class ContextKeyDefinedExpr implements IContextKeyExpression { public static create(key: string, negated: ContextKeyExpression | null = null): ContextKeyExpression { const constantValue = CONSTANT_VALUES.get(key); if (typeof constantValue === 'boolean') { return constantValue ? ContextKeyTrueExpr.INSTANCE : ContextKeyFalseExpr.INSTANCE; } return new ContextKeyDefinedExpr(key, negated); } public readonly type = ContextKeyExprType.Defined; protected constructor( readonly key: string, private negated: ContextKeyExpression | null ) { } public cmp(other: ContextKeyExpression): number { if (other.type !== this.type) { return this.type - other.type; } return cmp1(this.key, other.key); } public equals(other: ContextKeyExpression): boolean { if (other.type === this.type) { return (this.key === other.key); } return false; } public substituteConstants(): ContextKeyExpression | undefined { const constantValue = CONSTANT_VALUES.get(this.key); if (typeof constantValue === 'boolean') { return constantValue ? ContextKeyTrueExpr.INSTANCE : ContextKeyFalseExpr.INSTANCE; } return this; } public evaluate(context: IContext): boolean { return (!!context.getValue(this.key)); } public serialize(): string { return this.key; } public keys(): string[] { return [this.key]; } public map(mapFnc: IContextKeyExprMapper): ContextKeyExpression { return mapFnc.mapDefined(this.key); } public negate(): ContextKeyExpression { if (!this.negated) { this.negated = ContextKeyNotExpr.create(this.key, this); } return this.negated; } } export class ContextKeyEqualsExpr implements IContextKeyExpression { public static create(key: string, value: any, negated: ContextKeyExpression | null = null): ContextKeyExpression { if (typeof value === 'boolean') { return (value ? ContextKeyDefinedExpr.create(key, negated) : ContextKeyNotExpr.create(key, negated)); } const constantValue = CONSTANT_VALUES.get(key); if (typeof constantValue === 'boolean') { const trueValue = constantValue ? 'true' : 'false'; return (value === trueValue ? ContextKeyTrueExpr.INSTANCE : ContextKeyFalseExpr.INSTANCE); } return new ContextKeyEqualsExpr(key, value, negated); } public readonly type = ContextKeyExprType.Equals; private constructor( private readonly key: string, private readonly value: any, private negated: ContextKeyExpression | null ) { } public cmp(other: ContextKeyExpression): number { if (other.type !== this.type) { return this.type - other.type; } return cmp2(this.key, this.value, other.key, other.value); } public equals(other: ContextKeyExpression): boolean { if (other.type === this.type) { return (this.key === other.key && this.value === other.value); } return false; } public substituteConstants(): ContextKeyExpression | undefined { const constantValue = CONSTANT_VALUES.get(this.key); if (typeof constantValue === 'boolean') { const trueValue = constantValue ? 'true' : 'false'; return (this.value === trueValue ? ContextKeyTrueExpr.INSTANCE : ContextKeyFalseExpr.INSTANCE); } return this; } public evaluate(context: IContext): boolean { // Intentional == // eslint-disable-next-line eqeqeq return (context.getValue(this.key) == this.value); } public serialize(): string { return `${this.key} == '${this.value}'`; } public keys(): string[] { return [this.key]; } public map(mapFnc: IContextKeyExprMapper): ContextKeyExpression { return mapFnc.mapEquals(this.key, this.value); } public negate(): ContextKeyExpression { if (!this.negated) { this.negated = ContextKeyNotEqualsExpr.create(this.key, this.value, this); } return this.negated; } } export class ContextKeyInExpr implements IContextKeyExpression { public static create(key: string, valueKey: string): ContextKeyInExpr { return new ContextKeyInExpr(key, valueKey); } public readonly type = ContextKeyExprType.In; private negated: ContextKeyExpression | null = null; private constructor( private readonly key: string, private readonly valueKey: string, ) { } public cmp(other: ContextKeyExpression): number { if (other.type !== this.type) { return this.type - other.type; } return cmp2(this.key, this.valueKey, other.key, other.valueKey); } public equals(other: ContextKeyExpression): boolean { if (other.type === this.type) { return (this.key === other.key && this.valueKey === other.valueKey); } return false; } public substituteConstants(): ContextKeyExpression | undefined { return this; } public evaluate(context: IContext): boolean { const source = context.getValue(this.valueKey); const item = context.getValue(this.key); if (Array.isArray(source)) { return source.includes(item as any); } if (typeof item === 'string' && typeof source === 'object' && source !== null) { return hasOwnProperty.call(source, item); } return false; } public serialize(): string { return `${this.key} in '${this.valueKey}'`; } public keys(): string[] { return [this.key, this.valueKey]; } public map(mapFnc: IContextKeyExprMapper): ContextKeyInExpr { return mapFnc.mapIn(this.key, this.valueKey); } public negate(): ContextKeyExpression { if (!this.negated) { this.negated = ContextKeyNotInExpr.create(this.key, this.valueKey); } return this.negated; } } export class ContextKeyNotInExpr implements IContextKeyExpression { public static create(key: string, valueKey: string): ContextKeyNotInExpr { return new ContextKeyNotInExpr(key, valueKey); } public readonly type = ContextKeyExprType.NotIn; private readonly _negated: ContextKeyInExpr; private constructor( private readonly key: string, private readonly valueKey: string, ) { this._negated = ContextKeyInExpr.create(key, valueKey); } public cmp(other: ContextKeyExpression): number { if (other.type !== this.type) { return this.type - other.type; } return this._negated.cmp(other._negated); } public equals(other: ContextKeyExpression): boolean { if (other.type === this.type) { return this._negated.equals(other._negated); } return false; } public substituteConstants(): ContextKeyExpression | undefined { return this; } public evaluate(context: IContext): boolean { return !this._negated.evaluate(context); } public serialize(): string { return `${this.key} not in '${this.valueKey}'`; } public keys(): string[] { return this._negated.keys(); } public map(mapFnc: IContextKeyExprMapper): ContextKeyExpression { return mapFnc.mapNotIn(this.key, this.valueKey); } public negate(): ContextKeyExpression { return this._negated; } } export class ContextKeyNotEqualsExpr implements IContextKeyExpression { public static create(key: string, value: any, negated: ContextKeyExpression | null = null): ContextKeyExpression { if (typeof value === 'boolean') { if (value) { return ContextKeyNotExpr.create(key, negated); } return ContextKeyDefinedExpr.create(key, negated); } const constantValue = CONSTANT_VALUES.get(key); if (typeof constantValue === 'boolean') { const falseValue = constantValue ? 'true' : 'false'; return (value === falseValue ? ContextKeyFalseExpr.INSTANCE : ContextKeyTrueExpr.INSTANCE); } return new ContextKeyNotEqualsExpr(key, value, negated); } public readonly type = ContextKeyExprType.NotEquals; private constructor( private readonly key: string, private readonly value: any, private negated: ContextKeyExpression | null ) { } public cmp(other: ContextKeyExpression): number { if (other.type !== this.type) { return this.type - other.type; } return cmp2(this.key, this.value, other.key, other.value); } public equals(other: ContextKeyExpression): boolean { if (other.type === this.type) { return (this.key === other.key && this.value === other.value); } return false; } public substituteConstants(): ContextKeyExpression | undefined { const constantValue = CONSTANT_VALUES.get(this.key); if (typeof constantValue === 'boolean') { const falseValue = constantValue ? 'true' : 'false'; return (this.value === falseValue ? ContextKeyFalseExpr.INSTANCE : ContextKeyTrueExpr.INSTANCE); } return this; } public evaluate(context: IContext): boolean { // Intentional != // eslint-disable-next-line eqeqeq return (context.getValue(this.key) != this.value); } public serialize(): string { return `${this.key} != '${this.value}'`; } public keys(): string[] { return [this.key]; } public map(mapFnc: IContextKeyExprMapper): ContextKeyExpression { return mapFnc.mapNotEquals(this.key, this.value); } public negate(): ContextKeyExpression { if (!this.negated) { this.negated = ContextKeyEqualsExpr.create(this.key, this.value, this); } return this.negated; } } export class ContextKeyNotExpr implements IContextKeyExpression { public static create(key: string, negated: ContextKeyExpression | null = null): ContextKeyExpression { const constantValue = CONSTANT_VALUES.get(key); if (typeof constantValue === 'boolean') { return (constantValue ? ContextKeyFalseExpr.INSTANCE : ContextKeyTrueExpr.INSTANCE); } return new ContextKeyNotExpr(key, negated); } public readonly type = ContextKeyExprType.Not; private constructor( private readonly key: string, private negated: ContextKeyExpression | null ) { } public cmp(other: ContextKeyExpression): number { if (other.type !== this.type) { return this.type - other.type; } return cmp1(this.key, other.key); } public equals(other: ContextKeyExpression): boolean { if (other.type === this.type) { return (this.key === other.key); } return false; } public substituteConstants(): ContextKeyExpression | undefined { const constantValue = CONSTANT_VALUES.get(this.key); if (typeof constantValue === 'boolean') { return (constantValue ? ContextKeyFalseExpr.INSTANCE : ContextKeyTrueExpr.INSTANCE); } return this; } public evaluate(context: IContext): boolean { return (!context.getValue(this.key)); } public serialize(): string { return `!${this.key}`; } public keys(): string[] { return [this.key]; } public map(mapFnc: IContextKeyExprMapper): ContextKeyExpression { return mapFnc.mapNot(this.key); } public negate(): ContextKeyExpression { if (!this.negated) { this.negated = ContextKeyDefinedExpr.create(this.key, this); } return this.negated; } } function withFloatOrStr<T extends ContextKeyExpression>(value: any, callback: (value: number | string) => T): T | ContextKeyFalseExpr { if (typeof value === 'string') { const n = parseFloat(value); if (!isNaN(n)) { value = n; } } if (typeof value === 'string' || typeof value === 'number') { return callback(value); } return ContextKeyFalseExpr.INSTANCE; } export class ContextKeyGreaterExpr implements IContextKeyExpression { public static create(key: string, _value: any, negated: ContextKeyExpression | null = null): ContextKeyExpression { return withFloatOrStr(_value, (value) => new ContextKeyGreaterExpr(key, value, negated)); } public readonly type = ContextKeyExprType.Greater; private constructor( private readonly key: string, private readonly value: number | string, private negated: ContextKeyExpression | null ) { } public cmp(other: ContextKeyExpression): number { if (other.type !== this.type) { return this.type - other.type; } return cmp2(this.key, this.value, other.key, other.value); } public equals(other: ContextKeyExpression): boolean { if (other.type === this.type) { return (this.key === other.key && this.value === other.value); } return false; } public substituteConstants(): ContextKeyExpression | undefined { return this; } public evaluate(context: IContext): boolean { if (typeof this.value === 'string') { return false; } return (parseFloat(<any>context.getValue(this.key)) > this.value); } public serialize(): string { return `${this.key} > ${this.value}`; } public keys(): string[] { return [this.key]; } public map(mapFnc: IContextKeyExprMapper): ContextKeyExpression { return mapFnc.mapGreater(this.key, this.value); } public negate(): ContextKeyExpression { if (!this.negated) { this.negated = ContextKeySmallerEqualsExpr.create(this.key, this.value, this); } return this.negated; } } export class ContextKeyGreaterEqualsExpr implements IContextKeyExpression { public static create(key: string, _value: any, negated: ContextKeyExpression | null = null): ContextKeyExpression { return withFloatOrStr(_value, (value) => new ContextKeyGreaterEqualsExpr(key, value, negated)); } public readonly type = ContextKeyExprType.GreaterEquals; private constructor( private readonly key: string, private readonly value: number | string, private negated: ContextKeyExpression | null ) { } public cmp(other: ContextKeyExpression): number { if (other.type !== this.type) { return this.type - other.type; } return cmp2(this.key, this.value, other.key, other.value); } public equals(other: ContextKeyExpression): boolean { if (other.type === this.type) { return (this.key === other.key && this.value === other.value); } return false; } public substituteConstants(): ContextKeyExpression | undefined { return this; } public evaluate(context: IContext): boolean { if (typeof this.value === 'string') { return false; } return (parseFloat(<any>context.getValue(this.key)) >= this.value); } public serialize(): string { return `${this.key} >= ${this.value}`; } public keys(): string[] { return [this.key]; } public map(mapFnc: IContextKeyExprMapper): ContextKeyExpression { return mapFnc.mapGreaterEquals(this.key, this.value); } public negate(): ContextKeyExpression { if (!this.negated) { this.negated = ContextKeySmallerExpr.create(this.key, this.value, this); } return this.negated; } } export class ContextKeySmallerExpr implements IContextKeyExpression { public static create(key: string, _value: any, negated: ContextKeyExpression | null = null): ContextKeyExpression { return withFloatOrStr(_value, (value) => new ContextKeySmallerExpr(key, value, negated)); } public readonly type = ContextKeyExprType.Smaller; private constructor( private readonly key: string, private readonly value: number | string, private negated: ContextKeyExpression | null ) { } public cmp(other: ContextKeyExpression): number { if (other.type !== this.type) { return this.type - other.type; } return cmp2(this.key, this.value, other.key, other.value); } public equals(other: ContextKeyExpression): boolean { if (other.type === this.type) { return (this.key === other.key && this.value === other.value); } return false; } public substituteConstants(): ContextKeyExpression | undefined { return this; } public evaluate(context: IContext): boolean { if (typeof this.value === 'string') { return false; } return (parseFloat(<any>context.getValue(this.key)) < this.value); } public serialize(): string { return `${this.key} < ${this.value}`; } public keys(): string[] { return [this.key]; } public map(mapFnc: IContextKeyExprMapper): ContextKeyExpression { return mapFnc.mapSmaller(this.key, this.value); } public negate(): ContextKeyExpression { if (!this.negated) { this.negated = ContextKeyGreaterEqualsExpr.create(this.key, this.value, this); } return this.negated; } } export class ContextKeySmallerEqualsExpr implements IContextKeyExpression { public static create(key: string, _value: any, negated: ContextKeyExpression | null = null): ContextKeyExpression { return withFloatOrStr(_value, (value) => new ContextKeySmallerEqualsExpr(key, value, negated)); } public readonly type = ContextKeyExprType.SmallerEquals; private constructor( private readonly key: string, private readonly value: number | string, private negated: ContextKeyExpression | null ) { } public cmp(other: ContextKeyExpression): number { if (other.type !== this.type) { return this.type - other.type; } return cmp2(this.key, this.value, other.key, other.value); } public equals(other: ContextKeyExpression): boolean { if (other.type === this.type) { return (this.key === other.key && this.value === other.value); } return false; } public substituteConstants(): ContextKeyExpression | undefined { return this; } public evaluate(context: IContext): boolean { if (typeof this.value === 'string') { return false; } return (parseFloat(<any>context.getValue(this.key)) <= this.value); } public serialize(): string { return `${this.key} <= ${this.value}`; } public keys(): string[] { return [this.key]; } public map(mapFnc: IContextKeyExprMapper): ContextKeyExpression { return mapFnc.mapSmallerEquals(this.key, this.value); } public negate(): ContextKeyExpression { if (!this.negated) { this.negated = ContextKeyGreaterExpr.create(this.key, this.value, this); } return this.negated; } } export class ContextKeyRegexExpr implements IContextKeyExpression { public static create(key: string, regexp: RegExp | null): ContextKeyRegexExpr { return new ContextKeyRegexExpr(key, regexp); } public readonly type = ContextKeyExprType.Regex; private negated: ContextKeyExpression | null = null; private constructor( private readonly key: string, private readonly regexp: RegExp | null ) { // } public cmp(other: ContextKeyExpression): number { if (other.type !== this.type) { return this.type - other.type; } if (this.key < other.key) { return -1; } if (this.key > other.key) { return 1; } const thisSource = this.regexp ? this.regexp.source : ''; const otherSource = other.regexp ? other.regexp.source : ''; if (thisSource < otherSource) { return -1; } if (thisSource > otherSource) { return 1; } return 0; } public equals(other: ContextKeyExpression): boolean { if (other.type === this.type) { const thisSource = this.regexp ? this.regexp.source : ''; const otherSource = other.regexp ? other.regexp.source : ''; return (this.key === other.key && thisSource === otherSource); } return false; } public substituteConstants(): ContextKeyExpression | undefined { return this; } public evaluate(context: IContext): boolean { const value = context.getValue<any>(this.key); return this.regexp ? this.regexp.test(value) : false; } public serialize(): string { const value = this.regexp ? `/${this.regexp.source}/${this.regexp.ignoreCase ? 'i' : ''}` : '/invalid/'; return `${this.key} =~ ${value}`; } public keys(): string[] { return [this.key]; } public map(mapFnc: IContextKeyExprMapper): ContextKeyRegexExpr { return mapFnc.mapRegex(this.key, this.regexp); } public negate(): ContextKeyExpression { if (!this.negated) { this.negated = ContextKeyNotRegexExpr.create(this); } return this.negated; } } export class ContextKeyNotRegexExpr implements IContextKeyExpression { public static create(actual: ContextKeyRegexExpr): ContextKeyExpression { return new ContextKeyNotRegexExpr(actual); } public readonly type = ContextKeyExprType.NotRegex; private constructor(private readonly _actual: ContextKeyRegexExpr) { // } public cmp(other: ContextKeyExpression): number { if (other.type !== this.type) { return this.type - other.type; } return this._actual.cmp(other._actual); } public equals(other: ContextKeyExpression): boolean { if (other.type === this.type) { return this._actual.equals(other._actual); } return false; } public substituteConstants(): ContextKeyExpression | undefined { return this; } public evaluate(context: IContext): boolean { return !this._actual.evaluate(context); } public serialize(): string { throw new Error('Method not implemented.'); } public keys(): string[] { return this._actual.keys(); } public map(mapFnc: IContextKeyExprMapper): ContextKeyExpression { return new ContextKeyNotRegexExpr(this._actual.map(mapFnc)); } public negate(): ContextKeyExpression { return this._actual; } } /** * @returns the same instance if nothing changed. */ function eliminateConstantsInArray(arr: ContextKeyExpression[]): (ContextKeyExpression | undefined)[] { // Allocate array only if there is a difference let newArr: (ContextKeyExpression | undefined)[] | null = null; for (let i = 0, len = arr.length; i < len; i++) { const newExpr = arr[i].substituteConstants(); if (arr[i] !== newExpr) { // something has changed! // allocate array on first difference if (newArr === null) { newArr = []; for (let j = 0; j < i; j++) { newArr[j] = arr[j]; } } } if (newArr !== null) { newArr[i] = newExpr; } } if (newArr === null) { return arr; } return newArr; } class ContextKeyAndExpr implements IContextKeyExpression { public static create(_expr: ReadonlyArray<ContextKeyExpression | null | undefined>, negated: ContextKeyExpression | null, extraRedundantCheck: boolean): ContextKeyExpression | undefined { return ContextKeyAndExpr._normalizeArr(_expr, negated, extraRedundantCheck); } public readonly type = ContextKeyExprType.And; private constructor( public readonly expr: ContextKeyExpression[], private negated: ContextKeyExpression | null ) { } public cmp(other: ContextKeyExpression): number { if (other.type !== this.type) { return this.type - other.type; } if (this.expr.length < other.expr.length) { return -1; } if (this.expr.length > other.expr.length) { return 1; } for (let i = 0, len = this.expr.length; i < len; i++) { const r = cmp(this.expr[i], other.expr[i]); if (r !== 0) { return r; } } return 0; } public equals(other: ContextKeyExpression): boolean { if (other.type === this.type) { if (this.expr.length !== other.expr.length) { return false; } for (let i = 0, len = this.expr.length; i < len; i++) { if (!this.expr[i].equals(other.expr[i])) { return false; } } return true; } return false; } public substituteConstants(): ContextKeyExpression | undefined { const exprArr = eliminateConstantsInArray(this.expr); if (exprArr === this.expr) { // no change return this; } return ContextKeyAndExpr.create(exprArr, this.negated, false); } public evaluate(context: IContext): boolean { for (let i = 0, len = this.expr.length; i < len; i++) { if (!this.expr[i].evaluate(context)) { return false; } } return true; } private static _normalizeArr(arr: ReadonlyArray<ContextKeyExpression | null | undefined>, negated: ContextKeyExpression | null, extraRedundantCheck: boolean): ContextKeyExpression | undefined { const expr: ContextKeyExpression[] = []; let hasTrue = false; for (const e of arr) { if (!e) { continue; } if (e.type === ContextKeyExprType.True) { // anything && true ==> anything hasTrue = true; continue; } if (e.type === ContextKeyExprType.False) { // anything && false ==> false return ContextKeyFalseExpr.INSTANCE; } if (e.type === ContextKeyExprType.And) { expr.push(...e.expr); continue; } expr.push(e); } if (expr.length === 0 && hasTrue) { return ContextKeyTrueExpr.INSTANCE; } if (expr.length === 0) { return undefined; } if (expr.length === 1) { return expr[0]; } expr.sort(cmp); // eliminate duplicate terms for (let i = 1; i < expr.length; i++) { if (expr[i - 1].equals(expr[i])) { expr.splice(i, 1); i--; } } if (expr.length === 1) { return expr[0]; } // We must distribute any OR expression because we don't support parens // OR extensions will be at the end (due to sorting rules) while (expr.length > 1) { const lastElement = expr[expr.length - 1]; if (lastElement.type !== ContextKeyExprType.Or) { break; } // pop the last element expr.pop(); // pop the second to last element const secondToLastElement = expr.pop()!; const isFinished = (expr.length === 0); // distribute `lastElement` over `secondToLastElement` const resultElement = ContextKeyOrExpr.create( lastElement.expr.map(el => ContextKeyAndExpr.create([el, secondToLastElement], null, extraRedundantCheck)), null, isFinished ); if (resultElement) { expr.push(resultElement); expr.sort(cmp); } } if (expr.length === 1) { return expr[0]; } // resolve false AND expressions if (extraRedundantCheck) { for (let i = 0; i < expr.length; i++) { for (let j = i + 1; j < expr.length; j++) { if (expr[i].negate().equals(expr[j])) { // A && !A case return ContextKeyFalseExpr.INSTANCE; } } } if (expr.length === 1) { return expr[0]; } } return new ContextKeyAndExpr(expr, negated); } public serialize(): string { return this.expr.map(e => e.serialize()).join(' && '); } public keys(): string[] { const result: string[] = []; for (const expr of this.expr) { result.push(...expr.keys()); } return result; } public map(mapFnc: IContextKeyExprMapper): ContextKeyExpression { return new ContextKeyAndExpr(this.expr.map(expr => expr.map(mapFnc)), null); } public negate(): ContextKeyExpression { if (!this.negated) { const result: ContextKeyExpression[] = []; for (const expr of this.expr) { result.push(expr.negate()); } this.negated = ContextKeyOrExpr.create(result, this, true)!; } return this.negated; } } class ContextKeyOrExpr implements IContextKeyExpression { public static create(_expr: ReadonlyArray<ContextKeyExpression | null | undefined>, negated: ContextKeyExpression | null, extraRedundantCheck: boolean): ContextKeyExpression | undefined { return ContextKeyOrExpr._normalizeArr(_expr, negated, extraRedundantCheck); } public readonly type = ContextKeyExprType.Or; private constructor( public readonly expr: ContextKeyExpression[], private negated: ContextKeyExpression | null ) { } public cmp(other: ContextKeyExpression): number { if (other.type !== this.type) { return this.type - other.type; } if (this.expr.length < other.expr.length) { return -1; } if (this.expr.length > other.expr.length) { return 1; } for (let i = 0, len = this.expr.length; i < len; i++) { const r = cmp(this.expr[i], other.expr[i]); if (r !== 0) { return r; } } return 0; } public equals(other: ContextKeyExpression): boolean { if (other.type === this.type) { if (this.expr.length !== other.expr.length) { return false; } for (let i = 0, len = this.expr.length; i < len; i++) { if (!this.expr[i].equals(other.expr[i])) { return false; } } return true; } return false; } public substituteConstants(): ContextKeyExpression | undefined { const exprArr = eliminateConstantsInArray(this.expr); if (exprArr === this.expr) { // no change return this; } return ContextKeyOrExpr.create(exprArr, this.negated, false); } public evaluate(context: IContext): boolean { for (let i = 0, len = this.expr.length; i < len; i++) { if (this.expr[i].evaluate(context)) { return true; } } return false; } private static _normalizeArr(arr: ReadonlyArray<ContextKeyExpression | null | undefined>, negated: ContextKeyExpression | null, extraRedundantCheck: boolean): ContextKeyExpression | undefined { let expr: ContextKeyExpression[] = []; let hasFalse = false; if (arr) { for (let i = 0, len = arr.length; i < len; i++) { const e = arr[i]; if (!e) { continue; } if (e.type === ContextKeyExprType.False) { // anything || false ==> anything hasFalse = true; continue; } if (e.type === ContextKeyExprType.True) { // anything || true ==> true return ContextKeyTrueExpr.INSTANCE; } if (e.type === ContextKeyExprType.Or) { expr = expr.concat(e.expr); continue; } expr.push(e); } if (expr.length === 0 && hasFalse) { return ContextKeyFalseExpr.INSTANCE; } expr.sort(cmp); } if (expr.length === 0) { return undefined; } if (expr.length === 1) { return expr[0]; } // eliminate duplicate terms for (let i = 1; i < expr.length; i++) { if (expr[i - 1].equals(expr[i])) { expr.splice(i, 1); i--; } } if (expr.length === 1) { return expr[0]; } // resolve true OR expressions if (extraRedundantCheck) { for (let i = 0; i < expr.length; i++) { for (let j = i + 1; j < expr.length; j++) { if (expr[i].negate().equals(expr[j])) { // A || !A case return ContextKeyTrueExpr.INSTANCE; } } } if (expr.length === 1) { return expr[0]; } } return new ContextKeyOrExpr(expr, negated); } public serialize(): string { return this.expr.map(e => e.serialize()).join(' || '); } public keys(): string[] { const result: string[] = []; for (const expr of this.expr) { result.push(...expr.keys()); } return result; } public map(mapFnc: IContextKeyExprMapper): ContextKeyExpression { return new ContextKeyOrExpr(this.expr.map(expr => expr.map(mapFnc)), null); } public negate(): ContextKeyExpression { if (!this.negated) { const result: ContextKeyExpression[] = []; for (const expr of this.expr) { result.push(expr.negate()); } // We don't support parens, so here we distribute the AND over the OR terminals // We always take the first 2 AND pairs and distribute them while (result.length > 1) { const LEFT = result.shift()!; const RIGHT = result.shift()!; const all: ContextKeyExpression[] = []; for (const left of getTerminals(LEFT)) { for (const right of getTerminals(RIGHT)) { all.push(ContextKeyAndExpr.create([left, right], null, false)!); } } result.unshift(ContextKeyOrExpr.create(all, null, false)!); } this.negated = ContextKeyOrExpr.create(result, this, true)!; } return this.negated; } } export interface ContextKeyInfo { readonly key: string; readonly type?: string; readonly description?: string; } export class RawContextKey<T extends ContextKeyValue> extends ContextKeyDefinedExpr { private static _info: ContextKeyInfo[] = []; static all(): IterableIterator<ContextKeyInfo> { return RawContextKey._info.values(); } private readonly _defaultValue: T | undefined; constructor(key: string, defaultValue: T | undefined, metaOrHide?: string | true | { type: string; description: string }) { super(key, null); this._defaultValue = defaultValue; // collect all context keys into a central place if (typeof metaOrHide === 'object') { RawContextKey._info.push({ ...metaOrHide, key }); } else if (metaOrHide !== true) { RawContextKey._info.push({ key, description: metaOrHide, type: defaultValue !== null && defaultValue !== undefined ? typeof defaultValue : undefined }); } } public bindTo(target: IContextKeyService): IContextKey<T> { return target.createKey(this.key, this._defaultValue); } public getValue(target: IContextKeyService): T | undefined { return target.getContextKeyValue<T>(this.key); } public toNegated(): ContextKeyExpression { return this.negate(); } public isEqualTo(value: any): ContextKeyExpression { return ContextKeyEqualsExpr.create(this.key, value); } public notEqualsTo(value: any): ContextKeyExpression { return ContextKeyNotEqualsExpr.create(this.key, value); } } export type ContextKeyValue = null | undefined | boolean | number | string | Array<null | undefined | boolean | number | string> | Record<string, null | undefined | boolean | number | string>; export interface IContext { getValue<T extends ContextKeyValue = ContextKeyValue>(key: string): T | undefined; } export interface IContextKey<T extends ContextKeyValue = ContextKeyValue> { set(value: T): void; reset(): void; get(): T | undefined; } export interface IContextKeyServiceTarget { parentElement: IContextKeyServiceTarget | null; setAttribute(attr: string, value: string): void; removeAttribute(attr: string): void; hasAttribute(attr: string): boolean; getAttribute(attr: string): string | null; } export const IContextKeyService = createDecorator<IContextKeyService>('contextKeyService'); export interface IReadableSet<T> { has(value: T): boolean; } export interface IContextKeyChangeEvent { affectsSome(keys: IReadableSet<string>): boolean; allKeysContainedIn(keys: IReadableSet<string>): boolean; } export interface IContextKeyService { readonly _serviceBrand: undefined; dispose(): void; onDidChangeContext: Event<IContextKeyChangeEvent>; bufferChangeEvents(callback: Function): void; createKey<T extends ContextKeyValue>(key: string, defaultValue: T | undefined): IContextKey<T>; contextMatchesRules(rules: ContextKeyExpression | undefined): boolean; getContextKeyValue<T>(key: string): T | undefined; createScoped(target: IContextKeyServiceTarget): IContextKeyService; createOverlay(overlay: Iterable<[string, any]>): IContextKeyService; getContext(target: IContextKeyServiceTarget | null): IContext; updateParent(parentContextKeyService: IContextKeyService): void; } export const SET_CONTEXT_COMMAND_ID = 'setContext'; function cmp1(key1: string, key2: string): number { if (key1 < key2) { return -1; } if (key1 > key2) { return 1; } return 0; } function cmp2(key1: string, value1: any, key2: string, value2: any): number { if (key1 < key2) { return -1; } if (key1 > key2) { return 1; } if (value1 < value2) { return -1; } if (value1 > value2) { return 1; } return 0; } /** * Returns true if it is provable `p` implies `q`. */ export function implies(p: ContextKeyExpression, q: ContextKeyExpression): boolean { if (p.type === ContextKeyExprType.False || q.type === ContextKeyExprType.True) { // false implies anything // anything implies true return true; } if (p.type === ContextKeyExprType.Or) { if (q.type === ContextKeyExprType.Or) { // `a || b || c` can only imply something like `a || b || c || d` return allElementsIncluded(p.expr, q.expr); } return false; } if (q.type === ContextKeyExprType.Or) { for (const element of q.expr) { if (implies(p, element)) { return true; } } return false; } if (p.type === ContextKeyExprType.And) { if (q.type === ContextKeyExprType.And) { // `a && b && c` implies `a && c` return allElementsIncluded(q.expr, p.expr); } for (const element of p.expr) { if (implies(element, q)) { return true; } } return false; } return p.equals(q); } /** * Returns true if all elements in `p` are also present in `q`. * The two arrays are assumed to be sorted */ function allElementsIncluded(p: ContextKeyExpression[], q: ContextKeyExpression[]): boolean { let pIndex = 0; let qIndex = 0; while (pIndex < p.length && qIndex < q.length) { const cmp = p[pIndex].cmp(q[qIndex]); if (cmp < 0) { // an element from `p` is missing from `q` return false; } else if (cmp === 0) { pIndex++; qIndex++; } else { qIndex++; } } return (pIndex === p.length); } function getTerminals(node: ContextKeyExpression) { if (node.type === ContextKeyExprType.Or) { return node.expr; } return [node]; }
src/vs/platform/contextkey/common/contextkey.ts
1
https://github.com/microsoft/vscode/commit/bafda10a370cd7ac835c4a88f5885bf69e02037e
[ 0.0092161251232028, 0.0003437534614931792, 0.00016250117914751172, 0.00017554970690980554, 0.000905223423615098 ]
{ "id": 1, "code_window": [ "\t\treturn undefined;\n", "\t});\n", "}\n", "\n", "CommandsRegistry.registerCommand(SET_CONTEXT_COMMAND_ID, setContext);\n", "\n", "CommandsRegistry.registerCommand({\n", "\tid: 'getContextKeyInfo',\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "CommandsRegistry.registerCommand('_setContext', setContext);\n" ], "file_path": "src/vs/platform/contextkey/browser/contextKeyService.ts", "type": "replace", "edit_start_line_idx": 621 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as dom from 'vs/base/browser/dom'; import { EventType, Gesture } from 'vs/base/browser/touch'; import { ISelectBoxDelegate, ISelectBoxOptions, ISelectBoxStyles, ISelectData, ISelectOptionItem } from 'vs/base/browser/ui/selectBox/selectBox'; import * as arrays from 'vs/base/common/arrays'; import { Emitter, Event } from 'vs/base/common/event'; import { KeyCode } from 'vs/base/common/keyCodes'; import { Disposable } from 'vs/base/common/lifecycle'; import { isMacintosh } from 'vs/base/common/platform'; export class SelectBoxNative extends Disposable implements ISelectBoxDelegate { private selectElement: HTMLSelectElement; private selectBoxOptions: ISelectBoxOptions; private options: ISelectOptionItem[]; private selected = 0; private readonly _onDidSelect: Emitter<ISelectData>; private styles: ISelectBoxStyles; constructor(options: ISelectOptionItem[], selected: number, styles: ISelectBoxStyles, selectBoxOptions?: ISelectBoxOptions) { super(); this.selectBoxOptions = selectBoxOptions || Object.create(null); this.options = []; this.selectElement = document.createElement('select'); this.selectElement.className = 'monaco-select-box'; if (typeof this.selectBoxOptions.ariaLabel === 'string') { this.selectElement.setAttribute('aria-label', this.selectBoxOptions.ariaLabel); } if (typeof this.selectBoxOptions.ariaDescription === 'string') { this.selectElement.setAttribute('aria-description', this.selectBoxOptions.ariaDescription); } this._onDidSelect = this._register(new Emitter<ISelectData>()); this.styles = styles; this.registerListeners(); this.setOptions(options, selected); } private registerListeners() { this._register(Gesture.addTarget(this.selectElement)); [EventType.Tap].forEach(eventType => { this._register(dom.addDisposableListener(this.selectElement, eventType, (e) => { this.selectElement.focus(); })); }); this._register(dom.addStandardDisposableListener(this.selectElement, 'click', (e) => { dom.EventHelper.stop(e, true); })); this._register(dom.addStandardDisposableListener(this.selectElement, 'change', (e) => { this.selectElement.title = e.target.value; this._onDidSelect.fire({ index: e.target.selectedIndex, selected: e.target.value }); })); this._register(dom.addStandardDisposableListener(this.selectElement, 'keydown', (e) => { let showSelect = false; if (isMacintosh) { if (e.keyCode === KeyCode.DownArrow || e.keyCode === KeyCode.UpArrow || e.keyCode === KeyCode.Space) { showSelect = true; } } else { if (e.keyCode === KeyCode.DownArrow && e.altKey || e.keyCode === KeyCode.Space || e.keyCode === KeyCode.Enter) { showSelect = true; } } if (showSelect) { // Space, Enter, is used to expand select box, do not propagate it (prevent action bar action run) e.stopPropagation(); } })); } public get onDidSelect(): Event<ISelectData> { return this._onDidSelect.event; } public setOptions(options: ISelectOptionItem[], selected?: number): void { if (!this.options || !arrays.equals(this.options, options)) { this.options = options; this.selectElement.options.length = 0; this.options.forEach((option, index) => { this.selectElement.add(this.createOption(option.text, index, option.isDisabled)); }); } if (selected !== undefined) { this.select(selected); } } public select(index: number): void { if (this.options.length === 0) { this.selected = 0; } else if (index >= 0 && index < this.options.length) { this.selected = index; } else if (index > this.options.length - 1) { // Adjust index to end of list // This could make client out of sync with the select this.select(this.options.length - 1); } else if (this.selected < 0) { this.selected = 0; } this.selectElement.selectedIndex = this.selected; if ((this.selected < this.options.length) && typeof this.options[this.selected].text === 'string') { this.selectElement.title = this.options[this.selected].text; } else { this.selectElement.title = ''; } } public setAriaLabel(label: string): void { this.selectBoxOptions.ariaLabel = label; this.selectElement.setAttribute('aria-label', label); } public focus(): void { if (this.selectElement) { this.selectElement.tabIndex = 0; this.selectElement.focus(); } } public blur(): void { if (this.selectElement) { this.selectElement.tabIndex = -1; this.selectElement.blur(); } } public setFocusable(focusable: boolean): void { this.selectElement.tabIndex = focusable ? 0 : -1; } public render(container: HTMLElement): void { container.classList.add('select-container'); container.appendChild(this.selectElement); this.setOptions(this.options, this.selected); this.applyStyles(); } public style(styles: ISelectBoxStyles): void { this.styles = styles; this.applyStyles(); } public applyStyles(): void { // Style native select if (this.selectElement) { const background = this.styles.selectBackground ? this.styles.selectBackground.toString() : ''; const foreground = this.styles.selectForeground ? this.styles.selectForeground.toString() : ''; const border = this.styles.selectBorder ? this.styles.selectBorder.toString() : ''; this.selectElement.style.backgroundColor = background; this.selectElement.style.color = foreground; this.selectElement.style.borderColor = border; } } private createOption(value: string, index: number, disabled?: boolean): HTMLOptionElement { const option = document.createElement('option'); option.value = value; option.text = value; option.disabled = !!disabled; return option; } }
src/vs/base/browser/ui/selectBox/selectBoxNative.ts
0
https://github.com/microsoft/vscode/commit/bafda10a370cd7ac835c4a88f5885bf69e02037e
[ 0.00017477349319960922, 0.0001711068325676024, 0.00016578960639890283, 0.00017166623729281127, 0.000002573431856944808 ]
{ "id": 1, "code_window": [ "\t\treturn undefined;\n", "\t});\n", "}\n", "\n", "CommandsRegistry.registerCommand(SET_CONTEXT_COMMAND_ID, setContext);\n", "\n", "CommandsRegistry.registerCommand({\n", "\tid: 'getContextKeyInfo',\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "CommandsRegistry.registerCommand('_setContext', setContext);\n" ], "file_path": "src/vs/platform/contextkey/browser/contextKeyService.ts", "type": "replace", "edit_start_line_idx": 621 }
"use strict"; /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ Object.defineProperty(exports, "__esModule", { value: true }); exports.define = exports.parallel = exports.series = void 0; const fancyLog = require("fancy-log"); const ansiColors = require("ansi-colors"); function _isPromise(p) { if (typeof p.then === 'function') { return true; } return false; } function _renderTime(time) { return `${Math.round(time)} ms`; } async function _execute(task) { const name = task.taskName || task.displayName || `<anonymous>`; if (!task._tasks) { fancyLog('Starting', ansiColors.cyan(name), '...'); } const startTime = process.hrtime(); await _doExecute(task); const elapsedArr = process.hrtime(startTime); const elapsedNanoseconds = (elapsedArr[0] * 1e9 + elapsedArr[1]); if (!task._tasks) { fancyLog(`Finished`, ansiColors.cyan(name), 'after', ansiColors.magenta(_renderTime(elapsedNanoseconds / 1e6))); } } async function _doExecute(task) { // Always invoke as if it were a callback task return new Promise((resolve, reject) => { if (task.length === 1) { // this is a callback task task((err) => { if (err) { return reject(err); } resolve(); }); return; } const taskResult = task(); if (typeof taskResult === 'undefined') { // this is a sync task resolve(); return; } if (_isPromise(taskResult)) { // this is a promise returning task taskResult.then(resolve, reject); return; } // this is a stream returning task taskResult.on('end', _ => resolve()); taskResult.on('error', err => reject(err)); }); } function series(...tasks) { const result = async () => { for (let i = 0; i < tasks.length; i++) { await _execute(tasks[i]); } }; result._tasks = tasks; return result; } exports.series = series; function parallel(...tasks) { const result = async () => { await Promise.all(tasks.map(t => _execute(t))); }; result._tasks = tasks; return result; } exports.parallel = parallel; function define(name, task) { if (task._tasks) { // This is a composite task const lastTask = task._tasks[task._tasks.length - 1]; if (lastTask._tasks || lastTask.taskName) { // This is a composite task without a real task function // => generate a fake task function return define(name, series(task, () => Promise.resolve())); } lastTask.taskName = name; task.displayName = name; return task; } // This is a simple task task.taskName = name; task.displayName = name; return task; } exports.define = define; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGFzay5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbInRhc2sudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBOzs7Z0dBR2dHOzs7QUFFaEcsc0NBQXNDO0FBQ3RDLDBDQUEwQztBQW1CMUMsU0FBUyxVQUFVLENBQUMsQ0FBeUM7SUFDNUQsSUFBSSxPQUFhLENBQUUsQ0FBQyxJQUFJLEtBQUssVUFBVSxFQUFFO1FBQ3hDLE9BQU8sSUFBSSxDQUFDO0tBQ1o7SUFDRCxPQUFPLEtBQUssQ0FBQztBQUNkLENBQUM7QUFFRCxTQUFTLFdBQVcsQ0FBQyxJQUFZO0lBQ2hDLE9BQU8sR0FBRyxJQUFJLENBQUMsS0FBSyxDQUFDLElBQUksQ0FBQyxLQUFLLENBQUM7QUFDakMsQ0FBQztBQUVELEtBQUssVUFBVSxRQUFRLENBQUMsSUFBVTtJQUNqQyxNQUFNLElBQUksR0FBRyxJQUFJLENBQUMsUUFBUSxJQUFJLElBQUksQ0FBQyxXQUFXLElBQUksYUFBYSxDQUFDO0lBQ2hFLElBQUksQ0FBQyxJQUFJLENBQUMsTUFBTSxFQUFFO1FBQ2pCLFFBQVEsQ0FBQyxVQUFVLEVBQUUsVUFBVSxDQUFDLElBQUksQ0FBQyxJQUFJLENBQUMsRUFBRSxLQUFLLENBQUMsQ0FBQztLQUNuRDtJQUNELE1BQU0sU0FBUyxHQUFHLE9BQU8sQ0FBQyxNQUFNLEVBQUUsQ0FBQztJQUNuQyxNQUFNLFVBQVUsQ0FBQyxJQUFJLENBQUMsQ0FBQztJQUN2QixNQUFNLFVBQVUsR0FBRyxPQUFPLENBQUMsTUFBTSxDQUFDLFNBQVMsQ0FBQyxDQUFDO0lBQzdDLE1BQU0sa0JBQWtCLEdBQUcsQ0FBQyxVQUFVLENBQUMsQ0FBQyxDQUFDLEdBQUcsR0FBRyxHQUFHLFVBQVUsQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDO0lBQ2pFLElBQUksQ0FBQyxJQUFJLENBQUMsTUFBTSxFQUFFO1FBQ2pCLFFBQVEsQ0FBQyxVQUFVLEVBQUUsVUFBVSxDQUFDLElBQUksQ0FBQyxJQUFJLENBQUMsRUFBRSxPQUFPLEVBQUUsVUFBVSxDQUFDLE9BQU8sQ0FBQyxXQUFXLENBQUMsa0JBQWtCLEdBQUcsR0FBRyxDQUFDLENBQUMsQ0FBQyxDQUFDO0tBQ2hIO0FBQ0YsQ0FBQztBQUVELEtBQUssVUFBVSxVQUFVLENBQUMsSUFBVTtJQUNuQyw4Q0FBOEM7SUFDOUMsT0FBTyxJQUFJLE9BQU8sQ0FBQyxDQUFDLE9BQU8sRUFBRSxNQUFNLEVBQUUsRUFBRTtRQUN0QyxJQUFJLElBQUksQ0FBQyxNQUFNLEtBQUssQ0FBQyxFQUFFO1lBQ3RCLDBCQUEwQjtZQUMxQixJQUFJLENBQUMsQ0FBQyxHQUFHLEVBQUUsRUFBRTtnQkFDWixJQUFJLEdBQUcsRUFBRTtvQkFDUixPQUFPLE1BQU0sQ0FBQyxHQUFHLENBQUMsQ0FBQztpQkFDbkI7Z0JBQ0QsT0FBTyxFQUFFLENBQUM7WUFDWCxDQUFDLENBQUMsQ0FBQztZQUNILE9BQU87U0FDUDtRQUVELE1BQU0sVUFBVSxHQUFHLElBQUksRUFBRSxDQUFDO1FBRTFCLElBQUksT0FBTyxVQUFVLEtBQUssV0FBVyxFQUFFO1lBQ3RDLHNCQUFzQjtZQUN0QixPQUFPLEVBQUUsQ0FBQztZQUNWLE9BQU87U0FDUDtRQUVELElBQUksVUFBVSxDQUFDLFVBQVUsQ0FBQyxFQUFFO1lBQzNCLG1DQUFtQztZQUNuQyxVQUFVLENBQUMsSUFBSSxDQUFDLE9BQU8sRUFBRSxNQUFNLENBQUMsQ0FBQztZQUNqQyxPQUFPO1NBQ1A7UUFFRCxrQ0FBa0M7UUFDbEMsVUFBVSxDQUFDLEVBQUUsQ0FBQyxLQUFLLEVBQUUsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxPQUFPLEVBQUUsQ0FBQyxDQUFDO1FBQ3JDLFVBQVUsQ0FBQyxFQUFFLENBQUMsT0FBTyxFQUFFLEdBQUcsQ0FBQyxFQUFFLENBQUMsTUFBTSxDQUFDLEdBQUcsQ0FBQyxDQUFDLENBQUM7SUFDNUMsQ0FBQyxDQUFDLENBQUM7QUFDSixDQUFDO0FBRUQsU0FBZ0IsTUFBTSxDQUFDLEdBQUcsS0FBYTtJQUN0QyxNQUFNLE1BQU0sR0FBRyxLQUFLLElBQUksRUFBRTtRQUN6QixLQUFLLElBQUksQ0FBQyxHQUFHLENBQUMsRUFBRSxDQUFDLEdBQUcsS0FBSyxDQUFDLE1BQU0sRUFBRSxDQUFDLEVBQUUsRUFBRTtZQUN0QyxNQUFNLFFBQVEsQ0FBQyxLQUFLLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQztTQUN6QjtJQUNGLENBQUMsQ0FBQztJQUNGLE1BQU0sQ0FBQyxNQUFNLEdBQUcsS0FBSyxDQUFDO0lBQ3RCLE9BQU8sTUFBTSxDQUFDO0FBQ2YsQ0FBQztBQVJELHdCQVFDO0FBRUQsU0FBZ0IsUUFBUSxDQUFDLEdBQUcsS0FBYTtJQUN4QyxNQUFNLE1BQU0sR0FBRyxLQUFLLElBQUksRUFBRTtRQUN6QixNQUFNLE9BQU8sQ0FBQyxHQUFHLENBQUMsS0FBSyxDQUFDLEdBQUcsQ0FBQyxDQUFDLENBQUMsRUFBRSxDQUFDLFFBQVEsQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUM7SUFDaEQsQ0FBQyxDQUFDO0lBQ0YsTUFBTSxDQUFDLE1BQU0sR0FBRyxLQUFLLENBQUM7SUFDdEIsT0FBTyxNQUFNLENBQUM7QUFDZixDQUFDO0FBTkQsNEJBTUM7QUFFRCxTQUFnQixNQUFNLENBQUMsSUFBWSxFQUFFLElBQVU7SUFDOUMsSUFBSSxJQUFJLENBQUMsTUFBTSxFQUFFO1FBQ2hCLDJCQUEyQjtRQUMzQixNQUFNLFFBQVEsR0FBRyxJQUFJLENBQUMsTUFBTSxDQUFDLElBQUksQ0FBQyxNQUFNLENBQUMsTUFBTSxHQUFHLENBQUMsQ0FBQyxDQUFDO1FBRXJELElBQUksUUFBUSxDQUFDLE1BQU0sSUFBSSxRQUFRLENBQUMsUUFBUSxFQUFFO1lBQ3pDLHdEQUF3RDtZQUN4RCxtQ0FBbUM7WUFDbkMsT0FBTyxNQUFNLENBQUMsSUFBSSxFQUFFLE1BQU0sQ0FBQyxJQUFJLEVBQUUsR0FBRyxFQUFFLENBQUMsT0FBTyxDQUFDLE9BQU8sRUFBRSxDQUFDLENBQUMsQ0FBQztTQUMzRDtRQUVELFFBQVEsQ0FBQyxRQUFRLEdBQUcsSUFBSSxDQUFDO1FBQ3pCLElBQUksQ0FBQyxXQUFXLEdBQUcsSUFBSSxDQUFDO1FBQ3hCLE9BQU8sSUFBSSxDQUFDO0tBQ1o7SUFFRCx3QkFBd0I7SUFDeEIsSUFBSSxDQUFDLFFBQVEsR0FBRyxJQUFJLENBQUM7SUFDckIsSUFBSSxDQUFDLFdBQVcsR0FBRyxJQUFJLENBQUM7SUFDeEIsT0FBTyxJQUFJLENBQUM7QUFDYixDQUFDO0FBcEJELHdCQW9CQyJ9
build/lib/task.js
0
https://github.com/microsoft/vscode/commit/bafda10a370cd7ac835c4a88f5885bf69e02037e
[ 0.0062787714414298534, 0.0007822113111615181, 0.00016794474504422396, 0.00017207452037837356, 0.0018321879906579852 ]
{ "id": 1, "code_window": [ "\t\treturn undefined;\n", "\t});\n", "}\n", "\n", "CommandsRegistry.registerCommand(SET_CONTEXT_COMMAND_ID, setContext);\n", "\n", "CommandsRegistry.registerCommand({\n", "\tid: 'getContextKeyInfo',\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "CommandsRegistry.registerCommand('_setContext', setContext);\n" ], "file_path": "src/vs/platform/contextkey/browser/contextKeyService.ts", "type": "replace", "edit_start_line_idx": 621 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-editor .detected-link, .monaco-editor .detected-link-active { text-decoration: underline; text-underline-position: under; } .monaco-editor .detected-link-active { cursor: pointer; color: var(--vscode-editorLink-activeForeground) !important; }
src/vs/editor/contrib/links/browser/links.css
0
https://github.com/microsoft/vscode/commit/bafda10a370cd7ac835c4a88f5885bf69e02037e
[ 0.0001747318310663104, 0.00017315911827608943, 0.00017158642003778368, 0.00017315911827608943, 0.0000015727055142633617 ]
{ "id": 2, "code_window": [ "\tgetContext(target: IContextKeyServiceTarget | null): IContext;\n", "\n", "\tupdateParent(parentContextKeyService: IContextKeyService): void;\n", "}\n", "\n", "export const SET_CONTEXT_COMMAND_ID = 'setContext';\n", "\n", "function cmp1(key1: string, key2: string): number {\n", "\tif (key1 < key2) {\n", "\t\treturn -1;\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/platform/contextkey/common/contextkey.ts", "type": "replace", "edit_start_line_idx": 1000 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Emitter, Event, PauseableEmitter } from 'vs/base/common/event'; import { Iterable } from 'vs/base/common/iterator'; import { DisposableStore, IDisposable, MutableDisposable } from 'vs/base/common/lifecycle'; import { MarshalledObject } from 'vs/base/common/marshalling'; import { MarshalledId } from 'vs/base/common/marshallingIds'; import { cloneAndChange, distinct } from 'vs/base/common/objects'; import { TernarySearchTree } from 'vs/base/common/ternarySearchTree'; import { URI } from 'vs/base/common/uri'; import { localize } from 'vs/nls'; import { CommandsRegistry } from 'vs/platform/commands/common/commands'; import { ConfigurationTarget, IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { ContextKeyExpression, ContextKeyInfo, ContextKeyValue, IContext, IContextKey, IContextKeyChangeEvent, IContextKeyService, IContextKeyServiceTarget, IReadableSet, RawContextKey, SET_CONTEXT_COMMAND_ID } from 'vs/platform/contextkey/common/contextkey'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; const KEYBINDING_CONTEXT_ATTR = 'data-keybinding-context'; export class Context implements IContext { protected _parent: Context | null; protected _value: Record<string, any>; protected _id: number; constructor(id: number, parent: Context | null) { this._id = id; this._parent = parent; this._value = Object.create(null); this._value['_contextId'] = id; } public get value(): Record<string, any> { return { ...this._value }; } public setValue(key: string, value: any): boolean { // console.log('SET ' + key + ' = ' + value + ' ON ' + this._id); if (this._value[key] !== value) { this._value[key] = value; return true; } return false; } public removeValue(key: string): boolean { // console.log('REMOVE ' + key + ' FROM ' + this._id); if (key in this._value) { delete this._value[key]; return true; } return false; } public getValue<T>(key: string): T | undefined { const ret = this._value[key]; if (typeof ret === 'undefined' && this._parent) { return this._parent.getValue<T>(key); } return ret; } public updateParent(parent: Context): void { this._parent = parent; } public collectAllValues(): Record<string, any> { let result = this._parent ? this._parent.collectAllValues() : Object.create(null); result = { ...result, ...this._value }; delete result['_contextId']; return result; } } class NullContext extends Context { static readonly INSTANCE = new NullContext(); constructor() { super(-1, null); } public override setValue(key: string, value: any): boolean { return false; } public override removeValue(key: string): boolean { return false; } public override getValue<T>(key: string): T | undefined { return undefined; } override collectAllValues(): { [key: string]: any } { return Object.create(null); } } class ConfigAwareContextValuesContainer extends Context { private static readonly _keyPrefix = 'config.'; private readonly _values = TernarySearchTree.forConfigKeys<any>(); private readonly _listener: IDisposable; constructor( id: number, private readonly _configurationService: IConfigurationService, emitter: Emitter<IContextKeyChangeEvent> ) { super(id, null); this._listener = this._configurationService.onDidChangeConfiguration(event => { if (event.source === ConfigurationTarget.DEFAULT) { // new setting, reset everything const allKeys = Array.from(this._values, ([k]) => k); this._values.clear(); emitter.fire(new ArrayContextKeyChangeEvent(allKeys)); } else { const changedKeys: string[] = []; for (const configKey of event.affectedKeys) { const contextKey = `config.${configKey}`; const cachedItems = this._values.findSuperstr(contextKey); if (cachedItems !== undefined) { changedKeys.push(...Iterable.map(cachedItems, ([key]) => key)); this._values.deleteSuperstr(contextKey); } if (this._values.has(contextKey)) { changedKeys.push(contextKey); this._values.delete(contextKey); } } emitter.fire(new ArrayContextKeyChangeEvent(changedKeys)); } }); } dispose(): void { this._listener.dispose(); } override getValue(key: string): any { if (key.indexOf(ConfigAwareContextValuesContainer._keyPrefix) !== 0) { return super.getValue(key); } if (this._values.has(key)) { return this._values.get(key); } const configKey = key.substr(ConfigAwareContextValuesContainer._keyPrefix.length); const configValue = this._configurationService.getValue(configKey); let value: any = undefined; switch (typeof configValue) { case 'number': case 'boolean': case 'string': value = configValue; break; default: if (Array.isArray(configValue)) { value = JSON.stringify(configValue); } else { value = configValue; } } this._values.set(key, value); return value; } override setValue(key: string, value: any): boolean { return super.setValue(key, value); } override removeValue(key: string): boolean { return super.removeValue(key); } override collectAllValues(): { [key: string]: any } { const result: { [key: string]: any } = Object.create(null); this._values.forEach((value, index) => result[index] = value); return { ...result, ...super.collectAllValues() }; } } class ContextKey<T extends ContextKeyValue> implements IContextKey<T> { private _service: AbstractContextKeyService; private _key: string; private _defaultValue: T | undefined; constructor(service: AbstractContextKeyService, key: string, defaultValue: T | undefined) { this._service = service; this._key = key; this._defaultValue = defaultValue; this.reset(); } public set(value: T): void { this._service.setContext(this._key, value); } public reset(): void { if (typeof this._defaultValue === 'undefined') { this._service.removeContext(this._key); } else { this._service.setContext(this._key, this._defaultValue); } } public get(): T | undefined { return this._service.getContextKeyValue<T>(this._key); } } class SimpleContextKeyChangeEvent implements IContextKeyChangeEvent { constructor(readonly key: string) { } affectsSome(keys: IReadableSet<string>): boolean { return keys.has(this.key); } allKeysContainedIn(keys: IReadableSet<string>): boolean { return this.affectsSome(keys); } } class ArrayContextKeyChangeEvent implements IContextKeyChangeEvent { constructor(readonly keys: string[]) { } affectsSome(keys: IReadableSet<string>): boolean { for (const key of this.keys) { if (keys.has(key)) { return true; } } return false; } allKeysContainedIn(keys: IReadableSet<string>): boolean { return this.keys.every(key => keys.has(key)); } } class CompositeContextKeyChangeEvent implements IContextKeyChangeEvent { constructor(readonly events: IContextKeyChangeEvent[]) { } affectsSome(keys: IReadableSet<string>): boolean { for (const e of this.events) { if (e.affectsSome(keys)) { return true; } } return false; } allKeysContainedIn(keys: IReadableSet<string>): boolean { return this.events.every(evt => evt.allKeysContainedIn(keys)); } } function allEventKeysInContext(event: IContextKeyChangeEvent, context: Record<string, any>): boolean { return event.allKeysContainedIn(new Set(Object.keys(context))); } export abstract class AbstractContextKeyService implements IContextKeyService { declare _serviceBrand: undefined; protected _isDisposed: boolean; protected _myContextId: number; protected _onDidChangeContext = new PauseableEmitter<IContextKeyChangeEvent>({ merge: input => new CompositeContextKeyChangeEvent(input) }); readonly onDidChangeContext = this._onDidChangeContext.event; constructor(myContextId: number) { this._isDisposed = false; this._myContextId = myContextId; } public get contextId(): number { return this._myContextId; } abstract dispose(): void; public createKey<T extends ContextKeyValue>(key: string, defaultValue: T | undefined): IContextKey<T> { if (this._isDisposed) { throw new Error(`AbstractContextKeyService has been disposed`); } return new ContextKey(this, key, defaultValue); } bufferChangeEvents(callback: Function): void { this._onDidChangeContext.pause(); try { callback(); } finally { this._onDidChangeContext.resume(); } } public createScoped(domNode: IContextKeyServiceTarget): IContextKeyService { if (this._isDisposed) { throw new Error(`AbstractContextKeyService has been disposed`); } return new ScopedContextKeyService(this, domNode); } createOverlay(overlay: Iterable<[string, any]> = Iterable.empty()): IContextKeyService { if (this._isDisposed) { throw new Error(`AbstractContextKeyService has been disposed`); } return new OverlayContextKeyService(this, overlay); } public contextMatchesRules(rules: ContextKeyExpression | undefined): boolean { if (this._isDisposed) { throw new Error(`AbstractContextKeyService has been disposed`); } const context = this.getContextValuesContainer(this._myContextId); const result = (rules ? rules.evaluate(context) : true); // console.group(rules.serialize() + ' -> ' + result); // rules.keys().forEach(key => { console.log(key, ctx[key]); }); // console.groupEnd(); return result; } public getContextKeyValue<T>(key: string): T | undefined { if (this._isDisposed) { return undefined; } return this.getContextValuesContainer(this._myContextId).getValue<T>(key); } public setContext(key: string, value: any): void { if (this._isDisposed) { return; } const myContext = this.getContextValuesContainer(this._myContextId); if (!myContext) { return; } if (myContext.setValue(key, value)) { this._onDidChangeContext.fire(new SimpleContextKeyChangeEvent(key)); } } public removeContext(key: string): void { if (this._isDisposed) { return; } if (this.getContextValuesContainer(this._myContextId).removeValue(key)) { this._onDidChangeContext.fire(new SimpleContextKeyChangeEvent(key)); } } public getContext(target: IContextKeyServiceTarget | null): IContext { if (this._isDisposed) { return NullContext.INSTANCE; } return this.getContextValuesContainer(findContextAttr(target)); } public abstract getContextValuesContainer(contextId: number): Context; public abstract createChildContext(parentContextId?: number): number; public abstract disposeContext(contextId: number): void; public abstract updateParent(parentContextKeyService?: IContextKeyService): void; } export class ContextKeyService extends AbstractContextKeyService implements IContextKeyService { private _lastContextId: number; private readonly _contexts = new Map<number, Context>(); private readonly _toDispose = new DisposableStore(); constructor(@IConfigurationService configurationService: IConfigurationService) { super(0); this._lastContextId = 0; const myContext = new ConfigAwareContextValuesContainer(this._myContextId, configurationService, this._onDidChangeContext); this._contexts.set(this._myContextId, myContext); this._toDispose.add(myContext); // Uncomment this to see the contexts continuously logged // let lastLoggedValue: string | null = null; // setInterval(() => { // let values = Object.keys(this._contexts).map((key) => this._contexts[key]); // let logValue = values.map(v => JSON.stringify(v._value, null, '\t')).join('\n'); // if (lastLoggedValue !== logValue) { // lastLoggedValue = logValue; // console.log(lastLoggedValue); // } // }, 2000); } public dispose(): void { this._onDidChangeContext.dispose(); this._isDisposed = true; this._toDispose.dispose(); } public getContextValuesContainer(contextId: number): Context { if (this._isDisposed) { return NullContext.INSTANCE; } return this._contexts.get(contextId) || NullContext.INSTANCE; } public createChildContext(parentContextId: number = this._myContextId): number { if (this._isDisposed) { throw new Error(`ContextKeyService has been disposed`); } const id = (++this._lastContextId); this._contexts.set(id, new Context(id, this.getContextValuesContainer(parentContextId))); return id; } public disposeContext(contextId: number): void { if (!this._isDisposed) { this._contexts.delete(contextId); } } public updateParent(_parentContextKeyService: IContextKeyService): void { throw new Error('Cannot update parent of root ContextKeyService'); } } class ScopedContextKeyService extends AbstractContextKeyService { private _parent: AbstractContextKeyService; private _domNode: IContextKeyServiceTarget; private readonly _parentChangeListener = new MutableDisposable(); constructor(parent: AbstractContextKeyService, domNode: IContextKeyServiceTarget) { super(parent.createChildContext()); this._parent = parent; this._updateParentChangeListener(); this._domNode = domNode; if (this._domNode.hasAttribute(KEYBINDING_CONTEXT_ATTR)) { let extraInfo = ''; if ((this._domNode as HTMLElement).classList) { extraInfo = Array.from((this._domNode as HTMLElement).classList.values()).join(', '); } console.error(`Element already has context attribute${extraInfo ? ': ' + extraInfo : ''}`); } this._domNode.setAttribute(KEYBINDING_CONTEXT_ATTR, String(this._myContextId)); } private _updateParentChangeListener(): void { // Forward parent events to this listener. Parent will change. this._parentChangeListener.value = this._parent.onDidChangeContext(e => { const thisContainer = this._parent.getContextValuesContainer(this._myContextId); const thisContextValues = thisContainer.value; if (!allEventKeysInContext(e, thisContextValues)) { this._onDidChangeContext.fire(e); } }); } public dispose(): void { if (this._isDisposed) { return; } this._onDidChangeContext.dispose(); this._parent.disposeContext(this._myContextId); this._parentChangeListener.dispose(); this._domNode.removeAttribute(KEYBINDING_CONTEXT_ATTR); this._isDisposed = true; } public getContextValuesContainer(contextId: number): Context { if (this._isDisposed) { return NullContext.INSTANCE; } return this._parent.getContextValuesContainer(contextId); } public createChildContext(parentContextId: number = this._myContextId): number { if (this._isDisposed) { throw new Error(`ScopedContextKeyService has been disposed`); } return this._parent.createChildContext(parentContextId); } public disposeContext(contextId: number): void { if (this._isDisposed) { return; } this._parent.disposeContext(contextId); } public updateParent(parentContextKeyService: AbstractContextKeyService): void { const thisContainer = this._parent.getContextValuesContainer(this._myContextId); const oldAllValues = thisContainer.collectAllValues(); this._parent = parentContextKeyService; this._updateParentChangeListener(); const newParentContainer = this._parent.getContextValuesContainer(this._parent.contextId); thisContainer.updateParent(newParentContainer); const newAllValues = thisContainer.collectAllValues(); const allValuesDiff = { ...distinct(oldAllValues, newAllValues), ...distinct(newAllValues, oldAllValues) }; const changedKeys = Object.keys(allValuesDiff); this._onDidChangeContext.fire(new ArrayContextKeyChangeEvent(changedKeys)); } } class OverlayContext implements IContext { constructor(private parent: IContext, private overlay: ReadonlyMap<string, any>) { } getValue<T>(key: string): T | undefined { return this.overlay.has(key) ? this.overlay.get(key) : this.parent.getValue(key); } } class OverlayContextKeyService implements IContextKeyService { declare _serviceBrand: undefined; private overlay: Map<string, any>; get contextId(): number { return this.parent.contextId; } get onDidChangeContext(): Event<IContextKeyChangeEvent> { return this.parent.onDidChangeContext; } constructor(private parent: AbstractContextKeyService | OverlayContextKeyService, overlay: Iterable<[string, any]>) { this.overlay = new Map(overlay); } bufferChangeEvents(callback: Function): void { this.parent.bufferChangeEvents(callback); } createKey<T extends ContextKeyValue>(): IContextKey<T> { throw new Error('Not supported.'); } getContext(target: IContextKeyServiceTarget | null): IContext { return new OverlayContext(this.parent.getContext(target), this.overlay); } getContextValuesContainer(contextId: number): IContext { const parentContext = this.parent.getContextValuesContainer(contextId); return new OverlayContext(parentContext, this.overlay); } contextMatchesRules(rules: ContextKeyExpression | undefined): boolean { const context = this.getContextValuesContainer(this.contextId); const result = (rules ? rules.evaluate(context) : true); return result; } getContextKeyValue<T>(key: string): T | undefined { return this.overlay.has(key) ? this.overlay.get(key) : this.parent.getContextKeyValue(key); } createScoped(): IContextKeyService { throw new Error('Not supported.'); } createOverlay(overlay: Iterable<[string, any]> = Iterable.empty()): IContextKeyService { return new OverlayContextKeyService(this, overlay); } updateParent(): void { throw new Error('Not supported.'); } dispose(): void { // noop } } function findContextAttr(domNode: IContextKeyServiceTarget | null): number { while (domNode) { if (domNode.hasAttribute(KEYBINDING_CONTEXT_ATTR)) { const attr = domNode.getAttribute(KEYBINDING_CONTEXT_ATTR); if (attr) { return parseInt(attr, 10); } return NaN; } domNode = domNode.parentElement; } return 0; } export function setContext(accessor: ServicesAccessor, contextKey: any, contextValue: any) { const contextKeyService = accessor.get(IContextKeyService); contextKeyService.createKey(String(contextKey), stringifyURIs(contextValue)); } function stringifyURIs(contextValue: any): any { return cloneAndChange(contextValue, (obj) => { if (typeof obj === 'object' && (<MarshalledObject>obj).$mid === MarshalledId.Uri) { return URI.revive(obj).toString(); } if (obj instanceof URI) { return obj.toString(); } return undefined; }); } CommandsRegistry.registerCommand(SET_CONTEXT_COMMAND_ID, setContext); CommandsRegistry.registerCommand({ id: 'getContextKeyInfo', handler() { return [...RawContextKey.all()].sort((a, b) => a.key.localeCompare(b.key)); }, description: { description: localize('getContextKeyInfo', "A command that returns information about context keys"), args: [] } }); CommandsRegistry.registerCommand('_generateContextKeyInfo', function () { const result: ContextKeyInfo[] = []; const seen = new Set<string>(); for (const info of RawContextKey.all()) { if (!seen.has(info.key)) { seen.add(info.key); result.push(info); } } result.sort((a, b) => a.key.localeCompare(b.key)); console.log(JSON.stringify(result, undefined, 2)); });
src/vs/platform/contextkey/browser/contextKeyService.ts
1
https://github.com/microsoft/vscode/commit/bafda10a370cd7ac835c4a88f5885bf69e02037e
[ 0.9992167949676514, 0.03295475244522095, 0.00016369554214179516, 0.0007686906610615551, 0.1716182380914688 ]
{ "id": 2, "code_window": [ "\tgetContext(target: IContextKeyServiceTarget | null): IContext;\n", "\n", "\tupdateParent(parentContextKeyService: IContextKeyService): void;\n", "}\n", "\n", "export const SET_CONTEXT_COMMAND_ID = 'setContext';\n", "\n", "function cmp1(key1: string, key2: string): number {\n", "\tif (key1 < key2) {\n", "\t\treturn -1;\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/platform/contextkey/common/contextkey.ts", "type": "replace", "edit_start_line_idx": 1000 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { $, addDisposableListener, clearNode, EventHelper, EventType, hide, isAncestor, show } from 'vs/base/browser/dom'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar'; import { ButtonBar, ButtonWithDescription, IButtonStyles } from 'vs/base/browser/ui/button/button'; import { ICheckboxStyles, Checkbox } from 'vs/base/browser/ui/toggle/toggle'; import { IInputBoxStyles, InputBox } from 'vs/base/browser/ui/inputbox/inputBox'; import { Action } from 'vs/base/common/actions'; import { Codicon } from 'vs/base/common/codicons'; import { KeyCode, KeyMod } from 'vs/base/common/keyCodes'; import { mnemonicButtonLabel } from 'vs/base/common/labels'; import { Disposable } from 'vs/base/common/lifecycle'; import { isLinux, isMacintosh } from 'vs/base/common/platform'; import 'vs/css!./dialog'; import * as nls from 'vs/nls'; export interface IDialogInputOptions { readonly placeholder?: string; readonly type?: 'text' | 'password'; readonly value?: string; } export interface IDialogOptions { readonly cancelId?: number; readonly detail?: string; readonly checkboxLabel?: string; readonly checkboxChecked?: boolean; readonly type?: 'none' | 'info' | 'error' | 'question' | 'warning' | 'pending'; readonly inputs?: IDialogInputOptions[]; readonly keyEventProcessor?: (event: StandardKeyboardEvent) => void; readonly renderBody?: (container: HTMLElement) => void; readonly icon?: Codicon; readonly buttonDetails?: string[]; readonly disableCloseAction?: boolean; readonly disableDefaultAction?: boolean; readonly buttonStyles: IButtonStyles; readonly checkboxStyles: ICheckboxStyles; readonly inputBoxStyles: IInputBoxStyles; readonly dialogStyles: IDialogStyles; } export interface IDialogResult { readonly button: number; readonly checkboxChecked?: boolean; readonly values?: string[]; } export interface IDialogStyles { readonly dialogForeground: string | undefined; readonly dialogBackground: string | undefined; readonly dialogShadow: string | undefined; readonly dialogBorder: string | undefined; readonly errorIconForeground: string | undefined; readonly warningIconForeground: string | undefined; readonly infoIconForeground: string | undefined; readonly textLinkForeground: string | undefined; } interface ButtonMapEntry { readonly label: string; readonly index: number; } export class Dialog extends Disposable { private readonly element: HTMLElement; private readonly shadowElement: HTMLElement; private modalElement: HTMLElement | undefined; private readonly buttonsContainer: HTMLElement; private readonly messageDetailElement: HTMLElement; private readonly messageContainer: HTMLElement; private readonly iconElement: HTMLElement; private readonly checkbox: Checkbox | undefined; private readonly toolbarContainer: HTMLElement; private buttonBar: ButtonBar | undefined; private focusToReturn: HTMLElement | undefined; private readonly inputs: InputBox[]; private readonly buttons: string[]; private readonly buttonStyles: IButtonStyles; constructor(private container: HTMLElement, private message: string, buttons: string[] | undefined, private readonly options: IDialogOptions) { super(); this.modalElement = this.container.appendChild($(`.monaco-dialog-modal-block.dimmed`)); this.shadowElement = this.modalElement.appendChild($('.dialog-shadow')); this.element = this.shadowElement.appendChild($('.monaco-dialog-box')); this.element.setAttribute('role', 'dialog'); this.element.tabIndex = -1; hide(this.element); this.buttonStyles = options.buttonStyles; if (Array.isArray(buttons) && buttons.length > 0) { this.buttons = buttons; } else if (!this.options.disableDefaultAction) { this.buttons = [nls.localize('ok', "OK")]; } else { this.buttons = []; } const buttonsRowElement = this.element.appendChild($('.dialog-buttons-row')); this.buttonsContainer = buttonsRowElement.appendChild($('.dialog-buttons')); const messageRowElement = this.element.appendChild($('.dialog-message-row')); this.iconElement = messageRowElement.appendChild($('#monaco-dialog-icon.dialog-icon')); this.iconElement.setAttribute('aria-label', this.getIconAriaLabel()); this.messageContainer = messageRowElement.appendChild($('.dialog-message-container')); if (this.options.detail || this.options.renderBody) { const messageElement = this.messageContainer.appendChild($('.dialog-message')); const messageTextElement = messageElement.appendChild($('#monaco-dialog-message-text.dialog-message-text')); messageTextElement.innerText = this.message; } this.messageDetailElement = this.messageContainer.appendChild($('#monaco-dialog-message-detail.dialog-message-detail')); if (this.options.detail || !this.options.renderBody) { this.messageDetailElement.innerText = this.options.detail ? this.options.detail : message; } else { this.messageDetailElement.style.display = 'none'; } if (this.options.renderBody) { const customBody = this.messageContainer.appendChild($('#monaco-dialog-message-body.dialog-message-body')); this.options.renderBody(customBody); for (const el of this.messageContainer.querySelectorAll('a')) { el.tabIndex = 0; } } if (this.options.inputs) { this.inputs = this.options.inputs.map(input => { const inputRowElement = this.messageContainer.appendChild($('.dialog-message-input')); const inputBox = this._register(new InputBox(inputRowElement, undefined, { placeholder: input.placeholder, type: input.type ?? 'text', inputBoxStyles: options.inputBoxStyles })); if (input.value) { inputBox.value = input.value; } return inputBox; }); } else { this.inputs = []; } if (this.options.checkboxLabel) { const checkboxRowElement = this.messageContainer.appendChild($('.dialog-checkbox-row')); const checkbox = this.checkbox = this._register( new Checkbox(this.options.checkboxLabel, !!this.options.checkboxChecked, options.checkboxStyles) ); checkboxRowElement.appendChild(checkbox.domNode); const checkboxMessageElement = checkboxRowElement.appendChild($('.dialog-checkbox-message')); checkboxMessageElement.innerText = this.options.checkboxLabel; this._register(addDisposableListener(checkboxMessageElement, EventType.CLICK, () => checkbox.checked = !checkbox.checked)); } const toolbarRowElement = this.element.appendChild($('.dialog-toolbar-row')); this.toolbarContainer = toolbarRowElement.appendChild($('.dialog-toolbar')); this.applyStyles(); } private getIconAriaLabel(): string { const typeLabel = nls.localize('dialogInfoMessage', 'Info'); switch (this.options.type) { case 'error': nls.localize('dialogErrorMessage', 'Error'); break; case 'warning': nls.localize('dialogWarningMessage', 'Warning'); break; case 'pending': nls.localize('dialogPendingMessage', 'In Progress'); break; case 'none': case 'info': case 'question': default: break; } return typeLabel; } updateMessage(message: string): void { this.messageDetailElement.innerText = message; } async show(): Promise<IDialogResult> { this.focusToReturn = document.activeElement as HTMLElement; return new Promise<IDialogResult>((resolve) => { clearNode(this.buttonsContainer); const buttonBar = this.buttonBar = this._register(new ButtonBar(this.buttonsContainer)); const buttonMap = this.rearrangeButtons(this.buttons, this.options.cancelId); // Handle button clicks buttonMap.forEach((entry, index) => { const primary = buttonMap[index].index === 0; const button = this.options.buttonDetails ? this._register(buttonBar.addButtonWithDescription({ title: true, secondary: !primary, ...this.buttonStyles })) : this._register(buttonBar.addButton({ title: true, secondary: !primary, ...this.buttonStyles })); button.label = mnemonicButtonLabel(buttonMap[index].label, true); if (button instanceof ButtonWithDescription) { button.description = this.options.buttonDetails![buttonMap[index].index]; } this._register(button.onDidClick(e => { if (e) { EventHelper.stop(e); } resolve({ button: buttonMap[index].index, checkboxChecked: this.checkbox ? this.checkbox.checked : undefined, values: this.inputs.length > 0 ? this.inputs.map(input => input.value) : undefined }); })); }); // Handle keyboard events globally: Tab, Arrow-Left/Right this._register(addDisposableListener(window, 'keydown', e => { const evt = new StandardKeyboardEvent(e); if (evt.equals(KeyMod.Alt)) { evt.preventDefault(); } if (evt.equals(KeyCode.Enter)) { // Enter in input field should OK the dialog if (this.inputs.some(input => input.hasFocus())) { EventHelper.stop(e); resolve({ button: buttonMap.find(button => button.index !== this.options.cancelId)?.index ?? 0, checkboxChecked: this.checkbox ? this.checkbox.checked : undefined, values: this.inputs.length > 0 ? this.inputs.map(input => input.value) : undefined }); } return; // leave default handling } if (evt.equals(KeyCode.Space)) { return; // leave default handling } let eventHandled = false; // Focus: Next / Previous if (evt.equals(KeyCode.Tab) || evt.equals(KeyCode.RightArrow) || evt.equals(KeyMod.Shift | KeyCode.Tab) || evt.equals(KeyCode.LeftArrow)) { // Build a list of focusable elements in their visual order const focusableElements: { focus: () => void }[] = []; let focusedIndex = -1; if (this.messageContainer) { const links = this.messageContainer.querySelectorAll('a'); for (const link of links) { focusableElements.push(link); if (link === document.activeElement) { focusedIndex = focusableElements.length - 1; } } } for (const input of this.inputs) { focusableElements.push(input); if (input.hasFocus()) { focusedIndex = focusableElements.length - 1; } } if (this.checkbox) { focusableElements.push(this.checkbox); if (this.checkbox.hasFocus()) { focusedIndex = focusableElements.length - 1; } } if (this.buttonBar) { for (const button of this.buttonBar.buttons) { focusableElements.push(button); if (button.hasFocus()) { focusedIndex = focusableElements.length - 1; } } } // Focus next element (with wrapping) if (evt.equals(KeyCode.Tab) || evt.equals(KeyCode.RightArrow)) { if (focusedIndex === -1) { focusedIndex = 0; // default to focus first element if none have focus } const newFocusedIndex = (focusedIndex + 1) % focusableElements.length; focusableElements[newFocusedIndex].focus(); } // Focus previous element (with wrapping) else { if (focusedIndex === -1) { focusedIndex = focusableElements.length; // default to focus last element if none have focus } let newFocusedIndex = focusedIndex - 1; if (newFocusedIndex === -1) { newFocusedIndex = focusableElements.length - 1; } focusableElements[newFocusedIndex].focus(); } eventHandled = true; } if (eventHandled) { EventHelper.stop(e, true); } else if (this.options.keyEventProcessor) { this.options.keyEventProcessor(evt); } }, true)); this._register(addDisposableListener(window, 'keyup', e => { EventHelper.stop(e, true); const evt = new StandardKeyboardEvent(e); if (!this.options.disableCloseAction && evt.equals(KeyCode.Escape)) { resolve({ button: this.options.cancelId || 0, checkboxChecked: this.checkbox ? this.checkbox.checked : undefined }); } }, true)); // Detect focus out this._register(addDisposableListener(this.element, 'focusout', e => { if (!!e.relatedTarget && !!this.element) { if (!isAncestor(e.relatedTarget as HTMLElement, this.element)) { this.focusToReturn = e.relatedTarget as HTMLElement; if (e.target) { (e.target as HTMLElement).focus(); EventHelper.stop(e, true); } } } }, false)); const spinModifierClassName = 'codicon-modifier-spin'; this.iconElement.classList.remove(...Codicon.dialogError.classNamesArray, ...Codicon.dialogWarning.classNamesArray, ...Codicon.dialogInfo.classNamesArray, ...Codicon.loading.classNamesArray, spinModifierClassName); if (this.options.icon) { this.iconElement.classList.add(...this.options.icon.classNamesArray); } else { switch (this.options.type) { case 'error': this.iconElement.classList.add(...Codicon.dialogError.classNamesArray); break; case 'warning': this.iconElement.classList.add(...Codicon.dialogWarning.classNamesArray); break; case 'pending': this.iconElement.classList.add(...Codicon.loading.classNamesArray, spinModifierClassName); break; case 'none': case 'info': case 'question': default: this.iconElement.classList.add(...Codicon.dialogInfo.classNamesArray); break; } } if (!this.options.disableCloseAction) { const actionBar = this._register(new ActionBar(this.toolbarContainer, {})); const action = this._register(new Action('dialog.close', nls.localize('dialogClose', "Close Dialog"), Codicon.dialogClose.classNames, true, async () => { resolve({ button: this.options.cancelId || 0, checkboxChecked: this.checkbox ? this.checkbox.checked : undefined }); })); actionBar.push(action, { icon: true, label: false }); } this.applyStyles(); this.element.setAttribute('aria-modal', 'true'); this.element.setAttribute('aria-labelledby', 'monaco-dialog-icon monaco-dialog-message-text'); this.element.setAttribute('aria-describedby', 'monaco-dialog-icon monaco-dialog-message-text monaco-dialog-message-detail monaco-dialog-message-body'); show(this.element); // Focus first element (input or button) if (this.inputs.length > 0) { this.inputs[0].focus(); this.inputs[0].select(); } else { buttonMap.forEach((value, index) => { if (value.index === 0) { buttonBar.buttons[index].focus(); } }); } }); } private applyStyles() { const style = this.options.dialogStyles; const fgColor = style.dialogForeground; const bgColor = style.dialogBackground; const shadowColor = style.dialogShadow ? `0 0px 8px ${style.dialogShadow}` : ''; const border = style.dialogBorder ? `1px solid ${style.dialogBorder}` : ''; const linkFgColor = style.textLinkForeground; this.shadowElement.style.boxShadow = shadowColor; this.element.style.color = fgColor?.toString() ?? ''; this.element.style.backgroundColor = bgColor?.toString() ?? ''; this.element.style.border = border; // TODO fix // if (fgColor && bgColor) { // const messageDetailColor = fgColor.transparent(.9); // this.messageDetailElement.style.mixBlendMode = messageDetailColor.makeOpaque(bgColor).toString(); // } if (linkFgColor) { for (const el of this.messageContainer.getElementsByTagName('a')) { el.style.color = linkFgColor; } } let color; switch (this.options.type) { case 'error': color = style.errorIconForeground; break; case 'warning': color = style.warningIconForeground; break; default: color = style.infoIconForeground; break; } if (color) { this.iconElement.style.color = color; } } override dispose(): void { super.dispose(); if (this.modalElement) { this.modalElement.remove(); this.modalElement = undefined; } if (this.focusToReturn && isAncestor(this.focusToReturn, document.body)) { this.focusToReturn.focus(); this.focusToReturn = undefined; } } private rearrangeButtons(buttons: Array<string>, cancelId: number | undefined): ButtonMapEntry[] { const buttonMap: ButtonMapEntry[] = []; if (buttons.length === 0) { return buttonMap; } // Maps each button to its current label and old index so that when we move them around it's not a problem buttons.forEach((button, index) => { buttonMap.push({ label: button, index }); }); // macOS/linux: reverse button order if `cancelId` is defined if (isMacintosh || isLinux) { if (cancelId !== undefined && cancelId < buttons.length) { const cancelButton = buttonMap.splice(cancelId, 1)[0]; buttonMap.reverse(); buttonMap.splice(buttonMap.length - 1, 0, cancelButton); } } return buttonMap; } }
src/vs/base/browser/ui/dialog/dialog.ts
0
https://github.com/microsoft/vscode/commit/bafda10a370cd7ac835c4a88f5885bf69e02037e
[ 0.00019801949383690953, 0.0001737690472509712, 0.00016484838852193207, 0.00017325347289443016, 0.000005282050551613793 ]
{ "id": 2, "code_window": [ "\tgetContext(target: IContextKeyServiceTarget | null): IContext;\n", "\n", "\tupdateParent(parentContextKeyService: IContextKeyService): void;\n", "}\n", "\n", "export const SET_CONTEXT_COMMAND_ID = 'setContext';\n", "\n", "function cmp1(key1: string, key2: string): number {\n", "\tif (key1 < key2) {\n", "\t\treturn -1;\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/platform/contextkey/common/contextkey.ts", "type": "replace", "edit_start_line_idx": 1000 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IEmptyWindowBackupInfo } from 'vs/platform/backup/node/backup'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { IFolderBackupInfo, IWorkspaceBackupInfo } from 'vs/platform/backup/common/backup'; export const IBackupMainService = createDecorator<IBackupMainService>('backupMainService'); export interface IBackupMainService { readonly _serviceBrand: undefined; isHotExitEnabled(): boolean; getEmptyWindowBackups(): IEmptyWindowBackupInfo[]; registerWorkspaceBackup(workspaceInfo: IWorkspaceBackupInfo): string; registerWorkspaceBackup(workspaceInfo: IWorkspaceBackupInfo, migrateFrom: string): Promise<string>; registerFolderBackup(folderInfo: IFolderBackupInfo): string; registerEmptyWindowBackup(emptyWindowInfo: IEmptyWindowBackupInfo): string; /** * All folders or workspaces that are known to have * backups stored. This call is long running because * it checks for each backup location if any backups * are stored. */ getDirtyWorkspaces(): Promise<Array<IWorkspaceBackupInfo | IFolderBackupInfo>>; }
src/vs/platform/backup/electron-main/backup.ts
0
https://github.com/microsoft/vscode/commit/bafda10a370cd7ac835c4a88f5885bf69e02037e
[ 0.0002553528465796262, 0.00018889494822360575, 0.00016322203737217933, 0.00016850244719535112, 0.00003843157537630759 ]
{ "id": 2, "code_window": [ "\tgetContext(target: IContextKeyServiceTarget | null): IContext;\n", "\n", "\tupdateParent(parentContextKeyService: IContextKeyService): void;\n", "}\n", "\n", "export const SET_CONTEXT_COMMAND_ID = 'setContext';\n", "\n", "function cmp1(key1: string, key2: string): number {\n", "\tif (key1 < key2) {\n", "\t\treturn -1;\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/platform/contextkey/common/contextkey.ts", "type": "replace", "edit_start_line_idx": 1000 }
Small File
src/vs/platform/files/test/node/fixtures/service/small.txt
0
https://github.com/microsoft/vscode/commit/bafda10a370cd7ac835c4a88f5885bf69e02037e
[ 0.00017627404304221272, 0.00017627404304221272, 0.00017627404304221272, 0.00017627404304221272, 0 ]
{ "id": 3, "code_window": [ "\tnew ApiCommand(\n", "\t\t'vscode.experimental.editSession.continue', '_workbench.editSessions.actions.continueEditSession', 'Continue the current edit session in a different workspace',\n", "\t\t[ApiCommandArgument.Uri.with('workspaceUri', 'The target workspace to continue the current edit session in')],\n", "\t\tApiCommandResult.Void\n", "\t)\n", "];\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t),\n", "\t// --- context keys\n", "\tnew ApiCommand(\n", "\t\t'setContext', '_setContext', 'Set a custom context key value that can be used in when clauses.',\n", "\t\t[\n", "\t\t\tApiCommandArgument.String.with('name', 'The context key name'),\n", "\t\t\tnew ApiCommandArgument('value', 'The context key value', () => true, v => v),\n", "\t\t],\n", "\t\tApiCommandResult.Void\n" ], "file_path": "src/vs/workbench/api/common/extHostApiCommands.ts", "type": "add", "edit_start_line_idx": 444 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Emitter, Event, PauseableEmitter } from 'vs/base/common/event'; import { Iterable } from 'vs/base/common/iterator'; import { DisposableStore, IDisposable, MutableDisposable } from 'vs/base/common/lifecycle'; import { MarshalledObject } from 'vs/base/common/marshalling'; import { MarshalledId } from 'vs/base/common/marshallingIds'; import { cloneAndChange, distinct } from 'vs/base/common/objects'; import { TernarySearchTree } from 'vs/base/common/ternarySearchTree'; import { URI } from 'vs/base/common/uri'; import { localize } from 'vs/nls'; import { CommandsRegistry } from 'vs/platform/commands/common/commands'; import { ConfigurationTarget, IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { ContextKeyExpression, ContextKeyInfo, ContextKeyValue, IContext, IContextKey, IContextKeyChangeEvent, IContextKeyService, IContextKeyServiceTarget, IReadableSet, RawContextKey, SET_CONTEXT_COMMAND_ID } from 'vs/platform/contextkey/common/contextkey'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; const KEYBINDING_CONTEXT_ATTR = 'data-keybinding-context'; export class Context implements IContext { protected _parent: Context | null; protected _value: Record<string, any>; protected _id: number; constructor(id: number, parent: Context | null) { this._id = id; this._parent = parent; this._value = Object.create(null); this._value['_contextId'] = id; } public get value(): Record<string, any> { return { ...this._value }; } public setValue(key: string, value: any): boolean { // console.log('SET ' + key + ' = ' + value + ' ON ' + this._id); if (this._value[key] !== value) { this._value[key] = value; return true; } return false; } public removeValue(key: string): boolean { // console.log('REMOVE ' + key + ' FROM ' + this._id); if (key in this._value) { delete this._value[key]; return true; } return false; } public getValue<T>(key: string): T | undefined { const ret = this._value[key]; if (typeof ret === 'undefined' && this._parent) { return this._parent.getValue<T>(key); } return ret; } public updateParent(parent: Context): void { this._parent = parent; } public collectAllValues(): Record<string, any> { let result = this._parent ? this._parent.collectAllValues() : Object.create(null); result = { ...result, ...this._value }; delete result['_contextId']; return result; } } class NullContext extends Context { static readonly INSTANCE = new NullContext(); constructor() { super(-1, null); } public override setValue(key: string, value: any): boolean { return false; } public override removeValue(key: string): boolean { return false; } public override getValue<T>(key: string): T | undefined { return undefined; } override collectAllValues(): { [key: string]: any } { return Object.create(null); } } class ConfigAwareContextValuesContainer extends Context { private static readonly _keyPrefix = 'config.'; private readonly _values = TernarySearchTree.forConfigKeys<any>(); private readonly _listener: IDisposable; constructor( id: number, private readonly _configurationService: IConfigurationService, emitter: Emitter<IContextKeyChangeEvent> ) { super(id, null); this._listener = this._configurationService.onDidChangeConfiguration(event => { if (event.source === ConfigurationTarget.DEFAULT) { // new setting, reset everything const allKeys = Array.from(this._values, ([k]) => k); this._values.clear(); emitter.fire(new ArrayContextKeyChangeEvent(allKeys)); } else { const changedKeys: string[] = []; for (const configKey of event.affectedKeys) { const contextKey = `config.${configKey}`; const cachedItems = this._values.findSuperstr(contextKey); if (cachedItems !== undefined) { changedKeys.push(...Iterable.map(cachedItems, ([key]) => key)); this._values.deleteSuperstr(contextKey); } if (this._values.has(contextKey)) { changedKeys.push(contextKey); this._values.delete(contextKey); } } emitter.fire(new ArrayContextKeyChangeEvent(changedKeys)); } }); } dispose(): void { this._listener.dispose(); } override getValue(key: string): any { if (key.indexOf(ConfigAwareContextValuesContainer._keyPrefix) !== 0) { return super.getValue(key); } if (this._values.has(key)) { return this._values.get(key); } const configKey = key.substr(ConfigAwareContextValuesContainer._keyPrefix.length); const configValue = this._configurationService.getValue(configKey); let value: any = undefined; switch (typeof configValue) { case 'number': case 'boolean': case 'string': value = configValue; break; default: if (Array.isArray(configValue)) { value = JSON.stringify(configValue); } else { value = configValue; } } this._values.set(key, value); return value; } override setValue(key: string, value: any): boolean { return super.setValue(key, value); } override removeValue(key: string): boolean { return super.removeValue(key); } override collectAllValues(): { [key: string]: any } { const result: { [key: string]: any } = Object.create(null); this._values.forEach((value, index) => result[index] = value); return { ...result, ...super.collectAllValues() }; } } class ContextKey<T extends ContextKeyValue> implements IContextKey<T> { private _service: AbstractContextKeyService; private _key: string; private _defaultValue: T | undefined; constructor(service: AbstractContextKeyService, key: string, defaultValue: T | undefined) { this._service = service; this._key = key; this._defaultValue = defaultValue; this.reset(); } public set(value: T): void { this._service.setContext(this._key, value); } public reset(): void { if (typeof this._defaultValue === 'undefined') { this._service.removeContext(this._key); } else { this._service.setContext(this._key, this._defaultValue); } } public get(): T | undefined { return this._service.getContextKeyValue<T>(this._key); } } class SimpleContextKeyChangeEvent implements IContextKeyChangeEvent { constructor(readonly key: string) { } affectsSome(keys: IReadableSet<string>): boolean { return keys.has(this.key); } allKeysContainedIn(keys: IReadableSet<string>): boolean { return this.affectsSome(keys); } } class ArrayContextKeyChangeEvent implements IContextKeyChangeEvent { constructor(readonly keys: string[]) { } affectsSome(keys: IReadableSet<string>): boolean { for (const key of this.keys) { if (keys.has(key)) { return true; } } return false; } allKeysContainedIn(keys: IReadableSet<string>): boolean { return this.keys.every(key => keys.has(key)); } } class CompositeContextKeyChangeEvent implements IContextKeyChangeEvent { constructor(readonly events: IContextKeyChangeEvent[]) { } affectsSome(keys: IReadableSet<string>): boolean { for (const e of this.events) { if (e.affectsSome(keys)) { return true; } } return false; } allKeysContainedIn(keys: IReadableSet<string>): boolean { return this.events.every(evt => evt.allKeysContainedIn(keys)); } } function allEventKeysInContext(event: IContextKeyChangeEvent, context: Record<string, any>): boolean { return event.allKeysContainedIn(new Set(Object.keys(context))); } export abstract class AbstractContextKeyService implements IContextKeyService { declare _serviceBrand: undefined; protected _isDisposed: boolean; protected _myContextId: number; protected _onDidChangeContext = new PauseableEmitter<IContextKeyChangeEvent>({ merge: input => new CompositeContextKeyChangeEvent(input) }); readonly onDidChangeContext = this._onDidChangeContext.event; constructor(myContextId: number) { this._isDisposed = false; this._myContextId = myContextId; } public get contextId(): number { return this._myContextId; } abstract dispose(): void; public createKey<T extends ContextKeyValue>(key: string, defaultValue: T | undefined): IContextKey<T> { if (this._isDisposed) { throw new Error(`AbstractContextKeyService has been disposed`); } return new ContextKey(this, key, defaultValue); } bufferChangeEvents(callback: Function): void { this._onDidChangeContext.pause(); try { callback(); } finally { this._onDidChangeContext.resume(); } } public createScoped(domNode: IContextKeyServiceTarget): IContextKeyService { if (this._isDisposed) { throw new Error(`AbstractContextKeyService has been disposed`); } return new ScopedContextKeyService(this, domNode); } createOverlay(overlay: Iterable<[string, any]> = Iterable.empty()): IContextKeyService { if (this._isDisposed) { throw new Error(`AbstractContextKeyService has been disposed`); } return new OverlayContextKeyService(this, overlay); } public contextMatchesRules(rules: ContextKeyExpression | undefined): boolean { if (this._isDisposed) { throw new Error(`AbstractContextKeyService has been disposed`); } const context = this.getContextValuesContainer(this._myContextId); const result = (rules ? rules.evaluate(context) : true); // console.group(rules.serialize() + ' -> ' + result); // rules.keys().forEach(key => { console.log(key, ctx[key]); }); // console.groupEnd(); return result; } public getContextKeyValue<T>(key: string): T | undefined { if (this._isDisposed) { return undefined; } return this.getContextValuesContainer(this._myContextId).getValue<T>(key); } public setContext(key: string, value: any): void { if (this._isDisposed) { return; } const myContext = this.getContextValuesContainer(this._myContextId); if (!myContext) { return; } if (myContext.setValue(key, value)) { this._onDidChangeContext.fire(new SimpleContextKeyChangeEvent(key)); } } public removeContext(key: string): void { if (this._isDisposed) { return; } if (this.getContextValuesContainer(this._myContextId).removeValue(key)) { this._onDidChangeContext.fire(new SimpleContextKeyChangeEvent(key)); } } public getContext(target: IContextKeyServiceTarget | null): IContext { if (this._isDisposed) { return NullContext.INSTANCE; } return this.getContextValuesContainer(findContextAttr(target)); } public abstract getContextValuesContainer(contextId: number): Context; public abstract createChildContext(parentContextId?: number): number; public abstract disposeContext(contextId: number): void; public abstract updateParent(parentContextKeyService?: IContextKeyService): void; } export class ContextKeyService extends AbstractContextKeyService implements IContextKeyService { private _lastContextId: number; private readonly _contexts = new Map<number, Context>(); private readonly _toDispose = new DisposableStore(); constructor(@IConfigurationService configurationService: IConfigurationService) { super(0); this._lastContextId = 0; const myContext = new ConfigAwareContextValuesContainer(this._myContextId, configurationService, this._onDidChangeContext); this._contexts.set(this._myContextId, myContext); this._toDispose.add(myContext); // Uncomment this to see the contexts continuously logged // let lastLoggedValue: string | null = null; // setInterval(() => { // let values = Object.keys(this._contexts).map((key) => this._contexts[key]); // let logValue = values.map(v => JSON.stringify(v._value, null, '\t')).join('\n'); // if (lastLoggedValue !== logValue) { // lastLoggedValue = logValue; // console.log(lastLoggedValue); // } // }, 2000); } public dispose(): void { this._onDidChangeContext.dispose(); this._isDisposed = true; this._toDispose.dispose(); } public getContextValuesContainer(contextId: number): Context { if (this._isDisposed) { return NullContext.INSTANCE; } return this._contexts.get(contextId) || NullContext.INSTANCE; } public createChildContext(parentContextId: number = this._myContextId): number { if (this._isDisposed) { throw new Error(`ContextKeyService has been disposed`); } const id = (++this._lastContextId); this._contexts.set(id, new Context(id, this.getContextValuesContainer(parentContextId))); return id; } public disposeContext(contextId: number): void { if (!this._isDisposed) { this._contexts.delete(contextId); } } public updateParent(_parentContextKeyService: IContextKeyService): void { throw new Error('Cannot update parent of root ContextKeyService'); } } class ScopedContextKeyService extends AbstractContextKeyService { private _parent: AbstractContextKeyService; private _domNode: IContextKeyServiceTarget; private readonly _parentChangeListener = new MutableDisposable(); constructor(parent: AbstractContextKeyService, domNode: IContextKeyServiceTarget) { super(parent.createChildContext()); this._parent = parent; this._updateParentChangeListener(); this._domNode = domNode; if (this._domNode.hasAttribute(KEYBINDING_CONTEXT_ATTR)) { let extraInfo = ''; if ((this._domNode as HTMLElement).classList) { extraInfo = Array.from((this._domNode as HTMLElement).classList.values()).join(', '); } console.error(`Element already has context attribute${extraInfo ? ': ' + extraInfo : ''}`); } this._domNode.setAttribute(KEYBINDING_CONTEXT_ATTR, String(this._myContextId)); } private _updateParentChangeListener(): void { // Forward parent events to this listener. Parent will change. this._parentChangeListener.value = this._parent.onDidChangeContext(e => { const thisContainer = this._parent.getContextValuesContainer(this._myContextId); const thisContextValues = thisContainer.value; if (!allEventKeysInContext(e, thisContextValues)) { this._onDidChangeContext.fire(e); } }); } public dispose(): void { if (this._isDisposed) { return; } this._onDidChangeContext.dispose(); this._parent.disposeContext(this._myContextId); this._parentChangeListener.dispose(); this._domNode.removeAttribute(KEYBINDING_CONTEXT_ATTR); this._isDisposed = true; } public getContextValuesContainer(contextId: number): Context { if (this._isDisposed) { return NullContext.INSTANCE; } return this._parent.getContextValuesContainer(contextId); } public createChildContext(parentContextId: number = this._myContextId): number { if (this._isDisposed) { throw new Error(`ScopedContextKeyService has been disposed`); } return this._parent.createChildContext(parentContextId); } public disposeContext(contextId: number): void { if (this._isDisposed) { return; } this._parent.disposeContext(contextId); } public updateParent(parentContextKeyService: AbstractContextKeyService): void { const thisContainer = this._parent.getContextValuesContainer(this._myContextId); const oldAllValues = thisContainer.collectAllValues(); this._parent = parentContextKeyService; this._updateParentChangeListener(); const newParentContainer = this._parent.getContextValuesContainer(this._parent.contextId); thisContainer.updateParent(newParentContainer); const newAllValues = thisContainer.collectAllValues(); const allValuesDiff = { ...distinct(oldAllValues, newAllValues), ...distinct(newAllValues, oldAllValues) }; const changedKeys = Object.keys(allValuesDiff); this._onDidChangeContext.fire(new ArrayContextKeyChangeEvent(changedKeys)); } } class OverlayContext implements IContext { constructor(private parent: IContext, private overlay: ReadonlyMap<string, any>) { } getValue<T>(key: string): T | undefined { return this.overlay.has(key) ? this.overlay.get(key) : this.parent.getValue(key); } } class OverlayContextKeyService implements IContextKeyService { declare _serviceBrand: undefined; private overlay: Map<string, any>; get contextId(): number { return this.parent.contextId; } get onDidChangeContext(): Event<IContextKeyChangeEvent> { return this.parent.onDidChangeContext; } constructor(private parent: AbstractContextKeyService | OverlayContextKeyService, overlay: Iterable<[string, any]>) { this.overlay = new Map(overlay); } bufferChangeEvents(callback: Function): void { this.parent.bufferChangeEvents(callback); } createKey<T extends ContextKeyValue>(): IContextKey<T> { throw new Error('Not supported.'); } getContext(target: IContextKeyServiceTarget | null): IContext { return new OverlayContext(this.parent.getContext(target), this.overlay); } getContextValuesContainer(contextId: number): IContext { const parentContext = this.parent.getContextValuesContainer(contextId); return new OverlayContext(parentContext, this.overlay); } contextMatchesRules(rules: ContextKeyExpression | undefined): boolean { const context = this.getContextValuesContainer(this.contextId); const result = (rules ? rules.evaluate(context) : true); return result; } getContextKeyValue<T>(key: string): T | undefined { return this.overlay.has(key) ? this.overlay.get(key) : this.parent.getContextKeyValue(key); } createScoped(): IContextKeyService { throw new Error('Not supported.'); } createOverlay(overlay: Iterable<[string, any]> = Iterable.empty()): IContextKeyService { return new OverlayContextKeyService(this, overlay); } updateParent(): void { throw new Error('Not supported.'); } dispose(): void { // noop } } function findContextAttr(domNode: IContextKeyServiceTarget | null): number { while (domNode) { if (domNode.hasAttribute(KEYBINDING_CONTEXT_ATTR)) { const attr = domNode.getAttribute(KEYBINDING_CONTEXT_ATTR); if (attr) { return parseInt(attr, 10); } return NaN; } domNode = domNode.parentElement; } return 0; } export function setContext(accessor: ServicesAccessor, contextKey: any, contextValue: any) { const contextKeyService = accessor.get(IContextKeyService); contextKeyService.createKey(String(contextKey), stringifyURIs(contextValue)); } function stringifyURIs(contextValue: any): any { return cloneAndChange(contextValue, (obj) => { if (typeof obj === 'object' && (<MarshalledObject>obj).$mid === MarshalledId.Uri) { return URI.revive(obj).toString(); } if (obj instanceof URI) { return obj.toString(); } return undefined; }); } CommandsRegistry.registerCommand(SET_CONTEXT_COMMAND_ID, setContext); CommandsRegistry.registerCommand({ id: 'getContextKeyInfo', handler() { return [...RawContextKey.all()].sort((a, b) => a.key.localeCompare(b.key)); }, description: { description: localize('getContextKeyInfo', "A command that returns information about context keys"), args: [] } }); CommandsRegistry.registerCommand('_generateContextKeyInfo', function () { const result: ContextKeyInfo[] = []; const seen = new Set<string>(); for (const info of RawContextKey.all()) { if (!seen.has(info.key)) { seen.add(info.key); result.push(info); } } result.sort((a, b) => a.key.localeCompare(b.key)); console.log(JSON.stringify(result, undefined, 2)); });
src/vs/platform/contextkey/browser/contextKeyService.ts
1
https://github.com/microsoft/vscode/commit/bafda10a370cd7ac835c4a88f5885bf69e02037e
[ 0.0001770011440385133, 0.00017303235654253513, 0.00016572559252381325, 0.00017347035463899374, 0.0000025622537123126676 ]
{ "id": 3, "code_window": [ "\tnew ApiCommand(\n", "\t\t'vscode.experimental.editSession.continue', '_workbench.editSessions.actions.continueEditSession', 'Continue the current edit session in a different workspace',\n", "\t\t[ApiCommandArgument.Uri.with('workspaceUri', 'The target workspace to continue the current edit session in')],\n", "\t\tApiCommandResult.Void\n", "\t)\n", "];\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t),\n", "\t// --- context keys\n", "\tnew ApiCommand(\n", "\t\t'setContext', '_setContext', 'Set a custom context key value that can be used in when clauses.',\n", "\t\t[\n", "\t\t\tApiCommandArgument.String.with('name', 'The context key name'),\n", "\t\t\tnew ApiCommandArgument('value', 'The context key value', () => true, v => v),\n", "\t\t],\n", "\t\tApiCommandResult.Void\n" ], "file_path": "src/vs/workbench/api/common/extHostApiCommands.ts", "type": "add", "edit_start_line_idx": 444 }
{ "editor": [ { "name": "vs/platform", "project": "vscode-editor" }, { "name": "vs/editor/contrib", "project": "vscode-editor" }, { "name": "vs/editor", "project": "vscode-editor" }, { "name": "vs/base", "project": "vscode-editor" } ], "workbench": [ { "name": "vs/code", "project": "vscode-workbench" }, { "name": "vs/workbench", "project": "vscode-workbench" }, { "name": "vs/workbench/api/common", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/bulkEdit", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/cli", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/codeEditor", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/callHierarchy", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/typeHierarchy", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/codeActions", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/comments", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/debug", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/dialogs", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/emmet", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/experiments", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/extensions", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/externalTerminal", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/feedback", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/files", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/html", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/issue", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/inlayHints", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/interactive", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/languageStatus", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/keybindings", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/markers", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/mergeEditor", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/localization", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/logs", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/output", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/performance", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/preferences", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/notebook", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/quickaccess", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/userData", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/remote", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/relauncher", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/sash", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/scm", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/search", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/searchEditor", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/snippets", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/format", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/tags", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/surveys", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/tasks", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/testing", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/terminal", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/themes", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/trust", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/update", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/url", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/watermark", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/webview", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/webviewPanel", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/workspace", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/workspaces", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/customEditor", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/externalUriOpener", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/welcomeGettingStarted", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/welcomeOverlay", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/welcomePage", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/welcomeViews", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/welcomeWalkthrough", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/outline", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/userDataSync", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/editSessions", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/views", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/languageDetection", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/audioCues", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/deprecatedExtensionMigrator", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/bracketPairColorizer2Telemetry", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/offline", "project": "vscode-workbench" }, { "name": "vs/workbench/services/actions", "project": "vscode-workbench" }, { "name": "vs/workbench/services/authToken", "project": "vscode-workbench" }, { "name": "vs/workbench/services/backup", "project": "vscode-workbench" }, { "name": "vs/workbench/services/bulkEdit", "project": "vscode-workbench" }, { "name": "vs/workbench/services/clipboard", "project": "vscode-workbench" }, { "name": "vs/workbench/services/commands", "project": "vscode-workbench" }, { "name": "vs/workbench/services/configuration", "project": "vscode-workbench" }, { "name": "vs/workbench/services/configurationResolver", "project": "vscode-workbench" }, { "name": "vs/workbench/services/dialogs", "project": "vscode-workbench" }, { "name": "vs/workbench/services/editor", "project": "vscode-workbench" }, { "name": "vs/workbench/services/extensions", "project": "vscode-workbench" }, { "name": "vs/workbench/services/extensionManagement", "project": "vscode-workbench" }, { "name": "vs/workbench/services/files", "project": "vscode-workbench" }, { "name": "vs/workbench/services/history", "project": "vscode-workbench" }, { "name": "vs/workbench/services/log", "project": "vscode-workbench" }, { "name": "vs/workbench/services/integrity", "project": "vscode-workbench" }, { "name": "vs/workbench/services/keybinding", "project": "vscode-workbench" }, { "name": "vs/workbench/services/lifecycle", "project": "vscode-workbench" }, { "name": "vs/workbench/services/language", "project": "vscode-workbench" }, { "name": "vs/workbench/services/progress", "project": "vscode-workbench" }, { "name": "vs/workbench/services/remote", "project": "vscode-workbench" }, { "name": "vs/workbench/services/search", "project": "vscode-workbench" }, { "name": "vs/workbench/services/textfile", "project": "vscode-workbench" }, { "name": "vs/workbench/services/themes", "project": "vscode-workbench" }, { "name": "vs/workbench/services/textMate", "project": "vscode-workbench" }, { "name": "vs/workbench/services/workingCopy", "project": "vscode-workbench" }, { "name": "vs/workbench/services/workspaces", "project": "vscode-workbench" }, { "name": "vs/workbench/services/decorations", "project": "vscode-workbench" }, { "name": "vs/workbench/services/label", "project": "vscode-workbench" }, { "name": "vs/workbench/services/preferences", "project": "vscode-preferences" }, { "name": "vs/workbench/services/notification", "project": "vscode-workbench" }, { "name": "vs/workbench/services/userData", "project": "vscode-workbench" }, { "name": "vs/workbench/services/userDataSync", "project": "vscode-workbench" }, { "name": "vs/workbench/services/editSessions", "project": "vscode-workbench" }, { "name": "vs/workbench/services/views", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/timeline", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/localHistory", "project": "vscode-workbench" }, { "name": "vs/workbench/services/authentication", "project": "vscode-workbench" }, { "name": "vs/workbench/services/extensionRecommendations", "project": "vscode-workbench" }, { "name": "vs/workbench/services/gettingStarted", "project": "vscode-workbench" }, { "name": "vs/workbench/services/host", "project": "vscode-workbench" }, { "name": "vs/workbench/contrib/userDataProfile", "project": "vscode-profiles" }, { "name": "vs/workbench/services/userDataProfile", "project": "vscode-profiles" } ] }
src/vs/editor/test/node/diffing/fixtures/json-brackets/2.json
0
https://github.com/microsoft/vscode/commit/bafda10a370cd7ac835c4a88f5885bf69e02037e
[ 0.00017787126125767827, 0.00016969525313470513, 0.00016541806689929217, 0.00016953307203948498, 0.0000018446243075231905 ]
{ "id": 3, "code_window": [ "\tnew ApiCommand(\n", "\t\t'vscode.experimental.editSession.continue', '_workbench.editSessions.actions.continueEditSession', 'Continue the current edit session in a different workspace',\n", "\t\t[ApiCommandArgument.Uri.with('workspaceUri', 'The target workspace to continue the current edit session in')],\n", "\t\tApiCommandResult.Void\n", "\t)\n", "];\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t),\n", "\t// --- context keys\n", "\tnew ApiCommand(\n", "\t\t'setContext', '_setContext', 'Set a custom context key value that can be used in when clauses.',\n", "\t\t[\n", "\t\t\tApiCommandArgument.String.with('name', 'The context key name'),\n", "\t\t\tnew ApiCommandArgument('value', 'The context key value', () => true, v => v),\n", "\t\t],\n", "\t\tApiCommandResult.Void\n" ], "file_path": "src/vs/workbench/api/common/extHostApiCommands.ts", "type": "add", "edit_start_line_idx": 444 }
src/** out/** tsconfig.json extension.webpack.config.js extension-browser.webpack.config.js yarn.lock syntaxes/generateTMLanguage.js
extensions/search-result/.vscodeignore
0
https://github.com/microsoft/vscode/commit/bafda10a370cd7ac835c4a88f5885bf69e02037e
[ 0.00017066841246560216, 0.00017066841246560216, 0.00017066841246560216, 0.00017066841246560216, 0 ]
{ "id": 3, "code_window": [ "\tnew ApiCommand(\n", "\t\t'vscode.experimental.editSession.continue', '_workbench.editSessions.actions.continueEditSession', 'Continue the current edit session in a different workspace',\n", "\t\t[ApiCommandArgument.Uri.with('workspaceUri', 'The target workspace to continue the current edit session in')],\n", "\t\tApiCommandResult.Void\n", "\t)\n", "];\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t),\n", "\t// --- context keys\n", "\tnew ApiCommand(\n", "\t\t'setContext', '_setContext', 'Set a custom context key value that can be used in when clauses.',\n", "\t\t[\n", "\t\t\tApiCommandArgument.String.with('name', 'The context key name'),\n", "\t\t\tnew ApiCommandArgument('value', 'The context key value', () => true, v => v),\n", "\t\t],\n", "\t\tApiCommandResult.Void\n" ], "file_path": "src/vs/workbench/api/common/extHostApiCommands.ts", "type": "add", "edit_start_line_idx": 444 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { CharCode } from 'vs/base/common/charCode'; import { Schemas } from 'vs/base/common/network'; import { URI } from 'vs/base/common/uri'; export interface WebviewRemoteInfo { readonly isRemote: boolean; readonly authority: string | undefined; } /** * Root from which resources in webviews are loaded. * * This is hardcoded because we never expect to actually hit it. Instead these requests * should always go to a service worker. */ export const webviewResourceBaseHost = 'vscode-cdn.net'; export const webviewRootResourceAuthority = `vscode-resource.${webviewResourceBaseHost}`; export const webviewGenericCspSource = `'self' https://*.${webviewResourceBaseHost}`; /** * Construct a uri that can load resources inside a webview * * We encode the resource component of the uri so that on the main thread * we know where to load the resource from (remote or truly local): * * ```txt * ${scheme}+${resource-authority}.vscode-resource.vscode-cdn.net/${path} * ``` * * @param resource Uri of the resource to load. * @param remoteInfo Optional information about the remote that specifies where `resource` should be resolved from. */ export function asWebviewUri(resource: URI, remoteInfo?: WebviewRemoteInfo): URI { if (resource.scheme === Schemas.http || resource.scheme === Schemas.https) { return resource; } if (remoteInfo && remoteInfo.authority && remoteInfo.isRemote && resource.scheme === Schemas.file) { resource = URI.from({ scheme: Schemas.vscodeRemote, authority: remoteInfo.authority, path: resource.path, }); } return URI.from({ scheme: Schemas.https, authority: `${resource.scheme}+${encodeAuthority(resource.authority)}.${webviewRootResourceAuthority}`, path: resource.path, fragment: resource.fragment, query: resource.query, }); } function encodeAuthority(authority: string): string { return authority.replace(/./g, char => { const code = char.charCodeAt(0); if ( (code >= CharCode.a && code <= CharCode.z) || (code >= CharCode.A && code <= CharCode.Z) || (code >= CharCode.Digit0 && code <= CharCode.Digit9) ) { return char; } return '-' + code.toString(16).padStart(4, '0'); }); } export function decodeAuthority(authority: string) { return authority.replace(/-([0-9a-f]{4})/g, (_, code) => String.fromCharCode(parseInt(code, 16))); }
src/vs/workbench/contrib/webview/common/webview.ts
0
https://github.com/microsoft/vscode/commit/bafda10a370cd7ac835c4a88f5885bf69e02037e
[ 0.00017552333883941174, 0.00017055284115485847, 0.00016309898637700826, 0.00017113401554524899, 0.0000037667693959519966 ]
{ "id": 0, "code_window": [ "import {transformers, transformDataToTable} from '../transformers';\n", "\n", "describe('when transforming time series table.', () => {\n", " var table;\n", "\n", " describe('given 2 time series', () => {\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "describe('when transforming time series table', () => {\n" ], "file_path": "public/app/plugins/panel/table/specs/transformers.jest.ts", "type": "replace", "edit_start_line_idx": 2 }
import {transformers, transformDataToTable} from '../transformers'; describe('when transforming time series table.', () => { var table; describe('given 2 time series', () => { var time = new Date().getTime(); var timeSeries = [ { target: 'series1', datapoints: [[12.12, time], [14.44, time+1]], }, { target: 'series2', datapoints: [[16.12, time]], } ]; describe('timeseries_to_rows', () => { var panel = { transform: 'timeseries_to_rows', sort: {col: 0, desc: true}, }; beforeEach(() => { table = transformDataToTable(timeSeries, panel); }); it('should return 3 rows', () => { expect(table.rows.length).toBe(3); expect(table.rows[0][1]).toBe('series1'); expect(table.rows[1][1]).toBe('series1'); expect(table.rows[2][1]).toBe('series2'); expect(table.rows[0][2]).toBe(12.12); }); it('should return 3 rows', () => { expect(table.columns.length).toBe(3); expect(table.columns[0].text).toBe('Time'); expect(table.columns[1].text).toBe('Metric'); expect(table.columns[2].text).toBe('Value'); }); }); describe('timeseries_to_columns', () => { var panel = { transform: 'timeseries_to_columns' }; beforeEach(() => { table = transformDataToTable(timeSeries, panel); }); it ('should return 3 columns', () => { expect(table.columns.length).toBe(3); expect(table.columns[0].text).toBe('Time'); expect(table.columns[1].text).toBe('series1'); expect(table.columns[2].text).toBe('series2'); }); it ('should return 2 rows', () => { expect(table.rows.length).toBe(2); expect(table.rows[0][1]).toBe(12.12); expect(table.rows[0][2]).toBe(16.12); }); it ('should be undefined when no value for timestamp', () => { expect(table.rows[1][2]).toBe(undefined); }); }); describe('timeseries_aggregations', () => { var panel = { transform: 'timeseries_aggregations', sort: {col: 0, desc: true}, columns: [{text: 'Max', value: 'max'}, {text: 'Min', value: 'min'}] }; beforeEach(() => { table = transformDataToTable(timeSeries, panel); }); it('should return 2 rows', () => { expect(table.rows.length).toBe(2); expect(table.rows[0][0]).toBe('series1'); expect(table.rows[0][1]).toBe(14.44); expect(table.rows[0][2]).toBe(12.12); }); it('should return 2 columns', () => { expect(table.columns.length).toBe(3); expect(table.columns[0].text).toBe('Metric'); expect(table.columns[1].text).toBe('Max'); expect(table.columns[2].text).toBe('Min'); }); }); }); describe('table data sets', () => { describe('Table', () => { const transform = 'table'; var panel = { transform, }; var time = new Date().getTime(); var nonTableData = [ { type: 'foo', columns: [ { text: 'Time' }, { text: 'Label Key 1' }, { text: 'Value' }, ], rows: [ [time, 'Label Value 1', 42], ], } ]; var singleQueryData = [ { type: 'table', columns: [ { text: 'Time' }, { text: 'Label Key 1' }, { text: 'Value' }, ], rows: [ [time, 'Label Value 1', 42], ], } ]; var multipleQueriesDataSameLabels = [ { type: 'table', columns: [ { text: 'Time' }, { text: 'Label Key 1' }, { text: 'Label Key 2' }, { text: 'Value' }, ], rows: [ [time, 'Label Value 1', 'Label Value 2', 42], ], }, { type: 'table', columns: [ { text: 'Time' }, { text: 'Label Key 1' }, { text: 'Label Key 2' }, { text: 'Value' }, ], rows: [ [time, 'Label Value 1', 'Label Value 2', 13], ], } ]; var multipleQueriesDataDifferentLabels = [ { type: 'table', columns: [ { text: 'Time' }, { text: 'Label Key 1' }, { text: 'Value' }, ], rows: [ [time, 'Label Value 1', 42], ], }, { type: 'table', columns: [ { text: 'Time' }, { text: 'Label Key 2' }, { text: 'Value' }, ], rows: [ [time, 'Label Value 2', 13], ], } ]; describe('getColumns', function() { it('should return data columns given a single query', function() { var columns = transformers[transform].getColumns(singleQueryData); expect(columns[0].text).toBe('Time'); expect(columns[1].text).toBe('Label Key 1'); expect(columns[2].text).toBe('Value #A'); }); it('should return the union of data columns given a multiple queries', function() { var columns = transformers[transform].getColumns(multipleQueriesDataSameLabels); expect(columns[0].text).toBe('Time'); expect(columns[1].text).toBe('Label Key 1'); expect(columns[2].text).toBe('Label Key 2'); expect(columns[3].text).toBe('Value #A'); expect(columns[4].text).toBe('Value #B'); }); it('should return the union of data columns given a multiple queries with different labels', function() { var columns = transformers[transform].getColumns(multipleQueriesDataDifferentLabels); expect(columns[0].text).toBe('Time'); expect(columns[1].text).toBe('Label Key 1'); expect(columns[2].text).toBe('Label Key 2'); expect(columns[3].text).toBe('Value #A'); expect(columns[4].text).toBe('Value #B'); }); }); describe('transform', function() { it ('should throw an error with non-table data', () => { expect(() => transformDataToTable(nonTableData, panel)).toThrow(); }); it ('should return 3 columns for single queries', () => { table = transformDataToTable(singleQueryData, panel); expect(table.columns.length).toBe(3); expect(table.columns[0].text).toBe('Time'); expect(table.columns[1].text).toBe('Label Key 1'); expect(table.columns[2].text).toBe('Value #A'); }); it ('should return the union of columns for multiple queries', () => { table = transformDataToTable(multipleQueriesDataSameLabels, panel); expect(table.columns.length).toBe(5); expect(table.columns[0].text).toBe('Time'); expect(table.columns[1].text).toBe('Label Key 1'); expect(table.columns[2].text).toBe('Label Key 2'); expect(table.columns[3].text).toBe('Value #A'); expect(table.columns[4].text).toBe('Value #B'); }); it ('should return 1 row for a single query', () => { table = transformDataToTable(singleQueryData, panel); expect(table.rows.length).toBe(1); expect(table.rows[0][0]).toBe(time); expect(table.rows[0][1]).toBe('Label Value 1'); expect(table.rows[0][2]).toBe(42); }); it ('should return 1 row for a mulitple queries with same label values', () => { table = transformDataToTable(multipleQueriesDataSameLabels, panel); expect(table.rows.length).toBe(1); expect(table.rows[0][0]).toBe(time); expect(table.rows[0][1]).toBe('Label Value 1'); expect(table.rows[0][2]).toBe('Label Value 2'); expect(table.rows[0][3]).toBe(42); expect(table.rows[0][4]).toBe(13); }); it ('should return 2 rows for a mulitple queries with different label values', () => { table = transformDataToTable(multipleQueriesDataDifferentLabels, panel); expect(table.rows.length).toBe(2); expect(table.rows[0][0]).toBe(time); expect(table.rows[0][1]).toBe('Label Value 1'); expect(table.rows[0][2]).toBeUndefined(); expect(table.rows[0][3]).toBe(42); expect(table.rows[0][4]).toBeUndefined(); expect(table.rows[1][0]).toBe(time); expect(table.rows[1][1]).toBeUndefined(); expect(table.rows[1][2]).toBe('Label Value 2'); expect(table.rows[1][3]).toBeUndefined(); expect(table.rows[1][4]).toBe(13); }); }); }); }); describe('doc data sets', () => { describe('JSON Data', () => { var panel = { transform: 'json', columns: [ {text: 'Timestamp', value: 'timestamp'}, {text: 'Message', value: 'message'}, {text: 'nested.level2', value: 'nested.level2'}, ] }; var rawData = [ { type: 'docs', datapoints: [ { timestamp: 'time', message: 'message', nested: { level2: 'level2-value' } } ] } ]; describe('getColumns', function() { it('should return nested properties', function() { var columns = transformers['json'].getColumns(rawData); expect(columns[0].text).toBe('timestamp'); expect(columns[1].text).toBe('message'); expect(columns[2].text).toBe('nested.level2'); }); }); describe('transform', function() { beforeEach(() => { table = transformDataToTable(rawData, panel); }); it ('should return 2 columns', () => { expect(table.columns.length).toBe(3); expect(table.columns[0].text).toBe('Timestamp'); expect(table.columns[1].text).toBe('Message'); expect(table.columns[2].text).toBe('nested.level2'); }); it ('should return 2 rows', () => { expect(table.rows.length).toBe(1); expect(table.rows[0][0]).toBe('time'); expect(table.rows[0][1]).toBe('message'); expect(table.rows[0][2]).toBe('level2-value'); }); }); }); }); describe('annotation data', () => { describe('Annnotations', () => { var panel = {transform: 'annotations'}; var rawData = { annotations: [ { time: 1000, text: 'hej', tags: ['tags', 'asd'], title: 'title', } ] }; beforeEach(() => { table = transformDataToTable(rawData, panel); }); it ('should return 4 columns', () => { expect(table.columns.length).toBe(4); expect(table.columns[0].text).toBe('Time'); expect(table.columns[1].text).toBe('Title'); expect(table.columns[2].text).toBe('Text'); expect(table.columns[3].text).toBe('Tags'); }); it ('should return 1 rows', () => { expect(table.rows.length).toBe(1); expect(table.rows[0][0]).toBe(1000); }); }); }); });
public/app/plugins/panel/table/specs/transformers.jest.ts
1
https://github.com/grafana/grafana/commit/eb31833d521f03901e1d7de53301434fef72d010
[ 0.9987741112709045, 0.5125980377197266, 0.00016656778461765498, 0.9969649910926819, 0.4986160695552826 ]
{ "id": 0, "code_window": [ "import {transformers, transformDataToTable} from '../transformers';\n", "\n", "describe('when transforming time series table.', () => {\n", " var table;\n", "\n", " describe('given 2 time series', () => {\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "describe('when transforming time series table', () => {\n" ], "file_path": "public/app/plugins/panel/table/specs/transformers.jest.ts", "type": "replace", "edit_start_line_idx": 2 }
[*.*]
vendor/github.com/jmespath/go-jmespath/fuzz/corpus/expr-571
0
https://github.com/grafana/grafana/commit/eb31833d521f03901e1d7de53301434fef72d010
[ 0.00017806098912842572, 0.00017806098912842572, 0.00017806098912842572, 0.00017806098912842572, 0 ]
{ "id": 0, "code_window": [ "import {transformers, transformDataToTable} from '../transformers';\n", "\n", "describe('when transforming time series table.', () => {\n", " var table;\n", "\n", " describe('given 2 time series', () => {\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "describe('when transforming time series table', () => {\n" ], "file_path": "public/app/plugins/panel/table/specs/transformers.jest.ts", "type": "replace", "edit_start_line_idx": 2 }
I_
vendor/github.com/jmespath/go-jmespath/fuzz/corpus/expr-295
0
https://github.com/grafana/grafana/commit/eb31833d521f03901e1d7de53301434fef72d010
[ 0.00017825583927333355, 0.00017825583927333355, 0.00017825583927333355, 0.00017825583927333355, 0 ]
{ "id": 0, "code_window": [ "import {transformers, transformDataToTable} from '../transformers';\n", "\n", "describe('when transforming time series table.', () => {\n", " var table;\n", "\n", " describe('given 2 time series', () => {\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "describe('when transforming time series table', () => {\n" ], "file_path": "public/app/plugins/panel/table/specs/transformers.jest.ts", "type": "replace", "edit_start_line_idx": 2 }
min_by(people, &to_number(age_str))
vendor/github.com/jmespath/go-jmespath/fuzz/corpus/expr-196
0
https://github.com/grafana/grafana/commit/eb31833d521f03901e1d7de53301434fef72d010
[ 0.00017720210598781705, 0.00017720210598781705, 0.00017720210598781705, 0.00017720210598781705, 0 ]
{ "id": 1, "code_window": [ " describe('getColumns', function() {\n", " it('should return data columns given a single query', function() {\n", " var columns = transformers[transform].getColumns(singleQueryData);\n", " expect(columns[0].text).toBe('Time');\n", " expect(columns[1].text).toBe('Label Key 1');\n", " expect(columns[2].text).toBe('Value #A');\n", " });\n", "\n", " it('should return the union of data columns given a multiple queries', function() {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " expect(columns[2].text).toBe('Value');\n" ], "file_path": "public/app/plugins/panel/table/specs/transformers.jest.ts", "type": "replace", "edit_start_line_idx": 191 }
import {transformers, transformDataToTable} from '../transformers'; describe('when transforming time series table.', () => { var table; describe('given 2 time series', () => { var time = new Date().getTime(); var timeSeries = [ { target: 'series1', datapoints: [[12.12, time], [14.44, time+1]], }, { target: 'series2', datapoints: [[16.12, time]], } ]; describe('timeseries_to_rows', () => { var panel = { transform: 'timeseries_to_rows', sort: {col: 0, desc: true}, }; beforeEach(() => { table = transformDataToTable(timeSeries, panel); }); it('should return 3 rows', () => { expect(table.rows.length).toBe(3); expect(table.rows[0][1]).toBe('series1'); expect(table.rows[1][1]).toBe('series1'); expect(table.rows[2][1]).toBe('series2'); expect(table.rows[0][2]).toBe(12.12); }); it('should return 3 rows', () => { expect(table.columns.length).toBe(3); expect(table.columns[0].text).toBe('Time'); expect(table.columns[1].text).toBe('Metric'); expect(table.columns[2].text).toBe('Value'); }); }); describe('timeseries_to_columns', () => { var panel = { transform: 'timeseries_to_columns' }; beforeEach(() => { table = transformDataToTable(timeSeries, panel); }); it ('should return 3 columns', () => { expect(table.columns.length).toBe(3); expect(table.columns[0].text).toBe('Time'); expect(table.columns[1].text).toBe('series1'); expect(table.columns[2].text).toBe('series2'); }); it ('should return 2 rows', () => { expect(table.rows.length).toBe(2); expect(table.rows[0][1]).toBe(12.12); expect(table.rows[0][2]).toBe(16.12); }); it ('should be undefined when no value for timestamp', () => { expect(table.rows[1][2]).toBe(undefined); }); }); describe('timeseries_aggregations', () => { var panel = { transform: 'timeseries_aggregations', sort: {col: 0, desc: true}, columns: [{text: 'Max', value: 'max'}, {text: 'Min', value: 'min'}] }; beforeEach(() => { table = transformDataToTable(timeSeries, panel); }); it('should return 2 rows', () => { expect(table.rows.length).toBe(2); expect(table.rows[0][0]).toBe('series1'); expect(table.rows[0][1]).toBe(14.44); expect(table.rows[0][2]).toBe(12.12); }); it('should return 2 columns', () => { expect(table.columns.length).toBe(3); expect(table.columns[0].text).toBe('Metric'); expect(table.columns[1].text).toBe('Max'); expect(table.columns[2].text).toBe('Min'); }); }); }); describe('table data sets', () => { describe('Table', () => { const transform = 'table'; var panel = { transform, }; var time = new Date().getTime(); var nonTableData = [ { type: 'foo', columns: [ { text: 'Time' }, { text: 'Label Key 1' }, { text: 'Value' }, ], rows: [ [time, 'Label Value 1', 42], ], } ]; var singleQueryData = [ { type: 'table', columns: [ { text: 'Time' }, { text: 'Label Key 1' }, { text: 'Value' }, ], rows: [ [time, 'Label Value 1', 42], ], } ]; var multipleQueriesDataSameLabels = [ { type: 'table', columns: [ { text: 'Time' }, { text: 'Label Key 1' }, { text: 'Label Key 2' }, { text: 'Value' }, ], rows: [ [time, 'Label Value 1', 'Label Value 2', 42], ], }, { type: 'table', columns: [ { text: 'Time' }, { text: 'Label Key 1' }, { text: 'Label Key 2' }, { text: 'Value' }, ], rows: [ [time, 'Label Value 1', 'Label Value 2', 13], ], } ]; var multipleQueriesDataDifferentLabels = [ { type: 'table', columns: [ { text: 'Time' }, { text: 'Label Key 1' }, { text: 'Value' }, ], rows: [ [time, 'Label Value 1', 42], ], }, { type: 'table', columns: [ { text: 'Time' }, { text: 'Label Key 2' }, { text: 'Value' }, ], rows: [ [time, 'Label Value 2', 13], ], } ]; describe('getColumns', function() { it('should return data columns given a single query', function() { var columns = transformers[transform].getColumns(singleQueryData); expect(columns[0].text).toBe('Time'); expect(columns[1].text).toBe('Label Key 1'); expect(columns[2].text).toBe('Value #A'); }); it('should return the union of data columns given a multiple queries', function() { var columns = transformers[transform].getColumns(multipleQueriesDataSameLabels); expect(columns[0].text).toBe('Time'); expect(columns[1].text).toBe('Label Key 1'); expect(columns[2].text).toBe('Label Key 2'); expect(columns[3].text).toBe('Value #A'); expect(columns[4].text).toBe('Value #B'); }); it('should return the union of data columns given a multiple queries with different labels', function() { var columns = transformers[transform].getColumns(multipleQueriesDataDifferentLabels); expect(columns[0].text).toBe('Time'); expect(columns[1].text).toBe('Label Key 1'); expect(columns[2].text).toBe('Label Key 2'); expect(columns[3].text).toBe('Value #A'); expect(columns[4].text).toBe('Value #B'); }); }); describe('transform', function() { it ('should throw an error with non-table data', () => { expect(() => transformDataToTable(nonTableData, panel)).toThrow(); }); it ('should return 3 columns for single queries', () => { table = transformDataToTable(singleQueryData, panel); expect(table.columns.length).toBe(3); expect(table.columns[0].text).toBe('Time'); expect(table.columns[1].text).toBe('Label Key 1'); expect(table.columns[2].text).toBe('Value #A'); }); it ('should return the union of columns for multiple queries', () => { table = transformDataToTable(multipleQueriesDataSameLabels, panel); expect(table.columns.length).toBe(5); expect(table.columns[0].text).toBe('Time'); expect(table.columns[1].text).toBe('Label Key 1'); expect(table.columns[2].text).toBe('Label Key 2'); expect(table.columns[3].text).toBe('Value #A'); expect(table.columns[4].text).toBe('Value #B'); }); it ('should return 1 row for a single query', () => { table = transformDataToTable(singleQueryData, panel); expect(table.rows.length).toBe(1); expect(table.rows[0][0]).toBe(time); expect(table.rows[0][1]).toBe('Label Value 1'); expect(table.rows[0][2]).toBe(42); }); it ('should return 1 row for a mulitple queries with same label values', () => { table = transformDataToTable(multipleQueriesDataSameLabels, panel); expect(table.rows.length).toBe(1); expect(table.rows[0][0]).toBe(time); expect(table.rows[0][1]).toBe('Label Value 1'); expect(table.rows[0][2]).toBe('Label Value 2'); expect(table.rows[0][3]).toBe(42); expect(table.rows[0][4]).toBe(13); }); it ('should return 2 rows for a mulitple queries with different label values', () => { table = transformDataToTable(multipleQueriesDataDifferentLabels, panel); expect(table.rows.length).toBe(2); expect(table.rows[0][0]).toBe(time); expect(table.rows[0][1]).toBe('Label Value 1'); expect(table.rows[0][2]).toBeUndefined(); expect(table.rows[0][3]).toBe(42); expect(table.rows[0][4]).toBeUndefined(); expect(table.rows[1][0]).toBe(time); expect(table.rows[1][1]).toBeUndefined(); expect(table.rows[1][2]).toBe('Label Value 2'); expect(table.rows[1][3]).toBeUndefined(); expect(table.rows[1][4]).toBe(13); }); }); }); }); describe('doc data sets', () => { describe('JSON Data', () => { var panel = { transform: 'json', columns: [ {text: 'Timestamp', value: 'timestamp'}, {text: 'Message', value: 'message'}, {text: 'nested.level2', value: 'nested.level2'}, ] }; var rawData = [ { type: 'docs', datapoints: [ { timestamp: 'time', message: 'message', nested: { level2: 'level2-value' } } ] } ]; describe('getColumns', function() { it('should return nested properties', function() { var columns = transformers['json'].getColumns(rawData); expect(columns[0].text).toBe('timestamp'); expect(columns[1].text).toBe('message'); expect(columns[2].text).toBe('nested.level2'); }); }); describe('transform', function() { beforeEach(() => { table = transformDataToTable(rawData, panel); }); it ('should return 2 columns', () => { expect(table.columns.length).toBe(3); expect(table.columns[0].text).toBe('Timestamp'); expect(table.columns[1].text).toBe('Message'); expect(table.columns[2].text).toBe('nested.level2'); }); it ('should return 2 rows', () => { expect(table.rows.length).toBe(1); expect(table.rows[0][0]).toBe('time'); expect(table.rows[0][1]).toBe('message'); expect(table.rows[0][2]).toBe('level2-value'); }); }); }); }); describe('annotation data', () => { describe('Annnotations', () => { var panel = {transform: 'annotations'}; var rawData = { annotations: [ { time: 1000, text: 'hej', tags: ['tags', 'asd'], title: 'title', } ] }; beforeEach(() => { table = transformDataToTable(rawData, panel); }); it ('should return 4 columns', () => { expect(table.columns.length).toBe(4); expect(table.columns[0].text).toBe('Time'); expect(table.columns[1].text).toBe('Title'); expect(table.columns[2].text).toBe('Text'); expect(table.columns[3].text).toBe('Tags'); }); it ('should return 1 rows', () => { expect(table.rows.length).toBe(1); expect(table.rows[0][0]).toBe(1000); }); }); }); });
public/app/plugins/panel/table/specs/transformers.jest.ts
1
https://github.com/grafana/grafana/commit/eb31833d521f03901e1d7de53301434fef72d010
[ 0.9982447624206543, 0.1094033494591713, 0.00016426281945314258, 0.00021339581871870905, 0.3049634099006653 ]
{ "id": 1, "code_window": [ " describe('getColumns', function() {\n", " it('should return data columns given a single query', function() {\n", " var columns = transformers[transform].getColumns(singleQueryData);\n", " expect(columns[0].text).toBe('Time');\n", " expect(columns[1].text).toBe('Label Key 1');\n", " expect(columns[2].text).toBe('Value #A');\n", " });\n", "\n", " it('should return the union of data columns given a multiple queries', function() {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " expect(columns[2].text).toBe('Value');\n" ], "file_path": "public/app/plugins/panel/table/specs/transformers.jest.ts", "type": "replace", "edit_start_line_idx": 191 }
package pretty import "github.com/kr/pretty" Package pretty provides pretty-printing for Go values. Documentation http://godoc.org/github.com/kr/pretty
vendor/github.com/kr/pretty/Readme
0
https://github.com/grafana/grafana/commit/eb31833d521f03901e1d7de53301434fef72d010
[ 0.00017449542065151036, 0.00017449542065151036, 0.00017449542065151036, 0.00017449542065151036, 0 ]
{ "id": 1, "code_window": [ " describe('getColumns', function() {\n", " it('should return data columns given a single query', function() {\n", " var columns = transformers[transform].getColumns(singleQueryData);\n", " expect(columns[0].text).toBe('Time');\n", " expect(columns[1].text).toBe('Label Key 1');\n", " expect(columns[2].text).toBe('Value #A');\n", " });\n", "\n", " it('should return the union of data columns given a multiple queries', function() {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " expect(columns[2].text).toBe('Value');\n" ], "file_path": "public/app/plugins/panel/table/specs/transformers.jest.ts", "type": "replace", "edit_start_line_idx": 191 }
import _ from 'lodash'; class GrafanaDatasource { /** @ngInject */ constructor(private backendSrv, private $q) {} query(options) { return this.backendSrv .get('/api/tsdb/testdata/random-walk', { from: options.range.from.valueOf(), to: options.range.to.valueOf(), intervalMs: options.intervalMs, maxDataPoints: options.maxDataPoints, }) .then(res => { var data = []; if (res.results) { _.forEach(res.results, queryRes => { for (let series of queryRes.series) { data.push({ target: series.name, datapoints: series.points, }); } }); } return {data: data}; }); } metricFindQuery(options) { return this.$q.when({data: []}); } annotationQuery(options) { const params: any = { from: options.range.from.valueOf(), to: options.range.to.valueOf(), limit: options.annotation.limit, tags: options.annotation.tags, }; if (options.annotation.type === 'dashboard') { // if no dashboard id yet return if (!options.dashboard.id) { return this.$q.when([]); } // filter by dashboard id params.dashboardId = options.dashboard.id; // remove tags filter if any delete params.tags; } else { // require at least one tag if (!_.isArray(options.annotation.tags) || options.annotation.tags.length === 0) { return this.$q.when([]); } } return this.backendSrv.get('/api/annotations', params); } } export {GrafanaDatasource};
public/app/plugins/datasource/grafana/datasource.ts
0
https://github.com/grafana/grafana/commit/eb31833d521f03901e1d7de53301434fef72d010
[ 0.00022586209524888545, 0.0001779526937752962, 0.00016295176465064287, 0.00017014748300425708, 0.00001982346293516457 ]
{ "id": 1, "code_window": [ " describe('getColumns', function() {\n", " it('should return data columns given a single query', function() {\n", " var columns = transformers[transform].getColumns(singleQueryData);\n", " expect(columns[0].text).toBe('Time');\n", " expect(columns[1].text).toBe('Label Key 1');\n", " expect(columns[2].text).toBe('Value #A');\n", " });\n", "\n", " it('should return the union of data columns given a multiple queries', function() {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " expect(columns[2].text).toBe('Value');\n" ], "file_path": "public/app/plugins/panel/table/specs/transformers.jest.ts", "type": "replace", "edit_start_line_idx": 191 }
#!/bin/sh set -e echo "POSTTRANS: Running script" [ -f /etc/sysconfig/grafana-server ] && . /etc/sysconfig/grafana-server # copy config files if missing if [ ! -f /etc/grafana/grafana.ini ]; then echo "POSTTRANS: Config file not found" if [ -f /etc/grafana/grafana.ini.rpmsave ]; then echo "POSTTRANS: /etc/grafana/grafana.ini.rpmsave config file found." mv /etc/grafana/grafana.ini.rpmsave /etc/grafana/grafana.ini echo "POSTTRANS: /etc/grafana/grafana.ini restored" if [ -f /etc/grafana/ldap.toml.rpmsave ]; then echo "POSTTRANS: /etc/grafana/ldap.toml.rpmsave found" mv /etc/grafana/ldap.toml.rpmsave /etc/grafana/ldap.toml echo "POSTTRANS: /etc/grafana/ldap.toml restored" fi echo "POSTTRANS: Restoring config file permissions" chown -Rh root:$GRAFANA_GROUP /etc/grafana/* chmod 755 /etc/grafana find /etc/grafana -type f -exec chmod 640 {} ';' find /etc/grafana -type d -exec chmod 755 {} ';' fi fi
packaging/rpm/control/posttrans
0
https://github.com/grafana/grafana/commit/eb31833d521f03901e1d7de53301434fef72d010
[ 0.00017640454461798072, 0.00017224102339241654, 0.00016745766333770007, 0.0001725509500829503, 0.0000036839794574916596 ]
{ "id": 2, "code_window": [ " table = transformDataToTable(singleQueryData, panel);\n", " expect(table.columns.length).toBe(3);\n", " expect(table.columns[0].text).toBe('Time');\n", " expect(table.columns[1].text).toBe('Label Key 1');\n", " expect(table.columns[2].text).toBe('Value #A');\n", " });\n", "\n", " it ('should return the union of columns for multiple queries', () => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " expect(table.columns[2].text).toBe('Value');\n" ], "file_path": "public/app/plugins/panel/table/specs/transformers.jest.ts", "type": "replace", "edit_start_line_idx": 223 }
import {transformers, transformDataToTable} from '../transformers'; describe('when transforming time series table.', () => { var table; describe('given 2 time series', () => { var time = new Date().getTime(); var timeSeries = [ { target: 'series1', datapoints: [[12.12, time], [14.44, time+1]], }, { target: 'series2', datapoints: [[16.12, time]], } ]; describe('timeseries_to_rows', () => { var panel = { transform: 'timeseries_to_rows', sort: {col: 0, desc: true}, }; beforeEach(() => { table = transformDataToTable(timeSeries, panel); }); it('should return 3 rows', () => { expect(table.rows.length).toBe(3); expect(table.rows[0][1]).toBe('series1'); expect(table.rows[1][1]).toBe('series1'); expect(table.rows[2][1]).toBe('series2'); expect(table.rows[0][2]).toBe(12.12); }); it('should return 3 rows', () => { expect(table.columns.length).toBe(3); expect(table.columns[0].text).toBe('Time'); expect(table.columns[1].text).toBe('Metric'); expect(table.columns[2].text).toBe('Value'); }); }); describe('timeseries_to_columns', () => { var panel = { transform: 'timeseries_to_columns' }; beforeEach(() => { table = transformDataToTable(timeSeries, panel); }); it ('should return 3 columns', () => { expect(table.columns.length).toBe(3); expect(table.columns[0].text).toBe('Time'); expect(table.columns[1].text).toBe('series1'); expect(table.columns[2].text).toBe('series2'); }); it ('should return 2 rows', () => { expect(table.rows.length).toBe(2); expect(table.rows[0][1]).toBe(12.12); expect(table.rows[0][2]).toBe(16.12); }); it ('should be undefined when no value for timestamp', () => { expect(table.rows[1][2]).toBe(undefined); }); }); describe('timeseries_aggregations', () => { var panel = { transform: 'timeseries_aggregations', sort: {col: 0, desc: true}, columns: [{text: 'Max', value: 'max'}, {text: 'Min', value: 'min'}] }; beforeEach(() => { table = transformDataToTable(timeSeries, panel); }); it('should return 2 rows', () => { expect(table.rows.length).toBe(2); expect(table.rows[0][0]).toBe('series1'); expect(table.rows[0][1]).toBe(14.44); expect(table.rows[0][2]).toBe(12.12); }); it('should return 2 columns', () => { expect(table.columns.length).toBe(3); expect(table.columns[0].text).toBe('Metric'); expect(table.columns[1].text).toBe('Max'); expect(table.columns[2].text).toBe('Min'); }); }); }); describe('table data sets', () => { describe('Table', () => { const transform = 'table'; var panel = { transform, }; var time = new Date().getTime(); var nonTableData = [ { type: 'foo', columns: [ { text: 'Time' }, { text: 'Label Key 1' }, { text: 'Value' }, ], rows: [ [time, 'Label Value 1', 42], ], } ]; var singleQueryData = [ { type: 'table', columns: [ { text: 'Time' }, { text: 'Label Key 1' }, { text: 'Value' }, ], rows: [ [time, 'Label Value 1', 42], ], } ]; var multipleQueriesDataSameLabels = [ { type: 'table', columns: [ { text: 'Time' }, { text: 'Label Key 1' }, { text: 'Label Key 2' }, { text: 'Value' }, ], rows: [ [time, 'Label Value 1', 'Label Value 2', 42], ], }, { type: 'table', columns: [ { text: 'Time' }, { text: 'Label Key 1' }, { text: 'Label Key 2' }, { text: 'Value' }, ], rows: [ [time, 'Label Value 1', 'Label Value 2', 13], ], } ]; var multipleQueriesDataDifferentLabels = [ { type: 'table', columns: [ { text: 'Time' }, { text: 'Label Key 1' }, { text: 'Value' }, ], rows: [ [time, 'Label Value 1', 42], ], }, { type: 'table', columns: [ { text: 'Time' }, { text: 'Label Key 2' }, { text: 'Value' }, ], rows: [ [time, 'Label Value 2', 13], ], } ]; describe('getColumns', function() { it('should return data columns given a single query', function() { var columns = transformers[transform].getColumns(singleQueryData); expect(columns[0].text).toBe('Time'); expect(columns[1].text).toBe('Label Key 1'); expect(columns[2].text).toBe('Value #A'); }); it('should return the union of data columns given a multiple queries', function() { var columns = transformers[transform].getColumns(multipleQueriesDataSameLabels); expect(columns[0].text).toBe('Time'); expect(columns[1].text).toBe('Label Key 1'); expect(columns[2].text).toBe('Label Key 2'); expect(columns[3].text).toBe('Value #A'); expect(columns[4].text).toBe('Value #B'); }); it('should return the union of data columns given a multiple queries with different labels', function() { var columns = transformers[transform].getColumns(multipleQueriesDataDifferentLabels); expect(columns[0].text).toBe('Time'); expect(columns[1].text).toBe('Label Key 1'); expect(columns[2].text).toBe('Label Key 2'); expect(columns[3].text).toBe('Value #A'); expect(columns[4].text).toBe('Value #B'); }); }); describe('transform', function() { it ('should throw an error with non-table data', () => { expect(() => transformDataToTable(nonTableData, panel)).toThrow(); }); it ('should return 3 columns for single queries', () => { table = transformDataToTable(singleQueryData, panel); expect(table.columns.length).toBe(3); expect(table.columns[0].text).toBe('Time'); expect(table.columns[1].text).toBe('Label Key 1'); expect(table.columns[2].text).toBe('Value #A'); }); it ('should return the union of columns for multiple queries', () => { table = transformDataToTable(multipleQueriesDataSameLabels, panel); expect(table.columns.length).toBe(5); expect(table.columns[0].text).toBe('Time'); expect(table.columns[1].text).toBe('Label Key 1'); expect(table.columns[2].text).toBe('Label Key 2'); expect(table.columns[3].text).toBe('Value #A'); expect(table.columns[4].text).toBe('Value #B'); }); it ('should return 1 row for a single query', () => { table = transformDataToTable(singleQueryData, panel); expect(table.rows.length).toBe(1); expect(table.rows[0][0]).toBe(time); expect(table.rows[0][1]).toBe('Label Value 1'); expect(table.rows[0][2]).toBe(42); }); it ('should return 1 row for a mulitple queries with same label values', () => { table = transformDataToTable(multipleQueriesDataSameLabels, panel); expect(table.rows.length).toBe(1); expect(table.rows[0][0]).toBe(time); expect(table.rows[0][1]).toBe('Label Value 1'); expect(table.rows[0][2]).toBe('Label Value 2'); expect(table.rows[0][3]).toBe(42); expect(table.rows[0][4]).toBe(13); }); it ('should return 2 rows for a mulitple queries with different label values', () => { table = transformDataToTable(multipleQueriesDataDifferentLabels, panel); expect(table.rows.length).toBe(2); expect(table.rows[0][0]).toBe(time); expect(table.rows[0][1]).toBe('Label Value 1'); expect(table.rows[0][2]).toBeUndefined(); expect(table.rows[0][3]).toBe(42); expect(table.rows[0][4]).toBeUndefined(); expect(table.rows[1][0]).toBe(time); expect(table.rows[1][1]).toBeUndefined(); expect(table.rows[1][2]).toBe('Label Value 2'); expect(table.rows[1][3]).toBeUndefined(); expect(table.rows[1][4]).toBe(13); }); }); }); }); describe('doc data sets', () => { describe('JSON Data', () => { var panel = { transform: 'json', columns: [ {text: 'Timestamp', value: 'timestamp'}, {text: 'Message', value: 'message'}, {text: 'nested.level2', value: 'nested.level2'}, ] }; var rawData = [ { type: 'docs', datapoints: [ { timestamp: 'time', message: 'message', nested: { level2: 'level2-value' } } ] } ]; describe('getColumns', function() { it('should return nested properties', function() { var columns = transformers['json'].getColumns(rawData); expect(columns[0].text).toBe('timestamp'); expect(columns[1].text).toBe('message'); expect(columns[2].text).toBe('nested.level2'); }); }); describe('transform', function() { beforeEach(() => { table = transformDataToTable(rawData, panel); }); it ('should return 2 columns', () => { expect(table.columns.length).toBe(3); expect(table.columns[0].text).toBe('Timestamp'); expect(table.columns[1].text).toBe('Message'); expect(table.columns[2].text).toBe('nested.level2'); }); it ('should return 2 rows', () => { expect(table.rows.length).toBe(1); expect(table.rows[0][0]).toBe('time'); expect(table.rows[0][1]).toBe('message'); expect(table.rows[0][2]).toBe('level2-value'); }); }); }); }); describe('annotation data', () => { describe('Annnotations', () => { var panel = {transform: 'annotations'}; var rawData = { annotations: [ { time: 1000, text: 'hej', tags: ['tags', 'asd'], title: 'title', } ] }; beforeEach(() => { table = transformDataToTable(rawData, panel); }); it ('should return 4 columns', () => { expect(table.columns.length).toBe(4); expect(table.columns[0].text).toBe('Time'); expect(table.columns[1].text).toBe('Title'); expect(table.columns[2].text).toBe('Text'); expect(table.columns[3].text).toBe('Tags'); }); it ('should return 1 rows', () => { expect(table.rows.length).toBe(1); expect(table.rows[0][0]).toBe(1000); }); }); }); });
public/app/plugins/panel/table/specs/transformers.jest.ts
1
https://github.com/grafana/grafana/commit/eb31833d521f03901e1d7de53301434fef72d010
[ 0.9957089424133301, 0.062351033091545105, 0.00017035756900440902, 0.0027808668091893196, 0.22168105840682983 ]
{ "id": 2, "code_window": [ " table = transformDataToTable(singleQueryData, panel);\n", " expect(table.columns.length).toBe(3);\n", " expect(table.columns[0].text).toBe('Time');\n", " expect(table.columns[1].text).toBe('Label Key 1');\n", " expect(table.columns[2].text).toBe('Value #A');\n", " });\n", "\n", " it ('should return the union of columns for multiple queries', () => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " expect(table.columns[2].text).toBe('Value');\n" ], "file_path": "public/app/plugins/panel/table/specs/transformers.jest.ts", "type": "replace", "edit_start_line_idx": 223 }
// Copyright 2013 com authors // // Licensed under the Apache License, Version 2.0 (the "License"): you may // not use this file except in compliance with the License. You may obtain // a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations // under the License. package com import ( "bytes" "crypto/aes" "crypto/cipher" "crypto/rand" "errors" r "math/rand" "strconv" "strings" "time" "unicode" "unicode/utf8" ) // AESGCMEncrypt encrypts plaintext with the given key using AES in GCM mode. func AESGCMEncrypt(key, plaintext []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { return nil, err } gcm, err := cipher.NewGCM(block) if err != nil { return nil, err } nonce := make([]byte, gcm.NonceSize()) if _, err := rand.Read(nonce); err != nil { return nil, err } ciphertext := gcm.Seal(nil, nonce, plaintext, nil) return append(nonce, ciphertext...), nil } // AESGCMDecrypt decrypts ciphertext with the given key using AES in GCM mode. func AESGCMDecrypt(key, ciphertext []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { return nil, err } gcm, err := cipher.NewGCM(block) if err != nil { return nil, err } size := gcm.NonceSize() if len(ciphertext)-size <= 0 { return nil, errors.New("Ciphertext is empty") } nonce := ciphertext[:size] ciphertext = ciphertext[size:] plainText, err := gcm.Open(nil, nonce, ciphertext, nil) if err != nil { return nil, err } return plainText, nil } // IsLetter returns true if the 'l' is an English letter. func IsLetter(l uint8) bool { n := (l | 0x20) - 'a' if n >= 0 && n < 26 { return true } return false } // Expand replaces {k} in template with match[k] or subs[atoi(k)] if k is not in match. func Expand(template string, match map[string]string, subs ...string) string { var p []byte var i int for { i = strings.Index(template, "{") if i < 0 { break } p = append(p, template[:i]...) template = template[i+1:] i = strings.Index(template, "}") if s, ok := match[template[:i]]; ok { p = append(p, s...) } else { j, _ := strconv.Atoi(template[:i]) if j >= len(subs) { p = append(p, []byte("Missing")...) } else { p = append(p, subs[j]...) } } template = template[i+1:] } p = append(p, template...) return string(p) } // Reverse s string, support unicode func Reverse(s string) string { n := len(s) runes := make([]rune, n) for _, rune := range s { n-- runes[n] = rune } return string(runes[n:]) } // RandomCreateBytes generate random []byte by specify chars. func RandomCreateBytes(n int, alphabets ...byte) []byte { const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" var bytes = make([]byte, n) var randby bool if num, err := rand.Read(bytes); num != n || err != nil { r.Seed(time.Now().UnixNano()) randby = true } for i, b := range bytes { if len(alphabets) == 0 { if randby { bytes[i] = alphanum[r.Intn(len(alphanum))] } else { bytes[i] = alphanum[b%byte(len(alphanum))] } } else { if randby { bytes[i] = alphabets[r.Intn(len(alphabets))] } else { bytes[i] = alphabets[b%byte(len(alphabets))] } } } return bytes } // ToSnakeCase can convert all upper case characters in a string to // underscore format. // // Some samples. // "FirstName" => "first_name" // "HTTPServer" => "http_server" // "NoHTTPS" => "no_https" // "GO_PATH" => "go_path" // "GO PATH" => "go_path" // space is converted to underscore. // "GO-PATH" => "go_path" // hyphen is converted to underscore. // // From https://github.com/huandu/xstrings func ToSnakeCase(str string) string { if len(str) == 0 { return "" } buf := &bytes.Buffer{} var prev, r0, r1 rune var size int r0 = '_' for len(str) > 0 { prev = r0 r0, size = utf8.DecodeRuneInString(str) str = str[size:] switch { case r0 == utf8.RuneError: buf.WriteByte(byte(str[0])) case unicode.IsUpper(r0): if prev != '_' { buf.WriteRune('_') } buf.WriteRune(unicode.ToLower(r0)) if len(str) == 0 { break } r0, size = utf8.DecodeRuneInString(str) str = str[size:] if !unicode.IsUpper(r0) { buf.WriteRune(r0) break } // find next non-upper-case character and insert `_` properly. // it's designed to convert `HTTPServer` to `http_server`. // if there are more than 2 adjacent upper case characters in a word, // treat them as an abbreviation plus a normal word. for len(str) > 0 { r1 = r0 r0, size = utf8.DecodeRuneInString(str) str = str[size:] if r0 == utf8.RuneError { buf.WriteRune(unicode.ToLower(r1)) buf.WriteByte(byte(str[0])) break } if !unicode.IsUpper(r0) { if r0 == '_' || r0 == ' ' || r0 == '-' { r0 = '_' buf.WriteRune(unicode.ToLower(r1)) } else { buf.WriteRune('_') buf.WriteRune(unicode.ToLower(r1)) buf.WriteRune(r0) } break } buf.WriteRune(unicode.ToLower(r1)) } if len(str) == 0 || r0 == '_' { buf.WriteRune(unicode.ToLower(r0)) break } default: if r0 == ' ' || r0 == '-' { r0 = '_' } buf.WriteRune(r0) } } return buf.String() }
vendor/github.com/Unknwon/com/string.go
0
https://github.com/grafana/grafana/commit/eb31833d521f03901e1d7de53301434fef72d010
[ 0.0002584505418781191, 0.00017774940351955593, 0.00016514478193130344, 0.00017488503362983465, 0.000016972420780803077 ]
{ "id": 2, "code_window": [ " table = transformDataToTable(singleQueryData, panel);\n", " expect(table.columns.length).toBe(3);\n", " expect(table.columns[0].text).toBe('Time');\n", " expect(table.columns[1].text).toBe('Label Key 1');\n", " expect(table.columns[2].text).toBe('Value #A');\n", " });\n", "\n", " it ('should return the union of columns for multiple queries', () => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " expect(table.columns[2].text).toBe('Value');\n" ], "file_path": "public/app/plugins/panel/table/specs/transformers.jest.ts", "type": "replace", "edit_start_line_idx": 223 }
///<reference path="../../../headers/common.d.ts" /> export class GraphiteConfigCtrl { static templateUrl = 'public/app/plugins/datasource/graphite/partials/config.html'; datasourceSrv: any; current: any; /** @ngInject */ constructor($scope, datasourceSrv) { this.datasourceSrv = datasourceSrv; this.current.jsonData = this.current.jsonData || {}; this.current.jsonData.graphiteVersion = this.current.jsonData.graphiteVersion || '0.9'; this.autoDetectGraphiteVersion(); } autoDetectGraphiteVersion() { this.datasourceSrv.loadDatasource(this.current.name) .then((ds) => { return ds.getVersion(); }).then((version) => { this.graphiteVersions.push({name: version, value: version}); this.current.jsonData.graphiteVersion = version; }); } graphiteVersions = [ {name: '0.9.x', value: '0.9'}, {name: '1.0.x', value: '1.0'}, {name: '1.1.x', value: '1.1'}, ]; }
public/app/plugins/datasource/graphite/config_ctrl.ts
0
https://github.com/grafana/grafana/commit/eb31833d521f03901e1d7de53301434fef72d010
[ 0.00017650026711635292, 0.00017445613048039377, 0.0001729778159642592, 0.00017417324124835432, 0.000001373959662487323 ]
{ "id": 2, "code_window": [ " table = transformDataToTable(singleQueryData, panel);\n", " expect(table.columns.length).toBe(3);\n", " expect(table.columns[0].text).toBe('Time');\n", " expect(table.columns[1].text).toBe('Label Key 1');\n", " expect(table.columns[2].text).toBe('Value #A');\n", " });\n", "\n", " it ('should return the union of columns for multiple queries', () => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " expect(table.columns[2].text).toBe('Value');\n" ], "file_path": "public/app/plugins/panel/table/specs/transformers.jest.ts", "type": "replace", "edit_start_line_idx": 223 }
// Copyright 2013 Jeremy Saenz // Copyright 2015 The Macaron Authors // // Licensed under the Apache License, Version 2.0 (the "License"): you may // not use this file except in compliance with the License. You may obtain // a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations // under the License. // Package inject provides utilities for mapping and injecting dependencies in various ways. package inject import ( "fmt" "reflect" ) // Injector represents an interface for mapping and injecting dependencies into structs // and function arguments. type Injector interface { Applicator Invoker TypeMapper // SetParent sets the parent of the injector. If the injector cannot find a // dependency in its Type map it will check its parent before returning an // error. SetParent(Injector) } // Applicator represents an interface for mapping dependencies to a struct. type Applicator interface { // Maps dependencies in the Type map to each field in the struct // that is tagged with 'inject'. Returns an error if the injection // fails. Apply(interface{}) error } // Invoker represents an interface for calling functions via reflection. type Invoker interface { // Invoke attempts to call the interface{} provided as a function, // providing dependencies for function arguments based on Type. Returns // a slice of reflect.Value representing the returned values of the function. // Returns an error if the injection fails. Invoke(interface{}) ([]reflect.Value, error) } // FastInvoker represents an interface in order to avoid the calling function via reflection. // // example: // type handlerFuncHandler func(http.ResponseWriter, *http.Request) error // func (f handlerFuncHandler)Invoke([]interface{}) ([]reflect.Value, error){ // ret := f(p[0].(http.ResponseWriter), p[1].(*http.Request)) // return []reflect.Value{reflect.ValueOf(ret)}, nil // } // // type funcHandler func(int, string) // func (f funcHandler)Invoke([]interface{}) ([]reflect.Value, error){ // f(p[0].(int), p[1].(string)) // return nil, nil // } type FastInvoker interface { // Invoke attempts to call the ordinary functions. If f is a function // with the appropriate signature, f.Invoke([]interface{}) is a Call that calls f. // Returns a slice of reflect.Value representing the returned values of the function. // Returns an error if the injection fails. Invoke([]interface{}) ([]reflect.Value, error) } // IsFastInvoker check interface is FastInvoker func IsFastInvoker(h interface{}) bool { _, ok := h.(FastInvoker) return ok } // TypeMapper represents an interface for mapping interface{} values based on type. type TypeMapper interface { // Maps the interface{} value based on its immediate type from reflect.TypeOf. Map(interface{}) TypeMapper // Maps the interface{} value based on the pointer of an Interface provided. // This is really only useful for mapping a value as an interface, as interfaces // cannot at this time be referenced directly without a pointer. MapTo(interface{}, interface{}) TypeMapper // Provides a possibility to directly insert a mapping based on type and value. // This makes it possible to directly map type arguments not possible to instantiate // with reflect like unidirectional channels. Set(reflect.Type, reflect.Value) TypeMapper // Returns the Value that is mapped to the current type. Returns a zeroed Value if // the Type has not been mapped. GetVal(reflect.Type) reflect.Value } type injector struct { values map[reflect.Type]reflect.Value parent Injector } // InterfaceOf dereferences a pointer to an Interface type. // It panics if value is not an pointer to an interface. func InterfaceOf(value interface{}) reflect.Type { t := reflect.TypeOf(value) for t.Kind() == reflect.Ptr { t = t.Elem() } if t.Kind() != reflect.Interface { panic("Called inject.InterfaceOf with a value that is not a pointer to an interface. (*MyInterface)(nil)") } return t } // New returns a new Injector. func New() Injector { return &injector{ values: make(map[reflect.Type]reflect.Value), } } // Invoke attempts to call the interface{} provided as a function, // providing dependencies for function arguments based on Type. // Returns a slice of reflect.Value representing the returned values of the function. // Returns an error if the injection fails. // It panics if f is not a function func (inj *injector) Invoke(f interface{}) ([]reflect.Value, error) { t := reflect.TypeOf(f) switch v := f.(type) { case FastInvoker: return inj.fastInvoke(v, t, t.NumIn()) default: return inj.callInvoke(f, t, t.NumIn()) } } func (inj *injector) fastInvoke(f FastInvoker, t reflect.Type, numIn int) ([]reflect.Value, error) { var in []interface{} if numIn > 0 { in = make([]interface{}, numIn) // Panic if t is not kind of Func var argType reflect.Type var val reflect.Value for i := 0; i < numIn; i++ { argType = t.In(i) val = inj.GetVal(argType) if !val.IsValid() { return nil, fmt.Errorf("Value not found for type %v", argType) } in[i] = val.Interface() } } return f.Invoke(in) } // callInvoke reflect.Value.Call func (inj *injector) callInvoke(f interface{}, t reflect.Type, numIn int) ([]reflect.Value, error) { var in []reflect.Value if numIn > 0 { in = make([]reflect.Value, numIn) var argType reflect.Type var val reflect.Value for i := 0; i < numIn; i++ { argType = t.In(i) val = inj.GetVal(argType) if !val.IsValid() { return nil, fmt.Errorf("Value not found for type %v", argType) } in[i] = val } } return reflect.ValueOf(f).Call(in), nil } // Maps dependencies in the Type map to each field in the struct // that is tagged with 'inject'. // Returns an error if the injection fails. func (inj *injector) Apply(val interface{}) error { v := reflect.ValueOf(val) for v.Kind() == reflect.Ptr { v = v.Elem() } if v.Kind() != reflect.Struct { return nil // Should not panic here ? } t := v.Type() for i := 0; i < v.NumField(); i++ { f := v.Field(i) structField := t.Field(i) if f.CanSet() && (structField.Tag == "inject" || structField.Tag.Get("inject") != "") { ft := f.Type() v := inj.GetVal(ft) if !v.IsValid() { return fmt.Errorf("Value not found for type %v", ft) } f.Set(v) } } return nil } // Maps the concrete value of val to its dynamic type using reflect.TypeOf, // It returns the TypeMapper registered in. func (i *injector) Map(val interface{}) TypeMapper { i.values[reflect.TypeOf(val)] = reflect.ValueOf(val) return i } func (i *injector) MapTo(val interface{}, ifacePtr interface{}) TypeMapper { i.values[InterfaceOf(ifacePtr)] = reflect.ValueOf(val) return i } // Maps the given reflect.Type to the given reflect.Value and returns // the Typemapper the mapping has been registered in. func (i *injector) Set(typ reflect.Type, val reflect.Value) TypeMapper { i.values[typ] = val return i } func (i *injector) GetVal(t reflect.Type) reflect.Value { val := i.values[t] if val.IsValid() { return val } // no concrete types found, try to find implementors // if t is an interface if t.Kind() == reflect.Interface { for k, v := range i.values { if k.Implements(t) { val = v break } } } // Still no type found, try to look it up on the parent if !val.IsValid() && i.parent != nil { val = i.parent.GetVal(t) } return val } func (i *injector) SetParent(parent Injector) { i.parent = parent }
vendor/github.com/go-macaron/inject/inject.go
0
https://github.com/grafana/grafana/commit/eb31833d521f03901e1d7de53301434fef72d010
[ 0.0001774452393874526, 0.00017082026170101017, 0.00016056219465099275, 0.00017059504170902073, 0.000004385402462503407 ]
{ "id": 3, "code_window": [ " if (!data || data.length === 0) {\n", " return [];\n", " }\n", "\n", " // Track column indexes: name -> index\n", " const columnNames = {};\n", "\n", " // Union of all non-value columns\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " // Single query returns data columns as is\n", " if (data.length === 1) {\n", " return [...data[0].columns];\n", " }\n", "\n" ], "file_path": "public/app/plugins/panel/table/transformers.ts", "type": "add", "edit_start_line_idx": 138 }
import _ from 'lodash'; import flatten from '../../../core/utils/flatten'; import TimeSeries from '../../../core/time_series2'; import TableModel from '../../../core/table_model'; var transformers = {}; transformers['timeseries_to_rows'] = { description: 'Time series to rows', getColumns: function() { return []; }, transform: function(data, panel, model) { model.columns = [ {text: 'Time', type: 'date'}, {text: 'Metric'}, {text: 'Value'}, ]; for (var i = 0; i < data.length; i++) { var series = data[i]; for (var y = 0; y < series.datapoints.length; y++) { var dp = series.datapoints[y]; model.rows.push([dp[1], series.target, dp[0]]); } } }, }; transformers['timeseries_to_columns'] = { description: 'Time series to columns', getColumns: function() { return []; }, transform: function(data, panel, model) { model.columns.push({text: 'Time', type: 'date'}); // group by time var points = {}; for (let i = 0; i < data.length; i++) { var series = data[i]; model.columns.push({text: series.target}); for (var y = 0; y < series.datapoints.length; y++) { var dp = series.datapoints[y]; var timeKey = dp[1].toString(); if (!points[timeKey]) { points[timeKey] = {time: dp[1]}; points[timeKey][i] = dp[0]; } else { points[timeKey][i] = dp[0]; } } } for (var time in points) { var point = points[time]; var values = [point.time]; for (let i = 0; i < data.length; i++) { var value = point[i]; values.push(value); } model.rows.push(values); } } }; transformers['timeseries_aggregations'] = { description: 'Time series aggregations', getColumns: function() { return [ {text: 'Avg', value: 'avg'}, {text: 'Min', value: 'min'}, {text: 'Max', value: 'max'}, {text: 'Total', value: 'total'}, {text: 'Current', value: 'current'}, {text: 'Count', value: 'count'}, ]; }, transform: function(data, panel, model) { var i, y; model.columns.push({text: 'Metric'}); for (i = 0; i < panel.columns.length; i++) { model.columns.push({text: panel.columns[i].text}); } for (i = 0; i < data.length; i++) { var series = new TimeSeries({ datapoints: data[i].datapoints, alias: data[i].target, }); series.getFlotPairs('connected'); var cells = [series.alias]; for (y = 0; y < panel.columns.length; y++) { cells.push(series.stats[panel.columns[y].value]); } model.rows.push(cells); } } }; transformers['annotations'] = { description: 'Annotations', getColumns: function() { return []; }, transform: function(data, panel, model) { model.columns.push({text: 'Time', type: 'date'}); model.columns.push({text: 'Title'}); model.columns.push({text: 'Text'}); model.columns.push({text: 'Tags'}); if (!data || !data.annotations || data.annotations.length === 0) { return; } for (var i = 0; i < data.annotations.length; i++) { var evt = data.annotations[i]; model.rows.push([evt.time, evt.title, evt.text, evt.tags]); } } }; transformers['table'] = { description: 'Table', getColumns: function(data) { if (!data || data.length === 0) { return []; } // Track column indexes: name -> index const columnNames = {}; // Union of all non-value columns const columns = data.reduce((acc, d, i) => { d.columns.forEach((col, j) => { const { text } = col; if (text !== 'Value') { if (columnNames[text] === undefined) { columnNames[text] = acc.length; acc.push(col); } } }); return acc; }, []); // Append one value column per data set data.forEach((_, i) => { // Value (A), Value (B),... const text = `Value #${String.fromCharCode(65 + i)}`; columnNames[text] = columns.length; columns.push({ text }); }); return columns; }, transform: function(data, panel, model) { if (!data || data.length === 0) { return; } const noTableIndex = _.findIndex(data, d => d.type !== 'table'); if (noTableIndex > -1) { throw {message: `Result of query #${String.fromCharCode(65 + noTableIndex)} is not in table format, try using another transform.`}; } // Track column indexes: name -> index const columnNames = {}; const columnIndexes = []; // Union of all non-value columns const columns = data.reduce((acc, d, i) => { const indexes = []; d.columns.forEach((col, j) => { const { text } = col; if (text !== 'Value') { if (columnNames[text] === undefined) { columnNames[text] = acc.length; acc.push(col); } indexes[j] = columnNames[text]; } }); columnIndexes.push(indexes); return acc; }, []); const nonValueColumnCount = columns.length; // Append one value column per data set data.forEach((_, i) => { // Value #A, Value #B,... const text = `Value #${String.fromCharCode(65 + i)}`; columnNames[text] = columns.length; columns.push({ text }); columnIndexes[i].push(columnNames[text]); }); model.columns = columns; // Adjust rows to new column indexes let rows = data.reduce((acc, d, i) => { const indexes = columnIndexes[i]; d.rows.forEach((r, j) => { const alteredRow = []; indexes.forEach((to, from) => { alteredRow[to] = r[from]; }); acc.push(alteredRow); }); return acc; }, []); // Merge rows that have same columns const mergedRows = {}; rows = rows.reduce((acc, row, i) => { if (!mergedRows[i]) { const match = _.findIndex(rows, (other, j) => { let same = true; for (let index = 0; index < nonValueColumnCount; index++) { if (row[index] !== other[index]) { same = false; break; } } return same; }, i + 1); if (match > -1) { const matchedRow = rows[match]; // Merge values into current row for (let index = nonValueColumnCount; index < columns.length; index++) { if (row[index] === undefined && matchedRow[index] !== undefined) { row[index] = matchedRow[index]; break; } } mergedRows[match] = matchedRow; } acc.push(row); } return acc; }, []); model.rows = rows; } }; transformers['json'] = { description: 'JSON Data', getColumns: function(data) { if (!data || data.length === 0) { return []; } var names: any = {}; for (var i = 0; i < data.length; i++) { var series = data[i]; if (series.type !== 'docs') { continue; } // only look at 100 docs var maxDocs = Math.min(series.datapoints.length, 100); for (var y = 0; y < maxDocs; y++) { var doc = series.datapoints[y]; var flattened = flatten(doc, null); for (var propName in flattened) { names[propName] = true; } } } return _.map(names, function(value, key) { return {text: key, value: key}; }); }, transform: function(data, panel, model) { var i, y, z; for (let column of panel.columns) { var tableCol: any = {text: column.text}; // if filterable data then set columns to filterable if (data.length > 0 && data[0].filterable) { tableCol.filterable = true; } model.columns.push(tableCol); } if (model.columns.length === 0) { model.columns.push({text: 'JSON'}); } for (i = 0; i < data.length; i++) { var series = data[i]; for (y = 0; y < series.datapoints.length; y++) { var dp = series.datapoints[y]; var values = []; if (_.isObject(dp) && panel.columns.length > 0) { var flattened = flatten(dp, null); for (z = 0; z < panel.columns.length; z++) { values.push(flattened[panel.columns[z].value]); } } else { values.push(JSON.stringify(dp)); } model.rows.push(values); } } } }; function transformDataToTable(data, panel) { var model = new TableModel(); if (!data || data.length === 0) { return model; } var transformer = transformers[panel.transform]; if (!transformer) { throw {message: 'Transformer ' + panel.transform + ' not found'}; } transformer.transform(data, panel, model); return model; } export {transformers, transformDataToTable};
public/app/plugins/panel/table/transformers.ts
1
https://github.com/grafana/grafana/commit/eb31833d521f03901e1d7de53301434fef72d010
[ 0.999249279499054, 0.1724540740251541, 0.00016352081729564816, 0.0011816397309303284, 0.3758617341518402 ]
{ "id": 3, "code_window": [ " if (!data || data.length === 0) {\n", " return [];\n", " }\n", "\n", " // Track column indexes: name -> index\n", " const columnNames = {};\n", "\n", " // Union of all non-value columns\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " // Single query returns data columns as is\n", " if (data.length === 1) {\n", " return [...data[0].columns];\n", " }\n", "\n" ], "file_path": "public/app/plugins/panel/table/transformers.ts", "type": "add", "edit_start_line_idx": 138 }
+++ title = "Developing App Plugins" keywords = ["grafana", "plugins", "documentation"] type = "docs" [menu.docs] name = "Developing App Plugins" parent = "developing" weight = 6 +++ # Grafana Apps App plugins are a new kind of grafana plugin that can bundle datasource and panel plugins within one package. It also enable the plugin author to create custom pages within grafana. The custom pages enable the plugin author to include things like documentation, sign up forms or controlling other services using HTTP requests. Datasource and panel plugins will show up like normal plugins. The app pages will be available in the main menu. {{< imgbox img="/img/docs/v3/app-in-main-menu.png" caption="App in Main Menu" >}} ## Enabling app plugins After installing an app, it has to be enabled before it shows up as a datasource or panel. You can do that on the app page in the config tab. ## Developing an App Plugin An App is a bundle of panels, dashboards and/or data source(s). There is nothing different about developing panels and data sources for an app. Apps have to be enabled in Grafana and should import any included dashboards when the user enables it. A ConfigCtrl class should be created and the dashboards imported in the postUpdate hook. See example below: ```javascript export class ConfigCtrl { /** @ngInject */ constructor($scope, $injector, $q) { this.$q = $q; this.enabled = false; this.appEditCtrl.setPostUpdateHook(this.postUpdate.bind(this)); } postUpdate() { if (!this.appModel.enabled) { return this.$q.resolve(); } return this.appEditCtrl.importDashboards().then(() => { this.enabled = true; return { url: "plugins/raintank-kubernetes-app/page/clusters", message: "Kubernetes App enabled!" }; }); } } ConfigCtrl.templateUrl = 'components/config/config.html'; ``` If possible a link to a dashboard or custom page should be shown after enabling the app to guide the user to the appropriate place. {{< imgbox img="/img/docs/app_plugin_after_enable.png" caption="After enabling" >}} ### Develop your own App > Our goal is not to have a very extensive documentation but rather have actual > code that people can look at. An example implementation of an app can be found > in this [example app repo](https://github.com/grafana/example-app)
docs/sources/plugins/developing/apps.md
0
https://github.com/grafana/grafana/commit/eb31833d521f03901e1d7de53301434fef72d010
[ 0.00017656355339568108, 0.0001690037752268836, 0.0001614353823242709, 0.00016799102013465017, 0.0000053822286645299755 ]
{ "id": 3, "code_window": [ " if (!data || data.length === 0) {\n", " return [];\n", " }\n", "\n", " // Track column indexes: name -> index\n", " const columnNames = {};\n", "\n", " // Union of all non-value columns\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " // Single query returns data columns as is\n", " if (data.length === 1) {\n", " return [...data[0].columns];\n", " }\n", "\n" ], "file_path": "public/app/plugins/panel/table/transformers.ts", "type": "add", "edit_start_line_idx": 138 }
package datasources import ( "errors" "io/ioutil" "path/filepath" "strings" "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/log" "github.com/grafana/grafana/pkg/models" yaml "gopkg.in/yaml.v2" ) var ( ErrInvalidConfigToManyDefault = errors.New("datasource.yaml config is invalid. Only one datasource can be marked as default") ) func Provision(configDirectory string) error { dc := newDatasourceProvisioner(log.New("provisioning.datasources")) return dc.applyChanges(configDirectory) } type DatasourceProvisioner struct { log log.Logger cfgProvider configReader } func newDatasourceProvisioner(log log.Logger) DatasourceProvisioner { return DatasourceProvisioner{ log: log, cfgProvider: configReader{}, } } func (dc *DatasourceProvisioner) apply(cfg *DatasourcesAsConfig) error { if err := dc.deleteDatasources(cfg.DeleteDatasources); err != nil { return err } for _, ds := range cfg.Datasources { cmd := &models.GetDataSourceByNameQuery{OrgId: ds.OrgId, Name: ds.Name} err := bus.Dispatch(cmd) if err != nil && err != models.ErrDataSourceNotFound { return err } if err == models.ErrDataSourceNotFound { dc.log.Info("inserting datasource from configuration ", "name", ds.Name) insertCmd := createInsertCommand(ds) if err := bus.Dispatch(insertCmd); err != nil { return err } } else { dc.log.Debug("updating datasource from configuration", "name", ds.Name) updateCmd := createUpdateCommand(ds, cmd.Result.Id) if err := bus.Dispatch(updateCmd); err != nil { return err } } } return nil } func (dc *DatasourceProvisioner) applyChanges(configPath string) error { configs, err := dc.cfgProvider.readConfig(configPath) if err != nil { return err } for _, cfg := range configs { if err := dc.apply(cfg); err != nil { return err } } return nil } func (dc *DatasourceProvisioner) deleteDatasources(dsToDelete []*DeleteDatasourceConfig) error { for _, ds := range dsToDelete { cmd := &models.DeleteDataSourceByNameCommand{OrgId: ds.OrgId, Name: ds.Name} if err := bus.Dispatch(cmd); err != nil { return err } if cmd.DeletedDatasourcesCount > 0 { dc.log.Info("deleted datasource based on configuration", "name", ds.Name) } } return nil } type configReader struct{} func (configReader) readConfig(path string) ([]*DatasourcesAsConfig, error) { files, err := ioutil.ReadDir(path) if err != nil { return nil, err } var datasources []*DatasourcesAsConfig for _, file := range files { if strings.HasSuffix(file.Name(), ".yaml") || strings.HasSuffix(file.Name(), ".yml") { filename, _ := filepath.Abs(filepath.Join(path, file.Name())) yamlFile, err := ioutil.ReadFile(filename) if err != nil { return nil, err } var datasource *DatasourcesAsConfig err = yaml.Unmarshal(yamlFile, &datasource) if err != nil { return nil, err } datasources = append(datasources, datasource) } } defaultCount := 0 for _, cfg := range datasources { for _, ds := range cfg.Datasources { if ds.OrgId == 0 { ds.OrgId = 1 } if ds.IsDefault { defaultCount++ if defaultCount > 1 { return nil, ErrInvalidConfigToManyDefault } } } for _, ds := range cfg.DeleteDatasources { if ds.OrgId == 0 { ds.OrgId = 1 } } } return datasources, nil }
pkg/services/provisioning/datasources/datasources.go
0
https://github.com/grafana/grafana/commit/eb31833d521f03901e1d7de53301434fef72d010
[ 0.000176368877873756, 0.00017151249630842358, 0.00016623633564449847, 0.00017287064110860229, 0.0000034410236366966274 ]
{ "id": 3, "code_window": [ " if (!data || data.length === 0) {\n", " return [];\n", " }\n", "\n", " // Track column indexes: name -> index\n", " const columnNames = {};\n", "\n", " // Union of all non-value columns\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " // Single query returns data columns as is\n", " if (data.length === 1) {\n", " return [...data[0].columns];\n", " }\n", "\n" ], "file_path": "public/app/plugins/panel/table/transformers.ts", "type": "add", "edit_start_line_idx": 138 }
package api import ( "strings" "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/middleware" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/setting" ) func AdminGetSettings(c *middleware.Context) { settings := make(map[string]interface{}) for _, section := range setting.Cfg.Sections() { jsonSec := make(map[string]interface{}) settings[section.Name()] = jsonSec for _, key := range section.Keys() { keyName := key.Name() value := key.Value() if strings.Contains(keyName, "secret") || strings.Contains(keyName, "password") || (strings.Contains(keyName, "provider_config")) { value = "************" } jsonSec[keyName] = value } } c.JSON(200, settings) } func AdminGetStats(c *middleware.Context) { statsQuery := m.GetAdminStatsQuery{} if err := bus.Dispatch(&statsQuery); err != nil { c.JsonApiErr(500, "Failed to get admin stats from database", err) return } c.JSON(200, statsQuery.Result) }
pkg/api/admin.go
0
https://github.com/grafana/grafana/commit/eb31833d521f03901e1d7de53301434fef72d010
[ 0.00040518754394724965, 0.00021786699653603137, 0.00016632780898362398, 0.00017485750140622258, 0.0000937403819989413 ]
{ "id": 4, "code_window": [ " return acc;\n", " }, []);\n", "\n", " // Append one value column per data set\n", " data.forEach((_, i) => {\n", " // Value (A), Value (B),...\n", " const text = `Value #${String.fromCharCode(65 + i)}`;\n", " columnNames[text] = columns.length;\n", " columns.push({ text });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " // Value #A, Value #B,...\n" ], "file_path": "public/app/plugins/panel/table/transformers.ts", "type": "replace", "edit_start_line_idx": 157 }
import _ from 'lodash'; import flatten from '../../../core/utils/flatten'; import TimeSeries from '../../../core/time_series2'; import TableModel from '../../../core/table_model'; var transformers = {}; transformers['timeseries_to_rows'] = { description: 'Time series to rows', getColumns: function() { return []; }, transform: function(data, panel, model) { model.columns = [ {text: 'Time', type: 'date'}, {text: 'Metric'}, {text: 'Value'}, ]; for (var i = 0; i < data.length; i++) { var series = data[i]; for (var y = 0; y < series.datapoints.length; y++) { var dp = series.datapoints[y]; model.rows.push([dp[1], series.target, dp[0]]); } } }, }; transformers['timeseries_to_columns'] = { description: 'Time series to columns', getColumns: function() { return []; }, transform: function(data, panel, model) { model.columns.push({text: 'Time', type: 'date'}); // group by time var points = {}; for (let i = 0; i < data.length; i++) { var series = data[i]; model.columns.push({text: series.target}); for (var y = 0; y < series.datapoints.length; y++) { var dp = series.datapoints[y]; var timeKey = dp[1].toString(); if (!points[timeKey]) { points[timeKey] = {time: dp[1]}; points[timeKey][i] = dp[0]; } else { points[timeKey][i] = dp[0]; } } } for (var time in points) { var point = points[time]; var values = [point.time]; for (let i = 0; i < data.length; i++) { var value = point[i]; values.push(value); } model.rows.push(values); } } }; transformers['timeseries_aggregations'] = { description: 'Time series aggregations', getColumns: function() { return [ {text: 'Avg', value: 'avg'}, {text: 'Min', value: 'min'}, {text: 'Max', value: 'max'}, {text: 'Total', value: 'total'}, {text: 'Current', value: 'current'}, {text: 'Count', value: 'count'}, ]; }, transform: function(data, panel, model) { var i, y; model.columns.push({text: 'Metric'}); for (i = 0; i < panel.columns.length; i++) { model.columns.push({text: panel.columns[i].text}); } for (i = 0; i < data.length; i++) { var series = new TimeSeries({ datapoints: data[i].datapoints, alias: data[i].target, }); series.getFlotPairs('connected'); var cells = [series.alias]; for (y = 0; y < panel.columns.length; y++) { cells.push(series.stats[panel.columns[y].value]); } model.rows.push(cells); } } }; transformers['annotations'] = { description: 'Annotations', getColumns: function() { return []; }, transform: function(data, panel, model) { model.columns.push({text: 'Time', type: 'date'}); model.columns.push({text: 'Title'}); model.columns.push({text: 'Text'}); model.columns.push({text: 'Tags'}); if (!data || !data.annotations || data.annotations.length === 0) { return; } for (var i = 0; i < data.annotations.length; i++) { var evt = data.annotations[i]; model.rows.push([evt.time, evt.title, evt.text, evt.tags]); } } }; transformers['table'] = { description: 'Table', getColumns: function(data) { if (!data || data.length === 0) { return []; } // Track column indexes: name -> index const columnNames = {}; // Union of all non-value columns const columns = data.reduce((acc, d, i) => { d.columns.forEach((col, j) => { const { text } = col; if (text !== 'Value') { if (columnNames[text] === undefined) { columnNames[text] = acc.length; acc.push(col); } } }); return acc; }, []); // Append one value column per data set data.forEach((_, i) => { // Value (A), Value (B),... const text = `Value #${String.fromCharCode(65 + i)}`; columnNames[text] = columns.length; columns.push({ text }); }); return columns; }, transform: function(data, panel, model) { if (!data || data.length === 0) { return; } const noTableIndex = _.findIndex(data, d => d.type !== 'table'); if (noTableIndex > -1) { throw {message: `Result of query #${String.fromCharCode(65 + noTableIndex)} is not in table format, try using another transform.`}; } // Track column indexes: name -> index const columnNames = {}; const columnIndexes = []; // Union of all non-value columns const columns = data.reduce((acc, d, i) => { const indexes = []; d.columns.forEach((col, j) => { const { text } = col; if (text !== 'Value') { if (columnNames[text] === undefined) { columnNames[text] = acc.length; acc.push(col); } indexes[j] = columnNames[text]; } }); columnIndexes.push(indexes); return acc; }, []); const nonValueColumnCount = columns.length; // Append one value column per data set data.forEach((_, i) => { // Value #A, Value #B,... const text = `Value #${String.fromCharCode(65 + i)}`; columnNames[text] = columns.length; columns.push({ text }); columnIndexes[i].push(columnNames[text]); }); model.columns = columns; // Adjust rows to new column indexes let rows = data.reduce((acc, d, i) => { const indexes = columnIndexes[i]; d.rows.forEach((r, j) => { const alteredRow = []; indexes.forEach((to, from) => { alteredRow[to] = r[from]; }); acc.push(alteredRow); }); return acc; }, []); // Merge rows that have same columns const mergedRows = {}; rows = rows.reduce((acc, row, i) => { if (!mergedRows[i]) { const match = _.findIndex(rows, (other, j) => { let same = true; for (let index = 0; index < nonValueColumnCount; index++) { if (row[index] !== other[index]) { same = false; break; } } return same; }, i + 1); if (match > -1) { const matchedRow = rows[match]; // Merge values into current row for (let index = nonValueColumnCount; index < columns.length; index++) { if (row[index] === undefined && matchedRow[index] !== undefined) { row[index] = matchedRow[index]; break; } } mergedRows[match] = matchedRow; } acc.push(row); } return acc; }, []); model.rows = rows; } }; transformers['json'] = { description: 'JSON Data', getColumns: function(data) { if (!data || data.length === 0) { return []; } var names: any = {}; for (var i = 0; i < data.length; i++) { var series = data[i]; if (series.type !== 'docs') { continue; } // only look at 100 docs var maxDocs = Math.min(series.datapoints.length, 100); for (var y = 0; y < maxDocs; y++) { var doc = series.datapoints[y]; var flattened = flatten(doc, null); for (var propName in flattened) { names[propName] = true; } } } return _.map(names, function(value, key) { return {text: key, value: key}; }); }, transform: function(data, panel, model) { var i, y, z; for (let column of panel.columns) { var tableCol: any = {text: column.text}; // if filterable data then set columns to filterable if (data.length > 0 && data[0].filterable) { tableCol.filterable = true; } model.columns.push(tableCol); } if (model.columns.length === 0) { model.columns.push({text: 'JSON'}); } for (i = 0; i < data.length; i++) { var series = data[i]; for (y = 0; y < series.datapoints.length; y++) { var dp = series.datapoints[y]; var values = []; if (_.isObject(dp) && panel.columns.length > 0) { var flattened = flatten(dp, null); for (z = 0; z < panel.columns.length; z++) { values.push(flattened[panel.columns[z].value]); } } else { values.push(JSON.stringify(dp)); } model.rows.push(values); } } } }; function transformDataToTable(data, panel) { var model = new TableModel(); if (!data || data.length === 0) { return model; } var transformer = transformers[panel.transform]; if (!transformer) { throw {message: 'Transformer ' + panel.transform + ' not found'}; } transformer.transform(data, panel, model); return model; } export {transformers, transformDataToTable};
public/app/plugins/panel/table/transformers.ts
1
https://github.com/grafana/grafana/commit/eb31833d521f03901e1d7de53301434fef72d010
[ 0.9984055161476135, 0.3076067566871643, 0.00016889350081328303, 0.0013783376198261976, 0.4310377538204193 ]
{ "id": 4, "code_window": [ " return acc;\n", " }, []);\n", "\n", " // Append one value column per data set\n", " data.forEach((_, i) => {\n", " // Value (A), Value (B),...\n", " const text = `Value #${String.fromCharCode(65 + i)}`;\n", " columnNames[text] = columns.length;\n", " columns.push({ text });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " // Value #A, Value #B,...\n" ], "file_path": "public/app/plugins/panel/table/transformers.ts", "type": "replace", "edit_start_line_idx": 157 }
foo[:10:]
vendor/github.com/jmespath/go-jmespath/fuzz/corpus/expr-509
0
https://github.com/grafana/grafana/commit/eb31833d521f03901e1d7de53301434fef72d010
[ 0.00017325264343526214, 0.00017325264343526214, 0.00017325264343526214, 0.00017325264343526214, 0 ]