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": 9,
"code_window": [
" ie: \"11.0.0\",\n",
" edge: \"16.0.0\",\n",
" firefox: \"60.0.0\",\n",
" });\n",
" });\n",
" });\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" opera: \"48.0.0\",\n"
],
"file_path": "packages/babel-preset-env/test/targets-parser.spec.js",
"type": "add",
"edit_start_line_idx": 230
} | {
"type": "File",
"start": 0,
"end": 32,
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 1,
"column": 32
}
},
"program": {
"type": "Program",
"start": 0,
"end": 32,
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 1,
"column": 32
}
},
"sourceType": "module",
"interpreter": null,
"body": [
{
"type": "ExportNamedDeclaration",
"start": 0,
"end": 32,
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 1,
"column": 32
}
},
"specifiers": [],
"source": null,
"declaration": {
"type": "VariableDeclaration",
"start": 7,
"end": 32,
"loc": {
"start": {
"line": 1,
"column": 7
},
"end": {
"line": 1,
"column": 32
}
},
"declarations": [
{
"type": "VariableDeclarator",
"start": 11,
"end": 31,
"loc": {
"start": {
"line": 1,
"column": 11
},
"end": {
"line": 1,
"column": 31
}
},
"id": {
"type": "Identifier",
"start": 11,
"end": 14,
"loc": {
"start": {
"line": 1,
"column": 11
},
"end": {
"line": 1,
"column": 14
},
"identifierName": "foo"
},
"name": "foo"
},
"init": {
"type": "FunctionExpression",
"start": 17,
"end": 31,
"loc": {
"start": {
"line": 1,
"column": 17
},
"end": {
"line": 1,
"column": 31
}
},
"id": null,
"generator": false,
"async": false,
"params": [],
"body": {
"type": "BlockStatement",
"start": 29,
"end": 31,
"loc": {
"start": {
"line": 1,
"column": 29
},
"end": {
"line": 1,
"column": 31
}
},
"body": [],
"directives": []
}
}
}
],
"kind": "var"
}
}
],
"directives": []
}
} | packages/babel-parser/test/fixtures/esprima/es2015-export-declaration/export-var-anonymous-function/output.json | 0 | https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628 | [
0.00017367872351314873,
0.00017169378406833857,
0.00016823048645164818,
0.0001718132698442787,
0.0000015722640682724887
] |
{
"id": 9,
"code_window": [
" ie: \"11.0.0\",\n",
" edge: \"16.0.0\",\n",
" firefox: \"60.0.0\",\n",
" });\n",
" });\n",
" });\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" opera: \"48.0.0\",\n"
],
"file_path": "packages/babel-preset-env/test/targets-parser.spec.js",
"type": "add",
"edit_start_line_idx": 230
} | // @flow
import { types as tt, TokenType } from "../tokenizer/types";
import type Parser from "../parser";
import * as N from "../types";
import type { Pos, Position } from "../util/location";
function isSimpleProperty(node: N.Node): boolean {
return (
node != null &&
node.type === "Property" &&
node.kind === "init" &&
node.method === false
);
}
export default (superClass: Class<Parser>): Class<Parser> =>
class extends superClass {
estreeParseRegExpLiteral({ pattern, flags }: N.RegExpLiteral): N.Node {
let regex = null;
try {
regex = new RegExp(pattern, flags);
} catch (e) {
// In environments that don't support these flags value will
// be null as the regex can't be represented natively.
}
const node = this.estreeParseLiteral(regex);
node.regex = { pattern, flags };
return node;
}
estreeParseLiteral(value: any): N.Node {
return this.parseLiteral(value, "Literal");
}
directiveToStmt(directive: N.Directive): N.ExpressionStatement {
const directiveLiteral = directive.value;
const stmt = this.startNodeAt(directive.start, directive.loc.start);
const expression = this.startNodeAt(
directiveLiteral.start,
directiveLiteral.loc.start,
);
expression.value = directiveLiteral.value;
expression.raw = directiveLiteral.extra.raw;
stmt.expression = this.finishNodeAt(
expression,
"Literal",
directiveLiteral.end,
directiveLiteral.loc.end,
);
stmt.directive = directiveLiteral.extra.raw.slice(1, -1);
return this.finishNodeAt(
stmt,
"ExpressionStatement",
directive.end,
directive.loc.end,
);
}
// ==================================
// Overrides
// ==================================
initFunction(
node: N.BodilessFunctionOrMethodBase,
isAsync: ?boolean,
): void {
super.initFunction(node, isAsync);
node.expression = false;
}
checkDeclaration(node: N.Pattern | N.ObjectProperty): void {
if (isSimpleProperty(node)) {
this.checkDeclaration(((node: any): N.EstreeProperty).value);
} else {
super.checkDeclaration(node);
}
}
checkGetterSetterParams(method: N.ObjectMethod | N.ClassMethod): void {
const prop = ((method: any): N.EstreeProperty | N.EstreeMethodDefinition);
const paramCount = prop.kind === "get" ? 0 : 1;
const start = prop.start;
if (prop.value.params.length !== paramCount) {
if (prop.kind === "get") {
this.raise(start, "getter must not have any formal parameters");
} else {
this.raise(start, "setter must have exactly one formal parameter");
}
}
if (prop.kind === "set" && prop.value.params[0].type === "RestElement") {
this.raise(
start,
"setter function argument must not be a rest parameter",
);
}
}
checkLVal(
expr: N.Expression,
isBinding: ?boolean,
checkClashes: ?{ [key: string]: boolean },
contextDescription: string,
): void {
switch (expr.type) {
case "ObjectPattern":
expr.properties.forEach(prop => {
this.checkLVal(
prop.type === "Property" ? prop.value : prop,
isBinding,
checkClashes,
"object destructuring pattern",
);
});
break;
default:
super.checkLVal(expr, isBinding, checkClashes, contextDescription);
}
}
checkPropClash(
prop: N.ObjectMember,
propHash: { [key: string]: boolean },
): void {
if (prop.computed || !isSimpleProperty(prop)) return;
const key = prop.key;
// It is either an Identifier or a String/NumericLiteral
const name = key.type === "Identifier" ? key.name : String(key.value);
if (name === "__proto__") {
if (propHash.proto) {
this.raise(key.start, "Redefinition of __proto__ property");
}
propHash.proto = true;
}
}
isStrictBody(node: { body: N.BlockStatement }): boolean {
const isBlockStatement = node.body.type === "BlockStatement";
if (isBlockStatement && node.body.body.length > 0) {
for (const directive of node.body.body) {
if (
directive.type === "ExpressionStatement" &&
directive.expression.type === "Literal"
) {
if (directive.expression.value === "use strict") return true;
} else {
// Break for the first non literal expression
break;
}
}
}
return false;
}
isValidDirective(stmt: N.Statement): boolean {
return (
stmt.type === "ExpressionStatement" &&
stmt.expression.type === "Literal" &&
typeof stmt.expression.value === "string" &&
(!stmt.expression.extra || !stmt.expression.extra.parenthesized)
);
}
stmtToDirective(stmt: N.Statement): N.Directive {
const directive = super.stmtToDirective(stmt);
const value = stmt.expression.value;
// Reset value to the actual value as in estree mode we want
// the stmt to have the real value and not the raw value
directive.value.value = value;
return directive;
}
parseBlockBody(
node: N.BlockStatementLike,
allowDirectives: ?boolean,
topLevel: boolean,
end: TokenType,
): void {
super.parseBlockBody(node, allowDirectives, topLevel, end);
const directiveStatements = node.directives.map(d =>
this.directiveToStmt(d),
);
node.body = directiveStatements.concat(node.body);
delete node.directives;
}
pushClassMethod(
classBody: N.ClassBody,
method: N.ClassMethod,
isGenerator: boolean,
isAsync: boolean,
isConstructor: boolean,
): void {
this.parseMethod(
method,
isGenerator,
isAsync,
isConstructor,
"MethodDefinition",
);
if (method.typeParameters) {
// $FlowIgnore
method.value.typeParameters = method.typeParameters;
delete method.typeParameters;
}
classBody.body.push(method);
}
parseExprAtom(refShorthandDefaultPos?: ?Pos): N.Expression {
switch (this.state.type) {
case tt.regexp:
return this.estreeParseRegExpLiteral(this.state.value);
case tt.num:
case tt.string:
return this.estreeParseLiteral(this.state.value);
case tt._null:
return this.estreeParseLiteral(null);
case tt._true:
return this.estreeParseLiteral(true);
case tt._false:
return this.estreeParseLiteral(false);
default:
return super.parseExprAtom(refShorthandDefaultPos);
}
}
parseLiteral<T: N.Literal>(
value: any,
type: /*T["kind"]*/ string,
startPos?: number,
startLoc?: Position,
): T {
const node = super.parseLiteral(value, type, startPos, startLoc);
node.raw = node.extra.raw;
delete node.extra;
return node;
}
parseFunctionBody(node: N.Function, allowExpression: ?boolean): void {
super.parseFunctionBody(node, allowExpression);
node.expression = node.body.type !== "BlockStatement";
}
parseMethod<T: N.MethodLike>(
node: T,
isGenerator: boolean,
isAsync: boolean,
isConstructor: boolean,
type: string,
): T {
let funcNode = this.startNode();
funcNode.kind = node.kind; // provide kind, so super method correctly sets state
funcNode = super.parseMethod(
funcNode,
isGenerator,
isAsync,
isConstructor,
"FunctionExpression",
);
delete funcNode.kind;
// $FlowIgnore
node.value = funcNode;
return this.finishNode(node, type);
}
parseObjectMethod(
prop: N.ObjectMethod,
isGenerator: boolean,
isAsync: boolean,
isPattern: boolean,
containsEsc: boolean,
): ?N.ObjectMethod {
const node: N.EstreeProperty = (super.parseObjectMethod(
prop,
isGenerator,
isAsync,
isPattern,
containsEsc,
): any);
if (node) {
node.type = "Property";
if (node.kind === "method") node.kind = "init";
node.shorthand = false;
}
return (node: any);
}
parseObjectProperty(
prop: N.ObjectProperty,
startPos: ?number,
startLoc: ?Position,
isPattern: boolean,
refShorthandDefaultPos: ?Pos,
): ?N.ObjectProperty {
const node: N.EstreeProperty = (super.parseObjectProperty(
prop,
startPos,
startLoc,
isPattern,
refShorthandDefaultPos,
): any);
if (node) {
node.kind = "init";
node.type = "Property";
}
return (node: any);
}
toAssignable(
node: N.Node,
isBinding: ?boolean,
contextDescription: string,
): N.Node {
if (isSimpleProperty(node)) {
this.toAssignable(node.value, isBinding, contextDescription);
return node;
}
return super.toAssignable(node, isBinding, contextDescription);
}
toAssignableObjectExpressionProp(
prop: N.Node,
isBinding: ?boolean,
isLast: boolean,
) {
if (prop.kind === "get" || prop.kind === "set") {
this.raise(
prop.key.start,
"Object pattern can't contain getter or setter",
);
} else if (prop.method) {
this.raise(prop.key.start, "Object pattern can't contain methods");
} else {
super.toAssignableObjectExpressionProp(prop, isBinding, isLast);
}
}
};
| packages/babel-parser/src/plugins/estree.js | 0 | https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628 | [
0.00025706057203933597,
0.00017342562205158174,
0.0001625132717890665,
0.00017195739201270044,
0.00001432203316653613
] |
{
"id": 0,
"code_window": [
" <div className={cx(styles.headerRow, 'grid-drag-handle')}>\n",
" {onBack && (\n",
" <div className={styles.backButton}>\n",
" <IconButton name=\"arrow-left\" onClick={onBack} surface=\"header\" size=\"xl\" />\n",
" </div>\n",
" )}\n",
" {!onBack && (\n",
" <div className={styles.backButton}>\n",
" <Icon name=\"panel-add\" size=\"md\" />\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <IconButton aria-label=\"Go back\" name=\"arrow-left\" onClick={onBack} surface=\"header\" size=\"xl\" />\n"
],
"file_path": "public/app/features/dashboard/components/AddPanelWidget/AddPanelWidget.tsx",
"type": "replace",
"edit_start_line_idx": 217
} | import React, { PureComponent } from 'react';
import { Button, ClipboardButton, Icon, Spinner, Select, Input, LinkButton, Field, Modal } from '@grafana/ui';
import { AppEvents, SelectableValue } from '@grafana/data';
import { getBackendSrv } from '@grafana/runtime';
import { DashboardModel, PanelModel } from 'app/features/dashboard/state';
import { getTimeSrv } from 'app/features/dashboard/services/TimeSrv';
import { appEvents } from 'app/core/core';
import { VariableRefresh } from '../../../variables/types';
const snapshotApiUrl = '/api/snapshots';
const expireOptions: Array<SelectableValue<number>> = [
{ label: 'Never', value: 0 },
{ label: '1 Hour', value: 60 * 60 },
{ label: '1 Day', value: 60 * 60 * 24 },
{ label: '7 Days', value: 60 * 60 * 24 * 7 },
];
interface Props {
dashboard: DashboardModel;
panel?: PanelModel;
onDismiss(): void;
}
interface State {
isLoading: boolean;
step: number;
snapshotName: string;
selectedExpireOption: SelectableValue<number>;
snapshotExpires?: number;
snapshotUrl: string;
deleteUrl: string;
timeoutSeconds: number;
externalEnabled: boolean;
sharingButtonText: string;
}
export class ShareSnapshot extends PureComponent<Props, State> {
private dashboard: DashboardModel;
constructor(props: Props) {
super(props);
this.dashboard = props.dashboard;
this.state = {
isLoading: false,
step: 1,
selectedExpireOption: expireOptions[0],
snapshotExpires: expireOptions[0].value,
snapshotName: props.dashboard.title,
timeoutSeconds: 4,
snapshotUrl: '',
deleteUrl: '',
externalEnabled: false,
sharingButtonText: '',
};
}
componentDidMount() {
this.getSnaphotShareOptions();
}
async getSnaphotShareOptions() {
const shareOptions = await getBackendSrv().get('/api/snapshot/shared-options');
this.setState({
sharingButtonText: shareOptions['externalSnapshotName'],
externalEnabled: shareOptions['externalEnabled'],
});
}
createSnapshot = (external?: boolean) => () => {
const { timeoutSeconds } = this.state;
this.dashboard.snapshot = {
timestamp: new Date(),
};
if (!external) {
this.dashboard.snapshot.originalUrl = window.location.href;
}
this.setState({ isLoading: true });
this.dashboard.startRefresh();
setTimeout(() => {
this.saveSnapshot(this.dashboard, external);
}, timeoutSeconds * 1000);
};
saveSnapshot = async (dashboard: DashboardModel, external?: boolean) => {
const { snapshotExpires } = this.state;
const dash = this.dashboard.getSaveModelClone();
this.scrubDashboard(dash);
const cmdData = {
dashboard: dash,
name: dash.title,
expires: snapshotExpires,
external: external,
};
try {
const results: { deleteUrl: any; url: any } = await getBackendSrv().post(snapshotApiUrl, cmdData);
this.setState({
deleteUrl: results.deleteUrl,
snapshotUrl: results.url,
step: 2,
});
} finally {
this.setState({ isLoading: false });
}
};
scrubDashboard = (dash: DashboardModel) => {
const { panel } = this.props;
const { snapshotName } = this.state;
// change title
dash.title = snapshotName;
// make relative times absolute
dash.time = getTimeSrv().timeRange();
// Remove links
dash.links = [];
// remove panel queries & links
dash.panels.forEach((panel) => {
panel.targets = [];
panel.links = [];
panel.datasource = null;
});
// remove annotation queries
const annotations = dash.annotations.list.filter((annotation) => annotation.enable);
dash.annotations.list = annotations.map((annotation: any) => {
return {
name: annotation.name,
enable: annotation.enable,
iconColor: annotation.iconColor,
snapshotData: annotation.snapshotData,
type: annotation.type,
builtIn: annotation.builtIn,
hide: annotation.hide,
};
});
// remove template queries
dash.getVariables().forEach((variable: any) => {
variable.query = '';
variable.options = variable.current ? [variable.current] : [];
variable.refresh = VariableRefresh.never;
});
// snapshot single panel
if (panel) {
const singlePanel = panel.getSaveModel();
singlePanel.gridPos.w = 24;
singlePanel.gridPos.x = 0;
singlePanel.gridPos.y = 0;
singlePanel.gridPos.h = 20;
dash.panels = [singlePanel];
}
// cleanup snapshotData
delete this.dashboard.snapshot;
this.dashboard.forEachPanel((panel: PanelModel) => {
delete panel.snapshotData;
});
this.dashboard.annotations.list.forEach((annotation) => {
delete annotation.snapshotData;
});
};
deleteSnapshot = async () => {
const { deleteUrl } = this.state;
await getBackendSrv().get(deleteUrl);
this.setState({ step: 3 });
};
getSnapshotUrl = () => {
return this.state.snapshotUrl;
};
onSnapshotNameChange = (event: React.ChangeEvent<HTMLInputElement>) => {
this.setState({ snapshotName: event.target.value });
};
onTimeoutChange = (event: React.ChangeEvent<HTMLInputElement>) => {
this.setState({ timeoutSeconds: Number(event.target.value) });
};
onExpireChange = (option: SelectableValue<number>) => {
this.setState({
selectedExpireOption: option,
snapshotExpires: option.value,
});
};
onSnapshotUrlCopy = () => {
appEvents.emit(AppEvents.alertSuccess, ['Content copied to clipboard']);
};
renderStep1() {
const { onDismiss } = this.props;
const {
snapshotName,
selectedExpireOption,
timeoutSeconds,
isLoading,
sharingButtonText,
externalEnabled,
} = this.state;
return (
<>
<div>
<p className="share-modal-info-text">
A snapshot is an instant way to share an interactive dashboard publicly. When created, we strip sensitive
data like queries (metric, template, and annotation) and panel links, leaving only the visible metric data
and series names embedded in your dashboard.
</p>
<p className="share-modal-info-text">
Keep in mind, your snapshot <em>can be viewed by anyone</em> that has the link and can access the URL. Share
wisely.
</p>
</div>
<Field label="Snapshot name">
<Input width={30} value={snapshotName} onChange={this.onSnapshotNameChange} />
</Field>
<Field label="Expire">
<Select
menuShouldPortal
width={30}
options={expireOptions}
value={selectedExpireOption}
onChange={this.onExpireChange}
/>
</Field>
<Field
label="Timeout (seconds)"
description="You might need to configure the timeout value if it takes a long time to collect your dashboard
metrics."
>
<Input type="number" width={21} value={timeoutSeconds} onChange={this.onTimeoutChange} />
</Field>
<Modal.ButtonRow>
<Button variant="secondary" onClick={onDismiss} fill="outline">
Cancel
</Button>
{externalEnabled && (
<Button variant="secondary" disabled={isLoading} onClick={this.createSnapshot(true)}>
{sharingButtonText}
</Button>
)}
<Button variant="primary" disabled={isLoading} onClick={this.createSnapshot()}>
Local Snapshot
</Button>
</Modal.ButtonRow>
</>
);
}
renderStep2() {
const { snapshotUrl } = this.state;
return (
<>
<div className="gf-form" style={{ marginTop: '40px' }}>
<div className="gf-form-row">
<a href={snapshotUrl} className="large share-modal-link" target="_blank" rel="noreferrer">
<Icon name="external-link-alt" /> {snapshotUrl}
</a>
<br />
<ClipboardButton variant="secondary" getText={this.getSnapshotUrl} onClipboardCopy={this.onSnapshotUrlCopy}>
Copy Link
</ClipboardButton>
</div>
</div>
<div className="pull-right" style={{ padding: '5px' }}>
Did you make a mistake?{' '}
<LinkButton fill="text" target="_blank" onClick={this.deleteSnapshot}>
Delete snapshot.
</LinkButton>
</div>
</>
);
}
renderStep3() {
return (
<div className="share-modal-header">
<p className="share-modal-info-text">
The snapshot has been deleted. If you have already accessed it once, then it might take up to an hour before
before it is removed from browser caches or CDN caches.
</p>
</div>
);
}
render() {
const { isLoading, step } = this.state;
return (
<>
{step === 1 && this.renderStep1()}
{step === 2 && this.renderStep2()}
{step === 3 && this.renderStep3()}
{isLoading && <Spinner inline={true} />}
</>
);
}
}
| public/app/features/dashboard/components/ShareModal/ShareSnapshot.tsx | 1 | https://github.com/grafana/grafana/commit/3c52df960ad8a45191ee0141a8c169a0cc4f79a5 | [
0.0001768191286828369,
0.0001709258067421615,
0.00016492667782586068,
0.00017160974675789475,
0.000003822961843980011
] |
{
"id": 0,
"code_window": [
" <div className={cx(styles.headerRow, 'grid-drag-handle')}>\n",
" {onBack && (\n",
" <div className={styles.backButton}>\n",
" <IconButton name=\"arrow-left\" onClick={onBack} surface=\"header\" size=\"xl\" />\n",
" </div>\n",
" )}\n",
" {!onBack && (\n",
" <div className={styles.backButton}>\n",
" <Icon name=\"panel-add\" size=\"md\" />\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <IconButton aria-label=\"Go back\" name=\"arrow-left\" onClick={onBack} surface=\"header\" size=\"xl\" />\n"
],
"file_path": "public/app/features/dashboard/components/AddPanelWidget/AddPanelWidget.tsx",
"type": "replace",
"edit_start_line_idx": 217
} | package remotecache
import (
"crypto/tls"
"fmt"
"testing"
"github.com/go-redis/redis/v8"
"github.com/stretchr/testify/assert"
)
func Test_parseRedisConnStr(t *testing.T) {
cases := map[string]struct {
InputConnStr string
OutputOptions *redis.Options
ShouldErr bool
}{
"all redis options should parse": {
"addr=127.0.0.1:6379,pool_size=100,db=1,password=grafanaRocks,ssl=false",
&redis.Options{
Addr: "127.0.0.1:6379",
PoolSize: 100,
DB: 1,
Password: "grafanaRocks",
Network: "tcp",
TLSConfig: nil,
},
false,
},
"subset of redis options should parse": {
"addr=127.0.0.1:6379,pool_size=100",
&redis.Options{
Addr: "127.0.0.1:6379",
PoolSize: 100,
Network: "tcp",
},
false,
},
"ssl set to true should result in default TLS configuration with tls set to addr's host": {
"addr=grafana.com:6379,ssl=true",
&redis.Options{
Addr: "grafana.com:6379",
Network: "tcp",
TLSConfig: &tls.Config{ServerName: "grafana.com"},
},
false,
},
"ssl to insecure should result in TLS configuration with InsecureSkipVerify": {
"addr=127.0.0.1:6379,ssl=insecure",
&redis.Options{
Addr: "127.0.0.1:6379",
Network: "tcp",
TLSConfig: &tls.Config{InsecureSkipVerify: true},
},
false,
},
"invalid SSL option should err": {
"addr=127.0.0.1:6379,ssl=dragons",
nil,
true,
},
"invalid pool_size value should err": {
"addr=127.0.0.1:6379,pool_size=seven",
nil,
true,
},
"invalid db value should err": {
"addr=127.0.0.1:6379,db=seven",
nil,
true,
},
"trailing comma should err": {
"addr=127.0.0.1:6379,pool_size=100,",
nil,
true,
},
"invalid key should err": {
"addr=127.0.0.1:6379,puddle_size=100",
nil,
true,
},
"empty connection string should err": {
"",
nil,
true,
},
}
for reason, testCase := range cases {
options, err := parseRedisConnStr(testCase.InputConnStr)
if testCase.ShouldErr {
assert.Error(t, err, fmt.Sprintf("error cases should return non-nil error for test case %v", reason))
assert.Nil(t, options, fmt.Sprintf("error cases should return nil for redis options for test case %v", reason))
continue
}
assert.NoError(t, err, reason)
assert.EqualValues(t, testCase.OutputOptions, options, reason)
}
}
| pkg/infra/remotecache/redis_storage_test.go | 0 | https://github.com/grafana/grafana/commit/3c52df960ad8a45191ee0141a8c169a0cc4f79a5 | [
0.0001771137467585504,
0.00017295326688326895,
0.0001684412418399006,
0.000173771200934425,
0.0000026201871605735505
] |
{
"id": 0,
"code_window": [
" <div className={cx(styles.headerRow, 'grid-drag-handle')}>\n",
" {onBack && (\n",
" <div className={styles.backButton}>\n",
" <IconButton name=\"arrow-left\" onClick={onBack} surface=\"header\" size=\"xl\" />\n",
" </div>\n",
" )}\n",
" {!onBack && (\n",
" <div className={styles.backButton}>\n",
" <Icon name=\"panel-add\" size=\"md\" />\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <IconButton aria-label=\"Go back\" name=\"arrow-left\" onClick={onBack} surface=\"header\" size=\"xl\" />\n"
],
"file_path": "public/app/features/dashboard/components/AddPanelWidget/AddPanelWidget.tsx",
"type": "replace",
"edit_start_line_idx": 217
} | //go:build integration
// +build integration
package sqlstore
import (
"context"
"fmt"
"testing"
"github.com/grafana/grafana/pkg/models"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestStatsDataAccess(t *testing.T) {
sqlStore := InitTestDB(t)
populateDB(t, sqlStore)
t.Run("Get system stats should not results in error", func(t *testing.T) {
query := models.GetSystemStatsQuery{}
err := GetSystemStats(context.Background(), &query)
require.NoError(t, err)
assert.Equal(t, int64(3), query.Result.Users)
assert.Equal(t, int64(0), query.Result.Editors)
assert.Equal(t, int64(0), query.Result.Viewers)
assert.Equal(t, int64(3), query.Result.Admins)
assert.Equal(t, int64(0), query.Result.LibraryPanels)
assert.Equal(t, int64(0), query.Result.LibraryVariables)
})
t.Run("Get system user count stats should not results in error", func(t *testing.T) {
query := models.GetSystemUserCountStatsQuery{}
err := GetSystemUserCountStats(context.Background(), &query)
assert.NoError(t, err)
})
t.Run("Get datasource stats should not results in error", func(t *testing.T) {
query := models.GetDataSourceStatsQuery{}
err := GetDataSourceStats(context.Background(), &query)
assert.NoError(t, err)
})
t.Run("Get datasource access stats should not results in error", func(t *testing.T) {
query := models.GetDataSourceAccessStatsQuery{}
err := GetDataSourceAccessStats(context.Background(), &query)
assert.NoError(t, err)
})
t.Run("Get alert notifier stats should not results in error", func(t *testing.T) {
query := models.GetAlertNotifierUsageStatsQuery{}
err := GetAlertNotifiersUsageStats(context.Background(), &query)
assert.NoError(t, err)
})
t.Run("Get admin stats should not result in error", func(t *testing.T) {
query := models.GetAdminStatsQuery{}
err := GetAdminStats(context.Background(), &query)
assert.NoError(t, err)
})
}
func populateDB(t *testing.T, sqlStore *SQLStore) {
t.Helper()
users := make([]models.User, 3)
for i := range users {
cmd := models.CreateUserCommand{
Email: fmt.Sprintf("usertest%[email protected]", i),
Name: fmt.Sprintf("user name %v", i),
Login: fmt.Sprintf("user_test_%v_login", i),
OrgName: fmt.Sprintf("Org #%v", i),
}
user, err := sqlStore.CreateUser(context.Background(), cmd)
require.NoError(t, err)
users[i] = *user
}
// get 1st user's organisation
getOrgByIdQuery := &models.GetOrgByIdQuery{Id: users[0].OrgId}
err := GetOrgById(getOrgByIdQuery)
require.NoError(t, err)
org := getOrgByIdQuery.Result
// add 2nd user as editor
cmd := &models.AddOrgUserCommand{
OrgId: org.Id,
UserId: users[1].Id,
Role: models.ROLE_EDITOR,
}
err = sqlStore.AddOrgUser(context.Background(), cmd)
require.NoError(t, err)
// add 3rd user as viewer
cmd = &models.AddOrgUserCommand{
OrgId: org.Id,
UserId: users[2].Id,
Role: models.ROLE_VIEWER,
}
err = sqlStore.AddOrgUser(context.Background(), cmd)
require.NoError(t, err)
// get 2nd user's organisation
getOrgByIdQuery = &models.GetOrgByIdQuery{Id: users[1].OrgId}
err = GetOrgById(getOrgByIdQuery)
require.NoError(t, err)
org = getOrgByIdQuery.Result
// add 1st user as admin
cmd = &models.AddOrgUserCommand{
OrgId: org.Id,
UserId: users[0].Id,
Role: models.ROLE_ADMIN,
}
err = sqlStore.AddOrgUser(context.Background(), cmd)
require.NoError(t, err)
// update 1st user last seen at
updateUserLastSeenAtCmd := &models.UpdateUserLastSeenAtCommand{
UserId: users[0].Id,
}
err = UpdateUserLastSeenAt(context.Background(), updateUserLastSeenAtCmd)
require.NoError(t, err)
// force renewal of user stats
err = updateUserRoleCountsIfNecessary(context.Background(), true)
require.NoError(t, err)
}
| pkg/services/sqlstore/stats_test.go | 0 | https://github.com/grafana/grafana/commit/3c52df960ad8a45191ee0141a8c169a0cc4f79a5 | [
0.0001767608046066016,
0.00017445535922888666,
0.00017021223902702332,
0.0001751628878992051,
0.0000017700901935313595
] |
{
"id": 0,
"code_window": [
" <div className={cx(styles.headerRow, 'grid-drag-handle')}>\n",
" {onBack && (\n",
" <div className={styles.backButton}>\n",
" <IconButton name=\"arrow-left\" onClick={onBack} surface=\"header\" size=\"xl\" />\n",
" </div>\n",
" )}\n",
" {!onBack && (\n",
" <div className={styles.backButton}>\n",
" <Icon name=\"panel-add\" size=\"md\" />\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <IconButton aria-label=\"Go back\" name=\"arrow-left\" onClick={onBack} surface=\"header\" size=\"xl\" />\n"
],
"file_path": "public/app/features/dashboard/components/AddPanelWidget/AddPanelWidget.tsx",
"type": "replace",
"edit_start_line_idx": 217
} | module.exports = {
html: {
options: {
verbose: true,
removeComments: true,
},
files: [
{
expand: true, // Enable dynamic expansion.
cwd: 'dist', // Src matches are relative to this path.
src: ['*.html'], // Actual pattern(s) to match.
dest: '../public/emails/', // Destination path prefix.
},
],
},
txt: {
options: {
verbose: true,
mode: 'txt',
lineLength: 90,
},
files: [
{
expand: true, // Enable dynamic expansion.
cwd: 'dist', // Src matches are relative to this path.
src: ['*.txt'], // Actual patterns to match.
dest: '../public/emails/', // Destination path prefix.
},
],
},
};
| emails/grunt/premailer.js | 0 | https://github.com/grafana/grafana/commit/3c52df960ad8a45191ee0141a8c169a0cc4f79a5 | [
0.0001778076693881303,
0.00017442888929508626,
0.0001715572871034965,
0.00017417530762031674,
0.0000023152426820161054
] |
{
"id": 1,
"code_window": [
" return (\n",
" <>\n",
" <p className=\"share-modal-info-text\">Export this dashboard.</p>\n",
" <Field label=\"Export for sharing externally\">\n",
" <Switch value={shareExternally} onChange={this.onShareExternallyChange} />\n",
" </Field>\n",
" {config.featureToggles.trimDefaults && (\n",
" <Field label=\"Export with default values removed\">\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" <Switch id=\"share-externally-toggle\" value={shareExternally} onChange={this.onShareExternallyChange} />\n"
],
"file_path": "public/app/features/dashboard/components/ShareModal/ShareExport.tsx",
"type": "replace",
"edit_start_line_idx": 138
} | import React, { PureComponent } from 'react';
import { saveAs } from 'file-saver';
import { getBackendSrv } from 'app/core/services/backend_srv';
import { Button, Field, Modal, Switch } from '@grafana/ui';
import { DashboardModel, PanelModel } from 'app/features/dashboard/state';
import { DashboardExporter } from 'app/features/dashboard/components/DashExportModal';
import { appEvents } from 'app/core/core';
import { ShowModalReactEvent } from 'app/types/events';
import { ViewJsonModal } from './ViewJsonModal';
import { config } from '@grafana/runtime';
interface Props {
dashboard: DashboardModel;
panel?: PanelModel;
onDismiss(): void;
}
interface State {
shareExternally: boolean;
trimDefaults: boolean;
}
export class ShareExport extends PureComponent<Props, State> {
private exporter: DashboardExporter;
constructor(props: Props) {
super(props);
this.state = {
shareExternally: false,
trimDefaults: false,
};
this.exporter = new DashboardExporter();
}
onShareExternallyChange = () => {
this.setState({
shareExternally: !this.state.shareExternally,
});
};
onTrimDefaultsChange = () => {
this.setState({
trimDefaults: !this.state.trimDefaults,
});
};
onSaveAsFile = () => {
const { dashboard } = this.props;
const { shareExternally } = this.state;
const { trimDefaults } = this.state;
if (shareExternally) {
this.exporter.makeExportable(dashboard).then((dashboardJson: any) => {
if (trimDefaults) {
getBackendSrv()
.post('/api/dashboards/trim', { dashboard: dashboardJson })
.then((resp: any) => {
this.openSaveAsDialog(resp.dashboard);
});
} else {
this.openSaveAsDialog(dashboardJson);
}
});
} else {
if (trimDefaults) {
getBackendSrv()
.post('/api/dashboards/trim', { dashboard: dashboard.getSaveModelClone() })
.then((resp: any) => {
this.openSaveAsDialog(resp.dashboard);
});
} else {
this.openSaveAsDialog(dashboard.getSaveModelClone());
}
}
};
onViewJson = () => {
const { dashboard } = this.props;
const { shareExternally } = this.state;
const { trimDefaults } = this.state;
if (shareExternally) {
this.exporter.makeExportable(dashboard).then((dashboardJson: any) => {
if (trimDefaults) {
getBackendSrv()
.post('/api/dashboards/trim', { dashboard: dashboardJson })
.then((resp: any) => {
this.openJsonModal(resp.dashboard);
});
} else {
this.openJsonModal(dashboardJson);
}
});
} else {
if (trimDefaults) {
getBackendSrv()
.post('/api/dashboards/trim', { dashboard: dashboard.getSaveModelClone() })
.then((resp: any) => {
this.openJsonModal(resp.dashboard);
});
} else {
this.openJsonModal(dashboard.getSaveModelClone());
}
}
};
openSaveAsDialog = (dash: any) => {
const dashboardJsonPretty = JSON.stringify(dash, null, 2);
const blob = new Blob([dashboardJsonPretty], {
type: 'application/json;charset=utf-8',
});
const time = new Date().getTime();
saveAs(blob, `${dash.title}-${time}.json`);
};
openJsonModal = (clone: object) => {
appEvents.publish(
new ShowModalReactEvent({
props: {
json: JSON.stringify(clone, null, 2),
},
component: ViewJsonModal,
})
);
this.props.onDismiss();
};
render() {
const { onDismiss } = this.props;
const { shareExternally } = this.state;
const { trimDefaults } = this.state;
return (
<>
<p className="share-modal-info-text">Export this dashboard.</p>
<Field label="Export for sharing externally">
<Switch value={shareExternally} onChange={this.onShareExternallyChange} />
</Field>
{config.featureToggles.trimDefaults && (
<Field label="Export with default values removed">
<Switch value={trimDefaults} onChange={this.onTrimDefaultsChange} />
</Field>
)}
<Modal.ButtonRow>
<Button variant="secondary" onClick={onDismiss} fill="outline">
Cancel
</Button>
<Button variant="secondary" onClick={this.onViewJson}>
View JSON
</Button>
<Button variant="primary" onClick={this.onSaveAsFile}>
Save to file
</Button>
</Modal.ButtonRow>
</>
);
}
}
| public/app/features/dashboard/components/ShareModal/ShareExport.tsx | 1 | https://github.com/grafana/grafana/commit/3c52df960ad8a45191ee0141a8c169a0cc4f79a5 | [
0.029312152415513992,
0.006848218850791454,
0.00016493594739586115,
0.003607635386288166,
0.009076522663235664
] |
{
"id": 1,
"code_window": [
" return (\n",
" <>\n",
" <p className=\"share-modal-info-text\">Export this dashboard.</p>\n",
" <Field label=\"Export for sharing externally\">\n",
" <Switch value={shareExternally} onChange={this.onShareExternallyChange} />\n",
" </Field>\n",
" {config.featureToggles.trimDefaults && (\n",
" <Field label=\"Export with default values removed\">\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" <Switch id=\"share-externally-toggle\" value={shareExternally} onChange={this.onShareExternallyChange} />\n"
],
"file_path": "public/app/features/dashboard/components/ShareModal/ShareExport.tsx",
"type": "replace",
"edit_start_line_idx": 138
} | import React, { FC } from 'react';
import { QueryResultMetaNotice } from '@grafana/data';
import { Icon, Tooltip } from '@grafana/ui';
interface Props {
notice: QueryResultMetaNotice;
onClick: (e: React.SyntheticEvent, tab: string) => void;
}
export const PanelHeaderNotice: FC<Props> = ({ notice, onClick }) => {
const iconName =
notice.severity === 'error' || notice.severity === 'warning' ? 'exclamation-triangle' : 'info-circle';
return (
<Tooltip content={notice.text} key={notice.severity}>
{notice.inspect ? (
<div className="panel-info-notice pointer" onClick={(e) => onClick(e, notice.inspect!)}>
<Icon name={iconName} style={{ marginRight: '8px' }} />
</div>
) : (
<a className="panel-info-notice" href={notice.link} target="_blank" rel="noreferrer">
<Icon name={iconName} style={{ marginRight: '8px' }} />
</a>
)}
</Tooltip>
);
};
| public/app/features/dashboard/dashgrid/PanelHeader/PanelHeaderNotice.tsx | 0 | https://github.com/grafana/grafana/commit/3c52df960ad8a45191ee0141a8c169a0cc4f79a5 | [
0.00017676889547146857,
0.00017230906814802438,
0.00016689561016391963,
0.0001732627279125154,
0.000004086769422428915
] |
{
"id": 1,
"code_window": [
" return (\n",
" <>\n",
" <p className=\"share-modal-info-text\">Export this dashboard.</p>\n",
" <Field label=\"Export for sharing externally\">\n",
" <Switch value={shareExternally} onChange={this.onShareExternallyChange} />\n",
" </Field>\n",
" {config.featureToggles.trimDefaults && (\n",
" <Field label=\"Export with default values removed\">\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" <Switch id=\"share-externally-toggle\" value={shareExternally} onChange={this.onShareExternallyChange} />\n"
],
"file_path": "public/app/features/dashboard/components/ShareModal/ShareExport.tsx",
"type": "replace",
"edit_start_line_idx": 138
} | import { getBackendSrv } from '@grafana/runtime';
import { NotifierDTO } from 'app/types';
export function fetchNotifiers(): Promise<NotifierDTO[]> {
return getBackendSrv().get(`/api/alert-notifiers`);
}
| public/app/features/alerting/unified/api/grafana.ts | 0 | https://github.com/grafana/grafana/commit/3c52df960ad8a45191ee0141a8c169a0cc4f79a5 | [
0.00017491637845523655,
0.00017491637845523655,
0.00017491637845523655,
0.00017491637845523655,
0
] |
{
"id": 1,
"code_window": [
" return (\n",
" <>\n",
" <p className=\"share-modal-info-text\">Export this dashboard.</p>\n",
" <Field label=\"Export for sharing externally\">\n",
" <Switch value={shareExternally} onChange={this.onShareExternallyChange} />\n",
" </Field>\n",
" {config.featureToggles.trimDefaults && (\n",
" <Field label=\"Export with default values removed\">\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" <Switch id=\"share-externally-toggle\" value={shareExternally} onChange={this.onShareExternallyChange} />\n"
],
"file_path": "public/app/features/dashboard/components/ShareModal/ShareExport.tsx",
"type": "replace",
"edit_start_line_idx": 138
} | {
"type": "datasource",
"name": "Parent",
"id": "test-app",
"info": {
"description": "Parent plugin",
"author": {
"name": "Grafana Labs",
"url": "http://grafana.com"
},
"version": "1.0.0",
"updated": "2020-10-20"
}
}
| pkg/plugins/manager/testdata/duplicate-plugins/nested/plugin.json | 0 | https://github.com/grafana/grafana/commit/3c52df960ad8a45191ee0141a8c169a0cc4f79a5 | [
0.00017281675536651164,
0.00017175765242427588,
0.00017069853493012488,
0.00017175765242427588,
0.000001059110218193382
] |
{
"id": 2,
"code_window": [
" </Field>\n",
" {config.featureToggles.trimDefaults && (\n",
" <Field label=\"Export with default values removed\">\n",
" <Switch value={trimDefaults} onChange={this.onTrimDefaultsChange} />\n",
" </Field>\n",
" )}\n",
" <Modal.ButtonRow>\n",
" <Button variant=\"secondary\" onClick={onDismiss} fill=\"outline\">\n",
" Cancel\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <Switch id=\"trim-defaults-toggle\" value={trimDefaults} onChange={this.onTrimDefaultsChange} />\n"
],
"file_path": "public/app/features/dashboard/components/ShareModal/ShareExport.tsx",
"type": "replace",
"edit_start_line_idx": 142
} | import React, { useMemo, useState } from 'react';
import { connect, MapDispatchToProps } from 'react-redux';
import { css, cx, keyframes } from '@emotion/css';
import { chain, cloneDeep, defaults, find, sortBy } from 'lodash';
import tinycolor from 'tinycolor2';
import { locationService, reportInteraction } from '@grafana/runtime';
import { Icon, IconButton, styleMixins, useStyles2 } from '@grafana/ui';
import { selectors } from '@grafana/e2e-selectors';
import { GrafanaTheme2 } from '@grafana/data';
import config from 'app/core/config';
import store from 'app/core/store';
import { addPanel } from 'app/features/dashboard/state/reducers';
import { DashboardModel, PanelModel } from '../../state';
import { LS_PANEL_COPY_KEY } from 'app/core/constants';
import { LibraryElementDTO } from '../../../library-panels/types';
import { toPanelModelLibraryPanel } from '../../../library-panels/utils';
import {
LibraryPanelsSearch,
LibraryPanelsSearchVariant,
} from '../../../library-panels/components/LibraryPanelsSearch/LibraryPanelsSearch';
export type PanelPluginInfo = { id: any; defaults: { gridPos: { w: any; h: any }; title: any } };
export interface OwnProps {
panel: PanelModel;
dashboard: DashboardModel;
}
export interface DispatchProps {
addPanel: typeof addPanel;
}
export type Props = OwnProps & DispatchProps;
const getCopiedPanelPlugins = () => {
const panels = chain(config.panels)
.filter({ hideFromList: false })
.map((item) => item)
.value();
const copiedPanels = [];
const copiedPanelJson = store.get(LS_PANEL_COPY_KEY);
if (copiedPanelJson) {
const copiedPanel = JSON.parse(copiedPanelJson);
const pluginInfo: any = find(panels, { id: copiedPanel.type });
if (pluginInfo) {
const pluginCopy = cloneDeep(pluginInfo);
pluginCopy.name = copiedPanel.title;
pluginCopy.sort = -1;
pluginCopy.defaults = copiedPanel;
copiedPanels.push(pluginCopy);
}
}
return sortBy(copiedPanels, 'sort');
};
export const AddPanelWidgetUnconnected: React.FC<Props> = ({ panel, dashboard }) => {
const [addPanelView, setAddPanelView] = useState(false);
const onCancelAddPanel = (evt: React.MouseEvent<HTMLButtonElement>) => {
evt.preventDefault();
dashboard.removePanel(panel);
};
const onBack = () => {
setAddPanelView(false);
};
const onCreateNewPanel = () => {
const { gridPos } = panel;
const newPanel: Partial<PanelModel> = {
type: 'timeseries',
title: 'Panel Title',
gridPos: { x: gridPos.x, y: gridPos.y, w: gridPos.w, h: gridPos.h },
};
dashboard.addPanel(newPanel);
dashboard.removePanel(panel);
locationService.partial({ editPanel: newPanel.id });
};
const onPasteCopiedPanel = (panelPluginInfo: PanelPluginInfo) => {
const { gridPos } = panel;
const newPanel: any = {
type: panelPluginInfo.id,
title: 'Panel Title',
gridPos: {
x: gridPos.x,
y: gridPos.y,
w: panelPluginInfo.defaults.gridPos.w,
h: panelPluginInfo.defaults.gridPos.h,
},
};
// apply panel template / defaults
if (panelPluginInfo.defaults) {
defaults(newPanel, panelPluginInfo.defaults);
newPanel.title = panelPluginInfo.defaults.title;
store.delete(LS_PANEL_COPY_KEY);
}
dashboard.addPanel(newPanel);
dashboard.removePanel(panel);
};
const onAddLibraryPanel = (panelInfo: LibraryElementDTO) => {
const { gridPos } = panel;
const newPanel: PanelModel = {
...panelInfo.model,
gridPos,
libraryPanel: toPanelModelLibraryPanel(panelInfo),
};
dashboard.addPanel(newPanel);
dashboard.removePanel(panel);
};
const onCreateNewRow = () => {
const newRow: any = {
type: 'row',
title: 'Row title',
gridPos: { x: 0, y: 0 },
};
dashboard.addPanel(newRow);
dashboard.removePanel(panel);
};
const styles = useStyles2(getStyles);
const copiedPanelPlugins = useMemo(() => getCopiedPanelPlugins(), []);
return (
<div className={styles.wrapper}>
<div className={cx('panel-container', styles.callToAction)}>
<AddPanelWidgetHandle onCancel={onCancelAddPanel} onBack={addPanelView ? onBack : undefined} styles={styles}>
{addPanelView ? 'Add panel from panel library' : 'Add panel'}
</AddPanelWidgetHandle>
{addPanelView ? (
<LibraryPanelsSearch onClick={onAddLibraryPanel} variant={LibraryPanelsSearchVariant.Tight} showPanelFilter />
) : (
<div className={styles.actionsWrapper}>
<div className={cx(styles.actionsRow, styles.columnGap)}>
<div
onClick={() => {
reportInteraction('Create new panel');
onCreateNewPanel();
}}
aria-label={selectors.pages.AddDashboard.addNewPanel}
>
<Icon name="file-blank" size="xl" />
Add an empty panel
</div>
<div
className={styles.rowGap}
onClick={() => {
reportInteraction('Create new row');
onCreateNewRow();
}}
aria-label={selectors.pages.AddDashboard.addNewRow}
>
<Icon name="wrap-text" size="xl" />
Add a new row
</div>
</div>
<div className={styles.actionsRow}>
<div
onClick={() => {
reportInteraction('Add a panel from the panel library');
setAddPanelView(true);
}}
aria-label={selectors.pages.AddDashboard.addNewPanelLibrary}
>
<Icon name="book-open" size="xl" />
Add a panel from the panel library
</div>
{copiedPanelPlugins.length === 1 && (
<div
className={styles.rowGap}
onClick={() => {
reportInteraction('Paste panel from clipboard');
onPasteCopiedPanel(copiedPanelPlugins[0]);
}}
>
<Icon name="clipboard-alt" size="xl" />
Paste panel from clipboard
</div>
)}
</div>
</div>
)}
</div>
</div>
);
};
const mapDispatchToProps: MapDispatchToProps<DispatchProps, OwnProps> = { addPanel };
export const AddPanelWidget = connect(undefined, mapDispatchToProps)(AddPanelWidgetUnconnected);
interface AddPanelWidgetHandleProps {
onCancel: (e: React.MouseEvent<HTMLButtonElement>) => void;
onBack?: () => void;
children?: string;
styles: AddPanelStyles;
}
const AddPanelWidgetHandle: React.FC<AddPanelWidgetHandleProps> = ({ children, onBack, onCancel, styles }) => {
return (
<div className={cx(styles.headerRow, 'grid-drag-handle')}>
{onBack && (
<div className={styles.backButton}>
<IconButton name="arrow-left" onClick={onBack} surface="header" size="xl" />
</div>
)}
{!onBack && (
<div className={styles.backButton}>
<Icon name="panel-add" size="md" />
</div>
)}
{children && <span>{children}</span>}
<div className="flex-grow-1" />
<IconButton aria-label="Close 'Add Panel' widget" name="times" onClick={onCancel} surface="header" />
</div>
);
};
const getStyles = (theme: GrafanaTheme2) => {
const pulsate = keyframes`
0% {box-shadow: 0 0 0 2px ${theme.colors.background.canvas}, 0 0 0px 4px ${theme.colors.primary.main};}
50% {box-shadow: 0 0 0 2px ${theme.components.dashboard.background}, 0 0 0px 4px ${tinycolor(
theme.colors.primary.main
)
.darken(20)
.toHexString()};}
100% {box-shadow: 0 0 0 2px ${theme.components.dashboard.background}, 0 0 0px 4px ${theme.colors.primary.main};}
`;
return {
// wrapper is used to make sure box-shadow animation isn't cut off in dashboard page
wrapper: css`
height: 100%;
padding-top: ${theme.spacing(0.5)};
`,
callToAction: css`
overflow: hidden;
outline: 2px dotted transparent;
outline-offset: 2px;
box-shadow: 0 0 0 2px black, 0 0 0px 4px #1f60c4;
animation: ${pulsate} 2s ease infinite;
`,
rowGap: css`
margin-left: ${theme.spacing(1)};
`,
columnGap: css`
margin-bottom: ${theme.spacing(1)};
`,
actionsRow: css`
display: flex;
flex-direction: row;
height: 100%;
> div {
justify-self: center;
cursor: pointer;
background: ${theme.colors.background.secondary};
border-radius: ${theme.shape.borderRadius(1)};
color: ${theme.colors.text.primary};
width: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
text-align: center;
&:hover {
background: ${styleMixins.hoverColor(theme.colors.background.secondary, theme)};
}
&:hover > #book-icon {
background: linear-gradient(#f05a28 30%, #fbca0a 99%);
}
}
`,
actionsWrapper: css`
display: flex;
flex-direction: column;
padding: ${theme.spacing(0, 1, 1, 1)};
height: 100%;
`,
headerRow: css`
display: flex;
align-items: center;
height: 38px;
flex-shrink: 0;
width: 100%;
font-size: ${theme.typography.fontSize};
font-weight: ${theme.typography.fontWeightMedium};
padding-left: ${theme.spacing(1)};
transition: background-color 0.1s ease-in-out;
cursor: move;
&:hover {
background: ${theme.colors.background.secondary};
}
`,
backButton: css`
display: flex;
align-items: center;
cursor: pointer;
padding-left: ${theme.spacing(0.5)};
width: ${theme.spacing(4)};
`,
noMargin: css`
margin: 0;
`,
};
};
type AddPanelStyles = ReturnType<typeof getStyles>;
| public/app/features/dashboard/components/AddPanelWidget/AddPanelWidget.tsx | 1 | https://github.com/grafana/grafana/commit/3c52df960ad8a45191ee0141a8c169a0cc4f79a5 | [
0.0006522919284179807,
0.0002003518311539665,
0.0001639503170736134,
0.00016988113929983228,
0.00009314451017417014
] |
{
"id": 2,
"code_window": [
" </Field>\n",
" {config.featureToggles.trimDefaults && (\n",
" <Field label=\"Export with default values removed\">\n",
" <Switch value={trimDefaults} onChange={this.onTrimDefaultsChange} />\n",
" </Field>\n",
" )}\n",
" <Modal.ButtonRow>\n",
" <Button variant=\"secondary\" onClick={onDismiss} fill=\"outline\">\n",
" Cancel\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <Switch id=\"trim-defaults-toggle\" value={trimDefaults} onChange={this.onTrimDefaultsChange} />\n"
],
"file_path": "public/app/features/dashboard/components/ShareModal/ShareExport.tsx",
"type": "replace",
"edit_start_line_idx": 142
} | import React from 'react';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Playlist } from './types';
import { PlaylistNewPage } from './PlaylistNewPage';
import { backendSrv } from '../../core/services/backend_srv';
import { locationService } from '@grafana/runtime';
jest.mock('./usePlaylist', () => ({
// so we don't need to add dashboard items in test
usePlaylist: jest.fn().mockReturnValue({
playlist: { items: [{ title: 'First item', type: 'dashboard_by_id', order: 1, value: '1' }], loading: false },
}),
}));
jest.mock('@grafana/runtime', () => ({
...(jest.requireActual('@grafana/runtime') as any),
getBackendSrv: () => backendSrv,
}));
function getTestContext({ name, interval, items }: Partial<Playlist> = {}) {
jest.clearAllMocks();
const playlist = ({ name, items, interval } as unknown) as Playlist;
const queryParams = {};
const route: any = {};
const match: any = {};
const location: any = {};
const history: any = {};
const navModel: any = {
node: {},
main: {},
};
const backendSrvMock = jest.spyOn(backendSrv, 'post');
const { rerender } = render(
<PlaylistNewPage
queryParams={queryParams}
route={route}
match={match}
location={location}
history={history}
navModel={navModel}
/>
);
return { playlist, rerender, backendSrvMock };
}
describe('PlaylistNewPage', () => {
describe('when mounted', () => {
it('then header should be correct', () => {
getTestContext();
expect(screen.getByRole('heading', { name: /new playlist/i })).toBeInTheDocument();
});
});
describe('when submitted', () => {
it('then correct api should be called', async () => {
const { backendSrvMock } = getTestContext();
expect(locationService.getLocation().pathname).toEqual('/');
userEvent.type(screen.getByRole('textbox', { name: /playlist name/i }), 'A Name');
fireEvent.submit(screen.getByRole('button', { name: /save/i }));
await waitFor(() => expect(backendSrvMock).toHaveBeenCalledTimes(1));
expect(backendSrvMock).toHaveBeenCalledWith('/api/playlists', {
name: 'A Name',
interval: '5m',
items: [{ title: 'First item', type: 'dashboard_by_id', order: 1, value: '1' }],
});
expect(locationService.getLocation().pathname).toEqual('/playlists');
});
});
});
| public/app/features/playlist/PlaylistNewPage.test.tsx | 0 | https://github.com/grafana/grafana/commit/3c52df960ad8a45191ee0141a8c169a0cc4f79a5 | [
0.00017621942970436066,
0.000174461689312011,
0.00017286124057136476,
0.0001745822955854237,
0.0000010458354608999798
] |
{
"id": 2,
"code_window": [
" </Field>\n",
" {config.featureToggles.trimDefaults && (\n",
" <Field label=\"Export with default values removed\">\n",
" <Switch value={trimDefaults} onChange={this.onTrimDefaultsChange} />\n",
" </Field>\n",
" )}\n",
" <Modal.ButtonRow>\n",
" <Button variant=\"secondary\" onClick={onDismiss} fill=\"outline\">\n",
" Cancel\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <Switch id=\"trim-defaults-toggle\" value={trimDefaults} onChange={this.onTrimDefaultsChange} />\n"
],
"file_path": "public/app/features/dashboard/components/ShareModal/ShareExport.tsx",
"type": "replace",
"edit_start_line_idx": 142
} | package azcredentials
const (
AzureAuthManagedIdentity = "msi"
AzureAuthClientSecret = "clientsecret"
)
type AzureCredentials interface {
AzureAuthType() string
}
type AzureManagedIdentityCredentials struct {
ClientId string
}
type AzureClientSecretCredentials struct {
AzureCloud string
Authority string
TenantId string
ClientId string
ClientSecret string
}
func (credentials *AzureManagedIdentityCredentials) AzureAuthType() string {
return AzureAuthManagedIdentity
}
func (credentials *AzureClientSecretCredentials) AzureAuthType() string {
return AzureAuthClientSecret
}
| pkg/tsdb/azuremonitor/azcredentials/credentials.go | 0 | https://github.com/grafana/grafana/commit/3c52df960ad8a45191ee0141a8c169a0cc4f79a5 | [
0.0002090588241117075,
0.00017794332234188914,
0.00016180076636373997,
0.00017045685672201216,
0.00001841004632296972
] |
{
"id": 2,
"code_window": [
" </Field>\n",
" {config.featureToggles.trimDefaults && (\n",
" <Field label=\"Export with default values removed\">\n",
" <Switch value={trimDefaults} onChange={this.onTrimDefaultsChange} />\n",
" </Field>\n",
" )}\n",
" <Modal.ButtonRow>\n",
" <Button variant=\"secondary\" onClick={onDismiss} fill=\"outline\">\n",
" Cancel\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <Switch id=\"trim-defaults-toggle\" value={trimDefaults} onChange={this.onTrimDefaultsChange} />\n"
],
"file_path": "public/app/features/dashboard/components/ShareModal/ShareExport.tsx",
"type": "replace",
"edit_start_line_idx": 142
} | import { configurePanel, PartialAddPanelConfig } from './configurePanel';
import { getScenarioContext } from '../support/scenarioContext';
import { v4 as uuidv4 } from 'uuid';
export const addPanel = (config?: Partial<PartialAddPanelConfig>) =>
getScenarioContext().then(({ lastAddedDataSource }: any) =>
configurePanel({
dataSourceName: lastAddedDataSource,
panelTitle: `e2e-${uuidv4()}`,
...config,
isEdit: false,
isExplore: false,
})
);
| packages/grafana-e2e/src/flows/addPanel.ts | 0 | https://github.com/grafana/grafana/commit/3c52df960ad8a45191ee0141a8c169a0cc4f79a5 | [
0.00017242517787963152,
0.00017041996761690825,
0.00016841475735418499,
0.00017041996761690825,
0.000002005210262723267
] |
{
"id": 3,
"code_window": [
" Keep in mind, your snapshot <em>can be viewed by anyone</em> that has the link and can access the URL. Share\n",
" wisely.\n",
" </p>\n",
" </div>\n",
" <Field label=\"Snapshot name\">\n",
" <Input width={30} value={snapshotName} onChange={this.onSnapshotNameChange} />\n",
" </Field>\n",
" <Field label=\"Expire\">\n",
" <Select\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" <Input id=\"snapshot-name-input\" width={30} value={snapshotName} onChange={this.onSnapshotNameChange} />\n"
],
"file_path": "public/app/features/dashboard/components/ShareModal/ShareSnapshot.tsx",
"type": "replace",
"edit_start_line_idx": 225
} | import React, { PureComponent } from 'react';
import { Button, ClipboardButton, Icon, Spinner, Select, Input, LinkButton, Field, Modal } from '@grafana/ui';
import { AppEvents, SelectableValue } from '@grafana/data';
import { getBackendSrv } from '@grafana/runtime';
import { DashboardModel, PanelModel } from 'app/features/dashboard/state';
import { getTimeSrv } from 'app/features/dashboard/services/TimeSrv';
import { appEvents } from 'app/core/core';
import { VariableRefresh } from '../../../variables/types';
const snapshotApiUrl = '/api/snapshots';
const expireOptions: Array<SelectableValue<number>> = [
{ label: 'Never', value: 0 },
{ label: '1 Hour', value: 60 * 60 },
{ label: '1 Day', value: 60 * 60 * 24 },
{ label: '7 Days', value: 60 * 60 * 24 * 7 },
];
interface Props {
dashboard: DashboardModel;
panel?: PanelModel;
onDismiss(): void;
}
interface State {
isLoading: boolean;
step: number;
snapshotName: string;
selectedExpireOption: SelectableValue<number>;
snapshotExpires?: number;
snapshotUrl: string;
deleteUrl: string;
timeoutSeconds: number;
externalEnabled: boolean;
sharingButtonText: string;
}
export class ShareSnapshot extends PureComponent<Props, State> {
private dashboard: DashboardModel;
constructor(props: Props) {
super(props);
this.dashboard = props.dashboard;
this.state = {
isLoading: false,
step: 1,
selectedExpireOption: expireOptions[0],
snapshotExpires: expireOptions[0].value,
snapshotName: props.dashboard.title,
timeoutSeconds: 4,
snapshotUrl: '',
deleteUrl: '',
externalEnabled: false,
sharingButtonText: '',
};
}
componentDidMount() {
this.getSnaphotShareOptions();
}
async getSnaphotShareOptions() {
const shareOptions = await getBackendSrv().get('/api/snapshot/shared-options');
this.setState({
sharingButtonText: shareOptions['externalSnapshotName'],
externalEnabled: shareOptions['externalEnabled'],
});
}
createSnapshot = (external?: boolean) => () => {
const { timeoutSeconds } = this.state;
this.dashboard.snapshot = {
timestamp: new Date(),
};
if (!external) {
this.dashboard.snapshot.originalUrl = window.location.href;
}
this.setState({ isLoading: true });
this.dashboard.startRefresh();
setTimeout(() => {
this.saveSnapshot(this.dashboard, external);
}, timeoutSeconds * 1000);
};
saveSnapshot = async (dashboard: DashboardModel, external?: boolean) => {
const { snapshotExpires } = this.state;
const dash = this.dashboard.getSaveModelClone();
this.scrubDashboard(dash);
const cmdData = {
dashboard: dash,
name: dash.title,
expires: snapshotExpires,
external: external,
};
try {
const results: { deleteUrl: any; url: any } = await getBackendSrv().post(snapshotApiUrl, cmdData);
this.setState({
deleteUrl: results.deleteUrl,
snapshotUrl: results.url,
step: 2,
});
} finally {
this.setState({ isLoading: false });
}
};
scrubDashboard = (dash: DashboardModel) => {
const { panel } = this.props;
const { snapshotName } = this.state;
// change title
dash.title = snapshotName;
// make relative times absolute
dash.time = getTimeSrv().timeRange();
// Remove links
dash.links = [];
// remove panel queries & links
dash.panels.forEach((panel) => {
panel.targets = [];
panel.links = [];
panel.datasource = null;
});
// remove annotation queries
const annotations = dash.annotations.list.filter((annotation) => annotation.enable);
dash.annotations.list = annotations.map((annotation: any) => {
return {
name: annotation.name,
enable: annotation.enable,
iconColor: annotation.iconColor,
snapshotData: annotation.snapshotData,
type: annotation.type,
builtIn: annotation.builtIn,
hide: annotation.hide,
};
});
// remove template queries
dash.getVariables().forEach((variable: any) => {
variable.query = '';
variable.options = variable.current ? [variable.current] : [];
variable.refresh = VariableRefresh.never;
});
// snapshot single panel
if (panel) {
const singlePanel = panel.getSaveModel();
singlePanel.gridPos.w = 24;
singlePanel.gridPos.x = 0;
singlePanel.gridPos.y = 0;
singlePanel.gridPos.h = 20;
dash.panels = [singlePanel];
}
// cleanup snapshotData
delete this.dashboard.snapshot;
this.dashboard.forEachPanel((panel: PanelModel) => {
delete panel.snapshotData;
});
this.dashboard.annotations.list.forEach((annotation) => {
delete annotation.snapshotData;
});
};
deleteSnapshot = async () => {
const { deleteUrl } = this.state;
await getBackendSrv().get(deleteUrl);
this.setState({ step: 3 });
};
getSnapshotUrl = () => {
return this.state.snapshotUrl;
};
onSnapshotNameChange = (event: React.ChangeEvent<HTMLInputElement>) => {
this.setState({ snapshotName: event.target.value });
};
onTimeoutChange = (event: React.ChangeEvent<HTMLInputElement>) => {
this.setState({ timeoutSeconds: Number(event.target.value) });
};
onExpireChange = (option: SelectableValue<number>) => {
this.setState({
selectedExpireOption: option,
snapshotExpires: option.value,
});
};
onSnapshotUrlCopy = () => {
appEvents.emit(AppEvents.alertSuccess, ['Content copied to clipboard']);
};
renderStep1() {
const { onDismiss } = this.props;
const {
snapshotName,
selectedExpireOption,
timeoutSeconds,
isLoading,
sharingButtonText,
externalEnabled,
} = this.state;
return (
<>
<div>
<p className="share-modal-info-text">
A snapshot is an instant way to share an interactive dashboard publicly. When created, we strip sensitive
data like queries (metric, template, and annotation) and panel links, leaving only the visible metric data
and series names embedded in your dashboard.
</p>
<p className="share-modal-info-text">
Keep in mind, your snapshot <em>can be viewed by anyone</em> that has the link and can access the URL. Share
wisely.
</p>
</div>
<Field label="Snapshot name">
<Input width={30} value={snapshotName} onChange={this.onSnapshotNameChange} />
</Field>
<Field label="Expire">
<Select
menuShouldPortal
width={30}
options={expireOptions}
value={selectedExpireOption}
onChange={this.onExpireChange}
/>
</Field>
<Field
label="Timeout (seconds)"
description="You might need to configure the timeout value if it takes a long time to collect your dashboard
metrics."
>
<Input type="number" width={21} value={timeoutSeconds} onChange={this.onTimeoutChange} />
</Field>
<Modal.ButtonRow>
<Button variant="secondary" onClick={onDismiss} fill="outline">
Cancel
</Button>
{externalEnabled && (
<Button variant="secondary" disabled={isLoading} onClick={this.createSnapshot(true)}>
{sharingButtonText}
</Button>
)}
<Button variant="primary" disabled={isLoading} onClick={this.createSnapshot()}>
Local Snapshot
</Button>
</Modal.ButtonRow>
</>
);
}
renderStep2() {
const { snapshotUrl } = this.state;
return (
<>
<div className="gf-form" style={{ marginTop: '40px' }}>
<div className="gf-form-row">
<a href={snapshotUrl} className="large share-modal-link" target="_blank" rel="noreferrer">
<Icon name="external-link-alt" /> {snapshotUrl}
</a>
<br />
<ClipboardButton variant="secondary" getText={this.getSnapshotUrl} onClipboardCopy={this.onSnapshotUrlCopy}>
Copy Link
</ClipboardButton>
</div>
</div>
<div className="pull-right" style={{ padding: '5px' }}>
Did you make a mistake?{' '}
<LinkButton fill="text" target="_blank" onClick={this.deleteSnapshot}>
Delete snapshot.
</LinkButton>
</div>
</>
);
}
renderStep3() {
return (
<div className="share-modal-header">
<p className="share-modal-info-text">
The snapshot has been deleted. If you have already accessed it once, then it might take up to an hour before
before it is removed from browser caches or CDN caches.
</p>
</div>
);
}
render() {
const { isLoading, step } = this.state;
return (
<>
{step === 1 && this.renderStep1()}
{step === 2 && this.renderStep2()}
{step === 3 && this.renderStep3()}
{isLoading && <Spinner inline={true} />}
</>
);
}
}
| public/app/features/dashboard/components/ShareModal/ShareSnapshot.tsx | 1 | https://github.com/grafana/grafana/commit/3c52df960ad8a45191ee0141a8c169a0cc4f79a5 | [
0.9969161748886108,
0.03200965374708176,
0.00016667328600306064,
0.00031958031468093395,
0.17330752313137054
] |
{
"id": 3,
"code_window": [
" Keep in mind, your snapshot <em>can be viewed by anyone</em> that has the link and can access the URL. Share\n",
" wisely.\n",
" </p>\n",
" </div>\n",
" <Field label=\"Snapshot name\">\n",
" <Input width={30} value={snapshotName} onChange={this.onSnapshotNameChange} />\n",
" </Field>\n",
" <Field label=\"Expire\">\n",
" <Select\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" <Input id=\"snapshot-name-input\" width={30} value={snapshotName} onChange={this.onSnapshotNameChange} />\n"
],
"file_path": "public/app/features/dashboard/components/ShareModal/ShareSnapshot.tsx",
"type": "replace",
"edit_start_line_idx": 225
} | package migrations
import (
. "github.com/grafana/grafana/pkg/services/sqlstore/migrator"
"xorm.io/xorm"
)
func addAnnotationMig(mg *Migrator) {
table := Table{
Name: "annotation",
Columns: []*Column{
{Name: "id", Type: DB_BigInt, IsPrimaryKey: true, IsAutoIncrement: true},
{Name: "org_id", Type: DB_BigInt, Nullable: false},
{Name: "alert_id", Type: DB_BigInt, Nullable: true},
{Name: "user_id", Type: DB_BigInt, Nullable: true},
{Name: "dashboard_id", Type: DB_BigInt, Nullable: true},
{Name: "panel_id", Type: DB_BigInt, Nullable: true},
{Name: "category_id", Type: DB_BigInt, Nullable: true},
{Name: "type", Type: DB_NVarchar, Length: 25, Nullable: false},
{Name: "title", Type: DB_Text, Nullable: false},
{Name: "text", Type: DB_Text, Nullable: false},
{Name: "metric", Type: DB_NVarchar, Length: 255, Nullable: true},
{Name: "prev_state", Type: DB_NVarchar, Length: 25, Nullable: false},
{Name: "new_state", Type: DB_NVarchar, Length: 25, Nullable: false},
{Name: "data", Type: DB_Text, Nullable: false},
{Name: "epoch", Type: DB_BigInt, Nullable: false},
},
Indices: []*Index{
{Cols: []string{"org_id", "alert_id"}, Type: IndexType},
{Cols: []string{"org_id", "type"}, Type: IndexType},
{Cols: []string{"org_id", "category_id"}, Type: IndexType},
{Cols: []string{"org_id", "dashboard_id", "panel_id", "epoch"}, Type: IndexType},
{Cols: []string{"org_id", "epoch"}, Type: IndexType},
},
}
mg.AddMigration("Drop old annotation table v4", NewDropTableMigration("annotation"))
mg.AddMigration("create annotation table v5", NewAddTableMigration(table))
// create indices
mg.AddMigration("add index annotation 0 v3", NewAddIndexMigration(table, table.Indices[0]))
mg.AddMigration("add index annotation 1 v3", NewAddIndexMigration(table, table.Indices[1]))
mg.AddMigration("add index annotation 2 v3", NewAddIndexMigration(table, table.Indices[2]))
mg.AddMigration("add index annotation 3 v3", NewAddIndexMigration(table, table.Indices[3]))
mg.AddMigration("add index annotation 4 v3", NewAddIndexMigration(table, table.Indices[4]))
mg.AddMigration("Update annotation table charset", NewTableCharsetMigration("annotation", []*Column{
{Name: "type", Type: DB_NVarchar, Length: 25, Nullable: false},
{Name: "title", Type: DB_Text, Nullable: false},
{Name: "text", Type: DB_Text, Nullable: false},
{Name: "metric", Type: DB_NVarchar, Length: 255, Nullable: true},
{Name: "prev_state", Type: DB_NVarchar, Length: 25, Nullable: false},
{Name: "new_state", Type: DB_NVarchar, Length: 25, Nullable: false},
{Name: "data", Type: DB_Text, Nullable: false},
}))
mg.AddMigration("Add column region_id to annotation table", NewAddColumnMigration(table, &Column{
Name: "region_id", Type: DB_BigInt, Nullable: true, Default: "0",
}))
categoryIdIndex := &Index{Cols: []string{"org_id", "category_id"}, Type: IndexType}
mg.AddMigration("Drop category_id index", NewDropIndexMigration(table, categoryIdIndex))
mg.AddMigration("Add column tags to annotation table", NewAddColumnMigration(table, &Column{
Name: "tags", Type: DB_NVarchar, Nullable: true, Length: 500,
}))
//
// Annotation tag
//
annotationTagTable := Table{
Name: "annotation_tag",
Columns: []*Column{
{Name: "annotation_id", Type: DB_BigInt, Nullable: false},
{Name: "tag_id", Type: DB_BigInt, Nullable: false},
},
Indices: []*Index{
{Cols: []string{"annotation_id", "tag_id"}, Type: UniqueIndex},
},
}
mg.AddMigration("Create annotation_tag table v2", NewAddTableMigration(annotationTagTable))
mg.AddMigration("Add unique index annotation_tag.annotation_id_tag_id", NewAddIndexMigration(annotationTagTable, annotationTagTable.Indices[0]))
// drop dashboard indexes
addDropAllIndicesMigrations(mg, "v2", annotationTagTable)
// rename table
addTableRenameMigration(mg, "annotation_tag", "annotation_tag_v2", "v2")
// annotation_tag v3
annotationTagTableV3 := Table{
Name: "annotation_tag",
Columns: []*Column{
{Name: "id", Type: DB_BigInt, IsPrimaryKey: true, IsAutoIncrement: true},
{Name: "annotation_id", Type: DB_BigInt, Nullable: false},
{Name: "tag_id", Type: DB_BigInt, Nullable: false},
},
Indices: []*Index{
{Cols: []string{"annotation_id", "tag_id"}, Type: UniqueIndex},
},
}
// recreate table
mg.AddMigration("Create annotation_tag table v3", NewAddTableMigration(annotationTagTableV3))
// recreate indices
addTableIndicesMigrations(mg, "Add unique index annotation_tag.annotation_id_tag_id V3", annotationTagTableV3)
// copy data
mg.AddMigration("copy annotation_tag v2 to v3", NewCopyTableDataMigration("annotation_tag", "annotation_tag_v2", map[string]string{
"annotation_id": "annotation_id",
"tag_id": "tag_id",
}))
mg.AddMigration("drop table annotation_tag_v2", NewDropTableMigration("annotation_tag_v2"))
//
// clear alert text
//
updateTextFieldSQL := "UPDATE annotation SET TEXT = '' WHERE alert_id > 0"
mg.AddMigration("Update alert annotations and set TEXT to empty", NewRawSQLMigration(updateTextFieldSQL))
//
// Add a 'created' & 'updated' column
//
mg.AddMigration("Add created time to annotation table", NewAddColumnMigration(table, &Column{
Name: "created", Type: DB_BigInt, Nullable: true, Default: "0",
}))
mg.AddMigration("Add updated time to annotation table", NewAddColumnMigration(table, &Column{
Name: "updated", Type: DB_BigInt, Nullable: true, Default: "0",
}))
mg.AddMigration("Add index for created in annotation table", NewAddIndexMigration(table, &Index{
Cols: []string{"org_id", "created"}, Type: IndexType,
}))
mg.AddMigration("Add index for updated in annotation table", NewAddIndexMigration(table, &Index{
Cols: []string{"org_id", "updated"}, Type: IndexType,
}))
//
// Convert epoch saved as seconds to milliseconds
//
updateEpochSQL := "UPDATE annotation SET epoch = (epoch*1000) where epoch < 9999999999"
mg.AddMigration("Convert existing annotations from seconds to milliseconds", NewRawSQLMigration(updateEpochSQL))
//
// 6.4: Make Regions a single annotation row
//
mg.AddMigration("Add epoch_end column", NewAddColumnMigration(table, &Column{
Name: "epoch_end", Type: DB_BigInt, Nullable: false, Default: "0",
}))
mg.AddMigration("Add index for epoch_end", NewAddIndexMigration(table, &Index{
Cols: []string{"org_id", "epoch", "epoch_end"}, Type: IndexType,
}))
mg.AddMigration("Make epoch_end the same as epoch", NewRawSQLMigration("UPDATE annotation SET epoch_end = epoch"))
mg.AddMigration("Move region to single row", &AddMakeRegionSingleRowMigration{})
//
// 6.6.1: Optimize annotation queries
//
mg.AddMigration("Remove index org_id_epoch from annotation table", NewDropIndexMigration(table, &Index{
Cols: []string{"org_id", "epoch"}, Type: IndexType,
}))
mg.AddMigration("Remove index org_id_dashboard_id_panel_id_epoch from annotation table", NewDropIndexMigration(table, &Index{
Cols: []string{"org_id", "dashboard_id", "panel_id", "epoch"}, Type: IndexType,
}))
mg.AddMigration("Add index for org_id_dashboard_id_epoch_end_epoch on annotation table", NewAddIndexMigration(table, &Index{
Cols: []string{"org_id", "dashboard_id", "epoch_end", "epoch"}, Type: IndexType,
}))
mg.AddMigration("Add index for org_id_epoch_end_epoch on annotation table", NewAddIndexMigration(table, &Index{
Cols: []string{"org_id", "epoch_end", "epoch"}, Type: IndexType,
}))
mg.AddMigration("Remove index org_id_epoch_epoch_end from annotation table", NewDropIndexMigration(table, &Index{
Cols: []string{"org_id", "epoch", "epoch_end"}, Type: IndexType,
}))
mg.AddMigration("Add index for alert_id on annotation table", NewAddIndexMigration(table, &Index{
Cols: []string{"alert_id"}, Type: IndexType,
}))
}
type AddMakeRegionSingleRowMigration struct {
MigrationBase
}
func (m *AddMakeRegionSingleRowMigration) SQL(dialect Dialect) string {
return "code migration"
}
type TempRegionInfoDTO struct {
RegionId int64
Epoch int64
}
func (m *AddMakeRegionSingleRowMigration) Exec(sess *xorm.Session, mg *Migrator) error {
regions := make([]*TempRegionInfoDTO, 0)
err := sess.SQL("SELECT region_id, epoch FROM annotation WHERE region_id>0 AND region_id <> id").Find(®ions)
if err != nil {
return err
}
for _, region := range regions {
_, err := sess.Exec("UPDATE annotation SET epoch_end = ? WHERE id = ?", region.Epoch, region.RegionId)
if err != nil {
return err
}
}
_, err = sess.Exec("DELETE FROM annotation WHERE region_id > 0 AND id <> region_id")
return err
}
| pkg/services/sqlstore/migrations/annotation_mig.go | 0 | https://github.com/grafana/grafana/commit/3c52df960ad8a45191ee0141a8c169a0cc4f79a5 | [
0.0002244125062134117,
0.00017444240802433342,
0.00016387671348638833,
0.00017285658395849168,
0.00001128647545556305
] |
{
"id": 3,
"code_window": [
" Keep in mind, your snapshot <em>can be viewed by anyone</em> that has the link and can access the URL. Share\n",
" wisely.\n",
" </p>\n",
" </div>\n",
" <Field label=\"Snapshot name\">\n",
" <Input width={30} value={snapshotName} onChange={this.onSnapshotNameChange} />\n",
" </Field>\n",
" <Field label=\"Expire\">\n",
" <Select\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" <Input id=\"snapshot-name-input\" width={30} value={snapshotName} onChange={this.onSnapshotNameChange} />\n"
],
"file_path": "public/app/features/dashboard/components/ShareModal/ShareSnapshot.tsx",
"type": "replace",
"edit_start_line_idx": 225
} | // Copyright 2021 Grafana Labs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package grafanaschema
import (
ui "github.com/grafana/grafana/packages/grafana-schema/src/schema"
)
Panel: {
lineages: [
[
{
PanelOptions: {
frameIndex: number | *0
showHeader: bool | *true
showTypeIcons: bool | *false
sortBy?: [...ui.TableSortByFieldState]
}
PanelFieldConfig: {
width?: int
minWidth?: int
align?: string | *"auto"
displayMode?: string | *"auto" // TODO? TableCellDisplayMode
filterable?: bool
}
},
]
]
migrations: []
}
| public/app/plugins/panel/table/models.cue | 0 | https://github.com/grafana/grafana/commit/3c52df960ad8a45191ee0141a8c169a0cc4f79a5 | [
0.0001767962094163522,
0.00017069226305466145,
0.00016634445637464523,
0.00017030250455718488,
0.0000036172357340547023
] |
{
"id": 3,
"code_window": [
" Keep in mind, your snapshot <em>can be viewed by anyone</em> that has the link and can access the URL. Share\n",
" wisely.\n",
" </p>\n",
" </div>\n",
" <Field label=\"Snapshot name\">\n",
" <Input width={30} value={snapshotName} onChange={this.onSnapshotNameChange} />\n",
" </Field>\n",
" <Field label=\"Expire\">\n",
" <Select\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" <Input id=\"snapshot-name-input\" width={30} value={snapshotName} onChange={this.onSnapshotNameChange} />\n"
],
"file_path": "public/app/features/dashboard/components/ShareModal/ShareSnapshot.tsx",
"type": "replace",
"edit_start_line_idx": 225
} | .page-dashboard .footer {
display: none;
}
.footer {
color: $footer-link-color;
padding: $space-md 0 $space-md 0;
font-size: $font-size-sm;
position: relative;
width: 98%; /* was causing horiz scrollbars - need to examine */
a {
color: $footer-link-color;
&:hover {
color: $footer-link-hover;
}
i {
display: inline-block;
padding-right: $space-xxs;
}
}
ul {
list-style: none;
}
li {
display: inline-block;
&::after {
content: ' | ';
padding: 0 $space-sm;
}
}
li:last-child {
&::after {
padding-left: 0;
content: '';
}
}
}
.login-page {
.footer {
display: block;
bottom: $spacer;
position: absolute;
padding: $space-md 0 $space-md 0;
color: $text-color;
a {
color: $text-color;
&:hover {
color: $text-color-strong;
}
}
}
}
@include media-breakpoint-down(md) {
.login-page {
.footer {
display: none;
}
}
}
| public/sass/components/_footer.scss | 0 | https://github.com/grafana/grafana/commit/3c52df960ad8a45191ee0141a8c169a0cc4f79a5 | [
0.00017522837151773274,
0.0001716025872156024,
0.0001658371911616996,
0.00017233422840945423,
0.000003138447027595248
] |
{
"id": 4,
"code_window": [
" </Field>\n",
" <Field label=\"Expire\">\n",
" <Select\n",
" menuShouldPortal\n",
" width={30}\n",
" options={expireOptions}\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" inputId=\"expire-select-input\"\n"
],
"file_path": "public/app/features/dashboard/components/ShareModal/ShareSnapshot.tsx",
"type": "add",
"edit_start_line_idx": 229
} | import React, { PureComponent } from 'react';
import { Button, ClipboardButton, Icon, Spinner, Select, Input, LinkButton, Field, Modal } from '@grafana/ui';
import { AppEvents, SelectableValue } from '@grafana/data';
import { getBackendSrv } from '@grafana/runtime';
import { DashboardModel, PanelModel } from 'app/features/dashboard/state';
import { getTimeSrv } from 'app/features/dashboard/services/TimeSrv';
import { appEvents } from 'app/core/core';
import { VariableRefresh } from '../../../variables/types';
const snapshotApiUrl = '/api/snapshots';
const expireOptions: Array<SelectableValue<number>> = [
{ label: 'Never', value: 0 },
{ label: '1 Hour', value: 60 * 60 },
{ label: '1 Day', value: 60 * 60 * 24 },
{ label: '7 Days', value: 60 * 60 * 24 * 7 },
];
interface Props {
dashboard: DashboardModel;
panel?: PanelModel;
onDismiss(): void;
}
interface State {
isLoading: boolean;
step: number;
snapshotName: string;
selectedExpireOption: SelectableValue<number>;
snapshotExpires?: number;
snapshotUrl: string;
deleteUrl: string;
timeoutSeconds: number;
externalEnabled: boolean;
sharingButtonText: string;
}
export class ShareSnapshot extends PureComponent<Props, State> {
private dashboard: DashboardModel;
constructor(props: Props) {
super(props);
this.dashboard = props.dashboard;
this.state = {
isLoading: false,
step: 1,
selectedExpireOption: expireOptions[0],
snapshotExpires: expireOptions[0].value,
snapshotName: props.dashboard.title,
timeoutSeconds: 4,
snapshotUrl: '',
deleteUrl: '',
externalEnabled: false,
sharingButtonText: '',
};
}
componentDidMount() {
this.getSnaphotShareOptions();
}
async getSnaphotShareOptions() {
const shareOptions = await getBackendSrv().get('/api/snapshot/shared-options');
this.setState({
sharingButtonText: shareOptions['externalSnapshotName'],
externalEnabled: shareOptions['externalEnabled'],
});
}
createSnapshot = (external?: boolean) => () => {
const { timeoutSeconds } = this.state;
this.dashboard.snapshot = {
timestamp: new Date(),
};
if (!external) {
this.dashboard.snapshot.originalUrl = window.location.href;
}
this.setState({ isLoading: true });
this.dashboard.startRefresh();
setTimeout(() => {
this.saveSnapshot(this.dashboard, external);
}, timeoutSeconds * 1000);
};
saveSnapshot = async (dashboard: DashboardModel, external?: boolean) => {
const { snapshotExpires } = this.state;
const dash = this.dashboard.getSaveModelClone();
this.scrubDashboard(dash);
const cmdData = {
dashboard: dash,
name: dash.title,
expires: snapshotExpires,
external: external,
};
try {
const results: { deleteUrl: any; url: any } = await getBackendSrv().post(snapshotApiUrl, cmdData);
this.setState({
deleteUrl: results.deleteUrl,
snapshotUrl: results.url,
step: 2,
});
} finally {
this.setState({ isLoading: false });
}
};
scrubDashboard = (dash: DashboardModel) => {
const { panel } = this.props;
const { snapshotName } = this.state;
// change title
dash.title = snapshotName;
// make relative times absolute
dash.time = getTimeSrv().timeRange();
// Remove links
dash.links = [];
// remove panel queries & links
dash.panels.forEach((panel) => {
panel.targets = [];
panel.links = [];
panel.datasource = null;
});
// remove annotation queries
const annotations = dash.annotations.list.filter((annotation) => annotation.enable);
dash.annotations.list = annotations.map((annotation: any) => {
return {
name: annotation.name,
enable: annotation.enable,
iconColor: annotation.iconColor,
snapshotData: annotation.snapshotData,
type: annotation.type,
builtIn: annotation.builtIn,
hide: annotation.hide,
};
});
// remove template queries
dash.getVariables().forEach((variable: any) => {
variable.query = '';
variable.options = variable.current ? [variable.current] : [];
variable.refresh = VariableRefresh.never;
});
// snapshot single panel
if (panel) {
const singlePanel = panel.getSaveModel();
singlePanel.gridPos.w = 24;
singlePanel.gridPos.x = 0;
singlePanel.gridPos.y = 0;
singlePanel.gridPos.h = 20;
dash.panels = [singlePanel];
}
// cleanup snapshotData
delete this.dashboard.snapshot;
this.dashboard.forEachPanel((panel: PanelModel) => {
delete panel.snapshotData;
});
this.dashboard.annotations.list.forEach((annotation) => {
delete annotation.snapshotData;
});
};
deleteSnapshot = async () => {
const { deleteUrl } = this.state;
await getBackendSrv().get(deleteUrl);
this.setState({ step: 3 });
};
getSnapshotUrl = () => {
return this.state.snapshotUrl;
};
onSnapshotNameChange = (event: React.ChangeEvent<HTMLInputElement>) => {
this.setState({ snapshotName: event.target.value });
};
onTimeoutChange = (event: React.ChangeEvent<HTMLInputElement>) => {
this.setState({ timeoutSeconds: Number(event.target.value) });
};
onExpireChange = (option: SelectableValue<number>) => {
this.setState({
selectedExpireOption: option,
snapshotExpires: option.value,
});
};
onSnapshotUrlCopy = () => {
appEvents.emit(AppEvents.alertSuccess, ['Content copied to clipboard']);
};
renderStep1() {
const { onDismiss } = this.props;
const {
snapshotName,
selectedExpireOption,
timeoutSeconds,
isLoading,
sharingButtonText,
externalEnabled,
} = this.state;
return (
<>
<div>
<p className="share-modal-info-text">
A snapshot is an instant way to share an interactive dashboard publicly. When created, we strip sensitive
data like queries (metric, template, and annotation) and panel links, leaving only the visible metric data
and series names embedded in your dashboard.
</p>
<p className="share-modal-info-text">
Keep in mind, your snapshot <em>can be viewed by anyone</em> that has the link and can access the URL. Share
wisely.
</p>
</div>
<Field label="Snapshot name">
<Input width={30} value={snapshotName} onChange={this.onSnapshotNameChange} />
</Field>
<Field label="Expire">
<Select
menuShouldPortal
width={30}
options={expireOptions}
value={selectedExpireOption}
onChange={this.onExpireChange}
/>
</Field>
<Field
label="Timeout (seconds)"
description="You might need to configure the timeout value if it takes a long time to collect your dashboard
metrics."
>
<Input type="number" width={21} value={timeoutSeconds} onChange={this.onTimeoutChange} />
</Field>
<Modal.ButtonRow>
<Button variant="secondary" onClick={onDismiss} fill="outline">
Cancel
</Button>
{externalEnabled && (
<Button variant="secondary" disabled={isLoading} onClick={this.createSnapshot(true)}>
{sharingButtonText}
</Button>
)}
<Button variant="primary" disabled={isLoading} onClick={this.createSnapshot()}>
Local Snapshot
</Button>
</Modal.ButtonRow>
</>
);
}
renderStep2() {
const { snapshotUrl } = this.state;
return (
<>
<div className="gf-form" style={{ marginTop: '40px' }}>
<div className="gf-form-row">
<a href={snapshotUrl} className="large share-modal-link" target="_blank" rel="noreferrer">
<Icon name="external-link-alt" /> {snapshotUrl}
</a>
<br />
<ClipboardButton variant="secondary" getText={this.getSnapshotUrl} onClipboardCopy={this.onSnapshotUrlCopy}>
Copy Link
</ClipboardButton>
</div>
</div>
<div className="pull-right" style={{ padding: '5px' }}>
Did you make a mistake?{' '}
<LinkButton fill="text" target="_blank" onClick={this.deleteSnapshot}>
Delete snapshot.
</LinkButton>
</div>
</>
);
}
renderStep3() {
return (
<div className="share-modal-header">
<p className="share-modal-info-text">
The snapshot has been deleted. If you have already accessed it once, then it might take up to an hour before
before it is removed from browser caches or CDN caches.
</p>
</div>
);
}
render() {
const { isLoading, step } = this.state;
return (
<>
{step === 1 && this.renderStep1()}
{step === 2 && this.renderStep2()}
{step === 3 && this.renderStep3()}
{isLoading && <Spinner inline={true} />}
</>
);
}
}
| public/app/features/dashboard/components/ShareModal/ShareSnapshot.tsx | 1 | https://github.com/grafana/grafana/commit/3c52df960ad8a45191ee0141a8c169a0cc4f79a5 | [
0.9929526448249817,
0.03187600150704384,
0.0001640663540456444,
0.00017354634474031627,
0.17263998091220856
] |
{
"id": 4,
"code_window": [
" </Field>\n",
" <Field label=\"Expire\">\n",
" <Select\n",
" menuShouldPortal\n",
" width={30}\n",
" options={expireOptions}\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" inputId=\"expire-select-input\"\n"
],
"file_path": "public/app/features/dashboard/components/ShareModal/ShareSnapshot.tsx",
"type": "add",
"edit_start_line_idx": 229
} | package schemaloader
import (
"encoding/json"
"fmt"
"github.com/grafana/grafana"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/schema"
"github.com/grafana/grafana/pkg/schema/load"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/setting"
)
const ServiceName = "SchemaLoader"
var baseLoadPath load.BaseLoadPaths = load.BaseLoadPaths{
BaseCueFS: grafana.CoreSchema,
DistPluginCueFS: grafana.PluginSchema,
}
type RenderUser struct {
OrgID int64
UserID int64
OrgRole string
}
func ProvideService(cfg *setting.Cfg) (*SchemaLoaderService, error) {
dashFam, err := load.BaseDashboardFamily(baseLoadPath)
if err != nil {
return nil, fmt.Errorf("failed to load dashboard cue schema from path %q: %w", baseLoadPath, err)
}
s := &SchemaLoaderService{
Cfg: cfg,
DashFamily: dashFam,
log: log.New("schemaloader"),
}
return s, nil
}
type SchemaLoaderService struct {
log log.Logger
DashFamily schema.VersionedCueSchema
Cfg *setting.Cfg
}
func (rs *SchemaLoaderService) IsDisabled() bool {
if rs.Cfg == nil {
return true
}
return !rs.Cfg.IsTrimDefaultsEnabled()
}
func (rs *SchemaLoaderService) DashboardApplyDefaults(input *simplejson.Json) (*simplejson.Json, error) {
val, _ := input.Map()
val = removeNils(val)
data, _ := json.Marshal(val)
dsSchema := schema.Find(rs.DashFamily, schema.Latest())
result, err := schema.ApplyDefaults(schema.Resource{Value: data}, dsSchema.CUE())
if err != nil {
return input, err
}
output, err := simplejson.NewJson([]byte(result.Value.(string)))
if err != nil {
return input, err
}
return output, nil
}
func (rs *SchemaLoaderService) DashboardTrimDefaults(input simplejson.Json) (simplejson.Json, error) {
val, _ := input.Map()
val = removeNils(val)
data, _ := json.Marshal(val)
dsSchema, err := schema.SearchAndValidate(rs.DashFamily, string(data))
if err != nil {
return input, err
}
result, err := schema.TrimDefaults(schema.Resource{Value: data}, dsSchema.CUE())
if err != nil {
return input, err
}
output, err := simplejson.NewJson([]byte(result.Value.(string)))
if err != nil {
return input, err
}
return *output, nil
}
func removeNils(initialMap map[string]interface{}) map[string]interface{} {
withoutNils := map[string]interface{}{}
for key, value := range initialMap {
_, ok := value.(map[string]interface{})
if ok {
value = removeNils(value.(map[string]interface{}))
withoutNils[key] = value
continue
}
_, ok = value.([]interface{})
if ok {
value = removeNilArray(value.([]interface{}))
withoutNils[key] = value
continue
}
if value != nil {
if val, ok := value.(string); ok {
if val == "" {
continue
}
}
withoutNils[key] = value
}
}
return withoutNils
}
func removeNilArray(initialArray []interface{}) []interface{} {
withoutNils := []interface{}{}
for _, value := range initialArray {
_, ok := value.(map[string]interface{})
if ok {
value = removeNils(value.(map[string]interface{}))
withoutNils = append(withoutNils, value)
continue
}
_, ok = value.([]interface{})
if ok {
value = removeNilArray(value.([]interface{}))
withoutNils = append(withoutNils, value)
continue
}
if value != nil {
if val, ok := value.(string); ok {
if val == "" {
continue
}
}
withoutNils = append(withoutNils, value)
}
}
return withoutNils
}
| pkg/services/schemaloader/schemaloader.go | 0 | https://github.com/grafana/grafana/commit/3c52df960ad8a45191ee0141a8c169a0cc4f79a5 | [
0.00018114513659384102,
0.00017308797396253794,
0.00016597895591985434,
0.0001722137094475329,
0.0000036691371860797517
] |
{
"id": 4,
"code_window": [
" </Field>\n",
" <Field label=\"Expire\">\n",
" <Select\n",
" menuShouldPortal\n",
" width={30}\n",
" options={expireOptions}\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" inputId=\"expire-select-input\"\n"
],
"file_path": "public/app/features/dashboard/components/ShareModal/ShareSnapshot.tsx",
"type": "add",
"edit_start_line_idx": 229
} | package elasticsearch
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/Masterminds/semver"
"github.com/grafana/grafana-plugin-sdk-go/backend"
"github.com/grafana/grafana-plugin-sdk-go/backend/datasource"
"github.com/grafana/grafana-plugin-sdk-go/backend/instancemgmt"
"github.com/grafana/grafana/pkg/infra/httpclient"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/plugins/backendplugin"
"github.com/grafana/grafana/pkg/plugins/backendplugin/coreplugin"
es "github.com/grafana/grafana/pkg/tsdb/elasticsearch/client"
"github.com/grafana/grafana/pkg/tsdb/intervalv2"
)
var eslog = log.New("tsdb.elasticsearch")
type Service struct {
HTTPClientProvider httpclient.Provider
intervalCalculator intervalv2.Calculator
im instancemgmt.InstanceManager
}
func ProvideService(httpClientProvider httpclient.Provider, backendPluginManager backendplugin.Manager) (*Service, error) {
eslog.Debug("initializing")
im := datasource.NewInstanceManager(newInstanceSettings())
s := newService(im, httpClientProvider)
factory := coreplugin.New(backend.ServeOpts{
QueryDataHandler: newService(im, s.HTTPClientProvider),
})
if err := backendPluginManager.Register("elasticsearch", factory); err != nil {
eslog.Error("Failed to register plugin", "error", err)
return nil, err
}
return s, nil
}
// newService creates a new executor func.
func newService(im instancemgmt.InstanceManager, httpClientProvider httpclient.Provider) *Service {
return &Service{
im: im,
HTTPClientProvider: httpClientProvider,
intervalCalculator: intervalv2.NewCalculator(),
}
}
func (s *Service) QueryData(ctx context.Context, req *backend.QueryDataRequest) (*backend.QueryDataResponse, error) {
if len(req.Queries) == 0 {
return &backend.QueryDataResponse{}, fmt.Errorf("query contains no queries")
}
dsInfo, err := s.getDSInfo(req.PluginContext)
if err != nil {
return &backend.QueryDataResponse{}, err
}
client, err := es.NewClient(ctx, s.HTTPClientProvider, dsInfo, req.Queries[0].TimeRange)
if err != nil {
return &backend.QueryDataResponse{}, err
}
query := newTimeSeriesQuery(client, req.Queries, s.intervalCalculator)
return query.execute()
}
func newInstanceSettings() datasource.InstanceFactoryFunc {
return func(settings backend.DataSourceInstanceSettings) (instancemgmt.Instance, error) {
jsonData := map[string]interface{}{}
err := json.Unmarshal(settings.JSONData, &jsonData)
if err != nil {
return nil, fmt.Errorf("error reading settings: %w", err)
}
httpCliOpts, err := settings.HTTPClientOptions()
if err != nil {
return nil, fmt.Errorf("error getting http options: %w", err)
}
// Set SigV4 service namespace
if httpCliOpts.SigV4 != nil {
httpCliOpts.SigV4.Service = "es"
}
version, err := coerceVersion(jsonData["esVersion"])
if err != nil {
return nil, fmt.Errorf("elasticsearch version is required, err=%v", err)
}
timeField, ok := jsonData["timeField"].(string)
if !ok {
return nil, errors.New("timeField cannot be cast to string")
}
if timeField == "" {
return nil, errors.New("elasticsearch time field name is required")
}
interval, ok := jsonData["interval"].(string)
if !ok {
interval = ""
}
timeInterval, ok := jsonData["timeInterval"].(string)
if !ok {
timeInterval = ""
}
maxConcurrentShardRequests, ok := jsonData["maxConcurrentShardRequests"].(float64)
if !ok {
maxConcurrentShardRequests = 256
}
includeFrozen, ok := jsonData["includeFrozen"].(bool)
if !ok {
includeFrozen = false
}
xpack, ok := jsonData["xpack"].(bool)
if !ok {
xpack = false
}
model := es.DatasourceInfo{
ID: settings.ID,
URL: settings.URL,
HTTPClientOpts: httpCliOpts,
Database: settings.Database,
MaxConcurrentShardRequests: int64(maxConcurrentShardRequests),
ESVersion: version,
TimeField: timeField,
Interval: interval,
TimeInterval: timeInterval,
IncludeFrozen: includeFrozen,
XPack: xpack,
}
return model, nil
}
}
func (s *Service) getDSInfo(pluginCtx backend.PluginContext) (*es.DatasourceInfo, error) {
i, err := s.im.Get(pluginCtx)
if err != nil {
return nil, err
}
instance := i.(es.DatasourceInfo)
return &instance, nil
}
func coerceVersion(v interface{}) (*semver.Version, error) {
versionString, ok := v.(string)
if ok {
return semver.NewVersion(versionString)
}
versionNumber, ok := v.(float64)
if !ok {
return nil, fmt.Errorf("elasticsearch version %v, cannot be cast to int", v)
}
// Legacy version numbers (before Grafana 8)
// valid values were 2,5,56,60,70
switch int64(versionNumber) {
case 2:
return semver.NewVersion("2.0.0")
case 5:
return semver.NewVersion("5.0.0")
case 56:
return semver.NewVersion("5.6.0")
case 60:
return semver.NewVersion("6.0.0")
case 70:
return semver.NewVersion("7.0.0")
default:
return nil, fmt.Errorf("elasticsearch version=%d is not supported", int64(versionNumber))
}
}
| pkg/tsdb/elasticsearch/elasticsearch.go | 0 | https://github.com/grafana/grafana/commit/3c52df960ad8a45191ee0141a8c169a0cc4f79a5 | [
0.0001763555919751525,
0.00017039492377080023,
0.00016370444791391492,
0.0001696870313026011,
0.0000035043717616645154
] |
{
"id": 4,
"code_window": [
" </Field>\n",
" <Field label=\"Expire\">\n",
" <Select\n",
" menuShouldPortal\n",
" width={30}\n",
" options={expireOptions}\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" inputId=\"expire-select-input\"\n"
],
"file_path": "public/app/features/dashboard/components/ShareModal/ShareSnapshot.tsx",
"type": "add",
"edit_start_line_idx": 229
} | [
{
"key": "AK",
"latitude": 61.385,
"longitude": -152.2683,
"name": "Alaska"
},
{
"key": "AL",
"latitude": 32.799,
"longitude": -86.8073,
"name": "Alabama"
},
{
"key": "AR",
"latitude": 34.9513,
"longitude": -92.3809,
"name": "Arkansas"
},
{
"key": "AS",
"latitude": 14.2417,
"longitude": -170.7197,
"name": "American Samoa"
},
{
"key": "AZ",
"latitude": 33.7712,
"longitude": -111.3877,
"name": "Arizona"
},
{
"key": "CA",
"latitude": 36.17,
"longitude": -119.7462,
"name": "California"
},
{
"key": "CO",
"latitude": 39.0646,
"longitude": -105.3272,
"name": "Colorado"
},
{
"key": "CT",
"latitude": 41.5834,
"longitude": -72.7622,
"name": "Connecticut"
},
{
"key": "DC",
"latitude": 38.8964,
"longitude": -77.0262,
"name": "Washington DC"
},
{
"key": "DE",
"latitude": 39.3498,
"longitude": -75.5148,
"name": "Delaware"
},
{
"key": "FL",
"latitude": 27.8333,
"longitude": -81.717,
"name": "Florida"
},
{
"key": "GA",
"latitude": 32.9866,
"longitude": -83.6487,
"name": "Georgia"
},
{
"key": "HI",
"latitude": 21.1098,
"longitude": -157.5311,
"name": "Hawaii"
},
{
"key": "IA",
"latitude": 42.0046,
"longitude": -93.214,
"name": "Iowa"
},
{
"key": "ID",
"latitude": 44.2394,
"longitude": -114.5103,
"name": "Idaho"
},
{
"key": "IL",
"latitude": 40.3363,
"longitude": -89.0022,
"name": "Illinois"
},
{
"key": "IN",
"latitude": 39.8647,
"longitude": -86.2604,
"name": "Indiana"
},
{
"key": "KS",
"latitude": 38.5111,
"longitude": -96.8005,
"name": "Kansas"
},
{
"key": "KY",
"latitude": 37.669,
"longitude": -84.6514,
"name": "Kentucky"
},
{
"key": "LA",
"latitude": 31.1801,
"longitude": -91.8749,
"name": "Louisiana"
},
{
"key": "MA",
"latitude": 42.2373,
"longitude": -71.5314,
"name": "Massachusetts"
},
{
"key": "MD",
"latitude": 39.0724,
"longitude": -76.7902,
"name": "Maryland"
},
{
"key": "ME",
"latitude": 44.6074,
"longitude": -69.3977,
"name": "Maine"
},
{
"key": "MI",
"latitude": 43.3504,
"longitude": -84.5603,
"name": "Michigan"
},
{
"key": "MN",
"latitude": 45.7326,
"longitude": -93.9196,
"name": "Minnesota"
},
{
"key": "MO",
"latitude": 38.4623,
"longitude": -92.302,
"name": "Missouri"
},
{
"key": "MP",
"latitude": 14.8058,
"longitude": 145.5505,
"name": "Northern Mariana Islands"
},
{
"key": "MS",
"latitude": 32.7673,
"longitude": -89.6812,
"name": "Mississippi"
},
{
"key": "MT",
"latitude": 46.9048,
"longitude": -110.3261,
"name": "Montana"
},
{
"key": "NC",
"latitude": 35.6411,
"longitude": -79.8431,
"name": "North Carolina"
},
{
"key": "ND",
"latitude": 47.5362,
"longitude": -99.793,
"name": "North Dakota"
},
{
"key": "NE",
"latitude": 41.1289,
"longitude": -98.2883,
"name": "Nebraska"
},
{
"key": "NH",
"latitude": 43.4108,
"longitude": -71.5653,
"name": "New Hampshire"
},
{
"key": "NJ",
"latitude": 40.314,
"longitude": -74.5089,
"name": "New Jersey"
},
{
"key": "NM",
"latitude": 34.8375,
"longitude": -106.2371,
"name": "New Mexico"
},
{
"key": "NV",
"latitude": 38.4199,
"longitude": -117.1219,
"name": "Nevada"
},
{
"key": "NY",
"latitude": 42.1497,
"longitude": -74.9384,
"name": "New York"
},
{
"key": "OH",
"latitude": 40.3736,
"longitude": -82.7755,
"name": "Ohio"
},
{
"key": "OK",
"latitude": 35.5376,
"longitude": -96.9247,
"name": "Oklahoma"
},
{
"key": "OR",
"latitude": 44.5672,
"longitude": -122.1269,
"name": "Oregon"
},
{
"key": "PA",
"latitude": 40.5773,
"longitude": -77.264,
"name": "Pennsylvania"
},
{
"key": "PR",
"latitude": 18.2766,
"longitude": -66.335,
"name": "Puerto Rico"
},
{
"key": "RI",
"latitude": 41.6772,
"longitude": -71.5101,
"name": "Rhode Island"
},
{
"key": "SC",
"latitude": 33.8191,
"longitude": -80.9066,
"name": "South Carolina"
},
{
"key": "SD",
"latitude": 44.2853,
"longitude": -99.4632,
"name": "South Dakota"
},
{
"key": "TN",
"latitude": 35.7449,
"longitude": -86.7489,
"name": "Tennessee"
},
{
"key": "TX",
"latitude": 31.106,
"longitude": -97.6475,
"name": "Texas"
},
{
"key": "UT",
"latitude": 40.1135,
"longitude": -111.8535,
"name": "Utah"
},
{
"key": "VA",
"latitude": 37.768,
"longitude": -78.2057,
"name": "Virginia"
},
{
"key": "VI",
"latitude": 18.0001,
"longitude": -64.8199,
"name": "U.S. Virgin Islands"
},
{
"key": "VT",
"latitude": 44.0407,
"longitude": -72.7093,
"name": "Vermont"
},
{
"key": "WA",
"latitude": 47.3917,
"longitude": -121.5708,
"name": "Washington"
},
{
"key": "WI",
"latitude": 44.2563,
"longitude": -89.6385,
"name": "Wisconsin"
},
{
"key": "WV",
"latitude": 38.468,
"longitude": -80.9696,
"name": "West Virginia"
},
{
"key": "WY",
"latitude": 42.7475,
"longitude": -107.2085,
"name": "Wyoming"
}
]
| public/gazetteer/usa-states.json | 0 | https://github.com/grafana/grafana/commit/3c52df960ad8a45191ee0141a8c169a0cc4f79a5 | [
0.00017542445857543498,
0.00017330539412796497,
0.00017185101751238108,
0.00017331411072518677,
8.559127877560968e-7
] |
{
"id": 5,
"code_window": [
" label=\"Timeout (seconds)\"\n",
" description=\"You might need to configure the timeout value if it takes a long time to collect your dashboard\n",
" metrics.\"\n",
" >\n",
" <Input type=\"number\" width={21} value={timeoutSeconds} onChange={this.onTimeoutChange} />\n",
" </Field>\n",
"\n",
" <Modal.ButtonRow>\n",
" <Button variant=\"secondary\" onClick={onDismiss} fill=\"outline\">\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <Input id=\"timeout-input\" type=\"number\" width={21} value={timeoutSeconds} onChange={this.onTimeoutChange} />\n"
],
"file_path": "public/app/features/dashboard/components/ShareModal/ShareSnapshot.tsx",
"type": "replace",
"edit_start_line_idx": 241
} | import React, { useMemo, useState } from 'react';
import { connect, MapDispatchToProps } from 'react-redux';
import { css, cx, keyframes } from '@emotion/css';
import { chain, cloneDeep, defaults, find, sortBy } from 'lodash';
import tinycolor from 'tinycolor2';
import { locationService, reportInteraction } from '@grafana/runtime';
import { Icon, IconButton, styleMixins, useStyles2 } from '@grafana/ui';
import { selectors } from '@grafana/e2e-selectors';
import { GrafanaTheme2 } from '@grafana/data';
import config from 'app/core/config';
import store from 'app/core/store';
import { addPanel } from 'app/features/dashboard/state/reducers';
import { DashboardModel, PanelModel } from '../../state';
import { LS_PANEL_COPY_KEY } from 'app/core/constants';
import { LibraryElementDTO } from '../../../library-panels/types';
import { toPanelModelLibraryPanel } from '../../../library-panels/utils';
import {
LibraryPanelsSearch,
LibraryPanelsSearchVariant,
} from '../../../library-panels/components/LibraryPanelsSearch/LibraryPanelsSearch';
export type PanelPluginInfo = { id: any; defaults: { gridPos: { w: any; h: any }; title: any } };
export interface OwnProps {
panel: PanelModel;
dashboard: DashboardModel;
}
export interface DispatchProps {
addPanel: typeof addPanel;
}
export type Props = OwnProps & DispatchProps;
const getCopiedPanelPlugins = () => {
const panels = chain(config.panels)
.filter({ hideFromList: false })
.map((item) => item)
.value();
const copiedPanels = [];
const copiedPanelJson = store.get(LS_PANEL_COPY_KEY);
if (copiedPanelJson) {
const copiedPanel = JSON.parse(copiedPanelJson);
const pluginInfo: any = find(panels, { id: copiedPanel.type });
if (pluginInfo) {
const pluginCopy = cloneDeep(pluginInfo);
pluginCopy.name = copiedPanel.title;
pluginCopy.sort = -1;
pluginCopy.defaults = copiedPanel;
copiedPanels.push(pluginCopy);
}
}
return sortBy(copiedPanels, 'sort');
};
export const AddPanelWidgetUnconnected: React.FC<Props> = ({ panel, dashboard }) => {
const [addPanelView, setAddPanelView] = useState(false);
const onCancelAddPanel = (evt: React.MouseEvent<HTMLButtonElement>) => {
evt.preventDefault();
dashboard.removePanel(panel);
};
const onBack = () => {
setAddPanelView(false);
};
const onCreateNewPanel = () => {
const { gridPos } = panel;
const newPanel: Partial<PanelModel> = {
type: 'timeseries',
title: 'Panel Title',
gridPos: { x: gridPos.x, y: gridPos.y, w: gridPos.w, h: gridPos.h },
};
dashboard.addPanel(newPanel);
dashboard.removePanel(panel);
locationService.partial({ editPanel: newPanel.id });
};
const onPasteCopiedPanel = (panelPluginInfo: PanelPluginInfo) => {
const { gridPos } = panel;
const newPanel: any = {
type: panelPluginInfo.id,
title: 'Panel Title',
gridPos: {
x: gridPos.x,
y: gridPos.y,
w: panelPluginInfo.defaults.gridPos.w,
h: panelPluginInfo.defaults.gridPos.h,
},
};
// apply panel template / defaults
if (panelPluginInfo.defaults) {
defaults(newPanel, panelPluginInfo.defaults);
newPanel.title = panelPluginInfo.defaults.title;
store.delete(LS_PANEL_COPY_KEY);
}
dashboard.addPanel(newPanel);
dashboard.removePanel(panel);
};
const onAddLibraryPanel = (panelInfo: LibraryElementDTO) => {
const { gridPos } = panel;
const newPanel: PanelModel = {
...panelInfo.model,
gridPos,
libraryPanel: toPanelModelLibraryPanel(panelInfo),
};
dashboard.addPanel(newPanel);
dashboard.removePanel(panel);
};
const onCreateNewRow = () => {
const newRow: any = {
type: 'row',
title: 'Row title',
gridPos: { x: 0, y: 0 },
};
dashboard.addPanel(newRow);
dashboard.removePanel(panel);
};
const styles = useStyles2(getStyles);
const copiedPanelPlugins = useMemo(() => getCopiedPanelPlugins(), []);
return (
<div className={styles.wrapper}>
<div className={cx('panel-container', styles.callToAction)}>
<AddPanelWidgetHandle onCancel={onCancelAddPanel} onBack={addPanelView ? onBack : undefined} styles={styles}>
{addPanelView ? 'Add panel from panel library' : 'Add panel'}
</AddPanelWidgetHandle>
{addPanelView ? (
<LibraryPanelsSearch onClick={onAddLibraryPanel} variant={LibraryPanelsSearchVariant.Tight} showPanelFilter />
) : (
<div className={styles.actionsWrapper}>
<div className={cx(styles.actionsRow, styles.columnGap)}>
<div
onClick={() => {
reportInteraction('Create new panel');
onCreateNewPanel();
}}
aria-label={selectors.pages.AddDashboard.addNewPanel}
>
<Icon name="file-blank" size="xl" />
Add an empty panel
</div>
<div
className={styles.rowGap}
onClick={() => {
reportInteraction('Create new row');
onCreateNewRow();
}}
aria-label={selectors.pages.AddDashboard.addNewRow}
>
<Icon name="wrap-text" size="xl" />
Add a new row
</div>
</div>
<div className={styles.actionsRow}>
<div
onClick={() => {
reportInteraction('Add a panel from the panel library');
setAddPanelView(true);
}}
aria-label={selectors.pages.AddDashboard.addNewPanelLibrary}
>
<Icon name="book-open" size="xl" />
Add a panel from the panel library
</div>
{copiedPanelPlugins.length === 1 && (
<div
className={styles.rowGap}
onClick={() => {
reportInteraction('Paste panel from clipboard');
onPasteCopiedPanel(copiedPanelPlugins[0]);
}}
>
<Icon name="clipboard-alt" size="xl" />
Paste panel from clipboard
</div>
)}
</div>
</div>
)}
</div>
</div>
);
};
const mapDispatchToProps: MapDispatchToProps<DispatchProps, OwnProps> = { addPanel };
export const AddPanelWidget = connect(undefined, mapDispatchToProps)(AddPanelWidgetUnconnected);
interface AddPanelWidgetHandleProps {
onCancel: (e: React.MouseEvent<HTMLButtonElement>) => void;
onBack?: () => void;
children?: string;
styles: AddPanelStyles;
}
const AddPanelWidgetHandle: React.FC<AddPanelWidgetHandleProps> = ({ children, onBack, onCancel, styles }) => {
return (
<div className={cx(styles.headerRow, 'grid-drag-handle')}>
{onBack && (
<div className={styles.backButton}>
<IconButton name="arrow-left" onClick={onBack} surface="header" size="xl" />
</div>
)}
{!onBack && (
<div className={styles.backButton}>
<Icon name="panel-add" size="md" />
</div>
)}
{children && <span>{children}</span>}
<div className="flex-grow-1" />
<IconButton aria-label="Close 'Add Panel' widget" name="times" onClick={onCancel} surface="header" />
</div>
);
};
const getStyles = (theme: GrafanaTheme2) => {
const pulsate = keyframes`
0% {box-shadow: 0 0 0 2px ${theme.colors.background.canvas}, 0 0 0px 4px ${theme.colors.primary.main};}
50% {box-shadow: 0 0 0 2px ${theme.components.dashboard.background}, 0 0 0px 4px ${tinycolor(
theme.colors.primary.main
)
.darken(20)
.toHexString()};}
100% {box-shadow: 0 0 0 2px ${theme.components.dashboard.background}, 0 0 0px 4px ${theme.colors.primary.main};}
`;
return {
// wrapper is used to make sure box-shadow animation isn't cut off in dashboard page
wrapper: css`
height: 100%;
padding-top: ${theme.spacing(0.5)};
`,
callToAction: css`
overflow: hidden;
outline: 2px dotted transparent;
outline-offset: 2px;
box-shadow: 0 0 0 2px black, 0 0 0px 4px #1f60c4;
animation: ${pulsate} 2s ease infinite;
`,
rowGap: css`
margin-left: ${theme.spacing(1)};
`,
columnGap: css`
margin-bottom: ${theme.spacing(1)};
`,
actionsRow: css`
display: flex;
flex-direction: row;
height: 100%;
> div {
justify-self: center;
cursor: pointer;
background: ${theme.colors.background.secondary};
border-radius: ${theme.shape.borderRadius(1)};
color: ${theme.colors.text.primary};
width: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
text-align: center;
&:hover {
background: ${styleMixins.hoverColor(theme.colors.background.secondary, theme)};
}
&:hover > #book-icon {
background: linear-gradient(#f05a28 30%, #fbca0a 99%);
}
}
`,
actionsWrapper: css`
display: flex;
flex-direction: column;
padding: ${theme.spacing(0, 1, 1, 1)};
height: 100%;
`,
headerRow: css`
display: flex;
align-items: center;
height: 38px;
flex-shrink: 0;
width: 100%;
font-size: ${theme.typography.fontSize};
font-weight: ${theme.typography.fontWeightMedium};
padding-left: ${theme.spacing(1)};
transition: background-color 0.1s ease-in-out;
cursor: move;
&:hover {
background: ${theme.colors.background.secondary};
}
`,
backButton: css`
display: flex;
align-items: center;
cursor: pointer;
padding-left: ${theme.spacing(0.5)};
width: ${theme.spacing(4)};
`,
noMargin: css`
margin: 0;
`,
};
};
type AddPanelStyles = ReturnType<typeof getStyles>;
| public/app/features/dashboard/components/AddPanelWidget/AddPanelWidget.tsx | 1 | https://github.com/grafana/grafana/commit/3c52df960ad8a45191ee0141a8c169a0cc4f79a5 | [
0.0018710329895839095,
0.0002677437732927501,
0.00016198339289985597,
0.00017290969844907522,
0.00030047111795283854
] |
{
"id": 5,
"code_window": [
" label=\"Timeout (seconds)\"\n",
" description=\"You might need to configure the timeout value if it takes a long time to collect your dashboard\n",
" metrics.\"\n",
" >\n",
" <Input type=\"number\" width={21} value={timeoutSeconds} onChange={this.onTimeoutChange} />\n",
" </Field>\n",
"\n",
" <Modal.ButtonRow>\n",
" <Button variant=\"secondary\" onClick={onDismiss} fill=\"outline\">\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <Input id=\"timeout-input\" type=\"number\" width={21} value={timeoutSeconds} onChange={this.onTimeoutChange} />\n"
],
"file_path": "public/app/features/dashboard/components/ShareModal/ShareSnapshot.tsx",
"type": "replace",
"edit_start_line_idx": 241
} | #!/usr/bin/env bash
RELEASE_TYPE="${1:-}"
GCP_DB_BUCKET="${2:-grafana-aptly-db}"
GCP_REPO_BUCKET="${3:-grafana-repo}"
if [ -z "$RELEASE_TYPE" ]; then
echo "RELEASE_TYPE (arg 1) has to be set"
exit 1
fi
if [[ "$RELEASE_TYPE" != "oss" && "$RELEASE_TYPE" != "enterprise" ]]; then
echo "RELEASE_TYPE (arg 1) must be either oss or enterprise."
exit 1
fi
set -e
# Update the repo and db on gcp
gsutil -m rsync -r -d /deb-repo/db "gs://$GCP_DB_BUCKET/$RELEASE_TYPE"
# Uploads the binaries before the metadata (to prevent 404's for debs)
gsutil -m rsync -r /deb-repo/repo/grafana/pool "gs://$GCP_REPO_BUCKET/$RELEASE_TYPE/deb/pool"
gsutil -m rsync -r -d /deb-repo/repo/grafana "gs://$GCP_REPO_BUCKET/$RELEASE_TYPE/deb"
# usage:
#
# deb https://packages.grafana.com/oss/deb stable main
| scripts/build/update_repo/publish-deb.sh | 0 | https://github.com/grafana/grafana/commit/3c52df960ad8a45191ee0141a8c169a0cc4f79a5 | [
0.0001722283341223374,
0.00017058955563697964,
0.00016948716074693948,
0.0001703213492874056,
0.0000011051660067096236
] |
{
"id": 5,
"code_window": [
" label=\"Timeout (seconds)\"\n",
" description=\"You might need to configure the timeout value if it takes a long time to collect your dashboard\n",
" metrics.\"\n",
" >\n",
" <Input type=\"number\" width={21} value={timeoutSeconds} onChange={this.onTimeoutChange} />\n",
" </Field>\n",
"\n",
" <Modal.ButtonRow>\n",
" <Button variant=\"secondary\" onClick={onDismiss} fill=\"outline\">\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <Input id=\"timeout-input\" type=\"number\" width={21} value={timeoutSeconds} onChange={this.onTimeoutChange} />\n"
],
"file_path": "public/app/features/dashboard/components/ShareModal/ShareSnapshot.tsx",
"type": "replace",
"edit_start_line_idx": 241
} | ##################### Grafana Configuration Example #####################
#
# Everything has defaults so you only need to uncomment things you want to
# change
# possible values : production, development
;app_mode = production
# instance name, defaults to HOSTNAME environment variable value or hostname if HOSTNAME var is empty
;instance_name = ${HOSTNAME}
#################################### Paths ####################################
[paths]
# Path to where grafana can store temp files, sessions, and the sqlite3 db (if that is used)
;data = /var/lib/grafana
# Temporary files in `data` directory older than given duration will be removed
;temp_data_lifetime = 24h
# Directory where grafana can store logs
;logs = /var/log/grafana
# Directory where grafana will automatically scan and look for plugins
;plugins = /var/lib/grafana/plugins
# folder that contains provisioning config files that grafana will apply on startup and while running.
;provisioning = conf/provisioning
#################################### Server ####################################
[server]
# Protocol (http, https, h2, socket)
;protocol = http
# The ip address to bind to, empty will bind to all interfaces
;http_addr =
# The http port to use
;http_port = 3000
# The public facing domain name used to access grafana from a browser
;domain = localhost
# Redirect to correct domain if host header does not match domain
# Prevents DNS rebinding attacks
;enforce_domain = false
# The full public facing url you use in browser, used for redirects and emails
# If you use reverse proxy and sub path specify full url (with sub path)
;root_url = %(protocol)s://%(domain)s:%(http_port)s/
# Serve Grafana from subpath specified in `root_url` setting. By default it is set to `false` for compatibility reasons.
;serve_from_sub_path = false
# Log web requests
;router_logging = false
# the path relative working path
;static_root_path = public
# enable gzip
;enable_gzip = false
# https certs & key file
;cert_file =
;cert_key =
# Unix socket path
;socket =
# CDN Url
;cdn_url =
# Sets the maximum time using a duration format (5s/5m/5ms) before timing out read of an incoming request and closing idle connections.
# `0` means there is no timeout for reading the request.
;read_timeout = 0
#################################### Database ####################################
[database]
# You can configure the database connection by specifying type, host, name, user and password
# as separate properties or as on string using the url properties.
# Either "mysql", "postgres" or "sqlite3", it's your choice
;type = sqlite3
;host = 127.0.0.1:3306
;name = grafana
;user = root
# If the password contains # or ; you have to wrap it with triple quotes. Ex """#password;"""
;password =
# Use either URL or the previous fields to configure the database
# Example: mysql://user:secret@host:port/database
;url =
# For "postgres" only, either "disable", "require" or "verify-full"
;ssl_mode = disable
# Database drivers may support different transaction isolation levels.
# Currently, only "mysql" driver supports isolation levels.
# If the value is empty - driver's default isolation level is applied.
# For "mysql" use "READ-UNCOMMITTED", "READ-COMMITTED", "REPEATABLE-READ" or "SERIALIZABLE".
;isolation_level =
;ca_cert_path =
;client_key_path =
;client_cert_path =
;server_cert_name =
# For "sqlite3" only, path relative to data_path setting
;path = grafana.db
# Max idle conn setting default is 2
;max_idle_conn = 2
# Max conn setting default is 0 (mean not set)
;max_open_conn =
# Connection Max Lifetime default is 14400 (means 14400 seconds or 4 hours)
;conn_max_lifetime = 14400
# Set to true to log the sql calls and execution times.
;log_queries =
# For "sqlite3" only. cache mode setting used for connecting to the database. (private, shared)
;cache_mode = private
################################### Data sources #########################
[datasources]
# Upper limit of data sources that Grafana will return. This limit is a temporary configuration and it will be deprecated when pagination will be introduced on the list data sources API.
;datasource_limit = 5000
#################################### Cache server #############################
[remote_cache]
# Either "redis", "memcached" or "database" default is "database"
;type = database
# cache connectionstring options
# database: will use Grafana primary database.
# redis: config like redis server e.g. `addr=127.0.0.1:6379,pool_size=100,db=0,ssl=false`. Only addr is required. ssl may be 'true', 'false', or 'insecure'.
# memcache: 127.0.0.1:11211
;connstr =
#################################### Data proxy ###########################
[dataproxy]
# This enables data proxy logging, default is false
;logging = false
# How long the data proxy waits to read the headers of the response before timing out, default is 30 seconds.
# This setting also applies to core backend HTTP data sources where query requests use an HTTP client with timeout set.
;timeout = 30
# How long the data proxy waits to establish a TCP connection before timing out, default is 10 seconds.
;dialTimeout = 10
# How many seconds the data proxy waits before sending a keepalive probe request.
;keep_alive_seconds = 30
# How many seconds the data proxy waits for a successful TLS Handshake before timing out.
;tls_handshake_timeout_seconds = 10
# How many seconds the data proxy will wait for a server's first response headers after
# fully writing the request headers if the request has an "Expect: 100-continue"
# header. A value of 0 will result in the body being sent immediately, without
# waiting for the server to approve.
;expect_continue_timeout_seconds = 1
# Optionally limits the total number of connections per host, including connections in the dialing,
# active, and idle states. On limit violation, dials will block.
# A value of zero (0) means no limit.
;max_conns_per_host = 0
# The maximum number of idle connections that Grafana will keep alive.
;max_idle_connections = 100
# How many seconds the data proxy keeps an idle connection open before timing out.
;idle_conn_timeout_seconds = 90
# If enabled and user is not anonymous, data proxy will add X-Grafana-User header with username into the request, default is false.
;send_user_header = false
# Limit the amount of bytes that will be read/accepted from responses of outgoing HTTP requests.
;response_limit = 0
# Limits the number of rows that Grafana will process from SQL data sources.
;row_limit = 1000000
#################################### Analytics ####################################
[analytics]
# Server reporting, sends usage counters to stats.grafana.org every 24 hours.
# No ip addresses are being tracked, only simple counters to track
# running instances, dashboard and error counts. It is very helpful to us.
# Change this option to false to disable reporting.
;reporting_enabled = true
# The name of the distributor of the Grafana instance. Ex hosted-grafana, grafana-labs
;reporting_distributor = grafana-labs
# Set to false to disable all checks to https://grafana.net
# for new versions (grafana itself and plugins), check is used
# in some UI views to notify that grafana or plugin update exists
# This option does not cause any auto updates, nor send any information
# only a GET request to http://grafana.com to get latest versions
;check_for_updates = true
# Google Analytics universal tracking code, only enabled if you specify an id here
;google_analytics_ua_id =
# Google Tag Manager ID, only enabled if you specify an id here
;google_tag_manager_id =
#################################### Security ####################################
[security]
# disable creation of admin user on first start of grafana
;disable_initial_admin_creation = false
# default admin user, created on startup
;admin_user = admin
# default admin password, can be changed before first start of grafana, or in profile settings
;admin_password = admin
# used for signing
;secret_key = SW2YcwTIb9zpOOhoPsMm
# disable gravatar profile images
;disable_gravatar = false
# data source proxy whitelist (ip_or_domain:port separated by spaces)
;data_source_proxy_whitelist =
# disable protection against brute force login attempts
;disable_brute_force_login_protection = false
# set to true if you host Grafana behind HTTPS. default is false.
;cookie_secure = false
# set cookie SameSite attribute. defaults to `lax`. can be set to "lax", "strict", "none" and "disabled"
;cookie_samesite = lax
# set to true if you want to allow browsers to render Grafana in a <frame>, <iframe>, <embed> or <object>. default is false.
;allow_embedding = false
# Set to true if you want to enable http strict transport security (HSTS) response header.
# This is only sent when HTTPS is enabled in this configuration.
# HSTS tells browsers that the site should only be accessed using HTTPS.
;strict_transport_security = false
# Sets how long a browser should cache HSTS. Only applied if strict_transport_security is enabled.
;strict_transport_security_max_age_seconds = 86400
# Set to true if to enable HSTS preloading option. Only applied if strict_transport_security is enabled.
;strict_transport_security_preload = false
# Set to true if to enable the HSTS includeSubDomains option. Only applied if strict_transport_security is enabled.
;strict_transport_security_subdomains = false
# Set to true to enable the X-Content-Type-Options response header.
# The X-Content-Type-Options response HTTP header is a marker used by the server to indicate that the MIME types advertised
# in the Content-Type headers should not be changed and be followed.
;x_content_type_options = true
# Set to true to enable the X-XSS-Protection header, which tells browsers to stop pages from loading
# when they detect reflected cross-site scripting (XSS) attacks.
;x_xss_protection = true
# Enable adding the Content-Security-Policy header to your requests.
# CSP allows to control resources the user agent is allowed to load and helps prevent XSS attacks.
;content_security_policy = false
# Set Content Security Policy template used when adding the Content-Security-Policy header to your requests.
# $NONCE in the template includes a random nonce.
# $ROOT_PATH is server.root_url without the protocol.
;content_security_policy_template = """script-src 'self' 'unsafe-eval' 'unsafe-inline' 'strict-dynamic' $NONCE;object-src 'none';font-src 'self';style-src 'self' 'unsafe-inline' blob:;img-src * data:;base-uri 'self';connect-src 'self' grafana.com ws://$ROOT_PATH wss://$ROOT_PATH;manifest-src 'self';media-src 'none';form-action 'self';"""
#################################### Snapshots ###########################
[snapshots]
# snapshot sharing options
;external_enabled = true
;external_snapshot_url = https://snapshots-origin.raintank.io
;external_snapshot_name = Publish to snapshot.raintank.io
# Set to true to enable this Grafana instance act as an external snapshot server and allow unauthenticated requests for
# creating and deleting snapshots.
;public_mode = false
# remove expired snapshot
;snapshot_remove_expired = true
#################################### Dashboards History ##################
[dashboards]
# Number dashboard versions to keep (per dashboard). Default: 20, Minimum: 1
;versions_to_keep = 20
# Minimum dashboard refresh interval. When set, this will restrict users to set the refresh interval of a dashboard lower than given interval. Per default this is 5 seconds.
# The interval string is a possibly signed sequence of decimal numbers, followed by a unit suffix (ms, s, m, h, d), e.g. 30s or 1m.
;min_refresh_interval = 5s
# Path to the default home dashboard. If this value is empty, then Grafana uses StaticRootPath + "dashboards/home.json"
;default_home_dashboard_path =
#################################### Users ###############################
[users]
# disable user signup / registration
;allow_sign_up = true
# Allow non admin users to create organizations
;allow_org_create = true
# Set to true to automatically assign new users to the default organization (id 1)
;auto_assign_org = true
# Set this value to automatically add new users to the provided organization (if auto_assign_org above is set to true)
;auto_assign_org_id = 1
# Default role new users will be automatically assigned (if disabled above is set to true)
;auto_assign_org_role = Viewer
# Require email validation before sign up completes
;verify_email_enabled = false
# Background text for the user field on the login page
;login_hint = email or username
;password_hint = password
# Default UI theme ("dark" or "light")
;default_theme = dark
# Path to a custom home page. Users are only redirected to this if the default home dashboard is used. It should match a frontend route and contain a leading slash.
; home_page =
# External user management, these options affect the organization users view
;external_manage_link_url =
;external_manage_link_name =
;external_manage_info =
# Viewers can edit/inspect dashboard settings in the browser. But not save the dashboard.
;viewers_can_edit = false
# Editors can administrate dashboard, folders and teams they create
;editors_can_admin = false
# The duration in time a user invitation remains valid before expiring. This setting should be expressed as a duration. Examples: 6h (hours), 2d (days), 1w (week). Default is 24h (24 hours). The minimum supported duration is 15m (15 minutes).
;user_invite_max_lifetime_duration = 24h
# Enter a comma-separated list of users login to hide them in the Grafana UI. These users are shown to Grafana admins and themselves.
; hidden_users =
[auth]
# Login cookie name
;login_cookie_name = grafana_session
# The maximum lifetime (duration) an authenticated user can be inactive before being required to login at next visit. Default is 7 days (7d). This setting should be expressed as a duration, e.g. 5m (minutes), 6h (hours), 10d (days), 2w (weeks), 1M (month). The lifetime resets at each successful token rotation.
;login_maximum_inactive_lifetime_duration =
# The maximum lifetime (duration) an authenticated user can be logged in since login time before being required to login. Default is 30 days (30d). This setting should be expressed as a duration, e.g. 5m (minutes), 6h (hours), 10d (days), 2w (weeks), 1M (month).
;login_maximum_lifetime_duration =
# How often should auth tokens be rotated for authenticated users when being active. The default is each 10 minutes.
;token_rotation_interval_minutes = 10
# Set to true to disable (hide) the login form, useful if you use OAuth, defaults to false
;disable_login_form = false
# Set to true to disable the sign out link in the side menu. Useful if you use auth.proxy or auth.jwt, defaults to false
;disable_signout_menu = false
# URL to redirect the user to after sign out
;signout_redirect_url =
# Set to true to attempt login with OAuth automatically, skipping the login screen.
# This setting is ignored if multiple OAuth providers are configured.
;oauth_auto_login = false
# OAuth state max age cookie duration in seconds. Defaults to 600 seconds.
;oauth_state_cookie_max_age = 600
# limit of api_key seconds to live before expiration
;api_key_max_seconds_to_live = -1
# Set to true to enable SigV4 authentication option for HTTP-based datasources.
;sigv4_auth_enabled = false
#################################### Anonymous Auth ######################
[auth.anonymous]
# enable anonymous access
;enabled = false
# specify organization name that should be used for unauthenticated users
;org_name = Main Org.
# specify role for unauthenticated users
;org_role = Viewer
# mask the Grafana version number for unauthenticated users
;hide_version = false
#################################### GitHub Auth ##########################
[auth.github]
;enabled = false
;allow_sign_up = true
;client_id = some_id
;client_secret = some_secret
;scopes = user:email,read:org
;auth_url = https://github.com/login/oauth/authorize
;token_url = https://github.com/login/oauth/access_token
;api_url = https://api.github.com/user
;allowed_domains =
;team_ids =
;allowed_organizations =
#################################### GitLab Auth #########################
[auth.gitlab]
;enabled = false
;allow_sign_up = true
;client_id = some_id
;client_secret = some_secret
;scopes = api
;auth_url = https://gitlab.com/oauth/authorize
;token_url = https://gitlab.com/oauth/token
;api_url = https://gitlab.com/api/v4
;allowed_domains =
;allowed_groups =
#################################### Google Auth ##########################
[auth.google]
;enabled = false
;allow_sign_up = true
;client_id = some_client_id
;client_secret = some_client_secret
;scopes = https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email
;auth_url = https://accounts.google.com/o/oauth2/auth
;token_url = https://accounts.google.com/o/oauth2/token
;api_url = https://www.googleapis.com/oauth2/v1/userinfo
;allowed_domains =
;hosted_domain =
#################################### Grafana.com Auth ####################
[auth.grafana_com]
;enabled = false
;allow_sign_up = true
;client_id = some_id
;client_secret = some_secret
;scopes = user:email
;allowed_organizations =
#################################### Azure AD OAuth #######################
[auth.azuread]
;name = Azure AD
;enabled = false
;allow_sign_up = true
;client_id = some_client_id
;client_secret = some_client_secret
;scopes = openid email profile
;auth_url = https://login.microsoftonline.com/<tenant-id>/oauth2/v2.0/authorize
;token_url = https://login.microsoftonline.com/<tenant-id>/oauth2/v2.0/token
;allowed_domains =
;allowed_groups =
#################################### Okta OAuth #######################
[auth.okta]
;name = Okta
;enabled = false
;allow_sign_up = true
;client_id = some_id
;client_secret = some_secret
;scopes = openid profile email groups
;auth_url = https://<tenant-id>.okta.com/oauth2/v1/authorize
;token_url = https://<tenant-id>.okta.com/oauth2/v1/token
;api_url = https://<tenant-id>.okta.com/oauth2/v1/userinfo
;allowed_domains =
;allowed_groups =
;role_attribute_path =
;role_attribute_strict = false
#################################### Generic OAuth ##########################
[auth.generic_oauth]
;enabled = false
;name = OAuth
;allow_sign_up = true
;client_id = some_id
;client_secret = some_secret
;scopes = user:email,read:org
;empty_scopes = false
;email_attribute_name = email:primary
;email_attribute_path =
;login_attribute_path =
;name_attribute_path =
;id_token_attribute_name =
;auth_url = https://foo.bar/login/oauth/authorize
;token_url = https://foo.bar/login/oauth/access_token
;api_url = https://foo.bar/user
;teams_url =
;allowed_domains =
;team_ids =
;allowed_organizations =
;role_attribute_path =
;role_attribute_strict = false
;groups_attribute_path =
;team_ids_attribute_path =
;tls_skip_verify_insecure = false
;tls_client_cert =
;tls_client_key =
;tls_client_ca =
#################################### Basic Auth ##########################
[auth.basic]
;enabled = true
#################################### Auth Proxy ##########################
[auth.proxy]
;enabled = false
;header_name = X-WEBAUTH-USER
;header_property = username
;auto_sign_up = true
;sync_ttl = 60
;whitelist = 192.168.1.1, 192.168.2.1
;headers = Email:X-User-Email, Name:X-User-Name
# Read the auth proxy docs for details on what the setting below enables
;enable_login_token = false
#################################### Auth JWT ##########################
[auth.jwt]
;enabled = true
;header_name = X-JWT-Assertion
;email_claim = sub
;username_claim = sub
;jwk_set_url = https://foo.bar/.well-known/jwks.json
;jwk_set_file = /path/to/jwks.json
;cache_ttl = 60m
;expected_claims = {"aud": ["foo", "bar"]}
;key_file = /path/to/key/file
#################################### Auth LDAP ##########################
[auth.ldap]
;enabled = false
;config_file = /etc/grafana/ldap.toml
;allow_sign_up = true
# LDAP background sync (Enterprise only)
# At 1 am every day
;sync_cron = "0 0 1 * * *"
;active_sync_enabled = true
#################################### AWS ###########################
[aws]
# Enter a comma-separated list of allowed AWS authentication providers.
# Options are: default (AWS SDK Default), keys (Access && secret key), credentials (Credentials field), ec2_iam_role (EC2 IAM Role)
; allowed_auth_providers = default,keys,credentials
# Allow AWS users to assume a role using temporary security credentials.
# If true, assume role will be enabled for all AWS authentication providers that are specified in aws_auth_providers
; assume_role_enabled = true
#################################### Azure ###############################
[azure]
# Azure cloud environment where Grafana is hosted
# Possible values are AzureCloud, AzureChinaCloud, AzureUSGovernment and AzureGermanCloud
# Default value is AzureCloud (i.e. public cloud)
;cloud = AzureCloud
# Specifies whether Grafana hosted in Azure service with Managed Identity configured (e.g. Azure Virtual Machines instance)
# If enabled, the managed identity can be used for authentication of Grafana in Azure services
# Disabled by default, needs to be explicitly enabled
;managed_identity_enabled = false
# Client ID to use for user-assigned managed identity
# Should be set for user-assigned identity and should be empty for system-assigned identity
;managed_identity_client_id =
#################################### SMTP / Emailing ##########################
[smtp]
;enabled = false
;host = localhost:25
;user =
# If the password contains # or ; you have to wrap it with triple quotes. Ex """#password;"""
;password =
;cert_file =
;key_file =
;skip_verify = false
;from_address = [email protected]
;from_name = Grafana
# EHLO identity in SMTP dialog (defaults to instance_name)
;ehlo_identity = dashboard.example.com
# SMTP startTLS policy (defaults to 'OpportunisticStartTLS')
;startTLS_policy = NoStartTLS
[emails]
;welcome_email_on_sign_up = false
;templates_pattern = emails/*.html, emails/*.txt
;content_types = text/html
#################################### Logging ##########################
[log]
# Either "console", "file", "syslog". Default is console and file
# Use space to separate multiple modes, e.g. "console file"
;mode = console file
# Either "debug", "info", "warn", "error", "critical", default is "info"
;level = info
# optional settings to set different levels for specific loggers. Ex filters = sqlstore:debug
;filters =
# For "console" mode only
[log.console]
;level =
# log line format, valid options are text, console and json
;format = console
# For "file" mode only
[log.file]
;level =
# log line format, valid options are text, console and json
;format = text
# This enables automated log rotate(switch of following options), default is true
;log_rotate = true
# Max line number of single file, default is 1000000
;max_lines = 1000000
# Max size shift of single file, default is 28 means 1 << 28, 256MB
;max_size_shift = 28
# Segment log daily, default is true
;daily_rotate = true
# Expired days of log file(delete after max days), default is 7
;max_days = 7
[log.syslog]
;level =
# log line format, valid options are text, console and json
;format = text
# Syslog network type and address. This can be udp, tcp, or unix. If left blank, the default unix endpoints will be used.
;network =
;address =
# Syslog facility. user, daemon and local0 through local7 are valid.
;facility =
# Syslog tag. By default, the process' argv[0] is used.
;tag =
[log.frontend]
# Should Sentry javascript agent be initialized
;enabled = false
# Sentry DSN if you want to send events to Sentry.
;sentry_dsn =
# Custom HTTP endpoint to send events captured by the Sentry agent to. Default will log the events to stdout.
;custom_endpoint = /log
# Rate of events to be reported between 0 (none) and 1 (all), float
;sample_rate = 1.0
# Requests per second limit enforced an extended period, for Grafana backend log ingestion endpoint (/log).
;log_endpoint_requests_per_second_limit = 3
# Max requests accepted per short interval of time for Grafana backend log ingestion endpoint (/log).
;log_endpoint_burst_limit = 15
#################################### Usage Quotas ########################
[quota]
; enabled = false
#### set quotas to -1 to make unlimited. ####
# limit number of users per Org.
; org_user = 10
# limit number of dashboards per Org.
; org_dashboard = 100
# limit number of data_sources per Org.
; org_data_source = 10
# limit number of api_keys per Org.
; org_api_key = 10
# limit number of alerts per Org.
;org_alert_rule = 100
# limit number of orgs a user can create.
; user_org = 10
# Global limit of users.
; global_user = -1
# global limit of orgs.
; global_org = -1
# global limit of dashboards
; global_dashboard = -1
# global limit of api_keys
; global_api_key = -1
# global limit on number of logged in users.
; global_session = -1
# global limit of alerts
;global_alert_rule = -1
#################################### Unified Alerting ####################
[unified_alerting]
#Enable the Unified Alerting sub-system and interface. When enabled we'll migrate all of your alert rules and notification channels to the new system. New alert rules will be created and your notification channels will be converted into an Alertmanager configuration. Previous data is preserved to enable backwards compatibility but new data is removed.```
;enabled = false
# Comma-separated list of organization IDs for which to disable unified alerting. Only supported if unified alerting is enabled.
;disabled_orgs =
# Specify the frequency of polling for admin config changes.
# The interval string is a possibly signed sequence of decimal numbers, followed by a unit suffix (ms, s, m, h, d), e.g. 30s or 1m.
;admin_config_poll_interval = 60s
# Specify the frequency of polling for Alertmanager config changes.
# The interval string is a possibly signed sequence of decimal numbers, followed by a unit suffix (ms, s, m, h, d), e.g. 30s or 1m.
;alertmanager_config_poll_interval = 60s
# Listen address/hostname and port to receive unified alerting messages for other Grafana instances. The port is used for both TCP and UDP. It is assumed other Grafana instances are also running on the same port. The default value is `0.0.0.0:9094`.
;ha_listen_address = "0.0.0.0:9094"
# Listen address/hostname and port to receive unified alerting messages for other Grafana instances. The port is used for both TCP and UDP. It is assumed other Grafana instances are also running on the same port. The default value is `0.0.0.0:9094`.
;ha_advertise_address = ""
# Comma-separated list of initial instances (in a format of host:port) that will form the HA cluster. Configuring this setting will enable High Availability mode for alerting.
;ha_peers = ""
# Time to wait for an instance to send a notification via the Alertmanager. In HA, each Grafana instance will
# be assigned a position (e.g. 0, 1). We then multiply this position with the timeout to indicate how long should
# each instance wait before sending the notification to take into account replication lag.
# The interval string is a possibly signed sequence of decimal numbers, followed by a unit suffix (ms, s, m, h, d), e.g. 30s or 1m.
;ha_peer_timeout = "15s"
# The interval between sending gossip messages. By lowering this value (more frequent) gossip messages are propagated
# across cluster more quickly at the expense of increased bandwidth usage.
# The interval string is a possibly signed sequence of decimal numbers, followed by a unit suffix (ms, s, m, h, d), e.g. 30s or 1m.
;ha_gossip_interval = "200ms"
# The interval between gossip full state syncs. Setting this interval lower (more frequent) will increase convergence speeds
# across larger clusters at the expense of increased bandwidth usage.
# The interval string is a possibly signed sequence of decimal numbers, followed by a unit suffix (ms, s, m, h, d), e.g. 30s or 1m.
;ha_push_pull_interval = "60s"
# Enable or disable alerting rule execution. The alerting UI remains visible. This option has a legacy version in the `[alerting]` section that takes precedence.
;execute_alerts = true
# Alert evaluation timeout when fetching data from the datasource. This option has a legacy version in the `[alerting]` section that takes precedence.
# The timeout string is a possibly signed sequence of decimal numbers, followed by a unit suffix (ms, s, m, h, d), e.g. 30s or 1m.
;evaluation_timeout = 30s
# Number of times we'll attempt to evaluate an alert rule before giving up on that evaluation. This option has a legacy version in the `[alerting]` section that takes precedence.
;max_attempts = 3
# Minimum interval to enforce between rule evaluations. Rules will be adjusted if they are less than this value or if they are not multiple of the scheduler interval (10s). Higher values can help with resource management as we'll schedule fewer evaluations over time. This option has a legacy version in the `[alerting]` section that takes precedence.
# The interval string is a possibly signed sequence of decimal numbers, followed by a unit suffix (ms, s, m, h, d), e.g. 30s or 1m.
;min_interval = 10s
#################################### Alerting ############################
[alerting]
# Disable legacy alerting engine & UI features
;enabled = true
# Makes it possible to turn off alert execution but alerting UI is visible
;execute_alerts = true
# Default setting for new alert rules. Defaults to categorize error and timeouts as alerting. (alerting, keep_state)
;error_or_timeout = alerting
# Default setting for how Grafana handles nodata or null values in alerting. (alerting, no_data, keep_state, ok)
;nodata_or_nullvalues = no_data
# Alert notifications can include images, but rendering many images at the same time can overload the server
# This limit will protect the server from render overloading and make sure notifications are sent out quickly
;concurrent_render_limit = 5
# Default setting for alert calculation timeout. Default value is 30
;evaluation_timeout_seconds = 30
# Default setting for alert notification timeout. Default value is 30
;notification_timeout_seconds = 30
# Default setting for max attempts to sending alert notifications. Default value is 3
;max_attempts = 3
# Makes it possible to enforce a minimal interval between evaluations, to reduce load on the backend
;min_interval_seconds = 1
# Configures for how long alert annotations are stored. Default is 0, which keeps them forever.
# This setting should be expressed as a duration. Examples: 6h (hours), 10d (days), 2w (weeks), 1M (month).
;max_annotation_age =
# Configures max number of alert annotations that Grafana stores. Default value is 0, which keeps all alert annotations.
;max_annotations_to_keep =
#################################### Annotations #########################
[annotations]
# Configures the batch size for the annotation clean-up job. This setting is used for dashboard, API, and alert annotations.
;cleanupjob_batchsize = 100
[annotations.dashboard]
# Dashboard annotations means that annotations are associated with the dashboard they are created on.
# Configures how long dashboard annotations are stored. Default is 0, which keeps them forever.
# This setting should be expressed as a duration. Examples: 6h (hours), 10d (days), 2w (weeks), 1M (month).
;max_age =
# Configures max number of dashboard annotations that Grafana stores. Default value is 0, which keeps all dashboard annotations.
;max_annotations_to_keep =
[annotations.api]
# API annotations means that the annotations have been created using the API without any
# association with a dashboard.
# Configures how long Grafana stores API annotations. Default is 0, which keeps them forever.
# This setting should be expressed as a duration. Examples: 6h (hours), 10d (days), 2w (weeks), 1M (month).
;max_age =
# Configures max number of API annotations that Grafana keeps. Default value is 0, which keeps all API annotations.
;max_annotations_to_keep =
#################################### Explore #############################
[explore]
# Enable the Explore section
;enabled = true
#################################### Internal Grafana Metrics ##########################
# Metrics available at HTTP API Url /metrics
[metrics]
# Disable / Enable internal metrics
;enabled = true
# Graphite Publish interval
;interval_seconds = 10
# Disable total stats (stat_totals_*) metrics to be generated
;disable_total_stats = false
#If both are set, basic auth will be required for the metrics endpoint.
; basic_auth_username =
; basic_auth_password =
# Metrics environment info adds dimensions to the `grafana_environment_info` metric, which
# can expose more information about the Grafana instance.
[metrics.environment_info]
#exampleLabel1 = exampleValue1
#exampleLabel2 = exampleValue2
# Send internal metrics to Graphite
[metrics.graphite]
# Enable by setting the address setting (ex localhost:2003)
;address =
;prefix = prod.grafana.%(instance_name)s.
#################################### Grafana.com integration ##########################
# Url used to import dashboards directly from Grafana.com
[grafana_com]
;url = https://grafana.com
#################################### Distributed tracing ############
[tracing.jaeger]
# Enable by setting the address sending traces to jaeger (ex localhost:6831)
;address = localhost:6831
# Tag that will always be included in when creating new spans. ex (tag1:value1,tag2:value2)
;always_included_tag = tag1:value1
# Type specifies the type of the sampler: const, probabilistic, rateLimiting, or remote
;sampler_type = const
# jaeger samplerconfig param
# for "const" sampler, 0 or 1 for always false/true respectively
# for "probabilistic" sampler, a probability between 0 and 1
# for "rateLimiting" sampler, the number of spans per second
# for "remote" sampler, param is the same as for "probabilistic"
# and indicates the initial sampling rate before the actual one
# is received from the mothership
;sampler_param = 1
# sampling_server_url is the URL of a sampling manager providing a sampling strategy.
;sampling_server_url =
# Whether or not to use Zipkin propagation (x-b3- HTTP headers).
;zipkin_propagation = false
# Setting this to true disables shared RPC spans.
# Not disabling is the most common setting when using Zipkin elsewhere in your infrastructure.
;disable_shared_zipkin_spans = false
#################################### External image storage ##########################
[external_image_storage]
# Used for uploading images to public servers so they can be included in slack/email messages.
# you can choose between (s3, webdav, gcs, azure_blob, local)
;provider =
[external_image_storage.s3]
;endpoint =
;path_style_access =
;bucket =
;region =
;path =
;access_key =
;secret_key =
[external_image_storage.webdav]
;url =
;public_url =
;username =
;password =
[external_image_storage.gcs]
;key_file =
;bucket =
;path =
[external_image_storage.azure_blob]
;account_name =
;account_key =
;container_name =
[external_image_storage.local]
# does not require any configuration
[rendering]
# Options to configure a remote HTTP image rendering service, e.g. using https://github.com/grafana/grafana-image-renderer.
# URL to a remote HTTP image renderer service, e.g. http://localhost:8081/render, will enable Grafana to render panels and dashboards to PNG-images using HTTP requests to an external service.
;server_url =
# If the remote HTTP image renderer service runs on a different server than the Grafana server you may have to configure this to a URL where Grafana is reachable, e.g. http://grafana.domain/.
;callback_url =
# Concurrent render request limit affects when the /render HTTP endpoint is used. Rendering many images at the same time can overload the server,
# which this setting can help protect against by only allowing a certain amount of concurrent requests.
;concurrent_render_request_limit = 30
[panels]
# If set to true Grafana will allow script tags in text panels. Not recommended as it enable XSS vulnerabilities.
;disable_sanitize_html = false
[plugins]
;enable_alpha = false
;app_tls_skip_verify_insecure = false
# Enter a comma-separated list of plugin identifiers to identify plugins to load even if they are unsigned. Plugins with modified signatures are never loaded.
;allow_loading_unsigned_plugins =
# Enable or disable installing plugins directly from within Grafana.
;plugin_admin_enabled = false
;plugin_admin_external_manage_enabled = false
;plugin_catalog_url = https://grafana.com/grafana/plugins/
#################################### Grafana Live ##########################################
[live]
# max_connections to Grafana Live WebSocket endpoint per Grafana server instance. See Grafana Live docs
# if you are planning to make it higher than default 100 since this can require some OS and infrastructure
# tuning. 0 disables Live, -1 means unlimited connections.
;max_connections = 100
# allowed_origins is a comma-separated list of origins that can establish connection with Grafana Live.
# If not set then origin will be matched over root_url. Supports wildcard symbol "*".
;allowed_origins =
# engine defines an HA (high availability) engine to use for Grafana Live. By default no engine used - in
# this case Live features work only on a single Grafana server. Available options: "redis".
# Setting ha_engine is an EXPERIMENTAL feature.
;ha_engine =
# ha_engine_address sets a connection address for Live HA engine. Depending on engine type address format can differ.
# For now we only support Redis connection address in "host:port" format.
# This option is EXPERIMENTAL.
;ha_engine_address = "127.0.0.1:6379"
#################################### Grafana Image Renderer Plugin ##########################
[plugin.grafana-image-renderer]
# Instruct headless browser instance to use a default timezone when not provided by Grafana, e.g. when rendering panel image of alert.
# See ICU’s metaZones.txt (https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt) for a list of supported
# timezone IDs. Fallbacks to TZ environment variable if not set.
;rendering_timezone =
# Instruct headless browser instance to use a default language when not provided by Grafana, e.g. when rendering panel image of alert.
# Please refer to the HTTP header Accept-Language to understand how to format this value, e.g. 'fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7, *;q=0.5'.
;rendering_language =
# Instruct headless browser instance to use a default device scale factor when not provided by Grafana, e.g. when rendering panel image of alert.
# Default is 1. Using a higher value will produce more detailed images (higher DPI), but will require more disk space to store an image.
;rendering_viewport_device_scale_factor =
# Instruct headless browser instance whether to ignore HTTPS errors during navigation. Per default HTTPS errors are not ignored. Due to
# the security risk it's not recommended to ignore HTTPS errors.
;rendering_ignore_https_errors =
# Instruct headless browser instance whether to capture and log verbose information when rendering an image. Default is false and will
# only capture and log error messages. When enabled, debug messages are captured and logged as well.
# For the verbose information to be included in the Grafana server log you have to adjust the rendering log level to debug, configure
# [log].filter = rendering:debug.
;rendering_verbose_logging =
# Instruct headless browser instance whether to output its debug and error messages into running process of remote rendering service.
# Default is false. This can be useful to enable (true) when troubleshooting.
;rendering_dumpio =
# Additional arguments to pass to the headless browser instance. Default is --no-sandbox. The list of Chromium flags can be found
# here (https://peter.sh/experiments/chromium-command-line-switches/). Multiple arguments is separated with comma-character.
;rendering_args =
# You can configure the plugin to use a different browser binary instead of the pre-packaged version of Chromium.
# Please note that this is not recommended, since you may encounter problems if the installed version of Chrome/Chromium is not
# compatible with the plugin.
;rendering_chrome_bin =
# Instruct how headless browser instances are created. Default is 'default' and will create a new browser instance on each request.
# Mode 'clustered' will make sure that only a maximum of browsers/incognito pages can execute concurrently.
# Mode 'reusable' will have one browser instance and will create a new incognito page on each request.
;rendering_mode =
# When rendering_mode = clustered you can instruct how many browsers or incognito pages can execute concurrently. Default is 'browser'
# and will cluster using browser instances.
# Mode 'context' will cluster using incognito pages.
;rendering_clustering_mode =
# When rendering_mode = clustered you can define maximum number of browser instances/incognito pages that can execute concurrently..
;rendering_clustering_max_concurrency =
# Limit the maximum viewport width, height and device scale factor that can be requested.
;rendering_viewport_max_width =
;rendering_viewport_max_height =
;rendering_viewport_max_device_scale_factor =
# Change the listening host and port of the gRPC server. Default host is 127.0.0.1 and default port is 0 and will automatically assign
# a port not in use.
;grpc_host =
;grpc_port =
[enterprise]
# Path to a valid Grafana Enterprise license.jwt file
;license_path =
[feature_toggles]
# enable features, separated by spaces
;enable =
[date_formats]
# For information on what formatting patterns that are supported https://momentjs.com/docs/#/displaying/
# Default system date format used in time range picker and other places where full time is displayed
;full_date = YYYY-MM-DD HH:mm:ss
# Used by graph and other places where we only show small intervals
;interval_second = HH:mm:ss
;interval_minute = HH:mm
;interval_hour = MM/DD HH:mm
;interval_day = MM/DD
;interval_month = YYYY-MM
;interval_year = YYYY
# Experimental feature
;use_browser_locale = false
# Default timezone for user preferences. Options are 'browser' for the browser local timezone or a timezone name from IANA Time Zone database, e.g. 'UTC' or 'Europe/Amsterdam' etc.
;default_timezone = browser
[expressions]
# Enable or disable the expressions functionality.
;enabled = true
[geomap]
# Set the JSON configuration for the default basemap
;default_baselayer_config = `{
; "type": "xyz",
; "config": {
; "attribution": "Open street map",
; "url": "https://tile.openstreetmap.org/{z}/{x}/{y}.png"
; }
;}`
# Enable or disable loading other base map layers
;enable_custom_baselayers = true
| conf/sample.ini | 0 | https://github.com/grafana/grafana/commit/3c52df960ad8a45191ee0141a8c169a0cc4f79a5 | [
0.00043383552110753953,
0.00017423742974642664,
0.00016007776139304042,
0.00016865998622961342,
0.000030423965654335916
] |
{
"id": 5,
"code_window": [
" label=\"Timeout (seconds)\"\n",
" description=\"You might need to configure the timeout value if it takes a long time to collect your dashboard\n",
" metrics.\"\n",
" >\n",
" <Input type=\"number\" width={21} value={timeoutSeconds} onChange={this.onTimeoutChange} />\n",
" </Field>\n",
"\n",
" <Modal.ButtonRow>\n",
" <Button variant=\"secondary\" onClick={onDismiss} fill=\"outline\">\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <Input id=\"timeout-input\" type=\"number\" width={21} value={timeoutSeconds} onChange={this.onTimeoutChange} />\n"
],
"file_path": "public/app/features/dashboard/components/ShareModal/ShareSnapshot.tsx",
"type": "replace",
"edit_start_line_idx": 241
} | import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { initialVariableModelState, TextBoxVariableModel, VariableOption } from '../types';
import { getInstanceState, VariablePayload, initialVariablesState, VariablesState } from '../state/types';
export const initialTextBoxVariableModelState: TextBoxVariableModel = {
...initialVariableModelState,
type: 'textbox',
query: '',
current: {} as VariableOption,
options: [],
originalQuery: null,
};
export const textBoxVariableSlice = createSlice({
name: 'templating/textbox',
initialState: initialVariablesState,
reducers: {
createTextBoxOptions: (state: VariablesState, action: PayloadAction<VariablePayload>) => {
const instanceState = getInstanceState<TextBoxVariableModel>(state, action.payload.id);
const option = { text: instanceState.query.trim(), value: instanceState.query.trim(), selected: false };
instanceState.options = [option];
instanceState.current = option;
},
},
});
export const textBoxVariableReducer = textBoxVariableSlice.reducer;
export const { createTextBoxOptions } = textBoxVariableSlice.actions;
| public/app/features/variables/textbox/reducer.ts | 0 | https://github.com/grafana/grafana/commit/3c52df960ad8a45191ee0141a8c169a0cc4f79a5 | [
0.00017392630979884416,
0.0001722588058328256,
0.00016948716074693948,
0.0001728108909446746,
0.0000016814137779874727
] |
{
"id": 0,
"code_window": [
" \"react-dom\": \"^16.8.0 || ^17.0.0 || ^18.0.0\"\n",
" },\n",
" \"engines\": {\n",
" \"node\": \">=10.13.0\"\n",
" },\n",
" \"publishConfig\": {\n",
" \"access\": \"public\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"node\": \"^14.18 || >=16\"\n"
],
"file_path": "code/frameworks/react-vite/package.json",
"type": "replace",
"edit_start_line_idx": 72
} | {
"name": "@storybook/svelte-vite",
"version": "7.0.0-alpha.26",
"description": "Storybook for Svelte: Develop Svelte Component in isolation with Hot Reloading.",
"keywords": [
"storybook"
],
"homepage": "https://github.com/storybookjs/storybook/tree/main/frameworks/svelte-vite",
"bugs": {
"url": "https://github.com/storybookjs/storybook/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/storybookjs/storybook.git",
"directory": "frameworks/svelte-vite"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/storybook"
},
"license": "MIT",
"exports": {
".": {
"require": "./dist/index.js",
"import": "./dist/index.mjs",
"types": "./dist/index.d.ts"
},
"./preset": {
"require": "./dist/preset.js",
"import": "./dist/preset.mjs",
"types": "./dist/preset.d.ts"
},
"./package.json": {
"require": "./package.json",
"import": "./package.json",
"types": "./package.json"
}
},
"main": "dist/index.js",
"module": "dist/index.mjs",
"types": "dist/index.d.ts",
"files": [
"dist/**/*",
"types/**/*",
"README.md",
"*.js",
"*.d.ts"
],
"scripts": {
"check": "tsc --noEmit",
"prepare": "../../../scripts/prepare/bundle.ts"
},
"dependencies": {
"@rollup/pluginutils": "^4.2.0",
"@storybook/addon-svelte-csf": "^2.0.0",
"@storybook/builder-vite": "7.0.0-alpha.26",
"@storybook/core-server": "7.0.0-alpha.26",
"@storybook/node-logger": "7.0.0-alpha.26",
"@storybook/svelte": "7.0.0-alpha.26",
"@sveltejs/vite-plugin-svelte": "^1.0.0",
"@types/node": "^14.14.20 || ^16.0.0",
"@vitejs/plugin-react": "^1.0.8",
"ast-types": "^0.14.2",
"core-js": "^3.8.2",
"magic-string": "^0.26.1",
"regenerator-runtime": "^0.13.7",
"svelte": "^3.0.0",
"sveltedoc-parser": "^4.2.1",
"vite": "3"
},
"devDependencies": {
"jest-specific-snapshot": "^4.0.0",
"typescript": "~4.6.3"
},
"peerDependencies": {
"@babel/core": "^7.11.5",
"react": "^16.8.0 || ^17.0.0 || ^18.0.0",
"react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0"
},
"peerDependenciesMeta": {
"@babel/core": {
"optional": true
},
"typescript": {
"optional": true
}
},
"engines": {
"node": ">=10.13.0"
},
"publishConfig": {
"access": "public"
},
"bundler": {
"entries": [
"./src/index.ts",
"./src/preset.ts"
],
"platform": "node"
},
"gitHead": "e5c9cfe1d0482132e59734d9cfce57477045914f"
}
| code/frameworks/svelte-vite/package.json | 1 | https://github.com/storybookjs/storybook/commit/a8af64c05fd4595ddf5becf9d886100972bae925 | [
0.002070814836770296,
0.0005158266285434365,
0.00016594777116551995,
0.00017067477165255696,
0.000648443354293704
] |
{
"id": 0,
"code_window": [
" \"react-dom\": \"^16.8.0 || ^17.0.0 || ^18.0.0\"\n",
" },\n",
" \"engines\": {\n",
" \"node\": \">=10.13.0\"\n",
" },\n",
" \"publishConfig\": {\n",
" \"access\": \"public\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"node\": \"^14.18 || >=16\"\n"
],
"file_path": "code/frameworks/react-vite/package.json",
"type": "replace",
"edit_start_line_idx": 72
} | # Number of days of inactivity before an issue becomes stale
daysUntilStale: 21
# Number of days of inactivity before a stale issue is closed
daysUntilClose: 30
# Issues with these labels will never be considered stale
exemptLabels:
- linear
- todo
- ready
- 'in progress'
- 'do not merge'
- 'needs review'
- 'high priority'
- 'good first issue'
# Label to use when marking an issue as stale
staleLabel: inactive
# Comment to post when marking an issue as stale. Set to `false` to disable
markComment: >
Hi everyone! Seems like there hasn't been much going on in this issue lately.
If there are still questions, comments, or bugs, please feel free to continue
the discussion. Unfortunately, we don't have time to get to every issue. We
are always open to contributions so please send us a pull request if you would
like to help. Inactive issues will be closed after 30 days. Thanks!
# Comment to post when closing a stale issue. Set to `false` to disable
closeComment: >
Hey there, it's me again! I am going close this issue to help our maintainers
focus on the current development roadmap instead. If the issue mentioned is
still a concern, please open a new ticket and mention this old one. Cheers
and thanks for using Storybook!
| .github/stale.yml | 0 | https://github.com/storybookjs/storybook/commit/a8af64c05fd4595ddf5becf9d886100972bae925 | [
0.00016831136599648744,
0.0001677483960520476,
0.00016685135778971016,
0.00016791545203886926,
5.458917939904495e-7
] |
{
"id": 0,
"code_window": [
" \"react-dom\": \"^16.8.0 || ^17.0.0 || ^18.0.0\"\n",
" },\n",
" \"engines\": {\n",
" \"node\": \">=10.13.0\"\n",
" },\n",
" \"publishConfig\": {\n",
" \"access\": \"public\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"node\": \"^14.18 || >=16\"\n"
],
"file_path": "code/frameworks/react-vite/package.json",
"type": "replace",
"edit_start_line_idx": 72
} | import global from 'global';
import { dedent } from 'ts-dedent';
import { logger } from '@storybook/client-logger';
import { Background } from '../types';
const { document, window } = global;
export const isReduceMotionEnabled = () => {
const prefersReduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
return prefersReduceMotion.matches;
};
export const getBackgroundColorByName = (
currentSelectedValue: string,
backgrounds: Background[] = [],
defaultName: string
): string => {
if (currentSelectedValue === 'transparent') {
return 'transparent';
}
if (backgrounds.find((background) => background.value === currentSelectedValue)) {
return currentSelectedValue;
}
const defaultBackground = backgrounds.find((background) => background.name === defaultName);
if (defaultBackground) {
return defaultBackground.value;
}
if (defaultName) {
const availableColors = backgrounds.map((background) => background.name).join(', ');
logger.warn(
dedent`
Backgrounds Addon: could not find the default color "${defaultName}".
These are the available colors for your story based on your configuration:
${availableColors}.
`
);
}
return 'transparent';
};
export const clearStyles = (selector: string | string[]) => {
const selectors = Array.isArray(selector) ? selector : [selector];
selectors.forEach(clearStyle);
};
const clearStyle = (selector: string) => {
const element = document.getElementById(selector) as HTMLElement;
if (element) {
element.parentElement.removeChild(element);
}
};
export const addGridStyle = (selector: string, css: string) => {
const existingStyle = document.getElementById(selector) as HTMLElement;
if (existingStyle) {
if (existingStyle.innerHTML !== css) {
existingStyle.innerHTML = css;
}
} else {
const style = document.createElement('style') as HTMLElement;
style.setAttribute('id', selector);
style.innerHTML = css;
document.head.appendChild(style);
}
};
export const addBackgroundStyle = (selector: string, css: string, storyId: string) => {
const existingStyle = document.getElementById(selector) as HTMLElement;
if (existingStyle) {
if (existingStyle.innerHTML !== css) {
existingStyle.innerHTML = css;
}
} else {
const style = document.createElement('style') as HTMLElement;
style.setAttribute('id', selector);
style.innerHTML = css;
const gridStyleSelector = `addon-backgrounds-grid${storyId ? `-docs-${storyId}` : ''}`;
// If grids already exist, we want to add the style tag BEFORE it so the background doesn't override grid
const existingGridStyle = document.getElementById(gridStyleSelector) as HTMLElement;
if (existingGridStyle) {
existingGridStyle.parentElement.insertBefore(style, existingGridStyle);
} else {
document.head.appendChild(style);
}
}
};
| code/addons/backgrounds/src/helpers/index.ts | 0 | https://github.com/storybookjs/storybook/commit/a8af64c05fd4595ddf5becf9d886100972bae925 | [
0.00016974221216514707,
0.00016834685811772943,
0.0001655435044085607,
0.0001685313181951642,
0.0000011843304719150183
] |
{
"id": 0,
"code_window": [
" \"react-dom\": \"^16.8.0 || ^17.0.0 || ^18.0.0\"\n",
" },\n",
" \"engines\": {\n",
" \"node\": \">=10.13.0\"\n",
" },\n",
" \"publishConfig\": {\n",
" \"access\": \"public\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"node\": \"^14.18 || >=16\"\n"
],
"file_path": "code/frameworks/react-vite/package.json",
"type": "replace",
"edit_start_line_idx": 72
} | ```js
// .storybook/my-addon/manager.js
import { addons } from '@storybook/addons';
// Register the addon with a unique name.
addons.register('my-organisation/my-addon', (api) => {});
``` | docs/snippets/common/storybook-addons-api-register.js.mdx | 0 | https://github.com/storybookjs/storybook/commit/a8af64c05fd4595ddf5becf9d886100972bae925 | [
0.00016845778736751527,
0.00016845778736751527,
0.00016845778736751527,
0.00016845778736751527,
0
] |
{
"id": 1,
"code_window": [
" \"optional\": true\n",
" }\n",
" },\n",
" \"engines\": {\n",
" \"node\": \">=10.13.0\"\n",
" },\n",
" \"publishConfig\": {\n",
" \"access\": \"public\"\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"node\": \"^14.18 || >=16\"\n"
],
"file_path": "code/frameworks/svelte-vite/package.json",
"type": "replace",
"edit_start_line_idx": 88
} | {
"name": "@storybook/vue3-vite",
"version": "7.0.0-alpha.26",
"description": "Storybook for Vue3: Develop Vue3 Component in isolation with Hot Reloading.",
"keywords": [
"storybook"
],
"homepage": "https://github.com/storybookjs/storybook/tree/main/frameworks/vue3-vite",
"bugs": {
"url": "https://github.com/storybookjs/storybook/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/storybookjs/storybook.git",
"directory": "frameworks/vue3-vite"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/storybook"
},
"license": "MIT",
"exports": {
".": {
"require": "./dist/index.js",
"import": "./dist/index.mjs",
"types": "./dist/index.d.ts"
},
"./preset": {
"require": "./dist/preset.js",
"import": "./dist/preset.mjs",
"types": "./dist/preset.d.ts"
},
"./package.json": {
"require": "./package.json",
"import": "./package.json",
"types": "./package.json"
}
},
"main": "dist/index.js",
"module": "dist/index.mjs",
"types": "dist/index.d.ts",
"files": [
"dist/**/*",
"types/**/*",
"README.md",
"*.js",
"*.d.ts"
],
"scripts": {
"check": "tsc --noEmit",
"prepare": "../../../scripts/prepare/bundle.ts"
},
"dependencies": {
"@rollup/pluginutils": "^4.2.0",
"@storybook/builder-vite": "7.0.0-alpha.26",
"@storybook/core-server": "7.0.0-alpha.26",
"@storybook/vue3": "7.0.0-alpha.26",
"@types/node": "^14.14.20 || ^16.0.0",
"@vitejs/plugin-vue": "^3.0.3",
"ast-types": "^0.14.2",
"core-js": "^3.8.2",
"magic-string": "^0.26.1",
"react-docgen": "6.0.0-alpha.1",
"regenerator-runtime": "^0.13.7",
"vite": "3",
"vue-docgen-api": "^4.40.0"
},
"devDependencies": {
"jest-specific-snapshot": "^4.0.0",
"typescript": "~4.6.3"
},
"peerDependencies": {
"@babel/core": "^7.11.5",
"react": "^16.8.0 || ^17.0.0 || ^18.0.0",
"react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0"
},
"peerDependenciesMeta": {
"@babel/core": {
"optional": true
},
"typescript": {
"optional": true
}
},
"engines": {
"node": ">=10.13.0"
},
"publishConfig": {
"access": "public"
},
"bundler": {
"entries": [
"./src/index.ts",
"./src/preset.ts"
],
"platform": "node"
},
"gitHead": "e5c9cfe1d0482132e59734d9cfce57477045914f"
}
| code/frameworks/vue3-vite/package.json | 1 | https://github.com/storybookjs/storybook/commit/a8af64c05fd4595ddf5becf9d886100972bae925 | [
0.9923040270805359,
0.09938204288482666,
0.00016556307673454285,
0.00016891187988221645,
0.29764068126678467
] |
{
"id": 1,
"code_window": [
" \"optional\": true\n",
" }\n",
" },\n",
" \"engines\": {\n",
" \"node\": \">=10.13.0\"\n",
" },\n",
" \"publishConfig\": {\n",
" \"access\": \"public\"\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"node\": \"^14.18 || >=16\"\n"
],
"file_path": "code/frameworks/svelte-vite/package.json",
"type": "replace",
"edit_start_line_idx": 88
} | - Use the Storybook CLI to install it in a single command. Run this inside your _existing project’s_ root directory:
```shell
# Add Storybook:
npx storybook init
```
- Update your `angular.json` file to include Storybook's custom builder:
```json
{
"storybook": {
"builder": "@storybook/angular:start-storybook",
"options": {
"browserTarget": "angular-cli:build",
"port": 6006
}
},
"build-storybook": {
"builder": "@storybook/angular:build-storybook",
"options": {
"browserTarget": "angular-cli:build"
}
}
}
```
If you run into issues with the installation, check the [Troubleshooting section](#troubleshooting) below for guidance on how to solve it. | docs/get-started/installation-command-section/angular.mdx | 0 | https://github.com/storybookjs/storybook/commit/a8af64c05fd4595ddf5becf9d886100972bae925 | [
0.00016826226783450693,
0.00016733357915654778,
0.00016553876048419625,
0.00016819969459902495,
0.0000012693820963249891
] |
{
"id": 1,
"code_window": [
" \"optional\": true\n",
" }\n",
" },\n",
" \"engines\": {\n",
" \"node\": \">=10.13.0\"\n",
" },\n",
" \"publishConfig\": {\n",
" \"access\": \"public\"\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"node\": \"^14.18 || >=16\"\n"
],
"file_path": "code/frameworks/svelte-vite/package.json",
"type": "replace",
"edit_start_line_idx": 88
} | # Storybook addon Jest
Storybook addon for inspecting Jest unit test results.
[Framework Support](https://storybook.js.org/docs/react/api/frameworks-feature-support)
[](http://storybooks-official.netlify.com/?selectedKind=Addons%7Cjest&selectedStory=withTests&full=0&addons=1&stories=1&panelRight=0&addonPanel=storybook%2Ftests%2Fpanel)
> Check out the above [Live Storybook](http://storybooks-official.netlify.com/?selectedKind=Addons%7Cjest&selectedStory=withTests&full=0&addons=1&stories=1&panelRight=0&addonPanel=storybook%2Ftests%2Fpanel).
## Installation
Install this addon by adding the `@storybook/addon-jest` as a development dependency with:
`npm install --save-dev @storybook/addon-jest`
Or if you're using yarn as a package manager:
`yarn add --dev @storybook/addon-jest`
## Configuration
Register the addon in your [`.storybook/main.js`](https://storybook.js.org/docs/react/configure/overview#configure-your-storybook-project):
```js
module.exports = {
addons: ['@storybook/addon-jest'],
};
```
## Jest Configuration
When running **Jest**, be sure to save the results in a JSON file:
```js
"scripts": {
"test:generate-output": "jest --json --outputFile=.jest-test-results.json"
}
```
You may want to add the result file to `.gitignore`, since it's a generated file:
```
.jest-test-results.json
```
But much like lockfiles and snapshots, checking-in generated files can have certain advantages as well. It's up to you.
We recommend to **do** check in the test results file so starting Storybook from a clean git clone doesn't require running all tests first,
but this can mean you'll encounter merge conflicts on this file in the future (_re-generating this file is very similar to re-generating lockfiles and snapshots_).
### Generating the test results
Ensure the generated test-results file exists before you start Storybook. During development, you will likely start Jest in watch-mode and so the JSON file will be re-generated every time code or tests change.
```sh
npm run test:generate-output -- --watch
```
And in the jest config, add `jest-test-results.json` to `modulePathIgnorePatterns` to avoid an infinite loop.
```js
modulePathIgnorePatterns: ['node_modules', 'jest-test-results.json'],
```
This change will then be HMR (hot module reloaded) using webpack and displayed by this addon.
If you want to pre-run Jest automatically during development or a static build, you may need to consider that if your tests fail, the script receives a non-0 exit code and will exit.
You could create a `prebuild:storybook` npm script, which will never fail by appending `|| true`:
```json
"scripts": {
"test:generate-output": "jest --json --outputFile=.jest-test-results.json || true",
"test": "jest",
"prebuild:storybook": "npm run test:generate-output",
"build:storybook": "build-storybook -c .storybook -o build/",
"predeploy": "npm run build:storybook",
"deploy": "gh-pages -d build/",
}
```
## Usage
Assuming that you have already created a test file for your component (e.g., `MyComponent.test.js`).
### Story-level
In your story file, add a [decorator](https://storybook.js.org/docs/react/writing-stories/decorators) to your story's default export to display the results:
```js
// MyComponent.stories.js|jsx
import MyComponent from './MyComponent';
import results from '../.jest-test-results.json';
import { withTests } from '@storybook/addon-jest';
export default {
component: MyComponent,
title: 'MyComponent',
decorators: [withTests({ results })],
};
```
You can also add multiple tests results within your story by including the `jest` [parameter](https://storybook.js.org/docs/react/writing-stories/parameters), for example:
```js
// MyComponent.stories.js|jsx
import MyComponent from './MyComponent';
import results from '../.jest-test-results.json';
import { withTests } from '@storybook/addon-jest';
export default {
component: MyComponent,
title: 'MyComponent',
decorators: [withTests({ results })],
};
const Template = (args) => <MyComponent {....args} />;
export const Default = Template.bind({});
Default.args = {
text: 'Jest results in Storybook',
};
Default.parameters = {
jest: ['MyComponent.test.js', 'MyOtherComponent.test.js']
};
```
### Global level
To avoid importing the results of the tests in each story, you can update
your [`.storybook/preview.js`](https://storybook.js.org/docs/react/configure/overview#configure-story-rendering) and include a decorator allowing you to display the results only for the stories that have the `jest` parameter defined:
```js
// .storybook/preview.js
import { withTests } from '@storybook/addon-jest';
import results from '../.jest-test-results.json';
export const decorators = [
withTests({
results,
}),
];
```
Then in your story file:
```js
// MyComponent.stories.js|jsx
import MyComponent from './MyComponent';
export default {
component: MyComponent,
title: 'MyComponent',
};
const Template = (args) => <MyComponent {....args} />;
export const Default = Template.bind({});
Default.args={
text: 'Jest results in Storybook',
};
Default.parameters = {
jest: 'MyComponent.test.js',
};
```
The `jest` parameter will default to inferring from your story file name if not provided. For example, if your story file is `MyComponent.stories.js`,
then "MyComponent" will be used to find your test file results. It currently doesn't work in production environments.
### Disabling
You can disable the addon for a single story by setting the `jest` parameter to `{disable: true}`:
```js
// MyComponent.stories.js|jsx
import MyComponent from './MyComponent';
export default {
component: MyComponent,
title: 'MyComponent',
};
const Template = (args) => <MyComponent {...args} />;
export const Default = Template.bind({});
Default.args = {
text: 'Jest results in Storybook',
};
Default.parameters = {
jest: { disable: true },
};
```
## Usage with Angular
Using this addon with Angular will require some additional configuration. You'll need to install and configure Jest with [jest-preset-angular](https://www.npmjs.com/package/jest-preset-angular).
Then, in your `.storybook/preview.js`, you'll need to add a decorator with the following:
```js
// .storybook/preview.js
import { withTests } from '@storybook/addon-jest';
import results from '../.jest-test-results.json';
export const decorators = [
withTests({
results,
filesExt: '((\\.specs?)|(\\.tests?))?(\\.ts)?$',
}),
];
```
Finally, in your story, you'll need to include the following:
```ts
// MyComponent.stories.ts
import type { Meta, StoryFn } from '@storybook/angular';
import MyComponent from './MyComponent.component';
export default {
component: MyComponent,
title: 'MyComponent',
} as Meta;
const Template: StoryFn<MyComponent> = (args: MyComponent) => ({
props: args,
});
export const Default = Template.bind({});
Default.parameters = {
jest: 'MyComponent.component',
};
```
##### Example [here](https://github.com/storybookjs/storybook/tree/main/examples/angular-cli)
## Available options
- **options.results**: OBJECT jest output results. _mandatory_
- **filesExt**: STRING test file extension. _optional_. This allows you to write "MyComponent" and not "MyComponent.test.js". It will be used as regex to find your file results. Default value is `((\\.specs?)|(\\.tests?))?(\\.js)?$`. That means it will match: MyComponent.js, MyComponent.test.js, MyComponent.tests.js, MyComponent.spec.js, MyComponent.specs.js...
## TODO
- [ ] Add coverage
- [ ] Display nested test better (describe)
- [ ] Display the date of the test
- [ ] Add unit tests
- [ ] Add linting
- [ ] Split <TestPanel />
## Contributing
All ideas and contributions are welcome.
## Licence
MIT © 2017-present Renaud Tertrais
| code/addons/jest/README.md | 0 | https://github.com/storybookjs/storybook/commit/a8af64c05fd4595ddf5becf9d886100972bae925 | [
0.00017490317986812443,
0.00017021814710460603,
0.00016605951532255858,
0.00017068673332687467,
0.0000023798261281626765
] |
{
"id": 1,
"code_window": [
" \"optional\": true\n",
" }\n",
" },\n",
" \"engines\": {\n",
" \"node\": \">=10.13.0\"\n",
" },\n",
" \"publishConfig\": {\n",
" \"access\": \"public\"\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"node\": \"^14.18 || >=16\"\n"
],
"file_path": "code/frameworks/svelte-vite/package.json",
"type": "replace",
"edit_start_line_idx": 88
} | ```md
<!-- Button.stories.mdx -->
import { Meta, Story } from '@storybook/addon-docs';
import Button from './Button.svelte';
<Meta
title="Accessibility testing"
component={Button}
argTypes={{
backgroundColor: {
control: {
type: 'color',
}
}
}} />
<!--
👇 Render functions are a framework specific feature to allow you control on how the component renders.
See https://storybook.js.org/docs/7.0/svelte/api/csf
to learn how to use render functions.
-->
## This is an accessible story
<Story
name="Accessible"
args={{
primary: false,
label: 'Button'
}}
render={(args) => ({
Component: Button,
props: args,
})} />
## This is not
<Story
name="Inaccessible"
args={{
primary: false,
label: 'Button',
backgroundColor: 'red'
}}
render={(args) => ({
Component: Button,
props: args,
})} />
``` | docs/snippets/svelte/component-story-with-accessibility.mdx.mdx | 0 | https://github.com/storybookjs/storybook/commit/a8af64c05fd4595ddf5becf9d886100972bae925 | [
0.00017189887876156718,
0.00016906076052691787,
0.000164060402312316,
0.00016950767894741148,
0.000002614410732348915
] |
{
"id": 2,
"code_window": [
" }\n",
" },\n",
" \"engines\": {\n",
" \"node\": \">=10.13.0\"\n",
" },\n",
" \"publishConfig\": {\n",
" \"access\": \"public\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"node\": \"^14.18 || >=16\"\n"
],
"file_path": "code/frameworks/vue3-vite/package.json",
"type": "replace",
"edit_start_line_idx": 85
} | {
"name": "@storybook/react-vite",
"version": "7.0.0-alpha.26",
"description": "Storybook for React: Develop React Component in isolation with Hot Reloading.",
"keywords": [
"storybook"
],
"homepage": "https://github.com/storybookjs/storybook/tree/main/frameworks/react-vite",
"bugs": {
"url": "https://github.com/storybookjs/storybook/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/storybookjs/storybook.git",
"directory": "frameworks/react-vite"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/storybook"
},
"license": "MIT",
"exports": {
".": {
"require": "./dist/index.js",
"import": "./dist/index.mjs",
"types": "./dist/index.d.ts"
},
"./preset": {
"require": "./dist/preset.js",
"import": "./dist/preset.mjs",
"types": "./dist/preset.d.ts"
},
"./package.json": {
"require": "./package.json",
"import": "./package.json",
"types": "./package.json"
}
},
"main": "dist/index.js",
"module": "dist/index.mjs",
"types": "dist/index.d.ts",
"files": [
"dist/**/*",
"types/**/*",
"README.md",
"*.js",
"*.d.ts"
],
"scripts": {
"check": "tsc --noEmit",
"prepare": "../../../scripts/prepare/bundle.ts"
},
"dependencies": {
"@joshwooding/vite-plugin-react-docgen-typescript": "^0.0.5",
"@rollup/pluginutils": "^4.2.0",
"@storybook/builder-vite": "7.0.0-alpha.26",
"@storybook/core-server": "7.0.0-alpha.26",
"@storybook/react": "7.0.0-alpha.26",
"@vitejs/plugin-react": "^2.0.1",
"ast-types": "^0.14.2",
"magic-string": "^0.26.1",
"react-docgen": "^6.0.0-alpha.3"
},
"devDependencies": {
"@types/node": "^14.14.20 || ^16.0.0",
"typescript": "~4.6.3"
},
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0 || ^18.0.0",
"react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0"
},
"engines": {
"node": ">=10.13.0"
},
"publishConfig": {
"access": "public"
},
"bundler": {
"entries": [
"./src/index.ts",
"./src/preset.ts"
],
"platform": "node"
},
"gitHead": "e5c9cfe1d0482132e59734d9cfce57477045914f"
}
| code/frameworks/react-vite/package.json | 1 | https://github.com/storybookjs/storybook/commit/a8af64c05fd4595ddf5becf9d886100972bae925 | [
0.5903679728507996,
0.06574415415525436,
0.0001637798413867131,
0.0001662022405071184,
0.18548253178596497
] |
{
"id": 2,
"code_window": [
" }\n",
" },\n",
" \"engines\": {\n",
" \"node\": \">=10.13.0\"\n",
" },\n",
" \"publishConfig\": {\n",
" \"access\": \"public\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"node\": \"^14.18 || >=16\"\n"
],
"file_path": "code/frameworks/vue3-vite/package.json",
"type": "replace",
"edit_start_line_idx": 85
} | const fs = jest.createMockFromModule('fs');
// This is a custom function that our tests can use during setup to specify
// what the files on the "mock" filesystem should look like when any of the
// `fs` APIs are used.
let mockFiles = Object.create(null);
// eslint-disable-next-line no-underscore-dangle
function __setMockFiles(newMockFiles) {
mockFiles = newMockFiles;
}
// A custom version of `readdirSync` that reads from the special mocked out
// file list set via __setMockFiles
const readFileSync = (filePath = '') => mockFiles[filePath];
const existsSync = (filePath) => !!mockFiles[filePath];
const lstatSync = (filePath) => ({
isFile: () => !!mockFiles[filePath],
});
// eslint-disable-next-line no-underscore-dangle
fs.__setMockFiles = __setMockFiles;
fs.readFileSync = readFileSync;
fs.existsSync = existsSync;
fs.lstatSync = lstatSync;
module.exports = fs;
| code/__mocks__/fs.js | 0 | https://github.com/storybookjs/storybook/commit/a8af64c05fd4595ddf5becf9d886100972bae925 | [
0.0001704027090454474,
0.00016835896531119943,
0.00016726106696296483,
0.00016741311992518604,
0.0000014464776540989988
] |
{
"id": 2,
"code_window": [
" }\n",
" },\n",
" \"engines\": {\n",
" \"node\": \">=10.13.0\"\n",
" },\n",
" \"publishConfig\": {\n",
" \"access\": \"public\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"node\": \"^14.18 || >=16\"\n"
],
"file_path": "code/frameworks/vue3-vite/package.json",
"type": "replace",
"edit_start_line_idx": 85
} | const path = require('path');
const scriptPath = path.join(__dirname, '..', 'scripts');
module.exports = {
root: true,
extends: [path.join(scriptPath, '.eslintrc.js')],
overrides: [
{
// this package depends on a lot of peerDependencies we don't want to specify, because npm would install them
files: ['**/addons/docs/**/*'],
rules: {
'import/no-extraneous-dependencies': 'off',
},
},
{
// this package depends on a lot of peerDependencies we don't want to specify, because npm would install them
files: ['**/*.ts', '**/*.tsx'],
rules: {
'no-shadow': 'off',
'@typescript-eslint/ban-types': 'warn', // should become error, in the future
},
},
{
// this package uses pre-bundling, dependencies will be bundled, and will be in devDepenencies
files: [
'**/lib/theming/**/*',
'**/lib/router/**/*',
'**/lib/ui/**/*',
'**/lib/components/**/*',
],
rules: {
'import/no-extraneous-dependencies': ['error', { bundledDependencies: false }],
},
},
{
files: [
'**/__tests__/**',
'**/__testfixtures__/**',
'**/*.test.*',
'**/*.stories.*',
'**/storyshots/**/stories/**',
],
rules: {
'@typescript-eslint/no-empty-function': 'off',
'import/no-extraneous-dependencies': 'off',
},
},
{
files: ['**/__testfixtures__/**'],
rules: {
'react/forbid-prop-types': 'off',
'react/no-unused-prop-types': 'off',
'react/require-default-props': 'off',
},
},
{ files: '**/.storybook/config.js', rules: { 'global-require': 'off' } },
{ files: 'cypress/**', rules: { 'jest/expect-expect': 'off' } },
{
files: ['**/*.stories.*'],
rules: {
'no-console': 'off',
},
},
{
files: ['**/*.tsx', '**/*.ts'],
rules: {
'react/require-default-props': 'off',
'react/prop-types': 'off', // we should use types
'react/forbid-prop-types': 'off', // we should use types
'no-dupe-class-members': 'off', // this is called overloads in typescript
'react/no-unused-prop-types': 'off', // we should use types
'react/default-props-match-prop-types': 'off', // we should use types
'import/no-named-as-default': 'warn',
'import/no-named-as-default-member': 'warn',
'react/destructuring-assignment': 'warn',
// This warns about importing interfaces and types in a normal import, it's arguably better to import with the `type` prefix separate from the runtime imports,
// I leave this as a warning right now because we haven't really decided yet, and the codebase is riddled with errors if I set to 'error'.
// It IS set to 'error' for JS files.
'import/named': 'warn',
},
},
{
files: ['**/*.d.ts'],
rules: {
'vars-on-top': 'off',
'no-var': 'off', // this is how typescript works
'spaced-comment': 'off',
},
},
{
files: ['**/mithril/**/*'],
rules: {
'react/no-unknown-property': 'off', // Need to deactivate otherwise eslint replaces some unknown properties with React ones
},
},
{
files: ['**/e2e-tests/**/*'],
rules: {
'jest/no-test-callback': 'off', // These aren't jest tests
},
},
{
files: ['**/builder-vite/input/iframe.html'],
rules: {
'no-undef': 'off', // ignore "window" undef errors
},
},
],
};
| code/.eslintrc.js | 0 | https://github.com/storybookjs/storybook/commit/a8af64c05fd4595ddf5becf9d886100972bae925 | [
0.00017014813784044236,
0.0001678828994045034,
0.00016461277846246958,
0.00016875055734999478,
0.0000017968017118619173
] |
{
"id": 2,
"code_window": [
" }\n",
" },\n",
" \"engines\": {\n",
" \"node\": \">=10.13.0\"\n",
" },\n",
" \"publishConfig\": {\n",
" \"access\": \"public\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"node\": \"^14.18 || >=16\"\n"
],
"file_path": "code/frameworks/vue3-vite/package.json",
"type": "replace",
"edit_start_line_idx": 85
} | import type { StoryContext as DefaultStoryContext } from '@storybook/csf';
import { parameters } from './config';
export type { RenderContext } from '@storybook/core-client';
export type StoryFnHtmlReturnType = string | Node;
export interface IStorybookStory {
name: string;
render: (context: any) => any;
}
export interface IStorybookSection {
kind: string;
stories: IStorybookStory[];
}
export interface ShowErrorArgs {
title: string;
description: string;
}
export type HtmlFramework = {
component: HTMLElement;
storyResult: StoryFnHtmlReturnType;
};
export type StoryContext = DefaultStoryContext<HtmlFramework> & {
parameters: DefaultStoryContext<HtmlFramework>['parameters'] & typeof parameters;
};
| code/renderers/html/src/types.ts | 0 | https://github.com/storybookjs/storybook/commit/a8af64c05fd4595ddf5becf9d886100972bae925 | [
0.00017028869478963315,
0.00016823230544105172,
0.00016715456149540842,
0.00016774299729149789,
0.000001216517944158113
] |
{
"id": 0,
"code_window": [
"\n",
"\t// Global methods\n",
"\topenWindow(windowId: number, uris: IURIToOpen[], options: IOpenSettings): Promise<void>;\n",
"\topenExtensionDevelopmentHostWindow(args: ParsedArgs, env: IProcessEnvironment): Promise<void>;\n",
"\tgetWindows(): Promise<{ id: number; workspace?: IWorkspaceIdentifier; folderUri?: ISingleFolderWorkspaceIdentifier; title: string; filename?: string; }[]>;\n",
"\tgetActiveWindowId(): Promise<number | undefined>;\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/platform/windows/common/windows.ts",
"type": "replace",
"edit_start_line_idx": 99
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { IExtensionHostDebugService } from 'vs/platform/debug/common/extensionHostDebug';
import { IMainProcessService } from 'vs/platform/ipc/electron-browser/mainProcessService';
import { ExtensionHostDebugChannelClient, ExtensionHostDebugBroadcastChannel } from 'vs/platform/debug/common/extensionHostDebugIpc';
import { IWindowsService } from 'vs/platform/windows/common/windows';
import { IProcessEnvironment } from 'vs/base/common/platform';
import { ParsedArgs } from 'vs/platform/environment/common/environment';
export class ExtensionHostDebugService extends ExtensionHostDebugChannelClient {
constructor(
@IMainProcessService readonly mainProcessService: IMainProcessService,
@IWindowsService private readonly windowsService: IWindowsService
) {
super(mainProcessService.getChannel(ExtensionHostDebugBroadcastChannel.ChannelName));
}
openExtensionDevelopmentHostWindow(args: ParsedArgs, env: IProcessEnvironment): Promise<void> {
// TODO@Isidor use debug IPC channel
return this.windowsService.openExtensionDevelopmentHostWindow(args, env);
}
}
registerSingleton(IExtensionHostDebugService, ExtensionHostDebugService, true);
| src/vs/workbench/contrib/debug/electron-browser/extensionHostDebugService.ts | 1 | https://github.com/microsoft/vscode/commit/23f2275c23aeebf5e22f3d19a20528c8ba48c570 | [
0.9849506616592407,
0.32846927642822266,
0.00017399282660335302,
0.00028317159740254283,
0.4642024338245392
] |
{
"id": 0,
"code_window": [
"\n",
"\t// Global methods\n",
"\topenWindow(windowId: number, uris: IURIToOpen[], options: IOpenSettings): Promise<void>;\n",
"\topenExtensionDevelopmentHostWindow(args: ParsedArgs, env: IProcessEnvironment): Promise<void>;\n",
"\tgetWindows(): Promise<{ id: number; workspace?: IWorkspaceIdentifier; folderUri?: ISingleFolderWorkspaceIdentifier; title: string; filename?: string; }[]>;\n",
"\tgetActiveWindowId(): Promise<number | undefined>;\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/platform/windows/common/windows.ts",
"type": "replace",
"edit_start_line_idx": 99
} | /*---------------------------------------------------------------------------------------------
* 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 { Event } from 'vs/base/common/event';
import { Range } from 'vs/editor/common/core/range';
import { Selection } from 'vs/editor/common/core/selection';
import { Handler } from 'vs/editor/common/editorCommon';
import { EndOfLineSequence } from 'vs/editor/common/model';
import { CommonFindController } from 'vs/editor/contrib/find/findController';
import { AddSelectionToNextFindMatchAction, InsertCursorAbove, InsertCursorBelow, MultiCursorSelectionController, SelectHighlightsAction } from 'vs/editor/contrib/multicursor/multicursor';
import { TestCodeEditor, withTestCodeEditor } from 'vs/editor/test/browser/testCodeEditor';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { IStorageService } from 'vs/platform/storage/common/storage';
suite('Multicursor', () => {
test('issue #2205: Multi-cursor pastes in reverse order', () => {
withTestCodeEditor([
'abc',
'def'
], {}, (editor, cursor) => {
let addCursorUpAction = new InsertCursorAbove();
editor.setSelection(new Selection(2, 1, 2, 1));
addCursorUpAction.run(null!, editor, {});
assert.equal(cursor.getSelections().length, 2);
editor.trigger('test', Handler.Paste, {
text: '1\n2',
multicursorText: [
'1',
'2'
]
});
// cursorCommand(cursor, H.Paste, { text: '1\n2' });
assert.equal(editor.getModel()!.getLineContent(1), '1abc');
assert.equal(editor.getModel()!.getLineContent(2), '2def');
});
});
test('issue #1336: Insert cursor below on last line adds a cursor to the end of the current line', () => {
withTestCodeEditor([
'abc'
], {}, (editor, cursor) => {
let addCursorDownAction = new InsertCursorBelow();
addCursorDownAction.run(null!, editor, {});
assert.equal(cursor.getSelections().length, 1);
});
});
});
function fromRange(rng: Range): number[] {
return [rng.startLineNumber, rng.startColumn, rng.endLineNumber, rng.endColumn];
}
suite('Multicursor selection', () => {
let queryState: { [key: string]: any; } = {};
let serviceCollection = new ServiceCollection();
serviceCollection.set(IStorageService, {
_serviceBrand: undefined,
onDidChangeStorage: Event.None,
onWillSaveState: Event.None,
get: (key: string) => queryState[key],
getBoolean: (key: string) => !!queryState[key],
getNumber: (key: string) => undefined!,
store: (key: string, value: any) => { queryState[key] = value; return Promise.resolve(); },
remove: (key) => undefined,
logStorage: () => undefined,
migrate: (toWorkspace) => Promise.resolve(undefined)
} as IStorageService);
test('issue #8817: Cursor position changes when you cancel multicursor', () => {
withTestCodeEditor([
'var x = (3 * 5)',
'var y = (3 * 5)',
'var z = (3 * 5)',
], { serviceCollection: serviceCollection }, (editor, cursor) => {
let findController = editor.registerAndInstantiateContribution<CommonFindController>(CommonFindController);
let multiCursorSelectController = editor.registerAndInstantiateContribution<MultiCursorSelectionController>(MultiCursorSelectionController);
let selectHighlightsAction = new SelectHighlightsAction();
editor.setSelection(new Selection(2, 9, 2, 16));
selectHighlightsAction.run(null!, editor);
assert.deepEqual(editor.getSelections()!.map(fromRange), [
[2, 9, 2, 16],
[1, 9, 1, 16],
[3, 9, 3, 16],
]);
editor.trigger('test', 'removeSecondaryCursors', null);
assert.deepEqual(fromRange(editor.getSelection()!), [2, 9, 2, 16]);
multiCursorSelectController.dispose();
findController.dispose();
});
});
test('issue #5400: "Select All Occurrences of Find Match" does not select all if find uses regex', () => {
withTestCodeEditor([
'something',
'someething',
'someeething',
'nothing'
], { serviceCollection: serviceCollection }, (editor, cursor) => {
let findController = editor.registerAndInstantiateContribution<CommonFindController>(CommonFindController);
let multiCursorSelectController = editor.registerAndInstantiateContribution<MultiCursorSelectionController>(MultiCursorSelectionController);
let selectHighlightsAction = new SelectHighlightsAction();
editor.setSelection(new Selection(1, 1, 1, 1));
findController.getState().change({ searchString: 'some+thing', isRegex: true, isRevealed: true }, false);
selectHighlightsAction.run(null!, editor);
assert.deepEqual(editor.getSelections()!.map(fromRange), [
[1, 1, 1, 10],
[2, 1, 2, 11],
[3, 1, 3, 12],
]);
assert.equal(findController.getState().searchString, 'some+thing');
multiCursorSelectController.dispose();
findController.dispose();
});
});
test('AddSelectionToNextFindMatchAction can work with multiline', () => {
withTestCodeEditor([
'',
'qwe',
'rty',
'',
'qwe',
'',
'rty',
'qwe',
'rty'
], { serviceCollection: serviceCollection }, (editor, cursor) => {
let findController = editor.registerAndInstantiateContribution<CommonFindController>(CommonFindController);
let multiCursorSelectController = editor.registerAndInstantiateContribution<MultiCursorSelectionController>(MultiCursorSelectionController);
let addSelectionToNextFindMatch = new AddSelectionToNextFindMatchAction();
editor.setSelection(new Selection(2, 1, 3, 4));
addSelectionToNextFindMatch.run(null!, editor);
assert.deepEqual(editor.getSelections()!.map(fromRange), [
[2, 1, 3, 4],
[8, 1, 9, 4]
]);
editor.trigger('test', 'removeSecondaryCursors', null);
assert.deepEqual(fromRange(editor.getSelection()!), [2, 1, 3, 4]);
multiCursorSelectController.dispose();
findController.dispose();
});
});
test('issue #6661: AddSelectionToNextFindMatchAction can work with touching ranges', () => {
withTestCodeEditor([
'abcabc',
'abc',
'abcabc',
], { serviceCollection: serviceCollection }, (editor, cursor) => {
let findController = editor.registerAndInstantiateContribution<CommonFindController>(CommonFindController);
let multiCursorSelectController = editor.registerAndInstantiateContribution<MultiCursorSelectionController>(MultiCursorSelectionController);
let addSelectionToNextFindMatch = new AddSelectionToNextFindMatchAction();
editor.setSelection(new Selection(1, 1, 1, 4));
addSelectionToNextFindMatch.run(null!, editor);
assert.deepEqual(editor.getSelections()!.map(fromRange), [
[1, 1, 1, 4],
[1, 4, 1, 7]
]);
addSelectionToNextFindMatch.run(null!, editor);
addSelectionToNextFindMatch.run(null!, editor);
addSelectionToNextFindMatch.run(null!, editor);
assert.deepEqual(editor.getSelections()!.map(fromRange), [
[1, 1, 1, 4],
[1, 4, 1, 7],
[2, 1, 2, 4],
[3, 1, 3, 4],
[3, 4, 3, 7]
]);
editor.trigger('test', Handler.Type, { text: 'z' });
assert.deepEqual(editor.getSelections()!.map(fromRange), [
[1, 2, 1, 2],
[1, 3, 1, 3],
[2, 2, 2, 2],
[3, 2, 3, 2],
[3, 3, 3, 3]
]);
assert.equal(editor.getValue(), [
'zz',
'z',
'zz',
].join('\n'));
multiCursorSelectController.dispose();
findController.dispose();
});
});
test('issue #23541: Multiline Ctrl+D does not work in CRLF files', () => {
withTestCodeEditor([
'',
'qwe',
'rty',
'',
'qwe',
'',
'rty',
'qwe',
'rty'
], { serviceCollection: serviceCollection }, (editor, cursor) => {
editor.getModel()!.setEOL(EndOfLineSequence.CRLF);
let findController = editor.registerAndInstantiateContribution<CommonFindController>(CommonFindController);
let multiCursorSelectController = editor.registerAndInstantiateContribution<MultiCursorSelectionController>(MultiCursorSelectionController);
let addSelectionToNextFindMatch = new AddSelectionToNextFindMatchAction();
editor.setSelection(new Selection(2, 1, 3, 4));
addSelectionToNextFindMatch.run(null!, editor);
assert.deepEqual(editor.getSelections()!.map(fromRange), [
[2, 1, 3, 4],
[8, 1, 9, 4]
]);
editor.trigger('test', 'removeSecondaryCursors', null);
assert.deepEqual(fromRange(editor.getSelection()!), [2, 1, 3, 4]);
multiCursorSelectController.dispose();
findController.dispose();
});
});
function testMulticursor(text: string[], callback: (editor: TestCodeEditor, findController: CommonFindController) => void): void {
withTestCodeEditor(text, { serviceCollection: serviceCollection }, (editor, cursor) => {
let findController = editor.registerAndInstantiateContribution<CommonFindController>(CommonFindController);
let multiCursorSelectController = editor.registerAndInstantiateContribution<MultiCursorSelectionController>(MultiCursorSelectionController);
callback(editor, findController);
multiCursorSelectController.dispose();
findController.dispose();
});
}
function testAddSelectionToNextFindMatchAction(text: string[], callback: (editor: TestCodeEditor, action: AddSelectionToNextFindMatchAction, findController: CommonFindController) => void): void {
testMulticursor(text, (editor, findController) => {
let action = new AddSelectionToNextFindMatchAction();
callback(editor, action, findController);
});
}
test('AddSelectionToNextFindMatchAction starting with single collapsed selection', () => {
const text = [
'abc pizza',
'abc house',
'abc bar'
];
testAddSelectionToNextFindMatchAction(text, (editor, action, findController) => {
editor.setSelections([
new Selection(1, 2, 1, 2),
]);
action.run(null!, editor);
assert.deepEqual(editor.getSelections(), [
new Selection(1, 1, 1, 4),
]);
action.run(null!, editor);
assert.deepEqual(editor.getSelections(), [
new Selection(1, 1, 1, 4),
new Selection(2, 1, 2, 4),
]);
action.run(null!, editor);
assert.deepEqual(editor.getSelections(), [
new Selection(1, 1, 1, 4),
new Selection(2, 1, 2, 4),
new Selection(3, 1, 3, 4),
]);
action.run(null!, editor);
assert.deepEqual(editor.getSelections(), [
new Selection(1, 1, 1, 4),
new Selection(2, 1, 2, 4),
new Selection(3, 1, 3, 4),
]);
});
});
test('AddSelectionToNextFindMatchAction starting with two selections, one being collapsed 1)', () => {
const text = [
'abc pizza',
'abc house',
'abc bar'
];
testAddSelectionToNextFindMatchAction(text, (editor, action, findController) => {
editor.setSelections([
new Selection(1, 1, 1, 4),
new Selection(2, 2, 2, 2),
]);
action.run(null!, editor);
assert.deepEqual(editor.getSelections(), [
new Selection(1, 1, 1, 4),
new Selection(2, 1, 2, 4),
]);
action.run(null!, editor);
assert.deepEqual(editor.getSelections(), [
new Selection(1, 1, 1, 4),
new Selection(2, 1, 2, 4),
new Selection(3, 1, 3, 4),
]);
action.run(null!, editor);
assert.deepEqual(editor.getSelections(), [
new Selection(1, 1, 1, 4),
new Selection(2, 1, 2, 4),
new Selection(3, 1, 3, 4),
]);
});
});
test('AddSelectionToNextFindMatchAction starting with two selections, one being collapsed 2)', () => {
const text = [
'abc pizza',
'abc house',
'abc bar'
];
testAddSelectionToNextFindMatchAction(text, (editor, action, findController) => {
editor.setSelections([
new Selection(1, 2, 1, 2),
new Selection(2, 1, 2, 4),
]);
action.run(null!, editor);
assert.deepEqual(editor.getSelections(), [
new Selection(1, 1, 1, 4),
new Selection(2, 1, 2, 4),
]);
action.run(null!, editor);
assert.deepEqual(editor.getSelections(), [
new Selection(1, 1, 1, 4),
new Selection(2, 1, 2, 4),
new Selection(3, 1, 3, 4),
]);
action.run(null!, editor);
assert.deepEqual(editor.getSelections(), [
new Selection(1, 1, 1, 4),
new Selection(2, 1, 2, 4),
new Selection(3, 1, 3, 4),
]);
});
});
test('AddSelectionToNextFindMatchAction starting with all collapsed selections', () => {
const text = [
'abc pizza',
'abc house',
'abc bar'
];
testAddSelectionToNextFindMatchAction(text, (editor, action, findController) => {
editor.setSelections([
new Selection(1, 2, 1, 2),
new Selection(2, 2, 2, 2),
new Selection(3, 1, 3, 1),
]);
action.run(null!, editor);
assert.deepEqual(editor.getSelections(), [
new Selection(1, 1, 1, 4),
new Selection(2, 1, 2, 4),
new Selection(3, 1, 3, 4),
]);
action.run(null!, editor);
assert.deepEqual(editor.getSelections(), [
new Selection(1, 1, 1, 4),
new Selection(2, 1, 2, 4),
new Selection(3, 1, 3, 4),
]);
});
});
test('AddSelectionToNextFindMatchAction starting with all collapsed selections on different words', () => {
const text = [
'abc pizza',
'abc house',
'abc bar'
];
testAddSelectionToNextFindMatchAction(text, (editor, action, findController) => {
editor.setSelections([
new Selection(1, 6, 1, 6),
new Selection(2, 6, 2, 6),
new Selection(3, 6, 3, 6),
]);
action.run(null!, editor);
assert.deepEqual(editor.getSelections(), [
new Selection(1, 5, 1, 10),
new Selection(2, 5, 2, 10),
new Selection(3, 5, 3, 8),
]);
action.run(null!, editor);
assert.deepEqual(editor.getSelections(), [
new Selection(1, 5, 1, 10),
new Selection(2, 5, 2, 10),
new Selection(3, 5, 3, 8),
]);
});
});
test('issue #20651: AddSelectionToNextFindMatchAction case insensitive', () => {
const text = [
'test',
'testte',
'Test',
'testte',
'test'
];
testAddSelectionToNextFindMatchAction(text, (editor, action, findController) => {
editor.setSelections([
new Selection(1, 1, 1, 5),
]);
action.run(null!, editor);
assert.deepEqual(editor.getSelections(), [
new Selection(1, 1, 1, 5),
new Selection(2, 1, 2, 5),
]);
action.run(null!, editor);
assert.deepEqual(editor.getSelections(), [
new Selection(1, 1, 1, 5),
new Selection(2, 1, 2, 5),
new Selection(3, 1, 3, 5),
]);
action.run(null!, editor);
assert.deepEqual(editor.getSelections(), [
new Selection(1, 1, 1, 5),
new Selection(2, 1, 2, 5),
new Selection(3, 1, 3, 5),
new Selection(4, 1, 4, 5),
]);
action.run(null!, editor);
assert.deepEqual(editor.getSelections(), [
new Selection(1, 1, 1, 5),
new Selection(2, 1, 2, 5),
new Selection(3, 1, 3, 5),
new Selection(4, 1, 4, 5),
new Selection(5, 1, 5, 5),
]);
action.run(null!, editor);
assert.deepEqual(editor.getSelections(), [
new Selection(1, 1, 1, 5),
new Selection(2, 1, 2, 5),
new Selection(3, 1, 3, 5),
new Selection(4, 1, 4, 5),
new Selection(5, 1, 5, 5),
]);
});
});
suite('Find state disassociation', () => {
const text = [
'app',
'apples',
'whatsapp',
'app',
'App',
' app'
];
test('enters mode', () => {
testAddSelectionToNextFindMatchAction(text, (editor, action, findController) => {
editor.setSelections([
new Selection(1, 2, 1, 2),
]);
action.run(null!, editor);
assert.deepEqual(editor.getSelections(), [
new Selection(1, 1, 1, 4),
]);
action.run(null!, editor);
assert.deepEqual(editor.getSelections(), [
new Selection(1, 1, 1, 4),
new Selection(4, 1, 4, 4),
]);
action.run(null!, editor);
assert.deepEqual(editor.getSelections(), [
new Selection(1, 1, 1, 4),
new Selection(4, 1, 4, 4),
new Selection(6, 2, 6, 5),
]);
});
});
test('leaves mode when selection changes', () => {
testAddSelectionToNextFindMatchAction(text, (editor, action, findController) => {
editor.setSelections([
new Selection(1, 2, 1, 2),
]);
action.run(null!, editor);
assert.deepEqual(editor.getSelections(), [
new Selection(1, 1, 1, 4),
]);
action.run(null!, editor);
assert.deepEqual(editor.getSelections(), [
new Selection(1, 1, 1, 4),
new Selection(4, 1, 4, 4),
]);
// change selection
editor.setSelections([
new Selection(1, 1, 1, 4),
]);
action.run(null!, editor);
assert.deepEqual(editor.getSelections(), [
new Selection(1, 1, 1, 4),
new Selection(2, 1, 2, 4),
]);
});
});
test('Select Highlights respects mode ', () => {
testMulticursor(text, (editor, findController) => {
let action = new SelectHighlightsAction();
editor.setSelections([
new Selection(1, 2, 1, 2),
]);
action.run(null!, editor);
assert.deepEqual(editor.getSelections(), [
new Selection(1, 1, 1, 4),
new Selection(4, 1, 4, 4),
new Selection(6, 2, 6, 5),
]);
action.run(null!, editor);
assert.deepEqual(editor.getSelections(), [
new Selection(1, 1, 1, 4),
new Selection(4, 1, 4, 4),
new Selection(6, 2, 6, 5),
]);
});
});
});
});
| src/vs/editor/contrib/multicursor/test/multicursor.test.ts | 0 | https://github.com/microsoft/vscode/commit/23f2275c23aeebf5e22f3d19a20528c8ba48c570 | [
0.0001791128161130473,
0.0001764893386280164,
0.00016193969349842519,
0.00017711088003125042,
0.000002588629740785109
] |
{
"id": 0,
"code_window": [
"\n",
"\t// Global methods\n",
"\topenWindow(windowId: number, uris: IURIToOpen[], options: IOpenSettings): Promise<void>;\n",
"\topenExtensionDevelopmentHostWindow(args: ParsedArgs, env: IProcessEnvironment): Promise<void>;\n",
"\tgetWindows(): Promise<{ id: number; workspace?: IWorkspaceIdentifier; folderUri?: ISingleFolderWorkspaceIdentifier; title: string; filename?: string; }[]>;\n",
"\tgetActiveWindowId(): Promise<number | undefined>;\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/platform/windows/common/windows.ts",
"type": "replace",
"edit_start_line_idx": 99
} | {
"Insert bold text": {
"prefix": "bold",
"body": "**${1:${TM_SELECTED_TEXT}}**$0",
"description": "Insert bold text"
},
"Insert italic text": {
"prefix": "italic",
"body": "*${1:${TM_SELECTED_TEXT}}*$0",
"description": "Insert italic text"
},
"Insert quoted text": {
"prefix": "quote",
"body": "> ${1:${TM_SELECTED_TEXT}}",
"description": "Insert quoted text"
},
"Insert code": {
"prefix": "code",
"body": "`${1:${TM_SELECTED_TEXT}}`$0",
"description": "Insert code"
},
"Insert fenced code block": {
"prefix": "fenced codeblock",
"body": [
"```${1:language}",
"${TM_SELECTED_TEXT}$0",
"```"
],
"description": "Insert fenced code block"
},
"Insert heading": {
"prefix": "heading",
"body": "# ${1:${TM_SELECTED_TEXT}}",
"description": "Insert heading"
},
"Insert unordered list": {
"prefix": "unordered list",
"body": [
"- ${1:first}",
"- ${2:second}",
"- ${3:third}",
"$0"
],
"description": "Insert unordered list"
},
"Insert ordered list": {
"prefix": "ordered list",
"body": [
"1. ${1:first}",
"2. ${2:second}",
"3. ${3:third}",
"$0"
],
"description": "Insert ordered list"
},
"Insert horizontal rule": {
"prefix": "horizontal rule",
"body": "----------\n",
"description": "Insert horizontal rule"
},
"Insert link": {
"prefix": "link",
"body": "[${TM_SELECTED_TEXT:${1:text}}](https://${2:link})$0",
"description": "Insert link"
},
"Insert image": {
"prefix": "image",
"body": "$0",
"description": "Insert image"
}
}
| extensions/markdown-basics/snippets/markdown.json | 0 | https://github.com/microsoft/vscode/commit/23f2275c23aeebf5e22f3d19a20528c8ba48c570 | [
0.00017792877042666078,
0.0001761879975674674,
0.000174028828041628,
0.00017607116024009883,
0.0000012250179679540452
] |
{
"id": 0,
"code_window": [
"\n",
"\t// Global methods\n",
"\topenWindow(windowId: number, uris: IURIToOpen[], options: IOpenSettings): Promise<void>;\n",
"\topenExtensionDevelopmentHostWindow(args: ParsedArgs, env: IProcessEnvironment): Promise<void>;\n",
"\tgetWindows(): Promise<{ id: number; workspace?: IWorkspaceIdentifier; folderUri?: ISingleFolderWorkspaceIdentifier; title: string; filename?: string; }[]>;\n",
"\tgetActiveWindowId(): Promise<number | undefined>;\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/platform/windows/common/windows.ts",
"type": "replace",
"edit_start_line_idx": 99
} | [
{
"c": "#!",
"t": "source.shell comment.line.number-sign.shebang.shell punctuation.definition.comment.shebang.shell",
"r": {
"dark_plus": "comment: #6A9955",
"light_plus": "comment: #008000",
"dark_vs": "comment: #6A9955",
"light_vs": "comment: #008000",
"hc_black": "comment: #7CA668"
}
},
{
"c": "/usr/bin/env bash",
"t": "source.shell comment.line.number-sign.shebang.shell",
"r": {
"dark_plus": "comment: #6A9955",
"light_plus": "comment: #008000",
"dark_vs": "comment: #6A9955",
"light_vs": "comment: #008000",
"hc_black": "comment: #7CA668"
}
},
{
"c": "if",
"t": "source.shell meta.scope.if-block.shell keyword.control.shell",
"r": {
"dark_plus": "keyword.control: #C586C0",
"light_plus": "keyword.control: #AF00DB",
"dark_vs": "keyword.control: #569CD6",
"light_vs": "keyword.control: #0000FF",
"hc_black": "keyword.control: #C586C0"
}
},
{
"c": " ",
"t": "source.shell meta.scope.if-block.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "[[",
"t": "source.shell meta.scope.if-block.shell meta.scope.logical-expression.shell punctuation.definition.logical-expression.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": " ",
"t": "source.shell meta.scope.if-block.shell meta.scope.logical-expression.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "\"",
"t": "source.shell meta.scope.if-block.shell meta.scope.logical-expression.shell string.quoted.double.shell punctuation.definition.string.begin.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "$",
"t": "source.shell meta.scope.if-block.shell meta.scope.logical-expression.shell string.quoted.double.shell variable.other.normal.shell punctuation.definition.variable.shell",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "variable: #9CDCFE"
}
},
{
"c": "OSTYPE",
"t": "source.shell meta.scope.if-block.shell meta.scope.logical-expression.shell string.quoted.double.shell variable.other.normal.shell",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "variable: #9CDCFE"
}
},
{
"c": "\"",
"t": "source.shell meta.scope.if-block.shell meta.scope.logical-expression.shell string.quoted.double.shell punctuation.definition.string.end.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": " ",
"t": "source.shell meta.scope.if-block.shell meta.scope.logical-expression.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "==",
"t": "source.shell meta.scope.if-block.shell meta.scope.logical-expression.shell keyword.operator.logical.shell",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4"
}
},
{
"c": " ",
"t": "source.shell meta.scope.if-block.shell meta.scope.logical-expression.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "\"",
"t": "source.shell meta.scope.if-block.shell meta.scope.logical-expression.shell string.quoted.double.shell punctuation.definition.string.begin.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "darwin",
"t": "source.shell meta.scope.if-block.shell meta.scope.logical-expression.shell string.quoted.double.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "\"",
"t": "source.shell meta.scope.if-block.shell meta.scope.logical-expression.shell string.quoted.double.shell punctuation.definition.string.end.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "*",
"t": "source.shell meta.scope.if-block.shell meta.scope.logical-expression.shell keyword.operator.glob.shell",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4"
}
},
{
"c": " ",
"t": "source.shell meta.scope.if-block.shell meta.scope.logical-expression.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "]]",
"t": "source.shell meta.scope.if-block.shell meta.scope.logical-expression.shell punctuation.definition.logical-expression.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": ";",
"t": "source.shell meta.scope.if-block.shell keyword.operator.list.shell",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4"
}
},
{
"c": " ",
"t": "source.shell meta.scope.if-block.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "then",
"t": "source.shell meta.scope.if-block.shell keyword.control.shell",
"r": {
"dark_plus": "keyword.control: #C586C0",
"light_plus": "keyword.control: #AF00DB",
"dark_vs": "keyword.control: #569CD6",
"light_vs": "keyword.control: #0000FF",
"hc_black": "keyword.control: #C586C0"
}
},
{
"c": "\t",
"t": "source.shell meta.scope.if-block.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "realpath",
"t": "source.shell meta.scope.if-block.shell meta.function.shell entity.name.function.shell",
"r": {
"dark_plus": "entity.name.function: #DCDCAA",
"light_plus": "entity.name.function: #795E26",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.function: #DCDCAA"
}
},
{
"c": "()",
"t": "source.shell meta.scope.if-block.shell meta.function.shell punctuation.definition.arguments.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": " ",
"t": "source.shell meta.scope.if-block.shell meta.function.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "{",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell punctuation.definition.group.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": " ",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "[[",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell meta.scope.logical-expression.shell punctuation.definition.logical-expression.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": " ",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell meta.scope.logical-expression.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "$",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell meta.scope.logical-expression.shell variable.other.positional.shell punctuation.definition.variable.shell",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "variable: #9CDCFE"
}
},
{
"c": "1",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell meta.scope.logical-expression.shell variable.other.positional.shell",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "variable: #9CDCFE"
}
},
{
"c": " ",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell meta.scope.logical-expression.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "=",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell meta.scope.logical-expression.shell keyword.operator.logical.shell",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4"
}
},
{
"c": " /",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell meta.scope.logical-expression.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "*",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell meta.scope.logical-expression.shell keyword.operator.glob.shell",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4"
}
},
{
"c": " ",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell meta.scope.logical-expression.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "]]",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell meta.scope.logical-expression.shell punctuation.definition.logical-expression.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": " ",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "&&",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell keyword.operator.list.shell",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4"
}
},
{
"c": " ",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "echo",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell support.function.builtin.shell",
"r": {
"dark_plus": "support.function: #DCDCAA",
"light_plus": "support.function: #795E26",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "support.function: #DCDCAA"
}
},
{
"c": " ",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "\"",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell string.quoted.double.shell punctuation.definition.string.begin.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "$",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell string.quoted.double.shell variable.other.positional.shell punctuation.definition.variable.shell",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "variable: #9CDCFE"
}
},
{
"c": "1",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell string.quoted.double.shell variable.other.positional.shell",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "variable: #9CDCFE"
}
},
{
"c": "\"",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell string.quoted.double.shell punctuation.definition.string.end.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": " ",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "||",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell keyword.operator.pipe.shell",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4"
}
},
{
"c": " ",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "echo",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell support.function.builtin.shell",
"r": {
"dark_plus": "support.function: #DCDCAA",
"light_plus": "support.function: #795E26",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "support.function: #DCDCAA"
}
},
{
"c": " ",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "\"",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell string.quoted.double.shell punctuation.definition.string.begin.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "$",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell string.quoted.double.shell variable.other.normal.shell punctuation.definition.variable.shell",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "variable: #9CDCFE"
}
},
{
"c": "PWD",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell string.quoted.double.shell variable.other.normal.shell",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "variable: #9CDCFE"
}
},
{
"c": "/",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell string.quoted.double.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "${",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell string.quoted.double.shell variable.other.bracket.shell punctuation.definition.variable.shell",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "variable: #9CDCFE"
}
},
{
"c": "1",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell string.quoted.double.shell variable.other.bracket.shell",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "variable: #9CDCFE"
}
},
{
"c": "#",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell string.quoted.double.shell variable.other.bracket.shell keyword.operator.expansion.shell",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4"
}
},
{
"c": ".",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell string.quoted.double.shell variable.other.bracket.shell",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "variable: #9CDCFE"
}
},
{
"c": "/",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell string.quoted.double.shell variable.other.bracket.shell keyword.operator.expansion.shell",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4"
}
},
{
"c": "}",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell string.quoted.double.shell variable.other.bracket.shell punctuation.definition.variable.shell",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "variable: #9CDCFE"
}
},
{
"c": "\"",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell string.quoted.double.shell punctuation.definition.string.end.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": ";",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell keyword.operator.list.shell",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4"
}
},
{
"c": " ",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "}",
"t": "source.shell meta.scope.if-block.shell meta.function.shell meta.scope.group.shell punctuation.definition.group.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "\tROOT=",
"t": "source.shell meta.scope.if-block.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "$(",
"t": "source.shell meta.scope.if-block.shell string.interpolated.dollar.shell punctuation.definition.string.begin.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "dirname ",
"t": "source.shell meta.scope.if-block.shell string.interpolated.dollar.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "$(",
"t": "source.shell meta.scope.if-block.shell string.interpolated.dollar.shell string.interpolated.dollar.shell punctuation.definition.string.begin.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "dirname ",
"t": "source.shell meta.scope.if-block.shell string.interpolated.dollar.shell string.interpolated.dollar.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "$(",
"t": "source.shell meta.scope.if-block.shell string.interpolated.dollar.shell string.interpolated.dollar.shell string.interpolated.dollar.shell punctuation.definition.string.begin.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "realpath ",
"t": "source.shell meta.scope.if-block.shell string.interpolated.dollar.shell string.interpolated.dollar.shell string.interpolated.dollar.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "\"",
"t": "source.shell meta.scope.if-block.shell string.interpolated.dollar.shell string.interpolated.dollar.shell string.interpolated.dollar.shell string.quoted.double.shell punctuation.definition.string.begin.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "$",
"t": "source.shell meta.scope.if-block.shell string.interpolated.dollar.shell string.interpolated.dollar.shell string.interpolated.dollar.shell string.quoted.double.shell variable.other.special.shell punctuation.definition.variable.shell",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "variable: #9CDCFE"
}
},
{
"c": "0",
"t": "source.shell meta.scope.if-block.shell string.interpolated.dollar.shell string.interpolated.dollar.shell string.interpolated.dollar.shell string.quoted.double.shell variable.other.special.shell",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "variable: #9CDCFE"
}
},
{
"c": "\"",
"t": "source.shell meta.scope.if-block.shell string.interpolated.dollar.shell string.interpolated.dollar.shell string.interpolated.dollar.shell string.quoted.double.shell punctuation.definition.string.end.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": ")",
"t": "source.shell meta.scope.if-block.shell string.interpolated.dollar.shell string.interpolated.dollar.shell string.interpolated.dollar.shell punctuation.definition.string.end.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": ")",
"t": "source.shell meta.scope.if-block.shell string.interpolated.dollar.shell string.interpolated.dollar.shell punctuation.definition.string.end.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": ")",
"t": "source.shell meta.scope.if-block.shell string.interpolated.dollar.shell punctuation.definition.string.end.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "else",
"t": "source.shell meta.scope.if-block.shell keyword.control.shell",
"r": {
"dark_plus": "keyword.control: #C586C0",
"light_plus": "keyword.control: #AF00DB",
"dark_vs": "keyword.control: #569CD6",
"light_vs": "keyword.control: #0000FF",
"hc_black": "keyword.control: #C586C0"
}
},
{
"c": "\tROOT=",
"t": "source.shell meta.scope.if-block.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "$(",
"t": "source.shell meta.scope.if-block.shell string.interpolated.dollar.shell punctuation.definition.string.begin.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "dirname ",
"t": "source.shell meta.scope.if-block.shell string.interpolated.dollar.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "$(",
"t": "source.shell meta.scope.if-block.shell string.interpolated.dollar.shell string.interpolated.dollar.shell punctuation.definition.string.begin.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "dirname ",
"t": "source.shell meta.scope.if-block.shell string.interpolated.dollar.shell string.interpolated.dollar.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "$(",
"t": "source.shell meta.scope.if-block.shell string.interpolated.dollar.shell string.interpolated.dollar.shell string.interpolated.dollar.shell punctuation.definition.string.begin.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "readlink -f ",
"t": "source.shell meta.scope.if-block.shell string.interpolated.dollar.shell string.interpolated.dollar.shell string.interpolated.dollar.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "$",
"t": "source.shell meta.scope.if-block.shell string.interpolated.dollar.shell string.interpolated.dollar.shell string.interpolated.dollar.shell variable.other.special.shell punctuation.definition.variable.shell",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "variable: #9CDCFE"
}
},
{
"c": "0",
"t": "source.shell meta.scope.if-block.shell string.interpolated.dollar.shell string.interpolated.dollar.shell string.interpolated.dollar.shell variable.other.special.shell",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "variable: #9CDCFE"
}
},
{
"c": ")",
"t": "source.shell meta.scope.if-block.shell string.interpolated.dollar.shell string.interpolated.dollar.shell string.interpolated.dollar.shell punctuation.definition.string.end.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": ")",
"t": "source.shell meta.scope.if-block.shell string.interpolated.dollar.shell string.interpolated.dollar.shell punctuation.definition.string.end.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": ")",
"t": "source.shell meta.scope.if-block.shell string.interpolated.dollar.shell punctuation.definition.string.end.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "fi",
"t": "source.shell meta.scope.if-block.shell keyword.control.shell",
"r": {
"dark_plus": "keyword.control: #C586C0",
"light_plus": "keyword.control: #AF00DB",
"dark_vs": "keyword.control: #569CD6",
"light_vs": "keyword.control: #0000FF",
"hc_black": "keyword.control: #C586C0"
}
},
{
"c": "DEVELOPER=",
"t": "source.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "$(",
"t": "source.shell string.interpolated.dollar.shell punctuation.definition.string.begin.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "xcode-select -print-path",
"t": "source.shell string.interpolated.dollar.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": ")",
"t": "source.shell string.interpolated.dollar.shell punctuation.definition.string.end.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "LIPO=",
"t": "source.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "$(",
"t": "source.shell string.interpolated.dollar.shell punctuation.definition.string.begin.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "xcrun -sdk iphoneos -find lipo",
"t": "source.shell string.interpolated.dollar.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": ")",
"t": "source.shell string.interpolated.dollar.shell punctuation.definition.string.end.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "function",
"t": "source.shell meta.function.shell storage.type.function.shell",
"r": {
"dark_plus": "storage.type: #569CD6",
"light_plus": "storage.type: #0000FF",
"dark_vs": "storage.type: #569CD6",
"light_vs": "storage.type: #0000FF",
"hc_black": "storage.type: #569CD6"
}
},
{
"c": " ",
"t": "source.shell meta.function.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "code()",
"t": "source.shell meta.function.shell entity.name.function.shell",
"r": {
"dark_plus": "entity.name.function: #DCDCAA",
"light_plus": "entity.name.function: #795E26",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.function: #DCDCAA"
}
},
{
"c": " ",
"t": "source.shell meta.function.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "{",
"t": "source.shell meta.function.shell meta.scope.group.shell punctuation.definition.group.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "\t",
"t": "source.shell meta.function.shell meta.scope.group.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "cd",
"t": "source.shell meta.function.shell meta.scope.group.shell support.function.builtin.shell",
"r": {
"dark_plus": "support.function: #DCDCAA",
"light_plus": "support.function: #795E26",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "support.function: #DCDCAA"
}
},
{
"c": " ",
"t": "source.shell meta.function.shell meta.scope.group.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "$",
"t": "source.shell meta.function.shell meta.scope.group.shell variable.other.normal.shell punctuation.definition.variable.shell",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "variable: #9CDCFE"
}
},
{
"c": "ROOT",
"t": "source.shell meta.function.shell meta.scope.group.shell variable.other.normal.shell",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "variable: #9CDCFE"
}
},
{
"c": "\t",
"t": "source.shell meta.function.shell meta.scope.group.shell punctuation.whitespace.comment.leading.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "#",
"t": "source.shell meta.function.shell meta.scope.group.shell comment.line.number-sign.shell punctuation.definition.comment.shell",
"r": {
"dark_plus": "comment: #6A9955",
"light_plus": "comment: #008000",
"dark_vs": "comment: #6A9955",
"light_vs": "comment: #008000",
"hc_black": "comment: #7CA668"
}
},
{
"c": " Node modules",
"t": "source.shell meta.function.shell meta.scope.group.shell comment.line.number-sign.shell",
"r": {
"dark_plus": "comment: #6A9955",
"light_plus": "comment: #008000",
"dark_vs": "comment: #6A9955",
"light_vs": "comment: #008000",
"hc_black": "comment: #7CA668"
}
},
{
"c": "\t",
"t": "source.shell meta.function.shell meta.scope.group.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "test",
"t": "source.shell meta.function.shell meta.scope.group.shell support.function.builtin.shell",
"r": {
"dark_plus": "support.function: #DCDCAA",
"light_plus": "support.function: #795E26",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "support.function: #DCDCAA"
}
},
{
"c": " -d node_modules ",
"t": "source.shell meta.function.shell meta.scope.group.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "||",
"t": "source.shell meta.function.shell meta.scope.group.shell keyword.operator.pipe.shell",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4"
}
},
{
"c": " ./scripts/npm.sh install",
"t": "source.shell meta.function.shell meta.scope.group.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "\t",
"t": "source.shell meta.function.shell meta.scope.group.shell punctuation.whitespace.comment.leading.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "#",
"t": "source.shell meta.function.shell meta.scope.group.shell comment.line.number-sign.shell punctuation.definition.comment.shell",
"r": {
"dark_plus": "comment: #6A9955",
"light_plus": "comment: #008000",
"dark_vs": "comment: #6A9955",
"light_vs": "comment: #008000",
"hc_black": "comment: #7CA668"
}
},
{
"c": " Configuration",
"t": "source.shell meta.function.shell meta.scope.group.shell comment.line.number-sign.shell",
"r": {
"dark_plus": "comment: #6A9955",
"light_plus": "comment: #008000",
"dark_vs": "comment: #6A9955",
"light_vs": "comment: #008000",
"hc_black": "comment: #7CA668"
}
},
{
"c": "\t",
"t": "source.shell meta.function.shell meta.scope.group.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "export",
"t": "source.shell meta.function.shell meta.scope.group.shell storage.modifier.shell",
"r": {
"dark_plus": "storage.modifier: #569CD6",
"light_plus": "storage.modifier: #0000FF",
"dark_vs": "storage.modifier: #569CD6",
"light_vs": "storage.modifier: #0000FF",
"hc_black": "storage.modifier: #569CD6"
}
},
{
"c": " NODE_ENV=development",
"t": "source.shell meta.function.shell meta.scope.group.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "\t",
"t": "source.shell meta.function.shell meta.scope.group.shell punctuation.whitespace.comment.leading.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "#",
"t": "source.shell meta.function.shell meta.scope.group.shell comment.line.number-sign.shell punctuation.definition.comment.shell",
"r": {
"dark_plus": "comment: #6A9955",
"light_plus": "comment: #008000",
"dark_vs": "comment: #6A9955",
"light_vs": "comment: #008000",
"hc_black": "comment: #7CA668"
}
},
{
"c": " Launch Code",
"t": "source.shell meta.function.shell meta.scope.group.shell comment.line.number-sign.shell",
"r": {
"dark_plus": "comment: #6A9955",
"light_plus": "comment: #008000",
"dark_vs": "comment: #6A9955",
"light_vs": "comment: #008000",
"hc_black": "comment: #7CA668"
}
},
{
"c": "\t",
"t": "source.shell meta.function.shell meta.scope.group.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "if",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell keyword.control.shell",
"r": {
"dark_plus": "keyword.control: #C586C0",
"light_plus": "keyword.control: #AF00DB",
"dark_vs": "keyword.control: #569CD6",
"light_vs": "keyword.control: #0000FF",
"hc_black": "keyword.control: #C586C0"
}
},
{
"c": " ",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "[[",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell meta.scope.logical-expression.shell punctuation.definition.logical-expression.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": " ",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell meta.scope.logical-expression.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "\"",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell meta.scope.logical-expression.shell string.quoted.double.shell punctuation.definition.string.begin.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "$",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell meta.scope.logical-expression.shell string.quoted.double.shell variable.other.normal.shell punctuation.definition.variable.shell",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "variable: #9CDCFE"
}
},
{
"c": "OSTYPE",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell meta.scope.logical-expression.shell string.quoted.double.shell variable.other.normal.shell",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "variable: #9CDCFE"
}
},
{
"c": "\"",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell meta.scope.logical-expression.shell string.quoted.double.shell punctuation.definition.string.end.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": " ",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell meta.scope.logical-expression.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "==",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell meta.scope.logical-expression.shell keyword.operator.logical.shell",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4"
}
},
{
"c": " ",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell meta.scope.logical-expression.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "\"",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell meta.scope.logical-expression.shell string.quoted.double.shell punctuation.definition.string.begin.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "darwin",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell meta.scope.logical-expression.shell string.quoted.double.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "\"",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell meta.scope.logical-expression.shell string.quoted.double.shell punctuation.definition.string.end.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "*",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell meta.scope.logical-expression.shell keyword.operator.glob.shell",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4"
}
},
{
"c": " ",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell meta.scope.logical-expression.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "]]",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell meta.scope.logical-expression.shell punctuation.definition.logical-expression.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": ";",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell keyword.operator.list.shell",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4"
}
},
{
"c": " ",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "then",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell keyword.control.shell",
"r": {
"dark_plus": "keyword.control: #C586C0",
"light_plus": "keyword.control: #AF00DB",
"dark_vs": "keyword.control: #569CD6",
"light_vs": "keyword.control: #0000FF",
"hc_black": "keyword.control: #C586C0"
}
},
{
"c": "\t\t",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "exec",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell support.function.builtin.shell",
"r": {
"dark_plus": "support.function: #DCDCAA",
"light_plus": "support.function: #795E26",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "support.function: #DCDCAA"
}
},
{
"c": " ./.build/electron/Electron.app/Contents/MacOS/Electron ",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": ".",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell support.function.builtin.shell",
"r": {
"dark_plus": "support.function: #DCDCAA",
"light_plus": "support.function: #795E26",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "support.function: #DCDCAA"
}
},
{
"c": " ",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "\"",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell string.quoted.double.shell punctuation.definition.string.begin.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "$",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell string.quoted.double.shell variable.other.special.shell punctuation.definition.variable.shell",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "variable: #9CDCFE"
}
},
{
"c": "@",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell string.quoted.double.shell variable.other.special.shell",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "variable: #9CDCFE"
}
},
{
"c": "\"",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell string.quoted.double.shell punctuation.definition.string.end.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "\t",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "else",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell keyword.control.shell",
"r": {
"dark_plus": "keyword.control: #C586C0",
"light_plus": "keyword.control: #AF00DB",
"dark_vs": "keyword.control: #569CD6",
"light_vs": "keyword.control: #0000FF",
"hc_black": "keyword.control: #C586C0"
}
},
{
"c": "\t\t",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "exec",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell support.function.builtin.shell",
"r": {
"dark_plus": "support.function: #DCDCAA",
"light_plus": "support.function: #795E26",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "support.function: #DCDCAA"
}
},
{
"c": " ./.build/electron/electron ",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": ".",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell support.function.builtin.shell",
"r": {
"dark_plus": "support.function: #DCDCAA",
"light_plus": "support.function: #795E26",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "support.function: #DCDCAA"
}
},
{
"c": " ",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "\"",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell string.quoted.double.shell punctuation.definition.string.begin.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "$",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell string.quoted.double.shell variable.other.special.shell punctuation.definition.variable.shell",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "variable: #9CDCFE"
}
},
{
"c": "@",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell string.quoted.double.shell variable.other.special.shell",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "variable: #9CDCFE"
}
},
{
"c": "\"",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell string.quoted.double.shell punctuation.definition.string.end.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "\t",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "fi",
"t": "source.shell meta.function.shell meta.scope.group.shell meta.scope.if-block.shell keyword.control.shell",
"r": {
"dark_plus": "keyword.control: #C586C0",
"light_plus": "keyword.control: #AF00DB",
"dark_vs": "keyword.control: #569CD6",
"light_vs": "keyword.control: #0000FF",
"hc_black": "keyword.control: #C586C0"
}
},
{
"c": "}",
"t": "source.shell meta.function.shell meta.scope.group.shell punctuation.definition.group.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "code ",
"t": "source.shell",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "\"",
"t": "source.shell string.quoted.double.shell punctuation.definition.string.begin.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "$",
"t": "source.shell string.quoted.double.shell variable.other.special.shell punctuation.definition.variable.shell",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "variable: #9CDCFE"
}
},
{
"c": "@",
"t": "source.shell string.quoted.double.shell variable.other.special.shell",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "variable: #9CDCFE"
}
},
{
"c": "\"",
"t": "source.shell string.quoted.double.shell punctuation.definition.string.end.shell",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
}
] | extensions/shellscript/test/colorize-results/test_sh.json | 0 | https://github.com/microsoft/vscode/commit/23f2275c23aeebf5e22f3d19a20528c8ba48c570 | [
0.00017841413500718772,
0.00017609081987757236,
0.00017332419520244002,
0.00017601254512555897,
0.0000011881106729560997
] |
{
"id": 1,
"code_window": [
"\t\t\t\t\t}\n",
"\t\t\t\t});\n",
"\t\t\t\toptions.waitMarkerFileURI = options.waitMarkerFileURI && URI.revive(options.waitMarkerFileURI);\n",
"\t\t\t\treturn this.service.openWindow(arg[0], urisToOpen, options);\n",
"\t\t\t}\n",
"\t\t\tcase 'openExtensionDevelopmentHostWindow': return this.service.openExtensionDevelopmentHostWindow(arg[0], arg[1]);\n",
"\t\t\tcase 'getWindows': return this.service.getWindows();\n",
"\t\t\tcase 'getActiveWindowId': return this.service.getActiveWindowId();\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tcase 'openExtensionDevelopmentHostWindow': return (this.service as any).openExtensionDevelopmentHostWindow(arg[0], arg[1]); // TODO@Isidor move\n"
],
"file_path": "src/vs/platform/windows/common/windowsIpc.ts",
"type": "replace",
"edit_start_line_idx": 81
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'vs/workbench/contrib/files/browser/files.contribution'; // load our contribution into the test
import { FileEditorInput } from 'vs/workbench/contrib/files/common/editors/fileEditorInput';
import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock';
import { join } from 'vs/base/common/path';
import * as resources from 'vs/base/common/resources';
import { URI } from 'vs/base/common/uri';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { NullTelemetryService } from 'vs/platform/telemetry/common/telemetryUtils';
import { ConfirmResult, IEditorInputWithOptions, CloseDirection, IEditorIdentifier, IUntitledResourceInput, IResourceDiffInput, IResourceSideBySideInput, IEditorInput, IEditor, IEditorCloseEvent, IEditorPartOptions } from 'vs/workbench/common/editor';
import { IEditorOpeningEvent, EditorServiceImpl, IEditorGroupView } from 'vs/workbench/browser/parts/editor/editor';
import { Event, Emitter } from 'vs/base/common/event';
import Severity from 'vs/base/common/severity';
import { IBackupFileService, IResolvedBackup } from 'vs/workbench/services/backup/common/backup';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IWorkbenchLayoutService, Parts, Position as PartPosition } from 'vs/workbench/services/layout/browser/layoutService';
import { TextModelResolverService } from 'vs/workbench/services/textmodelResolver/common/textModelResolverService';
import { ITextModelService } from 'vs/editor/common/services/resolverService';
import { IEditorOptions, IResourceInput } from 'vs/platform/editor/common/editor';
import { IUntitledEditorService, UntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService';
import { IWorkspaceContextService, IWorkspace as IWorkbenchWorkspace, WorkbenchState, IWorkspaceFolder, IWorkspaceFoldersChangeEvent, Workspace } from 'vs/platform/workspace/common/workspace';
import { ILifecycleService, BeforeShutdownEvent, ShutdownReason, StartupKind, LifecyclePhase, WillShutdownEvent } from 'vs/platform/lifecycle/common/lifecycle';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { FileOperationEvent, IFileService, FileOperationError, IFileStat, IResolveFileResult, FileChangesEvent, IResolveFileOptions, ICreateFileOptions, IFileSystemProvider, FileSystemProviderCapabilities, IFileChange, IWatchOptions, IStat, FileType, FileDeleteOptions, FileOverwriteOptions, FileWriteOptions, FileOpenOptions, IFileStatWithMetadata, IResolveMetadataFileOptions, IWriteFileOptions, IReadFileOptions, IFileContent, IFileStreamContent } from 'vs/platform/files/common/files';
import { IModelService } from 'vs/editor/common/services/modelService';
import { ModeServiceImpl } from 'vs/editor/common/services/modeServiceImpl';
import { ModelServiceImpl } from 'vs/editor/common/services/modelServiceImpl';
import { ITextFileStreamContent, ITextFileService, IResourceEncoding, IReadTextFileOptions } from 'vs/workbench/services/textfile/common/textfiles';
import { parseArgs, OPTIONS } from 'vs/platform/environment/node/argv';
import { IModeService } from 'vs/editor/common/services/modeService';
import { IHistoryService } from 'vs/workbench/services/history/common/history';
import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService';
import { IWindowsService, IWindowService, IEnterWorkspaceResult, MenuBarVisibility, IURIToOpen, IOpenSettings, IWindowConfiguration } from 'vs/platform/windows/common/windows';
import { TestWorkspace } from 'vs/platform/workspace/test/common/testWorkspace';
import { createTextBufferFactoryFromStream } from 'vs/editor/common/model/textModel';
import { IEnvironmentService, ParsedArgs } from 'vs/platform/environment/common/environment';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { TestThemeService } from 'vs/platform/theme/test/common/testThemeService';
import { IWorkspaceIdentifier, ISingleFolderWorkspaceIdentifier, isSingleFolderWorkspaceIdentifier } from 'vs/platform/workspaces/common/workspaces';
import { IRecentlyOpened, IRecent } from 'vs/platform/history/common/history';
import { ITextResourceConfigurationService, ITextResourcePropertiesService } from 'vs/editor/common/services/resourceConfiguration';
import { IPosition, Position as EditorPosition } from 'vs/editor/common/core/position';
import { IMenuService, MenuId, IMenu } from 'vs/platform/actions/common/actions';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { MockContextKeyService, MockKeybindingService } from 'vs/platform/keybinding/test/common/mockKeybindingService';
import { ITextBufferFactory, DefaultEndOfLine, EndOfLinePreference, IModelDecorationOptions, ITextModel, ITextSnapshot } from 'vs/editor/common/model';
import { Range } from 'vs/editor/common/core/range';
import { IConfirmation, IConfirmationResult, IDialogService, IDialogOptions, IPickAndOpenOptions, ISaveDialogOptions, IOpenDialogOptions, IFileDialogService, IShowResult } from 'vs/platform/dialogs/common/dialogs';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { TestNotificationService } from 'vs/platform/notification/test/common/testNotificationService';
import { IExtensionService, NullExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IDecorationsService, IResourceDecorationChangeEvent, IDecoration, IDecorationData, IDecorationsProvider } from 'vs/workbench/services/decorations/browser/decorations';
import { IDisposable, toDisposable, Disposable } from 'vs/base/common/lifecycle';
import { IEditorGroupsService, IEditorGroup, GroupsOrder, GroupsArrangement, GroupDirection, IAddGroupOptions, IMergeGroupOptions, IMoveEditorOptions, ICopyEditorOptions, IEditorReplacement, IGroupChangeEvent, EditorsOrder, IFindGroupScope, EditorGroupLayout, ICloseEditorOptions } from 'vs/workbench/services/editor/common/editorGroupsService';
import { IEditorService, IOpenEditorOverrideHandler, IVisibleEditor } from 'vs/workbench/services/editor/common/editorService';
import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService';
import { ICodeEditor, IDiffEditor } from 'vs/editor/browser/editorBrowser';
import { IDecorationRenderOptions } from 'vs/editor/common/editorCommon';
import { EditorGroup } from 'vs/workbench/common/editor/editorGroup';
import { Dimension } from 'vs/base/browser/dom';
import { ILogService, NullLogService } from 'vs/platform/log/common/log';
import { ILabelService } from 'vs/platform/label/common/label';
import { timeout } from 'vs/base/common/async';
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
import { ViewletDescriptor, Viewlet } from 'vs/workbench/browser/viewlet';
import { IViewlet } from 'vs/workbench/common/viewlet';
import { IStorageService, InMemoryStorageService } from 'vs/platform/storage/common/storage';
import { isLinux, isMacintosh, IProcessEnvironment } from 'vs/base/common/platform';
import { LabelService } from 'vs/workbench/services/label/common/labelService';
import { IDimension } from 'vs/platform/layout/browser/layoutService';
import { Part } from 'vs/workbench/browser/part';
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
import { IPanel } from 'vs/workbench/common/panel';
import { IBadge } from 'vs/workbench/services/activity/common/activity';
import { ISharedProcessService } from 'vs/platform/ipc/electron-browser/sharedProcessService';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { WorkbenchEnvironmentService } from 'vs/workbench/services/environment/node/environmentService';
import { VSBuffer, VSBufferReadable } from 'vs/base/common/buffer';
import { NativeTextFileService } from 'vs/workbench/services/textfile/electron-browser/nativeTextFileService';
import { Schemas } from 'vs/base/common/network';
import { IProductService } from 'vs/platform/product/common/productService';
import product from 'vs/platform/product/common/product';
import { IHostService } from 'vs/workbench/services/host/browser/host';
export function createFileInput(instantiationService: IInstantiationService, resource: URI): FileEditorInput {
return instantiationService.createInstance(FileEditorInput, resource, undefined, undefined);
}
export const TestEnvironmentService = new WorkbenchEnvironmentService(parseArgs(process.argv, OPTIONS) as IWindowConfiguration, process.execPath);
export class TestContextService implements IWorkspaceContextService {
public _serviceBrand: undefined;
private workspace: Workspace;
private options: any;
private readonly _onDidChangeWorkspaceName: Emitter<void>;
private readonly _onDidChangeWorkspaceFolders: Emitter<IWorkspaceFoldersChangeEvent>;
private readonly _onDidChangeWorkbenchState: Emitter<WorkbenchState>;
constructor(workspace: any = TestWorkspace, options: any = null) {
this.workspace = workspace;
this.options = options || Object.create(null);
this._onDidChangeWorkspaceName = new Emitter<void>();
this._onDidChangeWorkspaceFolders = new Emitter<IWorkspaceFoldersChangeEvent>();
this._onDidChangeWorkbenchState = new Emitter<WorkbenchState>();
}
public get onDidChangeWorkspaceName(): Event<void> {
return this._onDidChangeWorkspaceName.event;
}
public get onDidChangeWorkspaceFolders(): Event<IWorkspaceFoldersChangeEvent> {
return this._onDidChangeWorkspaceFolders.event;
}
public get onDidChangeWorkbenchState(): Event<WorkbenchState> {
return this._onDidChangeWorkbenchState.event;
}
public getFolders(): IWorkspaceFolder[] {
return this.workspace ? this.workspace.folders : [];
}
public getWorkbenchState(): WorkbenchState {
if (this.workspace.configuration) {
return WorkbenchState.WORKSPACE;
}
if (this.workspace.folders.length) {
return WorkbenchState.FOLDER;
}
return WorkbenchState.EMPTY;
}
getCompleteWorkspace(): Promise<IWorkbenchWorkspace> {
return Promise.resolve(this.getWorkspace());
}
public getWorkspace(): IWorkbenchWorkspace {
return this.workspace;
}
public getWorkspaceFolder(resource: URI): IWorkspaceFolder | null {
return this.workspace.getFolder(resource);
}
public setWorkspace(workspace: any): void {
this.workspace = workspace;
}
public getOptions() {
return this.options;
}
public updateOptions() {
}
public isInsideWorkspace(resource: URI): boolean {
if (resource && this.workspace) {
return resources.isEqualOrParent(resource, this.workspace.folders[0].uri);
}
return false;
}
public toResource(workspaceRelativePath: string): URI {
return URI.file(join('C:\\', workspaceRelativePath));
}
public isCurrentWorkspace(workspaceIdentifier: ISingleFolderWorkspaceIdentifier | IWorkspaceIdentifier): boolean {
return isSingleFolderWorkspaceIdentifier(workspaceIdentifier) && resources.isEqual(this.workspace.folders[0].uri, workspaceIdentifier);
}
}
export class TestTextFileService extends NativeTextFileService {
public cleanupBackupsBeforeShutdownCalled: boolean;
private promptPath: URI;
private confirmResult: ConfirmResult;
private resolveTextContentError: FileOperationError | null;
constructor(
@IWorkspaceContextService contextService: IWorkspaceContextService,
@IFileService protected fileService: IFileService,
@IUntitledEditorService untitledEditorService: IUntitledEditorService,
@ILifecycleService lifecycleService: ILifecycleService,
@IInstantiationService instantiationService: IInstantiationService,
@IConfigurationService configurationService: IConfigurationService,
@IModeService modeService: IModeService,
@IModelService modelService: IModelService,
@IWorkbenchEnvironmentService environmentService: IWorkbenchEnvironmentService,
@INotificationService notificationService: INotificationService,
@IBackupFileService backupFileService: IBackupFileService,
@IHostService hostService: IHostService,
@IHistoryService historyService: IHistoryService,
@IContextKeyService contextKeyService: IContextKeyService,
@IDialogService dialogService: IDialogService,
@IFileDialogService fileDialogService: IFileDialogService,
@IEditorService editorService: IEditorService,
@ITextResourceConfigurationService textResourceConfigurationService: ITextResourceConfigurationService
) {
super(
contextService,
fileService,
untitledEditorService,
lifecycleService,
instantiationService,
configurationService,
modeService,
modelService,
environmentService,
notificationService,
backupFileService,
hostService,
historyService,
contextKeyService,
dialogService,
fileDialogService,
editorService,
textResourceConfigurationService
);
}
public setPromptPath(path: URI): void {
this.promptPath = path;
}
public setConfirmResult(result: ConfirmResult): void {
this.confirmResult = result;
}
public setResolveTextContentErrorOnce(error: FileOperationError): void {
this.resolveTextContentError = error;
}
public readStream(resource: URI, options?: IReadTextFileOptions): Promise<ITextFileStreamContent> {
if (this.resolveTextContentError) {
const error = this.resolveTextContentError;
this.resolveTextContentError = null;
return Promise.reject(error);
}
return this.fileService.readFileStream(resource, options).then(async (content): Promise<ITextFileStreamContent> => {
return {
resource: content.resource,
name: content.name,
mtime: content.mtime,
etag: content.etag,
encoding: 'utf8',
value: await createTextBufferFactoryFromStream(content.value),
size: 10
};
});
}
public promptForPath(_resource: URI, _defaultPath: URI): Promise<URI> {
return Promise.resolve(this.promptPath);
}
public confirmSave(_resources?: URI[]): Promise<ConfirmResult> {
return Promise.resolve(this.confirmResult);
}
public confirmOverwrite(_resource: URI): Promise<boolean> {
return Promise.resolve(true);
}
public onFilesConfigurationChange(configuration: any): void {
super.onFilesConfigurationChange(configuration);
}
protected cleanupBackupsBeforeShutdown(): Promise<void> {
this.cleanupBackupsBeforeShutdownCalled = true;
return Promise.resolve();
}
}
export function workbenchInstantiationService(): IInstantiationService {
let instantiationService = new TestInstantiationService(new ServiceCollection([ILifecycleService, new TestLifecycleService()]));
instantiationService.stub(IEnvironmentService, TestEnvironmentService);
instantiationService.stub(IContextKeyService, <IContextKeyService>instantiationService.createInstance(MockContextKeyService));
const workspaceContextService = new TestContextService(TestWorkspace);
instantiationService.stub(IWorkspaceContextService, workspaceContextService);
const configService = new TestConfigurationService();
instantiationService.stub(IConfigurationService, configService);
instantiationService.stub(ITextResourceConfigurationService, new TestTextResourceConfigurationService(configService));
instantiationService.stub(IUntitledEditorService, instantiationService.createInstance(UntitledEditorService));
instantiationService.stub(IStorageService, new TestStorageService());
instantiationService.stub(IWorkbenchLayoutService, new TestLayoutService());
instantiationService.stub(IModeService, instantiationService.createInstance(ModeServiceImpl));
instantiationService.stub(IHistoryService, new TestHistoryService());
instantiationService.stub(ITextResourcePropertiesService, new TestTextResourcePropertiesService(configService));
instantiationService.stub(IModelService, instantiationService.createInstance(ModelServiceImpl));
instantiationService.stub(IFileService, new TestFileService());
instantiationService.stub(IBackupFileService, new TestBackupFileService());
instantiationService.stub(ITelemetryService, NullTelemetryService);
instantiationService.stub(INotificationService, new TestNotificationService());
instantiationService.stub(IUntitledEditorService, instantiationService.createInstance(UntitledEditorService));
instantiationService.stub(IWindowService, new TestWindowService());
instantiationService.stub(IMenuService, new TestMenuService());
instantiationService.stub(IKeybindingService, new MockKeybindingService());
instantiationService.stub(IDecorationsService, new TestDecorationsService());
instantiationService.stub(IExtensionService, new TestExtensionService());
instantiationService.stub(IWindowsService, new TestWindowsService());
instantiationService.stub(IHostService, <IHostService>instantiationService.createInstance(TestHostService));
instantiationService.stub(ITextFileService, <ITextFileService>instantiationService.createInstance(TestTextFileService));
instantiationService.stub(ITextModelService, <ITextModelService>instantiationService.createInstance(TextModelResolverService));
instantiationService.stub(IThemeService, new TestThemeService());
instantiationService.stub(ILogService, new NullLogService());
instantiationService.stub(IEditorGroupsService, new TestEditorGroupsService([new TestEditorGroup(0)]));
instantiationService.stub(ILabelService, <ILabelService>instantiationService.createInstance(LabelService));
const editorService = new TestEditorService();
instantiationService.stub(IEditorService, editorService);
instantiationService.stub(ICodeEditorService, new TestCodeEditorService());
instantiationService.stub(IViewletService, new TestViewletService());
return instantiationService;
}
export class TestDecorationsService implements IDecorationsService {
_serviceBrand: undefined;
onDidChangeDecorations: Event<IResourceDecorationChangeEvent> = Event.None;
registerDecorationsProvider(_provider: IDecorationsProvider): IDisposable { return Disposable.None; }
getDecoration(_uri: URI, _includeChildren: boolean, _overwrite?: IDecorationData): IDecoration | undefined { return undefined; }
}
export class TestExtensionService extends NullExtensionService { }
export class TestMenuService implements IMenuService {
public _serviceBrand: undefined;
createMenu(_id: MenuId, _scopedKeybindingService: IContextKeyService): IMenu {
return {
onDidChange: Event.None,
dispose: () => undefined,
getActions: () => []
};
}
}
export class TestHistoryService implements IHistoryService {
public _serviceBrand: undefined;
constructor(private root?: URI) {
}
public reopenLastClosedEditor(): void {
}
public forward(_acrossEditors?: boolean): void {
}
public back(_acrossEditors?: boolean): void {
}
public last(): void {
}
public remove(_input: IEditorInput | IResourceInput): void {
}
public clear(): void {
}
public clearRecentlyOpened(): void {
}
public getHistory(): Array<IEditorInput | IResourceInput> {
return [];
}
public getLastActiveWorkspaceRoot(_schemeFilter: string): URI | undefined {
return this.root;
}
public getLastActiveFile(_schemeFilter: string): URI | undefined {
return undefined;
}
public openLastEditLocation(): void {
}
}
export class TestDialogService implements IDialogService {
public _serviceBrand: undefined;
public confirm(_confirmation: IConfirmation): Promise<IConfirmationResult> {
return Promise.resolve({ confirmed: false });
}
public show(_severity: Severity, _message: string, _buttons: string[], _options?: IDialogOptions): Promise<IShowResult> {
return Promise.resolve({ choice: 0 });
}
public about(): Promise<void> {
return Promise.resolve();
}
}
export class TestFileDialogService implements IFileDialogService {
public _serviceBrand: undefined;
public defaultFilePath(_schemeFilter?: string): URI | undefined {
return undefined;
}
public defaultFolderPath(_schemeFilter?: string): URI | undefined {
return undefined;
}
public defaultWorkspacePath(_schemeFilter?: string): URI | undefined {
return undefined;
}
public pickFileFolderAndOpen(_options: IPickAndOpenOptions): Promise<any> {
return Promise.resolve(0);
}
public pickFileAndOpen(_options: IPickAndOpenOptions): Promise<any> {
return Promise.resolve(0);
}
public pickFolderAndOpen(_options: IPickAndOpenOptions): Promise<any> {
return Promise.resolve(0);
}
public pickWorkspaceAndOpen(_options: IPickAndOpenOptions): Promise<any> {
return Promise.resolve(0);
}
public pickFileToSave(_options: ISaveDialogOptions): Promise<URI | undefined> {
return Promise.resolve(undefined);
}
public showSaveDialog(_options: ISaveDialogOptions): Promise<URI | undefined> {
return Promise.resolve(undefined);
}
public showOpenDialog(_options: IOpenDialogOptions): Promise<URI[] | undefined> {
return Promise.resolve(undefined);
}
}
export class TestLayoutService implements IWorkbenchLayoutService {
public _serviceBrand: undefined;
dimension: IDimension = { width: 800, height: 600 };
container: HTMLElement = window.document.body;
onZenModeChange: Event<boolean> = Event.None;
onCenteredLayoutChange: Event<boolean> = Event.None;
onFullscreenChange: Event<boolean> = Event.None;
onPanelPositionChange: Event<string> = Event.None;
onLayout = Event.None;
private readonly _onTitleBarVisibilityChange = new Emitter<void>();
private readonly _onMenubarVisibilityChange = new Emitter<Dimension>();
public get onTitleBarVisibilityChange(): Event<void> {
return this._onTitleBarVisibilityChange.event;
}
public get onMenubarVisibilityChange(): Event<Dimension> {
return this._onMenubarVisibilityChange.event;
}
public isRestored(): boolean {
return true;
}
public hasFocus(_part: Parts): boolean {
return false;
}
public isVisible(_part: Parts): boolean {
return true;
}
getDimension(_part: Parts): Dimension {
return new Dimension(0, 0);
}
public getContainer(_part: Parts): HTMLElement {
return null!;
}
public isTitleBarHidden(): boolean {
return false;
}
public getTitleBarOffset(): number {
return 0;
}
public isStatusBarHidden(): boolean {
return false;
}
public isActivityBarHidden(): boolean {
return false;
}
public setActivityBarHidden(_hidden: boolean): void { }
public isSideBarHidden(): boolean {
return false;
}
public setEditorHidden(_hidden: boolean): Promise<void> { return Promise.resolve(); }
public setSideBarHidden(_hidden: boolean): Promise<void> { return Promise.resolve(); }
public isPanelHidden(): boolean {
return false;
}
public setPanelHidden(_hidden: boolean): Promise<void> { return Promise.resolve(); }
public toggleMaximizedPanel(): void { }
public isPanelMaximized(): boolean {
return false;
}
public getMenubarVisibility(): MenuBarVisibility {
throw new Error('not implemented');
}
public getSideBarPosition() {
return 0;
}
public getPanelPosition() {
return 0;
}
public setPanelPosition(_position: PartPosition): Promise<void> {
return Promise.resolve();
}
public addClass(_clazz: string): void { }
public removeClass(_clazz: string): void { }
public getMaximumEditorDimensions(): Dimension { throw new Error('not implemented'); }
public getWorkbenchContainer(): HTMLElement { throw new Error('not implemented'); }
public getWorkbenchElement(): HTMLElement { throw new Error('not implemented'); }
public toggleZenMode(): void { }
public isEditorLayoutCentered(): boolean { return false; }
public centerEditorLayout(_active: boolean): void { }
public resizePart(_part: Parts, _sizeChange: number): void { }
public registerPart(part: Part): void { }
}
let activeViewlet: Viewlet = {} as any;
export class TestViewletService implements IViewletService {
public _serviceBrand: undefined;
onDidViewletRegisterEmitter = new Emitter<ViewletDescriptor>();
onDidViewletDeregisterEmitter = new Emitter<ViewletDescriptor>();
onDidViewletOpenEmitter = new Emitter<IViewlet>();
onDidViewletCloseEmitter = new Emitter<IViewlet>();
onDidViewletRegister = this.onDidViewletRegisterEmitter.event;
onDidViewletDeregister = this.onDidViewletDeregisterEmitter.event;
onDidViewletOpen = this.onDidViewletOpenEmitter.event;
onDidViewletClose = this.onDidViewletCloseEmitter.event;
public openViewlet(id: string, focus?: boolean): Promise<IViewlet> {
return Promise.resolve(null!);
}
public getViewlets(): ViewletDescriptor[] {
return [];
}
public getAllViewlets(): ViewletDescriptor[] {
return [];
}
public getActiveViewlet(): IViewlet {
return activeViewlet;
}
public dispose() {
}
public getDefaultViewletId(): string {
return 'workbench.view.explorer';
}
public getViewlet(id: string): ViewletDescriptor | undefined {
return undefined;
}
public getProgressIndicator(id: string) {
return null!;
}
public hideActiveViewlet(): void { }
public getLastActiveViewletId(): string {
return undefined!;
}
}
export class TestPanelService implements IPanelService {
public _serviceBrand: undefined;
onDidPanelOpen = new Emitter<{ panel: IPanel, focus: boolean }>().event;
onDidPanelClose = new Emitter<IPanel>().event;
public openPanel(id: string, focus?: boolean): IPanel {
return null!;
}
public getPanel(id: string): any {
return activeViewlet;
}
public getPanels(): any[] {
return [];
}
public getPinnedPanels(): any[] {
return [];
}
public getActivePanel(): IViewlet {
return activeViewlet;
}
public setPanelEnablement(id: string, enabled: boolean): void { }
public dispose() {
}
public showActivity(panelId: string, badge: IBadge, clazz?: string): IDisposable {
throw new Error('Method not implemented.');
}
public getProgressIndicator(id: string) {
return null!;
}
public hideActivePanel(): void { }
public getLastActivePanelId(): string {
return undefined!;
}
}
export class TestStorageService extends InMemoryStorageService { }
export class TestEditorGroupsService implements IEditorGroupsService {
_serviceBrand: undefined;
constructor(public groups: TestEditorGroup[] = []) { }
onDidActiveGroupChange: Event<IEditorGroup> = Event.None;
onDidActivateGroup: Event<IEditorGroup> = Event.None;
onDidAddGroup: Event<IEditorGroup> = Event.None;
onDidRemoveGroup: Event<IEditorGroup> = Event.None;
onDidMoveGroup: Event<IEditorGroup> = Event.None;
onDidGroupIndexChange: Event<IEditorGroup> = Event.None;
onDidLayout: Event<IDimension> = Event.None;
orientation: any;
whenRestored: Promise<void> = Promise.resolve(undefined);
willRestoreEditors = false;
contentDimension = { width: 800, height: 600 };
get activeGroup(): IEditorGroup {
return this.groups[0];
}
get count(): number {
return this.groups.length;
}
getGroups(_order?: GroupsOrder): ReadonlyArray<IEditorGroup> {
return this.groups;
}
getGroup(identifier: number): IEditorGroup {
for (const group of this.groups) {
if (group.id === identifier) {
return group;
}
}
return undefined!;
}
getLabel(_identifier: number): string {
return 'Group 1';
}
findGroup(_scope: IFindGroupScope, _source?: number | IEditorGroup, _wrap?: boolean): IEditorGroup {
throw new Error('not implemented');
}
activateGroup(_group: number | IEditorGroup): IEditorGroup {
throw new Error('not implemented');
}
restoreGroup(_group: number | IEditorGroup): IEditorGroup {
throw new Error('not implemented');
}
getSize(_group: number | IEditorGroup): { width: number, height: number } {
return { width: 100, height: 100 };
}
setSize(_group: number | IEditorGroup, _size: { width: number, height: number }): void { }
arrangeGroups(_arrangement: GroupsArrangement): void { }
applyLayout(_layout: EditorGroupLayout): void { }
setGroupOrientation(_orientation: any): void { }
addGroup(_location: number | IEditorGroup, _direction: GroupDirection, _options?: IAddGroupOptions): IEditorGroup {
throw new Error('not implemented');
}
removeGroup(_group: number | IEditorGroup): void { }
moveGroup(_group: number | IEditorGroup, _location: number | IEditorGroup, _direction: GroupDirection): IEditorGroup {
throw new Error('not implemented');
}
mergeGroup(_group: number | IEditorGroup, _target: number | IEditorGroup, _options?: IMergeGroupOptions): IEditorGroup {
throw new Error('not implemented');
}
copyGroup(_group: number | IEditorGroup, _location: number | IEditorGroup, _direction: GroupDirection): IEditorGroup {
throw new Error('not implemented');
}
centerLayout(active: boolean): void { }
isLayoutCentered(): boolean {
return false;
}
partOptions: IEditorPartOptions;
enforcePartOptions(options: IEditorPartOptions): IDisposable {
return Disposable.None;
}
}
export class TestEditorGroup implements IEditorGroupView {
constructor(public id: number) { }
get group(): EditorGroup { throw new Error('not implemented'); }
activeControl: IVisibleEditor;
activeEditor: IEditorInput;
previewEditor: IEditorInput;
count: number;
disposed: boolean;
editors: ReadonlyArray<IEditorInput> = [];
label: string;
index: number;
whenRestored: Promise<void> = Promise.resolve(undefined);
element: HTMLElement;
minimumWidth: number;
maximumWidth: number;
minimumHeight: number;
maximumHeight: number;
isEmpty = true;
isMinimized = false;
onWillDispose: Event<void> = Event.None;
onDidGroupChange: Event<IGroupChangeEvent> = Event.None;
onWillCloseEditor: Event<IEditorCloseEvent> = Event.None;
onDidCloseEditor: Event<IEditorCloseEvent> = Event.None;
onWillOpenEditor: Event<IEditorOpeningEvent> = Event.None;
onDidOpenEditorFail: Event<IEditorInput> = Event.None;
onDidFocus: Event<void> = Event.None;
onDidChange: Event<{ width: number; height: number; }> = Event.None;
getEditors(_order?: EditorsOrder): ReadonlyArray<IEditorInput> {
return [];
}
getEditor(_index: number): IEditorInput {
throw new Error('not implemented');
}
getIndexOfEditor(_editor: IEditorInput): number {
return -1;
}
openEditor(_editor: IEditorInput, _options?: IEditorOptions): Promise<IEditor> {
throw new Error('not implemented');
}
openEditors(_editors: IEditorInputWithOptions[]): Promise<IEditor> {
throw new Error('not implemented');
}
isOpened(_editor: IEditorInput): boolean {
return false;
}
isPinned(_editor: IEditorInput): boolean {
return false;
}
isActive(_editor: IEditorInput): boolean {
return false;
}
moveEditor(_editor: IEditorInput, _target: IEditorGroup, _options?: IMoveEditorOptions): void { }
copyEditor(_editor: IEditorInput, _target: IEditorGroup, _options?: ICopyEditorOptions): void { }
closeEditor(_editor?: IEditorInput, options?: ICloseEditorOptions): Promise<void> {
return Promise.resolve();
}
closeEditors(_editors: IEditorInput[] | { except?: IEditorInput; direction?: CloseDirection; savedOnly?: boolean; }, options?: ICloseEditorOptions): Promise<void> {
return Promise.resolve();
}
closeAllEditors(): Promise<void> {
return Promise.resolve();
}
replaceEditors(_editors: IEditorReplacement[]): Promise<void> {
return Promise.resolve();
}
pinEditor(_editor?: IEditorInput): void { }
focus(): void { }
invokeWithinContext<T>(fn: (accessor: ServicesAccessor) => T): T {
throw new Error('not implemented');
}
setActive(_isActive: boolean): void { }
notifyIndexChanged(_index: number): void { }
dispose(): void { }
toJSON(): object { return Object.create(null); }
layout(_width: number, _height: number): void { }
relayout() { }
}
export class TestEditorService implements EditorServiceImpl {
_serviceBrand: undefined;
onDidActiveEditorChange: Event<void> = Event.None;
onDidVisibleEditorsChange: Event<void> = Event.None;
onDidCloseEditor: Event<IEditorCloseEvent> = Event.None;
onDidOpenEditorFail: Event<IEditorIdentifier> = Event.None;
activeControl: IVisibleEditor;
activeTextEditorWidget: any;
activeEditor: IEditorInput;
editors: ReadonlyArray<IEditorInput> = [];
visibleControls: ReadonlyArray<IVisibleEditor> = [];
visibleTextEditorWidgets = [];
visibleEditors: ReadonlyArray<IEditorInput> = [];
overrideOpenEditor(_handler: IOpenEditorOverrideHandler): IDisposable {
return toDisposable(() => undefined);
}
openEditor(_editor: any, _options?: any, _group?: any): Promise<any> {
throw new Error('not implemented');
}
openEditors(_editors: any, _group?: any): Promise<IEditor[]> {
throw new Error('not implemented');
}
isOpen(_editor: IEditorInput | IResourceInput | IUntitledResourceInput): boolean {
return false;
}
getOpened(_editor: IEditorInput | IResourceInput | IUntitledResourceInput): IEditorInput {
throw new Error('not implemented');
}
replaceEditors(_editors: any, _group: any) {
return Promise.resolve(undefined);
}
invokeWithinEditorContext<T>(fn: (accessor: ServicesAccessor) => T): T {
throw new Error('not implemented');
}
createInput(_input: IResourceInput | IUntitledResourceInput | IResourceDiffInput | IResourceSideBySideInput): IEditorInput {
throw new Error('not implemented');
}
}
export class TestFileService implements IFileService {
public _serviceBrand: undefined;
private readonly _onFileChanges: Emitter<FileChangesEvent>;
private readonly _onAfterOperation: Emitter<FileOperationEvent>;
readonly onWillActivateFileSystemProvider = Event.None;
readonly onError: Event<Error> = Event.None;
private content = 'Hello Html';
private lastReadFileUri: URI;
constructor() {
this._onFileChanges = new Emitter<FileChangesEvent>();
this._onAfterOperation = new Emitter<FileOperationEvent>();
}
public setContent(content: string): void {
this.content = content;
}
public getContent(): string {
return this.content;
}
public getLastReadFileUri(): URI {
return this.lastReadFileUri;
}
public get onFileChanges(): Event<FileChangesEvent> {
return this._onFileChanges.event;
}
public fireFileChanges(event: FileChangesEvent): void {
this._onFileChanges.fire(event);
}
public get onAfterOperation(): Event<FileOperationEvent> {
return this._onAfterOperation.event;
}
public fireAfterOperation(event: FileOperationEvent): void {
this._onAfterOperation.fire(event);
}
resolve(resource: URI, _options?: IResolveFileOptions): Promise<IFileStat>;
resolve(resource: URI, _options: IResolveMetadataFileOptions): Promise<IFileStatWithMetadata>;
resolve(resource: URI, _options?: IResolveFileOptions): Promise<IFileStat> {
return Promise.resolve({
resource,
etag: Date.now().toString(),
encoding: 'utf8',
mtime: Date.now(),
size: 42,
isDirectory: false,
name: resources.basename(resource)
});
}
resolveAll(toResolve: { resource: URI, options?: IResolveFileOptions }[]): Promise<IResolveFileResult[]> {
return Promise.all(toResolve.map(resourceAndOption => this.resolve(resourceAndOption.resource, resourceAndOption.options))).then(stats => stats.map(stat => ({ stat, success: true })));
}
exists(_resource: URI): Promise<boolean> {
return Promise.resolve(true);
}
readFile(resource: URI, options?: IReadFileOptions | undefined): Promise<IFileContent> {
this.lastReadFileUri = resource;
return Promise.resolve({
resource: resource,
value: VSBuffer.fromString(this.content),
etag: 'index.txt',
encoding: 'utf8',
mtime: Date.now(),
name: resources.basename(resource),
size: 1
});
}
readFileStream(resource: URI, options?: IReadFileOptions | undefined): Promise<IFileStreamContent> {
this.lastReadFileUri = resource;
return Promise.resolve({
resource: resource,
value: {
on: (event: string, callback: Function): void => {
if (event === 'data') {
callback(this.content);
}
if (event === 'end') {
callback();
}
},
resume: () => { },
pause: () => { },
destroy: () => { }
},
etag: 'index.txt',
encoding: 'utf8',
mtime: Date.now(),
size: 1,
name: resources.basename(resource)
});
}
writeFile(resource: URI, bufferOrReadable: VSBuffer | VSBufferReadable, options?: IWriteFileOptions): Promise<IFileStatWithMetadata> {
return timeout(0).then(() => ({
resource,
etag: 'index.txt',
encoding: 'utf8',
mtime: Date.now(),
size: 42,
isDirectory: false,
name: resources.basename(resource)
}));
}
move(_source: URI, _target: URI, _overwrite?: boolean): Promise<IFileStatWithMetadata> {
return Promise.resolve(null!);
}
copy(_source: URI, _target: URI, _overwrite?: boolean): Promise<IFileStatWithMetadata> {
throw new Error('not implemented');
}
createFile(_resource: URI, _content?: VSBuffer | VSBufferReadable, _options?: ICreateFileOptions): Promise<IFileStatWithMetadata> {
throw new Error('not implemented');
}
createFolder(_resource: URI): Promise<IFileStatWithMetadata> {
throw new Error('not implemented');
}
onDidChangeFileSystemProviderRegistrations = Event.None;
private providers = new Map<string, IFileSystemProvider>();
registerProvider(scheme: string, provider: IFileSystemProvider) {
this.providers.set(scheme, provider);
return toDisposable(() => this.providers.delete(scheme));
}
activateProvider(_scheme: string): Promise<void> {
throw new Error('not implemented');
}
canHandleResource(resource: URI): boolean {
return resource.scheme === 'file' || this.providers.has(resource.scheme);
}
hasCapability(resource: URI, capability: FileSystemProviderCapabilities): boolean { return false; }
del(_resource: URI, _options?: { useTrash?: boolean, recursive?: boolean }): Promise<void> {
return Promise.resolve();
}
watch(_resource: URI): IDisposable {
return Disposable.None;
}
getWriteEncoding(_resource: URI): IResourceEncoding {
return { encoding: 'utf8', hasBOM: false };
}
dispose(): void {
}
}
export class TestBackupFileService implements IBackupFileService {
public _serviceBrand: undefined;
public hasBackups(): Promise<boolean> {
return Promise.resolve(false);
}
public hasBackup(_resource: URI): Promise<boolean> {
return Promise.resolve(false);
}
public hasBackupSync(resource: URI, versionId?: number): boolean {
return false;
}
public loadBackupResource(resource: URI): Promise<URI | undefined> {
return this.hasBackup(resource).then(hasBackup => {
if (hasBackup) {
return this.toBackupResource(resource);
}
return undefined;
});
}
public registerResourceForBackup(_resource: URI): Promise<void> {
return Promise.resolve();
}
public deregisterResourceForBackup(_resource: URI): Promise<void> {
return Promise.resolve();
}
public toBackupResource(_resource: URI): URI {
throw new Error('not implemented');
}
public backupResource<T extends object>(_resource: URI, _content: ITextSnapshot, versionId?: number, meta?: T): Promise<void> {
return Promise.resolve();
}
public getWorkspaceFileBackups(): Promise<URI[]> {
return Promise.resolve([]);
}
public parseBackupContent(textBufferFactory: ITextBufferFactory): string {
const textBuffer = textBufferFactory.create(DefaultEndOfLine.LF);
const lineCount = textBuffer.getLineCount();
const range = new Range(1, 1, lineCount, textBuffer.getLineLength(lineCount) + 1);
return textBuffer.getValueInRange(range, EndOfLinePreference.TextDefined);
}
public resolveBackupContent<T extends object>(_backup: URI): Promise<IResolvedBackup<T>> {
throw new Error('not implemented');
}
public discardResourceBackup(_resource: URI): Promise<void> {
return Promise.resolve();
}
public discardAllWorkspaceBackups(): Promise<void> {
return Promise.resolve();
}
}
export class TestCodeEditorService implements ICodeEditorService {
_serviceBrand: undefined;
onCodeEditorAdd: Event<ICodeEditor> = Event.None;
onCodeEditorRemove: Event<ICodeEditor> = Event.None;
onDiffEditorAdd: Event<IDiffEditor> = Event.None;
onDiffEditorRemove: Event<IDiffEditor> = Event.None;
onDidChangeTransientModelProperty: Event<ITextModel> = Event.None;
addCodeEditor(_editor: ICodeEditor): void { }
removeCodeEditor(_editor: ICodeEditor): void { }
listCodeEditors(): ICodeEditor[] { return []; }
addDiffEditor(_editor: IDiffEditor): void { }
removeDiffEditor(_editor: IDiffEditor): void { }
listDiffEditors(): IDiffEditor[] { return []; }
getFocusedCodeEditor(): ICodeEditor | undefined { return undefined; }
registerDecorationType(_key: string, _options: IDecorationRenderOptions, _parentTypeKey?: string): void { }
removeDecorationType(_key: string): void { }
resolveDecorationOptions(_typeKey: string, _writable: boolean): IModelDecorationOptions { return Object.create(null); }
setTransientModelProperty(_model: ITextModel, _key: string, _value: any): void { }
getTransientModelProperty(_model: ITextModel, _key: string) { }
getActiveCodeEditor(): ICodeEditor | undefined { return undefined; }
openCodeEditor(_input: IResourceInput, _source: ICodeEditor, _sideBySide?: boolean): Promise<ICodeEditor | undefined> { return Promise.resolve(undefined); }
}
export class TestWindowService implements IWindowService {
public _serviceBrand: undefined;
onDidChangeFocus: Event<boolean> = new Emitter<boolean>().event;
onDidChangeMaximize: Event<boolean>;
hasFocus = true;
readonly windowId = 0;
isFocused(): Promise<boolean> {
return Promise.resolve(false);
}
isMaximized(): Promise<boolean> {
return Promise.resolve(false);
}
enterWorkspace(_path: URI): Promise<IEnterWorkspaceResult | undefined> {
return Promise.resolve(undefined);
}
getRecentlyOpened(): Promise<IRecentlyOpened> {
return Promise.resolve({
workspaces: [],
files: []
});
}
addRecentlyOpened(_recents: IRecent[]): Promise<void> {
return Promise.resolve();
}
removeFromRecentlyOpened(_paths: URI[]): Promise<void> {
return Promise.resolve();
}
focusWindow(): Promise<void> {
return Promise.resolve();
}
maximizeWindow(): Promise<void> {
return Promise.resolve();
}
unmaximizeWindow(): Promise<void> {
return Promise.resolve();
}
minimizeWindow(): Promise<void> {
return Promise.resolve();
}
openWindow(_uris: IURIToOpen[], _options?: IOpenSettings): Promise<void> {
return Promise.resolve();
}
closeWindow(): Promise<void> {
return Promise.resolve();
}
}
export class TestLifecycleService implements ILifecycleService {
public _serviceBrand: undefined;
public phase: LifecyclePhase;
public startupKind: StartupKind;
private readonly _onBeforeShutdown = new Emitter<BeforeShutdownEvent>();
private readonly _onWillShutdown = new Emitter<WillShutdownEvent>();
private readonly _onShutdown = new Emitter<void>();
when(): Promise<void> {
return Promise.resolve();
}
public fireShutdown(reason = ShutdownReason.QUIT): void {
this._onWillShutdown.fire({
join: () => { },
reason
});
}
public fireWillShutdown(event: BeforeShutdownEvent): void {
this._onBeforeShutdown.fire(event);
}
public get onBeforeShutdown(): Event<BeforeShutdownEvent> {
return this._onBeforeShutdown.event;
}
public get onWillShutdown(): Event<WillShutdownEvent> {
return this._onWillShutdown.event;
}
public get onShutdown(): Event<void> {
return this._onShutdown.event;
}
}
export class TestWindowsService implements IWindowsService {
_serviceBrand: undefined;
readonly onWindowOpen: Event<number> = Event.None;
readonly onWindowFocus: Event<number> = Event.None;
readonly onWindowBlur: Event<number> = Event.None;
readonly onWindowMaximize: Event<number> = Event.None;
readonly onWindowUnmaximize: Event<number> = Event.None;
readonly onRecentlyOpenedChange: Event<void> = Event.None;
isFocused(_windowId: number): Promise<boolean> {
return Promise.resolve(false);
}
enterWorkspace(_windowId: number, _path: URI): Promise<IEnterWorkspaceResult | undefined> {
return Promise.resolve(undefined);
}
addRecentlyOpened(_recents: IRecent[]): Promise<void> {
return Promise.resolve();
}
removeFromRecentlyOpened(_paths: URI[]): Promise<void> {
return Promise.resolve();
}
clearRecentlyOpened(): Promise<void> {
return Promise.resolve();
}
getRecentlyOpened(_windowId: number): Promise<IRecentlyOpened> {
return Promise.resolve({
workspaces: [],
files: []
});
}
focusWindow(_windowId: number): Promise<void> {
return Promise.resolve();
}
closeWindow(_windowId: number): Promise<void> {
return Promise.resolve();
}
isMaximized(_windowId: number): Promise<boolean> {
return Promise.resolve(false);
}
maximizeWindow(_windowId: number): Promise<void> {
return Promise.resolve();
}
minimizeWindow(_windowId: number): Promise<void> {
return Promise.resolve();
}
unmaximizeWindow(_windowId: number): Promise<void> {
return Promise.resolve();
}
// Global methods
openWindow(_windowId: number, _uris: IURIToOpen[], _options: IOpenSettings): Promise<void> {
return Promise.resolve();
}
openExtensionDevelopmentHostWindow(args: ParsedArgs, env: IProcessEnvironment): Promise<void> {
return Promise.resolve();
}
getWindows(): Promise<{ id: number; workspace?: IWorkspaceIdentifier; folderUri?: ISingleFolderWorkspaceIdentifier; title: string; filename?: string; }[]> {
throw new Error('not implemented');
}
getActiveWindowId(): Promise<number | undefined> {
return Promise.resolve(undefined);
}
}
export class TestTextResourceConfigurationService implements ITextResourceConfigurationService {
_serviceBrand: undefined;
constructor(private configurationService = new TestConfigurationService()) {
}
public onDidChangeConfiguration() {
return { dispose() { } };
}
getValue<T>(resource: URI, arg2?: any, arg3?: any): T {
const position: IPosition | null = EditorPosition.isIPosition(arg2) ? arg2 : null;
const section: string | undefined = position ? (typeof arg3 === 'string' ? arg3 : undefined) : (typeof arg2 === 'string' ? arg2 : undefined);
return this.configurationService.getValue(section, { resource });
}
}
export class TestTextResourcePropertiesService implements ITextResourcePropertiesService {
_serviceBrand: undefined;
constructor(
@IConfigurationService private readonly configurationService: IConfigurationService,
) {
}
getEOL(resource: URI): string {
const filesConfiguration = this.configurationService.getValue<{ eol: string }>('files');
if (filesConfiguration && filesConfiguration.eol) {
if (filesConfiguration.eol !== 'auto') {
return filesConfiguration.eol;
}
}
return (isLinux || isMacintosh) ? '\n' : '\r\n';
}
}
export class TestSharedProcessService implements ISharedProcessService {
_serviceBrand: undefined;
getChannel(channelName: string): any {
return undefined;
}
registerChannel(channelName: string, channel: any): void { }
async toggleSharedProcessWindow(): Promise<void> { }
async whenSharedProcessReady(): Promise<void> { }
}
export class RemoteFileSystemProvider implements IFileSystemProvider {
constructor(private readonly diskFileSystemProvider: IFileSystemProvider, private readonly remoteAuthority: string) { }
readonly capabilities: FileSystemProviderCapabilities = this.diskFileSystemProvider.capabilities;
readonly onDidChangeCapabilities: Event<void> = this.diskFileSystemProvider.onDidChangeCapabilities;
readonly onDidChangeFile: Event<IFileChange[]> = Event.map(this.diskFileSystemProvider.onDidChangeFile, changes => changes.map(c => { c.resource = c.resource.with({ scheme: Schemas.vscodeRemote, authority: this.remoteAuthority }); return c; }));
watch(resource: URI, opts: IWatchOptions): IDisposable { return this.diskFileSystemProvider.watch(this.toFileResource(resource), opts); }
stat(resource: URI): Promise<IStat> { return this.diskFileSystemProvider.stat(this.toFileResource(resource)); }
mkdir(resource: URI): Promise<void> { return this.diskFileSystemProvider.mkdir(this.toFileResource(resource)); }
readdir(resource: URI): Promise<[string, FileType][]> { return this.diskFileSystemProvider.readdir(this.toFileResource(resource)); }
delete(resource: URI, opts: FileDeleteOptions): Promise<void> { return this.diskFileSystemProvider.delete(this.toFileResource(resource), opts); }
rename(from: URI, to: URI, opts: FileOverwriteOptions): Promise<void> { return this.diskFileSystemProvider.rename(this.toFileResource(from), this.toFileResource(to), opts); }
copy(from: URI, to: URI, opts: FileOverwriteOptions): Promise<void> { return this.diskFileSystemProvider.copy!(this.toFileResource(from), this.toFileResource(to), opts); }
readFile(resource: URI): Promise<Uint8Array> { return this.diskFileSystemProvider.readFile!(this.toFileResource(resource)); }
writeFile(resource: URI, content: Uint8Array, opts: FileWriteOptions): Promise<void> { return this.diskFileSystemProvider.writeFile!(this.toFileResource(resource), content, opts); }
open(resource: URI, opts: FileOpenOptions): Promise<number> { return this.diskFileSystemProvider.open!(this.toFileResource(resource), opts); }
close(fd: number): Promise<void> { return this.diskFileSystemProvider.close!(fd); }
read(fd: number, pos: number, data: Uint8Array, offset: number, length: number): Promise<number> { return this.diskFileSystemProvider.read!(fd, pos, data, offset, length); }
write(fd: number, pos: number, data: Uint8Array, offset: number, length: number): Promise<number> { return this.diskFileSystemProvider.write!(fd, pos, data, offset, length); }
private toFileResource(resource: URI): URI { return resource.with({ scheme: Schemas.file, authority: '' }); }
}
export const productService: IProductService = { _serviceBrand: undefined, ...product };
export class TestHostService implements IHostService {
_serviceBrand: undefined;
windowCount = Promise.resolve(1);
async restart(): Promise<void> { }
async reload(): Promise<void> { }
async closeWorkspace(): Promise<void> { }
async openEmptyWindow(options?: { reuse?: boolean, remoteAuthority?: string }): Promise<void> { }
async toggleFullScreen(): Promise<void> { }
}
| src/vs/workbench/test/workbenchTestServices.ts | 1 | https://github.com/microsoft/vscode/commit/23f2275c23aeebf5e22f3d19a20528c8ba48c570 | [
0.0013394386041909456,
0.00019116057956125587,
0.0001591153850313276,
0.00017171940999105573,
0.00013073152513243258
] |
{
"id": 1,
"code_window": [
"\t\t\t\t\t}\n",
"\t\t\t\t});\n",
"\t\t\t\toptions.waitMarkerFileURI = options.waitMarkerFileURI && URI.revive(options.waitMarkerFileURI);\n",
"\t\t\t\treturn this.service.openWindow(arg[0], urisToOpen, options);\n",
"\t\t\t}\n",
"\t\t\tcase 'openExtensionDevelopmentHostWindow': return this.service.openExtensionDevelopmentHostWindow(arg[0], arg[1]);\n",
"\t\t\tcase 'getWindows': return this.service.getWindows();\n",
"\t\t\tcase 'getActiveWindowId': return this.service.getActiveWindowId();\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tcase 'openExtensionDevelopmentHostWindow': return (this.service as any).openExtensionDevelopmentHostWindow(arg[0], arg[1]); // TODO@Isidor move\n"
],
"file_path": "src/vs/platform/windows/common/windowsIpc.ts",
"type": "replace",
"edit_start_line_idx": 81
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import { Command } from '../commandManager';
import { PreviewSecuritySelector } from '../security';
import { isMarkdownFile } from '../util/file';
import { MarkdownPreviewManager } from '../features/previewManager';
export class ShowPreviewSecuritySelectorCommand implements Command {
public readonly id = 'markdown.showPreviewSecuritySelector';
public constructor(
private readonly previewSecuritySelector: PreviewSecuritySelector,
private readonly previewManager: MarkdownPreviewManager
) { }
public execute(resource: string | undefined) {
if (this.previewManager.activePreviewResource) {
this.previewSecuritySelector.showSecuritySelectorForResource(this.previewManager.activePreviewResource);
} else if (resource) {
const source = vscode.Uri.parse(resource);
this.previewSecuritySelector.showSecuritySelectorForResource(source.query ? vscode.Uri.parse(source.query) : source);
} else if (vscode.window.activeTextEditor && isMarkdownFile(vscode.window.activeTextEditor.document)) {
this.previewSecuritySelector.showSecuritySelectorForResource(vscode.window.activeTextEditor.document.uri);
}
}
} | extensions/markdown-language-features/src/commands/showPreviewSecuritySelector.ts | 0 | https://github.com/microsoft/vscode/commit/23f2275c23aeebf5e22f3d19a20528c8ba48c570 | [
0.00017605333414394408,
0.00017384898092132062,
0.00017176975961774588,
0.0001737864367896691,
0.0000015651175999664702
] |
{
"id": 1,
"code_window": [
"\t\t\t\t\t}\n",
"\t\t\t\t});\n",
"\t\t\t\toptions.waitMarkerFileURI = options.waitMarkerFileURI && URI.revive(options.waitMarkerFileURI);\n",
"\t\t\t\treturn this.service.openWindow(arg[0], urisToOpen, options);\n",
"\t\t\t}\n",
"\t\t\tcase 'openExtensionDevelopmentHostWindow': return this.service.openExtensionDevelopmentHostWindow(arg[0], arg[1]);\n",
"\t\t\tcase 'getWindows': return this.service.getWindows();\n",
"\t\t\tcase 'getActiveWindowId': return this.service.getActiveWindowId();\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tcase 'openExtensionDevelopmentHostWindow': return (this.service as any).openExtensionDevelopmentHostWindow(arg[0], arg[1]); // TODO@Isidor move\n"
],
"file_path": "src/vs/platform/windows/common/windowsIpc.ts",
"type": "replace",
"edit_start_line_idx": 81
} | test/**
.vscode/**
server/.vscode/**
server/node_modules/**
client/src/**
server/src/**
client/out/**
server/out/**
client/tsconfig.json
server/tsconfig.json
server/test/**
server/bin/**
server/build/**
server/yarn.lock
server/.npmignore
yarn.lock
server/extension.webpack.config.js
extension.webpack.config.js
CONTRIBUTING.md | extensions/css-language-features/.vscodeignore | 0 | https://github.com/microsoft/vscode/commit/23f2275c23aeebf5e22f3d19a20528c8ba48c570 | [
0.00017564004519954324,
0.00017459431546740234,
0.00017354860028717667,
0.00017459431546740234,
0.0000010457224561832845
] |
{
"id": 1,
"code_window": [
"\t\t\t\t\t}\n",
"\t\t\t\t});\n",
"\t\t\t\toptions.waitMarkerFileURI = options.waitMarkerFileURI && URI.revive(options.waitMarkerFileURI);\n",
"\t\t\t\treturn this.service.openWindow(arg[0], urisToOpen, options);\n",
"\t\t\t}\n",
"\t\t\tcase 'openExtensionDevelopmentHostWindow': return this.service.openExtensionDevelopmentHostWindow(arg[0], arg[1]);\n",
"\t\t\tcase 'getWindows': return this.service.getWindows();\n",
"\t\t\tcase 'getActiveWindowId': return this.service.getActiveWindowId();\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tcase 'openExtensionDevelopmentHostWindow': return (this.service as any).openExtensionDevelopmentHostWindow(arg[0], arg[1]); // TODO@Isidor move\n"
],
"file_path": "src/vs/platform/windows/common/windowsIpc.ts",
"type": "replace",
"edit_start_line_idx": 81
} | /*---------------------------------------------------------------------------------------------
* 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 { LinkedList } from 'vs/base/common/linkedList';
suite('LinkedList', function () {
function assertElements<E>(list: LinkedList<E>, ...elements: E[]) {
// check size
assert.equal(list.size, elements.length);
// assert toArray
assert.deepEqual(list.toArray(), elements);
// assert iterator
for (let iter = list.iterator(), element = iter.next(); !element.done; element = iter.next()) {
assert.equal(elements.shift(), element.value);
}
assert.equal(elements.length, 0);
}
test('Push/Iter', () => {
const list = new LinkedList<number>();
list.push(0);
list.push(1);
list.push(2);
assertElements(list, 0, 1, 2);
});
test('Push/Remove', () => {
let list = new LinkedList<number>();
let disp = list.push(0);
list.push(1);
list.push(2);
disp();
assertElements(list, 1, 2);
list = new LinkedList<number>();
list.push(0);
disp = list.push(1);
list.push(2);
disp();
assertElements(list, 0, 2);
list = new LinkedList<number>();
list.push(0);
list.push(1);
disp = list.push(2);
disp();
assertElements(list, 0, 1);
list = new LinkedList<number>();
list.push(0);
list.push(1);
disp = list.push(2);
disp();
disp();
assertElements(list, 0, 1);
});
test('Push/toArray', () => {
let list = new LinkedList<string>();
list.push('foo');
list.push('bar');
list.push('far');
list.push('boo');
assertElements(list, 'foo', 'bar', 'far', 'boo');
});
test('unshift/Iter', () => {
const list = new LinkedList<number>();
list.unshift(0);
list.unshift(1);
list.unshift(2);
assertElements(list, 2, 1, 0);
});
test('unshift/Remove', () => {
let list = new LinkedList<number>();
let disp = list.unshift(0);
list.unshift(1);
list.unshift(2);
disp();
assertElements(list, 2, 1);
list = new LinkedList<number>();
list.unshift(0);
disp = list.unshift(1);
list.unshift(2);
disp();
assertElements(list, 2, 0);
list = new LinkedList<number>();
list.unshift(0);
list.unshift(1);
disp = list.unshift(2);
disp();
assertElements(list, 1, 0);
});
test('unshift/toArray', () => {
let list = new LinkedList<string>();
list.unshift('foo');
list.unshift('bar');
list.unshift('far');
list.unshift('boo');
assertElements(list, 'boo', 'far', 'bar', 'foo');
});
test('pop/unshift', function () {
let list = new LinkedList<string>();
list.push('a');
list.push('b');
assertElements(list, 'a', 'b');
let a = list.shift();
assert.equal(a, 'a');
assertElements(list, 'b');
list.unshift('a');
assertElements(list, 'a', 'b');
let b = list.pop();
assert.equal(b, 'b');
assertElements(list, 'a');
});
});
| src/vs/base/test/common/linkedList.test.ts | 0 | https://github.com/microsoft/vscode/commit/23f2275c23aeebf5e22f3d19a20528c8ba48c570 | [
0.00017754509462974966,
0.000175459761521779,
0.00017316760204266757,
0.0001754406257532537,
0.0000012743569186568493
] |
{
"id": 2,
"code_window": [
"import { addDisposableListener, EventType } from 'vs/base/browser/dom';\n",
"import { IEditorService, IResourceEditor } from 'vs/workbench/services/editor/common/editorService';\n",
"import { pathsToEditors } from 'vs/workbench/common/editor';\n",
"import { IFileService } from 'vs/platform/files/common/files';\n",
"import { IConfigurationService } from 'vs/platform/configuration/common/configuration';\n",
"import { ParsedArgs } from 'vs/platform/environment/common/environment';\n",
"import { IProcessEnvironment } from 'vs/base/common/platform';\n",
"import { toStoreData, restoreRecentlyOpened } from 'vs/platform/history/common/historyStorage';\n",
"\n",
"//#region Window\n",
"\n",
"export class SimpleWindowService extends Disposable implements IWindowService {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/browser/web.simpleservices.ts",
"type": "replace",
"edit_start_line_idx": 21
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { IExtensionHostDebugService } from 'vs/platform/debug/common/extensionHostDebug';
import { IMainProcessService } from 'vs/platform/ipc/electron-browser/mainProcessService';
import { ExtensionHostDebugChannelClient, ExtensionHostDebugBroadcastChannel } from 'vs/platform/debug/common/extensionHostDebugIpc';
import { IWindowsService } from 'vs/platform/windows/common/windows';
import { IProcessEnvironment } from 'vs/base/common/platform';
import { ParsedArgs } from 'vs/platform/environment/common/environment';
export class ExtensionHostDebugService extends ExtensionHostDebugChannelClient {
constructor(
@IMainProcessService readonly mainProcessService: IMainProcessService,
@IWindowsService private readonly windowsService: IWindowsService
) {
super(mainProcessService.getChannel(ExtensionHostDebugBroadcastChannel.ChannelName));
}
openExtensionDevelopmentHostWindow(args: ParsedArgs, env: IProcessEnvironment): Promise<void> {
// TODO@Isidor use debug IPC channel
return this.windowsService.openExtensionDevelopmentHostWindow(args, env);
}
}
registerSingleton(IExtensionHostDebugService, ExtensionHostDebugService, true);
| src/vs/workbench/contrib/debug/electron-browser/extensionHostDebugService.ts | 1 | https://github.com/microsoft/vscode/commit/23f2275c23aeebf5e22f3d19a20528c8ba48c570 | [
0.0015773342456668615,
0.0006365606677718461,
0.00016584384138695896,
0.00016650394536554813,
0.0006652274169027805
] |
{
"id": 2,
"code_window": [
"import { addDisposableListener, EventType } from 'vs/base/browser/dom';\n",
"import { IEditorService, IResourceEditor } from 'vs/workbench/services/editor/common/editorService';\n",
"import { pathsToEditors } from 'vs/workbench/common/editor';\n",
"import { IFileService } from 'vs/platform/files/common/files';\n",
"import { IConfigurationService } from 'vs/platform/configuration/common/configuration';\n",
"import { ParsedArgs } from 'vs/platform/environment/common/environment';\n",
"import { IProcessEnvironment } from 'vs/base/common/platform';\n",
"import { toStoreData, restoreRecentlyOpened } from 'vs/platform/history/common/historyStorage';\n",
"\n",
"//#region Window\n",
"\n",
"export class SimpleWindowService extends Disposable implements IWindowService {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/browser/web.simpleservices.ts",
"type": "replace",
"edit_start_line_idx": 21
} | test/**
cgmanifest.json
| extensions/go/.vscodeignore | 0 | https://github.com/microsoft/vscode/commit/23f2275c23aeebf5e22f3d19a20528c8ba48c570 | [
0.00016879223403520882,
0.00016879223403520882,
0.00016879223403520882,
0.00016879223403520882,
0
] |
{
"id": 2,
"code_window": [
"import { addDisposableListener, EventType } from 'vs/base/browser/dom';\n",
"import { IEditorService, IResourceEditor } from 'vs/workbench/services/editor/common/editorService';\n",
"import { pathsToEditors } from 'vs/workbench/common/editor';\n",
"import { IFileService } from 'vs/platform/files/common/files';\n",
"import { IConfigurationService } from 'vs/platform/configuration/common/configuration';\n",
"import { ParsedArgs } from 'vs/platform/environment/common/environment';\n",
"import { IProcessEnvironment } from 'vs/base/common/platform';\n",
"import { toStoreData, restoreRecentlyOpened } from 'vs/platform/history/common/historyStorage';\n",
"\n",
"//#region Window\n",
"\n",
"export class SimpleWindowService extends Disposable implements IWindowService {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/browser/web.simpleservices.ts",
"type": "replace",
"edit_start_line_idx": 21
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.monaco-workbench .part > .content > .composite {
height: 100%;
}
.monaco-workbench .part > .composite.title {
display: flex;
}
.monaco-workbench .part > .composite.title > .title-actions {
flex: 1;
padding-left: 5px;
} | src/vs/workbench/browser/parts/media/compositepart.css | 0 | https://github.com/microsoft/vscode/commit/23f2275c23aeebf5e22f3d19a20528c8ba48c570 | [
0.00017125003796536475,
0.0001687635522102937,
0.00016627706645522267,
0.0001687635522102937,
0.000002486485755071044
] |
{
"id": 2,
"code_window": [
"import { addDisposableListener, EventType } from 'vs/base/browser/dom';\n",
"import { IEditorService, IResourceEditor } from 'vs/workbench/services/editor/common/editorService';\n",
"import { pathsToEditors } from 'vs/workbench/common/editor';\n",
"import { IFileService } from 'vs/platform/files/common/files';\n",
"import { IConfigurationService } from 'vs/platform/configuration/common/configuration';\n",
"import { ParsedArgs } from 'vs/platform/environment/common/environment';\n",
"import { IProcessEnvironment } from 'vs/base/common/platform';\n",
"import { toStoreData, restoreRecentlyOpened } from 'vs/platform/history/common/historyStorage';\n",
"\n",
"//#region Window\n",
"\n",
"export class SimpleWindowService extends Disposable implements IWindowService {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/browser/web.simpleservices.ts",
"type": "replace",
"edit_start_line_idx": 21
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import * as types from 'vs/base/common/types';
import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { KeybindingsRegistry, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { TextCompareEditorVisibleContext, EditorInput, IEditorIdentifier, IEditorCommandsContext, ActiveEditorGroupEmptyContext, MultipleEditorGroupsContext, CloseDirection, IEditor, IEditorInput } from 'vs/workbench/common/editor';
import { IEditorService, IVisibleEditor } from 'vs/workbench/services/editor/common/editorService';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { TextDiffEditor } from 'vs/workbench/browser/parts/editor/textDiffEditor';
import { KeyMod, KeyCode, KeyChord } from 'vs/base/common/keyCodes';
import { URI } from 'vs/base/common/uri';
import { IQuickOpenService } from 'vs/platform/quickOpen/common/quickOpen';
import { IListService } from 'vs/platform/list/browser/listService';
import { List } from 'vs/base/browser/ui/list/listWidget';
import { distinct, coalesce } from 'vs/base/common/arrays';
import { IEditorGroupsService, IEditorGroup, GroupDirection, GroupLocation, GroupsOrder, preferredSideBySideGroupDirection, EditorGroupLayout } from 'vs/workbench/services/editor/common/editorGroupsService';
import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { IConfigurationService, ConfigurationTarget } from 'vs/platform/configuration/common/configuration';
import { CommandsRegistry, ICommandHandler } from 'vs/platform/commands/common/commands';
import { MenuRegistry, MenuId } from 'vs/platform/actions/common/actions';
export const CLOSE_SAVED_EDITORS_COMMAND_ID = 'workbench.action.closeUnmodifiedEditors';
export const CLOSE_EDITORS_IN_GROUP_COMMAND_ID = 'workbench.action.closeEditorsInGroup';
export const CLOSE_EDITORS_AND_GROUP_COMMAND_ID = 'workbench.action.closeEditorsAndGroup';
export const CLOSE_EDITORS_TO_THE_RIGHT_COMMAND_ID = 'workbench.action.closeEditorsToTheRight';
export const CLOSE_EDITOR_COMMAND_ID = 'workbench.action.closeActiveEditor';
export const CLOSE_EDITOR_GROUP_COMMAND_ID = 'workbench.action.closeGroup';
export const CLOSE_OTHER_EDITORS_IN_GROUP_COMMAND_ID = 'workbench.action.closeOtherEditors';
export const MOVE_ACTIVE_EDITOR_COMMAND_ID = 'moveActiveEditor';
export const LAYOUT_EDITOR_GROUPS_COMMAND_ID = 'layoutEditorGroups';
export const KEEP_EDITOR_COMMAND_ID = 'workbench.action.keepEditor';
export const SHOW_EDITORS_IN_GROUP = 'workbench.action.showEditorsInGroup';
export const TOGGLE_DIFF_SIDE_BY_SIDE = 'toggle.diff.renderSideBySide';
export const GOTO_NEXT_CHANGE = 'workbench.action.compareEditor.nextChange';
export const GOTO_PREVIOUS_CHANGE = 'workbench.action.compareEditor.previousChange';
export const TOGGLE_DIFF_IGNORE_TRIM_WHITESPACE = 'toggle.diff.ignoreTrimWhitespace';
export const SPLIT_EDITOR_UP = 'workbench.action.splitEditorUp';
export const SPLIT_EDITOR_DOWN = 'workbench.action.splitEditorDown';
export const SPLIT_EDITOR_LEFT = 'workbench.action.splitEditorLeft';
export const SPLIT_EDITOR_RIGHT = 'workbench.action.splitEditorRight';
export const NAVIGATE_ALL_EDITORS_GROUP_PREFIX = 'edt ';
export const NAVIGATE_IN_ACTIVE_GROUP_PREFIX = 'edt active ';
export const OPEN_EDITOR_AT_INDEX_COMMAND_ID = 'workbench.action.openEditorAtIndex';
export interface ActiveEditorMoveArguments {
to: 'first' | 'last' | 'left' | 'right' | 'up' | 'down' | 'center' | 'position' | 'previous' | 'next';
by: 'tab' | 'group';
value: number;
}
const isActiveEditorMoveArg = function (arg: ActiveEditorMoveArguments): boolean {
if (!types.isObject(arg)) {
return false;
}
if (!types.isString(arg.to)) {
return false;
}
if (!types.isUndefined(arg.by) && !types.isString(arg.by)) {
return false;
}
if (!types.isUndefined(arg.value) && !types.isNumber(arg.value)) {
return false;
}
return true;
};
function registerActiveEditorMoveCommand(): void {
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: MOVE_ACTIVE_EDITOR_COMMAND_ID,
weight: KeybindingWeight.WorkbenchContrib,
when: EditorContextKeys.editorTextFocus,
primary: 0,
handler: (accessor, args: any) => moveActiveEditor(args, accessor),
description: {
description: nls.localize('editorCommand.activeEditorMove.description', "Move the active editor by tabs or groups"),
args: [
{
name: nls.localize('editorCommand.activeEditorMove.arg.name', "Active editor move argument"),
description: nls.localize('editorCommand.activeEditorMove.arg.description', "Argument Properties:\n\t* 'to': String value providing where to move.\n\t* 'by': String value providing the unit for move (by tab or by group).\n\t* 'value': Number value providing how many positions or an absolute position to move."),
constraint: isActiveEditorMoveArg,
schema: {
'type': 'object',
'required': ['to'],
'properties': {
'to': {
'type': 'string',
'enum': ['left', 'right']
},
'by': {
'type': 'string',
'enum': ['tab', 'group']
},
'value': {
'type': 'number'
}
},
}
}
]
}
});
}
function moveActiveEditor(args: ActiveEditorMoveArguments = Object.create(null), accessor: ServicesAccessor): void {
args.to = args.to || 'right';
args.by = args.by || 'tab';
args.value = typeof args.value === 'number' ? args.value : 1;
const activeControl = accessor.get(IEditorService).activeControl;
if (activeControl) {
switch (args.by) {
case 'tab':
return moveActiveTab(args, activeControl, accessor);
case 'group':
return moveActiveEditorToGroup(args, activeControl, accessor);
}
}
}
function moveActiveTab(args: ActiveEditorMoveArguments, control: IVisibleEditor, accessor: ServicesAccessor): void {
const group = control.group;
let index = group.getIndexOfEditor(control.input);
switch (args.to) {
case 'first':
index = 0;
break;
case 'last':
index = group.count - 1;
break;
case 'left':
index = index - args.value;
break;
case 'right':
index = index + args.value;
break;
case 'center':
index = Math.round(group.count / 2) - 1;
break;
case 'position':
index = args.value - 1;
break;
}
index = index < 0 ? 0 : index >= group.count ? group.count - 1 : index;
group.moveEditor(control.input, group, { index });
}
function moveActiveEditorToGroup(args: ActiveEditorMoveArguments, control: IVisibleEditor, accessor: ServicesAccessor): void {
const editorGroupService = accessor.get(IEditorGroupsService);
const configurationService = accessor.get(IConfigurationService);
const sourceGroup = control.group;
let targetGroup: IEditorGroup | undefined;
switch (args.to) {
case 'left':
targetGroup = editorGroupService.findGroup({ direction: GroupDirection.LEFT }, sourceGroup);
if (!targetGroup) {
targetGroup = editorGroupService.addGroup(sourceGroup, GroupDirection.LEFT);
}
break;
case 'right':
targetGroup = editorGroupService.findGroup({ direction: GroupDirection.RIGHT }, sourceGroup);
if (!targetGroup) {
targetGroup = editorGroupService.addGroup(sourceGroup, GroupDirection.RIGHT);
}
break;
case 'up':
targetGroup = editorGroupService.findGroup({ direction: GroupDirection.UP }, sourceGroup);
if (!targetGroup) {
targetGroup = editorGroupService.addGroup(sourceGroup, GroupDirection.UP);
}
break;
case 'down':
targetGroup = editorGroupService.findGroup({ direction: GroupDirection.DOWN }, sourceGroup);
if (!targetGroup) {
targetGroup = editorGroupService.addGroup(sourceGroup, GroupDirection.DOWN);
}
break;
case 'first':
targetGroup = editorGroupService.findGroup({ location: GroupLocation.FIRST }, sourceGroup);
break;
case 'last':
targetGroup = editorGroupService.findGroup({ location: GroupLocation.LAST }, sourceGroup);
break;
case 'previous':
targetGroup = editorGroupService.findGroup({ location: GroupLocation.PREVIOUS }, sourceGroup);
break;
case 'next':
targetGroup = editorGroupService.findGroup({ location: GroupLocation.NEXT }, sourceGroup);
if (!targetGroup) {
targetGroup = editorGroupService.addGroup(sourceGroup, preferredSideBySideGroupDirection(configurationService));
}
break;
case 'center':
targetGroup = editorGroupService.getGroups(GroupsOrder.GRID_APPEARANCE)[(editorGroupService.count / 2) - 1];
break;
case 'position':
targetGroup = editorGroupService.getGroups(GroupsOrder.GRID_APPEARANCE)[args.value - 1];
break;
}
if (targetGroup) {
sourceGroup.moveEditor(control.input, targetGroup);
targetGroup.focus();
}
}
function registerEditorGroupsLayoutCommand(): void {
CommandsRegistry.registerCommand(LAYOUT_EDITOR_GROUPS_COMMAND_ID, (accessor: ServicesAccessor, args: EditorGroupLayout) => {
if (!args || typeof args !== 'object') {
return;
}
const editorGroupService = accessor.get(IEditorGroupsService);
editorGroupService.applyLayout(args);
});
}
export function mergeAllGroups(editorGroupService: IEditorGroupsService): void {
const target = editorGroupService.activeGroup;
editorGroupService.getGroups(GroupsOrder.MOST_RECENTLY_ACTIVE).forEach(group => {
if (group === target) {
return; // keep target
}
editorGroupService.mergeGroup(group, target);
});
}
function registerDiffEditorCommands(): void {
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: GOTO_NEXT_CHANGE,
weight: KeybindingWeight.WorkbenchContrib,
when: TextCompareEditorVisibleContext,
primary: KeyMod.Alt | KeyCode.F5,
handler: accessor => navigateInDiffEditor(accessor, true)
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: GOTO_PREVIOUS_CHANGE,
weight: KeybindingWeight.WorkbenchContrib,
when: TextCompareEditorVisibleContext,
primary: KeyMod.Alt | KeyMod.Shift | KeyCode.F5,
handler: accessor => navigateInDiffEditor(accessor, false)
});
function navigateInDiffEditor(accessor: ServicesAccessor, next: boolean): void {
const editorService = accessor.get(IEditorService);
const candidates = [editorService.activeControl, ...editorService.visibleControls].filter(e => e instanceof TextDiffEditor);
if (candidates.length > 0) {
const navigator = (<TextDiffEditor>candidates[0]).getDiffNavigator();
if (navigator) {
next ? navigator.next() : navigator.previous();
}
}
}
function toggleDiffSideBySide(accessor: ServicesAccessor): void {
const configurationService = accessor.get(IConfigurationService);
const newValue = !configurationService.getValue<boolean>('diffEditor.renderSideBySide');
configurationService.updateValue('diffEditor.renderSideBySide', newValue, ConfigurationTarget.USER);
}
function toggleDiffIgnoreTrimWhitespace(accessor: ServicesAccessor): void {
const configurationService = accessor.get(IConfigurationService);
const newValue = !configurationService.getValue<boolean>('diffEditor.ignoreTrimWhitespace');
configurationService.updateValue('diffEditor.ignoreTrimWhitespace', newValue, ConfigurationTarget.USER);
}
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: TOGGLE_DIFF_SIDE_BY_SIDE,
weight: KeybindingWeight.WorkbenchContrib,
when: undefined,
primary: undefined,
handler: accessor => toggleDiffSideBySide(accessor)
});
MenuRegistry.appendMenuItem(MenuId.CommandPalette, {
command: {
id: TOGGLE_DIFF_SIDE_BY_SIDE,
title: {
value: nls.localize('toggleInlineView', "Toggle Inline View"),
original: 'Compare: Toggle Inline View'
},
category: nls.localize('compare', "Compare")
},
when: ContextKeyExpr.has('textCompareEditorActive')
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: TOGGLE_DIFF_IGNORE_TRIM_WHITESPACE,
weight: KeybindingWeight.WorkbenchContrib,
when: undefined,
primary: undefined,
handler: accessor => toggleDiffIgnoreTrimWhitespace(accessor)
});
}
function registerOpenEditorAtIndexCommands(): void {
const openEditorAtIndex: ICommandHandler = (accessor: ServicesAccessor, editorIndex: number): void => {
const editorService = accessor.get(IEditorService);
const activeControl = editorService.activeControl;
if (activeControl) {
const editor = activeControl.group.getEditor(editorIndex);
if (editor) {
editorService.openEditor(editor);
}
}
};
// This command takes in the editor index number to open as an argument
CommandsRegistry.registerCommand({
id: OPEN_EDITOR_AT_INDEX_COMMAND_ID,
handler: openEditorAtIndex
});
// Keybindings to focus a specific index in the tab folder if tabs are enabled
for (let i = 0; i < 9; i++) {
const editorIndex = i;
const visibleIndex = i + 1;
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: OPEN_EDITOR_AT_INDEX_COMMAND_ID + visibleIndex,
weight: KeybindingWeight.WorkbenchContrib,
when: undefined,
primary: KeyMod.Alt | toKeyCode(visibleIndex),
mac: { primary: KeyMod.WinCtrl | toKeyCode(visibleIndex) },
handler: accessor => openEditorAtIndex(accessor, editorIndex)
});
}
function toKeyCode(index: number): KeyCode {
switch (index) {
case 0: return KeyCode.KEY_0;
case 1: return KeyCode.KEY_1;
case 2: return KeyCode.KEY_2;
case 3: return KeyCode.KEY_3;
case 4: return KeyCode.KEY_4;
case 5: return KeyCode.KEY_5;
case 6: return KeyCode.KEY_6;
case 7: return KeyCode.KEY_7;
case 8: return KeyCode.KEY_8;
case 9: return KeyCode.KEY_9;
}
throw new Error('invalid index');
}
}
function registerFocusEditorGroupAtIndexCommands(): void {
// Keybindings to focus a specific group (2-8) in the editor area
for (let groupIndex = 1; groupIndex < 8; groupIndex++) {
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: toCommandId(groupIndex),
weight: KeybindingWeight.WorkbenchContrib,
when: undefined,
primary: KeyMod.CtrlCmd | toKeyCode(groupIndex),
handler: accessor => {
const editorGroupService = accessor.get(IEditorGroupsService);
const configurationService = accessor.get(IConfigurationService);
// To keep backwards compatibility (pre-grid), allow to focus a group
// that does not exist as long as it is the next group after the last
// opened group. Otherwise we return.
if (groupIndex > editorGroupService.count) {
return;
}
// Group exists: just focus
const groups = editorGroupService.getGroups(GroupsOrder.GRID_APPEARANCE);
if (groups[groupIndex]) {
return groups[groupIndex].focus();
}
// Group does not exist: create new by splitting the active one of the last group
const direction = preferredSideBySideGroupDirection(configurationService);
const lastGroup = editorGroupService.findGroup({ location: GroupLocation.LAST });
const newGroup = editorGroupService.addGroup(lastGroup, direction);
// Focus
newGroup.focus();
}
});
}
function toCommandId(index: number): string {
switch (index) {
case 1: return 'workbench.action.focusSecondEditorGroup';
case 2: return 'workbench.action.focusThirdEditorGroup';
case 3: return 'workbench.action.focusFourthEditorGroup';
case 4: return 'workbench.action.focusFifthEditorGroup';
case 5: return 'workbench.action.focusSixthEditorGroup';
case 6: return 'workbench.action.focusSeventhEditorGroup';
case 7: return 'workbench.action.focusEighthEditorGroup';
}
throw new Error('Invalid index');
}
function toKeyCode(index: number): KeyCode {
switch (index) {
case 1: return KeyCode.KEY_2;
case 2: return KeyCode.KEY_3;
case 3: return KeyCode.KEY_4;
case 4: return KeyCode.KEY_5;
case 5: return KeyCode.KEY_6;
case 6: return KeyCode.KEY_7;
case 7: return KeyCode.KEY_8;
}
throw new Error('Invalid index');
}
}
export function splitEditor(editorGroupService: IEditorGroupsService, direction: GroupDirection, context?: IEditorCommandsContext): void {
let sourceGroup: IEditorGroup | undefined;
if (context && typeof context.groupId === 'number') {
sourceGroup = editorGroupService.getGroup(context.groupId);
} else {
sourceGroup = editorGroupService.activeGroup;
}
if (!sourceGroup) {
return;
}
// Add group
const newGroup = editorGroupService.addGroup(sourceGroup, direction);
// Split editor (if it can be split)
let editorToCopy: IEditorInput | undefined;
if (context && typeof context.editorIndex === 'number') {
editorToCopy = sourceGroup.getEditor(context.editorIndex);
} else {
editorToCopy = types.withNullAsUndefined(sourceGroup.activeEditor);
}
if (editorToCopy && (editorToCopy as EditorInput).supportsSplitEditor()) {
sourceGroup.copyEditor(editorToCopy, newGroup);
}
// Focus
newGroup.focus();
}
function registerSplitEditorCommands() {
[
{ id: SPLIT_EDITOR_UP, direction: GroupDirection.UP },
{ id: SPLIT_EDITOR_DOWN, direction: GroupDirection.DOWN },
{ id: SPLIT_EDITOR_LEFT, direction: GroupDirection.LEFT },
{ id: SPLIT_EDITOR_RIGHT, direction: GroupDirection.RIGHT }
].forEach(({ id, direction }) => {
CommandsRegistry.registerCommand(id, function (accessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) {
splitEditor(accessor.get(IEditorGroupsService), direction, getCommandsContext(resourceOrContext, context));
});
});
}
function registerCloseEditorCommands() {
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: CLOSE_SAVED_EDITORS_COMMAND_ID,
weight: KeybindingWeight.WorkbenchContrib,
when: undefined,
primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyCode.KEY_U),
handler: (accessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => {
const editorGroupService = accessor.get(IEditorGroupsService);
const contexts = getMultiSelectedEditorContexts(getCommandsContext(resourceOrContext, context), accessor.get(IListService), editorGroupService);
const activeGroup = editorGroupService.activeGroup;
if (contexts.length === 0) {
contexts.push({ groupId: activeGroup.id }); // active group as fallback
}
return Promise.all(distinct(contexts.map(c => c.groupId)).map(groupId => {
const group = editorGroupService.getGroup(groupId);
if (group) {
return group.closeEditors({ savedOnly: true });
}
return Promise.resolve();
}));
}
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: CLOSE_EDITORS_IN_GROUP_COMMAND_ID,
weight: KeybindingWeight.WorkbenchContrib,
when: undefined,
primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyCode.KEY_W),
handler: (accessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => {
const editorGroupService = accessor.get(IEditorGroupsService);
const contexts = getMultiSelectedEditorContexts(getCommandsContext(resourceOrContext, context), accessor.get(IListService), editorGroupService);
const distinctGroupIds = distinct(contexts.map(c => c.groupId));
if (distinctGroupIds.length === 0) {
distinctGroupIds.push(editorGroupService.activeGroup.id);
}
return Promise.all(distinctGroupIds.map(groupId => {
const group = editorGroupService.getGroup(groupId);
if (group) {
return group.closeAllEditors();
}
return Promise.resolve();
}));
}
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: CLOSE_EDITOR_COMMAND_ID,
weight: KeybindingWeight.WorkbenchContrib,
when: undefined,
primary: KeyMod.CtrlCmd | KeyCode.KEY_W,
win: { primary: KeyMod.CtrlCmd | KeyCode.F4, secondary: [KeyMod.CtrlCmd | KeyCode.KEY_W] },
handler: (accessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => {
const editorGroupService = accessor.get(IEditorGroupsService);
const contexts = getMultiSelectedEditorContexts(getCommandsContext(resourceOrContext, context), accessor.get(IListService), editorGroupService);
const activeGroup = editorGroupService.activeGroup;
if (contexts.length === 0 && activeGroup.activeEditor) {
contexts.push({ groupId: activeGroup.id, editorIndex: activeGroup.getIndexOfEditor(activeGroup.activeEditor) }); // active editor as fallback
}
const groupIds = distinct(contexts.map(context => context.groupId));
return Promise.all(groupIds.map(groupId => {
const group = editorGroupService.getGroup(groupId);
if (group) {
const editors = coalesce(contexts
.filter(context => context.groupId === groupId)
.map(context => typeof context.editorIndex === 'number' ? group.getEditor(context.editorIndex) : group.activeEditor));
return group.closeEditors(editors);
}
return Promise.resolve();
}));
}
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: CLOSE_EDITOR_GROUP_COMMAND_ID,
weight: KeybindingWeight.WorkbenchContrib,
when: ContextKeyExpr.and(ActiveEditorGroupEmptyContext, MultipleEditorGroupsContext),
primary: KeyMod.CtrlCmd | KeyCode.KEY_W,
win: { primary: KeyMod.CtrlCmd | KeyCode.F4, secondary: [KeyMod.CtrlCmd | KeyCode.KEY_W] },
handler: (accessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => {
const editorGroupService = accessor.get(IEditorGroupsService);
const commandsContext = getCommandsContext(resourceOrContext, context);
let group: IEditorGroup | undefined;
if (commandsContext && typeof commandsContext.groupId === 'number') {
group = editorGroupService.getGroup(commandsContext.groupId);
} else {
group = editorGroupService.activeGroup;
}
if (group) {
editorGroupService.removeGroup(group);
}
}
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: CLOSE_OTHER_EDITORS_IN_GROUP_COMMAND_ID,
weight: KeybindingWeight.WorkbenchContrib,
when: undefined,
primary: undefined,
mac: { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_T },
handler: (accessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => {
const editorGroupService = accessor.get(IEditorGroupsService);
const contexts = getMultiSelectedEditorContexts(getCommandsContext(resourceOrContext, context), accessor.get(IListService), editorGroupService);
const activeGroup = editorGroupService.activeGroup;
if (contexts.length === 0 && activeGroup.activeEditor) {
contexts.push({ groupId: activeGroup.id, editorIndex: activeGroup.getIndexOfEditor(activeGroup.activeEditor) }); // active editor as fallback
}
const groupIds = distinct(contexts.map(context => context.groupId));
return Promise.all(groupIds.map(groupId => {
const group = editorGroupService.getGroup(groupId);
if (group) {
const editors = contexts
.filter(context => context.groupId === groupId)
.map(context => typeof context.editorIndex === 'number' ? group.getEditor(context.editorIndex) : group.activeEditor);
const editorsToClose = group.editors.filter(e => editors.indexOf(e) === -1);
return group.closeEditors(editorsToClose);
}
return Promise.resolve();
}));
}
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: CLOSE_EDITORS_TO_THE_RIGHT_COMMAND_ID,
weight: KeybindingWeight.WorkbenchContrib,
when: undefined,
primary: undefined,
handler: (accessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => {
const editorGroupService = accessor.get(IEditorGroupsService);
const { group, editor } = resolveCommandsContext(editorGroupService, getCommandsContext(resourceOrContext, context));
if (group && editor) {
return group.closeEditors({ direction: CloseDirection.RIGHT, except: editor });
}
return Promise.resolve(false);
}
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: KEEP_EDITOR_COMMAND_ID,
weight: KeybindingWeight.WorkbenchContrib,
when: undefined,
primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyCode.Enter),
handler: (accessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => {
const editorGroupService = accessor.get(IEditorGroupsService);
const { group, editor } = resolveCommandsContext(editorGroupService, getCommandsContext(resourceOrContext, context));
if (group && editor) {
return group.pinEditor(editor);
}
return Promise.resolve(false);
}
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: SHOW_EDITORS_IN_GROUP,
weight: KeybindingWeight.WorkbenchContrib,
when: undefined,
primary: undefined,
handler: (accessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => {
const editorGroupService = accessor.get(IEditorGroupsService);
const quickOpenService = accessor.get(IQuickOpenService);
if (editorGroupService.count <= 1) {
return quickOpenService.show(NAVIGATE_ALL_EDITORS_GROUP_PREFIX);
}
const commandsContext = getCommandsContext(resourceOrContext, context);
if (commandsContext && typeof commandsContext.groupId === 'number') {
const group = editorGroupService.getGroup(commandsContext.groupId);
if (group) {
editorGroupService.activateGroup(group); // we need the group to be active
}
}
return quickOpenService.show(NAVIGATE_IN_ACTIVE_GROUP_PREFIX);
}
});
CommandsRegistry.registerCommand(CLOSE_EDITORS_AND_GROUP_COMMAND_ID, async (accessor: ServicesAccessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => {
const editorGroupService = accessor.get(IEditorGroupsService);
const { group } = resolveCommandsContext(editorGroupService, getCommandsContext(resourceOrContext, context));
if (group) {
await group.closeAllEditors();
if (group.count === 0 && editorGroupService.getGroup(group.id) /* could be gone by now */) {
editorGroupService.removeGroup(group); // only remove group if it is now empty
}
}
});
}
function getCommandsContext(resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext): IEditorCommandsContext | undefined {
if (URI.isUri(resourceOrContext)) {
return context;
}
if (resourceOrContext && typeof resourceOrContext.groupId === 'number') {
return resourceOrContext;
}
if (context && typeof context.groupId === 'number') {
return context;
}
return undefined;
}
function resolveCommandsContext(editorGroupService: IEditorGroupsService, context?: IEditorCommandsContext): { group: IEditorGroup, editor?: IEditorInput, control?: IEditor } {
// Resolve from context
let group = context && typeof context.groupId === 'number' ? editorGroupService.getGroup(context.groupId) : undefined;
let editor = group && context && typeof context.editorIndex === 'number' ? types.withNullAsUndefined(group.getEditor(context.editorIndex)) : undefined;
let control = group ? group.activeControl : undefined;
// Fallback to active group as needed
if (!group) {
group = editorGroupService.activeGroup;
editor = <EditorInput>group.activeEditor;
control = group.activeControl;
}
return { group, editor, control };
}
export function getMultiSelectedEditorContexts(editorContext: IEditorCommandsContext | undefined, listService: IListService, editorGroupService: IEditorGroupsService): IEditorCommandsContext[] {
// First check for a focused list to return the selected items from
const list = listService.lastFocusedList;
if (list instanceof List && list.getHTMLElement() === document.activeElement) {
const elementToContext = (element: IEditorIdentifier | IEditorGroup) => {
if (isEditorGroup(element)) {
return { groupId: element.id, editorIndex: undefined };
}
const group = editorGroupService.getGroup(element.groupId);
return { groupId: element.groupId, editorIndex: group ? group.getIndexOfEditor(element.editor) : -1 };
};
const onlyEditorGroupAndEditor = (e: IEditorIdentifier | IEditorGroup) => isEditorGroup(e) || isEditorIdentifier(e);
const focusedElements: Array<IEditorIdentifier | IEditorGroup> = list.getFocusedElements().filter(onlyEditorGroupAndEditor);
const focus = editorContext ? editorContext : focusedElements.length ? focusedElements.map(elementToContext)[0] : undefined; // need to take into account when editor context is { group: group }
if (focus) {
const selection: Array<IEditorIdentifier | IEditorGroup> = list.getSelectedElements().filter(onlyEditorGroupAndEditor);
// Only respect selection if it contains focused element
if (selection && selection.some(s => {
if (isEditorGroup(s)) {
return s.id === focus.groupId;
}
const group = editorGroupService.getGroup(s.groupId);
return s.groupId === focus.groupId && (group ? group.getIndexOfEditor(s.editor) : -1) === focus.editorIndex;
})) {
return selection.map(elementToContext);
}
return [focus];
}
}
// Otherwise go with passed in context
return !!editorContext ? [editorContext] : [];
}
function isEditorGroup(thing: unknown): thing is IEditorGroup {
const group = thing as IEditorGroup;
return group && typeof group.id === 'number' && Array.isArray(group.editors);
}
function isEditorIdentifier(thing: unknown): thing is IEditorIdentifier {
const identifier = thing as IEditorIdentifier;
return identifier && typeof identifier.groupId === 'number';
}
export function setup(): void {
registerActiveEditorMoveCommand();
registerEditorGroupsLayoutCommand();
registerDiffEditorCommands();
registerOpenEditorAtIndexCommands();
registerCloseEditorCommands();
registerFocusEditorGroupAtIndexCommands();
registerSplitEditorCommands();
}
| src/vs/workbench/browser/parts/editor/editorCommands.ts | 0 | https://github.com/microsoft/vscode/commit/23f2275c23aeebf5e22f3d19a20528c8ba48c570 | [
0.0003278898657299578,
0.0001724527683109045,
0.0001640788686927408,
0.00016784116451162845,
0.000020106277588638477
] |
{
"id": 3,
"code_window": [
"\t// Global methods\n",
"\topenWindow(_windowId: number, _uris: IURIToOpen[], _options: IOpenSettings): Promise<void> {\n",
"\t\treturn Promise.resolve();\n",
"\t}\n",
"\n",
"\topenExtensionDevelopmentHostWindow(args: ParsedArgs, env: IProcessEnvironment): Promise<void> {\n",
"\t\treturn Promise.resolve();\n",
"\t}\n",
"\n",
"\tgetWindows(): Promise<{ id: number; workspace?: IWorkspaceIdentifier; folderUri?: ISingleFolderWorkspaceIdentifier; title: string; filename?: string; }[]> {\n",
"\t\treturn Promise.resolve([]);\n",
"\t}\n",
"\n",
"\tgetActiveWindowId(): Promise<number | undefined> {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/browser/web.simpleservices.ts",
"type": "replace",
"edit_start_line_idx": 279
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { URI } from 'vs/base/common/uri';
import * as browser from 'vs/base/browser/browser';
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { Event } from 'vs/base/common/event';
import { ILogService } from 'vs/platform/log/common/log';
import { Disposable } from 'vs/base/common/lifecycle';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import { IWindowService, IEnterWorkspaceResult, IURIToOpen, IWindowsService, IOpenSettings, IWindowSettings } from 'vs/platform/windows/common/windows';
import { IWorkspaceIdentifier, ISingleFolderWorkspaceIdentifier } from 'vs/platform/workspaces/common/workspaces';
import { IRecentlyOpened, IRecent, isRecentFile, isRecentFolder } from 'vs/platform/history/common/history';
import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
import { addDisposableListener, EventType } from 'vs/base/browser/dom';
import { IEditorService, IResourceEditor } from 'vs/workbench/services/editor/common/editorService';
import { pathsToEditors } from 'vs/workbench/common/editor';
import { IFileService } from 'vs/platform/files/common/files';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ParsedArgs } from 'vs/platform/environment/common/environment';
import { IProcessEnvironment } from 'vs/base/common/platform';
import { toStoreData, restoreRecentlyOpened } from 'vs/platform/history/common/historyStorage';
//#region Window
export class SimpleWindowService extends Disposable implements IWindowService {
_serviceBrand: undefined;
readonly onDidChangeFocus: Event<boolean> = Event.None;
readonly onDidChangeMaximize: Event<boolean> = Event.None;
readonly hasFocus = true;
readonly windowId = 0;
static readonly RECENTLY_OPENED_KEY = 'recently.opened';
constructor(
@IEditorService private readonly editorService: IEditorService,
@IFileService private readonly fileService: IFileService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@IStorageService private readonly storageService: IStorageService,
@IWorkspaceContextService private readonly workspaceService: IWorkspaceContextService,
@ILogService private readonly logService: ILogService,
) {
super();
this.addWorkspaceToRecentlyOpened();
this.registerListeners();
}
private addWorkspaceToRecentlyOpened(): void {
const workspace = this.workspaceService.getWorkspace();
switch (this.workspaceService.getWorkbenchState()) {
case WorkbenchState.FOLDER:
this.addRecentlyOpened([{ folderUri: workspace.folders[0].uri }]);
break;
case WorkbenchState.WORKSPACE:
this.addRecentlyOpened([{ workspace: { id: workspace.id, configPath: workspace.configuration! } }]);
break;
}
}
private registerListeners(): void {
this._register(addDisposableListener(document, EventType.FULLSCREEN_CHANGE, () => {
if (document.fullscreenElement || (<any>document).webkitFullscreenElement) {
browser.setFullscreen(true);
} else {
browser.setFullscreen(false);
}
}));
this._register(addDisposableListener(document, EventType.WK_FULLSCREEN_CHANGE, () => {
if (document.fullscreenElement || (<any>document).webkitFullscreenElement || (<any>document).webkitIsFullScreen) {
browser.setFullscreen(true);
} else {
browser.setFullscreen(false);
}
}));
}
isFocused(): Promise<boolean> {
return Promise.resolve(this.hasFocus);
}
isMaximized(): Promise<boolean> {
return Promise.resolve(false);
}
enterWorkspace(_path: URI): Promise<IEnterWorkspaceResult | undefined> {
return Promise.resolve(undefined);
}
async getRecentlyOpened(): Promise<IRecentlyOpened> {
const recentlyOpenedRaw = this.storageService.get(SimpleWindowService.RECENTLY_OPENED_KEY, StorageScope.GLOBAL);
if (recentlyOpenedRaw) {
return restoreRecentlyOpened(JSON.parse(recentlyOpenedRaw), this.logService);
}
return { workspaces: [], files: [] };
}
async addRecentlyOpened(recents: IRecent[]): Promise<void> {
const recentlyOpened = await this.getRecentlyOpened();
recents.forEach(recent => {
if (isRecentFile(recent)) {
this.doRemoveFromRecentlyOpened(recentlyOpened, [recent.fileUri]);
recentlyOpened.files.unshift(recent);
} else if (isRecentFolder(recent)) {
this.doRemoveFromRecentlyOpened(recentlyOpened, [recent.folderUri]);
recentlyOpened.workspaces.unshift(recent);
} else {
this.doRemoveFromRecentlyOpened(recentlyOpened, [recent.workspace.configPath]);
recentlyOpened.workspaces.unshift(recent);
}
});
return this.saveRecentlyOpened(recentlyOpened);
}
async removeFromRecentlyOpened(paths: URI[]): Promise<void> {
const recentlyOpened = await this.getRecentlyOpened();
this.doRemoveFromRecentlyOpened(recentlyOpened, paths);
return this.saveRecentlyOpened(recentlyOpened);
}
private doRemoveFromRecentlyOpened(recentlyOpened: IRecentlyOpened, paths: URI[]): void {
recentlyOpened.files = recentlyOpened.files.filter(file => {
return !paths.some(path => path.toString() === file.fileUri.toString());
});
recentlyOpened.workspaces = recentlyOpened.workspaces.filter(workspace => {
return !paths.some(path => path.toString() === (isRecentFolder(workspace) ? workspace.folderUri.toString() : workspace.workspace.configPath.toString()));
});
}
private async saveRecentlyOpened(data: IRecentlyOpened): Promise<void> {
return this.storageService.store(SimpleWindowService.RECENTLY_OPENED_KEY, JSON.stringify(toStoreData(data)), StorageScope.GLOBAL);
}
focusWindow(): Promise<void> {
return Promise.resolve();
}
maximizeWindow(): Promise<void> {
return Promise.resolve();
}
unmaximizeWindow(): Promise<void> {
return Promise.resolve();
}
minimizeWindow(): Promise<void> {
return Promise.resolve();
}
async openWindow(_uris: IURIToOpen[], _options?: IOpenSettings): Promise<void> {
const { openFolderInNewWindow } = this.shouldOpenNewWindow(_options);
for (let i = 0; i < _uris.length; i++) {
const uri = _uris[i];
if ('folderUri' in uri) {
const newAddress = `${document.location.origin}${document.location.pathname}?folder=${uri.folderUri.path}`;
if (openFolderInNewWindow) {
window.open(newAddress);
} else {
window.location.href = newAddress;
}
}
if ('workspaceUri' in uri) {
const newAddress = `${document.location.origin}${document.location.pathname}?workspace=${uri.workspaceUri.path}`;
if (openFolderInNewWindow) {
window.open(newAddress);
} else {
window.location.href = newAddress;
}
}
if ('fileUri' in uri) {
const inputs: IResourceEditor[] = await pathsToEditors([uri], this.fileService);
this.editorService.openEditors(inputs);
}
}
return Promise.resolve();
}
private shouldOpenNewWindow(_options: IOpenSettings = {}): { openFolderInNewWindow: boolean } {
const windowConfig = this.configurationService.getValue<IWindowSettings>('window');
const openFolderInNewWindowConfig = (windowConfig && windowConfig.openFoldersInNewWindow) || 'default' /* default */;
let openFolderInNewWindow = !!_options.forceNewWindow && !_options.forceReuseWindow;
if (!_options.forceNewWindow && !_options.forceReuseWindow && (openFolderInNewWindowConfig === 'on' || openFolderInNewWindowConfig === 'off')) {
openFolderInNewWindow = (openFolderInNewWindowConfig === 'on');
}
return { openFolderInNewWindow };
}
closeWindow(): Promise<void> {
window.close();
return Promise.resolve();
}
}
registerSingleton(IWindowService, SimpleWindowService);
//#endregion
//#region Window
export class SimpleWindowsService implements IWindowsService {
_serviceBrand: undefined;
readonly onWindowOpen: Event<number> = Event.None;
readonly onWindowFocus: Event<number> = Event.None;
readonly onWindowBlur: Event<number> = Event.None;
readonly onWindowMaximize: Event<number> = Event.None;
readonly onWindowUnmaximize: Event<number> = Event.None;
readonly onRecentlyOpenedChange: Event<void> = Event.None;
isFocused(_windowId: number): Promise<boolean> {
return Promise.resolve(true);
}
enterWorkspace(_windowId: number, _path: URI): Promise<IEnterWorkspaceResult | undefined> {
return Promise.resolve(undefined);
}
addRecentlyOpened(recents: IRecent[]): Promise<void> {
return Promise.resolve();
}
removeFromRecentlyOpened(_paths: URI[]): Promise<void> {
return Promise.resolve();
}
clearRecentlyOpened(): Promise<void> {
return Promise.resolve();
}
getRecentlyOpened(_windowId: number): Promise<IRecentlyOpened> {
return Promise.resolve({
workspaces: [],
files: []
});
}
focusWindow(_windowId: number): Promise<void> {
return Promise.resolve();
}
closeWindow(_windowId: number): Promise<void> {
return Promise.resolve();
}
isMaximized(_windowId: number): Promise<boolean> {
return Promise.resolve(false);
}
maximizeWindow(_windowId: number): Promise<void> {
return Promise.resolve();
}
minimizeWindow(_windowId: number): Promise<void> {
return Promise.resolve();
}
unmaximizeWindow(_windowId: number): Promise<void> {
return Promise.resolve();
}
// Global methods
openWindow(_windowId: number, _uris: IURIToOpen[], _options: IOpenSettings): Promise<void> {
return Promise.resolve();
}
openExtensionDevelopmentHostWindow(args: ParsedArgs, env: IProcessEnvironment): Promise<void> {
return Promise.resolve();
}
getWindows(): Promise<{ id: number; workspace?: IWorkspaceIdentifier; folderUri?: ISingleFolderWorkspaceIdentifier; title: string; filename?: string; }[]> {
return Promise.resolve([]);
}
getActiveWindowId(): Promise<number | undefined> {
return Promise.resolve(0);
}
}
registerSingleton(IWindowsService, SimpleWindowsService);
//#endregion
| src/vs/workbench/browser/web.simpleservices.ts | 1 | https://github.com/microsoft/vscode/commit/23f2275c23aeebf5e22f3d19a20528c8ba48c570 | [
0.9962098598480225,
0.05522739142179489,
0.00016394202248193324,
0.00021399164688773453,
0.20927543938159943
] |
{
"id": 3,
"code_window": [
"\t// Global methods\n",
"\topenWindow(_windowId: number, _uris: IURIToOpen[], _options: IOpenSettings): Promise<void> {\n",
"\t\treturn Promise.resolve();\n",
"\t}\n",
"\n",
"\topenExtensionDevelopmentHostWindow(args: ParsedArgs, env: IProcessEnvironment): Promise<void> {\n",
"\t\treturn Promise.resolve();\n",
"\t}\n",
"\n",
"\tgetWindows(): Promise<{ id: number; workspace?: IWorkspaceIdentifier; folderUri?: ISingleFolderWorkspaceIdentifier; title: string; filename?: string; }[]> {\n",
"\t\treturn Promise.resolve([]);\n",
"\t}\n",
"\n",
"\tgetActiveWindowId(): Promise<number | undefined> {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/browser/web.simpleservices.ts",
"type": "replace",
"edit_start_line_idx": 279
} | /*---------------------------------------------------------------------------------------------
* 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 { MainThreadDocumentsAndEditors } from 'vs/workbench/api/browser/mainThreadDocumentsAndEditors';
import { SingleProxyRPCProtocol } from './testRPCProtocol';
import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService';
import { ModelServiceImpl } from 'vs/editor/common/services/modelServiceImpl';
import { TestCodeEditorService } from 'vs/editor/test/browser/editorTestServices';
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
import { ExtHostDocumentsAndEditorsShape, IDocumentsAndEditorsDelta } from 'vs/workbench/api/common/extHost.protocol';
import { createTestCodeEditor, TestCodeEditor } from 'vs/editor/test/browser/testCodeEditor';
import { mock } from 'vs/workbench/test/electron-browser/api/mock';
import { TestEditorService, TestEditorGroupsService, TestTextResourcePropertiesService, TestEnvironmentService } from 'vs/workbench/test/workbenchTestServices';
import { Event } from 'vs/base/common/event';
import { ITextModel } from 'vs/editor/common/model';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService';
import { IFileService } from 'vs/platform/files/common/files';
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
suite('MainThreadDocumentsAndEditors', () => {
let modelService: ModelServiceImpl;
let codeEditorService: TestCodeEditorService;
let textFileService: ITextFileService;
let deltas: IDocumentsAndEditorsDelta[] = [];
const hugeModelString = new Array(2 + (50 * 1024 * 1024)).join('-');
function myCreateTestCodeEditor(model: ITextModel | undefined): TestCodeEditor {
return createTestCodeEditor({
model: model,
serviceCollection: new ServiceCollection(
[ICodeEditorService, codeEditorService]
)
});
}
setup(() => {
deltas.length = 0;
const configService = new TestConfigurationService();
configService.setUserConfiguration('editor', { 'detectIndentation': false });
modelService = new ModelServiceImpl(configService, new TestTextResourcePropertiesService(configService));
codeEditorService = new TestCodeEditorService();
textFileService = new class extends mock<ITextFileService>() {
isDirty() { return false; }
models = <any>{
onModelSaved: Event.None,
onModelReverted: Event.None,
onModelDirty: Event.None,
};
};
const workbenchEditorService = new TestEditorService();
const editorGroupService = new TestEditorGroupsService();
const fileService = new class extends mock<IFileService>() {
onAfterOperation = Event.None;
};
/* tslint:disable */
new MainThreadDocumentsAndEditors(
SingleProxyRPCProtocol(new class extends mock<ExtHostDocumentsAndEditorsShape>() {
$acceptDocumentsAndEditorsDelta(delta: IDocumentsAndEditorsDelta) { deltas.push(delta); }
}),
modelService,
textFileService,
workbenchEditorService,
codeEditorService,
null!,
fileService,
null!,
null!,
editorGroupService,
null!,
new class extends mock<IPanelService>() implements IPanelService {
_serviceBrand: undefined;
onDidPanelOpen = Event.None;
onDidPanelClose = Event.None;
getActivePanel() {
return null;
}
},
TestEnvironmentService
);
/* tslint:enable */
});
test('Model#add', () => {
deltas.length = 0;
modelService.createModel('farboo', null);
assert.equal(deltas.length, 1);
const [delta] = deltas;
assert.equal(delta.addedDocuments!.length, 1);
assert.equal(delta.removedDocuments, undefined);
assert.equal(delta.addedEditors, undefined);
assert.equal(delta.removedEditors, undefined);
assert.equal(delta.newActiveEditor, null);
});
test('ignore huge model', function () {
this.timeout(1000 * 60); // increase timeout for this one test
const model = modelService.createModel(hugeModelString, null);
assert.ok(model.isTooLargeForSyncing());
assert.equal(deltas.length, 1);
const [delta] = deltas;
assert.equal(delta.newActiveEditor, null);
assert.equal(delta.addedDocuments, undefined);
assert.equal(delta.removedDocuments, undefined);
assert.equal(delta.addedEditors, undefined);
assert.equal(delta.removedEditors, undefined);
});
test('ignore simple widget model', function () {
this.timeout(1000 * 60); // increase timeout for this one test
const model = modelService.createModel('test', null, undefined, true);
assert.ok(model.isForSimpleWidget);
assert.equal(deltas.length, 1);
const [delta] = deltas;
assert.equal(delta.newActiveEditor, null);
assert.equal(delta.addedDocuments, undefined);
assert.equal(delta.removedDocuments, undefined);
assert.equal(delta.addedEditors, undefined);
assert.equal(delta.removedEditors, undefined);
});
test('ignore huge model from editor', function () {
this.timeout(1000 * 60); // increase timeout for this one test
const model = modelService.createModel(hugeModelString, null);
const editor = myCreateTestCodeEditor(model);
assert.equal(deltas.length, 1);
deltas.length = 0;
assert.equal(deltas.length, 0);
editor.dispose();
});
test('ignore editor w/o model', () => {
const editor = myCreateTestCodeEditor(undefined);
assert.equal(deltas.length, 1);
const [delta] = deltas;
assert.equal(delta.newActiveEditor, null);
assert.equal(delta.addedDocuments, undefined);
assert.equal(delta.removedDocuments, undefined);
assert.equal(delta.addedEditors, undefined);
assert.equal(delta.removedEditors, undefined);
editor.dispose();
});
test('editor with model', () => {
deltas.length = 0;
const model = modelService.createModel('farboo', null);
const editor = myCreateTestCodeEditor(model);
assert.equal(deltas.length, 2);
const [first, second] = deltas;
assert.equal(first.addedDocuments!.length, 1);
assert.equal(first.newActiveEditor, null);
assert.equal(first.removedDocuments, undefined);
assert.equal(first.addedEditors, undefined);
assert.equal(first.removedEditors, undefined);
assert.equal(second.addedEditors!.length, 1);
assert.equal(second.addedDocuments, undefined);
assert.equal(second.removedDocuments, undefined);
assert.equal(second.removedEditors, undefined);
assert.equal(second.newActiveEditor, undefined);
editor.dispose();
});
test('editor with dispos-ed/-ing model', () => {
modelService.createModel('foobar', null);
const model = modelService.createModel('farboo', null);
const editor = myCreateTestCodeEditor(model);
// ignore things until now
deltas.length = 0;
modelService.destroyModel(model.uri);
assert.equal(deltas.length, 1);
const [first] = deltas;
assert.equal(first.newActiveEditor, null);
assert.equal(first.removedEditors!.length, 1);
assert.equal(first.removedDocuments!.length, 1);
assert.equal(first.addedDocuments, undefined);
assert.equal(first.addedEditors, undefined);
editor.dispose();
});
});
| src/vs/workbench/test/electron-browser/api/mainThreadDocumentsAndEditors.test.ts | 0 | https://github.com/microsoft/vscode/commit/23f2275c23aeebf5e22f3d19a20528c8ba48c570 | [
0.0001775667624315247,
0.00017417021444998682,
0.00016653061902616173,
0.00017486483557149768,
0.0000026867758151638554
] |
{
"id": 3,
"code_window": [
"\t// Global methods\n",
"\topenWindow(_windowId: number, _uris: IURIToOpen[], _options: IOpenSettings): Promise<void> {\n",
"\t\treturn Promise.resolve();\n",
"\t}\n",
"\n",
"\topenExtensionDevelopmentHostWindow(args: ParsedArgs, env: IProcessEnvironment): Promise<void> {\n",
"\t\treturn Promise.resolve();\n",
"\t}\n",
"\n",
"\tgetWindows(): Promise<{ id: number; workspace?: IWorkspaceIdentifier; folderUri?: ISingleFolderWorkspaceIdentifier; title: string; filename?: string; }[]> {\n",
"\t\treturn Promise.resolve([]);\n",
"\t}\n",
"\n",
"\tgetActiveWindowId(): Promise<number | undefined> {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/browser/web.simpleservices.ts",
"type": "replace",
"edit_start_line_idx": 279
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { Emitter, Event } from 'vs/base/common/event';
import { Disposable } from 'vs/base/common/lifecycle';
import * as objects from 'vs/base/common/objects';
import * as arrays from 'vs/base/common/arrays';
import { IEditorOptions, editorOptionsRegistry, ValidatedEditorOptions, IEnvironmentalOptions, IComputedEditorOptions, ConfigurationChangedEvent, EDITOR_MODEL_DEFAULTS, EditorOption, FindComputedEditorOptionValueById } from 'vs/editor/common/config/editorOptions';
import { EditorZoom } from 'vs/editor/common/config/editorZoom';
import { BareFontInfo, FontInfo } from 'vs/editor/common/config/fontInfo';
import * as editorCommon from 'vs/editor/common/editorCommon';
import { ConfigurationScope, Extensions, IConfigurationNode, IConfigurationRegistry, IConfigurationPropertySchema } from 'vs/platform/configuration/common/configurationRegistry';
import { Registry } from 'vs/platform/registry/common/platform';
import { AccessibilitySupport } from 'vs/platform/accessibility/common/accessibility';
/**
* Control what pressing Tab does.
* If it is false, pressing Tab or Shift-Tab will be handled by the editor.
* If it is true, pressing Tab or Shift-Tab will move the browser focus.
* Defaults to false.
*/
export interface ITabFocus {
onDidChangeTabFocus: Event<boolean>;
getTabFocusMode(): boolean;
setTabFocusMode(tabFocusMode: boolean): void;
}
export const TabFocus: ITabFocus = new class implements ITabFocus {
private _tabFocus: boolean = false;
private readonly _onDidChangeTabFocus = new Emitter<boolean>();
public readonly onDidChangeTabFocus: Event<boolean> = this._onDidChangeTabFocus.event;
public getTabFocusMode(): boolean {
return this._tabFocus;
}
public setTabFocusMode(tabFocusMode: boolean): void {
if (this._tabFocus === tabFocusMode) {
return;
}
this._tabFocus = tabFocusMode;
this._onDidChangeTabFocus.fire(this._tabFocus);
}
};
export interface IEnvConfiguration {
extraEditorClassName: string;
outerWidth: number;
outerHeight: number;
emptySelectionClipboard: boolean;
pixelRatio: number;
zoomLevel: number;
accessibilitySupport: AccessibilitySupport;
}
const hasOwnProperty = Object.hasOwnProperty;
export class ComputedEditorOptions implements IComputedEditorOptions {
private readonly _values: any[] = [];
public _read<T>(id: EditorOption): T {
return this._values[id];
}
public get<T extends EditorOption>(id: T): FindComputedEditorOptionValueById<T> {
return this._values[id];
}
public _write<T>(id: EditorOption, value: T): void {
this._values[id] = value;
}
}
class RawEditorOptions {
private readonly _values: any[] = [];
public _read<T>(id: EditorOption): T | undefined {
return this._values[id];
}
public _write<T>(id: EditorOption, value: T | undefined): void {
this._values[id] = value;
}
}
class EditorConfiguration2 {
public static readOptions(_options: IEditorOptions): RawEditorOptions {
const options: { [key: string]: any; } = _options;
const result = new RawEditorOptions();
for (const editorOption of editorOptionsRegistry) {
const value = (editorOption.name === '_never_' ? undefined : options[editorOption.name]);
result._write(editorOption.id, value);
}
return result;
}
public static validateOptions(options: RawEditorOptions): ValidatedEditorOptions {
const result = new ValidatedEditorOptions();
for (const editorOption of editorOptionsRegistry) {
result._write(editorOption.id, editorOption.validate(options._read(editorOption.id)));
}
return result;
}
public static computeOptions(options: ValidatedEditorOptions, env: IEnvironmentalOptions): ComputedEditorOptions {
const result = new ComputedEditorOptions();
for (const editorOption of editorOptionsRegistry) {
result._write(editorOption.id, editorOption.compute(env, result, options._read(editorOption.id)));
}
return result;
}
private static _deepEquals<T>(a: T, b: T): boolean {
if (typeof a !== 'object' || typeof b !== 'object') {
return (a === b);
}
if (Array.isArray(a) || Array.isArray(b)) {
return (Array.isArray(a) && Array.isArray(b) ? arrays.equals(a, b) : false);
}
for (let key in a) {
if (!EditorConfiguration2._deepEquals(a[key], b[key])) {
return false;
}
}
return true;
}
public static checkEquals(a: ComputedEditorOptions, b: ComputedEditorOptions): ConfigurationChangedEvent | null {
const result: boolean[] = [];
let somethingChanged = false;
for (const editorOption of editorOptionsRegistry) {
const changed = !EditorConfiguration2._deepEquals(a._read(editorOption.id), b._read(editorOption.id));
result[editorOption.id] = changed;
if (changed) {
somethingChanged = true;
}
}
return (somethingChanged ? new ConfigurationChangedEvent(result) : null);
}
}
/**
* Compatibility with old options
*/
function migrateOptions(options: IEditorOptions): void {
const wordWrap = options.wordWrap;
if (<any>wordWrap === true) {
options.wordWrap = 'on';
} else if (<any>wordWrap === false) {
options.wordWrap = 'off';
}
const lineNumbers = options.lineNumbers;
if (<any>lineNumbers === true) {
options.lineNumbers = 'on';
} else if (<any>lineNumbers === false) {
options.lineNumbers = 'off';
}
const autoClosingBrackets = options.autoClosingBrackets;
if (<any>autoClosingBrackets === false) {
options.autoClosingBrackets = 'never';
options.autoClosingQuotes = 'never';
options.autoSurround = 'never';
}
const cursorBlinking = options.cursorBlinking;
if (<any>cursorBlinking === 'visible') {
options.cursorBlinking = 'solid';
}
const renderWhitespace = options.renderWhitespace;
if (<any>renderWhitespace === true) {
options.renderWhitespace = 'boundary';
} else if (<any>renderWhitespace === false) {
options.renderWhitespace = 'none';
}
const renderLineHighlight = options.renderLineHighlight;
if (<any>renderLineHighlight === true) {
options.renderLineHighlight = 'line';
} else if (<any>renderLineHighlight === false) {
options.renderLineHighlight = 'none';
}
const acceptSuggestionOnEnter = options.acceptSuggestionOnEnter;
if (<any>acceptSuggestionOnEnter === true) {
options.acceptSuggestionOnEnter = 'on';
} else if (<any>acceptSuggestionOnEnter === false) {
options.acceptSuggestionOnEnter = 'off';
}
const tabCompletion = options.tabCompletion;
if (<any>tabCompletion === false) {
options.tabCompletion = 'off';
} else if (<any>tabCompletion === true) {
options.tabCompletion = 'onlySnippets';
}
const hover = options.hover;
if (<any>hover === true) {
options.hover = {
enabled: true
};
} else if (<any>hover === false) {
options.hover = {
enabled: false
};
}
}
function deepCloneAndMigrateOptions(_options: IEditorOptions): IEditorOptions {
const options = objects.deepClone(_options);
migrateOptions(options);
return options;
}
export abstract class CommonEditorConfiguration extends Disposable implements editorCommon.IConfiguration {
private _onDidChange = this._register(new Emitter<ConfigurationChangedEvent>());
public readonly onDidChange: Event<ConfigurationChangedEvent> = this._onDidChange.event;
public readonly isSimpleWidget: boolean;
public options!: ComputedEditorOptions;
private _isDominatedByLongLines: boolean;
private _lineNumbersDigitCount: number;
private _rawOptions: IEditorOptions;
private _readOptions: RawEditorOptions;
protected _validatedOptions: ValidatedEditorOptions;
constructor(isSimpleWidget: boolean, _options: IEditorOptions) {
super();
this.isSimpleWidget = isSimpleWidget;
this._isDominatedByLongLines = false;
this._lineNumbersDigitCount = 1;
this._rawOptions = deepCloneAndMigrateOptions(_options);
this._readOptions = EditorConfiguration2.readOptions(this._rawOptions);
this._validatedOptions = EditorConfiguration2.validateOptions(this._readOptions);
this._register(EditorZoom.onDidChangeZoomLevel(_ => this._recomputeOptions()));
this._register(TabFocus.onDidChangeTabFocus(_ => this._recomputeOptions()));
}
public observeReferenceElement(dimension?: editorCommon.IDimension): void {
}
public dispose(): void {
super.dispose();
}
protected _recomputeOptions(): void {
const oldOptions = this.options;
const newOptions = this._computeInternalOptions();
if (!oldOptions) {
this.options = newOptions;
} else {
const changeEvent = EditorConfiguration2.checkEquals(oldOptions, newOptions);
if (changeEvent === null) {
// nothing changed!
return;
}
this.options = newOptions;
this._onDidChange.fire(changeEvent);
}
}
public getRawOptions(): IEditorOptions {
return this._rawOptions;
}
private _computeInternalOptions(): ComputedEditorOptions {
const partialEnv = this._getEnvConfiguration();
const bareFontInfo = BareFontInfo.createFromValidatedSettings(this._validatedOptions, partialEnv.zoomLevel, this.isSimpleWidget);
const env: IEnvironmentalOptions = {
outerWidth: partialEnv.outerWidth,
outerHeight: partialEnv.outerHeight,
fontInfo: this.readConfiguration(bareFontInfo),
extraEditorClassName: partialEnv.extraEditorClassName,
isDominatedByLongLines: this._isDominatedByLongLines,
lineNumbersDigitCount: this._lineNumbersDigitCount,
emptySelectionClipboard: partialEnv.emptySelectionClipboard,
pixelRatio: partialEnv.pixelRatio,
tabFocusMode: TabFocus.getTabFocusMode(),
accessibilitySupport: partialEnv.accessibilitySupport
};
return EditorConfiguration2.computeOptions(this._validatedOptions, env);
}
private static _primitiveArrayEquals(a: any[], b: any[]): boolean {
if (a.length !== b.length) {
return false;
}
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
private static _subsetEquals(base: { [key: string]: any }, subset: { [key: string]: any }): boolean {
for (const key in subset) {
if (hasOwnProperty.call(subset, key)) {
const subsetValue = subset[key];
const baseValue = base[key];
if (baseValue === subsetValue) {
continue;
}
if (Array.isArray(baseValue) && Array.isArray(subsetValue)) {
if (!this._primitiveArrayEquals(baseValue, subsetValue)) {
return false;
}
continue;
}
if (typeof baseValue === 'object' && typeof subsetValue === 'object') {
if (!this._subsetEquals(baseValue, subsetValue)) {
return false;
}
continue;
}
return false;
}
}
return true;
}
public updateOptions(_newOptions: IEditorOptions): void {
if (typeof _newOptions === 'undefined') {
return;
}
const newOptions = deepCloneAndMigrateOptions(_newOptions);
if (CommonEditorConfiguration._subsetEquals(this._rawOptions, newOptions)) {
return;
}
this._rawOptions = objects.mixin(this._rawOptions, newOptions || {});
this._readOptions = EditorConfiguration2.readOptions(this._rawOptions);
this._validatedOptions = EditorConfiguration2.validateOptions(this._readOptions);
this._recomputeOptions();
}
public setIsDominatedByLongLines(isDominatedByLongLines: boolean): void {
this._isDominatedByLongLines = isDominatedByLongLines;
this._recomputeOptions();
}
public setMaxLineNumber(maxLineNumber: number): void {
let digitCount = CommonEditorConfiguration._digitCount(maxLineNumber);
if (this._lineNumbersDigitCount === digitCount) {
return;
}
this._lineNumbersDigitCount = digitCount;
this._recomputeOptions();
}
private static _digitCount(n: number): number {
let r = 0;
while (n) {
n = Math.floor(n / 10);
r++;
}
return r ? r : 1;
}
protected abstract _getEnvConfiguration(): IEnvConfiguration;
protected abstract readConfiguration(styling: BareFontInfo): FontInfo;
}
const configurationRegistry = Registry.as<IConfigurationRegistry>(Extensions.Configuration);
const editorConfiguration: IConfigurationNode = {
id: 'editor',
order: 5,
type: 'object',
title: nls.localize('editorConfigurationTitle', "Editor"),
overridable: true,
scope: ConfigurationScope.RESOURCE,
properties: {
'editor.tabSize': {
type: 'number',
default: EDITOR_MODEL_DEFAULTS.tabSize,
minimum: 1,
markdownDescription: nls.localize('tabSize', "The number of spaces a tab is equal to. This setting is overridden based on the file contents when `#editor.detectIndentation#` is on.")
},
// 'editor.indentSize': {
// 'anyOf': [
// {
// type: 'string',
// enum: ['tabSize']
// },
// {
// type: 'number',
// minimum: 1
// }
// ],
// default: 'tabSize',
// markdownDescription: nls.localize('indentSize', "The number of spaces used for indentation or 'tabSize' to use the value from `#editor.tabSize#`. This setting is overridden based on the file contents when `#editor.detectIndentation#` is on.")
// },
'editor.insertSpaces': {
type: 'boolean',
default: EDITOR_MODEL_DEFAULTS.insertSpaces,
markdownDescription: nls.localize('insertSpaces', "Insert spaces when pressing `Tab`. This setting is overridden based on the file contents when `#editor.detectIndentation#` is on.")
},
'editor.detectIndentation': {
type: 'boolean',
default: EDITOR_MODEL_DEFAULTS.detectIndentation,
markdownDescription: nls.localize('detectIndentation', "Controls whether `#editor.tabSize#` and `#editor.insertSpaces#` will be automatically detected when a file is opened based on the file contents.")
},
'editor.trimAutoWhitespace': {
type: 'boolean',
default: EDITOR_MODEL_DEFAULTS.trimAutoWhitespace,
description: nls.localize('trimAutoWhitespace', "Remove trailing auto inserted whitespace.")
},
'editor.largeFileOptimizations': {
type: 'boolean',
default: EDITOR_MODEL_DEFAULTS.largeFileOptimizations,
description: nls.localize('largeFileOptimizations', "Special handling for large files to disable certain memory intensive features.")
},
'editor.wordBasedSuggestions': {
type: 'boolean',
default: true,
description: nls.localize('wordBasedSuggestions', "Controls whether completions should be computed based on words in the document.")
},
'editor.stablePeek': {
type: 'boolean',
default: false,
markdownDescription: nls.localize('stablePeek', "Keep peek editors open even when double clicking their content or when hitting `Escape`.")
},
'editor.maxTokenizationLineLength': {
type: 'integer',
default: 20_000,
description: nls.localize('maxTokenizationLineLength', "Lines above this length will not be tokenized for performance reasons")
},
'editor.codeActionsOnSave': {
type: 'object',
properties: {
'source.organizeImports': {
type: 'boolean',
description: nls.localize('codeActionsOnSave.organizeImports', "Controls whether organize imports action should be run on file save.")
},
'source.fixAll': {
type: 'boolean',
description: nls.localize('codeActionsOnSave.fixAll', "Controls whether auto fix action should be run on file save.")
}
},
'additionalProperties': {
type: 'boolean'
},
default: {},
description: nls.localize('codeActionsOnSave', "Code action kinds to be run on save.")
},
'editor.codeActionsOnSaveTimeout': {
type: 'number',
default: 750,
description: nls.localize('codeActionsOnSaveTimeout', "Timeout in milliseconds after which the code actions that are run on save are cancelled.")
},
'diffEditor.renderSideBySide': {
type: 'boolean',
default: true,
description: nls.localize('sideBySide', "Controls whether the diff editor shows the diff side by side or inline.")
},
'diffEditor.ignoreTrimWhitespace': {
type: 'boolean',
default: true,
description: nls.localize('ignoreTrimWhitespace', "Controls whether the diff editor shows changes in leading or trailing whitespace as diffs.")
},
'diffEditor.renderIndicators': {
type: 'boolean',
default: true,
description: nls.localize('renderIndicators', "Controls whether the diff editor shows +/- indicators for added/removed changes.")
}
}
};
function isConfigurationPropertySchema(x: IConfigurationPropertySchema | { [path: string]: IConfigurationPropertySchema; }): x is IConfigurationPropertySchema {
return (typeof x.type !== 'undefined' || typeof x.anyOf !== 'undefined');
}
// Add properties from the Editor Option Registry
for (const editorOption of editorOptionsRegistry) {
const schema = editorOption.schema;
if (typeof schema !== 'undefined') {
if (isConfigurationPropertySchema(schema)) {
// This is a single schema contribution
editorConfiguration.properties![`editor.${editorOption.name}`] = schema;
} else {
for (let key in schema) {
if (hasOwnProperty.call(schema, key)) {
editorConfiguration.properties![key] = schema[key];
}
}
}
}
}
let cachedEditorConfigurationKeys: { [key: string]: boolean; } | null = null;
function getEditorConfigurationKeys(): { [key: string]: boolean; } {
if (cachedEditorConfigurationKeys === null) {
cachedEditorConfigurationKeys = <{ [key: string]: boolean; }>Object.create(null);
Object.keys(editorConfiguration.properties!).forEach((prop) => {
cachedEditorConfigurationKeys![prop] = true;
});
}
return cachedEditorConfigurationKeys;
}
export function isEditorConfigurationKey(key: string): boolean {
const editorConfigurationKeys = getEditorConfigurationKeys();
return (editorConfigurationKeys[`editor.${key}`] || false);
}
export function isDiffEditorConfigurationKey(key: string): boolean {
const editorConfigurationKeys = getEditorConfigurationKeys();
return (editorConfigurationKeys[`diffEditor.${key}`] || false);
}
configurationRegistry.registerConfiguration(editorConfiguration);
| src/vs/editor/common/config/commonEditorConfig.ts | 0 | https://github.com/microsoft/vscode/commit/23f2275c23aeebf5e22f3d19a20528c8ba48c570 | [
0.00019445682119112462,
0.00017271103570237756,
0.00016643315029796213,
0.0001729893556330353,
0.000004067484042025171
] |
{
"id": 3,
"code_window": [
"\t// Global methods\n",
"\topenWindow(_windowId: number, _uris: IURIToOpen[], _options: IOpenSettings): Promise<void> {\n",
"\t\treturn Promise.resolve();\n",
"\t}\n",
"\n",
"\topenExtensionDevelopmentHostWindow(args: ParsedArgs, env: IProcessEnvironment): Promise<void> {\n",
"\t\treturn Promise.resolve();\n",
"\t}\n",
"\n",
"\tgetWindows(): Promise<{ id: number; workspace?: IWorkspaceIdentifier; folderUri?: ISingleFolderWorkspaceIdentifier; title: string; filename?: string; }[]> {\n",
"\t\treturn Promise.resolve([]);\n",
"\t}\n",
"\n",
"\tgetActiveWindowId(): Promise<number | undefined> {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/browser/web.simpleservices.ts",
"type": "replace",
"edit_start_line_idx": 279
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const fs = require('fs');
const path = require('path');
const os = require('os');
// @ts-ignore review
const { remote } = require('electron');
const dialog = remote.dialog;
const builtInExtensionsPath = path.join(__dirname, '..', 'builtInExtensions.json');
const controlFilePath = path.join(os.homedir(), '.vscode-oss-dev', 'extensions', 'control.json');
function readJson(filePath) {
return JSON.parse(fs.readFileSync(filePath, { encoding: 'utf8' }));
}
function writeJson(filePath, obj) {
fs.writeFileSync(filePath, JSON.stringify(obj, null, 2));
}
function renderOption(form, id, title, value, checked) {
const input = document.createElement('input');
input.type = 'radio';
input.id = id;
input.name = 'choice';
input.value = value;
input.checked = !!checked;
form.appendChild(input);
const label = document.createElement('label');
label.setAttribute('for', id);
label.textContent = title;
form.appendChild(label);
return input;
}
function render(el, state) {
function setState(state) {
try {
writeJson(controlFilePath, state.control);
} catch (err) {
console.error(err);
}
el.innerHTML = '';
render(el, state);
}
const ul = document.createElement('ul');
const { builtin, control } = state;
for (const ext of builtin) {
const controlState = control[ext.name] || 'marketplace';
const li = document.createElement('li');
ul.appendChild(li);
const name = document.createElement('code');
name.textContent = ext.name;
li.appendChild(name);
const form = document.createElement('form');
li.appendChild(form);
const marketplaceInput = renderOption(form, `marketplace-${ext.name}`, 'Marketplace', 'marketplace', controlState === 'marketplace');
marketplaceInput.onchange = function () {
control[ext.name] = 'marketplace';
setState({ builtin, control });
};
const disabledInput = renderOption(form, `disabled-${ext.name}`, 'Disabled', 'disabled', controlState === 'disabled');
disabledInput.onchange = function () {
control[ext.name] = 'disabled';
setState({ builtin, control });
};
let local = undefined;
if (controlState !== 'marketplace' && controlState !== 'disabled') {
local = controlState;
}
const localInput = renderOption(form, `local-${ext.name}`, 'Local', 'local', !!local);
localInput.onchange = function () {
const result = dialog.showOpenDialog(remote.getCurrentWindow(), {
title: 'Choose Folder',
properties: ['openDirectory']
});
if (result && result.length >= 1) {
control[ext.name] = result[0];
}
setState({ builtin, control });
};
if (local) {
const localSpan = document.createElement('code');
localSpan.className = 'local';
localSpan.textContent = local;
form.appendChild(localSpan);
}
}
el.appendChild(ul);
}
function main() {
const el = document.getElementById('extensions');
const builtin = readJson(builtInExtensionsPath);
let control;
try {
control = readJson(controlFilePath);
} catch (err) {
control = {};
}
render(el, { builtin, control });
}
window.onload = main; | build/builtin/browser-main.js | 0 | https://github.com/microsoft/vscode/commit/23f2275c23aeebf5e22f3d19a20528c8ba48c570 | [
0.00017944427963811904,
0.00017392387962900102,
0.00016318049165420234,
0.00017505284631624818,
0.000003991554422100307
] |
{
"id": 4,
"code_window": [
"import { IWindowsService } from 'vs/platform/windows/common/windows';\n",
"import { IProcessEnvironment } from 'vs/base/common/platform';\n",
"import { ParsedArgs } from 'vs/platform/environment/common/environment';\n",
"\n",
"export class ExtensionHostDebugService extends ExtensionHostDebugChannelClient {\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { WindowsService } from 'vs/platform/windows/electron-browser/windowsService';\n"
],
"file_path": "src/vs/workbench/contrib/debug/electron-browser/extensionHostDebugService.ts",
"type": "add",
"edit_start_line_idx": 12
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { IExtensionHostDebugService } from 'vs/platform/debug/common/extensionHostDebug';
import { IMainProcessService } from 'vs/platform/ipc/electron-browser/mainProcessService';
import { ExtensionHostDebugChannelClient, ExtensionHostDebugBroadcastChannel } from 'vs/platform/debug/common/extensionHostDebugIpc';
import { IWindowsService } from 'vs/platform/windows/common/windows';
import { IProcessEnvironment } from 'vs/base/common/platform';
import { ParsedArgs } from 'vs/platform/environment/common/environment';
export class ExtensionHostDebugService extends ExtensionHostDebugChannelClient {
constructor(
@IMainProcessService readonly mainProcessService: IMainProcessService,
@IWindowsService private readonly windowsService: IWindowsService
) {
super(mainProcessService.getChannel(ExtensionHostDebugBroadcastChannel.ChannelName));
}
openExtensionDevelopmentHostWindow(args: ParsedArgs, env: IProcessEnvironment): Promise<void> {
// TODO@Isidor use debug IPC channel
return this.windowsService.openExtensionDevelopmentHostWindow(args, env);
}
}
registerSingleton(IExtensionHostDebugService, ExtensionHostDebugService, true);
| src/vs/workbench/contrib/debug/electron-browser/extensionHostDebugService.ts | 1 | https://github.com/microsoft/vscode/commit/23f2275c23aeebf5e22f3d19a20528c8ba48c570 | [
0.9992315769195557,
0.9968640208244324,
0.9924542307853699,
0.998906135559082,
0.003120993496850133
] |
{
"id": 4,
"code_window": [
"import { IWindowsService } from 'vs/platform/windows/common/windows';\n",
"import { IProcessEnvironment } from 'vs/base/common/platform';\n",
"import { ParsedArgs } from 'vs/platform/environment/common/environment';\n",
"\n",
"export class ExtensionHostDebugService extends ExtensionHostDebugChannelClient {\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { WindowsService } from 'vs/platform/windows/electron-browser/windowsService';\n"
],
"file_path": "src/vs/workbench/contrib/debug/electron-browser/extensionHostDebugService.ts",
"type": "add",
"edit_start_line_idx": 12
} | <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M11.219 8.35484C11.6063 8.12309 12.049 8.00047 12.5003 8C12.8904 7.99939 13.2753 8.0901 13.6241 8.26486C13.9729 8.43963 14.276 8.6936 14.5091 9.00646C14.7421 9.31933 14.8987 9.6824 14.9664 10.0666C15.034 10.4509 15.0108 10.8456 14.8985 11.2192C14.7863 11.5929 14.5882 11.9351 14.32 12.2184C14.0518 12.5018 13.7211 12.7185 13.3542 12.8511C12.9873 12.9837 12.5944 13.0287 12.207 12.9823C11.8197 12.9359 11.4485 12.7995 11.1233 12.584L8.7683 14.9399L8.06055 14.2322L10.4163 11.877C10.1677 11.5003 10.0258 11.0634 10.0054 10.6126C9.98511 10.1618 10.0872 9.71384 10.3009 9.31634C10.5145 8.91885 10.8318 8.58659 11.219 8.35484ZM11.667 11.7472C11.9136 11.912 12.2036 12 12.5003 12C12.8981 12 13.2797 11.842 13.561 11.5607C13.8423 11.2794 14.0003 10.8978 14.0003 10.5C14.0003 10.2033 13.9123 9.91332 13.7475 9.66665C13.5827 9.41997 13.3484 9.22772 13.0743 9.11418C12.8002 9.00065 12.4986 8.97095 12.2077 9.02883C11.9167 9.0867 11.6494 9.22956 11.4396 9.43934C11.2299 9.64912 11.087 9.9164 11.0291 10.2074C10.9712 10.4983 11.001 10.7999 11.1145 11.074C11.228 11.3481 11.4203 11.5824 11.667 11.7472Z" fill="#424242"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M13 1L14 2V7.33573C13.6829 7.18584 13.3457 7.08481 13 7.03533V2L8 2L8 12.8787L6.87837 14H2L1 13V2L2 1H13ZM9.70794 14H9.70785L10 13.7077V13.7079L9.70794 14ZM13 10.5174C13.0002 10.5116 13.0003 10.5058 13.0003 10.5C13.0003 10.4942 13.0002 10.4884 13 10.4826V10.5174ZM2 2L7 2L7 13H2L2 2Z" fill="#424242"/>
</svg>
| src/vs/workbench/contrib/files/browser/media/preview-light.svg | 0 | https://github.com/microsoft/vscode/commit/23f2275c23aeebf5e22f3d19a20528c8ba48c570 | [
0.0018488949863240123,
0.0018488949863240123,
0.0018488949863240123,
0.0018488949863240123,
0
] |
{
"id": 4,
"code_window": [
"import { IWindowsService } from 'vs/platform/windows/common/windows';\n",
"import { IProcessEnvironment } from 'vs/base/common/platform';\n",
"import { ParsedArgs } from 'vs/platform/environment/common/environment';\n",
"\n",
"export class ExtensionHostDebugService extends ExtensionHostDebugChannelClient {\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { WindowsService } from 'vs/platform/windows/electron-browser/windowsService';\n"
],
"file_path": "src/vs/workbench/contrib/debug/electron-browser/extensionHostDebugService.ts",
"type": "add",
"edit_start_line_idx": 12
} | /*---------------------------------------------------------------------------------------------
* 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 { URI } from 'vs/base/common/uri';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { TextFileEditorModelManager } from 'vs/workbench/services/textfile/common/textFileEditorModelManager';
import { workbenchInstantiationService, TestFileService } from 'vs/workbench/test/workbenchTestServices';
import { TextFileEditorModel } from 'vs/workbench/services/textfile/common/textFileEditorModel';
import { IFileService, FileChangesEvent, FileChangeType } from 'vs/platform/files/common/files';
import { IModelService } from 'vs/editor/common/services/modelService';
import { timeout } from 'vs/base/common/async';
import { toResource } from 'vs/base/test/common/utils';
import { ModesRegistry, PLAINTEXT_MODE_ID } from 'vs/editor/common/modes/modesRegistry';
export class TestTextFileEditorModelManager extends TextFileEditorModelManager {
protected debounceDelay(): number {
return 10;
}
}
class ServiceAccessor {
constructor(
@IFileService public fileService: TestFileService,
@IModelService public modelService: IModelService
) {
}
}
suite('Files - TextFileEditorModelManager', () => {
let instantiationService: IInstantiationService;
let accessor: ServiceAccessor;
setup(() => {
instantiationService = workbenchInstantiationService();
accessor = instantiationService.createInstance(ServiceAccessor);
});
test('add, remove, clear, get, getAll', function () {
const manager: TestTextFileEditorModelManager = instantiationService.createInstance(TestTextFileEditorModelManager);
const model1: TextFileEditorModel = instantiationService.createInstance(TextFileEditorModel, toResource.call(this, '/path/random1.txt'), 'utf8', undefined);
const model2: TextFileEditorModel = instantiationService.createInstance(TextFileEditorModel, toResource.call(this, '/path/random2.txt'), 'utf8', undefined);
const model3: TextFileEditorModel = instantiationService.createInstance(TextFileEditorModel, toResource.call(this, '/path/random3.txt'), 'utf8', undefined);
manager.add(URI.file('/test.html'), model1);
manager.add(URI.file('/some/other.html'), model2);
manager.add(URI.file('/some/this.txt'), model3);
const fileUpper = URI.file('/TEST.html');
assert(!manager.get(URI.file('foo')));
assert.strictEqual(manager.get(URI.file('/test.html')), model1);
assert.ok(!manager.get(fileUpper));
let result = manager.getAll();
assert.strictEqual(3, result.length);
result = manager.getAll(URI.file('/yes'));
assert.strictEqual(0, result.length);
result = manager.getAll(URI.file('/some/other.txt'));
assert.strictEqual(0, result.length);
result = manager.getAll(URI.file('/some/other.html'));
assert.strictEqual(1, result.length);
result = manager.getAll(fileUpper);
assert.strictEqual(0, result.length);
manager.remove(URI.file(''));
result = manager.getAll();
assert.strictEqual(3, result.length);
manager.remove(URI.file('/some/other.html'));
result = manager.getAll();
assert.strictEqual(2, result.length);
manager.remove(fileUpper);
result = manager.getAll();
assert.strictEqual(2, result.length);
manager.clear();
result = manager.getAll();
assert.strictEqual(0, result.length);
model1.dispose();
model2.dispose();
model3.dispose();
});
test('loadOrCreate', async () => {
const manager: TestTextFileEditorModelManager = instantiationService.createInstance(TestTextFileEditorModelManager);
const resource = URI.file('/test.html');
const encoding = 'utf8';
const model = await manager.loadOrCreate(resource, { encoding });
assert.ok(model);
assert.equal(model.getEncoding(), encoding);
assert.equal(manager.get(resource), model);
const model2 = await manager.loadOrCreate(resource, { encoding });
assert.equal(model2, model);
model.dispose();
const model3 = await manager.loadOrCreate(resource, { encoding });
assert.notEqual(model3, model2);
assert.equal(manager.get(resource), model3);
model3.dispose();
});
test('removed from cache when model disposed', function () {
const manager: TestTextFileEditorModelManager = instantiationService.createInstance(TestTextFileEditorModelManager);
const model1: TextFileEditorModel = instantiationService.createInstance(TextFileEditorModel, toResource.call(this, '/path/random1.txt'), 'utf8', undefined);
const model2: TextFileEditorModel = instantiationService.createInstance(TextFileEditorModel, toResource.call(this, '/path/random2.txt'), 'utf8', undefined);
const model3: TextFileEditorModel = instantiationService.createInstance(TextFileEditorModel, toResource.call(this, '/path/random3.txt'), 'utf8', undefined);
manager.add(URI.file('/test.html'), model1);
manager.add(URI.file('/some/other.html'), model2);
manager.add(URI.file('/some/this.txt'), model3);
assert.strictEqual(manager.get(URI.file('/test.html')), model1);
model1.dispose();
assert(!manager.get(URI.file('/test.html')));
model2.dispose();
model3.dispose();
});
test('events', async function () {
TextFileEditorModel.DEFAULT_CONTENT_CHANGE_BUFFER_DELAY = 0;
TextFileEditorModel.DEFAULT_ORPHANED_CHANGE_BUFFER_DELAY = 0;
const manager: TestTextFileEditorModelManager = instantiationService.createInstance(TestTextFileEditorModelManager);
const resource1 = toResource.call(this, '/path/index.txt');
const resource2 = toResource.call(this, '/path/other.txt');
let dirtyCounter = 0;
let revertedCounter = 0;
let savedCounter = 0;
let encodingCounter = 0;
let disposeCounter = 0;
let contentCounter = 0;
manager.onModelDirty(e => {
if (e.resource.toString() === resource1.toString()) {
dirtyCounter++;
}
});
manager.onModelReverted(e => {
if (e.resource.toString() === resource1.toString()) {
revertedCounter++;
}
});
manager.onModelSaved(e => {
if (e.resource.toString() === resource1.toString()) {
savedCounter++;
}
});
manager.onModelEncodingChanged(e => {
if (e.resource.toString() === resource1.toString()) {
encodingCounter++;
}
});
manager.onModelContentChanged(e => {
if (e.resource.toString() === resource1.toString()) {
contentCounter++;
}
});
manager.onModelDisposed(e => {
disposeCounter++;
});
const model1 = await manager.loadOrCreate(resource1, { encoding: 'utf8' });
accessor.fileService.fireFileChanges(new FileChangesEvent([{ resource: resource1, type: FileChangeType.DELETED }]));
accessor.fileService.fireFileChanges(new FileChangesEvent([{ resource: resource1, type: FileChangeType.ADDED }]));
const model2 = await manager.loadOrCreate(resource2, { encoding: 'utf8' });
model1.textEditorModel!.setValue('changed');
model1.updatePreferredEncoding('utf16');
await model1.revert();
model1.textEditorModel!.setValue('changed again');
await model1.save();
model1.dispose();
model2.dispose();
assert.equal(disposeCounter, 2);
await model1.revert();
assert.equal(dirtyCounter, 2);
assert.equal(revertedCounter, 1);
assert.equal(savedCounter, 1);
assert.equal(encodingCounter, 2);
await timeout(10);
assert.equal(contentCounter, 2);
model1.dispose();
model2.dispose();
assert.ok(!accessor.modelService.getModel(resource1));
assert.ok(!accessor.modelService.getModel(resource2));
});
test('events debounced', async function () {
const manager: TestTextFileEditorModelManager = instantiationService.createInstance(TestTextFileEditorModelManager);
const resource1 = toResource.call(this, '/path/index.txt');
const resource2 = toResource.call(this, '/path/other.txt');
let dirtyCounter = 0;
let revertedCounter = 0;
let savedCounter = 0;
TextFileEditorModel.DEFAULT_CONTENT_CHANGE_BUFFER_DELAY = 0;
manager.onModelsDirty(e => {
dirtyCounter += e.length;
assert.equal(e[0].resource.toString(), resource1.toString());
});
manager.onModelsReverted(e => {
revertedCounter += e.length;
assert.equal(e[0].resource.toString(), resource1.toString());
});
manager.onModelsSaved(e => {
savedCounter += e.length;
assert.equal(e[0].resource.toString(), resource1.toString());
});
const model1 = await manager.loadOrCreate(resource1, { encoding: 'utf8' });
const model2 = await manager.loadOrCreate(resource2, { encoding: 'utf8' });
model1.textEditorModel!.setValue('changed');
model1.updatePreferredEncoding('utf16');
await model1.revert();
model1.textEditorModel!.setValue('changed again');
await model1.save();
model1.dispose();
model2.dispose();
await model1.revert();
await timeout(20);
assert.equal(dirtyCounter, 2);
assert.equal(revertedCounter, 1);
assert.equal(savedCounter, 1);
model1.dispose();
model2.dispose();
assert.ok(!accessor.modelService.getModel(resource1));
assert.ok(!accessor.modelService.getModel(resource2));
});
test('disposing model takes it out of the manager', async function () {
const manager: TestTextFileEditorModelManager = instantiationService.createInstance(TestTextFileEditorModelManager);
const resource = toResource.call(this, '/path/index_something.txt');
const model = await manager.loadOrCreate(resource, { encoding: 'utf8' });
model.dispose();
assert.ok(!manager.get(resource));
assert.ok(!accessor.modelService.getModel(model.getResource()));
manager.dispose();
});
test('dispose prevents dirty model from getting disposed', async function () {
const manager: TestTextFileEditorModelManager = instantiationService.createInstance(TestTextFileEditorModelManager);
const resource = toResource.call(this, '/path/index_something.txt');
const model = await manager.loadOrCreate(resource, { encoding: 'utf8' });
model.textEditorModel!.setValue('make dirty');
manager.disposeModel((model as TextFileEditorModel));
assert.ok(!model.isDisposed());
model.revert(true);
manager.disposeModel((model as TextFileEditorModel));
assert.ok(model.isDisposed());
manager.dispose();
});
test('mode', async function () {
const mode = 'text-file-model-manager-test';
ModesRegistry.registerLanguage({
id: mode,
});
const manager: TestTextFileEditorModelManager = instantiationService.createInstance(TestTextFileEditorModelManager);
const resource = toResource.call(this, '/path/index_something.txt');
let model = await manager.loadOrCreate(resource, { mode });
assert.equal(model.textEditorModel!.getModeId(), mode);
model = await manager.loadOrCreate(resource, { mode: 'text' });
assert.equal(model.textEditorModel!.getModeId(), PLAINTEXT_MODE_ID);
manager.disposeModel((model as TextFileEditorModel));
manager.dispose();
});
}); | src/vs/workbench/services/textfile/test/textFileEditorModelManager.test.ts | 0 | https://github.com/microsoft/vscode/commit/23f2275c23aeebf5e22f3d19a20528c8ba48c570 | [
0.0002138626587111503,
0.00017772878345567733,
0.00016592341125942767,
0.00017593998927623034,
0.000008822915333439596
] |
{
"id": 4,
"code_window": [
"import { IWindowsService } from 'vs/platform/windows/common/windows';\n",
"import { IProcessEnvironment } from 'vs/base/common/platform';\n",
"import { ParsedArgs } from 'vs/platform/environment/common/environment';\n",
"\n",
"export class ExtensionHostDebugService extends ExtensionHostDebugChannelClient {\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { WindowsService } from 'vs/platform/windows/electron-browser/windowsService';\n"
],
"file_path": "src/vs/workbench/contrib/debug/electron-browser/extensionHostDebugService.ts",
"type": "add",
"edit_start_line_idx": 12
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'vs/css!./gridview';
import { Event, Emitter, Relay } from 'vs/base/common/event';
import { Orientation, Sash } from 'vs/base/browser/ui/sash/sash';
import { SplitView, IView as ISplitView, Sizing, LayoutPriority, ISplitViewStyles } from 'vs/base/browser/ui/splitview/splitview';
import { Disposable, IDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { $ } from 'vs/base/browser/dom';
import { tail2 as tail } from 'vs/base/common/arrays';
import { Color } from 'vs/base/common/color';
import { clamp } from 'vs/base/common/numbers';
export { Sizing, LayoutPriority } from 'vs/base/browser/ui/splitview/splitview';
export { Orientation } from 'vs/base/browser/ui/sash/sash';
export interface IViewSize {
readonly width: number;
readonly height: number;
}
export interface IView {
readonly element: HTMLElement;
readonly minimumWidth: number;
readonly maximumWidth: number;
readonly minimumHeight: number;
readonly maximumHeight: number;
readonly onDidChange: Event<IViewSize | undefined>;
readonly priority?: LayoutPriority;
readonly snap?: boolean;
layout(width: number, height: number, orientation: Orientation): void;
setVisible?(visible: boolean): void;
}
export interface ISerializableView extends IView {
toJSON(): object;
}
export interface IViewDeserializer<T extends ISerializableView> {
fromJSON(json: any): T;
}
export interface ISerializedLeafNode {
type: 'leaf';
data: any;
size: number;
visible?: boolean;
}
export interface ISerializedBranchNode {
type: 'branch';
data: ISerializedNode[];
size: number;
}
export type ISerializedNode = ISerializedLeafNode | ISerializedBranchNode;
export interface ISerializedGridView {
root: ISerializedNode;
orientation: Orientation;
width: number;
height: number;
}
export function orthogonal(orientation: Orientation): Orientation {
return orientation === Orientation.VERTICAL ? Orientation.HORIZONTAL : Orientation.VERTICAL;
}
export interface Box {
top: number;
left: number;
width: number;
height: number;
}
export interface GridLeafNode {
readonly view: IView;
readonly box: Box;
readonly cachedVisibleSize: number | undefined;
}
export interface GridBranchNode {
readonly children: GridNode[];
readonly box: Box;
}
export type GridNode = GridLeafNode | GridBranchNode;
export function isGridBranchNode(node: GridNode): node is GridBranchNode {
return !!(node as any).children;
}
export interface IGridViewStyles extends ISplitViewStyles { }
const defaultStyles: IGridViewStyles = {
separatorBorder: Color.transparent
};
export interface ILayoutController {
readonly isLayoutEnabled: boolean;
}
export class LayoutController implements ILayoutController {
constructor(public isLayoutEnabled: boolean) { }
}
export class MultiplexLayoutController implements ILayoutController {
get isLayoutEnabled(): boolean { return this.layoutControllers.every(l => l.isLayoutEnabled); }
constructor(private layoutControllers: ILayoutController[]) { }
}
export interface IGridViewOptions {
readonly styles?: IGridViewStyles;
readonly proportionalLayout?: boolean; // default true
readonly layoutController?: ILayoutController;
}
class BranchNode implements ISplitView, IDisposable {
readonly element: HTMLElement;
readonly children: Node[] = [];
private splitview: SplitView;
private _size: number;
get size(): number { return this._size; }
private _orthogonalSize: number;
get orthogonalSize(): number { return this._orthogonalSize; }
private _styles: IGridViewStyles;
get styles(): IGridViewStyles { return this._styles; }
get width(): number {
return this.orientation === Orientation.HORIZONTAL ? this.size : this.orthogonalSize;
}
get height(): number {
return this.orientation === Orientation.HORIZONTAL ? this.orthogonalSize : this.size;
}
get minimumSize(): number {
return this.children.length === 0 ? 0 : Math.max(...this.children.map(c => c.minimumOrthogonalSize));
}
get maximumSize(): number {
return Math.min(...this.children.map(c => c.maximumOrthogonalSize));
}
get priority(): LayoutPriority {
if (this.children.length === 0) {
return LayoutPriority.Normal;
}
const priorities = this.children.map(c => typeof c.priority === 'undefined' ? LayoutPriority.Normal : c.priority);
if (priorities.some(p => p === LayoutPriority.High)) {
return LayoutPriority.High;
} else if (priorities.some(p => p === LayoutPriority.Low)) {
return LayoutPriority.Low;
}
return LayoutPriority.Normal;
}
get minimumOrthogonalSize(): number {
return this.splitview.minimumSize;
}
get maximumOrthogonalSize(): number {
return this.splitview.maximumSize;
}
get minimumWidth(): number {
return this.orientation === Orientation.HORIZONTAL ? this.minimumOrthogonalSize : this.minimumSize;
}
get minimumHeight(): number {
return this.orientation === Orientation.HORIZONTAL ? this.minimumSize : this.minimumOrthogonalSize;
}
get maximumWidth(): number {
return this.orientation === Orientation.HORIZONTAL ? this.maximumOrthogonalSize : this.maximumSize;
}
get maximumHeight(): number {
return this.orientation === Orientation.HORIZONTAL ? this.maximumSize : this.maximumOrthogonalSize;
}
private readonly _onDidChange = new Emitter<number | undefined>();
readonly onDidChange: Event<number | undefined> = this._onDidChange.event;
private childrenChangeDisposable: IDisposable = Disposable.None;
private readonly _onDidSashReset = new Emitter<number[]>();
readonly onDidSashReset: Event<number[]> = this._onDidSashReset.event;
private splitviewSashResetDisposable: IDisposable = Disposable.None;
private childrenSashResetDisposable: IDisposable = Disposable.None;
get orthogonalStartSash(): Sash | undefined { return this.splitview.orthogonalStartSash; }
set orthogonalStartSash(sash: Sash | undefined) { this.splitview.orthogonalStartSash = sash; }
get orthogonalEndSash(): Sash | undefined { return this.splitview.orthogonalEndSash; }
set orthogonalEndSash(sash: Sash | undefined) { this.splitview.orthogonalEndSash = sash; }
constructor(
readonly orientation: Orientation,
readonly layoutController: ILayoutController,
styles: IGridViewStyles,
readonly proportionalLayout: boolean,
size: number = 0,
orthogonalSize: number = 0,
childDescriptors?: INodeDescriptor[]
) {
this._styles = styles;
this._size = size;
this._orthogonalSize = orthogonalSize;
this.element = $('.monaco-grid-branch-node');
if (!childDescriptors) {
// Normal behavior, we have no children yet, just set up the splitview
this.splitview = new SplitView(this.element, { orientation, styles, proportionalLayout });
this.splitview.layout(size, orthogonalSize);
} else {
// Reconstruction behavior, we want to reconstruct a splitview
const descriptor = {
views: childDescriptors.map(childDescriptor => {
return {
view: childDescriptor.node,
size: childDescriptor.node.size,
visible: childDescriptor.node instanceof LeafNode && childDescriptor.visible !== undefined ? childDescriptor.visible : true
};
}),
size: this.orthogonalSize
};
const options = { proportionalLayout, orientation, styles };
this.children = childDescriptors.map(c => c.node);
this.splitview = new SplitView(this.element, { ...options, descriptor });
this.children.forEach((node, index) => {
// Set up orthogonal sashes for children
node.orthogonalStartSash = this.splitview.sashes[index - 1];
node.orthogonalEndSash = this.splitview.sashes[index];
});
}
const onDidSashReset = Event.map(this.splitview.onDidSashReset, i => [i]);
this.splitviewSashResetDisposable = onDidSashReset(this._onDidSashReset.fire, this._onDidSashReset);
const onDidChildrenChange = Event.map(Event.any(...this.children.map(c => c.onDidChange)), () => undefined);
this.childrenChangeDisposable = onDidChildrenChange(this._onDidChange.fire, this._onDidChange);
const onDidChildrenSashReset = Event.any(...this.children.map((c, i) => Event.map(c.onDidSashReset, location => [i, ...location])));
this.childrenSashResetDisposable = onDidChildrenSashReset(this._onDidSashReset.fire, this._onDidSashReset);
}
style(styles: IGridViewStyles): void {
this._styles = styles;
this.splitview.style(styles);
for (const child of this.children) {
if (child instanceof BranchNode) {
child.style(styles);
}
}
}
layout(size: number, orthogonalSize: number | undefined): void {
if (!this.layoutController.isLayoutEnabled) {
return;
}
if (typeof orthogonalSize !== 'number') {
throw new Error('Invalid state');
}
// branch nodes should flip the normal/orthogonal directions
this._size = orthogonalSize;
this._orthogonalSize = size;
this.splitview.layout(orthogonalSize, size);
}
setVisible(visible: boolean): void {
for (const child of this.children) {
child.setVisible(visible);
}
}
addChild(node: Node, size: number | Sizing, index: number, skipLayout?: boolean): void {
if (index < 0 || index > this.children.length) {
throw new Error('Invalid index');
}
this.splitview.addView(node, size, index);
this._addChild(node, index);
this.onDidChildrenChange();
}
private _addChild(node: Node, index: number): void {
const first = index === 0;
const last = index === this.children.length;
this.children.splice(index, 0, node);
node.orthogonalStartSash = this.splitview.sashes[index - 1];
node.orthogonalEndSash = this.splitview.sashes[index];
if (!first) {
this.children[index - 1].orthogonalEndSash = this.splitview.sashes[index - 1];
}
if (!last) {
this.children[index + 1].orthogonalStartSash = this.splitview.sashes[index];
}
}
removeChild(index: number, sizing?: Sizing): void {
if (index < 0 || index >= this.children.length) {
throw new Error('Invalid index');
}
this.splitview.removeView(index, sizing);
this._removeChild(index);
this.onDidChildrenChange();
}
private _removeChild(index: number): Node {
const first = index === 0;
const last = index === this.children.length - 1;
const [child] = this.children.splice(index, 1);
if (!first) {
this.children[index - 1].orthogonalEndSash = this.splitview.sashes[index - 1];
}
if (!last) { // [0,1,2,3] (2) => [0,1,3]
this.children[index].orthogonalStartSash = this.splitview.sashes[Math.max(index - 1, 0)];
}
return child;
}
moveChild(from: number, to: number): void {
if (from === to) {
return;
}
if (from < 0 || from >= this.children.length) {
throw new Error('Invalid from index');
}
to = clamp(to, 0, this.children.length);
if (from < to) {
to--;
}
this.splitview.moveView(from, to);
const child = this._removeChild(from);
this._addChild(child, to);
}
swapChildren(from: number, to: number): void {
if (from === to) {
return;
}
if (from < 0 || from >= this.children.length) {
throw new Error('Invalid from index');
}
to = clamp(to, 0, this.children.length);
this.splitview.swapViews(from, to);
[this.children[from].orthogonalStartSash, this.children[from].orthogonalEndSash, this.children[to].orthogonalStartSash, this.children[to].orthogonalEndSash] = [this.children[to].orthogonalStartSash, this.children[to].orthogonalEndSash, this.children[from].orthogonalStartSash, this.children[from].orthogonalEndSash];
[this.children[from], this.children[to]] = [this.children[to], this.children[from]];
}
resizeChild(index: number, size: number): void {
if (index < 0 || index >= this.children.length) {
throw new Error('Invalid index');
}
this.splitview.resizeView(index, size);
}
distributeViewSizes(recursive = false): void {
this.splitview.distributeViewSizes();
if (recursive) {
for (const child of this.children) {
if (child instanceof BranchNode) {
child.distributeViewSizes(true);
}
}
}
}
getChildSize(index: number): number {
if (index < 0 || index >= this.children.length) {
throw new Error('Invalid index');
}
return this.splitview.getViewSize(index);
}
isChildVisible(index: number): boolean {
if (index < 0 || index >= this.children.length) {
throw new Error('Invalid index');
}
return this.splitview.isViewVisible(index);
}
setChildVisible(index: number, visible: boolean): void {
if (index < 0 || index >= this.children.length) {
throw new Error('Invalid index');
}
if (this.splitview.isViewVisible(index) === visible) {
return;
}
this.splitview.setViewVisible(index, visible);
}
getChildCachedVisibleSize(index: number): number | undefined {
if (index < 0 || index >= this.children.length) {
throw new Error('Invalid index');
}
return this.splitview.getViewCachedVisibleSize(index);
}
private onDidChildrenChange(): void {
const onDidChildrenChange = Event.map(Event.any(...this.children.map(c => c.onDidChange)), () => undefined);
this.childrenChangeDisposable.dispose();
this.childrenChangeDisposable = onDidChildrenChange(this._onDidChange.fire, this._onDidChange);
const onDidChildrenSashReset = Event.any(...this.children.map((c, i) => Event.map(c.onDidSashReset, location => [i, ...location])));
this.childrenSashResetDisposable.dispose();
this.childrenSashResetDisposable = onDidChildrenSashReset(this._onDidSashReset.fire, this._onDidSashReset);
this._onDidChange.fire(undefined);
}
trySet2x2(other: BranchNode): IDisposable {
if (this.children.length !== 2 || other.children.length !== 2) {
return Disposable.None;
}
if (this.getChildSize(0) !== other.getChildSize(0)) {
return Disposable.None;
}
const [firstChild, secondChild] = this.children;
const [otherFirstChild, otherSecondChild] = other.children;
if (!(firstChild instanceof LeafNode) || !(secondChild instanceof LeafNode)) {
return Disposable.None;
}
if (!(otherFirstChild instanceof LeafNode) || !(otherSecondChild instanceof LeafNode)) {
return Disposable.None;
}
if (this.orientation === Orientation.VERTICAL) {
secondChild.linkedWidthNode = otherFirstChild.linkedHeightNode = firstChild;
firstChild.linkedWidthNode = otherSecondChild.linkedHeightNode = secondChild;
otherSecondChild.linkedWidthNode = firstChild.linkedHeightNode = otherFirstChild;
otherFirstChild.linkedWidthNode = secondChild.linkedHeightNode = otherSecondChild;
} else {
otherFirstChild.linkedWidthNode = secondChild.linkedHeightNode = firstChild;
otherSecondChild.linkedWidthNode = firstChild.linkedHeightNode = secondChild;
firstChild.linkedWidthNode = otherSecondChild.linkedHeightNode = otherFirstChild;
secondChild.linkedWidthNode = otherFirstChild.linkedHeightNode = otherSecondChild;
}
const mySash = this.splitview.sashes[0];
const otherSash = other.splitview.sashes[0];
mySash.linkedSash = otherSash;
otherSash.linkedSash = mySash;
this._onDidChange.fire(undefined);
other._onDidChange.fire(undefined);
return toDisposable(() => {
mySash.linkedSash = otherSash.linkedSash = undefined;
firstChild.linkedHeightNode = firstChild.linkedWidthNode = undefined;
secondChild.linkedHeightNode = secondChild.linkedWidthNode = undefined;
otherFirstChild.linkedHeightNode = otherFirstChild.linkedWidthNode = undefined;
otherSecondChild.linkedHeightNode = otherSecondChild.linkedWidthNode = undefined;
});
}
dispose(): void {
for (const child of this.children) {
child.dispose();
}
this._onDidChange.dispose();
this._onDidSashReset.dispose();
this.splitviewSashResetDisposable.dispose();
this.childrenSashResetDisposable.dispose();
this.childrenChangeDisposable.dispose();
this.splitview.dispose();
}
}
class LeafNode implements ISplitView, IDisposable {
private _size: number = 0;
get size(): number { return this._size; }
private _orthogonalSize: number;
get orthogonalSize(): number { return this._orthogonalSize; }
readonly onDidSashReset: Event<number[]> = Event.None;
private _onDidLinkedWidthNodeChange = new Relay<number | undefined>();
private _linkedWidthNode: LeafNode | undefined = undefined;
get linkedWidthNode(): LeafNode | undefined { return this._linkedWidthNode; }
set linkedWidthNode(node: LeafNode | undefined) {
this._onDidLinkedWidthNodeChange.input = node ? node._onDidViewChange : Event.None;
this._linkedWidthNode = node;
this._onDidSetLinkedNode.fire(undefined);
}
private _onDidLinkedHeightNodeChange = new Relay<number | undefined>();
private _linkedHeightNode: LeafNode | undefined = undefined;
get linkedHeightNode(): LeafNode | undefined { return this._linkedHeightNode; }
set linkedHeightNode(node: LeafNode | undefined) {
this._onDidLinkedHeightNodeChange.input = node ? node._onDidViewChange : Event.None;
this._linkedHeightNode = node;
this._onDidSetLinkedNode.fire(undefined);
}
private readonly _onDidSetLinkedNode = new Emitter<number | undefined>();
private _onDidViewChange: Event<number | undefined>;
readonly onDidChange: Event<number | undefined>;
constructor(
readonly view: IView,
readonly orientation: Orientation,
readonly layoutController: ILayoutController,
orthogonalSize: number,
size: number = 0
) {
this._orthogonalSize = orthogonalSize;
this._size = size;
this._onDidViewChange = Event.map(this.view.onDidChange, e => e && (this.orientation === Orientation.VERTICAL ? e.width : e.height));
this.onDidChange = Event.any(this._onDidViewChange, this._onDidSetLinkedNode.event, this._onDidLinkedWidthNodeChange.event, this._onDidLinkedHeightNodeChange.event);
}
get width(): number {
return this.orientation === Orientation.HORIZONTAL ? this.orthogonalSize : this.size;
}
get height(): number {
return this.orientation === Orientation.HORIZONTAL ? this.size : this.orthogonalSize;
}
get element(): HTMLElement {
return this.view.element;
}
private get minimumWidth(): number {
return this.linkedWidthNode ? Math.max(this.linkedWidthNode.view.minimumWidth, this.view.minimumWidth) : this.view.minimumWidth;
}
private get maximumWidth(): number {
return this.linkedWidthNode ? Math.min(this.linkedWidthNode.view.maximumWidth, this.view.maximumWidth) : this.view.maximumWidth;
}
private get minimumHeight(): number {
return this.linkedHeightNode ? Math.max(this.linkedHeightNode.view.minimumHeight, this.view.minimumHeight) : this.view.minimumHeight;
}
private get maximumHeight(): number {
return this.linkedHeightNode ? Math.min(this.linkedHeightNode.view.maximumHeight, this.view.maximumHeight) : this.view.maximumHeight;
}
get minimumSize(): number {
return this.orientation === Orientation.HORIZONTAL ? this.minimumHeight : this.minimumWidth;
}
get maximumSize(): number {
return this.orientation === Orientation.HORIZONTAL ? this.maximumHeight : this.maximumWidth;
}
get priority(): LayoutPriority | undefined {
return this.view.priority;
}
get snap(): boolean | undefined {
return this.view.snap;
}
get minimumOrthogonalSize(): number {
return this.orientation === Orientation.HORIZONTAL ? this.minimumWidth : this.minimumHeight;
}
get maximumOrthogonalSize(): number {
return this.orientation === Orientation.HORIZONTAL ? this.maximumWidth : this.maximumHeight;
}
set orthogonalStartSash(sash: Sash) {
// noop
}
set orthogonalEndSash(sash: Sash) {
// noop
}
layout(size: number, orthogonalSize: number | undefined): void {
if (!this.layoutController.isLayoutEnabled) {
return;
}
if (typeof orthogonalSize !== 'number') {
throw new Error('Invalid state');
}
this._size = size;
this._orthogonalSize = orthogonalSize;
this.view.layout(this.width, this.height, orthogonal(this.orientation));
}
setVisible(visible: boolean): void {
if (this.view.setVisible) {
this.view.setVisible(visible);
}
}
dispose(): void { }
}
type Node = BranchNode | LeafNode;
export interface INodeDescriptor {
node: Node;
visible?: boolean;
}
function flipNode<T extends Node>(node: T, size: number, orthogonalSize: number): T {
if (node instanceof BranchNode) {
const result = new BranchNode(orthogonal(node.orientation), node.layoutController, node.styles, node.proportionalLayout, size, orthogonalSize);
let totalSize = 0;
for (let i = node.children.length - 1; i >= 0; i--) {
const child = node.children[i];
const childSize = child instanceof BranchNode ? child.orthogonalSize : child.size;
let newSize = node.size === 0 ? 0 : Math.round((size * childSize) / node.size);
totalSize += newSize;
// The last view to add should adjust to rounding errors
if (i === 0) {
newSize += size - totalSize;
}
result.addChild(flipNode(child, orthogonalSize, newSize), newSize, 0);
}
return result as T;
} else {
return new LeafNode((node as LeafNode).view, orthogonal(node.orientation), node.layoutController, orthogonalSize) as T;
}
}
export class GridView implements IDisposable {
readonly element: HTMLElement;
private styles: IGridViewStyles;
private proportionalLayout: boolean;
private _root!: BranchNode;
private onDidSashResetRelay = new Relay<number[]>();
readonly onDidSashReset: Event<number[]> = this.onDidSashResetRelay.event;
private disposable2x2: IDisposable = Disposable.None;
private get root(): BranchNode {
return this._root;
}
private set root(root: BranchNode) {
const oldRoot = this._root;
if (oldRoot) {
this.element.removeChild(oldRoot.element);
oldRoot.dispose();
}
this._root = root;
this.element.appendChild(root.element);
this.onDidSashResetRelay.input = root.onDidSashReset;
this._onDidChange.input = Event.map(root.onDidChange, () => undefined); // TODO
}
get orientation(): Orientation {
return this._root.orientation;
}
set orientation(orientation: Orientation) {
if (this._root.orientation === orientation) {
return;
}
const { size, orthogonalSize } = this._root;
this.root = flipNode(this._root, orthogonalSize, size);
this.root.layout(size, orthogonalSize);
}
get width(): number { return this.root.width; }
get height(): number { return this.root.height; }
get minimumWidth(): number { return this.root.minimumWidth; }
get minimumHeight(): number { return this.root.minimumHeight; }
get maximumWidth(): number { return this.root.maximumHeight; }
get maximumHeight(): number { return this.root.maximumHeight; }
private _onDidChange = new Relay<IViewSize | undefined>();
readonly onDidChange = this._onDidChange.event;
/**
* The first layout controller makes sure layout only propagates
* to the views after the very first call to gridview.layout()
*/
private firstLayoutController: LayoutController;
private layoutController: LayoutController;
constructor(options: IGridViewOptions = {}) {
this.element = $('.monaco-grid-view');
this.styles = options.styles || defaultStyles;
this.proportionalLayout = typeof options.proportionalLayout !== 'undefined' ? !!options.proportionalLayout : true;
this.firstLayoutController = new LayoutController(false);
this.layoutController = new MultiplexLayoutController([
this.firstLayoutController,
...(options.layoutController ? [options.layoutController] : [])
]);
this.root = new BranchNode(Orientation.VERTICAL, this.layoutController, this.styles, this.proportionalLayout);
}
getViewMap(map: Map<IView, HTMLElement>, node?: Node): void {
if (!node) {
node = this.root;
}
if (node instanceof BranchNode) {
node.children.forEach(child => this.getViewMap(map, child));
} else {
map.set(node.view, node.element);
}
}
style(styles: IGridViewStyles): void {
this.styles = styles;
this.root.style(styles);
}
layout(width: number, height: number): void {
this.firstLayoutController.isLayoutEnabled = true;
const [size, orthogonalSize] = this.root.orientation === Orientation.HORIZONTAL ? [height, width] : [width, height];
this.root.layout(size, orthogonalSize);
}
addView(view: IView, size: number | Sizing, location: number[]): void {
this.disposable2x2.dispose();
this.disposable2x2 = Disposable.None;
const [rest, index] = tail(location);
const [pathToParent, parent] = this.getNode(rest);
if (parent instanceof BranchNode) {
const node = new LeafNode(view, orthogonal(parent.orientation), this.layoutController, parent.orthogonalSize);
parent.addChild(node, size, index);
} else {
const [, grandParent] = tail(pathToParent);
const [, parentIndex] = tail(rest);
let newSiblingSize: number | Sizing = 0;
const newSiblingCachedVisibleSize = grandParent.getChildCachedVisibleSize(parentIndex);
if (typeof newSiblingCachedVisibleSize === 'number') {
newSiblingSize = Sizing.Invisible(newSiblingCachedVisibleSize);
}
grandParent.removeChild(parentIndex);
const newParent = new BranchNode(parent.orientation, parent.layoutController, this.styles, this.proportionalLayout, parent.size, parent.orthogonalSize);
grandParent.addChild(newParent, parent.size, parentIndex);
const newSibling = new LeafNode(parent.view, grandParent.orientation, this.layoutController, parent.size);
newParent.addChild(newSibling, newSiblingSize, 0);
if (typeof size !== 'number' && size.type === 'split') {
size = Sizing.Split(0);
}
const node = new LeafNode(view, grandParent.orientation, this.layoutController, parent.size);
newParent.addChild(node, size, index);
}
}
removeView(location: number[], sizing?: Sizing): IView {
this.disposable2x2.dispose();
this.disposable2x2 = Disposable.None;
const [rest, index] = tail(location);
const [pathToParent, parent] = this.getNode(rest);
if (!(parent instanceof BranchNode)) {
throw new Error('Invalid location');
}
const node = parent.children[index];
if (!(node instanceof LeafNode)) {
throw new Error('Invalid location');
}
parent.removeChild(index, sizing);
if (parent.children.length === 0) {
throw new Error('Invalid grid state');
}
if (parent.children.length > 1) {
return node.view;
}
if (pathToParent.length === 0) { // parent is root
const sibling = parent.children[0];
if (sibling instanceof LeafNode) {
return node.view;
}
// we must promote sibling to be the new root
parent.removeChild(0);
this.root = sibling;
return node.view;
}
const [, grandParent] = tail(pathToParent);
const [, parentIndex] = tail(rest);
const sibling = parent.children[0];
const isSiblingVisible = parent.isChildVisible(0);
parent.removeChild(0);
const sizes = grandParent.children.map((_, i) => grandParent.getChildSize(i));
grandParent.removeChild(parentIndex, sizing);
if (sibling instanceof BranchNode) {
sizes.splice(parentIndex, 1, ...sibling.children.map(c => c.size));
for (let i = 0; i < sibling.children.length; i++) {
const child = sibling.children[i];
grandParent.addChild(child, child.size, parentIndex + i);
}
} else {
const newSibling = new LeafNode(sibling.view, orthogonal(sibling.orientation), this.layoutController, sibling.size);
const sizing = isSiblingVisible ? sibling.orthogonalSize : Sizing.Invisible(sibling.orthogonalSize);
grandParent.addChild(newSibling, sizing, parentIndex);
}
for (let i = 0; i < sizes.length; i++) {
grandParent.resizeChild(i, sizes[i]);
}
return node.view;
}
moveView(parentLocation: number[], from: number, to: number): void {
const [, parent] = this.getNode(parentLocation);
if (!(parent instanceof BranchNode)) {
throw new Error('Invalid location');
}
parent.moveChild(from, to);
}
swapViews(from: number[], to: number[]): void {
const [fromRest, fromIndex] = tail(from);
const [, fromParent] = this.getNode(fromRest);
if (!(fromParent instanceof BranchNode)) {
throw new Error('Invalid from location');
}
const fromSize = fromParent.getChildSize(fromIndex);
const fromNode = fromParent.children[fromIndex];
if (!(fromNode instanceof LeafNode)) {
throw new Error('Invalid from location');
}
const [toRest, toIndex] = tail(to);
const [, toParent] = this.getNode(toRest);
if (!(toParent instanceof BranchNode)) {
throw new Error('Invalid to location');
}
const toSize = toParent.getChildSize(toIndex);
const toNode = toParent.children[toIndex];
if (!(toNode instanceof LeafNode)) {
throw new Error('Invalid to location');
}
if (fromParent === toParent) {
fromParent.swapChildren(fromIndex, toIndex);
} else {
fromParent.removeChild(fromIndex);
toParent.removeChild(toIndex);
fromParent.addChild(toNode, fromSize, fromIndex);
toParent.addChild(fromNode, toSize, toIndex);
}
}
resizeView(location: number[], { width, height }: Partial<IViewSize>): void {
const [rest, index] = tail(location);
const [pathToParent, parent] = this.getNode(rest);
if (!(parent instanceof BranchNode)) {
throw new Error('Invalid location');
}
if (!width && !height) {
return;
}
const [parentSize, grandParentSize] = parent.orientation === Orientation.HORIZONTAL ? [width, height] : [height, width];
if (typeof grandParentSize === 'number' && pathToParent.length > 0) {
const [, grandParent] = tail(pathToParent);
const [, parentIndex] = tail(rest);
grandParent.resizeChild(parentIndex, grandParentSize);
}
if (typeof parentSize === 'number') {
parent.resizeChild(index, parentSize);
}
}
getViewSize(location?: number[]): IViewSize {
if (!location) {
return { width: this.root.width, height: this.root.height };
}
const [, node] = this.getNode(location);
return { width: node.width, height: node.height };
}
getViewCachedVisibleSize(location: number[]): number | undefined {
const [rest, index] = tail(location);
const [, parent] = this.getNode(rest);
if (!(parent instanceof BranchNode)) {
throw new Error('Invalid location');
}
return parent.getChildCachedVisibleSize(index);
}
maximizeViewSize(location: number[]): void {
const [ancestors, node] = this.getNode(location);
if (!(node instanceof LeafNode)) {
throw new Error('Invalid location');
}
for (let i = 0; i < ancestors.length; i++) {
ancestors[i].resizeChild(location[i], Number.POSITIVE_INFINITY);
}
}
distributeViewSizes(location?: number[]): void {
if (!location) {
this.root.distributeViewSizes(true);
return;
}
const [, node] = this.getNode(location);
if (!(node instanceof BranchNode)) {
throw new Error('Invalid location');
}
node.distributeViewSizes();
}
isViewVisible(location: number[]): boolean {
const [rest, index] = tail(location);
const [, parent] = this.getNode(rest);
if (!(parent instanceof BranchNode)) {
throw new Error('Invalid from location');
}
return parent.isChildVisible(index);
}
setViewVisible(location: number[], visible: boolean): void {
const [rest, index] = tail(location);
const [, parent] = this.getNode(rest);
if (!(parent instanceof BranchNode)) {
throw new Error('Invalid from location');
}
parent.setChildVisible(index, visible);
}
getView(): GridBranchNode;
getView(location?: number[]): GridNode;
getView(location?: number[]): GridNode {
const node = location ? this.getNode(location)[1] : this._root;
return this._getViews(node, this.orientation, { top: 0, left: 0, width: this.width, height: this.height });
}
static deserialize<T extends ISerializableView>(json: ISerializedGridView, deserializer: IViewDeserializer<T>, options: IGridViewOptions = {}): GridView {
if (typeof json.orientation !== 'number') {
throw new Error('Invalid JSON: \'orientation\' property must be a number.');
} else if (typeof json.width !== 'number') {
throw new Error('Invalid JSON: \'width\' property must be a number.');
} else if (typeof json.height !== 'number') {
throw new Error('Invalid JSON: \'height\' property must be a number.');
}
const orientation = json.orientation;
const height = json.height;
const result = new GridView(options);
result._deserialize(json.root as ISerializedBranchNode, orientation, deserializer, height);
return result;
}
private _deserialize(root: ISerializedBranchNode, orientation: Orientation, deserializer: IViewDeserializer<ISerializableView>, orthogonalSize: number): void {
this.root = this._deserializeNode(root, orientation, deserializer, orthogonalSize) as BranchNode;
}
private _deserializeNode(node: ISerializedNode, orientation: Orientation, deserializer: IViewDeserializer<ISerializableView>, orthogonalSize: number): Node {
let result: Node;
if (node.type === 'branch') {
const serializedChildren = node.data as ISerializedNode[];
const children = serializedChildren.map(serializedChild => {
return {
node: this._deserializeNode(serializedChild, orthogonal(orientation), deserializer, node.size),
visible: (serializedChild as { visible?: boolean }).visible
} as INodeDescriptor;
});
result = new BranchNode(orientation, this.layoutController, this.styles, this.proportionalLayout, node.size, orthogonalSize, children);
} else {
result = new LeafNode(deserializer.fromJSON(node.data), orientation, this.layoutController, orthogonalSize, node.size);
}
return result;
}
private _getViews(node: Node, orientation: Orientation, box: Box, cachedVisibleSize?: number): GridNode {
if (node instanceof LeafNode) {
return { view: node.view, box, cachedVisibleSize };
}
const children: GridNode[] = [];
let i = 0;
let offset = 0;
for (const child of node.children) {
const childOrientation = orthogonal(orientation);
const childBox: Box = orientation === Orientation.HORIZONTAL
? { top: box.top, left: box.left + offset, width: child.width, height: box.height }
: { top: box.top + offset, left: box.left, width: box.width, height: child.height };
const cachedVisibleSize = node.getChildCachedVisibleSize(i++);
children.push(this._getViews(child, childOrientation, childBox, cachedVisibleSize));
offset += orientation === Orientation.HORIZONTAL ? child.width : child.height;
}
return { children, box };
}
private getNode(location: number[], node: Node = this.root, path: BranchNode[] = []): [BranchNode[], Node] {
if (location.length === 0) {
return [path, node];
}
if (!(node instanceof BranchNode)) {
throw new Error('Invalid location');
}
const [index, ...rest] = location;
if (index < 0 || index >= node.children.length) {
throw new Error('Invalid location');
}
const child = node.children[index];
path.push(node);
return this.getNode(rest, child, path);
}
trySet2x2(): void {
this.disposable2x2.dispose();
this.disposable2x2 = Disposable.None;
if (this.root.children.length !== 2) {
return;
}
const [first, second] = this.root.children;
if (!(first instanceof BranchNode) || !(second instanceof BranchNode)) {
return;
}
this.disposable2x2 = first.trySet2x2(second);
}
dispose(): void {
this.onDidSashResetRelay.dispose();
this.root.dispose();
if (this.element && this.element.parentElement) {
this.element.parentElement.removeChild(this.element);
}
}
}
| src/vs/base/browser/ui/grid/gridview.ts | 0 | https://github.com/microsoft/vscode/commit/23f2275c23aeebf5e22f3d19a20528c8ba48c570 | [
0.00018254284805152565,
0.00017373377340845764,
0.00016106991097331047,
0.00017435038171242923,
0.0000030681271709909197
] |
{
"id": 5,
"code_window": [
"\t\tsuper(mainProcessService.getChannel(ExtensionHostDebugBroadcastChannel.ChannelName));\n",
"\t}\n",
"\n",
"\topenExtensionDevelopmentHostWindow(args: ParsedArgs, env: IProcessEnvironment): Promise<void> {\n",
"\t\t// TODO@Isidor use debug IPC channel\n",
"\t\treturn this.windowsService.openExtensionDevelopmentHostWindow(args, env);\n",
"\t}\n",
"}\n",
"\n",
"registerSingleton(IExtensionHostDebugService, ExtensionHostDebugService, true);"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn (this.windowsService as WindowsService).openExtensionDevelopmentHostWindow(args, env);\n"
],
"file_path": "src/vs/workbench/contrib/debug/electron-browser/extensionHostDebugService.ts",
"type": "replace",
"edit_start_line_idx": 24
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { Event } from 'vs/base/common/event';
import { ITelemetryData } from 'vs/platform/telemetry/common/telemetry';
import { IProcessEnvironment, isMacintosh, isLinux, isWeb } from 'vs/base/common/platform';
import { ParsedArgs, IEnvironmentService } from 'vs/platform/environment/common/environment';
import { IWorkspaceIdentifier, ISingleFolderWorkspaceIdentifier } from 'vs/platform/workspaces/common/workspaces';
import { IRecentlyOpened, IRecent } from 'vs/platform/history/common/history';
import { ExportData } from 'vs/base/common/performance';
import { LogLevel } from 'vs/platform/log/common/log';
import { DisposableStore, Disposable } from 'vs/base/common/lifecycle';
import { URI, UriComponents } from 'vs/base/common/uri';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { CancelablePromise, createCancelablePromise } from 'vs/base/common/async';
export const IWindowsService = createDecorator<IWindowsService>('windowsService');
export interface INativeOpenDialogOptions {
forceNewWindow?: boolean;
defaultPath?: string;
telemetryEventName?: string;
telemetryExtraData?: ITelemetryData;
}
export interface IEnterWorkspaceResult {
workspace: IWorkspaceIdentifier;
backupPath?: string;
}
export interface OpenDialogOptions {
title?: string;
defaultPath?: string;
buttonLabel?: string;
filters?: FileFilter[];
properties?: Array<'openFile' | 'openDirectory' | 'multiSelections' | 'showHiddenFiles' | 'createDirectory' | 'promptToCreate' | 'noResolveAliases' | 'treatPackageAsDirectory'>;
message?: string;
}
export interface FileFilter {
extensions: string[];
name: string;
}
export interface MessageBoxOptions {
type?: string;
buttons?: string[];
defaultId?: number;
title?: string;
message: string;
detail?: string;
checkboxLabel?: string;
checkboxChecked?: boolean;
cancelId?: number;
noLink?: boolean;
normalizeAccessKeys?: boolean;
}
export interface SaveDialogOptions {
title?: string;
defaultPath?: string;
buttonLabel?: string;
filters?: FileFilter[];
message?: string;
nameFieldLabel?: string;
showsTagField?: boolean;
}
export interface IWindowsService {
_serviceBrand: undefined;
readonly onWindowOpen: Event<number>;
readonly onWindowFocus: Event<number>;
readonly onWindowBlur: Event<number>;
readonly onWindowMaximize: Event<number>;
readonly onWindowUnmaximize: Event<number>;
readonly onRecentlyOpenedChange: Event<void>;
enterWorkspace(windowId: number, path: URI): Promise<IEnterWorkspaceResult | undefined>;
addRecentlyOpened(recents: IRecent[]): Promise<void>;
removeFromRecentlyOpened(paths: URI[]): Promise<void>;
clearRecentlyOpened(): Promise<void>;
getRecentlyOpened(windowId: number): Promise<IRecentlyOpened>;
focusWindow(windowId: number): Promise<void>;
closeWindow(windowId: number): Promise<void>;
isFocused(windowId: number): Promise<boolean>;
isMaximized(windowId: number): Promise<boolean>;
maximizeWindow(windowId: number): Promise<void>;
unmaximizeWindow(windowId: number): Promise<void>;
minimizeWindow(windowId: number): Promise<void>;
// Global methods
openWindow(windowId: number, uris: IURIToOpen[], options: IOpenSettings): Promise<void>;
openExtensionDevelopmentHostWindow(args: ParsedArgs, env: IProcessEnvironment): Promise<void>;
getWindows(): Promise<{ id: number; workspace?: IWorkspaceIdentifier; folderUri?: ISingleFolderWorkspaceIdentifier; title: string; filename?: string; }[]>;
getActiveWindowId(): Promise<number | undefined>;
}
export const IWindowService = createDecorator<IWindowService>('windowService');
export interface IOpenSettings {
forceNewWindow?: boolean;
forceReuseWindow?: boolean;
diffMode?: boolean;
addMode?: boolean;
gotoLineMode?: boolean;
noRecentEntry?: boolean;
waitMarkerFileURI?: URI;
args?: ParsedArgs;
}
export type IURIToOpen = IWorkspaceToOpen | IFolderToOpen | IFileToOpen;
export interface IWorkspaceToOpen {
workspaceUri: URI;
label?: string;
}
export interface IFolderToOpen {
folderUri: URI;
label?: string;
}
export interface IFileToOpen {
fileUri: URI;
label?: string;
}
export function isWorkspaceToOpen(uriToOpen: IURIToOpen): uriToOpen is IWorkspaceToOpen {
return !!(uriToOpen as IWorkspaceToOpen)['workspaceUri'];
}
export function isFolderToOpen(uriToOpen: IURIToOpen): uriToOpen is IFolderToOpen {
return !!(uriToOpen as IFolderToOpen)['folderUri'];
}
export function isFileToOpen(uriToOpen: IURIToOpen): uriToOpen is IFileToOpen {
return !!(uriToOpen as IFileToOpen)['fileUri'];
}
export interface IWindowService {
_serviceBrand: undefined;
readonly onDidChangeFocus: Event<boolean>;
readonly onDidChangeMaximize: Event<boolean>;
readonly hasFocus: boolean;
readonly windowId: number;
enterWorkspace(path: URI): Promise<IEnterWorkspaceResult | undefined>;
getRecentlyOpened(): Promise<IRecentlyOpened>;
addRecentlyOpened(recents: IRecent[]): Promise<void>;
removeFromRecentlyOpened(paths: URI[]): Promise<void>;
focusWindow(): Promise<void>;
closeWindow(): Promise<void>;
openWindow(uris: IURIToOpen[], options?: IOpenSettings): Promise<void>;
isFocused(): Promise<boolean>;
isMaximized(): Promise<boolean>;
maximizeWindow(): Promise<void>;
unmaximizeWindow(): Promise<void>;
minimizeWindow(): Promise<void>;
}
export type MenuBarVisibility = 'default' | 'visible' | 'toggle' | 'hidden';
export interface IWindowsConfiguration {
window: IWindowSettings;
}
export interface IWindowSettings {
openFilesInNewWindow: 'on' | 'off' | 'default';
openFoldersInNewWindow: 'on' | 'off' | 'default';
openWithoutArgumentsInNewWindow: 'on' | 'off';
restoreWindows: 'all' | 'folders' | 'one' | 'none';
restoreFullscreen: boolean;
zoomLevel: number;
titleBarStyle: 'native' | 'custom';
autoDetectHighContrast: boolean;
menuBarVisibility: MenuBarVisibility;
newWindowDimensions: 'default' | 'inherit' | 'maximized' | 'fullscreen';
nativeTabs: boolean;
nativeFullScreen: boolean;
enableMenuBarMnemonics: boolean;
closeWhenEmpty: boolean;
clickThroughInactive: boolean;
}
export function getTitleBarStyle(configurationService: IConfigurationService, environment: IEnvironmentService, isExtensionDevelopment = environment.isExtensionDevelopment): 'native' | 'custom' {
if (isWeb) {
return 'custom';
}
const configuration = configurationService.getValue<IWindowSettings>('window');
const isDev = !environment.isBuilt || isExtensionDevelopment;
if (isMacintosh && isDev) {
return 'native'; // not enabled when developing due to https://github.com/electron/electron/issues/3647
}
if (configuration) {
const useNativeTabs = isMacintosh && configuration.nativeTabs === true;
if (useNativeTabs) {
return 'native'; // native tabs on sierra do not work with custom title style
}
const useSimpleFullScreen = isMacintosh && configuration.nativeFullScreen === false;
if (useSimpleFullScreen) {
return 'native'; // simple fullscreen does not work well with custom title style (https://github.com/Microsoft/vscode/issues/63291)
}
const style = configuration.titleBarStyle;
if (style === 'native' || style === 'custom') {
return style;
}
}
return isLinux ? 'native' : 'custom'; // default to custom on all macOS and Windows
}
export const enum OpenContext {
// opening when running from the command line
CLI,
// macOS only: opening from the dock (also when opening files to a running instance from desktop)
DOCK,
// opening from the main application window
MENU,
// opening from a file or folder dialog
DIALOG,
// opening from the OS's UI
DESKTOP,
// opening through the API
API
}
export const enum ReadyState {
/**
* This window has not loaded any HTML yet
*/
NONE,
/**
* This window is loading HTML
*/
LOADING,
/**
* This window is navigating to another HTML
*/
NAVIGATING,
/**
* This window is done loading HTML
*/
READY
}
export interface IPath extends IPathData {
// the file path to open within the instance
fileUri?: URI;
}
export interface IPathsToWaitFor extends IPathsToWaitForData {
paths: IPath[];
waitMarkerFileUri: URI;
}
export interface IPathsToWaitForData {
paths: IPathData[];
waitMarkerFileUri: UriComponents;
}
export interface IPathData {
// the file path to open within the instance
fileUri?: UriComponents;
// the line number in the file path to open
lineNumber?: number;
// the column number in the file path to open
columnNumber?: number;
// a hint that the file exists. if true, the
// file exists, if false it does not. with
// undefined the state is unknown.
exists?: boolean;
}
export interface IOpenFileRequest {
filesToOpenOrCreate?: IPathData[];
filesToDiff?: IPathData[];
filesToWait?: IPathsToWaitForData;
termProgram?: string;
}
export interface IAddFoldersRequest {
foldersToAdd: UriComponents[];
}
export interface IWindowConfiguration extends ParsedArgs {
machineId: string;
windowId: number;
logLevel: LogLevel;
mainPid: number;
appRoot: string;
execPath: string;
isInitialStartup?: boolean;
userEnv: IProcessEnvironment;
nodeCachedDataDir?: string;
backupPath?: string;
backupWorkspaceResource?: URI;
workspace?: IWorkspaceIdentifier;
folderUri?: ISingleFolderWorkspaceIdentifier;
remoteAuthority?: string;
connectionToken?: string;
zoomLevel?: number;
fullscreen?: boolean;
maximized?: boolean;
highContrast?: boolean;
frameless?: boolean;
accessibilitySupport?: boolean;
partsSplashPath?: string;
perfStartTime?: number;
perfAppReady?: number;
perfWindowLoadTime?: number;
perfEntries: ExportData;
filesToOpenOrCreate?: IPath[];
filesToDiff?: IPath[];
filesToWait?: IPathsToWaitFor;
termProgram?: string;
}
export interface IRunActionInWindowRequest {
id: string;
from: 'menu' | 'touchbar' | 'mouse';
args?: any[];
}
export interface IRunKeybindingInWindowRequest {
userSettingsLabel: string;
}
export class ActiveWindowManager extends Disposable {
private readonly disposables = this._register(new DisposableStore());
private firstActiveWindowIdPromise: CancelablePromise<number | undefined> | undefined;
private activeWindowId: number | undefined;
constructor(@IWindowsService windowsService: IWindowsService) {
super();
const onActiveWindowChange = Event.latch(Event.any(windowsService.onWindowOpen, windowsService.onWindowFocus));
onActiveWindowChange(this.setActiveWindow, this, this.disposables);
this.firstActiveWindowIdPromise = createCancelablePromise(_ => windowsService.getActiveWindowId());
this.firstActiveWindowIdPromise
.then(id => this.activeWindowId = typeof this.activeWindowId === 'number' ? this.activeWindowId : id)
.finally(this.firstActiveWindowIdPromise = undefined);
}
private setActiveWindow(windowId: number | undefined) {
if (this.firstActiveWindowIdPromise) {
this.firstActiveWindowIdPromise.cancel();
this.firstActiveWindowIdPromise = undefined;
}
this.activeWindowId = windowId;
}
async getActiveClientId(): Promise<string | undefined> {
const id = this.firstActiveWindowIdPromise ? (await this.firstActiveWindowIdPromise) : this.activeWindowId;
return `window:${id}`;
}
}
| src/vs/platform/windows/common/windows.ts | 1 | https://github.com/microsoft/vscode/commit/23f2275c23aeebf5e22f3d19a20528c8ba48c570 | [
0.8787911534309387,
0.021669715642929077,
0.00016243891150224954,
0.00017116662638727576,
0.13552306592464447
] |
{
"id": 5,
"code_window": [
"\t\tsuper(mainProcessService.getChannel(ExtensionHostDebugBroadcastChannel.ChannelName));\n",
"\t}\n",
"\n",
"\topenExtensionDevelopmentHostWindow(args: ParsedArgs, env: IProcessEnvironment): Promise<void> {\n",
"\t\t// TODO@Isidor use debug IPC channel\n",
"\t\treturn this.windowsService.openExtensionDevelopmentHostWindow(args, env);\n",
"\t}\n",
"}\n",
"\n",
"registerSingleton(IExtensionHostDebugService, ExtensionHostDebugService, true);"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn (this.windowsService as WindowsService).openExtensionDevelopmentHostWindow(args, env);\n"
],
"file_path": "src/vs/workbench/contrib/debug/electron-browser/extensionHostDebugService.ts",
"type": "replace",
"edit_start_line_idx": 24
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as ts from 'typescript';
import * as Lint from 'tslint';
interface AbstractGlobalsRuleConfig {
target: string;
allowed: string[];
}
export abstract class AbstractGlobalsRuleWalker extends Lint.RuleWalker {
constructor(file: ts.SourceFile, private program: ts.Program, opts: Lint.IOptions, private _config: AbstractGlobalsRuleConfig) {
super(file, opts);
}
protected abstract getDisallowedGlobals(): string[];
protected abstract getDefinitionPattern(): string;
visitIdentifier(node: ts.Identifier) {
if (this.getDisallowedGlobals().some(disallowedGlobal => disallowedGlobal === node.text)) {
if (this._config.allowed && this._config.allowed.some(allowed => allowed === node.text)) {
return; // override
}
const checker = this.program.getTypeChecker();
const symbol = checker.getSymbolAtLocation(node);
if (symbol) {
const declarations = symbol.declarations;
if (Array.isArray(declarations) && symbol.declarations.some(declaration => {
if (declaration) {
const parent = declaration.parent;
if (parent) {
const sourceFile = parent.getSourceFile();
if (sourceFile) {
const fileName = sourceFile.fileName;
if (fileName && fileName.indexOf(this.getDefinitionPattern()) >= 0) {
return true;
}
}
}
}
return false;
})) {
this.addFailureAtNode(node, `Cannot use global '${node.text}' in '${this._config.target}'`);
}
}
}
super.visitIdentifier(node);
}
}
| build/lib/tslint/abstractGlobalsRule.ts | 0 | https://github.com/microsoft/vscode/commit/23f2275c23aeebf5e22f3d19a20528c8ba48c570 | [
0.00017578447295818478,
0.00017314928118139505,
0.00017020816449075937,
0.0001734036486595869,
0.0000022161955257615773
] |
{
"id": 5,
"code_window": [
"\t\tsuper(mainProcessService.getChannel(ExtensionHostDebugBroadcastChannel.ChannelName));\n",
"\t}\n",
"\n",
"\topenExtensionDevelopmentHostWindow(args: ParsedArgs, env: IProcessEnvironment): Promise<void> {\n",
"\t\t// TODO@Isidor use debug IPC channel\n",
"\t\treturn this.windowsService.openExtensionDevelopmentHostWindow(args, env);\n",
"\t}\n",
"}\n",
"\n",
"registerSingleton(IExtensionHostDebugService, ExtensionHostDebugService, true);"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn (this.windowsService as WindowsService).openExtensionDevelopmentHostWindow(args, env);\n"
],
"file_path": "src/vs/workbench/contrib/debug/electron-browser/extensionHostDebugService.ts",
"type": "replace",
"edit_start_line_idx": 24
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { VSBuffer } from 'vs/base/common/buffer';
import { CancellationToken } from 'vs/base/common/cancellation';
import { IRemoteConsoleLog } from 'vs/base/common/console';
import { SerializedError } from 'vs/base/common/errors';
import { IRelativePattern } from 'vs/base/common/glob';
import { IMarkdownString } from 'vs/base/common/htmlContent';
import { IDisposable } from 'vs/base/common/lifecycle';
import Severity from 'vs/base/common/severity';
import { URI, UriComponents } from 'vs/base/common/uri';
import { RenderLineNumbersType, TextEditorCursorStyle } from 'vs/editor/common/config/editorOptions';
import { IPosition } from 'vs/editor/common/core/position';
import { IRange } from 'vs/editor/common/core/range';
import { ISelection, Selection } from 'vs/editor/common/core/selection';
import * as editorCommon from 'vs/editor/common/editorCommon';
import { EndOfLineSequence, ISingleEditOperation } from 'vs/editor/common/model';
import { IModelChangedEvent } from 'vs/editor/common/model/mirrorTextModel';
import * as modes from 'vs/editor/common/modes';
import { CharacterPair, CommentRule, EnterAction } from 'vs/editor/common/modes/languageConfiguration';
import { ICommandHandlerDescription } from 'vs/platform/commands/common/commands';
import { ConfigurationTarget, IConfigurationData, IConfigurationModel } from 'vs/platform/configuration/common/configuration';
import { ConfigurationScope } from 'vs/platform/configuration/common/configurationRegistry';
import { ExtensionIdentifier, IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import * as files from 'vs/platform/files/common/files';
import { ResourceLabelFormatter } from 'vs/platform/label/common/label';
import { LogLevel } from 'vs/platform/log/common/log';
import { IMarkerData } from 'vs/platform/markers/common/markers';
import { IProgressOptions, IProgressStep } from 'vs/platform/progress/common/progress';
import * as quickInput from 'vs/platform/quickinput/common/quickInput';
import { RemoteAuthorityResolverErrorCode, ResolverResult } from 'vs/platform/remote/common/remoteAuthorityResolver';
import * as statusbar from 'vs/platform/statusbar/common/statusbar';
import { ClassifiedEvent, GDPRClassification, StrictPropertyCheck } from 'vs/platform/telemetry/common/gdprTypings';
import { ITelemetryInfo } from 'vs/platform/telemetry/common/telemetry';
import { ThemeColor } from 'vs/platform/theme/common/themeService';
import { EditorViewColumn } from 'vs/workbench/api/common/shared/editor';
import * as tasks from 'vs/workbench/api/common/shared/tasks';
import { IRevealOptions, ITreeItem } from 'vs/workbench/common/views';
import { IAdapterDescriptor, IConfig, IDebugSessionReplMode } from 'vs/workbench/contrib/debug/common/debug';
import { ITextQueryBuilderOptions } from 'vs/workbench/contrib/search/common/queryBuilder';
import { ITerminalDimensions, IShellLaunchConfig } from 'vs/workbench/contrib/terminal/common/terminal';
import { ExtensionActivationError } from 'vs/workbench/services/extensions/common/extensions';
import { createExtHostContextProxyIdentifier as createExtId, createMainContextProxyIdentifier as createMainId, IRPCProtocol } from 'vs/workbench/services/extensions/common/proxyIdentifier';
import * as search from 'vs/workbench/services/search/common/search';
import { SaveReason } from 'vs/workbench/services/textfile/common/textfiles';
import { ExtensionActivationReason } from 'vs/workbench/api/common/extHostExtensionActivator';
export interface IEnvironment {
isExtensionDevelopmentDebug: boolean;
appName: string;
appRoot?: URI;
appLanguage: string;
appUriScheme: string;
appSettingsHome?: URI;
extensionDevelopmentLocationURI?: URI[];
extensionTestsLocationURI?: URI;
globalStorageHome: URI;
userHome: URI;
webviewResourceRoot: string;
webviewCspSource: string;
}
export interface IStaticWorkspaceData {
id: string;
name: string;
configuration?: UriComponents | null;
isUntitled?: boolean | null;
}
export interface IWorkspaceData extends IStaticWorkspaceData {
folders: { uri: UriComponents, name: string, index: number }[];
}
export interface IInitData {
version: string;
commit?: string;
parentPid: number;
environment: IEnvironment;
workspace?: IStaticWorkspaceData | null;
resolvedExtensions: ExtensionIdentifier[];
hostExtensions: ExtensionIdentifier[];
extensions: IExtensionDescription[];
telemetryInfo: ITelemetryInfo;
logLevel: LogLevel;
logsLocation: URI;
autoStart: boolean;
remote: { isRemote: boolean; authority: string | undefined; };
uiKind: UIKind;
}
export interface IConfigurationInitData extends IConfigurationData {
configurationScopes: [string, ConfigurationScope | undefined][];
}
export interface IWorkspaceConfigurationChangeEventData {
changedConfiguration: IConfigurationModel;
changedConfigurationByResource: { [folder: string]: IConfigurationModel };
}
export interface IExtHostContext extends IRPCProtocol {
remoteAuthority: string;
}
export interface IMainContext extends IRPCProtocol {
}
export enum UIKind {
Desktop = 1,
Web = 2
}
// --- main thread
export interface MainThreadClipboardShape extends IDisposable {
$readText(): Promise<string>;
$writeText(value: string): Promise<void>;
}
export interface MainThreadCommandsShape extends IDisposable {
$registerCommand(id: string): void;
$unregisterCommand(id: string): void;
$executeCommand<T>(id: string, args: any[], retry: boolean): Promise<T | undefined>;
$getCommands(): Promise<string[]>;
}
export interface CommentProviderFeatures {
reactionGroup?: modes.CommentReaction[];
reactionHandler?: boolean;
}
export interface MainThreadCommentsShape extends IDisposable {
$registerCommentController(handle: number, id: string, label: string): void;
$unregisterCommentController(handle: number): void;
$updateCommentControllerFeatures(handle: number, features: CommentProviderFeatures): void;
$createCommentThread(handle: number, commentThreadHandle: number, threadId: string, resource: UriComponents, range: IRange, extensionId: ExtensionIdentifier): modes.CommentThread | undefined;
$updateCommentThread(handle: number, commentThreadHandle: number, threadId: string, resource: UriComponents, range: IRange, label: string | undefined, contextValue: string | undefined, comments: modes.Comment[], collapseState: modes.CommentThreadCollapsibleState): void;
$deleteCommentThread(handle: number, commentThreadHandle: number): void;
$onDidCommentThreadsChange(handle: number, event: modes.CommentThreadChangedEvent): void;
}
export interface MainThreadConfigurationShape extends IDisposable {
$updateConfigurationOption(target: ConfigurationTarget | null, key: string, value: any, resource: UriComponents | undefined): Promise<void>;
$removeConfigurationOption(target: ConfigurationTarget | null, key: string, resource: UriComponents | undefined): Promise<void>;
}
export interface MainThreadDiagnosticsShape extends IDisposable {
$changeMany(owner: string, entries: [UriComponents, IMarkerData[] | undefined][]): void;
$clear(owner: string): void;
}
export interface MainThreadDialogOpenOptions {
defaultUri?: UriComponents;
openLabel?: string;
canSelectFiles?: boolean;
canSelectFolders?: boolean;
canSelectMany?: boolean;
filters?: { [name: string]: string[] };
}
export interface MainThreadDialogSaveOptions {
defaultUri?: UriComponents;
saveLabel?: string;
filters?: { [name: string]: string[] };
}
export interface MainThreadDiaglogsShape extends IDisposable {
$showOpenDialog(options: MainThreadDialogOpenOptions): Promise<UriComponents[] | undefined>;
$showSaveDialog(options: MainThreadDialogSaveOptions): Promise<UriComponents | undefined>;
}
export interface MainThreadDecorationsShape extends IDisposable {
$registerDecorationProvider(handle: number, label: string): void;
$unregisterDecorationProvider(handle: number): void;
$onDidChange(handle: number, resources: UriComponents[] | null): void;
}
export interface MainThreadDocumentContentProvidersShape extends IDisposable {
$registerTextContentProvider(handle: number, scheme: string): void;
$unregisterTextContentProvider(handle: number): void;
$onVirtualDocumentChange(uri: UriComponents, value: string): void;
}
export interface MainThreadDocumentsShape extends IDisposable {
$tryCreateDocument(options?: { language?: string; content?: string; }): Promise<UriComponents>;
$tryOpenDocument(uri: UriComponents): Promise<void>;
$trySaveDocument(uri: UriComponents): Promise<boolean>;
}
export interface ITextEditorConfigurationUpdate {
tabSize?: number | 'auto';
indentSize?: number | 'tabSize';
insertSpaces?: boolean | 'auto';
cursorStyle?: TextEditorCursorStyle;
lineNumbers?: RenderLineNumbersType;
}
export interface IResolvedTextEditorConfiguration {
tabSize: number;
indentSize: number;
insertSpaces: boolean;
cursorStyle: TextEditorCursorStyle;
lineNumbers: RenderLineNumbersType;
}
export enum TextEditorRevealType {
Default = 0,
InCenter = 1,
InCenterIfOutsideViewport = 2,
AtTop = 3
}
export interface IUndoStopOptions {
undoStopBefore: boolean;
undoStopAfter: boolean;
}
export interface IApplyEditsOptions extends IUndoStopOptions {
setEndOfLine?: EndOfLineSequence;
}
export interface ITextDocumentShowOptions {
position?: EditorViewColumn;
preserveFocus?: boolean;
pinned?: boolean;
selection?: IRange;
}
export interface MainThreadTextEditorsShape extends IDisposable {
$tryShowTextDocument(resource: UriComponents, options: ITextDocumentShowOptions): Promise<string | undefined>;
$registerTextEditorDecorationType(key: string, options: editorCommon.IDecorationRenderOptions): void;
$removeTextEditorDecorationType(key: string): void;
$tryShowEditor(id: string, position: EditorViewColumn): Promise<void>;
$tryHideEditor(id: string): Promise<void>;
$trySetOptions(id: string, options: ITextEditorConfigurationUpdate): Promise<void>;
$trySetDecorations(id: string, key: string, ranges: editorCommon.IDecorationOptions[]): Promise<void>;
$trySetDecorationsFast(id: string, key: string, ranges: number[]): Promise<void>;
$tryRevealRange(id: string, range: IRange, revealType: TextEditorRevealType): Promise<void>;
$trySetSelections(id: string, selections: ISelection[]): Promise<void>;
$tryApplyEdits(id: string, modelVersionId: number, edits: ISingleEditOperation[], opts: IApplyEditsOptions): Promise<boolean>;
$tryApplyWorkspaceEdit(workspaceEditDto: IWorkspaceEditDto): Promise<boolean>;
$tryInsertSnippet(id: string, template: string, selections: readonly IRange[], opts: IUndoStopOptions): Promise<boolean>;
$getDiffInformation(id: string): Promise<editorCommon.ILineChange[]>;
}
export interface MainThreadTreeViewsShape extends IDisposable {
$registerTreeViewDataProvider(treeViewId: string, options: { showCollapseAll: boolean, canSelectMany: boolean }): void;
$refresh(treeViewId: string, itemsToRefresh?: { [treeItemHandle: string]: ITreeItem }): Promise<void>;
$reveal(treeViewId: string, treeItem: ITreeItem, parentChain: ITreeItem[], options: IRevealOptions): Promise<void>;
$setMessage(treeViewId: string, message: string): void;
$setTitle(treeViewId: string, title: string): void;
}
export interface MainThreadDownloadServiceShape extends IDisposable {
$download(uri: UriComponents, to: UriComponents): Promise<void>;
}
export interface MainThreadErrorsShape extends IDisposable {
$onUnexpectedError(err: any | SerializedError): void;
}
export interface MainThreadConsoleShape extends IDisposable {
$logExtensionHostMessage(msg: IRemoteConsoleLog): void;
}
export interface MainThreadKeytarShape extends IDisposable {
$getPassword(service: string, account: string): Promise<string | null>;
$setPassword(service: string, account: string, password: string): Promise<void>;
$deletePassword(service: string, account: string): Promise<boolean>;
$findPassword(service: string): Promise<string | null>;
$findCredentials(service: string): Promise<Array<{ account: string, password: string }>>;
}
export interface IRegExpDto {
pattern: string;
flags?: string;
}
export interface IIndentationRuleDto {
decreaseIndentPattern: IRegExpDto;
increaseIndentPattern: IRegExpDto;
indentNextLinePattern?: IRegExpDto;
unIndentedLinePattern?: IRegExpDto;
}
export interface IOnEnterRuleDto {
beforeText: IRegExpDto;
afterText?: IRegExpDto;
oneLineAboveText?: IRegExpDto;
action: EnterAction;
}
export interface ILanguageConfigurationDto {
comments?: CommentRule;
brackets?: CharacterPair[];
wordPattern?: IRegExpDto;
indentationRules?: IIndentationRuleDto;
onEnterRules?: IOnEnterRuleDto[];
__electricCharacterSupport?: {
brackets?: any;
docComment?: {
scope: string;
open: string;
lineStart: string;
close?: string;
};
};
__characterPairSupport?: {
autoClosingPairs: {
open: string;
close: string;
notIn?: string[];
}[];
};
}
export type GlobPattern = string | { base: string; pattern: string };
export interface IDocumentFilterDto {
$serialized: true;
language?: string;
scheme?: string;
pattern?: string | IRelativePattern;
exclusive?: boolean;
}
export interface ISignatureHelpProviderMetadataDto {
readonly triggerCharacters: readonly string[];
readonly retriggerCharacters: readonly string[];
}
export interface MainThreadLanguageFeaturesShape extends IDisposable {
$unregister(handle: number): void;
$registerDocumentSymbolProvider(handle: number, selector: IDocumentFilterDto[], label: string): void;
$registerCodeLensSupport(handle: number, selector: IDocumentFilterDto[], eventHandle: number | undefined): void;
$emitCodeLensEvent(eventHandle: number, event?: any): void;
$registerDefinitionSupport(handle: number, selector: IDocumentFilterDto[]): void;
$registerDeclarationSupport(handle: number, selector: IDocumentFilterDto[]): void;
$registerImplementationSupport(handle: number, selector: IDocumentFilterDto[]): void;
$registerTypeDefinitionSupport(handle: number, selector: IDocumentFilterDto[]): void;
$registerHoverProvider(handle: number, selector: IDocumentFilterDto[]): void;
$registerDocumentHighlightProvider(handle: number, selector: IDocumentFilterDto[]): void;
$registerReferenceSupport(handle: number, selector: IDocumentFilterDto[]): void;
$registerQuickFixSupport(handle: number, selector: IDocumentFilterDto[], supportedKinds?: string[]): void;
$registerDocumentFormattingSupport(handle: number, selector: IDocumentFilterDto[], extensionId: ExtensionIdentifier, displayName: string): void;
$registerRangeFormattingSupport(handle: number, selector: IDocumentFilterDto[], extensionId: ExtensionIdentifier, displayName: string): void;
$registerOnTypeFormattingSupport(handle: number, selector: IDocumentFilterDto[], autoFormatTriggerCharacters: string[], extensionId: ExtensionIdentifier): void;
$registerNavigateTypeSupport(handle: number): void;
$registerRenameSupport(handle: number, selector: IDocumentFilterDto[], supportsResolveInitialValues: boolean): void;
$registerSuggestSupport(handle: number, selector: IDocumentFilterDto[], triggerCharacters: string[], supportsResolveDetails: boolean, extensionId: ExtensionIdentifier): void;
$registerSignatureHelpProvider(handle: number, selector: IDocumentFilterDto[], metadata: ISignatureHelpProviderMetadataDto): void;
$registerDocumentLinkProvider(handle: number, selector: IDocumentFilterDto[], supportsResolve: boolean): void;
$registerDocumentColorProvider(handle: number, selector: IDocumentFilterDto[]): void;
$registerFoldingRangeProvider(handle: number, selector: IDocumentFilterDto[]): void;
$registerSelectionRangeProvider(handle: number, selector: IDocumentFilterDto[]): void;
$registerCallHierarchyProvider(handle: number, selector: IDocumentFilterDto[]): void;
$setLanguageConfiguration(handle: number, languageId: string, configuration: ILanguageConfigurationDto): void;
}
export interface MainThreadLanguagesShape extends IDisposable {
$getLanguages(): Promise<string[]>;
$changeLanguage(resource: UriComponents, languageId: string): Promise<void>;
}
export interface MainThreadMessageOptions {
extension?: IExtensionDescription;
modal?: boolean;
}
export interface MainThreadMessageServiceShape extends IDisposable {
$showMessage(severity: Severity, message: string, options: MainThreadMessageOptions, commands: { title: string; isCloseAffordance: boolean; handle: number; }[]): Promise<number | undefined>;
}
export interface MainThreadOutputServiceShape extends IDisposable {
$register(label: string, log: boolean, file?: UriComponents): Promise<string>;
$append(channelId: string, value: string): Promise<void> | undefined;
$update(channelId: string): Promise<void> | undefined;
$clear(channelId: string, till: number): Promise<void> | undefined;
$reveal(channelId: string, preserveFocus: boolean): Promise<void> | undefined;
$close(channelId: string): Promise<void> | undefined;
$dispose(channelId: string): Promise<void> | undefined;
}
export interface MainThreadProgressShape extends IDisposable {
$startProgress(handle: number, options: IProgressOptions, extension?: IExtensionDescription): void;
$progressReport(handle: number, message: IProgressStep): void;
$progressEnd(handle: number): void;
}
export interface TerminalLaunchConfig {
name?: string;
shellPath?: string;
shellArgs?: string[] | string;
cwd?: string | UriComponents;
env?: { [key: string]: string | null };
waitOnExit?: boolean;
strictEnv?: boolean;
hideFromUser?: boolean;
isExtensionTerminal?: boolean;
}
export interface MainThreadTerminalServiceShape extends IDisposable {
$createTerminal(config: TerminalLaunchConfig): Promise<{ id: number, name: string }>;
$dispose(terminalId: number): void;
$hide(terminalId: number): void;
$sendText(terminalId: number, text: string, addNewLine: boolean): void;
$show(terminalId: number, preserveFocus: boolean): void;
$startSendingDataEvents(): void;
$stopSendingDataEvents(): void;
// Process
$sendProcessTitle(terminalId: number, title: string): void;
$sendProcessData(terminalId: number, data: string): void;
$sendProcessReady(terminalId: number, pid: number, cwd: string): void;
$sendProcessExit(terminalId: number, exitCode: number): void;
$sendProcessInitialCwd(terminalId: number, cwd: string): void;
$sendProcessCwd(terminalId: number, initialCwd: string): void;
$sendOverrideDimensions(terminalId: number, dimensions: ITerminalDimensions | undefined): void;
$sendResolvedLaunchConfig(terminalId: number, shellLaunchConfig: IShellLaunchConfig): void;
}
export interface TransferQuickPickItems extends quickInput.IQuickPickItem {
handle: number;
}
export interface TransferQuickInputButton extends quickInput.IQuickInputButton {
handle: number;
}
export type TransferQuickInput = TransferQuickPick | TransferInputBox;
export interface BaseTransferQuickInput {
[key: string]: any;
id: number;
type?: 'quickPick' | 'inputBox';
enabled?: boolean;
busy?: boolean;
visible?: boolean;
}
export interface TransferQuickPick extends BaseTransferQuickInput {
type?: 'quickPick';
value?: string;
placeholder?: string;
buttons?: TransferQuickInputButton[];
items?: TransferQuickPickItems[];
activeItems?: number[];
selectedItems?: number[];
canSelectMany?: boolean;
ignoreFocusOut?: boolean;
matchOnDescription?: boolean;
matchOnDetail?: boolean;
}
export interface TransferInputBox extends BaseTransferQuickInput {
type?: 'inputBox';
value?: string;
placeholder?: string;
password?: boolean;
buttons?: TransferQuickInputButton[];
prompt?: string;
validationMessage?: string;
}
export interface IInputBoxOptions {
value?: string;
valueSelection?: [number, number];
prompt?: string;
placeHolder?: string;
password?: boolean;
ignoreFocusOut?: boolean;
}
export interface MainThreadQuickOpenShape extends IDisposable {
$show(instance: number, options: quickInput.IPickOptions<TransferQuickPickItems>, token: CancellationToken): Promise<number | number[] | undefined>;
$setItems(instance: number, items: TransferQuickPickItems[]): Promise<void>;
$setError(instance: number, error: Error): Promise<void>;
$input(options: IInputBoxOptions | undefined, validateInput: boolean, token: CancellationToken): Promise<string>;
$createOrUpdate(params: TransferQuickInput): Promise<void>;
$dispose(id: number): Promise<void>;
}
export interface MainThreadStatusBarShape extends IDisposable {
$setEntry(id: number, statusId: string, statusName: string, text: string, tooltip: string, command: string, color: string | ThemeColor, alignment: statusbar.StatusbarAlignment, priority: number | undefined): void;
$dispose(id: number): void;
}
export interface MainThreadStorageShape extends IDisposable {
$getValue<T>(shared: boolean, key: string): Promise<T | undefined>;
$setValue(shared: boolean, key: string, value: object): Promise<void>;
}
export interface MainThreadTelemetryShape extends IDisposable {
$publicLog(eventName: string, data?: any): void;
$publicLog2<E extends ClassifiedEvent<T> = never, T extends GDPRClassification<T> = never>(eventName: string, data?: StrictPropertyCheck<T, E>): void;
}
export interface MainThreadEditorInsetsShape extends IDisposable {
$createEditorInset(handle: number, id: string, uri: UriComponents, line: number, height: number, options: modes.IWebviewOptions, extensionId: ExtensionIdentifier, extensionLocation: UriComponents): Promise<void>;
$disposeEditorInset(handle: number): void;
$setHtml(handle: number, value: string): void;
$setOptions(handle: number, options: modes.IWebviewOptions): void;
$postMessage(handle: number, value: any): Promise<boolean>;
}
export interface ExtHostEditorInsetsShape {
$onDidDispose(handle: number): void;
$onDidReceiveMessage(handle: number, message: any): void;
}
export type WebviewPanelHandle = string;
export interface WebviewPanelShowOptions {
readonly viewColumn?: EditorViewColumn;
readonly preserveFocus?: boolean;
}
export interface MainThreadWebviewsShape extends IDisposable {
$createWebviewPanel(handle: WebviewPanelHandle, viewType: string, title: string, showOptions: WebviewPanelShowOptions, options: modes.IWebviewPanelOptions & modes.IWebviewOptions, extensionId: ExtensionIdentifier, extensionLocation: UriComponents): void;
$disposeWebview(handle: WebviewPanelHandle): void;
$reveal(handle: WebviewPanelHandle, showOptions: WebviewPanelShowOptions): void;
$setTitle(handle: WebviewPanelHandle, value: string): void;
$setState(handle: WebviewPanelHandle, state: modes.WebviewEditorState): void;
$setIconPath(handle: WebviewPanelHandle, value: { light: UriComponents, dark: UriComponents } | undefined): void;
$setHtml(handle: WebviewPanelHandle, value: string): void;
$setOptions(handle: WebviewPanelHandle, options: modes.IWebviewOptions): void;
$postMessage(handle: WebviewPanelHandle, value: any): Promise<boolean>;
$registerSerializer(viewType: string): void;
$unregisterSerializer(viewType: string): void;
$registerEditorProvider(viewType: string): void;
$unregisterEditorProvider(viewType: string): void;
}
export interface WebviewPanelViewStateData {
[handle: string]: {
readonly active: boolean;
readonly visible: boolean;
readonly position: EditorViewColumn;
};
}
export interface ExtHostWebviewsShape {
$onMessage(handle: WebviewPanelHandle, message: any): void;
$onMissingCsp(handle: WebviewPanelHandle, extensionId: string): void;
$onDidChangeWebviewPanelViewStates(newState: WebviewPanelViewStateData): void;
$onDidDisposeWebviewPanel(handle: WebviewPanelHandle): Promise<void>;
$deserializeWebviewPanel(newWebviewHandle: WebviewPanelHandle, viewType: string, title: string, state: any, position: EditorViewColumn, options: modes.IWebviewOptions & modes.IWebviewPanelOptions): Promise<void>;
$resolveWebviewEditor(resource: UriComponents, newWebviewHandle: WebviewPanelHandle, viewType: string, title: string, state: any, position: EditorViewColumn, options: modes.IWebviewOptions & modes.IWebviewPanelOptions): Promise<void>;
$save(handle: WebviewPanelHandle): Promise<boolean>;
}
export interface MainThreadUrlsShape extends IDisposable {
$registerUriHandler(handle: number, extensionId: ExtensionIdentifier): Promise<void>;
$unregisterUriHandler(handle: number): Promise<void>;
$createAppUri(extensionId: ExtensionIdentifier, options?: { payload?: Partial<UriComponents> }): Promise<UriComponents>;
}
export interface ExtHostUrlsShape {
$handleExternalUri(handle: number, uri: UriComponents): Promise<void>;
}
export interface ITextSearchComplete {
limitHit?: boolean;
}
export interface MainThreadWorkspaceShape extends IDisposable {
$startFileSearch(includePattern: string | null, includeFolder: UriComponents | null, excludePatternOrDisregardExcludes: string | false | null, maxResults: number | null, token: CancellationToken): Promise<UriComponents[] | null>;
$startTextSearch(query: search.IPatternInfo, options: ITextQueryBuilderOptions, requestId: number, token: CancellationToken): Promise<ITextSearchComplete>;
$checkExists(folders: UriComponents[], includes: string[], token: CancellationToken): Promise<boolean>;
$saveAll(includeUntitled?: boolean): Promise<boolean>;
$updateWorkspaceFolders(extensionName: string, index: number, deleteCount: number, workspaceFoldersToAdd: { uri: UriComponents, name?: string }[]): Promise<void>;
$resolveProxy(url: string): Promise<string | undefined>;
}
export interface IFileChangeDto {
resource: UriComponents;
type: files.FileChangeType;
}
export interface MainThreadFileSystemShape extends IDisposable {
$registerFileSystemProvider(handle: number, scheme: string, capabilities: files.FileSystemProviderCapabilities): void;
$unregisterProvider(handle: number): void;
$onFileSystemChange(handle: number, resource: IFileChangeDto[]): void;
$stat(uri: UriComponents): Promise<files.IStat>;
$readdir(resource: UriComponents): Promise<[string, files.FileType][]>;
$readFile(resource: UriComponents): Promise<VSBuffer>;
$writeFile(resource: UriComponents, content: VSBuffer): Promise<void>;
$rename(resource: UriComponents, target: UriComponents, opts: files.FileOverwriteOptions): Promise<void>;
$copy(resource: UriComponents, target: UriComponents, opts: files.FileOverwriteOptions): Promise<void>;
$mkdir(resource: UriComponents): Promise<void>;
$delete(resource: UriComponents, opts: files.FileDeleteOptions): Promise<void>;
}
export interface MainThreadLabelServiceShape extends IDisposable {
$registerResourceLabelFormatter(handle: number, formatter: ResourceLabelFormatter): void;
$unregisterResourceLabelFormatter(handle: number): void;
}
export interface MainThreadSearchShape extends IDisposable {
$registerFileSearchProvider(handle: number, scheme: string): void;
$registerTextSearchProvider(handle: number, scheme: string): void;
$unregisterProvider(handle: number): void;
$handleFileMatch(handle: number, session: number, data: UriComponents[]): void;
$handleTextMatch(handle: number, session: number, data: search.IRawFileMatch2[]): void;
$handleTelemetry(eventName: string, data: any): void;
}
export interface MainThreadTaskShape extends IDisposable {
$createTaskId(task: tasks.TaskDTO): Promise<string>;
$registerTaskProvider(handle: number, type: string): Promise<void>;
$unregisterTaskProvider(handle: number): Promise<void>;
$fetchTasks(filter?: tasks.TaskFilterDTO): Promise<tasks.TaskDTO[]>;
$executeTask(task: tasks.TaskHandleDTO | tasks.TaskDTO): Promise<tasks.TaskExecutionDTO>;
$terminateTask(id: string): Promise<void>;
$registerTaskSystem(scheme: string, info: tasks.TaskSystemInfoDTO): void;
$customExecutionComplete(id: string, result?: number): Promise<void>;
}
export interface MainThreadExtensionServiceShape extends IDisposable {
$activateExtension(extensionId: ExtensionIdentifier, reason: ExtensionActivationReason): Promise<void>;
$onWillActivateExtension(extensionId: ExtensionIdentifier): void;
$onDidActivateExtension(extensionId: ExtensionIdentifier, codeLoadingTime: number, activateCallTime: number, activateResolvedTime: number, activationReason: ExtensionActivationReason): void;
$onExtensionActivationError(extensionId: ExtensionIdentifier, error: ExtensionActivationError): Promise<void>;
$onExtensionRuntimeError(extensionId: ExtensionIdentifier, error: SerializedError): void;
$onExtensionHostExit(code: number): void;
}
export interface SCMProviderFeatures {
hasQuickDiffProvider?: boolean;
count?: number;
commitTemplate?: string;
acceptInputCommand?: modes.Command;
statusBarCommands?: ICommandDto[];
}
export interface SCMGroupFeatures {
hideWhenEmpty?: boolean;
}
export type SCMRawResource = [
number /*handle*/,
UriComponents /*resourceUri*/,
string[] /*icons: light, dark*/,
string /*tooltip*/,
boolean /*strike through*/,
boolean /*faded*/
];
export type SCMRawResourceSplice = [
number /* start */,
number /* delete count */,
SCMRawResource[]
];
export type SCMRawResourceSplices = [
number, /*handle*/
SCMRawResourceSplice[]
];
export interface MainThreadSCMShape extends IDisposable {
$registerSourceControl(handle: number, id: string, label: string, rootUri: UriComponents | undefined): void;
$updateSourceControl(handle: number, features: SCMProviderFeatures): void;
$unregisterSourceControl(handle: number): void;
$registerGroup(sourceControlHandle: number, handle: number, id: string, label: string): void;
$updateGroup(sourceControlHandle: number, handle: number, features: SCMGroupFeatures): void;
$updateGroupLabel(sourceControlHandle: number, handle: number, label: string): void;
$unregisterGroup(sourceControlHandle: number, handle: number): void;
$spliceResourceStates(sourceControlHandle: number, splices: SCMRawResourceSplices[]): void;
$setInputBoxValue(sourceControlHandle: number, value: string): void;
$setInputBoxPlaceholder(sourceControlHandle: number, placeholder: string): void;
$setInputBoxVisibility(sourceControlHandle: number, visible: boolean): void;
$setValidationProviderIsEnabled(sourceControlHandle: number, enabled: boolean): void;
}
export type DebugSessionUUID = string;
export interface IDebugConfiguration {
type: string;
name: string;
request: string;
[key: string]: any;
}
export interface IStartDebuggingOptions {
parentSessionID?: DebugSessionUUID;
repl?: IDebugSessionReplMode;
}
export interface MainThreadDebugServiceShape extends IDisposable {
$registerDebugTypes(debugTypes: string[]): void;
$sessionCached(sessionID: string): void;
$acceptDAMessage(handle: number, message: DebugProtocol.ProtocolMessage): void;
$acceptDAError(handle: number, name: string, message: string, stack: string | undefined): void;
$acceptDAExit(handle: number, code: number | undefined, signal: string | undefined): void;
$registerDebugConfigurationProvider(type: string, hasProvideMethod: boolean, hasResolveMethod: boolean, hasProvideDaMethod: boolean, handle: number): Promise<void>;
$registerDebugAdapterDescriptorFactory(type: string, handle: number): Promise<void>;
$unregisterDebugConfigurationProvider(handle: number): void;
$unregisterDebugAdapterDescriptorFactory(handle: number): void;
$startDebugging(folder: UriComponents | undefined, nameOrConfig: string | IDebugConfiguration, options: IStartDebuggingOptions): Promise<boolean>;
$setDebugSessionName(id: DebugSessionUUID, name: string): void;
$customDebugAdapterRequest(id: DebugSessionUUID, command: string, args: any): Promise<any>;
$appendDebugConsole(value: string): void;
$startBreakpointEvents(): void;
$registerBreakpoints(breakpoints: Array<ISourceMultiBreakpointDto | IFunctionBreakpointDto | IDataBreakpointDto>): Promise<void>;
$unregisterBreakpoints(breakpointIds: string[], functionBreakpointIds: string[], dataBreakpointIds: string[]): Promise<void>;
}
export interface IOpenUriOptions {
readonly allowTunneling?: boolean;
}
export interface MainThreadWindowShape extends IDisposable {
$getWindowVisibility(): Promise<boolean>;
$openUri(uri: UriComponents, options: IOpenUriOptions): Promise<boolean>;
$resolveExternalUri(uri: UriComponents, options: IOpenUriOptions): Promise<UriComponents>;
}
// -- extension host
export interface ExtHostCommandsShape {
$executeContributedCommand<T>(id: string, ...args: any[]): Promise<T>;
$getContributedCommandHandlerDescriptions(): Promise<{ [id: string]: string | ICommandHandlerDescription }>;
}
export interface ExtHostConfigurationShape {
$initializeConfiguration(data: IConfigurationInitData): void;
$acceptConfigurationChanged(data: IConfigurationInitData, eventData: IWorkspaceConfigurationChangeEventData): void;
}
export interface ExtHostDiagnosticsShape {
$acceptMarkersChange(data: [UriComponents, IMarkerData[]][]): void;
}
export interface ExtHostDocumentContentProvidersShape {
$provideTextDocumentContent(handle: number, uri: UriComponents): Promise<string | null | undefined>;
}
export interface IModelAddedData {
uri: UriComponents;
versionId: number;
lines: string[];
EOL: string;
modeId: string;
isDirty: boolean;
}
export interface ExtHostDocumentsShape {
$acceptModelModeChanged(strURL: UriComponents, oldModeId: string, newModeId: string): void;
$acceptModelSaved(strURL: UriComponents): void;
$acceptDirtyStateChanged(strURL: UriComponents, isDirty: boolean): void;
$acceptModelChanged(strURL: UriComponents, e: IModelChangedEvent, isDirty: boolean): void;
}
export interface ExtHostDocumentSaveParticipantShape {
$participateInSave(resource: UriComponents, reason: SaveReason): Promise<boolean[]>;
}
export interface ITextEditorAddData {
id: string;
documentUri: UriComponents;
options: IResolvedTextEditorConfiguration;
selections: ISelection[];
visibleRanges: IRange[];
editorPosition: EditorViewColumn | undefined;
}
export interface ITextEditorPositionData {
[id: string]: EditorViewColumn;
}
export interface IEditorPropertiesChangeData {
options: IResolvedTextEditorConfiguration | null;
selections: ISelectionChangeEvent | null;
visibleRanges: IRange[] | null;
}
export interface ISelectionChangeEvent {
selections: Selection[];
source?: string;
}
export interface ExtHostEditorsShape {
$acceptEditorPropertiesChanged(id: string, props: IEditorPropertiesChangeData): void;
$acceptEditorPositionData(data: ITextEditorPositionData): void;
}
export interface IDocumentsAndEditorsDelta {
removedDocuments?: UriComponents[];
addedDocuments?: IModelAddedData[];
removedEditors?: string[];
addedEditors?: ITextEditorAddData[];
newActiveEditor?: string | null;
}
export interface ExtHostDocumentsAndEditorsShape {
$acceptDocumentsAndEditorsDelta(delta: IDocumentsAndEditorsDelta): void;
}
export interface ExtHostTreeViewsShape {
$getChildren(treeViewId: string, treeItemHandle?: string): Promise<ITreeItem[]>;
$setExpanded(treeViewId: string, treeItemHandle: string, expanded: boolean): void;
$setSelection(treeViewId: string, treeItemHandles: string[]): void;
$setVisible(treeViewId: string, visible: boolean): void;
}
export interface ExtHostWorkspaceShape {
$initializeWorkspace(workspace: IWorkspaceData | null): void;
$acceptWorkspaceData(workspace: IWorkspaceData | null): void;
$handleTextSearchResult(result: search.IRawFileMatch2, requestId: number): void;
}
export interface ExtHostFileSystemShape {
$stat(handle: number, resource: UriComponents): Promise<files.IStat>;
$readdir(handle: number, resource: UriComponents): Promise<[string, files.FileType][]>;
$readFile(handle: number, resource: UriComponents): Promise<VSBuffer>;
$writeFile(handle: number, resource: UriComponents, content: VSBuffer, opts: files.FileWriteOptions): Promise<void>;
$rename(handle: number, resource: UriComponents, target: UriComponents, opts: files.FileOverwriteOptions): Promise<void>;
$copy(handle: number, resource: UriComponents, target: UriComponents, opts: files.FileOverwriteOptions): Promise<void>;
$mkdir(handle: number, resource: UriComponents): Promise<void>;
$delete(handle: number, resource: UriComponents, opts: files.FileDeleteOptions): Promise<void>;
$watch(handle: number, session: number, resource: UriComponents, opts: files.IWatchOptions): void;
$unwatch(handle: number, session: number): void;
$open(handle: number, resource: UriComponents, opts: files.FileOpenOptions): Promise<number>;
$close(handle: number, fd: number): Promise<void>;
$read(handle: number, fd: number, pos: number, length: number): Promise<VSBuffer>;
$write(handle: number, fd: number, pos: number, data: VSBuffer): Promise<number>;
}
export interface ExtHostLabelServiceShape {
$registerResourceLabelFormatter(formatter: ResourceLabelFormatter): IDisposable;
}
export interface ExtHostSearchShape {
$provideFileSearchResults(handle: number, session: number, query: search.IRawQuery, token: CancellationToken): Promise<search.ISearchCompleteStats>;
$provideTextSearchResults(handle: number, session: number, query: search.IRawTextQuery, token: CancellationToken): Promise<search.ISearchCompleteStats>;
$clearCache(cacheKey: string): Promise<void>;
}
export interface IResolveAuthorityErrorResult {
type: 'error';
error: {
message: string | undefined;
code: RemoteAuthorityResolverErrorCode;
detail: any;
};
}
export interface IResolveAuthorityOKResult {
type: 'ok';
value: ResolverResult;
}
export type IResolveAuthorityResult = IResolveAuthorityErrorResult | IResolveAuthorityOKResult;
export interface ExtHostExtensionServiceShape {
$resolveAuthority(remoteAuthority: string, resolveAttempt: number): Promise<IResolveAuthorityResult>;
$startExtensionHost(enabledExtensionIds: ExtensionIdentifier[]): Promise<void>;
$activateByEvent(activationEvent: string): Promise<void>;
$activate(extensionId: ExtensionIdentifier, reason: ExtensionActivationReason): Promise<boolean>;
$setRemoteEnvironment(env: { [key: string]: string | null }): Promise<void>;
$deltaExtensions(toAdd: IExtensionDescription[], toRemove: ExtensionIdentifier[]): Promise<void>;
$test_latency(n: number): Promise<number>;
$test_up(b: VSBuffer): Promise<number>;
$test_down(size: number): Promise<VSBuffer>;
}
export interface FileSystemEvents {
created: UriComponents[];
changed: UriComponents[];
deleted: UriComponents[];
}
export interface ExtHostFileSystemEventServiceShape {
$onFileEvent(events: FileSystemEvents): void;
$onFileRename(oldUri: UriComponents, newUri: UriComponents): void;
$onWillRename(oldUri: UriComponents, newUri: UriComponents): Promise<any>;
}
export interface ObjectIdentifier {
$ident?: number;
}
export namespace ObjectIdentifier {
export const name = '$ident';
export function mixin<T>(obj: T, id: number): T & ObjectIdentifier {
Object.defineProperty(obj, name, { value: id, enumerable: true });
return <T & ObjectIdentifier>obj;
}
export function of(obj: any): number {
return obj[name];
}
}
export interface ExtHostHeapServiceShape {
$onGarbageCollection(ids: number[]): void;
}
export interface IRawColorInfo {
color: [number, number, number, number];
range: IRange;
}
export class IdObject {
_id?: number;
private static _n = 0;
static mixin<T extends object>(object: T): T & IdObject {
(<any>object)._id = IdObject._n++;
return <any>object;
}
}
export interface ISuggestDataDto {
a/* label */: string;
b/* kind */: modes.CompletionItemKind;
c/* detail */?: string;
d/* documentation */?: string | IMarkdownString;
e/* sortText */?: string;
f/* filterText */?: string;
g/* preselect */?: boolean;
h/* insertText */?: string;
i/* insertTextRules */?: modes.CompletionItemInsertTextRule;
j/* range */?: IRange;
k/* commitCharacters */?: string[];
l/* additionalTextEdits */?: ISingleEditOperation[];
m/* command */?: modes.Command;
n/* kindModifier */?: modes.CompletionItemTag[];
// not-standard
x?: ChainedCacheId;
}
export interface ISuggestResultDto {
x?: number;
a: IRange;
b: ISuggestDataDto[];
c?: boolean;
}
export interface ISignatureHelpDto {
id: CacheId;
signatures: modes.SignatureInformation[];
activeSignature: number;
activeParameter: number;
}
export interface ISignatureHelpContextDto {
readonly triggerKind: modes.SignatureHelpTriggerKind;
readonly triggerCharacter?: string;
readonly isRetrigger: boolean;
readonly activeSignatureHelp?: ISignatureHelpDto;
}
export interface ILocationDto {
uri: UriComponents;
range: IRange;
}
export interface IDefinitionLinkDto {
originSelectionRange?: IRange;
uri: UriComponents;
range: IRange;
targetSelectionRange?: IRange;
}
export interface IWorkspaceSymbolDto extends IdObject {
name: string;
containerName?: string;
kind: modes.SymbolKind;
location: ILocationDto;
}
export interface IWorkspaceSymbolsDto extends IdObject {
symbols: IWorkspaceSymbolDto[];
}
export interface IResourceFileEditDto {
oldUri?: UriComponents;
newUri?: UriComponents;
options?: {
overwrite?: boolean;
ignoreIfExists?: boolean;
ignoreIfNotExists?: boolean;
recursive?: boolean;
};
}
export interface IResourceTextEditDto {
resource: UriComponents;
modelVersionId?: number;
edits: modes.TextEdit[];
}
export interface IWorkspaceEditDto {
edits: Array<IResourceFileEditDto | IResourceTextEditDto>;
// todo@joh reject should go into rename
rejectReason?: string;
}
export function reviveWorkspaceEditDto(data: IWorkspaceEditDto | undefined): modes.WorkspaceEdit {
if (data && data.edits) {
for (const edit of data.edits) {
if (typeof (<IResourceTextEditDto>edit).resource === 'object') {
(<IResourceTextEditDto>edit).resource = URI.revive((<IResourceTextEditDto>edit).resource);
} else {
(<IResourceFileEditDto>edit).newUri = URI.revive((<IResourceFileEditDto>edit).newUri);
(<IResourceFileEditDto>edit).oldUri = URI.revive((<IResourceFileEditDto>edit).oldUri);
}
}
}
return <modes.WorkspaceEdit>data;
}
export type ICommandDto = ObjectIdentifier & modes.Command;
export interface ICodeActionDto {
title: string;
edit?: IWorkspaceEditDto;
diagnostics?: IMarkerData[];
command?: ICommandDto;
kind?: string;
isPreferred?: boolean;
}
export interface ICodeActionListDto {
cacheId: number;
actions: ReadonlyArray<ICodeActionDto>;
}
export type CacheId = number;
export type ChainedCacheId = [CacheId, CacheId];
export interface ILinksListDto {
id?: CacheId;
links: ILinkDto[];
}
export interface ILinkDto {
cacheId?: ChainedCacheId;
range: IRange;
url?: string | UriComponents;
tooltip?: string;
}
export interface ICodeLensListDto {
cacheId?: number;
lenses: ICodeLensDto[];
}
export interface ICodeLensDto {
cacheId?: ChainedCacheId;
range: IRange;
command?: ICommandDto;
}
export interface ICallHierarchyItemDto {
kind: modes.SymbolKind;
name: string;
detail?: string;
uri: UriComponents;
range: IRange;
selectionRange: IRange;
}
export interface ExtHostLanguageFeaturesShape {
$provideDocumentSymbols(handle: number, resource: UriComponents, token: CancellationToken): Promise<modes.DocumentSymbol[] | undefined>;
$provideCodeLenses(handle: number, resource: UriComponents, token: CancellationToken): Promise<ICodeLensListDto | undefined>;
$resolveCodeLens(handle: number, symbol: ICodeLensDto, token: CancellationToken): Promise<ICodeLensDto | undefined>;
$releaseCodeLenses(handle: number, id: number): void;
$provideDefinition(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<IDefinitionLinkDto[]>;
$provideDeclaration(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<IDefinitionLinkDto[]>;
$provideImplementation(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<IDefinitionLinkDto[]>;
$provideTypeDefinition(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<IDefinitionLinkDto[]>;
$provideHover(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.Hover | undefined>;
$provideDocumentHighlights(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DocumentHighlight[] | undefined>;
$provideReferences(handle: number, resource: UriComponents, position: IPosition, context: modes.ReferenceContext, token: CancellationToken): Promise<ILocationDto[] | undefined>;
$provideCodeActions(handle: number, resource: UriComponents, rangeOrSelection: IRange | ISelection, context: modes.CodeActionContext, token: CancellationToken): Promise<ICodeActionListDto | undefined>;
$releaseCodeActions(handle: number, cacheId: number): void;
$provideDocumentFormattingEdits(handle: number, resource: UriComponents, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[] | undefined>;
$provideDocumentRangeFormattingEdits(handle: number, resource: UriComponents, range: IRange, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[] | undefined>;
$provideOnTypeFormattingEdits(handle: number, resource: UriComponents, position: IPosition, ch: string, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[] | undefined>;
$provideWorkspaceSymbols(handle: number, search: string, token: CancellationToken): Promise<IWorkspaceSymbolsDto>;
$resolveWorkspaceSymbol(handle: number, symbol: IWorkspaceSymbolDto, token: CancellationToken): Promise<IWorkspaceSymbolDto | undefined>;
$releaseWorkspaceSymbols(handle: number, id: number): void;
$provideRenameEdits(handle: number, resource: UriComponents, position: IPosition, newName: string, token: CancellationToken): Promise<IWorkspaceEditDto | undefined>;
$resolveRenameLocation(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.RenameLocation | undefined>;
$provideCompletionItems(handle: number, resource: UriComponents, position: IPosition, context: modes.CompletionContext, token: CancellationToken): Promise<ISuggestResultDto | undefined>;
$resolveCompletionItem(handle: number, resource: UriComponents, position: IPosition, id: ChainedCacheId, token: CancellationToken): Promise<ISuggestDataDto | undefined>;
$releaseCompletionItems(handle: number, id: number): void;
$provideSignatureHelp(handle: number, resource: UriComponents, position: IPosition, context: modes.SignatureHelpContext, token: CancellationToken): Promise<ISignatureHelpDto | undefined>;
$releaseSignatureHelp(handle: number, id: number): void;
$provideDocumentLinks(handle: number, resource: UriComponents, token: CancellationToken): Promise<ILinksListDto | undefined>;
$resolveDocumentLink(handle: number, id: ChainedCacheId, token: CancellationToken): Promise<ILinkDto | undefined>;
$releaseDocumentLinks(handle: number, id: number): void;
$provideDocumentColors(handle: number, resource: UriComponents, token: CancellationToken): Promise<IRawColorInfo[]>;
$provideColorPresentations(handle: number, resource: UriComponents, colorInfo: IRawColorInfo, token: CancellationToken): Promise<modes.IColorPresentation[] | undefined>;
$provideFoldingRanges(handle: number, resource: UriComponents, context: modes.FoldingContext, token: CancellationToken): Promise<modes.FoldingRange[] | undefined>;
$provideSelectionRanges(handle: number, resource: UriComponents, positions: IPosition[], token: CancellationToken): Promise<modes.SelectionRange[][]>;
$provideCallHierarchyIncomingCalls(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<[ICallHierarchyItemDto, IRange[]][] | undefined>;
$provideCallHierarchyOutgoingCalls(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<[ICallHierarchyItemDto, IRange[]][] | undefined>;
}
export interface ExtHostQuickOpenShape {
$onItemSelected(handle: number): void;
$validateInput(input: string): Promise<string | null | undefined>;
$onDidChangeActive(sessionId: number, handles: number[]): void;
$onDidChangeSelection(sessionId: number, handles: number[]): void;
$onDidAccept(sessionId: number): void;
$onDidChangeValue(sessionId: number, value: string): void;
$onDidTriggerButton(sessionId: number, handle: number): void;
$onDidHide(sessionId: number): void;
}
export interface IShellLaunchConfigDto {
name?: string;
executable?: string;
args?: string[] | string;
cwd?: string | UriComponents;
env?: { [key: string]: string | null };
}
export interface IShellDefinitionDto {
label: string;
path: string;
}
export interface IShellAndArgsDto {
shell: string;
args: string[] | string | undefined;
}
export interface ITerminalDimensionsDto {
columns: number;
rows: number;
}
export interface ExtHostTerminalServiceShape {
$acceptTerminalClosed(id: number): void;
$acceptTerminalOpened(id: number, name: string): void;
$acceptActiveTerminalChanged(id: number | null): void;
$acceptTerminalProcessId(id: number, processId: number): void;
$acceptTerminalProcessData(id: number, data: string): void;
$acceptTerminalTitleChange(id: number, name: string): void;
$acceptTerminalDimensions(id: number, cols: number, rows: number): void;
$acceptTerminalMaximumDimensions(id: number, cols: number, rows: number): void;
$spawnExtHostProcess(id: number, shellLaunchConfig: IShellLaunchConfigDto, activeWorkspaceRootUri: UriComponents, cols: number, rows: number, isWorkspaceShellAllowed: boolean): void;
$startExtensionTerminal(id: number, initialDimensions: ITerminalDimensionsDto | undefined): void;
$acceptProcessInput(id: number, data: string): void;
$acceptProcessResize(id: number, cols: number, rows: number): void;
$acceptProcessShutdown(id: number, immediate: boolean): void;
$acceptProcessRequestInitialCwd(id: number): void;
$acceptProcessRequestCwd(id: number): void;
$acceptProcessRequestLatency(id: number): number;
$acceptWorkspacePermissionsChanged(isAllowed: boolean): void;
$requestAvailableShells(): Promise<IShellDefinitionDto[]>;
$requestDefaultShellAndArgs(useAutomationShell: boolean): Promise<IShellAndArgsDto>;
}
export interface ExtHostSCMShape {
$provideOriginalResource(sourceControlHandle: number, uri: UriComponents, token: CancellationToken): Promise<UriComponents | null>;
$onInputBoxValueChange(sourceControlHandle: number, value: string): void;
$executeResourceCommand(sourceControlHandle: number, groupHandle: number, handle: number): Promise<void>;
$validateInput(sourceControlHandle: number, value: string, cursorPosition: number): Promise<[string, number] | undefined>;
$setSelectedSourceControls(selectedSourceControlHandles: number[]): Promise<void>;
}
export interface ExtHostTaskShape {
$provideTasks(handle: number, validTypes: { [key: string]: boolean; }): Thenable<tasks.TaskSetDTO>;
$resolveTask(handle: number, taskDTO: tasks.TaskDTO): Thenable<tasks.TaskDTO | undefined>;
$onDidStartTask(execution: tasks.TaskExecutionDTO, terminalId: number): void;
$onDidStartTaskProcess(value: tasks.TaskProcessStartedDTO): void;
$onDidEndTaskProcess(value: tasks.TaskProcessEndedDTO): void;
$OnDidEndTask(execution: tasks.TaskExecutionDTO): void;
$resolveVariables(workspaceFolder: UriComponents, toResolve: { process?: { name: string; cwd?: string }, variables: string[] }): Promise<{ process?: string; variables: { [key: string]: string } }>;
$getDefaultShellAndArgs(): Thenable<{ shell: string, args: string[] | string | undefined }>;
$jsonTasksSupported(): Thenable<boolean>;
}
export interface IBreakpointDto {
type: string;
id?: string;
enabled: boolean;
condition?: string;
hitCondition?: string;
logMessage?: string;
}
export interface IFunctionBreakpointDto extends IBreakpointDto {
type: 'function';
functionName: string;
}
export interface IDataBreakpointDto extends IBreakpointDto {
type: 'data';
dataId: string;
canPersist: boolean;
label: string;
}
export interface ISourceBreakpointDto extends IBreakpointDto {
type: 'source';
uri: UriComponents;
line: number;
character: number;
}
export interface IBreakpointsDeltaDto {
added?: Array<ISourceBreakpointDto | IFunctionBreakpointDto | IDataBreakpointDto>;
removed?: string[];
changed?: Array<ISourceBreakpointDto | IFunctionBreakpointDto | IDataBreakpointDto>;
}
export interface ISourceMultiBreakpointDto {
type: 'sourceMulti';
uri: UriComponents;
lines: {
id: string;
enabled: boolean;
condition?: string;
hitCondition?: string;
logMessage?: string;
line: number;
character: number;
}[];
}
export interface IDebugSessionFullDto {
id: DebugSessionUUID;
type: string;
name: string;
folderUri: UriComponents | undefined;
configuration: IConfig;
}
export type IDebugSessionDto = IDebugSessionFullDto | DebugSessionUUID;
export interface ExtHostDebugServiceShape {
$substituteVariables(folder: UriComponents | undefined, config: IConfig): Promise<IConfig>;
$runInTerminal(args: DebugProtocol.RunInTerminalRequestArguments): Promise<number | undefined>;
$startDASession(handle: number, session: IDebugSessionDto): Promise<void>;
$stopDASession(handle: number): Promise<void>;
$sendDAMessage(handle: number, message: DebugProtocol.ProtocolMessage): void;
$resolveDebugConfiguration(handle: number, folder: UriComponents | undefined, debugConfiguration: IConfig, token: CancellationToken): Promise<IConfig | null | undefined>;
$provideDebugConfigurations(handle: number, folder: UriComponents | undefined, token: CancellationToken): Promise<IConfig[]>;
$legacyDebugAdapterExecutable(handle: number, folderUri: UriComponents | undefined): Promise<IAdapterDescriptor>; // TODO@AW legacy
$provideDebugAdapter(handle: number, session: IDebugSessionDto): Promise<IAdapterDescriptor>;
$acceptDebugSessionStarted(session: IDebugSessionDto): void;
$acceptDebugSessionTerminated(session: IDebugSessionDto): void;
$acceptDebugSessionActiveChanged(session: IDebugSessionDto | undefined): void;
$acceptDebugSessionCustomEvent(session: IDebugSessionDto, event: any): void;
$acceptBreakpointsDelta(delta: IBreakpointsDeltaDto): void;
$acceptDebugSessionNameChanged(session: IDebugSessionDto, name: string): void;
}
export interface DecorationRequest {
readonly id: number;
readonly handle: number;
readonly uri: UriComponents;
}
export type DecorationData = [number, boolean, string, string, ThemeColor];
export type DecorationReply = { [id: number]: DecorationData };
export interface ExtHostDecorationsShape {
$provideDecorations(requests: DecorationRequest[], token: CancellationToken): Promise<DecorationReply>;
}
export interface ExtHostWindowShape {
$onDidChangeWindowFocus(value: boolean): void;
}
export interface ExtHostLogServiceShape {
$setLevel(level: LogLevel): void;
}
export interface MainThreadLogShape {
$log(file: UriComponents, level: LogLevel, args: any[]): void;
}
export interface ExtHostOutputServiceShape {
$setVisibleChannel(channelId: string | null): void;
}
export interface ExtHostProgressShape {
$acceptProgressCanceled(handle: number): void;
}
export interface ExtHostCommentsShape {
$createCommentThreadTemplate(commentControllerHandle: number, uriComponents: UriComponents, range: IRange): void;
$updateCommentThreadTemplate(commentControllerHandle: number, threadHandle: number, range: IRange): Promise<void>;
$deleteCommentThread(commentControllerHandle: number, commentThreadHandle: number): void;
$provideCommentingRanges(commentControllerHandle: number, uriComponents: UriComponents, token: CancellationToken): Promise<IRange[] | undefined>;
$toggleReaction(commentControllerHandle: number, threadHandle: number, uri: UriComponents, comment: modes.Comment, reaction: modes.CommentReaction): Promise<void>;
}
export interface ExtHostStorageShape {
$acceptValue(shared: boolean, key: string, value: object | undefined): void;
}
// --- proxy identifiers
export const MainContext = {
MainThreadClipboard: createMainId<MainThreadClipboardShape>('MainThreadClipboard'),
MainThreadCommands: createMainId<MainThreadCommandsShape>('MainThreadCommands'),
MainThreadComments: createMainId<MainThreadCommentsShape>('MainThreadComments'),
MainThreadConfiguration: createMainId<MainThreadConfigurationShape>('MainThreadConfiguration'),
MainThreadConsole: createMainId<MainThreadConsoleShape>('MainThreadConsole'),
MainThreadDebugService: createMainId<MainThreadDebugServiceShape>('MainThreadDebugService'),
MainThreadDecorations: createMainId<MainThreadDecorationsShape>('MainThreadDecorations'),
MainThreadDiagnostics: createMainId<MainThreadDiagnosticsShape>('MainThreadDiagnostics'),
MainThreadDialogs: createMainId<MainThreadDiaglogsShape>('MainThreadDiaglogs'),
MainThreadDocuments: createMainId<MainThreadDocumentsShape>('MainThreadDocuments'),
MainThreadDocumentContentProviders: createMainId<MainThreadDocumentContentProvidersShape>('MainThreadDocumentContentProviders'),
MainThreadTextEditors: createMainId<MainThreadTextEditorsShape>('MainThreadTextEditors'),
MainThreadEditorInsets: createMainId<MainThreadEditorInsetsShape>('MainThreadEditorInsets'),
MainThreadErrors: createMainId<MainThreadErrorsShape>('MainThreadErrors'),
MainThreadTreeViews: createMainId<MainThreadTreeViewsShape>('MainThreadTreeViews'),
MainThreadDownloadService: createMainId<MainThreadDownloadServiceShape>('MainThreadDownloadService'),
MainThreadKeytar: createMainId<MainThreadKeytarShape>('MainThreadKeytar'),
MainThreadLanguageFeatures: createMainId<MainThreadLanguageFeaturesShape>('MainThreadLanguageFeatures'),
MainThreadLanguages: createMainId<MainThreadLanguagesShape>('MainThreadLanguages'),
MainThreadLog: createMainId<MainThreadLogShape>('MainThread'),
MainThreadMessageService: createMainId<MainThreadMessageServiceShape>('MainThreadMessageService'),
MainThreadOutputService: createMainId<MainThreadOutputServiceShape>('MainThreadOutputService'),
MainThreadProgress: createMainId<MainThreadProgressShape>('MainThreadProgress'),
MainThreadQuickOpen: createMainId<MainThreadQuickOpenShape>('MainThreadQuickOpen'),
MainThreadStatusBar: createMainId<MainThreadStatusBarShape>('MainThreadStatusBar'),
MainThreadStorage: createMainId<MainThreadStorageShape>('MainThreadStorage'),
MainThreadTelemetry: createMainId<MainThreadTelemetryShape>('MainThreadTelemetry'),
MainThreadTerminalService: createMainId<MainThreadTerminalServiceShape>('MainThreadTerminalService'),
MainThreadWebviews: createMainId<MainThreadWebviewsShape>('MainThreadWebviews'),
MainThreadUrls: createMainId<MainThreadUrlsShape>('MainThreadUrls'),
MainThreadWorkspace: createMainId<MainThreadWorkspaceShape>('MainThreadWorkspace'),
MainThreadFileSystem: createMainId<MainThreadFileSystemShape>('MainThreadFileSystem'),
MainThreadExtensionService: createMainId<MainThreadExtensionServiceShape>('MainThreadExtensionService'),
MainThreadSCM: createMainId<MainThreadSCMShape>('MainThreadSCM'),
MainThreadSearch: createMainId<MainThreadSearchShape>('MainThreadSearch'),
MainThreadTask: createMainId<MainThreadTaskShape>('MainThreadTask'),
MainThreadWindow: createMainId<MainThreadWindowShape>('MainThreadWindow'),
MainThreadLabelService: createMainId<MainThreadLabelServiceShape>('MainThreadLabelService')
};
export const ExtHostContext = {
ExtHostCommands: createExtId<ExtHostCommandsShape>('ExtHostCommands'),
ExtHostConfiguration: createExtId<ExtHostConfigurationShape>('ExtHostConfiguration'),
ExtHostDiagnostics: createExtId<ExtHostDiagnosticsShape>('ExtHostDiagnostics'),
ExtHostDebugService: createExtId<ExtHostDebugServiceShape>('ExtHostDebugService'),
ExtHostDecorations: createExtId<ExtHostDecorationsShape>('ExtHostDecorations'),
ExtHostDocumentsAndEditors: createExtId<ExtHostDocumentsAndEditorsShape>('ExtHostDocumentsAndEditors'),
ExtHostDocuments: createExtId<ExtHostDocumentsShape>('ExtHostDocuments'),
ExtHostDocumentContentProviders: createExtId<ExtHostDocumentContentProvidersShape>('ExtHostDocumentContentProviders'),
ExtHostDocumentSaveParticipant: createExtId<ExtHostDocumentSaveParticipantShape>('ExtHostDocumentSaveParticipant'),
ExtHostEditors: createExtId<ExtHostEditorsShape>('ExtHostEditors'),
ExtHostTreeViews: createExtId<ExtHostTreeViewsShape>('ExtHostTreeViews'),
ExtHostFileSystem: createExtId<ExtHostFileSystemShape>('ExtHostFileSystem'),
ExtHostFileSystemEventService: createExtId<ExtHostFileSystemEventServiceShape>('ExtHostFileSystemEventService'),
ExtHostLanguageFeatures: createExtId<ExtHostLanguageFeaturesShape>('ExtHostLanguageFeatures'),
ExtHostQuickOpen: createExtId<ExtHostQuickOpenShape>('ExtHostQuickOpen'),
ExtHostExtensionService: createExtId<ExtHostExtensionServiceShape>('ExtHostExtensionService'),
ExtHostLogService: createExtId<ExtHostLogServiceShape>('ExtHostLogService'),
ExtHostTerminalService: createExtId<ExtHostTerminalServiceShape>('ExtHostTerminalService'),
ExtHostSCM: createExtId<ExtHostSCMShape>('ExtHostSCM'),
ExtHostSearch: createExtId<ExtHostSearchShape>('ExtHostSearch'),
ExtHostTask: createExtId<ExtHostTaskShape>('ExtHostTask'),
ExtHostWorkspace: createExtId<ExtHostWorkspaceShape>('ExtHostWorkspace'),
ExtHostWindow: createExtId<ExtHostWindowShape>('ExtHostWindow'),
ExtHostWebviews: createExtId<ExtHostWebviewsShape>('ExtHostWebviews'),
ExtHostEditorInsets: createExtId<ExtHostEditorInsetsShape>('ExtHostEditorInsets'),
ExtHostProgress: createMainId<ExtHostProgressShape>('ExtHostProgress'),
ExtHostComments: createMainId<ExtHostCommentsShape>('ExtHostComments'),
ExtHostStorage: createMainId<ExtHostStorageShape>('ExtHostStorage'),
ExtHostUrls: createExtId<ExtHostUrlsShape>('ExtHostUrls'),
ExtHostOutputService: createMainId<ExtHostOutputServiceShape>('ExtHostOutputService'),
ExtHosLabelService: createMainId<ExtHostLabelServiceShape>('ExtHostLabelService')
};
| src/vs/workbench/api/common/extHost.protocol.ts | 0 | https://github.com/microsoft/vscode/commit/23f2275c23aeebf5e22f3d19a20528c8ba48c570 | [
0.002460838295519352,
0.00020604088786058128,
0.00016348528151866049,
0.00017223850591108203,
0.00020507408771663904
] |
{
"id": 5,
"code_window": [
"\t\tsuper(mainProcessService.getChannel(ExtensionHostDebugBroadcastChannel.ChannelName));\n",
"\t}\n",
"\n",
"\topenExtensionDevelopmentHostWindow(args: ParsedArgs, env: IProcessEnvironment): Promise<void> {\n",
"\t\t// TODO@Isidor use debug IPC channel\n",
"\t\treturn this.windowsService.openExtensionDevelopmentHostWindow(args, env);\n",
"\t}\n",
"}\n",
"\n",
"registerSingleton(IExtensionHostDebugService, ExtensionHostDebugService, true);"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn (this.windowsService as WindowsService).openExtensionDevelopmentHostWindow(args, env);\n"
],
"file_path": "src/vs/workbench/contrib/debug/electron-browser/extensionHostDebugService.ts",
"type": "replace",
"edit_start_line_idx": 24
} | <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M2.5 2H4V2.24001L4 14L2.5 14L2.5 2ZM6 2.18094V14L15 8.06218L6 2.18094ZM12.3148 8.06218L7.50024 5L7.50024 11.1809L12.3148 8.06218Z" fill="#75BEFF"/>
</svg>
| src/vs/workbench/contrib/debug/browser/media/continue-light.svg | 0 | https://github.com/microsoft/vscode/commit/23f2275c23aeebf5e22f3d19a20528c8ba48c570 | [
0.0001748960348777473,
0.0001748960348777473,
0.0001748960348777473,
0.0001748960348777473,
0
] |
{
"id": 6,
"code_window": [
"import { IWindowsService, IWindowService, IEnterWorkspaceResult, MenuBarVisibility, IURIToOpen, IOpenSettings, IWindowConfiguration } from 'vs/platform/windows/common/windows';\n",
"import { TestWorkspace } from 'vs/platform/workspace/test/common/testWorkspace';\n",
"import { createTextBufferFactoryFromStream } from 'vs/editor/common/model/textModel';\n",
"import { IEnvironmentService, ParsedArgs } from 'vs/platform/environment/common/environment';\n",
"import { IThemeService } from 'vs/platform/theme/common/themeService';\n",
"import { TestThemeService } from 'vs/platform/theme/test/common/testThemeService';\n",
"import { IWorkspaceIdentifier, ISingleFolderWorkspaceIdentifier, isSingleFolderWorkspaceIdentifier } from 'vs/platform/workspaces/common/workspaces';\n",
"import { IRecentlyOpened, IRecent } from 'vs/platform/history/common/history';\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { IEnvironmentService } from 'vs/platform/environment/common/environment';\n"
],
"file_path": "src/vs/workbench/test/workbenchTestServices.ts",
"type": "replace",
"edit_start_line_idx": 40
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Event } from 'vs/base/common/event';
import { IServerChannel } from 'vs/base/parts/ipc/common/ipc';
import { IWindowsService, IURIToOpen, IOpenSettings, isWorkspaceToOpen, isFolderToOpen } from 'vs/platform/windows/common/windows';
import { reviveWorkspaceIdentifier } from 'vs/platform/workspaces/common/workspaces';
import { URI } from 'vs/base/common/uri';
import { IRecent, isRecentFile, isRecentFolder } from 'vs/platform/history/common/history';
export class WindowsChannel implements IServerChannel {
private readonly onWindowOpen: Event<number>;
private readonly onWindowFocus: Event<number>;
private readonly onWindowBlur: Event<number>;
private readonly onWindowMaximize: Event<number>;
private readonly onWindowUnmaximize: Event<number>;
private readonly onRecentlyOpenedChange: Event<void>;
constructor(private readonly service: IWindowsService) {
this.onWindowOpen = Event.buffer(service.onWindowOpen, true);
this.onWindowFocus = Event.buffer(service.onWindowFocus, true);
this.onWindowBlur = Event.buffer(service.onWindowBlur, true);
this.onWindowMaximize = Event.buffer(service.onWindowMaximize, true);
this.onWindowUnmaximize = Event.buffer(service.onWindowUnmaximize, true);
this.onRecentlyOpenedChange = Event.buffer(service.onRecentlyOpenedChange, true);
}
listen(_: unknown, event: string): Event<any> {
switch (event) {
case 'onWindowOpen': return this.onWindowOpen;
case 'onWindowFocus': return this.onWindowFocus;
case 'onWindowBlur': return this.onWindowBlur;
case 'onWindowMaximize': return this.onWindowMaximize;
case 'onWindowUnmaximize': return this.onWindowUnmaximize;
case 'onRecentlyOpenedChange': return this.onRecentlyOpenedChange;
}
throw new Error(`Event not found: ${event}`);
}
call(_: unknown, command: string, arg?: any): Promise<any> {
switch (command) {
case 'enterWorkspace': return this.service.enterWorkspace(arg[0], URI.revive(arg[1]));
case 'addRecentlyOpened': return this.service.addRecentlyOpened(arg.map((recent: IRecent) => {
if (isRecentFile(recent)) {
recent.fileUri = URI.revive(recent.fileUri);
} else if (isRecentFolder(recent)) {
recent.folderUri = URI.revive(recent.folderUri);
} else {
recent.workspace = reviveWorkspaceIdentifier(recent.workspace);
}
return recent;
}));
case 'removeFromRecentlyOpened': return this.service.removeFromRecentlyOpened(arg.map(URI.revive));
case 'clearRecentlyOpened': return this.service.clearRecentlyOpened();
case 'getRecentlyOpened': return this.service.getRecentlyOpened(arg);
case 'focusWindow': return this.service.focusWindow(arg);
case 'closeWindow': return this.service.closeWindow(arg);
case 'isFocused': return this.service.isFocused(arg);
case 'isMaximized': return this.service.isMaximized(arg);
case 'maximizeWindow': return this.service.maximizeWindow(arg);
case 'unmaximizeWindow': return this.service.unmaximizeWindow(arg);
case 'minimizeWindow': return this.service.minimizeWindow(arg);
case 'openWindow': {
const urisToOpen: IURIToOpen[] = arg[1];
const options: IOpenSettings = arg[2];
urisToOpen.forEach(r => {
if (isWorkspaceToOpen(r)) {
r.workspaceUri = URI.revive(r.workspaceUri);
} else if (isFolderToOpen(r)) {
r.folderUri = URI.revive(r.folderUri);
} else {
r.fileUri = URI.revive(r.fileUri);
}
});
options.waitMarkerFileURI = options.waitMarkerFileURI && URI.revive(options.waitMarkerFileURI);
return this.service.openWindow(arg[0], urisToOpen, options);
}
case 'openExtensionDevelopmentHostWindow': return this.service.openExtensionDevelopmentHostWindow(arg[0], arg[1]);
case 'getWindows': return this.service.getWindows();
case 'getActiveWindowId': return this.service.getActiveWindowId();
}
throw new Error(`Call not found: ${command}`);
}
}
| src/vs/platform/windows/common/windowsIpc.ts | 1 | https://github.com/microsoft/vscode/commit/23f2275c23aeebf5e22f3d19a20528c8ba48c570 | [
0.006869835779070854,
0.0014190442161634564,
0.0001666875759838149,
0.0005344238015823066,
0.002038335893303156
] |
{
"id": 6,
"code_window": [
"import { IWindowsService, IWindowService, IEnterWorkspaceResult, MenuBarVisibility, IURIToOpen, IOpenSettings, IWindowConfiguration } from 'vs/platform/windows/common/windows';\n",
"import { TestWorkspace } from 'vs/platform/workspace/test/common/testWorkspace';\n",
"import { createTextBufferFactoryFromStream } from 'vs/editor/common/model/textModel';\n",
"import { IEnvironmentService, ParsedArgs } from 'vs/platform/environment/common/environment';\n",
"import { IThemeService } from 'vs/platform/theme/common/themeService';\n",
"import { TestThemeService } from 'vs/platform/theme/test/common/testThemeService';\n",
"import { IWorkspaceIdentifier, ISingleFolderWorkspaceIdentifier, isSingleFolderWorkspaceIdentifier } from 'vs/platform/workspaces/common/workspaces';\n",
"import { IRecentlyOpened, IRecent } from 'vs/platform/history/common/history';\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { IEnvironmentService } from 'vs/platform/environment/common/environment';\n"
],
"file_path": "src/vs/workbench/test/workbenchTestServices.ts",
"type": "replace",
"edit_start_line_idx": 40
} | /*---------------------------------------------------------------------------------------------
* 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 { ITextModel } from 'vs/editor/common/model';
import { URI } from 'vs/base/common/uri';
import { ResourceEditorInput } from 'vs/workbench/common/editor/resourceEditorInput';
import { ResourceEditorModel } from 'vs/workbench/common/editor/resourceEditorModel';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { workbenchInstantiationService, TestTextFileService } from 'vs/workbench/test/workbenchTestServices';
import { toResource } from 'vs/base/test/common/utils';
import { ITextModelService } from 'vs/editor/common/services/resolverService';
import { IModelService } from 'vs/editor/common/services/modelService';
import { IModeService } from 'vs/editor/common/services/modeService';
import { TextFileEditorModel } from 'vs/workbench/services/textfile/common/textFileEditorModel';
import { ITextFileService, snapshotToString } from 'vs/workbench/services/textfile/common/textfiles';
import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService';
import { TextFileEditorModelManager } from 'vs/workbench/services/textfile/common/textFileEditorModelManager';
import { Event } from 'vs/base/common/event';
import { timeout } from 'vs/base/common/async';
class ServiceAccessor {
constructor(
@ITextModelService public textModelResolverService: ITextModelService,
@IModelService public modelService: IModelService,
@IModeService public modeService: IModeService,
@ITextFileService public textFileService: TestTextFileService,
@IUntitledEditorService public untitledEditorService: IUntitledEditorService
) {
}
}
suite('Workbench - TextModelResolverService', () => {
let instantiationService: IInstantiationService;
let accessor: ServiceAccessor;
let model: TextFileEditorModel;
setup(() => {
instantiationService = workbenchInstantiationService();
accessor = instantiationService.createInstance(ServiceAccessor);
});
teardown(() => {
if (model) {
model.dispose();
model = (undefined)!;
}
(<TextFileEditorModelManager>accessor.textFileService.models).clear();
(<TextFileEditorModelManager>accessor.textFileService.models).dispose();
accessor.untitledEditorService.revertAll();
});
test('resolve resource', async () => {
const dispose = accessor.textModelResolverService.registerTextModelContentProvider('test', {
provideTextContent: function (resource: URI): Promise<ITextModel> {
if (resource.scheme === 'test') {
let modelContent = 'Hello Test';
let languageSelection = accessor.modeService.create('json');
return Promise.resolve(accessor.modelService.createModel(modelContent, languageSelection, resource));
}
return Promise.resolve(null!);
}
});
let resource = URI.from({ scheme: 'test', authority: null!, path: 'thePath' });
let input: ResourceEditorInput = instantiationService.createInstance(ResourceEditorInput, 'The Name', 'The Description', resource, undefined);
const model = await input.resolve();
assert.ok(model);
assert.equal(snapshotToString(((model as ResourceEditorModel).createSnapshot()!)), 'Hello Test');
let disposed = false;
let disposedPromise = new Promise(resolve => {
Event.once(model.onDispose)(() => {
disposed = true;
resolve();
});
});
input.dispose();
await disposedPromise;
assert.equal(disposed, true);
dispose.dispose();
});
test('resolve file', async function () {
const textModel = instantiationService.createInstance(TextFileEditorModel, toResource.call(this, '/path/file_resolver.txt'), 'utf8', undefined);
(<TextFileEditorModelManager>accessor.textFileService.models).add(textModel.getResource(), textModel);
await textModel.load();
const ref = await accessor.textModelResolverService.createModelReference(textModel.getResource());
const model = ref.object;
const editorModel = model.textEditorModel;
assert.ok(editorModel);
assert.equal(editorModel.getValue(), 'Hello Html');
let disposed = false;
Event.once(model.onDispose)(() => {
disposed = true;
});
ref.dispose();
await timeout(0); // due to the reference resolving the model first which is async
assert.equal(disposed, true);
});
test('resolve untitled', async () => {
const service = accessor.untitledEditorService;
const input = service.createOrGet();
await input.resolve();
const ref = await accessor.textModelResolverService.createModelReference(input.getResource());
const model = ref.object;
const editorModel = model.textEditorModel;
assert.ok(editorModel);
ref.dispose();
input.dispose();
});
test('even loading documents should be refcounted', async () => {
let resolveModel!: Function;
let waitForIt = new Promise(c => resolveModel = c);
const disposable = accessor.textModelResolverService.registerTextModelContentProvider('test', {
provideTextContent: async (resource: URI): Promise<ITextModel> => {
await waitForIt;
let modelContent = 'Hello Test';
let languageSelection = accessor.modeService.create('json');
return accessor.modelService.createModel(modelContent, languageSelection, resource);
}
});
const uri = URI.from({ scheme: 'test', authority: null!, path: 'thePath' });
const modelRefPromise1 = accessor.textModelResolverService.createModelReference(uri);
const modelRefPromise2 = accessor.textModelResolverService.createModelReference(uri);
resolveModel();
const modelRef1 = await modelRefPromise1;
const model1 = modelRef1.object;
const modelRef2 = await modelRefPromise2;
const model2 = modelRef2.object;
const textModel = model1.textEditorModel;
assert.equal(model1, model2, 'they are the same model');
assert(!textModel.isDisposed(), 'the text model should not be disposed');
modelRef1.dispose();
assert(!textModel.isDisposed(), 'the text model should still not be disposed');
let p1 = new Promise(resolve => textModel.onWillDispose(resolve));
modelRef2.dispose();
await p1;
assert(textModel.isDisposed(), 'the text model should finally be disposed');
disposable.dispose();
});
});
| src/vs/workbench/services/textmodelResolver/test/textModelResolverService.test.ts | 0 | https://github.com/microsoft/vscode/commit/23f2275c23aeebf5e22f3d19a20528c8ba48c570 | [
0.00017223061877302825,
0.00016846317157614976,
0.00016372020763810724,
0.0001678755652392283,
0.0000024141363610397093
] |
{
"id": 6,
"code_window": [
"import { IWindowsService, IWindowService, IEnterWorkspaceResult, MenuBarVisibility, IURIToOpen, IOpenSettings, IWindowConfiguration } from 'vs/platform/windows/common/windows';\n",
"import { TestWorkspace } from 'vs/platform/workspace/test/common/testWorkspace';\n",
"import { createTextBufferFactoryFromStream } from 'vs/editor/common/model/textModel';\n",
"import { IEnvironmentService, ParsedArgs } from 'vs/platform/environment/common/environment';\n",
"import { IThemeService } from 'vs/platform/theme/common/themeService';\n",
"import { TestThemeService } from 'vs/platform/theme/test/common/testThemeService';\n",
"import { IWorkspaceIdentifier, ISingleFolderWorkspaceIdentifier, isSingleFolderWorkspaceIdentifier } from 'vs/platform/workspaces/common/workspaces';\n",
"import { IRecentlyOpened, IRecent } from 'vs/platform/history/common/history';\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { IEnvironmentService } from 'vs/platform/environment/common/environment';\n"
],
"file_path": "src/vs/workbench/test/workbenchTestServices.ts",
"type": "replace",
"edit_start_line_idx": 40
} | <svg width="14px" height="14px" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
<rect fill="#1B80B2" x="0" y="0" width="100" height="100" rx="35" ry="35"/>
<text x="50" y="75" font-size="75" text-anchor="middle" style="font-family: Menlo, Monaco, Consolas, "Droid Sans Mono", "Inconsolata", "Courier New", monospace, "Droid Sans Fallback";" fill="white">
M
</text>
</svg> | extensions/git/resources/icons/dark/status-modified.svg | 0 | https://github.com/microsoft/vscode/commit/23f2275c23aeebf5e22f3d19a20528c8ba48c570 | [
0.00017804298840928823,
0.00017804298840928823,
0.00017804298840928823,
0.00017804298840928823,
0
] |
{
"id": 6,
"code_window": [
"import { IWindowsService, IWindowService, IEnterWorkspaceResult, MenuBarVisibility, IURIToOpen, IOpenSettings, IWindowConfiguration } from 'vs/platform/windows/common/windows';\n",
"import { TestWorkspace } from 'vs/platform/workspace/test/common/testWorkspace';\n",
"import { createTextBufferFactoryFromStream } from 'vs/editor/common/model/textModel';\n",
"import { IEnvironmentService, ParsedArgs } from 'vs/platform/environment/common/environment';\n",
"import { IThemeService } from 'vs/platform/theme/common/themeService';\n",
"import { TestThemeService } from 'vs/platform/theme/test/common/testThemeService';\n",
"import { IWorkspaceIdentifier, ISingleFolderWorkspaceIdentifier, isSingleFolderWorkspaceIdentifier } from 'vs/platform/workspaces/common/workspaces';\n",
"import { IRecentlyOpened, IRecent } from 'vs/platform/history/common/history';\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { IEnvironmentService } from 'vs/platform/environment/common/environment';\n"
],
"file_path": "src/vs/workbench/test/workbenchTestServices.ts",
"type": "replace",
"edit_start_line_idx": 40
} | {
"displayName": "Kimbie Dark Theme",
"description": "Kimbie dark theme for Visual Studio Code"
} | extensions/theme-kimbie-dark/package.nls.json | 0 | https://github.com/microsoft/vscode/commit/23f2275c23aeebf5e22f3d19a20528c8ba48c570 | [
0.00017449972801841795,
0.00017449972801841795,
0.00017449972801841795,
0.00017449972801841795,
0
] |
{
"id": 7,
"code_window": [
"import { timeout } from 'vs/base/common/async';\n",
"import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';\n",
"import { ViewletDescriptor, Viewlet } from 'vs/workbench/browser/viewlet';\n",
"import { IViewlet } from 'vs/workbench/common/viewlet';\n",
"import { IStorageService, InMemoryStorageService } from 'vs/platform/storage/common/storage';\n",
"import { isLinux, isMacintosh, IProcessEnvironment } from 'vs/base/common/platform';\n",
"import { LabelService } from 'vs/workbench/services/label/common/labelService';\n",
"import { IDimension } from 'vs/platform/layout/browser/layoutService';\n",
"import { Part } from 'vs/workbench/browser/part';\n",
"import { IPanelService } from 'vs/workbench/services/panel/common/panelService';\n",
"import { IPanel } from 'vs/workbench/common/panel';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { isLinux, isMacintosh } from 'vs/base/common/platform';\n"
],
"file_path": "src/vs/workbench/test/workbenchTestServices.ts",
"type": "replace",
"edit_start_line_idx": 73
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'vs/workbench/contrib/files/browser/files.contribution'; // load our contribution into the test
import { FileEditorInput } from 'vs/workbench/contrib/files/common/editors/fileEditorInput';
import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock';
import { join } from 'vs/base/common/path';
import * as resources from 'vs/base/common/resources';
import { URI } from 'vs/base/common/uri';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { NullTelemetryService } from 'vs/platform/telemetry/common/telemetryUtils';
import { ConfirmResult, IEditorInputWithOptions, CloseDirection, IEditorIdentifier, IUntitledResourceInput, IResourceDiffInput, IResourceSideBySideInput, IEditorInput, IEditor, IEditorCloseEvent, IEditorPartOptions } from 'vs/workbench/common/editor';
import { IEditorOpeningEvent, EditorServiceImpl, IEditorGroupView } from 'vs/workbench/browser/parts/editor/editor';
import { Event, Emitter } from 'vs/base/common/event';
import Severity from 'vs/base/common/severity';
import { IBackupFileService, IResolvedBackup } from 'vs/workbench/services/backup/common/backup';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IWorkbenchLayoutService, Parts, Position as PartPosition } from 'vs/workbench/services/layout/browser/layoutService';
import { TextModelResolverService } from 'vs/workbench/services/textmodelResolver/common/textModelResolverService';
import { ITextModelService } from 'vs/editor/common/services/resolverService';
import { IEditorOptions, IResourceInput } from 'vs/platform/editor/common/editor';
import { IUntitledEditorService, UntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService';
import { IWorkspaceContextService, IWorkspace as IWorkbenchWorkspace, WorkbenchState, IWorkspaceFolder, IWorkspaceFoldersChangeEvent, Workspace } from 'vs/platform/workspace/common/workspace';
import { ILifecycleService, BeforeShutdownEvent, ShutdownReason, StartupKind, LifecyclePhase, WillShutdownEvent } from 'vs/platform/lifecycle/common/lifecycle';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { FileOperationEvent, IFileService, FileOperationError, IFileStat, IResolveFileResult, FileChangesEvent, IResolveFileOptions, ICreateFileOptions, IFileSystemProvider, FileSystemProviderCapabilities, IFileChange, IWatchOptions, IStat, FileType, FileDeleteOptions, FileOverwriteOptions, FileWriteOptions, FileOpenOptions, IFileStatWithMetadata, IResolveMetadataFileOptions, IWriteFileOptions, IReadFileOptions, IFileContent, IFileStreamContent } from 'vs/platform/files/common/files';
import { IModelService } from 'vs/editor/common/services/modelService';
import { ModeServiceImpl } from 'vs/editor/common/services/modeServiceImpl';
import { ModelServiceImpl } from 'vs/editor/common/services/modelServiceImpl';
import { ITextFileStreamContent, ITextFileService, IResourceEncoding, IReadTextFileOptions } from 'vs/workbench/services/textfile/common/textfiles';
import { parseArgs, OPTIONS } from 'vs/platform/environment/node/argv';
import { IModeService } from 'vs/editor/common/services/modeService';
import { IHistoryService } from 'vs/workbench/services/history/common/history';
import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService';
import { IWindowsService, IWindowService, IEnterWorkspaceResult, MenuBarVisibility, IURIToOpen, IOpenSettings, IWindowConfiguration } from 'vs/platform/windows/common/windows';
import { TestWorkspace } from 'vs/platform/workspace/test/common/testWorkspace';
import { createTextBufferFactoryFromStream } from 'vs/editor/common/model/textModel';
import { IEnvironmentService, ParsedArgs } from 'vs/platform/environment/common/environment';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { TestThemeService } from 'vs/platform/theme/test/common/testThemeService';
import { IWorkspaceIdentifier, ISingleFolderWorkspaceIdentifier, isSingleFolderWorkspaceIdentifier } from 'vs/platform/workspaces/common/workspaces';
import { IRecentlyOpened, IRecent } from 'vs/platform/history/common/history';
import { ITextResourceConfigurationService, ITextResourcePropertiesService } from 'vs/editor/common/services/resourceConfiguration';
import { IPosition, Position as EditorPosition } from 'vs/editor/common/core/position';
import { IMenuService, MenuId, IMenu } from 'vs/platform/actions/common/actions';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { MockContextKeyService, MockKeybindingService } from 'vs/platform/keybinding/test/common/mockKeybindingService';
import { ITextBufferFactory, DefaultEndOfLine, EndOfLinePreference, IModelDecorationOptions, ITextModel, ITextSnapshot } from 'vs/editor/common/model';
import { Range } from 'vs/editor/common/core/range';
import { IConfirmation, IConfirmationResult, IDialogService, IDialogOptions, IPickAndOpenOptions, ISaveDialogOptions, IOpenDialogOptions, IFileDialogService, IShowResult } from 'vs/platform/dialogs/common/dialogs';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { TestNotificationService } from 'vs/platform/notification/test/common/testNotificationService';
import { IExtensionService, NullExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IDecorationsService, IResourceDecorationChangeEvent, IDecoration, IDecorationData, IDecorationsProvider } from 'vs/workbench/services/decorations/browser/decorations';
import { IDisposable, toDisposable, Disposable } from 'vs/base/common/lifecycle';
import { IEditorGroupsService, IEditorGroup, GroupsOrder, GroupsArrangement, GroupDirection, IAddGroupOptions, IMergeGroupOptions, IMoveEditorOptions, ICopyEditorOptions, IEditorReplacement, IGroupChangeEvent, EditorsOrder, IFindGroupScope, EditorGroupLayout, ICloseEditorOptions } from 'vs/workbench/services/editor/common/editorGroupsService';
import { IEditorService, IOpenEditorOverrideHandler, IVisibleEditor } from 'vs/workbench/services/editor/common/editorService';
import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService';
import { ICodeEditor, IDiffEditor } from 'vs/editor/browser/editorBrowser';
import { IDecorationRenderOptions } from 'vs/editor/common/editorCommon';
import { EditorGroup } from 'vs/workbench/common/editor/editorGroup';
import { Dimension } from 'vs/base/browser/dom';
import { ILogService, NullLogService } from 'vs/platform/log/common/log';
import { ILabelService } from 'vs/platform/label/common/label';
import { timeout } from 'vs/base/common/async';
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
import { ViewletDescriptor, Viewlet } from 'vs/workbench/browser/viewlet';
import { IViewlet } from 'vs/workbench/common/viewlet';
import { IStorageService, InMemoryStorageService } from 'vs/platform/storage/common/storage';
import { isLinux, isMacintosh, IProcessEnvironment } from 'vs/base/common/platform';
import { LabelService } from 'vs/workbench/services/label/common/labelService';
import { IDimension } from 'vs/platform/layout/browser/layoutService';
import { Part } from 'vs/workbench/browser/part';
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
import { IPanel } from 'vs/workbench/common/panel';
import { IBadge } from 'vs/workbench/services/activity/common/activity';
import { ISharedProcessService } from 'vs/platform/ipc/electron-browser/sharedProcessService';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { WorkbenchEnvironmentService } from 'vs/workbench/services/environment/node/environmentService';
import { VSBuffer, VSBufferReadable } from 'vs/base/common/buffer';
import { NativeTextFileService } from 'vs/workbench/services/textfile/electron-browser/nativeTextFileService';
import { Schemas } from 'vs/base/common/network';
import { IProductService } from 'vs/platform/product/common/productService';
import product from 'vs/platform/product/common/product';
import { IHostService } from 'vs/workbench/services/host/browser/host';
export function createFileInput(instantiationService: IInstantiationService, resource: URI): FileEditorInput {
return instantiationService.createInstance(FileEditorInput, resource, undefined, undefined);
}
export const TestEnvironmentService = new WorkbenchEnvironmentService(parseArgs(process.argv, OPTIONS) as IWindowConfiguration, process.execPath);
export class TestContextService implements IWorkspaceContextService {
public _serviceBrand: undefined;
private workspace: Workspace;
private options: any;
private readonly _onDidChangeWorkspaceName: Emitter<void>;
private readonly _onDidChangeWorkspaceFolders: Emitter<IWorkspaceFoldersChangeEvent>;
private readonly _onDidChangeWorkbenchState: Emitter<WorkbenchState>;
constructor(workspace: any = TestWorkspace, options: any = null) {
this.workspace = workspace;
this.options = options || Object.create(null);
this._onDidChangeWorkspaceName = new Emitter<void>();
this._onDidChangeWorkspaceFolders = new Emitter<IWorkspaceFoldersChangeEvent>();
this._onDidChangeWorkbenchState = new Emitter<WorkbenchState>();
}
public get onDidChangeWorkspaceName(): Event<void> {
return this._onDidChangeWorkspaceName.event;
}
public get onDidChangeWorkspaceFolders(): Event<IWorkspaceFoldersChangeEvent> {
return this._onDidChangeWorkspaceFolders.event;
}
public get onDidChangeWorkbenchState(): Event<WorkbenchState> {
return this._onDidChangeWorkbenchState.event;
}
public getFolders(): IWorkspaceFolder[] {
return this.workspace ? this.workspace.folders : [];
}
public getWorkbenchState(): WorkbenchState {
if (this.workspace.configuration) {
return WorkbenchState.WORKSPACE;
}
if (this.workspace.folders.length) {
return WorkbenchState.FOLDER;
}
return WorkbenchState.EMPTY;
}
getCompleteWorkspace(): Promise<IWorkbenchWorkspace> {
return Promise.resolve(this.getWorkspace());
}
public getWorkspace(): IWorkbenchWorkspace {
return this.workspace;
}
public getWorkspaceFolder(resource: URI): IWorkspaceFolder | null {
return this.workspace.getFolder(resource);
}
public setWorkspace(workspace: any): void {
this.workspace = workspace;
}
public getOptions() {
return this.options;
}
public updateOptions() {
}
public isInsideWorkspace(resource: URI): boolean {
if (resource && this.workspace) {
return resources.isEqualOrParent(resource, this.workspace.folders[0].uri);
}
return false;
}
public toResource(workspaceRelativePath: string): URI {
return URI.file(join('C:\\', workspaceRelativePath));
}
public isCurrentWorkspace(workspaceIdentifier: ISingleFolderWorkspaceIdentifier | IWorkspaceIdentifier): boolean {
return isSingleFolderWorkspaceIdentifier(workspaceIdentifier) && resources.isEqual(this.workspace.folders[0].uri, workspaceIdentifier);
}
}
export class TestTextFileService extends NativeTextFileService {
public cleanupBackupsBeforeShutdownCalled: boolean;
private promptPath: URI;
private confirmResult: ConfirmResult;
private resolveTextContentError: FileOperationError | null;
constructor(
@IWorkspaceContextService contextService: IWorkspaceContextService,
@IFileService protected fileService: IFileService,
@IUntitledEditorService untitledEditorService: IUntitledEditorService,
@ILifecycleService lifecycleService: ILifecycleService,
@IInstantiationService instantiationService: IInstantiationService,
@IConfigurationService configurationService: IConfigurationService,
@IModeService modeService: IModeService,
@IModelService modelService: IModelService,
@IWorkbenchEnvironmentService environmentService: IWorkbenchEnvironmentService,
@INotificationService notificationService: INotificationService,
@IBackupFileService backupFileService: IBackupFileService,
@IHostService hostService: IHostService,
@IHistoryService historyService: IHistoryService,
@IContextKeyService contextKeyService: IContextKeyService,
@IDialogService dialogService: IDialogService,
@IFileDialogService fileDialogService: IFileDialogService,
@IEditorService editorService: IEditorService,
@ITextResourceConfigurationService textResourceConfigurationService: ITextResourceConfigurationService
) {
super(
contextService,
fileService,
untitledEditorService,
lifecycleService,
instantiationService,
configurationService,
modeService,
modelService,
environmentService,
notificationService,
backupFileService,
hostService,
historyService,
contextKeyService,
dialogService,
fileDialogService,
editorService,
textResourceConfigurationService
);
}
public setPromptPath(path: URI): void {
this.promptPath = path;
}
public setConfirmResult(result: ConfirmResult): void {
this.confirmResult = result;
}
public setResolveTextContentErrorOnce(error: FileOperationError): void {
this.resolveTextContentError = error;
}
public readStream(resource: URI, options?: IReadTextFileOptions): Promise<ITextFileStreamContent> {
if (this.resolveTextContentError) {
const error = this.resolveTextContentError;
this.resolveTextContentError = null;
return Promise.reject(error);
}
return this.fileService.readFileStream(resource, options).then(async (content): Promise<ITextFileStreamContent> => {
return {
resource: content.resource,
name: content.name,
mtime: content.mtime,
etag: content.etag,
encoding: 'utf8',
value: await createTextBufferFactoryFromStream(content.value),
size: 10
};
});
}
public promptForPath(_resource: URI, _defaultPath: URI): Promise<URI> {
return Promise.resolve(this.promptPath);
}
public confirmSave(_resources?: URI[]): Promise<ConfirmResult> {
return Promise.resolve(this.confirmResult);
}
public confirmOverwrite(_resource: URI): Promise<boolean> {
return Promise.resolve(true);
}
public onFilesConfigurationChange(configuration: any): void {
super.onFilesConfigurationChange(configuration);
}
protected cleanupBackupsBeforeShutdown(): Promise<void> {
this.cleanupBackupsBeforeShutdownCalled = true;
return Promise.resolve();
}
}
export function workbenchInstantiationService(): IInstantiationService {
let instantiationService = new TestInstantiationService(new ServiceCollection([ILifecycleService, new TestLifecycleService()]));
instantiationService.stub(IEnvironmentService, TestEnvironmentService);
instantiationService.stub(IContextKeyService, <IContextKeyService>instantiationService.createInstance(MockContextKeyService));
const workspaceContextService = new TestContextService(TestWorkspace);
instantiationService.stub(IWorkspaceContextService, workspaceContextService);
const configService = new TestConfigurationService();
instantiationService.stub(IConfigurationService, configService);
instantiationService.stub(ITextResourceConfigurationService, new TestTextResourceConfigurationService(configService));
instantiationService.stub(IUntitledEditorService, instantiationService.createInstance(UntitledEditorService));
instantiationService.stub(IStorageService, new TestStorageService());
instantiationService.stub(IWorkbenchLayoutService, new TestLayoutService());
instantiationService.stub(IModeService, instantiationService.createInstance(ModeServiceImpl));
instantiationService.stub(IHistoryService, new TestHistoryService());
instantiationService.stub(ITextResourcePropertiesService, new TestTextResourcePropertiesService(configService));
instantiationService.stub(IModelService, instantiationService.createInstance(ModelServiceImpl));
instantiationService.stub(IFileService, new TestFileService());
instantiationService.stub(IBackupFileService, new TestBackupFileService());
instantiationService.stub(ITelemetryService, NullTelemetryService);
instantiationService.stub(INotificationService, new TestNotificationService());
instantiationService.stub(IUntitledEditorService, instantiationService.createInstance(UntitledEditorService));
instantiationService.stub(IWindowService, new TestWindowService());
instantiationService.stub(IMenuService, new TestMenuService());
instantiationService.stub(IKeybindingService, new MockKeybindingService());
instantiationService.stub(IDecorationsService, new TestDecorationsService());
instantiationService.stub(IExtensionService, new TestExtensionService());
instantiationService.stub(IWindowsService, new TestWindowsService());
instantiationService.stub(IHostService, <IHostService>instantiationService.createInstance(TestHostService));
instantiationService.stub(ITextFileService, <ITextFileService>instantiationService.createInstance(TestTextFileService));
instantiationService.stub(ITextModelService, <ITextModelService>instantiationService.createInstance(TextModelResolverService));
instantiationService.stub(IThemeService, new TestThemeService());
instantiationService.stub(ILogService, new NullLogService());
instantiationService.stub(IEditorGroupsService, new TestEditorGroupsService([new TestEditorGroup(0)]));
instantiationService.stub(ILabelService, <ILabelService>instantiationService.createInstance(LabelService));
const editorService = new TestEditorService();
instantiationService.stub(IEditorService, editorService);
instantiationService.stub(ICodeEditorService, new TestCodeEditorService());
instantiationService.stub(IViewletService, new TestViewletService());
return instantiationService;
}
export class TestDecorationsService implements IDecorationsService {
_serviceBrand: undefined;
onDidChangeDecorations: Event<IResourceDecorationChangeEvent> = Event.None;
registerDecorationsProvider(_provider: IDecorationsProvider): IDisposable { return Disposable.None; }
getDecoration(_uri: URI, _includeChildren: boolean, _overwrite?: IDecorationData): IDecoration | undefined { return undefined; }
}
export class TestExtensionService extends NullExtensionService { }
export class TestMenuService implements IMenuService {
public _serviceBrand: undefined;
createMenu(_id: MenuId, _scopedKeybindingService: IContextKeyService): IMenu {
return {
onDidChange: Event.None,
dispose: () => undefined,
getActions: () => []
};
}
}
export class TestHistoryService implements IHistoryService {
public _serviceBrand: undefined;
constructor(private root?: URI) {
}
public reopenLastClosedEditor(): void {
}
public forward(_acrossEditors?: boolean): void {
}
public back(_acrossEditors?: boolean): void {
}
public last(): void {
}
public remove(_input: IEditorInput | IResourceInput): void {
}
public clear(): void {
}
public clearRecentlyOpened(): void {
}
public getHistory(): Array<IEditorInput | IResourceInput> {
return [];
}
public getLastActiveWorkspaceRoot(_schemeFilter: string): URI | undefined {
return this.root;
}
public getLastActiveFile(_schemeFilter: string): URI | undefined {
return undefined;
}
public openLastEditLocation(): void {
}
}
export class TestDialogService implements IDialogService {
public _serviceBrand: undefined;
public confirm(_confirmation: IConfirmation): Promise<IConfirmationResult> {
return Promise.resolve({ confirmed: false });
}
public show(_severity: Severity, _message: string, _buttons: string[], _options?: IDialogOptions): Promise<IShowResult> {
return Promise.resolve({ choice: 0 });
}
public about(): Promise<void> {
return Promise.resolve();
}
}
export class TestFileDialogService implements IFileDialogService {
public _serviceBrand: undefined;
public defaultFilePath(_schemeFilter?: string): URI | undefined {
return undefined;
}
public defaultFolderPath(_schemeFilter?: string): URI | undefined {
return undefined;
}
public defaultWorkspacePath(_schemeFilter?: string): URI | undefined {
return undefined;
}
public pickFileFolderAndOpen(_options: IPickAndOpenOptions): Promise<any> {
return Promise.resolve(0);
}
public pickFileAndOpen(_options: IPickAndOpenOptions): Promise<any> {
return Promise.resolve(0);
}
public pickFolderAndOpen(_options: IPickAndOpenOptions): Promise<any> {
return Promise.resolve(0);
}
public pickWorkspaceAndOpen(_options: IPickAndOpenOptions): Promise<any> {
return Promise.resolve(0);
}
public pickFileToSave(_options: ISaveDialogOptions): Promise<URI | undefined> {
return Promise.resolve(undefined);
}
public showSaveDialog(_options: ISaveDialogOptions): Promise<URI | undefined> {
return Promise.resolve(undefined);
}
public showOpenDialog(_options: IOpenDialogOptions): Promise<URI[] | undefined> {
return Promise.resolve(undefined);
}
}
export class TestLayoutService implements IWorkbenchLayoutService {
public _serviceBrand: undefined;
dimension: IDimension = { width: 800, height: 600 };
container: HTMLElement = window.document.body;
onZenModeChange: Event<boolean> = Event.None;
onCenteredLayoutChange: Event<boolean> = Event.None;
onFullscreenChange: Event<boolean> = Event.None;
onPanelPositionChange: Event<string> = Event.None;
onLayout = Event.None;
private readonly _onTitleBarVisibilityChange = new Emitter<void>();
private readonly _onMenubarVisibilityChange = new Emitter<Dimension>();
public get onTitleBarVisibilityChange(): Event<void> {
return this._onTitleBarVisibilityChange.event;
}
public get onMenubarVisibilityChange(): Event<Dimension> {
return this._onMenubarVisibilityChange.event;
}
public isRestored(): boolean {
return true;
}
public hasFocus(_part: Parts): boolean {
return false;
}
public isVisible(_part: Parts): boolean {
return true;
}
getDimension(_part: Parts): Dimension {
return new Dimension(0, 0);
}
public getContainer(_part: Parts): HTMLElement {
return null!;
}
public isTitleBarHidden(): boolean {
return false;
}
public getTitleBarOffset(): number {
return 0;
}
public isStatusBarHidden(): boolean {
return false;
}
public isActivityBarHidden(): boolean {
return false;
}
public setActivityBarHidden(_hidden: boolean): void { }
public isSideBarHidden(): boolean {
return false;
}
public setEditorHidden(_hidden: boolean): Promise<void> { return Promise.resolve(); }
public setSideBarHidden(_hidden: boolean): Promise<void> { return Promise.resolve(); }
public isPanelHidden(): boolean {
return false;
}
public setPanelHidden(_hidden: boolean): Promise<void> { return Promise.resolve(); }
public toggleMaximizedPanel(): void { }
public isPanelMaximized(): boolean {
return false;
}
public getMenubarVisibility(): MenuBarVisibility {
throw new Error('not implemented');
}
public getSideBarPosition() {
return 0;
}
public getPanelPosition() {
return 0;
}
public setPanelPosition(_position: PartPosition): Promise<void> {
return Promise.resolve();
}
public addClass(_clazz: string): void { }
public removeClass(_clazz: string): void { }
public getMaximumEditorDimensions(): Dimension { throw new Error('not implemented'); }
public getWorkbenchContainer(): HTMLElement { throw new Error('not implemented'); }
public getWorkbenchElement(): HTMLElement { throw new Error('not implemented'); }
public toggleZenMode(): void { }
public isEditorLayoutCentered(): boolean { return false; }
public centerEditorLayout(_active: boolean): void { }
public resizePart(_part: Parts, _sizeChange: number): void { }
public registerPart(part: Part): void { }
}
let activeViewlet: Viewlet = {} as any;
export class TestViewletService implements IViewletService {
public _serviceBrand: undefined;
onDidViewletRegisterEmitter = new Emitter<ViewletDescriptor>();
onDidViewletDeregisterEmitter = new Emitter<ViewletDescriptor>();
onDidViewletOpenEmitter = new Emitter<IViewlet>();
onDidViewletCloseEmitter = new Emitter<IViewlet>();
onDidViewletRegister = this.onDidViewletRegisterEmitter.event;
onDidViewletDeregister = this.onDidViewletDeregisterEmitter.event;
onDidViewletOpen = this.onDidViewletOpenEmitter.event;
onDidViewletClose = this.onDidViewletCloseEmitter.event;
public openViewlet(id: string, focus?: boolean): Promise<IViewlet> {
return Promise.resolve(null!);
}
public getViewlets(): ViewletDescriptor[] {
return [];
}
public getAllViewlets(): ViewletDescriptor[] {
return [];
}
public getActiveViewlet(): IViewlet {
return activeViewlet;
}
public dispose() {
}
public getDefaultViewletId(): string {
return 'workbench.view.explorer';
}
public getViewlet(id: string): ViewletDescriptor | undefined {
return undefined;
}
public getProgressIndicator(id: string) {
return null!;
}
public hideActiveViewlet(): void { }
public getLastActiveViewletId(): string {
return undefined!;
}
}
export class TestPanelService implements IPanelService {
public _serviceBrand: undefined;
onDidPanelOpen = new Emitter<{ panel: IPanel, focus: boolean }>().event;
onDidPanelClose = new Emitter<IPanel>().event;
public openPanel(id: string, focus?: boolean): IPanel {
return null!;
}
public getPanel(id: string): any {
return activeViewlet;
}
public getPanels(): any[] {
return [];
}
public getPinnedPanels(): any[] {
return [];
}
public getActivePanel(): IViewlet {
return activeViewlet;
}
public setPanelEnablement(id: string, enabled: boolean): void { }
public dispose() {
}
public showActivity(panelId: string, badge: IBadge, clazz?: string): IDisposable {
throw new Error('Method not implemented.');
}
public getProgressIndicator(id: string) {
return null!;
}
public hideActivePanel(): void { }
public getLastActivePanelId(): string {
return undefined!;
}
}
export class TestStorageService extends InMemoryStorageService { }
export class TestEditorGroupsService implements IEditorGroupsService {
_serviceBrand: undefined;
constructor(public groups: TestEditorGroup[] = []) { }
onDidActiveGroupChange: Event<IEditorGroup> = Event.None;
onDidActivateGroup: Event<IEditorGroup> = Event.None;
onDidAddGroup: Event<IEditorGroup> = Event.None;
onDidRemoveGroup: Event<IEditorGroup> = Event.None;
onDidMoveGroup: Event<IEditorGroup> = Event.None;
onDidGroupIndexChange: Event<IEditorGroup> = Event.None;
onDidLayout: Event<IDimension> = Event.None;
orientation: any;
whenRestored: Promise<void> = Promise.resolve(undefined);
willRestoreEditors = false;
contentDimension = { width: 800, height: 600 };
get activeGroup(): IEditorGroup {
return this.groups[0];
}
get count(): number {
return this.groups.length;
}
getGroups(_order?: GroupsOrder): ReadonlyArray<IEditorGroup> {
return this.groups;
}
getGroup(identifier: number): IEditorGroup {
for (const group of this.groups) {
if (group.id === identifier) {
return group;
}
}
return undefined!;
}
getLabel(_identifier: number): string {
return 'Group 1';
}
findGroup(_scope: IFindGroupScope, _source?: number | IEditorGroup, _wrap?: boolean): IEditorGroup {
throw new Error('not implemented');
}
activateGroup(_group: number | IEditorGroup): IEditorGroup {
throw new Error('not implemented');
}
restoreGroup(_group: number | IEditorGroup): IEditorGroup {
throw new Error('not implemented');
}
getSize(_group: number | IEditorGroup): { width: number, height: number } {
return { width: 100, height: 100 };
}
setSize(_group: number | IEditorGroup, _size: { width: number, height: number }): void { }
arrangeGroups(_arrangement: GroupsArrangement): void { }
applyLayout(_layout: EditorGroupLayout): void { }
setGroupOrientation(_orientation: any): void { }
addGroup(_location: number | IEditorGroup, _direction: GroupDirection, _options?: IAddGroupOptions): IEditorGroup {
throw new Error('not implemented');
}
removeGroup(_group: number | IEditorGroup): void { }
moveGroup(_group: number | IEditorGroup, _location: number | IEditorGroup, _direction: GroupDirection): IEditorGroup {
throw new Error('not implemented');
}
mergeGroup(_group: number | IEditorGroup, _target: number | IEditorGroup, _options?: IMergeGroupOptions): IEditorGroup {
throw new Error('not implemented');
}
copyGroup(_group: number | IEditorGroup, _location: number | IEditorGroup, _direction: GroupDirection): IEditorGroup {
throw new Error('not implemented');
}
centerLayout(active: boolean): void { }
isLayoutCentered(): boolean {
return false;
}
partOptions: IEditorPartOptions;
enforcePartOptions(options: IEditorPartOptions): IDisposable {
return Disposable.None;
}
}
export class TestEditorGroup implements IEditorGroupView {
constructor(public id: number) { }
get group(): EditorGroup { throw new Error('not implemented'); }
activeControl: IVisibleEditor;
activeEditor: IEditorInput;
previewEditor: IEditorInput;
count: number;
disposed: boolean;
editors: ReadonlyArray<IEditorInput> = [];
label: string;
index: number;
whenRestored: Promise<void> = Promise.resolve(undefined);
element: HTMLElement;
minimumWidth: number;
maximumWidth: number;
minimumHeight: number;
maximumHeight: number;
isEmpty = true;
isMinimized = false;
onWillDispose: Event<void> = Event.None;
onDidGroupChange: Event<IGroupChangeEvent> = Event.None;
onWillCloseEditor: Event<IEditorCloseEvent> = Event.None;
onDidCloseEditor: Event<IEditorCloseEvent> = Event.None;
onWillOpenEditor: Event<IEditorOpeningEvent> = Event.None;
onDidOpenEditorFail: Event<IEditorInput> = Event.None;
onDidFocus: Event<void> = Event.None;
onDidChange: Event<{ width: number; height: number; }> = Event.None;
getEditors(_order?: EditorsOrder): ReadonlyArray<IEditorInput> {
return [];
}
getEditor(_index: number): IEditorInput {
throw new Error('not implemented');
}
getIndexOfEditor(_editor: IEditorInput): number {
return -1;
}
openEditor(_editor: IEditorInput, _options?: IEditorOptions): Promise<IEditor> {
throw new Error('not implemented');
}
openEditors(_editors: IEditorInputWithOptions[]): Promise<IEditor> {
throw new Error('not implemented');
}
isOpened(_editor: IEditorInput): boolean {
return false;
}
isPinned(_editor: IEditorInput): boolean {
return false;
}
isActive(_editor: IEditorInput): boolean {
return false;
}
moveEditor(_editor: IEditorInput, _target: IEditorGroup, _options?: IMoveEditorOptions): void { }
copyEditor(_editor: IEditorInput, _target: IEditorGroup, _options?: ICopyEditorOptions): void { }
closeEditor(_editor?: IEditorInput, options?: ICloseEditorOptions): Promise<void> {
return Promise.resolve();
}
closeEditors(_editors: IEditorInput[] | { except?: IEditorInput; direction?: CloseDirection; savedOnly?: boolean; }, options?: ICloseEditorOptions): Promise<void> {
return Promise.resolve();
}
closeAllEditors(): Promise<void> {
return Promise.resolve();
}
replaceEditors(_editors: IEditorReplacement[]): Promise<void> {
return Promise.resolve();
}
pinEditor(_editor?: IEditorInput): void { }
focus(): void { }
invokeWithinContext<T>(fn: (accessor: ServicesAccessor) => T): T {
throw new Error('not implemented');
}
setActive(_isActive: boolean): void { }
notifyIndexChanged(_index: number): void { }
dispose(): void { }
toJSON(): object { return Object.create(null); }
layout(_width: number, _height: number): void { }
relayout() { }
}
export class TestEditorService implements EditorServiceImpl {
_serviceBrand: undefined;
onDidActiveEditorChange: Event<void> = Event.None;
onDidVisibleEditorsChange: Event<void> = Event.None;
onDidCloseEditor: Event<IEditorCloseEvent> = Event.None;
onDidOpenEditorFail: Event<IEditorIdentifier> = Event.None;
activeControl: IVisibleEditor;
activeTextEditorWidget: any;
activeEditor: IEditorInput;
editors: ReadonlyArray<IEditorInput> = [];
visibleControls: ReadonlyArray<IVisibleEditor> = [];
visibleTextEditorWidgets = [];
visibleEditors: ReadonlyArray<IEditorInput> = [];
overrideOpenEditor(_handler: IOpenEditorOverrideHandler): IDisposable {
return toDisposable(() => undefined);
}
openEditor(_editor: any, _options?: any, _group?: any): Promise<any> {
throw new Error('not implemented');
}
openEditors(_editors: any, _group?: any): Promise<IEditor[]> {
throw new Error('not implemented');
}
isOpen(_editor: IEditorInput | IResourceInput | IUntitledResourceInput): boolean {
return false;
}
getOpened(_editor: IEditorInput | IResourceInput | IUntitledResourceInput): IEditorInput {
throw new Error('not implemented');
}
replaceEditors(_editors: any, _group: any) {
return Promise.resolve(undefined);
}
invokeWithinEditorContext<T>(fn: (accessor: ServicesAccessor) => T): T {
throw new Error('not implemented');
}
createInput(_input: IResourceInput | IUntitledResourceInput | IResourceDiffInput | IResourceSideBySideInput): IEditorInput {
throw new Error('not implemented');
}
}
export class TestFileService implements IFileService {
public _serviceBrand: undefined;
private readonly _onFileChanges: Emitter<FileChangesEvent>;
private readonly _onAfterOperation: Emitter<FileOperationEvent>;
readonly onWillActivateFileSystemProvider = Event.None;
readonly onError: Event<Error> = Event.None;
private content = 'Hello Html';
private lastReadFileUri: URI;
constructor() {
this._onFileChanges = new Emitter<FileChangesEvent>();
this._onAfterOperation = new Emitter<FileOperationEvent>();
}
public setContent(content: string): void {
this.content = content;
}
public getContent(): string {
return this.content;
}
public getLastReadFileUri(): URI {
return this.lastReadFileUri;
}
public get onFileChanges(): Event<FileChangesEvent> {
return this._onFileChanges.event;
}
public fireFileChanges(event: FileChangesEvent): void {
this._onFileChanges.fire(event);
}
public get onAfterOperation(): Event<FileOperationEvent> {
return this._onAfterOperation.event;
}
public fireAfterOperation(event: FileOperationEvent): void {
this._onAfterOperation.fire(event);
}
resolve(resource: URI, _options?: IResolveFileOptions): Promise<IFileStat>;
resolve(resource: URI, _options: IResolveMetadataFileOptions): Promise<IFileStatWithMetadata>;
resolve(resource: URI, _options?: IResolveFileOptions): Promise<IFileStat> {
return Promise.resolve({
resource,
etag: Date.now().toString(),
encoding: 'utf8',
mtime: Date.now(),
size: 42,
isDirectory: false,
name: resources.basename(resource)
});
}
resolveAll(toResolve: { resource: URI, options?: IResolveFileOptions }[]): Promise<IResolveFileResult[]> {
return Promise.all(toResolve.map(resourceAndOption => this.resolve(resourceAndOption.resource, resourceAndOption.options))).then(stats => stats.map(stat => ({ stat, success: true })));
}
exists(_resource: URI): Promise<boolean> {
return Promise.resolve(true);
}
readFile(resource: URI, options?: IReadFileOptions | undefined): Promise<IFileContent> {
this.lastReadFileUri = resource;
return Promise.resolve({
resource: resource,
value: VSBuffer.fromString(this.content),
etag: 'index.txt',
encoding: 'utf8',
mtime: Date.now(),
name: resources.basename(resource),
size: 1
});
}
readFileStream(resource: URI, options?: IReadFileOptions | undefined): Promise<IFileStreamContent> {
this.lastReadFileUri = resource;
return Promise.resolve({
resource: resource,
value: {
on: (event: string, callback: Function): void => {
if (event === 'data') {
callback(this.content);
}
if (event === 'end') {
callback();
}
},
resume: () => { },
pause: () => { },
destroy: () => { }
},
etag: 'index.txt',
encoding: 'utf8',
mtime: Date.now(),
size: 1,
name: resources.basename(resource)
});
}
writeFile(resource: URI, bufferOrReadable: VSBuffer | VSBufferReadable, options?: IWriteFileOptions): Promise<IFileStatWithMetadata> {
return timeout(0).then(() => ({
resource,
etag: 'index.txt',
encoding: 'utf8',
mtime: Date.now(),
size: 42,
isDirectory: false,
name: resources.basename(resource)
}));
}
move(_source: URI, _target: URI, _overwrite?: boolean): Promise<IFileStatWithMetadata> {
return Promise.resolve(null!);
}
copy(_source: URI, _target: URI, _overwrite?: boolean): Promise<IFileStatWithMetadata> {
throw new Error('not implemented');
}
createFile(_resource: URI, _content?: VSBuffer | VSBufferReadable, _options?: ICreateFileOptions): Promise<IFileStatWithMetadata> {
throw new Error('not implemented');
}
createFolder(_resource: URI): Promise<IFileStatWithMetadata> {
throw new Error('not implemented');
}
onDidChangeFileSystemProviderRegistrations = Event.None;
private providers = new Map<string, IFileSystemProvider>();
registerProvider(scheme: string, provider: IFileSystemProvider) {
this.providers.set(scheme, provider);
return toDisposable(() => this.providers.delete(scheme));
}
activateProvider(_scheme: string): Promise<void> {
throw new Error('not implemented');
}
canHandleResource(resource: URI): boolean {
return resource.scheme === 'file' || this.providers.has(resource.scheme);
}
hasCapability(resource: URI, capability: FileSystemProviderCapabilities): boolean { return false; }
del(_resource: URI, _options?: { useTrash?: boolean, recursive?: boolean }): Promise<void> {
return Promise.resolve();
}
watch(_resource: URI): IDisposable {
return Disposable.None;
}
getWriteEncoding(_resource: URI): IResourceEncoding {
return { encoding: 'utf8', hasBOM: false };
}
dispose(): void {
}
}
export class TestBackupFileService implements IBackupFileService {
public _serviceBrand: undefined;
public hasBackups(): Promise<boolean> {
return Promise.resolve(false);
}
public hasBackup(_resource: URI): Promise<boolean> {
return Promise.resolve(false);
}
public hasBackupSync(resource: URI, versionId?: number): boolean {
return false;
}
public loadBackupResource(resource: URI): Promise<URI | undefined> {
return this.hasBackup(resource).then(hasBackup => {
if (hasBackup) {
return this.toBackupResource(resource);
}
return undefined;
});
}
public registerResourceForBackup(_resource: URI): Promise<void> {
return Promise.resolve();
}
public deregisterResourceForBackup(_resource: URI): Promise<void> {
return Promise.resolve();
}
public toBackupResource(_resource: URI): URI {
throw new Error('not implemented');
}
public backupResource<T extends object>(_resource: URI, _content: ITextSnapshot, versionId?: number, meta?: T): Promise<void> {
return Promise.resolve();
}
public getWorkspaceFileBackups(): Promise<URI[]> {
return Promise.resolve([]);
}
public parseBackupContent(textBufferFactory: ITextBufferFactory): string {
const textBuffer = textBufferFactory.create(DefaultEndOfLine.LF);
const lineCount = textBuffer.getLineCount();
const range = new Range(1, 1, lineCount, textBuffer.getLineLength(lineCount) + 1);
return textBuffer.getValueInRange(range, EndOfLinePreference.TextDefined);
}
public resolveBackupContent<T extends object>(_backup: URI): Promise<IResolvedBackup<T>> {
throw new Error('not implemented');
}
public discardResourceBackup(_resource: URI): Promise<void> {
return Promise.resolve();
}
public discardAllWorkspaceBackups(): Promise<void> {
return Promise.resolve();
}
}
export class TestCodeEditorService implements ICodeEditorService {
_serviceBrand: undefined;
onCodeEditorAdd: Event<ICodeEditor> = Event.None;
onCodeEditorRemove: Event<ICodeEditor> = Event.None;
onDiffEditorAdd: Event<IDiffEditor> = Event.None;
onDiffEditorRemove: Event<IDiffEditor> = Event.None;
onDidChangeTransientModelProperty: Event<ITextModel> = Event.None;
addCodeEditor(_editor: ICodeEditor): void { }
removeCodeEditor(_editor: ICodeEditor): void { }
listCodeEditors(): ICodeEditor[] { return []; }
addDiffEditor(_editor: IDiffEditor): void { }
removeDiffEditor(_editor: IDiffEditor): void { }
listDiffEditors(): IDiffEditor[] { return []; }
getFocusedCodeEditor(): ICodeEditor | undefined { return undefined; }
registerDecorationType(_key: string, _options: IDecorationRenderOptions, _parentTypeKey?: string): void { }
removeDecorationType(_key: string): void { }
resolveDecorationOptions(_typeKey: string, _writable: boolean): IModelDecorationOptions { return Object.create(null); }
setTransientModelProperty(_model: ITextModel, _key: string, _value: any): void { }
getTransientModelProperty(_model: ITextModel, _key: string) { }
getActiveCodeEditor(): ICodeEditor | undefined { return undefined; }
openCodeEditor(_input: IResourceInput, _source: ICodeEditor, _sideBySide?: boolean): Promise<ICodeEditor | undefined> { return Promise.resolve(undefined); }
}
export class TestWindowService implements IWindowService {
public _serviceBrand: undefined;
onDidChangeFocus: Event<boolean> = new Emitter<boolean>().event;
onDidChangeMaximize: Event<boolean>;
hasFocus = true;
readonly windowId = 0;
isFocused(): Promise<boolean> {
return Promise.resolve(false);
}
isMaximized(): Promise<boolean> {
return Promise.resolve(false);
}
enterWorkspace(_path: URI): Promise<IEnterWorkspaceResult | undefined> {
return Promise.resolve(undefined);
}
getRecentlyOpened(): Promise<IRecentlyOpened> {
return Promise.resolve({
workspaces: [],
files: []
});
}
addRecentlyOpened(_recents: IRecent[]): Promise<void> {
return Promise.resolve();
}
removeFromRecentlyOpened(_paths: URI[]): Promise<void> {
return Promise.resolve();
}
focusWindow(): Promise<void> {
return Promise.resolve();
}
maximizeWindow(): Promise<void> {
return Promise.resolve();
}
unmaximizeWindow(): Promise<void> {
return Promise.resolve();
}
minimizeWindow(): Promise<void> {
return Promise.resolve();
}
openWindow(_uris: IURIToOpen[], _options?: IOpenSettings): Promise<void> {
return Promise.resolve();
}
closeWindow(): Promise<void> {
return Promise.resolve();
}
}
export class TestLifecycleService implements ILifecycleService {
public _serviceBrand: undefined;
public phase: LifecyclePhase;
public startupKind: StartupKind;
private readonly _onBeforeShutdown = new Emitter<BeforeShutdownEvent>();
private readonly _onWillShutdown = new Emitter<WillShutdownEvent>();
private readonly _onShutdown = new Emitter<void>();
when(): Promise<void> {
return Promise.resolve();
}
public fireShutdown(reason = ShutdownReason.QUIT): void {
this._onWillShutdown.fire({
join: () => { },
reason
});
}
public fireWillShutdown(event: BeforeShutdownEvent): void {
this._onBeforeShutdown.fire(event);
}
public get onBeforeShutdown(): Event<BeforeShutdownEvent> {
return this._onBeforeShutdown.event;
}
public get onWillShutdown(): Event<WillShutdownEvent> {
return this._onWillShutdown.event;
}
public get onShutdown(): Event<void> {
return this._onShutdown.event;
}
}
export class TestWindowsService implements IWindowsService {
_serviceBrand: undefined;
readonly onWindowOpen: Event<number> = Event.None;
readonly onWindowFocus: Event<number> = Event.None;
readonly onWindowBlur: Event<number> = Event.None;
readonly onWindowMaximize: Event<number> = Event.None;
readonly onWindowUnmaximize: Event<number> = Event.None;
readonly onRecentlyOpenedChange: Event<void> = Event.None;
isFocused(_windowId: number): Promise<boolean> {
return Promise.resolve(false);
}
enterWorkspace(_windowId: number, _path: URI): Promise<IEnterWorkspaceResult | undefined> {
return Promise.resolve(undefined);
}
addRecentlyOpened(_recents: IRecent[]): Promise<void> {
return Promise.resolve();
}
removeFromRecentlyOpened(_paths: URI[]): Promise<void> {
return Promise.resolve();
}
clearRecentlyOpened(): Promise<void> {
return Promise.resolve();
}
getRecentlyOpened(_windowId: number): Promise<IRecentlyOpened> {
return Promise.resolve({
workspaces: [],
files: []
});
}
focusWindow(_windowId: number): Promise<void> {
return Promise.resolve();
}
closeWindow(_windowId: number): Promise<void> {
return Promise.resolve();
}
isMaximized(_windowId: number): Promise<boolean> {
return Promise.resolve(false);
}
maximizeWindow(_windowId: number): Promise<void> {
return Promise.resolve();
}
minimizeWindow(_windowId: number): Promise<void> {
return Promise.resolve();
}
unmaximizeWindow(_windowId: number): Promise<void> {
return Promise.resolve();
}
// Global methods
openWindow(_windowId: number, _uris: IURIToOpen[], _options: IOpenSettings): Promise<void> {
return Promise.resolve();
}
openExtensionDevelopmentHostWindow(args: ParsedArgs, env: IProcessEnvironment): Promise<void> {
return Promise.resolve();
}
getWindows(): Promise<{ id: number; workspace?: IWorkspaceIdentifier; folderUri?: ISingleFolderWorkspaceIdentifier; title: string; filename?: string; }[]> {
throw new Error('not implemented');
}
getActiveWindowId(): Promise<number | undefined> {
return Promise.resolve(undefined);
}
}
export class TestTextResourceConfigurationService implements ITextResourceConfigurationService {
_serviceBrand: undefined;
constructor(private configurationService = new TestConfigurationService()) {
}
public onDidChangeConfiguration() {
return { dispose() { } };
}
getValue<T>(resource: URI, arg2?: any, arg3?: any): T {
const position: IPosition | null = EditorPosition.isIPosition(arg2) ? arg2 : null;
const section: string | undefined = position ? (typeof arg3 === 'string' ? arg3 : undefined) : (typeof arg2 === 'string' ? arg2 : undefined);
return this.configurationService.getValue(section, { resource });
}
}
export class TestTextResourcePropertiesService implements ITextResourcePropertiesService {
_serviceBrand: undefined;
constructor(
@IConfigurationService private readonly configurationService: IConfigurationService,
) {
}
getEOL(resource: URI): string {
const filesConfiguration = this.configurationService.getValue<{ eol: string }>('files');
if (filesConfiguration && filesConfiguration.eol) {
if (filesConfiguration.eol !== 'auto') {
return filesConfiguration.eol;
}
}
return (isLinux || isMacintosh) ? '\n' : '\r\n';
}
}
export class TestSharedProcessService implements ISharedProcessService {
_serviceBrand: undefined;
getChannel(channelName: string): any {
return undefined;
}
registerChannel(channelName: string, channel: any): void { }
async toggleSharedProcessWindow(): Promise<void> { }
async whenSharedProcessReady(): Promise<void> { }
}
export class RemoteFileSystemProvider implements IFileSystemProvider {
constructor(private readonly diskFileSystemProvider: IFileSystemProvider, private readonly remoteAuthority: string) { }
readonly capabilities: FileSystemProviderCapabilities = this.diskFileSystemProvider.capabilities;
readonly onDidChangeCapabilities: Event<void> = this.diskFileSystemProvider.onDidChangeCapabilities;
readonly onDidChangeFile: Event<IFileChange[]> = Event.map(this.diskFileSystemProvider.onDidChangeFile, changes => changes.map(c => { c.resource = c.resource.with({ scheme: Schemas.vscodeRemote, authority: this.remoteAuthority }); return c; }));
watch(resource: URI, opts: IWatchOptions): IDisposable { return this.diskFileSystemProvider.watch(this.toFileResource(resource), opts); }
stat(resource: URI): Promise<IStat> { return this.diskFileSystemProvider.stat(this.toFileResource(resource)); }
mkdir(resource: URI): Promise<void> { return this.diskFileSystemProvider.mkdir(this.toFileResource(resource)); }
readdir(resource: URI): Promise<[string, FileType][]> { return this.diskFileSystemProvider.readdir(this.toFileResource(resource)); }
delete(resource: URI, opts: FileDeleteOptions): Promise<void> { return this.diskFileSystemProvider.delete(this.toFileResource(resource), opts); }
rename(from: URI, to: URI, opts: FileOverwriteOptions): Promise<void> { return this.diskFileSystemProvider.rename(this.toFileResource(from), this.toFileResource(to), opts); }
copy(from: URI, to: URI, opts: FileOverwriteOptions): Promise<void> { return this.diskFileSystemProvider.copy!(this.toFileResource(from), this.toFileResource(to), opts); }
readFile(resource: URI): Promise<Uint8Array> { return this.diskFileSystemProvider.readFile!(this.toFileResource(resource)); }
writeFile(resource: URI, content: Uint8Array, opts: FileWriteOptions): Promise<void> { return this.diskFileSystemProvider.writeFile!(this.toFileResource(resource), content, opts); }
open(resource: URI, opts: FileOpenOptions): Promise<number> { return this.diskFileSystemProvider.open!(this.toFileResource(resource), opts); }
close(fd: number): Promise<void> { return this.diskFileSystemProvider.close!(fd); }
read(fd: number, pos: number, data: Uint8Array, offset: number, length: number): Promise<number> { return this.diskFileSystemProvider.read!(fd, pos, data, offset, length); }
write(fd: number, pos: number, data: Uint8Array, offset: number, length: number): Promise<number> { return this.diskFileSystemProvider.write!(fd, pos, data, offset, length); }
private toFileResource(resource: URI): URI { return resource.with({ scheme: Schemas.file, authority: '' }); }
}
export const productService: IProductService = { _serviceBrand: undefined, ...product };
export class TestHostService implements IHostService {
_serviceBrand: undefined;
windowCount = Promise.resolve(1);
async restart(): Promise<void> { }
async reload(): Promise<void> { }
async closeWorkspace(): Promise<void> { }
async openEmptyWindow(options?: { reuse?: boolean, remoteAuthority?: string }): Promise<void> { }
async toggleFullScreen(): Promise<void> { }
}
| src/vs/workbench/test/workbenchTestServices.ts | 1 | https://github.com/microsoft/vscode/commit/23f2275c23aeebf5e22f3d19a20528c8ba48c570 | [
0.9906216859817505,
0.007062929216772318,
0.0001647273893468082,
0.00017348540131933987,
0.08168549835681915
] |
{
"id": 7,
"code_window": [
"import { timeout } from 'vs/base/common/async';\n",
"import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';\n",
"import { ViewletDescriptor, Viewlet } from 'vs/workbench/browser/viewlet';\n",
"import { IViewlet } from 'vs/workbench/common/viewlet';\n",
"import { IStorageService, InMemoryStorageService } from 'vs/platform/storage/common/storage';\n",
"import { isLinux, isMacintosh, IProcessEnvironment } from 'vs/base/common/platform';\n",
"import { LabelService } from 'vs/workbench/services/label/common/labelService';\n",
"import { IDimension } from 'vs/platform/layout/browser/layoutService';\n",
"import { Part } from 'vs/workbench/browser/part';\n",
"import { IPanelService } from 'vs/workbench/services/panel/common/panelService';\n",
"import { IPanel } from 'vs/workbench/common/panel';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { isLinux, isMacintosh } from 'vs/base/common/platform';\n"
],
"file_path": "src/vs/workbench/test/workbenchTestServices.ts",
"type": "replace",
"edit_start_line_idx": 73
} | <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M14.4198 0L15.2504 4.15289L18.7742 1.80367L22.1963 5.22578L19.8471 8.74964L24 9.58022V14.4198L19.8471 15.2504L22.1963 18.7742L18.7742 22.1963L15.2504 19.8471L14.4198 24H9.5802L8.74962 19.8471L5.22579 22.1963L1.80368 18.7742L4.15291 15.2504L0 14.4198V9.58022L4.1529 8.74964L1.80367 5.2258L5.22578 1.80369L8.74963 4.15292L9.5802 3.68124e-05L14.4198 0ZM18.2347 10.184L17.6927 8.87549L19.9795 5.44529L18.5547 4.02052L15.1245 6.30732L13.816 5.76534L13.0075 1.72278L10.9925 1.7228L10.184 5.76536L8.87549 6.30734L5.4453 4.02055L4.02053 5.44531L6.30734 8.87553L5.7653 10.184L1.72277 10.9926V13.0075L5.7653 13.816L6.30735 15.1245L4.02053 18.5547L5.4453 19.9795L8.87551 17.6927L10.184 18.2347L10.9925 22.2772H13.0075L13.816 18.2347L15.1245 17.6927L18.5547 19.9795L19.9795 18.5547L17.6927 15.1245L18.2347 13.816L22.2772 13.0075V10.9926L18.2347 10.184ZM13.7143 12C13.7143 12.9468 12.9468 13.7143 12 13.7143C11.0532 13.7143 10.2857 12.9468 10.2857 12C10.2857 11.0532 11.0532 10.2857 12 10.2857C12.9468 10.2857 13.7143 11.0532 13.7143 12ZM15.4286 12C15.4286 13.8935 13.8935 15.4286 12 15.4286C10.1065 15.4286 8.57143 13.8935 8.57143 12C8.57143 10.1065 10.1065 8.57143 12 8.57143C13.8935 8.57143 15.4286 10.1065 15.4286 12Z" fill="#F4F4F4"/>
</svg>
| src/vs/workbench/browser/parts/activitybar/media/settings-activity-bar.svg | 0 | https://github.com/microsoft/vscode/commit/23f2275c23aeebf5e22f3d19a20528c8ba48c570 | [
0.00021503263269551098,
0.00021503263269551098,
0.00021503263269551098,
0.00021503263269551098,
0
] |
{
"id": 7,
"code_window": [
"import { timeout } from 'vs/base/common/async';\n",
"import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';\n",
"import { ViewletDescriptor, Viewlet } from 'vs/workbench/browser/viewlet';\n",
"import { IViewlet } from 'vs/workbench/common/viewlet';\n",
"import { IStorageService, InMemoryStorageService } from 'vs/platform/storage/common/storage';\n",
"import { isLinux, isMacintosh, IProcessEnvironment } from 'vs/base/common/platform';\n",
"import { LabelService } from 'vs/workbench/services/label/common/labelService';\n",
"import { IDimension } from 'vs/platform/layout/browser/layoutService';\n",
"import { Part } from 'vs/workbench/browser/part';\n",
"import { IPanelService } from 'vs/workbench/services/panel/common/panelService';\n",
"import { IPanel } from 'vs/workbench/common/panel';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { isLinux, isMacintosh } from 'vs/base/common/platform';\n"
],
"file_path": "src/vs/workbench/test/workbenchTestServices.ts",
"type": "replace",
"edit_start_line_idx": 73
} | /*---------------------------------------------------------------------------------------------
* 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 * as vscode from 'vscode';
import { closeAllEditors, pathEquals } from '../utils';
import { join } from 'path';
suite('workspace-namespace', () => {
teardown(closeAllEditors);
test('rootPath', () => {
assert.ok(pathEquals(vscode.workspace.rootPath!, join(__dirname, '../../testWorkspace')));
});
test('workspaceFile', () => {
assert.ok(pathEquals(vscode.workspace.workspaceFile!.fsPath, join(__dirname, '../../testworkspace.code-workspace')));
});
test('workspaceFolders', () => {
assert.equal(vscode.workspace.workspaceFolders!.length, 2);
assert.ok(pathEquals(vscode.workspace.workspaceFolders![0].uri.fsPath, join(__dirname, '../../testWorkspace')));
assert.ok(pathEquals(vscode.workspace.workspaceFolders![1].uri.fsPath, join(__dirname, '../../testWorkspace2')));
assert.ok(pathEquals(vscode.workspace.workspaceFolders![1].name, 'Test Workspace 2'));
});
test('getWorkspaceFolder', () => {
const folder = vscode.workspace.getWorkspaceFolder(vscode.Uri.file(join(__dirname, '../../testWorkspace2/far.js')));
assert.ok(!!folder);
if (folder) {
assert.ok(pathEquals(folder.uri.fsPath, join(__dirname, '../../testWorkspace2')));
}
});
});
| extensions/vscode-api-tests/src/workspace-tests/workspace.test.ts | 0 | https://github.com/microsoft/vscode/commit/23f2275c23aeebf5e22f3d19a20528c8ba48c570 | [
0.00017663443577475846,
0.000173854103195481,
0.00017215838306583464,
0.00017331179697066545,
0.0000017016785704981885
] |
{
"id": 7,
"code_window": [
"import { timeout } from 'vs/base/common/async';\n",
"import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';\n",
"import { ViewletDescriptor, Viewlet } from 'vs/workbench/browser/viewlet';\n",
"import { IViewlet } from 'vs/workbench/common/viewlet';\n",
"import { IStorageService, InMemoryStorageService } from 'vs/platform/storage/common/storage';\n",
"import { isLinux, isMacintosh, IProcessEnvironment } from 'vs/base/common/platform';\n",
"import { LabelService } from 'vs/workbench/services/label/common/labelService';\n",
"import { IDimension } from 'vs/platform/layout/browser/layoutService';\n",
"import { Part } from 'vs/workbench/browser/part';\n",
"import { IPanelService } from 'vs/workbench/services/panel/common/panelService';\n",
"import { IPanel } from 'vs/workbench/common/panel';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { isLinux, isMacintosh } from 'vs/base/common/platform';\n"
],
"file_path": "src/vs/workbench/test/workbenchTestServices.ts",
"type": "replace",
"edit_start_line_idx": 73
} | /*---------------------------------------------------------------------------------------------
* 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 { URI } from 'vs/base/common/uri';
import { MainThreadDocumentContentProviders } from 'vs/workbench/api/browser/mainThreadDocumentContentProviders';
import { TextModel } from 'vs/editor/common/model/textModel';
import { mock } from 'vs/workbench/test/electron-browser/api/mock';
import { IModelService } from 'vs/editor/common/services/modelService';
import { IEditorWorkerService } from 'vs/editor/common/services/editorWorkerService';
import { TestRPCProtocol } from 'vs/workbench/test/electron-browser/api/testRPCProtocol';
import { TextEdit } from 'vs/editor/common/modes';
suite('MainThreadDocumentContentProviders', function () {
test('events are processed properly', function () {
let uri = URI.parse('test:uri');
let model = TextModel.createFromString('1', undefined, undefined, uri);
let providers = new MainThreadDocumentContentProviders(new TestRPCProtocol(), null!, null!,
new class extends mock<IModelService>() {
getModel(_uri: URI) {
assert.equal(uri.toString(), _uri.toString());
return model;
}
},
new class extends mock<IEditorWorkerService>() {
computeMoreMinimalEdits(_uri: URI, data: TextEdit[] | undefined) {
assert.equal(model.getValue(), '1');
return Promise.resolve(data);
}
},
);
return new Promise((resolve, reject) => {
let expectedEvents = 1;
model.onDidChangeContent(e => {
expectedEvents -= 1;
try {
assert.ok(expectedEvents >= 0);
} catch (err) {
reject(err);
}
if (model.getValue() === '1\n2\n3') {
resolve();
}
});
providers.$onVirtualDocumentChange(uri, '1\n2');
providers.$onVirtualDocumentChange(uri, '1\n2\n3');
});
});
});
| src/vs/workbench/test/electron-browser/api/mainThreadDocumentContentProviders.test.ts | 0 | https://github.com/microsoft/vscode/commit/23f2275c23aeebf5e22f3d19a20528c8ba48c570 | [
0.00017590199422556907,
0.0001715585240162909,
0.00016693635552655905,
0.00017220378504134715,
0.0000035441230465949047
] |
{
"id": 8,
"code_window": [
"\t// Global methods\n",
"\topenWindow(_windowId: number, _uris: IURIToOpen[], _options: IOpenSettings): Promise<void> {\n",
"\t\treturn Promise.resolve();\n",
"\t}\n",
"\n",
"\topenExtensionDevelopmentHostWindow(args: ParsedArgs, env: IProcessEnvironment): Promise<void> {\n",
"\t\treturn Promise.resolve();\n",
"\t}\n",
"\n",
"\tgetWindows(): Promise<{ id: number; workspace?: IWorkspaceIdentifier; folderUri?: ISingleFolderWorkspaceIdentifier; title: string; filename?: string; }[]> {\n",
"\t\tthrow new Error('not implemented');\n",
"\t}\n",
"\n",
"\tgetActiveWindowId(): Promise<number | undefined> {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/test/workbenchTestServices.ts",
"type": "replace",
"edit_start_line_idx": 1348
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { URI } from 'vs/base/common/uri';
import * as browser from 'vs/base/browser/browser';
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { Event } from 'vs/base/common/event';
import { ILogService } from 'vs/platform/log/common/log';
import { Disposable } from 'vs/base/common/lifecycle';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import { IWindowService, IEnterWorkspaceResult, IURIToOpen, IWindowsService, IOpenSettings, IWindowSettings } from 'vs/platform/windows/common/windows';
import { IWorkspaceIdentifier, ISingleFolderWorkspaceIdentifier } from 'vs/platform/workspaces/common/workspaces';
import { IRecentlyOpened, IRecent, isRecentFile, isRecentFolder } from 'vs/platform/history/common/history';
import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
import { addDisposableListener, EventType } from 'vs/base/browser/dom';
import { IEditorService, IResourceEditor } from 'vs/workbench/services/editor/common/editorService';
import { pathsToEditors } from 'vs/workbench/common/editor';
import { IFileService } from 'vs/platform/files/common/files';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ParsedArgs } from 'vs/platform/environment/common/environment';
import { IProcessEnvironment } from 'vs/base/common/platform';
import { toStoreData, restoreRecentlyOpened } from 'vs/platform/history/common/historyStorage';
//#region Window
export class SimpleWindowService extends Disposable implements IWindowService {
_serviceBrand: undefined;
readonly onDidChangeFocus: Event<boolean> = Event.None;
readonly onDidChangeMaximize: Event<boolean> = Event.None;
readonly hasFocus = true;
readonly windowId = 0;
static readonly RECENTLY_OPENED_KEY = 'recently.opened';
constructor(
@IEditorService private readonly editorService: IEditorService,
@IFileService private readonly fileService: IFileService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@IStorageService private readonly storageService: IStorageService,
@IWorkspaceContextService private readonly workspaceService: IWorkspaceContextService,
@ILogService private readonly logService: ILogService,
) {
super();
this.addWorkspaceToRecentlyOpened();
this.registerListeners();
}
private addWorkspaceToRecentlyOpened(): void {
const workspace = this.workspaceService.getWorkspace();
switch (this.workspaceService.getWorkbenchState()) {
case WorkbenchState.FOLDER:
this.addRecentlyOpened([{ folderUri: workspace.folders[0].uri }]);
break;
case WorkbenchState.WORKSPACE:
this.addRecentlyOpened([{ workspace: { id: workspace.id, configPath: workspace.configuration! } }]);
break;
}
}
private registerListeners(): void {
this._register(addDisposableListener(document, EventType.FULLSCREEN_CHANGE, () => {
if (document.fullscreenElement || (<any>document).webkitFullscreenElement) {
browser.setFullscreen(true);
} else {
browser.setFullscreen(false);
}
}));
this._register(addDisposableListener(document, EventType.WK_FULLSCREEN_CHANGE, () => {
if (document.fullscreenElement || (<any>document).webkitFullscreenElement || (<any>document).webkitIsFullScreen) {
browser.setFullscreen(true);
} else {
browser.setFullscreen(false);
}
}));
}
isFocused(): Promise<boolean> {
return Promise.resolve(this.hasFocus);
}
isMaximized(): Promise<boolean> {
return Promise.resolve(false);
}
enterWorkspace(_path: URI): Promise<IEnterWorkspaceResult | undefined> {
return Promise.resolve(undefined);
}
async getRecentlyOpened(): Promise<IRecentlyOpened> {
const recentlyOpenedRaw = this.storageService.get(SimpleWindowService.RECENTLY_OPENED_KEY, StorageScope.GLOBAL);
if (recentlyOpenedRaw) {
return restoreRecentlyOpened(JSON.parse(recentlyOpenedRaw), this.logService);
}
return { workspaces: [], files: [] };
}
async addRecentlyOpened(recents: IRecent[]): Promise<void> {
const recentlyOpened = await this.getRecentlyOpened();
recents.forEach(recent => {
if (isRecentFile(recent)) {
this.doRemoveFromRecentlyOpened(recentlyOpened, [recent.fileUri]);
recentlyOpened.files.unshift(recent);
} else if (isRecentFolder(recent)) {
this.doRemoveFromRecentlyOpened(recentlyOpened, [recent.folderUri]);
recentlyOpened.workspaces.unshift(recent);
} else {
this.doRemoveFromRecentlyOpened(recentlyOpened, [recent.workspace.configPath]);
recentlyOpened.workspaces.unshift(recent);
}
});
return this.saveRecentlyOpened(recentlyOpened);
}
async removeFromRecentlyOpened(paths: URI[]): Promise<void> {
const recentlyOpened = await this.getRecentlyOpened();
this.doRemoveFromRecentlyOpened(recentlyOpened, paths);
return this.saveRecentlyOpened(recentlyOpened);
}
private doRemoveFromRecentlyOpened(recentlyOpened: IRecentlyOpened, paths: URI[]): void {
recentlyOpened.files = recentlyOpened.files.filter(file => {
return !paths.some(path => path.toString() === file.fileUri.toString());
});
recentlyOpened.workspaces = recentlyOpened.workspaces.filter(workspace => {
return !paths.some(path => path.toString() === (isRecentFolder(workspace) ? workspace.folderUri.toString() : workspace.workspace.configPath.toString()));
});
}
private async saveRecentlyOpened(data: IRecentlyOpened): Promise<void> {
return this.storageService.store(SimpleWindowService.RECENTLY_OPENED_KEY, JSON.stringify(toStoreData(data)), StorageScope.GLOBAL);
}
focusWindow(): Promise<void> {
return Promise.resolve();
}
maximizeWindow(): Promise<void> {
return Promise.resolve();
}
unmaximizeWindow(): Promise<void> {
return Promise.resolve();
}
minimizeWindow(): Promise<void> {
return Promise.resolve();
}
async openWindow(_uris: IURIToOpen[], _options?: IOpenSettings): Promise<void> {
const { openFolderInNewWindow } = this.shouldOpenNewWindow(_options);
for (let i = 0; i < _uris.length; i++) {
const uri = _uris[i];
if ('folderUri' in uri) {
const newAddress = `${document.location.origin}${document.location.pathname}?folder=${uri.folderUri.path}`;
if (openFolderInNewWindow) {
window.open(newAddress);
} else {
window.location.href = newAddress;
}
}
if ('workspaceUri' in uri) {
const newAddress = `${document.location.origin}${document.location.pathname}?workspace=${uri.workspaceUri.path}`;
if (openFolderInNewWindow) {
window.open(newAddress);
} else {
window.location.href = newAddress;
}
}
if ('fileUri' in uri) {
const inputs: IResourceEditor[] = await pathsToEditors([uri], this.fileService);
this.editorService.openEditors(inputs);
}
}
return Promise.resolve();
}
private shouldOpenNewWindow(_options: IOpenSettings = {}): { openFolderInNewWindow: boolean } {
const windowConfig = this.configurationService.getValue<IWindowSettings>('window');
const openFolderInNewWindowConfig = (windowConfig && windowConfig.openFoldersInNewWindow) || 'default' /* default */;
let openFolderInNewWindow = !!_options.forceNewWindow && !_options.forceReuseWindow;
if (!_options.forceNewWindow && !_options.forceReuseWindow && (openFolderInNewWindowConfig === 'on' || openFolderInNewWindowConfig === 'off')) {
openFolderInNewWindow = (openFolderInNewWindowConfig === 'on');
}
return { openFolderInNewWindow };
}
closeWindow(): Promise<void> {
window.close();
return Promise.resolve();
}
}
registerSingleton(IWindowService, SimpleWindowService);
//#endregion
//#region Window
export class SimpleWindowsService implements IWindowsService {
_serviceBrand: undefined;
readonly onWindowOpen: Event<number> = Event.None;
readonly onWindowFocus: Event<number> = Event.None;
readonly onWindowBlur: Event<number> = Event.None;
readonly onWindowMaximize: Event<number> = Event.None;
readonly onWindowUnmaximize: Event<number> = Event.None;
readonly onRecentlyOpenedChange: Event<void> = Event.None;
isFocused(_windowId: number): Promise<boolean> {
return Promise.resolve(true);
}
enterWorkspace(_windowId: number, _path: URI): Promise<IEnterWorkspaceResult | undefined> {
return Promise.resolve(undefined);
}
addRecentlyOpened(recents: IRecent[]): Promise<void> {
return Promise.resolve();
}
removeFromRecentlyOpened(_paths: URI[]): Promise<void> {
return Promise.resolve();
}
clearRecentlyOpened(): Promise<void> {
return Promise.resolve();
}
getRecentlyOpened(_windowId: number): Promise<IRecentlyOpened> {
return Promise.resolve({
workspaces: [],
files: []
});
}
focusWindow(_windowId: number): Promise<void> {
return Promise.resolve();
}
closeWindow(_windowId: number): Promise<void> {
return Promise.resolve();
}
isMaximized(_windowId: number): Promise<boolean> {
return Promise.resolve(false);
}
maximizeWindow(_windowId: number): Promise<void> {
return Promise.resolve();
}
minimizeWindow(_windowId: number): Promise<void> {
return Promise.resolve();
}
unmaximizeWindow(_windowId: number): Promise<void> {
return Promise.resolve();
}
// Global methods
openWindow(_windowId: number, _uris: IURIToOpen[], _options: IOpenSettings): Promise<void> {
return Promise.resolve();
}
openExtensionDevelopmentHostWindow(args: ParsedArgs, env: IProcessEnvironment): Promise<void> {
return Promise.resolve();
}
getWindows(): Promise<{ id: number; workspace?: IWorkspaceIdentifier; folderUri?: ISingleFolderWorkspaceIdentifier; title: string; filename?: string; }[]> {
return Promise.resolve([]);
}
getActiveWindowId(): Promise<number | undefined> {
return Promise.resolve(0);
}
}
registerSingleton(IWindowsService, SimpleWindowsService);
//#endregion
| src/vs/workbench/browser/web.simpleservices.ts | 1 | https://github.com/microsoft/vscode/commit/23f2275c23aeebf5e22f3d19a20528c8ba48c570 | [
0.9917473793029785,
0.046202465891838074,
0.00016469770343974233,
0.0001965664268936962,
0.1880071461200714
] |
{
"id": 8,
"code_window": [
"\t// Global methods\n",
"\topenWindow(_windowId: number, _uris: IURIToOpen[], _options: IOpenSettings): Promise<void> {\n",
"\t\treturn Promise.resolve();\n",
"\t}\n",
"\n",
"\topenExtensionDevelopmentHostWindow(args: ParsedArgs, env: IProcessEnvironment): Promise<void> {\n",
"\t\treturn Promise.resolve();\n",
"\t}\n",
"\n",
"\tgetWindows(): Promise<{ id: number; workspace?: IWorkspaceIdentifier; folderUri?: ISingleFolderWorkspaceIdentifier; title: string; filename?: string; }[]> {\n",
"\t\tthrow new Error('not implemented');\n",
"\t}\n",
"\n",
"\tgetActiveWindowId(): Promise<number | undefined> {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/test/workbenchTestServices.ts",
"type": "replace",
"edit_start_line_idx": 1348
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
export interface Command {
readonly id: string;
execute(...args: any[]): void;
}
export class CommandManager {
private readonly commands = new Map<string, vscode.Disposable>();
public dispose() {
for (const registration of this.commands.values()) {
registration.dispose();
}
this.commands.clear();
}
public register<T extends Command>(command: T): T {
this.registerCommand(command.id, command.execute, command);
return command;
}
private registerCommand(id: string, impl: (...args: any[]) => void, thisArg?: any) {
if (this.commands.has(id)) {
return;
}
this.commands.set(id, vscode.commands.registerCommand(id, impl, thisArg));
}
} | extensions/markdown-language-features/src/commandManager.ts | 0 | https://github.com/microsoft/vscode/commit/23f2275c23aeebf5e22f3d19a20528c8ba48c570 | [
0.00017601590661797673,
0.00017431681044399738,
0.00017304561333730817,
0.00017410283908247948,
0.0000011041776133424719
] |
{
"id": 8,
"code_window": [
"\t// Global methods\n",
"\topenWindow(_windowId: number, _uris: IURIToOpen[], _options: IOpenSettings): Promise<void> {\n",
"\t\treturn Promise.resolve();\n",
"\t}\n",
"\n",
"\topenExtensionDevelopmentHostWindow(args: ParsedArgs, env: IProcessEnvironment): Promise<void> {\n",
"\t\treturn Promise.resolve();\n",
"\t}\n",
"\n",
"\tgetWindows(): Promise<{ id: number; workspace?: IWorkspaceIdentifier; folderUri?: ISingleFolderWorkspaceIdentifier; title: string; filename?: string; }[]> {\n",
"\t\tthrow new Error('not implemented');\n",
"\t}\n",
"\n",
"\tgetActiveWindowId(): Promise<number | undefined> {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/test/workbenchTestServices.ts",
"type": "replace",
"edit_start_line_idx": 1348
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Disposable } from 'vs/base/common/lifecycle';
import { ILocalExtension } from 'vs/platform/extensionManagement/common/extensionManagement';
import { ILogService } from 'vs/platform/log/common/log';
import { fork, ChildProcess } from 'child_process';
import { toErrorMessage } from 'vs/base/common/errorMessage';
import { join } from 'vs/base/common/path';
import { Limiter } from 'vs/base/common/async';
import { Event } from 'vs/base/common/event';
import { Schemas } from 'vs/base/common/network';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { rimraf } from 'vs/base/node/pfs';
export class ExtensionsLifecycle extends Disposable {
private processesLimiter: Limiter<void> = new Limiter(5); // Run max 5 processes in parallel
constructor(
private environmentService: IEnvironmentService,
private logService: ILogService
) {
super();
}
async postUninstall(extension: ILocalExtension): Promise<void> {
const script = this.parseScript(extension, 'uninstall');
if (script) {
this.logService.info(extension.identifier.id, extension.manifest.version, `Running post uninstall script`);
await this.processesLimiter.queue(() =>
this.runLifecycleHook(script.script, 'uninstall', script.args, true, extension)
.then(() => this.logService.info(extension.identifier.id, extension.manifest.version, `Finished running post uninstall script`), err => this.logService.error(extension.identifier.id, extension.manifest.version, `Failed to run post uninstall script: ${err}`)));
}
return rimraf(this.getExtensionStoragePath(extension)).then(undefined, e => this.logService.error('Error while removing extension storage path', e));
}
private parseScript(extension: ILocalExtension, type: string): { script: string, args: string[] } | null {
const scriptKey = `vscode:${type}`;
if (extension.location.scheme === Schemas.file && extension.manifest && extension.manifest['scripts'] && typeof extension.manifest['scripts'][scriptKey] === 'string') {
const script = (<string>extension.manifest['scripts'][scriptKey]).split(' ');
if (script.length < 2 || script[0] !== 'node' || !script[1]) {
this.logService.warn(extension.identifier.id, extension.manifest.version, `${scriptKey} should be a node script`);
return null;
}
return { script: join(extension.location.fsPath, script[1]), args: script.slice(2) || [] };
}
return null;
}
private runLifecycleHook(lifecycleHook: string, lifecycleType: string, args: string[], timeout: boolean, extension: ILocalExtension): Promise<void> {
return new Promise<void>((c, e) => {
const extensionLifecycleProcess = this.start(lifecycleHook, lifecycleType, args, extension);
let timeoutHandler: any;
const onexit = (error?: string) => {
if (timeoutHandler) {
clearTimeout(timeoutHandler);
timeoutHandler = null;
}
if (error) {
e(error);
} else {
c(undefined);
}
};
// on error
extensionLifecycleProcess.on('error', (err) => {
onexit(toErrorMessage(err) || 'Unknown');
});
// on exit
extensionLifecycleProcess.on('exit', (code: number, signal: string) => {
onexit(code ? `post-${lifecycleType} process exited with code ${code}` : undefined);
});
if (timeout) {
// timeout: kill process after waiting for 5s
timeoutHandler = setTimeout(() => {
timeoutHandler = null;
extensionLifecycleProcess.kill();
e('timed out');
}, 5000);
}
});
}
private start(uninstallHook: string, lifecycleType: string, args: string[], extension: ILocalExtension): ChildProcess {
const opts = {
silent: true,
execArgv: undefined
};
const extensionUninstallProcess = fork(uninstallHook, [`--type=extension-post-${lifecycleType}`, ...args], opts);
// Catch all output coming from the process
type Output = { data: string, format: string[] };
extensionUninstallProcess.stdout.setEncoding('utf8');
extensionUninstallProcess.stderr.setEncoding('utf8');
const onStdout = Event.fromNodeEventEmitter<string>(extensionUninstallProcess.stdout, 'data');
const onStderr = Event.fromNodeEventEmitter<string>(extensionUninstallProcess.stderr, 'data');
// Log output
onStdout(data => this.logService.info(extension.identifier.id, extension.manifest.version, `post-${lifecycleType}`, data));
onStderr(data => this.logService.error(extension.identifier.id, extension.manifest.version, `post-${lifecycleType}`, data));
const onOutput = Event.any(
Event.map(onStdout, o => ({ data: `%c${o}`, format: [''] })),
Event.map(onStderr, o => ({ data: `%c${o}`, format: ['color: red'] }))
);
// Debounce all output, so we can render it in the Chrome console as a group
const onDebouncedOutput = Event.debounce<Output>(onOutput, (r, o) => {
return r
? { data: r.data + o.data, format: [...r.format, ...o.format] }
: { data: o.data, format: o.format };
}, 100);
// Print out output
onDebouncedOutput(data => {
console.group(extension.identifier.id);
console.log(data.data, ...data.format);
console.groupEnd();
});
return extensionUninstallProcess;
}
private getExtensionStoragePath(extension: ILocalExtension): string {
return join(this.environmentService.globalStorageHome, extension.identifier.id.toLowerCase());
}
}
| src/vs/platform/extensionManagement/node/extensionLifecycle.ts | 0 | https://github.com/microsoft/vscode/commit/23f2275c23aeebf5e22f3d19a20528c8ba48c570 | [
0.00019036667072214186,
0.00017473365005571395,
0.00017039118392858654,
0.00017455025226809084,
0.000004642049134417903
] |
{
"id": 8,
"code_window": [
"\t// Global methods\n",
"\topenWindow(_windowId: number, _uris: IURIToOpen[], _options: IOpenSettings): Promise<void> {\n",
"\t\treturn Promise.resolve();\n",
"\t}\n",
"\n",
"\topenExtensionDevelopmentHostWindow(args: ParsedArgs, env: IProcessEnvironment): Promise<void> {\n",
"\t\treturn Promise.resolve();\n",
"\t}\n",
"\n",
"\tgetWindows(): Promise<{ id: number; workspace?: IWorkspaceIdentifier; folderUri?: ISingleFolderWorkspaceIdentifier; title: string; filename?: string; }[]> {\n",
"\t\tthrow new Error('not implemented');\n",
"\t}\n",
"\n",
"\tgetActiveWindowId(): Promise<number | undefined> {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/test/workbenchTestServices.ts",
"type": "replace",
"edit_start_line_idx": 1348
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
function entrypoint(name) {
return [{ name: name, include: [], exclude: ['vs/css', 'vs/nls'] }];
}
exports.base = [{
name: 'vs/base/common/worker/simpleWorker',
include: ['vs/editor/common/services/editorSimpleWorker'],
prepend: ['vs/loader.js'],
append: ['vs/base/worker/workerMain'],
dest: 'vs/base/worker/workerMain.js'
}];
exports.workerExtensionHost = [entrypoint('vs/workbench/services/extensions/worker/extensionHostWorker')];
exports.workbenchDesktop = require('./vs/workbench/buildfile.desktop').collectModules();
exports.workbenchWeb = require('./vs/workbench/buildfile.web').collectModules();
exports.keyboardMaps = [
entrypoint('vs/workbench/services/keybinding/browser/keyboardLayouts/layout.contribution.linux'),
entrypoint('vs/workbench/services/keybinding/browser/keyboardLayouts/layout.contribution.darwin'),
entrypoint('vs/workbench/services/keybinding/browser/keyboardLayouts/layout.contribution.win')
];
exports.code = require('./vs/code/buildfile').collectModules();
exports.entrypoint = entrypoint;
| src/buildfile.js | 0 | https://github.com/microsoft/vscode/commit/23f2275c23aeebf5e22f3d19a20528c8ba48c570 | [
0.00017614148964639753,
0.00017315131844952703,
0.000170118612004444,
0.0001731725933495909,
0.0000021940611532045295
] |
{
"id": 0,
"code_window": [
"\n",
"const rootEl = document ? document.getElementById('root') : null;\n",
"\n",
"function render(node: React.ReactElement, el: Element) {\n",
" ReactDOM.render(\n",
" process.env.STORYBOOK_EXAMPLE_APP ? <React.StrictMode>{node}</React.StrictMode> : node,\n",
" el\n",
" );\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"const render = (node: React.ReactElement, el: Element) =>\n",
" new Promise(resolve => {\n",
" ReactDOM.render(\n",
" process.env.STORYBOOK_EXAMPLE_APP ? <React.StrictMode>{node}</React.StrictMode> : node,\n",
" el,\n",
" resolve\n",
" );\n",
" });\n"
],
"file_path": "app/react/src/client/preview/render.tsx",
"type": "replace",
"edit_start_line_idx": 9
} | import { document } from 'global';
import React from 'react';
import ReactDOM from 'react-dom';
import { stripIndents } from 'common-tags';
import isReactRenderable from './element_check';
import { RenderMainArgs } from './types';
const rootEl = document ? document.getElementById('root') : null;
function render(node: React.ReactElement, el: Element) {
ReactDOM.render(
process.env.STORYBOOK_EXAMPLE_APP ? <React.StrictMode>{node}</React.StrictMode> : node,
el
);
}
export default function renderMain({
storyFn: StoryFn,
selectedKind,
selectedStory,
showMain,
showError,
forceRender,
}: RenderMainArgs) {
const element = <StoryFn />;
if (!element) {
showError({
title: `Expecting a React element from the story: "${selectedStory}" of "${selectedKind}".`,
description: stripIndents`
Did you forget to return the React element from the story?
Use "() => (<MyComp/>)" or "() => { return <MyComp/>; }" when defining the story.
`,
});
return;
}
if (!isReactRenderable(element)) {
showError({
title: `Expecting a valid React element from the story: "${selectedStory}" of "${selectedKind}".`,
description: stripIndents`
Seems like you are not returning a correct React element from the story.
Could you double check that?
`,
});
return;
}
// We need to unmount the existing set of components in the DOM node.
// Otherwise, React may not recreate instances for every story run.
// This could leads to issues like below:
// https://github.com/storybookjs/react-storybook/issues/81
// But forceRender means that it's the same story, so we want too keep the state in that case.
if (!forceRender) {
ReactDOM.unmountComponentAtNode(rootEl);
}
render(element, rootEl);
showMain();
}
| app/react/src/client/preview/render.tsx | 1 | https://github.com/storybookjs/storybook/commit/149cebaf43753ccd0a32ec606a63a73a2e0ebde0 | [
0.997913658618927,
0.4275660812854767,
0.00017404726531822234,
0.00029445585096254945,
0.49345436692237854
] |
{
"id": 0,
"code_window": [
"\n",
"const rootEl = document ? document.getElementById('root') : null;\n",
"\n",
"function render(node: React.ReactElement, el: Element) {\n",
" ReactDOM.render(\n",
" process.env.STORYBOOK_EXAMPLE_APP ? <React.StrictMode>{node}</React.StrictMode> : node,\n",
" el\n",
" );\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"const render = (node: React.ReactElement, el: Element) =>\n",
" new Promise(resolve => {\n",
" ReactDOM.render(\n",
" process.env.STORYBOOK_EXAMPLE_APP ? <React.StrictMode>{node}</React.StrictMode> : node,\n",
" el,\n",
" resolve\n",
" );\n",
" });\n"
],
"file_path": "app/react/src/client/preview/render.tsx",
"type": "replace",
"edit_start_line_idx": 9
} | <style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
h1, h2 {
font-weight: normal;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
<div id="app">
<h1>Welcome to Storybook for Marko</h1>
</div>
| app/marko/src/demo/Welcome.marko | 0 | https://github.com/storybookjs/storybook/commit/149cebaf43753ccd0a32ec606a63a73a2e0ebde0 | [
0.00017587850743439049,
0.0001720358122838661,
0.00016864712233655155,
0.0001718088169582188,
0.0000026816101126314607
] |
{
"id": 0,
"code_window": [
"\n",
"const rootEl = document ? document.getElementById('root') : null;\n",
"\n",
"function render(node: React.ReactElement, el: Element) {\n",
" ReactDOM.render(\n",
" process.env.STORYBOOK_EXAMPLE_APP ? <React.StrictMode>{node}</React.StrictMode> : node,\n",
" el\n",
" );\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"const render = (node: React.ReactElement, el: Element) =>\n",
" new Promise(resolve => {\n",
" ReactDOM.render(\n",
" process.env.STORYBOOK_EXAMPLE_APP ? <React.StrictMode>{node}</React.StrictMode> : node,\n",
" el,\n",
" resolve\n",
" );\n",
" });\n"
],
"file_path": "app/react/src/client/preview/render.tsx",
"type": "replace",
"edit_start_line_idx": 9
} | import React from 'react';
import { Source, SourceError } from './Source';
import { DocsPageWrapper } from './DocsPage';
export default {
title: 'Docs|Source',
component: Source,
decorators: [getStory => <DocsPageWrapper>{getStory()}</DocsPageWrapper>],
};
const jsxCode = `
<MyComponent boolProp scalarProp={1} complexProp={{ foo: 1, bar: '2' }}>
<SomeOtherComponent funcProp={(a) => a.id} />
</MyComponent>
`.trim();
const jsxProps = {};
export const jsx = () => <Source code={jsxCode} language="jsx" />;
const cssCode = `
@-webkit-keyframes blinker {
from { opacity: 1.0; }
to { opacity: 0.0; }
}
.waitingForConnection {
-webkit-animation-name: blinker;
-webkit-animation-iteration-count: infinite;
-webkit-animation-timing-function: cubic-bezier(.5, 0, 1, 1);
-webkit-animation-duration: 1.7s;
}
`.trim();
export const css = () => <Source code={cssCode} language="css" />;
export const noStory = () => <Source error={SourceError.NO_STORY} />;
noStory.story = { name: 'no story' };
export const sourceUnavailable = () => <Source error={SourceError.SOURCE_UNAVAILABLE} />;
sourceUnavailable.story = { name: 'source unavailable' };
| lib/components/src/blocks/Source.stories.tsx | 0 | https://github.com/storybookjs/storybook/commit/149cebaf43753ccd0a32ec606a63a73a2e0ebde0 | [
0.00017616483091842383,
0.00017303376807831228,
0.0001680068817222491,
0.00017404741083737463,
0.000002787311814245186
] |
{
"id": 0,
"code_window": [
"\n",
"const rootEl = document ? document.getElementById('root') : null;\n",
"\n",
"function render(node: React.ReactElement, el: Element) {\n",
" ReactDOM.render(\n",
" process.env.STORYBOOK_EXAMPLE_APP ? <React.StrictMode>{node}</React.StrictMode> : node,\n",
" el\n",
" );\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"const render = (node: React.ReactElement, el: Element) =>\n",
" new Promise(resolve => {\n",
" ReactDOM.render(\n",
" process.env.STORYBOOK_EXAMPLE_APP ? <React.StrictMode>{node}</React.StrictMode> : node,\n",
" el,\n",
" resolve\n",
" );\n",
" });\n"
],
"file_path": "app/react/src/client/preview/render.tsx",
"type": "replace",
"edit_start_line_idx": 9
} | <svg xmlns="http://www.w3.org/2000/svg" width="2500" height="749" viewBox="1.464 25.444 498.152 149.23"><title>background</title><title>Layer 1</title><path fill="#443642" d="M178.463 83.987c0-14.818 10.804-25.165 30.438-25.165 11.98 0 21.783 3.825 27.094 7.572.76.535 2.116 1.833 1.303 4.247-1.042 2.6-2.953 6.51-4.324 9.05-.798 1.48-2.836 1.285-3.88.756-3.783-1.917-9.988-5.16-15.688-5.758a33.378 33.378 0 0 0-4.347-.188c-5.02.112-9.214 1.855-10.691 5.685a6.74 6.74 0 0 0-.477 2.274c-.138 5.047 6.886 6.872 15.395 8.334 15.819 2.71 27.787 7.348 27.787 23.63 0 13.827-10.989 26.323-32.52 25.94-14.194-.287-24.264-5.083-29.66-9.737-.184-.158-2.238-2.25-1.137-4.766 1.26-3.239 3.387-6.951 5.056-8.922.928-1.266 3.377-1.467 4.65-.678 4.448 2.764 11.768 7.196 20.206 7.49.666.023 1.326.027 1.974.01 7.59-.184 12.182-3.062 12.086-7.91-.082-4.271-6.1-6.766-15.683-8.572-15.284-2.879-27.58-7.917-27.58-23.292M317.316 105.086c-10.778.141-20.66 3.087-20.945 11.51-.003 6.684 5.419 9.967 13.029 9.537 7.3-.703 12.867-3.869 15.32-8.07.907-1.557 1.045-7.383.99-9.873-.014-.53-1.062-1.533-1.521-1.726-2.29-.965-3.985-1.263-6.874-1.38m-35.862-33.938c5.04-4.51 15.033-11.53 30.959-11.16 21.017.437 32.12 10.29 33.154 33.86.426 9.72-.28 36.832-.448 43.587-.025.969-.353 1.639-1.659 1.664-3.461.139-11.457.084-15.131.036-1.854-.09-2.069-1.01-2.093-1.973-.016-.63-.07-2.498-.109-4.021-.021-.808-.78-.785-.974-.578-4.93 5.264-13.004 7.806-21.59 7.806-13.05 0-26.06-7.677-26.02-22.88.04-15.57 11.08-23.25 23.208-25.061 7.766-1.156 16.52-.128 23.149 2.506.424.17 1.29-.076 1.297-.677.027-1.984-.069-5.765-.45-7.557-.973-4.566-4.782-8.24-12.784-9.23-1.648-.203-3.307-.27-4.968-.138-6.361.5-14.016 5.46-17.186 7.317-.746.436-1.914.117-2.292-.37-1.85-2.39-6.5-9.38-6.866-10.497-.366-1.114.15-2.052.801-2.638l.002.004zM352.496 100.13c-.125-21.715 15.005-40.034 39.573-40.195 15.33-.1 26.467 6.85 28.431 10.128.399.77.194 1.413-.082 2.188-1.298 2.74-4.576 8.034-6.912 11.034-.995 1.278-2.075.183-3.33-.652-3.483-2.32-10.101-5.157-16.614-5.157-11.816.002-20.615 8.104-20.517 23.01.092 14.304 8.52 22.165 20.558 22.45 6.293.158 12.39-3.459 15.67-6.422 1.03-.899 2.096-.449 3.273.471 2.31 2.361 5.623 6.006 7.46 8.515 1.203 1.394.303 2.758-.13 3.306-4.984 6.307-14.61 11.615-27.349 11.687-26.674.187-39.906-18.568-40.029-40.36M479.823 139.514c1.252-.094 14.613-1.938 18.714-2.877 1.018-.232 1.38-1.088.811-1.936-2.29-3.434-8.311-13.186-14.617-21.916-5.8-8.027-11.913-15.087-13.89-17.803-.482-.66-.456-1.31.069-1.822 3.761-3.68 19.493-19.105 25.408-25.475 2.29-2.478.915-3.544-1.03-4.123-3.757-1.12-9.834-2.516-13.29-3.245-1.457-.308-3.212-.2-4.486 1.11-5.914 5.515-23.963 23.63-29.351 29.045-.97.977-1.535.76-1.54-.636-.044-10.44-.25-55.138-.623-62.49-.026-.972-1.195-1.71-1.854-1.745-3.388-.177-11.947-.228-15.32-.03-.945.107-1.848 1.07-1.93 1.884-.778 11.756.33 98.054.792 110.126.033.873.683 1.55 1.512 1.599 3.365.195 11.688.182 15.574.109 1.912 0 2.146-1.344 2.146-1.344l.288-23.157s.197-1.03.516-1.37c1.37-1.475 5.16-5.537 6.776-7.107.388-.377 1-.35 1.396.183 1.92 2.59 7.395 11.01 12.47 18.53 4.663 6.908 9.016 13.039 9.32 13.472.702 1 1.522 1.04 2.14 1.021v-.003zM252.59 139.434c1.175.039 10.09.029 14.04.024 1.33.026 2.021-.981 2.065-1.87.839-16.926.48-97.512-.05-110.237-.044-1.1-.515-1.513-1.266-1.613-3.39-.454-13.024-.348-16.112.46-.604.157-.96.616-.979 1.206-.756 32.8-.246 108.42-.086 109.852.159 1.434.909 2.128 2.39 2.178h-.002z"/><path fill="#70CADB" d="M13.997 105.78c-5.494.042-10.148-3.232-11.864-8.342a13.67 13.67 0 0 1-.178-.583c-1.87-6.544 1.756-13.39 8.255-15.582L114.45 46.35a14.128 14.128 0 0 1 3.807-.556c5.64-.044 10.422 3.302 12.18 8.52l.156.504c1.95 6.816-2.895 12.9-8.7 14.85-.004.003-1.06.36-103.662 35.391a13.49 13.49 0 0 1-4.234.721z"/><path fill="#E01765" d="M31.372 157.045c-5.537.04-10.207-3.188-11.903-8.225a13.34 13.34 0 0 1-.18-.579c-1.896-6.622 1.726-13.54 8.247-15.735L131.78 97.263c1.347-.45 2.738-.68 4.137-.693 5.552-.042 10.43 3.35 12.151 8.444l.16.53c1.007 3.521.412 7.478-1.59 10.601-1.492 2.322-6.198 4.366-6.198 4.366L35.8 156.29a14.356 14.356 0 0 1-4.428.757v-.002z"/><path fill="#E8A723" d="M118.148 157.268a12.798 12.798 0 0 1-12.255-8.723l-34.79-103.34-.174-.58c-1.885-6.59 1.74-13.464 8.237-15.654 1.3-.437 2.644-.665 3.997-.677 2.01-.015 3.955.438 5.787 1.343a12.772 12.772 0 0 1 6.449 7.392l34.787 103.331.101.332c1.954 6.842-1.663 13.72-8.16 15.91a12.935 12.935 0 0 1-3.979.666z"/><path fill="#3EB890" d="M66.435 174.674a12.803 12.803 0 0 1-12.26-8.73L19.394 62.608a12.797 12.797 0 0 1 8.051-16.23 12.96 12.96 0 0 1 3.985-.668 12.796 12.796 0 0 1 12.257 8.723l34.782 103.34a12.797 12.797 0 0 1-8.06 16.233 12.88 12.88 0 0 1-3.978.667h.004z"/><path fill="#CC2027" d="M100.997 133.996l24.258-8.294-7.93-23.55-24.286 8.207 7.958 23.637z"/><path fill="#361238" d="M49.364 151.65l24.256-8.293-7.99-23.73-24.28 8.21 8.014 23.813z"/><path fill="#65863A" d="M83.727 82.7l24.26-8.283-7.837-23.275-24.305 8.143L83.727 82.7z"/><path fill="#1A937D" d="M32.088 100.33l24.26-8.283-7.933-23.572-24.305 8.142 7.978 23.713z"/></svg> | docs/src/pages/logos/slack.svg | 0 | https://github.com/storybookjs/storybook/commit/149cebaf43753ccd0a32ec606a63a73a2e0ebde0 | [
0.00048269584658555686,
0.00048269584658555686,
0.00048269584658555686,
0.00048269584658555686,
0
] |
{
"id": 1,
"code_window": [
"\n",
"export default function renderMain({\n",
" storyFn: StoryFn,\n",
" selectedKind,\n",
" selectedStory,\n",
" showMain,\n",
" showError,\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export default async function renderMain({\n"
],
"file_path": "app/react/src/client/preview/render.tsx",
"type": "replace",
"edit_start_line_idx": 16
} | import { document } from 'global';
import React from 'react';
import ReactDOM from 'react-dom';
import { stripIndents } from 'common-tags';
import isReactRenderable from './element_check';
import { RenderMainArgs } from './types';
const rootEl = document ? document.getElementById('root') : null;
function render(node: React.ReactElement, el: Element) {
ReactDOM.render(
process.env.STORYBOOK_EXAMPLE_APP ? <React.StrictMode>{node}</React.StrictMode> : node,
el
);
}
export default function renderMain({
storyFn: StoryFn,
selectedKind,
selectedStory,
showMain,
showError,
forceRender,
}: RenderMainArgs) {
const element = <StoryFn />;
if (!element) {
showError({
title: `Expecting a React element from the story: "${selectedStory}" of "${selectedKind}".`,
description: stripIndents`
Did you forget to return the React element from the story?
Use "() => (<MyComp/>)" or "() => { return <MyComp/>; }" when defining the story.
`,
});
return;
}
if (!isReactRenderable(element)) {
showError({
title: `Expecting a valid React element from the story: "${selectedStory}" of "${selectedKind}".`,
description: stripIndents`
Seems like you are not returning a correct React element from the story.
Could you double check that?
`,
});
return;
}
// We need to unmount the existing set of components in the DOM node.
// Otherwise, React may not recreate instances for every story run.
// This could leads to issues like below:
// https://github.com/storybookjs/react-storybook/issues/81
// But forceRender means that it's the same story, so we want too keep the state in that case.
if (!forceRender) {
ReactDOM.unmountComponentAtNode(rootEl);
}
render(element, rootEl);
showMain();
}
| app/react/src/client/preview/render.tsx | 1 | https://github.com/storybookjs/storybook/commit/149cebaf43753ccd0a32ec606a63a73a2e0ebde0 | [
0.9988127946853638,
0.4251839518547058,
0.0001677854743320495,
0.07042302191257477,
0.47150757908821106
] |
{
"id": 1,
"code_window": [
"\n",
"export default function renderMain({\n",
" storyFn: StoryFn,\n",
" selectedKind,\n",
" selectedStory,\n",
" showMain,\n",
" showError,\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export default async function renderMain({\n"
],
"file_path": "app/react/src/client/preview/render.tsx",
"type": "replace",
"edit_start_line_idx": 16
} | package com.react_native;
import android.app.Application;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import java.util.Arrays;
import java.util.List;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage()
);
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
}
}
| lib/cli/test/fixtures/react_native/android/app/src/main/java/com/react_native/MainApplication.java | 0 | https://github.com/storybookjs/storybook/commit/149cebaf43753ccd0a32ec606a63a73a2e0ebde0 | [
0.0001801554171834141,
0.00017647634376771748,
0.00017366546671837568,
0.00017595465760678053,
0.0000025800729872571537
] |
{
"id": 1,
"code_window": [
"\n",
"export default function renderMain({\n",
" storyFn: StoryFn,\n",
" selectedKind,\n",
" selectedStory,\n",
" showMain,\n",
" showError,\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export default async function renderMain({\n"
],
"file_path": "app/react/src/client/preview/render.tsx",
"type": "replace",
"edit_start_line_idx": 16
} | ---
id: 'exporting-storybook'
title: 'Exporting Storybook as a Static App'
---
Storybook gives a great developer experience with its dev time features, like instant change updates via Webpack's HMR.
But Storybook is also a tool you can use to showcase your components to others.
Demos of [React Native Web](http://necolas.github.io/react-native-web/storybook/) and [React Dates](http://airbnb.io/react-dates/) are a good example for that.
For that, Storybook comes with a tool to export your storybook into a static web app. Then you can deploy it to GitHub pages or any static hosting service.
Simply add the following NPM script:
```json
{
"scripts": {
"build-storybook": "build-storybook -c .storybook -o .out"
}
}
```
Then run `yarn build-storybook`.
This will build the storybook configured in the Storybook directory into a static web app and place it inside the `.out` directory.
Now you can deploy the content in the `.out` directory wherever you want.
To test it locally:
```sh
npx http-server .out
```
## Deploying to GitHub Pages
Additionally, you can deploy Storybook directly into GitHub pages with our [storybook-deployer](https://github.com/storybookjs/storybook-deployer) tool.
Or, you can simply export your storybook into the docs directory and use it as the root for GitHub pages. Have a look at [this guide](https://github.com/blog/2233-publish-your-project-documentation-with-github-pages) for more information.
| docs/src/pages/basics/exporting-storybook/index.md | 0 | https://github.com/storybookjs/storybook/commit/149cebaf43753ccd0a32ec606a63a73a2e0ebde0 | [
0.00016436073929071426,
0.00016383531328756362,
0.0001632934872759506,
0.00016384349146392196,
4.065709617862012e-7
] |
{
"id": 1,
"code_window": [
"\n",
"export default function renderMain({\n",
" storyFn: StoryFn,\n",
" selectedKind,\n",
" selectedStory,\n",
" showMain,\n",
" showError,\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export default async function renderMain({\n"
],
"file_path": "app/react/src/client/preview/render.tsx",
"type": "replace",
"edit_start_line_idx": 16
} | import initAddons, { types } from '../modules/addons';
const PANELS = {
a11y: {
title: 'Accessibility',
paramKey: 'a11y',
},
actions: {
title: 'Actions',
paramKey: 'actions',
},
knobs: {
title: 'Knobs',
paramKey: 'knobs',
},
};
const provider = {
getElements(type) {
if (type === types.PANEL) {
return PANELS;
}
return null;
},
};
const store = {
getState: () => ({
selectedPanel: '',
}),
setState: jest.fn(),
};
describe('Addons API', () => {
describe('#getElements', () => {
it('should return provider elements', () => {
// given
const { api } = initAddons({ provider, store });
// when
const panels = api.getElements(types.PANEL);
// then
expect(panels).toBe(PANELS);
});
});
describe('#getPanels', () => {
it('should return provider panels', () => {
// given
const { api } = initAddons({ provider, store });
// when
const panels = api.getPanels();
// then
expect(panels).toBe(PANELS);
});
});
describe('#getStoryPanels', () => {
it('should return all panels by default', () => {
// given
const { api } = initAddons({ provider, store });
// when
const filteredPanels = api.getStoryPanels();
// then
expect(filteredPanels).toBe(PANELS);
});
it('should filter disabled addons', () => {
// given
const storyId = 'story 1';
const storeWithStory = {
getState: () => ({
storyId,
storiesHash: {
[storyId]: {
parameters: {
a11y: { disabled: true },
},
},
},
}),
setState: jest.fn(),
};
const { api } = initAddons({ provider, store: storeWithStory });
// when
const filteredPanels = api.getStoryPanels();
// then
expect(filteredPanels).toEqual({
actions: PANELS.actions,
knobs: PANELS.knobs,
});
});
});
describe('#getSelectedPanel', () => {
it('should return provider panels', () => {
// given
const storeWithSelectedPanel = {
getState: () => ({
selectedPanel: 'actions',
}),
setState: jest.fn(),
};
const { api } = initAddons({ provider, store: storeWithSelectedPanel });
// when
const selectedPanel = api.getSelectedPanel();
// then
expect(selectedPanel).toBe('actions');
});
it('should return first panel when selected is not a panel', () => {
// given
const storeWithSelectedPanel = {
getState: () => ({
selectedPanel: 'unknown',
}),
setState: jest.fn(),
};
const { api } = initAddons({ provider, store: storeWithSelectedPanel });
// when
const selectedPanel = api.getSelectedPanel();
// then
expect(selectedPanel).toBe('a11y');
});
});
describe('#setSelectedPanel', () => {
it('should set value inn store', () => {
// given
const setState = jest.fn();
const storeWithSelectedPanel = {
getState: () => ({
selectedPanel: 'actions',
}),
setState,
};
const { api } = initAddons({ provider, store: storeWithSelectedPanel });
expect(setState).not.toHaveBeenCalled();
// when
api.setSelectedPanel('knobs');
// then
expect(setState).toHaveBeenCalledWith({ selectedPanel: 'knobs' }, { persistence: 'session' });
});
});
});
| lib/api/src/tests/addons.test.js | 0 | https://github.com/storybookjs/storybook/commit/149cebaf43753ccd0a32ec606a63a73a2e0ebde0 | [
0.0006521948962472379,
0.00020701576431747526,
0.00016492573195137084,
0.00017014270997606218,
0.00011708115926012397
] |
{
"id": 2,
"code_window": [
" // But forceRender means that it's the same story, so we want too keep the state in that case.\n",
" if (!forceRender) {\n",
" ReactDOM.unmountComponentAtNode(rootEl);\n",
" }\n",
"\n",
" render(element, rootEl);\n",
" showMain();\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" await render(element, rootEl);\n"
],
"file_path": "app/react/src/client/preview/render.tsx",
"type": "replace",
"edit_start_line_idx": 57
} | import { document } from 'global';
import React from 'react';
import ReactDOM from 'react-dom';
import { stripIndents } from 'common-tags';
import isReactRenderable from './element_check';
import { RenderMainArgs } from './types';
const rootEl = document ? document.getElementById('root') : null;
function render(node: React.ReactElement, el: Element) {
ReactDOM.render(
process.env.STORYBOOK_EXAMPLE_APP ? <React.StrictMode>{node}</React.StrictMode> : node,
el
);
}
export default function renderMain({
storyFn: StoryFn,
selectedKind,
selectedStory,
showMain,
showError,
forceRender,
}: RenderMainArgs) {
const element = <StoryFn />;
if (!element) {
showError({
title: `Expecting a React element from the story: "${selectedStory}" of "${selectedKind}".`,
description: stripIndents`
Did you forget to return the React element from the story?
Use "() => (<MyComp/>)" or "() => { return <MyComp/>; }" when defining the story.
`,
});
return;
}
if (!isReactRenderable(element)) {
showError({
title: `Expecting a valid React element from the story: "${selectedStory}" of "${selectedKind}".`,
description: stripIndents`
Seems like you are not returning a correct React element from the story.
Could you double check that?
`,
});
return;
}
// We need to unmount the existing set of components in the DOM node.
// Otherwise, React may not recreate instances for every story run.
// This could leads to issues like below:
// https://github.com/storybookjs/react-storybook/issues/81
// But forceRender means that it's the same story, so we want too keep the state in that case.
if (!forceRender) {
ReactDOM.unmountComponentAtNode(rootEl);
}
render(element, rootEl);
showMain();
}
| app/react/src/client/preview/render.tsx | 1 | https://github.com/storybookjs/storybook/commit/149cebaf43753ccd0a32ec606a63a73a2e0ebde0 | [
0.996421217918396,
0.1432858556509018,
0.00016810350643936545,
0.0013752967352047563,
0.3482922315597534
] |
{
"id": 2,
"code_window": [
" // But forceRender means that it's the same story, so we want too keep the state in that case.\n",
" if (!forceRender) {\n",
" ReactDOM.unmountComponentAtNode(rootEl);\n",
" }\n",
"\n",
" render(element, rootEl);\n",
" showMain();\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" await render(element, rootEl);\n"
],
"file_path": "app/react/src/client/preview/render.tsx",
"type": "replace",
"edit_start_line_idx": 57
} | key.store=debug.keystore
key.alias=androiddebugkey
key.store.password=android
key.alias.password=android
| lib/cli/test/fixtures/react_native/android/keystores/debug.keystore.properties | 0 | https://github.com/storybookjs/storybook/commit/149cebaf43753ccd0a32ec606a63a73a2e0ebde0 | [
0.00017265188216697425,
0.00017265188216697425,
0.00017265188216697425,
0.00017265188216697425,
0
] |
{
"id": 2,
"code_window": [
" // But forceRender means that it's the same story, so we want too keep the state in that case.\n",
" if (!forceRender) {\n",
" ReactDOM.unmountComponentAtNode(rootEl);\n",
" }\n",
"\n",
" render(element, rootEl);\n",
" showMain();\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" await render(element, rootEl);\n"
],
"file_path": "app/react/src/client/preview/render.tsx",
"type": "replace",
"edit_start_line_idx": 57
} | import React, { Children, FunctionComponent } from 'react';
import { styled } from '@storybook/theming';
const Title = styled.div`
font-weight: ${props => props.theme.typography.weight.bold};
`;
const Desc = styled.div``;
const Message = styled.div`
padding: 30px;
text-align: center;
color: ${props => props.theme.color.defaultText};
font-size: ${props => props.theme.typography.size.s2 - 1}px;
`;
export const Placeholder: FunctionComponent = ({ children, ...props }) => {
const [title, desc] = Children.toArray(children);
return (
<Message {...props}>
<Title>{title}</Title>
{desc && <Desc>{desc}</Desc>}
</Message>
);
};
| lib/components/src/placeholder/placeholder.tsx | 0 | https://github.com/storybookjs/storybook/commit/149cebaf43753ccd0a32ec606a63a73a2e0ebde0 | [
0.00017715326976031065,
0.00017491406470071524,
0.00017129282059613615,
0.00017629606008995324,
0.000002584399226179812
] |
{
"id": 2,
"code_window": [
" // But forceRender means that it's the same story, so we want too keep the state in that case.\n",
" if (!forceRender) {\n",
" ReactDOM.unmountComponentAtNode(rootEl);\n",
" }\n",
"\n",
" render(element, rootEl);\n",
" showMain();\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" await render(element, rootEl);\n"
],
"file_path": "app/react/src/client/preview/render.tsx",
"type": "replace",
"edit_start_line_idx": 57
} | node_modules
*.log
.idea
*.iml
.vscode
*.sw*
npm-shrinkwrap.json
dist
.tern-port
*.DS_Store
.cache
junit.xml
coverage/
*.lerna_backup
build
packages/examples/automated-*
/**/LICENSE
docs/public
packs/*.tgz
package-lock.json
.nvmrc
storybook-static
integration/__image_snapshots__/__diff_output__
.jest-test-results.json
/examples/cra-kitchen-sink/src/__image_snapshots__/__diff_output__/
lib/*.jar
lib/**/dll
.expo/packager-info.json
scripts/storage
htpasswd
/false
storybook-out
/addons/docs/common/config-* | .gitignore | 0 | https://github.com/storybookjs/storybook/commit/149cebaf43753ccd0a32ec606a63a73a2e0ebde0 | [
0.00017593218944966793,
0.00017385795945301652,
0.00017253404075745493,
0.00017348281107842922,
0.000001345716782452655
] |
{
"id": 3,
"code_window": [
" }\n",
" case 'story':\n",
" default: {\n",
" if (getDecorated) {\n",
" render(renderContext);\n",
" addons.getChannel().emit(Events.STORY_RENDERED, id);\n",
" } else {\n",
" showNopreview();\n",
" addons.getChannel().emit(Events.STORY_MISSING, id);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" (async () => {\n",
" await render(renderContext);\n",
" addons.getChannel().emit(Events.STORY_RENDERED, id);\n",
" })();\n"
],
"file_path": "lib/core/src/client/preview/start.js",
"type": "replace",
"edit_start_line_idx": 228
} | import { document } from 'global';
import React from 'react';
import ReactDOM from 'react-dom';
import { stripIndents } from 'common-tags';
import isReactRenderable from './element_check';
import { RenderMainArgs } from './types';
const rootEl = document ? document.getElementById('root') : null;
function render(node: React.ReactElement, el: Element) {
ReactDOM.render(
process.env.STORYBOOK_EXAMPLE_APP ? <React.StrictMode>{node}</React.StrictMode> : node,
el
);
}
export default function renderMain({
storyFn: StoryFn,
selectedKind,
selectedStory,
showMain,
showError,
forceRender,
}: RenderMainArgs) {
const element = <StoryFn />;
if (!element) {
showError({
title: `Expecting a React element from the story: "${selectedStory}" of "${selectedKind}".`,
description: stripIndents`
Did you forget to return the React element from the story?
Use "() => (<MyComp/>)" or "() => { return <MyComp/>; }" when defining the story.
`,
});
return;
}
if (!isReactRenderable(element)) {
showError({
title: `Expecting a valid React element from the story: "${selectedStory}" of "${selectedKind}".`,
description: stripIndents`
Seems like you are not returning a correct React element from the story.
Could you double check that?
`,
});
return;
}
// We need to unmount the existing set of components in the DOM node.
// Otherwise, React may not recreate instances for every story run.
// This could leads to issues like below:
// https://github.com/storybookjs/react-storybook/issues/81
// But forceRender means that it's the same story, so we want too keep the state in that case.
if (!forceRender) {
ReactDOM.unmountComponentAtNode(rootEl);
}
render(element, rootEl);
showMain();
}
| app/react/src/client/preview/render.tsx | 1 | https://github.com/storybookjs/storybook/commit/149cebaf43753ccd0a32ec606a63a73a2e0ebde0 | [
0.00017320425831712782,
0.00016649735334794968,
0.00015957545838318765,
0.00016825761122163385,
0.000004283805537852459
] |
{
"id": 3,
"code_window": [
" }\n",
" case 'story':\n",
" default: {\n",
" if (getDecorated) {\n",
" render(renderContext);\n",
" addons.getChannel().emit(Events.STORY_RENDERED, id);\n",
" } else {\n",
" showNopreview();\n",
" addons.getChannel().emit(Events.STORY_MISSING, id);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" (async () => {\n",
" await render(renderContext);\n",
" addons.getChannel().emit(Events.STORY_RENDERED, id);\n",
" })();\n"
],
"file_path": "lib/core/src/client/preview/start.js",
"type": "replace",
"edit_start_line_idx": 228
} | import React from 'react';
import { storiesOf } from '@storybook/react';
const data = {
user: {
name: 'Joe',
},
};
storiesOf('My Component', module)
.add('state', () => <span>Hello {data.user?.name}</span>)
| lib/cli/test/fixtures/react_babel_custom_preset/stories/index.stories.js | 0 | https://github.com/storybookjs/storybook/commit/149cebaf43753ccd0a32ec606a63a73a2e0ebde0 | [
0.0001746468769852072,
0.00017390449647791684,
0.0001731621305225417,
0.00017390449647791684,
7.423732313327491e-7
] |
{
"id": 3,
"code_window": [
" }\n",
" case 'story':\n",
" default: {\n",
" if (getDecorated) {\n",
" render(renderContext);\n",
" addons.getChannel().emit(Events.STORY_RENDERED, id);\n",
" } else {\n",
" showNopreview();\n",
" addons.getChannel().emit(Events.STORY_MISSING, id);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" (async () => {\n",
" await render(renderContext);\n",
" addons.getChannel().emit(Events.STORY_RENDERED, id);\n",
" })();\n"
],
"file_path": "lib/core/src/client/preview/start.js",
"type": "replace",
"edit_start_line_idx": 228
} | <link rel="import" href="../../../../node_modules/@polymer/polymer/polymer-element.html">
<dom-module id="separated-button">
<template>
<button on-click="handleTap">
[[title]] [[counter]]
</button>
</template>
<script>
import { separatedButton } from './separated-button';
class PlaygroundButton extends separatedButton(Polymer.Element) {}
customElements.define(PlaygroundButton.is, PlaygroundButton);
</script>
</dom-module>
| examples/polymer-cli/src/separated-button/separated-button.html | 0 | https://github.com/storybookjs/storybook/commit/149cebaf43753ccd0a32ec606a63a73a2e0ebde0 | [
0.00017528250464238226,
0.00017370493151247501,
0.000172127372934483,
0.00017370493151247501,
0.0000015775658539496362
] |
{
"id": 3,
"code_window": [
" }\n",
" case 'story':\n",
" default: {\n",
" if (getDecorated) {\n",
" render(renderContext);\n",
" addons.getChannel().emit(Events.STORY_RENDERED, id);\n",
" } else {\n",
" showNopreview();\n",
" addons.getChannel().emit(Events.STORY_MISSING, id);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" (async () => {\n",
" await render(renderContext);\n",
" addons.getChannel().emit(Events.STORY_RENDERED, id);\n",
" })();\n"
],
"file_path": "lib/core/src/client/preview/start.js",
"type": "replace",
"edit_start_line_idx": 228
} | /* eslint-disable no-undef */
import { window, document } from 'global';
import { stripIndents } from 'common-tags';
const rootEl = document.getElementById('root');
const config = window.require(`${window.STORYBOOK_NAME}/config/environment`);
const app = window.require(`${window.STORYBOOK_NAME}/app`).default.create({
autoboot: false,
rootElement: rootEl,
...config.APP,
});
let lastPromise = app.boot();
let hasRendered = false;
function render(options, el) {
const { template, context = {}, element } = options;
if (hasRendered) {
lastPromise = lastPromise.then(instance => instance.destroy());
}
lastPromise = lastPromise
.then(() => {
const appInstancePrivate = app.buildInstance();
return appInstancePrivate.boot().then(() => appInstancePrivate);
})
.then(instance => {
instance.register(
'component:story-mode',
Ember.Component.extend({
layout: template || options,
...context,
})
);
const component = instance.lookup('component:story-mode');
if (element) {
component.appendTo(element);
element.appendTo(el);
} else {
component.appendTo(el);
}
hasRendered = true;
return instance;
});
}
export default function renderMain({
storyFn,
selectedKind,
selectedStory,
showMain,
showError,
// forceRender,
}) {
const element = storyFn();
if (!element) {
showError({
title: `Expecting a Ember element from the story: "${selectedStory}" of "${selectedKind}".`,
description: stripIndents`
Did you forget to return the Ember element from the story?
Use "() => hbs('{{component}}')" or "() => { return {
template: hbs\`{{component}}\`
} }" when defining the story.
`,
});
return;
}
showMain();
render(element, rootEl);
}
| app/ember/src/client/preview/render.js | 0 | https://github.com/storybookjs/storybook/commit/149cebaf43753ccd0a32ec606a63a73a2e0ebde0 | [
0.0011043214472010732,
0.00030616065487265587,
0.00016534049063920975,
0.00017139629926532507,
0.00030613577109761536
] |
{
"id": 0,
"code_window": [
" it('should ignore files with extensions listed in excludeExtensions', () => {\n",
" let testDir = {\n",
" 'dir1': {\n",
" 'file-1.ts': mockfs.file({content: 'file-1.ts content', mtime: new Date(1000)}),\n",
" 'file-1.cs': mockfs.file({content: 'file-1.cs content', mtime: new Date(1000)}),\n",
" 'file-1.d.cs': mockfs.file({content: 'file-1.d.cs content', mtime: new Date(1000)}),\n",
" 'file-2.md': mockfs.file({content: 'file-2.md content', mtime: new Date(1000)}),\n",
" 'file-3.ts': mockfs.file({content: 'file-3.ts content', mtime: new Date(1000)}),\n",
" 'file-4.d.ts': mockfs.file({content: 'file-4.d.ts content', mtime: new Date(1000)}),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" 'file-1d.cs': mockfs.file({content: 'file-1d.cs content', mtime: new Date(1000)}),\n"
],
"file_path": "tools/broccoli/tree-differ.spec.ts",
"type": "add",
"edit_start_line_idx": 153
} | /// <reference path="../typings/node/node.d.ts" />
/// <reference path="../typings/jasmine/jasmine.d.ts" />
let mockfs = require('mock-fs');
import fs = require('fs');
import {TreeDiffer} from './tree-differ';
describe('TreeDiffer', () => {
afterEach(() => mockfs.restore());
describe('diff of changed files', () => {
it('should list all files but no directories during the first diff', () => {
let testDir = {
'dir1': {
'file-1.txt': mockfs.file({content: 'file-1.txt content', mtime: new Date(1000)}),
'file-2.txt': mockfs.file({content: 'file-2.txt content', mtime: new Date(1000)}),
'subdir-1': {
'file-1.1.txt': mockfs.file({content: 'file-1.1.txt content', mtime: new Date(1000)})
},
'empty-dir': {}
}
};
mockfs(testDir);
let differ = new TreeDiffer('dir1');
let diffResult = differ.diffTree();
expect(diffResult.changedPaths)
.toEqual(['file-1.txt', 'file-2.txt', 'subdir-1/file-1.1.txt']);
expect(diffResult.removedPaths).toEqual([]);
});
it('should return empty diff if nothing has changed', () => {
let testDir = {
'dir1': {
'file-1.txt': mockfs.file({content: 'file-1.txt content', mtime: new Date(1000)}),
'file-2.txt': mockfs.file({content: 'file-2.txt content', mtime: new Date(1000)}),
'subdir-1': {
'file-1.1.txt': mockfs.file({content: 'file-1.1.txt content', mtime: new Date(1000)})
},
}
};
mockfs(testDir);
let differ = new TreeDiffer('dir1');
let diffResult = differ.diffTree();
expect(diffResult.changedPaths).not.toEqual([]);
expect(diffResult.removedPaths).toEqual([]);
diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual([]);
expect(diffResult.removedPaths).toEqual([]);
});
it('should list only changed files during the subsequent diffs', () => {
let testDir = {
'dir1': {
'file-1.txt': mockfs.file({content: 'file-1.txt content', mtime: new Date(1000)}),
'file-2.txt': mockfs.file({content: 'file-2.txt content', mtime: new Date(1000)}),
'subdir-1': {
'file-1.1.txt':
mockfs.file({content: 'file-1.1.txt content', mtime: new Date(1000)})
}
}
};
mockfs(testDir);
let differ = new TreeDiffer('dir1');
let diffResult = differ.diffTree();
expect(diffResult.changedPaths)
.toEqual(['file-1.txt', 'file-2.txt', 'subdir-1/file-1.1.txt']);
// change two files
testDir['dir1']['file-1.txt'] = mockfs.file({content: 'new content', mtime: new Date(1000)});
testDir['dir1']['subdir-1']['file-1.1.txt'] =
mockfs.file({content: 'file-1.1.txt content', mtime: new Date(9999)});
mockfs(testDir);
diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual(['file-1.txt', 'subdir-1/file-1.1.txt']);
expect(diffResult.removedPaths).toEqual([]);
// change one file
testDir['dir1']['file-1.txt'] = mockfs.file({content: 'super new', mtime: new Date(1000)});
mockfs(testDir);
diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual(['file-1.txt']);
});
it('should ignore files with extensions not listed in includeExtensions', () => {
let testDir = {
'dir1': {
'file-1.js': mockfs.file({content: 'file-1.js content', mtime: new Date(1000)}),
'file-2.md': mockfs.file({content: 'file-2.md content', mtime: new Date(1000)}),
'file-3.coffee': mockfs.file({content: 'file-3.coffee content', mtime: new Date(1000)}),
'subdir-1': {
'file-1.1.cc': mockfs.file({content: 'file-1.1.cc content', mtime: new Date(1000)})
}
}
};
mockfs(testDir);
let differ = new TreeDiffer('dir1', ['.js', '.coffee']);
let diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual(['file-1.js', 'file-3.coffee']);
// change two files
testDir['dir1']['file-1.js'] = mockfs.file({content: 'new content', mtime: new Date(1000)});
testDir['dir1']['file-3.coffee'] =
mockfs.file({content: 'new content', mtime: new Date(1000)});
testDir['dir1']['subdir-1']['file-1.1.cc'] =
mockfs.file({content: 'file-1.1.cc content', mtime: new Date(9999)});
mockfs(testDir);
diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual(['file-1.js', 'file-3.coffee']);
expect(diffResult.removedPaths).toEqual([]);
// change one file
testDir['dir1']['file-1.js'] = mockfs.file({content: 'super new', mtime: new Date(1000)});
mockfs(testDir);
diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual(['file-1.js']);
});
it('should ignore files with extensions listed in excludeExtensions', () => {
let testDir = {
'dir1': {
'file-1.ts': mockfs.file({content: 'file-1.ts content', mtime: new Date(1000)}),
'file-1.cs': mockfs.file({content: 'file-1.cs content', mtime: new Date(1000)}),
'file-1.d.cs': mockfs.file({content: 'file-1.d.cs content', mtime: new Date(1000)}),
'file-2.md': mockfs.file({content: 'file-2.md content', mtime: new Date(1000)}),
'file-3.ts': mockfs.file({content: 'file-3.ts content', mtime: new Date(1000)}),
'file-4.d.ts': mockfs.file({content: 'file-4.d.ts content', mtime: new Date(1000)}),
'subdir-1': {
'file-1.1.cc': mockfs.file({content: 'file-1.1.cc content', mtime: new Date(1000)})
}
}
};
mockfs(testDir);
let differ = new TreeDiffer('dir1', ['.ts', '.cs'], ['.d.ts', '.d.cs']);
let diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual(['file-1.cs', 'file-1.ts', 'file-3.ts']);
// change two files
testDir['dir1']['file-1.ts'] = mockfs.file({content: 'new content', mtime: new Date(1000)});
testDir['dir1']['file-1.cs'] = mockfs.file({content: 'new content', mtime: new Date(1000)});
testDir['dir1']['file-1.d.cs'] = mockfs.file({content: 'new content', mtime: new Date(1000)});
testDir['dir1']['file-3.ts'] = mockfs.file({content: 'new content', mtime: new Date(1000)});
testDir['dir1']['file-4.d.ts'] = mockfs.file({content: 'new content', mtime: new Date(1000)});
testDir['dir1']['subdir-1']['file-1.1.cc'] =
mockfs.file({content: 'file-1.1.cc content', mtime: new Date(9999)});
mockfs(testDir);
diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual(['file-1.cs', 'file-1.ts', 'file-3.ts']);
expect(diffResult.removedPaths).toEqual([]);
// change one file
testDir['dir1']['file-4.d.ts'] = mockfs.file({content: 'super new', mtime: new Date(1000)});
mockfs(testDir);
diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual([]);
});
});
describe('diff of new files', () => {
it('should detect file additions and report them as changed files', () => {
let testDir = {
'dir1':
{'file-1.txt': mockfs.file({content: 'file-1.txt content', mtime: new Date(1000)})}
};
mockfs(testDir);
let differ = new TreeDiffer('dir1');
differ.diffTree();
testDir['dir1']['file-2.txt'] = 'new file';
mockfs(testDir);
let diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual(['file-2.txt']);
});
});
it('should detect file additions mixed with file changes', () => {
let testDir = {
'dir1': {'file-1.txt': mockfs.file({content: 'file-1.txt content', mtime: new Date(1000)})}
};
mockfs(testDir);
let differ = new TreeDiffer('dir1');
differ.diffTree();
testDir['dir1']['file-1.txt'] = 'new content';
testDir['dir1']['file-2.txt'] = 'new file';
mockfs(testDir);
let diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual(['file-1.txt', 'file-2.txt']);
});
describe('diff of removed files', () => {
it('should detect file removals and report them as removed files', () => {
let testDir = {
'dir1':
{'file-1.txt': mockfs.file({content: 'file-1.txt content', mtime: new Date(1000)})}
};
mockfs(testDir);
let differ = new TreeDiffer('dir1');
differ.diffTree();
delete testDir['dir1']['file-1.txt'];
mockfs(testDir);
let diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual([]);
expect(diffResult.removedPaths).toEqual(['file-1.txt']);
});
});
it('should detect file removals mixed with file changes and additions', () => {
let testDir = {
'dir1': {
'file-1.txt': mockfs.file({content: 'file-1.txt content', mtime: new Date(1000)}),
'file-2.txt': mockfs.file({content: 'file-1.txt content', mtime: new Date(1000)})
}
};
mockfs(testDir);
let differ = new TreeDiffer('dir1');
differ.diffTree();
testDir['dir1']['file-1.txt'] = 'changed content';
delete testDir['dir1']['file-2.txt'];
testDir['dir1']['file-3.txt'] = 'new content';
mockfs(testDir);
let diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual(['file-1.txt', 'file-3.txt']);
expect(diffResult.removedPaths).toEqual(['file-2.txt']);
});
});
| tools/broccoli/tree-differ.spec.ts | 1 | https://github.com/angular/angular/commit/a58c9f83bd1a5be110a7982bab7023b209634c37 | [
0.9991230368614197,
0.8898588418960571,
0.00016685518494341522,
0.9978929162025452,
0.308093786239624
] |
{
"id": 0,
"code_window": [
" it('should ignore files with extensions listed in excludeExtensions', () => {\n",
" let testDir = {\n",
" 'dir1': {\n",
" 'file-1.ts': mockfs.file({content: 'file-1.ts content', mtime: new Date(1000)}),\n",
" 'file-1.cs': mockfs.file({content: 'file-1.cs content', mtime: new Date(1000)}),\n",
" 'file-1.d.cs': mockfs.file({content: 'file-1.d.cs content', mtime: new Date(1000)}),\n",
" 'file-2.md': mockfs.file({content: 'file-2.md content', mtime: new Date(1000)}),\n",
" 'file-3.ts': mockfs.file({content: 'file-3.ts content', mtime: new Date(1000)}),\n",
" 'file-4.d.ts': mockfs.file({content: 'file-4.d.ts content', mtime: new Date(1000)}),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" 'file-1d.cs': mockfs.file({content: 'file-1d.cs content', mtime: new Date(1000)}),\n"
],
"file_path": "tools/broccoli/tree-differ.spec.ts",
"type": "add",
"edit_start_line_idx": 153
} | library angular2.transform.reflection_remover.transformer;
import 'dart:async';
import 'package:angular2/src/transform/common/asset_reader.dart';
import 'package:angular2/src/transform/common/logging.dart' as log;
import 'package:angular2/src/transform/common/mirror_mode.dart';
import 'package:angular2/src/transform/common/names.dart';
import 'package:angular2/src/transform/common/options.dart';
import 'package:barback/barback.dart';
import 'remove_reflection_capabilities.dart';
/// Transformer responsible for removing the import and instantiation of
/// {@link ReflectionCapabilities}.
///
/// The goal of this is to break the app's dependency on dart:mirrors.
///
/// This transformer assumes that {@link DirectiveProcessor} and {@link DirectiveLinker}
/// have already been run and that a .ng_deps.dart file has been generated for
/// {@link options.entryPoint}. The instantiation of {@link ReflectionCapabilities} is
/// replaced by calling `setupReflection` in that .ng_deps.dart file.
class ReflectionRemover extends Transformer {
final TransformerOptions options;
ReflectionRemover(this.options);
@override
bool isPrimary(AssetId id) => options.reflectionEntryPoints != null &&
options.reflectionEntryPoints.contains(id.path);
@override
Future apply(Transform transform) async {
log.init(transform);
try {
var newEntryPoints = options.entryPoints.map((entryPoint) {
return new AssetId(transform.primaryInput.id.package, entryPoint)
.changeExtension(DEPS_EXTENSION);
});
var reader = new AssetReader.fromTransform(transform);
var mirrorMode = options.mirrorMode;
var writeStaticInit = options.initReflector;
if (options.modeName == TRANSFORM_DYNAMIC_MODE) {
mirrorMode = MirrorMode.debug;
writeStaticInit = false;
log.logger.info('Running in "${options.modeName}", '
'mirrorMode: ${mirrorMode}, '
'writeStaticInit: ${writeStaticInit}.');
}
var transformedCode = await removeReflectionCapabilities(
reader, transform.primaryInput.id, newEntryPoints,
mirrorMode: mirrorMode, writeStaticInit: writeStaticInit);
transform.addOutput(
new Asset.fromString(transform.primaryInput.id, transformedCode));
} catch (ex, stackTrace) {
log.logger.error('Removing reflection failed.\n'
'Exception: $ex\n'
'Stack Trace: $stackTrace');
}
}
}
| modules/angular2/src/transform/reflection_remover/transformer.dart | 0 | https://github.com/angular/angular/commit/a58c9f83bd1a5be110a7982bab7023b209634c37 | [
0.0001773253025021404,
0.00017291729454882443,
0.0001688678894424811,
0.0001731391967041418,
0.000002895954594350769
] |
{
"id": 0,
"code_window": [
" it('should ignore files with extensions listed in excludeExtensions', () => {\n",
" let testDir = {\n",
" 'dir1': {\n",
" 'file-1.ts': mockfs.file({content: 'file-1.ts content', mtime: new Date(1000)}),\n",
" 'file-1.cs': mockfs.file({content: 'file-1.cs content', mtime: new Date(1000)}),\n",
" 'file-1.d.cs': mockfs.file({content: 'file-1.d.cs content', mtime: new Date(1000)}),\n",
" 'file-2.md': mockfs.file({content: 'file-2.md content', mtime: new Date(1000)}),\n",
" 'file-3.ts': mockfs.file({content: 'file-3.ts content', mtime: new Date(1000)}),\n",
" 'file-4.d.ts': mockfs.file({content: 'file-4.d.ts content', mtime: new Date(1000)}),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" 'file-1d.cs': mockfs.file({content: 'file-1d.cs content', mtime: new Date(1000)}),\n"
],
"file_path": "tools/broccoli/tree-differ.spec.ts",
"type": "add",
"edit_start_line_idx": 153
} | <link>
<div style="width: 500px;">
<h2>Progress-linear demo</h2>
<p>
Determinate: primary
<md-progress-linear md-mode="determinate" [value]="progress" class="md-accent">
</md-progress-linear>
</p>
<p>
Determinate: accent
<md-progress-linear md-mode="determinate" [value]="progress" class="md-primary">
</md-progress-linear>
</p>
<p>
Buffer
<md-progress-linear md-mode="buffer"
[value]="progress" [buffer-value]="progress + (200 / progress)" class="md-warn">
</md-progress-linear>
</p>
<p>
Indeterminate
<md-progress-linear md-mode="indeterminate" class="md-primary">
</md-progress-linear>
</p>
<p>
Query
<md-progress-linear md-mode="query" class="md-accent">
</md-progress-linear>
</p>
<!--<md-progress-linear></md-progress-linear>-->
<p>Progress: {{progress}}</p>
<button type="button" (click)="step(10)" id="increment">Increment</button>
<button type="button" (click)="step(-10)" id="decrement">Decrement</button>
</div>
| modules/examples/src/material/progress-linear/demo_app.html | 0 | https://github.com/angular/angular/commit/a58c9f83bd1a5be110a7982bab7023b209634c37 | [
0.00017284277419093996,
0.00017144651792477816,
0.00016875151777639985,
0.00017194412066601217,
0.0000015311869674405898
] |
{
"id": 0,
"code_window": [
" it('should ignore files with extensions listed in excludeExtensions', () => {\n",
" let testDir = {\n",
" 'dir1': {\n",
" 'file-1.ts': mockfs.file({content: 'file-1.ts content', mtime: new Date(1000)}),\n",
" 'file-1.cs': mockfs.file({content: 'file-1.cs content', mtime: new Date(1000)}),\n",
" 'file-1.d.cs': mockfs.file({content: 'file-1.d.cs content', mtime: new Date(1000)}),\n",
" 'file-2.md': mockfs.file({content: 'file-2.md content', mtime: new Date(1000)}),\n",
" 'file-3.ts': mockfs.file({content: 'file-3.ts content', mtime: new Date(1000)}),\n",
" 'file-4.d.ts': mockfs.file({content: 'file-4.d.ts content', mtime: new Date(1000)}),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" 'file-1d.cs': mockfs.file({content: 'file-1d.cs content', mtime: new Date(1000)}),\n"
],
"file_path": "tools/broccoli/tree-differ.spec.ts",
"type": "add",
"edit_start_line_idx": 153
} | import {int, isBlank, isPresent, BaseException} from 'angular2/src/facade/lang';
import * as eiModule from './element_injector';
import {DirectiveBinding} from './element_injector';
import {List, StringMap} from 'angular2/src/facade/collection';
import * as viewModule from './view';
export class ElementBinder {
protoElementInjector:eiModule.ProtoElementInjector;
componentDirective:DirectiveBinding;
nestedProtoView: viewModule.AppProtoView;
hostListeners:StringMap;
parent:ElementBinder;
index:int;
distanceToParent:int;
constructor(
index:int, parent:ElementBinder, distanceToParent: int,
protoElementInjector: eiModule.ProtoElementInjector, componentDirective:DirectiveBinding) {
if (isBlank(index)) {
throw new BaseException('null index not allowed.');
}
this.protoElementInjector = protoElementInjector;
this.componentDirective = componentDirective;
this.parent = parent;
this.index = index;
this.distanceToParent = distanceToParent;
// updated later when events are bound
this.hostListeners = null;
// updated later, so we are able to resolve cycles
this.nestedProtoView = null;
}
hasStaticComponent() {
return isPresent(this.componentDirective) && isPresent(this.nestedProtoView);
}
hasDynamicComponent() {
return isPresent(this.componentDirective) && isBlank(this.nestedProtoView);
}
hasEmbeddedProtoView() {
return !isPresent(this.componentDirective) && isPresent(this.nestedProtoView);
}
}
| modules/angular2/src/core/compiler/element_binder.js | 0 | https://github.com/angular/angular/commit/a58c9f83bd1a5be110a7982bab7023b209634c37 | [
0.00017366149404551834,
0.0001721342996461317,
0.00016964109090622514,
0.00017284954083152115,
0.0000014257949487728183
] |
{
"id": 1,
"code_window": [
" let differ = new TreeDiffer('dir1', ['.ts', '.cs'], ['.d.ts', '.d.cs']);\n",
"\n",
" let diffResult = differ.diffTree();\n",
"\n",
" expect(diffResult.changedPaths).toEqual(['file-1.cs', 'file-1.ts', 'file-3.ts']);\n",
"\n",
" // change two files\n",
" testDir['dir1']['file-1.ts'] = mockfs.file({content: 'new content', mtime: new Date(1000)});\n",
" testDir['dir1']['file-1.cs'] = mockfs.file({content: 'new content', mtime: new Date(1000)});\n",
" testDir['dir1']['file-1.d.cs'] = mockfs.file({content: 'new content', mtime: new Date(1000)});\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(diffResult.changedPaths)\n",
" .toEqual(['file-1.cs', 'file-1.ts', 'file-1d.cs', 'file-3.ts']);\n"
],
"file_path": "tools/broccoli/tree-differ.spec.ts",
"type": "replace",
"edit_start_line_idx": 168
} | /// <reference path="../typings/node/node.d.ts" />
/// <reference path="../typings/jasmine/jasmine.d.ts" />
let mockfs = require('mock-fs');
import fs = require('fs');
import {TreeDiffer} from './tree-differ';
describe('TreeDiffer', () => {
afterEach(() => mockfs.restore());
describe('diff of changed files', () => {
it('should list all files but no directories during the first diff', () => {
let testDir = {
'dir1': {
'file-1.txt': mockfs.file({content: 'file-1.txt content', mtime: new Date(1000)}),
'file-2.txt': mockfs.file({content: 'file-2.txt content', mtime: new Date(1000)}),
'subdir-1': {
'file-1.1.txt': mockfs.file({content: 'file-1.1.txt content', mtime: new Date(1000)})
},
'empty-dir': {}
}
};
mockfs(testDir);
let differ = new TreeDiffer('dir1');
let diffResult = differ.diffTree();
expect(diffResult.changedPaths)
.toEqual(['file-1.txt', 'file-2.txt', 'subdir-1/file-1.1.txt']);
expect(diffResult.removedPaths).toEqual([]);
});
it('should return empty diff if nothing has changed', () => {
let testDir = {
'dir1': {
'file-1.txt': mockfs.file({content: 'file-1.txt content', mtime: new Date(1000)}),
'file-2.txt': mockfs.file({content: 'file-2.txt content', mtime: new Date(1000)}),
'subdir-1': {
'file-1.1.txt': mockfs.file({content: 'file-1.1.txt content', mtime: new Date(1000)})
},
}
};
mockfs(testDir);
let differ = new TreeDiffer('dir1');
let diffResult = differ.diffTree();
expect(diffResult.changedPaths).not.toEqual([]);
expect(diffResult.removedPaths).toEqual([]);
diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual([]);
expect(diffResult.removedPaths).toEqual([]);
});
it('should list only changed files during the subsequent diffs', () => {
let testDir = {
'dir1': {
'file-1.txt': mockfs.file({content: 'file-1.txt content', mtime: new Date(1000)}),
'file-2.txt': mockfs.file({content: 'file-2.txt content', mtime: new Date(1000)}),
'subdir-1': {
'file-1.1.txt':
mockfs.file({content: 'file-1.1.txt content', mtime: new Date(1000)})
}
}
};
mockfs(testDir);
let differ = new TreeDiffer('dir1');
let diffResult = differ.diffTree();
expect(diffResult.changedPaths)
.toEqual(['file-1.txt', 'file-2.txt', 'subdir-1/file-1.1.txt']);
// change two files
testDir['dir1']['file-1.txt'] = mockfs.file({content: 'new content', mtime: new Date(1000)});
testDir['dir1']['subdir-1']['file-1.1.txt'] =
mockfs.file({content: 'file-1.1.txt content', mtime: new Date(9999)});
mockfs(testDir);
diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual(['file-1.txt', 'subdir-1/file-1.1.txt']);
expect(diffResult.removedPaths).toEqual([]);
// change one file
testDir['dir1']['file-1.txt'] = mockfs.file({content: 'super new', mtime: new Date(1000)});
mockfs(testDir);
diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual(['file-1.txt']);
});
it('should ignore files with extensions not listed in includeExtensions', () => {
let testDir = {
'dir1': {
'file-1.js': mockfs.file({content: 'file-1.js content', mtime: new Date(1000)}),
'file-2.md': mockfs.file({content: 'file-2.md content', mtime: new Date(1000)}),
'file-3.coffee': mockfs.file({content: 'file-3.coffee content', mtime: new Date(1000)}),
'subdir-1': {
'file-1.1.cc': mockfs.file({content: 'file-1.1.cc content', mtime: new Date(1000)})
}
}
};
mockfs(testDir);
let differ = new TreeDiffer('dir1', ['.js', '.coffee']);
let diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual(['file-1.js', 'file-3.coffee']);
// change two files
testDir['dir1']['file-1.js'] = mockfs.file({content: 'new content', mtime: new Date(1000)});
testDir['dir1']['file-3.coffee'] =
mockfs.file({content: 'new content', mtime: new Date(1000)});
testDir['dir1']['subdir-1']['file-1.1.cc'] =
mockfs.file({content: 'file-1.1.cc content', mtime: new Date(9999)});
mockfs(testDir);
diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual(['file-1.js', 'file-3.coffee']);
expect(diffResult.removedPaths).toEqual([]);
// change one file
testDir['dir1']['file-1.js'] = mockfs.file({content: 'super new', mtime: new Date(1000)});
mockfs(testDir);
diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual(['file-1.js']);
});
it('should ignore files with extensions listed in excludeExtensions', () => {
let testDir = {
'dir1': {
'file-1.ts': mockfs.file({content: 'file-1.ts content', mtime: new Date(1000)}),
'file-1.cs': mockfs.file({content: 'file-1.cs content', mtime: new Date(1000)}),
'file-1.d.cs': mockfs.file({content: 'file-1.d.cs content', mtime: new Date(1000)}),
'file-2.md': mockfs.file({content: 'file-2.md content', mtime: new Date(1000)}),
'file-3.ts': mockfs.file({content: 'file-3.ts content', mtime: new Date(1000)}),
'file-4.d.ts': mockfs.file({content: 'file-4.d.ts content', mtime: new Date(1000)}),
'subdir-1': {
'file-1.1.cc': mockfs.file({content: 'file-1.1.cc content', mtime: new Date(1000)})
}
}
};
mockfs(testDir);
let differ = new TreeDiffer('dir1', ['.ts', '.cs'], ['.d.ts', '.d.cs']);
let diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual(['file-1.cs', 'file-1.ts', 'file-3.ts']);
// change two files
testDir['dir1']['file-1.ts'] = mockfs.file({content: 'new content', mtime: new Date(1000)});
testDir['dir1']['file-1.cs'] = mockfs.file({content: 'new content', mtime: new Date(1000)});
testDir['dir1']['file-1.d.cs'] = mockfs.file({content: 'new content', mtime: new Date(1000)});
testDir['dir1']['file-3.ts'] = mockfs.file({content: 'new content', mtime: new Date(1000)});
testDir['dir1']['file-4.d.ts'] = mockfs.file({content: 'new content', mtime: new Date(1000)});
testDir['dir1']['subdir-1']['file-1.1.cc'] =
mockfs.file({content: 'file-1.1.cc content', mtime: new Date(9999)});
mockfs(testDir);
diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual(['file-1.cs', 'file-1.ts', 'file-3.ts']);
expect(diffResult.removedPaths).toEqual([]);
// change one file
testDir['dir1']['file-4.d.ts'] = mockfs.file({content: 'super new', mtime: new Date(1000)});
mockfs(testDir);
diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual([]);
});
});
describe('diff of new files', () => {
it('should detect file additions and report them as changed files', () => {
let testDir = {
'dir1':
{'file-1.txt': mockfs.file({content: 'file-1.txt content', mtime: new Date(1000)})}
};
mockfs(testDir);
let differ = new TreeDiffer('dir1');
differ.diffTree();
testDir['dir1']['file-2.txt'] = 'new file';
mockfs(testDir);
let diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual(['file-2.txt']);
});
});
it('should detect file additions mixed with file changes', () => {
let testDir = {
'dir1': {'file-1.txt': mockfs.file({content: 'file-1.txt content', mtime: new Date(1000)})}
};
mockfs(testDir);
let differ = new TreeDiffer('dir1');
differ.diffTree();
testDir['dir1']['file-1.txt'] = 'new content';
testDir['dir1']['file-2.txt'] = 'new file';
mockfs(testDir);
let diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual(['file-1.txt', 'file-2.txt']);
});
describe('diff of removed files', () => {
it('should detect file removals and report them as removed files', () => {
let testDir = {
'dir1':
{'file-1.txt': mockfs.file({content: 'file-1.txt content', mtime: new Date(1000)})}
};
mockfs(testDir);
let differ = new TreeDiffer('dir1');
differ.diffTree();
delete testDir['dir1']['file-1.txt'];
mockfs(testDir);
let diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual([]);
expect(diffResult.removedPaths).toEqual(['file-1.txt']);
});
});
it('should detect file removals mixed with file changes and additions', () => {
let testDir = {
'dir1': {
'file-1.txt': mockfs.file({content: 'file-1.txt content', mtime: new Date(1000)}),
'file-2.txt': mockfs.file({content: 'file-1.txt content', mtime: new Date(1000)})
}
};
mockfs(testDir);
let differ = new TreeDiffer('dir1');
differ.diffTree();
testDir['dir1']['file-1.txt'] = 'changed content';
delete testDir['dir1']['file-2.txt'];
testDir['dir1']['file-3.txt'] = 'new content';
mockfs(testDir);
let diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual(['file-1.txt', 'file-3.txt']);
expect(diffResult.removedPaths).toEqual(['file-2.txt']);
});
});
| tools/broccoli/tree-differ.spec.ts | 1 | https://github.com/angular/angular/commit/a58c9f83bd1a5be110a7982bab7023b209634c37 | [
0.9984291195869446,
0.7364140152931213,
0.0012830878840759397,
0.9816408157348633,
0.39353933930397034
] |
{
"id": 1,
"code_window": [
" let differ = new TreeDiffer('dir1', ['.ts', '.cs'], ['.d.ts', '.d.cs']);\n",
"\n",
" let diffResult = differ.diffTree();\n",
"\n",
" expect(diffResult.changedPaths).toEqual(['file-1.cs', 'file-1.ts', 'file-3.ts']);\n",
"\n",
" // change two files\n",
" testDir['dir1']['file-1.ts'] = mockfs.file({content: 'new content', mtime: new Date(1000)});\n",
" testDir['dir1']['file-1.cs'] = mockfs.file({content: 'new content', mtime: new Date(1000)});\n",
" testDir['dir1']['file-1.d.cs'] = mockfs.file({content: 'new content', mtime: new Date(1000)});\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(diffResult.changedPaths)\n",
" .toEqual(['file-1.cs', 'file-1.ts', 'file-1d.cs', 'file-3.ts']);\n"
],
"file_path": "tools/broccoli/tree-differ.spec.ts",
"type": "replace",
"edit_start_line_idx": 168
} | import {List} from 'angular2/src/facade/collection';
import {BindingRecord} from './binding_record';
import {DirectiveIndex} from './directive_record';
export const RECORD_TYPE_SELF = 0;
export const RECORD_TYPE_CONST = 1;
export const RECORD_TYPE_PRIMITIVE_OP = 2;
export const RECORD_TYPE_PROPERTY = 3;
export const RECORD_TYPE_LOCAL = 4;
export const RECORD_TYPE_INVOKE_METHOD = 5;
export const RECORD_TYPE_INVOKE_CLOSURE = 6;
export const RECORD_TYPE_KEYED_ACCESS = 7;
export const RECORD_TYPE_PIPE = 8;
export const RECORD_TYPE_BINDING_PIPE = 9;
export const RECORD_TYPE_INTERPOLATE = 10;
export class ProtoRecord {
mode:number;
name:string;
funcOrValue:any;
args:List;
fixedArgs:List;
contextIndex:number;
directiveIndex:DirectiveIndex;
selfIndex:number;
bindingRecord:BindingRecord;
lastInBinding:boolean;
lastInDirective:boolean;
expressionAsString:string;
constructor(mode:number,
name:string,
funcOrValue,
args:List,
fixedArgs:List,
contextIndex:number,
directiveIndex:DirectiveIndex,
selfIndex:number,
bindingRecord:BindingRecord,
expressionAsString:string,
lastInBinding:boolean,
lastInDirective:boolean) {
this.mode = mode;
this.name = name;
this.funcOrValue = funcOrValue;
this.args = args;
this.fixedArgs = fixedArgs;
this.contextIndex = contextIndex;
this.directiveIndex = directiveIndex;
this.selfIndex = selfIndex;
this.bindingRecord = bindingRecord;
this.lastInBinding = lastInBinding;
this.lastInDirective = lastInDirective;
this.expressionAsString = expressionAsString;
}
isPureFunction():boolean {
return this.mode === RECORD_TYPE_INTERPOLATE ||
this.mode === RECORD_TYPE_PRIMITIVE_OP;
}
}
| modules/angular2/src/change_detection/proto_record.js | 0 | https://github.com/angular/angular/commit/a58c9f83bd1a5be110a7982bab7023b209634c37 | [
0.00017439876683056355,
0.00017293434939347208,
0.0001698926353128627,
0.00017339726036880165,
0.0000013667604434886016
] |
{
"id": 1,
"code_window": [
" let differ = new TreeDiffer('dir1', ['.ts', '.cs'], ['.d.ts', '.d.cs']);\n",
"\n",
" let diffResult = differ.diffTree();\n",
"\n",
" expect(diffResult.changedPaths).toEqual(['file-1.cs', 'file-1.ts', 'file-3.ts']);\n",
"\n",
" // change two files\n",
" testDir['dir1']['file-1.ts'] = mockfs.file({content: 'new content', mtime: new Date(1000)});\n",
" testDir['dir1']['file-1.cs'] = mockfs.file({content: 'new content', mtime: new Date(1000)});\n",
" testDir['dir1']['file-1.d.cs'] = mockfs.file({content: 'new content', mtime: new Date(1000)});\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(diffResult.changedPaths)\n",
" .toEqual(['file-1.cs', 'file-1.ts', 'file-1d.cs', 'file-3.ts']);\n"
],
"file_path": "tools/broccoli/tree-differ.spec.ts",
"type": "replace",
"edit_start_line_idx": 168
} | {
"name": "angular",
"version": "2.0.0-alpha.21",
"description": "Angular 2 - a web framework for modern web apps",
"homepage": "https://github.com/angular/angular",
"bugs": "https://github.com/angular/angular/issues",
"contributors": [
"Alex Eagle <[email protected]>",
"Chirayu Krishnappa <[email protected]>",
"Jeff Cross <[email protected]>",
"Misko Hevery <[email protected]>",
"Rado Kirov <[email protected]>",
"Tobias Bosch <[email protected]>",
"Victor Savkin <[email protected]>",
"Yegor Jbanov <[email protected]>"
],
"license": "Apache-2.0",
"repository": {
"type": "git",
"url": "https://github.com/angular/angular.git"
},
"scripts": {
"postinstall": "webdriver-manager update && bower install && gulp pubget.dart && tsd reinstall --config modules/angular2/tsd.json && tsd reinstall --config tools/tsd.json",
"test": "gulp test.all.js && gulp test.all.dart"
},
"dependencies": {
"es6-module-loader": "^0.9.2",
"googleapis": "1.0.x",
"gulp-insert": "^0.4.0",
"gulp-modify": "0.0.5",
"gulp-replace": "^0.5.3",
"node-uuid": "1.4.x",
"reflect-metadata": "^0.1.0",
"rx": "2.5.1",
"selenium-webdriver": "2.45.1",
"systemjs": "^0.9.1",
"traceur": "0.0.87",
"which": "~1",
"zone.js": "0.4.4"
},
"devDependencies": {
"angular": "1.3.5",
"bower": "^1.3.12",
"broccoli": "^0.15.3",
"broccoli-filter": "^0.1.12",
"broccoli-flatten": "^0.1.1",
"broccoli-funnel": "igorminar/broccoli-funnel#perf-files",
"broccoli-lodash": "^0.1.1",
"broccoli-merge-trees": "^0.2.1",
"broccoli-replace": "alexeagle/broccoli-replace#angular_patch",
"broccoli-slow-trees": "^1.1.0",
"broccoli-stew": "^0.2.1",
"broccoli-writer": "^0.1.1",
"canonical-path": "0.0.2",
"conventional-changelog": "^0.0.17",
"css": "mlaval/css#issue65",
"del": "~1",
"dgeni": "^0.4.1",
"dgeni-packages": "^0.10.11",
"event-stream": "^3.1.5",
"fs-extra": "^0.18.0",
"glob": "^4.0.6",
"gulp": "^3.8.8",
"gulp-autoprefixer": "^2.1.0",
"gulp-changed": "^1.0.0",
"gulp-clang-format": "^1.0.4",
"gulp-concat": "^2.5.2",
"gulp-connect": "~1.0.5",
"gulp-load-plugins": "^0.7.1",
"gulp-rename": "^1.2.0",
"gulp-sass": "^1.3.3",
"gulp-shell": "^0.2.10",
"gulp-sourcemaps": "1.3.*",
"gulp-template": "^3.0.0",
"gulp-traceur": "0.17.*",
"gulp-typescript": "^2.6.0",
"gulp-webserver": "^0.8.7",
"html2jade": "^0.8.3",
"indent-string": "^1.2.1",
"js-beautify": "^1.5.5",
"js-yaml": "^3.2.7",
"karma": "^0.12.23",
"karma-chrome-launcher": "^0.1.4",
"karma-cli": "^0.0.4",
"karma-dart": "^0.2.8",
"karma-jasmine": "^0.2.2",
"lodash": "^2.4.1",
"madge": "^0.5.0",
"marked": "^0.3.3",
"merge": "^1.2.0",
"merge2": "^0.3.5",
"minijasminenode2": "^1.0.0",
"minimatch": "^2.0.1",
"minimist": "1.1.x",
"mock-fs": "^2.5.0",
"node-html-encoder": "0.0.2",
"parse5": "1.3.2",
"protractor": "2.0.0",
"q": "^1.0.1",
"react": "^0.13.2",
"run-sequence": "^0.3.6",
"sorted-object": "^1.0.0",
"source-map": "^0.3.0",
"sprintf-js": "1.0.*",
"string": "^3.1.1",
"symlink-or-copy": "^1.0.1",
"systemjs-builder": "^0.10.3",
"temp": "^0.8.1",
"ternary-stream": "^1.2.3",
"through2": "^0.6.1",
"ts2dart": "^0.5.0",
"tsd": "^0.5.7",
"typescript": "alexeagle/TypeScript#error_is_class",
"vinyl": "^0.4.6",
"walk-sync": "^0.1.3",
"xtend": "^4.0.0",
"yargs": "2.3.*"
}
}
| package.json | 0 | https://github.com/angular/angular/commit/a58c9f83bd1a5be110a7982bab7023b209634c37 | [
0.00017661356832832098,
0.00017158202535938472,
0.00016822392353788018,
0.00017097491945605725,
0.0000020496652268775506
] |
{
"id": 1,
"code_window": [
" let differ = new TreeDiffer('dir1', ['.ts', '.cs'], ['.d.ts', '.d.cs']);\n",
"\n",
" let diffResult = differ.diffTree();\n",
"\n",
" expect(diffResult.changedPaths).toEqual(['file-1.cs', 'file-1.ts', 'file-3.ts']);\n",
"\n",
" // change two files\n",
" testDir['dir1']['file-1.ts'] = mockfs.file({content: 'new content', mtime: new Date(1000)});\n",
" testDir['dir1']['file-1.cs'] = mockfs.file({content: 'new content', mtime: new Date(1000)});\n",
" testDir['dir1']['file-1.d.cs'] = mockfs.file({content: 'new content', mtime: new Date(1000)});\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(diffResult.changedPaths)\n",
" .toEqual(['file-1.cs', 'file-1.ts', 'file-1d.cs', 'file-3.ts']);\n"
],
"file_path": "tools/broccoli/tree-differ.spec.ts",
"type": "replace",
"edit_start_line_idx": 168
} | library angular2.transform.common.property_utils;
import 'package:analyzer/src/generated/scanner.dart' show Keyword;
/// Whether `name` is a valid property name.
bool isValid(String name) => !Keyword.keywords.containsKey(name);
/// Prepares `name` to be emitted inside a string.
String sanitize(String name) => name.replaceAll('\$', '\\\$');
/// Get a string usable as a lazy invalid setter, that is, one which will
/// `throw` immediately upon use.
String lazyInvalidSetter(String setterName) {
var sName = sanitize(setterName);
return ''' '$sName': (o, v) => '''
''' throw 'Invalid setter name "$sName" is a Dart keyword.' ''';
}
/// Get a string usable as a lazy invalid getter, that is, one which will
/// `throw` immediately upon use.
String lazyInvalidGetter(String getterName) {
var sName = sanitize(getterName);
return ''' '$sName': (o) => '''
''' throw 'Invalid getter name "$sName" is a Dart keyword.' ''';
}
/// Get a string usable as a lazy invalid method, that is, one which will
/// `throw` immediately upon use.
String lazyInvalidMethod(String methodName) {
var sName = sanitize(methodName);
return ''' '$sName': (o, args) => '''
''' throw 'Invalid method name "$sName" is a Dart keyword.' ''';
}
| modules/angular2/src/transform/common/property_utils.dart | 0 | https://github.com/angular/angular/commit/a58c9f83bd1a5be110a7982bab7023b209634c37 | [
0.00016885792138054967,
0.0001682009024079889,
0.00016711630451027304,
0.00016841469914652407,
6.661846327915555e-7
] |
{
"id": 2,
"code_window": [
" this.exclude = (excludeExtensions || []).length ? buildRegexp(excludeExtensions) : null;\n",
"\n",
" function combine(prev, curr) {\n",
" if (curr.charAt(0) !== \".\") throw new TypeError(\"Extension must begin with '.'\");\n",
" curr = '(' + curr + ')';\n",
" return prev ? (prev + '|' + curr) : curr;\n",
" }\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" let kSpecialRegexpChars = /[\\-\\[\\]\\/\\{\\}\\(\\)\\*\\+\\?\\.\\\\\\^\\$\\|]/g;\n",
" curr = '(' + curr.replace(kSpecialRegexpChars, '\\\\$&') + ')';\n"
],
"file_path": "tools/broccoli/tree-differ.ts",
"type": "replace",
"edit_start_line_idx": 24
} | /// <reference path="../typings/node/node.d.ts" />
/// <reference path="../typings/jasmine/jasmine.d.ts" />
let mockfs = require('mock-fs');
import fs = require('fs');
import {TreeDiffer} from './tree-differ';
describe('TreeDiffer', () => {
afterEach(() => mockfs.restore());
describe('diff of changed files', () => {
it('should list all files but no directories during the first diff', () => {
let testDir = {
'dir1': {
'file-1.txt': mockfs.file({content: 'file-1.txt content', mtime: new Date(1000)}),
'file-2.txt': mockfs.file({content: 'file-2.txt content', mtime: new Date(1000)}),
'subdir-1': {
'file-1.1.txt': mockfs.file({content: 'file-1.1.txt content', mtime: new Date(1000)})
},
'empty-dir': {}
}
};
mockfs(testDir);
let differ = new TreeDiffer('dir1');
let diffResult = differ.diffTree();
expect(diffResult.changedPaths)
.toEqual(['file-1.txt', 'file-2.txt', 'subdir-1/file-1.1.txt']);
expect(diffResult.removedPaths).toEqual([]);
});
it('should return empty diff if nothing has changed', () => {
let testDir = {
'dir1': {
'file-1.txt': mockfs.file({content: 'file-1.txt content', mtime: new Date(1000)}),
'file-2.txt': mockfs.file({content: 'file-2.txt content', mtime: new Date(1000)}),
'subdir-1': {
'file-1.1.txt': mockfs.file({content: 'file-1.1.txt content', mtime: new Date(1000)})
},
}
};
mockfs(testDir);
let differ = new TreeDiffer('dir1');
let diffResult = differ.diffTree();
expect(diffResult.changedPaths).not.toEqual([]);
expect(diffResult.removedPaths).toEqual([]);
diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual([]);
expect(diffResult.removedPaths).toEqual([]);
});
it('should list only changed files during the subsequent diffs', () => {
let testDir = {
'dir1': {
'file-1.txt': mockfs.file({content: 'file-1.txt content', mtime: new Date(1000)}),
'file-2.txt': mockfs.file({content: 'file-2.txt content', mtime: new Date(1000)}),
'subdir-1': {
'file-1.1.txt':
mockfs.file({content: 'file-1.1.txt content', mtime: new Date(1000)})
}
}
};
mockfs(testDir);
let differ = new TreeDiffer('dir1');
let diffResult = differ.diffTree();
expect(diffResult.changedPaths)
.toEqual(['file-1.txt', 'file-2.txt', 'subdir-1/file-1.1.txt']);
// change two files
testDir['dir1']['file-1.txt'] = mockfs.file({content: 'new content', mtime: new Date(1000)});
testDir['dir1']['subdir-1']['file-1.1.txt'] =
mockfs.file({content: 'file-1.1.txt content', mtime: new Date(9999)});
mockfs(testDir);
diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual(['file-1.txt', 'subdir-1/file-1.1.txt']);
expect(diffResult.removedPaths).toEqual([]);
// change one file
testDir['dir1']['file-1.txt'] = mockfs.file({content: 'super new', mtime: new Date(1000)});
mockfs(testDir);
diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual(['file-1.txt']);
});
it('should ignore files with extensions not listed in includeExtensions', () => {
let testDir = {
'dir1': {
'file-1.js': mockfs.file({content: 'file-1.js content', mtime: new Date(1000)}),
'file-2.md': mockfs.file({content: 'file-2.md content', mtime: new Date(1000)}),
'file-3.coffee': mockfs.file({content: 'file-3.coffee content', mtime: new Date(1000)}),
'subdir-1': {
'file-1.1.cc': mockfs.file({content: 'file-1.1.cc content', mtime: new Date(1000)})
}
}
};
mockfs(testDir);
let differ = new TreeDiffer('dir1', ['.js', '.coffee']);
let diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual(['file-1.js', 'file-3.coffee']);
// change two files
testDir['dir1']['file-1.js'] = mockfs.file({content: 'new content', mtime: new Date(1000)});
testDir['dir1']['file-3.coffee'] =
mockfs.file({content: 'new content', mtime: new Date(1000)});
testDir['dir1']['subdir-1']['file-1.1.cc'] =
mockfs.file({content: 'file-1.1.cc content', mtime: new Date(9999)});
mockfs(testDir);
diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual(['file-1.js', 'file-3.coffee']);
expect(diffResult.removedPaths).toEqual([]);
// change one file
testDir['dir1']['file-1.js'] = mockfs.file({content: 'super new', mtime: new Date(1000)});
mockfs(testDir);
diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual(['file-1.js']);
});
it('should ignore files with extensions listed in excludeExtensions', () => {
let testDir = {
'dir1': {
'file-1.ts': mockfs.file({content: 'file-1.ts content', mtime: new Date(1000)}),
'file-1.cs': mockfs.file({content: 'file-1.cs content', mtime: new Date(1000)}),
'file-1.d.cs': mockfs.file({content: 'file-1.d.cs content', mtime: new Date(1000)}),
'file-2.md': mockfs.file({content: 'file-2.md content', mtime: new Date(1000)}),
'file-3.ts': mockfs.file({content: 'file-3.ts content', mtime: new Date(1000)}),
'file-4.d.ts': mockfs.file({content: 'file-4.d.ts content', mtime: new Date(1000)}),
'subdir-1': {
'file-1.1.cc': mockfs.file({content: 'file-1.1.cc content', mtime: new Date(1000)})
}
}
};
mockfs(testDir);
let differ = new TreeDiffer('dir1', ['.ts', '.cs'], ['.d.ts', '.d.cs']);
let diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual(['file-1.cs', 'file-1.ts', 'file-3.ts']);
// change two files
testDir['dir1']['file-1.ts'] = mockfs.file({content: 'new content', mtime: new Date(1000)});
testDir['dir1']['file-1.cs'] = mockfs.file({content: 'new content', mtime: new Date(1000)});
testDir['dir1']['file-1.d.cs'] = mockfs.file({content: 'new content', mtime: new Date(1000)});
testDir['dir1']['file-3.ts'] = mockfs.file({content: 'new content', mtime: new Date(1000)});
testDir['dir1']['file-4.d.ts'] = mockfs.file({content: 'new content', mtime: new Date(1000)});
testDir['dir1']['subdir-1']['file-1.1.cc'] =
mockfs.file({content: 'file-1.1.cc content', mtime: new Date(9999)});
mockfs(testDir);
diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual(['file-1.cs', 'file-1.ts', 'file-3.ts']);
expect(diffResult.removedPaths).toEqual([]);
// change one file
testDir['dir1']['file-4.d.ts'] = mockfs.file({content: 'super new', mtime: new Date(1000)});
mockfs(testDir);
diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual([]);
});
});
describe('diff of new files', () => {
it('should detect file additions and report them as changed files', () => {
let testDir = {
'dir1':
{'file-1.txt': mockfs.file({content: 'file-1.txt content', mtime: new Date(1000)})}
};
mockfs(testDir);
let differ = new TreeDiffer('dir1');
differ.diffTree();
testDir['dir1']['file-2.txt'] = 'new file';
mockfs(testDir);
let diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual(['file-2.txt']);
});
});
it('should detect file additions mixed with file changes', () => {
let testDir = {
'dir1': {'file-1.txt': mockfs.file({content: 'file-1.txt content', mtime: new Date(1000)})}
};
mockfs(testDir);
let differ = new TreeDiffer('dir1');
differ.diffTree();
testDir['dir1']['file-1.txt'] = 'new content';
testDir['dir1']['file-2.txt'] = 'new file';
mockfs(testDir);
let diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual(['file-1.txt', 'file-2.txt']);
});
describe('diff of removed files', () => {
it('should detect file removals and report them as removed files', () => {
let testDir = {
'dir1':
{'file-1.txt': mockfs.file({content: 'file-1.txt content', mtime: new Date(1000)})}
};
mockfs(testDir);
let differ = new TreeDiffer('dir1');
differ.diffTree();
delete testDir['dir1']['file-1.txt'];
mockfs(testDir);
let diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual([]);
expect(diffResult.removedPaths).toEqual(['file-1.txt']);
});
});
it('should detect file removals mixed with file changes and additions', () => {
let testDir = {
'dir1': {
'file-1.txt': mockfs.file({content: 'file-1.txt content', mtime: new Date(1000)}),
'file-2.txt': mockfs.file({content: 'file-1.txt content', mtime: new Date(1000)})
}
};
mockfs(testDir);
let differ = new TreeDiffer('dir1');
differ.diffTree();
testDir['dir1']['file-1.txt'] = 'changed content';
delete testDir['dir1']['file-2.txt'];
testDir['dir1']['file-3.txt'] = 'new content';
mockfs(testDir);
let diffResult = differ.diffTree();
expect(diffResult.changedPaths).toEqual(['file-1.txt', 'file-3.txt']);
expect(diffResult.removedPaths).toEqual(['file-2.txt']);
});
});
| tools/broccoli/tree-differ.spec.ts | 1 | https://github.com/angular/angular/commit/a58c9f83bd1a5be110a7982bab7023b209634c37 | [
0.0007857849705033004,
0.00020212850358802825,
0.00017045406275428832,
0.00017405531252734363,
0.00011734750296454877
] |
{
"id": 2,
"code_window": [
" this.exclude = (excludeExtensions || []).length ? buildRegexp(excludeExtensions) : null;\n",
"\n",
" function combine(prev, curr) {\n",
" if (curr.charAt(0) !== \".\") throw new TypeError(\"Extension must begin with '.'\");\n",
" curr = '(' + curr + ')';\n",
" return prev ? (prev + '|' + curr) : curr;\n",
" }\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" let kSpecialRegexpChars = /[\\-\\[\\]\\/\\{\\}\\(\\)\\*\\+\\?\\.\\\\\\^\\$\\|]/g;\n",
" curr = '(' + curr.replace(kSpecialRegexpChars, '\\\\$&') + ')';\n"
],
"file_path": "tools/broccoli/tree-differ.ts",
"type": "replace",
"edit_start_line_idx": 24
} | <link rel="import" href="polymer.html">
<dom-module id="binary-tree">
<template>
<span>
<span>{{data.value}}</span>
<!-- TODO(tbosch): use the builtin conditional template when it is available in Polymer 0.8 -->
<span id="leftTree"></span>
<span id="rightTree"></span>
</span>
</template>
</dom-module>
<script>
(function() {
Polymer({
is: 'binary-tree',
properties: {
data: Object
},
leftTree: null,
rightTree: null,
dataChanged: function() {
var data = this.data || {};
this._updateTree(data.left, 'leftTree');
this._updateTree(data.right, 'rightTree');
},
_updateTree: function(data, treeName) {
if (data) {
if (!this[treeName]) {
this[treeName] = document.createElement('binary-tree');
}
this[treeName].data = data;
this.$[treeName].appendChild(this[treeName]);
} else {
if (this[treeName]) this[treeName].remove();
this[treeName] = null;
}
},
properties: {
data: 'dataChanged'
}
});
})();
</script>
| modules/benchmarks_external/src/tree/polymer/binary_tree.html | 0 | https://github.com/angular/angular/commit/a58c9f83bd1a5be110a7982bab7023b209634c37 | [
0.00017209585348609835,
0.00016861400217749178,
0.00016412096738349646,
0.00016783394676167518,
0.0000030047326617932413
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.