hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
sequencelengths 5
5
|
---|---|---|---|---|---|
{
"id": 3,
"code_window": [
" [key: string]: string;\n",
"}\n",
"\n",
"export enum LogsDedupStrategy {\n",
" none = 'none',\n",
" exact = 'exact',\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"export enum LogsDedupDescription {\n",
" none = 'No de-duplication',\n",
" exact = 'De-duplication of successive lines that are identical, ignoring ISO datetimes.',\n",
" numbers = 'De-duplication of successive lines that are identical when ignoring numbers, e.g., IP addresses, latencies.',\n",
" signature = 'De-duplication of successive lines that have identical punctuation and whitespace.',\n",
"}\n",
"\n"
],
"file_path": "public/app/core/logs_model.ts",
"type": "add",
"edit_start_line_idx": 90
} | procfs provides functions to retrieve system, kernel and process
metrics from the pseudo-filesystem proc.
Copyright 2014-2015 The Prometheus Authors
This product includes software developed at
SoundCloud Ltd. (http://soundcloud.com/).
| vendor/github.com/prometheus/procfs/NOTICE | 0 | https://github.com/grafana/grafana/commit/487de2b832126060bb1001295765cd6dee3fdb34 | [
0.00016903849609661847,
0.00016903849609661847,
0.00016903849609661847,
0.00016903849609661847,
0
] |
{
"id": 3,
"code_window": [
" [key: string]: string;\n",
"}\n",
"\n",
"export enum LogsDedupStrategy {\n",
" none = 'none',\n",
" exact = 'exact',\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"export enum LogsDedupDescription {\n",
" none = 'No de-duplication',\n",
" exact = 'De-duplication of successive lines that are identical, ignoring ISO datetimes.',\n",
" numbers = 'De-duplication of successive lines that are identical when ignoring numbers, e.g., IP addresses, latencies.',\n",
" signature = 'De-duplication of successive lines that have identical punctuation and whitespace.',\n",
"}\n",
"\n"
],
"file_path": "public/app/core/logs_model.ts",
"type": "add",
"edit_start_line_idx": 90
} | package util
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
)
//WalkSkipDir is the Error returned when we want to skip descending into a directory
var WalkSkipDir = errors.New("skip this directory")
//WalkFunc is a callback function called for each path as a directory is walked
//If resolvedPath != "", then we are following symbolic links.
type WalkFunc func(resolvedPath string, info os.FileInfo, err error) error
//Walk walks a path, optionally following symbolic links, and for each path,
//it calls the walkFn passed.
//
//It is similar to filepath.Walk, except that it supports symbolic links and
//can detect infinite loops while following sym links.
//It solves the issue where your WalkFunc needs a path relative to the symbolic link
//(resolving links within walkfunc loses the path to the symbolic link for each traversal).
func Walk(path string, followSymlinks bool, detectSymlinkInfiniteLoop bool, walkFn WalkFunc) error {
info, err := os.Lstat(path)
if err != nil {
return err
}
var symlinkPathsFollowed map[string]bool
var resolvedPath string
if followSymlinks {
resolvedPath = path
if detectSymlinkInfiniteLoop {
symlinkPathsFollowed = make(map[string]bool, 8)
}
}
return walk(path, info, resolvedPath, symlinkPathsFollowed, walkFn)
}
//walk walks the path. It is a helper/sibling function to Walk.
//It takes a resolvedPath into consideration. This way, paths being walked are
//always relative to the path argument, even if symbolic links were resolved).
//
//If resolvedPath is "", then we are not following symbolic links.
//If symlinkPathsFollowed is not nil, then we need to detect infinite loop.
func walk(path string, info os.FileInfo, resolvedPath string, symlinkPathsFollowed map[string]bool, walkFn WalkFunc) error {
if info == nil {
return errors.New("Walk: Nil FileInfo passed")
}
err := walkFn(resolvedPath, info, nil)
if err != nil {
if info.IsDir() && err == WalkSkipDir {
err = nil
}
return err
}
if resolvedPath != "" && info.Mode()&os.ModeSymlink == os.ModeSymlink {
path2, err := os.Readlink(resolvedPath)
if err != nil {
return err
}
//vout("SymLink Path: %v, links to: %v", resolvedPath, path2)
if symlinkPathsFollowed != nil {
if _, ok := symlinkPathsFollowed[path2]; ok {
errMsg := "Potential SymLink Infinite Loop. Path: %v, Link To: %v"
return fmt.Errorf(errMsg, resolvedPath, path2)
}
symlinkPathsFollowed[path2] = true
}
info2, err := os.Lstat(path2)
if err != nil {
return err
}
return walk(path, info2, path2, symlinkPathsFollowed, walkFn)
}
if info.IsDir() {
list, err := ioutil.ReadDir(path)
if err != nil {
return walkFn(resolvedPath, info, err)
}
var subFiles = make([]subFile, 0)
for _, fileInfo := range list {
path2 := filepath.Join(path, fileInfo.Name())
var resolvedPath2 string
if resolvedPath != "" {
resolvedPath2 = filepath.Join(resolvedPath, fileInfo.Name())
}
subFiles = append(subFiles, subFile{path: path2, resolvedPath: resolvedPath2, fileInfo: fileInfo})
}
if containsDistFolder(subFiles) {
err := walk(
filepath.Join(path, "dist"),
info,
filepath.Join(resolvedPath, "dist"),
symlinkPathsFollowed,
walkFn)
if err != nil {
return err
}
} else {
for _, p := range subFiles {
err = walk(p.path, p.fileInfo, p.resolvedPath, symlinkPathsFollowed, walkFn)
if err != nil {
return err
}
}
}
return nil
}
return nil
}
type subFile struct {
path, resolvedPath string
fileInfo os.FileInfo
}
func containsDistFolder(subFiles []subFile) bool {
for _, p := range subFiles {
if p.fileInfo.IsDir() && p.fileInfo.Name() == "dist" {
return true
}
}
return false
}
| pkg/util/filepath.go | 0 | https://github.com/grafana/grafana/commit/487de2b832126060bb1001295765cd6dee3fdb34 | [
0.00042701023630797863,
0.0002073444047709927,
0.00016822456382215023,
0.00017353330622427166,
0.00006731352914357558
] |
{
"id": 4,
"code_window": [
"import classnames from 'classnames';\n",
"\n",
"import * as rangeUtil from 'app/core/utils/rangeutil';\n",
"import { RawTimeRange } from 'app/types/series';\n",
"import {\n",
" LogsDedupStrategy,\n",
" LogsModel,\n",
" dedupLogRows,\n",
" filterLogLevels,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" LogsDedupDescription,\n"
],
"file_path": "public/app/features/explore/Logs.tsx",
"type": "add",
"edit_start_line_idx": 8
} | import _ from 'lodash';
import { TimeSeries } from 'app/core/core';
import colors, { getThemeColor } from 'app/core/utils/colors';
export enum LogLevel {
crit = 'critical',
critical = 'critical',
warn = 'warning',
warning = 'warning',
err = 'error',
error = 'error',
info = 'info',
debug = 'debug',
trace = 'trace',
unkown = 'unkown',
}
export const LogLevelColor = {
[LogLevel.critical]: colors[7],
[LogLevel.warning]: colors[1],
[LogLevel.error]: colors[4],
[LogLevel.info]: colors[0],
[LogLevel.debug]: colors[5],
[LogLevel.trace]: colors[2],
[LogLevel.unkown]: getThemeColor('#8e8e8e', '#dde4ed'),
};
export interface LogSearchMatch {
start: number;
length: number;
text: string;
}
export interface LogRow {
duplicates?: number;
entry: string;
key: string; // timestamp + labels
labels: LogsStreamLabels;
logLevel: LogLevel;
searchWords?: string[];
timestamp: string; // ISO with nanosec precision
timeFromNow: string;
timeEpochMs: number;
timeLocal: string;
uniqueLabels?: LogsStreamLabels;
}
export interface LogsLabelStat {
active?: boolean;
count: number;
proportion: number;
value: string;
}
export enum LogsMetaKind {
Number,
String,
LabelsMap,
}
export interface LogsMetaItem {
label: string;
value: string | number | LogsStreamLabels;
kind: LogsMetaKind;
}
export interface LogsModel {
id: string; // Identify one logs result from another
meta?: LogsMetaItem[];
rows: LogRow[];
series?: TimeSeries[];
}
export interface LogsStream {
labels: string;
entries: LogsStreamEntry[];
search?: string;
parsedLabels?: LogsStreamLabels;
uniqueLabels?: LogsStreamLabels;
}
export interface LogsStreamEntry {
line: string;
timestamp: string;
}
export interface LogsStreamLabels {
[key: string]: string;
}
export enum LogsDedupStrategy {
none = 'none',
exact = 'exact',
numbers = 'numbers',
signature = 'signature',
}
export interface LogsParser {
/**
* Value-agnostic matcher for a field label.
* Used to filter rows, and first capture group contains the value.
*/
buildMatcher: (label: string) => RegExp;
/**
* Regex to find a field in the log line.
* First capture group contains the label value, second capture group the value.
*/
fieldRegex: RegExp;
/**
* Function to verify if this is a valid parser for the given line.
* The parser accepts the line unless it returns undefined.
*/
test: (line: string) => any;
}
export const LogsParsers: { [name: string]: LogsParser } = {
JSON: {
buildMatcher: label => new RegExp(`(?:{|,)\\s*"${label}"\\s*:\\s*"([^"]*)"`),
fieldRegex: /"(\w+)"\s*:\s*"([^"]*)"/,
test: line => {
try {
return JSON.parse(line);
} catch (error) {}
},
},
logfmt: {
buildMatcher: label => new RegExp(`(?:^|\\s)${label}=("[^"]*"|\\S+)`),
fieldRegex: /(?:^|\s)(\w+)=("[^"]*"|\S+)/,
test: line => LogsParsers.logfmt.fieldRegex.test(line),
},
};
export function calculateFieldStats(rows: LogRow[], extractor: RegExp): LogsLabelStat[] {
// Consider only rows that satisfy the matcher
const rowsWithField = rows.filter(row => extractor.test(row.entry));
const rowCount = rowsWithField.length;
// Get field value counts for eligible rows
const countsByValue = _.countBy(rowsWithField, row => (row as LogRow).entry.match(extractor)[1]);
const sortedCounts = _.chain(countsByValue)
.map((count, value) => ({ count, value, proportion: count / rowCount }))
.sortBy('count')
.reverse()
.value();
return sortedCounts;
}
export function calculateLogsLabelStats(rows: LogRow[], label: string): LogsLabelStat[] {
// Consider only rows that have the given label
const rowsWithLabel = rows.filter(row => row.labels[label] !== undefined);
const rowCount = rowsWithLabel.length;
// Get label value counts for eligible rows
const countsByValue = _.countBy(rowsWithLabel, row => (row as LogRow).labels[label]);
const sortedCounts = _.chain(countsByValue)
.map((count, value) => ({ count, value, proportion: count / rowCount }))
.sortBy('count')
.reverse()
.value();
return sortedCounts;
}
const isoDateRegexp = /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-6]\d[,\.]\d+([+-][0-2]\d:[0-5]\d|Z)/g;
function isDuplicateRow(row: LogRow, other: LogRow, strategy: LogsDedupStrategy): boolean {
switch (strategy) {
case LogsDedupStrategy.exact:
// Exact still strips dates
return row.entry.replace(isoDateRegexp, '') === other.entry.replace(isoDateRegexp, '');
case LogsDedupStrategy.numbers:
return row.entry.replace(/\d/g, '') === other.entry.replace(/\d/g, '');
case LogsDedupStrategy.signature:
return row.entry.replace(/\w/g, '') === other.entry.replace(/\w/g, '');
default:
return false;
}
}
export function dedupLogRows(logs: LogsModel, strategy: LogsDedupStrategy): LogsModel {
if (strategy === LogsDedupStrategy.none) {
return logs;
}
const dedupedRows = logs.rows.reduce((result: LogRow[], row: LogRow, index, list) => {
const previous = result[result.length - 1];
if (index > 0 && isDuplicateRow(row, previous, strategy)) {
previous.duplicates++;
} else {
row.duplicates = 0;
result.push(row);
}
return result;
}, []);
return {
...logs,
rows: dedupedRows,
};
}
export function getParser(line: string): LogsParser {
let parser;
try {
if (LogsParsers.JSON.test(line)) {
parser = LogsParsers.JSON;
}
} catch (error) {}
if (!parser && LogsParsers.logfmt.test(line)) {
parser = LogsParsers.logfmt;
}
return parser;
}
export function filterLogLevels(logs: LogsModel, hiddenLogLevels: Set<LogLevel>): LogsModel {
if (hiddenLogLevels.size === 0) {
return logs;
}
const filteredRows = logs.rows.reduce((result: LogRow[], row: LogRow, index, list) => {
if (!hiddenLogLevels.has(row.logLevel)) {
result.push(row);
}
return result;
}, []);
return {
...logs,
rows: filteredRows,
};
}
export function makeSeriesForLogs(rows: LogRow[], intervalMs: number): TimeSeries[] {
// currently interval is rangeMs / resolution, which is too low for showing series as bars.
// need at least 10px per bucket, so we multiply interval by 10. Should be solved higher up the chain
// when executing queries & interval calculated and not here but this is a temporary fix.
// intervalMs = intervalMs * 10;
// Graph time series by log level
const seriesByLevel = {};
const bucketSize = intervalMs * 10;
for (const row of rows) {
if (!seriesByLevel[row.logLevel]) {
seriesByLevel[row.logLevel] = { lastTs: null, datapoints: [], alias: row.logLevel };
}
const levelSeries = seriesByLevel[row.logLevel];
// Bucket to nearest minute
const time = Math.round(row.timeEpochMs / bucketSize) * bucketSize;
// Entry for time
if (time === levelSeries.lastTs) {
levelSeries.datapoints[levelSeries.datapoints.length - 1][0]++;
} else {
levelSeries.datapoints.push([1, time]);
levelSeries.lastTs = time;
}
}
return Object.keys(seriesByLevel).reduce((acc, level) => {
if (seriesByLevel[level]) {
const gs = new TimeSeries(seriesByLevel[level]);
gs.setColor(LogLevelColor[level]);
acc.push(gs);
}
return acc;
}, []);
}
| public/app/core/logs_model.ts | 1 | https://github.com/grafana/grafana/commit/487de2b832126060bb1001295765cd6dee3fdb34 | [
0.014358440414071083,
0.0013285493478178978,
0.0001654172665439546,
0.00022479459585156292,
0.002976472955197096
] |
{
"id": 4,
"code_window": [
"import classnames from 'classnames';\n",
"\n",
"import * as rangeUtil from 'app/core/utils/rangeutil';\n",
"import { RawTimeRange } from 'app/types/series';\n",
"import {\n",
" LogsDedupStrategy,\n",
" LogsModel,\n",
" dedupLogRows,\n",
" filterLogLevels,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" LogsDedupDescription,\n"
],
"file_path": "public/app/features/explore/Logs.tsx",
"type": "add",
"edit_start_line_idx": 8
} | #!/bin/bash
_circle_token=$1
trigger_build_url=https://circleci.com/api/v1/project/grafana/grafana-packer/tree/master?circle-token=${_circle_token}
curl \
--header "Accept: application/json" \
--header "Content-Type: application/json" \
--request POST ${trigger_build_url} | scripts/trigger_grafana_packer.sh | 0 | https://github.com/grafana/grafana/commit/487de2b832126060bb1001295765cd6dee3fdb34 | [
0.00017210323130711913,
0.00017172080697491765,
0.0001713383971946314,
0.00017172080697491765,
3.824170562438667e-7
] |
{
"id": 4,
"code_window": [
"import classnames from 'classnames';\n",
"\n",
"import * as rangeUtil from 'app/core/utils/rangeutil';\n",
"import { RawTimeRange } from 'app/types/series';\n",
"import {\n",
" LogsDedupStrategy,\n",
" LogsModel,\n",
" dedupLogRows,\n",
" filterLogLevels,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" LogsDedupDescription,\n"
],
"file_path": "public/app/features/explore/Logs.tsx",
"type": "add",
"edit_start_line_idx": 8
} | import uniqBy from 'lodash/uniqBy';
import { alignOptions, aggOptions } from './constants';
export const extractServicesFromMetricDescriptors = metricDescriptors => uniqBy(metricDescriptors, 'service');
export const getMetricTypesByService = (metricDescriptors, service) =>
metricDescriptors.filter(m => m.service === service);
export const getMetricTypes = (metricDescriptors, metricType, interpolatedMetricType, selectedService) => {
const metricTypes = getMetricTypesByService(metricDescriptors, selectedService).map(m => ({
value: m.type,
name: m.displayName,
}));
const metricTypeExistInArray = metricTypes.some(m => m.value === interpolatedMetricType);
const selectedMetricType = metricTypeExistInArray ? metricType : metricTypes[0].value;
return {
metricTypes,
selectedMetricType,
};
};
export const getAlignmentOptionsByMetric = (metricValueType, metricKind) => {
return !metricValueType
? []
: alignOptions.filter(i => {
return i.valueTypes.indexOf(metricValueType) !== -1 && i.metricKinds.indexOf(metricKind) !== -1;
});
};
export const getAggregationOptionsByMetric = (valueType, metricKind) => {
return !metricKind
? []
: aggOptions.filter(i => {
return i.valueTypes.indexOf(valueType) !== -1 && i.metricKinds.indexOf(metricKind) !== -1;
});
};
export const getLabelKeys = async (datasource, selectedMetricType) => {
const refId = 'handleLabelKeysQuery';
const response = await datasource.getLabels(selectedMetricType, refId);
const labelKeys = response.meta
? [
...Object.keys(response.meta.resourceLabels).map(l => `resource.label.${l}`),
...Object.keys(response.meta.metricLabels).map(l => `metric.label.${l}`),
]
: [];
return labelKeys;
};
| public/app/plugins/datasource/stackdriver/functions.ts | 0 | https://github.com/grafana/grafana/commit/487de2b832126060bb1001295765cd6dee3fdb34 | [
0.0001749347138684243,
0.00017247145297005773,
0.00016913523722905666,
0.0001726184564176947,
0.000001902302301459713
] |
{
"id": 4,
"code_window": [
"import classnames from 'classnames';\n",
"\n",
"import * as rangeUtil from 'app/core/utils/rangeutil';\n",
"import { RawTimeRange } from 'app/types/series';\n",
"import {\n",
" LogsDedupStrategy,\n",
" LogsModel,\n",
" dedupLogRows,\n",
" filterLogLevels,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" LogsDedupDescription,\n"
],
"file_path": "public/app/features/explore/Logs.tsx",
"type": "add",
"edit_start_line_idx": 8
} | +++
title = "Folder Permissions HTTP API "
description = "Grafana Folder Permissions HTTP API"
keywords = ["grafana", "http", "documentation", "api", "folder", "permission", "permissions", "acl"]
aliases = ["/http_api/dashboardpermissions/"]
type = "docs"
[menu.docs]
name = "Folder Permissions"
parent = "http_api"
+++
# Folder Permissions API
This API can be used to update/get the permissions for a folder.
Permissions with `folderId=-1` are the default permissions for users with the Viewer and Editor roles. Permissions can be set for a user, a team or a role (Viewer or Editor). Permissions cannot be set for Admins - they always have access to everything.
The permission levels for the permission field:
- 1 = View
- 2 = Edit
- 4 = Admin
## Get permissions for a folder
`GET /api/folders/:uid/permissions`
Gets all existing permissions for the folder with the given `uid`.
**Example request**:
```http
GET /api/folders/nErXDvCkzz/permissions HTTP/1.1
Accept: application/json
Content-Type: application/json
Authorization: Bearer eyJrIjoiT0tTcG1pUlY2RnVKZTFVaDFsNFZXdE9ZWmNrMkZYbk
```
**Example Response**
```http
HTTP/1.1 200 OK
Content-Type: application/json; charset=UTF-8
Content-Length: 551
[
{
"id": 1,
"folderId": -1,
"created": "2017-06-20T02:00:00+02:00",
"updated": "2017-06-20T02:00:00+02:00",
"userId": 0,
"userLogin": "",
"userEmail": "",
"teamId": 0,
"team": "",
"role": "Viewer",
"permission": 1,
"permissionName": "View",
"uid": "nErXDvCkzz",
"title": "",
"slug": "",
"isFolder": false,
"url": ""
},
{
"id": 2,
"dashboardId": -1,
"created": "2017-06-20T02:00:00+02:00",
"updated": "2017-06-20T02:00:00+02:00",
"userId": 0,
"userLogin": "",
"userEmail": "",
"teamId": 0,
"team": "",
"role": "Editor",
"permission": 2,
"permissionName": "Edit",
"uid": "",
"title": "",
"slug": "",
"isFolder": false,
"url": ""
}
]
```
Status Codes:
- **200** - Ok
- **401** - Unauthorized
- **403** - Access denied
- **404** - Folder not found
## Update permissions for a folder
`POST /api/folders/:uid/permissions`
Updates permissions for a folder. This operation will remove existing permissions if they're not included in the request.
**Example request**:
```http
POST /api/folders/nErXDvCkzz/permissions
Accept: application/json
Content-Type: application/json
Authorization: Bearer eyJrIjoiT0tTcG1pUlY2RnVKZTFVaDFsNFZXdE9ZWmNrMkZYbk
"items": [
{
"role": "Viewer",
"permission": 1
},
{
"role": "Editor",
"permission": 2
},
{
"teamId": 1,
"permission": 1
},
{
"userId": 11,
"permission": 4
}
]
}
```
JSON body schema:
- **items** - The permission items to add/update. Items that are omitted from the list will be removed.
**Example response**:
```http
HTTP/1.1 200 OK
Content-Type: application/json; charset=UTF-8
Content-Length: 35
{"message":"Folder permissions updated"}
```
Status Codes:
- **200** - Ok
- **401** - Unauthorized
- **403** - Access denied
- **404** - Dashboard not found
| docs/sources/http_api/folder_permissions.md | 0 | https://github.com/grafana/grafana/commit/487de2b832126060bb1001295765cd6dee3fdb34 | [
0.00017359164485242218,
0.0001692344230832532,
0.00016231441986747086,
0.0001697851112112403,
0.0000034066824809997343
] |
{
"id": 5,
"code_window": [
" <ToggleButton\n",
" className=\"btn-small\"\n",
" key={i}\n",
" value={dedupType}\n",
" onChange={onChange}\n",
" selected={selectedValue === dedupType}\n",
" >\n",
" {dedupType}\n",
" </ToggleButton>\n",
" ))\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" title={LogsDedupDescription[dedupType] || null}\n"
],
"file_path": "public/app/features/explore/Logs.tsx",
"type": "add",
"edit_start_line_idx": 447
} | import React, { SFC, ReactNode, PureComponent, ReactElement } from 'react';
interface ToggleButtonGroupProps {
onChange: (value) => void;
value?: any;
label?: string;
render: (props) => void;
}
export default class ToggleButtonGroup extends PureComponent<ToggleButtonGroupProps> {
getValues() {
const { children } = this.props;
return React.Children.toArray(children).map((c: ReactElement<any>) => c.props.value);
}
smallChildren() {
const { children } = this.props;
return React.Children.toArray(children).every((c: ReactElement<any>) => c.props.className.includes('small'));
}
handleToggle(toggleValue) {
const { value, onChange } = this.props;
if (value && value === toggleValue) {
return;
}
onChange(toggleValue);
}
render() {
const { value, label } = this.props;
const values = this.getValues();
const selectedValue = value || values[0];
const labelClassName = `gf-form-label ${this.smallChildren() ? 'small' : ''}`;
return (
<div className="gf-form">
<div className="toggle-button-group">
{label && <label className={labelClassName}>{label}</label>}
{this.props.render({ selectedValue, onChange: this.handleToggle.bind(this) })}
</div>
</div>
);
}
}
interface ToggleButtonProps {
onChange?: (value) => void;
selected?: boolean;
value: any;
className?: string;
children: ReactNode;
}
export const ToggleButton: SFC<ToggleButtonProps> = ({ children, selected, className = '', value, onChange }) => {
const handleChange = event => {
event.stopPropagation();
if (onChange) {
onChange(value);
}
};
const btnClassName = `btn ${className} ${selected ? 'active' : ''}`;
return (
<button className={btnClassName} onClick={handleChange}>
<span>{children}</span>
</button>
);
};
| public/app/core/components/ToggleButtonGroup/ToggleButtonGroup.tsx | 1 | https://github.com/grafana/grafana/commit/487de2b832126060bb1001295765cd6dee3fdb34 | [
0.039766643196344376,
0.008772926405072212,
0.00016805302584543824,
0.0035371279809623957,
0.012901270762085915
] |
{
"id": 5,
"code_window": [
" <ToggleButton\n",
" className=\"btn-small\"\n",
" key={i}\n",
" value={dedupType}\n",
" onChange={onChange}\n",
" selected={selectedValue === dedupType}\n",
" >\n",
" {dedupType}\n",
" </ToggleButton>\n",
" ))\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" title={LogsDedupDescription[dedupType] || null}\n"
],
"file_path": "public/app/features/explore/Logs.tsx",
"type": "add",
"edit_start_line_idx": 447
} | import _ from 'lodash';
import queryPart from './query_part';
import kbn from 'app/core/utils/kbn';
export default class InfluxQuery {
target: any;
selectModels: any[];
queryBuilder: any;
groupByParts: any;
templateSrv: any;
scopedVars: any;
/** @ngInject */
constructor(target, templateSrv?, scopedVars?) {
this.target = target;
this.templateSrv = templateSrv;
this.scopedVars = scopedVars;
target.policy = target.policy || 'default';
target.resultFormat = target.resultFormat || 'time_series';
target.orderByTime = target.orderByTime || 'ASC';
target.tags = target.tags || [];
target.groupBy = target.groupBy || [{ type: 'time', params: ['$__interval'] }, { type: 'fill', params: ['null'] }];
target.select = target.select || [[{ type: 'field', params: ['value'] }, { type: 'mean', params: [] }]];
this.updateProjection();
}
updateProjection() {
this.selectModels = _.map(this.target.select, (parts: any) => {
return _.map(parts, queryPart.create);
});
this.groupByParts = _.map(this.target.groupBy, queryPart.create);
}
updatePersistedParts() {
this.target.select = _.map(this.selectModels, selectParts => {
return _.map(selectParts, (part: any) => {
return { type: part.def.type, params: part.params };
});
});
}
hasGroupByTime() {
return _.find(this.target.groupBy, (g: any) => g.type === 'time');
}
hasFill() {
return _.find(this.target.groupBy, (g: any) => g.type === 'fill');
}
addGroupBy(value) {
const stringParts = value.match(/^(\w+)\((.*)\)$/);
const typePart = stringParts[1];
const arg = stringParts[2];
const partModel = queryPart.create({ type: typePart, params: [arg] });
const partCount = this.target.groupBy.length;
if (partCount === 0) {
this.target.groupBy.push(partModel.part);
} else if (typePart === 'time') {
this.target.groupBy.splice(0, 0, partModel.part);
} else if (typePart === 'tag') {
if (this.target.groupBy[partCount - 1].type === 'fill') {
this.target.groupBy.splice(partCount - 1, 0, partModel.part);
} else {
this.target.groupBy.push(partModel.part);
}
} else {
this.target.groupBy.push(partModel.part);
}
this.updateProjection();
}
removeGroupByPart(part, index) {
const categories = queryPart.getCategories();
if (part.def.type === 'time') {
// remove fill
this.target.groupBy = _.filter(this.target.groupBy, (g: any) => g.type !== 'fill');
// remove aggregations
this.target.select = _.map(this.target.select, (s: any) => {
return _.filter(s, (part: any) => {
const partModel = queryPart.create(part);
if (partModel.def.category === categories.Aggregations) {
return false;
}
if (partModel.def.category === categories.Selectors) {
return false;
}
return true;
});
});
}
this.target.groupBy.splice(index, 1);
this.updateProjection();
}
removeSelect(index: number) {
this.target.select.splice(index, 1);
this.updateProjection();
}
removeSelectPart(selectParts, part) {
// if we remove the field remove the whole statement
if (part.def.type === 'field') {
if (this.selectModels.length > 1) {
const modelsIndex = _.indexOf(this.selectModels, selectParts);
this.selectModels.splice(modelsIndex, 1);
}
} else {
const partIndex = _.indexOf(selectParts, part);
selectParts.splice(partIndex, 1);
}
this.updatePersistedParts();
}
addSelectPart(selectParts, type) {
const partModel = queryPart.create({ type: type });
partModel.def.addStrategy(selectParts, partModel, this);
this.updatePersistedParts();
}
private renderTagCondition(tag, index, interpolate) {
let str = '';
let operator = tag.operator;
let value = tag.value;
if (index > 0) {
str = (tag.condition || 'AND') + ' ';
}
if (!operator) {
if (/^\/.*\/$/.test(value)) {
operator = '=~';
} else {
operator = '=';
}
}
// quote value unless regex
if (operator !== '=~' && operator !== '!~') {
if (interpolate) {
value = this.templateSrv.replace(value, this.scopedVars);
}
if (operator !== '>' && operator !== '<') {
value = "'" + value.replace(/\\/g, '\\\\') + "'";
}
} else if (interpolate) {
value = this.templateSrv.replace(value, this.scopedVars, 'regex');
}
return str + '"' + tag.key + '" ' + operator + ' ' + value;
}
getMeasurementAndPolicy(interpolate) {
let policy = this.target.policy;
let measurement = this.target.measurement || 'measurement';
if (!measurement.match('^/.*/$')) {
measurement = '"' + measurement + '"';
} else if (interpolate) {
measurement = this.templateSrv.replace(measurement, this.scopedVars, 'regex');
}
if (policy !== 'default') {
policy = '"' + this.target.policy + '".';
} else {
policy = '';
}
return policy + measurement;
}
interpolateQueryStr(value, variable, defaultFormatFn) {
// if no multi or include all do not regexEscape
if (!variable.multi && !variable.includeAll) {
return value;
}
if (typeof value === 'string') {
return kbn.regexEscape(value);
}
const escapedValues = _.map(value, kbn.regexEscape);
return '(' + escapedValues.join('|') + ')';
}
render(interpolate?) {
const target = this.target;
if (target.rawQuery) {
if (interpolate) {
return this.templateSrv.replace(target.query, this.scopedVars, this.interpolateQueryStr);
} else {
return target.query;
}
}
let query = 'SELECT ';
let i, y;
for (i = 0; i < this.selectModels.length; i++) {
const parts = this.selectModels[i];
let selectText = '';
for (y = 0; y < parts.length; y++) {
const part = parts[y];
selectText = part.render(selectText);
}
if (i > 0) {
query += ', ';
}
query += selectText;
}
query += ' FROM ' + this.getMeasurementAndPolicy(interpolate) + ' WHERE ';
const conditions = _.map(target.tags, (tag, index) => {
return this.renderTagCondition(tag, index, interpolate);
});
if (conditions.length > 0) {
query += '(' + conditions.join(' ') + ') AND ';
}
query += '$timeFilter';
let groupBySection = '';
for (i = 0; i < this.groupByParts.length; i++) {
const part = this.groupByParts[i];
if (i > 0) {
// for some reason fill has no separator
groupBySection += part.def.type === 'fill' ? ' ' : ', ';
}
groupBySection += part.render('');
}
if (groupBySection.length) {
query += ' GROUP BY ' + groupBySection;
}
if (target.fill) {
query += ' fill(' + target.fill + ')';
}
if (target.orderByTime === 'DESC') {
query += ' ORDER BY time DESC';
}
if (target.limit) {
query += ' LIMIT ' + target.limit;
}
if (target.slimit) {
query += ' SLIMIT ' + target.slimit;
}
return query;
}
renderAdhocFilters(filters) {
const conditions = _.map(filters, (tag, index) => {
return this.renderTagCondition(tag, index, false);
});
return conditions.join(' ');
}
}
| public/app/plugins/datasource/influxdb/influx_query.ts | 0 | https://github.com/grafana/grafana/commit/487de2b832126060bb1001295765cd6dee3fdb34 | [
0.0014498988166451454,
0.0002332559524802491,
0.00016647124721203,
0.00017093258793465793,
0.00024963539908640087
] |
{
"id": 5,
"code_window": [
" <ToggleButton\n",
" className=\"btn-small\"\n",
" key={i}\n",
" value={dedupType}\n",
" onChange={onChange}\n",
" selected={selectedValue === dedupType}\n",
" >\n",
" {dedupType}\n",
" </ToggleButton>\n",
" ))\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" title={LogsDedupDescription[dedupType] || null}\n"
],
"file_path": "public/app/features/explore/Logs.tsx",
"type": "add",
"edit_start_line_idx": 447
} | [Unit]
Description=Grafana instance
Documentation=http://docs.grafana.org
Wants=network-online.target
After=network-online.target
After=postgresql.service mariadb.service mysql.service
[Service]
EnvironmentFile=/etc/sysconfig/grafana-server
User=grafana
Group=grafana
Type=notify
Restart=on-failure
WorkingDirectory=/usr/share/grafana
RuntimeDirectory=grafana
RuntimeDirectoryMode=0750
ExecStart=/usr/sbin/grafana-server \
--config=${CONF_FILE} \
--pidfile=${PID_FILE_DIR}/grafana-server.pid \
--packaging=rpm \
cfg:default.paths.logs=${LOG_DIR} \
cfg:default.paths.data=${DATA_DIR} \
cfg:default.paths.plugins=${PLUGINS_DIR} \
cfg:default.paths.provisioning=${PROVISIONING_CFG_DIR}
LimitNOFILE=10000
TimeoutStopSec=20
[Install]
WantedBy=multi-user.target
| packaging/rpm/systemd/grafana-server.service | 0 | https://github.com/grafana/grafana/commit/487de2b832126060bb1001295765cd6dee3fdb34 | [
0.0001728508505038917,
0.0001698308187769726,
0.00016680127009749413,
0.00016983557725325227,
0.0000027628091174847214
] |
{
"id": 5,
"code_window": [
" <ToggleButton\n",
" className=\"btn-small\"\n",
" key={i}\n",
" value={dedupType}\n",
" onChange={onChange}\n",
" selected={selectedValue === dedupType}\n",
" >\n",
" {dedupType}\n",
" </ToggleButton>\n",
" ))\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" title={LogsDedupDescription[dedupType] || null}\n"
],
"file_path": "public/app/features/explore/Logs.tsx",
"type": "add",
"edit_start_line_idx": 447
} | collectd:
build: docker/blocks/collectd
environment:
HOST_NAME: myserver
GRAPHITE_HOST: graphite
GRAPHITE_PORT: 2003
GRAPHITE_PREFIX: collectd.
REPORT_BY_CPU: 'false'
COLLECT_INTERVAL: 10
links:
- graphite
| devenv/docker/blocks/collectd/docker-compose.yaml | 0 | https://github.com/grafana/grafana/commit/487de2b832126060bb1001295765cd6dee3fdb34 | [
0.00017465355631429702,
0.0001710164942778647,
0.0001673794467933476,
0.0001710164942778647,
0.0000036370547604747117
] |
{
"id": 0,
"code_window": [
" font-weight: normal;\n",
" line-height: normal;\n",
" }\n",
"\n",
" p {\n",
" margin: 0 0 2px;\n",
"\n",
" font-size: 1.2rem;\n",
" line-height: normal;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" overflow: inherit;\n",
"\n"
],
"file_path": "src/components/item/item.ios.scss",
"type": "add",
"edit_start_line_idx": 64
} | @import "../../globals.wp";
@import "./item";
// Windows Item
// --------------------------------------------------
$item-wp-body-text-font-size: 1.4rem !default;
$item-wp-body-text-line-height: 1.5 !default;
$item-wp-body-background-color: $list-wp-background-color !default;
$item-wp-body-text-color: $list-wp-text-color !default;
$item-wp-paragraph-text-color: #666 !default;
$item-wp-font-size: 1.6rem !default;
$item-wp-avatar-size: 4rem !default;
$item-wp-thumbnail-size: 8rem !default;
$item-wp-note-color: $input-wp-border-color !default;
$item-wp-detail-push-show: false !default;
$item-wp-detail-push-color: $input-wp-border-color !default;
$item-wp-detail-push-svg: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 20'><path d='M2,20l-2-2l8-8L0,2l2-2l10,10L2,20z' fill='#{$item-wp-detail-push-color}'/></svg>" !default;
$item-wp-divider-background: #fff !default;
$item-wp-divider-color: #222 !default;
$item-wp-divider-padding: 5px 15px !default;
$item-wp-sliding-content-background: $list-wp-background-color !default;
.item {
position: relative;
padding-right: 0;
padding-left: ($item-wp-padding-left);
font-size: $item-wp-font-size;
font-weight: normal;
text-transform: none;
color: $item-wp-body-text-color;
background-color: $item-wp-body-background-color;
box-shadow: none;
h1 {
margin: 0 0 2px;
font-size: 2.4rem;
font-weight: normal;
}
h2 {
margin: 2px 0;
font-size: 1.6rem;
font-weight: normal;
}
h3,
h4,
h5,
h6 {
margin: 2px 0;
font-size: 1.4rem;
font-weight: normal;
line-height: normal;
}
p {
margin: 0 0 2px;
font-size: 1.4rem;
line-height: normal;
color: $item-wp-paragraph-text-color;
}
}
.item.activated {
background-color: $list-wp-activated-background-color;
}
.item[no-lines] {
border-width: 0;
}
.item .item-inner {
padding-right: ($item-wp-padding-right / 2);
border-bottom: 1px solid $list-wp-border-color;
}
// Windows Item Detail Push
// --------------------------------------------------
@mixin wp-detail-push() {
@include svg-background-image($item-wp-detail-push-svg);
padding-right: 32px;
background-repeat: no-repeat;
background-position: right ($item-wp-padding-right - 2) center;
background-size: 14px 14px;
}
// Only show the forward arrow icon if true
@if $item-wp-detail-push-show == true {
.item[detail-push] .item-inner,
button.item:not([detail-none]) .item-inner,
a.item:not([detail-none]) .item-inner {
@include wp-detail-push();
}
}
// Windows Item Media
// --------------------------------------------------
[item-left],
[item-right] {
margin: $item-wp-padding-media-top ($item-wp-padding-right / 2) $item-wp-padding-media-bottom 0;
}
ion-icon[item-left],
ion-icon[item-right] {
margin-top: $item-wp-padding-icon-top;
margin-bottom: $item-wp-padding-icon-bottom;
margin-left: 0;
}
.item-button {
padding: 0 .6em;
height: 25px;
font-size: 1.2rem;
}
.item-button.button-icon-only ion-icon,
.item-button.button-icon-only {
padding: 0 1px;
}
[text-wrap] ion-label {
font-size: $item-wp-body-text-font-size;
line-height: $item-wp-body-text-line-height;
}
ion-icon[item-left] + .item-inner,
ion-icon[item-left] + .item-input {
margin-left: ($item-wp-padding-left / 2);
}
ion-avatar[item-left],
ion-thumbnail[item-left] {
margin: ($item-wp-padding-right / 2) $item-wp-padding-right ($item-wp-padding-right / 2) 0;
}
ion-avatar[item-right],
ion-thumbnail[item-right] {
margin: ($item-wp-padding-right / 2);
}
ion-avatar {
min-width: $item-wp-avatar-size;
min-height: $item-wp-avatar-size;
img {
max-width: $item-wp-avatar-size;
max-height: $item-wp-avatar-size;
border-radius: $item-wp-avatar-size / 2;
}
}
ion-thumbnail {
min-width: $item-wp-thumbnail-size;
min-height: $item-wp-thumbnail-size;
img {
max-width: $item-wp-thumbnail-size;
max-height: $item-wp-thumbnail-size;
}
}
ion-note {
color: $item-wp-note-color;
}
// Windows Item Divider
// --------------------------------------------------
ion-item-divider {
padding-left: $item-wp-padding-left;
color: $item-wp-divider-color;
background-color: $item-wp-divider-background;
}
// Generate Windows Item Divider Colors
// --------------------------------------------------
@each $color-name, $color-base, $color-contrast in get-colors($colors-wp) {
ion-item-divider[#{$color-name}] {
color: $color-contrast;
background-color: $color-base;
}
}
// Windows Item Sliding
// --------------------------------------------------
ion-item-sliding {
background-color: $item-wp-sliding-content-background;
}
| src/components/item/item.wp.scss | 1 | https://github.com/ionic-team/ionic-framework/commit/400957517da4b368ad064740095223ceb725b7ec | [
0.9959243535995483,
0.04620298370718956,
0.00016348730423487723,
0.0001682452275417745,
0.2072548121213913
] |
{
"id": 0,
"code_window": [
" font-weight: normal;\n",
" line-height: normal;\n",
" }\n",
"\n",
" p {\n",
" margin: 0 0 2px;\n",
"\n",
" font-size: 1.2rem;\n",
" line-height: normal;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" overflow: inherit;\n",
"\n"
],
"file_path": "src/components/item/item.ios.scss",
"type": "add",
"edit_start_line_idx": 64
} | import {Component} from '@angular/core';
import {ionicBootstrap} from '../../../../../src';
@Component({
templateUrl: 'main.html'
})
class E2EPage {}
@Component({
template: '<ion-nav [root]="rootPage"></ion-nav>'
})
class E2EApp {
rootPage = E2EPage;
}
ionicBootstrap(E2EApp);
| src/components/card/test/basic/index.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/400957517da4b368ad064740095223ceb725b7ec | [
0.002339439233765006,
0.0012574007268995047,
0.00017536224913783371,
0.0012574007268995047,
0.0010820385068655014
] |
{
"id": 0,
"code_window": [
" font-weight: normal;\n",
" line-height: normal;\n",
" }\n",
"\n",
" p {\n",
" margin: 0 0 2px;\n",
"\n",
" font-size: 1.2rem;\n",
" line-height: normal;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" overflow: inherit;\n",
"\n"
],
"file_path": "src/components/item/item.ios.scss",
"type": "add",
"edit_start_line_idx": 64
} | @import "../globals.ios";
@import "./cordova";
// iOS Cordova
// --------------------------------------------------
$cordova-ios-statusbar-padding-modal-max-width: $cordova-statusbar-padding-modal-max-width !default;
ion-nav > ion-page,
ion-nav > ion-page > ion-header,
ion-tab > ion-page > ion-header,
ion-menu {
@include toolbar-statusbar-padding($toolbar-ios-height, $content-ios-padding);
@include toolbar-title-statusbar-padding($toolbar-ios-height, $content-ios-padding);
}
@media only screen and (max-width: $cordova-ios-statusbar-padding-modal-max-width) {
.modal-wrapper > ion-page > ion-header {
@include toolbar-statusbar-padding($toolbar-ios-height, $content-ios-padding);
@include toolbar-title-statusbar-padding($toolbar-ios-height, $content-ios-padding);
}
}
| src/platform/cordova.ios.scss | 0 | https://github.com/ionic-team/ionic-framework/commit/400957517da4b368ad064740095223ceb725b7ec | [
0.00017264117195736617,
0.00016949088603723794,
0.00016545118705835193,
0.00017038029909599572,
0.000003001917320943903
] |
{
"id": 0,
"code_window": [
" font-weight: normal;\n",
" line-height: normal;\n",
" }\n",
"\n",
" p {\n",
" margin: 0 0 2px;\n",
"\n",
" font-size: 1.2rem;\n",
" line-height: normal;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" overflow: inherit;\n",
"\n"
],
"file_path": "src/components/item/item.ios.scss",
"type": "add",
"edit_start_line_idx": 64
} | @import "../../globals.ios";
@import "./label";
// iOS Label
// --------------------------------------------------
$label-ios-text-color: #7f7f7f !default;
$label-ios-margin: $item-ios-padding-top ($item-ios-padding-right / 2) $item-ios-padding-bottom 0 !default;
// iOS Default Label
// --------------------------------------------------
ion-label {
margin: $label-ios-margin;
}
// iOS Default Label Inside An Input/Select Item
// --------------------------------------------------
.item-input ion-label,
.item-select ion-label,
.item-datetime ion-label {
color: $label-ios-text-color;
}
ion-label + ion-input .text-input,
ion-label + ion-textarea .text-input {
margin-left: $item-ios-padding-left;
width: calc(100% - (#{$item-ios-padding-right} / 2) - #{$item-ios-padding-left});
}
// iOS Stacked & Floating Labels
// --------------------------------------------------
ion-label[stacked] {
margin-bottom: 4px;
font-size: 1.2rem;
}
ion-label[floating] {
margin-bottom: 0;
transform: translate3d(0, 27px, 0);
transform-origin: left top;
transition: transform 150ms ease-in-out;
}
.input-has-focus ion-label[floating],
.input-has-value ion-label[floating] {
transform: translate3d(0, 0, 0) scale(.8);
}
.item-label-stacked [item-right],
.item-label-floating [item-right] {
margin-top: $item-ios-padding-media-top - 2;
margin-bottom: $item-ios-padding-media-bottom - 2;
}
// Generate iOS Label colors
// --------------------------------------------------
@each $color-name, $color-base, $color-contrast in get-colors($colors-ios) {
ion-label[#{$color-name}] {
color: $color-base;
}
}
| src/components/label/label.ios.scss | 0 | https://github.com/ionic-team/ionic-framework/commit/400957517da4b368ad064740095223ceb725b7ec | [
0.00019886603695340455,
0.00017151857900898904,
0.00016502232756465673,
0.00016743400192353874,
0.000010617317457217723
] |
{
"id": 1,
"code_window": [
"\n",
" font-size: 1.2rem;\n",
" line-height: normal;\n",
" color: $item-ios-paragraph-text-color;\n",
" }\n",
"\n",
" h2:last-child,\n",
" h3:last-child,\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" text-overflow: inherit;\n"
],
"file_path": "src/components/item/item.ios.scss",
"type": "add",
"edit_start_line_idx": 68
} | @import "../../globals.wp";
@import "./item";
// Windows Item
// --------------------------------------------------
$item-wp-body-text-font-size: 1.4rem !default;
$item-wp-body-text-line-height: 1.5 !default;
$item-wp-body-background-color: $list-wp-background-color !default;
$item-wp-body-text-color: $list-wp-text-color !default;
$item-wp-paragraph-text-color: #666 !default;
$item-wp-font-size: 1.6rem !default;
$item-wp-avatar-size: 4rem !default;
$item-wp-thumbnail-size: 8rem !default;
$item-wp-note-color: $input-wp-border-color !default;
$item-wp-detail-push-show: false !default;
$item-wp-detail-push-color: $input-wp-border-color !default;
$item-wp-detail-push-svg: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 20'><path d='M2,20l-2-2l8-8L0,2l2-2l10,10L2,20z' fill='#{$item-wp-detail-push-color}'/></svg>" !default;
$item-wp-divider-background: #fff !default;
$item-wp-divider-color: #222 !default;
$item-wp-divider-padding: 5px 15px !default;
$item-wp-sliding-content-background: $list-wp-background-color !default;
.item {
position: relative;
padding-right: 0;
padding-left: ($item-wp-padding-left);
font-size: $item-wp-font-size;
font-weight: normal;
text-transform: none;
color: $item-wp-body-text-color;
background-color: $item-wp-body-background-color;
box-shadow: none;
h1 {
margin: 0 0 2px;
font-size: 2.4rem;
font-weight: normal;
}
h2 {
margin: 2px 0;
font-size: 1.6rem;
font-weight: normal;
}
h3,
h4,
h5,
h6 {
margin: 2px 0;
font-size: 1.4rem;
font-weight: normal;
line-height: normal;
}
p {
margin: 0 0 2px;
font-size: 1.4rem;
line-height: normal;
color: $item-wp-paragraph-text-color;
}
}
.item.activated {
background-color: $list-wp-activated-background-color;
}
.item[no-lines] {
border-width: 0;
}
.item .item-inner {
padding-right: ($item-wp-padding-right / 2);
border-bottom: 1px solid $list-wp-border-color;
}
// Windows Item Detail Push
// --------------------------------------------------
@mixin wp-detail-push() {
@include svg-background-image($item-wp-detail-push-svg);
padding-right: 32px;
background-repeat: no-repeat;
background-position: right ($item-wp-padding-right - 2) center;
background-size: 14px 14px;
}
// Only show the forward arrow icon if true
@if $item-wp-detail-push-show == true {
.item[detail-push] .item-inner,
button.item:not([detail-none]) .item-inner,
a.item:not([detail-none]) .item-inner {
@include wp-detail-push();
}
}
// Windows Item Media
// --------------------------------------------------
[item-left],
[item-right] {
margin: $item-wp-padding-media-top ($item-wp-padding-right / 2) $item-wp-padding-media-bottom 0;
}
ion-icon[item-left],
ion-icon[item-right] {
margin-top: $item-wp-padding-icon-top;
margin-bottom: $item-wp-padding-icon-bottom;
margin-left: 0;
}
.item-button {
padding: 0 .6em;
height: 25px;
font-size: 1.2rem;
}
.item-button.button-icon-only ion-icon,
.item-button.button-icon-only {
padding: 0 1px;
}
[text-wrap] ion-label {
font-size: $item-wp-body-text-font-size;
line-height: $item-wp-body-text-line-height;
}
ion-icon[item-left] + .item-inner,
ion-icon[item-left] + .item-input {
margin-left: ($item-wp-padding-left / 2);
}
ion-avatar[item-left],
ion-thumbnail[item-left] {
margin: ($item-wp-padding-right / 2) $item-wp-padding-right ($item-wp-padding-right / 2) 0;
}
ion-avatar[item-right],
ion-thumbnail[item-right] {
margin: ($item-wp-padding-right / 2);
}
ion-avatar {
min-width: $item-wp-avatar-size;
min-height: $item-wp-avatar-size;
img {
max-width: $item-wp-avatar-size;
max-height: $item-wp-avatar-size;
border-radius: $item-wp-avatar-size / 2;
}
}
ion-thumbnail {
min-width: $item-wp-thumbnail-size;
min-height: $item-wp-thumbnail-size;
img {
max-width: $item-wp-thumbnail-size;
max-height: $item-wp-thumbnail-size;
}
}
ion-note {
color: $item-wp-note-color;
}
// Windows Item Divider
// --------------------------------------------------
ion-item-divider {
padding-left: $item-wp-padding-left;
color: $item-wp-divider-color;
background-color: $item-wp-divider-background;
}
// Generate Windows Item Divider Colors
// --------------------------------------------------
@each $color-name, $color-base, $color-contrast in get-colors($colors-wp) {
ion-item-divider[#{$color-name}] {
color: $color-contrast;
background-color: $color-base;
}
}
// Windows Item Sliding
// --------------------------------------------------
ion-item-sliding {
background-color: $item-wp-sliding-content-background;
}
| src/components/item/item.wp.scss | 1 | https://github.com/ionic-team/ionic-framework/commit/400957517da4b368ad064740095223ceb725b7ec | [
0.01710531674325466,
0.0017491038888692856,
0.00016392514226026833,
0.00016994430916383862,
0.0037184380926191807
] |
{
"id": 1,
"code_window": [
"\n",
" font-size: 1.2rem;\n",
" line-height: normal;\n",
" color: $item-ios-paragraph-text-color;\n",
" }\n",
"\n",
" h2:last-child,\n",
" h3:last-child,\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" text-overflow: inherit;\n"
],
"file_path": "src/components/item/item.ios.scss",
"type": "add",
"edit_start_line_idx": 68
} | @import "../../globals.core";
// Menu
// --------------------------------------------------
$menu-width: 304px !default;
$menu-small-width: $menu-width - 40px !default;
ion-menu {
position: absolute;
top: 0;
right: auto;
bottom: 0;
left: 0;
display: flex;
flex-direction: column;
width: $menu-width;
transform: translate3d(-9999px, 0, 0);
}
ion-menu[side=right] {
right: 0;
left: auto;
}
ion-menu ion-backdrop {
z-index: -1;
display: none;
}
.menu-content {
transform: translate3d(0, 0, 0);
}
.menu-content-open ion-pane,
.menu-content-open ion-content,
.menu-content-open .toolbar {
// the containing element itself should be clickable but
// everything inside of it should not clickable when menu is open
pointer-events: none;
}
@media (max-width: 340px) {
ion-menu {
width: $menu-small-width;
}
}
// Menu Reveal
// --------------------------------------------------
// The content slides over to reveal the menu underneath.
// The menu itself, which is under the content, does not move.
ion-menu[type=reveal].show-menu {
transform: translate3d(0, 0, 0);
}
// Menu Overlay
// --------------------------------------------------
// The menu slides over the content. The content
// itself, which is under the menu, does not move.
ion-menu[type=overlay] {
z-index: $z-index-menu-overlay;
ion-backdrop {
left: -3000px;
display: block;
width: 6000px;
opacity: .01;
transform: translate3d(-9999px, 0, 0);
&.show-backdrop {
transform: translate3d(0, 0, 0);
}
}
}
| src/components/menu/menu.scss | 0 | https://github.com/ionic-team/ionic-framework/commit/400957517da4b368ad064740095223ceb725b7ec | [
0.00017702984041534364,
0.00017104054859373719,
0.000165629229741171,
0.00017042904801201075,
0.0000033348444503644714
] |
{
"id": 1,
"code_window": [
"\n",
" font-size: 1.2rem;\n",
" line-height: normal;\n",
" color: $item-ios-paragraph-text-color;\n",
" }\n",
"\n",
" h2:last-child,\n",
" h3:last-child,\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" text-overflow: inherit;\n"
],
"file_path": "src/components/item/item.ios.scss",
"type": "add",
"edit_start_line_idx": 68
} | import { Directive, HostListener, Input } from '@angular/core';
import { MenuController } from './menu-controller';
/**
* @name MenuClose
* @description
* The `menuClose` directive can be placed on any button to close an open menu.
*
* @usage
*
* A simple `menuClose` button can be added using the following markup:
*
* ```html
* <button menuClose>Close Menu</button>
* ```
*
* To close a certain menu by its id or side, give the `menuClose`
* directive a value.
*
* ```html
* <button menuClose="left">Close Left Menu</button>
* ```
*
* @demo /docs/v2/demos/menu/
* @see {@link /docs/v2/components#menus Menu Component Docs}
* @see {@link ../../menu/Menu Menu API Docs}
*/
@Directive({
selector: '[menuClose]'
})
export class MenuClose {
/**
* @private
*/
@Input() menuClose: string;
constructor(private _menu: MenuController) {}
/**
* @private
*/
@HostListener('click')
close() {
let menu = this._menu.get(this.menuClose);
menu && menu.close();
}
}
| src/components/menu/menu-close.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/400957517da4b368ad064740095223ceb725b7ec | [
0.00017932265473064035,
0.00017240201123058796,
0.00016753336240071803,
0.00017263134941458702,
0.000003945410298911156
] |
{
"id": 1,
"code_window": [
"\n",
" font-size: 1.2rem;\n",
" line-height: normal;\n",
" color: $item-ios-paragraph-text-color;\n",
" }\n",
"\n",
" h2:last-child,\n",
" h3:last-child,\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" text-overflow: inherit;\n"
],
"file_path": "src/components/item/item.ios.scss",
"type": "add",
"edit_start_line_idx": 68
} | <ion-header>
<ion-navbar>
<ion-title>Item Groups</ion-title>
<ion-buttons end>
<button (click)="reload()">Reload</button>
</ion-buttons>
</ion-navbar>
</ion-header>
<ion-content class="outer-content">
<ion-list>
<ion-item-group *ngFor="let timeSlot of data">
<ion-item-divider sticky>
{{timeSlot.time}}
</ion-item-divider>
<ion-item-sliding *ngFor="let session of timeSlot.talks" [attr.category]="session.category" #slidingItem>
<button ion-item (click)="openSession(session)">
<h3>{{session.name}}</h3>
<p>
<span>{{session.timestart}}</span>
—
<span>{{session.timeend}}</span>
:
<span>{{session.location}}</span>
</p>
</button>
<ion-item-options>
<button (click)="addFavorite(timeSlot, session, slidingItem)">Add to<br>Favorites</button>
</ion-item-options>
</ion-item-sliding>
</ion-item-group>
</ion-list>
</ion-content>
| src/components/item/test/groups/session-list.html | 0 | https://github.com/ionic-team/ionic-framework/commit/400957517da4b368ad064740095223ceb725b7ec | [
0.00017971637134905905,
0.00017199847206939012,
0.00016672429046593606,
0.00017281953478232026,
0.00000460640512756072
] |
{
"id": 2,
"code_window": [
" }\n",
"\n",
" p {\n",
" margin: 0 0 2px;\n",
"\n",
" font-size: 1.4rem;\n",
" line-height: normal;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" overflow: inherit;\n",
"\n"
],
"file_path": "src/components/item/item.md.scss",
"type": "add",
"edit_start_line_idx": 67
} | @import "../../globals.wp";
@import "./item";
// Windows Item
// --------------------------------------------------
$item-wp-body-text-font-size: 1.4rem !default;
$item-wp-body-text-line-height: 1.5 !default;
$item-wp-body-background-color: $list-wp-background-color !default;
$item-wp-body-text-color: $list-wp-text-color !default;
$item-wp-paragraph-text-color: #666 !default;
$item-wp-font-size: 1.6rem !default;
$item-wp-avatar-size: 4rem !default;
$item-wp-thumbnail-size: 8rem !default;
$item-wp-note-color: $input-wp-border-color !default;
$item-wp-detail-push-show: false !default;
$item-wp-detail-push-color: $input-wp-border-color !default;
$item-wp-detail-push-svg: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 20'><path d='M2,20l-2-2l8-8L0,2l2-2l10,10L2,20z' fill='#{$item-wp-detail-push-color}'/></svg>" !default;
$item-wp-divider-background: #fff !default;
$item-wp-divider-color: #222 !default;
$item-wp-divider-padding: 5px 15px !default;
$item-wp-sliding-content-background: $list-wp-background-color !default;
.item {
position: relative;
padding-right: 0;
padding-left: ($item-wp-padding-left);
font-size: $item-wp-font-size;
font-weight: normal;
text-transform: none;
color: $item-wp-body-text-color;
background-color: $item-wp-body-background-color;
box-shadow: none;
h1 {
margin: 0 0 2px;
font-size: 2.4rem;
font-weight: normal;
}
h2 {
margin: 2px 0;
font-size: 1.6rem;
font-weight: normal;
}
h3,
h4,
h5,
h6 {
margin: 2px 0;
font-size: 1.4rem;
font-weight: normal;
line-height: normal;
}
p {
margin: 0 0 2px;
font-size: 1.4rem;
line-height: normal;
color: $item-wp-paragraph-text-color;
}
}
.item.activated {
background-color: $list-wp-activated-background-color;
}
.item[no-lines] {
border-width: 0;
}
.item .item-inner {
padding-right: ($item-wp-padding-right / 2);
border-bottom: 1px solid $list-wp-border-color;
}
// Windows Item Detail Push
// --------------------------------------------------
@mixin wp-detail-push() {
@include svg-background-image($item-wp-detail-push-svg);
padding-right: 32px;
background-repeat: no-repeat;
background-position: right ($item-wp-padding-right - 2) center;
background-size: 14px 14px;
}
// Only show the forward arrow icon if true
@if $item-wp-detail-push-show == true {
.item[detail-push] .item-inner,
button.item:not([detail-none]) .item-inner,
a.item:not([detail-none]) .item-inner {
@include wp-detail-push();
}
}
// Windows Item Media
// --------------------------------------------------
[item-left],
[item-right] {
margin: $item-wp-padding-media-top ($item-wp-padding-right / 2) $item-wp-padding-media-bottom 0;
}
ion-icon[item-left],
ion-icon[item-right] {
margin-top: $item-wp-padding-icon-top;
margin-bottom: $item-wp-padding-icon-bottom;
margin-left: 0;
}
.item-button {
padding: 0 .6em;
height: 25px;
font-size: 1.2rem;
}
.item-button.button-icon-only ion-icon,
.item-button.button-icon-only {
padding: 0 1px;
}
[text-wrap] ion-label {
font-size: $item-wp-body-text-font-size;
line-height: $item-wp-body-text-line-height;
}
ion-icon[item-left] + .item-inner,
ion-icon[item-left] + .item-input {
margin-left: ($item-wp-padding-left / 2);
}
ion-avatar[item-left],
ion-thumbnail[item-left] {
margin: ($item-wp-padding-right / 2) $item-wp-padding-right ($item-wp-padding-right / 2) 0;
}
ion-avatar[item-right],
ion-thumbnail[item-right] {
margin: ($item-wp-padding-right / 2);
}
ion-avatar {
min-width: $item-wp-avatar-size;
min-height: $item-wp-avatar-size;
img {
max-width: $item-wp-avatar-size;
max-height: $item-wp-avatar-size;
border-radius: $item-wp-avatar-size / 2;
}
}
ion-thumbnail {
min-width: $item-wp-thumbnail-size;
min-height: $item-wp-thumbnail-size;
img {
max-width: $item-wp-thumbnail-size;
max-height: $item-wp-thumbnail-size;
}
}
ion-note {
color: $item-wp-note-color;
}
// Windows Item Divider
// --------------------------------------------------
ion-item-divider {
padding-left: $item-wp-padding-left;
color: $item-wp-divider-color;
background-color: $item-wp-divider-background;
}
// Generate Windows Item Divider Colors
// --------------------------------------------------
@each $color-name, $color-base, $color-contrast in get-colors($colors-wp) {
ion-item-divider[#{$color-name}] {
color: $color-contrast;
background-color: $color-base;
}
}
// Windows Item Sliding
// --------------------------------------------------
ion-item-sliding {
background-color: $item-wp-sliding-content-background;
}
| src/components/item/item.wp.scss | 1 | https://github.com/ionic-team/ionic-framework/commit/400957517da4b368ad064740095223ceb725b7ec | [
0.9953060746192932,
0.04561362415552139,
0.00016583087563049048,
0.00020177742408122867,
0.2072402983903885
] |
{
"id": 2,
"code_window": [
" }\n",
"\n",
" p {\n",
" margin: 0 0 2px;\n",
"\n",
" font-size: 1.4rem;\n",
" line-height: normal;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" overflow: inherit;\n",
"\n"
],
"file_path": "src/components/item/item.md.scss",
"type": "add",
"edit_start_line_idx": 67
} |
it('should unify buttons', function() {
element(by.css('.e2eButtonDynamicUnify')).click();
});
| src/components/button/test/dynamic/e2e.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/400957517da4b368ad064740095223ceb725b7ec | [
0.0001663387520238757,
0.0001663387520238757,
0.0001663387520238757,
0.0001663387520238757,
0
] |
{
"id": 2,
"code_window": [
" }\n",
"\n",
" p {\n",
" margin: 0 0 2px;\n",
"\n",
" font-size: 1.4rem;\n",
" line-height: normal;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" overflow: inherit;\n",
"\n"
],
"file_path": "src/components/item/item.md.scss",
"type": "add",
"edit_start_line_idx": 67
} | import {Component, ViewChild, ElementRef} from '@angular/core';
import {ionicBootstrap, Platform} from '../../../../../src';
@Component({
templateUrl: 'main.html'
})
class E2EPage {
items: any[] = [];
webview: string;
@ViewChild('content') content: ElementRef;
constructor(platform: Platform) {
for (var i = 0; i < 200; i++) {
this.items.push({
value: i,
someMethod: function() {
return '!!';
}
});
}
if (platform.is('ios')) {
if (window.indexedDB) {
this.webview = ': WKWebView';
} else {
this.webview = ': UIWebView';
}
}
}
headerFn(record: any, index: number, records: any[]) {
if (index % 4 === 0) {
return index + ' is divisible by 4';
}
return null;
}
reload() {
window.location.reload(true);
}
}
@Component({
template: '<ion-nav [root]="root"></ion-nav>'
})
class E2EApp {
root = E2EPage;
}
ionicBootstrap(E2EApp, null, {
prodMode: true
});
| src/components/virtual-scroll/test/basic/index.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/400957517da4b368ad064740095223ceb725b7ec | [
0.0003430150100030005,
0.00020124165166635066,
0.00016452913405373693,
0.00016951316501945257,
0.0000641787119093351
] |
{
"id": 2,
"code_window": [
" }\n",
"\n",
" p {\n",
" margin: 0 0 2px;\n",
"\n",
" font-size: 1.4rem;\n",
" line-height: normal;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" overflow: inherit;\n",
"\n"
],
"file_path": "src/components/item/item.md.scss",
"type": "add",
"edit_start_line_idx": 67
} | import * as domUtil from './util/dom';
export const dom = domUtil;
export * from './util/util';
export * from './util/datetime-util';
| src/util.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/400957517da4b368ad064740095223ceb725b7ec | [
0.00017578143160790205,
0.00017578143160790205,
0.00017578143160790205,
0.00017578143160790205,
0
] |
{
"id": 3,
"code_window": [
"\n",
" font-size: 1.4rem;\n",
" line-height: normal;\n",
" color: $item-md-paragraph-text-color;\n",
" }\n",
"}\n",
"\n",
".item.activated {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" text-overflow: inherit;\n"
],
"file_path": "src/components/item/item.md.scss",
"type": "add",
"edit_start_line_idx": 71
} | @import "../../globals.ios";
@import "./item";
// iOS Item
// --------------------------------------------------
$item-ios-body-text-font-size: 1.6rem !default;
$item-ios-paragraph-text-color: #666 !default;
$item-ios-avatar-size: 3.6rem !default;
$item-ios-thumbnail-size: 5.6rem !default;
$item-ios-note-color: darken($list-ios-border-color, 10%) !default;
$item-ios-detail-push-show: true !default;
$item-ios-detail-push-color: $list-ios-border-color !default;
$item-ios-detail-push-svg: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 20'><path d='M2,20l-2-2l8-8L0,2l2-2l10,10L2,20z' fill='#{$item-ios-detail-push-color}'/></svg>" !default;
$item-ios-divider-background: #f7f7f7 !default;
$item-ios-divider-color: #222 !default;
$item-ios-divider-padding: 5px 15px !default;
$item-ios-sliding-content-background: $list-ios-background-color !default;
// iOS Item
// --------------------------------------------------
.item {
position: relative;
padding-left: $item-ios-padding-left;
border-radius: 0;
font-size: $item-ios-body-text-font-size;
color: $list-ios-text-color;
background-color: $list-ios-background-color;
transition-duration: 200ms;
h1 {
margin: 0 0 2px;
font-size: 2.4rem;
font-weight: normal;
}
h2 {
margin: 0 0 2px;
font-size: 1.6rem;
font-weight: normal;
}
h3,
h4,
h5,
h6 {
margin: 0 0 3px;
font-size: 1.4rem;
font-weight: normal;
line-height: normal;
}
p {
margin: 0 0 2px;
font-size: 1.2rem;
line-height: normal;
color: $item-ios-paragraph-text-color;
}
h2:last-child,
h3:last-child,
h4:last-child,
h5:last-child,
h6:last-child,
p:last-child {
margin-bottom: 0;
}
a {
text-decoration: none;
}
}
.item.activated {
background-color: $list-ios-activated-background-color;
transition-duration: 0ms;
}
.item .item-inner {
padding-right: ($item-ios-padding-right / 2);
border-bottom: 1px solid $list-ios-border-color;
}
&.hairlines .item-inner {
border-bottom-width: $hairlines-width;
}
// iOS Item Media
// --------------------------------------------------
[item-left] {
margin: $item-ios-padding-media-top $item-ios-padding-left $item-ios-padding-media-bottom 0;
}
[item-right] {
margin: $item-ios-padding-media-top ($item-ios-padding-left / 2) $item-ios-padding-media-bottom ($item-ios-padding-right / 2);
}
ion-icon[item-left],
ion-icon[item-right] {
margin-top: $item-ios-padding-icon-top;
margin-bottom: $item-ios-padding-icon-bottom;
margin-left: 0;
}
ion-avatar[item-left],
ion-thumbnail[item-left] {
margin: ($item-ios-padding-right / 2) $item-ios-padding-right ($item-ios-padding-right / 2) 0;
}
ion-avatar[item-right],
ion-thumbnail[item-right] {
margin: ($item-ios-padding-right / 2);
}
.item-button {
padding: 0 .5em;
height: 24px;
font-size: 1.3rem;
}
.item-button.button-icon-only ion-icon,
.item-button.button-icon-only {
padding: 0 1px;
}
ion-avatar {
min-width: $item-ios-avatar-size;
min-height: $item-ios-avatar-size;
img {
max-width: $item-ios-avatar-size;
max-height: $item-ios-avatar-size;
border-radius: $item-ios-avatar-size / 2;
}
}
ion-thumbnail {
min-width: $item-ios-thumbnail-size;
min-height: $item-ios-thumbnail-size;
img {
max-width: $item-ios-thumbnail-size;
max-height: $item-ios-thumbnail-size;
}
}
ion-note {
color: $item-ios-note-color;
}
// iOS Item Detail Push
// --------------------------------------------------
@mixin ios-detail-push() {
@include svg-background-image($item-ios-detail-push-svg);
padding-right: 32px;
background-repeat: no-repeat;
background-position: right ($item-ios-padding-right - 2) center;
background-size: 14px 14px;
}
// Only show the forward arrow icon if true
@if $item-ios-detail-push-show == true {
.item[detail-push] .item-inner,
button.item:not([detail-none]) .item-inner,
a.item:not([detail-none]) .item-inner {
@include ios-detail-push();
}
}
// iOS Item Group
// --------------------------------------------------
ion-item-group {
.item:first-child {
.item-inner {
border-top-width: 0;
}
}
.item:last-child .item-inner,
.item-wrapper:last-child .item-inner {
border: 0;
}
}
// iOS Item Divider
// --------------------------------------------------
ion-item-divider {
padding-left: $item-ios-padding-left;
color: $item-ios-divider-color;
background-color: $item-ios-divider-background;
}
// Generate iOS Item Divider Colors
// --------------------------------------------------
@each $color-name, $color-base, $color-contrast in get-colors($colors-ios) {
ion-item-divider[#{$color-name}] {
color: $color-contrast;
background-color: $color-base;
}
}
// iOS Item Sliding
// --------------------------------------------------
ion-item-sliding {
background-color: $item-ios-sliding-content-background;
}
// iOS item right-to-left
// --------------------------------------------------
@if $include-rtl {
@at-root {
.rtl.ios {
// todo
}
}
}
| src/components/item/item.ios.scss | 1 | https://github.com/ionic-team/ionic-framework/commit/400957517da4b368ad064740095223ceb725b7ec | [
0.016959335654973984,
0.001253611291758716,
0.00016328149649780244,
0.0001702841545920819,
0.0034694201312959194
] |
{
"id": 3,
"code_window": [
"\n",
" font-size: 1.4rem;\n",
" line-height: normal;\n",
" color: $item-md-paragraph-text-color;\n",
" }\n",
"}\n",
"\n",
".item.activated {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" text-overflow: inherit;\n"
],
"file_path": "src/components/item/item.md.scss",
"type": "add",
"edit_start_line_idx": 71
} | // Ionic: iOS
@charset "UTF-8";
// Core Components
@import "components.core";
// iOS Components
@import "components.ios";
// iOS Body
body {
@include ios-body();
}
| src/ionic.ios.scss | 0 | https://github.com/ionic-team/ionic-framework/commit/400957517da4b368ad064740095223ceb725b7ec | [
0.0001710440992610529,
0.00017079248209483922,
0.00017054087948054075,
0.00017079248209483922,
2.5160989025607705e-7
] |
{
"id": 3,
"code_window": [
"\n",
" font-size: 1.4rem;\n",
" line-height: normal;\n",
" color: $item-md-paragraph-text-color;\n",
" }\n",
"}\n",
"\n",
".item.activated {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" text-overflow: inherit;\n"
],
"file_path": "src/components/item/item.md.scss",
"type": "add",
"edit_start_line_idx": 71
} | .text-to-change div {
margin: 10px auto;
}
ion-row,
ion-col {
padding: 0;
}
.text-button {
padding-left: 0;
text-align: center;
min-height: 20px;
line-height: 18px;
}
.text-button .item-inner {
padding-right: 0;
}
.text-smaller {
font-size: 12px;
}
.ios .text-smaller {
border-right: 1px solid #c8c7cc;
}
.md .text-smaller {
border-right: 1px solid #dedede;
}
.text-larger {
font-size: 16px;
}
.row-dots {
text-align: center;
}
.ios .row-dots {
border-bottom: 1px solid #c8c7cc;
}
.md .row-dots {
border-bottom: 1px solid #dedede;
}
.ios .dot {
border: 1px solid #c8c7cc;
}
.md .dot {
border: 1px solid #dedede;
}
.wp .dot {
border: 2px solid #ccc;
}
.hairlines .text-smaller,
.hairlines .row-dots,
.hairlines .dot {
border-width: 0.55px;
}
.row-dots .dot {
height: 30px;
width: 30px;
border-radius: 50%;
margin: 10px auto;
position: relative;
}
.dot-white {
background-color: rgb(255,255,255);
}
.dot-tan {
background-color: rgb(249,241,228);
}
.dot-grey {
background-color: rgb(76,75,80);
}
.dot-black {
background-color: rgb(0,0,0);
}
.dot.selected {
border-width: 2px;
border-color: #327eff;
}
.text-athelas {
font-family: "Athelas";
}
.text-charter {
font-family: "Charter";
}
.text-iowan {
font-family: "Iowan";
}
.text-palatino {
font-family: "Palatino";
}
.text-san-francisco {
font-family: "San Francisco";
}
.text-seravek {
font-family: "Seravek";
}
.text-times-new-roman {
font-family: "Times New Roman";
}
| demos/popover/style.css | 0 | https://github.com/ionic-team/ionic-framework/commit/400957517da4b368ad064740095223ceb725b7ec | [
0.00017215624393429607,
0.0001684692397248,
0.00016601898823864758,
0.00016780706937424839,
0.000002064088221231941
] |
{
"id": 3,
"code_window": [
"\n",
" font-size: 1.4rem;\n",
" line-height: normal;\n",
" color: $item-md-paragraph-text-color;\n",
" }\n",
"}\n",
"\n",
".item.activated {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" text-overflow: inherit;\n"
],
"file_path": "src/components/item/item.md.scss",
"type": "add",
"edit_start_line_idx": 71
} | import { AfterViewInit, Component, ComponentResolver, ElementRef, Input, Optional, NgZone, Renderer, ViewChild, ViewContainerRef, ViewEncapsulation } from '@angular/core';
import { App } from '../app/app';
import { Config } from '../../config/config';
import { Keyboard } from '../../util/keyboard';
import { isTrueProperty } from '../../util/util';
import { NavController } from './nav-controller';
import { NavPortal } from './nav-portal';
import { ViewController } from './view-controller';
/**
* @name Nav
* @description
* _For a quick walkthrough of navigation in Ionic, check out the
* [Navigation section](../../../../components/#navigation) of the Component
* docs._
*
* Nav is a basic navigation controller component. As a subclass of NavController
* you use it to navigate to pages in your app and manipulate the navigation stack.
* Nav automatically animates transitions between pages for you.
*
* For more information on using navigation controllers like Nav or [Tab](../../Tabs/Tab/),
* take a look at the [NavController API Docs](../NavController/).
*
* You must set a root page to be loaded initially by any Nav you create, using
* the 'root' property:
*
* @usage
* ```ts
* import {Component} from '@angular/core';
* import {ionicBootstrap} from 'ionic-angular';
* import {GettingStartedPage} from './getting-started';
*
* @Component({
* template: `<ion-nav [root]="root"></ion-nav>`
* })
* class MyApp {
* root = GettingStartedPage;
* }
*
* ionicBootstrap(MyApp);
* ```
*
* ### Back Navigation
*
* If a [page](../NavController/#creating_pages) you navigate to has a [NavBar](../NavBar/),
* Nav will automatically add a back button to it if there is a page
* before the one you are navigating to in the navigation stack.
*
* Additionally, specifying the `swipeBackEnabled` property will allow you to
* swipe to go back:
* ```html
* <ion-nav swipeBackEnabled="false" [root]="rootPage"></ion-nav>
* ```
*
* Here is a diagram of how Nav animates smoothly between pages:
*
* <div class="highlight less-margin">
* <pre>
* +-------+
* | App |
* +---+---+
* <ion-app>
* |
* +------------+-------------+
* | Ionic Nav Controller |
* +------------+-------------+
* <ion-nav>
* |
* |
* Page 3 +--------------------+ LoginPage
* Page 2 +--------------------+ |
* Page 1 +--------------------+ | | +--------------------+
* | | Header |<-----------------| Login |
* +--------------------+ | | +--------------------+
* | | | | | | | Username: |
* | | | | | | | Password: |
* | | | Page 3 is | | | | |
* | | | only content | | | | |
* | | | |<-----------------| |
* | | | | | | | |
* | | | | | | | |
* | +------------------|-+ | | |
* | | Footer |-|-+ | |
* | +------------------|-+ | |
* +--------------------+ +--------------------+
*
* +--------------------+ +--------------------+ +--------------------+
* | Header | | Content | | Content |
* +--------------------+ | | | |
* | Content | | | | |
* | | | | | |
* | | | | | |
* | | | | | |
* | | | | | |
* | | | | | |
* | | | | | |
* | | | | | |
* | | +--------------------+ | |
* | | | Footer | | |
* +--------------------+ +--------------------+ +--------------------+
*
* </pre>
* </div>
*
* @demo /docs/v2/demos/navigation/
* @see {@link /docs/v2/components#navigation Navigation Component Docs}
*/
@Component({
selector: 'ion-nav',
template: '<div #viewport nav-viewport></div><div class="nav-decor"></div><div nav-portal></div>',
directives: [NavPortal],
encapsulation: ViewEncapsulation.None,
})
export class Nav extends NavController implements AfterViewInit {
private _root: any;
private _hasInit: boolean = false;
constructor(
@Optional() viewCtrl: ViewController,
@Optional() parent: NavController,
app: App,
config: Config,
keyboard: Keyboard,
elementRef: ElementRef,
zone: NgZone,
renderer: Renderer,
compiler: ComponentResolver
) {
super(parent, app, config, keyboard, elementRef, zone, renderer, compiler);
if (viewCtrl) {
// an ion-nav can also act as an ion-page within a parent ion-nav
// this would happen when an ion-nav nests a child ion-nav.
viewCtrl.setContent(this);
viewCtrl.setContentRef(elementRef);
}
if (parent) {
// this Nav has a parent Nav
parent.registerChildNav(this);
} else if (app) {
// this is the root navcontroller for the entire app
this._app.setRootNav(this);
}
}
/**
* @private
*/
@ViewChild('viewport', {read: ViewContainerRef})
set _vp(val: ViewContainerRef) {
this.setViewport(val);
}
/**
* @private
*/
ngAfterViewInit() {
this._hasInit = true;
if (this._root) {
if (typeof this._root !== 'function') {
throw 'The [root] property in <ion-nav> must be given a reference to a component class from within the constructor.';
}
this.push(this._root);
}
}
/**
* @input {Page} The Page component to load as the root page within this nav.
*/
@Input()
get root(): any {
return this._root;
}
set root(page: any) {
this._root = page;
if (this._hasInit) {
this.setRoot(page);
}
}
/**
* @input {boolean} Whether it's possible to swipe-to-go-back on this nav controller or not.
*/
@Input()
get swipeBackEnabled(): boolean {
return this._sbEnabled;
}
set swipeBackEnabled(val: boolean) {
this._sbEnabled = isTrueProperty(val);
}
@ViewChild(NavPortal)
private set _np(val: NavPortal) {
this.setPortal(val);
}
}
| src/components/nav/nav.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/400957517da4b368ad064740095223ceb725b7ec | [
0.00018908335187006742,
0.00016978057101368904,
0.00016273563960567117,
0.00016866496298462152,
0.000005198922735871747
] |
{
"id": 4,
"code_window": [
" line-height: normal;\n",
" }\n",
"\n",
" p {\n",
" margin: 0 0 2px;\n",
"\n",
" font-size: 1.4rem;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" overflow: inherit;\n",
"\n"
],
"file_path": "src/components/item/item.wp.scss",
"type": "add",
"edit_start_line_idx": 68
} | @import "../../globals.wp";
@import "./item";
// Windows Item
// --------------------------------------------------
$item-wp-body-text-font-size: 1.4rem !default;
$item-wp-body-text-line-height: 1.5 !default;
$item-wp-body-background-color: $list-wp-background-color !default;
$item-wp-body-text-color: $list-wp-text-color !default;
$item-wp-paragraph-text-color: #666 !default;
$item-wp-font-size: 1.6rem !default;
$item-wp-avatar-size: 4rem !default;
$item-wp-thumbnail-size: 8rem !default;
$item-wp-note-color: $input-wp-border-color !default;
$item-wp-detail-push-show: false !default;
$item-wp-detail-push-color: $input-wp-border-color !default;
$item-wp-detail-push-svg: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 20'><path d='M2,20l-2-2l8-8L0,2l2-2l10,10L2,20z' fill='#{$item-wp-detail-push-color}'/></svg>" !default;
$item-wp-divider-background: #fff !default;
$item-wp-divider-color: #222 !default;
$item-wp-divider-padding: 5px 15px !default;
$item-wp-sliding-content-background: $list-wp-background-color !default;
.item {
position: relative;
padding-right: 0;
padding-left: ($item-wp-padding-left);
font-size: $item-wp-font-size;
font-weight: normal;
text-transform: none;
color: $item-wp-body-text-color;
background-color: $item-wp-body-background-color;
box-shadow: none;
h1 {
margin: 0 0 2px;
font-size: 2.4rem;
font-weight: normal;
}
h2 {
margin: 2px 0;
font-size: 1.6rem;
font-weight: normal;
}
h3,
h4,
h5,
h6 {
margin: 2px 0;
font-size: 1.4rem;
font-weight: normal;
line-height: normal;
}
p {
margin: 0 0 2px;
font-size: 1.4rem;
line-height: normal;
color: $item-wp-paragraph-text-color;
}
}
.item.activated {
background-color: $list-wp-activated-background-color;
}
.item[no-lines] {
border-width: 0;
}
.item .item-inner {
padding-right: ($item-wp-padding-right / 2);
border-bottom: 1px solid $list-wp-border-color;
}
// Windows Item Detail Push
// --------------------------------------------------
@mixin wp-detail-push() {
@include svg-background-image($item-wp-detail-push-svg);
padding-right: 32px;
background-repeat: no-repeat;
background-position: right ($item-wp-padding-right - 2) center;
background-size: 14px 14px;
}
// Only show the forward arrow icon if true
@if $item-wp-detail-push-show == true {
.item[detail-push] .item-inner,
button.item:not([detail-none]) .item-inner,
a.item:not([detail-none]) .item-inner {
@include wp-detail-push();
}
}
// Windows Item Media
// --------------------------------------------------
[item-left],
[item-right] {
margin: $item-wp-padding-media-top ($item-wp-padding-right / 2) $item-wp-padding-media-bottom 0;
}
ion-icon[item-left],
ion-icon[item-right] {
margin-top: $item-wp-padding-icon-top;
margin-bottom: $item-wp-padding-icon-bottom;
margin-left: 0;
}
.item-button {
padding: 0 .6em;
height: 25px;
font-size: 1.2rem;
}
.item-button.button-icon-only ion-icon,
.item-button.button-icon-only {
padding: 0 1px;
}
[text-wrap] ion-label {
font-size: $item-wp-body-text-font-size;
line-height: $item-wp-body-text-line-height;
}
ion-icon[item-left] + .item-inner,
ion-icon[item-left] + .item-input {
margin-left: ($item-wp-padding-left / 2);
}
ion-avatar[item-left],
ion-thumbnail[item-left] {
margin: ($item-wp-padding-right / 2) $item-wp-padding-right ($item-wp-padding-right / 2) 0;
}
ion-avatar[item-right],
ion-thumbnail[item-right] {
margin: ($item-wp-padding-right / 2);
}
ion-avatar {
min-width: $item-wp-avatar-size;
min-height: $item-wp-avatar-size;
img {
max-width: $item-wp-avatar-size;
max-height: $item-wp-avatar-size;
border-radius: $item-wp-avatar-size / 2;
}
}
ion-thumbnail {
min-width: $item-wp-thumbnail-size;
min-height: $item-wp-thumbnail-size;
img {
max-width: $item-wp-thumbnail-size;
max-height: $item-wp-thumbnail-size;
}
}
ion-note {
color: $item-wp-note-color;
}
// Windows Item Divider
// --------------------------------------------------
ion-item-divider {
padding-left: $item-wp-padding-left;
color: $item-wp-divider-color;
background-color: $item-wp-divider-background;
}
// Generate Windows Item Divider Colors
// --------------------------------------------------
@each $color-name, $color-base, $color-contrast in get-colors($colors-wp) {
ion-item-divider[#{$color-name}] {
color: $color-contrast;
background-color: $color-base;
}
}
// Windows Item Sliding
// --------------------------------------------------
ion-item-sliding {
background-color: $item-wp-sliding-content-background;
}
| src/components/item/item.wp.scss | 1 | https://github.com/ionic-team/ionic-framework/commit/400957517da4b368ad064740095223ceb725b7ec | [
0.9971426129341125,
0.046034153550863266,
0.00016532470181118697,
0.00018852981156669557,
0.20755349099636078
] |
{
"id": 4,
"code_window": [
" line-height: normal;\n",
" }\n",
"\n",
" p {\n",
" margin: 0 0 2px;\n",
"\n",
" font-size: 1.4rem;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" overflow: inherit;\n",
"\n"
],
"file_path": "src/components/item/item.wp.scss",
"type": "add",
"edit_start_line_idx": 68
} | import {Injectable, NgZone} from '@angular/core';
import {Config} from '../config/config';
import {Form} from './form';
import {hasFocusedTextInput, nativeRaf, rafFrames, nativeTimeout} from './dom';
import {Key} from './key';
/**
* @name Keyboard
* @description
* The `Keyboard` class allows you to work with the keyboard events provided by the Ionic keyboard plugin.
*
* @usage
* ```ts
* export class MyClass{
* constructor(keyboard: Keyboard){
* this.keyboard = keyboard;
* }
* }
*
* ```
*/
@Injectable()
export class Keyboard {
constructor(config: Config, private _form: Form, private _zone: NgZone) {
_zone.runOutsideAngular(() => {
this.focusOutline(config.get('focusOutline'), document);
});
}
/**
* Check to see if the keyboard is open or not.
*
* ```ts
* export class MyClass{
* constructor(keyboard: Keyboard){
* this.keyboard = keyboard;
* }
* keyboardCheck(){
* setTimeout(() => console.log('is the keyboard open ', this.keyboard.isOpen()));
* }
* }
*
* ```
*
* @return {boolean} returns a true or flase value if the keyboard is open or not
*/
isOpen() {
return hasFocusedTextInput();
}
/**
* When the keyboard is closed, call any methods you want
*
* ```ts
* export class MyClass{
* constructor(keyboard: Keyboard){
* this.keyboard = keyboard;
* this.keyboard.onClose(this.closeCallback);
* }
* closeCallback(){
* // call what ever functionality you want on keyboard close
* console.log('Closing time');
* }
* }
*
* ```
* @param {function} callback method you want to call when the keyboard has been closed
* @return {function} returns a callback that gets fired when the keyboard is closed
*/
onClose(callback: Function, pollingInternval = KEYBOARD_CLOSE_POLLING, pollingChecksMax = KEYBOARD_POLLING_CHECKS_MAX) {
console.debug('keyboard onClose');
const self = this;
let checks = 0;
let promise: Promise<any> = null;
if (!callback) {
// a callback wasn't provided, so let's return a promise instead
promise = new Promise(resolve => { callback = resolve; });
}
function checkKeyboard() {
console.debug('keyboard isOpen', self.isOpen());
if (!self.isOpen() || checks > pollingChecksMax) {
rafFrames(30, () => {
self._zone.run(() => {
console.debug('keyboard closed');
callback();
});
});
} else {
nativeTimeout(checkKeyboard, pollingInternval);
}
checks++;
}
nativeTimeout(checkKeyboard, pollingInternval);
return promise;
}
/**
* Programmatically close the keyboard
*
*/
close() {
console.debug('keyboard close()');
nativeRaf(() => {
if (hasFocusedTextInput()) {
// only focus out when a text input has focus
this._form.focusOut();
}
});
}
/**
* @private
*/
focusOutline(setting: any, document: any) {
/* Focus Outline
* --------------------------------------------------
* By default, when a keydown event happens from a tab key, then
* the 'focus-outline' css class is added to the body element
* so focusable elements have an outline. On a mousedown or
* touchstart event, then the 'focus-outline' css class is removed.
*
* Config default overrides:
* focusOutline: true - Always add the focus-outline
* focusOutline: false - Do not add the focus-outline
*/
let self = this;
let isKeyInputEnabled = false;
function cssClass() {
nativeRaf(() => {
document.body.classList[isKeyInputEnabled ? 'add' : 'remove']('focus-outline');
});
}
if (setting === true) {
isKeyInputEnabled = true;
return cssClass();
} else if (setting === false) {
return;
}
// default is to add the focus-outline when the tab key is used
function keyDown(ev: KeyboardEvent) {
if (!isKeyInputEnabled && ev.keyCode === Key.TAB) {
isKeyInputEnabled = true;
enableKeyInput();
}
}
function pointerDown() {
isKeyInputEnabled = false;
enableKeyInput();
}
function enableKeyInput() {
cssClass();
self._zone.runOutsideAngular(() => {
document.removeEventListener('mousedown', pointerDown);
document.removeEventListener('touchstart', pointerDown);
if (isKeyInputEnabled) {
document.addEventListener('mousedown', pointerDown);
document.addEventListener('touchstart', pointerDown);
}
});
}
document.addEventListener('keydown', keyDown);
}
}
const KEYBOARD_CLOSE_POLLING = 150;
const KEYBOARD_POLLING_CHECKS_MAX = 100;
| src/util/keyboard.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/400957517da4b368ad064740095223ceb725b7ec | [
0.0003043735050596297,
0.0001814600545912981,
0.00016691407654434443,
0.00017000494699459523,
0.00003091718826908618
] |
{
"id": 4,
"code_window": [
" line-height: normal;\n",
" }\n",
"\n",
" p {\n",
" margin: 0 0 2px;\n",
"\n",
" font-size: 1.4rem;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" overflow: inherit;\n",
"\n"
],
"file_path": "src/components/item/item.wp.scss",
"type": "add",
"edit_start_line_idx": 68
} | <ion-header style="opacity: 0.9">
<ion-navbar>
<ion-title>Virtual Scroll: Image Gallery</ion-title>
<ion-buttons end>
<button (click)="reload()">
Reload
</button>
</ion-buttons>
</ion-navbar>
</ion-header>
<ion-content fullscreen>
<h4 padding>
Name these cars:
</h4>
<ion-list [virtualScroll]="items"
[headerFn]="headerFn"
[footerFn]="footerFn"
approxItemWidth="80px"
approxItemHeight="80px"
approxFooterWidth="80px"
approxFooterHeight="80px"
approxHeaderWidth="100%"
approxHeaderHeight="36px">
<div *virtualHeader="let header" class="virtual-header">
Header: {{header.date}}
</div>
<div *virtualItem="let item" class="virtual-item">
<ion-img [src]="item.imgSrc"></ion-img>
<!--{{ item.index }}-->
</div>
<div *virtualFooter="let footer" class="virtual-footer">
footer
</div>
</ion-list>
<h4 padding>
How many did you get right?
</h4>
</ion-content>
<style>
.virtual-header {
width: 100%;
margin-bottom: 5px;
padding: 10px;
background: #eee;
}
.virtual-item {
display: inline-block;
vertical-align: top;
width: 80px;
height: 80px;
margin-left: 5px;
margin-bottom: 5px;
border: 1px solid gray;
}
.virtual-footer {
display: inline-block;
width: 80px;
height: 80px;
border: 1px solid red;
margin-left: 5px;
margin-bottom: 5px;
padding: 10px;
}
.virtual-scroll > :first-child {
border-top: 2px solid blue;
}
.virtual-scroll > :last-child {
background: red;
}
</style>
| src/components/virtual-scroll/test/image-gallery/main.html | 0 | https://github.com/ionic-team/ionic-framework/commit/400957517da4b368ad064740095223ceb725b7ec | [
0.00023912489996291697,
0.00018273793102707714,
0.0001672031794441864,
0.00017426944395992905,
0.000022778238417231478
] |
{
"id": 4,
"code_window": [
" line-height: normal;\n",
" }\n",
"\n",
" p {\n",
" margin: 0 0 2px;\n",
"\n",
" font-size: 1.4rem;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" overflow: inherit;\n",
"\n"
],
"file_path": "src/components/item/item.wp.scss",
"type": "add",
"edit_start_line_idx": 68
} | import { Component, ContentChildren, ElementRef, EventEmitter, forwardRef, Input, HostListener, Optional, Output, Provider, Renderer, QueryList, ViewEncapsulation } from '@angular/core';
import { NG_VALUE_ACCESSOR } from '@angular/common';
import { ActionSheet } from '../action-sheet/action-sheet';
import { Alert } from '../alert/alert';
import { Form } from '../../util/form';
import { isBlank, isCheckedProperty, isTrueProperty, merge } from '../../util/util';
import { Item } from '../item/item';
import { NavController } from '../nav/nav-controller';
import { Option } from '../option/option';
const SELECT_VALUE_ACCESSOR = new Provider(
NG_VALUE_ACCESSOR, {useExisting: forwardRef(() => Select), multi: true});
/**
* @name Select
* @description
* The `ion-select` component is similar to an HTML `<select>` element, however,
* Ionic's select component makes it easier for users to sort through and select
* the preferred option or options. When users tap the select component, a
* dialog will appear with all of the options in a large, easy to select list
* for users.
*
* The select component takes child `ion-option` components. If `ion-option` is not
* given a `value` attribute then it will use its text as the value.
*
* ### Interfaces
*
* By default, the `ion-select` uses the {@link ../../alert/Alert Alert API} to
* open up the overlay of options in an alert. The interface can be changed to use the
* {@link ../../action-sheet/ActionSheet ActionSheet API} by passing `action-sheet` to
* the `interface` property. Read the other sections for the limitations of the
* action sheet interface.
*
* ### Single Value: Radio Buttons
*
* The standard `ion-select` component allows the user to select only one
* option. When selecting only one option the alert interface presents users with
* a radio button styled list of options. The action sheet interface can only be
* used with a single value select. If the number of options exceed 6, it will
* use the `alert` interface even if `action-sheet` is passed. The `ion-select`
* component's value receives the value of the selected option's value.
*
* ```html
* <ion-item>
* <ion-label>Gender</ion-label>
* <ion-select [(ngModel)]="gender">
* <ion-option value="f" checked="true">Female</ion-option>
* <ion-option value="m">Male</ion-option>
* </ion-select>
* </ion-item>
* ```
*
* ### Multiple Value: Checkboxes
*
* By adding the `multiple="true"` attribute to `ion-select`, users are able
* to select multiple options. When multiple options can be selected, the alert
* overlay presents users with a checkbox styled list of options. The
* `ion-select multiple="true"` component's value receives an array of all the
* selected option values. In the example below, because each option is not given
* a `value`, then it'll use its text as the value instead.
*
* Note: the action sheet interface will not work with a multi-value select.
*
* ```html
* <ion-item>
* <ion-label>Toppings</ion-label>
* <ion-select [(ngModel)]="toppings" multiple="true">
* <ion-option>Bacon</ion-option>
* <ion-option>Black Olives</ion-option>
* <ion-option>Extra Cheese</ion-option>
* <ion-option>Mushrooms</ion-option>
* <ion-option>Pepperoni</ion-option>
* <ion-option>Sausage</ion-option>
* </ion-select>
* </ion-item>
* ```
*
* ### Select Buttons
* By default, the two buttons read `Cancel` and `OK`. Each button's text
* can be customized using the `cancelText` and `okText` attributes:
*
* ```html
* <ion-select okText="Okay" cancelText="Dismiss">
* ...
* </ion-select>
* ```
*
* The action sheet interface does not have an `OK` button, clicking
* on any of the options will automatically close the overlay and select
* that value.
*
* ### Alert Options
*
* Since `ion-select` is a wrapper to `Alert`, by default, it can be
* passed options in the `alertOptions` property. This can be used to
* pass a custom alert title, subtitle or message. See the {@link ../../alert/Alert Alert API docs}
* for more properties.
*
* ```html
* <ion-select [alertOptions]="alertOptions">
* ...
* </ion-select>
* ```
*
* ```ts
* this.alertOptions = {
* title: 'Pizza Toppings',
* subTitle: 'Select your toppings'
* };
* ```
*
* @demo /docs/v2/demos/select/
*/
@Component({
selector: 'ion-select',
template:
'<div *ngIf="!_text" class="select-placeholder select-text">{{placeholder}}</div>' +
'<div *ngIf="_text" class="select-text">{{_text}}</div>' +
'<div class="select-icon">' +
'<div class="select-icon-inner"></div>' +
'</div>' +
'<button aria-haspopup="true" ' +
'[id]="id" ' +
'category="item-cover" ' +
'[attr.aria-labelledby]="_labelId" ' +
'[attr.aria-disabled]="_disabled" ' +
'class="item-cover">' +
'</button>',
host: {
'[class.select-disabled]': '_disabled'
},
providers: [SELECT_VALUE_ACCESSOR],
encapsulation: ViewEncapsulation.None,
})
export class Select {
private _disabled: any = false;
private _labelId: string;
private _multi: boolean = false;
private _options: QueryList<Option>;
private _values: string[] = [];
private _texts: string[] = [];
private _text: string = '';
private _fn: Function;
private _isOpen: boolean = false;
/**
* @private
*/
id: string;
/**
* @input {string} The text to display on the cancel button. Default: `Cancel`.
*/
@Input() cancelText: string = 'Cancel';
/**
* @input {string} The text to display on the ok button. Default: `OK`.
*/
@Input() okText: string = 'OK';
/**
* @input {string} The text to display when the select is empty.
*/
@Input() placeholder: string;
/**
* @input {any} Any addition options that the alert interface can take.
* See the [Alert API docs](../../alert/Alert) for the create options.
*/
@Input() alertOptions: any = {};
/**
* @private
*/
@Input() checked: any = false;
/**
* @input {string} The interface the select should use: `action-sheet` or `alert`. Default: `alert`.
*/
@Input() interface: string = '';
/**
* @output {any} Any expression you want to evaluate when the selection has changed.
*/
@Output() ionChange: EventEmitter<any> = new EventEmitter();
/**
* @output {any} Any expression you want to evaluate when the selection was cancelled.
*/
@Output() ionCancel: EventEmitter<any> = new EventEmitter();
constructor(
private _form: Form,
private _elementRef: ElementRef,
private _renderer: Renderer,
@Optional() private _item: Item,
@Optional() private _nav: NavController
) {
this._form.register(this);
if (_item) {
this.id = 'sel-' + _item.registerInput('select');
this._labelId = 'lbl-' + _item.id;
this._item.setCssClass('item-select', true);
}
if (!_nav) {
console.error('parent <ion-nav> required for <ion-select>');
}
}
@HostListener('click', ['$event'])
private _click(ev: UIEvent) {
if (ev.detail === 0) {
// do not continue if the click event came from a form submit
return;
}
ev.preventDefault();
ev.stopPropagation();
this._open();
}
@HostListener('keyup.space')
private _keyup() {
if (!this._isOpen) {
this._open();
}
}
private _open() {
if (this._disabled) {
return;
}
console.debug('select, open alert');
// the user may have assigned some options specifically for the alert
let alertOptions = merge({}, this.alertOptions);
// make sure their buttons array is removed from the options
// and we create a new array for the alert's two buttons
alertOptions.buttons = [{
text: this.cancelText,
role: 'cancel',
handler: () => {
this.ionCancel.emit(null);
}
}];
// if the alertOptions didn't provide an title then use the label's text
if (!alertOptions.title && this._item) {
alertOptions.title = this._item.getLabelText();
}
let options = this._options.toArray();
if (this.interface === 'action-sheet' && options.length > 6) {
console.warn('Interface cannot be "action-sheet" with more than 6 options. Using the "alert" interface.');
this.interface = 'alert';
}
if (this.interface === 'action-sheet' && this._multi) {
console.warn('Interface cannot be "action-sheet" with a multi-value select. Using the "alert" interface.');
this.interface = 'alert';
}
let overlay: any;
if (this.interface === 'action-sheet') {
alertOptions.buttons = alertOptions.buttons.concat(options.map(input => {
return {
role: (input.checked ? 'selected' : ''),
text: input.text,
handler: () => {
this.onChange(input.value);
this.ionChange.emit(input.value);
}
};
}));
alertOptions.cssClass = 'select-action-sheet';
overlay = ActionSheet.create(alertOptions);
} else {
// default to use the alert interface
this.interface = 'alert';
// user cannot provide inputs from alertOptions
// alert inputs must be created by ionic from ion-options
alertOptions.inputs = this._options.map(input => {
return {
type: (this._multi ? 'checkbox' : 'radio'),
label: input.text,
value: input.value,
checked: input.checked
};
});
// create the alert instance from our built up alertOptions
overlay = Alert.create(alertOptions);
if (this._multi) {
// use checkboxes
overlay.setCssClass('select-alert multiple-select-alert');
} else {
// use radio buttons
overlay.setCssClass('select-alert single-select-alert');
}
overlay.addButton({
text: this.okText,
handler: (selectedValues: any) => {
this.onChange(selectedValues);
this.ionChange.emit(selectedValues);
}
});
}
this._nav.present(overlay, alertOptions);
this._isOpen = true;
overlay.onDismiss(() => {
this._isOpen = false;
});
}
/**
* @input {boolean} Whether or not the select component can accept multiple values. Default: `false`.
*/
@Input()
get multiple(): any {
return this._multi;
}
set multiple(val: any) {
this._multi = isTrueProperty(val);
}
/**
* @private
*/
get text() {
return (this._multi ? this._texts : this._texts.join());
}
/**
* @private
*/
@ContentChildren(Option)
private set options(val: QueryList<Option>) {
this._options = val;
if (!this._values.length) {
// there are no values set at this point
// so check to see who should be checked
this._values = val.filter(o => o.checked).map(o => o.value);
}
this._updOpts();
}
/**
* @private
*/
private _updOpts() {
this._texts = [];
if (this._options) {
this._options.forEach(option => {
// check this option if the option's value is in the values array
option.checked = this._values.some(selectValue => {
return isCheckedProperty(selectValue, option.value);
});
if (option.checked) {
this._texts.push(option.text);
}
});
}
this._text = this._texts.join(', ');
}
/**
* @input {boolean} Whether or not the select component is disabled. Default `false`.
*/
@Input()
get disabled() {
return this._disabled;
}
set disabled(val) {
this._disabled = isTrueProperty(val);
this._item && this._item.setCssClass('item-select-disabled', this._disabled);
}
/**
* @private
*/
writeValue(val: any) {
console.debug('select, writeValue', val);
this._values = (Array.isArray(val) ? val : isBlank(val) ? [] : [val]);
this._updOpts();
}
/**
* @private
*/
ngAfterContentInit() {
this._updOpts();
}
/**
* @private
*/
registerOnChange(fn: Function): void {
this._fn = fn;
this.onChange = (val: any) => {
console.debug('select, onChange', val);
fn(val);
this._values = (Array.isArray(val) ? val : isBlank(val) ? [] : [val]);
this._updOpts();
this.onTouched();
};
}
/**
* @private
*/
registerOnTouched(fn: any) { this.onTouched = fn; }
/**
* @private
*/
onChange(val: any) {
// onChange used when there is not an ngControl
console.debug('select, onChange w/out ngControl', val);
this._values = (Array.isArray(val) ? val : isBlank(val) ? [] : [val]);
this._updOpts();
this.onTouched();
}
/**
* @private
*/
onTouched() { }
/**
* @private
*/
ngOnDestroy() {
this._form.deregister(this);
}
}
| src/components/select/select.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/400957517da4b368ad064740095223ceb725b7ec | [
0.00017954903887584805,
0.0001704618480289355,
0.00016448443057015538,
0.00017041295359376818,
0.0000034087233871105127
] |
{
"id": 5,
"code_window": [
" margin: 0 0 2px;\n",
"\n",
" font-size: 1.4rem;\n",
" line-height: normal;\n",
" color: $item-wp-paragraph-text-color;\n",
" }\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" text-overflow: inherit;\n"
],
"file_path": "src/components/item/item.wp.scss",
"type": "add",
"edit_start_line_idx": 72
} | @import "../../globals.wp";
@import "./item";
// Windows Item
// --------------------------------------------------
$item-wp-body-text-font-size: 1.4rem !default;
$item-wp-body-text-line-height: 1.5 !default;
$item-wp-body-background-color: $list-wp-background-color !default;
$item-wp-body-text-color: $list-wp-text-color !default;
$item-wp-paragraph-text-color: #666 !default;
$item-wp-font-size: 1.6rem !default;
$item-wp-avatar-size: 4rem !default;
$item-wp-thumbnail-size: 8rem !default;
$item-wp-note-color: $input-wp-border-color !default;
$item-wp-detail-push-show: false !default;
$item-wp-detail-push-color: $input-wp-border-color !default;
$item-wp-detail-push-svg: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 20'><path d='M2,20l-2-2l8-8L0,2l2-2l10,10L2,20z' fill='#{$item-wp-detail-push-color}'/></svg>" !default;
$item-wp-divider-background: #fff !default;
$item-wp-divider-color: #222 !default;
$item-wp-divider-padding: 5px 15px !default;
$item-wp-sliding-content-background: $list-wp-background-color !default;
.item {
position: relative;
padding-right: 0;
padding-left: ($item-wp-padding-left);
font-size: $item-wp-font-size;
font-weight: normal;
text-transform: none;
color: $item-wp-body-text-color;
background-color: $item-wp-body-background-color;
box-shadow: none;
h1 {
margin: 0 0 2px;
font-size: 2.4rem;
font-weight: normal;
}
h2 {
margin: 2px 0;
font-size: 1.6rem;
font-weight: normal;
}
h3,
h4,
h5,
h6 {
margin: 2px 0;
font-size: 1.4rem;
font-weight: normal;
line-height: normal;
}
p {
margin: 0 0 2px;
font-size: 1.4rem;
line-height: normal;
color: $item-wp-paragraph-text-color;
}
}
.item.activated {
background-color: $list-wp-activated-background-color;
}
.item[no-lines] {
border-width: 0;
}
.item .item-inner {
padding-right: ($item-wp-padding-right / 2);
border-bottom: 1px solid $list-wp-border-color;
}
// Windows Item Detail Push
// --------------------------------------------------
@mixin wp-detail-push() {
@include svg-background-image($item-wp-detail-push-svg);
padding-right: 32px;
background-repeat: no-repeat;
background-position: right ($item-wp-padding-right - 2) center;
background-size: 14px 14px;
}
// Only show the forward arrow icon if true
@if $item-wp-detail-push-show == true {
.item[detail-push] .item-inner,
button.item:not([detail-none]) .item-inner,
a.item:not([detail-none]) .item-inner {
@include wp-detail-push();
}
}
// Windows Item Media
// --------------------------------------------------
[item-left],
[item-right] {
margin: $item-wp-padding-media-top ($item-wp-padding-right / 2) $item-wp-padding-media-bottom 0;
}
ion-icon[item-left],
ion-icon[item-right] {
margin-top: $item-wp-padding-icon-top;
margin-bottom: $item-wp-padding-icon-bottom;
margin-left: 0;
}
.item-button {
padding: 0 .6em;
height: 25px;
font-size: 1.2rem;
}
.item-button.button-icon-only ion-icon,
.item-button.button-icon-only {
padding: 0 1px;
}
[text-wrap] ion-label {
font-size: $item-wp-body-text-font-size;
line-height: $item-wp-body-text-line-height;
}
ion-icon[item-left] + .item-inner,
ion-icon[item-left] + .item-input {
margin-left: ($item-wp-padding-left / 2);
}
ion-avatar[item-left],
ion-thumbnail[item-left] {
margin: ($item-wp-padding-right / 2) $item-wp-padding-right ($item-wp-padding-right / 2) 0;
}
ion-avatar[item-right],
ion-thumbnail[item-right] {
margin: ($item-wp-padding-right / 2);
}
ion-avatar {
min-width: $item-wp-avatar-size;
min-height: $item-wp-avatar-size;
img {
max-width: $item-wp-avatar-size;
max-height: $item-wp-avatar-size;
border-radius: $item-wp-avatar-size / 2;
}
}
ion-thumbnail {
min-width: $item-wp-thumbnail-size;
min-height: $item-wp-thumbnail-size;
img {
max-width: $item-wp-thumbnail-size;
max-height: $item-wp-thumbnail-size;
}
}
ion-note {
color: $item-wp-note-color;
}
// Windows Item Divider
// --------------------------------------------------
ion-item-divider {
padding-left: $item-wp-padding-left;
color: $item-wp-divider-color;
background-color: $item-wp-divider-background;
}
// Generate Windows Item Divider Colors
// --------------------------------------------------
@each $color-name, $color-base, $color-contrast in get-colors($colors-wp) {
ion-item-divider[#{$color-name}] {
color: $color-contrast;
background-color: $color-base;
}
}
// Windows Item Sliding
// --------------------------------------------------
ion-item-sliding {
background-color: $item-wp-sliding-content-background;
}
| src/components/item/item.wp.scss | 1 | https://github.com/ionic-team/ionic-framework/commit/400957517da4b368ad064740095223ceb725b7ec | [
0.9907929301261902,
0.12470633536577225,
0.0001656868844293058,
0.0004748511128127575,
0.2883273959159851
] |
{
"id": 5,
"code_window": [
" margin: 0 0 2px;\n",
"\n",
" font-size: 1.4rem;\n",
" line-height: normal;\n",
" color: $item-wp-paragraph-text-color;\n",
" }\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" text-overflow: inherit;\n"
],
"file_path": "src/components/item/item.wp.scss",
"type": "add",
"edit_start_line_idx": 72
} | import { Directive, Optional } from '@angular/core';
import { NavController } from './nav-controller';
/**
* @name NavPop
* @description
* Directive for declaratively pop the current page off from the navigation stack.
*
* @usage
* ```html
* <ion-content>
* <div block button nav-pop>go back</div>
* </ion-content>
* ```
* This will go back one page in the navigation stack
*
* Similar to {@link /docs/v2/api/components/nav/NavPush/ `NavPush` }
* @demo /docs/v2/demos/navigation/
* @see {@link /docs/v2/components#navigation Navigation Component Docs}
* @see {@link ../NavPush NavPush API Docs}
*/
@Directive({
selector: '[nav-pop]',
host: {
'(click)': 'onClick()',
'role': 'link'
}
})
export class NavPop {
constructor(@Optional() private _nav: NavController) {
if (!_nav) {
console.error('nav-pop must be within a NavController');
}
}
/**
* @private
*/
onClick() {
this._nav && this._nav.pop();
}
}
| src/components/nav/nav-pop.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/400957517da4b368ad064740095223ceb725b7ec | [
0.00020894983026664704,
0.00017787719843909144,
0.00016639030945952982,
0.00017159836716018617,
0.000015667168554500677
] |
{
"id": 5,
"code_window": [
" margin: 0 0 2px;\n",
"\n",
" font-size: 1.4rem;\n",
" line-height: normal;\n",
" color: $item-wp-paragraph-text-color;\n",
" }\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" text-overflow: inherit;\n"
],
"file_path": "src/components/item/item.wp.scss",
"type": "add",
"edit_start_line_idx": 72
} | import { Component } from '@angular/core';
import { ionicBootstrap } from 'ionic-angular';
@Component({
templateUrl: 'main.html'
})
class ApiDemoPage {
appType = "paid";
safari = "links";
news = "local";
favorites = "recent";
purchased = "all";
mapStyle = "sat";
teslaModels = "X";
pet = "puppies";
calendar = "day";
proxy = "auto";
}
@Component({
template: '<ion-nav [root]="root"></ion-nav>'
})
class ApiDemoApp {
root = ApiDemoPage;
}
ionicBootstrap(ApiDemoApp);
| demos/segment/index.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/400957517da4b368ad064740095223ceb725b7ec | [
0.00044861104106530547,
0.00026687042554840446,
0.00017189035133924335,
0.00022349014761857688,
0.00011187269410584122
] |
{
"id": 5,
"code_window": [
" margin: 0 0 2px;\n",
"\n",
" font-size: 1.4rem;\n",
" line-height: normal;\n",
" color: $item-wp-paragraph-text-color;\n",
" }\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" text-overflow: inherit;\n"
],
"file_path": "src/components/item/item.wp.scss",
"type": "add",
"edit_start_line_idx": 72
} | import { Component } from '@angular/core';
import { Animation, Config, IonicApp, ionicBootstrap, Modal, NavController, NavParams, Platform, ViewController } from 'ionic-angular';
@Component({
templateUrl: 'main.html'
})
export class ModalFirstPage {
myParam = '';
constructor(public nav: NavController) {}
openBasicModal() {
let myModal = Modal.create(ModalContentPage);
this.nav.present(myModal);
}
openModalWithParams() {
let myModal = Modal.create(ModalContentPage, { 'myParam': this.myParam });
this.nav.present(myModal);
}
openCustomAnimationModal() {
let myModal = Modal.create(ModalContentPage, {
animation: 'my-fade-in',
});
this.nav.present(myModal);
}
}
@Component({
templateUrl: "modal-content.html"
})
export class ModalContentPage {
myParam: string;
constructor(
public nav: NavController,
public viewCtrl: ViewController,
params: NavParams
) {
this.myParam = params.get('myParam');
}
dismiss() {
this.viewCtrl.dismiss();
}
}
@Component({
template: '<ion-nav [root]="root"></ion-nav>'
})
class ApiDemoApp {
root = ModalFirstPage;
}
ionicBootstrap(ApiDemoApp);
class FadeIn extends Animation {
constructor(enteringView, leavingView) {
super(enteringView.pageRef());
this
.easing('ease')
.duration(1000)
.fromTo('translateY', '0%', '0%')
.fadeIn()
.before.addClass('show-page');
}
}
Animation.register('my-fade-in', FadeIn);
class FadeOut extends Animation {
constructor(enteringView, leavingView) {
super(leavingView.pageRef());
this
.easing('ease')
.duration(500)
.fadeOut()
.before.addClass('show-page');
}
}
Animation.register('my-fade-out', FadeOut);
| demos/modal/index.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/400957517da4b368ad064740095223ceb725b7ec | [
0.0004098692152183503,
0.00021231432037893683,
0.000167167789186351,
0.00017391967412550002,
0.00007379966700682417
] |
{
"id": 0,
"code_window": [
" ...get('publicRuntimeConfig'),\n",
" ...get('privateRuntimeConfig'),\n",
" public: get('publicRuntimeConfig'),\n",
" app: {\n",
" baseURL: get('app.baseURL'),\n",
" buildAssetsDir: get('app.buildAssetsDir'),\n",
" cdnURL: get('app.cdnURL'),\n",
" }\n",
" })\n",
" },\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" baseURL: get('app').baseURL,\n",
" buildAssetsDir: get('app').buildAssetsDir,\n",
" cdnURL: get('app').cdnURL,\n"
],
"file_path": "packages/schema/src/config/_common.ts",
"type": "replace",
"edit_start_line_idx": 727
} | import { resolve } from 'pathe'
import { joinURL } from 'ufo'
/**
* @version 2
*/
export default {
/**
* Directory name that holds all the assets and generated pages for a `static` build.
*/
dir: {
$resolve: (val = 'dist', get) => resolve(get('rootDir'), val)
},
/**
* The routes to generate.
*
* If you are using the crawler, this will be only the starting point for route generation.
* This is often necessary when using dynamic routes.
*
* It can be an array or a function.
*
* @example
* ```js
* routes: ['/users/1', '/users/2', '/users/3']
* ```
*
* You can pass a function that returns a promise or a function that takes a callback. It should
* return an array of strings or objects with `route` and (optional) `payload` keys.
*
* @example
* ```js
* export default {
* generate: {
* async routes() {
* const res = await axios.get('https://my-api/users')
* return res.data.map(user => ({ route: '/users/' + user.id, payload: user }))
* }
* }
* }
* ```
* Or instead:
* ```js
* export default {
* generate: {
* routes(callback) {
* axios
* .get('https://my-api/users')
* .then(res => {
* const routes = res.data.map(user => '/users/' + user.id)
* callback(null, routes)
* })
* .catch(callback)
* }
* }
* }
* ```
*
* If `routes()` returns a payload, it can be accessed from the Nuxt context.
* @example
* ```js
* export default {
* async useAsyncData ({ params, error, payload }) {
* if (payload) return { user: payload }
* else return { user: await backend.fetchUser(params.id) }
* }
* }
* ```
*/
routes: [],
/**
* An array of string or regular expressions that will prevent generation
* of routes matching them. The routes will still be accessible when `fallback` is set.
*/
exclude: [],
/** The number of routes that are generated concurrently in the same thread. */
concurrency: 500,
/**
* Interval in milliseconds between two render cycles to avoid flooding a potential
* API with calls.
*/
interval: 0,
/**
* Set to `false` to disable creating a directory + `index.html` for each route.
*
* @example
* ```bash
* # subFolders: true
* -| dist/
* ---| index.html
* ---| about/
* -----| index.html
* ---| products/
* -----| item/
* -------| index.html
*
* # subFolders: false
* -| dist/
* ---| index.html
* ---| about.html
* ---| products/
* -----| item.html
* ```
*/
subFolders: true,
/**
* The path to the fallback HTML file.
*
* Set this as the error page in your static server configuration, so that unknown
* routes can be rendered (on the client-side) by Nuxt.
*
* * If unset or set to a falsy value, the name of the fallback HTML file will be `200.html`.
* * If set to true, the filename will be `404.html`.
* * If you provide a string as a value, it will be used instead.
*
* @note Multiple services (e.g. Netlify) detect a `404.html` automatically. If
* you configure your web server on your own, please consult its documentation
* to find out how to set up an error page (and set it to the 404.html file)
*/
fallback: { $resolve: val => val === true ? '400.html' : (val || '200.html') },
/**
* Set to `false` to disable generating pages discovered through crawling relative
* links in generated pages.
*/
crawler: true,
/** Set to `false` to disable generating a `manifest.js` with a list of all generated pages. */
manifest: true,
/** Set to `false` to disable generating a `.nojekyll` file (which aids compatibility with GitHub Pages). */
nojekyll: true,
/**
* Configure the cache (used with `static` target to avoid rebuilding when no files have changed).
*
* Set to `false` to disable completely.
*/
cache: {
/** An array of files or directories to ignore. (It can also be a function that returns an array.) */
ignore: [],
/**
* Options to pass to [`globby`](https://github.com/sindresorhus/globby), which
* is used to generate a 'snapshot' of the source files.
*/
globbyOptions: {
gitignore: true
}
},
staticAssets: {
/** The directory underneath `/_nuxt/`, where static assets (payload, state and manifest files) will live. */
dir: 'static',
/**
* The full path to the directory underneath `/_nuxt/` where static assets
* (payload, state and manifest files) will live.
*/
base: { $resolve: (val, get) => val || joinURL(get('app.buildAssetsDir'), get('generate.dir')) },
/** The full path to the versioned directory where static assets for the current buidl are located. */
versionBase: { $resolve: (val, get) => val || joinURL(get('generate.base'), get('generate.version')) },
/** A unique string to uniquely identify payload versions (defaults to the current timestamp). */
version: { $resolve: val => val || (String(Math.round(Date.now() / 1000))) }
}
}
| packages/schema/src/config/generate.ts | 1 | https://github.com/nuxt/nuxt/commit/71b808c8e96ae8bdbe4440f16d96f7242f864843 | [
0.06734206527471542,
0.004120993427932262,
0.00016307410260196775,
0.00016951592988334596,
0.01580527052283287
] |
{
"id": 0,
"code_window": [
" ...get('publicRuntimeConfig'),\n",
" ...get('privateRuntimeConfig'),\n",
" public: get('publicRuntimeConfig'),\n",
" app: {\n",
" baseURL: get('app.baseURL'),\n",
" buildAssetsDir: get('app.buildAssetsDir'),\n",
" cdnURL: get('app.cdnURL'),\n",
" }\n",
" })\n",
" },\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" baseURL: get('app').baseURL,\n",
" buildAssetsDir: get('app').buildAssetsDir,\n",
" cdnURL: get('app').cdnURL,\n"
],
"file_path": "packages/schema/src/config/_common.ts",
"type": "replace",
"edit_start_line_idx": 727
} | # `abortNavigation`
```ts
abortNavigation(err?: Error | string): false
```
* **err**: Optional error to be thrown by `abortNavigation()`.
::alert{type="warning"}
`abortNavigation()` is only usable inside a [route middleware handler](/guide/directory-structure/middleware).
::
Inside a route middleware handler, `abortNavigation()` will abort navigation, and throw an error if one is set as a parameter.
::ReadMore{link="/guide/features/routing"}
::
| docs/content/3.api/3.utils/abort-navigation.md | 0 | https://github.com/nuxt/nuxt/commit/71b808c8e96ae8bdbe4440f16d96f7242f864843 | [
0.00017017489881254733,
0.0001701576984487474,
0.0001701405126368627,
0.0001701576984487474,
1.7193089618672275e-8
] |
{
"id": 0,
"code_window": [
" ...get('publicRuntimeConfig'),\n",
" ...get('privateRuntimeConfig'),\n",
" public: get('publicRuntimeConfig'),\n",
" app: {\n",
" baseURL: get('app.baseURL'),\n",
" buildAssetsDir: get('app.buildAssetsDir'),\n",
" cdnURL: get('app.cdnURL'),\n",
" }\n",
" })\n",
" },\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" baseURL: get('app').baseURL,\n",
" buildAssetsDir: get('app').buildAssetsDir,\n",
" cdnURL: get('app').cdnURL,\n"
],
"file_path": "packages/schema/src/config/_common.ts",
"type": "replace",
"edit_start_line_idx": 727
} | /**
* This file is based on Vue.js (MIT) webpack plugins
* https://github.com/vuejs/vue/blob/dev/src/server/webpack-plugin/util.js
*/
import { logger } from '@nuxt/kit'
export const validate = (compiler) => {
if (compiler.options.target !== 'node') {
logger.warn('webpack config `target` should be "node".')
}
if (!compiler.options.externals) {
logger.info(
'It is recommended to externalize dependencies in the server build for ' +
'better build performance.'
)
}
}
const isJSRegExp = /\.[cm]?js(\?[^.]+)?$/
export const isJS = file => isJSRegExp.test(file)
export const extractQueryPartJS = file => isJSRegExp.exec(file)[1]
export const isCSS = file => /\.css(\?[^.]+)?$/.test(file)
export const isHotUpdate = file => file.includes('hot-update')
| packages/webpack/src/plugins/vue/util.ts | 0 | https://github.com/nuxt/nuxt/commit/71b808c8e96ae8bdbe4440f16d96f7242f864843 | [
0.00017302103515248746,
0.00017262808978557587,
0.00017217577260453254,
0.00017268744704779238,
3.476205847618985e-7
] |
{
"id": 0,
"code_window": [
" ...get('publicRuntimeConfig'),\n",
" ...get('privateRuntimeConfig'),\n",
" public: get('publicRuntimeConfig'),\n",
" app: {\n",
" baseURL: get('app.baseURL'),\n",
" buildAssetsDir: get('app.buildAssetsDir'),\n",
" cdnURL: get('app.cdnURL'),\n",
" }\n",
" })\n",
" },\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" baseURL: get('app').baseURL,\n",
" buildAssetsDir: get('app').buildAssetsDir,\n",
" cdnURL: get('app').cdnURL,\n"
],
"file_path": "packages/schema/src/config/_common.ts",
"type": "replace",
"edit_start_line_idx": 727
} | import { createUnplugin } from 'unplugin'
import escapeRE from 'escape-string-regexp'
import type { Plugin } from 'vite'
import MagicString from 'magic-string'
interface DynamicBasePluginOptions {
globalPublicPath?: string
}
export const RelativeAssetPlugin = function (): Plugin {
return {
name: 'nuxt:vite-relative-asset',
generateBundle (_, bundle) {
const generatedAssets = Object.entries(bundle).filter(([_, asset]) => asset.type === 'asset').map(([key]) => escapeRE(key))
const assetRE = new RegExp(`\\/__NUXT_BASE__\\/(${generatedAssets.join('|')})`, 'g')
for (const file in bundle) {
const asset = bundle[file]
if (asset.fileName.includes('legacy') && asset.type === 'chunk' && asset.code.includes('innerHTML')) {
for (const delimiter of ['`', '"', "'"]) {
asset.code = asset.code.replace(
new RegExp(`(?<=innerHTML=)${delimiter}([^${delimiter}]*)\\/__NUXT_BASE__\\/([^${delimiter}]*)${delimiter}`, 'g'),
/* eslint-disable-next-line no-template-curly-in-string */
'`$1${(window?.__NUXT__?.config.app.cdnURL || window?.__NUXT__?.config.app.baseURL) + window?.__NUXT__?.config.app.buildAssetsDir.slice(1)}$2`'
)
}
}
if (asset.type === 'asset' && typeof asset.source === 'string' && asset.fileName.endsWith('.css')) {
const depth = file.split('/').length - 1
const assetBase = depth === 0 ? '.' : Array.from({ length: depth }).map(() => '..').join('/')
const publicBase = Array.from({ length: depth + 1 }).map(() => '..').join('/')
asset.source = asset.source
.replace(assetRE, r => r.replace(/\/__NUXT_BASE__/g, assetBase))
.replace(/\/__NUXT_BASE__/g, publicBase)
}
if (asset.type === 'chunk' && typeof asset.code === 'string') {
asset.code = asset.code
.replace(/`\$\{(_?_?publicAssetsURL|buildAssetsURL|)\(\)\}([^`]*)`/g, '$1(`$2`)')
.replace(/"\/__NUXT_BASE__\/([^"]*)"\.replace\("\/__NUXT_BASE__", ""\)/g, '"$1"')
.replace(/'\/__NUXT_BASE__\/([^']*)'\.replace\("\/__NUXT_BASE__", ""\)/g, '"$1"')
}
}
}
}
}
const VITE_ASSET_RE = /^export default ["'](__VITE_ASSET.*)["']$/
export const DynamicBasePlugin = createUnplugin(function (options: DynamicBasePluginOptions = {}) {
return {
name: 'nuxt:dynamic-base-path',
resolveId (id) {
if (id.startsWith('/__NUXT_BASE__')) {
return id.replace('/__NUXT_BASE__', '')
}
if (id === '#internal/nitro') { return '#internal/nitro' }
return null
},
enforce: 'post',
transform (code, id) {
const s = new MagicString(code)
if (options.globalPublicPath && id.includes('paths.mjs') && code.includes('const appConfig = ')) {
s.append(`${options.globalPublicPath} = buildAssetsURL();\n`)
}
const assetId = code.match(VITE_ASSET_RE)
if (assetId) {
s.overwrite(0, code.length,
[
'import { buildAssetsURL } from \'#build/paths.mjs\';',
`export default buildAssetsURL("${assetId[1]}".replace("/__NUXT_BASE__", ""));`
].join('\n')
)
}
if (!id.includes('paths.mjs') && code.includes('NUXT_BASE') && !code.includes('import { publicAssetsURL as __publicAssetsURL }')) {
s.prepend('import { publicAssetsURL as __publicAssetsURL } from \'#build/paths.mjs\';\n')
}
if (id === 'vite/preload-helper') {
// Define vite base path as buildAssetsUrl (i.e. including _nuxt/)
s.prepend('import { buildAssetsDir } from \'#build/paths.mjs\';\n')
s.replace(/const base = ['"]\/__NUXT_BASE__\/['"]/, 'const base = buildAssetsDir()')
}
// Sanitize imports
s.replace(/from *['"]\/__NUXT_BASE__(\/[^'"]*)['"]/g, 'from "$1"')
// Dynamically compute string URLs featuring baseURL
for (const delimiter of ['`', "'", '"']) {
const delimiterRE = new RegExp(`(?<!(const base = |from *))${delimiter}([^${delimiter}]*)\\/__NUXT_BASE__\\/([^${delimiter}]*)${delimiter}`, 'g')
/* eslint-disable-next-line no-template-curly-in-string */
s.replace(delimiterRE, r => '`' + r.replace(/\/__NUXT_BASE__\//g, '${__publicAssetsURL()}').slice(1, -1) + '`')
}
if (s.hasChanged()) {
return {
code: s.toString(),
map: s.generateMap({ source: id, includeContent: true })
}
}
}
}
})
| packages/vite/src/plugins/dynamic-base.ts | 0 | https://github.com/nuxt/nuxt/commit/71b808c8e96ae8bdbe4440f16d96f7242f864843 | [
0.9951272010803223,
0.09286642074584961,
0.00016711774514988065,
0.00017339162877760828,
0.28534772992134094
] |
{
"id": 1,
"code_window": [
" * }\n",
" * ```\n",
" * @version 2\n",
" */\n",
" publicPath: {\n",
" $resolve: (val, get) => val ? withTrailingSlash(normalizeURL(val)) : get('app.buildAssetsDir')\n",
" },\n",
"\n",
" /**\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" $resolve: (val, get) => val ? withTrailingSlash(normalizeURL(val)) : get('app').buildAssetsDir\n"
],
"file_path": "packages/schema/src/config/build.ts",
"type": "replace",
"edit_start_line_idx": 194
} | import { join, resolve } from 'pathe'
import { isDevelopment } from 'std-env'
import createRequire from 'create-require'
import { pascalCase } from 'scule'
import jiti from 'jiti'
import defu from 'defu'
import { RuntimeConfig } from '../types/config'
export default {
/**
* Extend nested configurations from multiple local or remote sources
*
* Value should be either a string or array of strings pointing to source directories or config path relative to current config.
*
* You can use `github:`, `gitlab:`, `bitbucket:` or `https://` to extend from a remote git repository.
*
* @type {string|string[]}
*
* @version 3
*/
extends: null,
/**
* Define the workspace directory of your application.
*
* This property can be overwritten (for example, running `nuxt ./my-app/`
* will set the `rootDir` to the absolute path of `./my-app/` from the
* current/working directory.
*
* It is normally not needed to configure this option.
* @version 2
* @version 3
*/
rootDir: {
$resolve: val => typeof val === 'string' ? resolve(val) : process.cwd()
},
/**
* Define the source directory of your Nuxt application.
*
* If a relative path is specified it will be relative to the `rootDir`.
*
* @example
* ```js
* export default {
* srcDir: 'client/'
* }
* ```
* This would work with the following folder structure:
* ```bash
* -| app/
* ---| node_modules/
* ---| nuxt.config.js
* ---| package.json
* ---| client/
* ------| assets/
* ------| components/
* ------| layouts/
* ------| middleware/
* ------| pages/
* ------| plugins/
* ------| static/
* ------| store/
* ```
* @version 2
* @version 3
*/
srcDir: {
$resolve: (val, get) => resolve(get('rootDir'), val || '.')
},
/**
* Define the directory where your built Nuxt files will be placed.
*
* Many tools assume that `.nuxt` is a hidden directory (because it starts
* with a `.`). If that is a problem, you can use this option to prevent that.
*
* @example
* ```js
* export default {
* buildDir: 'nuxt-build'
* }
* ```
* @version 2
* @version 3
*/
buildDir: {
$resolve: (val, get) => resolve(get('rootDir'), val || '.nuxt')
},
/**
* Whether Nuxt is running in development mode.
*
* Normally you should not need to set this.
* @version 2
* @version 3
*/
dev: Boolean(isDevelopment),
/**
* Whether your app is being unit tested
* @version 2
*/
test: Boolean(isDevelopment),
/**
* Set to true to enable debug mode.
*
* By default it's only enabled in development mode.
* @version 2
*/
debug: {
$resolve: (val, get) => val ?? get('dev')
},
/**
* The env property defines environment variables that should be available
* throughout your app (server- and client-side). They can be assigned using
* server side environment variables.
*
* @note Nuxt uses webpack's `definePlugin` to define these environment variables.
* This means that the actual `process` or `process.env` from Node.js is neither
* available nor defined. Each of the `env` properties defined here is individually
* mapped to `process.env.xxxx` and converted during compilation.
*
* @note Environment variables starting with `NUXT_ENV_` are automatically injected
* into the process environment.
*
* @version 2
*/
env: {
$default: {},
$resolve: (val) => {
val = { ...val }
for (const key in process.env) {
if (key.startsWith('NUXT_ENV_')) {
val[key] = process.env[key]
}
}
return val
}
},
/**
* Set the method Nuxt uses to require modules, such as loading `nuxt.config`, server
* middleware, and so on - defaulting to `jiti` (which has support for TypeScript and ESM syntax).
*
* @see [jiti](https://github.com/unjs/jiti)
* @type {'jiti' | 'native' | ((p: string | { filename: string }) => NodeRequire)}
* @version 2
*/
createRequire: {
$resolve: (val: any) => {
val = process.env.NUXT_CREATE_REQUIRE || val ||
(typeof globalThis.jest !== 'undefined' ? 'native' : 'jiti')
if (val === 'jiti') {
return p => jiti(typeof p === 'string' ? p : p.filename)
}
if (val === 'native') {
return p => createRequire(typeof p === 'string' ? p : p.filename)
}
return val
}
},
/**
* Whether your Nuxt app should be built to be served by the Nuxt server (`server`)
* or as static HTML files suitable for a CDN or other static file server (`static`).
*
* This is unrelated to `ssr`.
* @type {'server' | 'static'}
* @version 2
*/
target: {
$resolve: val => ['server', 'static'].includes(val) ? val : 'server'
},
/**
* Whether to enable rendering of HTML - either dynamically (in server mode) or at generate time.
* If set to `false` and combined with `static` target, generated pages will simply display
* a loading screen with no content.
* @version 2
* @version 3
*/
ssr: true,
/**
* @deprecated use ssr option
*/
mode: {
$resolve: (val, get) => val || (get('ssr') ? 'spa' : 'universal'),
$schema: { deprecated: '`mode` option is deprecated' }
},
/**
* Whether to produce a separate modern build targeting browsers that support ES modules.
*
* Set to `'server'` to enable server mode, where the Nuxt server checks
* browser version based on the user agent and serves the correct bundle.
*
* Set to `'client'` to serve both the modern bundle with `<script type="module">`
* and the legacy bundle with `<script nomodule>`. It will also provide a
* `<link rel="modulepreload">` for the modern bundle. Every browser that understands
* the module type will load the modern bundle while older browsers fall back to the
* legacy (transpiled) bundle.
*
* If you have set `modern: true` and are generating your app or have `ssr: false`,
* modern will be set to `'client'`.
*
* If you have set `modern: true` and are serving your app, modern will be set to `'server'`.
*
* @see [concept of modern mode](https://philipwalton.com/articles/deploying-es2015-code-in-production-today/)
* @type {'server' | 'client' | boolean}
* @version 2
*/
modern: undefined,
/**
* Modules are Nuxt extensions which can extend its core functionality and add endless integrations
*
* Each module is either a string (which can refer to a package, or be a path to a file), a
* tuple with the module as first string and the options as a second object, or an inline module function.
*
* Nuxt tries to resolve each item in the modules array using node require path
* (in `node_modules`) and then will be resolved from project `srcDir` if `~` alias is used.
*
* @note Modules are executed sequentially so the order is important.
*
* @example
* ```js
* modules: [
* // Using package name
* '@nuxtjs/axios',
* // Relative to your project srcDir
* '~/modules/awesome.js',
* // Providing options
* ['@nuxtjs/google-analytics', { ua: 'X1234567' }],
* // Inline definition
* function () {}
* ]
* ```
* @type {(typeof import('../src/types/module').NuxtModule | string | [typeof import('../src/types/module').NuxtModule | string, Record<string, any>])[]}
* @version 2
* @version 3
*/
modules: [],
/**
* Modules that are only required during development and build time.
*
* Modules are Nuxt extensions which can extend its core functionality and add endless integrations
*
* Each module is either a string (which can refer to a package, or be a path to a file), a
* tuple with the module as first string and the options as a second object, or an inline module function.
*
* Nuxt tries to resolve each item in the modules array using node require path
* (in `node_modules`) and then will be resolved from project `srcDir` if `~` alias is used.
*
* @note Modules are executed sequentially so the order is important.
*
* @example
* ```js
* modules: [
* // Using package name
* '@nuxtjs/axios',
* // Relative to your project srcDir
* '~/modules/awesome.js',
* // Providing options
* ['@nuxtjs/google-analytics', { ua: 'X1234567' }],
* // Inline definition
* function () {}
* ]
* ```
*
* @note In Nuxt 2, using `buildModules` helps to make production startup faster and also significantly
* decreases the size of `node_modules` in production deployments. Please refer to each
* module's documentation to see if it is recommended to use `modules` or `buildModules`.
*
* @type {(typeof import('../src/types/module').NuxtModule | string | [typeof import('../src/types/module').NuxtModule | string, Record<string, any>])[]}
* @version 2
* @deprecated This is no longer needed in Nuxt 3 and Nuxt Bridge; all modules should be added to `modules` instead.
*/
buildModules: [],
/**
* Built-in ad-hoc modules
*
* @private
*/
_modules: [],
/**
* Installed module metadata
*
* @version 3
* @private
*/
_installedModules: [],
/**
* Allows customizing the global ID used in the main HTML template as well as the main
* Vue instance name and other options.
* @version 2
*/
globalName: {
$resolve: val => (typeof val === 'string' && /^[a-zA-Z]+$/.test(val)) ? val.toLocaleLowerCase() : 'nuxt'
},
/**
* Customizes specific global names (they are based on `globalName` by default).
* @version 2
*/
globals: {
/** @type {(globalName: string) => string} */
id: globalName => `__${globalName}`,
/** @type {(globalName: string) => string} */
nuxt: globalName => `$${globalName}`,
/** @type {(globalName: string) => string} */
context: globalName => `__${globalName.toUpperCase()}__`,
/** @type {(globalName: string) => string} */
pluginPrefix: globalName => globalName,
/** @type {(globalName: string) => string} */
readyCallback: globalName => `on${pascalCase(globalName)}Ready`,
/** @type {(globalName: string) => string} */
loadedCallback: globalName => `_on${pascalCase(globalName)}Loaded`
},
/**
* Server middleware are connect/express/h3-shaped functions that handle server-side requests. They
* run on the server and before the Vue renderer.
*
* By adding entries to `serverMiddleware` you can register additional routes without the need
* for an external server.
*
* You can pass a string, which can be the name of a node dependency or a path to a file. You
* can also pass an object with `path` and `handler` keys. (`handler` can be a path or a
* function.)
*
* @note If you pass a function directly, it will only run in development mode.
*
* @example
* ```js
* serverMiddleware: [
* // Will register redirect-ssl npm package
* 'redirect-ssl',
* // Will register file from project server-middleware directory to handle /server-middleware/* requires
* { path: '/server-middleware', handler: '~/server-middleware/index.js' },
* // We can create custom instances too, but only in development mode, they are ignored for the production bundle.
* { path: '/static2', handler: serveStatic(fileURLToPath(new URL('./static2', import.meta.url))) }
* ]
* ```
*
* @note If you don't want middleware to run on all routes you should use the object
* form with a specific path.
*
* If you pass a string handler, Nuxt will expect that file to export a default function
* that handles `(req, res, next) => void`.
*
* @example
* ```js
* export default function (req, res, next) {
* // req is the Node.js http request object
* console.log(req.url)
* // res is the Node.js http response object
* // next is a function to call to invoke the next middleware
* // Don't forget to call next at the end if your middleware is not an endpoint!
* next()
* }
* ```
*
* Alternatively, it can export a connect/express/h3-type app instance.
* @example
* ```js
* import bodyParser from 'body-parser'
* import createApp from 'express'
* const app = createApp()
* app.use(bodyParser.json())
* app.all('/getJSON', (req, res) => {
* res.json({ data: 'data' })
* })
* export default app
* ```
*
* Alternatively, instead of passing an array of `serverMiddleware`, you can pass an object
* whose keys are the paths and whose values are the handlers (string or function).
* @example
* ```js
* export default {
* serverMiddleware: {
* '/a': '~/server-middleware/a.js',
* '/b': '~/server-middleware/b.js',
* '/c': '~/server-middleware/c.js'
* }
* }
* ```
* @version 2
* @version 3
*/
serverMiddleware: {
$resolve: (val: any) => {
if (!val) {
return []
}
if (!Array.isArray(val)) {
return Object.entries(val).map(([path, handler]) => ({ path, handler }))
}
return val
}
},
/**
* Used to set the modules directories for path resolving (for example, webpack's
* `resolveLoading`, `nodeExternals` and `postcss`).
*
* The configuration path is relative to `options.rootDir` (default is current working directory).
*
* Setting this field may be necessary if your project is organized as a yarn workspace-styled mono-repository.
*
* @example
* ```js
* export default {
* modulesDir: ['../../node_modules']
* }
* ```
* @version 2
*/
modulesDir: {
$default: ['node_modules'],
$resolve: (val, get) => [].concat(
val.map(dir => resolve(get('rootDir'), dir)),
resolve(process.cwd(), 'node_modules')
)
},
/**
* Customize default directory structure used by nuxt.
*
* It is better to stick with defaults unless needed.
* @version 2
* @version 3
*/
dir: {
/**
* The assets directory (aliased as `~assets` in your build)
* @version 2
*/
assets: 'assets',
/**
* The directory containing app template files like `app.html` and `router.scrollBehavior.js`
* @version 2
*/
app: 'app',
/**
* The layouts directory, each file of which will be auto-registered as a Nuxt layout.
* @version 2
* @version 3
*/
layouts: 'layouts',
/**
* The middleware directory, each file of which will be auto-registered as a Nuxt middleware.
* @version 3
* @version 2
*/
middleware: 'middleware',
/**
* The directory which will be processed to auto-generate your application page routes.
* @version 2
* @version 3
*/
pages: 'pages',
/**
* The directory containing your static files, which will be directly accessible via the Nuxt server
* and copied across into your `dist` folder when your app is generated.
* @version 3
*/
public: {
$resolve: (val, get) => val || get('dir.static') || 'public',
},
/** @version 2 */
static: {
$schema: { deprecated: 'use `dir.public` option instead' },
$resolve: (val, get) => val || get('dir.public') || 'public',
},
/**
* The folder which will be used to auto-generate your Vuex store structure.
* @version 2
*/
store: 'store'
},
/**
* The extensions that should be resolved by the Nuxt resolver.
* @version 2
* @version 3
*/
extensions: {
$resolve: val => ['.js', '.jsx', '.mjs', '.ts', '.tsx', '.vue'].concat(val).filter(Boolean)
},
/**
* The style extensions that should be resolved by the Nuxt resolver (for example, in `css` property).
* @version 2
*/
styleExtensions: ['.css', '.pcss', '.postcss', '.styl', '.stylus', '.scss', '.sass', '.less'],
/**
* You can improve your DX by defining additional aliases to access custom directories
* within your JavaScript and CSS.
*
* @note Within a webpack context (image sources, CSS - but not JavaScript) you _must_ access
* your alias by prefixing it with `~`.
*
* @note These aliases will be automatically added to the generated `.nuxt/tsconfig.json` so you can get full
* type support and path auto-complete. In case you need to extend options provided by `./.nuxt/tsconfig.json`
* further, make sure to add them here or within the `typescript.tsConfig` property in `nuxt.config`.
*
* @example
* ```js
* export default {
* alias: {
* 'images': fileURLToPath(new URL('./assets/images', import.meta.url),
* 'style': fileURLToPath(new URL('./assets/style', import.meta.url),
* 'data': fileURLToPath(new URL('./assets/other/data', import.meta.url)
* }
* }
* ```
*
* ```html
* <template>
* <img src="~images/main-bg.jpg">
* </template>
*
* <script>
* import data from 'data/test.json'
* </script>
*
* <style>
* // Uncomment the below
* //@import '~style/variables.scss';
* //@import '~style/utils.scss';
* //@import '~style/base.scss';
* body {
* background-image: url('~images/main-bg.jpg');
* }
* </style>
* ```
*
* @type {Record<string, string>}
* @version 2
* @version 3
*/
alias: {
$resolve: (val, get) => ({
'~~': get('rootDir'),
'@@': get('rootDir'),
'~': get('srcDir'),
'@': get('srcDir'),
[get('dir.assets')]: join(get('srcDir'), get('dir.assets')),
[get('dir.public')]: join(get('srcDir'), get('dir.public')),
...val
})
},
/**
* Pass options directly to `node-ignore` (which is used by Nuxt to ignore files).
*
* @see [node-ignore](https://github.com/kaelzhang/node-ignore)
*
* @example
* ```js
* ignoreOptions: {
* ignorecase: false
* }
* ```
* @version 2
* @version 3
*/
ignoreOptions: undefined,
/**
* Any file in `pages/`, `layouts/`, `middleware/` or `store/` will be ignored during
* building if its filename starts with the prefix specified by `ignorePrefix`.
* @version 2
* @version 3
*/
ignorePrefix: '-',
/**
* More customizable than `ignorePrefix`: all files matching glob patterns specified
* inside the `ignore` array will be ignored in building.
* @version 2
* @version 3
*/
ignore: {
$resolve: (val, get) => [
'**/*.stories.{js,ts,jsx,tsx}', // ignore storybook files
'**/*.{spec,test}.{js,ts,jsx,tsx}', // ignore tests
'.output',
get('ignorePrefix') && `**/${get('ignorePrefix')}*.*`
].concat(val).filter(Boolean)
},
/**
* The watch property lets you watch custom files for restarting the server.
*
* `chokidar` is used to set up the watchers. To learn more about its pattern
* options, see chokidar documentation.
*
* @see [chokidar](https://github.com/paulmillr/chokidar#api)
*
* @example
* ```js
* watch: ['~/custom/*.js']
* ```
* @type {string[]}
* @version 2
*/
watch: {
$resolve: (val, get) => {
const rootDir = get('rootDir')
return Array.from(new Set([].concat(val, get('_nuxtConfigFiles'))
.filter(Boolean).map(p => resolve(rootDir, p))
))
}
},
/**
* The watchers property lets you overwrite watchers configuration in your `nuxt.config`.
* @version 2
* @version 3
*/
watchers: {
/** An array of event types, which, when received, will cause the watcher to restart. */
rewatchOnRawEvents: undefined,
/**
* `watchOptions` to pass directly to webpack.
*
* @see [webpack@4 watch options](https://v4.webpack.js.org/configuration/watch/#watchoptions).
* */
webpack: {
aggregateTimeout: 1000
},
/**
* Options to pass directly to `chokidar`.
*
* @see [chokidar](https://github.com/paulmillr/chokidar#api)
*/
chokidar: {
ignoreInitial: true
}
},
/**
* Your preferred code editor to launch when debugging.
*
* @see [documentation](https://github.com/yyx990803/launch-editor#supported-editors)
* @type {string}
* @version 2
*/
editor: undefined,
/**
* Hooks are listeners to Nuxt events that are typically used in modules,
* but are also available in `nuxt.config`.
*
* Internally, hooks follow a naming pattern using colons (e.g., build:done).
*
* For ease of configuration, you can also structure them as an hierarchical
* object in `nuxt.config` (as below).
*
* @example
* ```js'node:fs'
* import fs from 'node:fs'
* import path from 'node:path'
* export default {
* hooks: {
* build: {
* done(builder) {
* const extraFilePath = path.join(
* builder.nuxt.options.buildDir,
* 'extra-file'
* )
* fs.writeFileSync(extraFilePath, 'Something extra')
* }
* }
* }
* }
* ```
* @version 2
* @version 3
* @type {typeof import('../src/types/hooks').NuxtHooks}
*/
hooks: null,
/**
* Runtime config allows passing dynamic config and environment variables to the Nuxt app context.
*
* The value of this object is accessible from server only using `useRuntimeConfig`.
*
* It mainly should hold _private_ configuration which is not exposed on the frontend.
* This could include a reference to your API secret tokens.
*
* Anything under `public` and `app` will be exposed to the frontend as well.
*
* Values are automatically replaced by matching env variables at runtime, e.g. setting an environment
* variable `API_KEY=my-api-key PUBLIC_BASE_URL=/foo/` would overwrite the two values in the example below.
*
* @example
* ```js
* export default {
* runtimeConfig: {
* apiKey: '' // Default to an empty string, automatically loaded at runtime using process.env.NUXT_API_SECRET
* public: {
* baseURL: '' // Exposed to the frontend as well.
* }
* }
* }
* ```
* @type {typeof import('../src/types/config').RuntimeConfig}
* @version 3
*/
runtimeConfig: {
$resolve: (val: RuntimeConfig, get) => defu(val, {
...get('publicRuntimeConfig'),
...get('privateRuntimeConfig'),
public: get('publicRuntimeConfig'),
app: {
baseURL: get('app.baseURL'),
buildAssetsDir: get('app.buildAssetsDir'),
cdnURL: get('app.cdnURL'),
}
})
},
/**
* @type {typeof import('../src/types/config').PrivateRuntimeConfig}
* @version 2
* @version 3
* @deprecated Use `runtimeConfig` option
*/
privateRuntimeConfig: {},
/**
* @type {typeof import('../src/types/config').PublicRuntimeConfig}
* @version 2
* @version 3
* @deprecated Use `runtimeConfig` option with `public` key (`runtimeConfig.public.*`)
*/
publicRuntimeConfig: {}
}
| packages/schema/src/config/_common.ts | 1 | https://github.com/nuxt/nuxt/commit/71b808c8e96ae8bdbe4440f16d96f7242f864843 | [
0.03585483878850937,
0.0019188296282663941,
0.0001629516191314906,
0.00017070806643459946,
0.005340534262359142
] |
{
"id": 1,
"code_window": [
" * }\n",
" * ```\n",
" * @version 2\n",
" */\n",
" publicPath: {\n",
" $resolve: (val, get) => val ? withTrailingSlash(normalizeURL(val)) : get('app.buildAssetsDir')\n",
" },\n",
"\n",
" /**\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" $resolve: (val, get) => val ? withTrailingSlash(normalizeURL(val)) : get('app').buildAssetsDir\n"
],
"file_path": "packages/schema/src/config/build.ts",
"type": "replace",
"edit_start_line_idx": 194
} | import { pathToFileURL } from 'node:url'
import { createUnplugin } from 'unplugin'
import { parseQuery, parseURL } from 'ufo'
import { Component } from '@nuxt/schema'
import { genDynamicImport, genImport } from 'knitwork'
import MagicString from 'magic-string'
import { pascalCase } from 'scule'
interface LoaderOptions {
getComponents(): Component[]
}
export const loaderPlugin = createUnplugin((options: LoaderOptions) => ({
name: 'nuxt:components-loader',
enforce: 'post',
transformInclude (id) {
const { pathname, search } = parseURL(decodeURIComponent(pathToFileURL(id).href))
const query = parseQuery(search)
// we only transform render functions
// from `type=template` (in Webpack) and bare `.vue` file (in Vite)
return pathname.endsWith('.vue') && (query.type === 'template' || !!query.macro || !search)
},
transform (code, id) {
return transform(code, id, options.getComponents())
}
}))
function findComponent (components: Component[], name: string) {
const id = pascalCase(name).replace(/["']/g, '')
return components.find(component => id === component.pascalName)
}
function transform (code: string, id: string, components: Component[]) {
let num = 0
const imports = new Set<string>()
const map = new Map<Component, string>()
const s = new MagicString(code)
// replace `_resolveComponent("...")` to direct import
s.replace(/(?<=[ (])_?resolveComponent\(["'](lazy-|Lazy)?([^'"]*?)["']\)/g, (full, lazy, name) => {
const component = findComponent(components, name)
if (component) {
const identifier = map.get(component) || `__nuxt_component_${num++}`
map.set(component, identifier)
if (lazy) {
// Nuxt will auto-import `defineAsyncComponent` for us
imports.add(`const ${identifier}_lazy = defineAsyncComponent(${genDynamicImport(component.filePath)})`)
return `${identifier}_lazy`
} else {
imports.add(genImport(component.filePath, [{ name: component.export, as: identifier }]))
return identifier
}
}
// no matched
return full
})
if (imports.size) {
s.prepend([...imports, ''].join('\n'))
}
if (s.hasChanged()) {
return {
code: s.toString(),
map: s.generateMap({ source: id, includeContent: true })
}
}
}
| packages/nuxt3/src/components/loader.ts | 0 | https://github.com/nuxt/nuxt/commit/71b808c8e96ae8bdbe4440f16d96f7242f864843 | [
0.0001755548146320507,
0.00017242669127881527,
0.00016992195742204785,
0.0001725208858260885,
0.0000022524877749674488
] |
{
"id": 1,
"code_window": [
" * }\n",
" * ```\n",
" * @version 2\n",
" */\n",
" publicPath: {\n",
" $resolve: (val, get) => val ? withTrailingSlash(normalizeURL(val)) : get('app.buildAssetsDir')\n",
" },\n",
"\n",
" /**\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" $resolve: (val, get) => val ? withTrailingSlash(normalizeURL(val)) : get('app').buildAssetsDir\n"
],
"file_path": "packages/schema/src/config/build.ts",
"type": "replace",
"edit_start_line_idx": 194
} |
// Types
import './types/global'
export * from './types/compatibility'
export * from './types/components'
export * from './types/config'
export * from './types/hooks'
export * from './types/imports'
export * from './types/meta'
export * from './types/module'
export * from './types/nuxt'
export * from './types/router'
// Schema
export { default as NuxtConfigSchema } from './config/index'
| packages/schema/src/index.ts | 0 | https://github.com/nuxt/nuxt/commit/71b808c8e96ae8bdbe4440f16d96f7242f864843 | [
0.00017459709488321096,
0.0001721556473057717,
0.0001697142142802477,
0.0001721556473057717,
0.0000024414403014816344
] |
{
"id": 1,
"code_window": [
" * }\n",
" * ```\n",
" * @version 2\n",
" */\n",
" publicPath: {\n",
" $resolve: (val, get) => val ? withTrailingSlash(normalizeURL(val)) : get('app.buildAssetsDir')\n",
" },\n",
"\n",
" /**\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" $resolve: (val, get) => val ? withTrailingSlash(normalizeURL(val)) : get('app').buildAssetsDir\n"
],
"file_path": "packages/schema/src/config/build.ts",
"type": "replace",
"edit_start_line_idx": 194
} | <template>
<div>
You've landed on a page that wasn't in the menu!
</div>
</template>
<script setup>
definePageMeta({
middleware: 'named-test'
})
</script>
| examples/routing/middleware/pages/secret.vue | 0 | https://github.com/nuxt/nuxt/commit/71b808c8e96ae8bdbe4440f16d96f7242f864843 | [
0.00016933564620558172,
0.00016814030823297799,
0.00016694495570845902,
0.00016814030823297799,
0.0000011953452485613525
] |
{
"id": 2,
"code_window": [
" /**\n",
" * The full path to the directory underneath `/_nuxt/` where static assets\n",
" * (payload, state and manifest files) will live.\n",
" */\n",
" base: { $resolve: (val, get) => val || joinURL(get('app.buildAssetsDir'), get('generate.dir')) },\n",
" /** The full path to the versioned directory where static assets for the current buidl are located. */\n",
" versionBase: { $resolve: (val, get) => val || joinURL(get('generate.base'), get('generate.version')) },\n",
" /** A unique string to uniquely identify payload versions (defaults to the current timestamp). */\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" base: { $resolve: (val, get) => val || joinURL(get('app').buildAssetsDir, get('generate.dir')) },\n"
],
"file_path": "packages/schema/src/config/generate.ts",
"type": "replace",
"edit_start_line_idx": 162
} | import { resolve } from 'pathe'
import { joinURL } from 'ufo'
/**
* @version 2
*/
export default {
/**
* Directory name that holds all the assets and generated pages for a `static` build.
*/
dir: {
$resolve: (val = 'dist', get) => resolve(get('rootDir'), val)
},
/**
* The routes to generate.
*
* If you are using the crawler, this will be only the starting point for route generation.
* This is often necessary when using dynamic routes.
*
* It can be an array or a function.
*
* @example
* ```js
* routes: ['/users/1', '/users/2', '/users/3']
* ```
*
* You can pass a function that returns a promise or a function that takes a callback. It should
* return an array of strings or objects with `route` and (optional) `payload` keys.
*
* @example
* ```js
* export default {
* generate: {
* async routes() {
* const res = await axios.get('https://my-api/users')
* return res.data.map(user => ({ route: '/users/' + user.id, payload: user }))
* }
* }
* }
* ```
* Or instead:
* ```js
* export default {
* generate: {
* routes(callback) {
* axios
* .get('https://my-api/users')
* .then(res => {
* const routes = res.data.map(user => '/users/' + user.id)
* callback(null, routes)
* })
* .catch(callback)
* }
* }
* }
* ```
*
* If `routes()` returns a payload, it can be accessed from the Nuxt context.
* @example
* ```js
* export default {
* async useAsyncData ({ params, error, payload }) {
* if (payload) return { user: payload }
* else return { user: await backend.fetchUser(params.id) }
* }
* }
* ```
*/
routes: [],
/**
* An array of string or regular expressions that will prevent generation
* of routes matching them. The routes will still be accessible when `fallback` is set.
*/
exclude: [],
/** The number of routes that are generated concurrently in the same thread. */
concurrency: 500,
/**
* Interval in milliseconds between two render cycles to avoid flooding a potential
* API with calls.
*/
interval: 0,
/**
* Set to `false` to disable creating a directory + `index.html` for each route.
*
* @example
* ```bash
* # subFolders: true
* -| dist/
* ---| index.html
* ---| about/
* -----| index.html
* ---| products/
* -----| item/
* -------| index.html
*
* # subFolders: false
* -| dist/
* ---| index.html
* ---| about.html
* ---| products/
* -----| item.html
* ```
*/
subFolders: true,
/**
* The path to the fallback HTML file.
*
* Set this as the error page in your static server configuration, so that unknown
* routes can be rendered (on the client-side) by Nuxt.
*
* * If unset or set to a falsy value, the name of the fallback HTML file will be `200.html`.
* * If set to true, the filename will be `404.html`.
* * If you provide a string as a value, it will be used instead.
*
* @note Multiple services (e.g. Netlify) detect a `404.html` automatically. If
* you configure your web server on your own, please consult its documentation
* to find out how to set up an error page (and set it to the 404.html file)
*/
fallback: { $resolve: val => val === true ? '400.html' : (val || '200.html') },
/**
* Set to `false` to disable generating pages discovered through crawling relative
* links in generated pages.
*/
crawler: true,
/** Set to `false` to disable generating a `manifest.js` with a list of all generated pages. */
manifest: true,
/** Set to `false` to disable generating a `.nojekyll` file (which aids compatibility with GitHub Pages). */
nojekyll: true,
/**
* Configure the cache (used with `static` target to avoid rebuilding when no files have changed).
*
* Set to `false` to disable completely.
*/
cache: {
/** An array of files or directories to ignore. (It can also be a function that returns an array.) */
ignore: [],
/**
* Options to pass to [`globby`](https://github.com/sindresorhus/globby), which
* is used to generate a 'snapshot' of the source files.
*/
globbyOptions: {
gitignore: true
}
},
staticAssets: {
/** The directory underneath `/_nuxt/`, where static assets (payload, state and manifest files) will live. */
dir: 'static',
/**
* The full path to the directory underneath `/_nuxt/` where static assets
* (payload, state and manifest files) will live.
*/
base: { $resolve: (val, get) => val || joinURL(get('app.buildAssetsDir'), get('generate.dir')) },
/** The full path to the versioned directory where static assets for the current buidl are located. */
versionBase: { $resolve: (val, get) => val || joinURL(get('generate.base'), get('generate.version')) },
/** A unique string to uniquely identify payload versions (defaults to the current timestamp). */
version: { $resolve: val => val || (String(Math.round(Date.now() / 1000))) }
}
}
| packages/schema/src/config/generate.ts | 1 | https://github.com/nuxt/nuxt/commit/71b808c8e96ae8bdbe4440f16d96f7242f864843 | [
0.9972673654556274,
0.05888959392905235,
0.0001629421312827617,
0.00016932241851463914,
0.23459453880786896
] |
{
"id": 2,
"code_window": [
" /**\n",
" * The full path to the directory underneath `/_nuxt/` where static assets\n",
" * (payload, state and manifest files) will live.\n",
" */\n",
" base: { $resolve: (val, get) => val || joinURL(get('app.buildAssetsDir'), get('generate.dir')) },\n",
" /** The full path to the versioned directory where static assets for the current buidl are located. */\n",
" versionBase: { $resolve: (val, get) => val || joinURL(get('generate.base'), get('generate.version')) },\n",
" /** A unique string to uniquely identify payload versions (defaults to the current timestamp). */\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" base: { $resolve: (val, get) => val || joinURL(get('app').buildAssetsDir, get('generate.dir')) },\n"
],
"file_path": "packages/schema/src/config/generate.ts",
"type": "replace",
"edit_start_line_idx": 162
} | import { NuxtApp } from '../nuxt'
declare global {
namespace NodeJS {
interface Process {
browser: boolean
client: boolean
dev: boolean
mode: 'spa' | 'universal'
server: boolean
static: boolean
}
}
interface Window {
__NUXT__?: Record<string, any>
}
}
declare module '@vue/runtime-core' {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
interface App<HostElement> {
$nuxt: NuxtApp
}
interface ComponentInternalInstance {
_nuxtOnBeforeMountCbs: Function[]
}
}
| packages/nuxt3/src/app/types/augments.d.ts | 0 | https://github.com/nuxt/nuxt/commit/71b808c8e96ae8bdbe4440f16d96f7242f864843 | [
0.0002832634199876338,
0.0002057945093838498,
0.0001669105695327744,
0.00016720955318305641,
0.00005477892409544438
] |
{
"id": 2,
"code_window": [
" /**\n",
" * The full path to the directory underneath `/_nuxt/` where static assets\n",
" * (payload, state and manifest files) will live.\n",
" */\n",
" base: { $resolve: (val, get) => val || joinURL(get('app.buildAssetsDir'), get('generate.dir')) },\n",
" /** The full path to the versioned directory where static assets for the current buidl are located. */\n",
" versionBase: { $resolve: (val, get) => val || joinURL(get('generate.base'), get('generate.version')) },\n",
" /** A unique string to uniquely identify payload versions (defaults to the current timestamp). */\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" base: { $resolve: (val, get) => val || joinURL(get('app').buildAssetsDir, get('generate.dir')) },\n"
],
"file_path": "packages/schema/src/config/generate.ts",
"type": "replace",
"edit_start_line_idx": 162
} | {
"extends": "./.nuxt/tsconfig.json"
}
| examples/experimental/vite-node/tsconfig.json | 0 | https://github.com/nuxt/nuxt/commit/71b808c8e96ae8bdbe4440f16d96f7242f864843 | [
0.00016679395048413426,
0.00016679395048413426,
0.00016679395048413426,
0.00016679395048413426,
0
] |
{
"id": 2,
"code_window": [
" /**\n",
" * The full path to the directory underneath `/_nuxt/` where static assets\n",
" * (payload, state and manifest files) will live.\n",
" */\n",
" base: { $resolve: (val, get) => val || joinURL(get('app.buildAssetsDir'), get('generate.dir')) },\n",
" /** The full path to the versioned directory where static assets for the current buidl are located. */\n",
" versionBase: { $resolve: (val, get) => val || joinURL(get('generate.base'), get('generate.version')) },\n",
" /** A unique string to uniquely identify payload versions (defaults to the current timestamp). */\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" base: { $resolve: (val, get) => val || joinURL(get('app').buildAssetsDir, get('generate.dir')) },\n"
],
"file_path": "packages/schema/src/config/generate.ts",
"type": "replace",
"edit_start_line_idx": 162
} | {
"compilerOptions": {
"esModuleInterop": true,
"skipLibCheck": true,
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "Node",
"strict": false,
"allowJs": true,
"noUnusedLocals": true,
"resolveJsonModule": true,
"types": [
"node"
]
}
}
| docs/tsconfig.json | 0 | https://github.com/nuxt/nuxt/commit/71b808c8e96ae8bdbe4440f16d96f7242f864843 | [
0.0001696355757303536,
0.00016860419418662786,
0.00016757282719481736,
0.00016860419418662786,
0.0000010313742677681148
] |
{
"id": 3,
"code_window": [
" * This can be useful if you need to serve Nuxt as a different context root, from\n",
" * within a bigger web site.\n",
" * @version 2\n",
" */\n",
" base: {\n",
" $resolve: (val, get) => val ? withTrailingSlash(normalizeURL(val)) : get('app.baseURL')\n",
" },\n",
"\n",
" /** @private */\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" $resolve: (val, get) => val ? withTrailingSlash(normalizeURL(val)) : get('app').baseURL\n"
],
"file_path": "packages/schema/src/config/router.ts",
"type": "replace",
"edit_start_line_idx": 35
} | import { join, resolve } from 'pathe'
import { isDevelopment } from 'std-env'
import createRequire from 'create-require'
import { pascalCase } from 'scule'
import jiti from 'jiti'
import defu from 'defu'
import { RuntimeConfig } from '../types/config'
export default {
/**
* Extend nested configurations from multiple local or remote sources
*
* Value should be either a string or array of strings pointing to source directories or config path relative to current config.
*
* You can use `github:`, `gitlab:`, `bitbucket:` or `https://` to extend from a remote git repository.
*
* @type {string|string[]}
*
* @version 3
*/
extends: null,
/**
* Define the workspace directory of your application.
*
* This property can be overwritten (for example, running `nuxt ./my-app/`
* will set the `rootDir` to the absolute path of `./my-app/` from the
* current/working directory.
*
* It is normally not needed to configure this option.
* @version 2
* @version 3
*/
rootDir: {
$resolve: val => typeof val === 'string' ? resolve(val) : process.cwd()
},
/**
* Define the source directory of your Nuxt application.
*
* If a relative path is specified it will be relative to the `rootDir`.
*
* @example
* ```js
* export default {
* srcDir: 'client/'
* }
* ```
* This would work with the following folder structure:
* ```bash
* -| app/
* ---| node_modules/
* ---| nuxt.config.js
* ---| package.json
* ---| client/
* ------| assets/
* ------| components/
* ------| layouts/
* ------| middleware/
* ------| pages/
* ------| plugins/
* ------| static/
* ------| store/
* ```
* @version 2
* @version 3
*/
srcDir: {
$resolve: (val, get) => resolve(get('rootDir'), val || '.')
},
/**
* Define the directory where your built Nuxt files will be placed.
*
* Many tools assume that `.nuxt` is a hidden directory (because it starts
* with a `.`). If that is a problem, you can use this option to prevent that.
*
* @example
* ```js
* export default {
* buildDir: 'nuxt-build'
* }
* ```
* @version 2
* @version 3
*/
buildDir: {
$resolve: (val, get) => resolve(get('rootDir'), val || '.nuxt')
},
/**
* Whether Nuxt is running in development mode.
*
* Normally you should not need to set this.
* @version 2
* @version 3
*/
dev: Boolean(isDevelopment),
/**
* Whether your app is being unit tested
* @version 2
*/
test: Boolean(isDevelopment),
/**
* Set to true to enable debug mode.
*
* By default it's only enabled in development mode.
* @version 2
*/
debug: {
$resolve: (val, get) => val ?? get('dev')
},
/**
* The env property defines environment variables that should be available
* throughout your app (server- and client-side). They can be assigned using
* server side environment variables.
*
* @note Nuxt uses webpack's `definePlugin` to define these environment variables.
* This means that the actual `process` or `process.env` from Node.js is neither
* available nor defined. Each of the `env` properties defined here is individually
* mapped to `process.env.xxxx` and converted during compilation.
*
* @note Environment variables starting with `NUXT_ENV_` are automatically injected
* into the process environment.
*
* @version 2
*/
env: {
$default: {},
$resolve: (val) => {
val = { ...val }
for (const key in process.env) {
if (key.startsWith('NUXT_ENV_')) {
val[key] = process.env[key]
}
}
return val
}
},
/**
* Set the method Nuxt uses to require modules, such as loading `nuxt.config`, server
* middleware, and so on - defaulting to `jiti` (which has support for TypeScript and ESM syntax).
*
* @see [jiti](https://github.com/unjs/jiti)
* @type {'jiti' | 'native' | ((p: string | { filename: string }) => NodeRequire)}
* @version 2
*/
createRequire: {
$resolve: (val: any) => {
val = process.env.NUXT_CREATE_REQUIRE || val ||
(typeof globalThis.jest !== 'undefined' ? 'native' : 'jiti')
if (val === 'jiti') {
return p => jiti(typeof p === 'string' ? p : p.filename)
}
if (val === 'native') {
return p => createRequire(typeof p === 'string' ? p : p.filename)
}
return val
}
},
/**
* Whether your Nuxt app should be built to be served by the Nuxt server (`server`)
* or as static HTML files suitable for a CDN or other static file server (`static`).
*
* This is unrelated to `ssr`.
* @type {'server' | 'static'}
* @version 2
*/
target: {
$resolve: val => ['server', 'static'].includes(val) ? val : 'server'
},
/**
* Whether to enable rendering of HTML - either dynamically (in server mode) or at generate time.
* If set to `false` and combined with `static` target, generated pages will simply display
* a loading screen with no content.
* @version 2
* @version 3
*/
ssr: true,
/**
* @deprecated use ssr option
*/
mode: {
$resolve: (val, get) => val || (get('ssr') ? 'spa' : 'universal'),
$schema: { deprecated: '`mode` option is deprecated' }
},
/**
* Whether to produce a separate modern build targeting browsers that support ES modules.
*
* Set to `'server'` to enable server mode, where the Nuxt server checks
* browser version based on the user agent and serves the correct bundle.
*
* Set to `'client'` to serve both the modern bundle with `<script type="module">`
* and the legacy bundle with `<script nomodule>`. It will also provide a
* `<link rel="modulepreload">` for the modern bundle. Every browser that understands
* the module type will load the modern bundle while older browsers fall back to the
* legacy (transpiled) bundle.
*
* If you have set `modern: true` and are generating your app or have `ssr: false`,
* modern will be set to `'client'`.
*
* If you have set `modern: true` and are serving your app, modern will be set to `'server'`.
*
* @see [concept of modern mode](https://philipwalton.com/articles/deploying-es2015-code-in-production-today/)
* @type {'server' | 'client' | boolean}
* @version 2
*/
modern: undefined,
/**
* Modules are Nuxt extensions which can extend its core functionality and add endless integrations
*
* Each module is either a string (which can refer to a package, or be a path to a file), a
* tuple with the module as first string and the options as a second object, or an inline module function.
*
* Nuxt tries to resolve each item in the modules array using node require path
* (in `node_modules`) and then will be resolved from project `srcDir` if `~` alias is used.
*
* @note Modules are executed sequentially so the order is important.
*
* @example
* ```js
* modules: [
* // Using package name
* '@nuxtjs/axios',
* // Relative to your project srcDir
* '~/modules/awesome.js',
* // Providing options
* ['@nuxtjs/google-analytics', { ua: 'X1234567' }],
* // Inline definition
* function () {}
* ]
* ```
* @type {(typeof import('../src/types/module').NuxtModule | string | [typeof import('../src/types/module').NuxtModule | string, Record<string, any>])[]}
* @version 2
* @version 3
*/
modules: [],
/**
* Modules that are only required during development and build time.
*
* Modules are Nuxt extensions which can extend its core functionality and add endless integrations
*
* Each module is either a string (which can refer to a package, or be a path to a file), a
* tuple with the module as first string and the options as a second object, or an inline module function.
*
* Nuxt tries to resolve each item in the modules array using node require path
* (in `node_modules`) and then will be resolved from project `srcDir` if `~` alias is used.
*
* @note Modules are executed sequentially so the order is important.
*
* @example
* ```js
* modules: [
* // Using package name
* '@nuxtjs/axios',
* // Relative to your project srcDir
* '~/modules/awesome.js',
* // Providing options
* ['@nuxtjs/google-analytics', { ua: 'X1234567' }],
* // Inline definition
* function () {}
* ]
* ```
*
* @note In Nuxt 2, using `buildModules` helps to make production startup faster and also significantly
* decreases the size of `node_modules` in production deployments. Please refer to each
* module's documentation to see if it is recommended to use `modules` or `buildModules`.
*
* @type {(typeof import('../src/types/module').NuxtModule | string | [typeof import('../src/types/module').NuxtModule | string, Record<string, any>])[]}
* @version 2
* @deprecated This is no longer needed in Nuxt 3 and Nuxt Bridge; all modules should be added to `modules` instead.
*/
buildModules: [],
/**
* Built-in ad-hoc modules
*
* @private
*/
_modules: [],
/**
* Installed module metadata
*
* @version 3
* @private
*/
_installedModules: [],
/**
* Allows customizing the global ID used in the main HTML template as well as the main
* Vue instance name and other options.
* @version 2
*/
globalName: {
$resolve: val => (typeof val === 'string' && /^[a-zA-Z]+$/.test(val)) ? val.toLocaleLowerCase() : 'nuxt'
},
/**
* Customizes specific global names (they are based on `globalName` by default).
* @version 2
*/
globals: {
/** @type {(globalName: string) => string} */
id: globalName => `__${globalName}`,
/** @type {(globalName: string) => string} */
nuxt: globalName => `$${globalName}`,
/** @type {(globalName: string) => string} */
context: globalName => `__${globalName.toUpperCase()}__`,
/** @type {(globalName: string) => string} */
pluginPrefix: globalName => globalName,
/** @type {(globalName: string) => string} */
readyCallback: globalName => `on${pascalCase(globalName)}Ready`,
/** @type {(globalName: string) => string} */
loadedCallback: globalName => `_on${pascalCase(globalName)}Loaded`
},
/**
* Server middleware are connect/express/h3-shaped functions that handle server-side requests. They
* run on the server and before the Vue renderer.
*
* By adding entries to `serverMiddleware` you can register additional routes without the need
* for an external server.
*
* You can pass a string, which can be the name of a node dependency or a path to a file. You
* can also pass an object with `path` and `handler` keys. (`handler` can be a path or a
* function.)
*
* @note If you pass a function directly, it will only run in development mode.
*
* @example
* ```js
* serverMiddleware: [
* // Will register redirect-ssl npm package
* 'redirect-ssl',
* // Will register file from project server-middleware directory to handle /server-middleware/* requires
* { path: '/server-middleware', handler: '~/server-middleware/index.js' },
* // We can create custom instances too, but only in development mode, they are ignored for the production bundle.
* { path: '/static2', handler: serveStatic(fileURLToPath(new URL('./static2', import.meta.url))) }
* ]
* ```
*
* @note If you don't want middleware to run on all routes you should use the object
* form with a specific path.
*
* If you pass a string handler, Nuxt will expect that file to export a default function
* that handles `(req, res, next) => void`.
*
* @example
* ```js
* export default function (req, res, next) {
* // req is the Node.js http request object
* console.log(req.url)
* // res is the Node.js http response object
* // next is a function to call to invoke the next middleware
* // Don't forget to call next at the end if your middleware is not an endpoint!
* next()
* }
* ```
*
* Alternatively, it can export a connect/express/h3-type app instance.
* @example
* ```js
* import bodyParser from 'body-parser'
* import createApp from 'express'
* const app = createApp()
* app.use(bodyParser.json())
* app.all('/getJSON', (req, res) => {
* res.json({ data: 'data' })
* })
* export default app
* ```
*
* Alternatively, instead of passing an array of `serverMiddleware`, you can pass an object
* whose keys are the paths and whose values are the handlers (string or function).
* @example
* ```js
* export default {
* serverMiddleware: {
* '/a': '~/server-middleware/a.js',
* '/b': '~/server-middleware/b.js',
* '/c': '~/server-middleware/c.js'
* }
* }
* ```
* @version 2
* @version 3
*/
serverMiddleware: {
$resolve: (val: any) => {
if (!val) {
return []
}
if (!Array.isArray(val)) {
return Object.entries(val).map(([path, handler]) => ({ path, handler }))
}
return val
}
},
/**
* Used to set the modules directories for path resolving (for example, webpack's
* `resolveLoading`, `nodeExternals` and `postcss`).
*
* The configuration path is relative to `options.rootDir` (default is current working directory).
*
* Setting this field may be necessary if your project is organized as a yarn workspace-styled mono-repository.
*
* @example
* ```js
* export default {
* modulesDir: ['../../node_modules']
* }
* ```
* @version 2
*/
modulesDir: {
$default: ['node_modules'],
$resolve: (val, get) => [].concat(
val.map(dir => resolve(get('rootDir'), dir)),
resolve(process.cwd(), 'node_modules')
)
},
/**
* Customize default directory structure used by nuxt.
*
* It is better to stick with defaults unless needed.
* @version 2
* @version 3
*/
dir: {
/**
* The assets directory (aliased as `~assets` in your build)
* @version 2
*/
assets: 'assets',
/**
* The directory containing app template files like `app.html` and `router.scrollBehavior.js`
* @version 2
*/
app: 'app',
/**
* The layouts directory, each file of which will be auto-registered as a Nuxt layout.
* @version 2
* @version 3
*/
layouts: 'layouts',
/**
* The middleware directory, each file of which will be auto-registered as a Nuxt middleware.
* @version 3
* @version 2
*/
middleware: 'middleware',
/**
* The directory which will be processed to auto-generate your application page routes.
* @version 2
* @version 3
*/
pages: 'pages',
/**
* The directory containing your static files, which will be directly accessible via the Nuxt server
* and copied across into your `dist` folder when your app is generated.
* @version 3
*/
public: {
$resolve: (val, get) => val || get('dir.static') || 'public',
},
/** @version 2 */
static: {
$schema: { deprecated: 'use `dir.public` option instead' },
$resolve: (val, get) => val || get('dir.public') || 'public',
},
/**
* The folder which will be used to auto-generate your Vuex store structure.
* @version 2
*/
store: 'store'
},
/**
* The extensions that should be resolved by the Nuxt resolver.
* @version 2
* @version 3
*/
extensions: {
$resolve: val => ['.js', '.jsx', '.mjs', '.ts', '.tsx', '.vue'].concat(val).filter(Boolean)
},
/**
* The style extensions that should be resolved by the Nuxt resolver (for example, in `css` property).
* @version 2
*/
styleExtensions: ['.css', '.pcss', '.postcss', '.styl', '.stylus', '.scss', '.sass', '.less'],
/**
* You can improve your DX by defining additional aliases to access custom directories
* within your JavaScript and CSS.
*
* @note Within a webpack context (image sources, CSS - but not JavaScript) you _must_ access
* your alias by prefixing it with `~`.
*
* @note These aliases will be automatically added to the generated `.nuxt/tsconfig.json` so you can get full
* type support and path auto-complete. In case you need to extend options provided by `./.nuxt/tsconfig.json`
* further, make sure to add them here or within the `typescript.tsConfig` property in `nuxt.config`.
*
* @example
* ```js
* export default {
* alias: {
* 'images': fileURLToPath(new URL('./assets/images', import.meta.url),
* 'style': fileURLToPath(new URL('./assets/style', import.meta.url),
* 'data': fileURLToPath(new URL('./assets/other/data', import.meta.url)
* }
* }
* ```
*
* ```html
* <template>
* <img src="~images/main-bg.jpg">
* </template>
*
* <script>
* import data from 'data/test.json'
* </script>
*
* <style>
* // Uncomment the below
* //@import '~style/variables.scss';
* //@import '~style/utils.scss';
* //@import '~style/base.scss';
* body {
* background-image: url('~images/main-bg.jpg');
* }
* </style>
* ```
*
* @type {Record<string, string>}
* @version 2
* @version 3
*/
alias: {
$resolve: (val, get) => ({
'~~': get('rootDir'),
'@@': get('rootDir'),
'~': get('srcDir'),
'@': get('srcDir'),
[get('dir.assets')]: join(get('srcDir'), get('dir.assets')),
[get('dir.public')]: join(get('srcDir'), get('dir.public')),
...val
})
},
/**
* Pass options directly to `node-ignore` (which is used by Nuxt to ignore files).
*
* @see [node-ignore](https://github.com/kaelzhang/node-ignore)
*
* @example
* ```js
* ignoreOptions: {
* ignorecase: false
* }
* ```
* @version 2
* @version 3
*/
ignoreOptions: undefined,
/**
* Any file in `pages/`, `layouts/`, `middleware/` or `store/` will be ignored during
* building if its filename starts with the prefix specified by `ignorePrefix`.
* @version 2
* @version 3
*/
ignorePrefix: '-',
/**
* More customizable than `ignorePrefix`: all files matching glob patterns specified
* inside the `ignore` array will be ignored in building.
* @version 2
* @version 3
*/
ignore: {
$resolve: (val, get) => [
'**/*.stories.{js,ts,jsx,tsx}', // ignore storybook files
'**/*.{spec,test}.{js,ts,jsx,tsx}', // ignore tests
'.output',
get('ignorePrefix') && `**/${get('ignorePrefix')}*.*`
].concat(val).filter(Boolean)
},
/**
* The watch property lets you watch custom files for restarting the server.
*
* `chokidar` is used to set up the watchers. To learn more about its pattern
* options, see chokidar documentation.
*
* @see [chokidar](https://github.com/paulmillr/chokidar#api)
*
* @example
* ```js
* watch: ['~/custom/*.js']
* ```
* @type {string[]}
* @version 2
*/
watch: {
$resolve: (val, get) => {
const rootDir = get('rootDir')
return Array.from(new Set([].concat(val, get('_nuxtConfigFiles'))
.filter(Boolean).map(p => resolve(rootDir, p))
))
}
},
/**
* The watchers property lets you overwrite watchers configuration in your `nuxt.config`.
* @version 2
* @version 3
*/
watchers: {
/** An array of event types, which, when received, will cause the watcher to restart. */
rewatchOnRawEvents: undefined,
/**
* `watchOptions` to pass directly to webpack.
*
* @see [webpack@4 watch options](https://v4.webpack.js.org/configuration/watch/#watchoptions).
* */
webpack: {
aggregateTimeout: 1000
},
/**
* Options to pass directly to `chokidar`.
*
* @see [chokidar](https://github.com/paulmillr/chokidar#api)
*/
chokidar: {
ignoreInitial: true
}
},
/**
* Your preferred code editor to launch when debugging.
*
* @see [documentation](https://github.com/yyx990803/launch-editor#supported-editors)
* @type {string}
* @version 2
*/
editor: undefined,
/**
* Hooks are listeners to Nuxt events that are typically used in modules,
* but are also available in `nuxt.config`.
*
* Internally, hooks follow a naming pattern using colons (e.g., build:done).
*
* For ease of configuration, you can also structure them as an hierarchical
* object in `nuxt.config` (as below).
*
* @example
* ```js'node:fs'
* import fs from 'node:fs'
* import path from 'node:path'
* export default {
* hooks: {
* build: {
* done(builder) {
* const extraFilePath = path.join(
* builder.nuxt.options.buildDir,
* 'extra-file'
* )
* fs.writeFileSync(extraFilePath, 'Something extra')
* }
* }
* }
* }
* ```
* @version 2
* @version 3
* @type {typeof import('../src/types/hooks').NuxtHooks}
*/
hooks: null,
/**
* Runtime config allows passing dynamic config and environment variables to the Nuxt app context.
*
* The value of this object is accessible from server only using `useRuntimeConfig`.
*
* It mainly should hold _private_ configuration which is not exposed on the frontend.
* This could include a reference to your API secret tokens.
*
* Anything under `public` and `app` will be exposed to the frontend as well.
*
* Values are automatically replaced by matching env variables at runtime, e.g. setting an environment
* variable `API_KEY=my-api-key PUBLIC_BASE_URL=/foo/` would overwrite the two values in the example below.
*
* @example
* ```js
* export default {
* runtimeConfig: {
* apiKey: '' // Default to an empty string, automatically loaded at runtime using process.env.NUXT_API_SECRET
* public: {
* baseURL: '' // Exposed to the frontend as well.
* }
* }
* }
* ```
* @type {typeof import('../src/types/config').RuntimeConfig}
* @version 3
*/
runtimeConfig: {
$resolve: (val: RuntimeConfig, get) => defu(val, {
...get('publicRuntimeConfig'),
...get('privateRuntimeConfig'),
public: get('publicRuntimeConfig'),
app: {
baseURL: get('app.baseURL'),
buildAssetsDir: get('app.buildAssetsDir'),
cdnURL: get('app.cdnURL'),
}
})
},
/**
* @type {typeof import('../src/types/config').PrivateRuntimeConfig}
* @version 2
* @version 3
* @deprecated Use `runtimeConfig` option
*/
privateRuntimeConfig: {},
/**
* @type {typeof import('../src/types/config').PublicRuntimeConfig}
* @version 2
* @version 3
* @deprecated Use `runtimeConfig` option with `public` key (`runtimeConfig.public.*`)
*/
publicRuntimeConfig: {}
}
| packages/schema/src/config/_common.ts | 1 | https://github.com/nuxt/nuxt/commit/71b808c8e96ae8bdbe4440f16d96f7242f864843 | [
0.013071405701339245,
0.0010422199266031384,
0.00016366557974833995,
0.0001739942526910454,
0.0023955872748047113
] |
{
"id": 3,
"code_window": [
" * This can be useful if you need to serve Nuxt as a different context root, from\n",
" * within a bigger web site.\n",
" * @version 2\n",
" */\n",
" base: {\n",
" $resolve: (val, get) => val ? withTrailingSlash(normalizeURL(val)) : get('app.baseURL')\n",
" },\n",
"\n",
" /** @private */\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" $resolve: (val, get) => val ? withTrailingSlash(normalizeURL(val)) : get('app').baseURL\n"
],
"file_path": "packages/schema/src/config/router.ts",
"type": "replace",
"edit_start_line_idx": 35
} | <template>
<svg width="0.73em" height="1em" viewBox="0 0 256 351"><defs><filter
id="IconifyId-17c6fdde69b-f33216-99"
x="-50%"
y="-50%"
width="200%"
height="200%"
filterunits="objectBoundingBox"
><feGaussianBlur stddeviation="17.5" in="SourceAlpha" result="shadowBlurInner1" /><feOffset in="shadowBlurInner1" result="shadowOffsetInner1" /><feComposite
in="shadowOffsetInner1"
in2="SourceAlpha"
operator="arithmetic"
k2="-1"
k3="1"
result="shadowInnerInner1"
/><feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.06 0" in="shadowInnerInner1" /></filter><filter
id="IconifyId-17c6fdde69b-f33216-100"
x="-50%"
y="-50%"
width="200%"
height="200%"
filterunits="objectBoundingBox"
><feGaussianBlur stddeviation="3.5" in="SourceAlpha" result="shadowBlurInner1" /><feOffset dx="1" dy="-9" in="shadowBlurInner1" result="shadowOffsetInner1" /><feComposite
in="shadowOffsetInner1"
in2="SourceAlpha"
operator="arithmetic"
k2="-1"
k3="1"
result="shadowInnerInner1"
/><feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.09 0" in="shadowInnerInner1" /></filter><path id="IconifyId-17c6fdde69b-f33216-101" d="M1.253 280.732l1.605-3.131l99.353-188.518l-44.15-83.475C54.392-1.283 45.074.474 43.87 8.188L1.253 280.732z" /><path id="IconifyId-17c6fdde69b-f33216-102" d="M134.417 148.974l32.039-32.812l-32.039-61.007c-3.042-5.791-10.433-6.398-13.443-.59l-17.705 34.109l-.53 1.744l31.678 58.556z" /></defs><path d="M0 282.998l2.123-2.972L102.527 89.512l.212-2.017L58.48 4.358C54.77-2.606 44.33-.845 43.114 6.951L0 282.998z" fill="#FFC24A" /><use fill="#FFA712" fillRule="evenodd" xlink:href="#IconifyId-17c6fdde69b-f33216-101" /><use filter="url(#IconifyId-17c6fdde69b-f33216-99)" xlink:href="#IconifyId-17c6fdde69b-f33216-101" /><path d="M135.005 150.38l32.955-33.75l-32.965-62.93c-3.129-5.957-11.866-5.975-14.962 0L102.42 87.287v2.86l32.584 60.233z" fill="#F4BD62" /><use fill="#FFA50E" fillRule="evenodd" xlink:href="#IconifyId-17c6fdde69b-f33216-102" /><use filter="url(#IconifyId-17c6fdde69b-f33216-100)" xlink:href="#IconifyId-17c6fdde69b-f33216-102" /><path fill="#F6820C" d="M0 282.998l.962-.968l3.496-1.42l128.477-128l1.628-4.431l-32.05-61.074z" /><path d="M139.121 347.551l116.275-64.847l-33.204-204.495c-1.039-6.398-8.888-8.927-13.468-4.34L0 282.998l115.608 64.548a24.126 24.126 0 0 0 23.513.005" fill="#FDE068" /><path d="M254.354 282.16L221.402 79.218c-1.03-6.35-7.558-8.977-12.103-4.424L1.29 282.6l114.339 63.908a23.943 23.943 0 0 0 23.334.006l115.392-64.355z" fill="#FCCA3F" /><path d="M139.12 345.64a24.126 24.126 0 0 1-23.512-.005L.931 282.015l-.93.983l115.607 64.548a24.126 24.126 0 0 0 23.513.005l116.275-64.847l-.285-1.752l-115.99 64.689z" fill="#EEAB37" /></svg>
</template>
| docs/components/atoms/logo/LogoFirebase.vue | 0 | https://github.com/nuxt/nuxt/commit/71b808c8e96ae8bdbe4440f16d96f7242f864843 | [
0.000202469716896303,
0.00018197100143879652,
0.00017422773817088455,
0.00017559327534399927,
0.000011853347132273484
] |
{
"id": 3,
"code_window": [
" * This can be useful if you need to serve Nuxt as a different context root, from\n",
" * within a bigger web site.\n",
" * @version 2\n",
" */\n",
" base: {\n",
" $resolve: (val, get) => val ? withTrailingSlash(normalizeURL(val)) : get('app.baseURL')\n",
" },\n",
"\n",
" /** @private */\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" $resolve: (val, get) => val ? withTrailingSlash(normalizeURL(val)) : get('app').baseURL\n"
],
"file_path": "packages/schema/src/config/router.ts",
"type": "replace",
"edit_start_line_idx": 35
} | # `$fetch`
::ReadMore{link="/guide/features/data-fetching"}
::
Nuxt uses [ohmyfetch](https://github.com/unjs/ohmyfetch) to expose globally the `$fetch` helper for making HTTP requests within your Vue app or API routes.
During server-side rendering, calling `$fetch` to fetch your internal [API routes](/guide/directory-structure/server) will directly call the relevant function (emulating the request), **saving an additional API call**.
Note that `$fetch` is the preferred way to make HTTP calls in Nuxt 3 instead of [@nuxt/http](https://github.com/nuxt/http) and [@nuxtjs/axios](https://github.com/nuxt-community/axios-module) that are made for Nuxt 2.
::NeedContribution
::
| docs/content/3.api/3.utils/$fetch.md | 0 | https://github.com/nuxt/nuxt/commit/71b808c8e96ae8bdbe4440f16d96f7242f864843 | [
0.0007807628135196865,
0.00047710127546451986,
0.00017343975196126848,
0.00047710127546451986,
0.0003036615380551666
] |
{
"id": 3,
"code_window": [
" * This can be useful if you need to serve Nuxt as a different context root, from\n",
" * within a bigger web site.\n",
" * @version 2\n",
" */\n",
" base: {\n",
" $resolve: (val, get) => val ? withTrailingSlash(normalizeURL(val)) : get('app.baseURL')\n",
" },\n",
"\n",
" /** @private */\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" $resolve: (val, get) => val ? withTrailingSlash(normalizeURL(val)) : get('app').baseURL\n"
],
"file_path": "packages/schema/src/config/router.ts",
"type": "replace",
"edit_start_line_idx": 35
} | import { joinURL } from 'ufo'
import { useRuntimeConfig } from '#internal/nitro'
export function baseURL (): string {
return useRuntimeConfig().app.baseURL
}
export function buildAssetsDir (): string {
return useRuntimeConfig().app.buildAssetsDir
}
export function buildAssetsURL (...path: string[]): string {
return joinURL(publicAssetsURL(), useRuntimeConfig().app.buildAssetsDir, ...path)
}
export function publicAssetsURL (...path: string[]): string {
const publicBase = useRuntimeConfig().app.cdnURL || useRuntimeConfig().app.baseURL
return path.length ? joinURL(publicBase, ...path) : publicBase
}
| packages/nuxt3/src/core/runtime/nitro/paths.ts | 0 | https://github.com/nuxt/nuxt/commit/71b808c8e96ae8bdbe4440f16d96f7242f864843 | [
0.001420694636180997,
0.000798606313765049,
0.00017651794769335538,
0.000798606313765049,
0.0006220883806236088
] |
{
"id": 0,
"code_window": [
"export const renameTerminalIcon = registerIcon('terminal-rename', Codicon.gear, localize('renameTerminalIcon', 'Icon for rename in the terminal quick menu.'));\n",
"export const killTerminalIcon = registerIcon('terminal-kill', Codicon.trash, localize('killTerminalIcon', 'Icon for killing a terminal instance.'));\n",
"export const newTerminalIcon = registerIcon('terminal-new', Codicon.add, localize('newTerminalIcon', 'Icon for creating a new terminal instance.'));\n",
"\n",
"export const newQuickLaunchProfileIcon = registerIcon('terminal-quick-launch', Codicon.symbolEvent, localize('newQuickLaunchProfile', 'Icon for creating a new terminal quick launch profile.'));\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace"
],
"after_edit": [
"export const configureTerminalProfileIcon = registerIcon('terminal-configure-profile', Codicon.gear, localize('configureTerminalProfileIcon', 'Icon for creating a new terminal profile.'));"
],
"file_path": "src/vs/workbench/contrib/terminal/browser/terminalIcons.ts",
"type": "replace",
"edit_start_line_idx": 15
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { timeout } from 'vs/base/common/async';
import { debounce, throttle } from 'vs/base/common/decorators';
import { Emitter, Event } from 'vs/base/common/event';
import { IDisposable } from 'vs/base/common/lifecycle';
import { basename } from 'vs/base/common/path';
import { isMacintosh, isWeb, isWindows, OperatingSystem } from 'vs/base/common/platform';
import { FindReplaceState } from 'vs/editor/contrib/find/findState';
import * as nls from 'vs/nls';
import { ConfigurationTarget, IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
import { IInstantiationService, optional } from 'vs/platform/instantiation/common/instantiation';
import { IPickOptions, IQuickInputButton, IQuickInputService, IQuickPickItem } from 'vs/platform/quickinput/common/quickInput';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { ILocalTerminalService, IShellLaunchConfig, ITerminalLaunchError, ITerminalsLayoutInfo, ITerminalsLayoutInfoById, TerminalShellType, WindowsShellType } from 'vs/platform/terminal/common/terminal';
import { ThemeIcon } from 'vs/platform/theme/common/themeService';
import { IViewDescriptorService, IViewsService, ViewContainerLocation } from 'vs/workbench/common/views';
import { IRemoteTerminalService, ITerminalExternalLinkProvider, ITerminalInstance, ITerminalService, ITerminalTab, TerminalConnectionState } from 'vs/workbench/contrib/terminal/browser/terminal';
import { TerminalConfigHelper } from 'vs/workbench/contrib/terminal/browser/terminalConfigHelper';
import { TerminalInstance } from 'vs/workbench/contrib/terminal/browser/terminalInstance';
import { TerminalTab } from 'vs/workbench/contrib/terminal/browser/terminalTab';
import { TerminalViewPane } from 'vs/workbench/contrib/terminal/browser/terminalView';
import { IAvailableProfilesRequest, IRemoteTerminalAttachTarget, ITerminalProfile, IStartExtensionTerminalRequest, ITerminalConfigHelper, ITerminalNativeWindowsDelegate, ITerminalProcessExtHostProxy, KEYBINDING_CONTEXT_TERMINAL_ALT_BUFFER_ACTIVE, KEYBINDING_CONTEXT_TERMINAL_FIND_VISIBLE, KEYBINDING_CONTEXT_TERMINAL_FOCUS, KEYBINDING_CONTEXT_TERMINAL_IS_OPEN, KEYBINDING_CONTEXT_TERMINAL_PROCESS_SUPPORTED, KEYBINDING_CONTEXT_TERMINAL_SHELL_TYPE, LinuxDistro, TERMINAL_VIEW_ID, ITerminalProfileObject, ITerminalExecutable, ITerminalProfileSource } from 'vs/workbench/contrib/terminal/common/terminal';
import { escapeNonWindowsPath } from 'vs/workbench/contrib/terminal/common/terminalEnvironment';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService';
import { ILifecycleService, ShutdownReason, WillShutdownEvent } from 'vs/workbench/services/lifecycle/common/lifecycle';
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
import { newQuickLaunchProfileIcon } from 'vs/workbench/contrib/terminal/browser/terminalIcons';
import { equals } from 'vs/base/common/objects';
interface IExtHostReadyEntry {
promise: Promise<void>;
resolve: () => void;
}
export class TerminalService implements ITerminalService {
public _serviceBrand: undefined;
private _isShuttingDown: boolean;
private _terminalFocusContextKey: IContextKey<boolean>;
private _terminalShellTypeContextKey: IContextKey<string>;
private _terminalAltBufferActiveContextKey: IContextKey<boolean>;
private _findWidgetVisible: IContextKey<boolean>;
private _terminalTabs: ITerminalTab[] = [];
private _backgroundedTerminalInstances: ITerminalInstance[] = [];
private get _terminalInstances(): ITerminalInstance[] {
return this._terminalTabs.reduce((p, c) => p.concat(c.terminalInstances), <ITerminalInstance[]>[]);
}
private _findState: FindReplaceState;
private _extHostsReady: { [authority: string]: IExtHostReadyEntry | undefined } = {};
private _activeTabIndex: number;
private _linkProviders: Set<ITerminalExternalLinkProvider> = new Set();
private _linkProviderDisposables: Map<ITerminalExternalLinkProvider, IDisposable[]> = new Map();
private _processSupportContextKey: IContextKey<boolean>;
public get activeTabIndex(): number { return this._activeTabIndex; }
public get terminalInstances(): ITerminalInstance[] { return this._terminalInstances; }
public get terminalTabs(): ITerminalTab[] { return this._terminalTabs; }
public get isProcessSupportRegistered(): boolean { return !!this._processSupportContextKey.get(); }
private _configHelper: TerminalConfigHelper;
private _terminalContainer: HTMLElement | undefined;
private _nativeWindowsDelegate: ITerminalNativeWindowsDelegate | undefined;
private _remoteTerminalsInitPromise: Promise<void> | undefined;
private _localTerminalsInitPromise: Promise<void> | undefined;
private _connectionState: TerminalConnectionState;
private _availableProfiles: ITerminalProfile[] | undefined;
public get configHelper(): ITerminalConfigHelper { return this._configHelper; }
private readonly _onActiveTabChanged = new Emitter<void>();
public get onActiveTabChanged(): Event<void> { return this._onActiveTabChanged.event; }
private readonly _onInstanceCreated = new Emitter<ITerminalInstance>();
public get onInstanceCreated(): Event<ITerminalInstance> { return this._onInstanceCreated.event; }
private readonly _onInstanceDisposed = new Emitter<ITerminalInstance>();
public get onInstanceDisposed(): Event<ITerminalInstance> { return this._onInstanceDisposed.event; }
private readonly _onInstanceProcessIdReady = new Emitter<ITerminalInstance>();
public get onInstanceProcessIdReady(): Event<ITerminalInstance> { return this._onInstanceProcessIdReady.event; }
private readonly _onInstanceLinksReady = new Emitter<ITerminalInstance>();
public get onInstanceLinksReady(): Event<ITerminalInstance> { return this._onInstanceLinksReady.event; }
private readonly _onInstanceRequestStartExtensionTerminal = new Emitter<IStartExtensionTerminalRequest>();
public get onInstanceRequestStartExtensionTerminal(): Event<IStartExtensionTerminalRequest> { return this._onInstanceRequestStartExtensionTerminal.event; }
private readonly _onInstanceDimensionsChanged = new Emitter<ITerminalInstance>();
public get onInstanceDimensionsChanged(): Event<ITerminalInstance> { return this._onInstanceDimensionsChanged.event; }
private readonly _onInstanceMaximumDimensionsChanged = new Emitter<ITerminalInstance>();
public get onInstanceMaximumDimensionsChanged(): Event<ITerminalInstance> { return this._onInstanceMaximumDimensionsChanged.event; }
private readonly _onInstancesChanged = new Emitter<void>();
public get onInstancesChanged(): Event<void> { return this._onInstancesChanged.event; }
private readonly _onInstanceTitleChanged = new Emitter<ITerminalInstance | undefined>();
public get onInstanceTitleChanged(): Event<ITerminalInstance | undefined> { return this._onInstanceTitleChanged.event; }
private readonly _onActiveInstanceChanged = new Emitter<ITerminalInstance | undefined>();
public get onActiveInstanceChanged(): Event<ITerminalInstance | undefined> { return this._onActiveInstanceChanged.event; }
private readonly _onTabDisposed = new Emitter<ITerminalTab>();
public get onTabDisposed(): Event<ITerminalTab> { return this._onTabDisposed.event; }
private readonly _onRequestAvailableProfiles = new Emitter<IAvailableProfilesRequest>();
public get onRequestAvailableProfiles(): Event<IAvailableProfilesRequest> { return this._onRequestAvailableProfiles.event; }
private readonly _onDidRegisterProcessSupport = new Emitter<void>();
public get onDidRegisterProcessSupport(): Event<void> { return this._onDidRegisterProcessSupport.event; }
private readonly _onDidChangeConnectionState = new Emitter<void>();
public get onDidChangeConnectionState(): Event<void> { return this._onDidChangeConnectionState.event; }
public get connectionState(): TerminalConnectionState { return this._connectionState; }
private readonly _onProfilesConfigChanged = new Emitter<void>();
public get onProfilesConfigChanged(): Event<void> { return this._onProfilesConfigChanged.event; }
private readonly _localTerminalService?: ILocalTerminalService;
constructor(
@IContextKeyService private _contextKeyService: IContextKeyService,
@IWorkbenchLayoutService private _layoutService: IWorkbenchLayoutService,
@ILifecycleService lifecycleService: ILifecycleService,
@IDialogService private _dialogService: IDialogService,
@IInstantiationService private _instantiationService: IInstantiationService,
@IRemoteAgentService private _remoteAgentService: IRemoteAgentService,
@IQuickInputService private _quickInputService: IQuickInputService,
@IConfigurationService private _configurationService: IConfigurationService,
@IViewsService private _viewsService: IViewsService,
@IViewDescriptorService private readonly _viewDescriptorService: IViewDescriptorService,
@IWorkbenchEnvironmentService private readonly _environmentService: IWorkbenchEnvironmentService,
@IRemoteTerminalService private readonly _remoteTerminalService: IRemoteTerminalService,
@ITelemetryService private readonly _telemetryService: ITelemetryService,
@IExtensionService private readonly _extensionService: IExtensionService,
@optional(ILocalTerminalService) localTerminalService: ILocalTerminalService
) {
this._localTerminalService = localTerminalService;
this._activeTabIndex = 0;
this._isShuttingDown = false;
this._findState = new FindReplaceState();
lifecycleService.onBeforeShutdown(async e => e.veto(this._onBeforeShutdown(e.reason), 'veto.terminal'));
lifecycleService.onWillShutdown(e => this._onWillShutdown(e));
this._terminalFocusContextKey = KEYBINDING_CONTEXT_TERMINAL_FOCUS.bindTo(this._contextKeyService);
this._terminalShellTypeContextKey = KEYBINDING_CONTEXT_TERMINAL_SHELL_TYPE.bindTo(this._contextKeyService);
this._terminalAltBufferActiveContextKey = KEYBINDING_CONTEXT_TERMINAL_ALT_BUFFER_ACTIVE.bindTo(this._contextKeyService);
this._findWidgetVisible = KEYBINDING_CONTEXT_TERMINAL_FIND_VISIBLE.bindTo(this._contextKeyService);
this._configHelper = this._instantiationService.createInstance(TerminalConfigHelper);
this.onTabDisposed(tab => this._removeTab(tab));
this.onActiveTabChanged(() => {
const instance = this.getActiveInstance();
this._onActiveInstanceChanged.fire(instance ? instance : undefined);
});
this.onInstanceLinksReady(instance => this._setInstanceLinkProviders(instance));
this._handleInstanceContextKeys();
this._processSupportContextKey = KEYBINDING_CONTEXT_TERMINAL_PROCESS_SUPPORTED.bindTo(this._contextKeyService);
this._processSupportContextKey.set(!isWeb || this._remoteAgentService.getConnection() !== null);
this._configurationService.onDidChangeConfiguration(async e => {
if (e.affectsConfiguration('terminal.integrated.profiles.windows') ||
e.affectsConfiguration('terminal.integrated.profiles.osx') ||
e.affectsConfiguration('terminal.integrated.profiles.linux') ||
e.affectsConfiguration('terminal.integrated.showQuickLaunchWslProfiles')) {
this._updateAvailableProfilesNow();
}
});
const enableTerminalReconnection = this.configHelper.config.enablePersistentSessions;
const conn = this._remoteAgentService.getConnection();
const remoteAuthority = conn ? conn.remoteAuthority : 'null';
this._whenExtHostReady(remoteAuthority).then(() => {
this._updateAvailableProfiles();
});
// Connect to the extension host if it's there, set the connection state to connected when
// it's done. This should happen even when there is no extension host.
this._connectionState = TerminalConnectionState.Connecting;
let initPromise: Promise<any>;
if (!!this._environmentService.remoteAuthority && enableTerminalReconnection) {
initPromise = this._remoteTerminalsInitPromise = this._reconnectToRemoteTerminals();
} else if (enableTerminalReconnection) {
initPromise = this._localTerminalsInitPromise = this._reconnectToLocalTerminals();
} else {
initPromise = Promise.resolve();
}
initPromise.then(() => this._setConnected());
}
private _setConnected() {
this._connectionState = TerminalConnectionState.Connected;
this._onDidChangeConnectionState.fire();
}
private async _reconnectToRemoteTerminals(): Promise<void> {
// Reattach to all remote terminals
const layoutInfo = await this._remoteTerminalService.getTerminalLayoutInfo();
const reconnectCounter = this._recreateTerminalTabs(layoutInfo);
/* __GDPR__
"terminalReconnection" : {
"count" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
}
*/
const data = {
count: reconnectCounter
};
this._telemetryService.publicLog('terminalReconnection', data);
// now that terminals have been restored,
// attach listeners to update remote when terminals are changed
this.attachProcessLayoutListeners(true);
}
private async _reconnectToLocalTerminals(): Promise<void> {
if (!this._localTerminalService) {
return;
}
// Reattach to all local terminals
const layoutInfo = await this._localTerminalService.getTerminalLayoutInfo();
if (layoutInfo && layoutInfo.tabs.length > 0) {
this._recreateTerminalTabs(layoutInfo);
}
// now that terminals have been restored,
// attach listeners to update local state when terminals are changed
this.attachProcessLayoutListeners(false);
}
private _recreateTerminalTabs(layoutInfo?: ITerminalsLayoutInfo): number {
let reconnectCounter = 0;
let activeTab: ITerminalTab | undefined;
if (layoutInfo) {
layoutInfo.tabs.forEach(tabLayout => {
const terminalLayouts = tabLayout.terminals.filter(t => t.terminal && t.terminal.isOrphan);
if (terminalLayouts.length) {
reconnectCounter += terminalLayouts.length;
let terminalInstance: ITerminalInstance | undefined;
let tab: ITerminalTab | undefined;
terminalLayouts.forEach((terminalLayout) => {
if (!terminalInstance) {
// create tab and terminal
terminalInstance = this.createTerminal({ attachPersistentProcess: terminalLayout.terminal! });
tab = this._getTabForInstance(terminalInstance);
if (tabLayout.isActive) {
activeTab = tab;
}
} else {
// add split terminals to this tab
this.splitInstance(terminalInstance, { attachPersistentProcess: terminalLayout.terminal! });
}
});
const activeInstance = this.terminalInstances.find(t => {
return t.shellLaunchConfig.attachPersistentProcess?.id === tabLayout.activePersistentProcessId;
});
if (activeInstance) {
this.setActiveInstance(activeInstance);
}
tab?.resizePanes(tabLayout.terminals.map(terminal => terminal.relativeSize));
}
});
if (layoutInfo.tabs.length) {
this.setActiveTabByIndex(activeTab ? this.terminalTabs.indexOf(activeTab) : 0);
}
}
return reconnectCounter;
}
private attachProcessLayoutListeners(isRemote: boolean): void {
this.onActiveTabChanged(() => isRemote ? this._updateRemoteState() : this._updateLocalState());
this.onActiveInstanceChanged(() => isRemote ? this._updateRemoteState() : this._updateLocalState());
this.onInstancesChanged(() => isRemote ? this._updateRemoteState() : this._updateLocalState());
// The state must be updated when the terminal is relaunched, otherwise the persistent
// terminal ID will be stale and the process will be leaked.
this.onInstanceProcessIdReady(() => isRemote ? this._updateRemoteState() : this._updateLocalState());
}
public setNativeWindowsDelegate(delegate: ITerminalNativeWindowsDelegate): void {
this._nativeWindowsDelegate = delegate;
}
public setLinuxDistro(linuxDistro: LinuxDistro): void {
this._configHelper.setLinuxDistro(linuxDistro);
}
private _handleInstanceContextKeys(): void {
const terminalIsOpenContext = KEYBINDING_CONTEXT_TERMINAL_IS_OPEN.bindTo(this._contextKeyService);
const updateTerminalContextKeys = () => {
terminalIsOpenContext.set(this.terminalInstances.length > 0);
};
this.onInstancesChanged(() => updateTerminalContextKeys());
}
public getActiveOrCreateInstance(): ITerminalInstance {
const activeInstance = this.getActiveInstance();
return activeInstance ? activeInstance : this.createTerminal(undefined);
}
public requestStartExtensionTerminal(proxy: ITerminalProcessExtHostProxy, cols: number, rows: number): Promise<ITerminalLaunchError | undefined> {
// The initial request came from the extension host, no need to wait for it
return new Promise<ITerminalLaunchError | undefined>(callback => {
this._onInstanceRequestStartExtensionTerminal.fire({ proxy, cols, rows, callback });
});
}
public async extHostReady(remoteAuthority: string): Promise<void> {
this._createExtHostReadyEntry(remoteAuthority);
this._extHostsReady[remoteAuthority]!.resolve();
}
public getAvailableProfiles(): ITerminalProfile[] {
this._updateAvailableProfiles();
return this._availableProfiles || [];
}
private async _getWorkspaceProfilePermissions(profile: ITerminalProfile): Promise<boolean> {
const platformKey = await this._getPlatformKey();
const profiles = this._configurationService.inspect<{ [key: string]: ITerminalProfileObject }>(`terminal.integrated.profiles.${platformKey}`);
if (!profiles || !profiles.workspaceValue || !profiles.defaultValue) {
return false;
}
const workspaceProfile = Object.entries(profiles.workspaceValue).find(p => p[0] === profile.profileName);
const defaultProfile = Object.entries(profiles.defaultValue).find(p => p[0] === profile.profileName);
if (workspaceProfile && defaultProfile && workspaceProfile[0] === defaultProfile[0]) {
let result = !this._terminalProfileObjectEqual(workspaceProfile[1], defaultProfile[1]);
return result;
} else if (!workspaceProfile && !defaultProfile) {
// user profile
return false;
} else {
// this key is missing from either default or the workspace config
return true;
}
}
private _terminalProfileObjectEqual(one?: ITerminalProfileObject, two?: ITerminalProfileObject): boolean {
if (one === null && two === null) {
return true;
} else if ((one as ITerminalExecutable).path && (two as ITerminalExecutable).path) {
const oneExec = (one as ITerminalExecutable);
const twoExec = (two as ITerminalExecutable);
return ((Array.isArray(oneExec.path) && Array.isArray(twoExec.path) && oneExec.path.length === twoExec.path.length && oneExec.path.every((p, index) => p === twoExec.path[index])) ||
(oneExec.path === twoExec.path)
) && ((Array.isArray(oneExec.args) && Array.isArray(twoExec.args) && oneExec.args?.every((a, index) => a === twoExec.args?.[index])) ||
(oneExec.args === twoExec.args)
);
} else if ((one as ITerminalProfileSource).source && (two as ITerminalProfileSource).source) {
const oneSource = (one as ITerminalProfileSource);
const twoSource = (two as ITerminalProfileSource);
return oneSource.source === twoSource.source;
}
return false;
}
// when relevant config changes, update without debouncing
private async _updateAvailableProfilesNow(): Promise<void> {
const result = await this._detectProfiles(true);
for (const p of result) {
p.isWorkspaceProfile = await this._getWorkspaceProfilePermissions(p);
}
if (!equals(result, this._availableProfiles)) {
this._availableProfiles = result;
this._onProfilesConfigChanged.fire();
}
}
// avoid checking this very often, every ten seconds shoulds suffice
@throttle(10000)
private _updateAvailableProfiles(): Promise<void> {
return this._updateAvailableProfilesNow();
}
private async _detectProfiles(quickLaunchOnly: boolean): Promise<ITerminalProfile[]> {
await this._extensionService.whenInstalledExtensionsRegistered();
// Wait for the remoteAuthority to be ready (and listening for events) before firing
// the event to spawn the ext host process
const conn = this._remoteAgentService.getConnection();
const remoteAuthority = conn ? conn.remoteAuthority : 'null';
await this._whenExtHostReady(remoteAuthority);
return new Promise(r => this._onRequestAvailableProfiles.fire({ callback: r, quickLaunchOnly: quickLaunchOnly }));
}
private async _whenExtHostReady(remoteAuthority: string): Promise<void> {
this._createExtHostReadyEntry(remoteAuthority);
return this._extHostsReady[remoteAuthority]!.promise;
}
private _createExtHostReadyEntry(remoteAuthority: string): void {
if (this._extHostsReady[remoteAuthority]) {
return;
}
let resolve!: () => void;
const promise = new Promise<void>(r => resolve = r);
this._extHostsReady[remoteAuthority] = { promise, resolve };
}
private _onBeforeShutdown(reason: ShutdownReason): boolean | Promise<boolean> {
if (this.terminalInstances.length === 0) {
// No terminal instances, don't veto
return false;
}
const shouldPersistTerminals = this._configHelper.config.enablePersistentSessions && reason === ShutdownReason.RELOAD;
if (this.configHelper.config.confirmOnExit && !shouldPersistTerminals) {
return this._onBeforeShutdownAsync();
}
this._isShuttingDown = true;
return false;
}
private async _onBeforeShutdownAsync(): Promise<boolean> {
// veto if configured to show confirmation and the user chose not to exit
const veto = await this._showTerminalCloseConfirmation();
if (!veto) {
this._isShuttingDown = true;
}
return veto;
}
private _onWillShutdown(e: WillShutdownEvent): void {
// Don't touch processes if the shutdown was a result of reload as they will be reattached
const shouldPersistTerminals = this._configHelper.config.enablePersistentSessions && e.reason === ShutdownReason.RELOAD;
if (shouldPersistTerminals) {
this.terminalInstances.forEach(instance => instance.detachFromProcess());
return;
}
// Force dispose of all terminal instances, don't force immediate disposal of the terminal
// processes on Windows as an additional mitigation for https://github.com/microsoft/vscode/issues/71966
// which causes the pty host to become unresponsive, disconnecting all terminals across all
// windows
this.terminalInstances.forEach(instance => instance.dispose(!isWindows));
this._localTerminalService!.setTerminalLayoutInfo(undefined);
}
public getTabLabels(): string[] {
return this._terminalTabs.filter(tab => tab.terminalInstances.length > 0).map((tab, index) => {
return `${index + 1}: ${tab.title ? tab.title : ''}`;
});
}
public getFindState(): FindReplaceState {
return this._findState;
}
@debounce(500)
private _updateRemoteState(): void {
if (!!this._environmentService.remoteAuthority) {
const state: ITerminalsLayoutInfoById = {
tabs: this.terminalTabs.map(t => t.getLayoutInfo(t === this.getActiveTab()))
};
this._remoteTerminalService.setTerminalLayoutInfo(state);
}
}
@debounce(500)
private _updateLocalState(): void {
const state: ITerminalsLayoutInfoById = {
tabs: this.terminalTabs.map(t => t.getLayoutInfo(t === this.getActiveTab()))
};
this._localTerminalService!.setTerminalLayoutInfo(state);
}
private _removeTab(tab: ITerminalTab): void {
// Get the index of the tab and remove it from the list
const index = this._terminalTabs.indexOf(tab);
const activeTab = this.getActiveTab();
const activeTabIndex = activeTab ? this._terminalTabs.indexOf(activeTab) : -1;
const wasActiveTab = tab === activeTab;
if (index !== -1) {
this._terminalTabs.splice(index, 1);
}
// Adjust focus if the tab was active
if (wasActiveTab && this._terminalTabs.length > 0) {
// TODO: Only focus the new tab if the removed tab had focus?
// const hasFocusOnExit = tab.activeInstance.hadFocusOnExit;
const newIndex = index < this._terminalTabs.length ? index : this._terminalTabs.length - 1;
this.setActiveTabByIndex(newIndex);
const activeInstance = this.getActiveInstance();
if (activeInstance) {
activeInstance.focus(true);
}
} else if (activeTabIndex >= this._terminalTabs.length) {
const newIndex = this._terminalTabs.length - 1;
this.setActiveTabByIndex(newIndex);
}
// Hide the panel if there are no more instances, provided that VS Code is not shutting
// down. When shutting down the panel is locked in place so that it is restored upon next
// launch.
if (this._terminalTabs.length === 0 && !this._isShuttingDown) {
this.hidePanel();
this._onActiveInstanceChanged.fire(undefined);
}
// Fire events
this._onInstancesChanged.fire();
if (wasActiveTab) {
this._onActiveTabChanged.fire();
}
}
public refreshActiveTab(): void {
// Fire active instances changed
this._onActiveTabChanged.fire();
}
public getActiveTab(): ITerminalTab | null {
if (this._activeTabIndex < 0 || this._activeTabIndex >= this._terminalTabs.length) {
return null;
}
return this._terminalTabs[this._activeTabIndex];
}
public getActiveInstance(): ITerminalInstance | null {
const tab = this.getActiveTab();
if (!tab) {
return null;
}
return tab.activeInstance;
}
public doWithActiveInstance<T>(callback: (terminal: ITerminalInstance) => T): T | void {
const instance = this.getActiveInstance();
if (instance) {
return callback(instance);
}
}
public getInstanceFromId(terminalId: number): ITerminalInstance | undefined {
let bgIndex = -1;
this._backgroundedTerminalInstances.forEach((terminalInstance, i) => {
if (terminalInstance.instanceId === terminalId) {
bgIndex = i;
}
});
if (bgIndex !== -1) {
return this._backgroundedTerminalInstances[bgIndex];
}
try {
return this.terminalInstances[this._getIndexFromId(terminalId)];
} catch {
return undefined;
}
}
public getInstanceFromIndex(terminalIndex: number): ITerminalInstance {
return this.terminalInstances[terminalIndex];
}
public setActiveInstance(terminalInstance: ITerminalInstance): void {
// If this was a hideFromUser terminal created by the API this was triggered by show,
// in which case we need to create the terminal tab
if (terminalInstance.shellLaunchConfig.hideFromUser) {
this._showBackgroundTerminal(terminalInstance);
}
this.setActiveInstanceByIndex(this._getIndexFromId(terminalInstance.instanceId));
}
public setActiveTabByIndex(tabIndex: number): void {
if (tabIndex >= this._terminalTabs.length) {
return;
}
const didTabChange = this._activeTabIndex !== tabIndex;
this._activeTabIndex = tabIndex;
this._terminalTabs.forEach((t, i) => t.setVisible(i === this._activeTabIndex));
if (didTabChange) {
this._onActiveTabChanged.fire();
}
}
public isAttachedToTerminal(remoteTerm: IRemoteTerminalAttachTarget): boolean {
return this.terminalInstances.some(term => term.processId === remoteTerm.pid);
}
public async initializeTerminals(): Promise<void> {
if (this._remoteTerminalsInitPromise) {
await this._remoteTerminalsInitPromise;
} else if (this._localTerminalsInitPromise) {
await this._localTerminalsInitPromise;
}
if (this.terminalTabs.length === 0 && this.isProcessSupportRegistered) {
this.createTerminal();
}
}
private _getInstanceFromGlobalInstanceIndex(index: number): { tab: ITerminalTab, tabIndex: number, instance: ITerminalInstance, localInstanceIndex: number } | null {
let currentTabIndex = 0;
while (index >= 0 && currentTabIndex < this._terminalTabs.length) {
const tab = this._terminalTabs[currentTabIndex];
const count = tab.terminalInstances.length;
if (index < count) {
return {
tab,
tabIndex: currentTabIndex,
instance: tab.terminalInstances[index],
localInstanceIndex: index
};
}
index -= count;
currentTabIndex++;
}
return null;
}
public setActiveInstanceByIndex(terminalIndex: number): void {
const query = this._getInstanceFromGlobalInstanceIndex(terminalIndex);
if (!query) {
return;
}
query.tab.setActiveInstanceByIndex(query.localInstanceIndex);
const didTabChange = this._activeTabIndex !== query.tabIndex;
this._activeTabIndex = query.tabIndex;
this._terminalTabs.forEach((t, i) => t.setVisible(i === query.tabIndex));
// Only fire the event if there was a change
if (didTabChange) {
this._onActiveTabChanged.fire();
}
}
public setActiveTabToNext(): void {
if (this._terminalTabs.length <= 1) {
return;
}
let newIndex = this._activeTabIndex + 1;
if (newIndex >= this._terminalTabs.length) {
newIndex = 0;
}
this.setActiveTabByIndex(newIndex);
}
public setActiveTabToPrevious(): void {
if (this._terminalTabs.length <= 1) {
return;
}
let newIndex = this._activeTabIndex - 1;
if (newIndex < 0) {
newIndex = this._terminalTabs.length - 1;
}
this.setActiveTabByIndex(newIndex);
}
public splitInstance(instanceToSplit: ITerminalInstance, shellLaunchConfig: IShellLaunchConfig = {}): ITerminalInstance | null {
const tab = this._getTabForInstance(instanceToSplit);
if (!tab) {
return null;
}
const instance = tab.split(shellLaunchConfig);
this._initInstanceListeners(instance);
this._onInstancesChanged.fire();
this._terminalTabs.forEach((t, i) => t.setVisible(i === this._activeTabIndex));
return instance;
}
protected _initInstanceListeners(instance: ITerminalInstance): void {
instance.addDisposable(instance.onDisposed(this._onInstanceDisposed.fire, this._onInstanceDisposed));
instance.addDisposable(instance.onTitleChanged(this._onInstanceTitleChanged.fire, this._onInstanceTitleChanged));
instance.addDisposable(instance.onProcessIdReady(this._onInstanceProcessIdReady.fire, this._onInstanceProcessIdReady));
instance.addDisposable(instance.onLinksReady(this._onInstanceLinksReady.fire, this._onInstanceLinksReady));
instance.addDisposable(instance.onDimensionsChanged(() => {
this._onInstanceDimensionsChanged.fire(instance);
if (this.configHelper.config.enablePersistentSessions && this.isProcessSupportRegistered) {
!!this._environmentService.remoteAuthority ? this._updateRemoteState() : this._updateLocalState();
}
}));
instance.addDisposable(instance.onMaximumDimensionsChanged(() => this._onInstanceMaximumDimensionsChanged.fire(instance)));
instance.addDisposable(instance.onFocus(this._onActiveInstanceChanged.fire, this._onActiveInstanceChanged));
}
public registerProcessSupport(isSupported: boolean): void {
if (!isSupported) {
return;
}
this._processSupportContextKey.set(isSupported);
this._onDidRegisterProcessSupport.fire();
}
public registerLinkProvider(linkProvider: ITerminalExternalLinkProvider): IDisposable {
const disposables: IDisposable[] = [];
this._linkProviders.add(linkProvider);
for (const instance of this.terminalInstances) {
if (instance.areLinksReady) {
disposables.push(instance.registerLinkProvider(linkProvider));
}
}
this._linkProviderDisposables.set(linkProvider, disposables);
return {
dispose: () => {
const disposables = this._linkProviderDisposables.get(linkProvider) || [];
for (const disposable of disposables) {
disposable.dispose();
}
this._linkProviders.delete(linkProvider);
}
};
}
private _setInstanceLinkProviders(instance: ITerminalInstance): void {
for (const linkProvider of this._linkProviders) {
const disposables = this._linkProviderDisposables.get(linkProvider);
const provider = instance.registerLinkProvider(linkProvider);
disposables?.push(provider);
}
}
private _getTabForInstance(instance: ITerminalInstance): ITerminalTab | undefined {
return this._terminalTabs.find(tab => tab.terminalInstances.indexOf(instance) !== -1);
}
public async showPanel(focus?: boolean): Promise<void> {
const pane = this._viewsService.getActiveViewWithId(TERMINAL_VIEW_ID) as TerminalViewPane;
if (!pane) {
await this._viewsService.openView(TERMINAL_VIEW_ID, focus);
}
if (focus) {
// Do the focus call asynchronously as going through the
// command palette will force editor focus
await timeout(0);
const instance = this.getActiveInstance();
if (instance) {
await instance.focusWhenReady(true);
}
}
}
private _getIndexFromId(terminalId: number): number {
let terminalIndex = -1;
this.terminalInstances.forEach((terminalInstance, i) => {
if (terminalInstance.instanceId === terminalId) {
terminalIndex = i;
}
});
if (terminalIndex === -1) {
throw new Error(`Terminal with ID ${terminalId} does not exist (has it already been disposed?)`);
}
return terminalIndex;
}
public async manageWorkspaceShellPermissions(): Promise<void> {
const allowItem: IQuickPickItem = { label: nls.localize('workbench.action.terminal.allowWorkspaceShell', "Allow Workspace Shell Configuration") };
const disallowItem: IQuickPickItem = { label: nls.localize('workbench.action.terminal.disallowWorkspaceShell', "Disallow Workspace Shell Configuration") };
const value = await this._quickInputService.pick([allowItem, disallowItem], { canPickMany: false });
if (!value) {
return;
}
this.configHelper.setWorkspaceShellAllowed(value === allowItem);
}
protected async _showTerminalCloseConfirmation(): Promise<boolean> {
let message: string;
if (this.terminalInstances.length === 1) {
message = nls.localize('terminalService.terminalCloseConfirmationSingular', "There is an active terminal session, do you want to kill it?");
} else {
message = nls.localize('terminalService.terminalCloseConfirmationPlural', "There are {0} active terminal sessions, do you want to kill them?", this.terminalInstances.length);
}
const res = await this._dialogService.confirm({
message,
type: 'warning',
});
return !res.confirmed;
}
public preparePathForTerminalAsync(originalPath: string, executable: string, title: string, shellType: TerminalShellType): Promise<string> {
return new Promise<string>(c => {
if (!executable) {
c(originalPath);
return;
}
const hasSpace = originalPath.indexOf(' ') !== -1;
const hasParens = originalPath.indexOf('(') !== -1 || originalPath.indexOf(')') !== -1;
const pathBasename = basename(executable, '.exe');
const isPowerShell = pathBasename === 'pwsh' ||
title === 'pwsh' ||
pathBasename === 'powershell' ||
title === 'powershell';
if (isPowerShell && (hasSpace || originalPath.indexOf('\'') !== -1)) {
c(`& '${originalPath.replace(/'/g, '\'\'')}'`);
return;
}
if (hasParens && isPowerShell) {
c(`& '${originalPath}'`);
return;
}
if (isWindows) {
// 17063 is the build number where wsl path was introduced.
// Update Windows uriPath to be executed in WSL.
if (shellType !== undefined) {
if (shellType === WindowsShellType.GitBash) {
c(originalPath.replace(/\\/g, '/'));
return;
}
else if (shellType === WindowsShellType.Wsl) {
if (this._nativeWindowsDelegate && this._nativeWindowsDelegate.getWindowsBuildNumber() >= 17063) {
c(this._nativeWindowsDelegate.getWslPath(originalPath));
} else {
c(originalPath.replace(/\\/g, '/'));
}
return;
}
if (hasSpace) {
c('"' + originalPath + '"');
} else {
c(originalPath);
}
} else {
const lowerExecutable = executable.toLowerCase();
if (this._nativeWindowsDelegate && this._nativeWindowsDelegate.getWindowsBuildNumber() >= 17063 &&
(lowerExecutable.indexOf('wsl') !== -1 || (lowerExecutable.indexOf('bash.exe') !== -1 && lowerExecutable.toLowerCase().indexOf('git') === -1))) {
c(this._nativeWindowsDelegate.getWslPath(originalPath));
return;
} else if (hasSpace) {
c('"' + originalPath + '"');
} else {
c(originalPath);
}
}
return;
}
c(escapeNonWindowsPath(originalPath));
});
}
private async _getPlatformKey(): Promise<string> {
const env = await this._remoteAgentService.getEnvironment();
if (env) {
return env.os === OperatingSystem.Windows ? 'windows' : (env.os === OperatingSystem.Macintosh ? 'osx' : 'linux');
}
return isWindows ? 'windows' : (isMacintosh ? 'osx' : 'linux');
}
public async selectDefaultProfile(): Promise<void> {
const profiles = await this._detectProfiles(false);
const platformKey = await this._getPlatformKey();
interface IProfileQuickPickItem extends IQuickPickItem {
profile: ITerminalProfile;
}
const options: IPickOptions<IProfileQuickPickItem> = {
placeHolder: nls.localize('terminal.integrated.chooseWindowsShell', "Select your preferred terminal shell, you can change this later in your settings"),
onDidTriggerItemButton: async (context) => {
const configKey = `terminal.integrated.profiles.${platformKey}`;
const configProfiles = this._configurationService.inspect<{ [key: string]: ITerminalProfileObject }>(configKey);
const existingProfiles = configProfiles.userValue ? Object.keys(configProfiles.userValue) : [];
const name = await this._quickInputService.input({
prompt: nls.localize('enterTerminalProfileName', "Enter profile name"),
value: context.item.profile.profileName,
validateInput: async input => {
if (existingProfiles.includes(input)) {
return nls.localize('terminalProfileAlreadyExists', "A profile already exists with that name");
}
return undefined;
}
});
if (!name) {
return;
}
const newConfigValue: { [key: string]: ITerminalProfileObject } = { ...configProfiles.userValue } ?? {};
newConfigValue[name] = {
path: context.item.profile.path,
args: context.item.profile.args
};
await this._configurationService.updateValue(configKey, newConfigValue, ConfigurationTarget.USER);
}
};
const quickPickItems = profiles.map((profile): IProfileQuickPickItem => {
const buttons: IQuickInputButton[] = [{
iconClass: ThemeIcon.asClassName(newQuickLaunchProfileIcon),
tooltip: nls.localize('createQuickLaunchProfile', "Create a quick launch profile based on this shell")
}];
if (profile.args) {
if (typeof profile.args === 'string') {
return { label: profile.profileName, description: `${profile.path} ${profile.args}`, profile, buttons };
}
const argsString = profile.args.map(e => {
if (e.includes(' ')) {
return `"${e.replace('/"/g', '\\"')}"`;
}
return e;
}).join(' ');
return { label: profile.profileName, description: `${profile.path} ${argsString}`, profile, buttons };
}
return { label: profile.profileName, description: profile.path, profile, buttons };
});
const value = await this._quickInputService.pick(quickPickItems, options);
if (!value) {
return;
}
await this._configurationService.updateValue(`terminal.integrated.shell.${platformKey}`, value.profile.path, ConfigurationTarget.USER);
await this._configurationService.updateValue(`terminal.integrated.shellArgs.${platformKey}`, value.profile.args, ConfigurationTarget.USER);
}
public createInstance(container: HTMLElement | undefined, shellLaunchConfig: IShellLaunchConfig): ITerminalInstance {
const instance = this._instantiationService.createInstance(TerminalInstance,
this._terminalFocusContextKey,
this._terminalShellTypeContextKey,
this._terminalAltBufferActiveContextKey,
this._configHelper,
container,
shellLaunchConfig
);
this._onInstanceCreated.fire(instance);
return instance;
}
public createTerminal(shell: IShellLaunchConfig = {}): ITerminalInstance {
if (!shell.isExtensionCustomPtyTerminal && !this.isProcessSupportRegistered) {
throw new Error('Could not create terminal when process support is not registered');
}
if (shell.hideFromUser) {
const instance = this.createInstance(undefined, shell);
this._backgroundedTerminalInstances.push(instance);
this._initInstanceListeners(instance);
return instance;
}
const terminalTab = this._instantiationService.createInstance(TerminalTab, this._terminalContainer, shell);
this._terminalTabs.push(terminalTab);
const instance = terminalTab.terminalInstances[0];
terminalTab.addDisposable(terminalTab.onDisposed(this._onTabDisposed.fire, this._onTabDisposed));
terminalTab.addDisposable(terminalTab.onInstancesChanged(this._onInstancesChanged.fire, this._onInstancesChanged));
this._initInstanceListeners(instance);
if (this.terminalInstances.length === 1) {
// It's the first instance so it should be made active automatically
this.setActiveInstanceByIndex(0);
}
this._onInstancesChanged.fire();
return instance;
}
protected _showBackgroundTerminal(instance: ITerminalInstance): void {
this._backgroundedTerminalInstances.splice(this._backgroundedTerminalInstances.indexOf(instance), 1);
instance.shellLaunchConfig.hideFromUser = false;
const terminalTab = this._instantiationService.createInstance(TerminalTab, this._terminalContainer, instance);
this._terminalTabs.push(terminalTab);
terminalTab.addDisposable(terminalTab.onDisposed(this._onTabDisposed.fire, this._onTabDisposed));
terminalTab.addDisposable(terminalTab.onInstancesChanged(this._onInstancesChanged.fire, this._onInstancesChanged));
if (this.terminalInstances.length === 1) {
// It's the first instance so it should be made active automatically
this.setActiveInstanceByIndex(0);
}
this._onInstancesChanged.fire();
}
public async focusFindWidget(): Promise<void> {
await this.showPanel(false);
const pane = this._viewsService.getActiveViewWithId(TERMINAL_VIEW_ID) as TerminalViewPane;
pane.focusFindWidget();
this._findWidgetVisible.set(true);
}
public hideFindWidget(): void {
const pane = this._viewsService.getActiveViewWithId(TERMINAL_VIEW_ID) as TerminalViewPane;
if (pane) {
pane.hideFindWidget();
this._findWidgetVisible.reset();
pane.focus();
}
}
public findNext(): void {
const pane = this._viewsService.getActiveViewWithId(TERMINAL_VIEW_ID) as TerminalViewPane;
if (pane) {
pane.showFindWidget();
pane.getFindWidget().find(false);
}
}
public findPrevious(): void {
const pane = this._viewsService.getActiveViewWithId(TERMINAL_VIEW_ID) as TerminalViewPane;
if (pane) {
pane.showFindWidget();
pane.getFindWidget().find(true);
}
}
public async setContainers(panelContainer: HTMLElement, terminalContainer: HTMLElement): Promise<void> {
this._configHelper.panelContainer = panelContainer;
this._terminalContainer = terminalContainer;
this._terminalTabs.forEach(tab => tab.attachToElement(terminalContainer));
}
public hidePanel(): void {
// Hide the panel if the terminal is in the panel and it has no sibling views
const location = this._viewDescriptorService.getViewLocationById(TERMINAL_VIEW_ID);
if (location === ViewContainerLocation.Panel) {
const panel = this._viewDescriptorService.getViewContainerByViewId(TERMINAL_VIEW_ID);
if (panel && this._viewDescriptorService.getViewContainerModel(panel).activeViewDescriptors.length === 1) {
this._layoutService.setPanelHidden(true);
}
}
}
}
| src/vs/workbench/contrib/terminal/browser/terminalService.ts | 1 | https://github.com/microsoft/vscode/commit/8aac8643d77aa03300f7c62452b0583a0db2b741 | [
0.9988824725151062,
0.0199887752532959,
0.0001629082835279405,
0.00017385950195603073,
0.13864082098007202
] |
{
"id": 0,
"code_window": [
"export const renameTerminalIcon = registerIcon('terminal-rename', Codicon.gear, localize('renameTerminalIcon', 'Icon for rename in the terminal quick menu.'));\n",
"export const killTerminalIcon = registerIcon('terminal-kill', Codicon.trash, localize('killTerminalIcon', 'Icon for killing a terminal instance.'));\n",
"export const newTerminalIcon = registerIcon('terminal-new', Codicon.add, localize('newTerminalIcon', 'Icon for creating a new terminal instance.'));\n",
"\n",
"export const newQuickLaunchProfileIcon = registerIcon('terminal-quick-launch', Codicon.symbolEvent, localize('newQuickLaunchProfile', 'Icon for creating a new terminal quick launch profile.'));\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace"
],
"after_edit": [
"export const configureTerminalProfileIcon = registerIcon('terminal-configure-profile', Codicon.gear, localize('configureTerminalProfileIcon', 'Icon for creating a new terminal profile.'));"
],
"file_path": "src/vs/workbench/contrib/terminal/browser/terminalIcons.ts",
"type": "replace",
"edit_start_line_idx": 15
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.search-editor {
display: flex;
flex-direction: column;
}
.search-editor .search-results {
flex: 1;
}
.search-editor .query-container {
margin: 0px 12px 12px 2px;
padding-top: 6px;
}
.search-editor .search-widget .toggle-replace-button {
position: absolute;
top: 0;
left: 0;
width: 16px;
height: 100%;
box-sizing: border-box;
background-position: center center;
background-repeat: no-repeat;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
}
.search-editor .search-widget .search-container,
.search-editor .search-widget .replace-container {
margin-left: 18px;
display: flex;
align-items: center;
}
.search-editor .search-widget .monaco-findInput {
display: inline-block;
vertical-align: middle;
width: 100%;
}
.search-editor .search-widget .monaco-inputbox > .ibwrapper {
height: 100%;
}
.search-editor .search-widget .monaco-inputbox > .ibwrapper > .mirror,
.search-editor .search-widget .monaco-inputbox > .ibwrapper > textarea.input {
padding: 3px;
padding-left: 4px;
}
.search-editor .search-widget .monaco-inputbox > .ibwrapper > .mirror {
max-height: 134px;
}
/* NOTE: height is also used in searchWidget.ts as a constant*/
.search-editor .search-widget .monaco-inputbox > .ibwrapper > textarea.input {
overflow: initial;
height: 24px; /* set initial height before measure */
}
.search-editor .monaco-inputbox > .ibwrapper > textarea.input {
scrollbar-width: none; /* Firefox: hide scrollbar */
}
.search-editor .monaco-inputbox > .ibwrapper > textarea.input::-webkit-scrollbar {
display: none;
}
.search-editor .search-widget .context-lines-input {
display: none;
}
.search-editor .search-widget.show-context .context-lines-input {
display: inherit;
margin-left: 5px;
margin-right: 2px;
max-width: 50px;
}
.search-editor .search-widget .replace-container {
margin-top: 6px;
position: relative;
display: inline-flex;
}
.search-editor .search-widget .replace-input {
position: relative;
display: flex;
vertical-align: middle;
width: auto !important;
height: 25px;
}
.search-editor .search-widget .replace-input > .controls {
position: absolute;
top: 3px;
right: 2px;
}
.search-editor .search-widget .replace-container.disabled {
display: none;
}
.search-editor .search-widget .replace-container .monaco-action-bar {
margin-left: 0;
}
.search-editor .search-widget .replace-container .monaco-action-bar {
height: 25px;
}
.search-editor .search-widget .replace-container .monaco-action-bar .action-item .codicon {
background-repeat: no-repeat;
width: 25px;
height: 25px;
margin-right: 0;
display: flex;
align-items: center;
justify-content: center;
}
.search-editor .includes-excludes {
min-height: 1em;
position: relative;
margin: 0 0 0 17px;
}
.search-editor .includes-excludes .expand {
position: absolute;
right: -2px;
cursor: pointer;
width: 25px;
height: 16px;
z-index: 2; /* Force it above the search results message, which has a negative top margin */
}
.search-editor .includes-excludes .file-types {
display: none;
}
.search-editor .includes-excludes.expanded .file-types {
display: inherit;
}
.search-editor .includes-excludes.expanded .file-types:last-child {
padding-bottom: 10px;
}
.search-editor .includes-excludes.expanded h4 {
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
padding: 4px 0 0;
margin: 0;
font-size: 11px;
font-weight: normal;
}
.search-editor .messages {
margin-top: -5px;
cursor: default;
}
.search-editor .message {
padding-left: 22px;
padding-right: 22px;
padding-top: 0px;
}
.search-editor a.prominent {
text-decoration: underline;
}
| src/vs/workbench/contrib/searchEditor/browser/media/searchEditor.css | 0 | https://github.com/microsoft/vscode/commit/8aac8643d77aa03300f7c62452b0583a0db2b741 | [
0.0001765827473718673,
0.00017458196089137346,
0.0001699953863862902,
0.0001747634814819321,
0.0000014486565760307712
] |
{
"id": 0,
"code_window": [
"export const renameTerminalIcon = registerIcon('terminal-rename', Codicon.gear, localize('renameTerminalIcon', 'Icon for rename in the terminal quick menu.'));\n",
"export const killTerminalIcon = registerIcon('terminal-kill', Codicon.trash, localize('killTerminalIcon', 'Icon for killing a terminal instance.'));\n",
"export const newTerminalIcon = registerIcon('terminal-new', Codicon.add, localize('newTerminalIcon', 'Icon for creating a new terminal instance.'));\n",
"\n",
"export const newQuickLaunchProfileIcon = registerIcon('terminal-quick-launch', Codicon.symbolEvent, localize('newQuickLaunchProfile', 'Icon for creating a new terminal quick launch profile.'));\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace"
],
"after_edit": [
"export const configureTerminalProfileIcon = registerIcon('terminal-configure-profile', Codicon.gear, localize('configureTerminalProfileIcon', 'Icon for creating a new terminal profile.'));"
],
"file_path": "src/vs/workbench/contrib/terminal/browser/terminalIcons.ts",
"type": "replace",
"edit_start_line_idx": 15
} | [
{
"kind": 1,
"language": "markdown",
"value": "## tl;dr: Triage Inbox\n\nAll inbox issues but not those that need more information. These issues need to be triaged, e.g assigned to a user or ask for more information",
"editable": true,
"outputs": []
},
{
"kind": 2,
"language": "github-issues",
"value": "$inbox -label:\"needs more info\"",
"editable": true,
"outputs": []
},
{
"kind": 1,
"language": "markdown",
"value": "##### `Config`: defines the inbox query",
"editable": true,
"outputs": []
},
{
"kind": 2,
"language": "github-issues",
"value": "$inbox=repo:microsoft/vscode is:open no:assignee -label:feature-request -label:testplan-item -label:plan-item ",
"editable": true,
"outputs": []
},
{
"kind": 1,
"language": "markdown",
"value": "## Inbox tracking and Issue triage",
"editable": true,
"outputs": []
},
{
"kind": 1,
"language": "markdown",
"value": "New issues or pull requests submitted by the community are initially triaged by an [automatic classification bot](https://github.com/microsoft/vscode-github-triage-actions/tree/master/classifier-deep). Issues that the bot does not correctly triage are then triaged by a team member. The team rotates the inbox tracker on a weekly basis.\n\nA [mirror](https://github.com/JacksonKearl/testissues/issues) of the VS Code issue stream is available with details about how the bot classifies issues, including feature-area classifications and confidence ratings. Per-category confidence thresholds and feature-area ownership data is maintained in [.github/classifier.json](https://github.com/microsoft/vscode/blob/main/.github/classifier.json). \n\n💡 The bot is being run through a GitHub action that runs every 30 minutes. Give the bot the opportunity to classify an issue before doing it manually.\n\n### Inbox Tracking\n\nThe inbox tracker is responsible for the [global inbox](https://github.com/microsoft/vscode/issues?utf8=%E2%9C%93&q=is%3Aopen+no%3Aassignee+-label%3Afeature-request+-label%3Atestplan-item+-label%3Aplan-item) containing all **open issues and pull requests** that\n- are neither **feature requests** nor **test plan items** nor **plan items** and\n- have **no owner assignment**.\n\nThe **inbox tracker** may perform any step described in our [issue triaging documentation](https://github.com/microsoft/vscode/wiki/Issues-Triaging) but its main responsibility is to route issues to the actual feature area owner.\n\nFeature area owners track the **feature area inbox** containing all **open issues and pull requests** that\n- are personally assigned to them and are not assigned to any milestone\n- are labeled with their feature area label and are not assigned to any milestone.\nThis secondary triage may involve any of the steps described in our [issue triaging documentation](https://github.com/microsoft/vscode/wiki/Issues-Triaging) and results in a fully triaged or closed issue.\n\nThe [github triage extension](https://github.com/microsoft/vscode-github-triage-extension) can be used to assist with triaging — it provides a \"Command Palette\"-style list of triaging actions like assignment, labeling, and triggers for various bot actions.",
"editable": true,
"outputs": []
},
{
"kind": 1,
"language": "markdown",
"value": "## All Inbox Items\n\nAll issues that have no assignee and that have neither **feature requests** nor **test plan items** nor **plan items**.",
"editable": true,
"outputs": []
},
{
"kind": 2,
"language": "github-issues",
"value": "$inbox",
"editable": true,
"outputs": []
}
] | .vscode/notebooks/inbox.github-issues | 0 | https://github.com/microsoft/vscode/commit/8aac8643d77aa03300f7c62452b0583a0db2b741 | [
0.00017627303896006197,
0.00017373582522850484,
0.00016674434300512075,
0.00017496602958999574,
0.000003258246124460129
] |
{
"id": 0,
"code_window": [
"export const renameTerminalIcon = registerIcon('terminal-rename', Codicon.gear, localize('renameTerminalIcon', 'Icon for rename in the terminal quick menu.'));\n",
"export const killTerminalIcon = registerIcon('terminal-kill', Codicon.trash, localize('killTerminalIcon', 'Icon for killing a terminal instance.'));\n",
"export const newTerminalIcon = registerIcon('terminal-new', Codicon.add, localize('newTerminalIcon', 'Icon for creating a new terminal instance.'));\n",
"\n",
"export const newQuickLaunchProfileIcon = registerIcon('terminal-quick-launch', Codicon.symbolEvent, localize('newQuickLaunchProfile', 'Icon for creating a new terminal quick launch profile.'));\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace"
],
"after_edit": [
"export const configureTerminalProfileIcon = registerIcon('terminal-configure-profile', Codicon.gear, localize('configureTerminalProfileIcon', 'Icon for creating a new terminal profile.'));"
],
"file_path": "src/vs/workbench/contrib/terminal/browser/terminalIcons.ts",
"type": "replace",
"edit_start_line_idx": 15
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ITerminalContributionService, TerminalContributionService } from './terminalExtensionPoints';
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
registerSingleton(ITerminalContributionService, TerminalContributionService, true);
| src/vs/workbench/contrib/terminal/common/terminalExtensionPoints.contribution.ts | 0 | https://github.com/microsoft/vscode/commit/8aac8643d77aa03300f7c62452b0583a0db2b741 | [
0.0001731355587253347,
0.0001731355587253347,
0.0001731355587253347,
0.0001731355587253347,
0
] |
{
"id": 1,
"code_window": [
"import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService';\n",
"import { ILifecycleService, ShutdownReason, WillShutdownEvent } from 'vs/workbench/services/lifecycle/common/lifecycle';\n",
"import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';\n",
"import { newQuickLaunchProfileIcon } from 'vs/workbench/contrib/terminal/browser/terminalIcons';\n",
"import { equals } from 'vs/base/common/objects';\n",
"\n",
"interface IExtHostReadyEntry {\n",
"\tpromise: Promise<void>;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { configureTerminalProfileIcon } from 'vs/workbench/contrib/terminal/browser/terminalIcons';\n"
],
"file_path": "src/vs/workbench/contrib/terminal/browser/terminalService.ts",
"type": "replace",
"edit_start_line_idx": 34
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { timeout } from 'vs/base/common/async';
import { debounce, throttle } from 'vs/base/common/decorators';
import { Emitter, Event } from 'vs/base/common/event';
import { IDisposable } from 'vs/base/common/lifecycle';
import { basename } from 'vs/base/common/path';
import { isMacintosh, isWeb, isWindows, OperatingSystem } from 'vs/base/common/platform';
import { FindReplaceState } from 'vs/editor/contrib/find/findState';
import * as nls from 'vs/nls';
import { ConfigurationTarget, IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
import { IInstantiationService, optional } from 'vs/platform/instantiation/common/instantiation';
import { IPickOptions, IQuickInputButton, IQuickInputService, IQuickPickItem } from 'vs/platform/quickinput/common/quickInput';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { ILocalTerminalService, IShellLaunchConfig, ITerminalLaunchError, ITerminalsLayoutInfo, ITerminalsLayoutInfoById, TerminalShellType, WindowsShellType } from 'vs/platform/terminal/common/terminal';
import { ThemeIcon } from 'vs/platform/theme/common/themeService';
import { IViewDescriptorService, IViewsService, ViewContainerLocation } from 'vs/workbench/common/views';
import { IRemoteTerminalService, ITerminalExternalLinkProvider, ITerminalInstance, ITerminalService, ITerminalTab, TerminalConnectionState } from 'vs/workbench/contrib/terminal/browser/terminal';
import { TerminalConfigHelper } from 'vs/workbench/contrib/terminal/browser/terminalConfigHelper';
import { TerminalInstance } from 'vs/workbench/contrib/terminal/browser/terminalInstance';
import { TerminalTab } from 'vs/workbench/contrib/terminal/browser/terminalTab';
import { TerminalViewPane } from 'vs/workbench/contrib/terminal/browser/terminalView';
import { IAvailableProfilesRequest, IRemoteTerminalAttachTarget, ITerminalProfile, IStartExtensionTerminalRequest, ITerminalConfigHelper, ITerminalNativeWindowsDelegate, ITerminalProcessExtHostProxy, KEYBINDING_CONTEXT_TERMINAL_ALT_BUFFER_ACTIVE, KEYBINDING_CONTEXT_TERMINAL_FIND_VISIBLE, KEYBINDING_CONTEXT_TERMINAL_FOCUS, KEYBINDING_CONTEXT_TERMINAL_IS_OPEN, KEYBINDING_CONTEXT_TERMINAL_PROCESS_SUPPORTED, KEYBINDING_CONTEXT_TERMINAL_SHELL_TYPE, LinuxDistro, TERMINAL_VIEW_ID, ITerminalProfileObject, ITerminalExecutable, ITerminalProfileSource } from 'vs/workbench/contrib/terminal/common/terminal';
import { escapeNonWindowsPath } from 'vs/workbench/contrib/terminal/common/terminalEnvironment';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService';
import { ILifecycleService, ShutdownReason, WillShutdownEvent } from 'vs/workbench/services/lifecycle/common/lifecycle';
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
import { newQuickLaunchProfileIcon } from 'vs/workbench/contrib/terminal/browser/terminalIcons';
import { equals } from 'vs/base/common/objects';
interface IExtHostReadyEntry {
promise: Promise<void>;
resolve: () => void;
}
export class TerminalService implements ITerminalService {
public _serviceBrand: undefined;
private _isShuttingDown: boolean;
private _terminalFocusContextKey: IContextKey<boolean>;
private _terminalShellTypeContextKey: IContextKey<string>;
private _terminalAltBufferActiveContextKey: IContextKey<boolean>;
private _findWidgetVisible: IContextKey<boolean>;
private _terminalTabs: ITerminalTab[] = [];
private _backgroundedTerminalInstances: ITerminalInstance[] = [];
private get _terminalInstances(): ITerminalInstance[] {
return this._terminalTabs.reduce((p, c) => p.concat(c.terminalInstances), <ITerminalInstance[]>[]);
}
private _findState: FindReplaceState;
private _extHostsReady: { [authority: string]: IExtHostReadyEntry | undefined } = {};
private _activeTabIndex: number;
private _linkProviders: Set<ITerminalExternalLinkProvider> = new Set();
private _linkProviderDisposables: Map<ITerminalExternalLinkProvider, IDisposable[]> = new Map();
private _processSupportContextKey: IContextKey<boolean>;
public get activeTabIndex(): number { return this._activeTabIndex; }
public get terminalInstances(): ITerminalInstance[] { return this._terminalInstances; }
public get terminalTabs(): ITerminalTab[] { return this._terminalTabs; }
public get isProcessSupportRegistered(): boolean { return !!this._processSupportContextKey.get(); }
private _configHelper: TerminalConfigHelper;
private _terminalContainer: HTMLElement | undefined;
private _nativeWindowsDelegate: ITerminalNativeWindowsDelegate | undefined;
private _remoteTerminalsInitPromise: Promise<void> | undefined;
private _localTerminalsInitPromise: Promise<void> | undefined;
private _connectionState: TerminalConnectionState;
private _availableProfiles: ITerminalProfile[] | undefined;
public get configHelper(): ITerminalConfigHelper { return this._configHelper; }
private readonly _onActiveTabChanged = new Emitter<void>();
public get onActiveTabChanged(): Event<void> { return this._onActiveTabChanged.event; }
private readonly _onInstanceCreated = new Emitter<ITerminalInstance>();
public get onInstanceCreated(): Event<ITerminalInstance> { return this._onInstanceCreated.event; }
private readonly _onInstanceDisposed = new Emitter<ITerminalInstance>();
public get onInstanceDisposed(): Event<ITerminalInstance> { return this._onInstanceDisposed.event; }
private readonly _onInstanceProcessIdReady = new Emitter<ITerminalInstance>();
public get onInstanceProcessIdReady(): Event<ITerminalInstance> { return this._onInstanceProcessIdReady.event; }
private readonly _onInstanceLinksReady = new Emitter<ITerminalInstance>();
public get onInstanceLinksReady(): Event<ITerminalInstance> { return this._onInstanceLinksReady.event; }
private readonly _onInstanceRequestStartExtensionTerminal = new Emitter<IStartExtensionTerminalRequest>();
public get onInstanceRequestStartExtensionTerminal(): Event<IStartExtensionTerminalRequest> { return this._onInstanceRequestStartExtensionTerminal.event; }
private readonly _onInstanceDimensionsChanged = new Emitter<ITerminalInstance>();
public get onInstanceDimensionsChanged(): Event<ITerminalInstance> { return this._onInstanceDimensionsChanged.event; }
private readonly _onInstanceMaximumDimensionsChanged = new Emitter<ITerminalInstance>();
public get onInstanceMaximumDimensionsChanged(): Event<ITerminalInstance> { return this._onInstanceMaximumDimensionsChanged.event; }
private readonly _onInstancesChanged = new Emitter<void>();
public get onInstancesChanged(): Event<void> { return this._onInstancesChanged.event; }
private readonly _onInstanceTitleChanged = new Emitter<ITerminalInstance | undefined>();
public get onInstanceTitleChanged(): Event<ITerminalInstance | undefined> { return this._onInstanceTitleChanged.event; }
private readonly _onActiveInstanceChanged = new Emitter<ITerminalInstance | undefined>();
public get onActiveInstanceChanged(): Event<ITerminalInstance | undefined> { return this._onActiveInstanceChanged.event; }
private readonly _onTabDisposed = new Emitter<ITerminalTab>();
public get onTabDisposed(): Event<ITerminalTab> { return this._onTabDisposed.event; }
private readonly _onRequestAvailableProfiles = new Emitter<IAvailableProfilesRequest>();
public get onRequestAvailableProfiles(): Event<IAvailableProfilesRequest> { return this._onRequestAvailableProfiles.event; }
private readonly _onDidRegisterProcessSupport = new Emitter<void>();
public get onDidRegisterProcessSupport(): Event<void> { return this._onDidRegisterProcessSupport.event; }
private readonly _onDidChangeConnectionState = new Emitter<void>();
public get onDidChangeConnectionState(): Event<void> { return this._onDidChangeConnectionState.event; }
public get connectionState(): TerminalConnectionState { return this._connectionState; }
private readonly _onProfilesConfigChanged = new Emitter<void>();
public get onProfilesConfigChanged(): Event<void> { return this._onProfilesConfigChanged.event; }
private readonly _localTerminalService?: ILocalTerminalService;
constructor(
@IContextKeyService private _contextKeyService: IContextKeyService,
@IWorkbenchLayoutService private _layoutService: IWorkbenchLayoutService,
@ILifecycleService lifecycleService: ILifecycleService,
@IDialogService private _dialogService: IDialogService,
@IInstantiationService private _instantiationService: IInstantiationService,
@IRemoteAgentService private _remoteAgentService: IRemoteAgentService,
@IQuickInputService private _quickInputService: IQuickInputService,
@IConfigurationService private _configurationService: IConfigurationService,
@IViewsService private _viewsService: IViewsService,
@IViewDescriptorService private readonly _viewDescriptorService: IViewDescriptorService,
@IWorkbenchEnvironmentService private readonly _environmentService: IWorkbenchEnvironmentService,
@IRemoteTerminalService private readonly _remoteTerminalService: IRemoteTerminalService,
@ITelemetryService private readonly _telemetryService: ITelemetryService,
@IExtensionService private readonly _extensionService: IExtensionService,
@optional(ILocalTerminalService) localTerminalService: ILocalTerminalService
) {
this._localTerminalService = localTerminalService;
this._activeTabIndex = 0;
this._isShuttingDown = false;
this._findState = new FindReplaceState();
lifecycleService.onBeforeShutdown(async e => e.veto(this._onBeforeShutdown(e.reason), 'veto.terminal'));
lifecycleService.onWillShutdown(e => this._onWillShutdown(e));
this._terminalFocusContextKey = KEYBINDING_CONTEXT_TERMINAL_FOCUS.bindTo(this._contextKeyService);
this._terminalShellTypeContextKey = KEYBINDING_CONTEXT_TERMINAL_SHELL_TYPE.bindTo(this._contextKeyService);
this._terminalAltBufferActiveContextKey = KEYBINDING_CONTEXT_TERMINAL_ALT_BUFFER_ACTIVE.bindTo(this._contextKeyService);
this._findWidgetVisible = KEYBINDING_CONTEXT_TERMINAL_FIND_VISIBLE.bindTo(this._contextKeyService);
this._configHelper = this._instantiationService.createInstance(TerminalConfigHelper);
this.onTabDisposed(tab => this._removeTab(tab));
this.onActiveTabChanged(() => {
const instance = this.getActiveInstance();
this._onActiveInstanceChanged.fire(instance ? instance : undefined);
});
this.onInstanceLinksReady(instance => this._setInstanceLinkProviders(instance));
this._handleInstanceContextKeys();
this._processSupportContextKey = KEYBINDING_CONTEXT_TERMINAL_PROCESS_SUPPORTED.bindTo(this._contextKeyService);
this._processSupportContextKey.set(!isWeb || this._remoteAgentService.getConnection() !== null);
this._configurationService.onDidChangeConfiguration(async e => {
if (e.affectsConfiguration('terminal.integrated.profiles.windows') ||
e.affectsConfiguration('terminal.integrated.profiles.osx') ||
e.affectsConfiguration('terminal.integrated.profiles.linux') ||
e.affectsConfiguration('terminal.integrated.showQuickLaunchWslProfiles')) {
this._updateAvailableProfilesNow();
}
});
const enableTerminalReconnection = this.configHelper.config.enablePersistentSessions;
const conn = this._remoteAgentService.getConnection();
const remoteAuthority = conn ? conn.remoteAuthority : 'null';
this._whenExtHostReady(remoteAuthority).then(() => {
this._updateAvailableProfiles();
});
// Connect to the extension host if it's there, set the connection state to connected when
// it's done. This should happen even when there is no extension host.
this._connectionState = TerminalConnectionState.Connecting;
let initPromise: Promise<any>;
if (!!this._environmentService.remoteAuthority && enableTerminalReconnection) {
initPromise = this._remoteTerminalsInitPromise = this._reconnectToRemoteTerminals();
} else if (enableTerminalReconnection) {
initPromise = this._localTerminalsInitPromise = this._reconnectToLocalTerminals();
} else {
initPromise = Promise.resolve();
}
initPromise.then(() => this._setConnected());
}
private _setConnected() {
this._connectionState = TerminalConnectionState.Connected;
this._onDidChangeConnectionState.fire();
}
private async _reconnectToRemoteTerminals(): Promise<void> {
// Reattach to all remote terminals
const layoutInfo = await this._remoteTerminalService.getTerminalLayoutInfo();
const reconnectCounter = this._recreateTerminalTabs(layoutInfo);
/* __GDPR__
"terminalReconnection" : {
"count" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
}
*/
const data = {
count: reconnectCounter
};
this._telemetryService.publicLog('terminalReconnection', data);
// now that terminals have been restored,
// attach listeners to update remote when terminals are changed
this.attachProcessLayoutListeners(true);
}
private async _reconnectToLocalTerminals(): Promise<void> {
if (!this._localTerminalService) {
return;
}
// Reattach to all local terminals
const layoutInfo = await this._localTerminalService.getTerminalLayoutInfo();
if (layoutInfo && layoutInfo.tabs.length > 0) {
this._recreateTerminalTabs(layoutInfo);
}
// now that terminals have been restored,
// attach listeners to update local state when terminals are changed
this.attachProcessLayoutListeners(false);
}
private _recreateTerminalTabs(layoutInfo?: ITerminalsLayoutInfo): number {
let reconnectCounter = 0;
let activeTab: ITerminalTab | undefined;
if (layoutInfo) {
layoutInfo.tabs.forEach(tabLayout => {
const terminalLayouts = tabLayout.terminals.filter(t => t.terminal && t.terminal.isOrphan);
if (terminalLayouts.length) {
reconnectCounter += terminalLayouts.length;
let terminalInstance: ITerminalInstance | undefined;
let tab: ITerminalTab | undefined;
terminalLayouts.forEach((terminalLayout) => {
if (!terminalInstance) {
// create tab and terminal
terminalInstance = this.createTerminal({ attachPersistentProcess: terminalLayout.terminal! });
tab = this._getTabForInstance(terminalInstance);
if (tabLayout.isActive) {
activeTab = tab;
}
} else {
// add split terminals to this tab
this.splitInstance(terminalInstance, { attachPersistentProcess: terminalLayout.terminal! });
}
});
const activeInstance = this.terminalInstances.find(t => {
return t.shellLaunchConfig.attachPersistentProcess?.id === tabLayout.activePersistentProcessId;
});
if (activeInstance) {
this.setActiveInstance(activeInstance);
}
tab?.resizePanes(tabLayout.terminals.map(terminal => terminal.relativeSize));
}
});
if (layoutInfo.tabs.length) {
this.setActiveTabByIndex(activeTab ? this.terminalTabs.indexOf(activeTab) : 0);
}
}
return reconnectCounter;
}
private attachProcessLayoutListeners(isRemote: boolean): void {
this.onActiveTabChanged(() => isRemote ? this._updateRemoteState() : this._updateLocalState());
this.onActiveInstanceChanged(() => isRemote ? this._updateRemoteState() : this._updateLocalState());
this.onInstancesChanged(() => isRemote ? this._updateRemoteState() : this._updateLocalState());
// The state must be updated when the terminal is relaunched, otherwise the persistent
// terminal ID will be stale and the process will be leaked.
this.onInstanceProcessIdReady(() => isRemote ? this._updateRemoteState() : this._updateLocalState());
}
public setNativeWindowsDelegate(delegate: ITerminalNativeWindowsDelegate): void {
this._nativeWindowsDelegate = delegate;
}
public setLinuxDistro(linuxDistro: LinuxDistro): void {
this._configHelper.setLinuxDistro(linuxDistro);
}
private _handleInstanceContextKeys(): void {
const terminalIsOpenContext = KEYBINDING_CONTEXT_TERMINAL_IS_OPEN.bindTo(this._contextKeyService);
const updateTerminalContextKeys = () => {
terminalIsOpenContext.set(this.terminalInstances.length > 0);
};
this.onInstancesChanged(() => updateTerminalContextKeys());
}
public getActiveOrCreateInstance(): ITerminalInstance {
const activeInstance = this.getActiveInstance();
return activeInstance ? activeInstance : this.createTerminal(undefined);
}
public requestStartExtensionTerminal(proxy: ITerminalProcessExtHostProxy, cols: number, rows: number): Promise<ITerminalLaunchError | undefined> {
// The initial request came from the extension host, no need to wait for it
return new Promise<ITerminalLaunchError | undefined>(callback => {
this._onInstanceRequestStartExtensionTerminal.fire({ proxy, cols, rows, callback });
});
}
public async extHostReady(remoteAuthority: string): Promise<void> {
this._createExtHostReadyEntry(remoteAuthority);
this._extHostsReady[remoteAuthority]!.resolve();
}
public getAvailableProfiles(): ITerminalProfile[] {
this._updateAvailableProfiles();
return this._availableProfiles || [];
}
private async _getWorkspaceProfilePermissions(profile: ITerminalProfile): Promise<boolean> {
const platformKey = await this._getPlatformKey();
const profiles = this._configurationService.inspect<{ [key: string]: ITerminalProfileObject }>(`terminal.integrated.profiles.${platformKey}`);
if (!profiles || !profiles.workspaceValue || !profiles.defaultValue) {
return false;
}
const workspaceProfile = Object.entries(profiles.workspaceValue).find(p => p[0] === profile.profileName);
const defaultProfile = Object.entries(profiles.defaultValue).find(p => p[0] === profile.profileName);
if (workspaceProfile && defaultProfile && workspaceProfile[0] === defaultProfile[0]) {
let result = !this._terminalProfileObjectEqual(workspaceProfile[1], defaultProfile[1]);
return result;
} else if (!workspaceProfile && !defaultProfile) {
// user profile
return false;
} else {
// this key is missing from either default or the workspace config
return true;
}
}
private _terminalProfileObjectEqual(one?: ITerminalProfileObject, two?: ITerminalProfileObject): boolean {
if (one === null && two === null) {
return true;
} else if ((one as ITerminalExecutable).path && (two as ITerminalExecutable).path) {
const oneExec = (one as ITerminalExecutable);
const twoExec = (two as ITerminalExecutable);
return ((Array.isArray(oneExec.path) && Array.isArray(twoExec.path) && oneExec.path.length === twoExec.path.length && oneExec.path.every((p, index) => p === twoExec.path[index])) ||
(oneExec.path === twoExec.path)
) && ((Array.isArray(oneExec.args) && Array.isArray(twoExec.args) && oneExec.args?.every((a, index) => a === twoExec.args?.[index])) ||
(oneExec.args === twoExec.args)
);
} else if ((one as ITerminalProfileSource).source && (two as ITerminalProfileSource).source) {
const oneSource = (one as ITerminalProfileSource);
const twoSource = (two as ITerminalProfileSource);
return oneSource.source === twoSource.source;
}
return false;
}
// when relevant config changes, update without debouncing
private async _updateAvailableProfilesNow(): Promise<void> {
const result = await this._detectProfiles(true);
for (const p of result) {
p.isWorkspaceProfile = await this._getWorkspaceProfilePermissions(p);
}
if (!equals(result, this._availableProfiles)) {
this._availableProfiles = result;
this._onProfilesConfigChanged.fire();
}
}
// avoid checking this very often, every ten seconds shoulds suffice
@throttle(10000)
private _updateAvailableProfiles(): Promise<void> {
return this._updateAvailableProfilesNow();
}
private async _detectProfiles(quickLaunchOnly: boolean): Promise<ITerminalProfile[]> {
await this._extensionService.whenInstalledExtensionsRegistered();
// Wait for the remoteAuthority to be ready (and listening for events) before firing
// the event to spawn the ext host process
const conn = this._remoteAgentService.getConnection();
const remoteAuthority = conn ? conn.remoteAuthority : 'null';
await this._whenExtHostReady(remoteAuthority);
return new Promise(r => this._onRequestAvailableProfiles.fire({ callback: r, quickLaunchOnly: quickLaunchOnly }));
}
private async _whenExtHostReady(remoteAuthority: string): Promise<void> {
this._createExtHostReadyEntry(remoteAuthority);
return this._extHostsReady[remoteAuthority]!.promise;
}
private _createExtHostReadyEntry(remoteAuthority: string): void {
if (this._extHostsReady[remoteAuthority]) {
return;
}
let resolve!: () => void;
const promise = new Promise<void>(r => resolve = r);
this._extHostsReady[remoteAuthority] = { promise, resolve };
}
private _onBeforeShutdown(reason: ShutdownReason): boolean | Promise<boolean> {
if (this.terminalInstances.length === 0) {
// No terminal instances, don't veto
return false;
}
const shouldPersistTerminals = this._configHelper.config.enablePersistentSessions && reason === ShutdownReason.RELOAD;
if (this.configHelper.config.confirmOnExit && !shouldPersistTerminals) {
return this._onBeforeShutdownAsync();
}
this._isShuttingDown = true;
return false;
}
private async _onBeforeShutdownAsync(): Promise<boolean> {
// veto if configured to show confirmation and the user chose not to exit
const veto = await this._showTerminalCloseConfirmation();
if (!veto) {
this._isShuttingDown = true;
}
return veto;
}
private _onWillShutdown(e: WillShutdownEvent): void {
// Don't touch processes if the shutdown was a result of reload as they will be reattached
const shouldPersistTerminals = this._configHelper.config.enablePersistentSessions && e.reason === ShutdownReason.RELOAD;
if (shouldPersistTerminals) {
this.terminalInstances.forEach(instance => instance.detachFromProcess());
return;
}
// Force dispose of all terminal instances, don't force immediate disposal of the terminal
// processes on Windows as an additional mitigation for https://github.com/microsoft/vscode/issues/71966
// which causes the pty host to become unresponsive, disconnecting all terminals across all
// windows
this.terminalInstances.forEach(instance => instance.dispose(!isWindows));
this._localTerminalService!.setTerminalLayoutInfo(undefined);
}
public getTabLabels(): string[] {
return this._terminalTabs.filter(tab => tab.terminalInstances.length > 0).map((tab, index) => {
return `${index + 1}: ${tab.title ? tab.title : ''}`;
});
}
public getFindState(): FindReplaceState {
return this._findState;
}
@debounce(500)
private _updateRemoteState(): void {
if (!!this._environmentService.remoteAuthority) {
const state: ITerminalsLayoutInfoById = {
tabs: this.terminalTabs.map(t => t.getLayoutInfo(t === this.getActiveTab()))
};
this._remoteTerminalService.setTerminalLayoutInfo(state);
}
}
@debounce(500)
private _updateLocalState(): void {
const state: ITerminalsLayoutInfoById = {
tabs: this.terminalTabs.map(t => t.getLayoutInfo(t === this.getActiveTab()))
};
this._localTerminalService!.setTerminalLayoutInfo(state);
}
private _removeTab(tab: ITerminalTab): void {
// Get the index of the tab and remove it from the list
const index = this._terminalTabs.indexOf(tab);
const activeTab = this.getActiveTab();
const activeTabIndex = activeTab ? this._terminalTabs.indexOf(activeTab) : -1;
const wasActiveTab = tab === activeTab;
if (index !== -1) {
this._terminalTabs.splice(index, 1);
}
// Adjust focus if the tab was active
if (wasActiveTab && this._terminalTabs.length > 0) {
// TODO: Only focus the new tab if the removed tab had focus?
// const hasFocusOnExit = tab.activeInstance.hadFocusOnExit;
const newIndex = index < this._terminalTabs.length ? index : this._terminalTabs.length - 1;
this.setActiveTabByIndex(newIndex);
const activeInstance = this.getActiveInstance();
if (activeInstance) {
activeInstance.focus(true);
}
} else if (activeTabIndex >= this._terminalTabs.length) {
const newIndex = this._terminalTabs.length - 1;
this.setActiveTabByIndex(newIndex);
}
// Hide the panel if there are no more instances, provided that VS Code is not shutting
// down. When shutting down the panel is locked in place so that it is restored upon next
// launch.
if (this._terminalTabs.length === 0 && !this._isShuttingDown) {
this.hidePanel();
this._onActiveInstanceChanged.fire(undefined);
}
// Fire events
this._onInstancesChanged.fire();
if (wasActiveTab) {
this._onActiveTabChanged.fire();
}
}
public refreshActiveTab(): void {
// Fire active instances changed
this._onActiveTabChanged.fire();
}
public getActiveTab(): ITerminalTab | null {
if (this._activeTabIndex < 0 || this._activeTabIndex >= this._terminalTabs.length) {
return null;
}
return this._terminalTabs[this._activeTabIndex];
}
public getActiveInstance(): ITerminalInstance | null {
const tab = this.getActiveTab();
if (!tab) {
return null;
}
return tab.activeInstance;
}
public doWithActiveInstance<T>(callback: (terminal: ITerminalInstance) => T): T | void {
const instance = this.getActiveInstance();
if (instance) {
return callback(instance);
}
}
public getInstanceFromId(terminalId: number): ITerminalInstance | undefined {
let bgIndex = -1;
this._backgroundedTerminalInstances.forEach((terminalInstance, i) => {
if (terminalInstance.instanceId === terminalId) {
bgIndex = i;
}
});
if (bgIndex !== -1) {
return this._backgroundedTerminalInstances[bgIndex];
}
try {
return this.terminalInstances[this._getIndexFromId(terminalId)];
} catch {
return undefined;
}
}
public getInstanceFromIndex(terminalIndex: number): ITerminalInstance {
return this.terminalInstances[terminalIndex];
}
public setActiveInstance(terminalInstance: ITerminalInstance): void {
// If this was a hideFromUser terminal created by the API this was triggered by show,
// in which case we need to create the terminal tab
if (terminalInstance.shellLaunchConfig.hideFromUser) {
this._showBackgroundTerminal(terminalInstance);
}
this.setActiveInstanceByIndex(this._getIndexFromId(terminalInstance.instanceId));
}
public setActiveTabByIndex(tabIndex: number): void {
if (tabIndex >= this._terminalTabs.length) {
return;
}
const didTabChange = this._activeTabIndex !== tabIndex;
this._activeTabIndex = tabIndex;
this._terminalTabs.forEach((t, i) => t.setVisible(i === this._activeTabIndex));
if (didTabChange) {
this._onActiveTabChanged.fire();
}
}
public isAttachedToTerminal(remoteTerm: IRemoteTerminalAttachTarget): boolean {
return this.terminalInstances.some(term => term.processId === remoteTerm.pid);
}
public async initializeTerminals(): Promise<void> {
if (this._remoteTerminalsInitPromise) {
await this._remoteTerminalsInitPromise;
} else if (this._localTerminalsInitPromise) {
await this._localTerminalsInitPromise;
}
if (this.terminalTabs.length === 0 && this.isProcessSupportRegistered) {
this.createTerminal();
}
}
private _getInstanceFromGlobalInstanceIndex(index: number): { tab: ITerminalTab, tabIndex: number, instance: ITerminalInstance, localInstanceIndex: number } | null {
let currentTabIndex = 0;
while (index >= 0 && currentTabIndex < this._terminalTabs.length) {
const tab = this._terminalTabs[currentTabIndex];
const count = tab.terminalInstances.length;
if (index < count) {
return {
tab,
tabIndex: currentTabIndex,
instance: tab.terminalInstances[index],
localInstanceIndex: index
};
}
index -= count;
currentTabIndex++;
}
return null;
}
public setActiveInstanceByIndex(terminalIndex: number): void {
const query = this._getInstanceFromGlobalInstanceIndex(terminalIndex);
if (!query) {
return;
}
query.tab.setActiveInstanceByIndex(query.localInstanceIndex);
const didTabChange = this._activeTabIndex !== query.tabIndex;
this._activeTabIndex = query.tabIndex;
this._terminalTabs.forEach((t, i) => t.setVisible(i === query.tabIndex));
// Only fire the event if there was a change
if (didTabChange) {
this._onActiveTabChanged.fire();
}
}
public setActiveTabToNext(): void {
if (this._terminalTabs.length <= 1) {
return;
}
let newIndex = this._activeTabIndex + 1;
if (newIndex >= this._terminalTabs.length) {
newIndex = 0;
}
this.setActiveTabByIndex(newIndex);
}
public setActiveTabToPrevious(): void {
if (this._terminalTabs.length <= 1) {
return;
}
let newIndex = this._activeTabIndex - 1;
if (newIndex < 0) {
newIndex = this._terminalTabs.length - 1;
}
this.setActiveTabByIndex(newIndex);
}
public splitInstance(instanceToSplit: ITerminalInstance, shellLaunchConfig: IShellLaunchConfig = {}): ITerminalInstance | null {
const tab = this._getTabForInstance(instanceToSplit);
if (!tab) {
return null;
}
const instance = tab.split(shellLaunchConfig);
this._initInstanceListeners(instance);
this._onInstancesChanged.fire();
this._terminalTabs.forEach((t, i) => t.setVisible(i === this._activeTabIndex));
return instance;
}
protected _initInstanceListeners(instance: ITerminalInstance): void {
instance.addDisposable(instance.onDisposed(this._onInstanceDisposed.fire, this._onInstanceDisposed));
instance.addDisposable(instance.onTitleChanged(this._onInstanceTitleChanged.fire, this._onInstanceTitleChanged));
instance.addDisposable(instance.onProcessIdReady(this._onInstanceProcessIdReady.fire, this._onInstanceProcessIdReady));
instance.addDisposable(instance.onLinksReady(this._onInstanceLinksReady.fire, this._onInstanceLinksReady));
instance.addDisposable(instance.onDimensionsChanged(() => {
this._onInstanceDimensionsChanged.fire(instance);
if (this.configHelper.config.enablePersistentSessions && this.isProcessSupportRegistered) {
!!this._environmentService.remoteAuthority ? this._updateRemoteState() : this._updateLocalState();
}
}));
instance.addDisposable(instance.onMaximumDimensionsChanged(() => this._onInstanceMaximumDimensionsChanged.fire(instance)));
instance.addDisposable(instance.onFocus(this._onActiveInstanceChanged.fire, this._onActiveInstanceChanged));
}
public registerProcessSupport(isSupported: boolean): void {
if (!isSupported) {
return;
}
this._processSupportContextKey.set(isSupported);
this._onDidRegisterProcessSupport.fire();
}
public registerLinkProvider(linkProvider: ITerminalExternalLinkProvider): IDisposable {
const disposables: IDisposable[] = [];
this._linkProviders.add(linkProvider);
for (const instance of this.terminalInstances) {
if (instance.areLinksReady) {
disposables.push(instance.registerLinkProvider(linkProvider));
}
}
this._linkProviderDisposables.set(linkProvider, disposables);
return {
dispose: () => {
const disposables = this._linkProviderDisposables.get(linkProvider) || [];
for (const disposable of disposables) {
disposable.dispose();
}
this._linkProviders.delete(linkProvider);
}
};
}
private _setInstanceLinkProviders(instance: ITerminalInstance): void {
for (const linkProvider of this._linkProviders) {
const disposables = this._linkProviderDisposables.get(linkProvider);
const provider = instance.registerLinkProvider(linkProvider);
disposables?.push(provider);
}
}
private _getTabForInstance(instance: ITerminalInstance): ITerminalTab | undefined {
return this._terminalTabs.find(tab => tab.terminalInstances.indexOf(instance) !== -1);
}
public async showPanel(focus?: boolean): Promise<void> {
const pane = this._viewsService.getActiveViewWithId(TERMINAL_VIEW_ID) as TerminalViewPane;
if (!pane) {
await this._viewsService.openView(TERMINAL_VIEW_ID, focus);
}
if (focus) {
// Do the focus call asynchronously as going through the
// command palette will force editor focus
await timeout(0);
const instance = this.getActiveInstance();
if (instance) {
await instance.focusWhenReady(true);
}
}
}
private _getIndexFromId(terminalId: number): number {
let terminalIndex = -1;
this.terminalInstances.forEach((terminalInstance, i) => {
if (terminalInstance.instanceId === terminalId) {
terminalIndex = i;
}
});
if (terminalIndex === -1) {
throw new Error(`Terminal with ID ${terminalId} does not exist (has it already been disposed?)`);
}
return terminalIndex;
}
public async manageWorkspaceShellPermissions(): Promise<void> {
const allowItem: IQuickPickItem = { label: nls.localize('workbench.action.terminal.allowWorkspaceShell', "Allow Workspace Shell Configuration") };
const disallowItem: IQuickPickItem = { label: nls.localize('workbench.action.terminal.disallowWorkspaceShell', "Disallow Workspace Shell Configuration") };
const value = await this._quickInputService.pick([allowItem, disallowItem], { canPickMany: false });
if (!value) {
return;
}
this.configHelper.setWorkspaceShellAllowed(value === allowItem);
}
protected async _showTerminalCloseConfirmation(): Promise<boolean> {
let message: string;
if (this.terminalInstances.length === 1) {
message = nls.localize('terminalService.terminalCloseConfirmationSingular', "There is an active terminal session, do you want to kill it?");
} else {
message = nls.localize('terminalService.terminalCloseConfirmationPlural', "There are {0} active terminal sessions, do you want to kill them?", this.terminalInstances.length);
}
const res = await this._dialogService.confirm({
message,
type: 'warning',
});
return !res.confirmed;
}
public preparePathForTerminalAsync(originalPath: string, executable: string, title: string, shellType: TerminalShellType): Promise<string> {
return new Promise<string>(c => {
if (!executable) {
c(originalPath);
return;
}
const hasSpace = originalPath.indexOf(' ') !== -1;
const hasParens = originalPath.indexOf('(') !== -1 || originalPath.indexOf(')') !== -1;
const pathBasename = basename(executable, '.exe');
const isPowerShell = pathBasename === 'pwsh' ||
title === 'pwsh' ||
pathBasename === 'powershell' ||
title === 'powershell';
if (isPowerShell && (hasSpace || originalPath.indexOf('\'') !== -1)) {
c(`& '${originalPath.replace(/'/g, '\'\'')}'`);
return;
}
if (hasParens && isPowerShell) {
c(`& '${originalPath}'`);
return;
}
if (isWindows) {
// 17063 is the build number where wsl path was introduced.
// Update Windows uriPath to be executed in WSL.
if (shellType !== undefined) {
if (shellType === WindowsShellType.GitBash) {
c(originalPath.replace(/\\/g, '/'));
return;
}
else if (shellType === WindowsShellType.Wsl) {
if (this._nativeWindowsDelegate && this._nativeWindowsDelegate.getWindowsBuildNumber() >= 17063) {
c(this._nativeWindowsDelegate.getWslPath(originalPath));
} else {
c(originalPath.replace(/\\/g, '/'));
}
return;
}
if (hasSpace) {
c('"' + originalPath + '"');
} else {
c(originalPath);
}
} else {
const lowerExecutable = executable.toLowerCase();
if (this._nativeWindowsDelegate && this._nativeWindowsDelegate.getWindowsBuildNumber() >= 17063 &&
(lowerExecutable.indexOf('wsl') !== -1 || (lowerExecutable.indexOf('bash.exe') !== -1 && lowerExecutable.toLowerCase().indexOf('git') === -1))) {
c(this._nativeWindowsDelegate.getWslPath(originalPath));
return;
} else if (hasSpace) {
c('"' + originalPath + '"');
} else {
c(originalPath);
}
}
return;
}
c(escapeNonWindowsPath(originalPath));
});
}
private async _getPlatformKey(): Promise<string> {
const env = await this._remoteAgentService.getEnvironment();
if (env) {
return env.os === OperatingSystem.Windows ? 'windows' : (env.os === OperatingSystem.Macintosh ? 'osx' : 'linux');
}
return isWindows ? 'windows' : (isMacintosh ? 'osx' : 'linux');
}
public async selectDefaultProfile(): Promise<void> {
const profiles = await this._detectProfiles(false);
const platformKey = await this._getPlatformKey();
interface IProfileQuickPickItem extends IQuickPickItem {
profile: ITerminalProfile;
}
const options: IPickOptions<IProfileQuickPickItem> = {
placeHolder: nls.localize('terminal.integrated.chooseWindowsShell', "Select your preferred terminal shell, you can change this later in your settings"),
onDidTriggerItemButton: async (context) => {
const configKey = `terminal.integrated.profiles.${platformKey}`;
const configProfiles = this._configurationService.inspect<{ [key: string]: ITerminalProfileObject }>(configKey);
const existingProfiles = configProfiles.userValue ? Object.keys(configProfiles.userValue) : [];
const name = await this._quickInputService.input({
prompt: nls.localize('enterTerminalProfileName', "Enter profile name"),
value: context.item.profile.profileName,
validateInput: async input => {
if (existingProfiles.includes(input)) {
return nls.localize('terminalProfileAlreadyExists', "A profile already exists with that name");
}
return undefined;
}
});
if (!name) {
return;
}
const newConfigValue: { [key: string]: ITerminalProfileObject } = { ...configProfiles.userValue } ?? {};
newConfigValue[name] = {
path: context.item.profile.path,
args: context.item.profile.args
};
await this._configurationService.updateValue(configKey, newConfigValue, ConfigurationTarget.USER);
}
};
const quickPickItems = profiles.map((profile): IProfileQuickPickItem => {
const buttons: IQuickInputButton[] = [{
iconClass: ThemeIcon.asClassName(newQuickLaunchProfileIcon),
tooltip: nls.localize('createQuickLaunchProfile', "Create a quick launch profile based on this shell")
}];
if (profile.args) {
if (typeof profile.args === 'string') {
return { label: profile.profileName, description: `${profile.path} ${profile.args}`, profile, buttons };
}
const argsString = profile.args.map(e => {
if (e.includes(' ')) {
return `"${e.replace('/"/g', '\\"')}"`;
}
return e;
}).join(' ');
return { label: profile.profileName, description: `${profile.path} ${argsString}`, profile, buttons };
}
return { label: profile.profileName, description: profile.path, profile, buttons };
});
const value = await this._quickInputService.pick(quickPickItems, options);
if (!value) {
return;
}
await this._configurationService.updateValue(`terminal.integrated.shell.${platformKey}`, value.profile.path, ConfigurationTarget.USER);
await this._configurationService.updateValue(`terminal.integrated.shellArgs.${platformKey}`, value.profile.args, ConfigurationTarget.USER);
}
public createInstance(container: HTMLElement | undefined, shellLaunchConfig: IShellLaunchConfig): ITerminalInstance {
const instance = this._instantiationService.createInstance(TerminalInstance,
this._terminalFocusContextKey,
this._terminalShellTypeContextKey,
this._terminalAltBufferActiveContextKey,
this._configHelper,
container,
shellLaunchConfig
);
this._onInstanceCreated.fire(instance);
return instance;
}
public createTerminal(shell: IShellLaunchConfig = {}): ITerminalInstance {
if (!shell.isExtensionCustomPtyTerminal && !this.isProcessSupportRegistered) {
throw new Error('Could not create terminal when process support is not registered');
}
if (shell.hideFromUser) {
const instance = this.createInstance(undefined, shell);
this._backgroundedTerminalInstances.push(instance);
this._initInstanceListeners(instance);
return instance;
}
const terminalTab = this._instantiationService.createInstance(TerminalTab, this._terminalContainer, shell);
this._terminalTabs.push(terminalTab);
const instance = terminalTab.terminalInstances[0];
terminalTab.addDisposable(terminalTab.onDisposed(this._onTabDisposed.fire, this._onTabDisposed));
terminalTab.addDisposable(terminalTab.onInstancesChanged(this._onInstancesChanged.fire, this._onInstancesChanged));
this._initInstanceListeners(instance);
if (this.terminalInstances.length === 1) {
// It's the first instance so it should be made active automatically
this.setActiveInstanceByIndex(0);
}
this._onInstancesChanged.fire();
return instance;
}
protected _showBackgroundTerminal(instance: ITerminalInstance): void {
this._backgroundedTerminalInstances.splice(this._backgroundedTerminalInstances.indexOf(instance), 1);
instance.shellLaunchConfig.hideFromUser = false;
const terminalTab = this._instantiationService.createInstance(TerminalTab, this._terminalContainer, instance);
this._terminalTabs.push(terminalTab);
terminalTab.addDisposable(terminalTab.onDisposed(this._onTabDisposed.fire, this._onTabDisposed));
terminalTab.addDisposable(terminalTab.onInstancesChanged(this._onInstancesChanged.fire, this._onInstancesChanged));
if (this.terminalInstances.length === 1) {
// It's the first instance so it should be made active automatically
this.setActiveInstanceByIndex(0);
}
this._onInstancesChanged.fire();
}
public async focusFindWidget(): Promise<void> {
await this.showPanel(false);
const pane = this._viewsService.getActiveViewWithId(TERMINAL_VIEW_ID) as TerminalViewPane;
pane.focusFindWidget();
this._findWidgetVisible.set(true);
}
public hideFindWidget(): void {
const pane = this._viewsService.getActiveViewWithId(TERMINAL_VIEW_ID) as TerminalViewPane;
if (pane) {
pane.hideFindWidget();
this._findWidgetVisible.reset();
pane.focus();
}
}
public findNext(): void {
const pane = this._viewsService.getActiveViewWithId(TERMINAL_VIEW_ID) as TerminalViewPane;
if (pane) {
pane.showFindWidget();
pane.getFindWidget().find(false);
}
}
public findPrevious(): void {
const pane = this._viewsService.getActiveViewWithId(TERMINAL_VIEW_ID) as TerminalViewPane;
if (pane) {
pane.showFindWidget();
pane.getFindWidget().find(true);
}
}
public async setContainers(panelContainer: HTMLElement, terminalContainer: HTMLElement): Promise<void> {
this._configHelper.panelContainer = panelContainer;
this._terminalContainer = terminalContainer;
this._terminalTabs.forEach(tab => tab.attachToElement(terminalContainer));
}
public hidePanel(): void {
// Hide the panel if the terminal is in the panel and it has no sibling views
const location = this._viewDescriptorService.getViewLocationById(TERMINAL_VIEW_ID);
if (location === ViewContainerLocation.Panel) {
const panel = this._viewDescriptorService.getViewContainerByViewId(TERMINAL_VIEW_ID);
if (panel && this._viewDescriptorService.getViewContainerModel(panel).activeViewDescriptors.length === 1) {
this._layoutService.setPanelHidden(true);
}
}
}
}
| src/vs/workbench/contrib/terminal/browser/terminalService.ts | 1 | https://github.com/microsoft/vscode/commit/8aac8643d77aa03300f7c62452b0583a0db2b741 | [
0.998978853225708,
0.04037805646657944,
0.000162042400916107,
0.000171427454915829,
0.19308075308799744
] |
{
"id": 1,
"code_window": [
"import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService';\n",
"import { ILifecycleService, ShutdownReason, WillShutdownEvent } from 'vs/workbench/services/lifecycle/common/lifecycle';\n",
"import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';\n",
"import { newQuickLaunchProfileIcon } from 'vs/workbench/contrib/terminal/browser/terminalIcons';\n",
"import { equals } from 'vs/base/common/objects';\n",
"\n",
"interface IExtHostReadyEntry {\n",
"\tpromise: Promise<void>;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { configureTerminalProfileIcon } from 'vs/workbench/contrib/terminal/browser/terminalIcons';\n"
],
"file_path": "src/vs/workbench/contrib/terminal/browser/terminalService.ts",
"type": "replace",
"edit_start_line_idx": 34
} | /*---------------------------------------------------------------------------------------------
* 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 { renderExpressionValue, renderVariable, renderViewTree } from 'vs/workbench/contrib/debug/browser/baseDebugView';
import * as dom from 'vs/base/browser/dom';
import { Expression, Variable, Scope, StackFrame, Thread } from 'vs/workbench/contrib/debug/common/debugModel';
import { HighlightedLabel } from 'vs/base/browser/ui/highlightedlabel/highlightedLabel';
import { LinkDetector } from 'vs/workbench/contrib/debug/browser/linkDetector';
import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock';
import { workbenchInstantiationService } from 'vs/workbench/test/browser/workbenchTestServices';
import { createMockSession } from 'vs/workbench/contrib/debug/test/browser/callStack.test';
import { isStatusbarInDebugMode } from 'vs/workbench/contrib/debug/browser/statusbarColorProvider';
import { State } from 'vs/workbench/contrib/debug/common/debug';
import { isWindows } from 'vs/base/common/platform';
import { MockSession, createMockDebugModel } from 'vs/workbench/contrib/debug/test/browser/mockDebug';
const $ = dom.$;
suite('Debug - Base Debug View', () => {
let linkDetector: LinkDetector;
/**
* Instantiate services for use by the functions being tested.
*/
setup(() => {
const instantiationService: TestInstantiationService = <TestInstantiationService>workbenchInstantiationService();
linkDetector = instantiationService.createInstance(LinkDetector);
});
test('render view tree', () => {
const container = $('.container');
const treeContainer = renderViewTree(container);
assert.strictEqual(treeContainer.className, 'debug-view-content');
assert.strictEqual(container.childElementCount, 1);
assert.strictEqual(container.firstChild, treeContainer);
assert.strictEqual(treeContainer instanceof HTMLDivElement, true);
});
test('render expression value', () => {
let container = $('.container');
renderExpressionValue('render \n me', container, { showHover: true });
assert.strictEqual(container.className, 'value');
assert.strictEqual(container.title, 'render \n me');
assert.strictEqual(container.textContent, 'render \n me');
const expression = new Expression('console');
expression.value = 'Object';
container = $('.container');
renderExpressionValue(expression, container, { colorize: true });
assert.strictEqual(container.className, 'value unavailable error');
expression.available = true;
expression.value = '"string value"';
container = $('.container');
renderExpressionValue(expression, container, { colorize: true, linkDetector });
assert.strictEqual(container.className, 'value string');
assert.strictEqual(container.textContent, '"string value"');
expression.type = 'boolean';
container = $('.container');
renderExpressionValue(expression, container, { colorize: true });
assert.strictEqual(container.className, 'value boolean');
assert.strictEqual(container.textContent, expression.value);
expression.value = 'this is a long string';
container = $('.container');
renderExpressionValue(expression, container, { colorize: true, maxValueLength: 4, linkDetector });
assert.strictEqual(container.textContent, 'this...');
expression.value = isWindows ? 'C:\\foo.js:5' : '/foo.js:5';
container = $('.container');
renderExpressionValue(expression, container, { colorize: true, linkDetector });
assert.ok(container.querySelector('a'));
assert.strictEqual(container.querySelector('a')!.textContent, expression.value);
});
test('render variable', () => {
const session = new MockSession();
const thread = new Thread(session, 'mockthread', 1);
const stackFrame = new StackFrame(thread, 1, null!, 'app.js', 'normal', { startLineNumber: 1, startColumn: 1, endLineNumber: undefined!, endColumn: undefined! }, 0, true);
const scope = new Scope(stackFrame, 1, 'local', 1, false, 10, 10);
let variable = new Variable(session, 1, scope, 2, 'foo', 'bar.foo', undefined!, 0, 0, {}, 'string');
let expression = $('.');
let name = $('.');
let value = $('.');
let label = new HighlightedLabel(name, false);
renderVariable(variable, { expression, name, value, label }, false, []);
assert.strictEqual(label.element.textContent, 'foo');
assert.strictEqual(value.textContent, '');
assert.strictEqual(value.title, '');
variable.value = 'hey';
expression = $('.');
name = $('.');
value = $('.');
renderVariable(variable, { expression, name, value, label }, false, [], linkDetector);
assert.strictEqual(value.textContent, 'hey');
assert.strictEqual(label.element.textContent, 'foo:');
assert.strictEqual(label.element.title, 'string');
variable.value = isWindows ? 'C:\\foo.js:5' : '/foo.js:5';
expression = $('.');
name = $('.');
value = $('.');
renderVariable(variable, { expression, name, value, label }, false, [], linkDetector);
assert.ok(value.querySelector('a'));
assert.strictEqual(value.querySelector('a')!.textContent, variable.value);
variable = new Variable(session, 1, scope, 2, 'console', 'console', '5', 0, 0, { kind: 'virtual' });
expression = $('.');
name = $('.');
value = $('.');
renderVariable(variable, { expression, name, value, label }, false, [], linkDetector);
assert.strictEqual(name.className, 'virtual');
assert.strictEqual(label.element.textContent, 'console:');
assert.strictEqual(label.element.title, 'console');
assert.strictEqual(value.className, 'value number');
});
test('statusbar in debug mode', () => {
const model = createMockDebugModel();
const session = createMockSession(model);
assert.strictEqual(isStatusbarInDebugMode(State.Inactive, undefined), false);
assert.strictEqual(isStatusbarInDebugMode(State.Initializing, session), false);
assert.strictEqual(isStatusbarInDebugMode(State.Running, session), true);
assert.strictEqual(isStatusbarInDebugMode(State.Stopped, session), true);
session.configuration.noDebug = true;
assert.strictEqual(isStatusbarInDebugMode(State.Running, session), false);
});
});
| src/vs/workbench/contrib/debug/test/browser/baseDebugView.test.ts | 0 | https://github.com/microsoft/vscode/commit/8aac8643d77aa03300f7c62452b0583a0db2b741 | [
0.00017598638078197837,
0.00017259677406400442,
0.0001641159615246579,
0.00017393045709468424,
0.000003259567620261805
] |
{
"id": 1,
"code_window": [
"import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService';\n",
"import { ILifecycleService, ShutdownReason, WillShutdownEvent } from 'vs/workbench/services/lifecycle/common/lifecycle';\n",
"import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';\n",
"import { newQuickLaunchProfileIcon } from 'vs/workbench/contrib/terminal/browser/terminalIcons';\n",
"import { equals } from 'vs/base/common/objects';\n",
"\n",
"interface IExtHostReadyEntry {\n",
"\tpromise: Promise<void>;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { configureTerminalProfileIcon } from 'vs/workbench/contrib/terminal/browser/terminalIcons';\n"
],
"file_path": "src/vs/workbench/contrib/terminal/browser/terminalService.ts",
"type": "replace",
"edit_start_line_idx": 34
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as osLib from 'os';
import { virtualMachineHint } from 'vs/base/node/id';
import { IDiagnosticsService, IMachineInfo, WorkspaceStats, WorkspaceStatItem, PerformanceInfo, SystemInfo, IRemoteDiagnosticInfo, IRemoteDiagnosticError, isRemoteDiagnosticError, IWorkspaceInformation } from 'vs/platform/diagnostics/common/diagnostics';
import { exists, readFile } from 'fs';
import { join, basename } from 'vs/base/common/path';
import { parse, ParseError, getNodeType } from 'vs/base/common/json';
import { listProcesses } from 'vs/base/node/ps';
import { IProductService } from 'vs/platform/product/common/productService';
import { isWindows, isLinux } from 'vs/base/common/platform';
import { URI } from 'vs/base/common/uri';
import { ProcessItem } from 'vs/base/common/processes';
import { IMainProcessInfo } from 'vs/platform/launch/common/launch';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { Iterable } from 'vs/base/common/iterator';
import { Schemas } from 'vs/base/common/network';
import { ByteSize } from 'vs/platform/files/common/files';
import { IDirent, readdir } from 'vs/base/node/pfs';
export interface VersionInfo {
vscodeVersion: string;
os: string;
}
export interface ProcessInfo {
cpu: number;
memory: number;
pid: number;
name: string;
}
interface ConfigFilePatterns {
tag: string;
filePattern: RegExp;
relativePathPattern?: RegExp;
}
export async function collectWorkspaceStats(folder: string, filter: string[]): Promise<WorkspaceStats> {
const configFilePatterns: ConfigFilePatterns[] = [
{ tag: 'grunt.js', filePattern: /^gruntfile\.js$/i },
{ tag: 'gulp.js', filePattern: /^gulpfile\.js$/i },
{ tag: 'tsconfig.json', filePattern: /^tsconfig\.json$/i },
{ tag: 'package.json', filePattern: /^package\.json$/i },
{ tag: 'jsconfig.json', filePattern: /^jsconfig\.json$/i },
{ tag: 'tslint.json', filePattern: /^tslint\.json$/i },
{ tag: 'eslint.json', filePattern: /^eslint\.json$/i },
{ tag: 'tasks.json', filePattern: /^tasks\.json$/i },
{ tag: 'launch.json', filePattern: /^launch\.json$/i },
{ tag: 'settings.json', filePattern: /^settings\.json$/i },
{ tag: 'webpack.config.js', filePattern: /^webpack\.config\.js$/i },
{ tag: 'project.json', filePattern: /^project\.json$/i },
{ tag: 'makefile', filePattern: /^makefile$/i },
{ tag: 'sln', filePattern: /^.+\.sln$/i },
{ tag: 'csproj', filePattern: /^.+\.csproj$/i },
{ tag: 'cmake', filePattern: /^.+\.cmake$/i },
{ tag: 'github-actions', filePattern: /^.+\.yml$/i, relativePathPattern: /^\.github(?:\/|\\)workflows$/i }
];
const fileTypes = new Map<string, number>();
const configFiles = new Map<string, number>();
const MAX_FILES = 20000;
function collect(root: string, dir: string, filter: string[], token: { count: number, maxReached: boolean }): Promise<void> {
const relativePath = dir.substring(root.length + 1);
return new Promise(async resolve => {
let files: IDirent[];
try {
files = await readdir(dir, { withFileTypes: true });
} catch (error) {
// Ignore folders that can't be read
resolve();
return;
}
if (token.count >= MAX_FILES) {
token.count += files.length;
token.maxReached = true;
resolve();
return;
}
let pending = files.length;
if (pending === 0) {
resolve();
return;
}
let filesToRead = files;
if (token.count + files.length > MAX_FILES) {
token.maxReached = true;
pending = MAX_FILES - token.count;
filesToRead = files.slice(0, pending);
}
token.count += files.length;
for (const file of filesToRead) {
if (file.isDirectory()) {
if (!filter.includes(file.name)) {
await collect(root, join(dir, file.name), filter, token);
}
if (--pending === 0) {
resolve();
return;
}
} else {
const index = file.name.lastIndexOf('.');
if (index >= 0) {
const fileType = file.name.substring(index + 1);
if (fileType) {
fileTypes.set(fileType, (fileTypes.get(fileType) ?? 0) + 1);
}
}
for (const configFile of configFilePatterns) {
if (configFile.relativePathPattern?.test(relativePath) !== false && configFile.filePattern.test(file.name)) {
configFiles.set(configFile.tag, (configFiles.get(configFile.tag) ?? 0) + 1);
}
}
if (--pending === 0) {
resolve();
return;
}
}
}
});
}
const token: { count: number, maxReached: boolean } = { count: 0, maxReached: false };
await collect(folder, folder, filter, token);
const launchConfigs = await collectLaunchConfigs(folder);
return {
configFiles: asSortedItems(configFiles),
fileTypes: asSortedItems(fileTypes),
fileCount: token.count,
maxFilesReached: token.maxReached,
launchConfigFiles: launchConfigs
};
}
function asSortedItems(items: Map<string, number>): WorkspaceStatItem[] {
return [
...Iterable.map(items.entries(), ([name, count]) => ({ name: name, count: count }))
].sort((a, b) => b.count - a.count);
}
export function getMachineInfo(): IMachineInfo {
const machineInfo: IMachineInfo = {
os: `${osLib.type()} ${osLib.arch()} ${osLib.release()}`,
memory: `${(osLib.totalmem() / ByteSize.GB).toFixed(2)}GB (${(osLib.freemem() / ByteSize.GB).toFixed(2)}GB free)`,
vmHint: `${Math.round((virtualMachineHint.value() * 100))}%`,
};
const cpus = osLib.cpus();
if (cpus && cpus.length > 0) {
machineInfo.cpus = `${cpus[0].model} (${cpus.length} x ${cpus[0].speed})`;
}
return machineInfo;
}
export function collectLaunchConfigs(folder: string): Promise<WorkspaceStatItem[]> {
let launchConfigs = new Map<string, number>();
let launchConfig = join(folder, '.vscode', 'launch.json');
return new Promise((resolve, reject) => {
exists(launchConfig, (doesExist) => {
if (doesExist) {
readFile(launchConfig, (err, contents) => {
if (err) {
return resolve([]);
}
const errors: ParseError[] = [];
const json = parse(contents.toString(), errors);
if (errors.length) {
console.log(`Unable to parse ${launchConfig}`);
return resolve([]);
}
if (getNodeType(json) === 'object' && json['configurations']) {
for (const each of json['configurations']) {
const type = each['type'];
if (type) {
if (launchConfigs.has(type)) {
launchConfigs.set(type, launchConfigs.get(type)! + 1);
} else {
launchConfigs.set(type, 1);
}
}
}
}
return resolve(asSortedItems(launchConfigs));
});
} else {
return resolve([]);
}
});
});
}
export class DiagnosticsService implements IDiagnosticsService {
declare readonly _serviceBrand: undefined;
constructor(
@ITelemetryService private readonly telemetryService: ITelemetryService,
@IProductService private readonly productService: IProductService
) { }
private formatMachineInfo(info: IMachineInfo): string {
const output: string[] = [];
output.push(`OS Version: ${info.os}`);
output.push(`CPUs: ${info.cpus}`);
output.push(`Memory (System): ${info.memory}`);
output.push(`VM: ${info.vmHint}`);
return output.join('\n');
}
private formatEnvironment(info: IMainProcessInfo): string {
const output: string[] = [];
output.push(`Version: ${this.productService.nameShort} ${this.productService.version} (${this.productService.commit || 'Commit unknown'}, ${this.productService.date || 'Date unknown'})`);
output.push(`OS Version: ${osLib.type()} ${osLib.arch()} ${osLib.release()}`);
const cpus = osLib.cpus();
if (cpus && cpus.length > 0) {
output.push(`CPUs: ${cpus[0].model} (${cpus.length} x ${cpus[0].speed})`);
}
output.push(`Memory (System): ${(osLib.totalmem() / ByteSize.GB).toFixed(2)}GB (${(osLib.freemem() / ByteSize.GB).toFixed(2)}GB free)`);
if (!isWindows) {
output.push(`Load (avg): ${osLib.loadavg().map(l => Math.round(l)).join(', ')}`); // only provided on Linux/macOS
}
output.push(`VM: ${Math.round((virtualMachineHint.value() * 100))}%`);
output.push(`Screen Reader: ${info.screenReader ? 'yes' : 'no'}`);
output.push(`Process Argv: ${info.mainArguments.join(' ')}`);
output.push(`GPU Status: ${this.expandGPUFeatures(info.gpuFeatureStatus)}`);
return output.join('\n');
}
public async getPerformanceInfo(info: IMainProcessInfo, remoteData: (IRemoteDiagnosticInfo | IRemoteDiagnosticError)[]): Promise<PerformanceInfo> {
return Promise.all<ProcessItem, string>([listProcesses(info.mainPID), this.formatWorkspaceMetadata(info)]).then(async result => {
let [rootProcess, workspaceInfo] = result;
let processInfo = this.formatProcessList(info, rootProcess);
remoteData.forEach(diagnostics => {
if (isRemoteDiagnosticError(diagnostics)) {
processInfo += `\n${diagnostics.errorMessage}`;
workspaceInfo += `\n${diagnostics.errorMessage}`;
} else {
processInfo += `\n\nRemote: ${diagnostics.hostName}`;
if (diagnostics.processes) {
processInfo += `\n${this.formatProcessList(info, diagnostics.processes)}`;
}
if (diagnostics.workspaceMetadata) {
workspaceInfo += `\n| Remote: ${diagnostics.hostName}`;
for (const folder of Object.keys(diagnostics.workspaceMetadata)) {
const metadata = diagnostics.workspaceMetadata[folder];
let countMessage = `${metadata.fileCount} files`;
if (metadata.maxFilesReached) {
countMessage = `more than ${countMessage}`;
}
workspaceInfo += `| Folder (${folder}): ${countMessage}`;
workspaceInfo += this.formatWorkspaceStats(metadata);
}
}
}
});
return {
processInfo,
workspaceInfo
};
});
}
public async getSystemInfo(info: IMainProcessInfo, remoteData: (IRemoteDiagnosticInfo | IRemoteDiagnosticError)[]): Promise<SystemInfo> {
const { memory, vmHint, os, cpus } = getMachineInfo();
const systemInfo: SystemInfo = {
os,
memory,
cpus,
vmHint,
processArgs: `${info.mainArguments.join(' ')}`,
gpuStatus: info.gpuFeatureStatus,
screenReader: `${info.screenReader ? 'yes' : 'no'}`,
remoteData
};
if (!isWindows) {
systemInfo.load = `${osLib.loadavg().map(l => Math.round(l)).join(', ')}`;
}
if (isLinux) {
systemInfo.linuxEnv = {
desktopSession: process.env['DESKTOP_SESSION'],
xdgSessionDesktop: process.env['XDG_SESSION_DESKTOP'],
xdgCurrentDesktop: process.env['XDG_CURRENT_DESKTOP'],
xdgSessionType: process.env['XDG_SESSION_TYPE']
};
}
return Promise.resolve(systemInfo);
}
public async getDiagnostics(info: IMainProcessInfo, remoteDiagnostics: (IRemoteDiagnosticInfo | IRemoteDiagnosticError)[]): Promise<string> {
const output: string[] = [];
return listProcesses(info.mainPID).then(async rootProcess => {
// Environment Info
output.push('');
output.push(this.formatEnvironment(info));
// Process List
output.push('');
output.push(this.formatProcessList(info, rootProcess));
// Workspace Stats
if (info.windows.some(window => window.folderURIs && window.folderURIs.length > 0 && !window.remoteAuthority)) {
output.push('');
output.push('Workspace Stats: ');
output.push(await this.formatWorkspaceMetadata(info));
}
remoteDiagnostics.forEach(diagnostics => {
if (isRemoteDiagnosticError(diagnostics)) {
output.push(`\n${diagnostics.errorMessage}`);
} else {
output.push('\n\n');
output.push(`Remote: ${diagnostics.hostName}`);
output.push(this.formatMachineInfo(diagnostics.machineInfo));
if (diagnostics.processes) {
output.push(this.formatProcessList(info, diagnostics.processes));
}
if (diagnostics.workspaceMetadata) {
for (const folder of Object.keys(diagnostics.workspaceMetadata)) {
const metadata = diagnostics.workspaceMetadata[folder];
let countMessage = `${metadata.fileCount} files`;
if (metadata.maxFilesReached) {
countMessage = `more than ${countMessage}`;
}
output.push(`Folder (${folder}): ${countMessage}`);
output.push(this.formatWorkspaceStats(metadata));
}
}
}
});
output.push('');
output.push('');
return output.join('\n');
});
}
private formatWorkspaceStats(workspaceStats: WorkspaceStats): string {
const output: string[] = [];
const lineLength = 60;
let col = 0;
const appendAndWrap = (name: string, count: number) => {
const item = ` ${name}(${count})`;
if (col + item.length > lineLength) {
output.push(line);
line = '| ';
col = line.length;
}
else {
col += item.length;
}
line += item;
};
// File Types
let line = '| File types:';
const maxShown = 10;
let max = workspaceStats.fileTypes.length > maxShown ? maxShown : workspaceStats.fileTypes.length;
for (let i = 0; i < max; i++) {
const item = workspaceStats.fileTypes[i];
appendAndWrap(item.name, item.count);
}
output.push(line);
// Conf Files
if (workspaceStats.configFiles.length >= 0) {
line = '| Conf files:';
col = 0;
workspaceStats.configFiles.forEach((item) => {
appendAndWrap(item.name, item.count);
});
output.push(line);
}
if (workspaceStats.launchConfigFiles.length > 0) {
let line = '| Launch Configs:';
workspaceStats.launchConfigFiles.forEach(each => {
const item = each.count > 1 ? ` ${each.name}(${each.count})` : ` ${each.name}`;
line += item;
});
output.push(line);
}
return output.join('\n');
}
private expandGPUFeatures(gpuFeatures: any): string {
const longestFeatureName = Math.max(...Object.keys(gpuFeatures).map(feature => feature.length));
// Make columns aligned by adding spaces after feature name
return Object.keys(gpuFeatures).map(feature => `${feature}: ${' '.repeat(longestFeatureName - feature.length)} ${gpuFeatures[feature]}`).join('\n ');
}
private formatWorkspaceMetadata(info: IMainProcessInfo): Promise<string> {
const output: string[] = [];
const workspaceStatPromises: Promise<void>[] = [];
info.windows.forEach(window => {
if (window.folderURIs.length === 0 || !!window.remoteAuthority) {
return;
}
output.push(`| Window (${window.title})`);
window.folderURIs.forEach(uriComponents => {
const folderUri = URI.revive(uriComponents);
if (folderUri.scheme === Schemas.file) {
const folder = folderUri.fsPath;
workspaceStatPromises.push(collectWorkspaceStats(folder, ['node_modules', '.git']).then(stats => {
let countMessage = `${stats.fileCount} files`;
if (stats.maxFilesReached) {
countMessage = `more than ${countMessage}`;
}
output.push(`| Folder (${basename(folder)}): ${countMessage}`);
output.push(this.formatWorkspaceStats(stats));
}).catch(error => {
output.push(`| Error: Unable to collect workspace stats for folder ${folder} (${error.toString()})`);
}));
} else {
output.push(`| Folder (${folderUri.toString()}): Workspace stats not available.`);
}
});
});
return Promise.all(workspaceStatPromises)
.then(_ => output.join('\n'))
.catch(e => `Unable to collect workspace stats: ${e}`);
}
private formatProcessList(info: IMainProcessInfo, rootProcess: ProcessItem): string {
const mapPidToWindowTitle = new Map<number, string>();
info.windows.forEach(window => mapPidToWindowTitle.set(window.pid, window.title));
const output: string[] = [];
output.push('CPU %\tMem MB\t PID\tProcess');
if (rootProcess) {
this.formatProcessItem(info.mainPID, mapPidToWindowTitle, output, rootProcess, 0);
}
return output.join('\n');
}
private formatProcessItem(mainPid: number, mapPidToWindowTitle: Map<number, string>, output: string[], item: ProcessItem, indent: number): void {
const isRoot = (indent === 0);
// Format name with indent
let name: string;
if (isRoot) {
name = item.pid === mainPid ? `${this.productService.applicationName} main` : 'remote agent';
} else {
name = `${' '.repeat(indent)} ${item.name}`;
if (item.name === 'window') {
name = `${name} (${mapPidToWindowTitle.get(item.pid)})`;
}
}
const memory = process.platform === 'win32' ? item.mem : (osLib.totalmem() * (item.mem / 100));
output.push(`${item.load.toFixed(0).padStart(5, ' ')}\t${(memory / ByteSize.MB).toFixed(0).padStart(6, ' ')}\t${item.pid.toFixed(0).padStart(6, ' ')}\t${name}`);
// Recurse into children if any
if (Array.isArray(item.children)) {
item.children.forEach(child => this.formatProcessItem(mainPid, mapPidToWindowTitle, output, child, indent + 1));
}
}
public async reportWorkspaceStats(workspace: IWorkspaceInformation): Promise<void> {
for (const { uri } of workspace.folders) {
const folderUri = URI.revive(uri);
if (folderUri.scheme !== Schemas.file) {
continue;
}
const folder = folderUri.fsPath;
try {
const stats = await collectWorkspaceStats(folder, ['node_modules', '.git']);
type WorkspaceStatsClassification = {
'workspace.id': { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
rendererSessionId: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
};
type WorkspaceStatsEvent = {
'workspace.id': string | undefined;
rendererSessionId: string;
};
this.telemetryService.publicLog2<WorkspaceStatsEvent, WorkspaceStatsClassification>('workspace.stats', {
'workspace.id': workspace.telemetryId,
rendererSessionId: workspace.rendererSessionId
});
type WorkspaceStatsFileClassification = {
rendererSessionId: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
type: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
count: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
};
type WorkspaceStatsFileEvent = {
rendererSessionId: string;
type: string;
count: number;
};
stats.fileTypes.forEach(e => {
this.telemetryService.publicLog2<WorkspaceStatsFileEvent, WorkspaceStatsFileClassification>('workspace.stats.file', {
rendererSessionId: workspace.rendererSessionId,
type: e.name,
count: e.count
});
});
stats.launchConfigFiles.forEach(e => {
this.telemetryService.publicLog2<WorkspaceStatsFileEvent, WorkspaceStatsFileClassification>('workspace.stats.launchConfigFile', {
rendererSessionId: workspace.rendererSessionId,
type: e.name,
count: e.count
});
});
stats.configFiles.forEach(e => {
this.telemetryService.publicLog2<WorkspaceStatsFileEvent, WorkspaceStatsFileClassification>('workspace.stats.configFiles', {
rendererSessionId: workspace.rendererSessionId,
type: e.name,
count: e.count
});
});
} catch {
// Report nothing if collecting metadata fails.
}
}
}
}
| src/vs/platform/diagnostics/node/diagnosticsService.ts | 0 | https://github.com/microsoft/vscode/commit/8aac8643d77aa03300f7c62452b0583a0db2b741 | [
0.00020415605104062706,
0.00017297192243859172,
0.00016509456327185035,
0.00017256826686207205,
0.000005406216132541886
] |
{
"id": 1,
"code_window": [
"import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService';\n",
"import { ILifecycleService, ShutdownReason, WillShutdownEvent } from 'vs/workbench/services/lifecycle/common/lifecycle';\n",
"import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';\n",
"import { newQuickLaunchProfileIcon } from 'vs/workbench/contrib/terminal/browser/terminalIcons';\n",
"import { equals } from 'vs/base/common/objects';\n",
"\n",
"interface IExtHostReadyEntry {\n",
"\tpromise: Promise<void>;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { configureTerminalProfileIcon } from 'vs/workbench/contrib/terminal/browser/terminalIcons';\n"
],
"file_path": "src/vs/workbench/contrib/terminal/browser/terminalService.ts",
"type": "replace",
"edit_start_line_idx": 34
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { RawContextKey } from 'vs/platform/contextkey/common/contextkey';
export const FindInFilesActionId = 'workbench.action.findInFiles';
export const FocusActiveEditorCommandId = 'search.action.focusActiveEditor';
export const FocusSearchFromResults = 'search.action.focusSearchFromResults';
export const OpenMatch = 'search.action.openResult';
export const OpenMatchToSide = 'search.action.openResultToSide';
export const RemoveActionId = 'search.action.remove';
export const CopyPathCommandId = 'search.action.copyPath';
export const CopyMatchCommandId = 'search.action.copyMatch';
export const CopyAllCommandId = 'search.action.copyAll';
export const OpenInEditorCommandId = 'search.action.openInEditor';
export const ClearSearchHistoryCommandId = 'search.action.clearHistory';
export const FocusSearchListCommandID = 'search.action.focusSearchList';
export const ReplaceActionId = 'search.action.replace';
export const ReplaceAllInFileActionId = 'search.action.replaceAllInFile';
export const ReplaceAllInFolderActionId = 'search.action.replaceAllInFolder';
export const CloseReplaceWidgetActionId = 'closeReplaceInFilesWidget';
export const ToggleCaseSensitiveCommandId = 'toggleSearchCaseSensitive';
export const ToggleWholeWordCommandId = 'toggleSearchWholeWord';
export const ToggleRegexCommandId = 'toggleSearchRegex';
export const TogglePreserveCaseId = 'toggleSearchPreserveCase';
export const AddCursorsAtSearchResults = 'addCursorsAtSearchResults';
export const RevealInSideBarForSearchResults = 'search.action.revealInSideBar';
export const SearchViewVisibleKey = new RawContextKey<boolean>('searchViewletVisible', true);
export const SearchViewFocusedKey = new RawContextKey<boolean>('searchViewletFocus', false);
export const InputBoxFocusedKey = new RawContextKey<boolean>('inputBoxFocus', false);
export const SearchInputBoxFocusedKey = new RawContextKey<boolean>('searchInputBoxFocus', false);
export const ReplaceInputBoxFocusedKey = new RawContextKey<boolean>('replaceInputBoxFocus', false);
export const PatternIncludesFocusedKey = new RawContextKey<boolean>('patternIncludesInputBoxFocus', false);
export const PatternExcludesFocusedKey = new RawContextKey<boolean>('patternExcludesInputBoxFocus', false);
export const ReplaceActiveKey = new RawContextKey<boolean>('replaceActive', false);
export const HasSearchResults = new RawContextKey<boolean>('hasSearchResult', false);
export const FirstMatchFocusKey = new RawContextKey<boolean>('firstMatchFocus', false);
export const FileMatchOrMatchFocusKey = new RawContextKey<boolean>('fileMatchOrMatchFocus', false); // This is actually, Match or File or Folder
export const FileMatchOrFolderMatchFocusKey = new RawContextKey<boolean>('fileMatchOrFolderMatchFocus', false);
export const FileMatchOrFolderMatchWithResourceFocusKey = new RawContextKey<boolean>('fileMatchOrFolderMatchWithResourceFocus', false); // Excludes "Other files"
export const FileFocusKey = new RawContextKey<boolean>('fileMatchFocus', false);
export const FolderFocusKey = new RawContextKey<boolean>('folderMatchFocus', false);
export const MatchFocusKey = new RawContextKey<boolean>('matchFocus', false);
export const ViewHasSearchPatternKey = new RawContextKey<boolean>('viewHasSearchPattern', false);
export const ViewHasReplacePatternKey = new RawContextKey<boolean>('viewHasReplacePattern', false);
export const ViewHasFilePatternKey = new RawContextKey<boolean>('viewHasFilePattern', false);
export const ViewHasSomeCollapsibleKey = new RawContextKey<boolean>('viewHasSomeCollapsibleResult', false);
| src/vs/workbench/contrib/search/common/constants.ts | 0 | https://github.com/microsoft/vscode/commit/8aac8643d77aa03300f7c62452b0583a0db2b741 | [
0.0001756221172399819,
0.0001745677291182801,
0.00017248863878194243,
0.00017509268946014345,
0.0000010791887916639098
] |
{
"id": 2,
"code_window": [
"\t\tinterface IProfileQuickPickItem extends IQuickPickItem {\n",
"\t\t\tprofile: ITerminalProfile;\n",
"\t\t}\n",
"\t\tconst options: IPickOptions<IProfileQuickPickItem> = {\n",
"\t\t\tplaceHolder: nls.localize('terminal.integrated.chooseWindowsShell', \"Select your preferred terminal shell, you can change this later in your settings\"),\n",
"\t\t\tonDidTriggerItemButton: async (context) => {\n",
"\t\t\t\tconst configKey = `terminal.integrated.profiles.${platformKey}`;\n",
"\t\t\t\tconst configProfiles = this._configurationService.inspect<{ [key: string]: ITerminalProfileObject }>(configKey);\n",
"\t\t\t\tconst existingProfiles = configProfiles.userValue ? Object.keys(configProfiles.userValue) : [];\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tplaceHolder: nls.localize('terminal.integrated.chooseWindowsShell', \"Select your preferred terminal profile, you can change this later in your settings\"),\n"
],
"file_path": "src/vs/workbench/contrib/terminal/browser/terminalService.ts",
"type": "replace",
"edit_start_line_idx": 849
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Codicon } from 'vs/base/common/codicons';
import { localize } from 'vs/nls';
import { registerIcon } from 'vs/platform/theme/common/iconRegistry';
export const terminalViewIcon = registerIcon('terminal-view-icon', Codicon.terminal, localize('terminalViewIcon', 'View icon of the terminal view.'));
export const renameTerminalIcon = registerIcon('terminal-rename', Codicon.gear, localize('renameTerminalIcon', 'Icon for rename in the terminal quick menu.'));
export const killTerminalIcon = registerIcon('terminal-kill', Codicon.trash, localize('killTerminalIcon', 'Icon for killing a terminal instance.'));
export const newTerminalIcon = registerIcon('terminal-new', Codicon.add, localize('newTerminalIcon', 'Icon for creating a new terminal instance.'));
export const newQuickLaunchProfileIcon = registerIcon('terminal-quick-launch', Codicon.symbolEvent, localize('newQuickLaunchProfile', 'Icon for creating a new terminal quick launch profile.'));
| src/vs/workbench/contrib/terminal/browser/terminalIcons.ts | 1 | https://github.com/microsoft/vscode/commit/8aac8643d77aa03300f7c62452b0583a0db2b741 | [
0.0004871187557000667,
0.00032666430342942476,
0.00016620985115878284,
0.00032666430342942476,
0.00016045445227064192
] |
{
"id": 2,
"code_window": [
"\t\tinterface IProfileQuickPickItem extends IQuickPickItem {\n",
"\t\t\tprofile: ITerminalProfile;\n",
"\t\t}\n",
"\t\tconst options: IPickOptions<IProfileQuickPickItem> = {\n",
"\t\t\tplaceHolder: nls.localize('terminal.integrated.chooseWindowsShell', \"Select your preferred terminal shell, you can change this later in your settings\"),\n",
"\t\t\tonDidTriggerItemButton: async (context) => {\n",
"\t\t\t\tconst configKey = `terminal.integrated.profiles.${platformKey}`;\n",
"\t\t\t\tconst configProfiles = this._configurationService.inspect<{ [key: string]: ITerminalProfileObject }>(configKey);\n",
"\t\t\t\tconst existingProfiles = configProfiles.userValue ? Object.keys(configProfiles.userValue) : [];\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tplaceHolder: nls.localize('terminal.integrated.chooseWindowsShell', \"Select your preferred terminal profile, you can change this later in your settings\"),\n"
],
"file_path": "src/vs/workbench/contrib/terminal/browser/terminalService.ts",
"type": "replace",
"edit_start_line_idx": 849
} | {
"version": "0.2.0",
"compounds": [
{
"name": "Debug Extension and Language Server",
"configurations": ["Launch Extension", "Attach Language Server"]
}
],
"configurations": [
{
"name": "Launch Extension",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
"--extensionDevelopmentPath=${workspaceFolder}"
],
"stopOnEntry": false,
"sourceMaps": true,
"outFiles": ["${workspaceFolder}/client/out/**/*.js"]
},
{
"name": "Launch Tests",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": ["--extensionDevelopmentPath=${workspaceFolder}", "--extensionTestsPath=${workspaceFolder}/client/out/test" ],
"stopOnEntry": false,
"sourceMaps": true,
"outFiles": ["${workspaceFolder}/client/out/test/**/*.js"]
},
{
"name": "Attach Language Server",
"type": "node",
"request": "attach",
"port": 6045,
"protocol": "inspector",
"sourceMaps": true,
"outFiles": ["${workspaceFolder}/server/out/**/*.js"],
"restart": true
}
]
} | extensions/html-language-features/.vscode/launch.json | 0 | https://github.com/microsoft/vscode/commit/8aac8643d77aa03300f7c62452b0583a0db2b741 | [
0.0001755181438056752,
0.00017372806905768812,
0.00017143465811386704,
0.00017469169688411057,
0.0000016034667851272388
] |
{
"id": 2,
"code_window": [
"\t\tinterface IProfileQuickPickItem extends IQuickPickItem {\n",
"\t\t\tprofile: ITerminalProfile;\n",
"\t\t}\n",
"\t\tconst options: IPickOptions<IProfileQuickPickItem> = {\n",
"\t\t\tplaceHolder: nls.localize('terminal.integrated.chooseWindowsShell', \"Select your preferred terminal shell, you can change this later in your settings\"),\n",
"\t\t\tonDidTriggerItemButton: async (context) => {\n",
"\t\t\t\tconst configKey = `terminal.integrated.profiles.${platformKey}`;\n",
"\t\t\t\tconst configProfiles = this._configurationService.inspect<{ [key: string]: ITerminalProfileObject }>(configKey);\n",
"\t\t\t\tconst existingProfiles = configProfiles.userValue ? Object.keys(configProfiles.userValue) : [];\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tplaceHolder: nls.localize('terminal.integrated.chooseWindowsShell', \"Select your preferred terminal profile, you can change this later in your settings\"),\n"
],
"file_path": "src/vs/workbench/contrib/terminal/browser/terminalService.ts",
"type": "replace",
"edit_start_line_idx": 849
} | "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 });
const ts = require("typescript");
const fs_1 = require("fs");
const path_1 = require("path");
const minimatch_1 = require("minimatch");
//
// #############################################################################################
//
// A custom typescript checker for the specific task of detecting the use of certain types in a
// layer that does not allow such use. For example:
// - using DOM globals in common/node/electron-main layer (e.g. HTMLElement)
// - using node.js globals in common/browser layer (e.g. process)
//
// Make changes to below RULES to lift certain files from these checks only if absolutely needed
//
// #############################################################################################
//
// Types we assume are present in all implementations of JS VMs (node.js, browsers)
// Feel free to add more core types as you see needed if present in node.js and browsers
const CORE_TYPES = [
'require',
'setTimeout',
'clearTimeout',
'setInterval',
'clearInterval',
'console',
'log',
'info',
'warn',
'error',
'group',
'groupEnd',
'table',
'assert',
'Error',
'String',
'throws',
'stack',
'captureStackTrace',
'stackTraceLimit',
'TextDecoder',
'TextEncoder',
'encode',
'decode',
'self',
'trimLeft',
'trimRight'
];
// Types that are defined in a common layer but are known to be only
// available in native environments should not be allowed in browser
const NATIVE_TYPES = [
'NativeParsedArgs',
'INativeEnvironmentService',
'AbstractNativeEnvironmentService',
'INativeWindowConfiguration',
'ICommonNativeHostService'
];
const RULES = [
// Tests: skip
{
target: '**/vs/**/test/**',
skip: true // -> skip all test files
},
// Common: vs/base/common/platform.ts
{
target: '**/vs/base/common/platform.ts',
allowedTypes: [
...CORE_TYPES,
// Safe access to postMessage() and friends
'MessageEvent',
'data'
],
disallowedTypes: NATIVE_TYPES,
disallowedDefinitions: [
'lib.dom.d.ts',
'@types/node' // no node.js
]
},
// Common: vs/platform/environment/common/*
{
target: '**/vs/platform/environment/common/*.ts',
disallowedTypes: [ /* Ignore native types that are defined from here */],
allowedTypes: CORE_TYPES,
disallowedDefinitions: [
'lib.dom.d.ts',
'@types/node' // no node.js
]
},
// Common: vs/platform/windows/common/windows.ts
{
target: '**/vs/platform/windows/common/windows.ts',
disallowedTypes: [ /* Ignore native types that are defined from here */],
allowedTypes: CORE_TYPES,
disallowedDefinitions: [
'lib.dom.d.ts',
'@types/node' // no node.js
]
},
// Common: vs/platform/native/common/native.ts
{
target: '**/vs/platform/native/common/native.ts',
disallowedTypes: [ /* Ignore native types that are defined from here */],
allowedTypes: CORE_TYPES,
disallowedDefinitions: [
'lib.dom.d.ts',
'@types/node' // no node.js
]
},
// Common: vs/workbench/api/common/extHostExtensionService.ts
{
target: '**/vs/workbench/api/common/extHostExtensionService.ts',
allowedTypes: [
...CORE_TYPES,
// Safe access to global
'global'
],
disallowedTypes: NATIVE_TYPES,
disallowedDefinitions: [
'lib.dom.d.ts',
'@types/node' // no node.js
]
},
// Common
{
target: '**/vs/**/common/**',
allowedTypes: CORE_TYPES,
disallowedTypes: NATIVE_TYPES,
disallowedDefinitions: [
'lib.dom.d.ts',
'@types/node' // no node.js
]
},
// Browser
{
target: '**/vs/**/browser/**',
allowedTypes: CORE_TYPES,
disallowedTypes: NATIVE_TYPES,
disallowedDefinitions: [
'@types/node' // no node.js
]
},
// Browser (editor contrib)
{
target: '**/src/vs/editor/contrib/**',
allowedTypes: CORE_TYPES,
disallowedTypes: NATIVE_TYPES,
disallowedDefinitions: [
'@types/node' // no node.js
]
},
// node.js
{
target: '**/vs/**/node/**',
allowedTypes: [
...CORE_TYPES,
// --> types from node.d.ts that duplicate from lib.dom.d.ts
'URL',
'protocol',
'hostname',
'port',
'pathname',
'search',
'username',
'password'
],
disallowedDefinitions: [
'lib.dom.d.ts' // no DOM
]
},
// Electron (sandbox)
{
target: '**/vs/**/electron-sandbox/**',
allowedTypes: CORE_TYPES,
disallowedDefinitions: [
'@types/node' // no node.js
]
},
// Electron (renderer): skip
{
target: '**/vs/**/electron-browser/**',
skip: true // -> supports all types
},
// Electron (main)
{
target: '**/vs/**/electron-main/**',
allowedTypes: [
...CORE_TYPES,
// --> types from electron.d.ts that duplicate from lib.dom.d.ts
'Event',
'Request'
],
disallowedDefinitions: [
'lib.dom.d.ts' // no DOM
]
}
];
const TS_CONFIG_PATH = path_1.join(__dirname, '../../', 'src', 'tsconfig.json');
let hasErrors = false;
function checkFile(program, sourceFile, rule) {
checkNode(sourceFile);
function checkNode(node) {
var _a, _b;
if (node.kind !== ts.SyntaxKind.Identifier) {
return ts.forEachChild(node, checkNode); // recurse down
}
const text = node.getText(sourceFile);
if ((_a = rule.allowedTypes) === null || _a === void 0 ? void 0 : _a.some(allowed => allowed === text)) {
return; // override
}
if ((_b = rule.disallowedTypes) === null || _b === void 0 ? void 0 : _b.some(disallowed => disallowed === text)) {
const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
console.log(`[build/lib/layersChecker.ts]: Reference to '${text}' violates layer '${rule.target}' (${sourceFile.fileName} (${line + 1},${character + 1})`);
hasErrors = true;
return;
}
const checker = program.getTypeChecker();
const symbol = checker.getSymbolAtLocation(node);
if (symbol) {
const declarations = symbol.declarations;
if (Array.isArray(declarations)) {
for (const declaration of declarations) {
if (declaration) {
const parent = declaration.parent;
if (parent) {
const parentSourceFile = parent.getSourceFile();
if (parentSourceFile) {
const definitionFileName = parentSourceFile.fileName;
if (rule.disallowedDefinitions) {
for (const disallowedDefinition of rule.disallowedDefinitions) {
if (definitionFileName.indexOf(disallowedDefinition) >= 0) {
const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
console.log(`[build/lib/layersChecker.ts]: Reference to '${text}' from '${disallowedDefinition}' violates layer '${rule.target}' (${sourceFile.fileName} (${line + 1},${character + 1})`);
hasErrors = true;
return;
}
}
}
}
}
}
}
}
}
}
}
function createProgram(tsconfigPath) {
const tsConfig = ts.readConfigFile(tsconfigPath, ts.sys.readFile);
const configHostParser = { fileExists: fs_1.existsSync, readDirectory: ts.sys.readDirectory, readFile: file => fs_1.readFileSync(file, 'utf8'), useCaseSensitiveFileNames: process.platform === 'linux' };
const tsConfigParsed = ts.parseJsonConfigFileContent(tsConfig.config, configHostParser, path_1.resolve(path_1.dirname(tsconfigPath)), { noEmit: true });
const compilerHost = ts.createCompilerHost(tsConfigParsed.options, true);
return ts.createProgram(tsConfigParsed.fileNames, tsConfigParsed.options, compilerHost);
}
//
// Create program and start checking
//
const program = createProgram(TS_CONFIG_PATH);
for (const sourceFile of program.getSourceFiles()) {
for (const rule of RULES) {
if (minimatch_1.match([sourceFile.fileName], rule.target).length > 0) {
if (!rule.skip) {
checkFile(program, sourceFile, rule);
}
break;
}
}
}
if (hasErrors) {
process.exit(1);
}
| build/lib/layersChecker.js | 0 | https://github.com/microsoft/vscode/commit/8aac8643d77aa03300f7c62452b0583a0db2b741 | [
0.0007452352438122034,
0.00021446341997943819,
0.00016863249766174704,
0.00017423907411284745,
0.0001463987136958167
] |
{
"id": 2,
"code_window": [
"\t\tinterface IProfileQuickPickItem extends IQuickPickItem {\n",
"\t\t\tprofile: ITerminalProfile;\n",
"\t\t}\n",
"\t\tconst options: IPickOptions<IProfileQuickPickItem> = {\n",
"\t\t\tplaceHolder: nls.localize('terminal.integrated.chooseWindowsShell', \"Select your preferred terminal shell, you can change this later in your settings\"),\n",
"\t\t\tonDidTriggerItemButton: async (context) => {\n",
"\t\t\t\tconst configKey = `terminal.integrated.profiles.${platformKey}`;\n",
"\t\t\t\tconst configProfiles = this._configurationService.inspect<{ [key: string]: ITerminalProfileObject }>(configKey);\n",
"\t\t\t\tconst existingProfiles = configProfiles.userValue ? Object.keys(configProfiles.userValue) : [];\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tplaceHolder: nls.localize('terminal.integrated.chooseWindowsShell', \"Select your preferred terminal profile, you can change this later in your settings\"),\n"
],
"file_path": "src/vs/workbench/contrib/terminal/browser/terminalService.ts",
"type": "replace",
"edit_start_line_idx": 849
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IViewletViewOptions } from 'vs/workbench/browser/parts/views/viewsViewlet';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextKeyService, RawContextKey, IContextKey, ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { localize } from 'vs/nls';
import { IDebugService, CONTEXT_DEBUGGERS_AVAILABLE } from 'vs/workbench/contrib/debug/common/debug';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { ViewPane } from 'vs/workbench/browser/parts/views/viewPane';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IViewDescriptorService, IViewsRegistry, Extensions, ViewContentGroups } from 'vs/workbench/common/views';
import { Registry } from 'vs/platform/registry/common/platform';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { WorkbenchStateContext } from 'vs/workbench/browser/contextkeys';
import { OpenFolderAction, OpenFileAction, OpenFileFolderAction } from 'vs/workbench/browser/actions/workspaceActions';
import { isMacintosh } from 'vs/base/common/platform';
import { isCodeEditor } from 'vs/editor/browser/editorBrowser';
import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { DisposableStore } from 'vs/base/common/lifecycle';
import { SELECT_AND_START_ID, DEBUG_CONFIGURE_COMMAND_ID, DEBUG_START_COMMAND_ID } from 'vs/workbench/contrib/debug/browser/debugCommands';
const debugStartLanguageKey = 'debugStartLanguage';
const CONTEXT_DEBUG_START_LANGUAGE = new RawContextKey<string>(debugStartLanguageKey, undefined);
const CONTEXT_DEBUGGER_INTERESTED_IN_ACTIVE_EDITOR = new RawContextKey<boolean>('debuggerInterestedInActiveEditor', false);
export class WelcomeView extends ViewPane {
static ID = 'workbench.debug.welcome';
static LABEL = localize('run', "Run");
private debugStartLanguageContext: IContextKey<string | undefined>;
private debuggerInterestedContext: IContextKey<boolean>;
constructor(
options: IViewletViewOptions,
@IThemeService themeService: IThemeService,
@IKeybindingService keybindingService: IKeybindingService,
@IContextMenuService contextMenuService: IContextMenuService,
@IConfigurationService configurationService: IConfigurationService,
@IContextKeyService contextKeyService: IContextKeyService,
@IDebugService private readonly debugService: IDebugService,
@IEditorService private readonly editorService: IEditorService,
@IInstantiationService instantiationService: IInstantiationService,
@IViewDescriptorService viewDescriptorService: IViewDescriptorService,
@IOpenerService openerService: IOpenerService,
@IStorageService storageSevice: IStorageService,
@ITelemetryService telemetryService: ITelemetryService,
) {
super(options, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService);
this.debugStartLanguageContext = CONTEXT_DEBUG_START_LANGUAGE.bindTo(contextKeyService);
this.debuggerInterestedContext = CONTEXT_DEBUGGER_INTERESTED_IN_ACTIVE_EDITOR.bindTo(contextKeyService);
const lastSetLanguage = storageSevice.get(debugStartLanguageKey, StorageScope.WORKSPACE);
this.debugStartLanguageContext.set(lastSetLanguage);
const setContextKey = () => {
const editorControl = this.editorService.activeTextEditorControl;
if (isCodeEditor(editorControl)) {
const model = editorControl.getModel();
const language = model ? model.getLanguageIdentifier().language : undefined;
if (language && this.debugService.getAdapterManager().isDebuggerInterestedInLanguage(language)) {
this.debugStartLanguageContext.set(language);
this.debuggerInterestedContext.set(true);
storageSevice.store(debugStartLanguageKey, language, StorageScope.WORKSPACE, StorageTarget.MACHINE);
return;
}
}
this.debuggerInterestedContext.set(false);
};
const disposables = new DisposableStore();
this._register(disposables);
this._register(editorService.onDidActiveEditorChange(() => {
disposables.clear();
const editorControl = this.editorService.activeTextEditorControl;
if (isCodeEditor(editorControl)) {
disposables.add(editorControl.onDidChangeModelLanguage(setContextKey));
}
setContextKey();
}));
this._register(this.debugService.getAdapterManager().onDidRegisterDebugger(setContextKey));
this._register(this.onDidChangeBodyVisibility(visible => {
if (visible) {
setContextKey();
}
}));
setContextKey();
const debugKeybinding = this.keybindingService.lookupKeybinding(DEBUG_START_COMMAND_ID);
debugKeybindingLabel = debugKeybinding ? ` (${debugKeybinding.getLabel()})` : '';
}
shouldShowWelcome(): boolean {
return true;
}
}
const viewsRegistry = Registry.as<IViewsRegistry>(Extensions.ViewsRegistry);
viewsRegistry.registerViewWelcomeContent(WelcomeView.ID, {
content: localize({ key: 'openAFileWhichCanBeDebugged', comment: ['Please do not translate the word "commmand", it is part of our internal syntax which must not change'] },
"[Open a file](command:{0}) which can be debugged or run.", isMacintosh ? OpenFileFolderAction.ID : OpenFileAction.ID),
when: ContextKeyExpr.and(CONTEXT_DEBUGGERS_AVAILABLE, CONTEXT_DEBUGGER_INTERESTED_IN_ACTIVE_EDITOR.toNegated()),
group: ViewContentGroups.Open
});
let debugKeybindingLabel = '';
viewsRegistry.registerViewWelcomeContent(WelcomeView.ID, {
content: localize({ key: 'runAndDebugAction', comment: ['Please do not translate the word "commmand", it is part of our internal syntax which must not change'] },
"[Run and Debug{0}](command:{1})", debugKeybindingLabel, DEBUG_START_COMMAND_ID),
when: CONTEXT_DEBUGGERS_AVAILABLE,
group: ViewContentGroups.Debug
});
viewsRegistry.registerViewWelcomeContent(WelcomeView.ID, {
content: localize({ key: 'detectThenRunAndDebug', comment: ['Please do not translate the word "commmand", it is part of our internal syntax which must not change'] },
"[Show](command:{0}) all automatic debug configurations.", SELECT_AND_START_ID),
when: CONTEXT_DEBUGGERS_AVAILABLE,
group: ViewContentGroups.Debug,
order: 10
});
viewsRegistry.registerViewWelcomeContent(WelcomeView.ID, {
content: localize({ key: 'customizeRunAndDebug', comment: ['Please do not translate the word "commmand", it is part of our internal syntax which must not change'] },
"To customize Run and Debug [create a launch.json file](command:{0}).", DEBUG_CONFIGURE_COMMAND_ID),
when: ContextKeyExpr.and(CONTEXT_DEBUGGERS_AVAILABLE, WorkbenchStateContext.notEqualsTo('empty')),
group: ViewContentGroups.Debug
});
viewsRegistry.registerViewWelcomeContent(WelcomeView.ID, {
content: localize({ key: 'customizeRunAndDebugOpenFolder', comment: ['Please do not translate the word "commmand", it is part of our internal syntax which must not change'] },
"To customize Run and Debug, [open a folder](command:{0}) and create a launch.json file.", isMacintosh ? OpenFileFolderAction.ID : OpenFolderAction.ID),
when: ContextKeyExpr.and(CONTEXT_DEBUGGERS_AVAILABLE, WorkbenchStateContext.isEqualTo('empty')),
group: ViewContentGroups.Debug
});
| src/vs/workbench/contrib/debug/browser/welcomeView.ts | 0 | https://github.com/microsoft/vscode/commit/8aac8643d77aa03300f7c62452b0583a0db2b741 | [
0.00017638316785451025,
0.000171315623447299,
0.00016539377975277603,
0.00017241794557776302,
0.0000032253956305794418
] |
{
"id": 3,
"code_window": [
"\t\t\t\tconst configProfiles = this._configurationService.inspect<{ [key: string]: ITerminalProfileObject }>(configKey);\n",
"\t\t\t\tconst existingProfiles = configProfiles.userValue ? Object.keys(configProfiles.userValue) : [];\n",
"\t\t\t\tconst name = await this._quickInputService.input({\n",
"\t\t\t\t\tprompt: nls.localize('enterTerminalProfileName', \"Enter profile name\"),\n",
"\t\t\t\t\tvalue: context.item.profile.profileName,\n",
"\t\t\t\t\tvalidateInput: async input => {\n",
"\t\t\t\t\t\tif (existingProfiles.includes(input)) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\tprompt: nls.localize('enterTerminalProfileName', \"Enter terminal profile name\"),\n"
],
"file_path": "src/vs/workbench/contrib/terminal/browser/terminalService.ts",
"type": "replace",
"edit_start_line_idx": 855
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Codicon } from 'vs/base/common/codicons';
import { localize } from 'vs/nls';
import { registerIcon } from 'vs/platform/theme/common/iconRegistry';
export const terminalViewIcon = registerIcon('terminal-view-icon', Codicon.terminal, localize('terminalViewIcon', 'View icon of the terminal view.'));
export const renameTerminalIcon = registerIcon('terminal-rename', Codicon.gear, localize('renameTerminalIcon', 'Icon for rename in the terminal quick menu.'));
export const killTerminalIcon = registerIcon('terminal-kill', Codicon.trash, localize('killTerminalIcon', 'Icon for killing a terminal instance.'));
export const newTerminalIcon = registerIcon('terminal-new', Codicon.add, localize('newTerminalIcon', 'Icon for creating a new terminal instance.'));
export const newQuickLaunchProfileIcon = registerIcon('terminal-quick-launch', Codicon.symbolEvent, localize('newQuickLaunchProfile', 'Icon for creating a new terminal quick launch profile.'));
| src/vs/workbench/contrib/terminal/browser/terminalIcons.ts | 1 | https://github.com/microsoft/vscode/commit/8aac8643d77aa03300f7c62452b0583a0db2b741 | [
0.0001746007619658485,
0.0001697333063930273,
0.00016486583626829088,
0.0001697333063930273,
0.000004867462848778814
] |
{
"id": 3,
"code_window": [
"\t\t\t\tconst configProfiles = this._configurationService.inspect<{ [key: string]: ITerminalProfileObject }>(configKey);\n",
"\t\t\t\tconst existingProfiles = configProfiles.userValue ? Object.keys(configProfiles.userValue) : [];\n",
"\t\t\t\tconst name = await this._quickInputService.input({\n",
"\t\t\t\t\tprompt: nls.localize('enterTerminalProfileName', \"Enter profile name\"),\n",
"\t\t\t\t\tvalue: context.item.profile.profileName,\n",
"\t\t\t\t\tvalidateInput: async input => {\n",
"\t\t\t\t\t\tif (existingProfiles.includes(input)) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\tprompt: nls.localize('enterTerminalProfileName', \"Enter terminal profile name\"),\n"
],
"file_path": "src/vs/workbench/contrib/terminal/browser/terminalService.ts",
"type": "replace",
"edit_start_line_idx": 855
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
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;
| build/lib/task.js | 0 | https://github.com/microsoft/vscode/commit/8aac8643d77aa03300f7c62452b0583a0db2b741 | [
0.7408158183097839,
0.07512662559747696,
0.00017150187341030687,
0.0001772220857674256,
0.22190716862678528
] |
{
"id": 3,
"code_window": [
"\t\t\t\tconst configProfiles = this._configurationService.inspect<{ [key: string]: ITerminalProfileObject }>(configKey);\n",
"\t\t\t\tconst existingProfiles = configProfiles.userValue ? Object.keys(configProfiles.userValue) : [];\n",
"\t\t\t\tconst name = await this._quickInputService.input({\n",
"\t\t\t\t\tprompt: nls.localize('enterTerminalProfileName', \"Enter profile name\"),\n",
"\t\t\t\t\tvalue: context.item.profile.profileName,\n",
"\t\t\t\t\tvalidateInput: async input => {\n",
"\t\t\t\t\t\tif (existingProfiles.includes(input)) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\tprompt: nls.localize('enterTerminalProfileName', \"Enter terminal profile name\"),\n"
],
"file_path": "src/vs/workbench/contrib/terminal/browser/terminalService.ts",
"type": "replace",
"edit_start_line_idx": 855
} | /*---------------------------------------------------------------------------------------------
* 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: { name: '00000405', id: '', text: 'Czech' },
secondaryLayouts: [],
mapping: {
Sleep: [],
WakeUp: [],
KeyA: ['a', 'A', '', '', 0, 'VK_A'],
KeyB: ['b', 'B', '{', '', 0, 'VK_B'],
KeyC: ['c', 'C', '&', '', 0, 'VK_C'],
KeyD: ['d', 'D', 'Đ', '', 0, 'VK_D'],
KeyE: ['e', 'E', '€', '', 0, 'VK_E'],
KeyF: ['f', 'F', '[', '', 0, 'VK_F'],
KeyG: ['g', 'G', ']', '', 0, 'VK_G'],
KeyH: ['h', 'H', '', '', 0, 'VK_H'],
KeyI: ['i', 'I', '', '', 0, 'VK_I'],
KeyJ: ['j', 'J', '', '', 0, 'VK_J'],
KeyK: ['k', 'K', 'ł', '', 0, 'VK_K'],
KeyL: ['l', 'L', 'Ł', '', 0, 'VK_L'],
KeyM: ['m', 'M', '', '', 0, 'VK_M'],
KeyN: ['n', 'N', '}', '', 0, 'VK_N'],
KeyO: ['o', 'O', '', '', 0, 'VK_O'],
KeyP: ['p', 'P', '', '', 0, 'VK_P'],
KeyQ: ['q', 'Q', '\\', '', 0, 'VK_Q'],
KeyR: ['r', 'R', '', '', 0, 'VK_R'],
KeyS: ['s', 'S', 'đ', '', 0, 'VK_S'],
KeyT: ['t', 'T', '', '', 0, 'VK_T'],
KeyU: ['u', 'U', '', '', 0, 'VK_U'],
KeyV: ['v', 'V', '@', '', 0, 'VK_V'],
KeyW: ['w', 'W', '|', '', 0, 'VK_W'],
KeyX: ['x', 'X', '#', '', 0, 'VK_X'],
KeyY: ['z', 'Z', '', '', 0, 'VK_Z'],
KeyZ: ['y', 'Y', '', '', 0, 'VK_Y'],
Digit1: ['+', '1', '~', '', 0, 'VK_1'],
Digit2: ['ě', '2', 'ˇ', '', 0, 'VK_2'],
Digit3: ['š', '3', '^', '', 0, 'VK_3'],
Digit4: ['č', '4', '˘', '', 0, 'VK_4'],
Digit5: ['ř', '5', '°', '', 0, 'VK_5'],
Digit6: ['ž', '6', '˛', '', 0, 'VK_6'],
Digit7: ['ý', '7', '`', '', 0, 'VK_7'],
Digit8: ['á', '8', '˙', '', 0, 'VK_8'],
Digit9: ['í', '9', '´', '', 0, 'VK_9'],
Digit0: ['é', '0', '˝', '', 0, 'VK_0'],
Enter: [],
Escape: [],
Backspace: [],
Tab: [],
Space: [' ', ' ', '', '', 0, 'VK_SPACE'],
Minus: ['=', '%', '¨', '', 0, 'VK_OEM_PLUS'],
Equal: ['´', 'ˇ', '¸', '', 0, 'VK_OEM_2'],
BracketLeft: ['ú', '/', '÷', '', 0, 'VK_OEM_4'],
BracketRight: [')', '(', '×', '', 0, 'VK_OEM_6'],
Backslash: ['¨', '\'', '¤', '', 0, 'VK_OEM_5'],
Semicolon: ['ů', '"', '$', '', 0, 'VK_OEM_1'],
Quote: ['§', '!', 'ß', '', 0, 'VK_OEM_7'],
Backquote: [';', '°', '', '', 0, 'VK_OEM_3'],
Comma: [',', '?', '<', '', 0, 'VK_OEM_COMMA'],
Period: ['.', ':', '>', '', 0, 'VK_OEM_PERIOD'],
Slash: ['-', '_', '*', '', 0, 'VK_OEM_MINUS'],
CapsLock: [],
F1: [],
F2: [],
F3: [],
F4: [],
F5: [],
F6: [],
F7: [],
F8: [],
F9: [],
F10: [],
F11: [],
F12: [],
PrintScreen: [],
ScrollLock: [],
Pause: [],
Insert: [],
Home: [],
PageUp: [],
Delete: [],
End: [],
PageDown: [],
ArrowRight: [],
ArrowLeft: [],
ArrowDown: [],
ArrowUp: [],
NumLock: [],
NumpadDivide: ['/', '/', '', '', 0, 'VK_DIVIDE'],
NumpadMultiply: ['*', '*', '', '', 0, 'VK_MULTIPLY'],
NumpadSubtract: ['-', '-', '', '', 0, 'VK_SUBTRACT'],
NumpadAdd: ['+', '+', '', '', 0, 'VK_ADD'],
NumpadEnter: [],
Numpad1: [],
Numpad2: [],
Numpad3: [],
Numpad4: [],
Numpad5: [],
Numpad6: [],
Numpad7: [],
Numpad8: [],
Numpad9: [],
Numpad0: [],
NumpadDecimal: [],
IntlBackslash: ['\\', '|', '', '', 0, 'VK_OEM_102'],
ContextMenu: [],
Power: [],
NumpadEqual: [],
F13: [],
F14: [],
F15: [],
F16: [],
F17: [],
F18: [],
F19: [],
F20: [],
F21: [],
F22: [],
F23: [],
F24: [],
Help: [],
Undo: [],
Cut: [],
Copy: [],
Paste: [],
AudioVolumeMute: [],
AudioVolumeUp: [],
AudioVolumeDown: [],
NumpadComma: [],
IntlRo: [],
KanaMode: [],
IntlYen: [],
Convert: [],
NonConvert: [],
Lang1: [],
Lang2: [],
Lang3: [],
Lang4: [],
ControlLeft: [],
ShiftLeft: [],
AltLeft: [],
MetaLeft: [],
ControlRight: [],
ShiftRight: [],
AltRight: [],
MetaRight: [],
MediaTrackNext: [],
MediaTrackPrevious: [],
MediaStop: [],
Eject: [],
MediaPlayPause: [],
MediaSelect: [],
LaunchMail: [],
LaunchApp2: [],
LaunchApp1: [],
BrowserSearch: [],
BrowserHome: [],
BrowserBack: [],
BrowserForward: [],
BrowserStop: [],
BrowserRefresh: [],
BrowserFavorites: []
}
});
| src/vs/workbench/services/keybinding/browser/keyboardLayouts/cz.win.ts | 0 | https://github.com/microsoft/vscode/commit/8aac8643d77aa03300f7c62452b0583a0db2b741 | [
0.00017697582370601594,
0.00017442584794480354,
0.00017226905038114637,
0.00017426960403099656,
0.000001428468749509193
] |
{
"id": 3,
"code_window": [
"\t\t\t\tconst configProfiles = this._configurationService.inspect<{ [key: string]: ITerminalProfileObject }>(configKey);\n",
"\t\t\t\tconst existingProfiles = configProfiles.userValue ? Object.keys(configProfiles.userValue) : [];\n",
"\t\t\t\tconst name = await this._quickInputService.input({\n",
"\t\t\t\t\tprompt: nls.localize('enterTerminalProfileName', \"Enter profile name\"),\n",
"\t\t\t\t\tvalue: context.item.profile.profileName,\n",
"\t\t\t\t\tvalidateInput: async input => {\n",
"\t\t\t\t\t\tif (existingProfiles.includes(input)) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\tprompt: nls.localize('enterTerminalProfileName', \"Enter terminal profile name\"),\n"
],
"file_path": "src/vs/workbench/contrib/terminal/browser/terminalService.ts",
"type": "replace",
"edit_start_line_idx": 855
} | /*---------------------------------------------------------------------------------------------
* 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 { KeyChord, KeyCode, KeyMod, SimpleKeybinding, createKeybinding } from 'vs/base/common/keyCodes';
import { KeybindingParser } from 'vs/base/common/keybindingParser';
import { OperatingSystem } from 'vs/base/common/platform';
import { ScanCode, ScanCodeBinding } from 'vs/base/common/scanCode';
import { IUserFriendlyKeybinding } from 'vs/platform/keybinding/common/keybinding';
import { USLayoutResolvedKeybinding } from 'vs/platform/keybinding/common/usLayoutResolvedKeybinding';
import { KeybindingIO } from 'vs/workbench/services/keybinding/common/keybindingIO';
suite('keybindingIO', () => {
test('serialize/deserialize', () => {
function testOneSerialization(keybinding: number, expected: string, msg: string, OS: OperatingSystem): void {
let usLayoutResolvedKeybinding = new USLayoutResolvedKeybinding(createKeybinding(keybinding, OS)!, OS);
let actualSerialized = usLayoutResolvedKeybinding.getUserSettingsLabel();
assert.strictEqual(actualSerialized, expected, expected + ' - ' + msg);
}
function testSerialization(keybinding: number, expectedWin: string, expectedMac: string, expectedLinux: string): void {
testOneSerialization(keybinding, expectedWin, 'win', OperatingSystem.Windows);
testOneSerialization(keybinding, expectedMac, 'mac', OperatingSystem.Macintosh);
testOneSerialization(keybinding, expectedLinux, 'linux', OperatingSystem.Linux);
}
function testOneDeserialization(keybinding: string, _expected: number, msg: string, OS: OperatingSystem): void {
let actualDeserialized = KeybindingParser.parseKeybinding(keybinding, OS);
let expected = createKeybinding(_expected, OS);
assert.deepStrictEqual(actualDeserialized, expected, keybinding + ' - ' + msg);
}
function testDeserialization(inWin: string, inMac: string, inLinux: string, expected: number): void {
testOneDeserialization(inWin, expected, 'win', OperatingSystem.Windows);
testOneDeserialization(inMac, expected, 'mac', OperatingSystem.Macintosh);
testOneDeserialization(inLinux, expected, 'linux', OperatingSystem.Linux);
}
function testRoundtrip(keybinding: number, expectedWin: string, expectedMac: string, expectedLinux: string): void {
testSerialization(keybinding, expectedWin, expectedMac, expectedLinux);
testDeserialization(expectedWin, expectedMac, expectedLinux, keybinding);
}
testRoundtrip(KeyCode.KEY_0, '0', '0', '0');
testRoundtrip(KeyCode.KEY_A, 'a', 'a', 'a');
testRoundtrip(KeyCode.UpArrow, 'up', 'up', 'up');
testRoundtrip(KeyCode.RightArrow, 'right', 'right', 'right');
testRoundtrip(KeyCode.DownArrow, 'down', 'down', 'down');
testRoundtrip(KeyCode.LeftArrow, 'left', 'left', 'left');
// one modifier
testRoundtrip(KeyMod.Alt | KeyCode.KEY_A, 'alt+a', 'alt+a', 'alt+a');
testRoundtrip(KeyMod.CtrlCmd | KeyCode.KEY_A, 'ctrl+a', 'cmd+a', 'ctrl+a');
testRoundtrip(KeyMod.Shift | KeyCode.KEY_A, 'shift+a', 'shift+a', 'shift+a');
testRoundtrip(KeyMod.WinCtrl | KeyCode.KEY_A, 'win+a', 'ctrl+a', 'meta+a');
// two modifiers
testRoundtrip(KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_A, 'ctrl+alt+a', 'alt+cmd+a', 'ctrl+alt+a');
testRoundtrip(KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_A, 'ctrl+shift+a', 'shift+cmd+a', 'ctrl+shift+a');
testRoundtrip(KeyMod.CtrlCmd | KeyMod.WinCtrl | KeyCode.KEY_A, 'ctrl+win+a', 'ctrl+cmd+a', 'ctrl+meta+a');
testRoundtrip(KeyMod.Shift | KeyMod.Alt | KeyCode.KEY_A, 'shift+alt+a', 'shift+alt+a', 'shift+alt+a');
testRoundtrip(KeyMod.Shift | KeyMod.WinCtrl | KeyCode.KEY_A, 'shift+win+a', 'ctrl+shift+a', 'shift+meta+a');
testRoundtrip(KeyMod.Alt | KeyMod.WinCtrl | KeyCode.KEY_A, 'alt+win+a', 'ctrl+alt+a', 'alt+meta+a');
// three modifiers
testRoundtrip(KeyMod.CtrlCmd | KeyMod.Shift | KeyMod.Alt | KeyCode.KEY_A, 'ctrl+shift+alt+a', 'shift+alt+cmd+a', 'ctrl+shift+alt+a');
testRoundtrip(KeyMod.CtrlCmd | KeyMod.Shift | KeyMod.WinCtrl | KeyCode.KEY_A, 'ctrl+shift+win+a', 'ctrl+shift+cmd+a', 'ctrl+shift+meta+a');
testRoundtrip(KeyMod.Shift | KeyMod.Alt | KeyMod.WinCtrl | KeyCode.KEY_A, 'shift+alt+win+a', 'ctrl+shift+alt+a', 'shift+alt+meta+a');
// all modifiers
testRoundtrip(KeyMod.CtrlCmd | KeyMod.Shift | KeyMod.Alt | KeyMod.WinCtrl | KeyCode.KEY_A, 'ctrl+shift+alt+win+a', 'ctrl+shift+alt+cmd+a', 'ctrl+shift+alt+meta+a');
// chords
testRoundtrip(KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_A, KeyMod.CtrlCmd | KeyCode.KEY_A), 'ctrl+a ctrl+a', 'cmd+a cmd+a', 'ctrl+a ctrl+a');
testRoundtrip(KeyChord(KeyMod.CtrlCmd | KeyCode.UpArrow, KeyMod.CtrlCmd | KeyCode.UpArrow), 'ctrl+up ctrl+up', 'cmd+up cmd+up', 'ctrl+up ctrl+up');
// OEM keys
testRoundtrip(KeyCode.US_SEMICOLON, ';', ';', ';');
testRoundtrip(KeyCode.US_EQUAL, '=', '=', '=');
testRoundtrip(KeyCode.US_COMMA, ',', ',', ',');
testRoundtrip(KeyCode.US_MINUS, '-', '-', '-');
testRoundtrip(KeyCode.US_DOT, '.', '.', '.');
testRoundtrip(KeyCode.US_SLASH, '/', '/', '/');
testRoundtrip(KeyCode.US_BACKTICK, '`', '`', '`');
testRoundtrip(KeyCode.ABNT_C1, 'abnt_c1', 'abnt_c1', 'abnt_c1');
testRoundtrip(KeyCode.ABNT_C2, 'abnt_c2', 'abnt_c2', 'abnt_c2');
testRoundtrip(KeyCode.US_OPEN_SQUARE_BRACKET, '[', '[', '[');
testRoundtrip(KeyCode.US_BACKSLASH, '\\', '\\', '\\');
testRoundtrip(KeyCode.US_CLOSE_SQUARE_BRACKET, ']', ']', ']');
testRoundtrip(KeyCode.US_QUOTE, '\'', '\'', '\'');
testRoundtrip(KeyCode.OEM_8, 'oem_8', 'oem_8', 'oem_8');
testRoundtrip(KeyCode.OEM_102, 'oem_102', 'oem_102', 'oem_102');
// OEM aliases
testDeserialization('OEM_1', 'OEM_1', 'OEM_1', KeyCode.US_SEMICOLON);
testDeserialization('OEM_PLUS', 'OEM_PLUS', 'OEM_PLUS', KeyCode.US_EQUAL);
testDeserialization('OEM_COMMA', 'OEM_COMMA', 'OEM_COMMA', KeyCode.US_COMMA);
testDeserialization('OEM_MINUS', 'OEM_MINUS', 'OEM_MINUS', KeyCode.US_MINUS);
testDeserialization('OEM_PERIOD', 'OEM_PERIOD', 'OEM_PERIOD', KeyCode.US_DOT);
testDeserialization('OEM_2', 'OEM_2', 'OEM_2', KeyCode.US_SLASH);
testDeserialization('OEM_3', 'OEM_3', 'OEM_3', KeyCode.US_BACKTICK);
testDeserialization('ABNT_C1', 'ABNT_C1', 'ABNT_C1', KeyCode.ABNT_C1);
testDeserialization('ABNT_C2', 'ABNT_C2', 'ABNT_C2', KeyCode.ABNT_C2);
testDeserialization('OEM_4', 'OEM_4', 'OEM_4', KeyCode.US_OPEN_SQUARE_BRACKET);
testDeserialization('OEM_5', 'OEM_5', 'OEM_5', KeyCode.US_BACKSLASH);
testDeserialization('OEM_6', 'OEM_6', 'OEM_6', KeyCode.US_CLOSE_SQUARE_BRACKET);
testDeserialization('OEM_7', 'OEM_7', 'OEM_7', KeyCode.US_QUOTE);
testDeserialization('OEM_8', 'OEM_8', 'OEM_8', KeyCode.OEM_8);
testDeserialization('OEM_102', 'OEM_102', 'OEM_102', KeyCode.OEM_102);
// accepts '-' as separator
testDeserialization('ctrl-shift-alt-win-a', 'ctrl-shift-alt-cmd-a', 'ctrl-shift-alt-meta-a', KeyMod.CtrlCmd | KeyMod.Shift | KeyMod.Alt | KeyMod.WinCtrl | KeyCode.KEY_A);
// various input mistakes
testDeserialization(' ctrl-shift-alt-win-A ', ' shift-alt-cmd-Ctrl-A ', ' ctrl-shift-alt-META-A ', KeyMod.CtrlCmd | KeyMod.Shift | KeyMod.Alt | KeyMod.WinCtrl | KeyCode.KEY_A);
});
test('deserialize scan codes', () => {
assert.deepStrictEqual(
KeybindingParser.parseUserBinding('ctrl+shift+[comma] ctrl+/'),
[new ScanCodeBinding(true, true, false, false, ScanCode.Comma), new SimpleKeybinding(true, false, false, false, KeyCode.US_SLASH)]
);
});
test('issue #10452 - invalid command', () => {
let strJSON = `[{ "key": "ctrl+k ctrl+f", "command": ["firstcommand", "seccondcommand"] }]`;
let userKeybinding = <IUserFriendlyKeybinding>JSON.parse(strJSON)[0];
let keybindingItem = KeybindingIO.readUserKeybindingItem(userKeybinding);
assert.strictEqual(keybindingItem.command, null);
});
test('issue #10452 - invalid when', () => {
let strJSON = `[{ "key": "ctrl+k ctrl+f", "command": "firstcommand", "when": [] }]`;
let userKeybinding = <IUserFriendlyKeybinding>JSON.parse(strJSON)[0];
let keybindingItem = KeybindingIO.readUserKeybindingItem(userKeybinding);
assert.strictEqual(keybindingItem.when, undefined);
});
test('issue #10452 - invalid key', () => {
let strJSON = `[{ "key": [], "command": "firstcommand" }]`;
let userKeybinding = <IUserFriendlyKeybinding>JSON.parse(strJSON)[0];
let keybindingItem = KeybindingIO.readUserKeybindingItem(userKeybinding);
assert.deepStrictEqual(keybindingItem.parts, []);
});
test('issue #10452 - invalid key 2', () => {
let strJSON = `[{ "key": "", "command": "firstcommand" }]`;
let userKeybinding = <IUserFriendlyKeybinding>JSON.parse(strJSON)[0];
let keybindingItem = KeybindingIO.readUserKeybindingItem(userKeybinding);
assert.deepStrictEqual(keybindingItem.parts, []);
});
test('test commands args', () => {
let strJSON = `[{ "key": "ctrl+k ctrl+f", "command": "firstcommand", "when": [], "args": { "text": "theText" } }]`;
let userKeybinding = <IUserFriendlyKeybinding>JSON.parse(strJSON)[0];
let keybindingItem = KeybindingIO.readUserKeybindingItem(userKeybinding);
assert.strictEqual(keybindingItem.commandArgs.text, 'theText');
});
});
| src/vs/workbench/services/keybinding/test/browser/keybindingIO.test.ts | 0 | https://github.com/microsoft/vscode/commit/8aac8643d77aa03300f7c62452b0583a0db2b741 | [
0.00017564205336384475,
0.00017194314568769187,
0.0001693747180979699,
0.00017131537606474012,
0.0000017858419596450403
] |
{
"id": 4,
"code_window": [
"\t\t\t\t\tvalue: context.item.profile.profileName,\n",
"\t\t\t\t\tvalidateInput: async input => {\n",
"\t\t\t\t\t\tif (existingProfiles.includes(input)) {\n",
"\t\t\t\t\t\t\treturn nls.localize('terminalProfileAlreadyExists', \"A profile already exists with that name\");\n",
"\t\t\t\t\t\t}\n",
"\t\t\t\t\t\treturn undefined;\n",
"\t\t\t\t\t}\n",
"\t\t\t\t});\n",
"\t\t\t\tif (!name) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\t\t\treturn nls.localize('terminalProfileAlreadyExists', \"A terminal profile already exists with that name\");\n"
],
"file_path": "src/vs/workbench/contrib/terminal/browser/terminalService.ts",
"type": "replace",
"edit_start_line_idx": 859
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { timeout } from 'vs/base/common/async';
import { debounce, throttle } from 'vs/base/common/decorators';
import { Emitter, Event } from 'vs/base/common/event';
import { IDisposable } from 'vs/base/common/lifecycle';
import { basename } from 'vs/base/common/path';
import { isMacintosh, isWeb, isWindows, OperatingSystem } from 'vs/base/common/platform';
import { FindReplaceState } from 'vs/editor/contrib/find/findState';
import * as nls from 'vs/nls';
import { ConfigurationTarget, IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
import { IInstantiationService, optional } from 'vs/platform/instantiation/common/instantiation';
import { IPickOptions, IQuickInputButton, IQuickInputService, IQuickPickItem } from 'vs/platform/quickinput/common/quickInput';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { ILocalTerminalService, IShellLaunchConfig, ITerminalLaunchError, ITerminalsLayoutInfo, ITerminalsLayoutInfoById, TerminalShellType, WindowsShellType } from 'vs/platform/terminal/common/terminal';
import { ThemeIcon } from 'vs/platform/theme/common/themeService';
import { IViewDescriptorService, IViewsService, ViewContainerLocation } from 'vs/workbench/common/views';
import { IRemoteTerminalService, ITerminalExternalLinkProvider, ITerminalInstance, ITerminalService, ITerminalTab, TerminalConnectionState } from 'vs/workbench/contrib/terminal/browser/terminal';
import { TerminalConfigHelper } from 'vs/workbench/contrib/terminal/browser/terminalConfigHelper';
import { TerminalInstance } from 'vs/workbench/contrib/terminal/browser/terminalInstance';
import { TerminalTab } from 'vs/workbench/contrib/terminal/browser/terminalTab';
import { TerminalViewPane } from 'vs/workbench/contrib/terminal/browser/terminalView';
import { IAvailableProfilesRequest, IRemoteTerminalAttachTarget, ITerminalProfile, IStartExtensionTerminalRequest, ITerminalConfigHelper, ITerminalNativeWindowsDelegate, ITerminalProcessExtHostProxy, KEYBINDING_CONTEXT_TERMINAL_ALT_BUFFER_ACTIVE, KEYBINDING_CONTEXT_TERMINAL_FIND_VISIBLE, KEYBINDING_CONTEXT_TERMINAL_FOCUS, KEYBINDING_CONTEXT_TERMINAL_IS_OPEN, KEYBINDING_CONTEXT_TERMINAL_PROCESS_SUPPORTED, KEYBINDING_CONTEXT_TERMINAL_SHELL_TYPE, LinuxDistro, TERMINAL_VIEW_ID, ITerminalProfileObject, ITerminalExecutable, ITerminalProfileSource } from 'vs/workbench/contrib/terminal/common/terminal';
import { escapeNonWindowsPath } from 'vs/workbench/contrib/terminal/common/terminalEnvironment';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService';
import { ILifecycleService, ShutdownReason, WillShutdownEvent } from 'vs/workbench/services/lifecycle/common/lifecycle';
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
import { newQuickLaunchProfileIcon } from 'vs/workbench/contrib/terminal/browser/terminalIcons';
import { equals } from 'vs/base/common/objects';
interface IExtHostReadyEntry {
promise: Promise<void>;
resolve: () => void;
}
export class TerminalService implements ITerminalService {
public _serviceBrand: undefined;
private _isShuttingDown: boolean;
private _terminalFocusContextKey: IContextKey<boolean>;
private _terminalShellTypeContextKey: IContextKey<string>;
private _terminalAltBufferActiveContextKey: IContextKey<boolean>;
private _findWidgetVisible: IContextKey<boolean>;
private _terminalTabs: ITerminalTab[] = [];
private _backgroundedTerminalInstances: ITerminalInstance[] = [];
private get _terminalInstances(): ITerminalInstance[] {
return this._terminalTabs.reduce((p, c) => p.concat(c.terminalInstances), <ITerminalInstance[]>[]);
}
private _findState: FindReplaceState;
private _extHostsReady: { [authority: string]: IExtHostReadyEntry | undefined } = {};
private _activeTabIndex: number;
private _linkProviders: Set<ITerminalExternalLinkProvider> = new Set();
private _linkProviderDisposables: Map<ITerminalExternalLinkProvider, IDisposable[]> = new Map();
private _processSupportContextKey: IContextKey<boolean>;
public get activeTabIndex(): number { return this._activeTabIndex; }
public get terminalInstances(): ITerminalInstance[] { return this._terminalInstances; }
public get terminalTabs(): ITerminalTab[] { return this._terminalTabs; }
public get isProcessSupportRegistered(): boolean { return !!this._processSupportContextKey.get(); }
private _configHelper: TerminalConfigHelper;
private _terminalContainer: HTMLElement | undefined;
private _nativeWindowsDelegate: ITerminalNativeWindowsDelegate | undefined;
private _remoteTerminalsInitPromise: Promise<void> | undefined;
private _localTerminalsInitPromise: Promise<void> | undefined;
private _connectionState: TerminalConnectionState;
private _availableProfiles: ITerminalProfile[] | undefined;
public get configHelper(): ITerminalConfigHelper { return this._configHelper; }
private readonly _onActiveTabChanged = new Emitter<void>();
public get onActiveTabChanged(): Event<void> { return this._onActiveTabChanged.event; }
private readonly _onInstanceCreated = new Emitter<ITerminalInstance>();
public get onInstanceCreated(): Event<ITerminalInstance> { return this._onInstanceCreated.event; }
private readonly _onInstanceDisposed = new Emitter<ITerminalInstance>();
public get onInstanceDisposed(): Event<ITerminalInstance> { return this._onInstanceDisposed.event; }
private readonly _onInstanceProcessIdReady = new Emitter<ITerminalInstance>();
public get onInstanceProcessIdReady(): Event<ITerminalInstance> { return this._onInstanceProcessIdReady.event; }
private readonly _onInstanceLinksReady = new Emitter<ITerminalInstance>();
public get onInstanceLinksReady(): Event<ITerminalInstance> { return this._onInstanceLinksReady.event; }
private readonly _onInstanceRequestStartExtensionTerminal = new Emitter<IStartExtensionTerminalRequest>();
public get onInstanceRequestStartExtensionTerminal(): Event<IStartExtensionTerminalRequest> { return this._onInstanceRequestStartExtensionTerminal.event; }
private readonly _onInstanceDimensionsChanged = new Emitter<ITerminalInstance>();
public get onInstanceDimensionsChanged(): Event<ITerminalInstance> { return this._onInstanceDimensionsChanged.event; }
private readonly _onInstanceMaximumDimensionsChanged = new Emitter<ITerminalInstance>();
public get onInstanceMaximumDimensionsChanged(): Event<ITerminalInstance> { return this._onInstanceMaximumDimensionsChanged.event; }
private readonly _onInstancesChanged = new Emitter<void>();
public get onInstancesChanged(): Event<void> { return this._onInstancesChanged.event; }
private readonly _onInstanceTitleChanged = new Emitter<ITerminalInstance | undefined>();
public get onInstanceTitleChanged(): Event<ITerminalInstance | undefined> { return this._onInstanceTitleChanged.event; }
private readonly _onActiveInstanceChanged = new Emitter<ITerminalInstance | undefined>();
public get onActiveInstanceChanged(): Event<ITerminalInstance | undefined> { return this._onActiveInstanceChanged.event; }
private readonly _onTabDisposed = new Emitter<ITerminalTab>();
public get onTabDisposed(): Event<ITerminalTab> { return this._onTabDisposed.event; }
private readonly _onRequestAvailableProfiles = new Emitter<IAvailableProfilesRequest>();
public get onRequestAvailableProfiles(): Event<IAvailableProfilesRequest> { return this._onRequestAvailableProfiles.event; }
private readonly _onDidRegisterProcessSupport = new Emitter<void>();
public get onDidRegisterProcessSupport(): Event<void> { return this._onDidRegisterProcessSupport.event; }
private readonly _onDidChangeConnectionState = new Emitter<void>();
public get onDidChangeConnectionState(): Event<void> { return this._onDidChangeConnectionState.event; }
public get connectionState(): TerminalConnectionState { return this._connectionState; }
private readonly _onProfilesConfigChanged = new Emitter<void>();
public get onProfilesConfigChanged(): Event<void> { return this._onProfilesConfigChanged.event; }
private readonly _localTerminalService?: ILocalTerminalService;
constructor(
@IContextKeyService private _contextKeyService: IContextKeyService,
@IWorkbenchLayoutService private _layoutService: IWorkbenchLayoutService,
@ILifecycleService lifecycleService: ILifecycleService,
@IDialogService private _dialogService: IDialogService,
@IInstantiationService private _instantiationService: IInstantiationService,
@IRemoteAgentService private _remoteAgentService: IRemoteAgentService,
@IQuickInputService private _quickInputService: IQuickInputService,
@IConfigurationService private _configurationService: IConfigurationService,
@IViewsService private _viewsService: IViewsService,
@IViewDescriptorService private readonly _viewDescriptorService: IViewDescriptorService,
@IWorkbenchEnvironmentService private readonly _environmentService: IWorkbenchEnvironmentService,
@IRemoteTerminalService private readonly _remoteTerminalService: IRemoteTerminalService,
@ITelemetryService private readonly _telemetryService: ITelemetryService,
@IExtensionService private readonly _extensionService: IExtensionService,
@optional(ILocalTerminalService) localTerminalService: ILocalTerminalService
) {
this._localTerminalService = localTerminalService;
this._activeTabIndex = 0;
this._isShuttingDown = false;
this._findState = new FindReplaceState();
lifecycleService.onBeforeShutdown(async e => e.veto(this._onBeforeShutdown(e.reason), 'veto.terminal'));
lifecycleService.onWillShutdown(e => this._onWillShutdown(e));
this._terminalFocusContextKey = KEYBINDING_CONTEXT_TERMINAL_FOCUS.bindTo(this._contextKeyService);
this._terminalShellTypeContextKey = KEYBINDING_CONTEXT_TERMINAL_SHELL_TYPE.bindTo(this._contextKeyService);
this._terminalAltBufferActiveContextKey = KEYBINDING_CONTEXT_TERMINAL_ALT_BUFFER_ACTIVE.bindTo(this._contextKeyService);
this._findWidgetVisible = KEYBINDING_CONTEXT_TERMINAL_FIND_VISIBLE.bindTo(this._contextKeyService);
this._configHelper = this._instantiationService.createInstance(TerminalConfigHelper);
this.onTabDisposed(tab => this._removeTab(tab));
this.onActiveTabChanged(() => {
const instance = this.getActiveInstance();
this._onActiveInstanceChanged.fire(instance ? instance : undefined);
});
this.onInstanceLinksReady(instance => this._setInstanceLinkProviders(instance));
this._handleInstanceContextKeys();
this._processSupportContextKey = KEYBINDING_CONTEXT_TERMINAL_PROCESS_SUPPORTED.bindTo(this._contextKeyService);
this._processSupportContextKey.set(!isWeb || this._remoteAgentService.getConnection() !== null);
this._configurationService.onDidChangeConfiguration(async e => {
if (e.affectsConfiguration('terminal.integrated.profiles.windows') ||
e.affectsConfiguration('terminal.integrated.profiles.osx') ||
e.affectsConfiguration('terminal.integrated.profiles.linux') ||
e.affectsConfiguration('terminal.integrated.showQuickLaunchWslProfiles')) {
this._updateAvailableProfilesNow();
}
});
const enableTerminalReconnection = this.configHelper.config.enablePersistentSessions;
const conn = this._remoteAgentService.getConnection();
const remoteAuthority = conn ? conn.remoteAuthority : 'null';
this._whenExtHostReady(remoteAuthority).then(() => {
this._updateAvailableProfiles();
});
// Connect to the extension host if it's there, set the connection state to connected when
// it's done. This should happen even when there is no extension host.
this._connectionState = TerminalConnectionState.Connecting;
let initPromise: Promise<any>;
if (!!this._environmentService.remoteAuthority && enableTerminalReconnection) {
initPromise = this._remoteTerminalsInitPromise = this._reconnectToRemoteTerminals();
} else if (enableTerminalReconnection) {
initPromise = this._localTerminalsInitPromise = this._reconnectToLocalTerminals();
} else {
initPromise = Promise.resolve();
}
initPromise.then(() => this._setConnected());
}
private _setConnected() {
this._connectionState = TerminalConnectionState.Connected;
this._onDidChangeConnectionState.fire();
}
private async _reconnectToRemoteTerminals(): Promise<void> {
// Reattach to all remote terminals
const layoutInfo = await this._remoteTerminalService.getTerminalLayoutInfo();
const reconnectCounter = this._recreateTerminalTabs(layoutInfo);
/* __GDPR__
"terminalReconnection" : {
"count" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
}
*/
const data = {
count: reconnectCounter
};
this._telemetryService.publicLog('terminalReconnection', data);
// now that terminals have been restored,
// attach listeners to update remote when terminals are changed
this.attachProcessLayoutListeners(true);
}
private async _reconnectToLocalTerminals(): Promise<void> {
if (!this._localTerminalService) {
return;
}
// Reattach to all local terminals
const layoutInfo = await this._localTerminalService.getTerminalLayoutInfo();
if (layoutInfo && layoutInfo.tabs.length > 0) {
this._recreateTerminalTabs(layoutInfo);
}
// now that terminals have been restored,
// attach listeners to update local state when terminals are changed
this.attachProcessLayoutListeners(false);
}
private _recreateTerminalTabs(layoutInfo?: ITerminalsLayoutInfo): number {
let reconnectCounter = 0;
let activeTab: ITerminalTab | undefined;
if (layoutInfo) {
layoutInfo.tabs.forEach(tabLayout => {
const terminalLayouts = tabLayout.terminals.filter(t => t.terminal && t.terminal.isOrphan);
if (terminalLayouts.length) {
reconnectCounter += terminalLayouts.length;
let terminalInstance: ITerminalInstance | undefined;
let tab: ITerminalTab | undefined;
terminalLayouts.forEach((terminalLayout) => {
if (!terminalInstance) {
// create tab and terminal
terminalInstance = this.createTerminal({ attachPersistentProcess: terminalLayout.terminal! });
tab = this._getTabForInstance(terminalInstance);
if (tabLayout.isActive) {
activeTab = tab;
}
} else {
// add split terminals to this tab
this.splitInstance(terminalInstance, { attachPersistentProcess: terminalLayout.terminal! });
}
});
const activeInstance = this.terminalInstances.find(t => {
return t.shellLaunchConfig.attachPersistentProcess?.id === tabLayout.activePersistentProcessId;
});
if (activeInstance) {
this.setActiveInstance(activeInstance);
}
tab?.resizePanes(tabLayout.terminals.map(terminal => terminal.relativeSize));
}
});
if (layoutInfo.tabs.length) {
this.setActiveTabByIndex(activeTab ? this.terminalTabs.indexOf(activeTab) : 0);
}
}
return reconnectCounter;
}
private attachProcessLayoutListeners(isRemote: boolean): void {
this.onActiveTabChanged(() => isRemote ? this._updateRemoteState() : this._updateLocalState());
this.onActiveInstanceChanged(() => isRemote ? this._updateRemoteState() : this._updateLocalState());
this.onInstancesChanged(() => isRemote ? this._updateRemoteState() : this._updateLocalState());
// The state must be updated when the terminal is relaunched, otherwise the persistent
// terminal ID will be stale and the process will be leaked.
this.onInstanceProcessIdReady(() => isRemote ? this._updateRemoteState() : this._updateLocalState());
}
public setNativeWindowsDelegate(delegate: ITerminalNativeWindowsDelegate): void {
this._nativeWindowsDelegate = delegate;
}
public setLinuxDistro(linuxDistro: LinuxDistro): void {
this._configHelper.setLinuxDistro(linuxDistro);
}
private _handleInstanceContextKeys(): void {
const terminalIsOpenContext = KEYBINDING_CONTEXT_TERMINAL_IS_OPEN.bindTo(this._contextKeyService);
const updateTerminalContextKeys = () => {
terminalIsOpenContext.set(this.terminalInstances.length > 0);
};
this.onInstancesChanged(() => updateTerminalContextKeys());
}
public getActiveOrCreateInstance(): ITerminalInstance {
const activeInstance = this.getActiveInstance();
return activeInstance ? activeInstance : this.createTerminal(undefined);
}
public requestStartExtensionTerminal(proxy: ITerminalProcessExtHostProxy, cols: number, rows: number): Promise<ITerminalLaunchError | undefined> {
// The initial request came from the extension host, no need to wait for it
return new Promise<ITerminalLaunchError | undefined>(callback => {
this._onInstanceRequestStartExtensionTerminal.fire({ proxy, cols, rows, callback });
});
}
public async extHostReady(remoteAuthority: string): Promise<void> {
this._createExtHostReadyEntry(remoteAuthority);
this._extHostsReady[remoteAuthority]!.resolve();
}
public getAvailableProfiles(): ITerminalProfile[] {
this._updateAvailableProfiles();
return this._availableProfiles || [];
}
private async _getWorkspaceProfilePermissions(profile: ITerminalProfile): Promise<boolean> {
const platformKey = await this._getPlatformKey();
const profiles = this._configurationService.inspect<{ [key: string]: ITerminalProfileObject }>(`terminal.integrated.profiles.${platformKey}`);
if (!profiles || !profiles.workspaceValue || !profiles.defaultValue) {
return false;
}
const workspaceProfile = Object.entries(profiles.workspaceValue).find(p => p[0] === profile.profileName);
const defaultProfile = Object.entries(profiles.defaultValue).find(p => p[0] === profile.profileName);
if (workspaceProfile && defaultProfile && workspaceProfile[0] === defaultProfile[0]) {
let result = !this._terminalProfileObjectEqual(workspaceProfile[1], defaultProfile[1]);
return result;
} else if (!workspaceProfile && !defaultProfile) {
// user profile
return false;
} else {
// this key is missing from either default or the workspace config
return true;
}
}
private _terminalProfileObjectEqual(one?: ITerminalProfileObject, two?: ITerminalProfileObject): boolean {
if (one === null && two === null) {
return true;
} else if ((one as ITerminalExecutable).path && (two as ITerminalExecutable).path) {
const oneExec = (one as ITerminalExecutable);
const twoExec = (two as ITerminalExecutable);
return ((Array.isArray(oneExec.path) && Array.isArray(twoExec.path) && oneExec.path.length === twoExec.path.length && oneExec.path.every((p, index) => p === twoExec.path[index])) ||
(oneExec.path === twoExec.path)
) && ((Array.isArray(oneExec.args) && Array.isArray(twoExec.args) && oneExec.args?.every((a, index) => a === twoExec.args?.[index])) ||
(oneExec.args === twoExec.args)
);
} else if ((one as ITerminalProfileSource).source && (two as ITerminalProfileSource).source) {
const oneSource = (one as ITerminalProfileSource);
const twoSource = (two as ITerminalProfileSource);
return oneSource.source === twoSource.source;
}
return false;
}
// when relevant config changes, update without debouncing
private async _updateAvailableProfilesNow(): Promise<void> {
const result = await this._detectProfiles(true);
for (const p of result) {
p.isWorkspaceProfile = await this._getWorkspaceProfilePermissions(p);
}
if (!equals(result, this._availableProfiles)) {
this._availableProfiles = result;
this._onProfilesConfigChanged.fire();
}
}
// avoid checking this very often, every ten seconds shoulds suffice
@throttle(10000)
private _updateAvailableProfiles(): Promise<void> {
return this._updateAvailableProfilesNow();
}
private async _detectProfiles(quickLaunchOnly: boolean): Promise<ITerminalProfile[]> {
await this._extensionService.whenInstalledExtensionsRegistered();
// Wait for the remoteAuthority to be ready (and listening for events) before firing
// the event to spawn the ext host process
const conn = this._remoteAgentService.getConnection();
const remoteAuthority = conn ? conn.remoteAuthority : 'null';
await this._whenExtHostReady(remoteAuthority);
return new Promise(r => this._onRequestAvailableProfiles.fire({ callback: r, quickLaunchOnly: quickLaunchOnly }));
}
private async _whenExtHostReady(remoteAuthority: string): Promise<void> {
this._createExtHostReadyEntry(remoteAuthority);
return this._extHostsReady[remoteAuthority]!.promise;
}
private _createExtHostReadyEntry(remoteAuthority: string): void {
if (this._extHostsReady[remoteAuthority]) {
return;
}
let resolve!: () => void;
const promise = new Promise<void>(r => resolve = r);
this._extHostsReady[remoteAuthority] = { promise, resolve };
}
private _onBeforeShutdown(reason: ShutdownReason): boolean | Promise<boolean> {
if (this.terminalInstances.length === 0) {
// No terminal instances, don't veto
return false;
}
const shouldPersistTerminals = this._configHelper.config.enablePersistentSessions && reason === ShutdownReason.RELOAD;
if (this.configHelper.config.confirmOnExit && !shouldPersistTerminals) {
return this._onBeforeShutdownAsync();
}
this._isShuttingDown = true;
return false;
}
private async _onBeforeShutdownAsync(): Promise<boolean> {
// veto if configured to show confirmation and the user chose not to exit
const veto = await this._showTerminalCloseConfirmation();
if (!veto) {
this._isShuttingDown = true;
}
return veto;
}
private _onWillShutdown(e: WillShutdownEvent): void {
// Don't touch processes if the shutdown was a result of reload as they will be reattached
const shouldPersistTerminals = this._configHelper.config.enablePersistentSessions && e.reason === ShutdownReason.RELOAD;
if (shouldPersistTerminals) {
this.terminalInstances.forEach(instance => instance.detachFromProcess());
return;
}
// Force dispose of all terminal instances, don't force immediate disposal of the terminal
// processes on Windows as an additional mitigation for https://github.com/microsoft/vscode/issues/71966
// which causes the pty host to become unresponsive, disconnecting all terminals across all
// windows
this.terminalInstances.forEach(instance => instance.dispose(!isWindows));
this._localTerminalService!.setTerminalLayoutInfo(undefined);
}
public getTabLabels(): string[] {
return this._terminalTabs.filter(tab => tab.terminalInstances.length > 0).map((tab, index) => {
return `${index + 1}: ${tab.title ? tab.title : ''}`;
});
}
public getFindState(): FindReplaceState {
return this._findState;
}
@debounce(500)
private _updateRemoteState(): void {
if (!!this._environmentService.remoteAuthority) {
const state: ITerminalsLayoutInfoById = {
tabs: this.terminalTabs.map(t => t.getLayoutInfo(t === this.getActiveTab()))
};
this._remoteTerminalService.setTerminalLayoutInfo(state);
}
}
@debounce(500)
private _updateLocalState(): void {
const state: ITerminalsLayoutInfoById = {
tabs: this.terminalTabs.map(t => t.getLayoutInfo(t === this.getActiveTab()))
};
this._localTerminalService!.setTerminalLayoutInfo(state);
}
private _removeTab(tab: ITerminalTab): void {
// Get the index of the tab and remove it from the list
const index = this._terminalTabs.indexOf(tab);
const activeTab = this.getActiveTab();
const activeTabIndex = activeTab ? this._terminalTabs.indexOf(activeTab) : -1;
const wasActiveTab = tab === activeTab;
if (index !== -1) {
this._terminalTabs.splice(index, 1);
}
// Adjust focus if the tab was active
if (wasActiveTab && this._terminalTabs.length > 0) {
// TODO: Only focus the new tab if the removed tab had focus?
// const hasFocusOnExit = tab.activeInstance.hadFocusOnExit;
const newIndex = index < this._terminalTabs.length ? index : this._terminalTabs.length - 1;
this.setActiveTabByIndex(newIndex);
const activeInstance = this.getActiveInstance();
if (activeInstance) {
activeInstance.focus(true);
}
} else if (activeTabIndex >= this._terminalTabs.length) {
const newIndex = this._terminalTabs.length - 1;
this.setActiveTabByIndex(newIndex);
}
// Hide the panel if there are no more instances, provided that VS Code is not shutting
// down. When shutting down the panel is locked in place so that it is restored upon next
// launch.
if (this._terminalTabs.length === 0 && !this._isShuttingDown) {
this.hidePanel();
this._onActiveInstanceChanged.fire(undefined);
}
// Fire events
this._onInstancesChanged.fire();
if (wasActiveTab) {
this._onActiveTabChanged.fire();
}
}
public refreshActiveTab(): void {
// Fire active instances changed
this._onActiveTabChanged.fire();
}
public getActiveTab(): ITerminalTab | null {
if (this._activeTabIndex < 0 || this._activeTabIndex >= this._terminalTabs.length) {
return null;
}
return this._terminalTabs[this._activeTabIndex];
}
public getActiveInstance(): ITerminalInstance | null {
const tab = this.getActiveTab();
if (!tab) {
return null;
}
return tab.activeInstance;
}
public doWithActiveInstance<T>(callback: (terminal: ITerminalInstance) => T): T | void {
const instance = this.getActiveInstance();
if (instance) {
return callback(instance);
}
}
public getInstanceFromId(terminalId: number): ITerminalInstance | undefined {
let bgIndex = -1;
this._backgroundedTerminalInstances.forEach((terminalInstance, i) => {
if (terminalInstance.instanceId === terminalId) {
bgIndex = i;
}
});
if (bgIndex !== -1) {
return this._backgroundedTerminalInstances[bgIndex];
}
try {
return this.terminalInstances[this._getIndexFromId(terminalId)];
} catch {
return undefined;
}
}
public getInstanceFromIndex(terminalIndex: number): ITerminalInstance {
return this.terminalInstances[terminalIndex];
}
public setActiveInstance(terminalInstance: ITerminalInstance): void {
// If this was a hideFromUser terminal created by the API this was triggered by show,
// in which case we need to create the terminal tab
if (terminalInstance.shellLaunchConfig.hideFromUser) {
this._showBackgroundTerminal(terminalInstance);
}
this.setActiveInstanceByIndex(this._getIndexFromId(terminalInstance.instanceId));
}
public setActiveTabByIndex(tabIndex: number): void {
if (tabIndex >= this._terminalTabs.length) {
return;
}
const didTabChange = this._activeTabIndex !== tabIndex;
this._activeTabIndex = tabIndex;
this._terminalTabs.forEach((t, i) => t.setVisible(i === this._activeTabIndex));
if (didTabChange) {
this._onActiveTabChanged.fire();
}
}
public isAttachedToTerminal(remoteTerm: IRemoteTerminalAttachTarget): boolean {
return this.terminalInstances.some(term => term.processId === remoteTerm.pid);
}
public async initializeTerminals(): Promise<void> {
if (this._remoteTerminalsInitPromise) {
await this._remoteTerminalsInitPromise;
} else if (this._localTerminalsInitPromise) {
await this._localTerminalsInitPromise;
}
if (this.terminalTabs.length === 0 && this.isProcessSupportRegistered) {
this.createTerminal();
}
}
private _getInstanceFromGlobalInstanceIndex(index: number): { tab: ITerminalTab, tabIndex: number, instance: ITerminalInstance, localInstanceIndex: number } | null {
let currentTabIndex = 0;
while (index >= 0 && currentTabIndex < this._terminalTabs.length) {
const tab = this._terminalTabs[currentTabIndex];
const count = tab.terminalInstances.length;
if (index < count) {
return {
tab,
tabIndex: currentTabIndex,
instance: tab.terminalInstances[index],
localInstanceIndex: index
};
}
index -= count;
currentTabIndex++;
}
return null;
}
public setActiveInstanceByIndex(terminalIndex: number): void {
const query = this._getInstanceFromGlobalInstanceIndex(terminalIndex);
if (!query) {
return;
}
query.tab.setActiveInstanceByIndex(query.localInstanceIndex);
const didTabChange = this._activeTabIndex !== query.tabIndex;
this._activeTabIndex = query.tabIndex;
this._terminalTabs.forEach((t, i) => t.setVisible(i === query.tabIndex));
// Only fire the event if there was a change
if (didTabChange) {
this._onActiveTabChanged.fire();
}
}
public setActiveTabToNext(): void {
if (this._terminalTabs.length <= 1) {
return;
}
let newIndex = this._activeTabIndex + 1;
if (newIndex >= this._terminalTabs.length) {
newIndex = 0;
}
this.setActiveTabByIndex(newIndex);
}
public setActiveTabToPrevious(): void {
if (this._terminalTabs.length <= 1) {
return;
}
let newIndex = this._activeTabIndex - 1;
if (newIndex < 0) {
newIndex = this._terminalTabs.length - 1;
}
this.setActiveTabByIndex(newIndex);
}
public splitInstance(instanceToSplit: ITerminalInstance, shellLaunchConfig: IShellLaunchConfig = {}): ITerminalInstance | null {
const tab = this._getTabForInstance(instanceToSplit);
if (!tab) {
return null;
}
const instance = tab.split(shellLaunchConfig);
this._initInstanceListeners(instance);
this._onInstancesChanged.fire();
this._terminalTabs.forEach((t, i) => t.setVisible(i === this._activeTabIndex));
return instance;
}
protected _initInstanceListeners(instance: ITerminalInstance): void {
instance.addDisposable(instance.onDisposed(this._onInstanceDisposed.fire, this._onInstanceDisposed));
instance.addDisposable(instance.onTitleChanged(this._onInstanceTitleChanged.fire, this._onInstanceTitleChanged));
instance.addDisposable(instance.onProcessIdReady(this._onInstanceProcessIdReady.fire, this._onInstanceProcessIdReady));
instance.addDisposable(instance.onLinksReady(this._onInstanceLinksReady.fire, this._onInstanceLinksReady));
instance.addDisposable(instance.onDimensionsChanged(() => {
this._onInstanceDimensionsChanged.fire(instance);
if (this.configHelper.config.enablePersistentSessions && this.isProcessSupportRegistered) {
!!this._environmentService.remoteAuthority ? this._updateRemoteState() : this._updateLocalState();
}
}));
instance.addDisposable(instance.onMaximumDimensionsChanged(() => this._onInstanceMaximumDimensionsChanged.fire(instance)));
instance.addDisposable(instance.onFocus(this._onActiveInstanceChanged.fire, this._onActiveInstanceChanged));
}
public registerProcessSupport(isSupported: boolean): void {
if (!isSupported) {
return;
}
this._processSupportContextKey.set(isSupported);
this._onDidRegisterProcessSupport.fire();
}
public registerLinkProvider(linkProvider: ITerminalExternalLinkProvider): IDisposable {
const disposables: IDisposable[] = [];
this._linkProviders.add(linkProvider);
for (const instance of this.terminalInstances) {
if (instance.areLinksReady) {
disposables.push(instance.registerLinkProvider(linkProvider));
}
}
this._linkProviderDisposables.set(linkProvider, disposables);
return {
dispose: () => {
const disposables = this._linkProviderDisposables.get(linkProvider) || [];
for (const disposable of disposables) {
disposable.dispose();
}
this._linkProviders.delete(linkProvider);
}
};
}
private _setInstanceLinkProviders(instance: ITerminalInstance): void {
for (const linkProvider of this._linkProviders) {
const disposables = this._linkProviderDisposables.get(linkProvider);
const provider = instance.registerLinkProvider(linkProvider);
disposables?.push(provider);
}
}
private _getTabForInstance(instance: ITerminalInstance): ITerminalTab | undefined {
return this._terminalTabs.find(tab => tab.terminalInstances.indexOf(instance) !== -1);
}
public async showPanel(focus?: boolean): Promise<void> {
const pane = this._viewsService.getActiveViewWithId(TERMINAL_VIEW_ID) as TerminalViewPane;
if (!pane) {
await this._viewsService.openView(TERMINAL_VIEW_ID, focus);
}
if (focus) {
// Do the focus call asynchronously as going through the
// command palette will force editor focus
await timeout(0);
const instance = this.getActiveInstance();
if (instance) {
await instance.focusWhenReady(true);
}
}
}
private _getIndexFromId(terminalId: number): number {
let terminalIndex = -1;
this.terminalInstances.forEach((terminalInstance, i) => {
if (terminalInstance.instanceId === terminalId) {
terminalIndex = i;
}
});
if (terminalIndex === -1) {
throw new Error(`Terminal with ID ${terminalId} does not exist (has it already been disposed?)`);
}
return terminalIndex;
}
public async manageWorkspaceShellPermissions(): Promise<void> {
const allowItem: IQuickPickItem = { label: nls.localize('workbench.action.terminal.allowWorkspaceShell', "Allow Workspace Shell Configuration") };
const disallowItem: IQuickPickItem = { label: nls.localize('workbench.action.terminal.disallowWorkspaceShell', "Disallow Workspace Shell Configuration") };
const value = await this._quickInputService.pick([allowItem, disallowItem], { canPickMany: false });
if (!value) {
return;
}
this.configHelper.setWorkspaceShellAllowed(value === allowItem);
}
protected async _showTerminalCloseConfirmation(): Promise<boolean> {
let message: string;
if (this.terminalInstances.length === 1) {
message = nls.localize('terminalService.terminalCloseConfirmationSingular', "There is an active terminal session, do you want to kill it?");
} else {
message = nls.localize('terminalService.terminalCloseConfirmationPlural', "There are {0} active terminal sessions, do you want to kill them?", this.terminalInstances.length);
}
const res = await this._dialogService.confirm({
message,
type: 'warning',
});
return !res.confirmed;
}
public preparePathForTerminalAsync(originalPath: string, executable: string, title: string, shellType: TerminalShellType): Promise<string> {
return new Promise<string>(c => {
if (!executable) {
c(originalPath);
return;
}
const hasSpace = originalPath.indexOf(' ') !== -1;
const hasParens = originalPath.indexOf('(') !== -1 || originalPath.indexOf(')') !== -1;
const pathBasename = basename(executable, '.exe');
const isPowerShell = pathBasename === 'pwsh' ||
title === 'pwsh' ||
pathBasename === 'powershell' ||
title === 'powershell';
if (isPowerShell && (hasSpace || originalPath.indexOf('\'') !== -1)) {
c(`& '${originalPath.replace(/'/g, '\'\'')}'`);
return;
}
if (hasParens && isPowerShell) {
c(`& '${originalPath}'`);
return;
}
if (isWindows) {
// 17063 is the build number where wsl path was introduced.
// Update Windows uriPath to be executed in WSL.
if (shellType !== undefined) {
if (shellType === WindowsShellType.GitBash) {
c(originalPath.replace(/\\/g, '/'));
return;
}
else if (shellType === WindowsShellType.Wsl) {
if (this._nativeWindowsDelegate && this._nativeWindowsDelegate.getWindowsBuildNumber() >= 17063) {
c(this._nativeWindowsDelegate.getWslPath(originalPath));
} else {
c(originalPath.replace(/\\/g, '/'));
}
return;
}
if (hasSpace) {
c('"' + originalPath + '"');
} else {
c(originalPath);
}
} else {
const lowerExecutable = executable.toLowerCase();
if (this._nativeWindowsDelegate && this._nativeWindowsDelegate.getWindowsBuildNumber() >= 17063 &&
(lowerExecutable.indexOf('wsl') !== -1 || (lowerExecutable.indexOf('bash.exe') !== -1 && lowerExecutable.toLowerCase().indexOf('git') === -1))) {
c(this._nativeWindowsDelegate.getWslPath(originalPath));
return;
} else if (hasSpace) {
c('"' + originalPath + '"');
} else {
c(originalPath);
}
}
return;
}
c(escapeNonWindowsPath(originalPath));
});
}
private async _getPlatformKey(): Promise<string> {
const env = await this._remoteAgentService.getEnvironment();
if (env) {
return env.os === OperatingSystem.Windows ? 'windows' : (env.os === OperatingSystem.Macintosh ? 'osx' : 'linux');
}
return isWindows ? 'windows' : (isMacintosh ? 'osx' : 'linux');
}
public async selectDefaultProfile(): Promise<void> {
const profiles = await this._detectProfiles(false);
const platformKey = await this._getPlatformKey();
interface IProfileQuickPickItem extends IQuickPickItem {
profile: ITerminalProfile;
}
const options: IPickOptions<IProfileQuickPickItem> = {
placeHolder: nls.localize('terminal.integrated.chooseWindowsShell', "Select your preferred terminal shell, you can change this later in your settings"),
onDidTriggerItemButton: async (context) => {
const configKey = `terminal.integrated.profiles.${platformKey}`;
const configProfiles = this._configurationService.inspect<{ [key: string]: ITerminalProfileObject }>(configKey);
const existingProfiles = configProfiles.userValue ? Object.keys(configProfiles.userValue) : [];
const name = await this._quickInputService.input({
prompt: nls.localize('enterTerminalProfileName', "Enter profile name"),
value: context.item.profile.profileName,
validateInput: async input => {
if (existingProfiles.includes(input)) {
return nls.localize('terminalProfileAlreadyExists', "A profile already exists with that name");
}
return undefined;
}
});
if (!name) {
return;
}
const newConfigValue: { [key: string]: ITerminalProfileObject } = { ...configProfiles.userValue } ?? {};
newConfigValue[name] = {
path: context.item.profile.path,
args: context.item.profile.args
};
await this._configurationService.updateValue(configKey, newConfigValue, ConfigurationTarget.USER);
}
};
const quickPickItems = profiles.map((profile): IProfileQuickPickItem => {
const buttons: IQuickInputButton[] = [{
iconClass: ThemeIcon.asClassName(newQuickLaunchProfileIcon),
tooltip: nls.localize('createQuickLaunchProfile', "Create a quick launch profile based on this shell")
}];
if (profile.args) {
if (typeof profile.args === 'string') {
return { label: profile.profileName, description: `${profile.path} ${profile.args}`, profile, buttons };
}
const argsString = profile.args.map(e => {
if (e.includes(' ')) {
return `"${e.replace('/"/g', '\\"')}"`;
}
return e;
}).join(' ');
return { label: profile.profileName, description: `${profile.path} ${argsString}`, profile, buttons };
}
return { label: profile.profileName, description: profile.path, profile, buttons };
});
const value = await this._quickInputService.pick(quickPickItems, options);
if (!value) {
return;
}
await this._configurationService.updateValue(`terminal.integrated.shell.${platformKey}`, value.profile.path, ConfigurationTarget.USER);
await this._configurationService.updateValue(`terminal.integrated.shellArgs.${platformKey}`, value.profile.args, ConfigurationTarget.USER);
}
public createInstance(container: HTMLElement | undefined, shellLaunchConfig: IShellLaunchConfig): ITerminalInstance {
const instance = this._instantiationService.createInstance(TerminalInstance,
this._terminalFocusContextKey,
this._terminalShellTypeContextKey,
this._terminalAltBufferActiveContextKey,
this._configHelper,
container,
shellLaunchConfig
);
this._onInstanceCreated.fire(instance);
return instance;
}
public createTerminal(shell: IShellLaunchConfig = {}): ITerminalInstance {
if (!shell.isExtensionCustomPtyTerminal && !this.isProcessSupportRegistered) {
throw new Error('Could not create terminal when process support is not registered');
}
if (shell.hideFromUser) {
const instance = this.createInstance(undefined, shell);
this._backgroundedTerminalInstances.push(instance);
this._initInstanceListeners(instance);
return instance;
}
const terminalTab = this._instantiationService.createInstance(TerminalTab, this._terminalContainer, shell);
this._terminalTabs.push(terminalTab);
const instance = terminalTab.terminalInstances[0];
terminalTab.addDisposable(terminalTab.onDisposed(this._onTabDisposed.fire, this._onTabDisposed));
terminalTab.addDisposable(terminalTab.onInstancesChanged(this._onInstancesChanged.fire, this._onInstancesChanged));
this._initInstanceListeners(instance);
if (this.terminalInstances.length === 1) {
// It's the first instance so it should be made active automatically
this.setActiveInstanceByIndex(0);
}
this._onInstancesChanged.fire();
return instance;
}
protected _showBackgroundTerminal(instance: ITerminalInstance): void {
this._backgroundedTerminalInstances.splice(this._backgroundedTerminalInstances.indexOf(instance), 1);
instance.shellLaunchConfig.hideFromUser = false;
const terminalTab = this._instantiationService.createInstance(TerminalTab, this._terminalContainer, instance);
this._terminalTabs.push(terminalTab);
terminalTab.addDisposable(terminalTab.onDisposed(this._onTabDisposed.fire, this._onTabDisposed));
terminalTab.addDisposable(terminalTab.onInstancesChanged(this._onInstancesChanged.fire, this._onInstancesChanged));
if (this.terminalInstances.length === 1) {
// It's the first instance so it should be made active automatically
this.setActiveInstanceByIndex(0);
}
this._onInstancesChanged.fire();
}
public async focusFindWidget(): Promise<void> {
await this.showPanel(false);
const pane = this._viewsService.getActiveViewWithId(TERMINAL_VIEW_ID) as TerminalViewPane;
pane.focusFindWidget();
this._findWidgetVisible.set(true);
}
public hideFindWidget(): void {
const pane = this._viewsService.getActiveViewWithId(TERMINAL_VIEW_ID) as TerminalViewPane;
if (pane) {
pane.hideFindWidget();
this._findWidgetVisible.reset();
pane.focus();
}
}
public findNext(): void {
const pane = this._viewsService.getActiveViewWithId(TERMINAL_VIEW_ID) as TerminalViewPane;
if (pane) {
pane.showFindWidget();
pane.getFindWidget().find(false);
}
}
public findPrevious(): void {
const pane = this._viewsService.getActiveViewWithId(TERMINAL_VIEW_ID) as TerminalViewPane;
if (pane) {
pane.showFindWidget();
pane.getFindWidget().find(true);
}
}
public async setContainers(panelContainer: HTMLElement, terminalContainer: HTMLElement): Promise<void> {
this._configHelper.panelContainer = panelContainer;
this._terminalContainer = terminalContainer;
this._terminalTabs.forEach(tab => tab.attachToElement(terminalContainer));
}
public hidePanel(): void {
// Hide the panel if the terminal is in the panel and it has no sibling views
const location = this._viewDescriptorService.getViewLocationById(TERMINAL_VIEW_ID);
if (location === ViewContainerLocation.Panel) {
const panel = this._viewDescriptorService.getViewContainerByViewId(TERMINAL_VIEW_ID);
if (panel && this._viewDescriptorService.getViewContainerModel(panel).activeViewDescriptors.length === 1) {
this._layoutService.setPanelHidden(true);
}
}
}
}
| src/vs/workbench/contrib/terminal/browser/terminalService.ts | 1 | https://github.com/microsoft/vscode/commit/8aac8643d77aa03300f7c62452b0583a0db2b741 | [
0.7793400883674622,
0.00807877816259861,
0.00016453965508844703,
0.000170428553246893,
0.07713410258293152
] |
{
"id": 4,
"code_window": [
"\t\t\t\t\tvalue: context.item.profile.profileName,\n",
"\t\t\t\t\tvalidateInput: async input => {\n",
"\t\t\t\t\t\tif (existingProfiles.includes(input)) {\n",
"\t\t\t\t\t\t\treturn nls.localize('terminalProfileAlreadyExists', \"A profile already exists with that name\");\n",
"\t\t\t\t\t\t}\n",
"\t\t\t\t\t\treturn undefined;\n",
"\t\t\t\t\t}\n",
"\t\t\t\t});\n",
"\t\t\t\tif (!name) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\t\t\treturn nls.localize('terminalProfileAlreadyExists', \"A terminal profile already exists with that name\");\n"
],
"file_path": "src/vs/workbench/contrib/terminal/browser/terminalService.ts",
"type": "replace",
"edit_start_line_idx": 859
} | {
"displayName": "XML Language Basics",
"description": "Provides syntax highlighting and bracket matching in XML files."
}
| extensions/xml/package.nls.json | 0 | https://github.com/microsoft/vscode/commit/8aac8643d77aa03300f7c62452b0583a0db2b741 | [
0.0001724850299069658,
0.0001724850299069658,
0.0001724850299069658,
0.0001724850299069658,
0
] |
{
"id": 4,
"code_window": [
"\t\t\t\t\tvalue: context.item.profile.profileName,\n",
"\t\t\t\t\tvalidateInput: async input => {\n",
"\t\t\t\t\t\tif (existingProfiles.includes(input)) {\n",
"\t\t\t\t\t\t\treturn nls.localize('terminalProfileAlreadyExists', \"A profile already exists with that name\");\n",
"\t\t\t\t\t\t}\n",
"\t\t\t\t\t\treturn undefined;\n",
"\t\t\t\t\t}\n",
"\t\t\t\t});\n",
"\t\t\t\tif (!name) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\t\t\treturn nls.localize('terminalProfileAlreadyExists', \"A terminal profile already exists with that name\");\n"
],
"file_path": "src/vs/workbench/contrib/terminal/browser/terminalService.ts",
"type": "replace",
"edit_start_line_idx": 859
} | /*---------------------------------------------------------------------------------------------
* 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 { mapArrayOrNot } from 'vs/base/common/arrays';
import { CancellationTokenSource } from 'vs/base/common/cancellation';
import { isPromiseCanceledError } from 'vs/base/common/errors';
import { DisposableStore } from 'vs/base/common/lifecycle';
import { joinPath } from 'vs/base/common/resources';
import { URI, UriComponents } from 'vs/base/common/uri';
import * as pfs from 'vs/base/node/pfs';
import { MainContext, MainThreadSearchShape } from 'vs/workbench/api/common/extHost.protocol';
import { NativeExtHostSearch } from 'vs/workbench/api/node/extHostSearch';
import { Range } from 'vs/workbench/api/common/extHostTypes';
import { IFileMatch, IFileQuery, IPatternInfo, IRawFileMatch2, ISearchCompleteStats, ISearchQuery, ITextQuery, QueryType, resultIsMatch } from 'vs/workbench/services/search/common/search';
import { TestRPCProtocol } from 'vs/workbench/test/browser/api/testRPCProtocol';
import type * as vscode from 'vscode';
import { NullLogService } from 'vs/platform/log/common/log';
import { URITransformerService } from 'vs/workbench/api/common/extHostUriTransformerService';
import { mock } from 'vs/base/test/common/mock';
import { IExtHostInitDataService } from 'vs/workbench/api/common/extHostInitDataService';
import { TextSearchManager } from 'vs/workbench/services/search/common/textSearchManager';
import { NativeTextSearchManager } from 'vs/workbench/services/search/node/textSearchManager';
let rpcProtocol: TestRPCProtocol;
let extHostSearch: NativeExtHostSearch;
const disposables = new DisposableStore();
let mockMainThreadSearch: MockMainThreadSearch;
class MockMainThreadSearch implements MainThreadSearchShape {
lastHandle!: number;
results: Array<UriComponents | IRawFileMatch2> = [];
$registerFileSearchProvider(handle: number, scheme: string): void {
this.lastHandle = handle;
}
$registerTextSearchProvider(handle: number, scheme: string): void {
this.lastHandle = handle;
}
$unregisterProvider(handle: number): void {
}
$handleFileMatch(handle: number, session: number, data: UriComponents[]): void {
this.results.push(...data);
}
$handleTextMatch(handle: number, session: number, data: IRawFileMatch2[]): void {
this.results.push(...data);
}
$handleTelemetry(eventName: string, data: any): void {
}
dispose() {
}
}
let mockPFS: Partial<typeof pfs>;
export function extensionResultIsMatch(data: vscode.TextSearchResult): data is vscode.TextSearchMatch {
return !!(<vscode.TextSearchMatch>data).preview;
}
suite('ExtHostSearch', () => {
async function registerTestTextSearchProvider(provider: vscode.TextSearchProvider, scheme = 'file'): Promise<void> {
disposables.add(extHostSearch.registerTextSearchProvider(scheme, provider));
await rpcProtocol.sync();
}
async function registerTestFileSearchProvider(provider: vscode.FileSearchProvider, scheme = 'file'): Promise<void> {
disposables.add(extHostSearch.registerFileSearchProvider(scheme, provider));
await rpcProtocol.sync();
}
async function runFileSearch(query: IFileQuery, cancel = false): Promise<{ results: URI[]; stats: ISearchCompleteStats }> {
let stats: ISearchCompleteStats;
try {
const cancellation = new CancellationTokenSource();
const p = extHostSearch.$provideFileSearchResults(mockMainThreadSearch.lastHandle, 0, query, cancellation.token);
if (cancel) {
await new Promise(resolve => process.nextTick(resolve));
cancellation.cancel();
}
stats = await p;
} catch (err) {
if (!isPromiseCanceledError(err)) {
await rpcProtocol.sync();
throw err;
}
}
await rpcProtocol.sync();
return {
results: (<UriComponents[]>mockMainThreadSearch.results).map(r => URI.revive(r)),
stats: stats!
};
}
async function runTextSearch(query: ITextQuery, cancel = false): Promise<{ results: IFileMatch[], stats: ISearchCompleteStats }> {
let stats: ISearchCompleteStats;
try {
const cancellation = new CancellationTokenSource();
const p = extHostSearch.$provideTextSearchResults(mockMainThreadSearch.lastHandle, 0, query, cancellation.token);
if (cancel) {
await new Promise(resolve => process.nextTick(resolve));
cancellation.cancel();
}
stats = await p;
} catch (err) {
if (!isPromiseCanceledError(err)) {
await rpcProtocol.sync();
throw err;
}
}
await rpcProtocol.sync();
const results = (<IRawFileMatch2[]>mockMainThreadSearch.results).map(r => ({
...r,
...{
resource: URI.revive(r.resource)
}
}));
return { results, stats: stats! };
}
setup(() => {
rpcProtocol = new TestRPCProtocol();
mockMainThreadSearch = new MockMainThreadSearch();
const logService = new NullLogService();
rpcProtocol.set(MainContext.MainThreadSearch, mockMainThreadSearch);
mockPFS = {};
extHostSearch = new class extends NativeExtHostSearch {
constructor() {
super(
rpcProtocol,
new class extends mock<IExtHostInitDataService>() { remote = { isRemote: false, authority: undefined, connectionData: null }; },
new URITransformerService(null),
logService
);
this._pfs = mockPFS as any;
}
protected createTextSearchManager(query: ITextQuery, provider: vscode.TextSearchProvider): TextSearchManager {
return new NativeTextSearchManager(query, provider, this._pfs);
}
};
});
teardown(() => {
disposables.clear();
return rpcProtocol.sync();
});
const rootFolderA = URI.file('/foo/bar1');
const rootFolderB = URI.file('/foo/bar2');
const fancyScheme = 'fancy';
const fancySchemeFolderA = URI.from({ scheme: fancyScheme, path: '/project/folder1' });
suite('File:', () => {
function getSimpleQuery(filePattern = ''): IFileQuery {
return {
type: QueryType.File,
filePattern,
folderQueries: [
{ folder: rootFolderA }
]
};
}
function compareURIs(actual: URI[], expected: URI[]) {
const sortAndStringify = (arr: URI[]) => arr.sort().map(u => u.toString());
assert.deepEqual(
sortAndStringify(actual),
sortAndStringify(expected));
}
test('no results', async () => {
await registerTestFileSearchProvider({
provideFileSearchResults(query: vscode.FileSearchQuery, options: vscode.FileSearchOptions, token: vscode.CancellationToken): Promise<URI[]> {
return Promise.resolve(null!);
}
});
const { results, stats } = await runFileSearch(getSimpleQuery());
assert(!stats.limitHit);
assert(!results.length);
});
test('simple results', async () => {
const reportedResults = [
joinPath(rootFolderA, 'file1.ts'),
joinPath(rootFolderA, 'file2.ts'),
joinPath(rootFolderA, 'subfolder/file3.ts')
];
await registerTestFileSearchProvider({
provideFileSearchResults(query: vscode.FileSearchQuery, options: vscode.FileSearchOptions, token: vscode.CancellationToken): Promise<URI[]> {
return Promise.resolve(reportedResults);
}
});
const { results, stats } = await runFileSearch(getSimpleQuery());
assert(!stats.limitHit);
assert.equal(results.length, 3);
compareURIs(results, reportedResults);
});
test('Search canceled', async () => {
let cancelRequested = false;
await registerTestFileSearchProvider({
provideFileSearchResults(query: vscode.FileSearchQuery, options: vscode.FileSearchOptions, token: vscode.CancellationToken): Promise<URI[]> {
return new Promise((resolve, reject) => {
token.onCancellationRequested(() => {
cancelRequested = true;
resolve([joinPath(options.folder, 'file1.ts')]); // or reject or nothing?
});
});
}
});
const { results } = await runFileSearch(getSimpleQuery(), true);
assert(cancelRequested);
assert(!results.length);
});
test('provider returns null', async () => {
await registerTestFileSearchProvider({
provideFileSearchResults(query: vscode.FileSearchQuery, options: vscode.FileSearchOptions, token: vscode.CancellationToken): Promise<URI[]> {
return null!;
}
});
try {
await runFileSearch(getSimpleQuery());
assert(false, 'Expected to fail');
} catch {
// Expected to throw
}
});
test('all provider calls get global include/excludes', async () => {
await registerTestFileSearchProvider({
provideFileSearchResults(query: vscode.FileSearchQuery, options: vscode.FileSearchOptions, token: vscode.CancellationToken): Promise<URI[]> {
assert(options.excludes.length === 2 && options.includes.length === 2, 'Missing global include/excludes');
return Promise.resolve(null!);
}
});
const query: ISearchQuery = {
type: QueryType.File,
filePattern: '',
includePattern: {
'foo': true,
'bar': true
},
excludePattern: {
'something': true,
'else': true
},
folderQueries: [
{ folder: rootFolderA },
{ folder: rootFolderB }
]
};
await runFileSearch(query);
});
test('global/local include/excludes combined', async () => {
await registerTestFileSearchProvider({
provideFileSearchResults(query: vscode.FileSearchQuery, options: vscode.FileSearchOptions, token: vscode.CancellationToken): Promise<URI[]> {
if (options.folder.toString() === rootFolderA.toString()) {
assert.deepEqual(options.includes.sort(), ['*.ts', 'foo']);
assert.deepEqual(options.excludes.sort(), ['*.js', 'bar']);
} else {
assert.deepEqual(options.includes.sort(), ['*.ts']);
assert.deepEqual(options.excludes.sort(), ['*.js']);
}
return Promise.resolve(null!);
}
});
const query: ISearchQuery = {
type: QueryType.File,
filePattern: '',
includePattern: {
'*.ts': true
},
excludePattern: {
'*.js': true
},
folderQueries: [
{
folder: rootFolderA,
includePattern: {
'foo': true
},
excludePattern: {
'bar': true
}
},
{ folder: rootFolderB }
]
};
await runFileSearch(query);
});
test('include/excludes resolved correctly', async () => {
await registerTestFileSearchProvider({
provideFileSearchResults(query: vscode.FileSearchQuery, options: vscode.FileSearchOptions, token: vscode.CancellationToken): Promise<URI[]> {
assert.deepEqual(options.includes.sort(), ['*.jsx', '*.ts']);
assert.deepEqual(options.excludes.sort(), []);
return Promise.resolve(null!);
}
});
const query: ISearchQuery = {
type: QueryType.File,
filePattern: '',
includePattern: {
'*.ts': true,
'*.jsx': false
},
excludePattern: {
'*.js': true,
'*.tsx': false
},
folderQueries: [
{
folder: rootFolderA,
includePattern: {
'*.jsx': true
},
excludePattern: {
'*.js': false
}
}
]
};
await runFileSearch(query);
});
test('basic sibling exclude clause', async () => {
const reportedResults = [
'file1.ts',
'file1.js',
];
await registerTestFileSearchProvider({
provideFileSearchResults(query: vscode.FileSearchQuery, options: vscode.FileSearchOptions, token: vscode.CancellationToken): Promise<URI[]> {
return Promise.resolve(reportedResults
.map(relativePath => joinPath(options.folder, relativePath)));
}
});
const query: ISearchQuery = {
type: QueryType.File,
filePattern: '',
excludePattern: {
'*.js': {
when: '$(basename).ts'
}
},
folderQueries: [
{ folder: rootFolderA }
]
};
const { results } = await runFileSearch(query);
compareURIs(
results,
[
joinPath(rootFolderA, 'file1.ts')
]);
});
test('multiroot sibling exclude clause', async () => {
await registerTestFileSearchProvider({
provideFileSearchResults(query: vscode.FileSearchQuery, options: vscode.FileSearchOptions, token: vscode.CancellationToken): Promise<URI[]> {
let reportedResults: URI[];
if (options.folder.fsPath === rootFolderA.fsPath) {
reportedResults = [
'folder/fileA.scss',
'folder/fileA.css',
'folder/file2.css'
].map(relativePath => joinPath(rootFolderA, relativePath));
} else {
reportedResults = [
'fileB.ts',
'fileB.js',
'file3.js'
].map(relativePath => joinPath(rootFolderB, relativePath));
}
return Promise.resolve(reportedResults);
}
});
const query: ISearchQuery = {
type: QueryType.File,
filePattern: '',
excludePattern: {
'*.js': {
when: '$(basename).ts'
},
'*.css': true
},
folderQueries: [
{
folder: rootFolderA,
excludePattern: {
'folder/*.css': {
when: '$(basename).scss'
}
}
},
{
folder: rootFolderB,
excludePattern: {
'*.js': false
}
}
]
};
const { results } = await runFileSearch(query);
compareURIs(
results,
[
joinPath(rootFolderA, 'folder/fileA.scss'),
joinPath(rootFolderA, 'folder/file2.css'),
joinPath(rootFolderB, 'fileB.ts'),
joinPath(rootFolderB, 'fileB.js'),
joinPath(rootFolderB, 'file3.js'),
]);
});
test('max results = 1', async () => {
const reportedResults = [
joinPath(rootFolderA, 'file1.ts'),
joinPath(rootFolderA, 'file2.ts'),
joinPath(rootFolderA, 'file3.ts'),
];
let wasCanceled = false;
await registerTestFileSearchProvider({
provideFileSearchResults(query: vscode.FileSearchQuery, options: vscode.FileSearchOptions, token: vscode.CancellationToken): Promise<URI[]> {
token.onCancellationRequested(() => wasCanceled = true);
return Promise.resolve(reportedResults);
}
});
const query: ISearchQuery = {
type: QueryType.File,
filePattern: '',
maxResults: 1,
folderQueries: [
{
folder: rootFolderA
}
]
};
const { results, stats } = await runFileSearch(query);
assert(stats.limitHit, 'Expected to return limitHit');
assert.equal(results.length, 1);
compareURIs(results, reportedResults.slice(0, 1));
assert(wasCanceled, 'Expected to be canceled when hitting limit');
});
test('max results = 2', async () => {
const reportedResults = [
joinPath(rootFolderA, 'file1.ts'),
joinPath(rootFolderA, 'file2.ts'),
joinPath(rootFolderA, 'file3.ts'),
];
let wasCanceled = false;
await registerTestFileSearchProvider({
provideFileSearchResults(query: vscode.FileSearchQuery, options: vscode.FileSearchOptions, token: vscode.CancellationToken): Promise<URI[]> {
token.onCancellationRequested(() => wasCanceled = true);
return Promise.resolve(reportedResults);
}
});
const query: ISearchQuery = {
type: QueryType.File,
filePattern: '',
maxResults: 2,
folderQueries: [
{
folder: rootFolderA
}
]
};
const { results, stats } = await runFileSearch(query);
assert(stats.limitHit, 'Expected to return limitHit');
assert.equal(results.length, 2);
compareURIs(results, reportedResults.slice(0, 2));
assert(wasCanceled, 'Expected to be canceled when hitting limit');
});
test('provider returns maxResults exactly', async () => {
const reportedResults = [
joinPath(rootFolderA, 'file1.ts'),
joinPath(rootFolderA, 'file2.ts'),
];
let wasCanceled = false;
await registerTestFileSearchProvider({
provideFileSearchResults(query: vscode.FileSearchQuery, options: vscode.FileSearchOptions, token: vscode.CancellationToken): Promise<URI[]> {
token.onCancellationRequested(() => wasCanceled = true);
return Promise.resolve(reportedResults);
}
});
const query: ISearchQuery = {
type: QueryType.File,
filePattern: '',
maxResults: 2,
folderQueries: [
{
folder: rootFolderA
}
]
};
const { results, stats } = await runFileSearch(query);
assert(!stats.limitHit, 'Expected not to return limitHit');
assert.equal(results.length, 2);
compareURIs(results, reportedResults);
assert(!wasCanceled, 'Expected not to be canceled when just reaching limit');
});
test('multiroot max results', async () => {
let cancels = 0;
await registerTestFileSearchProvider({
async provideFileSearchResults(query: vscode.FileSearchQuery, options: vscode.FileSearchOptions, token: vscode.CancellationToken): Promise<URI[]> {
token.onCancellationRequested(() => cancels++);
// Provice results async so it has a chance to invoke every provider
await new Promise(r => process.nextTick(r));
return [
'file1.ts',
'file2.ts',
'file3.ts',
].map(relativePath => joinPath(options.folder, relativePath));
}
});
const query: ISearchQuery = {
type: QueryType.File,
filePattern: '',
maxResults: 2,
folderQueries: [
{
folder: rootFolderA
},
{
folder: rootFolderB
}
]
};
const { results } = await runFileSearch(query);
assert.equal(results.length, 2); // Don't care which 2 we got
assert.equal(cancels, 2, 'Expected all invocations to be canceled when hitting limit');
});
test('works with non-file schemes', async () => {
const reportedResults = [
joinPath(fancySchemeFolderA, 'file1.ts'),
joinPath(fancySchemeFolderA, 'file2.ts'),
joinPath(fancySchemeFolderA, 'subfolder/file3.ts'),
];
await registerTestFileSearchProvider({
provideFileSearchResults(query: vscode.FileSearchQuery, options: vscode.FileSearchOptions, token: vscode.CancellationToken): Promise<URI[]> {
return Promise.resolve(reportedResults);
}
}, fancyScheme);
const query: ISearchQuery = {
type: QueryType.File,
filePattern: '',
folderQueries: [
{
folder: fancySchemeFolderA
}
]
};
const { results } = await runFileSearch(query);
compareURIs(results, reportedResults);
});
});
suite('Text:', () => {
function makePreview(text: string): vscode.TextSearchMatch['preview'] {
return {
matches: [new Range(0, 0, 0, text.length)],
text
};
}
function makeTextResult(baseFolder: URI, relativePath: string): vscode.TextSearchMatch {
return {
preview: makePreview('foo'),
ranges: [new Range(0, 0, 0, 3)],
uri: joinPath(baseFolder, relativePath)
};
}
function getSimpleQuery(queryText: string): ITextQuery {
return {
type: QueryType.Text,
contentPattern: getPattern(queryText),
folderQueries: [
{ folder: rootFolderA }
]
};
}
function getPattern(queryText: string): IPatternInfo {
return {
pattern: queryText
};
}
function assertResults(actual: IFileMatch[], expected: vscode.TextSearchResult[]) {
const actualTextSearchResults: vscode.TextSearchResult[] = [];
for (let fileMatch of actual) {
// Make relative
for (let lineResult of fileMatch.results!) {
if (resultIsMatch(lineResult)) {
actualTextSearchResults.push({
preview: {
text: lineResult.preview.text,
matches: mapArrayOrNot(
lineResult.preview.matches,
m => new Range(m.startLineNumber, m.startColumn, m.endLineNumber, m.endColumn))
},
ranges: mapArrayOrNot(
lineResult.ranges,
r => new Range(r.startLineNumber, r.startColumn, r.endLineNumber, r.endColumn),
),
uri: fileMatch.resource
});
} else {
actualTextSearchResults.push(<vscode.TextSearchContext>{
text: lineResult.text,
lineNumber: lineResult.lineNumber,
uri: fileMatch.resource
});
}
}
}
const rangeToString = (r: vscode.Range) => `(${r.start.line}, ${r.start.character}), (${r.end.line}, ${r.end.character})`;
const makeComparable = (results: vscode.TextSearchResult[]) => results
.sort((a, b) => {
const compareKeyA = a.uri.toString() + ': ' + (extensionResultIsMatch(a) ? a.preview.text : a.text);
const compareKeyB = b.uri.toString() + ': ' + (extensionResultIsMatch(b) ? b.preview.text : b.text);
return compareKeyB.localeCompare(compareKeyA);
})
.map(r => extensionResultIsMatch(r) ? {
uri: r.uri.toString(),
range: mapArrayOrNot(r.ranges, rangeToString),
preview: {
text: r.preview.text,
match: null // Don't care about this right now
}
} : {
uri: r.uri.toString(),
text: r.text,
lineNumber: r.lineNumber
});
return assert.deepEqual(
makeComparable(actualTextSearchResults),
makeComparable(expected));
}
test('no results', async () => {
await registerTestTextSearchProvider({
provideTextSearchResults(query: vscode.TextSearchQuery, options: vscode.TextSearchOptions, progress: vscode.Progress<vscode.TextSearchResult>, token: vscode.CancellationToken): Promise<vscode.TextSearchComplete> {
return Promise.resolve(null!);
}
});
const { results, stats } = await runTextSearch(getSimpleQuery('foo'));
assert(!stats.limitHit);
assert(!results.length);
});
test('basic results', async () => {
const providedResults: vscode.TextSearchResult[] = [
makeTextResult(rootFolderA, 'file1.ts'),
makeTextResult(rootFolderA, 'file2.ts')
];
await registerTestTextSearchProvider({
provideTextSearchResults(query: vscode.TextSearchQuery, options: vscode.TextSearchOptions, progress: vscode.Progress<vscode.TextSearchResult>, token: vscode.CancellationToken): Promise<vscode.TextSearchComplete> {
providedResults.forEach(r => progress.report(r));
return Promise.resolve(null!);
}
});
const { results, stats } = await runTextSearch(getSimpleQuery('foo'));
assert(!stats.limitHit);
assertResults(results, providedResults);
});
test('all provider calls get global include/excludes', async () => {
await registerTestTextSearchProvider({
provideTextSearchResults(query: vscode.TextSearchQuery, options: vscode.TextSearchOptions, progress: vscode.Progress<vscode.TextSearchResult>, token: vscode.CancellationToken): Promise<vscode.TextSearchComplete> {
assert.equal(options.includes.length, 1);
assert.equal(options.excludes.length, 1);
return Promise.resolve(null!);
}
});
const query: ITextQuery = {
type: QueryType.Text,
contentPattern: getPattern('foo'),
includePattern: {
'*.ts': true
},
excludePattern: {
'*.js': true
},
folderQueries: [
{ folder: rootFolderA },
{ folder: rootFolderB }
]
};
await runTextSearch(query);
});
test('global/local include/excludes combined', async () => {
await registerTestTextSearchProvider({
provideTextSearchResults(query: vscode.TextSearchQuery, options: vscode.TextSearchOptions, progress: vscode.Progress<vscode.TextSearchResult>, token: vscode.CancellationToken): Promise<vscode.TextSearchComplete> {
if (options.folder.toString() === rootFolderA.toString()) {
assert.deepEqual(options.includes.sort(), ['*.ts', 'foo']);
assert.deepEqual(options.excludes.sort(), ['*.js', 'bar']);
} else {
assert.deepEqual(options.includes.sort(), ['*.ts']);
assert.deepEqual(options.excludes.sort(), ['*.js']);
}
return Promise.resolve(null!);
}
});
const query: ITextQuery = {
type: QueryType.Text,
contentPattern: getPattern('foo'),
includePattern: {
'*.ts': true
},
excludePattern: {
'*.js': true
},
folderQueries: [
{
folder: rootFolderA,
includePattern: {
'foo': true
},
excludePattern: {
'bar': true
}
},
{ folder: rootFolderB }
]
};
await runTextSearch(query);
});
test('include/excludes resolved correctly', async () => {
await registerTestTextSearchProvider({
provideTextSearchResults(query: vscode.TextSearchQuery, options: vscode.TextSearchOptions, progress: vscode.Progress<vscode.TextSearchResult>, token: vscode.CancellationToken): Promise<vscode.TextSearchComplete> {
assert.deepEqual(options.includes.sort(), ['*.jsx', '*.ts']);
assert.deepEqual(options.excludes.sort(), []);
return Promise.resolve(null!);
}
});
const query: ISearchQuery = {
type: QueryType.Text,
contentPattern: getPattern('foo'),
includePattern: {
'*.ts': true,
'*.jsx': false
},
excludePattern: {
'*.js': true,
'*.tsx': false
},
folderQueries: [
{
folder: rootFolderA,
includePattern: {
'*.jsx': true
},
excludePattern: {
'*.js': false
}
}
]
};
await runTextSearch(query);
});
test('provider fail', async () => {
await registerTestTextSearchProvider({
provideTextSearchResults(query: vscode.TextSearchQuery, options: vscode.TextSearchOptions, progress: vscode.Progress<vscode.TextSearchResult>, token: vscode.CancellationToken): Promise<vscode.TextSearchComplete> {
throw new Error('Provider fail');
}
});
try {
await runTextSearch(getSimpleQuery('foo'));
assert(false, 'Expected to fail');
} catch {
// expected to fail
}
});
test('basic sibling clause', async () => {
mockPFS.readdir = (_path: string): any => {
if (_path === rootFolderA.fsPath) {
return Promise.resolve([
'file1.js',
'file1.ts'
]);
} else {
return Promise.reject(new Error('Wrong path'));
}
};
const providedResults: vscode.TextSearchResult[] = [
makeTextResult(rootFolderA, 'file1.js'),
makeTextResult(rootFolderA, 'file1.ts')
];
await registerTestTextSearchProvider({
provideTextSearchResults(query: vscode.TextSearchQuery, options: vscode.TextSearchOptions, progress: vscode.Progress<vscode.TextSearchResult>, token: vscode.CancellationToken): Promise<vscode.TextSearchComplete> {
providedResults.forEach(r => progress.report(r));
return Promise.resolve(null!);
}
});
const query: ISearchQuery = {
type: QueryType.Text,
contentPattern: getPattern('foo'),
excludePattern: {
'*.js': {
when: '$(basename).ts'
}
},
folderQueries: [
{ folder: rootFolderA }
]
};
const { results } = await runTextSearch(query);
assertResults(results, providedResults.slice(1));
});
test('multiroot sibling clause', async () => {
mockPFS.readdir = (_path: string): any => {
if (_path === joinPath(rootFolderA, 'folder').fsPath) {
return Promise.resolve([
'fileA.scss',
'fileA.css',
'file2.css'
]);
} else if (_path === rootFolderB.fsPath) {
return Promise.resolve([
'fileB.ts',
'fileB.js',
'file3.js'
]);
} else {
return Promise.reject(new Error('Wrong path'));
}
};
await registerTestTextSearchProvider({
provideTextSearchResults(query: vscode.TextSearchQuery, options: vscode.TextSearchOptions, progress: vscode.Progress<vscode.TextSearchResult>, token: vscode.CancellationToken): Promise<vscode.TextSearchComplete> {
let reportedResults;
if (options.folder.fsPath === rootFolderA.fsPath) {
reportedResults = [
makeTextResult(rootFolderA, 'folder/fileA.scss'),
makeTextResult(rootFolderA, 'folder/fileA.css'),
makeTextResult(rootFolderA, 'folder/file2.css')
];
} else {
reportedResults = [
makeTextResult(rootFolderB, 'fileB.ts'),
makeTextResult(rootFolderB, 'fileB.js'),
makeTextResult(rootFolderB, 'file3.js')
];
}
reportedResults.forEach(r => progress.report(r));
return Promise.resolve(null!);
}
});
const query: ISearchQuery = {
type: QueryType.Text,
contentPattern: getPattern('foo'),
excludePattern: {
'*.js': {
when: '$(basename).ts'
},
'*.css': true
},
folderQueries: [
{
folder: rootFolderA,
excludePattern: {
'folder/*.css': {
when: '$(basename).scss'
}
}
},
{
folder: rootFolderB,
excludePattern: {
'*.js': false
}
}
]
};
const { results } = await runTextSearch(query);
assertResults(results, [
makeTextResult(rootFolderA, 'folder/fileA.scss'),
makeTextResult(rootFolderA, 'folder/file2.css'),
makeTextResult(rootFolderB, 'fileB.ts'),
makeTextResult(rootFolderB, 'fileB.js'),
makeTextResult(rootFolderB, 'file3.js')]);
});
test('include pattern applied', async () => {
const providedResults: vscode.TextSearchResult[] = [
makeTextResult(rootFolderA, 'file1.js'),
makeTextResult(rootFolderA, 'file1.ts')
];
await registerTestTextSearchProvider({
provideTextSearchResults(query: vscode.TextSearchQuery, options: vscode.TextSearchOptions, progress: vscode.Progress<vscode.TextSearchResult>, token: vscode.CancellationToken): Promise<vscode.TextSearchComplete> {
providedResults.forEach(r => progress.report(r));
return Promise.resolve(null!);
}
});
const query: ISearchQuery = {
type: QueryType.Text,
contentPattern: getPattern('foo'),
includePattern: {
'*.ts': true
},
folderQueries: [
{ folder: rootFolderA }
]
};
const { results } = await runTextSearch(query);
assertResults(results, providedResults.slice(1));
});
test('max results = 1', async () => {
const providedResults: vscode.TextSearchResult[] = [
makeTextResult(rootFolderA, 'file1.ts'),
makeTextResult(rootFolderA, 'file2.ts')
];
let wasCanceled = false;
await registerTestTextSearchProvider({
provideTextSearchResults(query: vscode.TextSearchQuery, options: vscode.TextSearchOptions, progress: vscode.Progress<vscode.TextSearchResult>, token: vscode.CancellationToken): Promise<vscode.TextSearchComplete> {
token.onCancellationRequested(() => wasCanceled = true);
providedResults.forEach(r => progress.report(r));
return Promise.resolve(null!);
}
});
const query: ISearchQuery = {
type: QueryType.Text,
contentPattern: getPattern('foo'),
maxResults: 1,
folderQueries: [
{ folder: rootFolderA }
]
};
const { results, stats } = await runTextSearch(query);
assert(stats.limitHit, 'Expected to return limitHit');
assertResults(results, providedResults.slice(0, 1));
assert(wasCanceled, 'Expected to be canceled');
});
test('max results = 2', async () => {
const providedResults: vscode.TextSearchResult[] = [
makeTextResult(rootFolderA, 'file1.ts'),
makeTextResult(rootFolderA, 'file2.ts'),
makeTextResult(rootFolderA, 'file3.ts')
];
let wasCanceled = false;
await registerTestTextSearchProvider({
provideTextSearchResults(query: vscode.TextSearchQuery, options: vscode.TextSearchOptions, progress: vscode.Progress<vscode.TextSearchResult>, token: vscode.CancellationToken): Promise<vscode.TextSearchComplete> {
token.onCancellationRequested(() => wasCanceled = true);
providedResults.forEach(r => progress.report(r));
return Promise.resolve(null!);
}
});
const query: ISearchQuery = {
type: QueryType.Text,
contentPattern: getPattern('foo'),
maxResults: 2,
folderQueries: [
{ folder: rootFolderA }
]
};
const { results, stats } = await runTextSearch(query);
assert(stats.limitHit, 'Expected to return limitHit');
assertResults(results, providedResults.slice(0, 2));
assert(wasCanceled, 'Expected to be canceled');
});
test('provider returns maxResults exactly', async () => {
const providedResults: vscode.TextSearchResult[] = [
makeTextResult(rootFolderA, 'file1.ts'),
makeTextResult(rootFolderA, 'file2.ts')
];
let wasCanceled = false;
await registerTestTextSearchProvider({
provideTextSearchResults(query: vscode.TextSearchQuery, options: vscode.TextSearchOptions, progress: vscode.Progress<vscode.TextSearchResult>, token: vscode.CancellationToken): Promise<vscode.TextSearchComplete> {
token.onCancellationRequested(() => wasCanceled = true);
providedResults.forEach(r => progress.report(r));
return Promise.resolve(null!);
}
});
const query: ISearchQuery = {
type: QueryType.Text,
contentPattern: getPattern('foo'),
maxResults: 2,
folderQueries: [
{ folder: rootFolderA }
]
};
const { results, stats } = await runTextSearch(query);
assert(!stats.limitHit, 'Expected not to return limitHit');
assertResults(results, providedResults);
assert(!wasCanceled, 'Expected not to be canceled');
});
test('provider returns early with limitHit', async () => {
const providedResults: vscode.TextSearchResult[] = [
makeTextResult(rootFolderA, 'file1.ts'),
makeTextResult(rootFolderA, 'file2.ts'),
makeTextResult(rootFolderA, 'file3.ts')
];
await registerTestTextSearchProvider({
provideTextSearchResults(query: vscode.TextSearchQuery, options: vscode.TextSearchOptions, progress: vscode.Progress<vscode.TextSearchResult>, token: vscode.CancellationToken): Promise<vscode.TextSearchComplete> {
providedResults.forEach(r => progress.report(r));
return Promise.resolve({ limitHit: true });
}
});
const query: ISearchQuery = {
type: QueryType.Text,
contentPattern: getPattern('foo'),
maxResults: 1000,
folderQueries: [
{ folder: rootFolderA }
]
};
const { results, stats } = await runTextSearch(query);
assert(stats.limitHit, 'Expected to return limitHit');
assertResults(results, providedResults);
});
test('multiroot max results', async () => {
let cancels = 0;
await registerTestTextSearchProvider({
async provideTextSearchResults(query: vscode.TextSearchQuery, options: vscode.TextSearchOptions, progress: vscode.Progress<vscode.TextSearchResult>, token: vscode.CancellationToken): Promise<vscode.TextSearchComplete> {
token.onCancellationRequested(() => cancels++);
await new Promise(r => process.nextTick(r));
[
'file1.ts',
'file2.ts',
'file3.ts',
].forEach(f => progress.report(makeTextResult(options.folder, f)));
return null!;
}
});
const query: ISearchQuery = {
type: QueryType.Text,
contentPattern: getPattern('foo'),
maxResults: 2,
folderQueries: [
{ folder: rootFolderA },
{ folder: rootFolderB }
]
};
const { results } = await runTextSearch(query);
assert.equal(results.length, 2);
assert.equal(cancels, 2);
});
test('works with non-file schemes', async () => {
const providedResults: vscode.TextSearchResult[] = [
makeTextResult(fancySchemeFolderA, 'file1.ts'),
makeTextResult(fancySchemeFolderA, 'file2.ts'),
makeTextResult(fancySchemeFolderA, 'file3.ts')
];
await registerTestTextSearchProvider({
provideTextSearchResults(query: vscode.TextSearchQuery, options: vscode.TextSearchOptions, progress: vscode.Progress<vscode.TextSearchResult>, token: vscode.CancellationToken): Promise<vscode.TextSearchComplete> {
providedResults.forEach(r => progress.report(r));
return Promise.resolve(null!);
}
}, fancyScheme);
const query: ISearchQuery = {
type: QueryType.Text,
contentPattern: getPattern('foo'),
folderQueries: [
{ folder: fancySchemeFolderA }
]
};
const { results } = await runTextSearch(query);
assertResults(results, providedResults);
});
});
});
| src/vs/workbench/test/electron-browser/api/extHostSearch.test.ts | 0 | https://github.com/microsoft/vscode/commit/8aac8643d77aa03300f7c62452b0583a0db2b741 | [
0.00019358271674718708,
0.0001734408433549106,
0.00016468780813738704,
0.00017352227587252855,
0.0000035830439628625754
] |
{
"id": 4,
"code_window": [
"\t\t\t\t\tvalue: context.item.profile.profileName,\n",
"\t\t\t\t\tvalidateInput: async input => {\n",
"\t\t\t\t\t\tif (existingProfiles.includes(input)) {\n",
"\t\t\t\t\t\t\treturn nls.localize('terminalProfileAlreadyExists', \"A profile already exists with that name\");\n",
"\t\t\t\t\t\t}\n",
"\t\t\t\t\t\treturn undefined;\n",
"\t\t\t\t\t}\n",
"\t\t\t\t});\n",
"\t\t\t\tif (!name) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\t\t\treturn nls.localize('terminalProfileAlreadyExists', \"A terminal profile already exists with that name\");\n"
],
"file_path": "src/vs/workbench/contrib/terminal/browser/terminalService.ts",
"type": "replace",
"edit_start_line_idx": 859
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// NOTE: VSCode's copy of nodejs path library to be usable in common (non-node) namespace
// Copied from: https://github.com/nodejs/node/tree/43dd49c9782848c25e5b03448c8a0f923f13c158
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
import * as assert from 'assert';
import * as path from 'vs/base/common/path';
import { isWeb, isWindows } from 'vs/base/common/platform';
import * as process from 'vs/base/common/process';
suite('Paths (Node Implementation)', () => {
const __filename = 'path.test.js';
test('join', () => {
const failures = [] as string[];
const backslashRE = /\\/g;
const joinTests: any = [
[[path.posix.join, path.win32.join],
// arguments result
[[['.', 'x/b', '..', '/b/c.js'], 'x/b/c.js'],
[[], '.'],
[['/.', 'x/b', '..', '/b/c.js'], '/x/b/c.js'],
[['/foo', '../../../bar'], '/bar'],
[['foo', '../../../bar'], '../../bar'],
[['foo/', '../../../bar'], '../../bar'],
[['foo/x', '../../../bar'], '../bar'],
[['foo/x', './bar'], 'foo/x/bar'],
[['foo/x/', './bar'], 'foo/x/bar'],
[['foo/x/', '.', 'bar'], 'foo/x/bar'],
[['./'], './'],
[['.', './'], './'],
[['.', '.', '.'], '.'],
[['.', './', '.'], '.'],
[['.', '/./', '.'], '.'],
[['.', '/////./', '.'], '.'],
[['.'], '.'],
[['', '.'], '.'],
[['', 'foo'], 'foo'],
[['foo', '/bar'], 'foo/bar'],
[['', '/foo'], '/foo'],
[['', '', '/foo'], '/foo'],
[['', '', 'foo'], 'foo'],
[['foo', ''], 'foo'],
[['foo/', ''], 'foo/'],
[['foo', '', '/bar'], 'foo/bar'],
[['./', '..', '/foo'], '../foo'],
[['./', '..', '..', '/foo'], '../../foo'],
[['.', '..', '..', '/foo'], '../../foo'],
[['', '..', '..', '/foo'], '../../foo'],
[['/'], '/'],
[['/', '.'], '/'],
[['/', '..'], '/'],
[['/', '..', '..'], '/'],
[[''], '.'],
[['', ''], '.'],
[[' /foo'], ' /foo'],
[[' ', 'foo'], ' /foo'],
[[' ', '.'], ' '],
[[' ', '/'], ' /'],
[[' ', ''], ' '],
[['/', 'foo'], '/foo'],
[['/', '/foo'], '/foo'],
[['/', '//foo'], '/foo'],
[['/', '', '/foo'], '/foo'],
[['', '/', 'foo'], '/foo'],
[['', '/', '/foo'], '/foo']
]
]
];
// Windows-specific join tests
joinTests.push([
path.win32.join,
joinTests[0][1].slice(0).concat(
[// arguments result
// UNC path expected
[['//foo/bar'], '\\\\foo\\bar\\'],
[['\\/foo/bar'], '\\\\foo\\bar\\'],
[['\\\\foo/bar'], '\\\\foo\\bar\\'],
// UNC path expected - server and share separate
[['//foo', 'bar'], '\\\\foo\\bar\\'],
[['//foo/', 'bar'], '\\\\foo\\bar\\'],
[['//foo', '/bar'], '\\\\foo\\bar\\'],
// UNC path expected - questionable
[['//foo', '', 'bar'], '\\\\foo\\bar\\'],
[['//foo/', '', 'bar'], '\\\\foo\\bar\\'],
[['//foo/', '', '/bar'], '\\\\foo\\bar\\'],
// UNC path expected - even more questionable
[['', '//foo', 'bar'], '\\\\foo\\bar\\'],
[['', '//foo/', 'bar'], '\\\\foo\\bar\\'],
[['', '//foo/', '/bar'], '\\\\foo\\bar\\'],
// No UNC path expected (no double slash in first component)
[['\\', 'foo/bar'], '\\foo\\bar'],
[['\\', '/foo/bar'], '\\foo\\bar'],
[['', '/', '/foo/bar'], '\\foo\\bar'],
// No UNC path expected (no non-slashes in first component -
// questionable)
[['//', 'foo/bar'], '\\foo\\bar'],
[['//', '/foo/bar'], '\\foo\\bar'],
[['\\\\', '/', '/foo/bar'], '\\foo\\bar'],
[['//'], '\\'],
// No UNC path expected (share name missing - questionable).
[['//foo'], '\\foo'],
[['//foo/'], '\\foo\\'],
[['//foo', '/'], '\\foo\\'],
[['//foo', '', '/'], '\\foo\\'],
// No UNC path expected (too many leading slashes - questionable)
[['///foo/bar'], '\\foo\\bar'],
[['////foo', 'bar'], '\\foo\\bar'],
[['\\\\\\/foo/bar'], '\\foo\\bar'],
// Drive-relative vs drive-absolute paths. This merely describes the
// status quo, rather than being obviously right
[['c:'], 'c:.'],
[['c:.'], 'c:.'],
[['c:', ''], 'c:.'],
[['', 'c:'], 'c:.'],
[['c:.', '/'], 'c:.\\'],
[['c:.', 'file'], 'c:file'],
[['c:', '/'], 'c:\\'],
[['c:', 'file'], 'c:\\file']
]
)
]);
joinTests.forEach((test: any[]) => {
if (!Array.isArray(test[0])) {
test[0] = [test[0]];
}
test[0].forEach((join: any) => {
test[1].forEach((test: any) => {
const actual = join.apply(null, test[0]);
const expected = test[1];
// For non-Windows specific tests with the Windows join(), we need to try
// replacing the slashes since the non-Windows specific tests' `expected`
// use forward slashes
let actualAlt;
let os;
if (join === path.win32.join) {
actualAlt = actual.replace(backslashRE, '/');
os = 'win32';
} else {
os = 'posix';
}
const message =
`path.${os}.join(${test[0].map(JSON.stringify).join(',')})\n expect=${JSON.stringify(expected)}\n actual=${JSON.stringify(actual)}`;
if (actual !== expected && actualAlt !== expected) {
failures.push(`\n${message}`);
}
});
});
});
assert.strictEqual(failures.length, 0, failures.join(''));
});
test('dirname', () => {
assert.strictEqual(path.posix.dirname('/a/b/'), '/a');
assert.strictEqual(path.posix.dirname('/a/b'), '/a');
assert.strictEqual(path.posix.dirname('/a'), '/');
assert.strictEqual(path.posix.dirname(''), '.');
assert.strictEqual(path.posix.dirname('/'), '/');
assert.strictEqual(path.posix.dirname('////'), '/');
assert.strictEqual(path.posix.dirname('//a'), '//');
assert.strictEqual(path.posix.dirname('foo'), '.');
assert.strictEqual(path.win32.dirname('c:\\'), 'c:\\');
assert.strictEqual(path.win32.dirname('c:\\foo'), 'c:\\');
assert.strictEqual(path.win32.dirname('c:\\foo\\'), 'c:\\');
assert.strictEqual(path.win32.dirname('c:\\foo\\bar'), 'c:\\foo');
assert.strictEqual(path.win32.dirname('c:\\foo\\bar\\'), 'c:\\foo');
assert.strictEqual(path.win32.dirname('c:\\foo\\bar\\baz'), 'c:\\foo\\bar');
assert.strictEqual(path.win32.dirname('\\'), '\\');
assert.strictEqual(path.win32.dirname('\\foo'), '\\');
assert.strictEqual(path.win32.dirname('\\foo\\'), '\\');
assert.strictEqual(path.win32.dirname('\\foo\\bar'), '\\foo');
assert.strictEqual(path.win32.dirname('\\foo\\bar\\'), '\\foo');
assert.strictEqual(path.win32.dirname('\\foo\\bar\\baz'), '\\foo\\bar');
assert.strictEqual(path.win32.dirname('c:'), 'c:');
assert.strictEqual(path.win32.dirname('c:foo'), 'c:');
assert.strictEqual(path.win32.dirname('c:foo\\'), 'c:');
assert.strictEqual(path.win32.dirname('c:foo\\bar'), 'c:foo');
assert.strictEqual(path.win32.dirname('c:foo\\bar\\'), 'c:foo');
assert.strictEqual(path.win32.dirname('c:foo\\bar\\baz'), 'c:foo\\bar');
assert.strictEqual(path.win32.dirname('file:stream'), '.');
assert.strictEqual(path.win32.dirname('dir\\file:stream'), 'dir');
assert.strictEqual(path.win32.dirname('\\\\unc\\share'),
'\\\\unc\\share');
assert.strictEqual(path.win32.dirname('\\\\unc\\share\\foo'),
'\\\\unc\\share\\');
assert.strictEqual(path.win32.dirname('\\\\unc\\share\\foo\\'),
'\\\\unc\\share\\');
assert.strictEqual(path.win32.dirname('\\\\unc\\share\\foo\\bar'),
'\\\\unc\\share\\foo');
assert.strictEqual(path.win32.dirname('\\\\unc\\share\\foo\\bar\\'),
'\\\\unc\\share\\foo');
assert.strictEqual(path.win32.dirname('\\\\unc\\share\\foo\\bar\\baz'),
'\\\\unc\\share\\foo\\bar');
assert.strictEqual(path.win32.dirname('/a/b/'), '/a');
assert.strictEqual(path.win32.dirname('/a/b'), '/a');
assert.strictEqual(path.win32.dirname('/a'), '/');
assert.strictEqual(path.win32.dirname(''), '.');
assert.strictEqual(path.win32.dirname('/'), '/');
assert.strictEqual(path.win32.dirname('////'), '/');
assert.strictEqual(path.win32.dirname('foo'), '.');
// Tests from VSCode
function assertDirname(p: string, expected: string, win = false) {
const actual = win ? path.win32.dirname(p) : path.posix.dirname(p);
if (actual !== expected) {
assert.fail(`${p}: expected: ${expected}, ours: ${actual}`);
}
}
assertDirname('foo/bar', 'foo');
assertDirname('foo\\bar', 'foo', true);
assertDirname('/foo/bar', '/foo');
assertDirname('\\foo\\bar', '\\foo', true);
assertDirname('/foo', '/');
assertDirname('\\foo', '\\', true);
assertDirname('/', '/');
assertDirname('\\', '\\', true);
assertDirname('foo', '.');
assertDirname('f', '.');
assertDirname('f/', '.');
assertDirname('/folder/', '/');
assertDirname('c:\\some\\file.txt', 'c:\\some', true);
assertDirname('c:\\some', 'c:\\', true);
assertDirname('c:\\', 'c:\\', true);
assertDirname('c:', 'c:', true);
assertDirname('\\\\server\\share\\some\\path', '\\\\server\\share\\some', true);
assertDirname('\\\\server\\share\\some', '\\\\server\\share\\', true);
assertDirname('\\\\server\\share\\', '\\\\server\\share\\', true);
});
test('extname', () => {
const failures = [] as string[];
const slashRE = /\//g;
[
[__filename, '.js'],
['', ''],
['/path/to/file', ''],
['/path/to/file.ext', '.ext'],
['/path.to/file.ext', '.ext'],
['/path.to/file', ''],
['/path.to/.file', ''],
['/path.to/.file.ext', '.ext'],
['/path/to/f.ext', '.ext'],
['/path/to/..ext', '.ext'],
['/path/to/..', ''],
['file', ''],
['file.ext', '.ext'],
['.file', ''],
['.file.ext', '.ext'],
['/file', ''],
['/file.ext', '.ext'],
['/.file', ''],
['/.file.ext', '.ext'],
['.path/file.ext', '.ext'],
['file.ext.ext', '.ext'],
['file.', '.'],
['.', ''],
['./', ''],
['.file.ext', '.ext'],
['.file', ''],
['.file.', '.'],
['.file..', '.'],
['..', ''],
['../', ''],
['..file.ext', '.ext'],
['..file', '.file'],
['..file.', '.'],
['..file..', '.'],
['...', '.'],
['...ext', '.ext'],
['....', '.'],
['file.ext/', '.ext'],
['file.ext//', '.ext'],
['file/', ''],
['file//', ''],
['file./', '.'],
['file.//', '.'],
].forEach((test) => {
const expected = test[1];
[path.posix.extname, path.win32.extname].forEach((extname) => {
let input = test[0];
let os;
if (extname === path.win32.extname) {
input = input.replace(slashRE, '\\');
os = 'win32';
} else {
os = 'posix';
}
const actual = extname(input);
const message = `path.${os}.extname(${JSON.stringify(input)})\n expect=${JSON.stringify(expected)}\n actual=${JSON.stringify(actual)}`;
if (actual !== expected) {
failures.push(`\n${message}`);
}
});
{
const input = `C:${test[0].replace(slashRE, '\\')}`;
const actual = path.win32.extname(input);
const message = `path.win32.extname(${JSON.stringify(input)})\n expect=${JSON.stringify(expected)}\n actual=${JSON.stringify(actual)}`;
if (actual !== expected) {
failures.push(`\n${message}`);
}
}
});
assert.strictEqual(failures.length, 0, failures.join(''));
// On Windows, backslash is a path separator.
assert.strictEqual(path.win32.extname('.\\'), '');
assert.strictEqual(path.win32.extname('..\\'), '');
assert.strictEqual(path.win32.extname('file.ext\\'), '.ext');
assert.strictEqual(path.win32.extname('file.ext\\\\'), '.ext');
assert.strictEqual(path.win32.extname('file\\'), '');
assert.strictEqual(path.win32.extname('file\\\\'), '');
assert.strictEqual(path.win32.extname('file.\\'), '.');
assert.strictEqual(path.win32.extname('file.\\\\'), '.');
// On *nix, backslash is a valid name component like any other character.
assert.strictEqual(path.posix.extname('.\\'), '');
assert.strictEqual(path.posix.extname('..\\'), '.\\');
assert.strictEqual(path.posix.extname('file.ext\\'), '.ext\\');
assert.strictEqual(path.posix.extname('file.ext\\\\'), '.ext\\\\');
assert.strictEqual(path.posix.extname('file\\'), '');
assert.strictEqual(path.posix.extname('file\\\\'), '');
assert.strictEqual(path.posix.extname('file.\\'), '.\\');
assert.strictEqual(path.posix.extname('file.\\\\'), '.\\\\');
// Tests from VSCode
assert.equal(path.extname('far.boo'), '.boo');
assert.equal(path.extname('far.b'), '.b');
assert.equal(path.extname('far.'), '.');
assert.equal(path.extname('far.boo/boo.far'), '.far');
assert.equal(path.extname('far.boo/boo'), '');
});
(isWeb && isWindows ? test.skip : test)('resolve', () => { // TODO@sbatten fails on windows & browser only
const failures = [] as string[];
const slashRE = /\//g;
const backslashRE = /\\/g;
const resolveTests = [
[path.win32.resolve,
// arguments result
[[['c:/blah\\blah', 'd:/games', 'c:../a'], 'c:\\blah\\a'],
[['c:/ignore', 'd:\\a/b\\c/d', '\\e.exe'], 'd:\\e.exe'],
[['c:/ignore', 'c:/some/file'], 'c:\\some\\file'],
[['d:/ignore', 'd:some/dir//'], 'd:\\ignore\\some\\dir'],
[['.'], process.cwd()],
[['//server/share', '..', 'relative\\'], '\\\\server\\share\\relative'],
[['c:/', '//'], 'c:\\'],
[['c:/', '//dir'], 'c:\\dir'],
[['c:/', '//server/share'], '\\\\server\\share\\'],
[['c:/', '//server//share'], '\\\\server\\share\\'],
[['c:/', '///some//dir'], 'c:\\some\\dir'],
[['C:\\foo\\tmp.3\\', '..\\tmp.3\\cycles\\root.js'],
'C:\\foo\\tmp.3\\cycles\\root.js']
]
],
[path.posix.resolve,
// arguments result
[[['/var/lib', '../', 'file/'], '/var/file'],
[['/var/lib', '/../', 'file/'], '/file'],
[['a/b/c/', '../../..'], process.cwd()],
[['.'], process.cwd()],
[['/some/dir', '.', '/absolute/'], '/absolute'],
[['/foo/tmp.3/', '../tmp.3/cycles/root.js'], '/foo/tmp.3/cycles/root.js']
]
]
];
resolveTests.forEach((test) => {
const resolve = test[0];
//@ts-expect-error
test[1].forEach((test) => {
//@ts-expect-error
const actual = resolve.apply(null, test[0]);
let actualAlt;
const os = resolve === path.win32.resolve ? 'win32' : 'posix';
if (resolve === path.win32.resolve && !isWindows) {
actualAlt = actual.replace(backslashRE, '/');
}
else if (resolve !== path.win32.resolve && isWindows) {
actualAlt = actual.replace(slashRE, '\\');
}
const expected = test[1];
const message =
`path.${os}.resolve(${test[0].map(JSON.stringify).join(',')})\n expect=${JSON.stringify(expected)}\n actual=${JSON.stringify(actual)}`;
if (actual !== expected && actualAlt !== expected) {
failures.push(`\n${message}`);
}
});
});
assert.strictEqual(failures.length, 0, failures.join(''));
// if (isWindows) {
// // Test resolving the current Windows drive letter from a spawned process.
// // See https://github.com/nodejs/node/issues/7215
// const currentDriveLetter = path.parse(process.cwd()).root.substring(0, 2);
// const resolveFixture = fixtures.path('path-resolve.js');
// const spawnResult = child.spawnSync(
// process.argv[0], [resolveFixture, currentDriveLetter]);
// const resolvedPath = spawnResult.stdout.toString().trim();
// assert.strictEqual(resolvedPath.toLowerCase(), process.cwd().toLowerCase());
// }
});
test('basename', () => {
assert.strictEqual(path.basename(__filename), 'path.test.js');
assert.strictEqual(path.basename(__filename, '.js'), 'path.test');
assert.strictEqual(path.basename('.js', '.js'), '');
assert.strictEqual(path.basename(''), '');
assert.strictEqual(path.basename('/dir/basename.ext'), 'basename.ext');
assert.strictEqual(path.basename('/basename.ext'), 'basename.ext');
assert.strictEqual(path.basename('basename.ext'), 'basename.ext');
assert.strictEqual(path.basename('basename.ext/'), 'basename.ext');
assert.strictEqual(path.basename('basename.ext//'), 'basename.ext');
assert.strictEqual(path.basename('aaa/bbb', '/bbb'), 'bbb');
assert.strictEqual(path.basename('aaa/bbb', 'a/bbb'), 'bbb');
assert.strictEqual(path.basename('aaa/bbb', 'bbb'), 'bbb');
assert.strictEqual(path.basename('aaa/bbb//', 'bbb'), 'bbb');
assert.strictEqual(path.basename('aaa/bbb', 'bb'), 'b');
assert.strictEqual(path.basename('aaa/bbb', 'b'), 'bb');
assert.strictEqual(path.basename('/aaa/bbb', '/bbb'), 'bbb');
assert.strictEqual(path.basename('/aaa/bbb', 'a/bbb'), 'bbb');
assert.strictEqual(path.basename('/aaa/bbb', 'bbb'), 'bbb');
assert.strictEqual(path.basename('/aaa/bbb//', 'bbb'), 'bbb');
assert.strictEqual(path.basename('/aaa/bbb', 'bb'), 'b');
assert.strictEqual(path.basename('/aaa/bbb', 'b'), 'bb');
assert.strictEqual(path.basename('/aaa/bbb'), 'bbb');
assert.strictEqual(path.basename('/aaa/'), 'aaa');
assert.strictEqual(path.basename('/aaa/b'), 'b');
assert.strictEqual(path.basename('/a/b'), 'b');
assert.strictEqual(path.basename('//a'), 'a');
assert.strictEqual(path.basename('a', 'a'), '');
// On Windows a backslash acts as a path separator.
assert.strictEqual(path.win32.basename('\\dir\\basename.ext'), 'basename.ext');
assert.strictEqual(path.win32.basename('\\basename.ext'), 'basename.ext');
assert.strictEqual(path.win32.basename('basename.ext'), 'basename.ext');
assert.strictEqual(path.win32.basename('basename.ext\\'), 'basename.ext');
assert.strictEqual(path.win32.basename('basename.ext\\\\'), 'basename.ext');
assert.strictEqual(path.win32.basename('foo'), 'foo');
assert.strictEqual(path.win32.basename('aaa\\bbb', '\\bbb'), 'bbb');
assert.strictEqual(path.win32.basename('aaa\\bbb', 'a\\bbb'), 'bbb');
assert.strictEqual(path.win32.basename('aaa\\bbb', 'bbb'), 'bbb');
assert.strictEqual(path.win32.basename('aaa\\bbb\\\\\\\\', 'bbb'), 'bbb');
assert.strictEqual(path.win32.basename('aaa\\bbb', 'bb'), 'b');
assert.strictEqual(path.win32.basename('aaa\\bbb', 'b'), 'bb');
assert.strictEqual(path.win32.basename('C:'), '');
assert.strictEqual(path.win32.basename('C:.'), '.');
assert.strictEqual(path.win32.basename('C:\\'), '');
assert.strictEqual(path.win32.basename('C:\\dir\\base.ext'), 'base.ext');
assert.strictEqual(path.win32.basename('C:\\basename.ext'), 'basename.ext');
assert.strictEqual(path.win32.basename('C:basename.ext'), 'basename.ext');
assert.strictEqual(path.win32.basename('C:basename.ext\\'), 'basename.ext');
assert.strictEqual(path.win32.basename('C:basename.ext\\\\'), 'basename.ext');
assert.strictEqual(path.win32.basename('C:foo'), 'foo');
assert.strictEqual(path.win32.basename('file:stream'), 'file:stream');
assert.strictEqual(path.win32.basename('a', 'a'), '');
// On unix a backslash is just treated as any other character.
assert.strictEqual(path.posix.basename('\\dir\\basename.ext'),
'\\dir\\basename.ext');
assert.strictEqual(path.posix.basename('\\basename.ext'), '\\basename.ext');
assert.strictEqual(path.posix.basename('basename.ext'), 'basename.ext');
assert.strictEqual(path.posix.basename('basename.ext\\'), 'basename.ext\\');
assert.strictEqual(path.posix.basename('basename.ext\\\\'), 'basename.ext\\\\');
assert.strictEqual(path.posix.basename('foo'), 'foo');
// POSIX filenames may include control characters
// c.f. http://www.dwheeler.com/essays/fixing-unix-linux-filenames.html
const controlCharFilename = `Icon${String.fromCharCode(13)}`;
assert.strictEqual(path.posix.basename(`/a/b/${controlCharFilename}`),
controlCharFilename);
// Tests from VSCode
assert.equal(path.basename('foo/bar'), 'bar');
assert.equal(path.posix.basename('foo\\bar'), 'foo\\bar');
assert.equal(path.win32.basename('foo\\bar'), 'bar');
assert.equal(path.basename('/foo/bar'), 'bar');
assert.equal(path.posix.basename('\\foo\\bar'), '\\foo\\bar');
assert.equal(path.win32.basename('\\foo\\bar'), 'bar');
assert.equal(path.basename('./bar'), 'bar');
assert.equal(path.posix.basename('.\\bar'), '.\\bar');
assert.equal(path.win32.basename('.\\bar'), 'bar');
assert.equal(path.basename('/bar'), 'bar');
assert.equal(path.posix.basename('\\bar'), '\\bar');
assert.equal(path.win32.basename('\\bar'), 'bar');
assert.equal(path.basename('bar/'), 'bar');
assert.equal(path.posix.basename('bar\\'), 'bar\\');
assert.equal(path.win32.basename('bar\\'), 'bar');
assert.equal(path.basename('bar'), 'bar');
assert.equal(path.basename('////////'), '');
assert.equal(path.posix.basename('\\\\\\\\'), '\\\\\\\\');
assert.equal(path.win32.basename('\\\\\\\\'), '');
});
test('relative', () => {
const failures = [] as string[];
const relativeTests = [
[path.win32.relative,
// arguments result
[['c:/blah\\blah', 'd:/games', 'd:\\games'],
['c:/aaaa/bbbb', 'c:/aaaa', '..'],
['c:/aaaa/bbbb', 'c:/cccc', '..\\..\\cccc'],
['c:/aaaa/bbbb', 'c:/aaaa/bbbb', ''],
['c:/aaaa/bbbb', 'c:/aaaa/cccc', '..\\cccc'],
['c:/aaaa/', 'c:/aaaa/cccc', 'cccc'],
['c:/', 'c:\\aaaa\\bbbb', 'aaaa\\bbbb'],
['c:/aaaa/bbbb', 'd:\\', 'd:\\'],
['c:/AaAa/bbbb', 'c:/aaaa/bbbb', ''],
['c:/aaaaa/', 'c:/aaaa/cccc', '..\\aaaa\\cccc'],
['C:\\foo\\bar\\baz\\quux', 'C:\\', '..\\..\\..\\..'],
['C:\\foo\\test', 'C:\\foo\\test\\bar\\package.json', 'bar\\package.json'],
['C:\\foo\\bar\\baz-quux', 'C:\\foo\\bar\\baz', '..\\baz'],
['C:\\foo\\bar\\baz', 'C:\\foo\\bar\\baz-quux', '..\\baz-quux'],
['\\\\foo\\bar', '\\\\foo\\bar\\baz', 'baz'],
['\\\\foo\\bar\\baz', '\\\\foo\\bar', '..'],
['\\\\foo\\bar\\baz-quux', '\\\\foo\\bar\\baz', '..\\baz'],
['\\\\foo\\bar\\baz', '\\\\foo\\bar\\baz-quux', '..\\baz-quux'],
['C:\\baz-quux', 'C:\\baz', '..\\baz'],
['C:\\baz', 'C:\\baz-quux', '..\\baz-quux'],
['\\\\foo\\baz-quux', '\\\\foo\\baz', '..\\baz'],
['\\\\foo\\baz', '\\\\foo\\baz-quux', '..\\baz-quux'],
['C:\\baz', '\\\\foo\\bar\\baz', '\\\\foo\\bar\\baz'],
['\\\\foo\\bar\\baz', 'C:\\baz', 'C:\\baz']
]
],
[path.posix.relative,
// arguments result
[['/var/lib', '/var', '..'],
['/var/lib', '/bin', '../../bin'],
['/var/lib', '/var/lib', ''],
['/var/lib', '/var/apache', '../apache'],
['/var/', '/var/lib', 'lib'],
['/', '/var/lib', 'var/lib'],
['/foo/test', '/foo/test/bar/package.json', 'bar/package.json'],
['/Users/a/web/b/test/mails', '/Users/a/web/b', '../..'],
['/foo/bar/baz-quux', '/foo/bar/baz', '../baz'],
['/foo/bar/baz', '/foo/bar/baz-quux', '../baz-quux'],
['/baz-quux', '/baz', '../baz'],
['/baz', '/baz-quux', '../baz-quux']
]
]
];
relativeTests.forEach((test) => {
const relative = test[0];
//@ts-expect-error
test[1].forEach((test) => {
//@ts-expect-error
const actual = relative(test[0], test[1]);
const expected = test[2];
const os = relative === path.win32.relative ? 'win32' : 'posix';
const message = `path.${os}.relative(${test.slice(0, 2).map(JSON.stringify).join(',')})\n expect=${JSON.stringify(expected)}\n actual=${JSON.stringify(actual)}`;
if (actual !== expected) {
failures.push(`\n${message}`);
}
});
});
assert.strictEqual(failures.length, 0, failures.join(''));
});
test('normalize', () => {
assert.strictEqual(path.win32.normalize('./fixtures///b/../b/c.js'),
'fixtures\\b\\c.js');
assert.strictEqual(path.win32.normalize('/foo/../../../bar'), '\\bar');
assert.strictEqual(path.win32.normalize('a//b//../b'), 'a\\b');
assert.strictEqual(path.win32.normalize('a//b//./c'), 'a\\b\\c');
assert.strictEqual(path.win32.normalize('a//b//.'), 'a\\b');
assert.strictEqual(path.win32.normalize('//server/share/dir/file.ext'),
'\\\\server\\share\\dir\\file.ext');
assert.strictEqual(path.win32.normalize('/a/b/c/../../../x/y/z'), '\\x\\y\\z');
assert.strictEqual(path.win32.normalize('C:'), 'C:.');
assert.strictEqual(path.win32.normalize('C:..\\abc'), 'C:..\\abc');
assert.strictEqual(path.win32.normalize('C:..\\..\\abc\\..\\def'),
'C:..\\..\\def');
assert.strictEqual(path.win32.normalize('C:\\.'), 'C:\\');
assert.strictEqual(path.win32.normalize('file:stream'), 'file:stream');
assert.strictEqual(path.win32.normalize('bar\\foo..\\..\\'), 'bar\\');
assert.strictEqual(path.win32.normalize('bar\\foo..\\..'), 'bar');
assert.strictEqual(path.win32.normalize('bar\\foo..\\..\\baz'), 'bar\\baz');
assert.strictEqual(path.win32.normalize('bar\\foo..\\'), 'bar\\foo..\\');
assert.strictEqual(path.win32.normalize('bar\\foo..'), 'bar\\foo..');
assert.strictEqual(path.win32.normalize('..\\foo..\\..\\..\\bar'),
'..\\..\\bar');
assert.strictEqual(path.win32.normalize('..\\...\\..\\.\\...\\..\\..\\bar'),
'..\\..\\bar');
assert.strictEqual(path.win32.normalize('../../../foo/../../../bar'),
'..\\..\\..\\..\\..\\bar');
assert.strictEqual(path.win32.normalize('../../../foo/../../../bar/../../'),
'..\\..\\..\\..\\..\\..\\');
assert.strictEqual(
path.win32.normalize('../foobar/barfoo/foo/../../../bar/../../'),
'..\\..\\'
);
assert.strictEqual(
path.win32.normalize('../.../../foobar/../../../bar/../../baz'),
'..\\..\\..\\..\\baz'
);
assert.strictEqual(path.win32.normalize('foo/bar\\baz'), 'foo\\bar\\baz');
assert.strictEqual(path.posix.normalize('./fixtures///b/../b/c.js'),
'fixtures/b/c.js');
assert.strictEqual(path.posix.normalize('/foo/../../../bar'), '/bar');
assert.strictEqual(path.posix.normalize('a//b//../b'), 'a/b');
assert.strictEqual(path.posix.normalize('a//b//./c'), 'a/b/c');
assert.strictEqual(path.posix.normalize('a//b//.'), 'a/b');
assert.strictEqual(path.posix.normalize('/a/b/c/../../../x/y/z'), '/x/y/z');
assert.strictEqual(path.posix.normalize('///..//./foo/.//bar'), '/foo/bar');
assert.strictEqual(path.posix.normalize('bar/foo../../'), 'bar/');
assert.strictEqual(path.posix.normalize('bar/foo../..'), 'bar');
assert.strictEqual(path.posix.normalize('bar/foo../../baz'), 'bar/baz');
assert.strictEqual(path.posix.normalize('bar/foo../'), 'bar/foo../');
assert.strictEqual(path.posix.normalize('bar/foo..'), 'bar/foo..');
assert.strictEqual(path.posix.normalize('../foo../../../bar'), '../../bar');
assert.strictEqual(path.posix.normalize('../.../.././.../../../bar'),
'../../bar');
assert.strictEqual(path.posix.normalize('../../../foo/../../../bar'),
'../../../../../bar');
assert.strictEqual(path.posix.normalize('../../../foo/../../../bar/../../'),
'../../../../../../');
assert.strictEqual(
path.posix.normalize('../foobar/barfoo/foo/../../../bar/../../'),
'../../'
);
assert.strictEqual(
path.posix.normalize('../.../../foobar/../../../bar/../../baz'),
'../../../../baz'
);
assert.strictEqual(path.posix.normalize('foo/bar\\baz'), 'foo/bar\\baz');
});
test('isAbsolute', () => {
assert.strictEqual(path.win32.isAbsolute('/'), true);
assert.strictEqual(path.win32.isAbsolute('//'), true);
assert.strictEqual(path.win32.isAbsolute('//server'), true);
assert.strictEqual(path.win32.isAbsolute('//server/file'), true);
assert.strictEqual(path.win32.isAbsolute('\\\\server\\file'), true);
assert.strictEqual(path.win32.isAbsolute('\\\\server'), true);
assert.strictEqual(path.win32.isAbsolute('\\\\'), true);
assert.strictEqual(path.win32.isAbsolute('c'), false);
assert.strictEqual(path.win32.isAbsolute('c:'), false);
assert.strictEqual(path.win32.isAbsolute('c:\\'), true);
assert.strictEqual(path.win32.isAbsolute('c:/'), true);
assert.strictEqual(path.win32.isAbsolute('c://'), true);
assert.strictEqual(path.win32.isAbsolute('C:/Users/'), true);
assert.strictEqual(path.win32.isAbsolute('C:\\Users\\'), true);
assert.strictEqual(path.win32.isAbsolute('C:cwd/another'), false);
assert.strictEqual(path.win32.isAbsolute('C:cwd\\another'), false);
assert.strictEqual(path.win32.isAbsolute('directory/directory'), false);
assert.strictEqual(path.win32.isAbsolute('directory\\directory'), false);
assert.strictEqual(path.posix.isAbsolute('/home/foo'), true);
assert.strictEqual(path.posix.isAbsolute('/home/foo/..'), true);
assert.strictEqual(path.posix.isAbsolute('bar/'), false);
assert.strictEqual(path.posix.isAbsolute('./baz'), false);
// Tests from VSCode:
// Absolute Paths
[
'C:/',
'C:\\',
'C:/foo',
'C:\\foo',
'z:/foo/bar.txt',
'z:\\foo\\bar.txt',
'\\\\localhost\\c$\\foo',
'/',
'/foo'
].forEach(absolutePath => {
assert.ok(path.win32.isAbsolute(absolutePath), absolutePath);
});
[
'/',
'/foo',
'/foo/bar.txt'
].forEach(absolutePath => {
assert.ok(path.posix.isAbsolute(absolutePath), absolutePath);
});
// Relative Paths
[
'',
'foo',
'foo/bar',
'./foo',
'http://foo.com/bar'
].forEach(nonAbsolutePath => {
assert.ok(!path.win32.isAbsolute(nonAbsolutePath), nonAbsolutePath);
});
[
'',
'foo',
'foo/bar',
'./foo',
'http://foo.com/bar',
'z:/foo/bar.txt',
].forEach(nonAbsolutePath => {
assert.ok(!path.posix.isAbsolute(nonAbsolutePath), nonAbsolutePath);
});
});
test('path', () => {
// path.sep tests
// windows
assert.strictEqual(path.win32.sep, '\\');
// posix
assert.strictEqual(path.posix.sep, '/');
// path.delimiter tests
// windows
assert.strictEqual(path.win32.delimiter, ';');
// posix
assert.strictEqual(path.posix.delimiter, ':');
// if (isWindows) {
// assert.strictEqual(path, path.win32);
// } else {
// assert.strictEqual(path, path.posix);
// }
});
// test('perf', () => {
// const folderNames = [
// 'abc',
// 'Users',
// 'reallylongfoldername',
// 's',
// 'reallyreallyreallylongfoldername',
// 'home'
// ];
// const basePaths = [
// 'C:',
// '',
// ];
// const separators = [
// '\\',
// '/'
// ];
// function randomInt(ciel: number): number {
// return Math.floor(Math.random() * ciel);
// }
// let pathsToNormalize = [];
// let pathsToJoin = [];
// let i;
// for (i = 0; i < 1000000; i++) {
// const basePath = basePaths[randomInt(basePaths.length)];
// let lengthOfPath = randomInt(10) + 2;
// let pathToNormalize = basePath + separators[randomInt(separators.length)];
// while (lengthOfPath-- > 0) {
// pathToNormalize = pathToNormalize + folderNames[randomInt(folderNames.length)] + separators[randomInt(separators.length)];
// }
// pathsToNormalize.push(pathToNormalize);
// let pathToJoin = '';
// lengthOfPath = randomInt(10) + 2;
// while (lengthOfPath-- > 0) {
// pathToJoin = pathToJoin + folderNames[randomInt(folderNames.length)] + separators[randomInt(separators.length)];
// }
// pathsToJoin.push(pathToJoin + '.ts');
// }
// let newTime = 0;
// let j;
// for(j = 0; j < pathsToJoin.length; j++) {
// const path1 = pathsToNormalize[j];
// const path2 = pathsToNormalize[j];
// const newStart = performance.now();
// path.join(path1, path2);
// newTime += performance.now() - newStart;
// }
// assert.ok(false, `Time: ${newTime}ms.`);
// });
});
| src/vs/base/test/common/path.test.ts | 0 | https://github.com/microsoft/vscode/commit/8aac8643d77aa03300f7c62452b0583a0db2b741 | [
0.00017756811575964093,
0.0001724933972582221,
0.00016296139801852405,
0.00017329808906652033,
0.000003324141744087683
] |
{
"id": 5,
"code_window": [
"\t\t\t\tawait this._configurationService.updateValue(configKey, newConfigValue, ConfigurationTarget.USER);\n",
"\t\t\t}\n",
"\t\t};\n",
"\t\tconst quickPickItems = profiles.map((profile): IProfileQuickPickItem => {\n",
"\t\t\tconst buttons: IQuickInputButton[] = [{\n",
"\t\t\t\ticonClass: ThemeIcon.asClassName(newQuickLaunchProfileIcon),\n",
"\t\t\t\ttooltip: nls.localize('createQuickLaunchProfile', \"Create a quick launch profile based on this shell\")\n",
"\t\t\t}];\n",
"\t\t\tif (profile.args) {\n",
"\t\t\t\tif (typeof profile.args === 'string') {\n",
"\t\t\t\t\treturn { label: profile.profileName, description: `${profile.path} ${profile.args}`, profile, buttons };\n",
"\t\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\ticonClass: ThemeIcon.asClassName(configureTerminalProfileIcon),\n",
"\t\t\t\ttooltip: nls.localize('createQuickLaunchProfile', \"Configure Terminal Profile\")\n"
],
"file_path": "src/vs/workbench/contrib/terminal/browser/terminalService.ts",
"type": "replace",
"edit_start_line_idx": 877
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Codicon } from 'vs/base/common/codicons';
import { localize } from 'vs/nls';
import { registerIcon } from 'vs/platform/theme/common/iconRegistry';
export const terminalViewIcon = registerIcon('terminal-view-icon', Codicon.terminal, localize('terminalViewIcon', 'View icon of the terminal view.'));
export const renameTerminalIcon = registerIcon('terminal-rename', Codicon.gear, localize('renameTerminalIcon', 'Icon for rename in the terminal quick menu.'));
export const killTerminalIcon = registerIcon('terminal-kill', Codicon.trash, localize('killTerminalIcon', 'Icon for killing a terminal instance.'));
export const newTerminalIcon = registerIcon('terminal-new', Codicon.add, localize('newTerminalIcon', 'Icon for creating a new terminal instance.'));
export const newQuickLaunchProfileIcon = registerIcon('terminal-quick-launch', Codicon.symbolEvent, localize('newQuickLaunchProfile', 'Icon for creating a new terminal quick launch profile.'));
| src/vs/workbench/contrib/terminal/browser/terminalIcons.ts | 1 | https://github.com/microsoft/vscode/commit/8aac8643d77aa03300f7c62452b0583a0db2b741 | [
0.0016400173772126436,
0.0009070350788533688,
0.0001740527368383482,
0.0009070350788533688,
0.0007329822983592749
] |
{
"id": 5,
"code_window": [
"\t\t\t\tawait this._configurationService.updateValue(configKey, newConfigValue, ConfigurationTarget.USER);\n",
"\t\t\t}\n",
"\t\t};\n",
"\t\tconst quickPickItems = profiles.map((profile): IProfileQuickPickItem => {\n",
"\t\t\tconst buttons: IQuickInputButton[] = [{\n",
"\t\t\t\ticonClass: ThemeIcon.asClassName(newQuickLaunchProfileIcon),\n",
"\t\t\t\ttooltip: nls.localize('createQuickLaunchProfile', \"Create a quick launch profile based on this shell\")\n",
"\t\t\t}];\n",
"\t\t\tif (profile.args) {\n",
"\t\t\t\tif (typeof profile.args === 'string') {\n",
"\t\t\t\t\treturn { label: profile.profileName, description: `${profile.path} ${profile.args}`, profile, buttons };\n",
"\t\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\ticonClass: ThemeIcon.asClassName(configureTerminalProfileIcon),\n",
"\t\t\t\ttooltip: nls.localize('createQuickLaunchProfile', \"Configure Terminal Profile\")\n"
],
"file_path": "src/vs/workbench/contrib/terminal/browser/terminalService.ts",
"type": "replace",
"edit_start_line_idx": 877
} | # THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1
"@types/node@^12.19.9":
version "12.19.9"
resolved "https://registry.yarnpkg.com/@types/node/-/node-12.19.9.tgz#990ad687ad8b26ef6dcc34a4f69c33d40c95b679"
integrity sha512-yj0DOaQeUrk3nJ0bd3Y5PeDRJ6W0r+kilosLA+dzF3dola/o9hxhMSg2sFvVcA2UHS5JSOsZp4S0c1OEXc4m1Q==
vscode-nls@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/vscode-nls/-/vscode-nls-4.0.0.tgz#4001c8a6caba5cedb23a9c5ce1090395c0e44002"
integrity sha512-qCfdzcH+0LgQnBpZA53bA32kzp9rpq/f66Som577ObeuDlFIrtbEJ+A/+CCxjIh4G8dpJYNCKIsxpRAHIfsbNw==
| extensions/debug-auto-launch/yarn.lock | 0 | https://github.com/microsoft/vscode/commit/8aac8643d77aa03300f7c62452b0583a0db2b741 | [
0.00017104457947425544,
0.00016992790915537626,
0.00016881123883649707,
0.00016992790915537626,
0.0000011166703188791871
] |
{
"id": 5,
"code_window": [
"\t\t\t\tawait this._configurationService.updateValue(configKey, newConfigValue, ConfigurationTarget.USER);\n",
"\t\t\t}\n",
"\t\t};\n",
"\t\tconst quickPickItems = profiles.map((profile): IProfileQuickPickItem => {\n",
"\t\t\tconst buttons: IQuickInputButton[] = [{\n",
"\t\t\t\ticonClass: ThemeIcon.asClassName(newQuickLaunchProfileIcon),\n",
"\t\t\t\ttooltip: nls.localize('createQuickLaunchProfile', \"Create a quick launch profile based on this shell\")\n",
"\t\t\t}];\n",
"\t\t\tif (profile.args) {\n",
"\t\t\t\tif (typeof profile.args === 'string') {\n",
"\t\t\t\t\treturn { label: profile.profileName, description: `${profile.path} ${profile.args}`, profile, buttons };\n",
"\t\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\ticonClass: ThemeIcon.asClassName(configureTerminalProfileIcon),\n",
"\t\t\t\ttooltip: nls.localize('createQuickLaunchProfile', \"Configure Terminal Profile\")\n"
],
"file_path": "src/vs/workbench/contrib/terminal/browser/terminalService.ts",
"type": "replace",
"edit_start_line_idx": 877
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as paths from 'vs/base/common/path';
import * as process from 'vs/base/common/process';
import * as types from 'vs/base/common/types';
import * as objects from 'vs/base/common/objects';
import { IStringDictionary } from 'vs/base/common/collections';
import { IProcessEnvironment, isWindows, isMacintosh, isLinux } from 'vs/base/common/platform';
import { normalizeDriveLetter } from 'vs/base/common/labels';
import { localize } from 'vs/nls';
import { URI as uri } from 'vs/base/common/uri';
import { IConfigurationResolverService } from 'vs/workbench/services/configurationResolver/common/configurationResolver';
import { IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { ILabelService } from 'vs/platform/label/common/label';
export interface IVariableResolveContext {
getFolderUri(folderName: string): uri | undefined;
getWorkspaceFolderCount(): number;
getConfigurationValue(folderUri: uri | undefined, section: string): string | undefined;
getAppRoot(): string | undefined;
getExecPath(): string | undefined;
getFilePath(): string | undefined;
getWorkspaceFolderPathForFile?(): string | undefined;
getSelectedText(): string | undefined;
getLineNumber(): string | undefined;
}
export class AbstractVariableResolverService implements IConfigurationResolverService {
static readonly VARIABLE_LHS = '${';
static readonly VARIABLE_REGEXP = /\$\{(.*?)\}/g;
declare readonly _serviceBrand: undefined;
private _context: IVariableResolveContext;
private _labelService?: ILabelService;
private _envVariables?: IProcessEnvironment;
protected _contributedVariables: Map<string, () => Promise<string | undefined>> = new Map();
constructor(_context: IVariableResolveContext, _labelService?: ILabelService, _envVariables?: IProcessEnvironment) {
this._context = _context;
this._labelService = _labelService;
if (_envVariables) {
if (isWindows) {
// windows env variables are case insensitive
const ev: IProcessEnvironment = Object.create(null);
this._envVariables = ev;
Object.keys(_envVariables).forEach(key => {
ev[key.toLowerCase()] = _envVariables[key];
});
} else {
this._envVariables = _envVariables;
}
}
}
public resolve(root: IWorkspaceFolder | undefined, value: string): string;
public resolve(root: IWorkspaceFolder | undefined, value: string[]): string[];
public resolve(root: IWorkspaceFolder | undefined, value: IStringDictionary<string>): IStringDictionary<string>;
public resolve(root: IWorkspaceFolder | undefined, value: any): any {
return this.recursiveResolve(root ? root.uri : undefined, value);
}
public resolveAnyBase(workspaceFolder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>, resolvedVariables?: Map<string, string>): any {
const result = objects.deepClone(config) as any;
// hoist platform specific attributes to top level
if (isWindows && result.windows) {
Object.keys(result.windows).forEach(key => result[key] = result.windows[key]);
} else if (isMacintosh && result.osx) {
Object.keys(result.osx).forEach(key => result[key] = result.osx[key]);
} else if (isLinux && result.linux) {
Object.keys(result.linux).forEach(key => result[key] = result.linux[key]);
}
// delete all platform specific sections
delete result.windows;
delete result.osx;
delete result.linux;
// substitute all variables recursively in string values
return this.recursiveResolve(workspaceFolder ? workspaceFolder.uri : undefined, result, commandValueMapping, resolvedVariables);
}
public resolveAny(workspaceFolder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>): any {
return this.resolveAnyBase(workspaceFolder, config, commandValueMapping);
}
public resolveAnyMap(workspaceFolder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>): { newConfig: any, resolvedVariables: Map<string, string> } {
const resolvedVariables = new Map<string, string>();
const newConfig = this.resolveAnyBase(workspaceFolder, config, commandValueMapping, resolvedVariables);
return { newConfig, resolvedVariables };
}
public resolveWithInteractionReplace(folder: IWorkspaceFolder | undefined, config: any, section?: string, variables?: IStringDictionary<string>): Promise<any> {
throw new Error('resolveWithInteractionReplace not implemented.');
}
public resolveWithInteraction(folder: IWorkspaceFolder | undefined, config: any, section?: string, variables?: IStringDictionary<string>): Promise<Map<string, string> | undefined> {
throw new Error('resolveWithInteraction not implemented.');
}
public contributeVariable(variable: string, resolution: () => Promise<string | undefined>): void {
if (this._contributedVariables.has(variable)) {
throw new Error('Variable ' + variable + ' is contributed twice.');
} else {
this._contributedVariables.set(variable, resolution);
}
}
private recursiveResolve(folderUri: uri | undefined, value: any, commandValueMapping?: IStringDictionary<string>, resolvedVariables?: Map<string, string>): any {
if (types.isString(value)) {
return this.resolveString(folderUri, value, commandValueMapping, resolvedVariables);
} else if (types.isArray(value)) {
return value.map(s => this.recursiveResolve(folderUri, s, commandValueMapping, resolvedVariables));
} else if (types.isObject(value)) {
let result: IStringDictionary<string | IStringDictionary<string> | string[]> = Object.create(null);
Object.keys(value).forEach(key => {
const replaced = this.resolveString(folderUri, key, commandValueMapping, resolvedVariables);
result[replaced] = this.recursiveResolve(folderUri, value[key], commandValueMapping, resolvedVariables);
});
return result;
}
return value;
}
private resolveString(folderUri: uri | undefined, value: string, commandValueMapping: IStringDictionary<string> | undefined, resolvedVariables?: Map<string, string>): string {
// loop through all variables occurrences in 'value'
const replaced = value.replace(AbstractVariableResolverService.VARIABLE_REGEXP, (match: string, variable: string) => {
// disallow attempted nesting, see #77289
if (variable.includes(AbstractVariableResolverService.VARIABLE_LHS)) {
return match;
}
let resolvedValue = this.evaluateSingleVariable(match, variable, folderUri, commandValueMapping);
if (resolvedVariables) {
resolvedVariables.set(variable, resolvedValue);
}
return resolvedValue;
});
return replaced;
}
private fsPath(displayUri: uri): string {
return this._labelService ? this._labelService.getUriLabel(displayUri, { noPrefix: true }) : displayUri.fsPath;
}
private evaluateSingleVariable(match: string, variable: string, folderUri: uri | undefined, commandValueMapping: IStringDictionary<string> | undefined): string {
// try to separate variable arguments from variable name
let argument: string | undefined;
const parts = variable.split(':');
if (parts.length > 1) {
variable = parts[0];
argument = parts[1];
}
// common error handling for all variables that require an open editor
const getFilePath = (): string => {
const filePath = this._context.getFilePath();
if (filePath) {
return filePath;
}
throw new Error(localize('canNotResolveFile', "Variable {0} can not be resolved. Please open an editor.", match));
};
// common error handling for all variables that require an open editor
const getFolderPathForFile = (): string => {
const filePath = getFilePath(); // throws error if no editor open
if (this._context.getWorkspaceFolderPathForFile) {
const folderPath = this._context.getWorkspaceFolderPathForFile();
if (folderPath) {
return folderPath;
}
}
throw new Error(localize('canNotResolveFolderForFile', "Variable {0}: can not find workspace folder of '{1}'.", match, paths.basename(filePath)));
};
// common error handling for all variables that require an open folder and accept a folder name argument
const getFolderUri = (): uri => {
if (argument) {
const folder = this._context.getFolderUri(argument);
if (folder) {
return folder;
}
throw new Error(localize('canNotFindFolder', "Variable {0} can not be resolved. No such folder '{1}'.", match, argument));
}
if (folderUri) {
return folderUri;
}
if (this._context.getWorkspaceFolderCount() > 1) {
throw new Error(localize('canNotResolveWorkspaceFolderMultiRoot', "Variable {0} can not be resolved in a multi folder workspace. Scope this variable using ':' and a workspace folder name.", match));
}
throw new Error(localize('canNotResolveWorkspaceFolder', "Variable {0} can not be resolved. Please open a folder.", match));
};
switch (variable) {
case 'env':
if (argument) {
if (this._envVariables) {
const env = this._envVariables[isWindows ? argument.toLowerCase() : argument];
if (types.isString(env)) {
return env;
}
}
// For `env` we should do the same as a normal shell does - evaluates undefined envs to an empty string #46436
return '';
}
throw new Error(localize('missingEnvVarName', "Variable {0} can not be resolved because no environment variable name is given.", match));
case 'config':
if (argument) {
const config = this._context.getConfigurationValue(folderUri, argument);
if (types.isUndefinedOrNull(config)) {
throw new Error(localize('configNotFound', "Variable {0} can not be resolved because setting '{1}' not found.", match, argument));
}
if (types.isObject(config)) {
throw new Error(localize('configNoString', "Variable {0} can not be resolved because '{1}' is a structured value.", match, argument));
}
return config;
}
throw new Error(localize('missingConfigName', "Variable {0} can not be resolved because no settings name is given.", match));
case 'command':
return this.resolveFromMap(match, argument, commandValueMapping, 'command');
case 'input':
return this.resolveFromMap(match, argument, commandValueMapping, 'input');
default: {
switch (variable) {
case 'workspaceRoot':
case 'workspaceFolder':
return normalizeDriveLetter(this.fsPath(getFolderUri()));
case 'cwd':
return ((folderUri || argument) ? normalizeDriveLetter(this.fsPath(getFolderUri())) : process.cwd());
case 'workspaceRootFolderName':
case 'workspaceFolderBasename':
return paths.basename(this.fsPath(getFolderUri()));
case 'lineNumber':
const lineNumber = this._context.getLineNumber();
if (lineNumber) {
return lineNumber;
}
throw new Error(localize('canNotResolveLineNumber', "Variable {0} can not be resolved. Make sure to have a line selected in the active editor.", match));
case 'selectedText':
const selectedText = this._context.getSelectedText();
if (selectedText) {
return selectedText;
}
throw new Error(localize('canNotResolveSelectedText', "Variable {0} can not be resolved. Make sure to have some text selected in the active editor.", match));
case 'file':
return getFilePath();
case 'fileWorkspaceFolder':
return getFolderPathForFile();
case 'relativeFile':
if (folderUri || argument) {
return paths.relative(this.fsPath(getFolderUri()), getFilePath());
}
return getFilePath();
case 'relativeFileDirname':
const dirname = paths.dirname(getFilePath());
if (folderUri || argument) {
const relative = paths.relative(this.fsPath(getFolderUri()), dirname);
return relative.length === 0 ? '.' : relative;
}
return dirname;
case 'fileDirname':
return paths.dirname(getFilePath());
case 'fileExtname':
return paths.extname(getFilePath());
case 'fileBasename':
return paths.basename(getFilePath());
case 'fileBasenameNoExtension':
const basename = paths.basename(getFilePath());
return (basename.slice(0, basename.length - paths.extname(basename).length));
case 'fileDirnameBasename':
return paths.basename(paths.dirname(getFilePath()));
case 'execPath':
const ep = this._context.getExecPath();
if (ep) {
return ep;
}
return match;
case 'execInstallFolder':
const ar = this._context.getAppRoot();
if (ar) {
return ar;
}
return match;
case 'pathSeparator':
return paths.sep;
default:
try {
const key = argument ? `${variable}:${argument}` : variable;
return this.resolveFromMap(match, key, commandValueMapping, undefined);
} catch (error) {
return match;
}
}
}
}
}
private resolveFromMap(match: string, argument: string | undefined, commandValueMapping: IStringDictionary<string> | undefined, prefix: string | undefined): string {
if (argument && commandValueMapping) {
const v = (prefix === undefined) ? commandValueMapping[argument] : commandValueMapping[prefix + ':' + argument];
if (typeof v === 'string') {
return v;
}
throw new Error(localize('noValueForCommand', "Variable {0} can not be resolved because the command has no value.", match));
}
return match;
}
}
| src/vs/workbench/services/configurationResolver/common/variableResolver.ts | 0 | https://github.com/microsoft/vscode/commit/8aac8643d77aa03300f7c62452b0583a0db2b741 | [
0.00018257905321661383,
0.0001719960564514622,
0.0001582313416292891,
0.00017273059347644448,
0.000003745595449800021
] |
{
"id": 5,
"code_window": [
"\t\t\t\tawait this._configurationService.updateValue(configKey, newConfigValue, ConfigurationTarget.USER);\n",
"\t\t\t}\n",
"\t\t};\n",
"\t\tconst quickPickItems = profiles.map((profile): IProfileQuickPickItem => {\n",
"\t\t\tconst buttons: IQuickInputButton[] = [{\n",
"\t\t\t\ticonClass: ThemeIcon.asClassName(newQuickLaunchProfileIcon),\n",
"\t\t\t\ttooltip: nls.localize('createQuickLaunchProfile', \"Create a quick launch profile based on this shell\")\n",
"\t\t\t}];\n",
"\t\t\tif (profile.args) {\n",
"\t\t\t\tif (typeof profile.args === 'string') {\n",
"\t\t\t\t\treturn { label: profile.profileName, description: `${profile.path} ${profile.args}`, profile, buttons };\n",
"\t\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\ticonClass: ThemeIcon.asClassName(configureTerminalProfileIcon),\n",
"\t\t\t\ttooltip: nls.localize('createQuickLaunchProfile', \"Configure Terminal Profile\")\n"
],
"file_path": "src/vs/workbench/contrib/terminal/browser/terminalService.ts",
"type": "replace",
"edit_start_line_idx": 877
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { INotificationsModel, INotificationChangeEvent, NotificationChangeType, IStatusMessageChangeEvent, StatusMessageChangeType, IStatusMessageViewItem } from 'vs/workbench/common/notifications';
import { IStatusbarService, StatusbarAlignment, IStatusbarEntryAccessor, IStatusbarEntry } from 'vs/workbench/services/statusbar/common/statusbar';
import { Disposable, IDisposable, dispose } from 'vs/base/common/lifecycle';
import { HIDE_NOTIFICATIONS_CENTER, SHOW_NOTIFICATIONS_CENTER } from 'vs/workbench/browser/parts/notifications/notificationsCommands';
import { localize } from 'vs/nls';
export class NotificationsStatus extends Disposable {
private notificationsCenterStatusItem: IStatusbarEntryAccessor | undefined;
private newNotificationsCount = 0;
private currentStatusMessage: [IStatusMessageViewItem, IDisposable] | undefined;
private isNotificationsCenterVisible: boolean = false;
private isNotificationsToastsVisible: boolean = false;
constructor(
private readonly model: INotificationsModel,
@IStatusbarService private readonly statusbarService: IStatusbarService
) {
super();
this.updateNotificationsCenterStatusItem();
if (model.statusMessage) {
this.doSetStatusMessage(model.statusMessage);
}
this.registerListeners();
}
private registerListeners(): void {
this._register(this.model.onDidChangeNotification(e => this.onDidChangeNotification(e)));
this._register(this.model.onDidChangeStatusMessage(e => this.onDidChangeStatusMessage(e)));
}
private onDidChangeNotification(e: INotificationChangeEvent): void {
// Consider a notification as unread as long as it only
// appeared as toast and not in the notification center
if (!this.isNotificationsCenterVisible) {
if (e.kind === NotificationChangeType.ADD) {
this.newNotificationsCount++;
} else if (e.kind === NotificationChangeType.REMOVE && this.newNotificationsCount > 0) {
this.newNotificationsCount--;
}
}
// Update in status bar
this.updateNotificationsCenterStatusItem();
}
private updateNotificationsCenterStatusItem(): void {
// Figure out how many notifications have progress only if neither
// toasts are visible nor center is visible. In that case we still
// want to give a hint to the user that something is running.
let notificationsInProgress = 0;
if (!this.isNotificationsCenterVisible && !this.isNotificationsToastsVisible) {
for (const notification of this.model.notifications) {
if (notification.hasProgress) {
notificationsInProgress++;
}
}
}
// Show the bell with a dot if there are unread or in-progress notifications
const statusProperties: IStatusbarEntry = {
text: `${notificationsInProgress > 0 || this.newNotificationsCount > 0 ? '$(bell-dot)' : '$(bell)'}`,
ariaLabel: localize('status.notifications', "Notifications"),
command: this.isNotificationsCenterVisible ? HIDE_NOTIFICATIONS_CENTER : SHOW_NOTIFICATIONS_CENTER,
tooltip: this.getTooltip(notificationsInProgress),
showBeak: this.isNotificationsCenterVisible
};
if (!this.notificationsCenterStatusItem) {
this.notificationsCenterStatusItem = this.statusbarService.addEntry(
statusProperties,
'status.notifications',
localize('status.notifications', "Notifications"),
StatusbarAlignment.RIGHT,
-Number.MAX_VALUE /* towards the far end of the right hand side */
);
} else {
this.notificationsCenterStatusItem.update(statusProperties);
}
}
private getTooltip(notificationsInProgress: number): string {
if (this.isNotificationsCenterVisible) {
return localize('hideNotifications', "Hide Notifications");
}
if (this.model.notifications.length === 0) {
return localize('zeroNotifications', "No Notifications");
}
if (notificationsInProgress === 0) {
if (this.newNotificationsCount === 0) {
return localize('noNotifications', "No New Notifications");
}
if (this.newNotificationsCount === 1) {
return localize('oneNotification', "1 New Notification");
}
return localize({ key: 'notifications', comment: ['{0} will be replaced by a number'] }, "{0} New Notifications", this.newNotificationsCount);
}
if (this.newNotificationsCount === 0) {
return localize({ key: 'noNotificationsWithProgress', comment: ['{0} will be replaced by a number'] }, "No New Notifications ({0} in progress)", notificationsInProgress);
}
if (this.newNotificationsCount === 1) {
return localize({ key: 'oneNotificationWithProgress', comment: ['{0} will be replaced by a number'] }, "1 New Notification ({0} in progress)", notificationsInProgress);
}
return localize({ key: 'notificationsWithProgress', comment: ['{0} and {1} will be replaced by a number'] }, "{0} New Notifications ({1} in progress)", this.newNotificationsCount, notificationsInProgress);
}
update(isCenterVisible: boolean, isToastsVisible: boolean): void {
let updateNotificationsCenterStatusItem = false;
if (this.isNotificationsCenterVisible !== isCenterVisible) {
this.isNotificationsCenterVisible = isCenterVisible;
this.newNotificationsCount = 0; // Showing the notification center resets the unread counter to 0
updateNotificationsCenterStatusItem = true;
}
if (this.isNotificationsToastsVisible !== isToastsVisible) {
this.isNotificationsToastsVisible = isToastsVisible;
updateNotificationsCenterStatusItem = true;
}
// Update in status bar as needed
if (updateNotificationsCenterStatusItem) {
this.updateNotificationsCenterStatusItem();
}
}
private onDidChangeStatusMessage(e: IStatusMessageChangeEvent): void {
const statusItem = e.item;
switch (e.kind) {
// Show status notification
case StatusMessageChangeType.ADD:
this.doSetStatusMessage(statusItem);
break;
// Hide status notification (if its still the current one)
case StatusMessageChangeType.REMOVE:
if (this.currentStatusMessage && this.currentStatusMessage[0] === statusItem) {
dispose(this.currentStatusMessage[1]);
this.currentStatusMessage = undefined;
}
break;
}
}
private doSetStatusMessage(item: IStatusMessageViewItem): void {
const message = item.message;
const showAfter = item.options && typeof item.options.showAfter === 'number' ? item.options.showAfter : 0;
const hideAfter = item.options && typeof item.options.hideAfter === 'number' ? item.options.hideAfter : -1;
// Dismiss any previous
if (this.currentStatusMessage) {
dispose(this.currentStatusMessage[1]);
}
// Create new
let statusMessageEntry: IStatusbarEntryAccessor;
let showHandle: any = setTimeout(() => {
statusMessageEntry = this.statusbarService.addEntry(
{ text: message, ariaLabel: message },
'status.message',
localize('status.message', "Status Message"),
StatusbarAlignment.LEFT,
-Number.MAX_VALUE /* far right on left hand side */
);
showHandle = null;
}, showAfter);
// Dispose function takes care of timeouts and actual entry
let hideHandle: any;
const statusMessageDispose = {
dispose: () => {
if (showHandle) {
clearTimeout(showHandle);
}
if (hideHandle) {
clearTimeout(hideHandle);
}
if (statusMessageEntry) {
statusMessageEntry.dispose();
}
}
};
if (hideAfter > 0) {
hideHandle = setTimeout(() => statusMessageDispose.dispose(), hideAfter);
}
// Remember as current status message
this.currentStatusMessage = [item, statusMessageDispose];
}
}
| src/vs/workbench/browser/parts/notifications/notificationsStatus.ts | 0 | https://github.com/microsoft/vscode/commit/8aac8643d77aa03300f7c62452b0583a0db2b741 | [
0.00017543650756124407,
0.00017099666001740843,
0.00015862200234550983,
0.00017219918663613498,
0.000004516506578511326
] |
{
"id": 0,
"code_window": [
"export function queryEditorSetSelectedText(queryEditor, sql) {\n",
" return { type: QUERY_EDITOR_SET_SELECTED_TEXT, queryEditor, sql };\n",
"}\n",
"\n",
"export function mergeTable(table, query) {\n",
" return { type: MERGE_TABLE, table, query };\n",
"}\n",
"\n",
"function getTableMetadata(table, query, dispatch) {\n",
" return SupersetClient.get({\n",
" endpoint: encodeURI(\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export function mergeTable(table, query, prepend) {\n",
" return { type: MERGE_TABLE, table, query, prepend };\n"
],
"file_path": "superset-frontend/src/SqlLab/actions/sqlLab.js",
"type": "replace",
"edit_start_line_idx": 1000
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
import shortid from 'shortid';
import JSONbig from 'json-bigint';
import { t, SupersetClient } from '@superset-ui/core';
import invert from 'lodash/invert';
import mapKeys from 'lodash/mapKeys';
import { isFeatureEnabled, FeatureFlag } from 'src/featureFlags';
import { now } from 'src/modules/dates';
import {
addDangerToast as addDangerToastAction,
addInfoToast as addInfoToastAction,
addSuccessToast as addSuccessToastAction,
addWarningToast as addWarningToastAction,
} from 'src/components/MessageToasts/actions';
import { getClientErrorObject } from 'src/utils/getClientErrorObject';
import COMMON_ERR_MESSAGES from 'src/utils/errorMessages';
export const RESET_STATE = 'RESET_STATE';
export const ADD_QUERY_EDITOR = 'ADD_QUERY_EDITOR';
export const UPDATE_QUERY_EDITOR = 'UPDATE_QUERY_EDITOR';
export const QUERY_EDITOR_SAVED = 'QUERY_EDITOR_SAVED';
export const CLONE_QUERY_TO_NEW_TAB = 'CLONE_QUERY_TO_NEW_TAB';
export const REMOVE_QUERY_EDITOR = 'REMOVE_QUERY_EDITOR';
export const MERGE_TABLE = 'MERGE_TABLE';
export const REMOVE_TABLE = 'REMOVE_TABLE';
export const END_QUERY = 'END_QUERY';
export const REMOVE_QUERY = 'REMOVE_QUERY';
export const EXPAND_TABLE = 'EXPAND_TABLE';
export const COLLAPSE_TABLE = 'COLLAPSE_TABLE';
export const QUERY_EDITOR_SETDB = 'QUERY_EDITOR_SETDB';
export const QUERY_EDITOR_SET_SCHEMA = 'QUERY_EDITOR_SET_SCHEMA';
export const QUERY_EDITOR_SET_SCHEMA_OPTIONS =
'QUERY_EDITOR_SET_SCHEMA_OPTIONS';
export const QUERY_EDITOR_SET_TABLE_OPTIONS = 'QUERY_EDITOR_SET_TABLE_OPTIONS';
export const QUERY_EDITOR_SET_TITLE = 'QUERY_EDITOR_SET_TITLE';
export const QUERY_EDITOR_SET_AUTORUN = 'QUERY_EDITOR_SET_AUTORUN';
export const QUERY_EDITOR_SET_SQL = 'QUERY_EDITOR_SET_SQL';
export const QUERY_EDITOR_SET_QUERY_LIMIT = 'QUERY_EDITOR_SET_QUERY_LIMIT';
export const QUERY_EDITOR_SET_TEMPLATE_PARAMS =
'QUERY_EDITOR_SET_TEMPLATE_PARAMS';
export const QUERY_EDITOR_SET_SELECTED_TEXT = 'QUERY_EDITOR_SET_SELECTED_TEXT';
export const QUERY_EDITOR_SET_FUNCTION_NAMES =
'QUERY_EDITOR_SET_FUNCTION_NAMES';
export const QUERY_EDITOR_PERSIST_HEIGHT = 'QUERY_EDITOR_PERSIST_HEIGHT';
export const QUERY_EDITOR_TOGGLE_LEFT_BAR = 'QUERY_EDITOR_TOGGLE_LEFT_BAR';
export const MIGRATE_QUERY_EDITOR = 'MIGRATE_QUERY_EDITOR';
export const MIGRATE_TAB_HISTORY = 'MIGRATE_TAB_HISTORY';
export const MIGRATE_TABLE = 'MIGRATE_TABLE';
export const MIGRATE_QUERY = 'MIGRATE_QUERY';
export const SET_DATABASES = 'SET_DATABASES';
export const SET_ACTIVE_QUERY_EDITOR = 'SET_ACTIVE_QUERY_EDITOR';
export const LOAD_QUERY_EDITOR = 'LOAD_QUERY_EDITOR';
export const SET_TABLES = 'SET_TABLES';
export const SET_ACTIVE_SOUTHPANE_TAB = 'SET_ACTIVE_SOUTHPANE_TAB';
export const REFRESH_QUERIES = 'REFRESH_QUERIES';
export const SET_USER_OFFLINE = 'SET_USER_OFFLINE';
export const RUN_QUERY = 'RUN_QUERY';
export const START_QUERY = 'START_QUERY';
export const STOP_QUERY = 'STOP_QUERY';
export const REQUEST_QUERY_RESULTS = 'REQUEST_QUERY_RESULTS';
export const QUERY_SUCCESS = 'QUERY_SUCCESS';
export const QUERY_FAILED = 'QUERY_FAILED';
export const CLEAR_QUERY_RESULTS = 'CLEAR_QUERY_RESULTS';
export const REMOVE_DATA_PREVIEW = 'REMOVE_DATA_PREVIEW';
export const CHANGE_DATA_PREVIEW_ID = 'CHANGE_DATA_PREVIEW_ID';
export const START_QUERY_VALIDATION = 'START_QUERY_VALIDATION';
export const QUERY_VALIDATION_RETURNED = 'QUERY_VALIDATION_RETURNED';
export const QUERY_VALIDATION_FAILED = 'QUERY_VALIDATION_FAILED';
export const COST_ESTIMATE_STARTED = 'COST_ESTIMATE_STARTED';
export const COST_ESTIMATE_RETURNED = 'COST_ESTIMATE_RETURNED';
export const COST_ESTIMATE_FAILED = 'COST_ESTIMATE_FAILED';
export const CREATE_DATASOURCE_STARTED = 'CREATE_DATASOURCE_STARTED';
export const CREATE_DATASOURCE_SUCCESS = 'CREATE_DATASOURCE_SUCCESS';
export const CREATE_DATASOURCE_FAILED = 'CREATE_DATASOURCE_FAILED';
export const addInfoToast = addInfoToastAction;
export const addSuccessToast = addSuccessToastAction;
export const addDangerToast = addDangerToastAction;
export const addWarningToast = addWarningToastAction;
export const CtasEnum = {
TABLE: 'TABLE',
VIEW: 'VIEW',
};
const ERR_MSG_CANT_LOAD_QUERY = t("The query couldn't be loaded");
// a map of SavedQuery field names to the different names used client-side,
// because for now making the names consistent is too complicated
// so it might as well only happen in one place
const queryClientMapping = {
id: 'remoteId',
db_id: 'dbId',
client_id: 'id',
label: 'title',
};
const queryServerMapping = invert(queryClientMapping);
// uses a mapping like those above to convert object key names to another style
const fieldConverter = mapping => obj =>
mapKeys(obj, (value, key) => (key in mapping ? mapping[key] : key));
const convertQueryToServer = fieldConverter(queryServerMapping);
const convertQueryToClient = fieldConverter(queryClientMapping);
export function resetState() {
return { type: RESET_STATE };
}
export function startQueryValidation(query) {
Object.assign(query, {
id: query.id ? query.id : shortid.generate(),
});
return { type: START_QUERY_VALIDATION, query };
}
export function queryValidationReturned(query, results) {
return { type: QUERY_VALIDATION_RETURNED, query, results };
}
export function queryValidationFailed(query, message, error) {
return { type: QUERY_VALIDATION_FAILED, query, message, error };
}
export function updateQueryEditor(alterations) {
return { type: UPDATE_QUERY_EDITOR, alterations };
}
export function scheduleQuery(query) {
return dispatch =>
SupersetClient.post({
endpoint: '/savedqueryviewapi/api/create',
postPayload: query,
stringify: false,
})
.then(() =>
dispatch(
addSuccessToast(
t(
'Your query has been scheduled. To see details of your query, navigate to Saved queries',
),
),
),
)
.catch(() =>
dispatch(addDangerToast(t('Your query could not be scheduled'))),
);
}
export function estimateQueryCost(query) {
const { dbId, schema, sql, templateParams } = query;
const endpoint =
schema === null
? `/superset/estimate_query_cost/${dbId}/`
: `/superset/estimate_query_cost/${dbId}/${schema}/`;
return dispatch =>
Promise.all([
dispatch({ type: COST_ESTIMATE_STARTED, query }),
SupersetClient.post({
endpoint,
postPayload: {
sql,
templateParams: JSON.parse(templateParams || '{}'),
},
})
.then(({ json }) =>
dispatch({ type: COST_ESTIMATE_RETURNED, query, json }),
)
.catch(response =>
getClientErrorObject(response).then(error => {
const message =
error.error ||
error.statusText ||
t('Failed at retrieving results');
return dispatch({
type: COST_ESTIMATE_FAILED,
query,
error: message,
});
}),
),
]);
}
export function startQuery(query) {
Object.assign(query, {
id: query.id ? query.id : shortid.generate(),
progress: 0,
startDttm: now(),
state: query.runAsync ? 'pending' : 'running',
cached: false,
});
return { type: START_QUERY, query };
}
export function querySuccess(query, results) {
return function (dispatch) {
const sync =
!query.isDataPreview &&
isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)
? SupersetClient.put({
endpoint: encodeURI(`/tabstateview/${results.query.sqlEditorId}`),
postPayload: { latest_query_id: query.id },
})
: Promise.resolve();
return sync
.then(() => dispatch({ type: QUERY_SUCCESS, query, results }))
.catch(() =>
dispatch(
addDangerToast(
t(
'An error occurred while storing the latest query id in the backend. ' +
'Please contact your administrator if this problem persists.',
),
),
),
);
};
}
export function queryFailed(query, msg, link, errors) {
return function (dispatch) {
const sync =
!query.isDataPreview &&
isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)
? SupersetClient.put({
endpoint: encodeURI(`/tabstateview/${query.sqlEditorId}`),
postPayload: { latest_query_id: query.id },
})
: Promise.resolve();
return (
sync
.catch(() =>
dispatch(
addDangerToast(
t(
'An error occurred while storing the latest query id in the backend. ' +
'Please contact your administrator if this problem persists.',
),
),
),
)
// We should always show the error message, even if we couldn't sync the
// state to the backend
.then(() => dispatch({ type: QUERY_FAILED, query, msg, link, errors }))
);
};
}
export function stopQuery(query) {
return { type: STOP_QUERY, query };
}
export function clearQueryResults(query) {
return { type: CLEAR_QUERY_RESULTS, query };
}
export function removeDataPreview(table) {
return { type: REMOVE_DATA_PREVIEW, table };
}
export function requestQueryResults(query) {
return { type: REQUEST_QUERY_RESULTS, query };
}
export function fetchQueryResults(query, displayLimit) {
return function (dispatch) {
dispatch(requestQueryResults(query));
return SupersetClient.get({
endpoint: `/superset/results/${query.resultsKey}/?rows=${displayLimit}`,
parseMethod: 'text',
})
.then(({ text = '{}' }) => {
const bigIntJson = JSONbig.parse(text);
return dispatch(querySuccess(query, bigIntJson));
})
.catch(response =>
getClientErrorObject(response).then(error => {
const message =
error.error ||
error.statusText ||
t('Failed at retrieving results');
return dispatch(
queryFailed(query, message, error.link, error.errors),
);
}),
);
};
}
export function runQuery(query) {
return function (dispatch) {
dispatch(startQuery(query));
const postPayload = {
client_id: query.id,
database_id: query.dbId,
json: true,
runAsync: query.runAsync,
schema: query.schema,
sql: query.sql,
sql_editor_id: query.sqlEditorId,
tab: query.tab,
tmp_table_name: query.tempTable,
select_as_cta: query.ctas,
ctas_method: query.ctas_method,
templateParams: query.templateParams,
queryLimit: query.queryLimit,
expand_data: true,
};
const search = window.location.search || '';
return SupersetClient.post({
endpoint: `/superset/sql_json/${search}`,
body: JSON.stringify(postPayload),
headers: { 'Content-Type': 'application/json' },
parseMethod: 'text',
})
.then(({ text = '{}' }) => {
if (!query.runAsync) {
const bigIntJson = JSONbig.parse(text);
dispatch(querySuccess(query, bigIntJson));
}
})
.catch(response =>
getClientErrorObject(response).then(error => {
let message = error.error || error.statusText || t('Unknown error');
if (message.includes('CSRF token')) {
message = t(COMMON_ERR_MESSAGES.SESSION_TIMED_OUT);
}
dispatch(queryFailed(query, message, error.link, error.errors));
}),
);
};
}
export function reRunQuery(query) {
// run Query with a new id
return function (dispatch) {
dispatch(runQuery({ ...query, id: shortid.generate() }));
};
}
export function validateQuery(query) {
return function (dispatch) {
dispatch(startQueryValidation(query));
const postPayload = {
client_id: query.id,
database_id: query.dbId,
json: true,
schema: query.schema,
sql: query.sql,
sql_editor_id: query.sqlEditorId,
templateParams: query.templateParams,
validate_only: true,
};
return SupersetClient.post({
endpoint: `/superset/validate_sql_json/${window.location.search}`,
postPayload,
stringify: false,
})
.then(({ json }) => dispatch(queryValidationReturned(query, json)))
.catch(response =>
getClientErrorObject(response).then(error => {
let message = error.error || error.statusText || t('Unknown error');
if (message.includes('CSRF token')) {
message = t(COMMON_ERR_MESSAGES.SESSION_TIMED_OUT);
}
dispatch(queryValidationFailed(query, message, error));
}),
);
};
}
export function postStopQuery(query) {
return function (dispatch) {
return SupersetClient.post({
endpoint: '/superset/stop_query/',
postPayload: { client_id: query.id },
stringify: false,
})
.then(() => dispatch(stopQuery(query)))
.then(() => dispatch(addSuccessToast(t('Query was stopped.'))))
.catch(() =>
dispatch(addDangerToast(t('Failed at stopping query. %s', query.id))),
);
};
}
export function setDatabases(databases) {
return { type: SET_DATABASES, databases };
}
function migrateTable(table, queryEditorId, dispatch) {
return SupersetClient.post({
endpoint: encodeURI('/tableschemaview/'),
postPayload: { table: { ...table, queryEditorId } },
})
.then(({ json }) => {
const newTable = {
...table,
id: json.id,
queryEditorId,
};
return dispatch({ type: MIGRATE_TABLE, oldTable: table, newTable });
})
.catch(() =>
dispatch(
addWarningToast(
t(
'Unable to migrate table schema state to backend. Superset will retry ' +
'later. Please contact your administrator if this problem persists.',
),
),
),
);
}
function migrateQuery(queryId, queryEditorId, dispatch) {
return SupersetClient.post({
endpoint: encodeURI(`/tabstateview/${queryEditorId}/migrate_query`),
postPayload: { queryId },
})
.then(() => dispatch({ type: MIGRATE_QUERY, queryId, queryEditorId }))
.catch(() =>
dispatch(
addWarningToast(
t(
'Unable to migrate query state to backend. Superset will retry later. ' +
'Please contact your administrator if this problem persists.',
),
),
),
);
}
export function migrateQueryEditorFromLocalStorage(
queryEditor,
tables,
queries,
) {
return function (dispatch) {
return SupersetClient.post({
endpoint: '/tabstateview/',
postPayload: { queryEditor },
})
.then(({ json }) => {
const newQueryEditor = {
...queryEditor,
id: json.id.toString(),
};
dispatch({
type: MIGRATE_QUERY_EDITOR,
oldQueryEditor: queryEditor,
newQueryEditor,
});
dispatch({
type: MIGRATE_TAB_HISTORY,
oldId: queryEditor.id,
newId: newQueryEditor.id,
});
return Promise.all([
...tables.map(table =>
migrateTable(table, newQueryEditor.id, dispatch),
),
...queries.map(query =>
migrateQuery(query.id, newQueryEditor.id, dispatch),
),
]);
})
.catch(() =>
dispatch(
addWarningToast(
t(
'Unable to migrate query editor state to backend. Superset will retry ' +
'later. Please contact your administrator if this problem persists.',
),
),
),
);
};
}
export function addQueryEditor(queryEditor) {
return function (dispatch) {
const sync = isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)
? SupersetClient.post({
endpoint: '/tabstateview/',
postPayload: { queryEditor },
})
: Promise.resolve({ json: { id: shortid.generate() } });
return sync
.then(({ json }) => {
const newQueryEditor = {
...queryEditor,
id: json.id.toString(),
};
return dispatch({
type: ADD_QUERY_EDITOR,
queryEditor: newQueryEditor,
});
})
.catch(() =>
dispatch(
addDangerToast(
t(
'Unable to add a new tab to the backend. Please contact your administrator.',
),
),
),
);
};
}
export function cloneQueryToNewTab(query, autorun) {
return function (dispatch, getState) {
const state = getState();
const { queryEditors, tabHistory } = state.sqlLab;
const sourceQueryEditor = queryEditors.find(
qe => qe.id === tabHistory[tabHistory.length - 1],
);
const queryEditor = {
title: t('Copy of %s', sourceQueryEditor.title),
dbId: query.dbId ? query.dbId : null,
schema: query.schema ? query.schema : null,
autorun,
sql: query.sql,
queryLimit: sourceQueryEditor.queryLimit,
maxRow: sourceQueryEditor.maxRow,
templateParams: sourceQueryEditor.templateParams,
};
return dispatch(addQueryEditor(queryEditor));
};
}
export function setActiveQueryEditor(queryEditor) {
return function (dispatch) {
const sync = isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)
? SupersetClient.post({
endpoint: encodeURI(`/tabstateview/${queryEditor.id}/activate`),
})
: Promise.resolve();
return sync
.then(() => dispatch({ type: SET_ACTIVE_QUERY_EDITOR, queryEditor }))
.catch(response => {
if (response.status !== 404) {
return dispatch(
addDangerToast(
t(
'An error occurred while setting the active tab. Please contact ' +
'your administrator.',
),
),
);
}
return dispatch({ type: REMOVE_QUERY_EDITOR, queryEditor });
});
};
}
export function loadQueryEditor(queryEditor) {
return { type: LOAD_QUERY_EDITOR, queryEditor };
}
export function setTables(tableSchemas) {
const tables = tableSchemas
.filter(tableSchema => tableSchema.description !== null)
.map(tableSchema => {
const {
columns,
selectStar,
primaryKey,
foreignKeys,
indexes,
dataPreviewQueryId,
} = tableSchema.description;
return {
dbId: tableSchema.database_id,
queryEditorId: tableSchema.tab_state_id.toString(),
schema: tableSchema.schema,
name: tableSchema.table,
expanded: tableSchema.expanded,
id: tableSchema.id,
dataPreviewQueryId,
columns,
selectStar,
primaryKey,
foreignKeys,
indexes,
isMetadataLoading: false,
isExtraMetadataLoading: false,
};
});
return { type: SET_TABLES, tables };
}
export function switchQueryEditor(queryEditor, displayLimit) {
return function (dispatch) {
if (
isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE) &&
!queryEditor.loaded
) {
SupersetClient.get({
endpoint: encodeURI(`/tabstateview/${queryEditor.id}`),
})
.then(({ json }) => {
const loadedQueryEditor = {
id: json.id.toString(),
loaded: true,
title: json.label,
sql: json.sql,
selectedText: null,
latestQueryId: json.latest_query?.id,
autorun: json.autorun,
dbId: json.database_id,
templateParams: json.template_params,
schema: json.schema,
queryLimit: json.query_limit,
remoteId: json.saved_query?.id,
validationResult: {
id: null,
errors: [],
completed: false,
},
hideLeftBar: json.hide_left_bar,
};
dispatch(loadQueryEditor(loadedQueryEditor));
dispatch(setTables(json.table_schemas || []));
dispatch(setActiveQueryEditor(loadedQueryEditor));
if (json.latest_query && json.latest_query.resultsKey) {
dispatch(fetchQueryResults(json.latest_query, displayLimit));
}
})
.catch(response => {
if (response.status !== 404) {
return dispatch(
addDangerToast(t('An error occurred while fetching tab state')),
);
}
return dispatch({ type: REMOVE_QUERY_EDITOR, queryEditor });
});
} else {
dispatch(setActiveQueryEditor(queryEditor));
}
};
}
export function setActiveSouthPaneTab(tabId) {
return { type: SET_ACTIVE_SOUTHPANE_TAB, tabId };
}
export function toggleLeftBar(queryEditor) {
const hideLeftBar = !queryEditor.hideLeftBar;
return function (dispatch) {
const sync = isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)
? SupersetClient.put({
endpoint: encodeURI(`/tabstateview/${queryEditor.id}`),
postPayload: { hide_left_bar: hideLeftBar },
})
: Promise.resolve();
return sync
.then(() =>
dispatch({
type: QUERY_EDITOR_TOGGLE_LEFT_BAR,
queryEditor,
hideLeftBar,
}),
)
.catch(() =>
dispatch(
addDangerToast(
t(
'An error occurred while hiding the left bar. Please contact your administrator.',
),
),
),
);
};
}
export function removeQueryEditor(queryEditor) {
return function (dispatch) {
const sync = isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)
? SupersetClient.delete({
endpoint: encodeURI(`/tabstateview/${queryEditor.id}`),
})
: Promise.resolve();
return sync
.then(() => dispatch({ type: REMOVE_QUERY_EDITOR, queryEditor }))
.catch(() =>
dispatch(
addDangerToast(
t(
'An error occurred while removing tab. Please contact your administrator.',
),
),
),
);
};
}
export function removeQuery(query) {
return function (dispatch) {
const sync = isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)
? SupersetClient.delete({
endpoint: encodeURI(
`/tabstateview/${query.sqlEditorId}/query/${query.id}`,
),
})
: Promise.resolve();
return sync
.then(() => dispatch({ type: REMOVE_QUERY, query }))
.catch(() =>
dispatch(
addDangerToast(
t(
'An error occurred while removing query. Please contact your administrator.',
),
),
),
);
};
}
export function queryEditorSetDb(queryEditor, dbId) {
return function (dispatch) {
const sync = isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)
? SupersetClient.put({
endpoint: encodeURI(`/tabstateview/${queryEditor.id}`),
postPayload: { database_id: dbId },
})
: Promise.resolve();
return sync
.then(() => dispatch({ type: QUERY_EDITOR_SETDB, queryEditor, dbId }))
.catch(() =>
dispatch(
addDangerToast(
t(
'An error occurred while setting the tab database ID. Please contact your administrator.',
),
),
),
);
};
}
export function queryEditorSetSchema(queryEditor, schema) {
return function (dispatch) {
const sync =
isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE) &&
typeof queryEditor === 'object'
? SupersetClient.put({
endpoint: encodeURI(`/tabstateview/${queryEditor.id}`),
postPayload: { schema },
})
: Promise.resolve();
return sync
.then(() =>
dispatch({
type: QUERY_EDITOR_SET_SCHEMA,
queryEditor: queryEditor || {},
schema: schema || {},
}),
)
.catch(() =>
dispatch(
addDangerToast(
t(
'An error occurred while setting the tab schema. Please contact your administrator.',
),
),
),
);
};
}
export function queryEditorSetSchemaOptions(queryEditor, options) {
return { type: QUERY_EDITOR_SET_SCHEMA_OPTIONS, queryEditor, options };
}
export function queryEditorSetTableOptions(queryEditor, options) {
return { type: QUERY_EDITOR_SET_TABLE_OPTIONS, queryEditor, options };
}
export function queryEditorSetAutorun(queryEditor, autorun) {
return function (dispatch) {
const sync = isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)
? SupersetClient.put({
endpoint: encodeURI(`/tabstateview/${queryEditor.id}`),
postPayload: { autorun },
})
: Promise.resolve();
return sync
.then(() =>
dispatch({ type: QUERY_EDITOR_SET_AUTORUN, queryEditor, autorun }),
)
.catch(() =>
dispatch(
addDangerToast(
t(
'An error occurred while setting the tab autorun. Please contact your administrator.',
),
),
),
);
};
}
export function queryEditorSetTitle(queryEditor, title) {
return function (dispatch) {
const sync = isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)
? SupersetClient.put({
endpoint: encodeURI(`/tabstateview/${queryEditor.id}`),
postPayload: { label: title },
})
: Promise.resolve();
return sync
.then(() =>
dispatch({ type: QUERY_EDITOR_SET_TITLE, queryEditor, title }),
)
.catch(() =>
dispatch(
addDangerToast(
t(
'An error occurred while setting the tab title. Please contact your administrator.',
),
),
),
);
};
}
export function saveQuery(query) {
return dispatch =>
SupersetClient.post({
endpoint: '/savedqueryviewapi/api/create',
postPayload: convertQueryToServer(query),
stringify: false,
})
.then(result => {
const savedQuery = convertQueryToClient(result.json.item);
dispatch({
type: QUERY_EDITOR_SAVED,
query,
result: savedQuery,
});
dispatch(queryEditorSetTitle(query, query.title));
return savedQuery;
})
.catch(() =>
dispatch(addDangerToast(t('Your query could not be saved'))),
);
}
export const addSavedQueryToTabState =
(queryEditor, savedQuery) => dispatch => {
const sync = isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)
? SupersetClient.put({
endpoint: `/tabstateview/${queryEditor.id}`,
postPayload: { saved_query_id: savedQuery.remoteId },
})
: Promise.resolve();
return sync
.catch(() => {
dispatch(addDangerToast(t('Your query was not properly saved')));
})
.then(() => {
dispatch(addSuccessToast(t('Your query was saved')));
});
};
export function updateSavedQuery(query) {
return dispatch =>
SupersetClient.put({
endpoint: `/savedqueryviewapi/api/update/${query.remoteId}`,
postPayload: convertQueryToServer(query),
stringify: false,
})
.then(() => {
dispatch(addSuccessToast(t('Your query was updated')));
dispatch(queryEditorSetTitle(query, query.title));
})
.catch(() =>
dispatch(addDangerToast(t('Your query could not be updated'))),
)
.then(() => dispatch(updateQueryEditor(query)));
}
export function queryEditorSetSql(queryEditor, sql) {
return function (dispatch) {
// saved query and set tab state use this action
dispatch({ type: QUERY_EDITOR_SET_SQL, queryEditor, sql });
if (isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)) {
return SupersetClient.put({
endpoint: encodeURI(`/tabstateview/${queryEditor.id}`),
postPayload: { sql, latest_query_id: queryEditor.latestQueryId },
}).catch(() =>
dispatch(
addDangerToast(
t(
'An error occurred while storing your query in the backend. To ' +
'avoid losing your changes, please save your query using the ' +
'"Save Query" button.',
),
),
),
);
}
return Promise.resolve();
};
}
export function queryEditorSetQueryLimit(queryEditor, queryLimit) {
return function (dispatch) {
const sync = isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)
? SupersetClient.put({
endpoint: encodeURI(`/tabstateview/${queryEditor.id}`),
postPayload: { query_limit: queryLimit },
})
: Promise.resolve();
return sync
.then(() =>
dispatch({
type: QUERY_EDITOR_SET_QUERY_LIMIT,
queryEditor,
queryLimit,
}),
)
.catch(() =>
dispatch(
addDangerToast(
t(
'An error occurred while setting the tab title. Please contact your administrator.',
),
),
),
);
};
}
export function queryEditorSetTemplateParams(queryEditor, templateParams) {
return function (dispatch) {
dispatch({
type: QUERY_EDITOR_SET_TEMPLATE_PARAMS,
queryEditor,
templateParams,
});
const sync = isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)
? SupersetClient.put({
endpoint: encodeURI(`/tabstateview/${queryEditor.id}`),
postPayload: { template_params: templateParams },
})
: Promise.resolve();
return sync.catch(() =>
dispatch(
addDangerToast(
t(
'An error occurred while setting the tab template parameters. ' +
'Please contact your administrator.',
),
),
),
);
};
}
export function queryEditorSetSelectedText(queryEditor, sql) {
return { type: QUERY_EDITOR_SET_SELECTED_TEXT, queryEditor, sql };
}
export function mergeTable(table, query) {
return { type: MERGE_TABLE, table, query };
}
function getTableMetadata(table, query, dispatch) {
return SupersetClient.get({
endpoint: encodeURI(
`/api/v1/database/${query.dbId}/table/${encodeURIComponent(
table.name,
)}/${encodeURIComponent(table.schema)}/`,
),
})
.then(({ json }) => {
const newTable = {
...table,
...json,
expanded: true,
isMetadataLoading: false,
};
dispatch(mergeTable(newTable)); // Merge table to tables in state
return newTable;
})
.catch(() =>
Promise.all([
dispatch(
mergeTable({
...table,
isMetadataLoading: false,
}),
),
dispatch(
addDangerToast(t('An error occurred while fetching table metadata')),
),
]),
);
}
function getTableExtendedMetadata(table, query, dispatch) {
return SupersetClient.get({
endpoint: encodeURI(
`/superset/extra_table_metadata/${query.dbId}/` +
`${encodeURIComponent(table.name)}/${encodeURIComponent(
table.schema,
)}/`,
),
})
.then(({ json }) => {
dispatch(
mergeTable({ ...table, ...json, isExtraMetadataLoading: false }),
);
return json;
})
.catch(() =>
Promise.all([
dispatch(mergeTable({ ...table, isExtraMetadataLoading: false })),
dispatch(
addDangerToast(t('An error occurred while fetching table metadata')),
),
]),
);
}
export function addTable(query, database, tableName, schemaName) {
return function (dispatch) {
const table = {
dbId: query.dbId,
queryEditorId: query.id,
schema: schemaName,
name: tableName,
};
dispatch(
mergeTable({
...table,
isMetadataLoading: true,
isExtraMetadataLoading: true,
expanded: true,
}),
);
return Promise.all([
getTableMetadata(table, query, dispatch),
getTableExtendedMetadata(table, query, dispatch),
]).then(([newTable, json]) => {
const sync = isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)
? SupersetClient.post({
endpoint: encodeURI('/tableschemaview/'),
postPayload: { table: { ...newTable, ...json } },
})
: Promise.resolve({ json: { id: shortid.generate() } });
if (!database.disable_data_preview && database.id === query.dbId) {
const dataPreviewQuery = {
id: shortid.generate(),
dbId: query.dbId,
sql: newTable.selectStar,
tableName: table.name,
sqlEditorId: null,
tab: '',
runAsync: database.allow_run_async,
ctas: false,
isDataPreview: true,
};
Promise.all([
dispatch(
mergeTable(
{
...newTable,
dataPreviewQueryId: dataPreviewQuery.id,
},
dataPreviewQuery,
),
),
dispatch(runQuery(dataPreviewQuery)),
]);
}
return sync
.then(({ json: resultJson }) =>
dispatch(mergeTable({ ...table, id: resultJson.id })),
)
.catch(() =>
dispatch(
addDangerToast(
t(
'An error occurred while fetching table metadata. ' +
'Please contact your administrator.',
),
),
),
);
});
};
}
export function changeDataPreviewId(oldQueryId, newQuery) {
return { type: CHANGE_DATA_PREVIEW_ID, oldQueryId, newQuery };
}
export function reFetchQueryResults(query) {
return function (dispatch) {
const newQuery = {
id: shortid.generate(),
dbId: query.dbId,
sql: query.sql,
tableName: query.tableName,
sqlEditorId: null,
tab: '',
runAsync: false,
ctas: false,
queryLimit: query.queryLimit,
isDataPreview: query.isDataPreview,
};
dispatch(runQuery(newQuery));
dispatch(changeDataPreviewId(query.id, newQuery));
};
}
export function expandTable(table) {
return function (dispatch) {
const sync = isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)
? SupersetClient.post({
endpoint: encodeURI(`/tableschemaview/${table.id}/expanded`),
postPayload: { expanded: true },
})
: Promise.resolve();
return sync
.then(() => dispatch({ type: EXPAND_TABLE, table }))
.catch(() =>
dispatch(
addDangerToast(
t(
'An error occurred while expanding the table schema. ' +
'Please contact your administrator.',
),
),
),
);
};
}
export function collapseTable(table) {
return function (dispatch) {
const sync = isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)
? SupersetClient.post({
endpoint: encodeURI(`/tableschemaview/${table.id}/expanded`),
postPayload: { expanded: false },
})
: Promise.resolve();
return sync
.then(() => dispatch({ type: COLLAPSE_TABLE, table }))
.catch(() =>
dispatch(
addDangerToast(
t(
'An error occurred while collapsing the table schema. ' +
'Please contact your administrator.',
),
),
),
);
};
}
export function removeTable(table) {
return function (dispatch) {
const sync = isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)
? SupersetClient.delete({
endpoint: encodeURI(`/tableschemaview/${table.id}`),
})
: Promise.resolve();
return sync
.then(() => dispatch({ type: REMOVE_TABLE, table }))
.catch(() =>
dispatch(
addDangerToast(
t(
'An error occurred while removing the table schema. ' +
'Please contact your administrator.',
),
),
),
);
};
}
export function refreshQueries(alteredQueries) {
return { type: REFRESH_QUERIES, alteredQueries };
}
export function setUserOffline(offline) {
return { type: SET_USER_OFFLINE, offline };
}
export function persistEditorHeight(queryEditor, northPercent, southPercent) {
return {
type: QUERY_EDITOR_PERSIST_HEIGHT,
queryEditor,
northPercent,
southPercent,
};
}
export function popStoredQuery(urlId) {
return function (dispatch) {
return SupersetClient.get({ endpoint: `/kv/${urlId}` })
.then(({ json }) =>
dispatch(
addQueryEditor({
title: json.title ? json.title : t('Shared query'),
dbId: json.dbId ? parseInt(json.dbId, 10) : null,
schema: json.schema ? json.schema : null,
autorun: json.autorun ? json.autorun : false,
sql: json.sql ? json.sql : 'SELECT ...',
}),
),
)
.catch(() => dispatch(addDangerToast(ERR_MSG_CANT_LOAD_QUERY)));
};
}
export function popSavedQuery(saveQueryId) {
return function (dispatch) {
return SupersetClient.get({
endpoint: `/savedqueryviewapi/api/get/${saveQueryId}`,
})
.then(({ json }) => {
const queryEditorProps = {
...convertQueryToClient(json.result),
autorun: false,
};
return dispatch(addQueryEditor(queryEditorProps));
})
.catch(() => dispatch(addDangerToast(ERR_MSG_CANT_LOAD_QUERY)));
};
}
export function popQuery(queryId) {
return function (dispatch) {
return SupersetClient.get({
endpoint: `/api/v1/query/${queryId}`,
})
.then(({ json }) => {
const queryData = json.result;
const queryEditorProps = {
dbId: queryData.database.id,
schema: queryData.schema,
sql: queryData.sql,
title: `Copy of ${queryData.tab_name}`,
autorun: false,
};
return dispatch(addQueryEditor(queryEditorProps));
})
.catch(() => dispatch(addDangerToast(ERR_MSG_CANT_LOAD_QUERY)));
};
}
export function popDatasourceQuery(datasourceKey, sql) {
return function (dispatch) {
return SupersetClient.get({
endpoint: `/superset/fetch_datasource_metadata?datasourceKey=${datasourceKey}`,
})
.then(({ json }) =>
dispatch(
addQueryEditor({
title: `Query ${json.name}`,
dbId: json.database.id,
schema: json.schema,
autorun: sql !== undefined,
sql: sql || json.select_star,
}),
),
)
.catch(() =>
dispatch(addDangerToast(t("The datasource couldn't be loaded"))),
);
};
}
export function createDatasourceStarted() {
return { type: CREATE_DATASOURCE_STARTED };
}
export function createDatasourceSuccess(data) {
const datasource = `${data.table_id}__table`;
return { type: CREATE_DATASOURCE_SUCCESS, datasource };
}
export function createDatasourceFailed(err) {
return { type: CREATE_DATASOURCE_FAILED, err };
}
export function createDatasource(vizOptions) {
return dispatch => {
dispatch(createDatasourceStarted());
return SupersetClient.post({
endpoint: '/superset/sqllab_viz/',
postPayload: { data: vizOptions },
})
.then(({ json }) => {
dispatch(createDatasourceSuccess(json));
return Promise.resolve(json);
})
.catch(() => {
dispatch(
createDatasourceFailed(
t('An error occurred while creating the data source'),
),
);
return Promise.reject();
});
};
}
export function createCtasDatasource(vizOptions) {
return dispatch => {
dispatch(createDatasourceStarted());
return SupersetClient.post({
endpoint: '/superset/get_or_create_table/',
postPayload: { data: vizOptions },
})
.then(({ json }) => {
dispatch(createDatasourceSuccess(json));
return json;
})
.catch(() => {
const errorMsg = t('An error occurred while creating the data source');
dispatch(createDatasourceFailed(errorMsg));
return Promise.reject(new Error(errorMsg));
});
};
}
export function queryEditorSetFunctionNames(queryEditor, dbId) {
return function (dispatch) {
return SupersetClient.get({
endpoint: encodeURI(`/api/v1/database/${dbId}/function_names/`),
})
.then(({ json }) =>
dispatch({
type: QUERY_EDITOR_SET_FUNCTION_NAMES,
queryEditor,
functionNames: json.function_names,
}),
)
.catch(() =>
dispatch(
addDangerToast(t('An error occurred while fetching function names.')),
),
);
};
}
| superset-frontend/src/SqlLab/actions/sqlLab.js | 1 | https://github.com/apache/superset/commit/4669b6ce11dd74e5d1020a1f124e8696b801d730 | [
0.9992345571517944,
0.07672301679849625,
0.00016644535935483873,
0.004041037987917662,
0.2441481202840805
] |
{
"id": 0,
"code_window": [
"export function queryEditorSetSelectedText(queryEditor, sql) {\n",
" return { type: QUERY_EDITOR_SET_SELECTED_TEXT, queryEditor, sql };\n",
"}\n",
"\n",
"export function mergeTable(table, query) {\n",
" return { type: MERGE_TABLE, table, query };\n",
"}\n",
"\n",
"function getTableMetadata(table, query, dispatch) {\n",
" return SupersetClient.get({\n",
" endpoint: encodeURI(\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export function mergeTable(table, query, prepend) {\n",
" return { type: MERGE_TABLE, table, query, prepend };\n"
],
"file_path": "superset-frontend/src/SqlLab/actions/sqlLab.js",
"type": "replace",
"edit_start_line_idx": 1000
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
import { getColumnLabel } from '@superset-ui/core';
describe('getColumnLabel', () => {
it('should handle physical column', () => {
expect(getColumnLabel('gender')).toEqual('gender');
});
it('should handle adhoc columns with label', () => {
expect(
getColumnLabel({
sqlExpression: "case when 1 then 'a' else 'b' end",
label: 'my col',
}),
).toEqual('my col');
});
it('should handle adhoc columns without label', () => {
expect(
getColumnLabel({
sqlExpression: "case when 1 then 'a' else 'b' end",
}),
).toEqual("case when 1 then 'a' else 'b' end");
});
});
| superset-frontend/packages/superset-ui-core/test/query/getColumnLabel.test.ts | 0 | https://github.com/apache/superset/commit/4669b6ce11dd74e5d1020a1f124e8696b801d730 | [
0.00017755862791091204,
0.00017460472008679062,
0.00017141374701168388,
0.00017546076560392976,
0.000002467644208081765
] |
{
"id": 0,
"code_window": [
"export function queryEditorSetSelectedText(queryEditor, sql) {\n",
" return { type: QUERY_EDITOR_SET_SELECTED_TEXT, queryEditor, sql };\n",
"}\n",
"\n",
"export function mergeTable(table, query) {\n",
" return { type: MERGE_TABLE, table, query };\n",
"}\n",
"\n",
"function getTableMetadata(table, query, dispatch) {\n",
" return SupersetClient.get({\n",
" endpoint: encodeURI(\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export function mergeTable(table, query, prepend) {\n",
" return { type: MERGE_TABLE, table, query, prepend };\n"
],
"file_path": "superset-frontend/src/SqlLab/actions/sqlLab.js",
"type": "replace",
"edit_start_line_idx": 1000
} | {
"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features": [
{ "type": "Feature", "properties": { "ISO": "JO-IR", "NAME_1": "Irbid" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 35.57439660600005, 32.554396464000021 ], [ 35.575843546000044, 32.554964905000091 ], [ 35.5799776610001, 32.560390930000054 ], [ 35.57439660600005, 32.572767436000035 ], [ 35.571296021000137, 32.59855397500003 ], [ 35.565611613000101, 32.607545675000082 ], [ 35.565611613000101, 32.615012920000098 ], [ 35.572536255000045, 32.615012920000098 ], [ 35.572536255000045, 32.621239930000101 ], [ 35.564061320000064, 32.62547739700004 ], [ 35.560030558000051, 32.632686260000085 ], [ 35.560547323000094, 32.64090281200005 ], [ 35.562717733000113, 32.644210104000038 ], [ 35.56984908000004, 32.646768087000041 ], [ 35.578737427000135, 32.653434347000044 ], [ 35.593826945000046, 32.670358378000046 ], [ 35.612250289302779, 32.681588176566216 ], [ 35.612333850000084, 32.681535197000031 ], [ 35.635994913000104, 32.679143372000041 ], [ 35.652014608000059, 32.686171366000039 ], [ 35.685190877000082, 32.711234437000044 ], [ 35.740174601000035, 32.740534973000095 ], [ 35.757434530000069, 32.744281514000122 ], [ 35.757590349000111, 32.7443468580001 ], [ 35.763842407000141, 32.74696869000006 ], [ 35.769733520000045, 32.748053894000051 ], [ 35.774901164000141, 32.747278748000028 ], [ 35.77913863100008, 32.744462383000084 ], [ 35.779035278000094, 32.744359030000041 ], [ 35.779035278000094, 32.744281514000122 ], [ 35.78823368400009, 32.734411317000038 ], [ 35.895720663000077, 32.713275656000107 ], [ 35.905229126000052, 32.708573100000123 ], [ 35.922489054000039, 32.693767802000096 ], [ 35.927449992000106, 32.692372539000118 ], [ 35.940369100000112, 32.692501729000057 ], [ 35.94419315600004, 32.690770569000094 ], [ 35.945743449000076, 32.68410431000008 ], [ 35.944399862000068, 32.677618917000117 ], [ 35.941195922000134, 32.673536479000106 ], [ 35.937475219000135, 32.674001567000019 ], [ 35.946570272000088, 32.664441427000028 ], [ 35.955355265000094, 32.65743927100003 ], [ 35.965793905000112, 32.654364523000098 ], [ 35.98026330600004, 32.656612448000104 ], [ 36.003621053000074, 32.655087992000077 ], [ 36.008271932000071, 32.643719178000097 ], [ 36.00527469900004, 32.626691793000063 ], [ 36.005998169000122, 32.607907410000067 ], [ 36.0154032800001, 32.591164246000019 ], [ 36.060465128000146, 32.53326080300009 ], [ 36.06604618300014, 32.521607768000123 ], [ 36.066252889000111, 32.517318624000055 ], [ 36.069870239000068, 32.516595154000058 ], [ 36.081905548602151, 32.516264773300634 ], [ 36.09421064570472, 32.434247952580904 ], [ 36.087234327602118, 32.408254706289654 ], [ 36.080102979868627, 32.406161811218567 ], [ 36.071369662579855, 32.407712103930407 ], [ 36.053076205702325, 32.419881904326417 ], [ 36.041759067826717, 32.423215032847452 ], [ 36.029356724333354, 32.421432197038257 ], [ 36.015042352022931, 32.411432806978439 ], [ 36.011631708236735, 32.403293768892297 ], [ 36.01287194168674, 32.395128893283754 ], [ 36.018142938345932, 32.387093207085798 ], [ 36.023258905374178, 32.377145493869421 ], [ 36.026359490797859, 32.362314358520791 ], [ 36.025015902761709, 32.354640408428111 ], [ 36.017212762359065, 32.345958767083403 ], [ 35.984036493289523, 32.347147325488663 ], [ 35.952978956813411, 32.354743761215559 ], [ 35.939646437333181, 32.3513331165301 ], [ 35.905333285802499, 32.338879096193295 ], [ 35.883784213870342, 32.364639796689232 ], [ 35.864095493012599, 32.378179023543055 ], [ 35.859134555615242, 32.386369737573318 ], [ 35.854793735842236, 32.399443875534416 ], [ 35.848075799258709, 32.402001857699531 ], [ 35.840944452424537, 32.398074449076546 ], [ 35.83381310379167, 32.389599514206168 ], [ 35.821875848291768, 32.383656724877937 ], [ 35.805597772119484, 32.381589667329251 ], [ 35.776555617247936, 32.382984931309522 ], [ 35.760122512344026, 32.380246080192421 ], [ 35.729685092592945, 32.366035061568823 ], [ 35.705655551962138, 32.360221463449761 ], [ 35.680489128870192, 32.361668403374097 ], [ 35.663125847979472, 32.360531520912957 ], [ 35.648863153411753, 32.35536387794059 ], [ 35.639096307348666, 32.344847723943303 ], [ 35.63206831240268, 32.329344794126939 ], [ 35.616720412217205, 32.266764634979893 ], [ 35.618425733660672, 32.25152008758198 ], [ 35.624471876675727, 32.235319525775481 ], [ 35.638321160992746, 32.208318590030899 ], [ 35.640801628792133, 32.199662787107911 ], [ 35.640026483335532, 32.193797512145466 ], [ 35.635530633032261, 32.183823961406688 ], [ 35.565974154883293, 32.190929469819139 ], [ 35.55956241677211, 32.190370872118024 ], [ 35.572536255000045, 32.237594096000052 ], [ 35.559410441000068, 32.237594096000052 ], [ 35.561064087000034, 32.243149312000057 ], [ 35.56375126100005, 32.246818339000058 ], [ 35.567575318000081, 32.249505514000091 ], [ 35.572536255000045, 32.251908468000053 ], [ 35.564578084000118, 32.263587342 ], [ 35.560857381000062, 32.282630107000088 ], [ 35.561167440000077, 32.301698711000071 ], [ 35.565611613000101, 32.313351745000048 ], [ 35.556516560000034, 32.328208720000063 ], [ 35.557343384000035, 32.35820688900013 ], [ 35.55196903500007, 32.367947896000075 ], [ 35.55196903500007, 32.37482086200005 ], [ 35.559410441000068, 32.37482086200005 ], [ 35.559410441000068, 32.367947896000075 ], [ 35.565611613000101, 32.367947896000075 ], [ 35.563957967000135, 32.377042949000057 ], [ 35.560960734000105, 32.384716899000026 ], [ 35.556826620000095, 32.39091807100003 ], [ 35.55196903500007, 32.395284730000085 ], [ 35.549591919000136, 32.398540345000086 ], [ 35.545147746000112, 32.40957326300007 ], [ 35.554862915000058, 32.411175232000019 ], [ 35.5591003830001, 32.413965759000078 ], [ 35.558170207000046, 32.417996522000081 ], [ 35.55196903500007, 32.4232416790001 ], [ 35.55196903500007, 32.429442851000076 ], [ 35.559410441000068, 32.429442851000076 ], [ 35.557860149000078, 32.434119568000042 ], [ 35.556206502000123, 32.434791362000041 ], [ 35.554139445000146, 32.434455465000056 ], [ 35.55196903500007, 32.436212464000036 ], [ 35.565611613000101, 32.443705546000061 ], [ 35.559410441000068, 32.450526835000105 ], [ 35.56623173000014, 32.453110657000096 ], [ 35.572536255000045, 32.456728007 ], [ 35.572536255000045, 32.464195252000124 ], [ 35.568092082000135, 32.464970398000034 ], [ 35.565404907000129, 32.466313985000099 ], [ 35.563131144000124, 32.468174337 ], [ 35.559410441000068, 32.470396423000111 ], [ 35.561270792000073, 32.47708852200013 ], [ 35.564991495000129, 32.483909811000089 ], [ 35.570985962000123, 32.489206645000124 ], [ 35.5799776610001, 32.491480408000129 ], [ 35.5799776610001, 32.497733256000046 ], [ 35.570572550000122, 32.506027324000073 ], [ 35.568505493000146, 32.51026479100004 ], [ 35.561374145000116, 32.519178976000049 ], [ 35.557240031000106, 32.51933400500009 ], [ 35.55196903500007, 32.518817241000065 ], [ 35.55196903500007, 32.525586853 ], [ 35.565611613000101, 32.525586853 ], [ 35.562821086000042, 32.532020569000039 ], [ 35.559410441000068, 32.552949524000027 ], [ 35.565611613000101, 32.54610239700007 ], [ 35.570159139000111, 32.556825257000085 ], [ 35.572536255000045, 32.560390930000054 ], [ 35.57387984200011, 32.55674774200007 ], [ 35.57439660600005, 32.554396464000021 ] ] ] } },
{ "type": "Feature", "properties": { "ISO": "JO-MD", "NAME_1": "Madaba" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 35.457127555592194, 31.433524394235405 ], [ 35.458538045000068, 31.491618958000075 ], [ 35.458124634000058, 31.491929016000043 ], [ 35.45874475100004, 31.491567281000059 ], [ 35.459158163000041, 31.49187734000013 ], [ 35.459054810000112, 31.492807516000099 ], [ 35.45874475100004, 31.49440948500002 ], [ 35.464222453000048, 31.568565165000066 ], [ 35.48013879400014, 31.641118876000078 ], [ 35.502478566832394, 31.68536038937043 ], [ 35.514762811354615, 31.684087022198298 ], [ 35.583544142248343, 31.680805568722008 ], [ 35.597496779352866, 31.686464138109443 ], [ 35.610054151577799, 31.696851100897561 ], [ 35.626487258280349, 31.722301743930302 ], [ 35.638166131361857, 31.749225165309099 ], [ 35.644212274376912, 31.755968940314347 ], [ 35.656304558608497, 31.762841904730124 ], [ 35.668706903001123, 31.766071682262293 ], [ 35.695423617905647, 31.768112901389259 ], [ 35.708291050291734, 31.774649969920176 ], [ 35.745859815977724, 31.782969876058928 ], [ 35.796399366837306, 31.783124904790498 ], [ 35.811798943866165, 31.786406358266788 ], [ 35.824356316990418, 31.790824693304955 ], [ 35.831022576730504, 31.78992035573981 ], [ 35.838153923564676, 31.784184271986533 ], [ 35.840479364431076, 31.711759752410615 ], [ 35.838308954094941, 31.702406318396868 ], [ 35.832417839811455, 31.69318207469297 ], [ 35.815209587652305, 31.675560411383856 ], [ 35.810248651154325, 31.667912298813519 ], [ 35.808853387174054, 31.659230658368188 ], [ 35.810403679885894, 31.649541327570205 ], [ 35.818155145243736, 31.623780626174948 ], [ 35.825596551339743, 31.608070990783574 ], [ 35.869056431309218, 31.567995917077894 ], [ 35.875102573425011, 31.555335191166137 ], [ 35.87432742706909, 31.545826728420764 ], [ 35.870916782383574, 31.538592027000448 ], [ 35.871846958370384, 31.530659695388636 ], [ 35.877738070855287, 31.524458522742634 ], [ 35.885644565844018, 31.517895615789996 ], [ 35.887504916918374, 31.511746120886755 ], [ 35.884404330595373, 31.505415757930848 ], [ 35.870606724021059, 31.488259181715819 ], [ 35.863940464280972, 31.477381293411952 ], [ 35.846835564909384, 31.432138576733905 ], [ 35.842494745136378, 31.425627345725388 ], [ 35.834898309409425, 31.418831894776076 ], [ 35.82885216639437, 31.414801134264906 ], [ 35.818000115612847, 31.405938625766964 ], [ 35.773300002193309, 31.414749457421522 ], [ 35.752216017355295, 31.415111191728101 ], [ 35.718057896354821, 31.412268988722815 ], [ 35.687155388610279, 31.403819892274214 ], [ 35.673357782035964, 31.403923245061662 ], [ 35.654444208433461, 31.407153021694569 ], [ 35.55419192901428, 31.435859279781937 ], [ 35.478485955962071, 31.438468939689812 ], [ 35.457127555592194, 31.433524394235405 ] ] ] } },
{ "type": "Feature", "properties": { "ISO": "JO-KA", "NAME_1": "Karak" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 35.347110283612665, 30.922709634841738 ], [ 35.374098755000034, 30.945140686000073 ], [ 35.385260864000088, 30.963279114000031 ], [ 35.385157511000045, 30.994646708000047 ], [ 35.391565389000107, 31.023947246 ], [ 35.438487590000136, 31.103735657000087 ], [ 35.443241821000129, 31.13220937100003 ], [ 35.436213827000131, 31.159546204000051 ], [ 35.421331014000089, 31.184505921000024 ], [ 35.410685669000088, 31.204608053000086 ], [ 35.401177206000114, 31.230291239000067 ], [ 35.395699504000106, 31.257679749000104 ], [ 35.408205200000111, 31.282019349 ], [ 35.422261190000143, 31.302999980000024 ], [ 35.423914835000062, 31.324600728000078 ], [ 35.416473429000064, 31.331835429000066 ], [ 35.435076945000105, 31.36061920200008 ], [ 35.452853637000146, 31.400823466000091 ], [ 35.456884400000035, 31.423509420000059 ], [ 35.457127555592194, 31.433524394235405 ], [ 35.478485955962071, 31.438468939689812 ], [ 35.55419192901428, 31.435859279781937 ], [ 35.654444208433461, 31.407153021694569 ], [ 35.673357782035964, 31.403923245061662 ], [ 35.687155388610279, 31.403819892274214 ], [ 35.718057896354821, 31.412268988722815 ], [ 35.752216017355295, 31.415111191728101 ], [ 35.773300002193309, 31.414749457421522 ], [ 35.818000115612847, 31.405938625766964 ], [ 35.842339714606112, 31.3692483592244 ], [ 35.849161003977144, 31.350205593513294 ], [ 35.85179650230674, 31.337053941186412 ], [ 35.849936151232384, 31.328062242378564 ], [ 35.841874626612707, 31.308166815945754 ], [ 35.838153923564676, 31.294007473266277 ], [ 35.835673455765345, 31.274551297304527 ], [ 35.839239129182431, 31.262536526539463 ], [ 35.849161003977144, 31.254940089913191 ], [ 36.151778192409608, 31.248635566278324 ], [ 36.168521355675978, 31.15050202125127 ], [ 36.19193077958181, 31.094794827419321 ], [ 36.140926140728766, 30.955061754396411 ], [ 36.023775669311647, 30.767062892738295 ], [ 35.980935906966522, 30.804166572229519 ], [ 35.938561231715425, 30.831270859862286 ], [ 35.930654737626014, 30.838893134010902 ], [ 35.920267774837896, 30.853956814255525 ], [ 35.91246463443531, 30.861269029142363 ], [ 35.902077670747872, 30.866643377689684 ], [ 35.865800816254648, 30.881086941209333 ], [ 35.853243443130395, 30.888838406567174 ], [ 35.843890008217272, 30.896589871025697 ], [ 35.839704217175836, 30.903695380337524 ], [ 35.83691369011467, 30.909793199296701 ], [ 35.830247430374584, 30.914857490380882 ], [ 35.669947137350505, 30.969918728166761 ], [ 35.584629346966778, 30.97353607842723 ], [ 35.570314975555675, 30.978367825514738 ], [ 35.556362339350471, 30.986222642760708 ], [ 35.545200230206433, 30.994775091996871 ], [ 35.533883091431505, 30.997694811166582 ], [ 35.521170688676307, 30.998418281578438 ], [ 35.503445671680367, 30.996222031921207 ], [ 35.490733269824545, 30.996687119914611 ], [ 35.481276483023237, 30.994077460006736 ], [ 35.475075311276555, 30.986248481182429 ], [ 35.470734490604229, 30.965913805177934 ], [ 35.460605910234563, 30.939998074151788 ], [ 35.454249708856935, 30.899354560564518 ], [ 35.447738477848475, 30.889432684870485 ], [ 35.436576368704436, 30.883593248329703 ], [ 35.418747999820312, 30.884678453048139 ], [ 35.404795362715788, 30.887959907423749 ], [ 35.354824252637115, 30.918164781379517 ], [ 35.347110283612665, 30.922709634841738 ] ] ] } },
{ "type": "Feature", "properties": { "ISO": "JO-AT", "NAME_1": "Tafilah" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 35.263881904000129, 30.719966986000102 ], [ 35.271572713000069, 30.74370595300006 ], [ 35.276120239000136, 30.768975728000029 ], [ 35.279530884000053, 30.780241191000087 ], [ 35.28614546700004, 30.792333476000053 ], [ 35.293896932000052, 30.80018829300009 ], [ 35.310846802000071, 30.813314107000068 ], [ 35.316634562000047, 30.82282257100006 ], [ 35.320045206000145, 30.844940084000072 ], [ 35.319528442000035, 30.867315979000054 ], [ 35.32221561700004, 30.889950256000091 ], [ 35.33492802000012, 30.912584534000032 ], [ 35.347110283612665, 30.922709634841738 ], [ 35.354824252637115, 30.918164781379517 ], [ 35.404795362715788, 30.887959907423749 ], [ 35.418747999820312, 30.884678453048139 ], [ 35.436576368704436, 30.883593248329703 ], [ 35.447738477848475, 30.889432684870485 ], [ 35.454249708856935, 30.899354560564518 ], [ 35.460605910234563, 30.939998074151788 ], [ 35.470734490604229, 30.965913805177934 ], [ 35.475075311276555, 30.986248481182429 ], [ 35.481276483023237, 30.994077460006736 ], [ 35.490733269824545, 30.996687119914611 ], [ 35.503445671680367, 30.996222031921207 ], [ 35.521170688676307, 30.998418281578438 ], [ 35.533883091431505, 30.997694811166582 ], [ 35.545200230206433, 30.994775091996871 ], [ 35.556362339350471, 30.986222642760708 ], [ 35.570314975555675, 30.978367825514738 ], [ 35.584629346966778, 30.97353607842723 ], [ 35.669947137350505, 30.969918728166761 ], [ 35.830247430374584, 30.914857490380882 ], [ 35.83691369011467, 30.909793199296701 ], [ 35.839704217175836, 30.903695380337524 ], [ 35.843890008217272, 30.896589871025697 ], [ 35.853243443130395, 30.888838406567174 ], [ 35.865800816254648, 30.881086941209333 ], [ 35.902077670747872, 30.866643377689684 ], [ 35.91246463443531, 30.861269029142363 ], [ 35.920267774837896, 30.853956814255525 ], [ 35.930654737626014, 30.838893134010902 ], [ 35.938561231715425, 30.831270859862286 ], [ 35.980935906966522, 30.804166572229519 ], [ 36.023775669311647, 30.767062892738295 ], [ 35.947707961053538, 30.656423652329693 ], [ 35.911224400085985, 30.644744778348809 ], [ 35.884404330595373, 30.653788154000097 ], [ 35.873862339075686, 30.654537461934297 ], [ 35.863165317925052, 30.652547918751452 ], [ 35.850711296688985, 30.645054836711324 ], [ 35.840789421894272, 30.636657416206788 ], [ 35.826681756058179, 30.628931790169986 ], [ 35.75578169077238, 30.614229845131206 ], [ 35.662350701623552, 30.603351955928019 ], [ 35.628347609354648, 30.605987454257615 ], [ 35.528922153134829, 30.603274441562235 ], [ 35.488097772394269, 30.608571274844451 ], [ 35.448048537110253, 30.608493761377986 ], [ 35.425259229929509, 30.609346422099691 ], [ 35.413942092053901, 30.612912096416096 ], [ 35.399782749374367, 30.618984076054232 ], [ 35.387535434612573, 30.632755846005466 ], [ 35.375598179112671, 30.650687568576416 ], [ 35.362575717994957, 30.660841987367803 ], [ 35.347176140966099, 30.667844142992806 ], [ 35.278911574009896, 30.71008962703462 ], [ 35.263881904000129, 30.719966986000102 ] ] ] } },
{ "type": "Feature", "properties": { "ISO": "JO-AQ", "NAME_1": "Aqaba" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 34.955577019000089, 29.558986721000053 ], [ 34.959860474000095, 29.586205547000063 ], [ 34.966991822000125, 29.608116354000103 ], [ 34.980324341000141, 29.627004090000028 ], [ 34.989832804000059, 29.651963807000115 ], [ 34.995103801000084, 29.708161927000091 ], [ 35.002545207000082, 29.733095805000076 ], [ 35.048950642000079, 29.842313945000043 ], [ 35.053188110000065, 29.862622782000059 ], [ 35.054118286000119, 29.923394267000063 ], [ 35.06145634000012, 29.957345683000099 ], [ 35.065383748000045, 29.965975647000036 ], [ 35.070344686000112, 29.973727112000049 ], [ 35.074065389000111, 29.982563782000042 ], [ 35.074685506000094, 29.99460439100001 ], [ 35.086261027000035, 30.034033509000025 ], [ 35.129049113000065, 30.089740702000071 ], [ 35.145275512000069, 30.123382060000026 ], [ 35.145275512000069, 30.154904684000073 ], [ 35.124811645000079, 30.216089579000098 ], [ 35.125225057000137, 30.244666647000074 ], [ 35.132356405000053, 30.26187489800013 ], [ 35.141761515000042, 30.313964743 ], [ 35.147755981000046, 30.32647043900009 ], [ 35.154473918000065, 30.336754049 ], [ 35.159951620000072, 30.347502747000092 ], [ 35.162122029000045, 30.361403707000065 ], [ 35.1593315020001, 30.375614726000052 ], [ 35.144965454000101, 30.395871887000041 ], [ 35.140004517000136, 30.406155497000029 ], [ 35.140004517000136, 30.430185038000062 ], [ 35.157367797000063, 30.470854391000032 ], [ 35.162122029000045, 30.494677226000093 ], [ 35.205323527000076, 30.617098694000063 ], [ 35.263821249000102, 30.719779765000041 ], [ 35.263881904000129, 30.719966986000102 ], [ 35.278911574009896, 30.71008962703462 ], [ 35.347176140966099, 30.667844142992806 ], [ 35.362575717994957, 30.660841987367803 ], [ 35.375598179112671, 30.650687568576416 ], [ 35.387535434612573, 30.632755846005466 ], [ 35.399782749374367, 30.618984076054232 ], [ 35.413942092053901, 30.612912096416096 ], [ 35.425259229929509, 30.609346422099691 ], [ 35.448048537110253, 30.608493761377986 ], [ 35.442312453357033, 30.546016954119125 ], [ 35.421848586143312, 30.466822822015615 ], [ 35.377458530186971, 30.344969793820894 ], [ 35.379473910892273, 30.232392686173512 ], [ 35.371412388071235, 30.203247179413779 ], [ 35.3129146662788, 30.103098252782104 ], [ 35.301442498772303, 30.053385525121882 ], [ 35.299117058805223, 30.027056382945716 ], [ 35.303767937840064, 30.008323676496445 ], [ 35.309038933599879, 29.998530992011638 ], [ 35.316790398957721, 29.986981310139356 ], [ 35.325937127396514, 29.976594347351238 ], [ 35.338184442158251, 29.966724148500646 ], [ 35.351878695945061, 29.959747830398044 ], [ 35.368311801748234, 29.955019436098098 ], [ 35.384279818658683, 29.954425156895468 ], [ 35.399162631750016, 29.956052964872413 ], [ 35.412081740080225, 29.960135403126344 ], [ 35.424949171566993, 29.962435003772384 ], [ 35.450684035439849, 29.963080959818399 ], [ 35.480501335767997, 29.957990831211873 ], [ 35.499104851907362, 29.951944688196761 ], [ 35.518690219977657, 29.942487901395509 ], [ 35.538068881573622, 29.927734280412665 ], [ 35.556052280088636, 29.910991116246976 ], [ 35.570935093179969, 29.890888984239211 ], [ 35.623541700688918, 29.78735525224306 ], [ 35.688395623858923, 29.557188421808178 ], [ 35.737901645944191, 29.240592760547429 ], [ 35.740175409067831, 29.232014471990283 ], [ 35.740250622000076, 29.231730714000022 ], [ 35.622042277000105, 29.249688619000025 ], [ 35.473627564000083, 29.272064515000082 ], [ 35.334617960000116, 29.293148499000026 ], [ 35.179071899000064, 29.316661275000016 ], [ 35.060319458000095, 29.334696350000016 ], [ 34.949385116795497, 29.351685826515777 ], [ 34.962412957000083, 29.359767971000053 ], [ 34.969004754000082, 29.450832424000055 ], [ 34.976084832000083, 29.477036851000037 ], [ 34.99781334700009, 29.517971096000053 ], [ 34.996836785000085, 29.533880927000041 ], [ 34.976084832000083, 29.552150783000059 ], [ 34.962412957000083, 29.552150783000059 ], [ 34.961599155000044, 29.55540599200009 ], [ 34.961599155000044, 29.558091539000088 ], [ 34.960215691000087, 29.559515692000048 ], [ 34.955577019000089, 29.558986721000053 ] ] ] } },
{ "type": "Feature", "properties": { "ISO": "JO-BA", "NAME_1": "Balqa" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 35.502478566832394, 31.68536038937043 ], [ 35.527577758000064, 31.73506663000002 ], [ 35.559410441000068, 31.765349019000055 ], [ 35.53832645600005, 31.8192992150001 ], [ 35.53832645600005, 31.826740621000013 ], [ 35.549075154000093, 31.839194641000105 ], [ 35.524683879000065, 31.919241435000046 ], [ 35.527474406000124, 31.927354635000071 ], [ 35.53367557700011, 31.930300192000047 ], [ 35.540600220000101, 31.932005514000124 ], [ 35.545147746000112, 31.936604716000076 ], [ 35.545871216000137, 31.944562887000032 ], [ 35.539980103000119, 31.955621643000043 ], [ 35.53832645600005, 31.963941549000097 ], [ 35.537706340000113, 31.977584127000014 ], [ 35.535535929000105, 31.988229473 ], [ 35.524683879000065, 32.011690572000063 ], [ 35.522823527000071, 32.057837627000097 ], [ 35.528301229000135, 32.075097555000085 ], [ 35.545147746000112, 32.086828105000095 ], [ 35.534605753000051, 32.099230449000046 ], [ 35.535225871000137, 32.110805969000111 ], [ 35.55196903500007, 32.135197245000128 ], [ 35.546698038000045, 32.141605123000076 ], [ 35.546698038000045, 32.147031149000057 ], [ 35.551245565000102, 32.15152699800008 ], [ 35.559410441000068, 32.155092672000038 ], [ 35.559410441000068, 32.162534079000054 ], [ 35.55517297300014, 32.17439382 ], [ 35.55956241677211, 32.190370872118024 ], [ 35.565974154883293, 32.190929469819139 ], [ 35.635530633032261, 32.183823961406688 ], [ 35.651808709204545, 32.166564033303473 ], [ 35.668706903001123, 32.160698757441708 ], [ 35.694803501180616, 32.156177070515355 ], [ 35.696198765160887, 32.147831325954883 ], [ 35.706430698318059, 32.144601549322033 ], [ 35.719763217798231, 32.143516343704277 ], [ 35.806682976837862, 32.145376694778633 ], [ 35.826371697695663, 32.142198594989168 ], [ 35.840324333900867, 32.137108466382585 ], [ 35.851641472675794, 32.127393297162939 ], [ 35.859134555615242, 32.118970038236682 ], [ 35.89587649900119, 32.095663967118355 ], [ 35.901612582754467, 32.069851588879715 ], [ 35.906728549782713, 32.064683945907348 ], [ 35.914841750346454, 32.058224391742272 ], [ 35.921663038818167, 32.0556922470995 ], [ 35.941196730045021, 32.045847887569948 ], [ 35.911741164023454, 32.037631334218702 ], [ 35.880528598815772, 32.01158641198333 ], [ 35.864870640267839, 32.004093329043883 ], [ 35.826836785689068, 31.99419729357021 ], [ 35.811953972597735, 31.983706977095324 ], [ 35.766943800815739, 31.938335069208051 ], [ 35.741932407354682, 31.922832140291007 ], [ 35.683744744824082, 31.897433173202387 ], [ 35.668706903001123, 31.885935167274113 ], [ 35.661730583999258, 31.874928086861701 ], [ 35.663900995234712, 31.865729682478843 ], [ 35.670877313337314, 31.858779201898642 ], [ 35.681574333588628, 31.854128322863801 ], [ 35.694803501180616, 31.850795193443389 ], [ 35.717747837092986, 31.84756541591122 ], [ 35.723483920846263, 31.842191067363842 ], [ 35.725189243188993, 31.833716132493521 ], [ 35.712476841333114, 31.803072008066692 ], [ 35.710151402265353, 31.792530016547005 ], [ 35.708291050291734, 31.774649969920176 ], [ 35.695423617905647, 31.768112901389259 ], [ 35.668706903001123, 31.766071682262293 ], [ 35.656304558608497, 31.762841904730124 ], [ 35.644212274376912, 31.755968940314347 ], [ 35.638166131361857, 31.749225165309099 ], [ 35.626487258280349, 31.722301743930302 ], [ 35.610054151577799, 31.696851100897561 ], [ 35.597496779352866, 31.686464138109443 ], [ 35.583544142248343, 31.680805568722008 ], [ 35.514762811354615, 31.684087022198298 ], [ 35.502478566832394, 31.68536038937043 ] ] ] } },
{ "type": "Feature", "properties": { "ISO": "JO-MA", "NAME_1": "Mafraq" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 36.80656945800007, 32.313041687000052 ], [ 36.819385213000146, 32.316788229000068 ], [ 36.980098918000124, 32.410038351000097 ], [ 37.133164510000086, 32.494529318000062 ], [ 37.133371216000057, 32.494580994000088 ], [ 37.244062134000046, 32.554396464000021 ], [ 37.415214478000053, 32.647129822000025 ], [ 37.49460567371284, 32.690055622768739 ], [ 37.586676880000084, 32.73983734200003 ], [ 37.758035929000073, 32.832519023000103 ], [ 37.929394979000051, 32.925329896 ], [ 38.056725708000045, 32.994343770000071 ], [ 38.230875285000138, 33.086301982000052 ], [ 38.31574206300013, 33.131180063000087 ], [ 38.529565063000121, 33.244250997000066 ], [ 38.774511352000047, 33.371685079000102 ], [ 38.821020142000066, 33.229032288000028 ], [ 38.862567993000084, 33.100719706000078 ], [ 38.897191203000091, 32.994343770000071 ], [ 38.942769816000066, 32.852336934000093 ], [ 38.99000207500012, 32.705575867 ], [ 39.057181438000043, 32.496596374000021 ], [ 38.979976848000092, 32.476054993000034 ], [ 38.978633260000038, 32.475693258000049 ], [ 38.978219849000084, 32.474969788000053 ], [ 38.978633260000038, 32.47372955400003 ], [ 38.979976848000092, 32.472101746000064 ], [ 39.028759399000137, 32.328337911000105 ], [ 39.036200806000068, 32.313351745000048 ], [ 39.046329387000128, 32.308494161000013 ], [ 39.235775187000058, 32.352858378000079 ], [ 39.256342407000091, 32.342678121000105 ], [ 39.27112186700009, 32.31195648200007 ], [ 39.291999145000091, 32.244518738000025 ], [ 39.266470988000037, 32.21286692300005 ], [ 39.146168253000042, 32.125843811 ], [ 39.146374960000117, 32.118144023000085 ], [ 39.136246378000067, 32.115353496000054 ], [ 39.11681604000006, 32.102899475000058 ], [ 38.998063599000091, 32.00693634100007 ], [ 38.963440389000084, 31.994482320000103 ], [ 38.963440389000084, 31.994327291000062 ], [ 38.963337036000041, 31.99437896700006 ], [ 38.849752238000121, 31.966318664000042 ], [ 38.624856405000116, 31.910869853000079 ], [ 38.400167277000037, 31.855369365000101 ], [ 38.175374796000085, 31.799920552000046 ], [ 37.98652246000006, 31.753358384000123 ], [ 37.95047896300008, 31.744471741000055 ], [ 37.76141217300011, 31.696120493000095 ], [ 37.7608272638671, 31.696308499437691 ], [ 37.759380323942764, 31.696773587431096 ], [ 36.51795739102073, 32.063417874035622 ], [ 36.482765741245942, 32.080806993348062 ], [ 36.450933058413909, 32.106283473903204 ], [ 36.4334147478923, 32.11411245452615 ], [ 36.37941287640308, 32.119073391024131 ], [ 36.360912713051221, 32.117497259890627 ], [ 36.348045281564453, 32.11253632339259 ], [ 36.337503290044765, 32.105663357178173 ], [ 36.324635857658677, 32.100650742937432 ], [ 36.309598015835718, 32.100314846153196 ], [ 36.294198438806859, 32.104190578832117 ], [ 36.27668012918457, 32.11504263051296 ], [ 36.236320834638775, 32.131966660932619 ], [ 36.195858189104115, 32.135299791252351 ], [ 36.183404167868048, 32.13390452727208 ], [ 36.173017205979249, 32.13181163220105 ], [ 36.15224328040307, 32.124602769202397 ], [ 36.138393996086052, 32.123620917271467 ], [ 36.123046095900577, 32.127160753166208 ], [ 36.098706496007935, 32.142896226979246 ], [ 36.086149122883683, 32.149510809875949 ], [ 36.076175571245585, 32.150621853016105 ], [ 36.062532993402897, 32.139098009565487 ], [ 36.052456088977294, 32.134369615265484 ], [ 36.040673862208962, 32.13222504335107 ], [ 36.029976841058328, 32.133827012906295 ], [ 36.019693231057772, 32.139950670287192 ], [ 36.014732292761096, 32.146849474024009 ], [ 36.013957147304495, 32.156332099246981 ], [ 36.01690270399655, 32.163540961346257 ], [ 36.021398553400502, 32.169664617827834 ], [ 36.022948846112342, 32.17615001131395 ], [ 36.019383171795937, 32.183048814151448 ], [ 36.010856560981495, 32.190851956352674 ], [ 35.990702752130289, 32.196665554471736 ], [ 35.980315790241491, 32.217103583263736 ], [ 35.967138298593568, 32.235810452190606 ], [ 35.960265334177791, 32.241133123894542 ], [ 35.952048780826544, 32.245784002929383 ], [ 35.947242873060134, 32.252605292300359 ], [ 35.948018019416054, 32.262475491150951 ], [ 35.957629835848252, 32.278055935333157 ], [ 36.003105095623653, 32.321593328769097 ], [ 36.017212762359065, 32.345958767083403 ], [ 36.025015902761709, 32.354640408428111 ], [ 36.026359490797859, 32.362314358520791 ], [ 36.023258905374178, 32.377145493869421 ], [ 36.018142938345932, 32.387093207085798 ], [ 36.01287194168674, 32.395128893283754 ], [ 36.011631708236735, 32.403293768892297 ], [ 36.015042352022931, 32.411432806978439 ], [ 36.029356724333354, 32.421432197038257 ], [ 36.041759067826717, 32.423215032847452 ], [ 36.053076205702325, 32.419881904326417 ], [ 36.071369662579855, 32.407712103930407 ], [ 36.080102979868627, 32.406161811218567 ], [ 36.087234327602118, 32.408254706289654 ], [ 36.09421064570472, 32.434247952580904 ], [ 36.081905548602151, 32.516264773300634 ], [ 36.096225220000065, 32.515871684000061 ], [ 36.133225546000119, 32.520109151000028 ], [ 36.139530070000035, 32.519540710000072 ], [ 36.149865356000134, 32.516130067000049 ], [ 36.155859822000139, 32.51519989100008 ], [ 36.160820760000092, 32.51721527100004 ], [ 36.172189575000061, 32.525922750000078 ], [ 36.177357218000111, 32.527318014000073 ], [ 36.18820926900014, 32.522279561000104 ], [ 36.220765421000067, 32.494580994000088 ], [ 36.285257609000098, 32.456934713000052 ], [ 36.373107544000106, 32.386422221000075 ], [ 36.387887004000106, 32.379316712000062 ], [ 36.407627400000081, 32.374226583000066 ], [ 36.463954712000145, 32.369394837000058 ], [ 36.480181111000093, 32.360790711000035 ], [ 36.516683926721839, 32.357014182458556 ], [ 36.653503865000062, 32.34285898800006 ], [ 36.689574015000062, 32.319656271000056 ], [ 36.706937296000092, 32.328337911000105 ], [ 36.728641398000093, 32.327795309000052 ], [ 36.792513468000038, 32.313532614000096 ], [ 36.80656945800007, 32.313041687000052 ] ] ] } },
{ "type": "Feature", "properties": { "ISO": "JO-MN", "NAME_1": "Ma`an" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 37.221722009000075, 31.247292129000115 ], [ 37.349895467000067, 31.128230286000033 ], [ 37.480016724000052, 31.007255758000056 ], [ 37.483117309000079, 31.004103495000024 ], [ 37.486321249000071, 31.000899557000039 ], [ 37.489421834000098, 30.997695618000066 ], [ 37.492625773000043, 30.994491679000092 ], [ 37.602283162000049, 30.883232321000051 ], [ 37.712043905000087, 30.772024638000048 ], [ 37.821908000000121, 30.66086863200006 ], [ 37.931565389000127, 30.549660950000131 ], [ 37.981071411000073, 30.499483134000101 ], [ 37.981381469000041, 30.498811340000103 ], [ 37.980968058000144, 30.498397929000092 ], [ 37.98003788200009, 30.49808787100001 ], [ 37.97331994700005, 30.494522196000062 ], [ 37.900146118000066, 30.459072164000119 ], [ 37.779326620000063, 30.400419414000069 ], [ 37.670702759000051, 30.347606100000021 ], [ 37.647551718000045, 30.330862936000088 ], [ 37.634529256000121, 30.312776184000072 ], [ 37.605177042000037, 30.250712789000104 ], [ 37.569210246000068, 30.174955139000119 ], [ 37.536137329000098, 30.105295309 ], [ 37.491695597000103, 30.011192526000016 ], [ 37.470198201000073, 29.994552714000108 ], [ 37.352375936000044, 29.973313701000038 ], [ 37.21853397600006, 29.94912913000006 ], [ 37.075803670000084, 29.923290915000038 ], [ 36.931936483000129, 29.897245992000066 ], [ 36.842949666000038, 29.881226299 ], [ 36.756236613000056, 29.865516663000037 ], [ 36.728744751000079, 29.853527731000085 ], [ 36.704870239000115, 29.831151836000103 ], [ 36.64957645700008, 29.74939972 ], [ 36.603584432000105, 29.681471049000052 ], [ 36.541262655000082, 29.589409485000104 ], [ 36.477080526000123, 29.494609070000067 ], [ 36.3999792890001, 29.438901876000031 ], [ 36.283707316000061, 29.354850159000094 ], [ 36.177977336000083, 29.278369039000026 ], [ 36.069456828000057, 29.200027568000039 ], [ 36.043825318000131, 29.190880840000133 ], [ 36.016436808000094, 29.189950664 ], [ 35.912463827000124, 29.205686137000058 ], [ 35.797225382000079, 29.223075257000076 ], [ 35.740250622000076, 29.231730714000022 ], [ 35.740175409067831, 29.232014471990283 ], [ 35.737901645944191, 29.240592760547429 ], [ 35.688395623858923, 29.557188421808178 ], [ 35.623541700688918, 29.78735525224306 ], [ 35.570935093179969, 29.890888984239211 ], [ 35.556052280088636, 29.910991116246976 ], [ 35.538068881573622, 29.927734280412665 ], [ 35.518690219977657, 29.942487901395509 ], [ 35.499104851907362, 29.951944688196761 ], [ 35.480501335767997, 29.957990831211873 ], [ 35.450684035439849, 29.963080959818399 ], [ 35.424949171566993, 29.962435003772384 ], [ 35.412081740080225, 29.960135403126344 ], [ 35.399162631750016, 29.956052964872413 ], [ 35.384279818658683, 29.954425156895468 ], [ 35.368311801748234, 29.955019436098098 ], [ 35.351878695945061, 29.959747830398044 ], [ 35.338184442158251, 29.966724148500646 ], [ 35.325937127396514, 29.976594347351238 ], [ 35.316790398957721, 29.986981310139356 ], [ 35.309038933599879, 29.998530992011638 ], [ 35.303767937840064, 30.008323676496445 ], [ 35.299117058805223, 30.027056382945716 ], [ 35.301442498772303, 30.053385525121882 ], [ 35.3129146662788, 30.103098252782104 ], [ 35.371412388071235, 30.203247179413779 ], [ 35.379473910892273, 30.232392686173512 ], [ 35.377458530186971, 30.344969793820894 ], [ 35.421848586143312, 30.466822822015615 ], [ 35.442312453357033, 30.546016954119125 ], [ 35.448048537110253, 30.608493761377986 ], [ 35.488097772394269, 30.608571274844451 ], [ 35.528922153134829, 30.603274441562235 ], [ 35.628347609354648, 30.605987454257615 ], [ 35.662350701623552, 30.603351955928019 ], [ 35.75578169077238, 30.614229845131206 ], [ 35.826681756058179, 30.628931790169986 ], [ 35.840789421894272, 30.636657416206788 ], [ 35.850711296688985, 30.645054836711324 ], [ 35.863165317925052, 30.652547918751452 ], [ 35.873862339075686, 30.654537461934297 ], [ 35.884404330595373, 30.653788154000097 ], [ 35.911224400085985, 30.644744778348809 ], [ 35.947707961053538, 30.656423652329693 ], [ 36.023775669311647, 30.767062892738295 ], [ 36.140926140728766, 30.955061754396411 ], [ 36.19193077958181, 31.094794827419321 ], [ 36.168521355675978, 31.15050202125127 ], [ 36.151778192409608, 31.248635566278324 ], [ 37.221722009000075, 31.247292129000115 ] ] ] } },
{ "type": "Feature", "properties": { "ISO": "JO-AM", "NAME_1": "Amman" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 36.997911518701585, 31.500813954900082 ], [ 36.959531698000035, 31.490998840000103 ], [ 37.089652954000087, 31.370075989000057 ], [ 37.219774211000129, 31.24910146100008 ], [ 37.221722009000075, 31.247292129000115 ], [ 36.151778192409608, 31.248635566278324 ], [ 35.849161003977144, 31.254940089913191 ], [ 35.839239129182431, 31.262536526539463 ], [ 35.835673455765345, 31.274551297304527 ], [ 35.838153923564676, 31.294007473266277 ], [ 35.841874626612707, 31.308166815945754 ], [ 35.849936151232384, 31.328062242378564 ], [ 35.85179650230674, 31.337053941186412 ], [ 35.849161003977144, 31.350205593513294 ], [ 35.842339714606112, 31.3692483592244 ], [ 35.818000115612847, 31.405938625766964 ], [ 35.82885216639437, 31.414801134264906 ], [ 35.834898309409425, 31.418831894776076 ], [ 35.842494745136378, 31.425627345725388 ], [ 35.846835564909384, 31.432138576733905 ], [ 35.863940464280972, 31.477381293411952 ], [ 35.870606724021059, 31.488259181715819 ], [ 35.884404330595373, 31.505415757930848 ], [ 35.887504916918374, 31.511746120886755 ], [ 35.885644565844018, 31.517895615789996 ], [ 35.877738070855287, 31.524458522742634 ], [ 35.871846958370384, 31.530659695388636 ], [ 35.870916782383574, 31.538592027000448 ], [ 35.87432742706909, 31.545826728420764 ], [ 35.875102573425011, 31.555335191166137 ], [ 35.869056431309218, 31.567995917077894 ], [ 35.825596551339743, 31.608070990783574 ], [ 35.818155145243736, 31.623780626174948 ], [ 35.810403679885894, 31.649541327570205 ], [ 35.808853387174054, 31.659230658368188 ], [ 35.810248651154325, 31.667912298813519 ], [ 35.815209587652305, 31.675560411383856 ], [ 35.832417839811455, 31.69318207469297 ], [ 35.838308954094941, 31.702406318396868 ], [ 35.840479364431076, 31.711759752410615 ], [ 35.838153923564676, 31.784184271986533 ], [ 35.831022576730504, 31.78992035573981 ], [ 35.824356316990418, 31.790824693304955 ], [ 35.811798943866165, 31.786406358266788 ], [ 35.796399366837306, 31.783124904790498 ], [ 35.745859815977724, 31.782969876058928 ], [ 35.708291050291734, 31.774649969920176 ], [ 35.710151402265353, 31.792530016547005 ], [ 35.712476841333114, 31.803072008066692 ], [ 35.725189243188993, 31.833716132493521 ], [ 35.723483920846263, 31.842191067363842 ], [ 35.717747837092986, 31.84756541591122 ], [ 35.694803501180616, 31.850795193443389 ], [ 35.681574333588628, 31.854128322863801 ], [ 35.670877313337314, 31.858779201898642 ], [ 35.663900995234712, 31.865729682478843 ], [ 35.661730583999258, 31.874928086861701 ], [ 35.668706903001123, 31.885935167274113 ], [ 35.683744744824082, 31.897433173202387 ], [ 35.741932407354682, 31.922832140291007 ], [ 35.766943800815739, 31.938335069208051 ], [ 35.811953972597735, 31.983706977095324 ], [ 35.826836785689068, 31.99419729357021 ], [ 35.864870640267839, 32.004093329043883 ], [ 35.880528598815772, 32.01158641198333 ], [ 35.911741164023454, 32.037631334218702 ], [ 35.941196730045021, 32.045847887569948 ], [ 35.964141065957392, 32.020164700540477 ], [ 35.988222284330959, 32.001276964460317 ], [ 36.021915318237347, 31.966317856883563 ], [ 36.041293979833256, 31.95448395417111 ], [ 36.054471469682539, 31.950995795119809 ], [ 36.074005160909451, 31.960504258764502 ], [ 36.086304151615309, 31.962674669100693 ], [ 36.102427199055967, 31.963914903450018 ], [ 36.15146813314783, 31.977221585407847 ], [ 36.215856968324431, 31.97683401088085 ], [ 36.236475864269721, 31.980115465256517 ], [ 36.249394971700553, 31.986885076884789 ], [ 36.268463575833323, 32.006625475485293 ], [ 36.280400832232601, 32.015436306240531 ], [ 36.301691521746307, 32.019337877341172 ], [ 36.407473179343754, 32.011483059195825 ], [ 36.428453809595624, 32.003473212318852 ], [ 36.449072707339553, 31.988693752914344 ], [ 36.505865105889882, 31.93562205741199 ], [ 36.53459720239897, 31.903815213001678 ], [ 36.5363025247417, 31.888028062345199 ], [ 36.527104120358842, 31.875806586005126 ], [ 36.499043817418226, 31.860846259447271 ], [ 36.47656456859994, 31.845162462477617 ], [ 36.468916456928923, 31.836248277136235 ], [ 36.467521192948652, 31.826869004700768 ], [ 36.473774040639455, 31.81591360113174 ], [ 36.500749138861636, 31.789661974220735 ], [ 36.545604281912063, 31.754031073974886 ], [ 36.589064161881538, 31.728606269363809 ], [ 36.612318556156424, 31.721139023946762 ], [ 36.631077101027358, 31.721604111940167 ], [ 36.678567743306701, 31.746641343822944 ], [ 36.69567264177897, 31.75062042928937 ], [ 36.714276157019015, 31.746899726241338 ], [ 36.994362419789809, 31.502470201238793 ], [ 36.99746300611281, 31.501023261314458 ], [ 36.997911518701585, 31.500813954900082 ] ] ] } },
{ "type": "Feature", "properties": { "ISO": "JO-AZ", "NAME_1": "Zarqa" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 37.76141217300011, 31.696120493000095 ], [ 37.702742147000038, 31.68111643500005 ], [ 37.455005331000052, 31.617709452000028 ], [ 37.207268514000134, 31.554354147000097 ], [ 36.997911518701585, 31.500813954900082 ], [ 36.99746300611281, 31.501023261314458 ], [ 36.994362419789809, 31.502470201238793 ], [ 36.714276157019015, 31.746899726241338 ], [ 36.69567264177897, 31.75062042928937 ], [ 36.678567743306701, 31.746641343822944 ], [ 36.631077101027358, 31.721604111940167 ], [ 36.612318556156424, 31.721139023946762 ], [ 36.589064161881538, 31.728606269363809 ], [ 36.545604281912063, 31.754031073974886 ], [ 36.500749138861636, 31.789661974220735 ], [ 36.473774040639455, 31.81591360113174 ], [ 36.467521192948652, 31.826869004700768 ], [ 36.468916456928923, 31.836248277136235 ], [ 36.47656456859994, 31.845162462477617 ], [ 36.499043817418226, 31.860846259447271 ], [ 36.527104120358842, 31.875806586005126 ], [ 36.5363025247417, 31.888028062345199 ], [ 36.53459720239897, 31.903815213001678 ], [ 36.505865105889882, 31.93562205741199 ], [ 36.449072707339553, 31.988693752914344 ], [ 36.428453809595624, 32.003473212318852 ], [ 36.407473179343754, 32.011483059195825 ], [ 36.301691521746307, 32.019337877341172 ], [ 36.280400832232601, 32.015436306240531 ], [ 36.268463575833323, 32.006625475485293 ], [ 36.249394971700553, 31.986885076884789 ], [ 36.236475864269721, 31.980115465256517 ], [ 36.215856968324431, 31.97683401088085 ], [ 36.15146813314783, 31.977221585407847 ], [ 36.102427199055967, 31.963914903450018 ], [ 36.086304151615309, 31.962674669100693 ], [ 36.074005160909451, 31.960504258764502 ], [ 36.054471469682539, 31.950995795119809 ], [ 36.041293979833256, 31.95448395417111 ], [ 36.021915318237347, 31.966317856883563 ], [ 35.988222284330959, 32.001276964460317 ], [ 35.964141065957392, 32.020164700540477 ], [ 35.941196730045021, 32.045847887569948 ], [ 35.921663038818167, 32.0556922470995 ], [ 35.914841750346454, 32.058224391742272 ], [ 35.906728549782713, 32.064683945907348 ], [ 35.901612582754467, 32.069851588879715 ], [ 35.89587649900119, 32.095663967118355 ], [ 35.93329023595561, 32.138374539153631 ], [ 35.944917433093053, 32.146151842033873 ], [ 35.960730422171252, 32.15416168891079 ], [ 35.973804559232974, 32.159355170304821 ], [ 35.982331170047416, 32.166796576400884 ], [ 35.987292108344093, 32.175633246477105 ], [ 35.990702752130289, 32.196665554471736 ], [ 36.010856560981495, 32.190851956352674 ], [ 36.019383171795937, 32.183048814151448 ], [ 36.022948846112342, 32.17615001131395 ], [ 36.021398553400502, 32.169664617827834 ], [ 36.01690270399655, 32.163540961346257 ], [ 36.013957147304495, 32.156332099246981 ], [ 36.014732292761096, 32.146849474024009 ], [ 36.019693231057772, 32.139950670287192 ], [ 36.029976841058328, 32.133827012906295 ], [ 36.040673862208962, 32.13222504335107 ], [ 36.052456088977294, 32.134369615265484 ], [ 36.062532993402897, 32.139098009565487 ], [ 36.076175571245585, 32.150621853016105 ], [ 36.086149122883683, 32.149510809875949 ], [ 36.098706496007935, 32.142896226979246 ], [ 36.123046095900577, 32.127160753166208 ], [ 36.138393996086052, 32.123620917271467 ], [ 36.15224328040307, 32.124602769202397 ], [ 36.173017205979249, 32.13181163220105 ], [ 36.183404167868048, 32.13390452727208 ], [ 36.195858189104115, 32.135299791252351 ], [ 36.236320834638775, 32.131966660932619 ], [ 36.27668012918457, 32.11504263051296 ], [ 36.294198438806859, 32.104190578832117 ], [ 36.309598015835718, 32.100314846153196 ], [ 36.324635857658677, 32.100650742937432 ], [ 36.337503290044765, 32.105663357178173 ], [ 36.348045281564453, 32.11253632339259 ], [ 36.360912713051221, 32.117497259890627 ], [ 36.37941287640308, 32.119073391024131 ], [ 36.4334147478923, 32.11411245452615 ], [ 36.450933058413909, 32.106283473903204 ], [ 36.482765741245942, 32.080806993348062 ], [ 36.51795739102073, 32.063417874035622 ], [ 37.759380323942764, 31.696773587431096 ], [ 37.7608272638671, 31.696308499437691 ], [ 37.76141217300011, 31.696120493000095 ] ] ] } },
{ "type": "Feature", "properties": { "ISO": "JO-AJ", "NAME_1": "Ajlun" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 35.694803501180616, 32.156177070515355 ], [ 35.668706903001123, 32.160698757441708 ], [ 35.651808709204545, 32.166564033303473 ], [ 35.635530633032261, 32.183823961406688 ], [ 35.640026483335532, 32.193797512145466 ], [ 35.640801628792133, 32.199662787107911 ], [ 35.638321160992746, 32.208318590030899 ], [ 35.624471876675727, 32.235319525775481 ], [ 35.618425733660672, 32.25152008758198 ], [ 35.616720412217205, 32.266764634979893 ], [ 35.63206831240268, 32.329344794126939 ], [ 35.639096307348666, 32.344847723943303 ], [ 35.648863153411753, 32.35536387794059 ], [ 35.663125847979472, 32.360531520912957 ], [ 35.680489128870192, 32.361668403374097 ], [ 35.705655551962138, 32.360221463449761 ], [ 35.729685092592945, 32.366035061568823 ], [ 35.760122512344026, 32.380246080192421 ], [ 35.776555617247936, 32.382984931309522 ], [ 35.805597772119484, 32.381589667329251 ], [ 35.821875848291768, 32.383656724877937 ], [ 35.83381310379167, 32.389599514206168 ], [ 35.840944452424537, 32.398074449076546 ], [ 35.848075799258709, 32.402001857699531 ], [ 35.854793735842236, 32.399443875534416 ], [ 35.859134555615242, 32.386369737573318 ], [ 35.864095493012599, 32.378179023543055 ], [ 35.883784213870342, 32.364639796689232 ], [ 35.905333285802499, 32.338879096193295 ], [ 35.884094273132177, 32.328957221398639 ], [ 35.873242222350655, 32.325003974353933 ], [ 35.857687615690907, 32.31621898022172 ], [ 35.841874626612707, 32.302886460741547 ], [ 35.824976433715449, 32.280278022512732 ], [ 35.818000115612847, 32.263819078287838 ], [ 35.815209587652305, 32.249892280504298 ], [ 35.815984734907545, 32.240357978437942 ], [ 35.813659294940464, 32.23146963151828 ], [ 35.804667596132617, 32.222736314229508 ], [ 35.73650638196392, 32.196510524840846 ], [ 35.694803501180616, 32.156177070515355 ] ] ] } },
{ "type": "Feature", "properties": { "ISO": "JO-JA", "NAME_1": "Jarash" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 35.719763217798231, 32.143516343704277 ], [ 35.706430698318059, 32.144601549322033 ], [ 35.696198765160887, 32.147831325954883 ], [ 35.694803501180616, 32.156177070515355 ], [ 35.73650638196392, 32.196510524840846 ], [ 35.804667596132617, 32.222736314229508 ], [ 35.813659294940464, 32.23146963151828 ], [ 35.815984734907545, 32.240357978437942 ], [ 35.815209587652305, 32.249892280504298 ], [ 35.818000115612847, 32.263819078287838 ], [ 35.824976433715449, 32.280278022512732 ], [ 35.841874626612707, 32.302886460741547 ], [ 35.857687615690907, 32.31621898022172 ], [ 35.873242222350655, 32.325003974353933 ], [ 35.884094273132177, 32.328957221398639 ], [ 35.905333285802499, 32.338879096193295 ], [ 35.939646437333181, 32.3513331165301 ], [ 35.952978956813411, 32.354743761215559 ], [ 35.984036493289523, 32.347147325488663 ], [ 36.017212762359065, 32.345958767083403 ], [ 36.003105095623653, 32.321593328769097 ], [ 35.957629835848252, 32.278055935333157 ], [ 35.948018019416054, 32.262475491150951 ], [ 35.947242873060134, 32.252605292300359 ], [ 35.952048780826544, 32.245784002929383 ], [ 35.960265334177791, 32.241133123894542 ], [ 35.967138298593568, 32.235810452190606 ], [ 35.980315790241491, 32.217103583263736 ], [ 35.990702752130289, 32.196665554471736 ], [ 35.987292108344093, 32.175633246477105 ], [ 35.982331170047416, 32.166796576400884 ], [ 35.973804559232974, 32.159355170304821 ], [ 35.960730422171252, 32.15416168891079 ], [ 35.944917433093053, 32.146151842033873 ], [ 35.93329023595561, 32.138374539153631 ], [ 35.89587649900119, 32.095663967118355 ], [ 35.859134555615242, 32.118970038236682 ], [ 35.851641472675794, 32.127393297162939 ], [ 35.840324333900867, 32.137108466382585 ], [ 35.826371697695663, 32.142198594989168 ], [ 35.806682976837862, 32.145376694778633 ], [ 35.719763217798231, 32.143516343704277 ] ] ] } }
]
}
| superset-frontend/plugins/legacy-plugin-chart-country-map/src/countries/jordan.geojson | 0 | https://github.com/apache/superset/commit/4669b6ce11dd74e5d1020a1f124e8696b801d730 | [
0.001392333535477519,
0.0011168373748660088,
0.0008413413306698203,
0.0011168373748660088,
0.00027549610240384936
] |
{
"id": 0,
"code_window": [
"export function queryEditorSetSelectedText(queryEditor, sql) {\n",
" return { type: QUERY_EDITOR_SET_SELECTED_TEXT, queryEditor, sql };\n",
"}\n",
"\n",
"export function mergeTable(table, query) {\n",
" return { type: MERGE_TABLE, table, query };\n",
"}\n",
"\n",
"function getTableMetadata(table, query, dispatch) {\n",
" return SupersetClient.get({\n",
" endpoint: encodeURI(\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export function mergeTable(table, query, prepend) {\n",
" return { type: MERGE_TABLE, table, query, prepend };\n"
],
"file_path": "superset-frontend/src/SqlLab/actions/sqlLab.js",
"type": "replace",
"edit_start_line_idx": 1000
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
# pylint: disable=unused-import
from .bart_lines import load_bart_lines
from .big_data import load_big_data
from .birth_names import load_birth_names
from .country_map import load_country_map_data
from .css_templates import load_css_templates
from .deck import load_deck_dash
from .energy import load_energy
from .flights import load_flights
from .long_lat import load_long_lat_data
from .misc_dashboard import load_misc_dashboard
from .multi_line import load_multi_line
from .multiformat_time_series import load_multiformat_time_series
from .paris import load_paris_iris_geojson
from .random_time_series import load_random_time_series_data
from .sf_population_polygons import load_sf_population_polygons
from .tabbed_dashboard import load_tabbed_dashboard
from .utils import load_examples_from_configs
from .world_bank import load_world_bank_health_n_pop
| superset/examples/data_loading.py | 0 | https://github.com/apache/superset/commit/4669b6ce11dd74e5d1020a1f124e8696b801d730 | [
0.0001788532390492037,
0.0001768283691490069,
0.00017538682732265443,
0.00017653670511208475,
0.0000014412549944609054
] |
{
"id": 1,
"code_window": [
" queryEditorId: query.id,\n",
" schema: schemaName,\n",
" name: tableName,\n",
" };\n",
" dispatch(\n",
" mergeTable({\n",
" ...table,\n",
" isMetadataLoading: true,\n",
" isExtraMetadataLoading: true,\n",
" expanded: true,\n",
" }),\n",
" );\n",
"\n",
" return Promise.all([\n",
" getTableMetadata(table, query, dispatch),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" mergeTable(\n",
" {\n",
" ...table,\n",
" isMetadataLoading: true,\n",
" isExtraMetadataLoading: true,\n",
" expanded: true,\n",
" },\n",
" null,\n",
" true,\n",
" ),\n"
],
"file_path": "superset-frontend/src/SqlLab/actions/sqlLab.js",
"type": "replace",
"edit_start_line_idx": 1071
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
import { t } from '@superset-ui/core';
import getInitialState from './getInitialState';
import * as actions from '../actions/sqlLab';
import { now } from '../../modules/dates';
import {
addToObject,
alterInObject,
alterInArr,
removeFromArr,
getFromArr,
addToArr,
extendArr,
} from '../../reduxUtils';
export default function sqlLabReducer(state = {}, action) {
const actionHandlers = {
[actions.ADD_QUERY_EDITOR]() {
const tabHistory = state.tabHistory.slice();
tabHistory.push(action.queryEditor.id);
const newState = { ...state, tabHistory };
return addToArr(newState, 'queryEditors', action.queryEditor);
},
[actions.QUERY_EDITOR_SAVED]() {
const { query, result } = action;
const existing = state.queryEditors.find(qe => qe.id === query.id);
return alterInArr(
state,
'queryEditors',
existing,
{
remoteId: result.remoteId,
title: query.title,
},
'id',
);
},
[actions.UPDATE_QUERY_EDITOR]() {
const id = action.alterations.remoteId;
const existing = state.queryEditors.find(qe => qe.remoteId === id);
if (existing == null) return state;
return alterInArr(
state,
'queryEditors',
existing,
action.alterations,
'remoteId',
);
},
[actions.CLONE_QUERY_TO_NEW_TAB]() {
const progenitor = state.queryEditors.find(
qe => qe.id === state.tabHistory[state.tabHistory.length - 1],
);
const qe = {
remoteId: progenitor.remoteId,
title: t('Copy of %s', progenitor.title),
dbId: action.query.dbId ? action.query.dbId : null,
schema: action.query.schema ? action.query.schema : null,
autorun: true,
sql: action.query.sql,
queryLimit: action.query.queryLimit,
maxRow: action.query.maxRow,
};
return sqlLabReducer(state, actions.addQueryEditor(qe));
},
[actions.REMOVE_QUERY_EDITOR]() {
let newState = removeFromArr(state, 'queryEditors', action.queryEditor);
// List of remaining queryEditor ids
const qeIds = newState.queryEditors.map(qe => qe.id);
const queries = {};
Object.keys(state.queries).forEach(k => {
const query = state.queries[k];
if (qeIds.indexOf(query.sqlEditorId) > -1) {
queries[k] = query;
}
});
let tabHistory = state.tabHistory.slice();
tabHistory = tabHistory.filter(id => qeIds.indexOf(id) > -1);
// Remove associated table schemas
const tables = state.tables.filter(
table => table.queryEditorId !== action.queryEditor.id,
);
newState = { ...newState, tabHistory, tables, queries };
return newState;
},
[actions.REMOVE_QUERY]() {
const newQueries = { ...state.queries };
delete newQueries[action.query.id];
return { ...state, queries: newQueries };
},
[actions.RESET_STATE]() {
return { ...getInitialState() };
},
[actions.MERGE_TABLE]() {
const at = { ...action.table };
let existingTable;
state.tables.forEach(xt => {
if (
xt.dbId === at.dbId &&
xt.queryEditorId === at.queryEditorId &&
xt.schema === at.schema &&
xt.name === at.name
) {
existingTable = xt;
}
});
if (existingTable) {
if (action.query) {
at.dataPreviewQueryId = action.query.id;
}
return alterInArr(state, 'tables', existingTable, at);
}
// for new table, associate Id of query for data preview
at.dataPreviewQueryId = null;
let newState = addToArr(state, 'tables', at);
if (action.query) {
newState = alterInArr(newState, 'tables', at, {
dataPreviewQueryId: action.query.id,
});
}
return newState;
},
[actions.EXPAND_TABLE]() {
return alterInArr(state, 'tables', action.table, { expanded: true });
},
[actions.REMOVE_DATA_PREVIEW]() {
const queries = { ...state.queries };
delete queries[action.table.dataPreviewQueryId];
const newState = alterInArr(state, 'tables', action.table, {
dataPreviewQueryId: null,
});
return { ...newState, queries };
},
[actions.CHANGE_DATA_PREVIEW_ID]() {
const queries = { ...state.queries };
delete queries[action.oldQueryId];
const newTables = [];
state.tables.forEach(xt => {
if (xt.dataPreviewQueryId === action.oldQueryId) {
newTables.push({ ...xt, dataPreviewQueryId: action.newQuery.id });
} else {
newTables.push(xt);
}
});
return {
...state,
queries,
tables: newTables,
activeSouthPaneTab: action.newQuery.id,
};
},
[actions.COLLAPSE_TABLE]() {
return alterInArr(state, 'tables', action.table, { expanded: false });
},
[actions.REMOVE_TABLE]() {
return removeFromArr(state, 'tables', action.table);
},
[actions.START_QUERY_VALIDATION]() {
let newState = { ...state };
const sqlEditor = { id: action.query.sqlEditorId };
newState = alterInArr(newState, 'queryEditors', sqlEditor, {
validationResult: {
id: action.query.id,
errors: [],
completed: false,
},
});
return newState;
},
[actions.QUERY_VALIDATION_RETURNED]() {
// If the server is very slow about answering us, we might get validation
// responses back out of order. This check confirms the response we're
// handling corresponds to the most recently dispatched request.
//
// We don't care about any but the most recent because validations are
// only valid for the SQL text they correspond to -- once the SQL has
// changed, the old validation doesn't tell us anything useful anymore.
const qe = getFromArr(state.queryEditors, action.query.sqlEditorId);
if (qe.validationResult.id !== action.query.id) {
return state;
}
// Otherwise, persist the results on the queryEditor state
let newState = { ...state };
const sqlEditor = { id: action.query.sqlEditorId };
newState = alterInArr(newState, 'queryEditors', sqlEditor, {
validationResult: {
id: action.query.id,
errors: action.results,
completed: true,
},
});
return newState;
},
[actions.QUERY_VALIDATION_FAILED]() {
// If the server is very slow about answering us, we might get validation
// responses back out of order. This check confirms the response we're
// handling corresponds to the most recently dispatched request.
//
// We don't care about any but the most recent because validations are
// only valid for the SQL text they correspond to -- once the SQL has
// changed, the old validation doesn't tell us anything useful anymore.
const qe = getFromArr(state.queryEditors, action.query.sqlEditorId);
if (qe.validationResult.id !== action.query.id) {
return state;
}
// Otherwise, persist the results on the queryEditor state
let newState = { ...state };
const sqlEditor = { id: action.query.sqlEditorId };
newState = alterInArr(newState, 'queryEditors', sqlEditor, {
validationResult: {
id: action.query.id,
errors: [
{
line_number: 1,
start_column: 1,
end_column: 1,
message: `The server failed to validate your query.\n${action.message}`,
},
],
completed: true,
},
});
return newState;
},
[actions.COST_ESTIMATE_STARTED]() {
let newState = { ...state };
const sqlEditor = { id: action.query.sqlEditorId };
newState = alterInArr(newState, 'queryEditors', sqlEditor, {
queryCostEstimate: {
completed: false,
cost: null,
error: null,
},
});
return newState;
},
[actions.COST_ESTIMATE_RETURNED]() {
let newState = { ...state };
const sqlEditor = { id: action.query.sqlEditorId };
newState = alterInArr(newState, 'queryEditors', sqlEditor, {
queryCostEstimate: {
completed: true,
cost: action.json,
error: null,
},
});
return newState;
},
[actions.COST_ESTIMATE_FAILED]() {
let newState = { ...state };
const sqlEditor = { id: action.query.sqlEditorId };
newState = alterInArr(newState, 'queryEditors', sqlEditor, {
queryCostEstimate: {
completed: false,
cost: null,
error: action.error,
},
});
return newState;
},
[actions.START_QUERY]() {
let newState = { ...state };
if (action.query.sqlEditorId) {
const qe = getFromArr(state.queryEditors, action.query.sqlEditorId);
if (qe.latestQueryId && state.queries[qe.latestQueryId]) {
const newResults = {
...state.queries[qe.latestQueryId].results,
data: [],
query: null,
};
const q = { ...state.queries[qe.latestQueryId], results: newResults };
const queries = { ...state.queries, [q.id]: q };
newState = { ...state, queries };
}
} else {
newState.activeSouthPaneTab = action.query.id;
}
newState = addToObject(newState, 'queries', action.query);
const sqlEditor = { id: action.query.sqlEditorId };
return alterInArr(newState, 'queryEditors', sqlEditor, {
latestQueryId: action.query.id,
});
},
[actions.STOP_QUERY]() {
return alterInObject(state, 'queries', action.query, {
state: 'stopped',
results: [],
});
},
[actions.CLEAR_QUERY_RESULTS]() {
const newResults = { ...action.query.results };
newResults.data = [];
return alterInObject(state, 'queries', action.query, {
results: newResults,
cached: true,
});
},
[actions.REQUEST_QUERY_RESULTS]() {
return alterInObject(state, 'queries', action.query, {
state: 'fetching',
});
},
[actions.QUERY_SUCCESS]() {
// prevent race condition were query succeeds shortly after being canceled
if (action.query.state === 'stopped') {
return state;
}
const alts = {
endDttm: now(),
progress: 100,
results: action.results,
rows: action?.results?.query?.rows || 0,
state: 'success',
limitingFactor: action?.results?.query?.limitingFactor,
tempSchema: action?.results?.query?.tempSchema,
tempTable: action?.results?.query?.tempTable,
errorMessage: null,
cached: false,
};
return alterInObject(state, 'queries', action.query, alts);
},
[actions.QUERY_FAILED]() {
if (action.query.state === 'stopped') {
return state;
}
const alts = {
state: 'failed',
errors: action.errors,
errorMessage: action.msg,
endDttm: now(),
link: action.link,
};
return alterInObject(state, 'queries', action.query, alts);
},
[actions.SET_ACTIVE_QUERY_EDITOR]() {
const qeIds = state.queryEditors.map(qe => qe.id);
if (
qeIds.indexOf(action.queryEditor?.id) > -1 &&
state.tabHistory[state.tabHistory.length - 1] !== action.queryEditor.id
) {
const tabHistory = state.tabHistory.slice();
tabHistory.push(action.queryEditor.id);
return { ...state, tabHistory };
}
return state;
},
[actions.LOAD_QUERY_EDITOR]() {
return alterInArr(state, 'queryEditors', action.queryEditor, {
...action.queryEditor,
});
},
[actions.SET_TABLES]() {
return extendArr(state, 'tables', action.tables);
},
[actions.SET_ACTIVE_SOUTHPANE_TAB]() {
return { ...state, activeSouthPaneTab: action.tabId };
},
[actions.MIGRATE_QUERY_EDITOR]() {
// remove migrated query editor from localStorage
const { sqlLab } = JSON.parse(localStorage.getItem('redux'));
sqlLab.queryEditors = sqlLab.queryEditors.filter(
qe => qe.id !== action.oldQueryEditor.id,
);
localStorage.setItem('redux', JSON.stringify({ sqlLab }));
// replace localStorage query editor with the server backed one
return addToArr(
removeFromArr(state, 'queryEditors', action.oldQueryEditor),
'queryEditors',
action.newQueryEditor,
);
},
[actions.MIGRATE_TABLE]() {
// remove migrated table from localStorage
const { sqlLab } = JSON.parse(localStorage.getItem('redux'));
sqlLab.tables = sqlLab.tables.filter(
table => table.id !== action.oldTable.id,
);
localStorage.setItem('redux', JSON.stringify({ sqlLab }));
// replace localStorage table with the server backed one
return addToArr(
removeFromArr(state, 'tables', action.oldTable),
'tables',
action.newTable,
);
},
[actions.MIGRATE_TAB_HISTORY]() {
// remove migrated tab from localStorage tabHistory
const { sqlLab } = JSON.parse(localStorage.getItem('redux'));
sqlLab.tabHistory = sqlLab.tabHistory.filter(
tabId => tabId !== action.oldId,
);
localStorage.setItem('redux', JSON.stringify({ sqlLab }));
const tabHistory = state.tabHistory.filter(
tabId => tabId !== action.oldId,
);
tabHistory.push(action.newId);
return { ...state, tabHistory };
},
[actions.MIGRATE_QUERY]() {
const query = {
...state.queries[action.queryId],
// point query to migrated query editor
sqlEditorId: action.queryEditorId,
};
const queries = { ...state.queries, [query.id]: query };
return { ...state, queries };
},
[actions.QUERY_EDITOR_SETDB]() {
return alterInArr(state, 'queryEditors', action.queryEditor, {
dbId: action.dbId,
});
},
[actions.QUERY_EDITOR_SET_FUNCTION_NAMES]() {
return alterInArr(state, 'queryEditors', action.queryEditor, {
functionNames: action.functionNames,
});
},
[actions.QUERY_EDITOR_SET_SCHEMA]() {
return alterInArr(state, 'queryEditors', action.queryEditor, {
schema: action.schema,
});
},
[actions.QUERY_EDITOR_SET_SCHEMA_OPTIONS]() {
return alterInArr(state, 'queryEditors', action.queryEditor, {
schemaOptions: action.options,
});
},
[actions.QUERY_EDITOR_SET_TABLE_OPTIONS]() {
return alterInArr(state, 'queryEditors', action.queryEditor, {
tableOptions: action.options,
});
},
[actions.QUERY_EDITOR_SET_TITLE]() {
return alterInArr(state, 'queryEditors', action.queryEditor, {
title: action.title,
});
},
[actions.QUERY_EDITOR_SET_SQL]() {
return alterInArr(state, 'queryEditors', action.queryEditor, {
sql: action.sql,
});
},
[actions.QUERY_EDITOR_SET_QUERY_LIMIT]() {
return alterInArr(state, 'queryEditors', action.queryEditor, {
queryLimit: action.queryLimit,
});
},
[actions.QUERY_EDITOR_SET_TEMPLATE_PARAMS]() {
return alterInArr(state, 'queryEditors', action.queryEditor, {
templateParams: action.templateParams,
});
},
[actions.QUERY_EDITOR_SET_SELECTED_TEXT]() {
return alterInArr(state, 'queryEditors', action.queryEditor, {
selectedText: action.sql,
});
},
[actions.QUERY_EDITOR_SET_AUTORUN]() {
return alterInArr(state, 'queryEditors', action.queryEditor, {
autorun: action.autorun,
});
},
[actions.QUERY_EDITOR_PERSIST_HEIGHT]() {
return alterInArr(state, 'queryEditors', action.queryEditor, {
northPercent: action.northPercent,
southPercent: action.southPercent,
});
},
[actions.QUERY_EDITOR_TOGGLE_LEFT_BAR]() {
return alterInArr(state, 'queryEditors', action.queryEditor, {
hideLeftBar: action.hideLeftBar,
});
},
[actions.SET_DATABASES]() {
const databases = {};
action.databases.forEach(db => {
databases[db.id] = {
...db,
extra_json: JSON.parse(db.extra || ''),
};
});
return { ...state, databases };
},
[actions.REFRESH_QUERIES]() {
let newQueries = { ...state.queries };
// Fetch the updates to the queries present in the store.
let change = false;
let { queriesLastUpdate } = state;
Object.entries(action.alteredQueries).forEach(([id, changedQuery]) => {
if (
!state.queries.hasOwnProperty(id) ||
(state.queries[id].state !== 'stopped' &&
state.queries[id].state !== 'failed')
) {
if (changedQuery.changedOn > queriesLastUpdate) {
queriesLastUpdate = changedQuery.changedOn;
}
const prevState = state.queries[id]?.state;
const currentState = changedQuery.state;
newQueries[id] = {
...state.queries[id],
...changedQuery,
// race condition:
// because of async behavior, sql lab may still poll a couple of seconds
// when it started fetching or finished rendering results
state:
currentState === 'success' &&
['fetching', 'success'].includes(prevState)
? prevState
: currentState,
};
change = true;
}
});
if (!change) {
newQueries = state.queries;
}
return { ...state, queries: newQueries, queriesLastUpdate };
},
[actions.SET_USER_OFFLINE]() {
return { ...state, offline: action.offline };
},
[actions.CREATE_DATASOURCE_STARTED]() {
return { ...state, isDatasourceLoading: true, errorMessage: null };
},
[actions.CREATE_DATASOURCE_SUCCESS]() {
return {
...state,
isDatasourceLoading: false,
errorMessage: null,
datasource: action.datasource,
};
},
[actions.CREATE_DATASOURCE_FAILED]() {
return { ...state, isDatasourceLoading: false, errorMessage: action.err };
},
};
if (action.type in actionHandlers) {
return actionHandlers[action.type]();
}
return state;
}
| superset-frontend/src/SqlLab/reducers/sqlLab.js | 1 | https://github.com/apache/superset/commit/4669b6ce11dd74e5d1020a1f124e8696b801d730 | [
0.0032637242693454027,
0.0003220426442567259,
0.00016472363495267928,
0.00016930641140788794,
0.0005924460128881037
] |
{
"id": 1,
"code_window": [
" queryEditorId: query.id,\n",
" schema: schemaName,\n",
" name: tableName,\n",
" };\n",
" dispatch(\n",
" mergeTable({\n",
" ...table,\n",
" isMetadataLoading: true,\n",
" isExtraMetadataLoading: true,\n",
" expanded: true,\n",
" }),\n",
" );\n",
"\n",
" return Promise.all([\n",
" getTableMetadata(table, query, dispatch),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" mergeTable(\n",
" {\n",
" ...table,\n",
" isMetadataLoading: true,\n",
" isExtraMetadataLoading: true,\n",
" expanded: true,\n",
" },\n",
" null,\n",
" true,\n",
" ),\n"
],
"file_path": "superset-frontend/src/SqlLab/actions/sqlLab.js",
"type": "replace",
"edit_start_line_idx": 1071
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
export * from './Datasource';
export * from './Column';
export * from './Filter';
export * from './Metric';
export * from './Operator';
export * from './Query';
export * from './QueryFormData';
export * from './QueryResponse';
export * from './Time';
export * from './AdvancedAnalytics';
export * from './PostProcessing';
export { default as __hack_reexport_Datasource } from './Datasource';
export { default as __hack_reexport_Column } from './Column';
export { default as __hack_reexport_Metric } from './Metric';
export { default as __hack_reexport_Query } from './Query';
export { default as __hack_reexport_QueryResponse } from './QueryResponse';
export { default as __hack_reexport_QueryFormData } from './QueryFormData';
export { default as __hack_reexport_Time } from './Time';
export { default as __hack_reexport_AdvancedAnalytics } from './AdvancedAnalytics';
export default {};
| superset-frontend/packages/superset-ui-core/src/query/types/index.ts | 0 | https://github.com/apache/superset/commit/4669b6ce11dd74e5d1020a1f124e8696b801d730 | [
0.00017555381054989994,
0.00017291367112193257,
0.0001674225350143388,
0.00017349168774671853,
0.0000028846177428931696
] |
{
"id": 1,
"code_window": [
" queryEditorId: query.id,\n",
" schema: schemaName,\n",
" name: tableName,\n",
" };\n",
" dispatch(\n",
" mergeTable({\n",
" ...table,\n",
" isMetadataLoading: true,\n",
" isExtraMetadataLoading: true,\n",
" expanded: true,\n",
" }),\n",
" );\n",
"\n",
" return Promise.all([\n",
" getTableMetadata(table, query, dispatch),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" mergeTable(\n",
" {\n",
" ...table,\n",
" isMetadataLoading: true,\n",
" isExtraMetadataLoading: true,\n",
" expanded: true,\n",
" },\n",
" null,\n",
" true,\n",
" ),\n"
],
"file_path": "superset-frontend/src/SqlLab/actions/sqlLab.js",
"type": "replace",
"edit_start_line_idx": 1071
} | bundle
dist
lib
| superset-embedded-sdk/.gitignore | 0 | https://github.com/apache/superset/commit/4669b6ce11dd74e5d1020a1f124e8696b801d730 | [
0.00016818945005070418,
0.00016818945005070418,
0.00016818945005070418,
0.00016818945005070418,
0
] |
{
"id": 1,
"code_window": [
" queryEditorId: query.id,\n",
" schema: schemaName,\n",
" name: tableName,\n",
" };\n",
" dispatch(\n",
" mergeTable({\n",
" ...table,\n",
" isMetadataLoading: true,\n",
" isExtraMetadataLoading: true,\n",
" expanded: true,\n",
" }),\n",
" );\n",
"\n",
" return Promise.all([\n",
" getTableMetadata(table, query, dispatch),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" mergeTable(\n",
" {\n",
" ...table,\n",
" isMetadataLoading: true,\n",
" isExtraMetadataLoading: true,\n",
" expanded: true,\n",
" },\n",
" null,\n",
" true,\n",
" ),\n"
],
"file_path": "superset-frontend/src/SqlLab/actions/sqlLab.js",
"type": "replace",
"edit_start_line_idx": 1071
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
import React from 'react';
import { styledMount as mount } from 'spec/helpers/theming';
import { act } from 'react-dom/test-utils';
import { ReactWrapper } from 'enzyme';
import { Provider } from 'react-redux';
import fetchMock from 'fetch-mock';
import thunk from 'redux-thunk';
import configureStore from 'redux-mock-store';
import ActivityTable from 'src/views/CRUD/welcome/ActivityTable';
const mockStore = configureStore([thunk]);
const store = mockStore({});
const chartsEndpoint = 'glob:*/api/v1/chart/?*';
const dashboardsEndpoint = 'glob:*/api/v1/dashboard/?*';
const mockData = {
Viewed: [
{
slice_name: 'ChartyChart',
changed_on_utc: '24 Feb 2014 10:13:14',
url: '/fakeUrl/explore',
id: '4',
table: {},
},
],
Created: [
{
dashboard_title: 'Dashboard_Test',
changed_on_utc: '24 Feb 2014 10:13:14',
url: '/fakeUrl/dashboard',
id: '3',
},
],
};
fetchMock.get(chartsEndpoint, {
result: [
{
slice_name: 'ChartyChart',
changed_on_utc: '24 Feb 2014 10:13:14',
url: '/fakeUrl/explore',
id: '4',
table: {},
},
],
});
fetchMock.get(dashboardsEndpoint, {
result: [
{
dashboard_title: 'Dashboard_Test',
changed_on_utc: '24 Feb 2014 10:13:14',
url: '/fakeUrl/dashboard',
id: '3',
},
],
});
describe('ActivityTable', () => {
const activityProps = {
activeChild: 'Created',
activityData: mockData,
setActiveChild: jest.fn(),
user: { userId: '1' },
loadedCount: 3,
};
let wrapper: ReactWrapper;
beforeAll(async () => {
await act(async () => {
wrapper = mount(
<Provider store={store}>
<ActivityTable {...activityProps} />
</Provider>,
);
});
});
it('the component renders', () => {
expect(wrapper.find(ActivityTable)).toExist();
});
it('renders tabs with three buttons', () => {
expect(wrapper.find('li.no-router')).toHaveLength(3);
});
it('renders ActivityCards', async () => {
expect(wrapper.find('ListViewCard')).toExist();
});
it('calls the getEdited batch call when edited tab is clicked', async () => {
act(() => {
const handler = wrapper.find('li.no-router a').at(1).prop('onClick');
if (handler) {
handler({} as any);
}
});
const dashboardCall = fetchMock.calls(/dashboard\/\?q/);
const chartCall = fetchMock.calls(/chart\/\?q/);
// waitforcomponenttopaint does not work here in this instance...
setTimeout(() => {
expect(chartCall).toHaveLength(1);
expect(dashboardCall).toHaveLength(1);
});
});
it('show empty state if there is no data', () => {
const activityProps = {
activeChild: 'Created',
activityData: {},
setActiveChild: jest.fn(),
user: { userId: '1' },
loadedCount: 3,
};
const wrapper = mount(
<Provider store={store}>
<ActivityTable {...activityProps} />
</Provider>,
);
expect(wrapper.find('EmptyState')).toExist();
});
});
| superset-frontend/src/views/CRUD/welcome/ActivityTable.test.tsx | 0 | https://github.com/apache/superset/commit/4669b6ce11dd74e5d1020a1f124e8696b801d730 | [
0.00017594291421119124,
0.0001719865103950724,
0.00016384045011363924,
0.0001725957845337689,
0.000002988039796036901
] |
{
"id": 2,
"code_window": [
"\n",
" describe('addTable', () => {\n",
" it('updates the table schema state in the backend', () => {\n",
" expect.assertions(5);\n",
"\n",
" const database = { disable_data_preview: true };\n",
" const tableName = 'table';\n",
" const schemaName = 'schema';\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect.assertions(6);\n"
],
"file_path": "superset-frontend/src/SqlLab/actions/sqlLab.test.js",
"type": "replace",
"edit_start_line_idx": 727
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/* eslint no-unused-expressions: 0 */
import sinon from 'sinon';
import fetchMock from 'fetch-mock';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import shortid from 'shortid';
import * as featureFlags from 'src/featureFlags';
import * as actions from 'src/SqlLab/actions/sqlLab';
import { defaultQueryEditor, query } from '../fixtures';
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
describe('async actions', () => {
const mockBigNumber = '9223372036854775807';
const queryEditor = {
id: 'abcd',
autorun: false,
dbId: null,
latestQueryId: null,
selectedText: null,
sql: 'SELECT *\nFROM\nWHERE',
title: 'Untitled Query 1',
schemaOptions: [{ value: 'main', label: 'main', title: 'main' }],
};
let dispatch;
beforeEach(() => {
dispatch = sinon.spy();
});
afterEach(fetchMock.resetHistory);
const fetchQueryEndpoint = 'glob:*/superset/results/*';
fetchMock.get(
fetchQueryEndpoint,
JSON.stringify({ data: mockBigNumber, query: { sqlEditorId: 'dfsadfs' } }),
);
const runQueryEndpoint = 'glob:*/superset/sql_json/';
fetchMock.post(runQueryEndpoint, `{ "data": ${mockBigNumber} }`);
describe('saveQuery', () => {
const saveQueryEndpoint = 'glob:*/savedqueryviewapi/api/create';
fetchMock.post(saveQueryEndpoint, { results: { json: {} } });
const makeRequest = () => {
const request = actions.saveQuery(query);
return request(dispatch);
};
it('posts to the correct url', () => {
expect.assertions(1);
const store = mockStore({});
return store.dispatch(actions.saveQuery(query)).then(() => {
expect(fetchMock.calls(saveQueryEndpoint)).toHaveLength(1);
});
});
it('posts the correct query object', () => {
const store = mockStore({});
return store.dispatch(actions.saveQuery(query)).then(() => {
const call = fetchMock.calls(saveQueryEndpoint)[0];
const formData = call[1].body;
Object.keys(query).forEach(key => {
expect(formData.get(key)).toBeDefined();
});
});
});
it('calls 3 dispatch actions', () => {
expect.assertions(1);
return makeRequest().then(() => {
expect(dispatch.callCount).toBe(2);
});
});
it('calls QUERY_EDITOR_SAVED after making a request', () => {
expect.assertions(1);
return makeRequest().then(() => {
expect(dispatch.args[0][0].type).toBe(actions.QUERY_EDITOR_SAVED);
});
});
it('onSave calls QUERY_EDITOR_SAVED and QUERY_EDITOR_SET_TITLE', () => {
expect.assertions(1);
const store = mockStore({});
const expectedActionTypes = [
actions.QUERY_EDITOR_SAVED,
actions.QUERY_EDITOR_SET_TITLE,
];
return store.dispatch(actions.saveQuery(query)).then(() => {
expect(store.getActions().map(a => a.type)).toEqual(
expectedActionTypes,
);
});
});
});
describe('fetchQueryResults', () => {
const makeRequest = () => {
const request = actions.fetchQueryResults(query);
return request(dispatch);
};
it('makes the fetch request', () => {
expect.assertions(1);
return makeRequest().then(() => {
expect(fetchMock.calls(fetchQueryEndpoint)).toHaveLength(1);
});
});
it('calls requestQueryResults', () => {
expect.assertions(1);
return makeRequest().then(() => {
expect(dispatch.args[0][0].type).toBe(actions.REQUEST_QUERY_RESULTS);
});
});
it.skip('parses large number result without losing precision', () =>
makeRequest().then(() => {
expect(fetchMock.calls(fetchQueryEndpoint)).toHaveLength(1);
expect(dispatch.callCount).toBe(2);
expect(dispatch.getCall(1).lastArg.results.data.toString()).toBe(
mockBigNumber,
);
}));
it('calls querySuccess on fetch success', () => {
expect.assertions(1);
const store = mockStore({});
const expectedActionTypes = [
actions.REQUEST_QUERY_RESULTS,
actions.QUERY_SUCCESS,
];
return store.dispatch(actions.fetchQueryResults(query)).then(() => {
expect(store.getActions().map(a => a.type)).toEqual(
expectedActionTypes,
);
});
});
it('calls queryFailed on fetch error', () => {
expect.assertions(1);
fetchMock.get(
fetchQueryEndpoint,
{ throws: { message: 'error text' } },
{ overwriteRoutes: true },
);
const store = mockStore({});
const expectedActionTypes = [
actions.REQUEST_QUERY_RESULTS,
actions.QUERY_FAILED,
];
return store.dispatch(actions.fetchQueryResults(query)).then(() => {
expect(store.getActions().map(a => a.type)).toEqual(
expectedActionTypes,
);
});
});
});
describe('runQuery without query params', () => {
const makeRequest = () => {
const request = actions.runQuery(query);
return request(dispatch);
};
it('makes the fetch request', () => {
expect.assertions(1);
return makeRequest().then(() => {
expect(fetchMock.calls(runQueryEndpoint)).toHaveLength(1);
});
});
it('calls startQuery', () => {
expect.assertions(1);
return makeRequest().then(() => {
expect(dispatch.args[0][0].type).toBe(actions.START_QUERY);
});
});
it.skip('parses large number result without losing precision', () =>
makeRequest().then(() => {
expect(fetchMock.calls(runQueryEndpoint)).toHaveLength(1);
expect(dispatch.callCount).toBe(2);
expect(dispatch.getCall(1).lastArg.results.data.toString()).toBe(
mockBigNumber,
);
}));
it('calls querySuccess on fetch success', () => {
expect.assertions(1);
const store = mockStore({});
const expectedActionTypes = [actions.START_QUERY, actions.QUERY_SUCCESS];
return store.dispatch(actions.runQuery(query)).then(() => {
expect(store.getActions().map(a => a.type)).toEqual(
expectedActionTypes,
);
});
});
it('calls queryFailed on fetch error', () => {
expect.assertions(1);
fetchMock.post(
runQueryEndpoint,
{ throws: { message: 'error text' } },
{ overwriteRoutes: true },
);
const store = mockStore({});
const expectedActionTypes = [actions.START_QUERY, actions.QUERY_FAILED];
return store.dispatch(actions.runQuery(query)).then(() => {
expect(store.getActions().map(a => a.type)).toEqual(
expectedActionTypes,
);
});
});
});
describe('runQuery with query params', () => {
const { location } = window;
beforeAll(() => {
delete window.location;
window.location = new URL('http://localhost/sqllab/?foo=bar');
});
afterAll(() => {
delete window.location;
window.location = location;
});
const makeRequest = () => {
const request = actions.runQuery(query);
return request(dispatch);
};
it('makes the fetch request', () =>
makeRequest().then(() => {
expect(
fetchMock.calls('glob:*/superset/sql_json/?foo=bar'),
).toHaveLength(1);
}));
});
describe('reRunQuery', () => {
let stub;
beforeEach(() => {
stub = sinon.stub(shortid, 'generate').returns('abcd');
});
afterEach(() => {
stub.restore();
});
it('creates new query with a new id', () => {
const id = 'id';
const state = {
sqlLab: {
tabHistory: [id],
queryEditors: [{ id, title: 'Dummy query editor' }],
},
};
const store = mockStore(state);
store.dispatch(actions.reRunQuery(query));
expect(store.getActions()[0].query.id).toEqual('abcd');
});
});
describe('postStopQuery', () => {
const stopQueryEndpoint = 'glob:*/superset/stop_query/*';
fetchMock.post(stopQueryEndpoint, {});
const makeRequest = () => {
const request = actions.postStopQuery(query);
return request(dispatch);
};
it('makes the fetch request', () => {
expect.assertions(1);
return makeRequest().then(() => {
expect(fetchMock.calls(stopQueryEndpoint)).toHaveLength(1);
});
});
it('calls stopQuery', () => {
expect.assertions(1);
return makeRequest().then(() => {
expect(dispatch.getCall(0).args[0].type).toBe(actions.STOP_QUERY);
});
});
it('sends the correct data', () => {
expect.assertions(1);
return makeRequest().then(() => {
const call = fetchMock.calls(stopQueryEndpoint)[0];
expect(call[1].body.get('client_id')).toBe(query.id);
});
});
});
describe('cloneQueryToNewTab', () => {
let stub;
beforeEach(() => {
stub = sinon.stub(shortid, 'generate').returns('abcd');
});
afterEach(() => {
stub.restore();
});
it('creates new query editor', () => {
expect.assertions(1);
const id = 'id';
const state = {
sqlLab: {
tabHistory: [id],
queryEditors: [{ id, title: 'Dummy query editor' }],
},
};
const store = mockStore(state);
const expectedActions = [
{
type: actions.ADD_QUERY_EDITOR,
queryEditor: {
title: 'Copy of Dummy query editor',
dbId: 1,
schema: null,
autorun: true,
sql: 'SELECT * FROM something',
queryLimit: undefined,
maxRow: undefined,
id: 'abcd',
},
},
];
return store
.dispatch(actions.cloneQueryToNewTab(query, true))
.then(() => {
expect(store.getActions()).toEqual(expectedActions);
});
});
});
describe('addQueryEditor', () => {
let stub;
beforeEach(() => {
stub = sinon.stub(shortid, 'generate').returns('abcd');
});
afterEach(() => {
stub.restore();
});
it('creates new query editor', () => {
expect.assertions(1);
const store = mockStore({});
const expectedActions = [
{
type: actions.ADD_QUERY_EDITOR,
queryEditor,
},
];
return store
.dispatch(actions.addQueryEditor(defaultQueryEditor))
.then(() => {
expect(store.getActions()).toEqual(expectedActions);
});
});
});
describe('backend sync', () => {
const updateTabStateEndpoint = 'glob:*/tabstateview/*';
fetchMock.put(updateTabStateEndpoint, {});
fetchMock.delete(updateTabStateEndpoint, {});
fetchMock.post(updateTabStateEndpoint, JSON.stringify({ id: 1 }));
const updateTableSchemaEndpoint = 'glob:*/tableschemaview/*';
fetchMock.put(updateTableSchemaEndpoint, {});
fetchMock.delete(updateTableSchemaEndpoint, {});
fetchMock.post(updateTableSchemaEndpoint, JSON.stringify({ id: 1 }));
const getTableMetadataEndpoint = 'glob:*/api/v1/database/*';
fetchMock.get(getTableMetadataEndpoint, {});
const getExtraTableMetadataEndpoint =
'glob:*/superset/extra_table_metadata/*';
fetchMock.get(getExtraTableMetadataEndpoint, {});
let isFeatureEnabledMock;
beforeEach(() => {
isFeatureEnabledMock = jest
.spyOn(featureFlags, 'isFeatureEnabled')
.mockImplementation(
feature => feature === 'SQLLAB_BACKEND_PERSISTENCE',
);
});
afterEach(() => {
isFeatureEnabledMock.mockRestore();
});
afterEach(fetchMock.resetHistory);
describe('querySuccess', () => {
it('updates the tab state in the backend', () => {
expect.assertions(2);
const store = mockStore({});
const results = { query: { sqlEditorId: 'abcd' } };
const expectedActions = [
{
type: actions.QUERY_SUCCESS,
query,
results,
},
];
return store.dispatch(actions.querySuccess(query, results)).then(() => {
expect(store.getActions()).toEqual(expectedActions);
expect(fetchMock.calls(updateTabStateEndpoint)).toHaveLength(1);
});
});
});
describe('fetchQueryResults', () => {
it('updates the tab state in the backend', () => {
expect.assertions(2);
const results = {
data: mockBigNumber,
query: { sqlEditorId: 'abcd' },
query_id: 'efgh',
};
fetchMock.get(fetchQueryEndpoint, JSON.stringify(results), {
overwriteRoutes: true,
});
const store = mockStore({});
const expectedActions = [
{
type: actions.REQUEST_QUERY_RESULTS,
query,
},
// missing below
{
type: actions.QUERY_SUCCESS,
query,
results,
},
];
return store.dispatch(actions.fetchQueryResults(query)).then(() => {
expect(store.getActions()).toEqual(expectedActions);
expect(fetchMock.calls(updateTabStateEndpoint)).toHaveLength(1);
});
});
});
describe('addQueryEditor', () => {
it('updates the tab state in the backend', () => {
expect.assertions(2);
const store = mockStore({});
const expectedActions = [
{
type: actions.ADD_QUERY_EDITOR,
queryEditor: { ...queryEditor, id: '1' },
},
];
return store.dispatch(actions.addQueryEditor(queryEditor)).then(() => {
expect(store.getActions()).toEqual(expectedActions);
expect(fetchMock.calls(updateTabStateEndpoint)).toHaveLength(1);
});
});
});
describe('setActiveQueryEditor', () => {
it('updates the tab state in the backend', () => {
expect.assertions(2);
const store = mockStore({});
const expectedActions = [
{
type: actions.SET_ACTIVE_QUERY_EDITOR,
queryEditor,
},
];
return store
.dispatch(actions.setActiveQueryEditor(queryEditor))
.then(() => {
expect(store.getActions()).toEqual(expectedActions);
expect(fetchMock.calls(updateTabStateEndpoint)).toHaveLength(1);
});
});
});
describe('removeQueryEditor', () => {
it('updates the tab state in the backend', () => {
expect.assertions(2);
const store = mockStore({});
const expectedActions = [
{
type: actions.REMOVE_QUERY_EDITOR,
queryEditor,
},
];
return store
.dispatch(actions.removeQueryEditor(queryEditor))
.then(() => {
expect(store.getActions()).toEqual(expectedActions);
expect(fetchMock.calls(updateTabStateEndpoint)).toHaveLength(1);
});
});
});
describe('queryEditorSetDb', () => {
it('updates the tab state in the backend', () => {
expect.assertions(2);
const dbId = 42;
const store = mockStore({});
const expectedActions = [
{
type: actions.QUERY_EDITOR_SETDB,
queryEditor,
dbId,
},
];
return store
.dispatch(actions.queryEditorSetDb(queryEditor, dbId))
.then(() => {
expect(store.getActions()).toEqual(expectedActions);
expect(fetchMock.calls(updateTabStateEndpoint)).toHaveLength(1);
});
});
});
describe('queryEditorSetSchema', () => {
it('updates the tab state in the backend', () => {
expect.assertions(2);
const schema = 'schema';
const store = mockStore({});
const expectedActions = [
{
type: actions.QUERY_EDITOR_SET_SCHEMA,
queryEditor,
schema,
},
];
return store
.dispatch(actions.queryEditorSetSchema(queryEditor, schema))
.then(() => {
expect(store.getActions()).toEqual(expectedActions);
expect(fetchMock.calls(updateTabStateEndpoint)).toHaveLength(1);
});
});
});
describe('queryEditorSetAutorun', () => {
it('updates the tab state in the backend', () => {
expect.assertions(2);
const autorun = true;
const store = mockStore({});
const expectedActions = [
{
type: actions.QUERY_EDITOR_SET_AUTORUN,
queryEditor,
autorun,
},
];
return store
.dispatch(actions.queryEditorSetAutorun(queryEditor, autorun))
.then(() => {
expect(store.getActions()).toEqual(expectedActions);
expect(fetchMock.calls(updateTabStateEndpoint)).toHaveLength(1);
});
});
});
describe('queryEditorSetTitle', () => {
it('updates the tab state in the backend', () => {
expect.assertions(2);
const title = 'title';
const store = mockStore({});
const expectedActions = [
{
type: actions.QUERY_EDITOR_SET_TITLE,
queryEditor,
title,
},
];
return store
.dispatch(actions.queryEditorSetTitle(queryEditor, title))
.then(() => {
expect(store.getActions()).toEqual(expectedActions);
expect(fetchMock.calls(updateTabStateEndpoint)).toHaveLength(1);
});
});
});
describe('queryEditorSetSql', () => {
const sql = 'SELECT * ';
const expectedActions = [
{
type: actions.QUERY_EDITOR_SET_SQL,
queryEditor,
sql,
},
];
describe('with backend persistence flag on', () => {
it('updates the tab state in the backend', () => {
expect.assertions(2);
const store = mockStore({});
return store
.dispatch(actions.queryEditorSetSql(queryEditor, sql))
.then(() => {
expect(store.getActions()).toEqual(expectedActions);
expect(fetchMock.calls(updateTabStateEndpoint)).toHaveLength(1);
});
});
});
describe('with backend persistence flag off', () => {
it('does not update the tab state in the backend', () => {
const backendPersistenceOffMock = jest
.spyOn(featureFlags, 'isFeatureEnabled')
.mockImplementation(
feature => !(feature === 'SQLLAB_BACKEND_PERSISTENCE'),
);
const store = mockStore({});
store.dispatch(actions.queryEditorSetSql(queryEditor, sql));
expect(store.getActions()).toEqual(expectedActions);
expect(fetchMock.calls(updateTabStateEndpoint)).toHaveLength(0);
backendPersistenceOffMock.mockRestore();
});
});
});
describe('queryEditorSetQueryLimit', () => {
it('updates the tab state in the backend', () => {
expect.assertions(2);
const queryLimit = 10;
const store = mockStore({});
const expectedActions = [
{
type: actions.QUERY_EDITOR_SET_QUERY_LIMIT,
queryEditor,
queryLimit,
},
];
return store
.dispatch(actions.queryEditorSetQueryLimit(queryEditor, queryLimit))
.then(() => {
expect(store.getActions()).toEqual(expectedActions);
expect(fetchMock.calls(updateTabStateEndpoint)).toHaveLength(1);
});
});
});
describe('queryEditorSetTemplateParams', () => {
it('updates the tab state in the backend', () => {
expect.assertions(2);
const templateParams = '{"foo": "bar"}';
const store = mockStore({});
const expectedActions = [
{
type: actions.QUERY_EDITOR_SET_TEMPLATE_PARAMS,
queryEditor,
templateParams,
},
];
return store
.dispatch(
actions.queryEditorSetTemplateParams(queryEditor, templateParams),
)
.then(() => {
expect(store.getActions()).toEqual(expectedActions);
expect(fetchMock.calls(updateTabStateEndpoint)).toHaveLength(1);
});
});
});
describe('addTable', () => {
it('updates the table schema state in the backend', () => {
expect.assertions(5);
const database = { disable_data_preview: true };
const tableName = 'table';
const schemaName = 'schema';
const store = mockStore({});
const expectedActionTypes = [
actions.MERGE_TABLE, // addTable
actions.MERGE_TABLE, // getTableMetadata
actions.MERGE_TABLE, // getTableExtendedMetadata
actions.MERGE_TABLE, // addTable
];
return store
.dispatch(actions.addTable(query, database, tableName, schemaName))
.then(() => {
expect(store.getActions().map(a => a.type)).toEqual(
expectedActionTypes,
);
expect(fetchMock.calls(updateTableSchemaEndpoint)).toHaveLength(1);
expect(fetchMock.calls(getTableMetadataEndpoint)).toHaveLength(1);
expect(fetchMock.calls(getExtraTableMetadataEndpoint)).toHaveLength(
1,
);
// tab state is not updated, since no query was run
expect(fetchMock.calls(updateTabStateEndpoint)).toHaveLength(0);
});
});
it('updates and runs data preview query when configured', () => {
expect.assertions(5);
const results = {
data: mockBigNumber,
query: { sqlEditorId: 'null', dbId: 1 },
query_id: 'efgh',
};
fetchMock.post(runQueryEndpoint, JSON.stringify(results), {
overwriteRoutes: true,
});
const database = { disable_data_preview: false, id: 1 };
const tableName = 'table';
const schemaName = 'schema';
const store = mockStore({});
const expectedActionTypes = [
actions.MERGE_TABLE, // addTable
actions.MERGE_TABLE, // getTableMetadata
actions.MERGE_TABLE, // getTableExtendedMetadata
actions.MERGE_TABLE, // addTable (data preview)
actions.START_QUERY, // runQuery (data preview)
actions.MERGE_TABLE, // addTable
actions.QUERY_SUCCESS, // querySuccess
];
return store
.dispatch(actions.addTable(query, database, tableName, schemaName))
.then(() => {
expect(store.getActions().map(a => a.type)).toEqual(
expectedActionTypes,
);
expect(fetchMock.calls(updateTableSchemaEndpoint)).toHaveLength(1);
expect(fetchMock.calls(getTableMetadataEndpoint)).toHaveLength(1);
expect(fetchMock.calls(getExtraTableMetadataEndpoint)).toHaveLength(
1,
);
// tab state is not updated, since the query is a data preview
expect(fetchMock.calls(updateTabStateEndpoint)).toHaveLength(0);
});
});
});
describe('expandTable', () => {
it('updates the table schema state in the backend', () => {
expect.assertions(2);
const table = { id: 1 };
const store = mockStore({});
const expectedActions = [
{
type: actions.EXPAND_TABLE,
table,
},
];
return store.dispatch(actions.expandTable(table)).then(() => {
expect(store.getActions()).toEqual(expectedActions);
expect(fetchMock.calls(updateTableSchemaEndpoint)).toHaveLength(1);
});
});
});
describe('collapseTable', () => {
it('updates the table schema state in the backend', () => {
expect.assertions(2);
const table = { id: 1 };
const store = mockStore({});
const expectedActions = [
{
type: actions.COLLAPSE_TABLE,
table,
},
];
return store.dispatch(actions.collapseTable(table)).then(() => {
expect(store.getActions()).toEqual(expectedActions);
expect(fetchMock.calls(updateTableSchemaEndpoint)).toHaveLength(1);
});
});
});
describe('removeTable', () => {
it('updates the table schema state in the backend', () => {
expect.assertions(2);
const table = { id: 1 };
const store = mockStore({});
const expectedActions = [
{
type: actions.REMOVE_TABLE,
table,
},
];
return store.dispatch(actions.removeTable(table)).then(() => {
expect(store.getActions()).toEqual(expectedActions);
expect(fetchMock.calls(updateTableSchemaEndpoint)).toHaveLength(1);
});
});
});
describe('migrateQueryEditorFromLocalStorage', () => {
it('updates the tab state in the backend', () => {
expect.assertions(3);
const results = {
data: mockBigNumber,
query: { sqlEditorId: 'null' },
query_id: 'efgh',
};
fetchMock.post(runQueryEndpoint, JSON.stringify(results), {
overwriteRoutes: true,
});
const tables = [
{ id: 'one', dataPreviewQueryId: 'previewOne' },
{ id: 'two', dataPreviewQueryId: 'previewTwo' },
];
const queries = [
{ ...query, id: 'previewOne' },
{ ...query, id: 'previewTwo' },
];
const store = mockStore({});
const expectedActions = [
{
type: actions.MIGRATE_QUERY_EDITOR,
oldQueryEditor: queryEditor,
// new qe has a different id
newQueryEditor: { ...queryEditor, id: '1' },
},
{
type: actions.MIGRATE_TAB_HISTORY,
newId: '1',
oldId: 'abcd',
},
{
type: actions.MIGRATE_TABLE,
oldTable: tables[0],
// new table has a different id and points to new query editor
newTable: { ...tables[0], id: 1, queryEditorId: '1' },
},
{
type: actions.MIGRATE_TABLE,
oldTable: tables[1],
// new table has a different id and points to new query editor
newTable: { ...tables[1], id: 1, queryEditorId: '1' },
},
{
type: actions.MIGRATE_QUERY,
queryId: 'previewOne',
queryEditorId: '1',
},
{
type: actions.MIGRATE_QUERY,
queryId: 'previewTwo',
queryEditorId: '1',
},
];
return store
.dispatch(
actions.migrateQueryEditorFromLocalStorage(
queryEditor,
tables,
queries,
),
)
.then(() => {
expect(store.getActions()).toEqual(expectedActions);
expect(fetchMock.calls(updateTabStateEndpoint)).toHaveLength(3);
// query editor has 2 tables loaded in the schema viewer
expect(fetchMock.calls(updateTableSchemaEndpoint)).toHaveLength(2);
});
});
});
});
});
| superset-frontend/src/SqlLab/actions/sqlLab.test.js | 1 | https://github.com/apache/superset/commit/4669b6ce11dd74e5d1020a1f124e8696b801d730 | [
0.9987233281135559,
0.0636831745505333,
0.0001651663624215871,
0.00017198198474943638,
0.2415347844362259
] |
{
"id": 2,
"code_window": [
"\n",
" describe('addTable', () => {\n",
" it('updates the table schema state in the backend', () => {\n",
" expect.assertions(5);\n",
"\n",
" const database = { disable_data_preview: true };\n",
" const tableName = 'table';\n",
" const schemaName = 'schema';\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect.assertions(6);\n"
],
"file_path": "superset-frontend/src/SqlLab/actions/sqlLab.test.js",
"type": "replace",
"edit_start_line_idx": 727
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
"""Add columns for external management
Revision ID: 5fd49410a97a
Revises: c53bae8f08dd
Create Date: 2022-01-19 07:34:20.594786
"""
# revision identifiers, used by Alembic.
revision = "5fd49410a97a"
down_revision = "c53bae8f08dd"
import sqlalchemy as sa
from alembic import op
def upgrade():
with op.batch_alter_table("dashboards") as batch_op:
batch_op.add_column(
sa.Column(
"is_managed_externally",
sa.Boolean(),
nullable=False,
server_default=sa.false(),
)
)
batch_op.add_column(sa.Column("external_url", sa.Text(), nullable=True))
with op.batch_alter_table("datasources") as batch_op:
batch_op.add_column(
sa.Column(
"is_managed_externally",
sa.Boolean(),
nullable=False,
server_default=sa.false(),
)
)
batch_op.add_column(sa.Column("external_url", sa.Text(), nullable=True))
with op.batch_alter_table("dbs") as batch_op:
batch_op.add_column(
sa.Column(
"is_managed_externally",
sa.Boolean(),
nullable=False,
server_default=sa.false(),
)
)
batch_op.add_column(sa.Column("external_url", sa.Text(), nullable=True))
with op.batch_alter_table("slices") as batch_op:
batch_op.add_column(
sa.Column(
"is_managed_externally",
sa.Boolean(),
nullable=False,
server_default=sa.false(),
)
)
batch_op.add_column(sa.Column("external_url", sa.Text(), nullable=True))
with op.batch_alter_table("tables") as batch_op:
batch_op.add_column(
sa.Column(
"is_managed_externally",
sa.Boolean(),
nullable=False,
server_default=sa.false(),
)
)
batch_op.add_column(sa.Column("external_url", sa.Text(), nullable=True))
def downgrade():
with op.batch_alter_table("tables") as batch_op:
batch_op.drop_column("external_url")
batch_op.drop_column("is_managed_externally")
with op.batch_alter_table("slices") as batch_op:
batch_op.drop_column("external_url")
batch_op.drop_column("is_managed_externally")
with op.batch_alter_table("dbs") as batch_op:
batch_op.drop_column("external_url")
batch_op.drop_column("is_managed_externally")
with op.batch_alter_table("datasources") as batch_op:
batch_op.drop_column("external_url")
batch_op.drop_column("is_managed_externally")
with op.batch_alter_table("dashboards") as batch_op:
batch_op.drop_column("external_url")
batch_op.drop_column("is_managed_externally")
| superset/migrations/versions/5fd49410a97a_add_columns_for_external_management.py | 0 | https://github.com/apache/superset/commit/4669b6ce11dd74e5d1020a1f124e8696b801d730 | [
0.00017686450155451894,
0.00017286452930420637,
0.00016715662786737084,
0.00017324520740658045,
0.000002920282440754818
] |
{
"id": 2,
"code_window": [
"\n",
" describe('addTable', () => {\n",
" it('updates the table schema state in the backend', () => {\n",
" expect.assertions(5);\n",
"\n",
" const database = { disable_data_preview: true };\n",
" const tableName = 'table';\n",
" const schemaName = 'schema';\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect.assertions(6);\n"
],
"file_path": "superset-frontend/src/SqlLab/actions/sqlLab.test.js",
"type": "replace",
"edit_start_line_idx": 727
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
import logging
import random
import string
from typing import Any, Dict, List, Optional, Tuple
from sqlalchemy import func
from superset import appbuilder, db, security_manager
from superset.connectors.sqla.models import SqlaTable
from superset.models.dashboard import Dashboard
from superset.models.slice import Slice
from tests.integration_tests.dashboards.consts import DEFAULT_DASHBOARD_SLUG_TO_TEST
logger = logging.getLogger(__name__)
session = appbuilder.get_session
def get_mock_positions(dashboard: Dashboard) -> Dict[str, Any]:
positions = {"DASHBOARD_VERSION_KEY": "v2"}
for i, slc in enumerate(dashboard.slices):
id_ = "DASHBOARD_CHART_TYPE-{}".format(i)
position_data: Any = {
"type": "CHART",
"id": id_,
"children": [],
"meta": {"width": 4, "height": 50, "chartId": slc.id},
}
positions[id_] = position_data
return positions
def build_save_dash_parts(
dashboard_slug: Optional[str] = None, dashboard_to_edit: Optional[Dashboard] = None
) -> Tuple[Dashboard, Dict[str, Any], Dict[str, Any]]:
if not dashboard_to_edit:
dashboard_slug = (
dashboard_slug if dashboard_slug else DEFAULT_DASHBOARD_SLUG_TO_TEST
)
dashboard_to_edit = get_dashboard_by_slug(dashboard_slug)
data_before_change = {
"positions": dashboard_to_edit.position,
"dashboard_title": dashboard_to_edit.dashboard_title,
}
data_after_change = {
"css": "",
"expanded_slices": {},
"positions": get_mock_positions(dashboard_to_edit),
"dashboard_title": dashboard_to_edit.dashboard_title,
}
return dashboard_to_edit, data_before_change, data_after_change
def get_all_dashboards() -> List[Dashboard]:
return db.session.query(Dashboard).all()
def get_dashboard_by_slug(dashboard_slug: str) -> Dashboard:
return db.session.query(Dashboard).filter_by(slug=dashboard_slug).first()
def get_slice_by_name(slice_name: str) -> Slice:
return db.session.query(Slice).filter_by(slice_name=slice_name).first()
def get_sql_table_by_name(table_name: str):
return db.session.query(SqlaTable).filter_by(table_name=table_name).one()
def count_dashboards() -> int:
return db.session.query(func.count(Dashboard.id)).first()[0]
def random_title():
return f"title{random_str()}"
def random_slug():
return f"slug{random_str()}"
def get_random_string(length):
letters = string.ascii_lowercase
result_str = "".join(random.choice(letters) for i in range(length))
print("Random string of length", length, "is:", result_str)
return result_str
def random_str():
return get_random_string(8)
def grant_access_to_dashboard(dashboard, role_name):
role = security_manager.find_role(role_name)
dashboard.roles.append(role)
db.session.merge(dashboard)
db.session.commit()
def revoke_access_to_dashboard(dashboard, role_name):
role = security_manager.find_role(role_name)
dashboard.roles.remove(role)
db.session.merge(dashboard)
db.session.commit()
| tests/integration_tests/dashboards/dashboard_test_utils.py | 0 | https://github.com/apache/superset/commit/4669b6ce11dd74e5d1020a1f124e8696b801d730 | [
0.0008347275434061885,
0.00022397538123186678,
0.00016690501070115715,
0.00017432827735319734,
0.00017634726827964187
] |
{
"id": 2,
"code_window": [
"\n",
" describe('addTable', () => {\n",
" it('updates the table schema state in the backend', () => {\n",
" expect.assertions(5);\n",
"\n",
" const database = { disable_data_preview: true };\n",
" const tableName = 'table';\n",
" const schemaName = 'schema';\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect.assertions(6);\n"
],
"file_path": "superset-frontend/src/SqlLab/actions/sqlLab.test.js",
"type": "replace",
"edit_start_line_idx": 727
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
"""empty message
Revision ID: d6db5a5cdb5d
Revises: ('a99f2f7c195a', 'bcf3126872fc')
Create Date: 2017-02-10 17:58:20.149960
"""
# revision identifiers, used by Alembic.
revision = "d6db5a5cdb5d"
down_revision = ("a99f2f7c195a", "bcf3126872fc")
import sqlalchemy as sa
from alembic import op
def upgrade():
pass
def downgrade():
pass
| superset/migrations/versions/d6db5a5cdb5d_.py | 0 | https://github.com/apache/superset/commit/4669b6ce11dd74e5d1020a1f124e8696b801d730 | [
0.0001768402144080028,
0.00017278378072660416,
0.0001688609627308324,
0.00017271697288379073,
0.000002843525408025016
] |
{
"id": 3,
"code_window": [
" .dispatch(actions.addTable(query, database, tableName, schemaName))\n",
" .then(() => {\n",
" expect(store.getActions().map(a => a.type)).toEqual(\n",
" expectedActionTypes,\n",
" );\n",
" expect(fetchMock.calls(updateTableSchemaEndpoint)).toHaveLength(1);\n",
" expect(fetchMock.calls(getTableMetadataEndpoint)).toHaveLength(1);\n",
" expect(fetchMock.calls(getExtraTableMetadataEndpoint)).toHaveLength(\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(store.getActions()[0].prepend).toBeTruthy();\n"
],
"file_path": "superset-frontend/src/SqlLab/actions/sqlLab.test.js",
"type": "add",
"edit_start_line_idx": 745
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
import shortid from 'shortid';
import JSONbig from 'json-bigint';
import { t, SupersetClient } from '@superset-ui/core';
import invert from 'lodash/invert';
import mapKeys from 'lodash/mapKeys';
import { isFeatureEnabled, FeatureFlag } from 'src/featureFlags';
import { now } from 'src/modules/dates';
import {
addDangerToast as addDangerToastAction,
addInfoToast as addInfoToastAction,
addSuccessToast as addSuccessToastAction,
addWarningToast as addWarningToastAction,
} from 'src/components/MessageToasts/actions';
import { getClientErrorObject } from 'src/utils/getClientErrorObject';
import COMMON_ERR_MESSAGES from 'src/utils/errorMessages';
export const RESET_STATE = 'RESET_STATE';
export const ADD_QUERY_EDITOR = 'ADD_QUERY_EDITOR';
export const UPDATE_QUERY_EDITOR = 'UPDATE_QUERY_EDITOR';
export const QUERY_EDITOR_SAVED = 'QUERY_EDITOR_SAVED';
export const CLONE_QUERY_TO_NEW_TAB = 'CLONE_QUERY_TO_NEW_TAB';
export const REMOVE_QUERY_EDITOR = 'REMOVE_QUERY_EDITOR';
export const MERGE_TABLE = 'MERGE_TABLE';
export const REMOVE_TABLE = 'REMOVE_TABLE';
export const END_QUERY = 'END_QUERY';
export const REMOVE_QUERY = 'REMOVE_QUERY';
export const EXPAND_TABLE = 'EXPAND_TABLE';
export const COLLAPSE_TABLE = 'COLLAPSE_TABLE';
export const QUERY_EDITOR_SETDB = 'QUERY_EDITOR_SETDB';
export const QUERY_EDITOR_SET_SCHEMA = 'QUERY_EDITOR_SET_SCHEMA';
export const QUERY_EDITOR_SET_SCHEMA_OPTIONS =
'QUERY_EDITOR_SET_SCHEMA_OPTIONS';
export const QUERY_EDITOR_SET_TABLE_OPTIONS = 'QUERY_EDITOR_SET_TABLE_OPTIONS';
export const QUERY_EDITOR_SET_TITLE = 'QUERY_EDITOR_SET_TITLE';
export const QUERY_EDITOR_SET_AUTORUN = 'QUERY_EDITOR_SET_AUTORUN';
export const QUERY_EDITOR_SET_SQL = 'QUERY_EDITOR_SET_SQL';
export const QUERY_EDITOR_SET_QUERY_LIMIT = 'QUERY_EDITOR_SET_QUERY_LIMIT';
export const QUERY_EDITOR_SET_TEMPLATE_PARAMS =
'QUERY_EDITOR_SET_TEMPLATE_PARAMS';
export const QUERY_EDITOR_SET_SELECTED_TEXT = 'QUERY_EDITOR_SET_SELECTED_TEXT';
export const QUERY_EDITOR_SET_FUNCTION_NAMES =
'QUERY_EDITOR_SET_FUNCTION_NAMES';
export const QUERY_EDITOR_PERSIST_HEIGHT = 'QUERY_EDITOR_PERSIST_HEIGHT';
export const QUERY_EDITOR_TOGGLE_LEFT_BAR = 'QUERY_EDITOR_TOGGLE_LEFT_BAR';
export const MIGRATE_QUERY_EDITOR = 'MIGRATE_QUERY_EDITOR';
export const MIGRATE_TAB_HISTORY = 'MIGRATE_TAB_HISTORY';
export const MIGRATE_TABLE = 'MIGRATE_TABLE';
export const MIGRATE_QUERY = 'MIGRATE_QUERY';
export const SET_DATABASES = 'SET_DATABASES';
export const SET_ACTIVE_QUERY_EDITOR = 'SET_ACTIVE_QUERY_EDITOR';
export const LOAD_QUERY_EDITOR = 'LOAD_QUERY_EDITOR';
export const SET_TABLES = 'SET_TABLES';
export const SET_ACTIVE_SOUTHPANE_TAB = 'SET_ACTIVE_SOUTHPANE_TAB';
export const REFRESH_QUERIES = 'REFRESH_QUERIES';
export const SET_USER_OFFLINE = 'SET_USER_OFFLINE';
export const RUN_QUERY = 'RUN_QUERY';
export const START_QUERY = 'START_QUERY';
export const STOP_QUERY = 'STOP_QUERY';
export const REQUEST_QUERY_RESULTS = 'REQUEST_QUERY_RESULTS';
export const QUERY_SUCCESS = 'QUERY_SUCCESS';
export const QUERY_FAILED = 'QUERY_FAILED';
export const CLEAR_QUERY_RESULTS = 'CLEAR_QUERY_RESULTS';
export const REMOVE_DATA_PREVIEW = 'REMOVE_DATA_PREVIEW';
export const CHANGE_DATA_PREVIEW_ID = 'CHANGE_DATA_PREVIEW_ID';
export const START_QUERY_VALIDATION = 'START_QUERY_VALIDATION';
export const QUERY_VALIDATION_RETURNED = 'QUERY_VALIDATION_RETURNED';
export const QUERY_VALIDATION_FAILED = 'QUERY_VALIDATION_FAILED';
export const COST_ESTIMATE_STARTED = 'COST_ESTIMATE_STARTED';
export const COST_ESTIMATE_RETURNED = 'COST_ESTIMATE_RETURNED';
export const COST_ESTIMATE_FAILED = 'COST_ESTIMATE_FAILED';
export const CREATE_DATASOURCE_STARTED = 'CREATE_DATASOURCE_STARTED';
export const CREATE_DATASOURCE_SUCCESS = 'CREATE_DATASOURCE_SUCCESS';
export const CREATE_DATASOURCE_FAILED = 'CREATE_DATASOURCE_FAILED';
export const addInfoToast = addInfoToastAction;
export const addSuccessToast = addSuccessToastAction;
export const addDangerToast = addDangerToastAction;
export const addWarningToast = addWarningToastAction;
export const CtasEnum = {
TABLE: 'TABLE',
VIEW: 'VIEW',
};
const ERR_MSG_CANT_LOAD_QUERY = t("The query couldn't be loaded");
// a map of SavedQuery field names to the different names used client-side,
// because for now making the names consistent is too complicated
// so it might as well only happen in one place
const queryClientMapping = {
id: 'remoteId',
db_id: 'dbId',
client_id: 'id',
label: 'title',
};
const queryServerMapping = invert(queryClientMapping);
// uses a mapping like those above to convert object key names to another style
const fieldConverter = mapping => obj =>
mapKeys(obj, (value, key) => (key in mapping ? mapping[key] : key));
const convertQueryToServer = fieldConverter(queryServerMapping);
const convertQueryToClient = fieldConverter(queryClientMapping);
export function resetState() {
return { type: RESET_STATE };
}
export function startQueryValidation(query) {
Object.assign(query, {
id: query.id ? query.id : shortid.generate(),
});
return { type: START_QUERY_VALIDATION, query };
}
export function queryValidationReturned(query, results) {
return { type: QUERY_VALIDATION_RETURNED, query, results };
}
export function queryValidationFailed(query, message, error) {
return { type: QUERY_VALIDATION_FAILED, query, message, error };
}
export function updateQueryEditor(alterations) {
return { type: UPDATE_QUERY_EDITOR, alterations };
}
export function scheduleQuery(query) {
return dispatch =>
SupersetClient.post({
endpoint: '/savedqueryviewapi/api/create',
postPayload: query,
stringify: false,
})
.then(() =>
dispatch(
addSuccessToast(
t(
'Your query has been scheduled. To see details of your query, navigate to Saved queries',
),
),
),
)
.catch(() =>
dispatch(addDangerToast(t('Your query could not be scheduled'))),
);
}
export function estimateQueryCost(query) {
const { dbId, schema, sql, templateParams } = query;
const endpoint =
schema === null
? `/superset/estimate_query_cost/${dbId}/`
: `/superset/estimate_query_cost/${dbId}/${schema}/`;
return dispatch =>
Promise.all([
dispatch({ type: COST_ESTIMATE_STARTED, query }),
SupersetClient.post({
endpoint,
postPayload: {
sql,
templateParams: JSON.parse(templateParams || '{}'),
},
})
.then(({ json }) =>
dispatch({ type: COST_ESTIMATE_RETURNED, query, json }),
)
.catch(response =>
getClientErrorObject(response).then(error => {
const message =
error.error ||
error.statusText ||
t('Failed at retrieving results');
return dispatch({
type: COST_ESTIMATE_FAILED,
query,
error: message,
});
}),
),
]);
}
export function startQuery(query) {
Object.assign(query, {
id: query.id ? query.id : shortid.generate(),
progress: 0,
startDttm: now(),
state: query.runAsync ? 'pending' : 'running',
cached: false,
});
return { type: START_QUERY, query };
}
export function querySuccess(query, results) {
return function (dispatch) {
const sync =
!query.isDataPreview &&
isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)
? SupersetClient.put({
endpoint: encodeURI(`/tabstateview/${results.query.sqlEditorId}`),
postPayload: { latest_query_id: query.id },
})
: Promise.resolve();
return sync
.then(() => dispatch({ type: QUERY_SUCCESS, query, results }))
.catch(() =>
dispatch(
addDangerToast(
t(
'An error occurred while storing the latest query id in the backend. ' +
'Please contact your administrator if this problem persists.',
),
),
),
);
};
}
export function queryFailed(query, msg, link, errors) {
return function (dispatch) {
const sync =
!query.isDataPreview &&
isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)
? SupersetClient.put({
endpoint: encodeURI(`/tabstateview/${query.sqlEditorId}`),
postPayload: { latest_query_id: query.id },
})
: Promise.resolve();
return (
sync
.catch(() =>
dispatch(
addDangerToast(
t(
'An error occurred while storing the latest query id in the backend. ' +
'Please contact your administrator if this problem persists.',
),
),
),
)
// We should always show the error message, even if we couldn't sync the
// state to the backend
.then(() => dispatch({ type: QUERY_FAILED, query, msg, link, errors }))
);
};
}
export function stopQuery(query) {
return { type: STOP_QUERY, query };
}
export function clearQueryResults(query) {
return { type: CLEAR_QUERY_RESULTS, query };
}
export function removeDataPreview(table) {
return { type: REMOVE_DATA_PREVIEW, table };
}
export function requestQueryResults(query) {
return { type: REQUEST_QUERY_RESULTS, query };
}
export function fetchQueryResults(query, displayLimit) {
return function (dispatch) {
dispatch(requestQueryResults(query));
return SupersetClient.get({
endpoint: `/superset/results/${query.resultsKey}/?rows=${displayLimit}`,
parseMethod: 'text',
})
.then(({ text = '{}' }) => {
const bigIntJson = JSONbig.parse(text);
return dispatch(querySuccess(query, bigIntJson));
})
.catch(response =>
getClientErrorObject(response).then(error => {
const message =
error.error ||
error.statusText ||
t('Failed at retrieving results');
return dispatch(
queryFailed(query, message, error.link, error.errors),
);
}),
);
};
}
export function runQuery(query) {
return function (dispatch) {
dispatch(startQuery(query));
const postPayload = {
client_id: query.id,
database_id: query.dbId,
json: true,
runAsync: query.runAsync,
schema: query.schema,
sql: query.sql,
sql_editor_id: query.sqlEditorId,
tab: query.tab,
tmp_table_name: query.tempTable,
select_as_cta: query.ctas,
ctas_method: query.ctas_method,
templateParams: query.templateParams,
queryLimit: query.queryLimit,
expand_data: true,
};
const search = window.location.search || '';
return SupersetClient.post({
endpoint: `/superset/sql_json/${search}`,
body: JSON.stringify(postPayload),
headers: { 'Content-Type': 'application/json' },
parseMethod: 'text',
})
.then(({ text = '{}' }) => {
if (!query.runAsync) {
const bigIntJson = JSONbig.parse(text);
dispatch(querySuccess(query, bigIntJson));
}
})
.catch(response =>
getClientErrorObject(response).then(error => {
let message = error.error || error.statusText || t('Unknown error');
if (message.includes('CSRF token')) {
message = t(COMMON_ERR_MESSAGES.SESSION_TIMED_OUT);
}
dispatch(queryFailed(query, message, error.link, error.errors));
}),
);
};
}
export function reRunQuery(query) {
// run Query with a new id
return function (dispatch) {
dispatch(runQuery({ ...query, id: shortid.generate() }));
};
}
export function validateQuery(query) {
return function (dispatch) {
dispatch(startQueryValidation(query));
const postPayload = {
client_id: query.id,
database_id: query.dbId,
json: true,
schema: query.schema,
sql: query.sql,
sql_editor_id: query.sqlEditorId,
templateParams: query.templateParams,
validate_only: true,
};
return SupersetClient.post({
endpoint: `/superset/validate_sql_json/${window.location.search}`,
postPayload,
stringify: false,
})
.then(({ json }) => dispatch(queryValidationReturned(query, json)))
.catch(response =>
getClientErrorObject(response).then(error => {
let message = error.error || error.statusText || t('Unknown error');
if (message.includes('CSRF token')) {
message = t(COMMON_ERR_MESSAGES.SESSION_TIMED_OUT);
}
dispatch(queryValidationFailed(query, message, error));
}),
);
};
}
export function postStopQuery(query) {
return function (dispatch) {
return SupersetClient.post({
endpoint: '/superset/stop_query/',
postPayload: { client_id: query.id },
stringify: false,
})
.then(() => dispatch(stopQuery(query)))
.then(() => dispatch(addSuccessToast(t('Query was stopped.'))))
.catch(() =>
dispatch(addDangerToast(t('Failed at stopping query. %s', query.id))),
);
};
}
export function setDatabases(databases) {
return { type: SET_DATABASES, databases };
}
function migrateTable(table, queryEditorId, dispatch) {
return SupersetClient.post({
endpoint: encodeURI('/tableschemaview/'),
postPayload: { table: { ...table, queryEditorId } },
})
.then(({ json }) => {
const newTable = {
...table,
id: json.id,
queryEditorId,
};
return dispatch({ type: MIGRATE_TABLE, oldTable: table, newTable });
})
.catch(() =>
dispatch(
addWarningToast(
t(
'Unable to migrate table schema state to backend. Superset will retry ' +
'later. Please contact your administrator if this problem persists.',
),
),
),
);
}
function migrateQuery(queryId, queryEditorId, dispatch) {
return SupersetClient.post({
endpoint: encodeURI(`/tabstateview/${queryEditorId}/migrate_query`),
postPayload: { queryId },
})
.then(() => dispatch({ type: MIGRATE_QUERY, queryId, queryEditorId }))
.catch(() =>
dispatch(
addWarningToast(
t(
'Unable to migrate query state to backend. Superset will retry later. ' +
'Please contact your administrator if this problem persists.',
),
),
),
);
}
export function migrateQueryEditorFromLocalStorage(
queryEditor,
tables,
queries,
) {
return function (dispatch) {
return SupersetClient.post({
endpoint: '/tabstateview/',
postPayload: { queryEditor },
})
.then(({ json }) => {
const newQueryEditor = {
...queryEditor,
id: json.id.toString(),
};
dispatch({
type: MIGRATE_QUERY_EDITOR,
oldQueryEditor: queryEditor,
newQueryEditor,
});
dispatch({
type: MIGRATE_TAB_HISTORY,
oldId: queryEditor.id,
newId: newQueryEditor.id,
});
return Promise.all([
...tables.map(table =>
migrateTable(table, newQueryEditor.id, dispatch),
),
...queries.map(query =>
migrateQuery(query.id, newQueryEditor.id, dispatch),
),
]);
})
.catch(() =>
dispatch(
addWarningToast(
t(
'Unable to migrate query editor state to backend. Superset will retry ' +
'later. Please contact your administrator if this problem persists.',
),
),
),
);
};
}
export function addQueryEditor(queryEditor) {
return function (dispatch) {
const sync = isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)
? SupersetClient.post({
endpoint: '/tabstateview/',
postPayload: { queryEditor },
})
: Promise.resolve({ json: { id: shortid.generate() } });
return sync
.then(({ json }) => {
const newQueryEditor = {
...queryEditor,
id: json.id.toString(),
};
return dispatch({
type: ADD_QUERY_EDITOR,
queryEditor: newQueryEditor,
});
})
.catch(() =>
dispatch(
addDangerToast(
t(
'Unable to add a new tab to the backend. Please contact your administrator.',
),
),
),
);
};
}
export function cloneQueryToNewTab(query, autorun) {
return function (dispatch, getState) {
const state = getState();
const { queryEditors, tabHistory } = state.sqlLab;
const sourceQueryEditor = queryEditors.find(
qe => qe.id === tabHistory[tabHistory.length - 1],
);
const queryEditor = {
title: t('Copy of %s', sourceQueryEditor.title),
dbId: query.dbId ? query.dbId : null,
schema: query.schema ? query.schema : null,
autorun,
sql: query.sql,
queryLimit: sourceQueryEditor.queryLimit,
maxRow: sourceQueryEditor.maxRow,
templateParams: sourceQueryEditor.templateParams,
};
return dispatch(addQueryEditor(queryEditor));
};
}
export function setActiveQueryEditor(queryEditor) {
return function (dispatch) {
const sync = isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)
? SupersetClient.post({
endpoint: encodeURI(`/tabstateview/${queryEditor.id}/activate`),
})
: Promise.resolve();
return sync
.then(() => dispatch({ type: SET_ACTIVE_QUERY_EDITOR, queryEditor }))
.catch(response => {
if (response.status !== 404) {
return dispatch(
addDangerToast(
t(
'An error occurred while setting the active tab. Please contact ' +
'your administrator.',
),
),
);
}
return dispatch({ type: REMOVE_QUERY_EDITOR, queryEditor });
});
};
}
export function loadQueryEditor(queryEditor) {
return { type: LOAD_QUERY_EDITOR, queryEditor };
}
export function setTables(tableSchemas) {
const tables = tableSchemas
.filter(tableSchema => tableSchema.description !== null)
.map(tableSchema => {
const {
columns,
selectStar,
primaryKey,
foreignKeys,
indexes,
dataPreviewQueryId,
} = tableSchema.description;
return {
dbId: tableSchema.database_id,
queryEditorId: tableSchema.tab_state_id.toString(),
schema: tableSchema.schema,
name: tableSchema.table,
expanded: tableSchema.expanded,
id: tableSchema.id,
dataPreviewQueryId,
columns,
selectStar,
primaryKey,
foreignKeys,
indexes,
isMetadataLoading: false,
isExtraMetadataLoading: false,
};
});
return { type: SET_TABLES, tables };
}
export function switchQueryEditor(queryEditor, displayLimit) {
return function (dispatch) {
if (
isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE) &&
!queryEditor.loaded
) {
SupersetClient.get({
endpoint: encodeURI(`/tabstateview/${queryEditor.id}`),
})
.then(({ json }) => {
const loadedQueryEditor = {
id: json.id.toString(),
loaded: true,
title: json.label,
sql: json.sql,
selectedText: null,
latestQueryId: json.latest_query?.id,
autorun: json.autorun,
dbId: json.database_id,
templateParams: json.template_params,
schema: json.schema,
queryLimit: json.query_limit,
remoteId: json.saved_query?.id,
validationResult: {
id: null,
errors: [],
completed: false,
},
hideLeftBar: json.hide_left_bar,
};
dispatch(loadQueryEditor(loadedQueryEditor));
dispatch(setTables(json.table_schemas || []));
dispatch(setActiveQueryEditor(loadedQueryEditor));
if (json.latest_query && json.latest_query.resultsKey) {
dispatch(fetchQueryResults(json.latest_query, displayLimit));
}
})
.catch(response => {
if (response.status !== 404) {
return dispatch(
addDangerToast(t('An error occurred while fetching tab state')),
);
}
return dispatch({ type: REMOVE_QUERY_EDITOR, queryEditor });
});
} else {
dispatch(setActiveQueryEditor(queryEditor));
}
};
}
export function setActiveSouthPaneTab(tabId) {
return { type: SET_ACTIVE_SOUTHPANE_TAB, tabId };
}
export function toggleLeftBar(queryEditor) {
const hideLeftBar = !queryEditor.hideLeftBar;
return function (dispatch) {
const sync = isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)
? SupersetClient.put({
endpoint: encodeURI(`/tabstateview/${queryEditor.id}`),
postPayload: { hide_left_bar: hideLeftBar },
})
: Promise.resolve();
return sync
.then(() =>
dispatch({
type: QUERY_EDITOR_TOGGLE_LEFT_BAR,
queryEditor,
hideLeftBar,
}),
)
.catch(() =>
dispatch(
addDangerToast(
t(
'An error occurred while hiding the left bar. Please contact your administrator.',
),
),
),
);
};
}
export function removeQueryEditor(queryEditor) {
return function (dispatch) {
const sync = isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)
? SupersetClient.delete({
endpoint: encodeURI(`/tabstateview/${queryEditor.id}`),
})
: Promise.resolve();
return sync
.then(() => dispatch({ type: REMOVE_QUERY_EDITOR, queryEditor }))
.catch(() =>
dispatch(
addDangerToast(
t(
'An error occurred while removing tab. Please contact your administrator.',
),
),
),
);
};
}
export function removeQuery(query) {
return function (dispatch) {
const sync = isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)
? SupersetClient.delete({
endpoint: encodeURI(
`/tabstateview/${query.sqlEditorId}/query/${query.id}`,
),
})
: Promise.resolve();
return sync
.then(() => dispatch({ type: REMOVE_QUERY, query }))
.catch(() =>
dispatch(
addDangerToast(
t(
'An error occurred while removing query. Please contact your administrator.',
),
),
),
);
};
}
export function queryEditorSetDb(queryEditor, dbId) {
return function (dispatch) {
const sync = isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)
? SupersetClient.put({
endpoint: encodeURI(`/tabstateview/${queryEditor.id}`),
postPayload: { database_id: dbId },
})
: Promise.resolve();
return sync
.then(() => dispatch({ type: QUERY_EDITOR_SETDB, queryEditor, dbId }))
.catch(() =>
dispatch(
addDangerToast(
t(
'An error occurred while setting the tab database ID. Please contact your administrator.',
),
),
),
);
};
}
export function queryEditorSetSchema(queryEditor, schema) {
return function (dispatch) {
const sync =
isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE) &&
typeof queryEditor === 'object'
? SupersetClient.put({
endpoint: encodeURI(`/tabstateview/${queryEditor.id}`),
postPayload: { schema },
})
: Promise.resolve();
return sync
.then(() =>
dispatch({
type: QUERY_EDITOR_SET_SCHEMA,
queryEditor: queryEditor || {},
schema: schema || {},
}),
)
.catch(() =>
dispatch(
addDangerToast(
t(
'An error occurred while setting the tab schema. Please contact your administrator.',
),
),
),
);
};
}
export function queryEditorSetSchemaOptions(queryEditor, options) {
return { type: QUERY_EDITOR_SET_SCHEMA_OPTIONS, queryEditor, options };
}
export function queryEditorSetTableOptions(queryEditor, options) {
return { type: QUERY_EDITOR_SET_TABLE_OPTIONS, queryEditor, options };
}
export function queryEditorSetAutorun(queryEditor, autorun) {
return function (dispatch) {
const sync = isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)
? SupersetClient.put({
endpoint: encodeURI(`/tabstateview/${queryEditor.id}`),
postPayload: { autorun },
})
: Promise.resolve();
return sync
.then(() =>
dispatch({ type: QUERY_EDITOR_SET_AUTORUN, queryEditor, autorun }),
)
.catch(() =>
dispatch(
addDangerToast(
t(
'An error occurred while setting the tab autorun. Please contact your administrator.',
),
),
),
);
};
}
export function queryEditorSetTitle(queryEditor, title) {
return function (dispatch) {
const sync = isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)
? SupersetClient.put({
endpoint: encodeURI(`/tabstateview/${queryEditor.id}`),
postPayload: { label: title },
})
: Promise.resolve();
return sync
.then(() =>
dispatch({ type: QUERY_EDITOR_SET_TITLE, queryEditor, title }),
)
.catch(() =>
dispatch(
addDangerToast(
t(
'An error occurred while setting the tab title. Please contact your administrator.',
),
),
),
);
};
}
export function saveQuery(query) {
return dispatch =>
SupersetClient.post({
endpoint: '/savedqueryviewapi/api/create',
postPayload: convertQueryToServer(query),
stringify: false,
})
.then(result => {
const savedQuery = convertQueryToClient(result.json.item);
dispatch({
type: QUERY_EDITOR_SAVED,
query,
result: savedQuery,
});
dispatch(queryEditorSetTitle(query, query.title));
return savedQuery;
})
.catch(() =>
dispatch(addDangerToast(t('Your query could not be saved'))),
);
}
export const addSavedQueryToTabState =
(queryEditor, savedQuery) => dispatch => {
const sync = isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)
? SupersetClient.put({
endpoint: `/tabstateview/${queryEditor.id}`,
postPayload: { saved_query_id: savedQuery.remoteId },
})
: Promise.resolve();
return sync
.catch(() => {
dispatch(addDangerToast(t('Your query was not properly saved')));
})
.then(() => {
dispatch(addSuccessToast(t('Your query was saved')));
});
};
export function updateSavedQuery(query) {
return dispatch =>
SupersetClient.put({
endpoint: `/savedqueryviewapi/api/update/${query.remoteId}`,
postPayload: convertQueryToServer(query),
stringify: false,
})
.then(() => {
dispatch(addSuccessToast(t('Your query was updated')));
dispatch(queryEditorSetTitle(query, query.title));
})
.catch(() =>
dispatch(addDangerToast(t('Your query could not be updated'))),
)
.then(() => dispatch(updateQueryEditor(query)));
}
export function queryEditorSetSql(queryEditor, sql) {
return function (dispatch) {
// saved query and set tab state use this action
dispatch({ type: QUERY_EDITOR_SET_SQL, queryEditor, sql });
if (isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)) {
return SupersetClient.put({
endpoint: encodeURI(`/tabstateview/${queryEditor.id}`),
postPayload: { sql, latest_query_id: queryEditor.latestQueryId },
}).catch(() =>
dispatch(
addDangerToast(
t(
'An error occurred while storing your query in the backend. To ' +
'avoid losing your changes, please save your query using the ' +
'"Save Query" button.',
),
),
),
);
}
return Promise.resolve();
};
}
export function queryEditorSetQueryLimit(queryEditor, queryLimit) {
return function (dispatch) {
const sync = isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)
? SupersetClient.put({
endpoint: encodeURI(`/tabstateview/${queryEditor.id}`),
postPayload: { query_limit: queryLimit },
})
: Promise.resolve();
return sync
.then(() =>
dispatch({
type: QUERY_EDITOR_SET_QUERY_LIMIT,
queryEditor,
queryLimit,
}),
)
.catch(() =>
dispatch(
addDangerToast(
t(
'An error occurred while setting the tab title. Please contact your administrator.',
),
),
),
);
};
}
export function queryEditorSetTemplateParams(queryEditor, templateParams) {
return function (dispatch) {
dispatch({
type: QUERY_EDITOR_SET_TEMPLATE_PARAMS,
queryEditor,
templateParams,
});
const sync = isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)
? SupersetClient.put({
endpoint: encodeURI(`/tabstateview/${queryEditor.id}`),
postPayload: { template_params: templateParams },
})
: Promise.resolve();
return sync.catch(() =>
dispatch(
addDangerToast(
t(
'An error occurred while setting the tab template parameters. ' +
'Please contact your administrator.',
),
),
),
);
};
}
export function queryEditorSetSelectedText(queryEditor, sql) {
return { type: QUERY_EDITOR_SET_SELECTED_TEXT, queryEditor, sql };
}
export function mergeTable(table, query) {
return { type: MERGE_TABLE, table, query };
}
function getTableMetadata(table, query, dispatch) {
return SupersetClient.get({
endpoint: encodeURI(
`/api/v1/database/${query.dbId}/table/${encodeURIComponent(
table.name,
)}/${encodeURIComponent(table.schema)}/`,
),
})
.then(({ json }) => {
const newTable = {
...table,
...json,
expanded: true,
isMetadataLoading: false,
};
dispatch(mergeTable(newTable)); // Merge table to tables in state
return newTable;
})
.catch(() =>
Promise.all([
dispatch(
mergeTable({
...table,
isMetadataLoading: false,
}),
),
dispatch(
addDangerToast(t('An error occurred while fetching table metadata')),
),
]),
);
}
function getTableExtendedMetadata(table, query, dispatch) {
return SupersetClient.get({
endpoint: encodeURI(
`/superset/extra_table_metadata/${query.dbId}/` +
`${encodeURIComponent(table.name)}/${encodeURIComponent(
table.schema,
)}/`,
),
})
.then(({ json }) => {
dispatch(
mergeTable({ ...table, ...json, isExtraMetadataLoading: false }),
);
return json;
})
.catch(() =>
Promise.all([
dispatch(mergeTable({ ...table, isExtraMetadataLoading: false })),
dispatch(
addDangerToast(t('An error occurred while fetching table metadata')),
),
]),
);
}
export function addTable(query, database, tableName, schemaName) {
return function (dispatch) {
const table = {
dbId: query.dbId,
queryEditorId: query.id,
schema: schemaName,
name: tableName,
};
dispatch(
mergeTable({
...table,
isMetadataLoading: true,
isExtraMetadataLoading: true,
expanded: true,
}),
);
return Promise.all([
getTableMetadata(table, query, dispatch),
getTableExtendedMetadata(table, query, dispatch),
]).then(([newTable, json]) => {
const sync = isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)
? SupersetClient.post({
endpoint: encodeURI('/tableschemaview/'),
postPayload: { table: { ...newTable, ...json } },
})
: Promise.resolve({ json: { id: shortid.generate() } });
if (!database.disable_data_preview && database.id === query.dbId) {
const dataPreviewQuery = {
id: shortid.generate(),
dbId: query.dbId,
sql: newTable.selectStar,
tableName: table.name,
sqlEditorId: null,
tab: '',
runAsync: database.allow_run_async,
ctas: false,
isDataPreview: true,
};
Promise.all([
dispatch(
mergeTable(
{
...newTable,
dataPreviewQueryId: dataPreviewQuery.id,
},
dataPreviewQuery,
),
),
dispatch(runQuery(dataPreviewQuery)),
]);
}
return sync
.then(({ json: resultJson }) =>
dispatch(mergeTable({ ...table, id: resultJson.id })),
)
.catch(() =>
dispatch(
addDangerToast(
t(
'An error occurred while fetching table metadata. ' +
'Please contact your administrator.',
),
),
),
);
});
};
}
export function changeDataPreviewId(oldQueryId, newQuery) {
return { type: CHANGE_DATA_PREVIEW_ID, oldQueryId, newQuery };
}
export function reFetchQueryResults(query) {
return function (dispatch) {
const newQuery = {
id: shortid.generate(),
dbId: query.dbId,
sql: query.sql,
tableName: query.tableName,
sqlEditorId: null,
tab: '',
runAsync: false,
ctas: false,
queryLimit: query.queryLimit,
isDataPreview: query.isDataPreview,
};
dispatch(runQuery(newQuery));
dispatch(changeDataPreviewId(query.id, newQuery));
};
}
export function expandTable(table) {
return function (dispatch) {
const sync = isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)
? SupersetClient.post({
endpoint: encodeURI(`/tableschemaview/${table.id}/expanded`),
postPayload: { expanded: true },
})
: Promise.resolve();
return sync
.then(() => dispatch({ type: EXPAND_TABLE, table }))
.catch(() =>
dispatch(
addDangerToast(
t(
'An error occurred while expanding the table schema. ' +
'Please contact your administrator.',
),
),
),
);
};
}
export function collapseTable(table) {
return function (dispatch) {
const sync = isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)
? SupersetClient.post({
endpoint: encodeURI(`/tableschemaview/${table.id}/expanded`),
postPayload: { expanded: false },
})
: Promise.resolve();
return sync
.then(() => dispatch({ type: COLLAPSE_TABLE, table }))
.catch(() =>
dispatch(
addDangerToast(
t(
'An error occurred while collapsing the table schema. ' +
'Please contact your administrator.',
),
),
),
);
};
}
export function removeTable(table) {
return function (dispatch) {
const sync = isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)
? SupersetClient.delete({
endpoint: encodeURI(`/tableschemaview/${table.id}`),
})
: Promise.resolve();
return sync
.then(() => dispatch({ type: REMOVE_TABLE, table }))
.catch(() =>
dispatch(
addDangerToast(
t(
'An error occurred while removing the table schema. ' +
'Please contact your administrator.',
),
),
),
);
};
}
export function refreshQueries(alteredQueries) {
return { type: REFRESH_QUERIES, alteredQueries };
}
export function setUserOffline(offline) {
return { type: SET_USER_OFFLINE, offline };
}
export function persistEditorHeight(queryEditor, northPercent, southPercent) {
return {
type: QUERY_EDITOR_PERSIST_HEIGHT,
queryEditor,
northPercent,
southPercent,
};
}
export function popStoredQuery(urlId) {
return function (dispatch) {
return SupersetClient.get({ endpoint: `/kv/${urlId}` })
.then(({ json }) =>
dispatch(
addQueryEditor({
title: json.title ? json.title : t('Shared query'),
dbId: json.dbId ? parseInt(json.dbId, 10) : null,
schema: json.schema ? json.schema : null,
autorun: json.autorun ? json.autorun : false,
sql: json.sql ? json.sql : 'SELECT ...',
}),
),
)
.catch(() => dispatch(addDangerToast(ERR_MSG_CANT_LOAD_QUERY)));
};
}
export function popSavedQuery(saveQueryId) {
return function (dispatch) {
return SupersetClient.get({
endpoint: `/savedqueryviewapi/api/get/${saveQueryId}`,
})
.then(({ json }) => {
const queryEditorProps = {
...convertQueryToClient(json.result),
autorun: false,
};
return dispatch(addQueryEditor(queryEditorProps));
})
.catch(() => dispatch(addDangerToast(ERR_MSG_CANT_LOAD_QUERY)));
};
}
export function popQuery(queryId) {
return function (dispatch) {
return SupersetClient.get({
endpoint: `/api/v1/query/${queryId}`,
})
.then(({ json }) => {
const queryData = json.result;
const queryEditorProps = {
dbId: queryData.database.id,
schema: queryData.schema,
sql: queryData.sql,
title: `Copy of ${queryData.tab_name}`,
autorun: false,
};
return dispatch(addQueryEditor(queryEditorProps));
})
.catch(() => dispatch(addDangerToast(ERR_MSG_CANT_LOAD_QUERY)));
};
}
export function popDatasourceQuery(datasourceKey, sql) {
return function (dispatch) {
return SupersetClient.get({
endpoint: `/superset/fetch_datasource_metadata?datasourceKey=${datasourceKey}`,
})
.then(({ json }) =>
dispatch(
addQueryEditor({
title: `Query ${json.name}`,
dbId: json.database.id,
schema: json.schema,
autorun: sql !== undefined,
sql: sql || json.select_star,
}),
),
)
.catch(() =>
dispatch(addDangerToast(t("The datasource couldn't be loaded"))),
);
};
}
export function createDatasourceStarted() {
return { type: CREATE_DATASOURCE_STARTED };
}
export function createDatasourceSuccess(data) {
const datasource = `${data.table_id}__table`;
return { type: CREATE_DATASOURCE_SUCCESS, datasource };
}
export function createDatasourceFailed(err) {
return { type: CREATE_DATASOURCE_FAILED, err };
}
export function createDatasource(vizOptions) {
return dispatch => {
dispatch(createDatasourceStarted());
return SupersetClient.post({
endpoint: '/superset/sqllab_viz/',
postPayload: { data: vizOptions },
})
.then(({ json }) => {
dispatch(createDatasourceSuccess(json));
return Promise.resolve(json);
})
.catch(() => {
dispatch(
createDatasourceFailed(
t('An error occurred while creating the data source'),
),
);
return Promise.reject();
});
};
}
export function createCtasDatasource(vizOptions) {
return dispatch => {
dispatch(createDatasourceStarted());
return SupersetClient.post({
endpoint: '/superset/get_or_create_table/',
postPayload: { data: vizOptions },
})
.then(({ json }) => {
dispatch(createDatasourceSuccess(json));
return json;
})
.catch(() => {
const errorMsg = t('An error occurred while creating the data source');
dispatch(createDatasourceFailed(errorMsg));
return Promise.reject(new Error(errorMsg));
});
};
}
export function queryEditorSetFunctionNames(queryEditor, dbId) {
return function (dispatch) {
return SupersetClient.get({
endpoint: encodeURI(`/api/v1/database/${dbId}/function_names/`),
})
.then(({ json }) =>
dispatch({
type: QUERY_EDITOR_SET_FUNCTION_NAMES,
queryEditor,
functionNames: json.function_names,
}),
)
.catch(() =>
dispatch(
addDangerToast(t('An error occurred while fetching function names.')),
),
);
};
}
| superset-frontend/src/SqlLab/actions/sqlLab.js | 1 | https://github.com/apache/superset/commit/4669b6ce11dd74e5d1020a1f124e8696b801d730 | [
0.0052813137881457806,
0.00033696251921355724,
0.0001593645429238677,
0.00016871333355084062,
0.0005878890515305102
] |
{
"id": 3,
"code_window": [
" .dispatch(actions.addTable(query, database, tableName, schemaName))\n",
" .then(() => {\n",
" expect(store.getActions().map(a => a.type)).toEqual(\n",
" expectedActionTypes,\n",
" );\n",
" expect(fetchMock.calls(updateTableSchemaEndpoint)).toHaveLength(1);\n",
" expect(fetchMock.calls(getTableMetadataEndpoint)).toHaveLength(1);\n",
" expect(fetchMock.calls(getExtraTableMetadataEndpoint)).toHaveLength(\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(store.getActions()[0].prepend).toBeTruthy();\n"
],
"file_path": "superset-frontend/src/SqlLab/actions/sqlLab.test.js",
"type": "add",
"edit_start_line_idx": 745
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
import { t } from '@superset-ui/core';
export const commonMenuData = {
name: t('Data'),
tabs: [
{
name: 'Databases',
label: t('Databases'),
url: '/databaseview/list/',
usesRouter: true,
},
{
name: 'Datasets',
label: t('Datasets'),
url: '/tablemodelview/list/',
usesRouter: true,
},
{
name: 'Saved queries',
label: t('Saved queries'),
url: '/savedqueryview/list/',
usesRouter: true,
},
{
name: 'Query history',
label: t('Query history'),
url: '/superset/sqllab/history/',
usesRouter: true,
},
],
};
| superset-frontend/src/views/CRUD/data/common.ts | 0 | https://github.com/apache/superset/commit/4669b6ce11dd74e5d1020a1f124e8696b801d730 | [
0.000178596077603288,
0.0001747685018926859,
0.00017113873036578298,
0.0001753512187860906,
0.000002937587851192802
] |
{
"id": 3,
"code_window": [
" .dispatch(actions.addTable(query, database, tableName, schemaName))\n",
" .then(() => {\n",
" expect(store.getActions().map(a => a.type)).toEqual(\n",
" expectedActionTypes,\n",
" );\n",
" expect(fetchMock.calls(updateTableSchemaEndpoint)).toHaveLength(1);\n",
" expect(fetchMock.calls(getTableMetadataEndpoint)).toHaveLength(1);\n",
" expect(fetchMock.calls(getExtraTableMetadataEndpoint)).toHaveLength(\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(store.getActions()[0].prepend).toBeTruthy();\n"
],
"file_path": "superset-frontend/src/SqlLab/actions/sqlLab.test.js",
"type": "add",
"edit_start_line_idx": 745
} | ---
title: Security
hide_title: true
sidebar_position: 10
---
### Roles
Security in Superset is handled by Flask AppBuilder (FAB), an application development framework
built on top of Flask. FAB provides authentication, user management, permissions and roles.
Please read its [Security documentation](https://flask-appbuilder.readthedocs.io/en/latest/security.html).
### Provided Roles
Superset ships with a set of roles that are handled by Superset itself. You can assume
that these roles will stay up-to-date as Superset evolves (and as you update Superset versions).
Even though **Admin** users have the ability, we don't recommend altering the
permissions associated with each role (e.g. by removing or adding permissions to them). The permissions
associated with each role will be re-synchronized to their original values when you run
the **superset init** command (often done between Superset versions).
### Admin
Admins have all possible rights, including granting or revoking rights from other
users and altering other people’s slices and dashboards.
### Alpha
Alpha users have access to all data sources, but they cannot grant or revoke access
from other users. They are also limited to altering the objects that they own. Alpha users can add and alter data sources.
### Gamma
Gamma users have limited access. They can only consume data coming from data sources
they have been given access to through another complementary role. They only have access to
view the slices and dashboards made from data sources that they have access to. Currently Gamma
users are not able to alter or add data sources. We assume that they are mostly content consumers, though they can create slices and dashboards.
Also note that when Gamma users look at the dashboards and slices list view, they will
only see the objects that they have access to.
### sql_lab
The **sql_lab** role grants access to SQL Lab. Note that while **Admin** users have access
to all databases by default, both **Alpha** and **Gamma** users need to be given access on a per database basis.
### Public
To allow logged-out users to access some Superset features, you can use the `PUBLIC_ROLE_LIKE` config setting and assign it to another role whose permissions you want passed to this role.
For example, by setting `PUBLIC_ROLE_LIKE = Gamma` in your `superset_config.py` file, you grant
public role the same set of permissions as for the **Gamma** role. This is useful if one
wants to enable anonymous users to view dashboards. Explicit grant on specific datasets is
still required, meaning that you need to edit the **Public** role and add the public data sources to the role manually.
### Managing Data Source Access for Gamma Roles
Here’s how to provide users access to only specific datasets. First make sure the users with
limited access have [only] the Gamma role assigned to them. Second, create a new role (Menu -> Security -> List Roles) and click the + sign.
This new window allows you to give this new role a name, attribute it to users and select the
tables in the **Permissions** dropdown. To select the data sources you want to associate with this role, simply click on the dropdown and use the typeahead to search for your table names.
You can then confirm with users assigned to the **Gamma** role that they see the
objects (dashboards and slices) associated with the tables you just extended them.
### Customizing Permissions
The permissions exposed by FAB are very granular and allow for a great level of
customization. FAB creates many permissions automagically for each model that is
created (can_add, can_delete, can_show, can_edit, …) as well as for each view.
On top of that, Superset can expose more granular permissions like **all_datasource_access**.
**We do not recommend altering the 3 base roles as there are a set of assumptions that
Superset is built upon**. It is possible though for you to create your own roles, and union them to existing ones.
### Permissions
Roles are composed of a set of permissions, and Superset has many categories of
permissions. Here are the different categories of permissions:
- Model & Action: models are entities like Dashboard, Slice, or User. Each model has
a fixed set of permissions, like **can_edit**, **can_show**, **can_delete**, **can_list**, **can_add**,
and so on. For example, you can allow a user to delete dashboards by adding **can_delete** on
Dashboard entity to a role and granting this user that role.
- Views: views are individual web pages, like the Explore view or the SQL Lab view.
When granted to a user, they will see that view in its menu items, and be able to load that page.
- Data source: For each data source, a permission is created. If the user does not have the
`all_datasource_access permission` granted, the user will only be able to see Slices or explore the data sources that are granted to them
- Database: Granting access to a database allows for the user to access all
data sources within that database, and will enable the user to query that
database in SQL Lab, provided that the SQL Lab specific permission have been granted to the user
### Restricting Access to a Subset of Data Sources
We recommend giving a user the **Gamma** role plus any other roles that would add
access to specific data sources. We recommend that you create individual roles for
each access profile. For example, the users on the Finance team might have access to a set of
databases and data sources; these permissions can be consolidated in a single role.
Users with this profile then need to be assigned the **Gamma** role as a foundation to
the models and views they can access, and that Finance role that is a collection of permissions to data objects.
A user can have multiple roles associated with them. For example, an executive on the Finance
team could be granted **Gamma**, **Finance**, and the **Executive** roles. The **Executive**
role could provide access to a set of data sources and dashboards made available only to executives.
In the **Dashboards** view, a user can only see the ones they have access too
based on the roles and permissions that were attributed.
### Row Level Security
Using Row Level Security filters (under the **Security** menu) you can create filters
that are assigned to a particular table, as well as a set of roles.
If you want members of the Finance team to only have access to
rows where `department = "finance"`, you could:
- Create a Row Level Security filter with that clause (`department = "finance"`)
- Then assign the clause to the **Finance** role and the table it applies to
The **clause** field, which can contain arbitrary text, is then added to the generated
SQL statement’s WHERE clause. So you could even do something like create a filter
for the last 30 days and apply it to a specific role, with a clause
like `date_field > DATE_SUB(NOW(), INTERVAL 30 DAY)`. It can also support
multiple conditions: `client_id = 6` AND `advertiser="foo"`, etc.
All relevant Row level security filters will be combined together (under the hood,
the different SQL clauses are combined using AND statements). This means it's
possible to create a situation where two roles conflict in such a way as to limit a table subset to empty.
For example, the filters `client_id=4` and `client_id=5`, applied to a role,
will result in users of that role having `client_id=4` AND `client_id=5`
added to their query, which can never be true.
### Reporting Security Vulnerabilities
Apache Software Foundation takes a rigorous standpoint in annihilating the security issues in its
software projects. Apache Superset is highly sensitive and forthcoming to issues pertaining to its
features and functionality.
If you have apprehensions regarding Superset security or you discover vulnerability or potential
threat, don’t hesitate to get in touch with the Apache Security Team by dropping a mail at
[email protected]. In the mail, specify the project name Superset with the description of the
issue or potential threat. You are also urged to recommend the way to reproduce and replicate the
issue. The security team and the Superset community will get back to you after assessing and
analysing the findings.
PLEASE PAY ATTENTION to report the security issue on the security email before disclosing it on
public domain. The ASF Security Team maintains a page with the description of how vulnerabilities
and potential threats are handled, check their web page for more details.
| docs/docs/security.mdx | 0 | https://github.com/apache/superset/commit/4669b6ce11dd74e5d1020a1f124e8696b801d730 | [
0.00017879015649668872,
0.0001706378097878769,
0.00015885477478150278,
0.00017022764950525016,
0.000005452106051961891
] |
{
"id": 3,
"code_window": [
" .dispatch(actions.addTable(query, database, tableName, schemaName))\n",
" .then(() => {\n",
" expect(store.getActions().map(a => a.type)).toEqual(\n",
" expectedActionTypes,\n",
" );\n",
" expect(fetchMock.calls(updateTableSchemaEndpoint)).toHaveLength(1);\n",
" expect(fetchMock.calls(getTableMetadataEndpoint)).toHaveLength(1);\n",
" expect(fetchMock.calls(getExtraTableMetadataEndpoint)).toHaveLength(\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(store.getActions()[0].prepend).toBeTruthy();\n"
],
"file_path": "superset-frontend/src/SqlLab/actions/sqlLab.test.js",
"type": "add",
"edit_start_line_idx": 745
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
import { sortAlphanumericCaseInsensitive } from '../src/DataTable/utils/sortAlphanumericCaseInsensitive';
const testData = [
{
values: {
col: 'test value',
},
},
{
values: {
col: 'a lowercase test value',
},
},
{
values: {
col: '5',
},
},
{
values: {
col: NaN,
},
},
{
values: {
col: '1234',
},
},
{
values: {
col: Infinity,
},
},
{
values: {
col: '.!# value starting with non-letter characters',
},
},
{
values: {
col: 'An uppercase test value',
},
},
{
values: {
col: undefined,
},
},
{
values: {
col: null,
},
},
];
describe('sortAlphanumericCaseInsensitive', () => {
it('Sort rows', () => {
const sorted = [...testData].sort((a, b) =>
// @ts-ignore
sortAlphanumericCaseInsensitive(a, b, 'col'),
);
expect(sorted).toEqual([
{
values: {
col: null,
},
},
{
values: {
col: undefined,
},
},
{
values: {
col: Infinity,
},
},
{
values: {
col: NaN,
},
},
{
values: {
col: '.!# value starting with non-letter characters',
},
},
{
values: {
col: '1234',
},
},
{
values: {
col: '5',
},
},
{
values: {
col: 'a lowercase test value',
},
},
{
values: {
col: 'An uppercase test value',
},
},
{
values: {
col: 'test value',
},
},
]);
});
});
| superset-frontend/plugins/plugin-chart-table/test/sortAlphanumericCaseInsensitive.test.ts | 0 | https://github.com/apache/superset/commit/4669b6ce11dd74e5d1020a1f124e8696b801d730 | [
0.000178596077603288,
0.00017427401326131076,
0.0001692284713499248,
0.00017400119395460933,
0.0000020255972685845336
] |
{
"id": 4,
"code_window": [
" }\n",
" // for new table, associate Id of query for data preview\n",
" at.dataPreviewQueryId = null;\n",
" let newState = addToArr(state, 'tables', at);\n",
" if (action.query) {\n",
" newState = alterInArr(newState, 'tables', at, {\n",
" dataPreviewQueryId: action.query.id,\n",
" });\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" let newState = addToArr(state, 'tables', at, Boolean(action.prepend));\n"
],
"file_path": "superset-frontend/src/SqlLab/reducers/sqlLab.js",
"type": "replace",
"edit_start_line_idx": 136
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
import { t } from '@superset-ui/core';
import getInitialState from './getInitialState';
import * as actions from '../actions/sqlLab';
import { now } from '../../modules/dates';
import {
addToObject,
alterInObject,
alterInArr,
removeFromArr,
getFromArr,
addToArr,
extendArr,
} from '../../reduxUtils';
export default function sqlLabReducer(state = {}, action) {
const actionHandlers = {
[actions.ADD_QUERY_EDITOR]() {
const tabHistory = state.tabHistory.slice();
tabHistory.push(action.queryEditor.id);
const newState = { ...state, tabHistory };
return addToArr(newState, 'queryEditors', action.queryEditor);
},
[actions.QUERY_EDITOR_SAVED]() {
const { query, result } = action;
const existing = state.queryEditors.find(qe => qe.id === query.id);
return alterInArr(
state,
'queryEditors',
existing,
{
remoteId: result.remoteId,
title: query.title,
},
'id',
);
},
[actions.UPDATE_QUERY_EDITOR]() {
const id = action.alterations.remoteId;
const existing = state.queryEditors.find(qe => qe.remoteId === id);
if (existing == null) return state;
return alterInArr(
state,
'queryEditors',
existing,
action.alterations,
'remoteId',
);
},
[actions.CLONE_QUERY_TO_NEW_TAB]() {
const progenitor = state.queryEditors.find(
qe => qe.id === state.tabHistory[state.tabHistory.length - 1],
);
const qe = {
remoteId: progenitor.remoteId,
title: t('Copy of %s', progenitor.title),
dbId: action.query.dbId ? action.query.dbId : null,
schema: action.query.schema ? action.query.schema : null,
autorun: true,
sql: action.query.sql,
queryLimit: action.query.queryLimit,
maxRow: action.query.maxRow,
};
return sqlLabReducer(state, actions.addQueryEditor(qe));
},
[actions.REMOVE_QUERY_EDITOR]() {
let newState = removeFromArr(state, 'queryEditors', action.queryEditor);
// List of remaining queryEditor ids
const qeIds = newState.queryEditors.map(qe => qe.id);
const queries = {};
Object.keys(state.queries).forEach(k => {
const query = state.queries[k];
if (qeIds.indexOf(query.sqlEditorId) > -1) {
queries[k] = query;
}
});
let tabHistory = state.tabHistory.slice();
tabHistory = tabHistory.filter(id => qeIds.indexOf(id) > -1);
// Remove associated table schemas
const tables = state.tables.filter(
table => table.queryEditorId !== action.queryEditor.id,
);
newState = { ...newState, tabHistory, tables, queries };
return newState;
},
[actions.REMOVE_QUERY]() {
const newQueries = { ...state.queries };
delete newQueries[action.query.id];
return { ...state, queries: newQueries };
},
[actions.RESET_STATE]() {
return { ...getInitialState() };
},
[actions.MERGE_TABLE]() {
const at = { ...action.table };
let existingTable;
state.tables.forEach(xt => {
if (
xt.dbId === at.dbId &&
xt.queryEditorId === at.queryEditorId &&
xt.schema === at.schema &&
xt.name === at.name
) {
existingTable = xt;
}
});
if (existingTable) {
if (action.query) {
at.dataPreviewQueryId = action.query.id;
}
return alterInArr(state, 'tables', existingTable, at);
}
// for new table, associate Id of query for data preview
at.dataPreviewQueryId = null;
let newState = addToArr(state, 'tables', at);
if (action.query) {
newState = alterInArr(newState, 'tables', at, {
dataPreviewQueryId: action.query.id,
});
}
return newState;
},
[actions.EXPAND_TABLE]() {
return alterInArr(state, 'tables', action.table, { expanded: true });
},
[actions.REMOVE_DATA_PREVIEW]() {
const queries = { ...state.queries };
delete queries[action.table.dataPreviewQueryId];
const newState = alterInArr(state, 'tables', action.table, {
dataPreviewQueryId: null,
});
return { ...newState, queries };
},
[actions.CHANGE_DATA_PREVIEW_ID]() {
const queries = { ...state.queries };
delete queries[action.oldQueryId];
const newTables = [];
state.tables.forEach(xt => {
if (xt.dataPreviewQueryId === action.oldQueryId) {
newTables.push({ ...xt, dataPreviewQueryId: action.newQuery.id });
} else {
newTables.push(xt);
}
});
return {
...state,
queries,
tables: newTables,
activeSouthPaneTab: action.newQuery.id,
};
},
[actions.COLLAPSE_TABLE]() {
return alterInArr(state, 'tables', action.table, { expanded: false });
},
[actions.REMOVE_TABLE]() {
return removeFromArr(state, 'tables', action.table);
},
[actions.START_QUERY_VALIDATION]() {
let newState = { ...state };
const sqlEditor = { id: action.query.sqlEditorId };
newState = alterInArr(newState, 'queryEditors', sqlEditor, {
validationResult: {
id: action.query.id,
errors: [],
completed: false,
},
});
return newState;
},
[actions.QUERY_VALIDATION_RETURNED]() {
// If the server is very slow about answering us, we might get validation
// responses back out of order. This check confirms the response we're
// handling corresponds to the most recently dispatched request.
//
// We don't care about any but the most recent because validations are
// only valid for the SQL text they correspond to -- once the SQL has
// changed, the old validation doesn't tell us anything useful anymore.
const qe = getFromArr(state.queryEditors, action.query.sqlEditorId);
if (qe.validationResult.id !== action.query.id) {
return state;
}
// Otherwise, persist the results on the queryEditor state
let newState = { ...state };
const sqlEditor = { id: action.query.sqlEditorId };
newState = alterInArr(newState, 'queryEditors', sqlEditor, {
validationResult: {
id: action.query.id,
errors: action.results,
completed: true,
},
});
return newState;
},
[actions.QUERY_VALIDATION_FAILED]() {
// If the server is very slow about answering us, we might get validation
// responses back out of order. This check confirms the response we're
// handling corresponds to the most recently dispatched request.
//
// We don't care about any but the most recent because validations are
// only valid for the SQL text they correspond to -- once the SQL has
// changed, the old validation doesn't tell us anything useful anymore.
const qe = getFromArr(state.queryEditors, action.query.sqlEditorId);
if (qe.validationResult.id !== action.query.id) {
return state;
}
// Otherwise, persist the results on the queryEditor state
let newState = { ...state };
const sqlEditor = { id: action.query.sqlEditorId };
newState = alterInArr(newState, 'queryEditors', sqlEditor, {
validationResult: {
id: action.query.id,
errors: [
{
line_number: 1,
start_column: 1,
end_column: 1,
message: `The server failed to validate your query.\n${action.message}`,
},
],
completed: true,
},
});
return newState;
},
[actions.COST_ESTIMATE_STARTED]() {
let newState = { ...state };
const sqlEditor = { id: action.query.sqlEditorId };
newState = alterInArr(newState, 'queryEditors', sqlEditor, {
queryCostEstimate: {
completed: false,
cost: null,
error: null,
},
});
return newState;
},
[actions.COST_ESTIMATE_RETURNED]() {
let newState = { ...state };
const sqlEditor = { id: action.query.sqlEditorId };
newState = alterInArr(newState, 'queryEditors', sqlEditor, {
queryCostEstimate: {
completed: true,
cost: action.json,
error: null,
},
});
return newState;
},
[actions.COST_ESTIMATE_FAILED]() {
let newState = { ...state };
const sqlEditor = { id: action.query.sqlEditorId };
newState = alterInArr(newState, 'queryEditors', sqlEditor, {
queryCostEstimate: {
completed: false,
cost: null,
error: action.error,
},
});
return newState;
},
[actions.START_QUERY]() {
let newState = { ...state };
if (action.query.sqlEditorId) {
const qe = getFromArr(state.queryEditors, action.query.sqlEditorId);
if (qe.latestQueryId && state.queries[qe.latestQueryId]) {
const newResults = {
...state.queries[qe.latestQueryId].results,
data: [],
query: null,
};
const q = { ...state.queries[qe.latestQueryId], results: newResults };
const queries = { ...state.queries, [q.id]: q };
newState = { ...state, queries };
}
} else {
newState.activeSouthPaneTab = action.query.id;
}
newState = addToObject(newState, 'queries', action.query);
const sqlEditor = { id: action.query.sqlEditorId };
return alterInArr(newState, 'queryEditors', sqlEditor, {
latestQueryId: action.query.id,
});
},
[actions.STOP_QUERY]() {
return alterInObject(state, 'queries', action.query, {
state: 'stopped',
results: [],
});
},
[actions.CLEAR_QUERY_RESULTS]() {
const newResults = { ...action.query.results };
newResults.data = [];
return alterInObject(state, 'queries', action.query, {
results: newResults,
cached: true,
});
},
[actions.REQUEST_QUERY_RESULTS]() {
return alterInObject(state, 'queries', action.query, {
state: 'fetching',
});
},
[actions.QUERY_SUCCESS]() {
// prevent race condition were query succeeds shortly after being canceled
if (action.query.state === 'stopped') {
return state;
}
const alts = {
endDttm: now(),
progress: 100,
results: action.results,
rows: action?.results?.query?.rows || 0,
state: 'success',
limitingFactor: action?.results?.query?.limitingFactor,
tempSchema: action?.results?.query?.tempSchema,
tempTable: action?.results?.query?.tempTable,
errorMessage: null,
cached: false,
};
return alterInObject(state, 'queries', action.query, alts);
},
[actions.QUERY_FAILED]() {
if (action.query.state === 'stopped') {
return state;
}
const alts = {
state: 'failed',
errors: action.errors,
errorMessage: action.msg,
endDttm: now(),
link: action.link,
};
return alterInObject(state, 'queries', action.query, alts);
},
[actions.SET_ACTIVE_QUERY_EDITOR]() {
const qeIds = state.queryEditors.map(qe => qe.id);
if (
qeIds.indexOf(action.queryEditor?.id) > -1 &&
state.tabHistory[state.tabHistory.length - 1] !== action.queryEditor.id
) {
const tabHistory = state.tabHistory.slice();
tabHistory.push(action.queryEditor.id);
return { ...state, tabHistory };
}
return state;
},
[actions.LOAD_QUERY_EDITOR]() {
return alterInArr(state, 'queryEditors', action.queryEditor, {
...action.queryEditor,
});
},
[actions.SET_TABLES]() {
return extendArr(state, 'tables', action.tables);
},
[actions.SET_ACTIVE_SOUTHPANE_TAB]() {
return { ...state, activeSouthPaneTab: action.tabId };
},
[actions.MIGRATE_QUERY_EDITOR]() {
// remove migrated query editor from localStorage
const { sqlLab } = JSON.parse(localStorage.getItem('redux'));
sqlLab.queryEditors = sqlLab.queryEditors.filter(
qe => qe.id !== action.oldQueryEditor.id,
);
localStorage.setItem('redux', JSON.stringify({ sqlLab }));
// replace localStorage query editor with the server backed one
return addToArr(
removeFromArr(state, 'queryEditors', action.oldQueryEditor),
'queryEditors',
action.newQueryEditor,
);
},
[actions.MIGRATE_TABLE]() {
// remove migrated table from localStorage
const { sqlLab } = JSON.parse(localStorage.getItem('redux'));
sqlLab.tables = sqlLab.tables.filter(
table => table.id !== action.oldTable.id,
);
localStorage.setItem('redux', JSON.stringify({ sqlLab }));
// replace localStorage table with the server backed one
return addToArr(
removeFromArr(state, 'tables', action.oldTable),
'tables',
action.newTable,
);
},
[actions.MIGRATE_TAB_HISTORY]() {
// remove migrated tab from localStorage tabHistory
const { sqlLab } = JSON.parse(localStorage.getItem('redux'));
sqlLab.tabHistory = sqlLab.tabHistory.filter(
tabId => tabId !== action.oldId,
);
localStorage.setItem('redux', JSON.stringify({ sqlLab }));
const tabHistory = state.tabHistory.filter(
tabId => tabId !== action.oldId,
);
tabHistory.push(action.newId);
return { ...state, tabHistory };
},
[actions.MIGRATE_QUERY]() {
const query = {
...state.queries[action.queryId],
// point query to migrated query editor
sqlEditorId: action.queryEditorId,
};
const queries = { ...state.queries, [query.id]: query };
return { ...state, queries };
},
[actions.QUERY_EDITOR_SETDB]() {
return alterInArr(state, 'queryEditors', action.queryEditor, {
dbId: action.dbId,
});
},
[actions.QUERY_EDITOR_SET_FUNCTION_NAMES]() {
return alterInArr(state, 'queryEditors', action.queryEditor, {
functionNames: action.functionNames,
});
},
[actions.QUERY_EDITOR_SET_SCHEMA]() {
return alterInArr(state, 'queryEditors', action.queryEditor, {
schema: action.schema,
});
},
[actions.QUERY_EDITOR_SET_SCHEMA_OPTIONS]() {
return alterInArr(state, 'queryEditors', action.queryEditor, {
schemaOptions: action.options,
});
},
[actions.QUERY_EDITOR_SET_TABLE_OPTIONS]() {
return alterInArr(state, 'queryEditors', action.queryEditor, {
tableOptions: action.options,
});
},
[actions.QUERY_EDITOR_SET_TITLE]() {
return alterInArr(state, 'queryEditors', action.queryEditor, {
title: action.title,
});
},
[actions.QUERY_EDITOR_SET_SQL]() {
return alterInArr(state, 'queryEditors', action.queryEditor, {
sql: action.sql,
});
},
[actions.QUERY_EDITOR_SET_QUERY_LIMIT]() {
return alterInArr(state, 'queryEditors', action.queryEditor, {
queryLimit: action.queryLimit,
});
},
[actions.QUERY_EDITOR_SET_TEMPLATE_PARAMS]() {
return alterInArr(state, 'queryEditors', action.queryEditor, {
templateParams: action.templateParams,
});
},
[actions.QUERY_EDITOR_SET_SELECTED_TEXT]() {
return alterInArr(state, 'queryEditors', action.queryEditor, {
selectedText: action.sql,
});
},
[actions.QUERY_EDITOR_SET_AUTORUN]() {
return alterInArr(state, 'queryEditors', action.queryEditor, {
autorun: action.autorun,
});
},
[actions.QUERY_EDITOR_PERSIST_HEIGHT]() {
return alterInArr(state, 'queryEditors', action.queryEditor, {
northPercent: action.northPercent,
southPercent: action.southPercent,
});
},
[actions.QUERY_EDITOR_TOGGLE_LEFT_BAR]() {
return alterInArr(state, 'queryEditors', action.queryEditor, {
hideLeftBar: action.hideLeftBar,
});
},
[actions.SET_DATABASES]() {
const databases = {};
action.databases.forEach(db => {
databases[db.id] = {
...db,
extra_json: JSON.parse(db.extra || ''),
};
});
return { ...state, databases };
},
[actions.REFRESH_QUERIES]() {
let newQueries = { ...state.queries };
// Fetch the updates to the queries present in the store.
let change = false;
let { queriesLastUpdate } = state;
Object.entries(action.alteredQueries).forEach(([id, changedQuery]) => {
if (
!state.queries.hasOwnProperty(id) ||
(state.queries[id].state !== 'stopped' &&
state.queries[id].state !== 'failed')
) {
if (changedQuery.changedOn > queriesLastUpdate) {
queriesLastUpdate = changedQuery.changedOn;
}
const prevState = state.queries[id]?.state;
const currentState = changedQuery.state;
newQueries[id] = {
...state.queries[id],
...changedQuery,
// race condition:
// because of async behavior, sql lab may still poll a couple of seconds
// when it started fetching or finished rendering results
state:
currentState === 'success' &&
['fetching', 'success'].includes(prevState)
? prevState
: currentState,
};
change = true;
}
});
if (!change) {
newQueries = state.queries;
}
return { ...state, queries: newQueries, queriesLastUpdate };
},
[actions.SET_USER_OFFLINE]() {
return { ...state, offline: action.offline };
},
[actions.CREATE_DATASOURCE_STARTED]() {
return { ...state, isDatasourceLoading: true, errorMessage: null };
},
[actions.CREATE_DATASOURCE_SUCCESS]() {
return {
...state,
isDatasourceLoading: false,
errorMessage: null,
datasource: action.datasource,
};
},
[actions.CREATE_DATASOURCE_FAILED]() {
return { ...state, isDatasourceLoading: false, errorMessage: action.err };
},
};
if (action.type in actionHandlers) {
return actionHandlers[action.type]();
}
return state;
}
| superset-frontend/src/SqlLab/reducers/sqlLab.js | 1 | https://github.com/apache/superset/commit/4669b6ce11dd74e5d1020a1f124e8696b801d730 | [
0.999151349067688,
0.321958988904953,
0.00016676516679581255,
0.000902719737496227,
0.4581463038921356
] |
{
"id": 4,
"code_window": [
" }\n",
" // for new table, associate Id of query for data preview\n",
" at.dataPreviewQueryId = null;\n",
" let newState = addToArr(state, 'tables', at);\n",
" if (action.query) {\n",
" newState = alterInArr(newState, 'tables', at, {\n",
" dataPreviewQueryId: action.query.id,\n",
" });\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" let newState = addToArr(state, 'tables', at, Boolean(action.prepend));\n"
],
"file_path": "superset-frontend/src/SqlLab/reducers/sqlLab.js",
"type": "replace",
"edit_start_line_idx": 136
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
import logging
from flask_appbuilder.models.sqla import Model
from flask_appbuilder.security.sqla.models import User
from superset.dao.exceptions import DAODeleteFailedError
from superset.dashboards.filter_sets.commands.base import BaseFilterSetCommand
from superset.dashboards.filter_sets.commands.exceptions import (
FilterSetDeleteFailedError,
FilterSetForbiddenError,
FilterSetNotFoundError,
)
from superset.dashboards.filter_sets.dao import FilterSetDAO
logger = logging.getLogger(__name__)
class DeleteFilterSetCommand(BaseFilterSetCommand):
def __init__(self, user: User, dashboard_id: int, filter_set_id: int):
super().__init__(user, dashboard_id)
self._filter_set_id = filter_set_id
def run(self) -> Model:
try:
self.validate()
return FilterSetDAO.delete(self._filter_set, commit=True)
except DAODeleteFailedError as err:
raise FilterSetDeleteFailedError(str(self._filter_set_id), "") from err
def validate(self) -> None:
self._validate_filterset_dashboard_exists()
try:
self.validate_exist_filter_use_cases_set()
except FilterSetNotFoundError as err:
if FilterSetDAO.find_by_id(self._filter_set_id): # type: ignore
raise FilterSetForbiddenError(
'the filter-set does not related to dashboard "%s"'
% str(self._dashboard_id)
) from err
raise err
| superset/dashboards/filter_sets/commands/delete.py | 0 | https://github.com/apache/superset/commit/4669b6ce11dd74e5d1020a1f124e8696b801d730 | [
0.00017782532086130232,
0.0001737593993311748,
0.00017082522390410304,
0.00017277873121201992,
0.0000029547074973379495
] |
{
"id": 4,
"code_window": [
" }\n",
" // for new table, associate Id of query for data preview\n",
" at.dataPreviewQueryId = null;\n",
" let newState = addToArr(state, 'tables', at);\n",
" if (action.query) {\n",
" newState = alterInArr(newState, 'tables', at, {\n",
" dataPreviewQueryId: action.query.id,\n",
" });\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" let newState = addToArr(state, 'tables', at, Boolean(action.prepend));\n"
],
"file_path": "superset-frontend/src/SqlLab/reducers/sqlLab.js",
"type": "replace",
"edit_start_line_idx": 136
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
import { QueryFormData, supersetTheme, TimeseriesDataRecord } from '@superset-ui/core';
export interface <%= packageLabel %>StylesProps {
height: number;
width: number;
headerFontSize: keyof typeof supersetTheme.typography.sizes;
boldText: boolean;
}
interface <%= packageLabel %>CustomizeProps {
headerText: string;
}
export type <%= packageLabel %>QueryFormData = QueryFormData &
<%= packageLabel %>StylesProps &
<%= packageLabel %>CustomizeProps;
export type <%= packageLabel %>Props = <%= packageLabel %>StylesProps &
<%= packageLabel %>CustomizeProps & {
data: TimeseriesDataRecord[];
// add typing here for the props you pass in from transformProps.ts!
};
| superset-frontend/packages/generator-superset/generators/plugin-chart/templates/src/types.erb | 0 | https://github.com/apache/superset/commit/4669b6ce11dd74e5d1020a1f124e8696b801d730 | [
0.00017555197700858116,
0.0001724909379845485,
0.00016701244749128819,
0.00017393575399182737,
0.000003205493840141571
] |
{
"id": 4,
"code_window": [
" }\n",
" // for new table, associate Id of query for data preview\n",
" at.dataPreviewQueryId = null;\n",
" let newState = addToArr(state, 'tables', at);\n",
" if (action.query) {\n",
" newState = alterInArr(newState, 'tables', at, {\n",
" dataPreviewQueryId: action.query.id,\n",
" });\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" let newState = addToArr(state, 'tables', at, Boolean(action.prepend));\n"
],
"file_path": "superset-frontend/src/SqlLab/reducers/sqlLab.js",
"type": "replace",
"edit_start_line_idx": 136
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
import { useCallback, useEffect } from 'react';
/* eslint camelcase: 0 */
import URI from 'urijs';
import {
buildQueryContext,
ensureIsArray,
getChartBuildQueryRegistry,
getChartMetadataRegistry,
} from '@superset-ui/core';
import { availableDomains } from 'src/utils/hostNamesConfig';
import { safeStringify } from 'src/utils/safeStringify';
import { URL_PARAMS } from 'src/constants';
import {
MULTI_OPERATORS,
OPERATOR_ENUM_TO_OPERATOR_TYPE,
} from 'src/explore/constants';
import { DashboardStandaloneMode } from 'src/dashboard/util/constants';
import { optionLabel } from '../../utils/common';
export function getChartKey(explore) {
const { slice } = explore;
return slice ? slice.slice_id : 0;
}
let requestCounter = 0;
export function getHostName(allowDomainSharding = false) {
let currentIndex = 0;
if (allowDomainSharding) {
currentIndex = requestCounter % availableDomains.length;
requestCounter += 1;
// if domain sharding is enabled, skip main domain for fetching chart API
// leave main domain free for other calls like fav star, save change, etc.
// to make dashboard be responsive when it's loading large number of charts
if (currentIndex === 0) {
currentIndex += 1;
requestCounter += 1;
}
}
return availableDomains[currentIndex];
}
export function getAnnotationJsonUrl(slice_id, form_data, isNative, force) {
if (slice_id === null || slice_id === undefined) {
return null;
}
const uri = URI(window.location.search);
const endpoint = isNative ? 'annotation_json' : 'slice_json';
return uri
.pathname(`/superset/${endpoint}/${slice_id}`)
.search({
form_data: safeStringify(form_data, (key, value) =>
value === null ? undefined : value,
),
force,
})
.toString();
}
export function getURIDirectory(endpointType = 'base') {
// Building the directory part of the URI
if (
['full', 'json', 'csv', 'query', 'results', 'samples'].includes(
endpointType,
)
) {
return '/superset/explore_json/';
}
return '/superset/explore/';
}
export function mountExploreUrl(endpointType, extraSearch = {}, force = false) {
const uri = new URI('/');
const directory = getURIDirectory(endpointType);
const search = uri.search(true);
Object.keys(extraSearch).forEach(key => {
search[key] = extraSearch[key];
});
if (endpointType === URL_PARAMS.standalone.name) {
if (force) {
search.force = '1';
}
search.standalone = DashboardStandaloneMode.HIDE_NAV;
}
return uri.directory(directory).search(search).toString();
}
export function getChartDataUri({ path, qs, allowDomainSharding = false }) {
// The search params from the window.location are carried through,
// but can be specified with curUrl (used for unit tests to spoof
// the window.location).
let uri = new URI({
protocol: window.location.protocol.slice(0, -1),
hostname: getHostName(allowDomainSharding),
port: window.location.port ? window.location.port : '',
path,
});
if (qs) {
uri = uri.search(qs);
}
return uri;
}
/**
* This gets the minimal url for the given form data.
* If there are dashboard overrides present in the form data,
* they will not be included in the url.
*/
export function getExploreUrl({
formData,
endpointType = 'base',
force = false,
curUrl = null,
requestParams = {},
allowDomainSharding = false,
method = 'POST',
}) {
if (!formData.datasource) {
return null;
}
// label_colors should not pollute the URL
// eslint-disable-next-line no-param-reassign
delete formData.label_colors;
let uri = getChartDataUri({ path: '/', allowDomainSharding });
if (curUrl) {
uri = URI(URI(curUrl).search());
}
const directory = getURIDirectory(endpointType);
// Building the querystring (search) part of the URI
const search = uri.search(true);
const { slice_id, extra_filters, adhoc_filters, viz_type } = formData;
if (slice_id) {
const form_data = { slice_id };
if (method === 'GET') {
form_data.viz_type = viz_type;
if (extra_filters && extra_filters.length) {
form_data.extra_filters = extra_filters;
}
if (adhoc_filters && adhoc_filters.length) {
form_data.adhoc_filters = adhoc_filters;
}
}
search.form_data = safeStringify(form_data);
}
if (force) {
search.force = 'true';
}
if (endpointType === 'csv') {
search.csv = 'true';
}
if (endpointType === URL_PARAMS.standalone.name) {
search.standalone = '1';
}
if (endpointType === 'query') {
search.query = 'true';
}
if (endpointType === 'results') {
search.results = 'true';
}
if (endpointType === 'samples') {
search.samples = 'true';
}
const paramNames = Object.keys(requestParams);
if (paramNames.length) {
paramNames.forEach(name => {
if (requestParams.hasOwnProperty(name)) {
search[name] = requestParams[name];
}
});
}
return uri.search(search).directory(directory).toString();
}
export const shouldUseLegacyApi = formData => {
const vizMetadata = getChartMetadataRegistry().get(formData.viz_type);
return vizMetadata ? vizMetadata.useLegacyApi : false;
};
export const buildV1ChartDataPayload = ({
formData,
force,
resultFormat,
resultType,
setDataMask,
ownState,
}) => {
const buildQuery =
getChartBuildQueryRegistry().get(formData.viz_type) ??
(buildQueryformData =>
buildQueryContext(buildQueryformData, baseQueryObject => [
{
...baseQueryObject,
},
]));
return buildQuery(
{
...formData,
force,
result_format: resultFormat,
result_type: resultType,
},
{
ownState,
hooks: {
setDataMask,
},
},
);
};
export const getLegacyEndpointType = ({ resultType, resultFormat }) =>
resultFormat === 'csv' ? resultFormat : resultType;
export function postForm(url, payload, target = '_blank') {
if (!url) {
return;
}
const hiddenForm = document.createElement('form');
hiddenForm.action = url;
hiddenForm.method = 'POST';
hiddenForm.target = target;
const token = document.createElement('input');
token.type = 'hidden';
token.name = 'csrf_token';
token.value = (document.getElementById('csrf_token') || {}).value;
hiddenForm.appendChild(token);
const data = document.createElement('input');
data.type = 'hidden';
data.name = 'form_data';
data.value = safeStringify(payload);
hiddenForm.appendChild(data);
document.body.appendChild(hiddenForm);
hiddenForm.submit();
document.body.removeChild(hiddenForm);
}
export const exportChart = ({
formData,
resultFormat = 'json',
resultType = 'full',
force = false,
ownState = {},
}) => {
let url;
let payload;
if (shouldUseLegacyApi(formData)) {
const endpointType = getLegacyEndpointType({ resultFormat, resultType });
url = getExploreUrl({
formData,
endpointType,
allowDomainSharding: false,
});
payload = formData;
} else {
url = '/api/v1/chart/data';
payload = buildV1ChartDataPayload({
formData,
force,
resultFormat,
resultType,
ownState,
});
}
postForm(url, payload);
};
export const exploreChart = formData => {
const url = getExploreUrl({
formData,
endpointType: 'base',
allowDomainSharding: false,
});
postForm(url, formData);
};
export const useDebouncedEffect = (effect, delay, deps) => {
// eslint-disable-next-line react-hooks/exhaustive-deps
const callback = useCallback(effect, deps);
useEffect(() => {
const handler = setTimeout(() => {
callback();
}, delay);
return () => {
clearTimeout(handler);
};
}, [callback, delay]);
};
export const getSimpleSQLExpression = (subject, operator, comparator) => {
const isMulti =
[...MULTI_OPERATORS]
.map(op => OPERATOR_ENUM_TO_OPERATOR_TYPE[op].operation)
.indexOf(operator) >= 0;
let expression = subject ?? '';
if (subject && operator) {
expression += ` ${operator}`;
const firstValue =
isMulti && Array.isArray(comparator) ? comparator[0] : comparator;
const comparatorArray = ensureIsArray(comparator);
const isString =
firstValue !== undefined && Number.isNaN(Number(firstValue));
const quote = isString ? "'" : '';
const [prefix, suffix] = isMulti ? ['(', ')'] : ['', ''];
const formattedComparators = comparatorArray
.map(val => optionLabel(val))
.map(
val =>
`${quote}${isString ? String(val).replace("'", "''") : val}${quote}`,
);
if (comparatorArray.length > 0) {
expression += ` ${prefix}${formattedComparators.join(', ')}${suffix}`;
}
}
return expression;
};
| superset-frontend/src/explore/exploreUtils/index.js | 0 | https://github.com/apache/superset/commit/4669b6ce11dd74e5d1020a1f124e8696b801d730 | [
0.000516509055159986,
0.00018208070832770318,
0.00016555470938328654,
0.00017233738617505878,
0.00005753022924182005
] |
{
"id": 0,
"code_window": [
" seriesLabels: { __name__: 'test' },\n",
" exemplars: [\n",
" {\n",
" timestamp: 1610449069957,\n",
" labels: { traceID: '5020b5bc45117f07' },\n",
" value: 0.002074123,\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" timestamp: 1610449069.957,\n"
],
"file_path": "public/app/plugins/datasource/prometheus/result_transformer.test.ts",
"type": "replace",
"edit_start_line_idx": 494
} | import { DataFrame, FieldType } from '@grafana/data';
import { transform } from './result_transformer';
jest.mock('@grafana/runtime', () => ({
getTemplateSrv: () => ({
replace: (str: string) => str,
}),
getDataSourceSrv: () => {
return {
getInstanceSettings: () => {
return { name: 'Tempo' };
},
};
},
}));
const matrixResponse = {
status: 'success',
data: {
resultType: 'matrix',
result: [
{
metric: { __name__: 'test', job: 'testjob' },
values: [
[1, '10'],
[2, '0'],
],
},
],
},
};
describe('Prometheus Result Transformer', () => {
const options: any = { target: {}, query: {} };
describe('When nothing is returned', () => {
it('should return empty array', () => {
const response = {
status: 'success',
data: {
resultType: '',
result: null,
},
};
const series = transform({ data: response } as any, options);
expect(series).toEqual([]);
});
it('should return empty array', () => {
const response = {
status: 'success',
data: {
resultType: '',
result: null,
},
};
const result = transform({ data: response } as any, { ...options, target: { format: 'table' } });
expect(result).toHaveLength(0);
});
});
describe('When resultFormat is table', () => {
const response = {
status: 'success',
data: {
resultType: 'matrix',
result: [
{
metric: { __name__: 'test', job: 'testjob' },
values: [
[1443454528, '3846'],
[1443454530, '3848'],
],
},
{
metric: {
__name__: 'test2',
instance: 'localhost:8080',
job: 'otherjob',
},
values: [
[1443454529, '3847'],
[1443454531, '3849'],
],
},
],
},
};
it('should return data frame', () => {
const result = transform({ data: response } as any, {
...options,
target: {
responseListLength: 0,
refId: 'A',
format: 'table',
},
});
expect(result[0].fields[0].values.toArray()).toEqual([
1443454528000,
1443454530000,
1443454529000,
1443454531000,
]);
expect(result[0].fields[0].name).toBe('Time');
expect(result[0].fields[0].type).toBe(FieldType.time);
expect(result[0].fields[1].values.toArray()).toEqual(['test', 'test', 'test2', 'test2']);
expect(result[0].fields[1].name).toBe('__name__');
expect(result[0].fields[1].config.filterable).toBe(true);
expect(result[0].fields[1].type).toBe(FieldType.string);
expect(result[0].fields[2].values.toArray()).toEqual(['', '', 'localhost:8080', 'localhost:8080']);
expect(result[0].fields[2].name).toBe('instance');
expect(result[0].fields[2].type).toBe(FieldType.string);
expect(result[0].fields[3].values.toArray()).toEqual(['testjob', 'testjob', 'otherjob', 'otherjob']);
expect(result[0].fields[3].name).toBe('job');
expect(result[0].fields[3].type).toBe(FieldType.string);
expect(result[0].fields[4].values.toArray()).toEqual([3846, 3848, 3847, 3849]);
expect(result[0].fields[4].name).toEqual('Value');
expect(result[0].fields[4].type).toBe(FieldType.number);
expect(result[0].refId).toBe('A');
});
it('should include refId if response count is more than 2', () => {
const result = transform({ data: response } as any, {
...options,
target: {
refId: 'B',
format: 'table',
},
responseListLength: 2,
});
expect(result[0].fields[4].name).toEqual('Value #B');
});
});
describe('When resultFormat is table and instant = true', () => {
const response = {
status: 'success',
data: {
resultType: 'vector',
result: [
{
metric: { __name__: 'test', job: 'testjob' },
value: [1443454528, '3846'],
},
],
},
};
it('should return data frame', () => {
const result = transform({ data: response } as any, { ...options, target: { format: 'table' } });
expect(result[0].fields[0].values.toArray()).toEqual([1443454528000]);
expect(result[0].fields[0].name).toBe('Time');
expect(result[0].fields[1].values.toArray()).toEqual(['test']);
expect(result[0].fields[1].name).toBe('__name__');
expect(result[0].fields[2].values.toArray()).toEqual(['testjob']);
expect(result[0].fields[2].name).toBe('job');
expect(result[0].fields[3].values.toArray()).toEqual([3846]);
expect(result[0].fields[3].name).toEqual('Value');
});
it('should return le label values parsed as numbers', () => {
const response = {
status: 'success',
data: {
resultType: 'vector',
result: [
{
metric: { le: '102' },
value: [1594908838, '0'],
},
],
},
};
const result = transform({ data: response } as any, { ...options, target: { format: 'table' } });
expect(result[0].fields[1].values.toArray()).toEqual([102]);
expect(result[0].fields[1].type).toEqual(FieldType.number);
});
});
describe('When instant = true', () => {
const response = {
status: 'success',
data: {
resultType: 'vector',
result: [
{
metric: { __name__: 'test', job: 'testjob' },
value: [1443454528, '3846'],
},
],
},
};
it('should return data frame', () => {
const result: DataFrame[] = transform({ data: response } as any, { ...options, query: { instant: true } });
expect(result[0].name).toBe('test{job="testjob"}');
});
});
describe('When resultFormat is heatmap', () => {
const getResponse = (result: any) => ({
status: 'success',
data: {
resultType: 'matrix',
result,
},
});
const options = {
format: 'heatmap',
start: 1445000010,
end: 1445000030,
legendFormat: '{{le}}',
};
it('should convert cumulative histogram to regular', () => {
const response = getResponse([
{
metric: { __name__: 'test', job: 'testjob', le: '1' },
values: [
[1445000010, '10'],
[1445000020, '10'],
[1445000030, '0'],
],
},
{
metric: { __name__: 'test', job: 'testjob', le: '2' },
values: [
[1445000010, '20'],
[1445000020, '10'],
[1445000030, '30'],
],
},
{
metric: { __name__: 'test', job: 'testjob', le: '3' },
values: [
[1445000010, '30'],
[1445000020, '10'],
[1445000030, '40'],
],
},
]);
const result = transform({ data: response } as any, { query: options, target: options } as any);
expect(result[0].fields[0].values.toArray()).toEqual([1445000010000, 1445000020000, 1445000030000]);
expect(result[0].fields[1].values.toArray()).toEqual([10, 10, 0]);
expect(result[1].fields[0].values.toArray()).toEqual([1445000010000, 1445000020000, 1445000030000]);
expect(result[1].fields[1].values.toArray()).toEqual([10, 0, 30]);
expect(result[2].fields[0].values.toArray()).toEqual([1445000010000, 1445000020000, 1445000030000]);
expect(result[2].fields[1].values.toArray()).toEqual([10, 0, 10]);
});
it('should handle missing datapoints', () => {
const response = getResponse([
{
metric: { __name__: 'test', job: 'testjob', le: '1' },
values: [
[1445000010, '1'],
[1445000020, '2'],
],
},
{
metric: { __name__: 'test', job: 'testjob', le: '2' },
values: [
[1445000010, '2'],
[1445000020, '5'],
[1445000030, '1'],
],
},
{
metric: { __name__: 'test', job: 'testjob', le: '3' },
values: [
[1445000010, '3'],
[1445000020, '7'],
],
},
]);
const result = transform({ data: response } as any, { query: options, target: options } as any);
expect(result[0].fields[1].values.toArray()).toEqual([1, 2]);
expect(result[1].fields[1].values.toArray()).toEqual([1, 3, 1]);
expect(result[2].fields[1].values.toArray()).toEqual([1, 2]);
});
});
describe('When the response is a matrix', () => {
it('should have labels with the value field', () => {
const response = {
status: 'success',
data: {
resultType: 'matrix',
result: [
{
metric: { __name__: 'test', job: 'testjob', instance: 'testinstance' },
values: [
[0, '10'],
[1, '10'],
[2, '0'],
],
},
],
},
};
const result: DataFrame[] = transform({ data: response } as any, {
...options,
});
expect(result[0].fields[1].labels).toBeDefined();
expect(result[0].fields[1].labels?.instance).toBe('testinstance');
expect(result[0].fields[1].labels?.job).toBe('testjob');
});
it('should transform into a data frame', () => {
const response = {
status: 'success',
data: {
resultType: 'matrix',
result: [
{
metric: { __name__: 'test', job: 'testjob' },
values: [
[0, '10'],
[1, '10'],
[2, '0'],
],
},
],
},
};
const result: DataFrame[] = transform({ data: response } as any, {
...options,
query: {
start: 0,
end: 2,
},
});
expect(result[0].fields[0].values.toArray()).toEqual([0, 1000, 2000]);
expect(result[0].fields[1].values.toArray()).toEqual([10, 10, 0]);
expect(result[0].name).toBe('test{job="testjob"}');
});
it('should fill null values', () => {
const result = transform({ data: matrixResponse } as any, { ...options, query: { step: 1, start: 0, end: 2 } });
expect(result[0].fields[0].values.toArray()).toEqual([0, 1000, 2000]);
expect(result[0].fields[1].values.toArray()).toEqual([null, 10, 0]);
});
it('should use __name__ label as series name', () => {
const result = transform({ data: matrixResponse } as any, {
...options,
query: {
step: 1,
start: 0,
end: 2,
},
});
expect(result[0].name).toEqual('test{job="testjob"}');
});
it('should use query as series name when __name__ is not available and metric is empty', () => {
const response = {
status: 'success',
data: {
resultType: 'matrix',
result: [
{
metric: {},
values: [[0, '10']],
},
],
},
};
const expr = 'histogram_quantile(0.95, sum(rate(tns_request_duration_seconds_bucket[5m])) by (le))';
const result = transform({ data: response } as any, {
...options,
query: {
step: 1,
start: 0,
end: 2,
expr,
},
});
expect(result[0].name).toEqual(expr);
});
it('should set frame name to undefined if no __name__ label but there are other labels', () => {
const response = {
status: 'success',
data: {
resultType: 'matrix',
result: [
{
metric: { job: 'testjob' },
values: [
[1, '10'],
[2, '0'],
],
},
],
},
};
const result = transform({ data: response } as any, {
...options,
query: {
step: 1,
start: 0,
end: 2,
},
});
expect(result[0].name).toBe('{job="testjob"}');
});
it('should not set displayName for ValueFields', () => {
const result = transform({ data: matrixResponse } as any, options);
expect(result[0].fields[1].config.displayName).toBeUndefined();
expect(result[0].fields[1].config.displayNameFromDS).toBe('test{job="testjob"}');
});
it('should align null values with step', () => {
const response = {
status: 'success',
data: {
resultType: 'matrix',
result: [
{
metric: { __name__: 'test', job: 'testjob' },
values: [
[4, '10'],
[8, '10'],
],
},
],
},
};
const result = transform({ data: response } as any, { ...options, query: { step: 2, start: 0, end: 8 } });
expect(result[0].fields[0].values.toArray()).toEqual([0, 2000, 4000, 6000, 8000]);
expect(result[0].fields[1].values.toArray()).toEqual([null, null, 10, null, 10]);
});
});
describe('When infinity values are returned', () => {
describe('When resultType is scalar', () => {
const response = {
status: 'success',
data: {
resultType: 'scalar',
result: [1443454528, '+Inf'],
},
};
it('should correctly parse values', () => {
const result: DataFrame[] = transform({ data: response } as any, { ...options, target: { format: 'table' } });
expect(result[0].fields[1].values.toArray()).toEqual([Number.POSITIVE_INFINITY]);
});
});
describe('When resultType is vector', () => {
const response = {
status: 'success',
data: {
resultType: 'vector',
result: [
{
metric: { __name__: 'test', job: 'testjob' },
value: [1443454528, '+Inf'],
},
{
metric: { __name__: 'test', job: 'testjob' },
value: [1443454528, '-Inf'],
},
],
},
};
describe('When format is table', () => {
it('should correctly parse values', () => {
const result: DataFrame[] = transform({ data: response } as any, { ...options, target: { format: 'table' } });
expect(result[0].fields[3].values.toArray()).toEqual([Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]);
});
});
});
});
const exemplarsResponse = {
status: 'success',
data: [
{
seriesLabels: { __name__: 'test' },
exemplars: [
{
timestamp: 1610449069957,
labels: { traceID: '5020b5bc45117f07' },
value: 0.002074123,
},
],
},
],
};
describe('When the response is exemplar data', () => {
it('should return as an data frame with a dataTopic annotations', () => {
const result = transform({ data: exemplarsResponse } as any, options);
expect(result[0].meta?.dataTopic).toBe('annotations');
expect(result[0].fields.length).toBe(4); // __name__, traceID, Time, Value
expect(result[0].length).toBe(1);
});
it('should remove exemplars that are too close to each other', () => {
const response = {
status: 'success',
data: [
{
exemplars: [
{
timestamp: 1610449070000,
value: 5,
},
{
timestamp: 1610449070000,
value: 1,
},
{
timestamp: 1610449070500,
value: 13,
},
{
timestamp: 1610449070300,
value: 20,
},
],
},
],
};
/**
* the standard deviation for the above values is 8.4 this means that we show the highest
* value (20) and then the next value should be 2 times the standard deviation which is 1
**/
const result = transform({ data: response } as any, options);
expect(result[0].length).toBe(2);
});
describe('data link', () => {
it('should be added to the field if found with url', () => {
const result = transform({ data: exemplarsResponse } as any, {
...options,
exemplarTraceIdDestinations: [{ name: 'traceID', url: 'http://localhost' }],
});
expect(result[0].fields.some((f) => f.config.links?.length)).toBe(true);
});
it('should be added to the field if found with internal link', () => {
const result = transform({ data: exemplarsResponse } as any, {
...options,
exemplarTraceIdDestinations: [{ name: 'traceID', datasourceUid: 'jaeger' }],
});
expect(result[0].fields.some((f) => f.config.links?.length)).toBe(true);
});
it('should not add link if exemplarTraceIdDestinations is not configured', () => {
const result = transform({ data: exemplarsResponse } as any, options);
expect(result[0].fields.some((f) => f.config.links?.length)).toBe(false);
});
});
});
});
| public/app/plugins/datasource/prometheus/result_transformer.test.ts | 1 | https://github.com/grafana/grafana/commit/8c35ed40147946c36ae318b54cfe29275553ceea | [
0.965610921382904,
0.016908295452594757,
0.0001649370533414185,
0.00017058156663551927,
0.12565937638282776
] |
{
"id": 0,
"code_window": [
" seriesLabels: { __name__: 'test' },\n",
" exemplars: [\n",
" {\n",
" timestamp: 1610449069957,\n",
" labels: { traceID: '5020b5bc45117f07' },\n",
" value: 0.002074123,\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" timestamp: 1610449069.957,\n"
],
"file_path": "public/app/plugins/datasource/prometheus/result_transformer.test.ts",
"type": "replace",
"edit_start_line_idx": 494
} | #!/bin/sh
##
# Script to deploy a docker image. Must return exit code 0
#
do_exit() {
message="$1"
exit_code="$2"
echo "$message"
exit $exit_code
}
##
# Get file, get's a file, validates the SHA
# @param filename
# @param expected sha value
# @returns 0 if successful, -1 of checksum validation failed.
#
get_file () {
[ -n "$1" ] && url=$1 || do_exit "url required" 1
[ -n "$2" ] && dest=$2 || do_exit "destination required" 2
sha=$3
file=$(basename $dest)
curl -fL "${url}" -o "$dest"
if [ -n "$sha" ]; then
echo "$sha $dest" | sha256sum || do_exit "Checksum validation failed for $file. Exiting" 1
fi
}
untar_file () {
[ -n "$1" ] && src=$1 || do_exit "src required" 1
[ -n "$2" ] && dest=$2 || dest="/usr/local"
tar -C "$dest" -xf "$src" && /bin/rm -rf "$src"
}
##
# WIP: Just started this and not finished.
# The intent it to download a release from a git repo,
# compile, and install
get_latest_release () {
tarsrc=$(curl -sL "https://api.github.com/repos/$1/$2/releases/latest" | jq ".tarball_url" | tr -d '"')
curl -fL -o /tmp/autoretrieved.tar.gz "$tarsrc"
origdir=$PWD
reponame=$(tar zxvf autoretrieved.tar.gz | tail -1 | awk -F / '{print $1}')
cd "/tmp/$reponame"
#perform compile
cd $origdir
}
| packages/grafana-toolkit/docker/grafana-plugin-ci-alpine/scripts/deploy-common.sh | 0 | https://github.com/grafana/grafana/commit/8c35ed40147946c36ae318b54cfe29275553ceea | [
0.00017515369108878076,
0.0001706421171547845,
0.00016750222130212933,
0.00017081023543141782,
0.0000025333245048386743
] |
{
"id": 0,
"code_window": [
" seriesLabels: { __name__: 'test' },\n",
" exemplars: [\n",
" {\n",
" timestamp: 1610449069957,\n",
" labels: { traceID: '5020b5bc45117f07' },\n",
" value: 0.002074123,\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" timestamp: 1610449069.957,\n"
],
"file_path": "public/app/plugins/datasource/prometheus/result_transformer.test.ts",
"type": "replace",
"edit_start_line_idx": 494
} | import _ from 'lodash';
import { Observable, of, throwError } from 'rxjs';
import {
ArrayVector,
CoreApp,
DataQueryRequest,
DataSourceInstanceSettings,
DataSourcePluginMeta,
dateMath,
DateTime,
dateTime,
Field,
MutableDataFrame,
TimeRange,
toUtc,
} from '@grafana/data';
import { BackendSrvRequest, FetchResponse } from '@grafana/runtime';
import { ElasticDatasource, enhanceDataFrame } from './datasource';
import { backendSrv } from 'app/core/services/backend_srv'; // will use the version in __mocks__
import { ElasticsearchOptions, ElasticsearchQuery } from './types';
import { Filters } from './components/QueryEditor/BucketAggregationsEditor/aggregations';
import { createFetchResponse } from '../../../../test/helpers/createFetchResponse';
const ELASTICSEARCH_MOCK_URL = 'http://elasticsearch.local';
jest.mock('@grafana/runtime', () => ({
...((jest.requireActual('@grafana/runtime') as unknown) as object),
getBackendSrv: () => backendSrv,
getDataSourceSrv: () => {
return {
getInstanceSettings: () => {
return { name: 'elastic25' };
},
};
},
}));
const createTimeRange = (from: DateTime, to: DateTime): TimeRange => ({
from,
to,
raw: {
from,
to,
},
});
interface Args {
data?: any;
from?: string;
jsonData?: any;
database?: string;
mockImplementation?: (options: BackendSrvRequest) => Observable<FetchResponse>;
}
function getTestContext({
data = {},
from = 'now-5m',
jsonData = {},
database = '[asd-]YYYY.MM.DD',
mockImplementation = undefined,
}: Args = {}) {
jest.clearAllMocks();
const defaultMock = (options: BackendSrvRequest) => of(createFetchResponse(data));
const fetchMock = jest.spyOn(backendSrv, 'fetch');
fetchMock.mockImplementation(mockImplementation ?? defaultMock);
const templateSrv: any = {
replace: jest.fn((text) => {
if (text.startsWith('$')) {
return `resolvedVariable`;
} else {
return text;
}
}),
getAdhocFilters: jest.fn(() => []),
};
const timeSrv: any = {
time: { from, to: 'now' },
};
timeSrv.timeRange = jest.fn(() => {
return {
from: dateMath.parse(timeSrv.time.from, false),
to: dateMath.parse(timeSrv.time.to, true),
};
});
timeSrv.setTime = jest.fn((time) => {
timeSrv.time = time;
});
const instanceSettings: DataSourceInstanceSettings<ElasticsearchOptions> = {
id: 1,
meta: {} as DataSourcePluginMeta,
name: 'test-elastic',
type: 'type',
uid: 'uid',
url: ELASTICSEARCH_MOCK_URL,
database,
jsonData,
};
const ds = new ElasticDatasource(instanceSettings, templateSrv);
return { timeSrv, ds, fetchMock };
}
describe('ElasticDatasource', function (this: any) {
describe('When testing datasource with index pattern', () => {
it('should translate index pattern to current day', () => {
const { ds, fetchMock } = getTestContext({ jsonData: { interval: 'Daily', esVersion: 2 } });
ds.testDatasource();
const today = toUtc().format('YYYY.MM.DD');
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock.mock.calls[0][0].url).toBe(`${ELASTICSEARCH_MOCK_URL}/asd-${today}/_mapping`);
});
});
describe('When issuing metric query with interval pattern', () => {
async function runScenario() {
const range = { from: toUtc([2015, 4, 30, 10]), to: toUtc([2015, 5, 1, 10]) };
const targets = [
{
alias: '$varAlias',
bucketAggs: [{ type: 'date_histogram', field: '@timestamp', id: '1' }],
metrics: [{ type: 'count', id: '1' }],
query: 'escape\\:test',
},
];
const query: any = { range, targets };
const data = {
responses: [
{
aggregations: {
'1': {
buckets: [
{
doc_count: 10,
key: 1000,
},
],
},
},
},
],
};
const { ds, fetchMock } = getTestContext({ jsonData: { interval: 'Daily', esVersion: 2 }, data });
let result: any = {};
await expect(ds.query(query)).toEmitValuesWith((received) => {
expect(received.length).toBe(1);
expect(received[0]).toEqual({
data: [
{
datapoints: [[10, 1000]],
metric: 'count',
props: {},
refId: undefined,
target: 'resolvedVariable',
},
],
});
result = received[0];
});
expect(fetchMock).toHaveBeenCalledTimes(1);
const requestOptions = fetchMock.mock.calls[0][0];
const parts = requestOptions.data.split('\n');
const header = JSON.parse(parts[0]);
const body = JSON.parse(parts[1]);
return { result, body, header, query };
}
it('should translate index pattern to current day', async () => {
const { header } = await runScenario();
expect(header.index).toEqual(['asd-2015.05.30', 'asd-2015.05.31', 'asd-2015.06.01']);
});
it('should not resolve the variable in the original alias field in the query', async () => {
const { query } = await runScenario();
expect(query.targets[0].alias).toEqual('$varAlias');
});
it('should resolve the alias variable for the alias/target in the result', async () => {
const { result } = await runScenario();
expect(result.data[0].target).toEqual('resolvedVariable');
});
it('should json escape lucene query', async () => {
const { body } = await runScenario();
expect(body.query.bool.filter[1].query_string.query).toBe('escape\\:test');
});
});
describe('When issuing logs query with interval pattern', () => {
async function setupDataSource(jsonData?: Partial<ElasticsearchOptions>) {
jsonData = {
interval: 'Daily',
esVersion: 2,
timeField: '@timestamp',
...(jsonData || {}),
};
const { ds } = getTestContext({
jsonData,
data: logsResponse.data,
database: 'mock-index',
});
const query: DataQueryRequest<ElasticsearchQuery> = {
range: createTimeRange(toUtc([2015, 4, 30, 10]), toUtc([2019, 7, 1, 10])),
targets: [
{
alias: '$varAlias',
refId: 'A',
bucketAggs: [
{
type: 'date_histogram',
settings: { interval: 'auto' },
id: '2',
},
],
metrics: [{ type: 'count', id: '1' }],
query: 'escape\\:test',
isLogsQuery: true,
timeField: '@timestamp',
},
],
} as DataQueryRequest<ElasticsearchQuery>;
const queryBuilderSpy = jest.spyOn(ds.queryBuilder, 'getLogsQuery');
let response: any = {};
await expect(ds.query(query)).toEmitValuesWith((received) => {
expect(received.length).toBe(1);
response = received[0];
});
return { queryBuilderSpy, response };
}
it('should call getLogsQuery()', async () => {
const { queryBuilderSpy } = await setupDataSource();
expect(queryBuilderSpy).toHaveBeenCalled();
});
it('should enhance fields with links', async () => {
const { response } = await setupDataSource({
dataLinks: [
{
field: 'host',
url: 'http://localhost:3000/${__value.raw}',
},
],
});
expect(response.data.length).toBe(1);
const links = response.data[0].fields.find((field: Field) => field.name === 'host').config.links;
expect(links.length).toBe(1);
expect(links[0].url).toBe('http://localhost:3000/${__value.raw}');
});
});
describe('When issuing document query', () => {
async function runScenario() {
const range = createTimeRange(dateTime([2015, 4, 30, 10]), dateTime([2015, 5, 1, 10]));
const targets = [{ refId: 'A', metrics: [{ type: 'raw_document', id: '1' }], query: 'test' }];
const query: any = { range, targets };
const data = { responses: [] };
const { ds, fetchMock } = getTestContext({ jsonData: { esVersion: 2 }, data, database: 'test' });
await expect(ds.query(query)).toEmitValuesWith((received) => {
expect(received.length).toBe(1);
expect(received[0]).toEqual({ data: [] });
});
expect(fetchMock).toHaveBeenCalledTimes(1);
const requestOptions = fetchMock.mock.calls[0][0];
const parts = requestOptions.data.split('\n');
const header = JSON.parse(parts[0]);
const body = JSON.parse(parts[1]);
return { body, header };
}
it('should set search type to query_then_fetch', async () => {
const { header } = await runScenario();
expect(header.search_type).toEqual('query_then_fetch');
});
it('should set size', async () => {
const { body } = await runScenario();
expect(body.size).toBe(500);
});
});
describe('When getting an error on response', () => {
const query: DataQueryRequest<ElasticsearchQuery> = {
range: createTimeRange(toUtc([2020, 1, 1, 10]), toUtc([2020, 2, 1, 10])),
targets: [
{
refId: 'A',
alias: '$varAlias',
bucketAggs: [{ type: 'date_histogram', field: '@timestamp', id: '1' }],
metrics: [{ type: 'count', id: '1' }],
query: 'escape\\:test',
},
],
} as DataQueryRequest<ElasticsearchQuery>;
it('should process it properly', async () => {
const { ds } = getTestContext({
jsonData: { interval: 'Daily', esVersion: 7 },
data: {
took: 1,
responses: [
{
error: {
reason: 'all shards failed',
},
status: 400,
},
],
},
});
const errObject = {
data: '{\n "reason": "all shards failed"\n}',
message: 'all shards failed',
config: {
url: 'http://localhost:3000/api/tsdb/query',
},
};
await expect(ds.query(query)).toEmitValuesWith((received) => {
expect(received.length).toBe(1);
expect(received[0]).toEqual(errObject);
});
});
it('should properly throw an error with just a message', async () => {
const response: FetchResponse = {
data: {
error: 'Bad Request',
message: 'Authentication to data source failed',
},
status: 400,
url: 'http://localhost:3000/api/tsdb/query',
config: { url: 'http://localhost:3000/api/tsdb/query' },
type: 'basic',
statusText: 'Bad Request',
redirected: false,
headers: ({} as unknown) as Headers,
ok: false,
};
const { ds } = getTestContext({
mockImplementation: () => throwError(response),
});
const errObject = {
error: 'Bad Request',
message: 'Elasticsearch error: Authentication to data source failed',
};
await expect(ds.query(query)).toEmitValuesWith((received) => {
expect(received.length).toBe(1);
expect(received[0]).toEqual(errObject);
});
});
it('should properly throw an unknown error', async () => {
const { ds } = getTestContext({
jsonData: { interval: 'Daily', esVersion: 7 },
data: {
took: 1,
responses: [
{
error: {},
status: 400,
},
],
},
});
const errObject = {
data: '{}',
message: 'Unknown elastic error response',
config: {
url: 'http://localhost:3000/api/tsdb/query',
},
};
await expect(ds.query(query)).toEmitValuesWith((received) => {
expect(received.length).toBe(1);
expect(received[0]).toEqual(errObject);
});
});
});
describe('When getting fields', () => {
const data = {
metricbeat: {
mappings: {
metricsets: {
_all: {},
_meta: {
test: 'something',
},
properties: {
'@timestamp': { type: 'date' },
__timestamp: { type: 'date' },
'@timestampnano': { type: 'date_nanos' },
beat: {
properties: {
name: {
fields: { raw: { type: 'keyword' } },
type: 'string',
},
hostname: { type: 'string' },
},
},
system: {
properties: {
cpu: {
properties: {
system: { type: 'float' },
user: { type: 'float' },
},
},
process: {
properties: {
cpu: {
properties: {
total: { type: 'float' },
},
},
name: { type: 'string' },
},
},
},
},
},
},
},
},
};
it('should return nested fields', async () => {
const { ds } = getTestContext({ data, jsonData: { esVersion: 50 }, database: 'metricbeat' });
await expect(ds.getFields()).toEmitValuesWith((received) => {
expect(received.length).toBe(1);
const fieldObjects = received[0];
const fields = _.map(fieldObjects, 'text');
expect(fields).toEqual([
'@timestamp',
'__timestamp',
'@timestampnano',
'beat.name.raw',
'beat.name',
'beat.hostname',
'system.cpu.system',
'system.cpu.user',
'system.process.cpu.total',
'system.process.name',
]);
});
});
it('should return number fields', async () => {
const { ds } = getTestContext({ data, jsonData: { esVersion: 50 }, database: 'metricbeat' });
await expect(ds.getFields('number')).toEmitValuesWith((received) => {
expect(received.length).toBe(1);
const fieldObjects = received[0];
const fields = _.map(fieldObjects, 'text');
expect(fields).toEqual(['system.cpu.system', 'system.cpu.user', 'system.process.cpu.total']);
});
});
it('should return date fields', async () => {
const { ds } = getTestContext({ data, jsonData: { esVersion: 50 }, database: 'metricbeat' });
await expect(ds.getFields('date')).toEmitValuesWith((received) => {
expect(received.length).toBe(1);
const fieldObjects = received[0];
const fields = _.map(fieldObjects, 'text');
expect(fields).toEqual(['@timestamp', '__timestamp', '@timestampnano']);
});
});
});
describe('When getting field mappings on indices with gaps', () => {
const basicResponse = {
metricbeat: {
mappings: {
metricsets: {
_all: {},
properties: {
'@timestamp': { type: 'date' },
beat: {
properties: {
hostname: { type: 'string' },
},
},
},
},
},
},
};
const alternateResponse = {
metricbeat: {
mappings: {
metricsets: {
_all: {},
properties: {
'@timestamp': { type: 'date' },
},
},
},
},
};
it('should return fields of the newest available index', async () => {
const twoDaysBefore = toUtc().subtract(2, 'day').format('YYYY.MM.DD');
const threeDaysBefore = toUtc().subtract(3, 'day').format('YYYY.MM.DD');
const baseUrl = `${ELASTICSEARCH_MOCK_URL}/asd-${twoDaysBefore}/_mapping`;
const alternateUrl = `${ELASTICSEARCH_MOCK_URL}/asd-${threeDaysBefore}/_mapping`;
const { ds, timeSrv } = getTestContext({
from: 'now-2w',
jsonData: { interval: 'Daily', esVersion: 50 },
mockImplementation: (options) => {
if (options.url === baseUrl) {
return of(createFetchResponse(basicResponse));
} else if (options.url === alternateUrl) {
return of(createFetchResponse(alternateResponse));
}
return throwError({ status: 404 });
},
});
const range = timeSrv.timeRange();
await expect(ds.getFields(undefined, range)).toEmitValuesWith((received) => {
expect(received.length).toBe(1);
const fieldObjects = received[0];
const fields = _.map(fieldObjects, 'text');
expect(fields).toEqual(['@timestamp', 'beat.hostname']);
});
});
it('should not retry when ES is down', async () => {
const twoDaysBefore = toUtc().subtract(2, 'day').format('YYYY.MM.DD');
const { ds, timeSrv, fetchMock } = getTestContext({
from: 'now-2w',
jsonData: { interval: 'Daily', esVersion: 50 },
mockImplementation: (options) => {
if (options.url === `${ELASTICSEARCH_MOCK_URL}/asd-${twoDaysBefore}/_mapping`) {
return of(createFetchResponse(basicResponse));
}
return throwError({ status: 500 });
},
});
const range = timeSrv.timeRange();
await expect(ds.getFields(undefined, range)).toEmitValuesWith((received) => {
expect(received.length).toBe(1);
expect(received[0]).toStrictEqual({ status: 500 });
expect(fetchMock).toBeCalledTimes(1);
});
});
it('should not retry more than 7 indices', async () => {
const { ds, timeSrv, fetchMock } = getTestContext({
from: 'now-2w',
jsonData: { interval: 'Daily', esVersion: 50 },
mockImplementation: (options) => {
return throwError({ status: 404 });
},
});
const range = timeSrv.timeRange();
await expect(ds.getFields(undefined, range)).toEmitValuesWith((received) => {
expect(received.length).toBe(1);
expect(received[0]).toStrictEqual('Could not find an available index for this time range.');
expect(fetchMock).toBeCalledTimes(7);
});
});
});
describe('When getting fields from ES 7.0', () => {
const data = {
'genuine.es7._mapping.response': {
mappings: {
properties: {
'@timestamp_millis': {
type: 'date',
format: 'epoch_millis',
},
classification_terms: {
type: 'keyword',
},
domains: {
type: 'keyword',
},
ip_address: {
type: 'ip',
},
justification_blob: {
properties: {
criterion: {
type: 'text',
fields: {
keyword: {
type: 'keyword',
ignore_above: 256,
},
},
},
overall_vote_score: {
type: 'float',
},
shallow: {
properties: {
jsi: {
properties: {
sdb: {
properties: {
dsel2: {
properties: {
'bootlegged-gille': {
properties: {
botness: {
type: 'float',
},
general_algorithm_score: {
type: 'float',
},
},
},
'uncombed-boris': {
properties: {
botness: {
type: 'float',
},
general_algorithm_score: {
type: 'float',
},
},
},
},
},
},
},
},
},
},
},
},
},
overall_vote_score: {
type: 'float',
},
ua_terms_long: {
type: 'keyword',
},
ua_terms_short: {
type: 'keyword',
},
},
},
},
};
it('should return nested fields', async () => {
const { ds } = getTestContext({ data, database: 'genuine.es7._mapping.response', jsonData: { esVersion: 70 } });
await expect(ds.getFields()).toEmitValuesWith((received) => {
expect(received.length).toBe(1);
const fieldObjects = received[0];
const fields = _.map(fieldObjects, 'text');
expect(fields).toEqual([
'@timestamp_millis',
'classification_terms',
'domains',
'ip_address',
'justification_blob.criterion.keyword',
'justification_blob.criterion',
'justification_blob.overall_vote_score',
'justification_blob.shallow.jsi.sdb.dsel2.bootlegged-gille.botness',
'justification_blob.shallow.jsi.sdb.dsel2.bootlegged-gille.general_algorithm_score',
'justification_blob.shallow.jsi.sdb.dsel2.uncombed-boris.botness',
'justification_blob.shallow.jsi.sdb.dsel2.uncombed-boris.general_algorithm_score',
'overall_vote_score',
'ua_terms_long',
'ua_terms_short',
]);
});
});
it('should return number fields', async () => {
const { ds } = getTestContext({ data, database: 'genuine.es7._mapping.response', jsonData: { esVersion: 70 } });
await expect(ds.getFields('number')).toEmitValuesWith((received) => {
expect(received.length).toBe(1);
const fieldObjects = received[0];
const fields = _.map(fieldObjects, 'text');
expect(fields).toEqual([
'justification_blob.overall_vote_score',
'justification_blob.shallow.jsi.sdb.dsel2.bootlegged-gille.botness',
'justification_blob.shallow.jsi.sdb.dsel2.bootlegged-gille.general_algorithm_score',
'justification_blob.shallow.jsi.sdb.dsel2.uncombed-boris.botness',
'justification_blob.shallow.jsi.sdb.dsel2.uncombed-boris.general_algorithm_score',
'overall_vote_score',
]);
});
});
it('should return date fields', async () => {
const { ds } = getTestContext({ data, database: 'genuine.es7._mapping.response', jsonData: { esVersion: 70 } });
await expect(ds.getFields('date')).toEmitValuesWith((received) => {
expect(received.length).toBe(1);
const fieldObjects = received[0];
const fields = _.map(fieldObjects, 'text');
expect(fields).toEqual(['@timestamp_millis']);
});
});
});
describe('When issuing aggregation query on es5.x', () => {
async function runScenario() {
const range = createTimeRange(dateTime([2015, 4, 30, 10]), dateTime([2015, 5, 1, 10]));
const targets = [
{
refId: 'A',
bucketAggs: [{ type: 'date_histogram', field: '@timestamp', id: '2' }],
metrics: [{ type: 'count', id: '1' }],
query: 'test',
},
];
const query: any = { range, targets };
const data = { responses: [] };
const { ds, fetchMock } = getTestContext({ jsonData: { esVersion: 5 }, data, database: 'test' });
await expect(ds.query(query)).toEmitValuesWith((received) => {
expect(received.length).toBe(1);
expect(received[0]).toEqual({ data: [] });
});
expect(fetchMock).toHaveBeenCalledTimes(1);
const requestOptions = fetchMock.mock.calls[0][0];
const parts = requestOptions.data.split('\n');
const header = JSON.parse(parts[0]);
const body = JSON.parse(parts[1]);
return { body, header };
}
it('should not set search type to count', async () => {
const { header } = await runScenario();
expect(header.search_type).not.toEqual('count');
});
it('should set size to 0', async () => {
const { body } = await runScenario();
expect(body.size).toBe(0);
});
});
describe('When issuing metricFind query on es5.x', () => {
async function runScenario() {
const data = {
responses: [
{
aggregations: {
'1': {
buckets: [
{ doc_count: 1, key: 'test' },
{
doc_count: 2,
key: 'test2',
key_as_string: 'test2_as_string',
},
],
},
},
},
],
};
const { ds, fetchMock } = getTestContext({ jsonData: { esVersion: 5 }, data, database: 'test' });
const results = await ds.metricFindQuery('{"find": "terms", "field": "test"}');
expect(fetchMock).toHaveBeenCalledTimes(1);
const requestOptions = fetchMock.mock.calls[0][0];
const parts = requestOptions.data.split('\n');
const header = JSON.parse(parts[0]);
const body = JSON.parse(parts[1]);
return { results, body, header };
}
it('should get results', async () => {
const { results } = await runScenario();
expect(results.length).toEqual(2);
});
it('should use key or key_as_string', async () => {
const { results } = await runScenario();
expect(results[0].text).toEqual('test');
expect(results[1].text).toEqual('test2_as_string');
});
it('should not set search type to count', async () => {
const { header } = await runScenario();
expect(header.search_type).not.toEqual('count');
});
it('should set size to 0', async () => {
const { body } = await runScenario();
expect(body.size).toBe(0);
});
it('should not set terms aggregation size to 0', async () => {
const { body } = await runScenario();
expect(body['aggs']['1']['terms'].size).not.toBe(0);
});
});
describe('query', () => {
it('should replace range as integer not string', async () => {
const { ds } = getTestContext({ jsonData: { interval: 'Daily', esVersion: 2, timeField: '@time' } });
const postMock = jest.fn((url: string, data: any) => of(createFetchResponse({ responses: [] })));
ds['post'] = postMock;
await expect(ds.query(createElasticQuery())).toEmitValuesWith((received) => {
expect(postMock).toHaveBeenCalledTimes(1);
const query = postMock.mock.calls[0][1];
expect(typeof JSON.parse(query.split('\n')[1]).query.bool.filter[0].range['@time'].gte).toBe('number');
});
});
});
it('should correctly interpolate variables in query', () => {
const { ds } = getTestContext();
const query: ElasticsearchQuery = {
refId: 'A',
bucketAggs: [{ type: 'filters', settings: { filters: [{ query: '$var', label: '' }] }, id: '1' }],
metrics: [{ type: 'count', id: '1' }],
query: '$var',
};
const interpolatedQuery = ds.interpolateVariablesInQueries([query], {})[0];
expect(interpolatedQuery.query).toBe('resolvedVariable');
expect((interpolatedQuery.bucketAggs![0] as Filters).settings!.filters![0].query).toBe('resolvedVariable');
});
it('should correctly handle empty query strings', () => {
const { ds } = getTestContext();
const query: ElasticsearchQuery = {
refId: 'A',
bucketAggs: [{ type: 'filters', settings: { filters: [{ query: '', label: '' }] }, id: '1' }],
metrics: [{ type: 'count', id: '1' }],
query: '',
};
const interpolatedQuery = ds.interpolateVariablesInQueries([query], {})[0];
expect(interpolatedQuery.query).toBe('*');
expect((interpolatedQuery.bucketAggs![0] as Filters).settings!.filters![0].query).toBe('*');
});
});
describe('enhanceDataFrame', () => {
it('adds links to dataframe', () => {
const df = new MutableDataFrame({
fields: [
{
name: 'urlField',
values: new ArrayVector([]),
},
{
name: 'traceField',
values: new ArrayVector([]),
},
],
});
enhanceDataFrame(df, [
{
field: 'urlField',
url: 'someUrl',
},
{
field: 'traceField',
url: 'query',
datasourceUid: 'dsUid',
},
]);
expect(df.fields[0].config.links!.length).toBe(1);
expect(df.fields[0].config.links![0]).toEqual({
title: '',
url: 'someUrl',
});
expect(df.fields[1].config.links!.length).toBe(1);
expect(df.fields[1].config.links![0]).toEqual({
title: '',
url: '',
internal: {
query: { query: 'query' },
datasourceName: 'elastic25',
datasourceUid: 'dsUid',
},
});
});
});
const createElasticQuery = (): DataQueryRequest<ElasticsearchQuery> => {
return {
requestId: '',
dashboardId: 0,
interval: '',
panelId: 0,
intervalMs: 1,
scopedVars: {},
timezone: '',
app: CoreApp.Dashboard,
startTime: 0,
range: {
from: dateTime([2015, 4, 30, 10]),
to: dateTime([2015, 5, 1, 10]),
} as any,
targets: [
{
refId: '',
isLogsQuery: false,
bucketAggs: [{ type: 'date_histogram', field: '@timestamp', id: '2' }],
metrics: [{ type: 'count', id: '' }],
query: 'test',
},
],
};
};
const logsResponse = {
data: {
responses: [
{
aggregations: {
'2': {
buckets: [
{
doc_count: 10,
key: 1000,
},
{
doc_count: 15,
key: 2000,
},
],
},
},
hits: {
hits: [
{
'@timestamp': ['2019-06-24T09:51:19.765Z'],
_id: 'fdsfs',
_type: '_doc',
_index: 'mock-index',
_source: {
'@timestamp': '2019-06-24T09:51:19.765Z',
host: 'djisaodjsoad',
message: 'hello, i am a message',
},
fields: {
'@timestamp': ['2019-06-24T09:51:19.765Z'],
},
},
{
'@timestamp': ['2019-06-24T09:52:19.765Z'],
_id: 'kdospaidopa',
_type: '_doc',
_index: 'mock-index',
_source: {
'@timestamp': '2019-06-24T09:52:19.765Z',
host: 'dsalkdakdop',
message: 'hello, i am also message',
},
fields: {
'@timestamp': ['2019-06-24T09:52:19.765Z'],
},
},
],
},
},
],
},
};
| public/app/plugins/datasource/elasticsearch/datasource.test.ts | 0 | https://github.com/grafana/grafana/commit/8c35ed40147946c36ae318b54cfe29275553ceea | [
0.00017842280794866383,
0.0001711509539745748,
0.0001649595651542768,
0.00017142943397630006,
0.0000031655720249545993
] |
{
"id": 0,
"code_window": [
" seriesLabels: { __name__: 'test' },\n",
" exemplars: [\n",
" {\n",
" timestamp: 1610449069957,\n",
" labels: { traceID: '5020b5bc45117f07' },\n",
" value: 0.002074123,\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" timestamp: 1610449069.957,\n"
],
"file_path": "public/app/plugins/datasource/prometheus/result_transformer.test.ts",
"type": "replace",
"edit_start_line_idx": 494
} | import { ComponentClass } from 'react';
import { KeyValue } from './data';
import { NavModel } from './navModel';
import { PluginMeta, GrafanaPlugin, PluginIncludeType } from './plugin';
export enum CoreApp {
Dashboard = 'dashboard',
Explore = 'explore',
}
export interface AppRootProps<T = KeyValue> {
meta: AppPluginMeta<T>;
path: string; // The URL path to this page
query: KeyValue; // The URL query parameters
/**
* Pass the nav model to the container... is there a better way?
*/
onNavChanged: (nav: NavModel) => void;
}
export interface AppPluginMeta<T = KeyValue> extends PluginMeta<T> {
// TODO anything specific to apps?
}
export class AppPlugin<T = KeyValue> extends GrafanaPlugin<AppPluginMeta<T>> {
// Content under: /a/${plugin-id}/*
root?: ComponentClass<AppRootProps<T>>;
rootNav?: NavModel; // Initial navigation model
// Old style pages
angularPages?: { [component: string]: any };
/**
* Called after the module has loaded, and before the app is used.
* This function may be called multiple times on the same instance.
* The first time, `this.meta` will be undefined
*/
init(meta: AppPluginMeta) {}
/**
* Set the component displayed under:
* /a/${plugin-id}/*
*
* If the NavModel is configured, the page will have a managed frame, otheriwse it has full control.
*
* NOTE: this structure will change in 7.2+ so that it is managed with a normal react router
*/
setRootPage(root: ComponentClass<AppRootProps<T>>, rootNav?: NavModel) {
this.root = root;
this.rootNav = rootNav;
return this;
}
setComponentsFromLegacyExports(pluginExports: any) {
if (pluginExports.ConfigCtrl) {
this.angularConfigCtrl = pluginExports.ConfigCtrl;
}
if (this.meta && this.meta.includes) {
for (const include of this.meta.includes) {
if (include.type === PluginIncludeType.page && include.component) {
const exp = pluginExports[include.component];
if (!exp) {
console.warn('App Page uses unknown component: ', include.component, this.meta);
continue;
}
if (!this.angularPages) {
this.angularPages = {};
}
this.angularPages[include.component] = exp;
}
}
}
}
}
/**
* Defines life cycle of a feature
* @internal
*/
export enum FeatureState {
alpha = 'alpha',
beta = 'beta',
}
| packages/grafana-data/src/types/app.ts | 0 | https://github.com/grafana/grafana/commit/8c35ed40147946c36ae318b54cfe29275553ceea | [
0.0001751343224896118,
0.00017069379100576043,
0.0001649486948736012,
0.00017170376668218523,
0.0000034467625482648145
] |
{
"id": 1,
"code_window": [
" status: 'success',\n",
" data: [\n",
" {\n",
" exemplars: [\n",
" {\n",
" timestamp: 1610449070000,\n",
" value: 5,\n",
" },\n",
" {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" timestamp: 1610449070.0,\n"
],
"file_path": "public/app/plugins/datasource/prometheus/result_transformer.test.ts",
"type": "replace",
"edit_start_line_idx": 519
} | import { DataFrame, FieldType } from '@grafana/data';
import { transform } from './result_transformer';
jest.mock('@grafana/runtime', () => ({
getTemplateSrv: () => ({
replace: (str: string) => str,
}),
getDataSourceSrv: () => {
return {
getInstanceSettings: () => {
return { name: 'Tempo' };
},
};
},
}));
const matrixResponse = {
status: 'success',
data: {
resultType: 'matrix',
result: [
{
metric: { __name__: 'test', job: 'testjob' },
values: [
[1, '10'],
[2, '0'],
],
},
],
},
};
describe('Prometheus Result Transformer', () => {
const options: any = { target: {}, query: {} };
describe('When nothing is returned', () => {
it('should return empty array', () => {
const response = {
status: 'success',
data: {
resultType: '',
result: null,
},
};
const series = transform({ data: response } as any, options);
expect(series).toEqual([]);
});
it('should return empty array', () => {
const response = {
status: 'success',
data: {
resultType: '',
result: null,
},
};
const result = transform({ data: response } as any, { ...options, target: { format: 'table' } });
expect(result).toHaveLength(0);
});
});
describe('When resultFormat is table', () => {
const response = {
status: 'success',
data: {
resultType: 'matrix',
result: [
{
metric: { __name__: 'test', job: 'testjob' },
values: [
[1443454528, '3846'],
[1443454530, '3848'],
],
},
{
metric: {
__name__: 'test2',
instance: 'localhost:8080',
job: 'otherjob',
},
values: [
[1443454529, '3847'],
[1443454531, '3849'],
],
},
],
},
};
it('should return data frame', () => {
const result = transform({ data: response } as any, {
...options,
target: {
responseListLength: 0,
refId: 'A',
format: 'table',
},
});
expect(result[0].fields[0].values.toArray()).toEqual([
1443454528000,
1443454530000,
1443454529000,
1443454531000,
]);
expect(result[0].fields[0].name).toBe('Time');
expect(result[0].fields[0].type).toBe(FieldType.time);
expect(result[0].fields[1].values.toArray()).toEqual(['test', 'test', 'test2', 'test2']);
expect(result[0].fields[1].name).toBe('__name__');
expect(result[0].fields[1].config.filterable).toBe(true);
expect(result[0].fields[1].type).toBe(FieldType.string);
expect(result[0].fields[2].values.toArray()).toEqual(['', '', 'localhost:8080', 'localhost:8080']);
expect(result[0].fields[2].name).toBe('instance');
expect(result[0].fields[2].type).toBe(FieldType.string);
expect(result[0].fields[3].values.toArray()).toEqual(['testjob', 'testjob', 'otherjob', 'otherjob']);
expect(result[0].fields[3].name).toBe('job');
expect(result[0].fields[3].type).toBe(FieldType.string);
expect(result[0].fields[4].values.toArray()).toEqual([3846, 3848, 3847, 3849]);
expect(result[0].fields[4].name).toEqual('Value');
expect(result[0].fields[4].type).toBe(FieldType.number);
expect(result[0].refId).toBe('A');
});
it('should include refId if response count is more than 2', () => {
const result = transform({ data: response } as any, {
...options,
target: {
refId: 'B',
format: 'table',
},
responseListLength: 2,
});
expect(result[0].fields[4].name).toEqual('Value #B');
});
});
describe('When resultFormat is table and instant = true', () => {
const response = {
status: 'success',
data: {
resultType: 'vector',
result: [
{
metric: { __name__: 'test', job: 'testjob' },
value: [1443454528, '3846'],
},
],
},
};
it('should return data frame', () => {
const result = transform({ data: response } as any, { ...options, target: { format: 'table' } });
expect(result[0].fields[0].values.toArray()).toEqual([1443454528000]);
expect(result[0].fields[0].name).toBe('Time');
expect(result[0].fields[1].values.toArray()).toEqual(['test']);
expect(result[0].fields[1].name).toBe('__name__');
expect(result[0].fields[2].values.toArray()).toEqual(['testjob']);
expect(result[0].fields[2].name).toBe('job');
expect(result[0].fields[3].values.toArray()).toEqual([3846]);
expect(result[0].fields[3].name).toEqual('Value');
});
it('should return le label values parsed as numbers', () => {
const response = {
status: 'success',
data: {
resultType: 'vector',
result: [
{
metric: { le: '102' },
value: [1594908838, '0'],
},
],
},
};
const result = transform({ data: response } as any, { ...options, target: { format: 'table' } });
expect(result[0].fields[1].values.toArray()).toEqual([102]);
expect(result[0].fields[1].type).toEqual(FieldType.number);
});
});
describe('When instant = true', () => {
const response = {
status: 'success',
data: {
resultType: 'vector',
result: [
{
metric: { __name__: 'test', job: 'testjob' },
value: [1443454528, '3846'],
},
],
},
};
it('should return data frame', () => {
const result: DataFrame[] = transform({ data: response } as any, { ...options, query: { instant: true } });
expect(result[0].name).toBe('test{job="testjob"}');
});
});
describe('When resultFormat is heatmap', () => {
const getResponse = (result: any) => ({
status: 'success',
data: {
resultType: 'matrix',
result,
},
});
const options = {
format: 'heatmap',
start: 1445000010,
end: 1445000030,
legendFormat: '{{le}}',
};
it('should convert cumulative histogram to regular', () => {
const response = getResponse([
{
metric: { __name__: 'test', job: 'testjob', le: '1' },
values: [
[1445000010, '10'],
[1445000020, '10'],
[1445000030, '0'],
],
},
{
metric: { __name__: 'test', job: 'testjob', le: '2' },
values: [
[1445000010, '20'],
[1445000020, '10'],
[1445000030, '30'],
],
},
{
metric: { __name__: 'test', job: 'testjob', le: '3' },
values: [
[1445000010, '30'],
[1445000020, '10'],
[1445000030, '40'],
],
},
]);
const result = transform({ data: response } as any, { query: options, target: options } as any);
expect(result[0].fields[0].values.toArray()).toEqual([1445000010000, 1445000020000, 1445000030000]);
expect(result[0].fields[1].values.toArray()).toEqual([10, 10, 0]);
expect(result[1].fields[0].values.toArray()).toEqual([1445000010000, 1445000020000, 1445000030000]);
expect(result[1].fields[1].values.toArray()).toEqual([10, 0, 30]);
expect(result[2].fields[0].values.toArray()).toEqual([1445000010000, 1445000020000, 1445000030000]);
expect(result[2].fields[1].values.toArray()).toEqual([10, 0, 10]);
});
it('should handle missing datapoints', () => {
const response = getResponse([
{
metric: { __name__: 'test', job: 'testjob', le: '1' },
values: [
[1445000010, '1'],
[1445000020, '2'],
],
},
{
metric: { __name__: 'test', job: 'testjob', le: '2' },
values: [
[1445000010, '2'],
[1445000020, '5'],
[1445000030, '1'],
],
},
{
metric: { __name__: 'test', job: 'testjob', le: '3' },
values: [
[1445000010, '3'],
[1445000020, '7'],
],
},
]);
const result = transform({ data: response } as any, { query: options, target: options } as any);
expect(result[0].fields[1].values.toArray()).toEqual([1, 2]);
expect(result[1].fields[1].values.toArray()).toEqual([1, 3, 1]);
expect(result[2].fields[1].values.toArray()).toEqual([1, 2]);
});
});
describe('When the response is a matrix', () => {
it('should have labels with the value field', () => {
const response = {
status: 'success',
data: {
resultType: 'matrix',
result: [
{
metric: { __name__: 'test', job: 'testjob', instance: 'testinstance' },
values: [
[0, '10'],
[1, '10'],
[2, '0'],
],
},
],
},
};
const result: DataFrame[] = transform({ data: response } as any, {
...options,
});
expect(result[0].fields[1].labels).toBeDefined();
expect(result[0].fields[1].labels?.instance).toBe('testinstance');
expect(result[0].fields[1].labels?.job).toBe('testjob');
});
it('should transform into a data frame', () => {
const response = {
status: 'success',
data: {
resultType: 'matrix',
result: [
{
metric: { __name__: 'test', job: 'testjob' },
values: [
[0, '10'],
[1, '10'],
[2, '0'],
],
},
],
},
};
const result: DataFrame[] = transform({ data: response } as any, {
...options,
query: {
start: 0,
end: 2,
},
});
expect(result[0].fields[0].values.toArray()).toEqual([0, 1000, 2000]);
expect(result[0].fields[1].values.toArray()).toEqual([10, 10, 0]);
expect(result[0].name).toBe('test{job="testjob"}');
});
it('should fill null values', () => {
const result = transform({ data: matrixResponse } as any, { ...options, query: { step: 1, start: 0, end: 2 } });
expect(result[0].fields[0].values.toArray()).toEqual([0, 1000, 2000]);
expect(result[0].fields[1].values.toArray()).toEqual([null, 10, 0]);
});
it('should use __name__ label as series name', () => {
const result = transform({ data: matrixResponse } as any, {
...options,
query: {
step: 1,
start: 0,
end: 2,
},
});
expect(result[0].name).toEqual('test{job="testjob"}');
});
it('should use query as series name when __name__ is not available and metric is empty', () => {
const response = {
status: 'success',
data: {
resultType: 'matrix',
result: [
{
metric: {},
values: [[0, '10']],
},
],
},
};
const expr = 'histogram_quantile(0.95, sum(rate(tns_request_duration_seconds_bucket[5m])) by (le))';
const result = transform({ data: response } as any, {
...options,
query: {
step: 1,
start: 0,
end: 2,
expr,
},
});
expect(result[0].name).toEqual(expr);
});
it('should set frame name to undefined if no __name__ label but there are other labels', () => {
const response = {
status: 'success',
data: {
resultType: 'matrix',
result: [
{
metric: { job: 'testjob' },
values: [
[1, '10'],
[2, '0'],
],
},
],
},
};
const result = transform({ data: response } as any, {
...options,
query: {
step: 1,
start: 0,
end: 2,
},
});
expect(result[0].name).toBe('{job="testjob"}');
});
it('should not set displayName for ValueFields', () => {
const result = transform({ data: matrixResponse } as any, options);
expect(result[0].fields[1].config.displayName).toBeUndefined();
expect(result[0].fields[1].config.displayNameFromDS).toBe('test{job="testjob"}');
});
it('should align null values with step', () => {
const response = {
status: 'success',
data: {
resultType: 'matrix',
result: [
{
metric: { __name__: 'test', job: 'testjob' },
values: [
[4, '10'],
[8, '10'],
],
},
],
},
};
const result = transform({ data: response } as any, { ...options, query: { step: 2, start: 0, end: 8 } });
expect(result[0].fields[0].values.toArray()).toEqual([0, 2000, 4000, 6000, 8000]);
expect(result[0].fields[1].values.toArray()).toEqual([null, null, 10, null, 10]);
});
});
describe('When infinity values are returned', () => {
describe('When resultType is scalar', () => {
const response = {
status: 'success',
data: {
resultType: 'scalar',
result: [1443454528, '+Inf'],
},
};
it('should correctly parse values', () => {
const result: DataFrame[] = transform({ data: response } as any, { ...options, target: { format: 'table' } });
expect(result[0].fields[1].values.toArray()).toEqual([Number.POSITIVE_INFINITY]);
});
});
describe('When resultType is vector', () => {
const response = {
status: 'success',
data: {
resultType: 'vector',
result: [
{
metric: { __name__: 'test', job: 'testjob' },
value: [1443454528, '+Inf'],
},
{
metric: { __name__: 'test', job: 'testjob' },
value: [1443454528, '-Inf'],
},
],
},
};
describe('When format is table', () => {
it('should correctly parse values', () => {
const result: DataFrame[] = transform({ data: response } as any, { ...options, target: { format: 'table' } });
expect(result[0].fields[3].values.toArray()).toEqual([Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]);
});
});
});
});
const exemplarsResponse = {
status: 'success',
data: [
{
seriesLabels: { __name__: 'test' },
exemplars: [
{
timestamp: 1610449069957,
labels: { traceID: '5020b5bc45117f07' },
value: 0.002074123,
},
],
},
],
};
describe('When the response is exemplar data', () => {
it('should return as an data frame with a dataTopic annotations', () => {
const result = transform({ data: exemplarsResponse } as any, options);
expect(result[0].meta?.dataTopic).toBe('annotations');
expect(result[0].fields.length).toBe(4); // __name__, traceID, Time, Value
expect(result[0].length).toBe(1);
});
it('should remove exemplars that are too close to each other', () => {
const response = {
status: 'success',
data: [
{
exemplars: [
{
timestamp: 1610449070000,
value: 5,
},
{
timestamp: 1610449070000,
value: 1,
},
{
timestamp: 1610449070500,
value: 13,
},
{
timestamp: 1610449070300,
value: 20,
},
],
},
],
};
/**
* the standard deviation for the above values is 8.4 this means that we show the highest
* value (20) and then the next value should be 2 times the standard deviation which is 1
**/
const result = transform({ data: response } as any, options);
expect(result[0].length).toBe(2);
});
describe('data link', () => {
it('should be added to the field if found with url', () => {
const result = transform({ data: exemplarsResponse } as any, {
...options,
exemplarTraceIdDestinations: [{ name: 'traceID', url: 'http://localhost' }],
});
expect(result[0].fields.some((f) => f.config.links?.length)).toBe(true);
});
it('should be added to the field if found with internal link', () => {
const result = transform({ data: exemplarsResponse } as any, {
...options,
exemplarTraceIdDestinations: [{ name: 'traceID', datasourceUid: 'jaeger' }],
});
expect(result[0].fields.some((f) => f.config.links?.length)).toBe(true);
});
it('should not add link if exemplarTraceIdDestinations is not configured', () => {
const result = transform({ data: exemplarsResponse } as any, options);
expect(result[0].fields.some((f) => f.config.links?.length)).toBe(false);
});
});
});
});
| public/app/plugins/datasource/prometheus/result_transformer.test.ts | 1 | https://github.com/grafana/grafana/commit/8c35ed40147946c36ae318b54cfe29275553ceea | [
0.371039479970932,
0.007119451649487019,
0.00016342962044291198,
0.00016895213047973812,
0.048309486359357834
] |
{
"id": 1,
"code_window": [
" status: 'success',\n",
" data: [\n",
" {\n",
" exemplars: [\n",
" {\n",
" timestamp: 1610449070000,\n",
" value: 5,\n",
" },\n",
" {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" timestamp: 1610449070.0,\n"
],
"file_path": "public/app/plugins/datasource/prometheus/result_transformer.test.ts",
"type": "replace",
"edit_start_line_idx": 519
} | {
"annotations": {
"list": [
{
"builtIn": 1,
"datasource": "-- Grafana --",
"enable": true,
"hide": true,
"iconColor": "rgba(0, 211, 255, 1)",
"name": "Annotations & Alerts",
"type": "dashboard"
}
]
},
"editable": true,
"gnetId": null,
"graphTooltip": 0,
"links": [],
"panels": [
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "gdev-testdata",
"fill": 2,
"gridPos": {
"h": 8,
"w": 24,
"x": 0,
"y": 0
},
"id": 2,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 2,
"links": [],
"nullPointMode": "null",
"percentage": false,
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"refId": "A",
"scenarioId": "random_walk",
"target": ""
}
],
"thresholds": [],
"timeFrom": null,
"timeRegions": [
{
"colorMode": "gray",
"fill": true,
"fillColor": "rgba(255, 255, 255, 0.03)",
"from": "08:30",
"fromDayOfWeek": 1,
"line": false,
"lineColor": "rgba(255, 255, 255, 0.2)",
"op": "time",
"to": "16:45",
"toDayOfWeek": 5
}
],
"timeShift": null,
"title": "Business Hours",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
],
"yaxis": {
"align": false,
"alignLevel": null
}
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "gdev-testdata",
"fill": 2,
"gridPos": {
"h": 8,
"w": 24,
"x": 0,
"y": 8
},
"id": 4,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 2,
"links": [],
"nullPointMode": "null",
"percentage": false,
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"expr": "",
"format": "time_series",
"intervalFactor": 1,
"refId": "A",
"scenarioId": "random_walk",
"target": ""
}
],
"thresholds": [],
"timeFrom": null,
"timeRegions": [
{
"colorMode": "red",
"fill": true,
"fillColor": "rgba(255, 255, 255, 0.03)",
"from": "20:00",
"fromDayOfWeek": 7,
"line": false,
"lineColor": "rgba(255, 255, 255, 0.2)",
"op": "time",
"to": "23:00",
"toDayOfWeek": 7
}
],
"timeShift": null,
"title": "Sunday's 20-23",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
],
"yaxis": {
"align": false,
"alignLevel": null
}
},
{
"aliasColors": {
"A-series": "#d683ce"
},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "gdev-testdata",
"fill": 2,
"gridPos": {
"h": 8,
"w": 24,
"x": 0,
"y": 16
},
"id": 3,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 2,
"links": [],
"nullPointMode": "null",
"percentage": false,
"pointradius": 0.5,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"refId": "A",
"scenarioId": "random_walk",
"target": ""
}
],
"thresholds": [],
"timeFrom": null,
"timeRegions": [
{
"colorMode": "custom",
"fill": true,
"fillColor": "rgba(255, 0, 0, 0.22)",
"from": "",
"fromDayOfWeek": 1,
"line": true,
"lineColor": "rgba(255, 0, 0, 0.32)",
"op": "time",
"to": "",
"toDayOfWeek": 1
},
{
"colorMode": "custom",
"fill": true,
"fillColor": "rgba(255, 127, 0, 0.22)",
"fromDayOfWeek": 2,
"line": true,
"lineColor": "rgba(255, 127, 0, 0.32)",
"op": "time",
"toDayOfWeek": 2
},
{
"colorMode": "custom",
"fill": true,
"fillColor": "rgba(255, 255, 0, 0.22)",
"fromDayOfWeek": 3,
"line": true,
"lineColor": "rgba(255, 255, 0, 0.22)",
"op": "time",
"toDayOfWeek": 3
},
{
"colorMode": "custom",
"fill": true,
"fillColor": "rgba(0, 255, 0, 0.22)",
"fromDayOfWeek": 4,
"line": true,
"lineColor": "rgba(0, 255, 0, 0.32)",
"op": "time",
"toDayOfWeek": 4
},
{
"colorMode": "custom",
"fill": true,
"fillColor": "rgba(0, 0, 255, 0.22)",
"fromDayOfWeek": 5,
"line": true,
"lineColor": "rgba(0, 0, 255, 0.32)",
"op": "time",
"toDayOfWeek": 5
},
{
"colorMode": "custom",
"fill": true,
"fillColor": "rgba(75, 0, 130, 0.22)",
"fromDayOfWeek": 6,
"line": true,
"lineColor": "rgba(75, 0, 130, 0.32)",
"op": "time",
"toDayOfWeek": 6
},
{
"colorMode": "custom",
"fill": true,
"fillColor": "rgba(148, 0, 211, 0.22)",
"fromDayOfWeek": 7,
"line": true,
"lineColor": "rgba(148, 0, 211, 0.32)",
"op": "time",
"toDayOfWeek": 7
}
],
"timeShift": null,
"title": "Each day of week",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
],
"yaxis": {
"align": false,
"alignLevel": null
}
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "gdev-testdata",
"fill": 2,
"gridPos": {
"h": 8,
"w": 24,
"x": 0,
"y": 24
},
"id": 5,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 2,
"links": [],
"nullPointMode": "null",
"percentage": false,
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"expr": "",
"format": "time_series",
"intervalFactor": 1,
"refId": "A",
"scenarioId": "random_walk",
"target": ""
}
],
"thresholds": [],
"timeFrom": null,
"timeRegions": [
{
"colorMode": "red",
"fill": false,
"from": "05:00",
"line": true,
"op": "time"
}
],
"timeShift": null,
"title": "05:00",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
],
"yaxis": {
"align": false,
"alignLevel": null
}
}
],
"refresh": false,
"schemaVersion": 16,
"style": "dark",
"tags": [
"gdev",
"panel-tests"
],
"templating": {
"list": []
},
"time": {
"from": "now-30d",
"to": "now"
},
"timepicker": {
"refresh_intervals": [
"5s",
"10s",
"30s",
"1m",
"5m",
"15m",
"30m",
"1h",
"2h",
"1d"
],
"time_options": [
"5m",
"15m",
"1h",
"6h",
"12h",
"24h",
"2d",
"7d",
"30d"
]
},
"timezone": "browser",
"title": "Panel Tests - Graph (Time Regions)",
"version": 1
} | devenv/dev-dashboards-without-uid/panel_tests_graph_time_regions.json | 0 | https://github.com/grafana/grafana/commit/8c35ed40147946c36ae318b54cfe29275553ceea | [
0.00017326106899417937,
0.00016814669652376324,
0.00016377891006413847,
0.00016816621064208448,
0.000001830862061069638
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.